repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
wandb/client | wandb/vendor/prompt_toolkit/interface.py | _InterfaceEventLoopCallbacks.feed_key | def feed_key(self, key_press):
"""
Feed a key press to the CommandLineInterface.
"""
assert isinstance(key_press, KeyPress)
cli = self._active_cli
# Feed the key and redraw.
# (When the CLI is in 'done' state, it should return to the event loop
# as soon as possible. Ignore all key presses beyond this point.)
if not cli.is_done:
cli.input_processor.feed(key_press)
cli.input_processor.process_keys() | python | def feed_key(self, key_press):
"""
Feed a key press to the CommandLineInterface.
"""
assert isinstance(key_press, KeyPress)
cli = self._active_cli
# Feed the key and redraw.
# (When the CLI is in 'done' state, it should return to the event loop
# as soon as possible. Ignore all key presses beyond this point.)
if not cli.is_done:
cli.input_processor.feed(key_press)
cli.input_processor.process_keys() | [
"def",
"feed_key",
"(",
"self",
",",
"key_press",
")",
":",
"assert",
"isinstance",
"(",
"key_press",
",",
"KeyPress",
")",
"cli",
"=",
"self",
".",
"_active_cli",
"# Feed the key and redraw.",
"# (When the CLI is in 'done' state, it should return to the event loop",
"# a... | Feed a key press to the CommandLineInterface. | [
"Feed",
"a",
"key",
"press",
"to",
"the",
"CommandLineInterface",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/interface.py#L1036-L1048 | train | 207,500 |
wandb/client | wandb/vendor/prompt_toolkit/layout/mouse_handlers.py | MouseHandlers.set_mouse_handler_for_range | def set_mouse_handler_for_range(self, x_min, x_max, y_min, y_max, handler=None):
"""
Set mouse handler for a region.
"""
for x, y in product(range(x_min, x_max), range(y_min, y_max)):
self.mouse_handlers[x,y] = handler | python | def set_mouse_handler_for_range(self, x_min, x_max, y_min, y_max, handler=None):
"""
Set mouse handler for a region.
"""
for x, y in product(range(x_min, x_max), range(y_min, y_max)):
self.mouse_handlers[x,y] = handler | [
"def",
"set_mouse_handler_for_range",
"(",
"self",
",",
"x_min",
",",
"x_max",
",",
"y_min",
",",
"y_max",
",",
"handler",
"=",
"None",
")",
":",
"for",
"x",
",",
"y",
"in",
"product",
"(",
"range",
"(",
"x_min",
",",
"x_max",
")",
",",
"range",
"(",... | Set mouse handler for a region. | [
"Set",
"mouse",
"handler",
"for",
"a",
"region",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/layout/mouse_handlers.py#L24-L29 | train | 207,501 |
wandb/client | wandb/wandb_run.py | Run.send_message | def send_message(self, options):
""" Sends a message to the wandb process changing the policy
of saved files. This is primarily used internally by wandb.save
"""
if not options.get("save_policy"):
raise ValueError("Only configuring save_policy is supported")
if self.socket:
self.socket.send(options)
elif self._jupyter_agent:
self._jupyter_agent.start()
self._jupyter_agent.rm.update_user_file_policy(
options["save_policy"])
else:
wandb.termerror(
"wandb.init hasn't been called, can't configure run") | python | def send_message(self, options):
""" Sends a message to the wandb process changing the policy
of saved files. This is primarily used internally by wandb.save
"""
if not options.get("save_policy"):
raise ValueError("Only configuring save_policy is supported")
if self.socket:
self.socket.send(options)
elif self._jupyter_agent:
self._jupyter_agent.start()
self._jupyter_agent.rm.update_user_file_policy(
options["save_policy"])
else:
wandb.termerror(
"wandb.init hasn't been called, can't configure run") | [
"def",
"send_message",
"(",
"self",
",",
"options",
")",
":",
"if",
"not",
"options",
".",
"get",
"(",
"\"save_policy\"",
")",
":",
"raise",
"ValueError",
"(",
"\"Only configuring save_policy is supported\"",
")",
"if",
"self",
".",
"socket",
":",
"self",
".",... | Sends a message to the wandb process changing the policy
of saved files. This is primarily used internally by wandb.save | [
"Sends",
"a",
"message",
"to",
"the",
"wandb",
"process",
"changing",
"the",
"policy",
"of",
"saved",
"files",
".",
"This",
"is",
"primarily",
"used",
"internally",
"by",
"wandb",
".",
"save"
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/wandb_run.py#L125-L139 | train | 207,502 |
wandb/client | wandb/wandb_run.py | Run.from_environment_or_defaults | def from_environment_or_defaults(cls, environment=None):
"""Create a Run object taking values from the local environment where possible.
The run ID comes from WANDB_RUN_ID or is randomly generated.
The run mode ("dryrun", or "run") comes from WANDB_MODE or defaults to "dryrun".
The run directory comes from WANDB_RUN_DIR or is generated from the run ID.
The Run will have a .config attribute but its run directory won't be set by
default.
"""
if environment is None:
environment = os.environ
run_id = environment.get(env.RUN_ID)
resume = environment.get(env.RESUME)
storage_id = environment.get(env.RUN_STORAGE_ID)
mode = environment.get(env.MODE)
disabled = InternalApi().disabled()
if not mode and disabled:
mode = "dryrun"
elif disabled and mode != "dryrun":
wandb.termlog(
"WARNING: WANDB_MODE is set to run, but W&B was disabled. Run `wandb on` to remove this message")
elif disabled:
wandb.termlog(
'W&B is disabled in this directory. Run `wandb on` to enable cloud syncing.')
group = environment.get(env.RUN_GROUP)
job_type = environment.get(env.JOB_TYPE)
run_dir = environment.get(env.RUN_DIR)
sweep_id = environment.get(env.SWEEP_ID)
program = environment.get(env.PROGRAM)
description = environment.get(env.DESCRIPTION)
args = env.get_args()
wandb_dir = env.get_dir()
tags = env.get_tags()
config = Config.from_environment_or_defaults()
run = cls(run_id, mode, run_dir,
group, job_type, config,
sweep_id, storage_id, program=program, description=description,
args=args, wandb_dir=wandb_dir, tags=tags,
resume=resume)
return run | python | def from_environment_or_defaults(cls, environment=None):
"""Create a Run object taking values from the local environment where possible.
The run ID comes from WANDB_RUN_ID or is randomly generated.
The run mode ("dryrun", or "run") comes from WANDB_MODE or defaults to "dryrun".
The run directory comes from WANDB_RUN_DIR or is generated from the run ID.
The Run will have a .config attribute but its run directory won't be set by
default.
"""
if environment is None:
environment = os.environ
run_id = environment.get(env.RUN_ID)
resume = environment.get(env.RESUME)
storage_id = environment.get(env.RUN_STORAGE_ID)
mode = environment.get(env.MODE)
disabled = InternalApi().disabled()
if not mode and disabled:
mode = "dryrun"
elif disabled and mode != "dryrun":
wandb.termlog(
"WARNING: WANDB_MODE is set to run, but W&B was disabled. Run `wandb on` to remove this message")
elif disabled:
wandb.termlog(
'W&B is disabled in this directory. Run `wandb on` to enable cloud syncing.')
group = environment.get(env.RUN_GROUP)
job_type = environment.get(env.JOB_TYPE)
run_dir = environment.get(env.RUN_DIR)
sweep_id = environment.get(env.SWEEP_ID)
program = environment.get(env.PROGRAM)
description = environment.get(env.DESCRIPTION)
args = env.get_args()
wandb_dir = env.get_dir()
tags = env.get_tags()
config = Config.from_environment_or_defaults()
run = cls(run_id, mode, run_dir,
group, job_type, config,
sweep_id, storage_id, program=program, description=description,
args=args, wandb_dir=wandb_dir, tags=tags,
resume=resume)
return run | [
"def",
"from_environment_or_defaults",
"(",
"cls",
",",
"environment",
"=",
"None",
")",
":",
"if",
"environment",
"is",
"None",
":",
"environment",
"=",
"os",
".",
"environ",
"run_id",
"=",
"environment",
".",
"get",
"(",
"env",
".",
"RUN_ID",
")",
"resum... | Create a Run object taking values from the local environment where possible.
The run ID comes from WANDB_RUN_ID or is randomly generated.
The run mode ("dryrun", or "run") comes from WANDB_MODE or defaults to "dryrun".
The run directory comes from WANDB_RUN_DIR or is generated from the run ID.
The Run will have a .config attribute but its run directory won't be set by
default. | [
"Create",
"a",
"Run",
"object",
"taking",
"values",
"from",
"the",
"local",
"environment",
"where",
"possible",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/wandb_run.py#L142-L183 | train | 207,503 |
wandb/client | wandb/wandb_run.py | Run.upload_debug | def upload_debug(self):
"""Uploads the debug log to cloud storage"""
if os.path.exists(self.log_fname):
api = InternalApi()
api.set_current_run_id(self.id)
pusher = FilePusher(api)
pusher.update_file("wandb-debug.log", self.log_fname)
pusher.file_changed("wandb-debug.log", self.log_fname)
pusher.finish() | python | def upload_debug(self):
"""Uploads the debug log to cloud storage"""
if os.path.exists(self.log_fname):
api = InternalApi()
api.set_current_run_id(self.id)
pusher = FilePusher(api)
pusher.update_file("wandb-debug.log", self.log_fname)
pusher.file_changed("wandb-debug.log", self.log_fname)
pusher.finish() | [
"def",
"upload_debug",
"(",
"self",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"log_fname",
")",
":",
"api",
"=",
"InternalApi",
"(",
")",
"api",
".",
"set_current_run_id",
"(",
"self",
".",
"id",
")",
"pusher",
"=",
"FilePus... | Uploads the debug log to cloud storage | [
"Uploads",
"the",
"debug",
"log",
"to",
"cloud",
"storage"
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/wandb_run.py#L357-L365 | train | 207,504 |
wandb/client | wandb/wandb_run.py | Run.enable_logging | def enable_logging(self):
"""Enable logging to the global debug log. This adds a run_id to the log,
in case of muliple processes on the same machine.
Currently no way to disable logging after it's enabled.
"""
handler = logging.FileHandler(self.log_fname)
handler.setLevel(logging.INFO)
run_id = self.id
class WBFilter(logging.Filter):
def filter(self, record):
record.run_id = run_id
return True
formatter = logging.Formatter(
'%(asctime)s %(levelname)-7s %(threadName)-10s:%(process)d [%(run_id)s:%(filename)s:%(funcName)s():%(lineno)s] %(message)s')
handler.setFormatter(formatter)
handler.addFilter(WBFilter())
root = logging.getLogger()
root.addHandler(handler) | python | def enable_logging(self):
"""Enable logging to the global debug log. This adds a run_id to the log,
in case of muliple processes on the same machine.
Currently no way to disable logging after it's enabled.
"""
handler = logging.FileHandler(self.log_fname)
handler.setLevel(logging.INFO)
run_id = self.id
class WBFilter(logging.Filter):
def filter(self, record):
record.run_id = run_id
return True
formatter = logging.Formatter(
'%(asctime)s %(levelname)-7s %(threadName)-10s:%(process)d [%(run_id)s:%(filename)s:%(funcName)s():%(lineno)s] %(message)s')
handler.setFormatter(formatter)
handler.addFilter(WBFilter())
root = logging.getLogger()
root.addHandler(handler) | [
"def",
"enable_logging",
"(",
"self",
")",
":",
"handler",
"=",
"logging",
".",
"FileHandler",
"(",
"self",
".",
"log_fname",
")",
"handler",
".",
"setLevel",
"(",
"logging",
".",
"INFO",
")",
"run_id",
"=",
"self",
".",
"id",
"class",
"WBFilter",
"(",
... | Enable logging to the global debug log. This adds a run_id to the log,
in case of muliple processes on the same machine.
Currently no way to disable logging after it's enabled. | [
"Enable",
"logging",
"to",
"the",
"global",
"debug",
"log",
".",
"This",
"adds",
"a",
"run_id",
"to",
"the",
"log",
"in",
"case",
"of",
"muliple",
"processes",
"on",
"the",
"same",
"machine",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/wandb_run.py#L415-L436 | train | 207,505 |
wandb/client | wandb/vendor/prompt_toolkit/key_binding/bindings/completion.py | display_completions_like_readline | def display_completions_like_readline(event):
"""
Key binding handler for readline-style tab completion.
This is meant to be as similar as possible to the way how readline displays
completions.
Generate the completions immediately (blocking) and display them above the
prompt in columns.
Usage::
# Call this handler when 'Tab' has been pressed.
registry.add_binding(Keys.ControlI)(display_completions_like_readline)
"""
# Request completions.
b = event.current_buffer
if b.completer is None:
return
complete_event = CompleteEvent(completion_requested=True)
completions = list(b.completer.get_completions(b.document, complete_event))
# Calculate the common suffix.
common_suffix = get_common_complete_suffix(b.document, completions)
# One completion: insert it.
if len(completions) == 1:
b.delete_before_cursor(-completions[0].start_position)
b.insert_text(completions[0].text)
# Multiple completions with common part.
elif common_suffix:
b.insert_text(common_suffix)
# Otherwise: display all completions.
elif completions:
_display_completions_like_readline(event.cli, completions) | python | def display_completions_like_readline(event):
"""
Key binding handler for readline-style tab completion.
This is meant to be as similar as possible to the way how readline displays
completions.
Generate the completions immediately (blocking) and display them above the
prompt in columns.
Usage::
# Call this handler when 'Tab' has been pressed.
registry.add_binding(Keys.ControlI)(display_completions_like_readline)
"""
# Request completions.
b = event.current_buffer
if b.completer is None:
return
complete_event = CompleteEvent(completion_requested=True)
completions = list(b.completer.get_completions(b.document, complete_event))
# Calculate the common suffix.
common_suffix = get_common_complete_suffix(b.document, completions)
# One completion: insert it.
if len(completions) == 1:
b.delete_before_cursor(-completions[0].start_position)
b.insert_text(completions[0].text)
# Multiple completions with common part.
elif common_suffix:
b.insert_text(common_suffix)
# Otherwise: display all completions.
elif completions:
_display_completions_like_readline(event.cli, completions) | [
"def",
"display_completions_like_readline",
"(",
"event",
")",
":",
"# Request completions.",
"b",
"=",
"event",
".",
"current_buffer",
"if",
"b",
".",
"completer",
"is",
"None",
":",
"return",
"complete_event",
"=",
"CompleteEvent",
"(",
"completion_requested",
"="... | Key binding handler for readline-style tab completion.
This is meant to be as similar as possible to the way how readline displays
completions.
Generate the completions immediately (blocking) and display them above the
prompt in columns.
Usage::
# Call this handler when 'Tab' has been pressed.
registry.add_binding(Keys.ControlI)(display_completions_like_readline) | [
"Key",
"binding",
"handler",
"for",
"readline",
"-",
"style",
"tab",
"completion",
".",
"This",
"is",
"meant",
"to",
"be",
"as",
"similar",
"as",
"possible",
"to",
"the",
"way",
"how",
"readline",
"displays",
"completions",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/key_binding/bindings/completion.py#L31-L64 | train | 207,506 |
wandb/client | wandb/vendor/prompt_toolkit/key_binding/bindings/completion.py | _display_completions_like_readline | def _display_completions_like_readline(cli, completions):
"""
Display the list of completions in columns above the prompt.
This will ask for a confirmation if there are too many completions to fit
on a single page and provide a paginator to walk through them.
"""
from prompt_toolkit.shortcuts import create_confirm_application
assert isinstance(completions, list)
# Get terminal dimensions.
term_size = cli.output.get_size()
term_width = term_size.columns
term_height = term_size.rows
# Calculate amount of required columns/rows for displaying the
# completions. (Keep in mind that completions are displayed
# alphabetically column-wise.)
max_compl_width = min(term_width,
max(get_cwidth(c.text) for c in completions) + 1)
column_count = max(1, term_width // max_compl_width)
completions_per_page = column_count * (term_height - 1)
page_count = int(math.ceil(len(completions) / float(completions_per_page)))
# Note: math.ceil can return float on Python2.
def display(page):
# Display completions.
page_completions = completions[page * completions_per_page:
(page+1) * completions_per_page]
page_row_count = int(math.ceil(len(page_completions) / float(column_count)))
page_columns = [page_completions[i * page_row_count:(i+1) * page_row_count]
for i in range(column_count)]
result = []
for r in range(page_row_count):
for c in range(column_count):
try:
result.append(page_columns[c][r].text.ljust(max_compl_width))
except IndexError:
pass
result.append('\n')
cli.output.write(''.join(result))
cli.output.flush()
# User interaction through an application generator function.
def run():
if len(completions) > completions_per_page:
# Ask confirmation if it doesn't fit on the screen.
message = 'Display all {} possibilities? (y on n) '.format(len(completions))
confirm = yield create_confirm_application(message)
if confirm:
# Display pages.
for page in range(page_count):
display(page)
if page != page_count - 1:
# Display --MORE-- and go to the next page.
show_more = yield _create_more_application()
if not show_more:
return
else:
cli.output.write('\n'); cli.output.flush()
else:
# Display all completions.
display(0)
cli.run_application_generator(run, render_cli_done=True) | python | def _display_completions_like_readline(cli, completions):
"""
Display the list of completions in columns above the prompt.
This will ask for a confirmation if there are too many completions to fit
on a single page and provide a paginator to walk through them.
"""
from prompt_toolkit.shortcuts import create_confirm_application
assert isinstance(completions, list)
# Get terminal dimensions.
term_size = cli.output.get_size()
term_width = term_size.columns
term_height = term_size.rows
# Calculate amount of required columns/rows for displaying the
# completions. (Keep in mind that completions are displayed
# alphabetically column-wise.)
max_compl_width = min(term_width,
max(get_cwidth(c.text) for c in completions) + 1)
column_count = max(1, term_width // max_compl_width)
completions_per_page = column_count * (term_height - 1)
page_count = int(math.ceil(len(completions) / float(completions_per_page)))
# Note: math.ceil can return float on Python2.
def display(page):
# Display completions.
page_completions = completions[page * completions_per_page:
(page+1) * completions_per_page]
page_row_count = int(math.ceil(len(page_completions) / float(column_count)))
page_columns = [page_completions[i * page_row_count:(i+1) * page_row_count]
for i in range(column_count)]
result = []
for r in range(page_row_count):
for c in range(column_count):
try:
result.append(page_columns[c][r].text.ljust(max_compl_width))
except IndexError:
pass
result.append('\n')
cli.output.write(''.join(result))
cli.output.flush()
# User interaction through an application generator function.
def run():
if len(completions) > completions_per_page:
# Ask confirmation if it doesn't fit on the screen.
message = 'Display all {} possibilities? (y on n) '.format(len(completions))
confirm = yield create_confirm_application(message)
if confirm:
# Display pages.
for page in range(page_count):
display(page)
if page != page_count - 1:
# Display --MORE-- and go to the next page.
show_more = yield _create_more_application()
if not show_more:
return
else:
cli.output.write('\n'); cli.output.flush()
else:
# Display all completions.
display(0)
cli.run_application_generator(run, render_cli_done=True) | [
"def",
"_display_completions_like_readline",
"(",
"cli",
",",
"completions",
")",
":",
"from",
"prompt_toolkit",
".",
"shortcuts",
"import",
"create_confirm_application",
"assert",
"isinstance",
"(",
"completions",
",",
"list",
")",
"# Get terminal dimensions.",
"term_siz... | Display the list of completions in columns above the prompt.
This will ask for a confirmation if there are too many completions to fit
on a single page and provide a paginator to walk through them. | [
"Display",
"the",
"list",
"of",
"completions",
"in",
"columns",
"above",
"the",
"prompt",
".",
"This",
"will",
"ask",
"for",
"a",
"confirmation",
"if",
"there",
"are",
"too",
"many",
"completions",
"to",
"fit",
"on",
"a",
"single",
"page",
"and",
"provide"... | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/key_binding/bindings/completion.py#L67-L134 | train | 207,507 |
wandb/client | wandb/vendor/prompt_toolkit/filters/utils.py | to_simple_filter | def to_simple_filter(bool_or_filter):
"""
Accept both booleans and CLIFilters as input and
turn it into a SimpleFilter.
"""
if not isinstance(bool_or_filter, (bool, SimpleFilter)):
raise TypeError('Expecting a bool or a SimpleFilter instance. Got %r' % bool_or_filter)
return {
True: _always,
False: _never,
}.get(bool_or_filter, bool_or_filter) | python | def to_simple_filter(bool_or_filter):
"""
Accept both booleans and CLIFilters as input and
turn it into a SimpleFilter.
"""
if not isinstance(bool_or_filter, (bool, SimpleFilter)):
raise TypeError('Expecting a bool or a SimpleFilter instance. Got %r' % bool_or_filter)
return {
True: _always,
False: _never,
}.get(bool_or_filter, bool_or_filter) | [
"def",
"to_simple_filter",
"(",
"bool_or_filter",
")",
":",
"if",
"not",
"isinstance",
"(",
"bool_or_filter",
",",
"(",
"bool",
",",
"SimpleFilter",
")",
")",
":",
"raise",
"TypeError",
"(",
"'Expecting a bool or a SimpleFilter instance. Got %r'",
"%",
"bool_or_filter... | Accept both booleans and CLIFilters as input and
turn it into a SimpleFilter. | [
"Accept",
"both",
"booleans",
"and",
"CLIFilters",
"as",
"input",
"and",
"turn",
"it",
"into",
"a",
"SimpleFilter",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/filters/utils.py#L14-L25 | train | 207,508 |
wandb/client | wandb/vendor/prompt_toolkit/filters/utils.py | to_cli_filter | def to_cli_filter(bool_or_filter):
"""
Accept both booleans and CLIFilters as input and
turn it into a CLIFilter.
"""
if not isinstance(bool_or_filter, (bool, CLIFilter)):
raise TypeError('Expecting a bool or a CLIFilter instance. Got %r' % bool_or_filter)
return {
True: _always,
False: _never,
}.get(bool_or_filter, bool_or_filter) | python | def to_cli_filter(bool_or_filter):
"""
Accept both booleans and CLIFilters as input and
turn it into a CLIFilter.
"""
if not isinstance(bool_or_filter, (bool, CLIFilter)):
raise TypeError('Expecting a bool or a CLIFilter instance. Got %r' % bool_or_filter)
return {
True: _always,
False: _never,
}.get(bool_or_filter, bool_or_filter) | [
"def",
"to_cli_filter",
"(",
"bool_or_filter",
")",
":",
"if",
"not",
"isinstance",
"(",
"bool_or_filter",
",",
"(",
"bool",
",",
"CLIFilter",
")",
")",
":",
"raise",
"TypeError",
"(",
"'Expecting a bool or a CLIFilter instance. Got %r'",
"%",
"bool_or_filter",
")",... | Accept both booleans and CLIFilters as input and
turn it into a CLIFilter. | [
"Accept",
"both",
"booleans",
"and",
"CLIFilters",
"as",
"input",
"and",
"turn",
"it",
"into",
"a",
"CLIFilter",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/filters/utils.py#L28-L39 | train | 207,509 |
wandb/client | wandb/vendor/prompt_toolkit/eventloop/posix_utils.py | PosixStdinReader.read | def read(self, count=1024):
# By default we choose a rather small chunk size, because reading
# big amounts of input at once, causes the event loop to process
# all these key bindings also at once without going back to the
# loop. This will make the application feel unresponsive.
"""
Read the input and return it as a string.
Return the text. Note that this can return an empty string, even when
the input stream was not yet closed. This means that something went
wrong during the decoding.
"""
if self.closed:
return b''
# Note: the following works better than wrapping `self.stdin` like
# `codecs.getreader('utf-8')(stdin)` and doing `read(1)`.
# Somehow that causes some latency when the escape
# character is pressed. (Especially on combination with the `select`.)
try:
data = os.read(self.stdin_fd, count)
# Nothing more to read, stream is closed.
if data == b'':
self.closed = True
return ''
except OSError:
# In case of SIGWINCH
data = b''
return self._stdin_decoder.decode(data) | python | def read(self, count=1024):
# By default we choose a rather small chunk size, because reading
# big amounts of input at once, causes the event loop to process
# all these key bindings also at once without going back to the
# loop. This will make the application feel unresponsive.
"""
Read the input and return it as a string.
Return the text. Note that this can return an empty string, even when
the input stream was not yet closed. This means that something went
wrong during the decoding.
"""
if self.closed:
return b''
# Note: the following works better than wrapping `self.stdin` like
# `codecs.getreader('utf-8')(stdin)` and doing `read(1)`.
# Somehow that causes some latency when the escape
# character is pressed. (Especially on combination with the `select`.)
try:
data = os.read(self.stdin_fd, count)
# Nothing more to read, stream is closed.
if data == b'':
self.closed = True
return ''
except OSError:
# In case of SIGWINCH
data = b''
return self._stdin_decoder.decode(data) | [
"def",
"read",
"(",
"self",
",",
"count",
"=",
"1024",
")",
":",
"# By default we choose a rather small chunk size, because reading",
"# big amounts of input at once, causes the event loop to process",
"# all these key bindings also at once without going back to the",
"# loop. This will ma... | Read the input and return it as a string.
Return the text. Note that this can return an empty string, even when
the input stream was not yet closed. This means that something went
wrong during the decoding. | [
"Read",
"the",
"input",
"and",
"return",
"it",
"as",
"a",
"string",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/eventloop/posix_utils.py#L52-L82 | train | 207,510 |
wandb/client | wandb/streaming_log.py | LineBuffer.add_string | def add_string(self, data):
"""Process some data splitting it into complete lines and buffering the rest
Args:
data: A `str` in Python 2 or `bytes` in Python 3
Returns:
list of complete lines ending with a carriage return (eg. a progress
bar) or a newline.
"""
lines = []
while data:
match = self._line_end_re.search(data)
if match is None:
chunk = data
else:
chunk = data[:match.end()]
data = data[len(chunk):]
if self._buf and self._buf[-1].endswith(b('\r')) and not chunk.startswith(b('\n')):
# if we get a carriage return followed by something other than
# a newline then we assume that we're overwriting the current
# line (ie. a progress bar)
#
# We don't terminate lines that end with a carriage return until
# we see what's coming next so we can distinguish between a
# progress bar situation and a Windows line terminator.
#
# TODO(adrian): some day these hacks should be replaced with
# real terminal emulation
lines.append(self._finish_line())
self._buf.append(chunk)
if chunk.endswith(b('\n')):
lines.append(self._finish_line())
return lines | python | def add_string(self, data):
"""Process some data splitting it into complete lines and buffering the rest
Args:
data: A `str` in Python 2 or `bytes` in Python 3
Returns:
list of complete lines ending with a carriage return (eg. a progress
bar) or a newline.
"""
lines = []
while data:
match = self._line_end_re.search(data)
if match is None:
chunk = data
else:
chunk = data[:match.end()]
data = data[len(chunk):]
if self._buf and self._buf[-1].endswith(b('\r')) and not chunk.startswith(b('\n')):
# if we get a carriage return followed by something other than
# a newline then we assume that we're overwriting the current
# line (ie. a progress bar)
#
# We don't terminate lines that end with a carriage return until
# we see what's coming next so we can distinguish between a
# progress bar situation and a Windows line terminator.
#
# TODO(adrian): some day these hacks should be replaced with
# real terminal emulation
lines.append(self._finish_line())
self._buf.append(chunk)
if chunk.endswith(b('\n')):
lines.append(self._finish_line())
return lines | [
"def",
"add_string",
"(",
"self",
",",
"data",
")",
":",
"lines",
"=",
"[",
"]",
"while",
"data",
":",
"match",
"=",
"self",
".",
"_line_end_re",
".",
"search",
"(",
"data",
")",
"if",
"match",
"is",
"None",
":",
"chunk",
"=",
"data",
"else",
":",
... | Process some data splitting it into complete lines and buffering the rest
Args:
data: A `str` in Python 2 or `bytes` in Python 3
Returns:
list of complete lines ending with a carriage return (eg. a progress
bar) or a newline. | [
"Process",
"some",
"data",
"splitting",
"it",
"into",
"complete",
"lines",
"and",
"buffering",
"the",
"rest"
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/streaming_log.py#L27-L63 | train | 207,511 |
wandb/client | wandb/streaming_log.py | TextStreamPusher.write | def write(self, message, cur_time=None):
"""Write some text to the pusher.
Args:
message: a string to push for this file.
cur_time: used for unit testing. override line timestamp.
"""
if cur_time is None:
cur_time = time.time()
lines = self._line_buffer.add_string(message)
for line in lines:
#print('ts line', repr(line))
timestamp = ''
if self._prepend_timestamp:
timestamp = datetime.datetime.utcfromtimestamp(
cur_time).isoformat() + ' '
line = u'{}{}{}'.format(self._line_prepend, timestamp, line)
self._fsapi.push(self._filename, line) | python | def write(self, message, cur_time=None):
"""Write some text to the pusher.
Args:
message: a string to push for this file.
cur_time: used for unit testing. override line timestamp.
"""
if cur_time is None:
cur_time = time.time()
lines = self._line_buffer.add_string(message)
for line in lines:
#print('ts line', repr(line))
timestamp = ''
if self._prepend_timestamp:
timestamp = datetime.datetime.utcfromtimestamp(
cur_time).isoformat() + ' '
line = u'{}{}{}'.format(self._line_prepend, timestamp, line)
self._fsapi.push(self._filename, line) | [
"def",
"write",
"(",
"self",
",",
"message",
",",
"cur_time",
"=",
"None",
")",
":",
"if",
"cur_time",
"is",
"None",
":",
"cur_time",
"=",
"time",
".",
"time",
"(",
")",
"lines",
"=",
"self",
".",
"_line_buffer",
".",
"add_string",
"(",
"message",
")... | Write some text to the pusher.
Args:
message: a string to push for this file.
cur_time: used for unit testing. override line timestamp. | [
"Write",
"some",
"text",
"to",
"the",
"pusher",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/streaming_log.py#L95-L112 | train | 207,512 |
wandb/client | wandb/tensorflow/__init__.py | stream_tfevents | def stream_tfevents(path, file_api, step=0):
"""Parses and streams a tfevents file to the server"""
last_step = 0
row = {}
buffer = []
last_row = {}
for summary in tf.train.summary_iterator(path):
parsed = tf_summary_to_dict(summary)
if last_step != parsed["tensorflow_step"]:
step += 1
last_step = parsed["tensorflow_step"]
# TODO: handle time
if len(row) > 0:
last_row = to_json(row)
buffer.append(Chunk("wandb-history.jsonl",
util.json_dumps_safer_history(to_json(row))))
row.update(parsed)
file_api._send(buffer)
return last_row | python | def stream_tfevents(path, file_api, step=0):
"""Parses and streams a tfevents file to the server"""
last_step = 0
row = {}
buffer = []
last_row = {}
for summary in tf.train.summary_iterator(path):
parsed = tf_summary_to_dict(summary)
if last_step != parsed["tensorflow_step"]:
step += 1
last_step = parsed["tensorflow_step"]
# TODO: handle time
if len(row) > 0:
last_row = to_json(row)
buffer.append(Chunk("wandb-history.jsonl",
util.json_dumps_safer_history(to_json(row))))
row.update(parsed)
file_api._send(buffer)
return last_row | [
"def",
"stream_tfevents",
"(",
"path",
",",
"file_api",
",",
"step",
"=",
"0",
")",
":",
"last_step",
"=",
"0",
"row",
"=",
"{",
"}",
"buffer",
"=",
"[",
"]",
"last_row",
"=",
"{",
"}",
"for",
"summary",
"in",
"tf",
".",
"train",
".",
"summary_iter... | Parses and streams a tfevents file to the server | [
"Parses",
"and",
"streams",
"a",
"tfevents",
"file",
"to",
"the",
"server"
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/tensorflow/__init__.py#L28-L46 | train | 207,513 |
wandb/client | wandb/internal_cli.py | agent_run | def agent_run(args):
"""A version of `wandb run` that the agent uses to run things.
"""
run = wandb.wandb_run.Run.from_environment_or_defaults()
run.enable_logging()
api = wandb.apis.InternalApi()
api.set_current_run_id(run.id)
# TODO: better failure handling
root = api.git.root
# handle non-git directories
if not root:
root = os.path.abspath(os.getcwd())
host = socket.gethostname()
remote_url = 'file://{}{}'.format(host, root)
run.save(program=args['program'], api=api)
env = dict(os.environ)
run.set_environment(env)
try:
rm = wandb.run_manager.RunManager(api, run)
except wandb.run_manager.Error:
exc_type, exc_value, exc_traceback = sys.exc_info()
wandb.termerror('An Exception was raised during setup, see %s for full traceback.' %
util.get_log_file_path())
wandb.termerror(exc_value)
if 'permission' in str(exc_value):
wandb.termerror(
'Are you sure you provided the correct API key to "wandb login"?')
lines = traceback.format_exception(
exc_type, exc_value, exc_traceback)
logging.error('\n'.join(lines))
else:
rm.run_user_process(args['program'], args['args'], env) | python | def agent_run(args):
"""A version of `wandb run` that the agent uses to run things.
"""
run = wandb.wandb_run.Run.from_environment_or_defaults()
run.enable_logging()
api = wandb.apis.InternalApi()
api.set_current_run_id(run.id)
# TODO: better failure handling
root = api.git.root
# handle non-git directories
if not root:
root = os.path.abspath(os.getcwd())
host = socket.gethostname()
remote_url = 'file://{}{}'.format(host, root)
run.save(program=args['program'], api=api)
env = dict(os.environ)
run.set_environment(env)
try:
rm = wandb.run_manager.RunManager(api, run)
except wandb.run_manager.Error:
exc_type, exc_value, exc_traceback = sys.exc_info()
wandb.termerror('An Exception was raised during setup, see %s for full traceback.' %
util.get_log_file_path())
wandb.termerror(exc_value)
if 'permission' in str(exc_value):
wandb.termerror(
'Are you sure you provided the correct API key to "wandb login"?')
lines = traceback.format_exception(
exc_type, exc_value, exc_traceback)
logging.error('\n'.join(lines))
else:
rm.run_user_process(args['program'], args['args'], env) | [
"def",
"agent_run",
"(",
"args",
")",
":",
"run",
"=",
"wandb",
".",
"wandb_run",
".",
"Run",
".",
"from_environment_or_defaults",
"(",
")",
"run",
".",
"enable_logging",
"(",
")",
"api",
"=",
"wandb",
".",
"apis",
".",
"InternalApi",
"(",
")",
"api",
... | A version of `wandb run` that the agent uses to run things. | [
"A",
"version",
"of",
"wandb",
"run",
"that",
"the",
"agent",
"uses",
"to",
"run",
"things",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/internal_cli.py#L49-L84 | train | 207,514 |
wandb/client | wandb/tensorboard/__init__.py | patch | def patch(save=True, tensorboardX=tensorboardX_loaded):
"""Monkeypatches tensorboard or tensorboardX so that all events are logged to tfevents files and wandb.
We save the tfevents files and graphs to wandb by default.
Arguments:
save, default: True - Passing False will skip sending events.
tensorboardX, default: True if module can be imported - You can override this when calling patch
"""
global Summary, Event
if tensorboardX:
tensorboard_module = "tensorboardX.writer"
if tensorflow_loaded:
wandb.termlog(
"Found TensorboardX and tensorflow, pass tensorboardX=False to patch regular tensorboard.")
from tensorboardX.proto.summary_pb2 import Summary
from tensorboardX.proto.event_pb2 import Event
else:
tensorboard_module = "tensorflow.python.summary.writer.writer"
from tensorflow.summary import Summary, Event
writers = set()
def _add_event(self, event, step, walltime=None):
event.wall_time = time.time() if walltime is None else walltime
if step is not None:
event.step = int(step)
try:
# TensorboardX uses _file_name
if hasattr(self.event_writer._ev_writer, "_file_name"):
name = self.event_writer._ev_writer._file_name
else:
name = self.event_writer._ev_writer.FileName().decode("utf-8")
writers.add(name)
# This is a little hacky, there is a case where the log_dir changes.
# Because the events files will have the same names in sub directories
# we simply overwrite the previous symlink in wandb.save if the log_dir
# changes.
log_dir = os.path.dirname(os.path.commonprefix(list(writers)))
filename = os.path.basename(name)
# Tensorboard loads all tfevents files in a directory and prepends
# their values with the path. Passing namespace to log allows us
# to nest the values in wandb
namespace = name.replace(filename, "").replace(
log_dir, "").strip(os.sep)
if save:
wandb.save(name, base_path=log_dir)
wandb.save(os.path.join(log_dir, "*.pbtxt"),
base_path=log_dir)
log(event, namespace=namespace, step=event.step)
except Exception as e:
wandb.termerror("Unable to log event %s" % e)
# six.reraise(type(e), e, sys.exc_info()[2])
self.event_writer.add_event(event)
writer = wandb.util.get_module(tensorboard_module)
writer.SummaryToEventTransformer._add_event = _add_event | python | def patch(save=True, tensorboardX=tensorboardX_loaded):
"""Monkeypatches tensorboard or tensorboardX so that all events are logged to tfevents files and wandb.
We save the tfevents files and graphs to wandb by default.
Arguments:
save, default: True - Passing False will skip sending events.
tensorboardX, default: True if module can be imported - You can override this when calling patch
"""
global Summary, Event
if tensorboardX:
tensorboard_module = "tensorboardX.writer"
if tensorflow_loaded:
wandb.termlog(
"Found TensorboardX and tensorflow, pass tensorboardX=False to patch regular tensorboard.")
from tensorboardX.proto.summary_pb2 import Summary
from tensorboardX.proto.event_pb2 import Event
else:
tensorboard_module = "tensorflow.python.summary.writer.writer"
from tensorflow.summary import Summary, Event
writers = set()
def _add_event(self, event, step, walltime=None):
event.wall_time = time.time() if walltime is None else walltime
if step is not None:
event.step = int(step)
try:
# TensorboardX uses _file_name
if hasattr(self.event_writer._ev_writer, "_file_name"):
name = self.event_writer._ev_writer._file_name
else:
name = self.event_writer._ev_writer.FileName().decode("utf-8")
writers.add(name)
# This is a little hacky, there is a case where the log_dir changes.
# Because the events files will have the same names in sub directories
# we simply overwrite the previous symlink in wandb.save if the log_dir
# changes.
log_dir = os.path.dirname(os.path.commonprefix(list(writers)))
filename = os.path.basename(name)
# Tensorboard loads all tfevents files in a directory and prepends
# their values with the path. Passing namespace to log allows us
# to nest the values in wandb
namespace = name.replace(filename, "").replace(
log_dir, "").strip(os.sep)
if save:
wandb.save(name, base_path=log_dir)
wandb.save(os.path.join(log_dir, "*.pbtxt"),
base_path=log_dir)
log(event, namespace=namespace, step=event.step)
except Exception as e:
wandb.termerror("Unable to log event %s" % e)
# six.reraise(type(e), e, sys.exc_info()[2])
self.event_writer.add_event(event)
writer = wandb.util.get_module(tensorboard_module)
writer.SummaryToEventTransformer._add_event = _add_event | [
"def",
"patch",
"(",
"save",
"=",
"True",
",",
"tensorboardX",
"=",
"tensorboardX_loaded",
")",
":",
"global",
"Summary",
",",
"Event",
"if",
"tensorboardX",
":",
"tensorboard_module",
"=",
"\"tensorboardX.writer\"",
"if",
"tensorflow_loaded",
":",
"wandb",
".",
... | Monkeypatches tensorboard or tensorboardX so that all events are logged to tfevents files and wandb.
We save the tfevents files and graphs to wandb by default.
Arguments:
save, default: True - Passing False will skip sending events.
tensorboardX, default: True if module can be imported - You can override this when calling patch | [
"Monkeypatches",
"tensorboard",
"or",
"tensorboardX",
"so",
"that",
"all",
"events",
"are",
"logged",
"to",
"tfevents",
"files",
"and",
"wandb",
".",
"We",
"save",
"the",
"tfevents",
"files",
"and",
"graphs",
"to",
"wandb",
"by",
"default",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/tensorboard/__init__.py#L20-L74 | train | 207,515 |
wandb/client | wandb/tensorboard/__init__.py | tf_summary_to_dict | def tf_summary_to_dict(tf_summary_str_or_pb, namespace=""):
"""Convert a Tensorboard Summary to a dictionary
Accepts either a tensorflow.summary.Summary
or one encoded as a string.
"""
values = {}
if isinstance(tf_summary_str_or_pb, Summary):
summary_pb = tf_summary_str_or_pb
elif isinstance(tf_summary_str_or_pb, Event):
summary_pb = tf_summary_str_or_pb.summary
values["global_step"] = tf_summary_str_or_pb.step
values["_timestamp"] = tf_summary_str_or_pb.wall_time
else:
summary_pb = Summary()
summary_pb.ParseFromString(tf_summary_str_or_pb)
for value in summary_pb.value:
kind = value.WhichOneof("value")
if kind == "simple_value":
values[namespaced_tag(value.tag, namespace)] = value.simple_value
elif kind == "image":
from PIL import Image
image = wandb.Image(Image.open(
six.BytesIO(value.image.encoded_image_string)))
tag_idx = value.tag.rsplit('/', 1)
if len(tag_idx) > 1 and tag_idx[1].isdigit():
tag, idx = tag_idx
values.setdefault(history_image_key(tag), []).append(image)
else:
values[history_image_key(value.tag)] = image
# Coming soon...
# elif kind == "audio":
# audio = wandb.Audio(six.BytesIO(value.audio.encoded_audio_string),
# sample_rate=value.audio.sample_rate, content_type=value.audio.content_type)
elif kind == "histo":
first = value.histo.bucket_limit[0] + \
value.histo.bucket_limit[0] - value.histo.bucket_limit[1]
last = value.histo.bucket_limit[-2] + \
value.histo.bucket_limit[-2] - value.histo.bucket_limit[-3]
np_histogram = (list(value.histo.bucket), [
first] + value.histo.bucket_limit[:-1] + [last])
values[namespaced_tag(value.tag)] = wandb.Histogram(
np_histogram=np_histogram)
return values | python | def tf_summary_to_dict(tf_summary_str_or_pb, namespace=""):
"""Convert a Tensorboard Summary to a dictionary
Accepts either a tensorflow.summary.Summary
or one encoded as a string.
"""
values = {}
if isinstance(tf_summary_str_or_pb, Summary):
summary_pb = tf_summary_str_or_pb
elif isinstance(tf_summary_str_or_pb, Event):
summary_pb = tf_summary_str_or_pb.summary
values["global_step"] = tf_summary_str_or_pb.step
values["_timestamp"] = tf_summary_str_or_pb.wall_time
else:
summary_pb = Summary()
summary_pb.ParseFromString(tf_summary_str_or_pb)
for value in summary_pb.value:
kind = value.WhichOneof("value")
if kind == "simple_value":
values[namespaced_tag(value.tag, namespace)] = value.simple_value
elif kind == "image":
from PIL import Image
image = wandb.Image(Image.open(
six.BytesIO(value.image.encoded_image_string)))
tag_idx = value.tag.rsplit('/', 1)
if len(tag_idx) > 1 and tag_idx[1].isdigit():
tag, idx = tag_idx
values.setdefault(history_image_key(tag), []).append(image)
else:
values[history_image_key(value.tag)] = image
# Coming soon...
# elif kind == "audio":
# audio = wandb.Audio(six.BytesIO(value.audio.encoded_audio_string),
# sample_rate=value.audio.sample_rate, content_type=value.audio.content_type)
elif kind == "histo":
first = value.histo.bucket_limit[0] + \
value.histo.bucket_limit[0] - value.histo.bucket_limit[1]
last = value.histo.bucket_limit[-2] + \
value.histo.bucket_limit[-2] - value.histo.bucket_limit[-3]
np_histogram = (list(value.histo.bucket), [
first] + value.histo.bucket_limit[:-1] + [last])
values[namespaced_tag(value.tag)] = wandb.Histogram(
np_histogram=np_histogram)
return values | [
"def",
"tf_summary_to_dict",
"(",
"tf_summary_str_or_pb",
",",
"namespace",
"=",
"\"\"",
")",
":",
"values",
"=",
"{",
"}",
"if",
"isinstance",
"(",
"tf_summary_str_or_pb",
",",
"Summary",
")",
":",
"summary_pb",
"=",
"tf_summary_str_or_pb",
"elif",
"isinstance",
... | Convert a Tensorboard Summary to a dictionary
Accepts either a tensorflow.summary.Summary
or one encoded as a string. | [
"Convert",
"a",
"Tensorboard",
"Summary",
"to",
"a",
"dictionary"
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/tensorboard/__init__.py#L100-L145 | train | 207,516 |
wandb/client | wandb/vendor/prompt_toolkit/layout/processors.py | HighlightSearchProcessor._get_search_text | def _get_search_text(self, cli):
"""
The text we are searching for.
"""
# When the search buffer has focus, take that text.
if self.preview_search(cli) and cli.buffers[self.search_buffer_name].text:
return cli.buffers[self.search_buffer_name].text
# Otherwise, take the text of the last active search.
else:
return self.get_search_state(cli).text | python | def _get_search_text(self, cli):
"""
The text we are searching for.
"""
# When the search buffer has focus, take that text.
if self.preview_search(cli) and cli.buffers[self.search_buffer_name].text:
return cli.buffers[self.search_buffer_name].text
# Otherwise, take the text of the last active search.
else:
return self.get_search_state(cli).text | [
"def",
"_get_search_text",
"(",
"self",
",",
"cli",
")",
":",
"# When the search buffer has focus, take that text.",
"if",
"self",
".",
"preview_search",
"(",
"cli",
")",
"and",
"cli",
".",
"buffers",
"[",
"self",
".",
"search_buffer_name",
"]",
".",
"text",
":"... | The text we are searching for. | [
"The",
"text",
"we",
"are",
"searching",
"for",
"."
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/layout/processors.py#L107-L116 | train | 207,517 |
wandb/client | wandb/wandb_socket.py | Server.listen | def listen(self, max_seconds=30):
"""Waits to receive up to two bytes for up to max_seconds"""
if not self.connection:
self.connect()
start = time.time()
conn, _, err = select([self.connection], [], [
self.connection], max_seconds)
try:
if len(err) > 0:
raise socket.error("Couldn't open socket")
message = b''
while True:
if time.time() - start > max_seconds:
raise socket.error(
"Timeout of %s seconds waiting for W&B process" % max_seconds)
res = self.connection.recv(1024)
term = res.find(b'\0')
if term != -1:
message += res[:term]
break
else:
message += res
message = json.loads(message.decode('utf8'))
if message['status'] == 'done':
return True, None
elif message['status'] == 'ready':
return True, message
elif message['status'] == 'launch_error':
return False, None
else:
raise socket.error("Invalid status: %s" % message['status'])
except (socket.error, ValueError) as e:
util.sentry_exc(e)
return False, None | python | def listen(self, max_seconds=30):
"""Waits to receive up to two bytes for up to max_seconds"""
if not self.connection:
self.connect()
start = time.time()
conn, _, err = select([self.connection], [], [
self.connection], max_seconds)
try:
if len(err) > 0:
raise socket.error("Couldn't open socket")
message = b''
while True:
if time.time() - start > max_seconds:
raise socket.error(
"Timeout of %s seconds waiting for W&B process" % max_seconds)
res = self.connection.recv(1024)
term = res.find(b'\0')
if term != -1:
message += res[:term]
break
else:
message += res
message = json.loads(message.decode('utf8'))
if message['status'] == 'done':
return True, None
elif message['status'] == 'ready':
return True, message
elif message['status'] == 'launch_error':
return False, None
else:
raise socket.error("Invalid status: %s" % message['status'])
except (socket.error, ValueError) as e:
util.sentry_exc(e)
return False, None | [
"def",
"listen",
"(",
"self",
",",
"max_seconds",
"=",
"30",
")",
":",
"if",
"not",
"self",
".",
"connection",
":",
"self",
".",
"connect",
"(",
")",
"start",
"=",
"time",
".",
"time",
"(",
")",
"conn",
",",
"_",
",",
"err",
"=",
"select",
"(",
... | Waits to receive up to two bytes for up to max_seconds | [
"Waits",
"to",
"receive",
"up",
"to",
"two",
"bytes",
"for",
"up",
"to",
"max_seconds"
] | 7d08954ed5674fee223cd85ed0d8518fe47266b2 | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/wandb_socket.py#L39-L72 | train | 207,518 |
OCA/ddmrp | ddmrp_adjustment/models/stock_warehouse_orderpoint.py | StockWarehouseOrderpoint._calc_adu | def _calc_adu(self):
"""Apply DAFs if existing for the buffer."""
res = super()._calc_adu()
self.ensure_one()
dafs_to_apply = self.env['ddmrp.adjustment'].search(
self._daf_to_apply_domain())
if dafs_to_apply:
daf = 1
values = dafs_to_apply.mapped('value')
for val in values:
daf *= val
prev = self.adu
self.adu *= daf
_logger.debug(
"DAF=%s applied to %s. ADU: %s -> %s" %
(daf, self.name, prev, self.adu))
# Compute generated demand to be applied to components:
dafs_to_explode = self.env['ddmrp.adjustment'].search(
self._daf_to_apply_domain(False))
for daf in dafs_to_explode:
prev = self.adu
increased_demand = prev * daf.value - prev
self.explode_demand_to_components(
daf, increased_demand, self.product_uom)
return res | python | def _calc_adu(self):
"""Apply DAFs if existing for the buffer."""
res = super()._calc_adu()
self.ensure_one()
dafs_to_apply = self.env['ddmrp.adjustment'].search(
self._daf_to_apply_domain())
if dafs_to_apply:
daf = 1
values = dafs_to_apply.mapped('value')
for val in values:
daf *= val
prev = self.adu
self.adu *= daf
_logger.debug(
"DAF=%s applied to %s. ADU: %s -> %s" %
(daf, self.name, prev, self.adu))
# Compute generated demand to be applied to components:
dafs_to_explode = self.env['ddmrp.adjustment'].search(
self._daf_to_apply_domain(False))
for daf in dafs_to_explode:
prev = self.adu
increased_demand = prev * daf.value - prev
self.explode_demand_to_components(
daf, increased_demand, self.product_uom)
return res | [
"def",
"_calc_adu",
"(",
"self",
")",
":",
"res",
"=",
"super",
"(",
")",
".",
"_calc_adu",
"(",
")",
"self",
".",
"ensure_one",
"(",
")",
"dafs_to_apply",
"=",
"self",
".",
"env",
"[",
"'ddmrp.adjustment'",
"]",
".",
"search",
"(",
"self",
".",
"_da... | Apply DAFs if existing for the buffer. | [
"Apply",
"DAFs",
"if",
"existing",
"for",
"the",
"buffer",
"."
] | 86c47b05edd29dc355e2e7b9dd394f800f71a4b4 | https://github.com/OCA/ddmrp/blob/86c47b05edd29dc355e2e7b9dd394f800f71a4b4/ddmrp_adjustment/models/stock_warehouse_orderpoint.py#L40-L64 | train | 207,519 |
OCA/ddmrp | ddmrp_adjustment/models/stock_warehouse_orderpoint.py | StockWarehouseOrderpoint.cron_ddmrp_adu | def cron_ddmrp_adu(self, automatic=False):
"""Apply extra demand originated by Demand Adjustment Factors to
components after the cron update of all the buffers."""
self.env['ddmrp.adjustment.demand'].search([]).unlink()
super().cron_ddmrp_adu(automatic)
today = fields.Date.today()
for op in self.search([]).filtered('extra_demand_ids'):
to_add = sum(op.extra_demand_ids.filtered(
lambda r: r.date_start <= today <= r.date_end
).mapped('extra_demand'))
if to_add:
op.adu += to_add
_logger.debug(
"DAFs-originated demand applied. %s: ADU += %s"
% (op.name, to_add)) | python | def cron_ddmrp_adu(self, automatic=False):
"""Apply extra demand originated by Demand Adjustment Factors to
components after the cron update of all the buffers."""
self.env['ddmrp.adjustment.demand'].search([]).unlink()
super().cron_ddmrp_adu(automatic)
today = fields.Date.today()
for op in self.search([]).filtered('extra_demand_ids'):
to_add = sum(op.extra_demand_ids.filtered(
lambda r: r.date_start <= today <= r.date_end
).mapped('extra_demand'))
if to_add:
op.adu += to_add
_logger.debug(
"DAFs-originated demand applied. %s: ADU += %s"
% (op.name, to_add)) | [
"def",
"cron_ddmrp_adu",
"(",
"self",
",",
"automatic",
"=",
"False",
")",
":",
"self",
".",
"env",
"[",
"'ddmrp.adjustment.demand'",
"]",
".",
"search",
"(",
"[",
"]",
")",
".",
"unlink",
"(",
")",
"super",
"(",
")",
".",
"cron_ddmrp_adu",
"(",
"autom... | Apply extra demand originated by Demand Adjustment Factors to
components after the cron update of all the buffers. | [
"Apply",
"extra",
"demand",
"originated",
"by",
"Demand",
"Adjustment",
"Factors",
"to",
"components",
"after",
"the",
"cron",
"update",
"of",
"all",
"the",
"buffers",
"."
] | 86c47b05edd29dc355e2e7b9dd394f800f71a4b4 | https://github.com/OCA/ddmrp/blob/86c47b05edd29dc355e2e7b9dd394f800f71a4b4/ddmrp_adjustment/models/stock_warehouse_orderpoint.py#L118-L132 | train | 207,520 |
OCA/ddmrp | ddmrp_adjustment/models/stock_warehouse_orderpoint.py | StockWarehouseOrderpoint._compute_dlt | def _compute_dlt(self):
"""Apply Lead Time Adj Factor if existing"""
res = super()._compute_dlt()
for rec in self:
ltaf_to_apply = self.env['ddmrp.adjustment'].search(
rec._ltaf_to_apply_domain())
if ltaf_to_apply:
ltaf = 1
values = ltaf_to_apply.mapped('value')
for val in values:
ltaf *= val
prev = rec.dlt
rec.dlt *= ltaf
_logger.debug(
"LTAF=%s applied to %s. DLT: %s -> %s" %
(ltaf, rec.name, prev, rec.dlt))
return res | python | def _compute_dlt(self):
"""Apply Lead Time Adj Factor if existing"""
res = super()._compute_dlt()
for rec in self:
ltaf_to_apply = self.env['ddmrp.adjustment'].search(
rec._ltaf_to_apply_domain())
if ltaf_to_apply:
ltaf = 1
values = ltaf_to_apply.mapped('value')
for val in values:
ltaf *= val
prev = rec.dlt
rec.dlt *= ltaf
_logger.debug(
"LTAF=%s applied to %s. DLT: %s -> %s" %
(ltaf, rec.name, prev, rec.dlt))
return res | [
"def",
"_compute_dlt",
"(",
"self",
")",
":",
"res",
"=",
"super",
"(",
")",
".",
"_compute_dlt",
"(",
")",
"for",
"rec",
"in",
"self",
":",
"ltaf_to_apply",
"=",
"self",
".",
"env",
"[",
"'ddmrp.adjustment'",
"]",
".",
"search",
"(",
"rec",
".",
"_l... | Apply Lead Time Adj Factor if existing | [
"Apply",
"Lead",
"Time",
"Adj",
"Factor",
"if",
"existing"
] | 86c47b05edd29dc355e2e7b9dd394f800f71a4b4 | https://github.com/OCA/ddmrp/blob/86c47b05edd29dc355e2e7b9dd394f800f71a4b4/ddmrp_adjustment/models/stock_warehouse_orderpoint.py#L144-L160 | train | 207,521 |
amirziai/flatten | flatten_json.py | flatten | def flatten(nested_dict, separator="_", root_keys_to_ignore=set()):
"""
Flattens a dictionary with nested structure to a dictionary with no
hierarchy
Consider ignoring keys that you are not interested in to prevent
unnecessary processing
This is specially true for very deep objects
:param nested_dict: dictionary we want to flatten
:param separator: string to separate dictionary keys by
:param root_keys_to_ignore: set of root keys to ignore from flattening
:return: flattened dictionary
"""
assert isinstance(nested_dict, dict), "flatten requires a dictionary input"
assert isinstance(separator, six.string_types), "separator must be string"
# This global dictionary stores the flattened keys and values and is
# ultimately returned
flattened_dict = dict()
def _flatten(object_, key):
"""
For dict, list and set objects_ calls itself on the elements and for
other types assigns the object_ to
the corresponding key in the global flattened_dict
:param object_: object to flatten
:param key: carries the concatenated key for the object_
:return: None
"""
# Empty object can't be iterated, take as is
if not object_:
flattened_dict[key] = object_
# These object types support iteration
elif isinstance(object_, dict):
for object_key in object_:
if not (not key and object_key in root_keys_to_ignore):
_flatten(object_[object_key], _construct_key(key,
separator,
object_key))
elif isinstance(object_, (list, set, tuple)):
for index, item in enumerate(object_):
_flatten(item, _construct_key(key, separator, index))
# Anything left take as is
else:
flattened_dict[key] = object_
_flatten(nested_dict, None)
return flattened_dict | python | def flatten(nested_dict, separator="_", root_keys_to_ignore=set()):
"""
Flattens a dictionary with nested structure to a dictionary with no
hierarchy
Consider ignoring keys that you are not interested in to prevent
unnecessary processing
This is specially true for very deep objects
:param nested_dict: dictionary we want to flatten
:param separator: string to separate dictionary keys by
:param root_keys_to_ignore: set of root keys to ignore from flattening
:return: flattened dictionary
"""
assert isinstance(nested_dict, dict), "flatten requires a dictionary input"
assert isinstance(separator, six.string_types), "separator must be string"
# This global dictionary stores the flattened keys and values and is
# ultimately returned
flattened_dict = dict()
def _flatten(object_, key):
"""
For dict, list and set objects_ calls itself on the elements and for
other types assigns the object_ to
the corresponding key in the global flattened_dict
:param object_: object to flatten
:param key: carries the concatenated key for the object_
:return: None
"""
# Empty object can't be iterated, take as is
if not object_:
flattened_dict[key] = object_
# These object types support iteration
elif isinstance(object_, dict):
for object_key in object_:
if not (not key and object_key in root_keys_to_ignore):
_flatten(object_[object_key], _construct_key(key,
separator,
object_key))
elif isinstance(object_, (list, set, tuple)):
for index, item in enumerate(object_):
_flatten(item, _construct_key(key, separator, index))
# Anything left take as is
else:
flattened_dict[key] = object_
_flatten(nested_dict, None)
return flattened_dict | [
"def",
"flatten",
"(",
"nested_dict",
",",
"separator",
"=",
"\"_\"",
",",
"root_keys_to_ignore",
"=",
"set",
"(",
")",
")",
":",
"assert",
"isinstance",
"(",
"nested_dict",
",",
"dict",
")",
",",
"\"flatten requires a dictionary input\"",
"assert",
"isinstance",
... | Flattens a dictionary with nested structure to a dictionary with no
hierarchy
Consider ignoring keys that you are not interested in to prevent
unnecessary processing
This is specially true for very deep objects
:param nested_dict: dictionary we want to flatten
:param separator: string to separate dictionary keys by
:param root_keys_to_ignore: set of root keys to ignore from flattening
:return: flattened dictionary | [
"Flattens",
"a",
"dictionary",
"with",
"nested",
"structure",
"to",
"a",
"dictionary",
"with",
"no",
"hierarchy",
"Consider",
"ignoring",
"keys",
"that",
"you",
"are",
"not",
"interested",
"in",
"to",
"prevent",
"unnecessary",
"processing",
"This",
"is",
"specia... | e8e2cbbdd6fe21177bfc0ce034562463ae555799 | https://github.com/amirziai/flatten/blob/e8e2cbbdd6fe21177bfc0ce034562463ae555799/flatten_json.py#L32-L79 | train | 207,522 |
amirziai/flatten | util.py | check_if_numbers_are_consecutive | def check_if_numbers_are_consecutive(list_):
"""
Returns True if numbers in the list are consecutive
:param list_: list of integers
:return: Boolean
"""
return all((True if second - first == 1 else False
for first, second in zip(list_[:-1], list_[1:]))) | python | def check_if_numbers_are_consecutive(list_):
"""
Returns True if numbers in the list are consecutive
:param list_: list of integers
:return: Boolean
"""
return all((True if second - first == 1 else False
for first, second in zip(list_[:-1], list_[1:]))) | [
"def",
"check_if_numbers_are_consecutive",
"(",
"list_",
")",
":",
"return",
"all",
"(",
"(",
"True",
"if",
"second",
"-",
"first",
"==",
"1",
"else",
"False",
"for",
"first",
",",
"second",
"in",
"zip",
"(",
"list_",
"[",
":",
"-",
"1",
"]",
",",
"l... | Returns True if numbers in the list are consecutive
:param list_: list of integers
:return: Boolean | [
"Returns",
"True",
"if",
"numbers",
"in",
"the",
"list",
"are",
"consecutive"
] | e8e2cbbdd6fe21177bfc0ce034562463ae555799 | https://github.com/amirziai/flatten/blob/e8e2cbbdd6fe21177bfc0ce034562463ae555799/util.py#L1-L9 | train | 207,523 |
FNNDSC/med2image | med2image/_colors.py | Colors.strip | def strip( text ):
'''
Strips all color codes from a text.
'''
members = [attr for attr in Colors.__dict__.keys() if not attr.startswith( "__" ) and not attr == 'strip']
for c in members:
text = text.replace( vars( Colors )[c], '' )
return text | python | def strip( text ):
'''
Strips all color codes from a text.
'''
members = [attr for attr in Colors.__dict__.keys() if not attr.startswith( "__" ) and not attr == 'strip']
for c in members:
text = text.replace( vars( Colors )[c], '' )
return text | [
"def",
"strip",
"(",
"text",
")",
":",
"members",
"=",
"[",
"attr",
"for",
"attr",
"in",
"Colors",
".",
"__dict__",
".",
"keys",
"(",
")",
"if",
"not",
"attr",
".",
"startswith",
"(",
"\"__\"",
")",
"and",
"not",
"attr",
"==",
"'strip'",
"]",
"for"... | Strips all color codes from a text. | [
"Strips",
"all",
"color",
"codes",
"from",
"a",
"text",
"."
] | 638d5d230de47608af20f9764acf8e382c2bf2ff | https://github.com/FNNDSC/med2image/blob/638d5d230de47608af20f9764acf8e382c2bf2ff/med2image/_colors.py#L53-L61 | train | 207,524 |
FNNDSC/med2image | med2image/message.py | Message.vprintf | def vprintf(self, alevel, format, *args):
'''
A verbosity-aware printf.
'''
if self._verbosity and self._verbosity >= alevel:
sys.stdout.write(format % args) | python | def vprintf(self, alevel, format, *args):
'''
A verbosity-aware printf.
'''
if self._verbosity and self._verbosity >= alevel:
sys.stdout.write(format % args) | [
"def",
"vprintf",
"(",
"self",
",",
"alevel",
",",
"format",
",",
"*",
"args",
")",
":",
"if",
"self",
".",
"_verbosity",
"and",
"self",
".",
"_verbosity",
">=",
"alevel",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"format",
"%",
"args",
")"
] | A verbosity-aware printf. | [
"A",
"verbosity",
"-",
"aware",
"printf",
"."
] | 638d5d230de47608af20f9764acf8e382c2bf2ff | https://github.com/FNNDSC/med2image/blob/638d5d230de47608af20f9764acf8e382c2bf2ff/med2image/message.py#L194-L200 | train | 207,525 |
FNNDSC/med2image | med2image/systemMisc.py | density | def density(a_M, *args, **kwargs):
"""
ARGS
a_M matrix to analyze
*args[0] optional mask matrix; if passed, calculate
density of a_M using non-zero elements of
args[0] as a mask.
DESC
Determine the "density" of a passed matrix. Two densities are returned:
o f_actualDensity -- density of the matrix using matrix values
as "mass"
o f_binaryDensity -- density of the matrix irrespective of actual
matrix values
If the passed matrix contains only "ones", the f_binaryDensity will
be equal to the f_actualDensity.
"""
rows, cols = a_M.shape
a_Mmask = ones( (rows, cols) )
if len(args):
a_Mmask = args[0]
a_M *= a_Mmask
# The "binary" density determines the density of nonzero elements,
# irrespective of their actual value
f_binaryMass = float(size(nonzero(a_M)[0]))
f_actualMass = a_M.sum()
f_area = float(size(nonzero(a_Mmask)[0]))
f_binaryDensity = f_binaryMass / f_area;
f_actualDensity = f_actualMass / f_area;
return f_actualDensity, f_binaryDensity | python | def density(a_M, *args, **kwargs):
"""
ARGS
a_M matrix to analyze
*args[0] optional mask matrix; if passed, calculate
density of a_M using non-zero elements of
args[0] as a mask.
DESC
Determine the "density" of a passed matrix. Two densities are returned:
o f_actualDensity -- density of the matrix using matrix values
as "mass"
o f_binaryDensity -- density of the matrix irrespective of actual
matrix values
If the passed matrix contains only "ones", the f_binaryDensity will
be equal to the f_actualDensity.
"""
rows, cols = a_M.shape
a_Mmask = ones( (rows, cols) )
if len(args):
a_Mmask = args[0]
a_M *= a_Mmask
# The "binary" density determines the density of nonzero elements,
# irrespective of their actual value
f_binaryMass = float(size(nonzero(a_M)[0]))
f_actualMass = a_M.sum()
f_area = float(size(nonzero(a_Mmask)[0]))
f_binaryDensity = f_binaryMass / f_area;
f_actualDensity = f_actualMass / f_area;
return f_actualDensity, f_binaryDensity | [
"def",
"density",
"(",
"a_M",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"rows",
",",
"cols",
"=",
"a_M",
".",
"shape",
"a_Mmask",
"=",
"ones",
"(",
"(",
"rows",
",",
"cols",
")",
")",
"if",
"len",
"(",
"args",
")",
":",
"a_Mmask",
... | ARGS
a_M matrix to analyze
*args[0] optional mask matrix; if passed, calculate
density of a_M using non-zero elements of
args[0] as a mask.
DESC
Determine the "density" of a passed matrix. Two densities are returned:
o f_actualDensity -- density of the matrix using matrix values
as "mass"
o f_binaryDensity -- density of the matrix irrespective of actual
matrix values
If the passed matrix contains only "ones", the f_binaryDensity will
be equal to the f_actualDensity. | [
"ARGS",
"a_M",
"matrix",
"to",
"analyze"
] | 638d5d230de47608af20f9764acf8e382c2bf2ff | https://github.com/FNNDSC/med2image/blob/638d5d230de47608af20f9764acf8e382c2bf2ff/med2image/systemMisc.py#L65-L102 | train | 207,526 |
FNNDSC/med2image | med2image/systemMisc.py | cdf | def cdf(arr, **kwargs):
"""
ARGS
arr array to calculate cumulative distribution function
**kwargs
Passed directly to numpy.histogram. Typical options include:
bins = <num_bins>
normed = True|False
DESC
Determines the cumulative distribution function.
"""
counts, bin_edges = histogram(arr, **kwargs)
cdf = cumsum(counts)
return cdf | python | def cdf(arr, **kwargs):
"""
ARGS
arr array to calculate cumulative distribution function
**kwargs
Passed directly to numpy.histogram. Typical options include:
bins = <num_bins>
normed = True|False
DESC
Determines the cumulative distribution function.
"""
counts, bin_edges = histogram(arr, **kwargs)
cdf = cumsum(counts)
return cdf | [
"def",
"cdf",
"(",
"arr",
",",
"*",
"*",
"kwargs",
")",
":",
"counts",
",",
"bin_edges",
"=",
"histogram",
"(",
"arr",
",",
"*",
"*",
"kwargs",
")",
"cdf",
"=",
"cumsum",
"(",
"counts",
")",
"return",
"cdf"
] | ARGS
arr array to calculate cumulative distribution function
**kwargs
Passed directly to numpy.histogram. Typical options include:
bins = <num_bins>
normed = True|False
DESC
Determines the cumulative distribution function. | [
"ARGS",
"arr",
"array",
"to",
"calculate",
"cumulative",
"distribution",
"function"
] | 638d5d230de47608af20f9764acf8e382c2bf2ff | https://github.com/FNNDSC/med2image/blob/638d5d230de47608af20f9764acf8e382c2bf2ff/med2image/systemMisc.py#L105-L120 | train | 207,527 |
FNNDSC/med2image | med2image/systemMisc.py | array2DIndices_enumerate | def array2DIndices_enumerate(arr):
"""
DESC
Given a 2D array defined by arr, prepare an explicit list
of the indices.
ARGS
arr in 2 element array with the first
element the rows and the second
the cols
RET
A list of explicit 2D coordinates.
"""
rows = arr[0]
cols = arr[1]
arr_index = zeros((rows * cols, 2))
count = 0
for row in arange(0, rows):
for col in arange(0, cols):
arr_index[count] = array([row, col])
count = count + 1
return arr_index | python | def array2DIndices_enumerate(arr):
"""
DESC
Given a 2D array defined by arr, prepare an explicit list
of the indices.
ARGS
arr in 2 element array with the first
element the rows and the second
the cols
RET
A list of explicit 2D coordinates.
"""
rows = arr[0]
cols = arr[1]
arr_index = zeros((rows * cols, 2))
count = 0
for row in arange(0, rows):
for col in arange(0, cols):
arr_index[count] = array([row, col])
count = count + 1
return arr_index | [
"def",
"array2DIndices_enumerate",
"(",
"arr",
")",
":",
"rows",
"=",
"arr",
"[",
"0",
"]",
"cols",
"=",
"arr",
"[",
"1",
"]",
"arr_index",
"=",
"zeros",
"(",
"(",
"rows",
"*",
"cols",
",",
"2",
")",
")",
"count",
"=",
"0",
"for",
"row",
"in",
... | DESC
Given a 2D array defined by arr, prepare an explicit list
of the indices.
ARGS
arr in 2 element array with the first
element the rows and the second
the cols
RET
A list of explicit 2D coordinates. | [
"DESC",
"Given",
"a",
"2D",
"array",
"defined",
"by",
"arr",
"prepare",
"an",
"explicit",
"list",
"of",
"the",
"indices",
"."
] | 638d5d230de47608af20f9764acf8e382c2bf2ff | https://github.com/FNNDSC/med2image/blob/638d5d230de47608af20f9764acf8e382c2bf2ff/med2image/systemMisc.py#L217-L240 | train | 207,528 |
FNNDSC/med2image | med2image/systemMisc.py | toc | def toc(*args, **kwargs):
"""
Port of the MatLAB function of same name
Behaviour is controllable to some extent by the keyword
args:
"""
global Gtic_start
f_elapsedTime = time.time() - Gtic_start
for key, value in kwargs.items():
if key == 'sysprint': return value % f_elapsedTime
if key == 'default': return "Elapsed time = %f seconds." % f_elapsedTime
return f_elapsedTime | python | def toc(*args, **kwargs):
"""
Port of the MatLAB function of same name
Behaviour is controllable to some extent by the keyword
args:
"""
global Gtic_start
f_elapsedTime = time.time() - Gtic_start
for key, value in kwargs.items():
if key == 'sysprint': return value % f_elapsedTime
if key == 'default': return "Elapsed time = %f seconds." % f_elapsedTime
return f_elapsedTime | [
"def",
"toc",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"global",
"Gtic_start",
"f_elapsedTime",
"=",
"time",
".",
"time",
"(",
")",
"-",
"Gtic_start",
"for",
"key",
",",
"value",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"if",
"key",... | Port of the MatLAB function of same name
Behaviour is controllable to some extent by the keyword
args: | [
"Port",
"of",
"the",
"MatLAB",
"function",
"of",
"same",
"name"
] | 638d5d230de47608af20f9764acf8e382c2bf2ff | https://github.com/FNNDSC/med2image/blob/638d5d230de47608af20f9764acf8e382c2bf2ff/med2image/systemMisc.py#L333-L347 | train | 207,529 |
FNNDSC/med2image | med2image/systemMisc.py | base10toN | def base10toN(num, n):
"""Change a num to a base-n number.
Up to base-36 is supported without special notation."""
num_rep = {10:'a',
11:'b',
12:'c',
13:'d',
14:'e',
15:'f',
16:'g',
17:'h',
18:'i',
19:'j',
20:'k',
21:'l',
22:'m',
23:'n',
24:'o',
25:'p',
26:'q',
27:'r',
28:'s',
29:'t',
30:'u',
31:'v',
32:'w',
33:'x',
34:'y',
35:'z'}
new_num_string = ''
new_num_arr = array(())
current = num
while current != 0:
remainder = current % n
if 36 > remainder > 9:
remainder_string = num_rep[remainder]
elif remainder >= 36:
remainder_string = '(' + str(remainder) + ')'
else:
remainder_string = str(remainder)
new_num_string = remainder_string + new_num_string
new_num_arr = r_[remainder, new_num_arr]
current = current / n
print(new_num_arr)
return new_num_string | python | def base10toN(num, n):
"""Change a num to a base-n number.
Up to base-36 is supported without special notation."""
num_rep = {10:'a',
11:'b',
12:'c',
13:'d',
14:'e',
15:'f',
16:'g',
17:'h',
18:'i',
19:'j',
20:'k',
21:'l',
22:'m',
23:'n',
24:'o',
25:'p',
26:'q',
27:'r',
28:'s',
29:'t',
30:'u',
31:'v',
32:'w',
33:'x',
34:'y',
35:'z'}
new_num_string = ''
new_num_arr = array(())
current = num
while current != 0:
remainder = current % n
if 36 > remainder > 9:
remainder_string = num_rep[remainder]
elif remainder >= 36:
remainder_string = '(' + str(remainder) + ')'
else:
remainder_string = str(remainder)
new_num_string = remainder_string + new_num_string
new_num_arr = r_[remainder, new_num_arr]
current = current / n
print(new_num_arr)
return new_num_string | [
"def",
"base10toN",
"(",
"num",
",",
"n",
")",
":",
"num_rep",
"=",
"{",
"10",
":",
"'a'",
",",
"11",
":",
"'b'",
",",
"12",
":",
"'c'",
",",
"13",
":",
"'d'",
",",
"14",
":",
"'e'",
",",
"15",
":",
"'f'",
",",
"16",
":",
"'g'",
",",
"17"... | Change a num to a base-n number.
Up to base-36 is supported without special notation. | [
"Change",
"a",
"num",
"to",
"a",
"base",
"-",
"n",
"number",
".",
"Up",
"to",
"base",
"-",
"36",
"is",
"supported",
"without",
"special",
"notation",
"."
] | 638d5d230de47608af20f9764acf8e382c2bf2ff | https://github.com/FNNDSC/med2image/blob/638d5d230de47608af20f9764acf8e382c2bf2ff/med2image/systemMisc.py#L768-L812 | train | 207,530 |
FNNDSC/med2image | med2image/systemMisc.py | list_i2str | def list_i2str(ilist):
"""
Convert an integer list into a string list.
"""
slist = []
for el in ilist:
slist.append(str(el))
return slist | python | def list_i2str(ilist):
"""
Convert an integer list into a string list.
"""
slist = []
for el in ilist:
slist.append(str(el))
return slist | [
"def",
"list_i2str",
"(",
"ilist",
")",
":",
"slist",
"=",
"[",
"]",
"for",
"el",
"in",
"ilist",
":",
"slist",
".",
"append",
"(",
"str",
"(",
"el",
")",
")",
"return",
"slist"
] | Convert an integer list into a string list. | [
"Convert",
"an",
"integer",
"list",
"into",
"a",
"string",
"list",
"."
] | 638d5d230de47608af20f9764acf8e382c2bf2ff | https://github.com/FNNDSC/med2image/blob/638d5d230de47608af20f9764acf8e382c2bf2ff/med2image/systemMisc.py#L814-L821 | train | 207,531 |
FNNDSC/med2image | med2image/systemMisc.py | shellne | def shellne(command):
"""
Runs 'commands' on the underlying shell; any stderr is echo'd to the
console.
Raises a RuntimeException on any shell exec errors.
"""
child = os.popen(command)
data = child.read()
err = child.close()
if err:
raise RuntimeError('%s failed w/ exit code %d' % (command, err))
return data | python | def shellne(command):
"""
Runs 'commands' on the underlying shell; any stderr is echo'd to the
console.
Raises a RuntimeException on any shell exec errors.
"""
child = os.popen(command)
data = child.read()
err = child.close()
if err:
raise RuntimeError('%s failed w/ exit code %d' % (command, err))
return data | [
"def",
"shellne",
"(",
"command",
")",
":",
"child",
"=",
"os",
".",
"popen",
"(",
"command",
")",
"data",
"=",
"child",
".",
"read",
"(",
")",
"err",
"=",
"child",
".",
"close",
"(",
")",
"if",
"err",
":",
"raise",
"RuntimeError",
"(",
"'%s failed... | Runs 'commands' on the underlying shell; any stderr is echo'd to the
console.
Raises a RuntimeException on any shell exec errors. | [
"Runs",
"commands",
"on",
"the",
"underlying",
"shell",
";",
"any",
"stderr",
"is",
"echo",
"d",
"to",
"the",
"console",
"."
] | 638d5d230de47608af20f9764acf8e382c2bf2ff | https://github.com/FNNDSC/med2image/blob/638d5d230de47608af20f9764acf8e382c2bf2ff/med2image/systemMisc.py#L1034-L1047 | train | 207,532 |
FNNDSC/med2image | med2image/systemMisc.py | find | def find(pattern, root=os.curdir):
'''Helper around 'locate' '''
hits = ''
for F in locate(pattern, root):
hits = hits + F + '\n'
l = hits.split('\n')
if(not len(l[-1])): l.pop()
if len(l) == 1 and not len(l[0]):
return None
else:
return l | python | def find(pattern, root=os.curdir):
'''Helper around 'locate' '''
hits = ''
for F in locate(pattern, root):
hits = hits + F + '\n'
l = hits.split('\n')
if(not len(l[-1])): l.pop()
if len(l) == 1 and not len(l[0]):
return None
else:
return l | [
"def",
"find",
"(",
"pattern",
",",
"root",
"=",
"os",
".",
"curdir",
")",
":",
"hits",
"=",
"''",
"for",
"F",
"in",
"locate",
"(",
"pattern",
",",
"root",
")",
":",
"hits",
"=",
"hits",
"+",
"F",
"+",
"'\\n'",
"l",
"=",
"hits",
".",
"split",
... | Helper around 'locate' | [
"Helper",
"around",
"locate"
] | 638d5d230de47608af20f9764acf8e382c2bf2ff | https://github.com/FNNDSC/med2image/blob/638d5d230de47608af20f9764acf8e382c2bf2ff/med2image/systemMisc.py#L1136-L1146 | train | 207,533 |
FNNDSC/med2image | med2image/systemMisc.py | switch.match | def match(self, *args):
"""Indicate whether or not to enter a case suite"""
if self.fall or not args:
return True
elif self.value in args: # changed for v1.5, see below
self.fall = True
return True
else:
return False | python | def match(self, *args):
"""Indicate whether or not to enter a case suite"""
if self.fall or not args:
return True
elif self.value in args: # changed for v1.5, see below
self.fall = True
return True
else:
return False | [
"def",
"match",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"self",
".",
"fall",
"or",
"not",
"args",
":",
"return",
"True",
"elif",
"self",
".",
"value",
"in",
"args",
":",
"# changed for v1.5, see below",
"self",
".",
"fall",
"=",
"True",
"return"... | Indicate whether or not to enter a case suite | [
"Indicate",
"whether",
"or",
"not",
"to",
"enter",
"a",
"case",
"suite"
] | 638d5d230de47608af20f9764acf8e382c2bf2ff | https://github.com/FNNDSC/med2image/blob/638d5d230de47608af20f9764acf8e382c2bf2ff/med2image/systemMisc.py#L1245-L1253 | train | 207,534 |
FNNDSC/med2image | med2image/med2image.py | med2image.process_slice | def process_slice(self, b_rot90=None):
'''
Processes a single slice.
'''
if b_rot90:
self._Mnp_2Dslice = np.rot90(self._Mnp_2Dslice)
if self.func == 'invertIntensities':
self.invert_slice_intensities() | python | def process_slice(self, b_rot90=None):
'''
Processes a single slice.
'''
if b_rot90:
self._Mnp_2Dslice = np.rot90(self._Mnp_2Dslice)
if self.func == 'invertIntensities':
self.invert_slice_intensities() | [
"def",
"process_slice",
"(",
"self",
",",
"b_rot90",
"=",
"None",
")",
":",
"if",
"b_rot90",
":",
"self",
".",
"_Mnp_2Dslice",
"=",
"np",
".",
"rot90",
"(",
"self",
".",
"_Mnp_2Dslice",
")",
"if",
"self",
".",
"func",
"==",
"'invertIntensities'",
":",
... | Processes a single slice. | [
"Processes",
"a",
"single",
"slice",
"."
] | 638d5d230de47608af20f9764acf8e382c2bf2ff | https://github.com/FNNDSC/med2image/blob/638d5d230de47608af20f9764acf8e382c2bf2ff/med2image/med2image.py#L307-L314 | train | 207,535 |
FNNDSC/med2image | med2image/med2image.py | med2image.slice_save | def slice_save(self, astr_outputFile):
'''
Saves a single slice.
ARGS
o astr_output
The output filename to save the slice to.
'''
self._log('Outputfile = %s\n' % astr_outputFile)
fformat = astr_outputFile.split('.')[-1]
if fformat == 'dcm':
if self._dcm:
self._dcm.pixel_array.flat = self._Mnp_2Dslice.flat
self._dcm.PixelData = self._dcm.pixel_array.tostring()
self._dcm.save_as(astr_outputFile)
else:
raise ValueError('dcm output format only available for DICOM files')
else:
pylab.imsave(astr_outputFile, self._Mnp_2Dslice, format=fformat, cmap = cm.Greys_r) | python | def slice_save(self, astr_outputFile):
'''
Saves a single slice.
ARGS
o astr_output
The output filename to save the slice to.
'''
self._log('Outputfile = %s\n' % astr_outputFile)
fformat = astr_outputFile.split('.')[-1]
if fformat == 'dcm':
if self._dcm:
self._dcm.pixel_array.flat = self._Mnp_2Dslice.flat
self._dcm.PixelData = self._dcm.pixel_array.tostring()
self._dcm.save_as(astr_outputFile)
else:
raise ValueError('dcm output format only available for DICOM files')
else:
pylab.imsave(astr_outputFile, self._Mnp_2Dslice, format=fformat, cmap = cm.Greys_r) | [
"def",
"slice_save",
"(",
"self",
",",
"astr_outputFile",
")",
":",
"self",
".",
"_log",
"(",
"'Outputfile = %s\\n'",
"%",
"astr_outputFile",
")",
"fformat",
"=",
"astr_outputFile",
".",
"split",
"(",
"'.'",
")",
"[",
"-",
"1",
"]",
"if",
"fformat",
"==",
... | Saves a single slice.
ARGS
o astr_output
The output filename to save the slice to. | [
"Saves",
"a",
"single",
"slice",
"."
] | 638d5d230de47608af20f9764acf8e382c2bf2ff | https://github.com/FNNDSC/med2image/blob/638d5d230de47608af20f9764acf8e382c2bf2ff/med2image/med2image.py#L316-L335 | train | 207,536 |
FNNDSC/med2image | med2image/med2image.py | med2image_dcm.run | def run(self):
'''
Runs the DICOM conversion based on internal state.
'''
self._log('Converting DICOM image.\n')
try:
self._log('PatientName: %s\n' % self._dcm.PatientName)
except AttributeError:
self._log('PatientName: %s\n' % 'PatientName not found in DCM header.')
error.warn(self, 'PatientNameTag')
try:
self._log('PatientAge: %s\n' % self._dcm.PatientAge)
except AttributeError:
self._log('PatientAge: %s\n' % 'PatientAge not found in DCM header.')
error.warn(self, 'PatientAgeTag')
try:
self._log('PatientSex: %s\n' % self._dcm.PatientSex)
except AttributeError:
self._log('PatientSex: %s\n' % 'PatientSex not found in DCM header.')
error.warn(self, 'PatientSexTag')
try:
self._log('PatientID: %s\n' % self._dcm.PatientID)
except AttributeError:
self._log('PatientID: %s\n' % 'PatientID not found in DCM header.')
error.warn(self, 'PatientIDTag')
try:
self._log('SeriesDescription: %s\n' % self._dcm.SeriesDescription)
except AttributeError:
self._log('SeriesDescription: %s\n' % 'SeriesDescription not found in DCM header.')
error.warn(self, 'SeriesDescriptionTag')
try:
self._log('ProtocolName: %s\n' % self._dcm.ProtocolName)
except AttributeError:
self._log('ProtocolName: %s\n' % 'ProtocolName not found in DCM header.')
error.warn(self, 'ProtocolNameTag')
if self._b_convertMiddleSlice:
self._log('Converting middle slice in DICOM series: %d\n' % self._sliceToConvert)
l_rot90 = [ True, True, False ]
misc.mkdir(self._str_outputDir)
if not self._b_3D:
str_outputFile = '%s/%s.%s' % (self._str_outputDir,
self._str_outputFileStem,
self._str_outputFileType)
self.process_slice()
self.slice_save(str_outputFile)
if self._b_3D:
rotCount = 0
if self._b_reslice:
for dim in ['x', 'y', 'z']:
self.dim_save(dimension = dim, makeSubDir = True, rot90 = l_rot90[rotCount], indexStart = 0, indexStop = -1)
rotCount += 1
else:
self.dim_save(dimension = 'z', makeSubDir = False, rot90 = False, indexStart = 0, indexStop = -1) | python | def run(self):
'''
Runs the DICOM conversion based on internal state.
'''
self._log('Converting DICOM image.\n')
try:
self._log('PatientName: %s\n' % self._dcm.PatientName)
except AttributeError:
self._log('PatientName: %s\n' % 'PatientName not found in DCM header.')
error.warn(self, 'PatientNameTag')
try:
self._log('PatientAge: %s\n' % self._dcm.PatientAge)
except AttributeError:
self._log('PatientAge: %s\n' % 'PatientAge not found in DCM header.')
error.warn(self, 'PatientAgeTag')
try:
self._log('PatientSex: %s\n' % self._dcm.PatientSex)
except AttributeError:
self._log('PatientSex: %s\n' % 'PatientSex not found in DCM header.')
error.warn(self, 'PatientSexTag')
try:
self._log('PatientID: %s\n' % self._dcm.PatientID)
except AttributeError:
self._log('PatientID: %s\n' % 'PatientID not found in DCM header.')
error.warn(self, 'PatientIDTag')
try:
self._log('SeriesDescription: %s\n' % self._dcm.SeriesDescription)
except AttributeError:
self._log('SeriesDescription: %s\n' % 'SeriesDescription not found in DCM header.')
error.warn(self, 'SeriesDescriptionTag')
try:
self._log('ProtocolName: %s\n' % self._dcm.ProtocolName)
except AttributeError:
self._log('ProtocolName: %s\n' % 'ProtocolName not found in DCM header.')
error.warn(self, 'ProtocolNameTag')
if self._b_convertMiddleSlice:
self._log('Converting middle slice in DICOM series: %d\n' % self._sliceToConvert)
l_rot90 = [ True, True, False ]
misc.mkdir(self._str_outputDir)
if not self._b_3D:
str_outputFile = '%s/%s.%s' % (self._str_outputDir,
self._str_outputFileStem,
self._str_outputFileType)
self.process_slice()
self.slice_save(str_outputFile)
if self._b_3D:
rotCount = 0
if self._b_reslice:
for dim in ['x', 'y', 'z']:
self.dim_save(dimension = dim, makeSubDir = True, rot90 = l_rot90[rotCount], indexStart = 0, indexStop = -1)
rotCount += 1
else:
self.dim_save(dimension = 'z', makeSubDir = False, rot90 = False, indexStart = 0, indexStop = -1) | [
"def",
"run",
"(",
"self",
")",
":",
"self",
".",
"_log",
"(",
"'Converting DICOM image.\\n'",
")",
"try",
":",
"self",
".",
"_log",
"(",
"'PatientName: %s\\n'",
"%",
"self",
".",
"_dcm",
".",
"PatientName",
")",
"except",
"Attribu... | Runs the DICOM conversion based on internal state. | [
"Runs",
"the",
"DICOM",
"conversion",
"based",
"on",
"internal",
"state",
"."
] | 638d5d230de47608af20f9764acf8e382c2bf2ff | https://github.com/FNNDSC/med2image/blob/638d5d230de47608af20f9764acf8e382c2bf2ff/med2image/med2image.py#L416-L470 | train | 207,537 |
FNNDSC/med2image | med2image/med2image.py | med2image_nii.run | def run(self):
'''
Runs the NIfTI conversion based on internal state.
'''
self._log('About to perform NifTI to %s conversion...\n' %
self._str_outputFileType)
frames = 1
frameStart = 0
frameEnd = 0
sliceStart = 0
sliceEnd = 0
if self._b_4D:
self._log('4D volume detected.\n')
frames = self._Vnp_4DVol.shape[3]
if self._b_3D:
self._log('3D volume detected.\n')
if self._b_convertMiddleFrame:
self._frameToConvert = int(frames/2)
if self._frameToConvert == -1:
frameEnd = frames
else:
frameStart = self._frameToConvert
frameEnd = self._frameToConvert + 1
for f in range(frameStart, frameEnd):
if self._b_4D:
self._Vnp_3DVol = self._Vnp_4DVol[:,:,:,f]
slices = self._Vnp_3DVol.shape[2]
if self._b_convertMiddleSlice:
self._sliceToConvert = int(slices/2)
if self._sliceToConvert == -1:
sliceEnd = -1
else:
sliceStart = self._sliceToConvert
sliceEnd = self._sliceToConvert + 1
misc.mkdir(self._str_outputDir)
if self._b_reslice:
for dim in ['x', 'y', 'z']:
self.dim_save(dimension = dim, makeSubDir = True, indexStart = sliceStart, indexStop = sliceEnd, rot90 = True)
else:
self.dim_save(dimension = 'z', makeSubDir = False, indexStart = sliceStart, indexStop = sliceEnd, rot90 = True) | python | def run(self):
'''
Runs the NIfTI conversion based on internal state.
'''
self._log('About to perform NifTI to %s conversion...\n' %
self._str_outputFileType)
frames = 1
frameStart = 0
frameEnd = 0
sliceStart = 0
sliceEnd = 0
if self._b_4D:
self._log('4D volume detected.\n')
frames = self._Vnp_4DVol.shape[3]
if self._b_3D:
self._log('3D volume detected.\n')
if self._b_convertMiddleFrame:
self._frameToConvert = int(frames/2)
if self._frameToConvert == -1:
frameEnd = frames
else:
frameStart = self._frameToConvert
frameEnd = self._frameToConvert + 1
for f in range(frameStart, frameEnd):
if self._b_4D:
self._Vnp_3DVol = self._Vnp_4DVol[:,:,:,f]
slices = self._Vnp_3DVol.shape[2]
if self._b_convertMiddleSlice:
self._sliceToConvert = int(slices/2)
if self._sliceToConvert == -1:
sliceEnd = -1
else:
sliceStart = self._sliceToConvert
sliceEnd = self._sliceToConvert + 1
misc.mkdir(self._str_outputDir)
if self._b_reslice:
for dim in ['x', 'y', 'z']:
self.dim_save(dimension = dim, makeSubDir = True, indexStart = sliceStart, indexStop = sliceEnd, rot90 = True)
else:
self.dim_save(dimension = 'z', makeSubDir = False, indexStart = sliceStart, indexStop = sliceEnd, rot90 = True) | [
"def",
"run",
"(",
"self",
")",
":",
"self",
".",
"_log",
"(",
"'About to perform NifTI to %s conversion...\\n'",
"%",
"self",
".",
"_str_outputFileType",
")",
"frames",
"=",
"1",
"frameStart",
"=",
"0",
"frameEnd",
"=",
"0",
"sliceStart",
"=",
"0",
"sliceEnd"... | Runs the NIfTI conversion based on internal state. | [
"Runs",
"the",
"NIfTI",
"conversion",
"based",
"on",
"internal",
"state",
"."
] | 638d5d230de47608af20f9764acf8e382c2bf2ff | https://github.com/FNNDSC/med2image/blob/638d5d230de47608af20f9764acf8e382c2bf2ff/med2image/med2image.py#L489-L537 | train | 207,538 |
ziwenxie/netease-dl | netease/logger.py | get_logger | def get_logger(name):
"""Return a logger with a file handler."""
logger = logging.getLogger(name)
logger.setLevel(logging.INFO)
# File output handler
file_handler = logging.FileHandler(log_path)
file_handler.setLevel(logging.INFO)
formatter = logging.Formatter(
'%(asctime)s %(name)12s %(levelname)8s %(lineno)s %(message)s',
datefmt='%m/%d/%Y %I:%M:%S %p')
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
return logger | python | def get_logger(name):
"""Return a logger with a file handler."""
logger = logging.getLogger(name)
logger.setLevel(logging.INFO)
# File output handler
file_handler = logging.FileHandler(log_path)
file_handler.setLevel(logging.INFO)
formatter = logging.Formatter(
'%(asctime)s %(name)12s %(levelname)8s %(lineno)s %(message)s',
datefmt='%m/%d/%Y %I:%M:%S %p')
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
return logger | [
"def",
"get_logger",
"(",
"name",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"name",
")",
"logger",
".",
"setLevel",
"(",
"logging",
".",
"INFO",
")",
"# File output handler",
"file_handler",
"=",
"logging",
".",
"FileHandler",
"(",
"log_path... | Return a logger with a file handler. | [
"Return",
"a",
"logger",
"with",
"a",
"file",
"handler",
"."
] | 84b226fc07b10f7f66580f0fc69f10356f66b5c3 | https://github.com/ziwenxie/netease-dl/blob/84b226fc07b10f7f66580f0fc69f10356f66b5c3/netease/logger.py#L24-L38 | train | 207,539 |
ziwenxie/netease-dl | netease/download.py | timeit | def timeit(method):
"""Compute the download time."""
def wrapper(*args, **kwargs):
start = time.time()
result = method(*args, **kwargs)
end = time.time()
click.echo('Cost {}s'.format(int(end-start)))
return result
return wrapper | python | def timeit(method):
"""Compute the download time."""
def wrapper(*args, **kwargs):
start = time.time()
result = method(*args, **kwargs)
end = time.time()
click.echo('Cost {}s'.format(int(end-start)))
return result
return wrapper | [
"def",
"timeit",
"(",
"method",
")",
":",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"start",
"=",
"time",
".",
"time",
"(",
")",
"result",
"=",
"method",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"end",
"=",
... | Compute the download time. | [
"Compute",
"the",
"download",
"time",
"."
] | 84b226fc07b10f7f66580f0fc69f10356f66b5c3 | https://github.com/ziwenxie/netease-dl/blob/84b226fc07b10f7f66580f0fc69f10356f66b5c3/netease/download.py#L25-L36 | train | 207,540 |
ziwenxie/netease-dl | netease/download.py | login | def login(method):
"""Require user to login."""
def wrapper(*args, **kwargs):
crawler = args[0].crawler # args[0] is a NetEase object
try:
if os.path.isfile(cookie_path):
with open(cookie_path, 'r') as cookie_file:
cookie = cookie_file.read()
expire_time = re.compile(r'\d{4}-\d{2}-\d{2}').findall(cookie)
now = time.strftime('%Y-%m-%d', time.localtime(time.time()))
if expire_time[0] > now:
crawler.session.cookies.load()
else:
crawler.login()
else:
crawler.login()
except RequestException:
click.echo('Maybe password error, please try again.')
sys.exit(1)
result = method(*args, **kwargs)
return result
return wrapper | python | def login(method):
"""Require user to login."""
def wrapper(*args, **kwargs):
crawler = args[0].crawler # args[0] is a NetEase object
try:
if os.path.isfile(cookie_path):
with open(cookie_path, 'r') as cookie_file:
cookie = cookie_file.read()
expire_time = re.compile(r'\d{4}-\d{2}-\d{2}').findall(cookie)
now = time.strftime('%Y-%m-%d', time.localtime(time.time()))
if expire_time[0] > now:
crawler.session.cookies.load()
else:
crawler.login()
else:
crawler.login()
except RequestException:
click.echo('Maybe password error, please try again.')
sys.exit(1)
result = method(*args, **kwargs)
return result
return wrapper | [
"def",
"login",
"(",
"method",
")",
":",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"crawler",
"=",
"args",
"[",
"0",
"]",
".",
"crawler",
"# args[0] is a NetEase object",
"try",
":",
"if",
"os",
".",
"path",
".",
"isfile"... | Require user to login. | [
"Require",
"user",
"to",
"login",
"."
] | 84b226fc07b10f7f66580f0fc69f10356f66b5c3 | https://github.com/ziwenxie/netease-dl/blob/84b226fc07b10f7f66580f0fc69f10356f66b5c3/netease/download.py#L39-L63 | train | 207,541 |
ziwenxie/netease-dl | netease/download.py | NetEase.download_song_by_search | def download_song_by_search(self, song_name):
"""Download a song by its name.
:params song_name: song name.
"""
try:
song = self.crawler.search_song(song_name, self.quiet)
except RequestException as exception:
click.echo(exception)
else:
self.download_song_by_id(song.song_id, song.song_name, self.folder) | python | def download_song_by_search(self, song_name):
"""Download a song by its name.
:params song_name: song name.
"""
try:
song = self.crawler.search_song(song_name, self.quiet)
except RequestException as exception:
click.echo(exception)
else:
self.download_song_by_id(song.song_id, song.song_name, self.folder) | [
"def",
"download_song_by_search",
"(",
"self",
",",
"song_name",
")",
":",
"try",
":",
"song",
"=",
"self",
".",
"crawler",
".",
"search_song",
"(",
"song_name",
",",
"self",
".",
"quiet",
")",
"except",
"RequestException",
"as",
"exception",
":",
"click",
... | Download a song by its name.
:params song_name: song name. | [
"Download",
"a",
"song",
"by",
"its",
"name",
"."
] | 84b226fc07b10f7f66580f0fc69f10356f66b5c3 | https://github.com/ziwenxie/netease-dl/blob/84b226fc07b10f7f66580f0fc69f10356f66b5c3/netease/download.py#L80-L91 | train | 207,542 |
ziwenxie/netease-dl | netease/download.py | NetEase.download_song_by_id | def download_song_by_id(self, song_id, song_name, folder='.'):
"""Download a song by id and save it to disk.
:params song_id: song id.
:params song_name: song name.
:params folder: storage path.
"""
try:
url = self.crawler.get_song_url(song_id)
if self.lyric:
# use old api
lyric_info = self.crawler.get_song_lyric(song_id)
else:
lyric_info = None
song_name = song_name.replace('/', '')
song_name = song_name.replace('.', '')
self.crawler.get_song_by_url(url, song_name, folder, lyric_info)
except RequestException as exception:
click.echo(exception) | python | def download_song_by_id(self, song_id, song_name, folder='.'):
"""Download a song by id and save it to disk.
:params song_id: song id.
:params song_name: song name.
:params folder: storage path.
"""
try:
url = self.crawler.get_song_url(song_id)
if self.lyric:
# use old api
lyric_info = self.crawler.get_song_lyric(song_id)
else:
lyric_info = None
song_name = song_name.replace('/', '')
song_name = song_name.replace('.', '')
self.crawler.get_song_by_url(url, song_name, folder, lyric_info)
except RequestException as exception:
click.echo(exception) | [
"def",
"download_song_by_id",
"(",
"self",
",",
"song_id",
",",
"song_name",
",",
"folder",
"=",
"'.'",
")",
":",
"try",
":",
"url",
"=",
"self",
".",
"crawler",
".",
"get_song_url",
"(",
"song_id",
")",
"if",
"self",
".",
"lyric",
":",
"# use old api",
... | Download a song by id and save it to disk.
:params song_id: song id.
:params song_name: song name.
:params folder: storage path. | [
"Download",
"a",
"song",
"by",
"id",
"and",
"save",
"it",
"to",
"disk",
"."
] | 84b226fc07b10f7f66580f0fc69f10356f66b5c3 | https://github.com/ziwenxie/netease-dl/blob/84b226fc07b10f7f66580f0fc69f10356f66b5c3/netease/download.py#L93-L112 | train | 207,543 |
ziwenxie/netease-dl | netease/download.py | NetEase.download_playlist_by_search | def download_playlist_by_search(self, playlist_name):
"""Download a playlist's songs by its name.
:params playlist_name: playlist name.
"""
try:
playlist = self.crawler.search_playlist(
playlist_name, self.quiet)
except RequestException as exception:
click.echo(exception)
else:
self.download_playlist_by_id(
playlist.playlist_id, playlist.playlist_name) | python | def download_playlist_by_search(self, playlist_name):
"""Download a playlist's songs by its name.
:params playlist_name: playlist name.
"""
try:
playlist = self.crawler.search_playlist(
playlist_name, self.quiet)
except RequestException as exception:
click.echo(exception)
else:
self.download_playlist_by_id(
playlist.playlist_id, playlist.playlist_name) | [
"def",
"download_playlist_by_search",
"(",
"self",
",",
"playlist_name",
")",
":",
"try",
":",
"playlist",
"=",
"self",
".",
"crawler",
".",
"search_playlist",
"(",
"playlist_name",
",",
"self",
".",
"quiet",
")",
"except",
"RequestException",
"as",
"exception",... | Download a playlist's songs by its name.
:params playlist_name: playlist name. | [
"Download",
"a",
"playlist",
"s",
"songs",
"by",
"its",
"name",
"."
] | 84b226fc07b10f7f66580f0fc69f10356f66b5c3 | https://github.com/ziwenxie/netease-dl/blob/84b226fc07b10f7f66580f0fc69f10356f66b5c3/netease/download.py#L176-L189 | train | 207,544 |
ziwenxie/netease-dl | netease/download.py | NetEase.download_playlist_by_id | def download_playlist_by_id(self, playlist_id, playlist_name):
"""Download a playlist's songs by its id.
:params playlist_id: playlist id.
:params playlist_name: playlist name.
"""
try:
songs = self.crawler.get_playlist_songs(
playlist_id)
except RequestException as exception:
click.echo(exception)
else:
folder = os.path.join(self.folder, playlist_name)
for song in songs:
self.download_song_by_id(song.song_id, song.song_name, folder) | python | def download_playlist_by_id(self, playlist_id, playlist_name):
"""Download a playlist's songs by its id.
:params playlist_id: playlist id.
:params playlist_name: playlist name.
"""
try:
songs = self.crawler.get_playlist_songs(
playlist_id)
except RequestException as exception:
click.echo(exception)
else:
folder = os.path.join(self.folder, playlist_name)
for song in songs:
self.download_song_by_id(song.song_id, song.song_name, folder) | [
"def",
"download_playlist_by_id",
"(",
"self",
",",
"playlist_id",
",",
"playlist_name",
")",
":",
"try",
":",
"songs",
"=",
"self",
".",
"crawler",
".",
"get_playlist_songs",
"(",
"playlist_id",
")",
"except",
"RequestException",
"as",
"exception",
":",
"click"... | Download a playlist's songs by its id.
:params playlist_id: playlist id.
:params playlist_name: playlist name. | [
"Download",
"a",
"playlist",
"s",
"songs",
"by",
"its",
"id",
"."
] | 84b226fc07b10f7f66580f0fc69f10356f66b5c3 | https://github.com/ziwenxie/netease-dl/blob/84b226fc07b10f7f66580f0fc69f10356f66b5c3/netease/download.py#L192-L207 | train | 207,545 |
ziwenxie/netease-dl | netease/download.py | NetEase.download_person_playlists | def download_person_playlists(self):
"""Download person playlist including private playlist.
note: login required.
"""
with open(person_info_path, 'r') as person_info:
user_id = int(person_info.read())
self.download_user_playlists_by_id(user_id) | python | def download_person_playlists(self):
"""Download person playlist including private playlist.
note: login required.
"""
with open(person_info_path, 'r') as person_info:
user_id = int(person_info.read())
self.download_user_playlists_by_id(user_id) | [
"def",
"download_person_playlists",
"(",
"self",
")",
":",
"with",
"open",
"(",
"person_info_path",
",",
"'r'",
")",
"as",
"person_info",
":",
"user_id",
"=",
"int",
"(",
"person_info",
".",
"read",
"(",
")",
")",
"self",
".",
"download_user_playlists_by_id",
... | Download person playlist including private playlist.
note: login required. | [
"Download",
"person",
"playlist",
"including",
"private",
"playlist",
"."
] | 84b226fc07b10f7f66580f0fc69f10356f66b5c3 | https://github.com/ziwenxie/netease-dl/blob/84b226fc07b10f7f66580f0fc69f10356f66b5c3/netease/download.py#L237-L245 | train | 207,546 |
ziwenxie/netease-dl | netease/start.py | signal_handler | def signal_handler(sign, frame):
"""Capture Ctrl+C."""
LOG.info('%s => %s', sign, frame)
click.echo('Bye')
sys.exit(0) | python | def signal_handler(sign, frame):
"""Capture Ctrl+C."""
LOG.info('%s => %s', sign, frame)
click.echo('Bye')
sys.exit(0) | [
"def",
"signal_handler",
"(",
"sign",
",",
"frame",
")",
":",
"LOG",
".",
"info",
"(",
"'%s => %s'",
",",
"sign",
",",
"frame",
")",
"click",
".",
"echo",
"(",
"'Bye'",
")",
"sys",
".",
"exit",
"(",
"0",
")"
] | Capture Ctrl+C. | [
"Capture",
"Ctrl",
"+",
"C",
"."
] | 84b226fc07b10f7f66580f0fc69f10356f66b5c3 | https://github.com/ziwenxie/netease-dl/blob/84b226fc07b10f7f66580f0fc69f10356f66b5c3/netease/start.py#L21-L25 | train | 207,547 |
ziwenxie/netease-dl | netease/start.py | cli | def cli(ctx, timeout, proxy, output, quiet, lyric, again):
"""A command tool to download NetEase-Music's songs."""
ctx.obj = NetEase(timeout, proxy, output, quiet, lyric, again) | python | def cli(ctx, timeout, proxy, output, quiet, lyric, again):
"""A command tool to download NetEase-Music's songs."""
ctx.obj = NetEase(timeout, proxy, output, quiet, lyric, again) | [
"def",
"cli",
"(",
"ctx",
",",
"timeout",
",",
"proxy",
",",
"output",
",",
"quiet",
",",
"lyric",
",",
"again",
")",
":",
"ctx",
".",
"obj",
"=",
"NetEase",
"(",
"timeout",
",",
"proxy",
",",
"output",
",",
"quiet",
",",
"lyric",
",",
"again",
"... | A command tool to download NetEase-Music's songs. | [
"A",
"command",
"tool",
"to",
"download",
"NetEase",
"-",
"Music",
"s",
"songs",
"."
] | 84b226fc07b10f7f66580f0fc69f10356f66b5c3 | https://github.com/ziwenxie/netease-dl/blob/84b226fc07b10f7f66580f0fc69f10356f66b5c3/netease/start.py#L41-L43 | train | 207,548 |
ziwenxie/netease-dl | netease/start.py | song | def song(netease, name, id):
"""Download a song by name or id."""
if name:
netease.download_song_by_search(name)
if id:
netease.download_song_by_id(id, 'song'+str(id)) | python | def song(netease, name, id):
"""Download a song by name or id."""
if name:
netease.download_song_by_search(name)
if id:
netease.download_song_by_id(id, 'song'+str(id)) | [
"def",
"song",
"(",
"netease",
",",
"name",
",",
"id",
")",
":",
"if",
"name",
":",
"netease",
".",
"download_song_by_search",
"(",
"name",
")",
"if",
"id",
":",
"netease",
".",
"download_song_by_id",
"(",
"id",
",",
"'song'",
"+",
"str",
"(",
"id",
... | Download a song by name or id. | [
"Download",
"a",
"song",
"by",
"name",
"or",
"id",
"."
] | 84b226fc07b10f7f66580f0fc69f10356f66b5c3 | https://github.com/ziwenxie/netease-dl/blob/84b226fc07b10f7f66580f0fc69f10356f66b5c3/netease/start.py#L50-L56 | train | 207,549 |
ziwenxie/netease-dl | netease/start.py | album | def album(netease, name, id):
"""Download a album's songs by name or id."""
if name:
netease.download_album_by_search(name)
if id:
netease.download_album_by_id(id, 'album'+str(id)) | python | def album(netease, name, id):
"""Download a album's songs by name or id."""
if name:
netease.download_album_by_search(name)
if id:
netease.download_album_by_id(id, 'album'+str(id)) | [
"def",
"album",
"(",
"netease",
",",
"name",
",",
"id",
")",
":",
"if",
"name",
":",
"netease",
".",
"download_album_by_search",
"(",
"name",
")",
"if",
"id",
":",
"netease",
".",
"download_album_by_id",
"(",
"id",
",",
"'album'",
"+",
"str",
"(",
"id"... | Download a album's songs by name or id. | [
"Download",
"a",
"album",
"s",
"songs",
"by",
"name",
"or",
"id",
"."
] | 84b226fc07b10f7f66580f0fc69f10356f66b5c3 | https://github.com/ziwenxie/netease-dl/blob/84b226fc07b10f7f66580f0fc69f10356f66b5c3/netease/start.py#L63-L69 | train | 207,550 |
ziwenxie/netease-dl | netease/start.py | artist | def artist(netease, name, id):
"""Download a artist's hot songs by name or id."""
if name:
netease.download_artist_by_search(name)
if id:
netease.download_artist_by_id(id, 'artist'+str(id)) | python | def artist(netease, name, id):
"""Download a artist's hot songs by name or id."""
if name:
netease.download_artist_by_search(name)
if id:
netease.download_artist_by_id(id, 'artist'+str(id)) | [
"def",
"artist",
"(",
"netease",
",",
"name",
",",
"id",
")",
":",
"if",
"name",
":",
"netease",
".",
"download_artist_by_search",
"(",
"name",
")",
"if",
"id",
":",
"netease",
".",
"download_artist_by_id",
"(",
"id",
",",
"'artist'",
"+",
"str",
"(",
... | Download a artist's hot songs by name or id. | [
"Download",
"a",
"artist",
"s",
"hot",
"songs",
"by",
"name",
"or",
"id",
"."
] | 84b226fc07b10f7f66580f0fc69f10356f66b5c3 | https://github.com/ziwenxie/netease-dl/blob/84b226fc07b10f7f66580f0fc69f10356f66b5c3/netease/start.py#L76-L82 | train | 207,551 |
ziwenxie/netease-dl | netease/start.py | playlist | def playlist(netease, name, id):
"""Download a playlist's songs by id."""
if name:
netease.download_playlist_by_search(name)
if id:
netease.download_playlist_by_id(id, 'playlist'+str(id)) | python | def playlist(netease, name, id):
"""Download a playlist's songs by id."""
if name:
netease.download_playlist_by_search(name)
if id:
netease.download_playlist_by_id(id, 'playlist'+str(id)) | [
"def",
"playlist",
"(",
"netease",
",",
"name",
",",
"id",
")",
":",
"if",
"name",
":",
"netease",
".",
"download_playlist_by_search",
"(",
"name",
")",
"if",
"id",
":",
"netease",
".",
"download_playlist_by_id",
"(",
"id",
",",
"'playlist'",
"+",
"str",
... | Download a playlist's songs by id. | [
"Download",
"a",
"playlist",
"s",
"songs",
"by",
"id",
"."
] | 84b226fc07b10f7f66580f0fc69f10356f66b5c3 | https://github.com/ziwenxie/netease-dl/blob/84b226fc07b10f7f66580f0fc69f10356f66b5c3/netease/start.py#L89-L95 | train | 207,552 |
ziwenxie/netease-dl | netease/start.py | user | def user(netease, name, id):
"""Download a user\'s playlists by id."""
if name:
netease.download_user_playlists_by_search(name)
if id:
netease.download_user_playlists_by_id(id) | python | def user(netease, name, id):
"""Download a user\'s playlists by id."""
if name:
netease.download_user_playlists_by_search(name)
if id:
netease.download_user_playlists_by_id(id) | [
"def",
"user",
"(",
"netease",
",",
"name",
",",
"id",
")",
":",
"if",
"name",
":",
"netease",
".",
"download_user_playlists_by_search",
"(",
"name",
")",
"if",
"id",
":",
"netease",
".",
"download_user_playlists_by_id",
"(",
"id",
")"
] | Download a user\'s playlists by id. | [
"Download",
"a",
"user",
"\\",
"s",
"playlists",
"by",
"id",
"."
] | 84b226fc07b10f7f66580f0fc69f10356f66b5c3 | https://github.com/ziwenxie/netease-dl/blob/84b226fc07b10f7f66580f0fc69f10356f66b5c3/netease/start.py#L102-L108 | train | 207,553 |
ziwenxie/netease-dl | netease/utils.py | Display.select_one_song | def select_one_song(songs):
"""Display the songs returned by search api.
:params songs: API['result']['songs']
:return: a Song object.
"""
if len(songs) == 1:
select_i = 0
else:
table = PrettyTable(['Sequence', 'Song Name', 'Artist Name'])
for i, song in enumerate(songs, 1):
table.add_row([i, song['name'], song['ar'][0]['name']])
click.echo(table)
select_i = click.prompt('Select one song', type=int, default=1)
while select_i < 1 or select_i > len(songs):
select_i = click.prompt('Error Select! Select Again', type=int)
song_id, song_name = songs[select_i-1]['id'], songs[select_i-1]['name']
song = Song(song_id, song_name)
return song | python | def select_one_song(songs):
"""Display the songs returned by search api.
:params songs: API['result']['songs']
:return: a Song object.
"""
if len(songs) == 1:
select_i = 0
else:
table = PrettyTable(['Sequence', 'Song Name', 'Artist Name'])
for i, song in enumerate(songs, 1):
table.add_row([i, song['name'], song['ar'][0]['name']])
click.echo(table)
select_i = click.prompt('Select one song', type=int, default=1)
while select_i < 1 or select_i > len(songs):
select_i = click.prompt('Error Select! Select Again', type=int)
song_id, song_name = songs[select_i-1]['id'], songs[select_i-1]['name']
song = Song(song_id, song_name)
return song | [
"def",
"select_one_song",
"(",
"songs",
")",
":",
"if",
"len",
"(",
"songs",
")",
"==",
"1",
":",
"select_i",
"=",
"0",
"else",
":",
"table",
"=",
"PrettyTable",
"(",
"[",
"'Sequence'",
",",
"'Song Name'",
",",
"'Artist Name'",
"]",
")",
"for",
"i",
... | Display the songs returned by search api.
:params songs: API['result']['songs']
:return: a Song object. | [
"Display",
"the",
"songs",
"returned",
"by",
"search",
"api",
"."
] | 84b226fc07b10f7f66580f0fc69f10356f66b5c3 | https://github.com/ziwenxie/netease-dl/blob/84b226fc07b10f7f66580f0fc69f10356f66b5c3/netease/utils.py#L19-L40 | train | 207,554 |
ziwenxie/netease-dl | netease/utils.py | Display.select_one_album | def select_one_album(albums):
"""Display the albums returned by search api.
:params albums: API['result']['albums']
:return: a Album object.
"""
if len(albums) == 1:
select_i = 0
else:
table = PrettyTable(['Sequence', 'Album Name', 'Artist Name'])
for i, album in enumerate(albums, 1):
table.add_row([i, album['name'], album['artist']['name']])
click.echo(table)
select_i = click.prompt('Select one album', type=int, default=1)
while select_i < 1 or select_i > len(albums):
select_i = click.prompt('Error Select! Select Again', type=int)
album_id = albums[select_i-1]['id']
album_name = albums[select_i-1]['name']
album = Album(album_id, album_name)
return album | python | def select_one_album(albums):
"""Display the albums returned by search api.
:params albums: API['result']['albums']
:return: a Album object.
"""
if len(albums) == 1:
select_i = 0
else:
table = PrettyTable(['Sequence', 'Album Name', 'Artist Name'])
for i, album in enumerate(albums, 1):
table.add_row([i, album['name'], album['artist']['name']])
click.echo(table)
select_i = click.prompt('Select one album', type=int, default=1)
while select_i < 1 or select_i > len(albums):
select_i = click.prompt('Error Select! Select Again', type=int)
album_id = albums[select_i-1]['id']
album_name = albums[select_i-1]['name']
album = Album(album_id, album_name)
return album | [
"def",
"select_one_album",
"(",
"albums",
")",
":",
"if",
"len",
"(",
"albums",
")",
"==",
"1",
":",
"select_i",
"=",
"0",
"else",
":",
"table",
"=",
"PrettyTable",
"(",
"[",
"'Sequence'",
",",
"'Album Name'",
",",
"'Artist Name'",
"]",
")",
"for",
"i"... | Display the albums returned by search api.
:params albums: API['result']['albums']
:return: a Album object. | [
"Display",
"the",
"albums",
"returned",
"by",
"search",
"api",
"."
] | 84b226fc07b10f7f66580f0fc69f10356f66b5c3 | https://github.com/ziwenxie/netease-dl/blob/84b226fc07b10f7f66580f0fc69f10356f66b5c3/netease/utils.py#L43-L65 | train | 207,555 |
ziwenxie/netease-dl | netease/utils.py | Display.select_one_artist | def select_one_artist(artists):
"""Display the artists returned by search api.
:params artists: API['result']['artists']
:return: a Artist object.
"""
if len(artists) == 1:
select_i = 0
else:
table = PrettyTable(['Sequence', 'Artist Name'])
for i, artist in enumerate(artists, 1):
table.add_row([i, artist['name']])
click.echo(table)
select_i = click.prompt('Select one artist', type=int, default=1)
while select_i < 1 or select_i > len(artists):
select_i = click.prompt('Error Select! Select Again', type=int)
artist_id = artists[select_i-1]['id']
artist_name = artists[select_i-1]['name']
artist = Artist(artist_id, artist_name)
return artist | python | def select_one_artist(artists):
"""Display the artists returned by search api.
:params artists: API['result']['artists']
:return: a Artist object.
"""
if len(artists) == 1:
select_i = 0
else:
table = PrettyTable(['Sequence', 'Artist Name'])
for i, artist in enumerate(artists, 1):
table.add_row([i, artist['name']])
click.echo(table)
select_i = click.prompt('Select one artist', type=int, default=1)
while select_i < 1 or select_i > len(artists):
select_i = click.prompt('Error Select! Select Again', type=int)
artist_id = artists[select_i-1]['id']
artist_name = artists[select_i-1]['name']
artist = Artist(artist_id, artist_name)
return artist | [
"def",
"select_one_artist",
"(",
"artists",
")",
":",
"if",
"len",
"(",
"artists",
")",
"==",
"1",
":",
"select_i",
"=",
"0",
"else",
":",
"table",
"=",
"PrettyTable",
"(",
"[",
"'Sequence'",
",",
"'Artist Name'",
"]",
")",
"for",
"i",
",",
"artist",
... | Display the artists returned by search api.
:params artists: API['result']['artists']
:return: a Artist object. | [
"Display",
"the",
"artists",
"returned",
"by",
"search",
"api",
"."
] | 84b226fc07b10f7f66580f0fc69f10356f66b5c3 | https://github.com/ziwenxie/netease-dl/blob/84b226fc07b10f7f66580f0fc69f10356f66b5c3/netease/utils.py#L68-L90 | train | 207,556 |
ziwenxie/netease-dl | netease/utils.py | Display.select_one_playlist | def select_one_playlist(playlists):
"""Display the playlists returned by search api or user playlist.
:params playlists: API['result']['playlists'] or API['playlist']
:return: a Playlist object.
"""
if len(playlists) == 1:
select_i = 0
else:
table = PrettyTable(['Sequence', 'Name'])
for i, playlist in enumerate(playlists, 1):
table.add_row([i, playlist['name']])
click.echo(table)
select_i = click.prompt('Select one playlist', type=int, default=1)
while select_i < 1 or select_i > len(playlists):
select_i = click.prompt('Error Select! Select Again', type=int)
playlist_id = playlists[select_i-1]['id']
playlist_name = playlists[select_i-1]['name']
playlist = Playlist(playlist_id, playlist_name)
return playlist | python | def select_one_playlist(playlists):
"""Display the playlists returned by search api or user playlist.
:params playlists: API['result']['playlists'] or API['playlist']
:return: a Playlist object.
"""
if len(playlists) == 1:
select_i = 0
else:
table = PrettyTable(['Sequence', 'Name'])
for i, playlist in enumerate(playlists, 1):
table.add_row([i, playlist['name']])
click.echo(table)
select_i = click.prompt('Select one playlist', type=int, default=1)
while select_i < 1 or select_i > len(playlists):
select_i = click.prompt('Error Select! Select Again', type=int)
playlist_id = playlists[select_i-1]['id']
playlist_name = playlists[select_i-1]['name']
playlist = Playlist(playlist_id, playlist_name)
return playlist | [
"def",
"select_one_playlist",
"(",
"playlists",
")",
":",
"if",
"len",
"(",
"playlists",
")",
"==",
"1",
":",
"select_i",
"=",
"0",
"else",
":",
"table",
"=",
"PrettyTable",
"(",
"[",
"'Sequence'",
",",
"'Name'",
"]",
")",
"for",
"i",
",",
"playlist",
... | Display the playlists returned by search api or user playlist.
:params playlists: API['result']['playlists'] or API['playlist']
:return: a Playlist object. | [
"Display",
"the",
"playlists",
"returned",
"by",
"search",
"api",
"or",
"user",
"playlist",
"."
] | 84b226fc07b10f7f66580f0fc69f10356f66b5c3 | https://github.com/ziwenxie/netease-dl/blob/84b226fc07b10f7f66580f0fc69f10356f66b5c3/netease/utils.py#L93-L115 | train | 207,557 |
ziwenxie/netease-dl | netease/utils.py | Display.select_one_user | def select_one_user(users):
"""Display the users returned by search api.
:params users: API['result']['userprofiles']
:return: a User object.
"""
if len(users) == 1:
select_i = 0
else:
table = PrettyTable(['Sequence', 'Name'])
for i, user in enumerate(users, 1):
table.add_row([i, user['nickname']])
click.echo(table)
select_i = click.prompt('Select one user', type=int, default=1)
while select_i < 1 or select_i > len(users):
select_i = click.prompt('Error Select! Select Again', type=int)
user_id = users[select_i-1]['userId']
user_name = users[select_i-1]['nickname']
user = User(user_id, user_name)
return user | python | def select_one_user(users):
"""Display the users returned by search api.
:params users: API['result']['userprofiles']
:return: a User object.
"""
if len(users) == 1:
select_i = 0
else:
table = PrettyTable(['Sequence', 'Name'])
for i, user in enumerate(users, 1):
table.add_row([i, user['nickname']])
click.echo(table)
select_i = click.prompt('Select one user', type=int, default=1)
while select_i < 1 or select_i > len(users):
select_i = click.prompt('Error Select! Select Again', type=int)
user_id = users[select_i-1]['userId']
user_name = users[select_i-1]['nickname']
user = User(user_id, user_name)
return user | [
"def",
"select_one_user",
"(",
"users",
")",
":",
"if",
"len",
"(",
"users",
")",
"==",
"1",
":",
"select_i",
"=",
"0",
"else",
":",
"table",
"=",
"PrettyTable",
"(",
"[",
"'Sequence'",
",",
"'Name'",
"]",
")",
"for",
"i",
",",
"user",
"in",
"enume... | Display the users returned by search api.
:params users: API['result']['userprofiles']
:return: a User object. | [
"Display",
"the",
"users",
"returned",
"by",
"search",
"api",
"."
] | 84b226fc07b10f7f66580f0fc69f10356f66b5c3 | https://github.com/ziwenxie/netease-dl/blob/84b226fc07b10f7f66580f0fc69f10356f66b5c3/netease/utils.py#L118-L140 | train | 207,558 |
ziwenxie/netease-dl | netease/weapi.py | exception_handle | def exception_handle(method):
"""Handle exception raised by requests library."""
def wrapper(*args, **kwargs):
try:
result = method(*args, **kwargs)
return result
except ProxyError:
LOG.exception('ProxyError when try to get %s.', args)
raise ProxyError('A proxy error occurred.')
except ConnectionException:
LOG.exception('ConnectionError when try to get %s.', args)
raise ConnectionException('DNS failure, refused connection, etc.')
except Timeout:
LOG.exception('Timeout when try to get %s', args)
raise Timeout('The request timed out.')
except RequestException:
LOG.exception('RequestException when try to get %s.', args)
raise RequestException('Please check out your network.')
return wrapper | python | def exception_handle(method):
"""Handle exception raised by requests library."""
def wrapper(*args, **kwargs):
try:
result = method(*args, **kwargs)
return result
except ProxyError:
LOG.exception('ProxyError when try to get %s.', args)
raise ProxyError('A proxy error occurred.')
except ConnectionException:
LOG.exception('ConnectionError when try to get %s.', args)
raise ConnectionException('DNS failure, refused connection, etc.')
except Timeout:
LOG.exception('Timeout when try to get %s', args)
raise Timeout('The request timed out.')
except RequestException:
LOG.exception('RequestException when try to get %s.', args)
raise RequestException('Please check out your network.')
return wrapper | [
"def",
"exception_handle",
"(",
"method",
")",
":",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"result",
"=",
"method",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"result",
"except",
"ProxyError"... | Handle exception raised by requests library. | [
"Handle",
"exception",
"raised",
"by",
"requests",
"library",
"."
] | 84b226fc07b10f7f66580f0fc69f10356f66b5c3 | https://github.com/ziwenxie/netease-dl/blob/84b226fc07b10f7f66580f0fc69f10356f66b5c3/netease/weapi.py#L32-L52 | train | 207,559 |
ziwenxie/netease-dl | netease/weapi.py | Crawler.get_request | def get_request(self, url):
"""Send a get request.
warning: old api.
:return: a dict or raise Exception.
"""
resp = self.session.get(url, timeout=self.timeout,
proxies=self.proxies)
result = resp.json()
if result['code'] != 200:
LOG.error('Return %s when try to get %s', result, url)
raise GetRequestIllegal(result)
else:
return result | python | def get_request(self, url):
"""Send a get request.
warning: old api.
:return: a dict or raise Exception.
"""
resp = self.session.get(url, timeout=self.timeout,
proxies=self.proxies)
result = resp.json()
if result['code'] != 200:
LOG.error('Return %s when try to get %s', result, url)
raise GetRequestIllegal(result)
else:
return result | [
"def",
"get_request",
"(",
"self",
",",
"url",
")",
":",
"resp",
"=",
"self",
".",
"session",
".",
"get",
"(",
"url",
",",
"timeout",
"=",
"self",
".",
"timeout",
",",
"proxies",
"=",
"self",
".",
"proxies",
")",
"result",
"=",
"resp",
".",
"json",... | Send a get request.
warning: old api.
:return: a dict or raise Exception. | [
"Send",
"a",
"get",
"request",
"."
] | 84b226fc07b10f7f66580f0fc69f10356f66b5c3 | https://github.com/ziwenxie/netease-dl/blob/84b226fc07b10f7f66580f0fc69f10356f66b5c3/netease/weapi.py#L69-L83 | train | 207,560 |
ziwenxie/netease-dl | netease/weapi.py | Crawler.post_request | def post_request(self, url, params):
"""Send a post request.
:return: a dict or raise Exception.
"""
data = encrypted_request(params)
resp = self.session.post(url, data=data, timeout=self.timeout,
proxies=self.proxies)
result = resp.json()
if result['code'] != 200:
LOG.error('Return %s when try to post %s => %s',
result, url, params)
raise PostRequestIllegal(result)
else:
return result | python | def post_request(self, url, params):
"""Send a post request.
:return: a dict or raise Exception.
"""
data = encrypted_request(params)
resp = self.session.post(url, data=data, timeout=self.timeout,
proxies=self.proxies)
result = resp.json()
if result['code'] != 200:
LOG.error('Return %s when try to post %s => %s',
result, url, params)
raise PostRequestIllegal(result)
else:
return result | [
"def",
"post_request",
"(",
"self",
",",
"url",
",",
"params",
")",
":",
"data",
"=",
"encrypted_request",
"(",
"params",
")",
"resp",
"=",
"self",
".",
"session",
".",
"post",
"(",
"url",
",",
"data",
"=",
"data",
",",
"timeout",
"=",
"self",
".",
... | Send a post request.
:return: a dict or raise Exception. | [
"Send",
"a",
"post",
"request",
"."
] | 84b226fc07b10f7f66580f0fc69f10356f66b5c3 | https://github.com/ziwenxie/netease-dl/blob/84b226fc07b10f7f66580f0fc69f10356f66b5c3/netease/weapi.py#L86-L101 | train | 207,561 |
ziwenxie/netease-dl | netease/weapi.py | Crawler.search | def search(self, search_content, search_type, limit=9):
"""Search entrance.
:params search_content: search content.
:params search_type: search type.
:params limit: result count returned by weapi.
:return: a dict.
"""
url = 'http://music.163.com/weapi/cloudsearch/get/web?csrf_token='
params = {'s': search_content, 'type': search_type, 'offset': 0,
'sub': 'false', 'limit': limit}
result = self.post_request(url, params)
return result | python | def search(self, search_content, search_type, limit=9):
"""Search entrance.
:params search_content: search content.
:params search_type: search type.
:params limit: result count returned by weapi.
:return: a dict.
"""
url = 'http://music.163.com/weapi/cloudsearch/get/web?csrf_token='
params = {'s': search_content, 'type': search_type, 'offset': 0,
'sub': 'false', 'limit': limit}
result = self.post_request(url, params)
return result | [
"def",
"search",
"(",
"self",
",",
"search_content",
",",
"search_type",
",",
"limit",
"=",
"9",
")",
":",
"url",
"=",
"'http://music.163.com/weapi/cloudsearch/get/web?csrf_token='",
"params",
"=",
"{",
"'s'",
":",
"search_content",
",",
"'type'",
":",
"search_typ... | Search entrance.
:params search_content: search content.
:params search_type: search type.
:params limit: result count returned by weapi.
:return: a dict. | [
"Search",
"entrance",
"."
] | 84b226fc07b10f7f66580f0fc69f10356f66b5c3 | https://github.com/ziwenxie/netease-dl/blob/84b226fc07b10f7f66580f0fc69f10356f66b5c3/netease/weapi.py#L103-L116 | train | 207,562 |
ziwenxie/netease-dl | netease/weapi.py | Crawler.search_song | def search_song(self, song_name, quiet=False, limit=9):
"""Search song by song name.
:params song_name: song name.
:params quiet: automatically select the best one.
:params limit: song count returned by weapi.
:return: a Song object.
"""
result = self.search(song_name, search_type=1, limit=limit)
if result['result']['songCount'] <= 0:
LOG.warning('Song %s not existed!', song_name)
raise SearchNotFound('Song {} not existed.'.format(song_name))
else:
songs = result['result']['songs']
if quiet:
song_id, song_name = songs[0]['id'], songs[0]['name']
song = Song(song_id, song_name)
return song
else:
return self.display.select_one_song(songs) | python | def search_song(self, song_name, quiet=False, limit=9):
"""Search song by song name.
:params song_name: song name.
:params quiet: automatically select the best one.
:params limit: song count returned by weapi.
:return: a Song object.
"""
result = self.search(song_name, search_type=1, limit=limit)
if result['result']['songCount'] <= 0:
LOG.warning('Song %s not existed!', song_name)
raise SearchNotFound('Song {} not existed.'.format(song_name))
else:
songs = result['result']['songs']
if quiet:
song_id, song_name = songs[0]['id'], songs[0]['name']
song = Song(song_id, song_name)
return song
else:
return self.display.select_one_song(songs) | [
"def",
"search_song",
"(",
"self",
",",
"song_name",
",",
"quiet",
"=",
"False",
",",
"limit",
"=",
"9",
")",
":",
"result",
"=",
"self",
".",
"search",
"(",
"song_name",
",",
"search_type",
"=",
"1",
",",
"limit",
"=",
"limit",
")",
"if",
"result",
... | Search song by song name.
:params song_name: song name.
:params quiet: automatically select the best one.
:params limit: song count returned by weapi.
:return: a Song object. | [
"Search",
"song",
"by",
"song",
"name",
"."
] | 84b226fc07b10f7f66580f0fc69f10356f66b5c3 | https://github.com/ziwenxie/netease-dl/blob/84b226fc07b10f7f66580f0fc69f10356f66b5c3/netease/weapi.py#L118-L139 | train | 207,563 |
ziwenxie/netease-dl | netease/weapi.py | Crawler.search_album | def search_album(self, album_name, quiet=False, limit=9):
"""Search album by album name.
:params album_name: album name.
:params quiet: automatically select the best one.
:params limit: album count returned by weapi.
:return: a Album object.
"""
result = self.search(album_name, search_type=10, limit=limit)
if result['result']['albumCount'] <= 0:
LOG.warning('Album %s not existed!', album_name)
raise SearchNotFound('Album {} not existed'.format(album_name))
else:
albums = result['result']['albums']
if quiet:
album_id, album_name = albums[0]['id'], albums[0]['name']
album = Album(album_id, album_name)
return album
else:
return self.display.select_one_album(albums) | python | def search_album(self, album_name, quiet=False, limit=9):
"""Search album by album name.
:params album_name: album name.
:params quiet: automatically select the best one.
:params limit: album count returned by weapi.
:return: a Album object.
"""
result = self.search(album_name, search_type=10, limit=limit)
if result['result']['albumCount'] <= 0:
LOG.warning('Album %s not existed!', album_name)
raise SearchNotFound('Album {} not existed'.format(album_name))
else:
albums = result['result']['albums']
if quiet:
album_id, album_name = albums[0]['id'], albums[0]['name']
album = Album(album_id, album_name)
return album
else:
return self.display.select_one_album(albums) | [
"def",
"search_album",
"(",
"self",
",",
"album_name",
",",
"quiet",
"=",
"False",
",",
"limit",
"=",
"9",
")",
":",
"result",
"=",
"self",
".",
"search",
"(",
"album_name",
",",
"search_type",
"=",
"10",
",",
"limit",
"=",
"limit",
")",
"if",
"resul... | Search album by album name.
:params album_name: album name.
:params quiet: automatically select the best one.
:params limit: album count returned by weapi.
:return: a Album object. | [
"Search",
"album",
"by",
"album",
"name",
"."
] | 84b226fc07b10f7f66580f0fc69f10356f66b5c3 | https://github.com/ziwenxie/netease-dl/blob/84b226fc07b10f7f66580f0fc69f10356f66b5c3/netease/weapi.py#L141-L162 | train | 207,564 |
ziwenxie/netease-dl | netease/weapi.py | Crawler.search_artist | def search_artist(self, artist_name, quiet=False, limit=9):
"""Search artist by artist name.
:params artist_name: artist name.
:params quiet: automatically select the best one.
:params limit: artist count returned by weapi.
:return: a Artist object.
"""
result = self.search(artist_name, search_type=100, limit=limit)
if result['result']['artistCount'] <= 0:
LOG.warning('Artist %s not existed!', artist_name)
raise SearchNotFound('Artist {} not existed.'.format(artist_name))
else:
artists = result['result']['artists']
if quiet:
artist_id, artist_name = artists[0]['id'], artists[0]['name']
artist = Artist(artist_id, artist_name)
return artist
else:
return self.display.select_one_artist(artists) | python | def search_artist(self, artist_name, quiet=False, limit=9):
"""Search artist by artist name.
:params artist_name: artist name.
:params quiet: automatically select the best one.
:params limit: artist count returned by weapi.
:return: a Artist object.
"""
result = self.search(artist_name, search_type=100, limit=limit)
if result['result']['artistCount'] <= 0:
LOG.warning('Artist %s not existed!', artist_name)
raise SearchNotFound('Artist {} not existed.'.format(artist_name))
else:
artists = result['result']['artists']
if quiet:
artist_id, artist_name = artists[0]['id'], artists[0]['name']
artist = Artist(artist_id, artist_name)
return artist
else:
return self.display.select_one_artist(artists) | [
"def",
"search_artist",
"(",
"self",
",",
"artist_name",
",",
"quiet",
"=",
"False",
",",
"limit",
"=",
"9",
")",
":",
"result",
"=",
"self",
".",
"search",
"(",
"artist_name",
",",
"search_type",
"=",
"100",
",",
"limit",
"=",
"limit",
")",
"if",
"r... | Search artist by artist name.
:params artist_name: artist name.
:params quiet: automatically select the best one.
:params limit: artist count returned by weapi.
:return: a Artist object. | [
"Search",
"artist",
"by",
"artist",
"name",
"."
] | 84b226fc07b10f7f66580f0fc69f10356f66b5c3 | https://github.com/ziwenxie/netease-dl/blob/84b226fc07b10f7f66580f0fc69f10356f66b5c3/netease/weapi.py#L164-L185 | train | 207,565 |
ziwenxie/netease-dl | netease/weapi.py | Crawler.search_playlist | def search_playlist(self, playlist_name, quiet=False, limit=9):
"""Search playlist by playlist name.
:params playlist_name: playlist name.
:params quiet: automatically select the best one.
:params limit: playlist count returned by weapi.
:return: a Playlist object.
"""
result = self.search(playlist_name, search_type=1000, limit=limit)
if result['result']['playlistCount'] <= 0:
LOG.warning('Playlist %s not existed!', playlist_name)
raise SearchNotFound('playlist {} not existed'.format(playlist_name))
else:
playlists = result['result']['playlists']
if quiet:
playlist_id, playlist_name = playlists[0]['id'], playlists[0]['name']
playlist = Playlist(playlist_id, playlist_name)
return playlist
else:
return self.display.select_one_playlist(playlists) | python | def search_playlist(self, playlist_name, quiet=False, limit=9):
"""Search playlist by playlist name.
:params playlist_name: playlist name.
:params quiet: automatically select the best one.
:params limit: playlist count returned by weapi.
:return: a Playlist object.
"""
result = self.search(playlist_name, search_type=1000, limit=limit)
if result['result']['playlistCount'] <= 0:
LOG.warning('Playlist %s not existed!', playlist_name)
raise SearchNotFound('playlist {} not existed'.format(playlist_name))
else:
playlists = result['result']['playlists']
if quiet:
playlist_id, playlist_name = playlists[0]['id'], playlists[0]['name']
playlist = Playlist(playlist_id, playlist_name)
return playlist
else:
return self.display.select_one_playlist(playlists) | [
"def",
"search_playlist",
"(",
"self",
",",
"playlist_name",
",",
"quiet",
"=",
"False",
",",
"limit",
"=",
"9",
")",
":",
"result",
"=",
"self",
".",
"search",
"(",
"playlist_name",
",",
"search_type",
"=",
"1000",
",",
"limit",
"=",
"limit",
")",
"if... | Search playlist by playlist name.
:params playlist_name: playlist name.
:params quiet: automatically select the best one.
:params limit: playlist count returned by weapi.
:return: a Playlist object. | [
"Search",
"playlist",
"by",
"playlist",
"name",
"."
] | 84b226fc07b10f7f66580f0fc69f10356f66b5c3 | https://github.com/ziwenxie/netease-dl/blob/84b226fc07b10f7f66580f0fc69f10356f66b5c3/netease/weapi.py#L187-L208 | train | 207,566 |
ziwenxie/netease-dl | netease/weapi.py | Crawler.search_user | def search_user(self, user_name, quiet=False, limit=9):
"""Search user by user name.
:params user_name: user name.
:params quiet: automatically select the best one.
:params limit: user count returned by weapi.
:return: a User object.
"""
result = self.search(user_name, search_type=1002, limit=limit)
if result['result']['userprofileCount'] <= 0:
LOG.warning('User %s not existed!', user_name)
raise SearchNotFound('user {} not existed'.format(user_name))
else:
users = result['result']['userprofiles']
if quiet:
user_id, user_name = users[0]['userId'], users[0]['nickname']
user = User(user_id, user_name)
return user
else:
return self.display.select_one_user(users) | python | def search_user(self, user_name, quiet=False, limit=9):
"""Search user by user name.
:params user_name: user name.
:params quiet: automatically select the best one.
:params limit: user count returned by weapi.
:return: a User object.
"""
result = self.search(user_name, search_type=1002, limit=limit)
if result['result']['userprofileCount'] <= 0:
LOG.warning('User %s not existed!', user_name)
raise SearchNotFound('user {} not existed'.format(user_name))
else:
users = result['result']['userprofiles']
if quiet:
user_id, user_name = users[0]['userId'], users[0]['nickname']
user = User(user_id, user_name)
return user
else:
return self.display.select_one_user(users) | [
"def",
"search_user",
"(",
"self",
",",
"user_name",
",",
"quiet",
"=",
"False",
",",
"limit",
"=",
"9",
")",
":",
"result",
"=",
"self",
".",
"search",
"(",
"user_name",
",",
"search_type",
"=",
"1002",
",",
"limit",
"=",
"limit",
")",
"if",
"result... | Search user by user name.
:params user_name: user name.
:params quiet: automatically select the best one.
:params limit: user count returned by weapi.
:return: a User object. | [
"Search",
"user",
"by",
"user",
"name",
"."
] | 84b226fc07b10f7f66580f0fc69f10356f66b5c3 | https://github.com/ziwenxie/netease-dl/blob/84b226fc07b10f7f66580f0fc69f10356f66b5c3/netease/weapi.py#L210-L231 | train | 207,567 |
ziwenxie/netease-dl | netease/weapi.py | Crawler.get_user_playlists | def get_user_playlists(self, user_id, limit=1000):
"""Get a user's all playlists.
warning: login is required for private playlist.
:params user_id: user id.
:params limit: playlist count returned by weapi.
:return: a Playlist Object.
"""
url = 'http://music.163.com/weapi/user/playlist?csrf_token='
csrf = ''
params = {'offset': 0, 'uid': user_id, 'limit': limit,
'csrf_token': csrf}
result = self.post_request(url, params)
playlists = result['playlist']
return self.display.select_one_playlist(playlists) | python | def get_user_playlists(self, user_id, limit=1000):
"""Get a user's all playlists.
warning: login is required for private playlist.
:params user_id: user id.
:params limit: playlist count returned by weapi.
:return: a Playlist Object.
"""
url = 'http://music.163.com/weapi/user/playlist?csrf_token='
csrf = ''
params = {'offset': 0, 'uid': user_id, 'limit': limit,
'csrf_token': csrf}
result = self.post_request(url, params)
playlists = result['playlist']
return self.display.select_one_playlist(playlists) | [
"def",
"get_user_playlists",
"(",
"self",
",",
"user_id",
",",
"limit",
"=",
"1000",
")",
":",
"url",
"=",
"'http://music.163.com/weapi/user/playlist?csrf_token='",
"csrf",
"=",
"''",
"params",
"=",
"{",
"'offset'",
":",
"0",
",",
"'uid'",
":",
"user_id",
",",... | Get a user's all playlists.
warning: login is required for private playlist.
:params user_id: user id.
:params limit: playlist count returned by weapi.
:return: a Playlist Object. | [
"Get",
"a",
"user",
"s",
"all",
"playlists",
"."
] | 84b226fc07b10f7f66580f0fc69f10356f66b5c3 | https://github.com/ziwenxie/netease-dl/blob/84b226fc07b10f7f66580f0fc69f10356f66b5c3/netease/weapi.py#L233-L248 | train | 207,568 |
ziwenxie/netease-dl | netease/weapi.py | Crawler.get_playlist_songs | def get_playlist_songs(self, playlist_id, limit=1000):
"""Get a playlists's all songs.
:params playlist_id: playlist id.
:params limit: length of result returned by weapi.
:return: a list of Song object.
"""
url = 'http://music.163.com/weapi/v3/playlist/detail?csrf_token='
csrf = ''
params = {'id': playlist_id, 'offset': 0, 'total': True,
'limit': limit, 'n': 1000, 'csrf_token': csrf}
result = self.post_request(url, params)
songs = result['playlist']['tracks']
songs = [Song(song['id'], song['name']) for song in songs]
return songs | python | def get_playlist_songs(self, playlist_id, limit=1000):
"""Get a playlists's all songs.
:params playlist_id: playlist id.
:params limit: length of result returned by weapi.
:return: a list of Song object.
"""
url = 'http://music.163.com/weapi/v3/playlist/detail?csrf_token='
csrf = ''
params = {'id': playlist_id, 'offset': 0, 'total': True,
'limit': limit, 'n': 1000, 'csrf_token': csrf}
result = self.post_request(url, params)
songs = result['playlist']['tracks']
songs = [Song(song['id'], song['name']) for song in songs]
return songs | [
"def",
"get_playlist_songs",
"(",
"self",
",",
"playlist_id",
",",
"limit",
"=",
"1000",
")",
":",
"url",
"=",
"'http://music.163.com/weapi/v3/playlist/detail?csrf_token='",
"csrf",
"=",
"''",
"params",
"=",
"{",
"'id'",
":",
"playlist_id",
",",
"'offset'",
":",
... | Get a playlists's all songs.
:params playlist_id: playlist id.
:params limit: length of result returned by weapi.
:return: a list of Song object. | [
"Get",
"a",
"playlists",
"s",
"all",
"songs",
"."
] | 84b226fc07b10f7f66580f0fc69f10356f66b5c3 | https://github.com/ziwenxie/netease-dl/blob/84b226fc07b10f7f66580f0fc69f10356f66b5c3/netease/weapi.py#L250-L266 | train | 207,569 |
ziwenxie/netease-dl | netease/weapi.py | Crawler.get_album_songs | def get_album_songs(self, album_id):
"""Get a album's all songs.
warning: use old api.
:params album_id: album id.
:return: a list of Song object.
"""
url = 'http://music.163.com/api/album/{}/'.format(album_id)
result = self.get_request(url)
songs = result['album']['songs']
songs = [Song(song['id'], song['name']) for song in songs]
return songs | python | def get_album_songs(self, album_id):
"""Get a album's all songs.
warning: use old api.
:params album_id: album id.
:return: a list of Song object.
"""
url = 'http://music.163.com/api/album/{}/'.format(album_id)
result = self.get_request(url)
songs = result['album']['songs']
songs = [Song(song['id'], song['name']) for song in songs]
return songs | [
"def",
"get_album_songs",
"(",
"self",
",",
"album_id",
")",
":",
"url",
"=",
"'http://music.163.com/api/album/{}/'",
".",
"format",
"(",
"album_id",
")",
"result",
"=",
"self",
".",
"get_request",
"(",
"url",
")",
"songs",
"=",
"result",
"[",
"'album'",
"]"... | Get a album's all songs.
warning: use old api.
:params album_id: album id.
:return: a list of Song object. | [
"Get",
"a",
"album",
"s",
"all",
"songs",
"."
] | 84b226fc07b10f7f66580f0fc69f10356f66b5c3 | https://github.com/ziwenxie/netease-dl/blob/84b226fc07b10f7f66580f0fc69f10356f66b5c3/netease/weapi.py#L268-L281 | train | 207,570 |
ziwenxie/netease-dl | netease/weapi.py | Crawler.get_artists_hot_songs | def get_artists_hot_songs(self, artist_id):
"""Get a artist's top50 songs.
warning: use old api.
:params artist_id: artist id.
:return: a list of Song object.
"""
url = 'http://music.163.com/api/artist/{}'.format(artist_id)
result = self.get_request(url)
hot_songs = result['hotSongs']
songs = [Song(song['id'], song['name']) for song in hot_songs]
return songs | python | def get_artists_hot_songs(self, artist_id):
"""Get a artist's top50 songs.
warning: use old api.
:params artist_id: artist id.
:return: a list of Song object.
"""
url = 'http://music.163.com/api/artist/{}'.format(artist_id)
result = self.get_request(url)
hot_songs = result['hotSongs']
songs = [Song(song['id'], song['name']) for song in hot_songs]
return songs | [
"def",
"get_artists_hot_songs",
"(",
"self",
",",
"artist_id",
")",
":",
"url",
"=",
"'http://music.163.com/api/artist/{}'",
".",
"format",
"(",
"artist_id",
")",
"result",
"=",
"self",
".",
"get_request",
"(",
"url",
")",
"hot_songs",
"=",
"result",
"[",
"'ho... | Get a artist's top50 songs.
warning: use old api.
:params artist_id: artist id.
:return: a list of Song object. | [
"Get",
"a",
"artist",
"s",
"top50",
"songs",
"."
] | 84b226fc07b10f7f66580f0fc69f10356f66b5c3 | https://github.com/ziwenxie/netease-dl/blob/84b226fc07b10f7f66580f0fc69f10356f66b5c3/netease/weapi.py#L283-L295 | train | 207,571 |
ziwenxie/netease-dl | netease/weapi.py | Crawler.get_song_url | def get_song_url(self, song_id, bit_rate=320000):
"""Get a song's download address.
:params song_id: song id<int>.
:params bit_rate: {'MD 128k': 128000, 'HD 320k': 320000}
:return: a song's download address.
"""
url = 'http://music.163.com/weapi/song/enhance/player/url?csrf_token='
csrf = ''
params = {'ids': [song_id], 'br': bit_rate, 'csrf_token': csrf}
result = self.post_request(url, params)
song_url = result['data'][0]['url'] # download address
if song_url is None: # Taylor Swift's song is not available
LOG.warning(
'Song %s is not available due to copyright issue. => %s',
song_id, result)
raise SongNotAvailable(
'Song {} is not available due to copyright issue.'.format(song_id))
else:
return song_url | python | def get_song_url(self, song_id, bit_rate=320000):
"""Get a song's download address.
:params song_id: song id<int>.
:params bit_rate: {'MD 128k': 128000, 'HD 320k': 320000}
:return: a song's download address.
"""
url = 'http://music.163.com/weapi/song/enhance/player/url?csrf_token='
csrf = ''
params = {'ids': [song_id], 'br': bit_rate, 'csrf_token': csrf}
result = self.post_request(url, params)
song_url = result['data'][0]['url'] # download address
if song_url is None: # Taylor Swift's song is not available
LOG.warning(
'Song %s is not available due to copyright issue. => %s',
song_id, result)
raise SongNotAvailable(
'Song {} is not available due to copyright issue.'.format(song_id))
else:
return song_url | [
"def",
"get_song_url",
"(",
"self",
",",
"song_id",
",",
"bit_rate",
"=",
"320000",
")",
":",
"url",
"=",
"'http://music.163.com/weapi/song/enhance/player/url?csrf_token='",
"csrf",
"=",
"''",
"params",
"=",
"{",
"'ids'",
":",
"[",
"song_id",
"]",
",",
"'br'",
... | Get a song's download address.
:params song_id: song id<int>.
:params bit_rate: {'MD 128k': 128000, 'HD 320k': 320000}
:return: a song's download address. | [
"Get",
"a",
"song",
"s",
"download",
"address",
"."
] | 84b226fc07b10f7f66580f0fc69f10356f66b5c3 | https://github.com/ziwenxie/netease-dl/blob/84b226fc07b10f7f66580f0fc69f10356f66b5c3/netease/weapi.py#L297-L318 | train | 207,572 |
ziwenxie/netease-dl | netease/weapi.py | Crawler.get_song_lyric | def get_song_lyric(self, song_id):
"""Get a song's lyric.
warning: use old api.
:params song_id: song id.
:return: a song's lyric.
"""
url = 'http://music.163.com/api/song/lyric?os=osx&id={}&lv=-1&kv=-1&tv=-1'.format( # NOQA
song_id)
result = self.get_request(url)
if 'lrc' in result and result['lrc']['lyric'] is not None:
lyric_info = result['lrc']['lyric']
else:
lyric_info = 'Lyric not found.'
return lyric_info | python | def get_song_lyric(self, song_id):
"""Get a song's lyric.
warning: use old api.
:params song_id: song id.
:return: a song's lyric.
"""
url = 'http://music.163.com/api/song/lyric?os=osx&id={}&lv=-1&kv=-1&tv=-1'.format( # NOQA
song_id)
result = self.get_request(url)
if 'lrc' in result and result['lrc']['lyric'] is not None:
lyric_info = result['lrc']['lyric']
else:
lyric_info = 'Lyric not found.'
return lyric_info | [
"def",
"get_song_lyric",
"(",
"self",
",",
"song_id",
")",
":",
"url",
"=",
"'http://music.163.com/api/song/lyric?os=osx&id={}&lv=-1&kv=-1&tv=-1'",
".",
"format",
"(",
"# NOQA",
"song_id",
")",
"result",
"=",
"self",
".",
"get_request",
"(",
"url",
")",
"if",
"'lr... | Get a song's lyric.
warning: use old api.
:params song_id: song id.
:return: a song's lyric. | [
"Get",
"a",
"song",
"s",
"lyric",
"."
] | 84b226fc07b10f7f66580f0fc69f10356f66b5c3 | https://github.com/ziwenxie/netease-dl/blob/84b226fc07b10f7f66580f0fc69f10356f66b5c3/netease/weapi.py#L320-L335 | train | 207,573 |
ziwenxie/netease-dl | netease/weapi.py | Crawler.get_song_by_url | def get_song_by_url(self, song_url, song_name, folder, lyric_info):
"""Download a song and save it to disk.
:params song_url: download address.
:params song_name: song name.
:params folder: storage path.
:params lyric: lyric info.
"""
if not os.path.exists(folder):
os.makedirs(folder)
fpath = os.path.join(folder, song_name+'.mp3')
if sys.platform == 'win32' or sys.platform == 'cygwin':
valid_name = re.sub(r'[<>:"/\\|?*]', '', song_name)
if valid_name != song_name:
click.echo('{} will be saved as: {}.mp3'.format(song_name, valid_name))
fpath = os.path.join(folder, valid_name + '.mp3')
if not os.path.exists(fpath):
resp = self.download_session.get(
song_url, timeout=self.timeout, stream=True)
length = int(resp.headers.get('content-length'))
label = 'Downloading {} {}kb'.format(song_name, int(length/1024))
with click.progressbar(length=length, label=label) as progressbar:
with open(fpath, 'wb') as song_file:
for chunk in resp.iter_content(chunk_size=1024):
if chunk: # filter out keep-alive new chunks
song_file.write(chunk)
progressbar.update(1024)
if lyric_info:
folder = os.path.join(folder, 'lyric')
if not os.path.exists(folder):
os.makedirs(folder)
fpath = os.path.join(folder, song_name+'.lrc')
with open(fpath, 'w') as lyric_file:
lyric_file.write(lyric_info) | python | def get_song_by_url(self, song_url, song_name, folder, lyric_info):
"""Download a song and save it to disk.
:params song_url: download address.
:params song_name: song name.
:params folder: storage path.
:params lyric: lyric info.
"""
if not os.path.exists(folder):
os.makedirs(folder)
fpath = os.path.join(folder, song_name+'.mp3')
if sys.platform == 'win32' or sys.platform == 'cygwin':
valid_name = re.sub(r'[<>:"/\\|?*]', '', song_name)
if valid_name != song_name:
click.echo('{} will be saved as: {}.mp3'.format(song_name, valid_name))
fpath = os.path.join(folder, valid_name + '.mp3')
if not os.path.exists(fpath):
resp = self.download_session.get(
song_url, timeout=self.timeout, stream=True)
length = int(resp.headers.get('content-length'))
label = 'Downloading {} {}kb'.format(song_name, int(length/1024))
with click.progressbar(length=length, label=label) as progressbar:
with open(fpath, 'wb') as song_file:
for chunk in resp.iter_content(chunk_size=1024):
if chunk: # filter out keep-alive new chunks
song_file.write(chunk)
progressbar.update(1024)
if lyric_info:
folder = os.path.join(folder, 'lyric')
if not os.path.exists(folder):
os.makedirs(folder)
fpath = os.path.join(folder, song_name+'.lrc')
with open(fpath, 'w') as lyric_file:
lyric_file.write(lyric_info) | [
"def",
"get_song_by_url",
"(",
"self",
",",
"song_url",
",",
"song_name",
",",
"folder",
",",
"lyric_info",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"folder",
")",
":",
"os",
".",
"makedirs",
"(",
"folder",
")",
"fpath",
"=",
"os... | Download a song and save it to disk.
:params song_url: download address.
:params song_name: song name.
:params folder: storage path.
:params lyric: lyric info. | [
"Download",
"a",
"song",
"and",
"save",
"it",
"to",
"disk",
"."
] | 84b226fc07b10f7f66580f0fc69f10356f66b5c3 | https://github.com/ziwenxie/netease-dl/blob/84b226fc07b10f7f66580f0fc69f10356f66b5c3/netease/weapi.py#L338-L376 | train | 207,574 |
ziwenxie/netease-dl | netease/weapi.py | Crawler.login | def login(self):
"""Login entrance."""
username = click.prompt('Please enter your email or phone number')
password = click.prompt('Please enter your password', hide_input=True)
pattern = re.compile(r'^0\d{2,3}\d{7,8}$|^1[34578]\d{9}$')
if pattern.match(username): # use phone number to login
url = 'https://music.163.com/weapi/login/cellphone'
params = {
'phone': username,
'password': hashlib.md5(password.encode('utf-8')).hexdigest(),
'rememberLogin': 'true'}
else: # use email to login
url = 'https://music.163.com/weapi/login?csrf_token='
params = {
'username': username,
'password': hashlib.md5(password.encode('utf-8')).hexdigest(),
'rememberLogin': 'true'}
try:
result = self.post_request(url, params)
except PostRequestIllegal:
click.echo('Password Error!')
sys.exit(1)
self.session.cookies.save()
uid = result['account']['id']
with open(person_info_path, 'w') as person_info:
person_info.write(str(uid)) | python | def login(self):
"""Login entrance."""
username = click.prompt('Please enter your email or phone number')
password = click.prompt('Please enter your password', hide_input=True)
pattern = re.compile(r'^0\d{2,3}\d{7,8}$|^1[34578]\d{9}$')
if pattern.match(username): # use phone number to login
url = 'https://music.163.com/weapi/login/cellphone'
params = {
'phone': username,
'password': hashlib.md5(password.encode('utf-8')).hexdigest(),
'rememberLogin': 'true'}
else: # use email to login
url = 'https://music.163.com/weapi/login?csrf_token='
params = {
'username': username,
'password': hashlib.md5(password.encode('utf-8')).hexdigest(),
'rememberLogin': 'true'}
try:
result = self.post_request(url, params)
except PostRequestIllegal:
click.echo('Password Error!')
sys.exit(1)
self.session.cookies.save()
uid = result['account']['id']
with open(person_info_path, 'w') as person_info:
person_info.write(str(uid)) | [
"def",
"login",
"(",
"self",
")",
":",
"username",
"=",
"click",
".",
"prompt",
"(",
"'Please enter your email or phone number'",
")",
"password",
"=",
"click",
".",
"prompt",
"(",
"'Please enter your password'",
",",
"hide_input",
"=",
"True",
")",
"pattern",
"... | Login entrance. | [
"Login",
"entrance",
"."
] | 84b226fc07b10f7f66580f0fc69f10356f66b5c3 | https://github.com/ziwenxie/netease-dl/blob/84b226fc07b10f7f66580f0fc69f10356f66b5c3/netease/weapi.py#L378-L405 | train | 207,575 |
djangonauts/django-rest-framework-gis | rest_framework_gis/serializers.py | GeoFeatureModelSerializer.to_representation | def to_representation(self, instance):
"""
Serialize objects -> primitives.
"""
# prepare OrderedDict geojson structure
feature = OrderedDict()
# the list of fields that will be processed by get_properties
# we will remove fields that have been already processed
# to increase performance on large numbers
fields = list(self.fields.values())
# optional id attribute
if self.Meta.id_field:
field = self.fields[self.Meta.id_field]
value = field.get_attribute(instance)
feature["id"] = field.to_representation(value)
fields.remove(field)
# required type attribute
# must be "Feature" according to GeoJSON spec
feature["type"] = "Feature"
# required geometry attribute
# MUST be present in output according to GeoJSON spec
field = self.fields[self.Meta.geo_field]
geo_value = field.get_attribute(instance)
feature["geometry"] = field.to_representation(geo_value)
fields.remove(field)
# Bounding Box
# if auto_bbox feature is enabled
# bbox will be determined automatically automatically
if self.Meta.auto_bbox and geo_value:
feature["bbox"] = geo_value.extent
# otherwise it can be determined via another field
elif self.Meta.bbox_geo_field:
field = self.fields[self.Meta.bbox_geo_field]
value = field.get_attribute(instance)
feature["bbox"] = value.extent if hasattr(value, 'extent') else None
fields.remove(field)
# GeoJSON properties
feature["properties"] = self.get_properties(instance, fields)
return feature | python | def to_representation(self, instance):
"""
Serialize objects -> primitives.
"""
# prepare OrderedDict geojson structure
feature = OrderedDict()
# the list of fields that will be processed by get_properties
# we will remove fields that have been already processed
# to increase performance on large numbers
fields = list(self.fields.values())
# optional id attribute
if self.Meta.id_field:
field = self.fields[self.Meta.id_field]
value = field.get_attribute(instance)
feature["id"] = field.to_representation(value)
fields.remove(field)
# required type attribute
# must be "Feature" according to GeoJSON spec
feature["type"] = "Feature"
# required geometry attribute
# MUST be present in output according to GeoJSON spec
field = self.fields[self.Meta.geo_field]
geo_value = field.get_attribute(instance)
feature["geometry"] = field.to_representation(geo_value)
fields.remove(field)
# Bounding Box
# if auto_bbox feature is enabled
# bbox will be determined automatically automatically
if self.Meta.auto_bbox and geo_value:
feature["bbox"] = geo_value.extent
# otherwise it can be determined via another field
elif self.Meta.bbox_geo_field:
field = self.fields[self.Meta.bbox_geo_field]
value = field.get_attribute(instance)
feature["bbox"] = value.extent if hasattr(value, 'extent') else None
fields.remove(field)
# GeoJSON properties
feature["properties"] = self.get_properties(instance, fields)
return feature | [
"def",
"to_representation",
"(",
"self",
",",
"instance",
")",
":",
"# prepare OrderedDict geojson structure",
"feature",
"=",
"OrderedDict",
"(",
")",
"# the list of fields that will be processed by get_properties",
"# we will remove fields that have been already processed",
"# to i... | Serialize objects -> primitives. | [
"Serialize",
"objects",
"-",
">",
"primitives",
"."
] | 7430d6b1ca480222c1b837748f4c60ea10c85f22 | https://github.com/djangonauts/django-rest-framework-gis/blob/7430d6b1ca480222c1b837748f4c60ea10c85f22/rest_framework_gis/serializers.py#L91-L134 | train | 207,576 |
djangonauts/django-rest-framework-gis | rest_framework_gis/serializers.py | GeoFeatureModelSerializer.get_properties | def get_properties(self, instance, fields):
"""
Get the feature metadata which will be used for the GeoJSON
"properties" key.
By default it returns all serializer fields excluding those used for
the ID, the geometry and the bounding box.
:param instance: The current Django model instance
:param fields: The list of fields to process (fields already processed have been removed)
:return: OrderedDict containing the properties of the current feature
:rtype: OrderedDict
"""
properties = OrderedDict()
for field in fields:
if field.write_only:
continue
value = field.get_attribute(instance)
representation = None
if value is not None:
representation = field.to_representation(value)
properties[field.field_name] = representation
return properties | python | def get_properties(self, instance, fields):
"""
Get the feature metadata which will be used for the GeoJSON
"properties" key.
By default it returns all serializer fields excluding those used for
the ID, the geometry and the bounding box.
:param instance: The current Django model instance
:param fields: The list of fields to process (fields already processed have been removed)
:return: OrderedDict containing the properties of the current feature
:rtype: OrderedDict
"""
properties = OrderedDict()
for field in fields:
if field.write_only:
continue
value = field.get_attribute(instance)
representation = None
if value is not None:
representation = field.to_representation(value)
properties[field.field_name] = representation
return properties | [
"def",
"get_properties",
"(",
"self",
",",
"instance",
",",
"fields",
")",
":",
"properties",
"=",
"OrderedDict",
"(",
")",
"for",
"field",
"in",
"fields",
":",
"if",
"field",
".",
"write_only",
":",
"continue",
"value",
"=",
"field",
".",
"get_attribute",... | Get the feature metadata which will be used for the GeoJSON
"properties" key.
By default it returns all serializer fields excluding those used for
the ID, the geometry and the bounding box.
:param instance: The current Django model instance
:param fields: The list of fields to process (fields already processed have been removed)
:return: OrderedDict containing the properties of the current feature
:rtype: OrderedDict | [
"Get",
"the",
"feature",
"metadata",
"which",
"will",
"be",
"used",
"for",
"the",
"GeoJSON",
"properties",
"key",
"."
] | 7430d6b1ca480222c1b837748f4c60ea10c85f22 | https://github.com/djangonauts/django-rest-framework-gis/blob/7430d6b1ca480222c1b837748f4c60ea10c85f22/rest_framework_gis/serializers.py#L136-L160 | train | 207,577 |
djangonauts/django-rest-framework-gis | rest_framework_gis/serializers.py | GeoFeatureModelSerializer.to_internal_value | def to_internal_value(self, data):
"""
Override the parent method to first remove the GeoJSON formatting
"""
if 'properties' in data:
data = self.unformat_geojson(data)
return super(GeoFeatureModelSerializer, self).to_internal_value(data) | python | def to_internal_value(self, data):
"""
Override the parent method to first remove the GeoJSON formatting
"""
if 'properties' in data:
data = self.unformat_geojson(data)
return super(GeoFeatureModelSerializer, self).to_internal_value(data) | [
"def",
"to_internal_value",
"(",
"self",
",",
"data",
")",
":",
"if",
"'properties'",
"in",
"data",
":",
"data",
"=",
"self",
".",
"unformat_geojson",
"(",
"data",
")",
"return",
"super",
"(",
"GeoFeatureModelSerializer",
",",
"self",
")",
".",
"to_internal_... | Override the parent method to first remove the GeoJSON formatting | [
"Override",
"the",
"parent",
"method",
"to",
"first",
"remove",
"the",
"GeoJSON",
"formatting"
] | 7430d6b1ca480222c1b837748f4c60ea10c85f22 | https://github.com/djangonauts/django-rest-framework-gis/blob/7430d6b1ca480222c1b837748f4c60ea10c85f22/rest_framework_gis/serializers.py#L162-L168 | train | 207,578 |
djangonauts/django-rest-framework-gis | rest_framework_gis/serializers.py | GeoFeatureModelSerializer.unformat_geojson | def unformat_geojson(self, feature):
"""
This function should return a dictionary containing keys which maps
to serializer fields.
Remember that GeoJSON contains a key "properties" which contains the
feature metadata. This should be flattened to make sure this
metadata is stored in the right serializer fields.
:param feature: The dictionary containing the feature data directly
from the GeoJSON data.
:return: A new dictionary which maps the GeoJSON values to
serializer fields
"""
attrs = feature["properties"]
if 'geometry' in feature:
attrs[self.Meta.geo_field] = feature['geometry']
if self.Meta.bbox_geo_field and 'bbox' in feature:
attrs[self.Meta.bbox_geo_field] = Polygon.from_bbox(feature['bbox'])
return attrs | python | def unformat_geojson(self, feature):
"""
This function should return a dictionary containing keys which maps
to serializer fields.
Remember that GeoJSON contains a key "properties" which contains the
feature metadata. This should be flattened to make sure this
metadata is stored in the right serializer fields.
:param feature: The dictionary containing the feature data directly
from the GeoJSON data.
:return: A new dictionary which maps the GeoJSON values to
serializer fields
"""
attrs = feature["properties"]
if 'geometry' in feature:
attrs[self.Meta.geo_field] = feature['geometry']
if self.Meta.bbox_geo_field and 'bbox' in feature:
attrs[self.Meta.bbox_geo_field] = Polygon.from_bbox(feature['bbox'])
return attrs | [
"def",
"unformat_geojson",
"(",
"self",
",",
"feature",
")",
":",
"attrs",
"=",
"feature",
"[",
"\"properties\"",
"]",
"if",
"'geometry'",
"in",
"feature",
":",
"attrs",
"[",
"self",
".",
"Meta",
".",
"geo_field",
"]",
"=",
"feature",
"[",
"'geometry'",
... | This function should return a dictionary containing keys which maps
to serializer fields.
Remember that GeoJSON contains a key "properties" which contains the
feature metadata. This should be flattened to make sure this
metadata is stored in the right serializer fields.
:param feature: The dictionary containing the feature data directly
from the GeoJSON data.
:return: A new dictionary which maps the GeoJSON values to
serializer fields | [
"This",
"function",
"should",
"return",
"a",
"dictionary",
"containing",
"keys",
"which",
"maps",
"to",
"serializer",
"fields",
"."
] | 7430d6b1ca480222c1b837748f4c60ea10c85f22 | https://github.com/djangonauts/django-rest-framework-gis/blob/7430d6b1ca480222c1b837748f4c60ea10c85f22/rest_framework_gis/serializers.py#L170-L192 | train | 207,579 |
djangonauts/django-rest-framework-gis | rest_framework_gis/apps.py | AppConfig.ready | def ready(self):
"""
update Django Rest Framework serializer mappings
"""
from django.contrib.gis.db import models
from rest_framework.serializers import ModelSerializer
from .fields import GeometryField
try:
# drf 3.0
field_mapping = ModelSerializer._field_mapping.mapping
except AttributeError:
# drf 3.1
field_mapping = ModelSerializer.serializer_field_mapping
# map GeoDjango fields to drf-gis GeometryField
field_mapping.update({
models.GeometryField: GeometryField,
models.PointField: GeometryField,
models.LineStringField: GeometryField,
models.PolygonField: GeometryField,
models.MultiPointField: GeometryField,
models.MultiLineStringField: GeometryField,
models.MultiPolygonField: GeometryField,
models.GeometryCollectionField: GeometryField
}) | python | def ready(self):
"""
update Django Rest Framework serializer mappings
"""
from django.contrib.gis.db import models
from rest_framework.serializers import ModelSerializer
from .fields import GeometryField
try:
# drf 3.0
field_mapping = ModelSerializer._field_mapping.mapping
except AttributeError:
# drf 3.1
field_mapping = ModelSerializer.serializer_field_mapping
# map GeoDjango fields to drf-gis GeometryField
field_mapping.update({
models.GeometryField: GeometryField,
models.PointField: GeometryField,
models.LineStringField: GeometryField,
models.PolygonField: GeometryField,
models.MultiPointField: GeometryField,
models.MultiLineStringField: GeometryField,
models.MultiPolygonField: GeometryField,
models.GeometryCollectionField: GeometryField
}) | [
"def",
"ready",
"(",
"self",
")",
":",
"from",
"django",
".",
"contrib",
".",
"gis",
".",
"db",
"import",
"models",
"from",
"rest_framework",
".",
"serializers",
"import",
"ModelSerializer",
"from",
".",
"fields",
"import",
"GeometryField",
"try",
":",
"# dr... | update Django Rest Framework serializer mappings | [
"update",
"Django",
"Rest",
"Framework",
"serializer",
"mappings"
] | 7430d6b1ca480222c1b837748f4c60ea10c85f22 | https://github.com/djangonauts/django-rest-framework-gis/blob/7430d6b1ca480222c1b837748f4c60ea10c85f22/rest_framework_gis/apps.py#L7-L32 | train | 207,580 |
djangonauts/django-rest-framework-gis | rest_framework_gis/filters.py | DistanceToPointFilter.dist_to_deg | def dist_to_deg(self, distance, latitude):
"""
distance = distance in meters
latitude = latitude in degrees
at the equator, the distance of one degree is equal in latitude and longitude.
at higher latitudes, a degree longitude is shorter in length, proportional to cos(latitude)
http://en.wikipedia.org/wiki/Decimal_degrees
This function is part of a distance filter where the database 'distance' is in degrees.
There's no good single-valued answer to this problem.
The distance/ degree is quite constant N/S around the earth (latitude),
but varies over a huge range E/W (longitude).
Split the difference: I'm going to average the the degrees latitude and degrees longitude
corresponding to the given distance. At high latitudes, this will be too short N/S
and too long E/W. It splits the errors between the two axes.
Errors are < 25 percent for latitudes < 60 degrees N/S.
"""
# d * (180 / pi) / earthRadius ==> degrees longitude
# (degrees longitude) / cos(latitude) ==> degrees latitude
lat = latitude if latitude >= 0 else -1 * latitude
rad2deg = 180 / pi
earthRadius = 6378160.0
latitudeCorrection = 0.5 * (1 + cos(lat * pi / 180))
return (distance / (earthRadius * latitudeCorrection) * rad2deg) | python | def dist_to_deg(self, distance, latitude):
"""
distance = distance in meters
latitude = latitude in degrees
at the equator, the distance of one degree is equal in latitude and longitude.
at higher latitudes, a degree longitude is shorter in length, proportional to cos(latitude)
http://en.wikipedia.org/wiki/Decimal_degrees
This function is part of a distance filter where the database 'distance' is in degrees.
There's no good single-valued answer to this problem.
The distance/ degree is quite constant N/S around the earth (latitude),
but varies over a huge range E/W (longitude).
Split the difference: I'm going to average the the degrees latitude and degrees longitude
corresponding to the given distance. At high latitudes, this will be too short N/S
and too long E/W. It splits the errors between the two axes.
Errors are < 25 percent for latitudes < 60 degrees N/S.
"""
# d * (180 / pi) / earthRadius ==> degrees longitude
# (degrees longitude) / cos(latitude) ==> degrees latitude
lat = latitude if latitude >= 0 else -1 * latitude
rad2deg = 180 / pi
earthRadius = 6378160.0
latitudeCorrection = 0.5 * (1 + cos(lat * pi / 180))
return (distance / (earthRadius * latitudeCorrection) * rad2deg) | [
"def",
"dist_to_deg",
"(",
"self",
",",
"distance",
",",
"latitude",
")",
":",
"# d * (180 / pi) / earthRadius ==> degrees longitude",
"# (degrees longitude) / cos(latitude) ==> degrees latitude",
"lat",
"=",
"latitude",
"if",
"latitude",
">=",
"0",
"else",
"-",
"1",... | distance = distance in meters
latitude = latitude in degrees
at the equator, the distance of one degree is equal in latitude and longitude.
at higher latitudes, a degree longitude is shorter in length, proportional to cos(latitude)
http://en.wikipedia.org/wiki/Decimal_degrees
This function is part of a distance filter where the database 'distance' is in degrees.
There's no good single-valued answer to this problem.
The distance/ degree is quite constant N/S around the earth (latitude),
but varies over a huge range E/W (longitude).
Split the difference: I'm going to average the the degrees latitude and degrees longitude
corresponding to the given distance. At high latitudes, this will be too short N/S
and too long E/W. It splits the errors between the two axes.
Errors are < 25 percent for latitudes < 60 degrees N/S. | [
"distance",
"=",
"distance",
"in",
"meters",
"latitude",
"=",
"latitude",
"in",
"degrees"
] | 7430d6b1ca480222c1b837748f4c60ea10c85f22 | https://github.com/djangonauts/django-rest-framework-gis/blob/7430d6b1ca480222c1b837748f4c60ea10c85f22/rest_framework_gis/filters.py#L139-L165 | train | 207,581 |
google/apitools | apitools/base/py/base_api.py | BaseApiClient._SetCredentials | def _SetCredentials(self, **kwds):
"""Fetch credentials, and set them for this client.
Note that we can't simply return credentials, since creating them
may involve side-effecting self.
Args:
**kwds: Additional keyword arguments are passed on to GetCredentials.
Returns:
None. Sets self._credentials.
"""
args = {
'api_key': self._API_KEY,
'client': self,
'client_id': self._CLIENT_ID,
'client_secret': self._CLIENT_SECRET,
'package_name': self._PACKAGE,
'scopes': self._SCOPES,
'user_agent': self._USER_AGENT,
}
args.update(kwds)
# credentials_lib can be expensive to import so do it only if needed.
from apitools.base.py import credentials_lib
# TODO(craigcitro): It's a bit dangerous to pass this
# still-half-initialized self into this method, but we might need
# to set attributes on it associated with our credentials.
# Consider another way around this (maybe a callback?) and whether
# or not it's worth it.
self._credentials = credentials_lib.GetCredentials(**args) | python | def _SetCredentials(self, **kwds):
"""Fetch credentials, and set them for this client.
Note that we can't simply return credentials, since creating them
may involve side-effecting self.
Args:
**kwds: Additional keyword arguments are passed on to GetCredentials.
Returns:
None. Sets self._credentials.
"""
args = {
'api_key': self._API_KEY,
'client': self,
'client_id': self._CLIENT_ID,
'client_secret': self._CLIENT_SECRET,
'package_name': self._PACKAGE,
'scopes': self._SCOPES,
'user_agent': self._USER_AGENT,
}
args.update(kwds)
# credentials_lib can be expensive to import so do it only if needed.
from apitools.base.py import credentials_lib
# TODO(craigcitro): It's a bit dangerous to pass this
# still-half-initialized self into this method, but we might need
# to set attributes on it associated with our credentials.
# Consider another way around this (maybe a callback?) and whether
# or not it's worth it.
self._credentials = credentials_lib.GetCredentials(**args) | [
"def",
"_SetCredentials",
"(",
"self",
",",
"*",
"*",
"kwds",
")",
":",
"args",
"=",
"{",
"'api_key'",
":",
"self",
".",
"_API_KEY",
",",
"'client'",
":",
"self",
",",
"'client_id'",
":",
"self",
".",
"_CLIENT_ID",
",",
"'client_secret'",
":",
"self",
... | Fetch credentials, and set them for this client.
Note that we can't simply return credentials, since creating them
may involve side-effecting self.
Args:
**kwds: Additional keyword arguments are passed on to GetCredentials.
Returns:
None. Sets self._credentials. | [
"Fetch",
"credentials",
"and",
"set",
"them",
"for",
"this",
"client",
"."
] | f3745a7ea535aa0e88b0650c16479b696d6fd446 | https://github.com/google/apitools/blob/f3745a7ea535aa0e88b0650c16479b696d6fd446/apitools/base/py/base_api.py#L280-L309 | train | 207,582 |
google/apitools | apitools/base/py/base_api.py | BaseApiClient.JsonResponseModel | def JsonResponseModel(self):
"""In this context, return raw JSON instead of proto."""
old_model = self.response_type_model
self.__response_type_model = 'json'
yield
self.__response_type_model = old_model | python | def JsonResponseModel(self):
"""In this context, return raw JSON instead of proto."""
old_model = self.response_type_model
self.__response_type_model = 'json'
yield
self.__response_type_model = old_model | [
"def",
"JsonResponseModel",
"(",
"self",
")",
":",
"old_model",
"=",
"self",
".",
"response_type_model",
"self",
".",
"__response_type_model",
"=",
"'json'",
"yield",
"self",
".",
"__response_type_model",
"=",
"old_model"
] | In this context, return raw JSON instead of proto. | [
"In",
"this",
"context",
"return",
"raw",
"JSON",
"instead",
"of",
"proto",
"."
] | f3745a7ea535aa0e88b0650c16479b696d6fd446 | https://github.com/google/apitools/blob/f3745a7ea535aa0e88b0650c16479b696d6fd446/apitools/base/py/base_api.py#L370-L375 | train | 207,583 |
google/apitools | apitools/base/py/base_api.py | BaseApiClient.ProcessRequest | def ProcessRequest(self, method_config, request):
"""Hook for pre-processing of requests."""
if self.log_request:
logging.info(
'Calling method %s with %s: %s', method_config.method_id,
method_config.request_type_name, request)
return request | python | def ProcessRequest(self, method_config, request):
"""Hook for pre-processing of requests."""
if self.log_request:
logging.info(
'Calling method %s with %s: %s', method_config.method_id,
method_config.request_type_name, request)
return request | [
"def",
"ProcessRequest",
"(",
"self",
",",
"method_config",
",",
"request",
")",
":",
"if",
"self",
".",
"log_request",
":",
"logging",
".",
"info",
"(",
"'Calling method %s with %s: %s'",
",",
"method_config",
".",
"method_id",
",",
"method_config",
".",
"reque... | Hook for pre-processing of requests. | [
"Hook",
"for",
"pre",
"-",
"processing",
"of",
"requests",
"."
] | f3745a7ea535aa0e88b0650c16479b696d6fd446 | https://github.com/google/apitools/blob/f3745a7ea535aa0e88b0650c16479b696d6fd446/apitools/base/py/base_api.py#L408-L414 | train | 207,584 |
google/apitools | apitools/base/py/base_api.py | BaseApiClient.ProcessHttpRequest | def ProcessHttpRequest(self, http_request):
"""Hook for pre-processing of http requests."""
http_request.headers.update(self.additional_http_headers)
if self.log_request:
logging.info('Making http %s to %s',
http_request.http_method, http_request.url)
logging.info('Headers: %s', pprint.pformat(http_request.headers))
if http_request.body:
# TODO(craigcitro): Make this safe to print in the case of
# non-printable body characters.
logging.info('Body:\n%s',
http_request.loggable_body or http_request.body)
else:
logging.info('Body: (none)')
return http_request | python | def ProcessHttpRequest(self, http_request):
"""Hook for pre-processing of http requests."""
http_request.headers.update(self.additional_http_headers)
if self.log_request:
logging.info('Making http %s to %s',
http_request.http_method, http_request.url)
logging.info('Headers: %s', pprint.pformat(http_request.headers))
if http_request.body:
# TODO(craigcitro): Make this safe to print in the case of
# non-printable body characters.
logging.info('Body:\n%s',
http_request.loggable_body or http_request.body)
else:
logging.info('Body: (none)')
return http_request | [
"def",
"ProcessHttpRequest",
"(",
"self",
",",
"http_request",
")",
":",
"http_request",
".",
"headers",
".",
"update",
"(",
"self",
".",
"additional_http_headers",
")",
"if",
"self",
".",
"log_request",
":",
"logging",
".",
"info",
"(",
"'Making http %s to %s'"... | Hook for pre-processing of http requests. | [
"Hook",
"for",
"pre",
"-",
"processing",
"of",
"http",
"requests",
"."
] | f3745a7ea535aa0e88b0650c16479b696d6fd446 | https://github.com/google/apitools/blob/f3745a7ea535aa0e88b0650c16479b696d6fd446/apitools/base/py/base_api.py#L416-L430 | train | 207,585 |
google/apitools | apitools/base/py/base_api.py | BaseApiClient.DeserializeMessage | def DeserializeMessage(self, response_type, data):
"""Deserialize the given data as method_config.response_type."""
try:
message = encoding.JsonToMessage(response_type, data)
except (exceptions.InvalidDataFromServerError,
messages.ValidationError, ValueError) as e:
raise exceptions.InvalidDataFromServerError(
'Error decoding response "%s" as type %s: %s' % (
data, response_type.__name__, e))
return message | python | def DeserializeMessage(self, response_type, data):
"""Deserialize the given data as method_config.response_type."""
try:
message = encoding.JsonToMessage(response_type, data)
except (exceptions.InvalidDataFromServerError,
messages.ValidationError, ValueError) as e:
raise exceptions.InvalidDataFromServerError(
'Error decoding response "%s" as type %s: %s' % (
data, response_type.__name__, e))
return message | [
"def",
"DeserializeMessage",
"(",
"self",
",",
"response_type",
",",
"data",
")",
":",
"try",
":",
"message",
"=",
"encoding",
".",
"JsonToMessage",
"(",
"response_type",
",",
"data",
")",
"except",
"(",
"exceptions",
".",
"InvalidDataFromServerError",
",",
"m... | Deserialize the given data as method_config.response_type. | [
"Deserialize",
"the",
"given",
"data",
"as",
"method_config",
".",
"response_type",
"."
] | f3745a7ea535aa0e88b0650c16479b696d6fd446 | https://github.com/google/apitools/blob/f3745a7ea535aa0e88b0650c16479b696d6fd446/apitools/base/py/base_api.py#L443-L452 | train | 207,586 |
google/apitools | apitools/base/py/base_api.py | BaseApiClient.FinalizeTransferUrl | def FinalizeTransferUrl(self, url):
"""Modify the url for a given transfer, based on auth and version."""
url_builder = _UrlBuilder.FromUrl(url)
if self.global_params.key:
url_builder.query_params['key'] = self.global_params.key
return url_builder.url | python | def FinalizeTransferUrl(self, url):
"""Modify the url for a given transfer, based on auth and version."""
url_builder = _UrlBuilder.FromUrl(url)
if self.global_params.key:
url_builder.query_params['key'] = self.global_params.key
return url_builder.url | [
"def",
"FinalizeTransferUrl",
"(",
"self",
",",
"url",
")",
":",
"url_builder",
"=",
"_UrlBuilder",
".",
"FromUrl",
"(",
"url",
")",
"if",
"self",
".",
"global_params",
".",
"key",
":",
"url_builder",
".",
"query_params",
"[",
"'key'",
"]",
"=",
"self",
... | Modify the url for a given transfer, based on auth and version. | [
"Modify",
"the",
"url",
"for",
"a",
"given",
"transfer",
"based",
"on",
"auth",
"and",
"version",
"."
] | f3745a7ea535aa0e88b0650c16479b696d6fd446 | https://github.com/google/apitools/blob/f3745a7ea535aa0e88b0650c16479b696d6fd446/apitools/base/py/base_api.py#L454-L459 | train | 207,587 |
google/apitools | apitools/base/py/base_api.py | BaseApiService.GetMethodConfig | def GetMethodConfig(self, method):
"""Returns service cached method config for given method."""
method_config = self._method_configs.get(method)
if method_config:
return method_config
func = getattr(self, method, None)
if func is None:
raise KeyError(method)
method_config = getattr(func, 'method_config', None)
if method_config is None:
raise KeyError(method)
self._method_configs[method] = config = method_config()
return config | python | def GetMethodConfig(self, method):
"""Returns service cached method config for given method."""
method_config = self._method_configs.get(method)
if method_config:
return method_config
func = getattr(self, method, None)
if func is None:
raise KeyError(method)
method_config = getattr(func, 'method_config', None)
if method_config is None:
raise KeyError(method)
self._method_configs[method] = config = method_config()
return config | [
"def",
"GetMethodConfig",
"(",
"self",
",",
"method",
")",
":",
"method_config",
"=",
"self",
".",
"_method_configs",
".",
"get",
"(",
"method",
")",
"if",
"method_config",
":",
"return",
"method_config",
"func",
"=",
"getattr",
"(",
"self",
",",
"method",
... | Returns service cached method config for given method. | [
"Returns",
"service",
"cached",
"method",
"config",
"for",
"given",
"method",
"."
] | f3745a7ea535aa0e88b0650c16479b696d6fd446 | https://github.com/google/apitools/blob/f3745a7ea535aa0e88b0650c16479b696d6fd446/apitools/base/py/base_api.py#L479-L491 | train | 207,588 |
google/apitools | apitools/base/py/base_api.py | BaseApiService.__CombineGlobalParams | def __CombineGlobalParams(self, global_params, default_params):
"""Combine the given params with the defaults."""
util.Typecheck(global_params, (type(None), self.__client.params_type))
result = self.__client.params_type()
global_params = global_params or self.__client.params_type()
for field in result.all_fields():
value = global_params.get_assigned_value(field.name)
if value is None:
value = default_params.get_assigned_value(field.name)
if value not in (None, [], ()):
setattr(result, field.name, value)
return result | python | def __CombineGlobalParams(self, global_params, default_params):
"""Combine the given params with the defaults."""
util.Typecheck(global_params, (type(None), self.__client.params_type))
result = self.__client.params_type()
global_params = global_params or self.__client.params_type()
for field in result.all_fields():
value = global_params.get_assigned_value(field.name)
if value is None:
value = default_params.get_assigned_value(field.name)
if value not in (None, [], ()):
setattr(result, field.name, value)
return result | [
"def",
"__CombineGlobalParams",
"(",
"self",
",",
"global_params",
",",
"default_params",
")",
":",
"util",
".",
"Typecheck",
"(",
"global_params",
",",
"(",
"type",
"(",
"None",
")",
",",
"self",
".",
"__client",
".",
"params_type",
")",
")",
"result",
"=... | Combine the given params with the defaults. | [
"Combine",
"the",
"given",
"params",
"with",
"the",
"defaults",
"."
] | f3745a7ea535aa0e88b0650c16479b696d6fd446 | https://github.com/google/apitools/blob/f3745a7ea535aa0e88b0650c16479b696d6fd446/apitools/base/py/base_api.py#L511-L522 | train | 207,589 |
google/apitools | apitools/base/py/base_api.py | BaseApiService.__FinalUrlValue | def __FinalUrlValue(self, value, field):
"""Encode value for the URL, using field to skip encoding for bytes."""
if isinstance(field, messages.BytesField) and value is not None:
return base64.urlsafe_b64encode(value)
elif isinstance(value, six.text_type):
return value.encode('utf8')
elif isinstance(value, six.binary_type):
return value.decode('utf8')
elif isinstance(value, datetime.datetime):
return value.isoformat()
return value | python | def __FinalUrlValue(self, value, field):
"""Encode value for the URL, using field to skip encoding for bytes."""
if isinstance(field, messages.BytesField) and value is not None:
return base64.urlsafe_b64encode(value)
elif isinstance(value, six.text_type):
return value.encode('utf8')
elif isinstance(value, six.binary_type):
return value.decode('utf8')
elif isinstance(value, datetime.datetime):
return value.isoformat()
return value | [
"def",
"__FinalUrlValue",
"(",
"self",
",",
"value",
",",
"field",
")",
":",
"if",
"isinstance",
"(",
"field",
",",
"messages",
".",
"BytesField",
")",
"and",
"value",
"is",
"not",
"None",
":",
"return",
"base64",
".",
"urlsafe_b64encode",
"(",
"value",
... | Encode value for the URL, using field to skip encoding for bytes. | [
"Encode",
"value",
"for",
"the",
"URL",
"using",
"field",
"to",
"skip",
"encoding",
"for",
"bytes",
"."
] | f3745a7ea535aa0e88b0650c16479b696d6fd446 | https://github.com/google/apitools/blob/f3745a7ea535aa0e88b0650c16479b696d6fd446/apitools/base/py/base_api.py#L535-L545 | train | 207,590 |
google/apitools | apitools/base/py/base_api.py | BaseApiService.__ConstructQueryParams | def __ConstructQueryParams(self, query_params, request, global_params):
"""Construct a dictionary of query parameters for this request."""
# First, handle the global params.
global_params = self.__CombineGlobalParams(
global_params, self.__client.global_params)
global_param_names = util.MapParamNames(
[x.name for x in self.__client.params_type.all_fields()],
self.__client.params_type)
global_params_type = type(global_params)
query_info = dict(
(param,
self.__FinalUrlValue(getattr(global_params, param),
getattr(global_params_type, param)))
for param in global_param_names)
# Next, add the query params.
query_param_names = util.MapParamNames(query_params, type(request))
request_type = type(request)
query_info.update(
(param,
self.__FinalUrlValue(getattr(request, param, None),
getattr(request_type, param)))
for param in query_param_names)
query_info = dict((k, v) for k, v in query_info.items()
if v is not None)
query_info = self.__EncodePrettyPrint(query_info)
query_info = util.MapRequestParams(query_info, type(request))
return query_info | python | def __ConstructQueryParams(self, query_params, request, global_params):
"""Construct a dictionary of query parameters for this request."""
# First, handle the global params.
global_params = self.__CombineGlobalParams(
global_params, self.__client.global_params)
global_param_names = util.MapParamNames(
[x.name for x in self.__client.params_type.all_fields()],
self.__client.params_type)
global_params_type = type(global_params)
query_info = dict(
(param,
self.__FinalUrlValue(getattr(global_params, param),
getattr(global_params_type, param)))
for param in global_param_names)
# Next, add the query params.
query_param_names = util.MapParamNames(query_params, type(request))
request_type = type(request)
query_info.update(
(param,
self.__FinalUrlValue(getattr(request, param, None),
getattr(request_type, param)))
for param in query_param_names)
query_info = dict((k, v) for k, v in query_info.items()
if v is not None)
query_info = self.__EncodePrettyPrint(query_info)
query_info = util.MapRequestParams(query_info, type(request))
return query_info | [
"def",
"__ConstructQueryParams",
"(",
"self",
",",
"query_params",
",",
"request",
",",
"global_params",
")",
":",
"# First, handle the global params.",
"global_params",
"=",
"self",
".",
"__CombineGlobalParams",
"(",
"global_params",
",",
"self",
".",
"__client",
"."... | Construct a dictionary of query parameters for this request. | [
"Construct",
"a",
"dictionary",
"of",
"query",
"parameters",
"for",
"this",
"request",
"."
] | f3745a7ea535aa0e88b0650c16479b696d6fd446 | https://github.com/google/apitools/blob/f3745a7ea535aa0e88b0650c16479b696d6fd446/apitools/base/py/base_api.py#L547-L573 | train | 207,591 |
google/apitools | apitools/base/py/base_api.py | BaseApiService.__FinalizeRequest | def __FinalizeRequest(self, http_request, url_builder):
"""Make any final general adjustments to the request."""
if (http_request.http_method == 'GET' and
len(http_request.url) > _MAX_URL_LENGTH):
http_request.http_method = 'POST'
http_request.headers['x-http-method-override'] = 'GET'
http_request.headers[
'content-type'] = 'application/x-www-form-urlencoded'
http_request.body = url_builder.query
url_builder.query_params = {}
http_request.url = url_builder.url | python | def __FinalizeRequest(self, http_request, url_builder):
"""Make any final general adjustments to the request."""
if (http_request.http_method == 'GET' and
len(http_request.url) > _MAX_URL_LENGTH):
http_request.http_method = 'POST'
http_request.headers['x-http-method-override'] = 'GET'
http_request.headers[
'content-type'] = 'application/x-www-form-urlencoded'
http_request.body = url_builder.query
url_builder.query_params = {}
http_request.url = url_builder.url | [
"def",
"__FinalizeRequest",
"(",
"self",
",",
"http_request",
",",
"url_builder",
")",
":",
"if",
"(",
"http_request",
".",
"http_method",
"==",
"'GET'",
"and",
"len",
"(",
"http_request",
".",
"url",
")",
">",
"_MAX_URL_LENGTH",
")",
":",
"http_request",
".... | Make any final general adjustments to the request. | [
"Make",
"any",
"final",
"general",
"adjustments",
"to",
"the",
"request",
"."
] | f3745a7ea535aa0e88b0650c16479b696d6fd446 | https://github.com/google/apitools/blob/f3745a7ea535aa0e88b0650c16479b696d6fd446/apitools/base/py/base_api.py#L586-L596 | train | 207,592 |
google/apitools | apitools/base/py/base_api.py | BaseApiService.__ProcessHttpResponse | def __ProcessHttpResponse(self, method_config, http_response, request):
"""Process the given http response."""
if http_response.status_code not in (http_client.OK,
http_client.CREATED,
http_client.NO_CONTENT):
raise exceptions.HttpError.FromResponse(
http_response, method_config=method_config, request=request)
if http_response.status_code == http_client.NO_CONTENT:
# TODO(craigcitro): Find out why _replace doesn't seem to work
# here.
http_response = http_wrapper.Response(
info=http_response.info, content='{}',
request_url=http_response.request_url)
content = http_response.content
if self._client.response_encoding and isinstance(content, bytes):
content = content.decode(self._client.response_encoding)
if self.__client.response_type_model == 'json':
return content
response_type = _LoadClass(method_config.response_type_name,
self.__client.MESSAGES_MODULE)
return self.__client.DeserializeMessage(response_type, content) | python | def __ProcessHttpResponse(self, method_config, http_response, request):
"""Process the given http response."""
if http_response.status_code not in (http_client.OK,
http_client.CREATED,
http_client.NO_CONTENT):
raise exceptions.HttpError.FromResponse(
http_response, method_config=method_config, request=request)
if http_response.status_code == http_client.NO_CONTENT:
# TODO(craigcitro): Find out why _replace doesn't seem to work
# here.
http_response = http_wrapper.Response(
info=http_response.info, content='{}',
request_url=http_response.request_url)
content = http_response.content
if self._client.response_encoding and isinstance(content, bytes):
content = content.decode(self._client.response_encoding)
if self.__client.response_type_model == 'json':
return content
response_type = _LoadClass(method_config.response_type_name,
self.__client.MESSAGES_MODULE)
return self.__client.DeserializeMessage(response_type, content) | [
"def",
"__ProcessHttpResponse",
"(",
"self",
",",
"method_config",
",",
"http_response",
",",
"request",
")",
":",
"if",
"http_response",
".",
"status_code",
"not",
"in",
"(",
"http_client",
".",
"OK",
",",
"http_client",
".",
"CREATED",
",",
"http_client",
".... | Process the given http response. | [
"Process",
"the",
"given",
"http",
"response",
"."
] | f3745a7ea535aa0e88b0650c16479b696d6fd446 | https://github.com/google/apitools/blob/f3745a7ea535aa0e88b0650c16479b696d6fd446/apitools/base/py/base_api.py#L598-L620 | train | 207,593 |
google/apitools | apitools/base/py/base_api.py | BaseApiService.__SetBaseHeaders | def __SetBaseHeaders(self, http_request, client):
"""Fill in the basic headers on http_request."""
# TODO(craigcitro): Make the default a little better here, and
# include the apitools version.
user_agent = client.user_agent or 'apitools-client/1.0'
http_request.headers['user-agent'] = user_agent
http_request.headers['accept'] = 'application/json'
http_request.headers['accept-encoding'] = 'gzip, deflate' | python | def __SetBaseHeaders(self, http_request, client):
"""Fill in the basic headers on http_request."""
# TODO(craigcitro): Make the default a little better here, and
# include the apitools version.
user_agent = client.user_agent or 'apitools-client/1.0'
http_request.headers['user-agent'] = user_agent
http_request.headers['accept'] = 'application/json'
http_request.headers['accept-encoding'] = 'gzip, deflate' | [
"def",
"__SetBaseHeaders",
"(",
"self",
",",
"http_request",
",",
"client",
")",
":",
"# TODO(craigcitro): Make the default a little better here, and",
"# include the apitools version.",
"user_agent",
"=",
"client",
".",
"user_agent",
"or",
"'apitools-client/1.0'",
"http_reques... | Fill in the basic headers on http_request. | [
"Fill",
"in",
"the",
"basic",
"headers",
"on",
"http_request",
"."
] | f3745a7ea535aa0e88b0650c16479b696d6fd446 | https://github.com/google/apitools/blob/f3745a7ea535aa0e88b0650c16479b696d6fd446/apitools/base/py/base_api.py#L622-L629 | train | 207,594 |
google/apitools | apitools/base/py/base_api.py | BaseApiService.__SetBody | def __SetBody(self, http_request, method_config, request, upload):
"""Fill in the body on http_request."""
if not method_config.request_field:
return
request_type = _LoadClass(
method_config.request_type_name, self.__client.MESSAGES_MODULE)
if method_config.request_field == REQUEST_IS_BODY:
body_value = request
body_type = request_type
else:
body_value = getattr(request, method_config.request_field)
body_field = request_type.field_by_name(
method_config.request_field)
util.Typecheck(body_field, messages.MessageField)
body_type = body_field.type
# If there was no body provided, we use an empty message of the
# appropriate type.
body_value = body_value or body_type()
if upload and not body_value:
# We're going to fill in the body later.
return
util.Typecheck(body_value, body_type)
http_request.headers['content-type'] = 'application/json'
http_request.body = self.__client.SerializeMessage(body_value) | python | def __SetBody(self, http_request, method_config, request, upload):
"""Fill in the body on http_request."""
if not method_config.request_field:
return
request_type = _LoadClass(
method_config.request_type_name, self.__client.MESSAGES_MODULE)
if method_config.request_field == REQUEST_IS_BODY:
body_value = request
body_type = request_type
else:
body_value = getattr(request, method_config.request_field)
body_field = request_type.field_by_name(
method_config.request_field)
util.Typecheck(body_field, messages.MessageField)
body_type = body_field.type
# If there was no body provided, we use an empty message of the
# appropriate type.
body_value = body_value or body_type()
if upload and not body_value:
# We're going to fill in the body later.
return
util.Typecheck(body_value, body_type)
http_request.headers['content-type'] = 'application/json'
http_request.body = self.__client.SerializeMessage(body_value) | [
"def",
"__SetBody",
"(",
"self",
",",
"http_request",
",",
"method_config",
",",
"request",
",",
"upload",
")",
":",
"if",
"not",
"method_config",
".",
"request_field",
":",
"return",
"request_type",
"=",
"_LoadClass",
"(",
"method_config",
".",
"request_type_na... | Fill in the body on http_request. | [
"Fill",
"in",
"the",
"body",
"on",
"http_request",
"."
] | f3745a7ea535aa0e88b0650c16479b696d6fd446 | https://github.com/google/apitools/blob/f3745a7ea535aa0e88b0650c16479b696d6fd446/apitools/base/py/base_api.py#L631-L656 | train | 207,595 |
google/apitools | apitools/base/py/base_api.py | BaseApiService.PrepareHttpRequest | def PrepareHttpRequest(self, method_config, request, global_params=None,
upload=None, upload_config=None, download=None):
"""Prepares an HTTP request to be sent."""
request_type = _LoadClass(
method_config.request_type_name, self.__client.MESSAGES_MODULE)
util.Typecheck(request, request_type)
request = self.__client.ProcessRequest(method_config, request)
http_request = http_wrapper.Request(
http_method=method_config.http_method)
self.__SetBaseHeaders(http_request, self.__client)
self.__SetBody(http_request, method_config, request, upload)
url_builder = _UrlBuilder(
self.__client.url, relative_path=method_config.relative_path)
url_builder.query_params = self.__ConstructQueryParams(
method_config.query_params, request, global_params)
# It's important that upload and download go before we fill in the
# relative path, so that they can replace it.
if upload is not None:
upload.ConfigureRequest(upload_config, http_request, url_builder)
if download is not None:
download.ConfigureRequest(http_request, url_builder)
url_builder.relative_path = self.__ConstructRelativePath(
method_config, request, relative_path=url_builder.relative_path)
self.__FinalizeRequest(http_request, url_builder)
return self.__client.ProcessHttpRequest(http_request) | python | def PrepareHttpRequest(self, method_config, request, global_params=None,
upload=None, upload_config=None, download=None):
"""Prepares an HTTP request to be sent."""
request_type = _LoadClass(
method_config.request_type_name, self.__client.MESSAGES_MODULE)
util.Typecheck(request, request_type)
request = self.__client.ProcessRequest(method_config, request)
http_request = http_wrapper.Request(
http_method=method_config.http_method)
self.__SetBaseHeaders(http_request, self.__client)
self.__SetBody(http_request, method_config, request, upload)
url_builder = _UrlBuilder(
self.__client.url, relative_path=method_config.relative_path)
url_builder.query_params = self.__ConstructQueryParams(
method_config.query_params, request, global_params)
# It's important that upload and download go before we fill in the
# relative path, so that they can replace it.
if upload is not None:
upload.ConfigureRequest(upload_config, http_request, url_builder)
if download is not None:
download.ConfigureRequest(http_request, url_builder)
url_builder.relative_path = self.__ConstructRelativePath(
method_config, request, relative_path=url_builder.relative_path)
self.__FinalizeRequest(http_request, url_builder)
return self.__client.ProcessHttpRequest(http_request) | [
"def",
"PrepareHttpRequest",
"(",
"self",
",",
"method_config",
",",
"request",
",",
"global_params",
"=",
"None",
",",
"upload",
"=",
"None",
",",
"upload_config",
"=",
"None",
",",
"download",
"=",
"None",
")",
":",
"request_type",
"=",
"_LoadClass",
"(",
... | Prepares an HTTP request to be sent. | [
"Prepares",
"an",
"HTTP",
"request",
"to",
"be",
"sent",
"."
] | f3745a7ea535aa0e88b0650c16479b696d6fd446 | https://github.com/google/apitools/blob/f3745a7ea535aa0e88b0650c16479b696d6fd446/apitools/base/py/base_api.py#L658-L687 | train | 207,596 |
google/apitools | apitools/base/py/base_api.py | BaseApiService._RunMethod | def _RunMethod(self, method_config, request, global_params=None,
upload=None, upload_config=None, download=None):
"""Call this method with request."""
if upload is not None and download is not None:
# TODO(craigcitro): This just involves refactoring the logic
# below into callbacks that we can pass around; in particular,
# the order should be that the upload gets the initial request,
# and then passes its reply to a download if one exists, and
# then that goes to ProcessResponse and is returned.
raise exceptions.NotYetImplementedError(
'Cannot yet use both upload and download at once')
http_request = self.PrepareHttpRequest(
method_config, request, global_params, upload, upload_config,
download)
# TODO(craigcitro): Make num_retries customizable on Transfer
# objects, and pass in self.__client.num_retries when initializing
# an upload or download.
if download is not None:
download.InitializeDownload(http_request, client=self.client)
return
http_response = None
if upload is not None:
http_response = upload.InitializeUpload(
http_request, client=self.client)
if http_response is None:
http = self.__client.http
if upload and upload.bytes_http:
http = upload.bytes_http
opts = {
'retries': self.__client.num_retries,
'max_retry_wait': self.__client.max_retry_wait,
}
if self.__client.check_response_func:
opts['check_response_func'] = self.__client.check_response_func
if self.__client.retry_func:
opts['retry_func'] = self.__client.retry_func
http_response = http_wrapper.MakeRequest(
http, http_request, **opts)
return self.ProcessHttpResponse(method_config, http_response, request) | python | def _RunMethod(self, method_config, request, global_params=None,
upload=None, upload_config=None, download=None):
"""Call this method with request."""
if upload is not None and download is not None:
# TODO(craigcitro): This just involves refactoring the logic
# below into callbacks that we can pass around; in particular,
# the order should be that the upload gets the initial request,
# and then passes its reply to a download if one exists, and
# then that goes to ProcessResponse and is returned.
raise exceptions.NotYetImplementedError(
'Cannot yet use both upload and download at once')
http_request = self.PrepareHttpRequest(
method_config, request, global_params, upload, upload_config,
download)
# TODO(craigcitro): Make num_retries customizable on Transfer
# objects, and pass in self.__client.num_retries when initializing
# an upload or download.
if download is not None:
download.InitializeDownload(http_request, client=self.client)
return
http_response = None
if upload is not None:
http_response = upload.InitializeUpload(
http_request, client=self.client)
if http_response is None:
http = self.__client.http
if upload and upload.bytes_http:
http = upload.bytes_http
opts = {
'retries': self.__client.num_retries,
'max_retry_wait': self.__client.max_retry_wait,
}
if self.__client.check_response_func:
opts['check_response_func'] = self.__client.check_response_func
if self.__client.retry_func:
opts['retry_func'] = self.__client.retry_func
http_response = http_wrapper.MakeRequest(
http, http_request, **opts)
return self.ProcessHttpResponse(method_config, http_response, request) | [
"def",
"_RunMethod",
"(",
"self",
",",
"method_config",
",",
"request",
",",
"global_params",
"=",
"None",
",",
"upload",
"=",
"None",
",",
"upload_config",
"=",
"None",
",",
"download",
"=",
"None",
")",
":",
"if",
"upload",
"is",
"not",
"None",
"and",
... | Call this method with request. | [
"Call",
"this",
"method",
"with",
"request",
"."
] | f3745a7ea535aa0e88b0650c16479b696d6fd446 | https://github.com/google/apitools/blob/f3745a7ea535aa0e88b0650c16479b696d6fd446/apitools/base/py/base_api.py#L689-L731 | train | 207,597 |
google/apitools | apitools/base/py/base_api.py | BaseApiService.ProcessHttpResponse | def ProcessHttpResponse(self, method_config, http_response, request=None):
"""Convert an HTTP response to the expected message type."""
return self.__client.ProcessResponse(
method_config,
self.__ProcessHttpResponse(method_config, http_response, request)) | python | def ProcessHttpResponse(self, method_config, http_response, request=None):
"""Convert an HTTP response to the expected message type."""
return self.__client.ProcessResponse(
method_config,
self.__ProcessHttpResponse(method_config, http_response, request)) | [
"def",
"ProcessHttpResponse",
"(",
"self",
",",
"method_config",
",",
"http_response",
",",
"request",
"=",
"None",
")",
":",
"return",
"self",
".",
"__client",
".",
"ProcessResponse",
"(",
"method_config",
",",
"self",
".",
"__ProcessHttpResponse",
"(",
"method... | Convert an HTTP response to the expected message type. | [
"Convert",
"an",
"HTTP",
"response",
"to",
"the",
"expected",
"message",
"type",
"."
] | f3745a7ea535aa0e88b0650c16479b696d6fd446 | https://github.com/google/apitools/blob/f3745a7ea535aa0e88b0650c16479b696d6fd446/apitools/base/py/base_api.py#L733-L737 | train | 207,598 |
google/apitools | apitools/base/protorpclite/descriptor.py | describe_enum_value | def describe_enum_value(enum_value):
"""Build descriptor for Enum instance.
Args:
enum_value: Enum value to provide descriptor for.
Returns:
Initialized EnumValueDescriptor instance describing the Enum instance.
"""
enum_value_descriptor = EnumValueDescriptor()
enum_value_descriptor.name = six.text_type(enum_value.name)
enum_value_descriptor.number = enum_value.number
return enum_value_descriptor | python | def describe_enum_value(enum_value):
"""Build descriptor for Enum instance.
Args:
enum_value: Enum value to provide descriptor for.
Returns:
Initialized EnumValueDescriptor instance describing the Enum instance.
"""
enum_value_descriptor = EnumValueDescriptor()
enum_value_descriptor.name = six.text_type(enum_value.name)
enum_value_descriptor.number = enum_value.number
return enum_value_descriptor | [
"def",
"describe_enum_value",
"(",
"enum_value",
")",
":",
"enum_value_descriptor",
"=",
"EnumValueDescriptor",
"(",
")",
"enum_value_descriptor",
".",
"name",
"=",
"six",
".",
"text_type",
"(",
"enum_value",
".",
"name",
")",
"enum_value_descriptor",
".",
"number",... | Build descriptor for Enum instance.
Args:
enum_value: Enum value to provide descriptor for.
Returns:
Initialized EnumValueDescriptor instance describing the Enum instance. | [
"Build",
"descriptor",
"for",
"Enum",
"instance",
"."
] | f3745a7ea535aa0e88b0650c16479b696d6fd446 | https://github.com/google/apitools/blob/f3745a7ea535aa0e88b0650c16479b696d6fd446/apitools/base/protorpclite/descriptor.py#L267-L279 | train | 207,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.