partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
train
IoU
Calculates Intersection over Union Args: cm (ConfusionMatrix): instance of confusion matrix metric ignore_index (int, optional): index to ignore, e.g. background index Returns: MetricsLambda Examples: .. code-block:: python train_evaluator = ... cm = Confusi...
ignite/metrics/confusion_matrix.py
def IoU(cm, ignore_index=None): """Calculates Intersection over Union Args: cm (ConfusionMatrix): instance of confusion matrix metric ignore_index (int, optional): index to ignore, e.g. background index Returns: MetricsLambda Examples: .. code-block:: python trai...
def IoU(cm, ignore_index=None): """Calculates Intersection over Union Args: cm (ConfusionMatrix): instance of confusion matrix metric ignore_index (int, optional): index to ignore, e.g. background index Returns: MetricsLambda Examples: .. code-block:: python trai...
[ "Calculates", "Intersection", "over", "Union" ]
pytorch/ignite
python
https://github.com/pytorch/ignite/blob/a96bd07cb58822cfb39fd81765135712f1db41ca/ignite/metrics/confusion_matrix.py#L105-L150
[ "def", "IoU", "(", "cm", ",", "ignore_index", "=", "None", ")", ":", "if", "not", "isinstance", "(", "cm", ",", "ConfusionMatrix", ")", ":", "raise", "TypeError", "(", "\"Argument cm should be instance of ConfusionMatrix, but given {}\"", ".", "format", "(", "type...
a96bd07cb58822cfb39fd81765135712f1db41ca
train
cmAccuracy
Calculates accuracy using :class:`~ignite.metrics.ConfusionMatrix` metric. Args: cm (ConfusionMatrix): instance of confusion matrix metric Returns: MetricsLambda
ignite/metrics/confusion_matrix.py
def cmAccuracy(cm): """ Calculates accuracy using :class:`~ignite.metrics.ConfusionMatrix` metric. Args: cm (ConfusionMatrix): instance of confusion matrix metric Returns: MetricsLambda """ # Increase floating point precision cm = cm.type(torch.float64) return cm.diag()....
def cmAccuracy(cm): """ Calculates accuracy using :class:`~ignite.metrics.ConfusionMatrix` metric. Args: cm (ConfusionMatrix): instance of confusion matrix metric Returns: MetricsLambda """ # Increase floating point precision cm = cm.type(torch.float64) return cm.diag()....
[ "Calculates", "accuracy", "using", ":", "class", ":", "~ignite", ".", "metrics", ".", "ConfusionMatrix", "metric", ".", "Args", ":", "cm", "(", "ConfusionMatrix", ")", ":", "instance", "of", "confusion", "matrix", "metric" ]
pytorch/ignite
python
https://github.com/pytorch/ignite/blob/a96bd07cb58822cfb39fd81765135712f1db41ca/ignite/metrics/confusion_matrix.py#L180-L191
[ "def", "cmAccuracy", "(", "cm", ")", ":", "# Increase floating point precision", "cm", "=", "cm", ".", "type", "(", "torch", ".", "float64", ")", "return", "cm", ".", "diag", "(", ")", ".", "sum", "(", ")", "/", "(", "cm", ".", "sum", "(", ")", "+"...
a96bd07cb58822cfb39fd81765135712f1db41ca
train
cmPrecision
Calculates precision using :class:`~ignite.metrics.ConfusionMatrix` metric. Args: cm (ConfusionMatrix): instance of confusion matrix metric average (bool, optional): if True metric value is averaged over all classes Returns: MetricsLambda
ignite/metrics/confusion_matrix.py
def cmPrecision(cm, average=True): """ Calculates precision using :class:`~ignite.metrics.ConfusionMatrix` metric. Args: cm (ConfusionMatrix): instance of confusion matrix metric average (bool, optional): if True metric value is averaged over all classes Returns: MetricsLambda ...
def cmPrecision(cm, average=True): """ Calculates precision using :class:`~ignite.metrics.ConfusionMatrix` metric. Args: cm (ConfusionMatrix): instance of confusion matrix metric average (bool, optional): if True metric value is averaged over all classes Returns: MetricsLambda ...
[ "Calculates", "precision", "using", ":", "class", ":", "~ignite", ".", "metrics", ".", "ConfusionMatrix", "metric", ".", "Args", ":", "cm", "(", "ConfusionMatrix", ")", ":", "instance", "of", "confusion", "matrix", "metric", "average", "(", "bool", "optional",...
pytorch/ignite
python
https://github.com/pytorch/ignite/blob/a96bd07cb58822cfb39fd81765135712f1db41ca/ignite/metrics/confusion_matrix.py#L194-L209
[ "def", "cmPrecision", "(", "cm", ",", "average", "=", "True", ")", ":", "# Increase floating point precision", "cm", "=", "cm", ".", "type", "(", "torch", ".", "float64", ")", "precision", "=", "cm", ".", "diag", "(", ")", "/", "(", "cm", ".", "sum", ...
a96bd07cb58822cfb39fd81765135712f1db41ca
train
cmRecall
Calculates recall using :class:`~ignite.metrics.ConfusionMatrix` metric. Args: cm (ConfusionMatrix): instance of confusion matrix metric average (bool, optional): if True metric value is averaged over all classes Returns: MetricsLambda
ignite/metrics/confusion_matrix.py
def cmRecall(cm, average=True): """ Calculates recall using :class:`~ignite.metrics.ConfusionMatrix` metric. Args: cm (ConfusionMatrix): instance of confusion matrix metric average (bool, optional): if True metric value is averaged over all classes Returns: MetricsLambda """ ...
def cmRecall(cm, average=True): """ Calculates recall using :class:`~ignite.metrics.ConfusionMatrix` metric. Args: cm (ConfusionMatrix): instance of confusion matrix metric average (bool, optional): if True metric value is averaged over all classes Returns: MetricsLambda """ ...
[ "Calculates", "recall", "using", ":", "class", ":", "~ignite", ".", "metrics", ".", "ConfusionMatrix", "metric", ".", "Args", ":", "cm", "(", "ConfusionMatrix", ")", ":", "instance", "of", "confusion", "matrix", "metric", "average", "(", "bool", "optional", ...
pytorch/ignite
python
https://github.com/pytorch/ignite/blob/a96bd07cb58822cfb39fd81765135712f1db41ca/ignite/metrics/confusion_matrix.py#L212-L227
[ "def", "cmRecall", "(", "cm", ",", "average", "=", "True", ")", ":", "# Increase floating point precision", "cm", "=", "cm", ".", "type", "(", "torch", ".", "float64", ")", "recall", "=", "cm", ".", "diag", "(", ")", "/", "(", "cm", ".", "sum", "(", ...
a96bd07cb58822cfb39fd81765135712f1db41ca
train
convert_tensor
Move tensors to relevant device.
ignite/utils.py
def convert_tensor(input_, device=None, non_blocking=False): """Move tensors to relevant device.""" def _func(tensor): return tensor.to(device=device, non_blocking=non_blocking) if device else tensor return apply_to_tensor(input_, _func)
def convert_tensor(input_, device=None, non_blocking=False): """Move tensors to relevant device.""" def _func(tensor): return tensor.to(device=device, non_blocking=non_blocking) if device else tensor return apply_to_tensor(input_, _func)
[ "Move", "tensors", "to", "relevant", "device", "." ]
pytorch/ignite
python
https://github.com/pytorch/ignite/blob/a96bd07cb58822cfb39fd81765135712f1db41ca/ignite/utils.py#L14-L19
[ "def", "convert_tensor", "(", "input_", ",", "device", "=", "None", ",", "non_blocking", "=", "False", ")", ":", "def", "_func", "(", "tensor", ")", ":", "return", "tensor", ".", "to", "(", "device", "=", "device", ",", "non_blocking", "=", "non_blocking...
a96bd07cb58822cfb39fd81765135712f1db41ca
train
apply_to_type
Apply a function on a object of `input_type` or mapping, or sequence of objects of `input_type`.
ignite/utils.py
def apply_to_type(input_, input_type, func): """Apply a function on a object of `input_type` or mapping, or sequence of objects of `input_type`. """ if isinstance(input_, input_type): return func(input_) elif isinstance(input_, string_classes): return input_ elif isinstance(input_, c...
def apply_to_type(input_, input_type, func): """Apply a function on a object of `input_type` or mapping, or sequence of objects of `input_type`. """ if isinstance(input_, input_type): return func(input_) elif isinstance(input_, string_classes): return input_ elif isinstance(input_, c...
[ "Apply", "a", "function", "on", "a", "object", "of", "input_type", "or", "mapping", "or", "sequence", "of", "objects", "of", "input_type", "." ]
pytorch/ignite
python
https://github.com/pytorch/ignite/blob/a96bd07cb58822cfb39fd81765135712f1db41ca/ignite/utils.py#L28-L41
[ "def", "apply_to_type", "(", "input_", ",", "input_type", ",", "func", ")", ":", "if", "isinstance", "(", "input_", ",", "input_type", ")", ":", "return", "func", "(", "input_", ")", "elif", "isinstance", "(", "input_", ",", "string_classes", ")", ":", "...
a96bd07cb58822cfb39fd81765135712f1db41ca
train
to_onehot
Convert a tensor of indices of any shape `(N, ...)` to a tensor of one-hot indicators of shape `(N, num_classes, ...)`.
ignite/utils.py
def to_onehot(indices, num_classes): """Convert a tensor of indices of any shape `(N, ...)` to a tensor of one-hot indicators of shape `(N, num_classes, ...)`. """ onehot = torch.zeros(indices.shape[0], num_classes, *indices.shape[1:], device=indices.device) return onehot.scatter_(1, indices.unsquee...
def to_onehot(indices, num_classes): """Convert a tensor of indices of any shape `(N, ...)` to a tensor of one-hot indicators of shape `(N, num_classes, ...)`. """ onehot = torch.zeros(indices.shape[0], num_classes, *indices.shape[1:], device=indices.device) return onehot.scatter_(1, indices.unsquee...
[ "Convert", "a", "tensor", "of", "indices", "of", "any", "shape", "(", "N", "...", ")", "to", "a", "tensor", "of", "one", "-", "hot", "indicators", "of", "shape", "(", "N", "num_classes", "...", ")", "." ]
pytorch/ignite
python
https://github.com/pytorch/ignite/blob/a96bd07cb58822cfb39fd81765135712f1db41ca/ignite/utils.py#L44-L49
[ "def", "to_onehot", "(", "indices", ",", "num_classes", ")", ":", "onehot", "=", "torch", ".", "zeros", "(", "indices", ".", "shape", "[", "0", "]", ",", "num_classes", ",", "*", "indices", ".", "shape", "[", "1", ":", "]", ",", "device", "=", "ind...
a96bd07cb58822cfb39fd81765135712f1db41ca
train
ProgressBar.attach
Attaches the progress bar to an engine object. Args: engine (Engine): engine object. metric_names (list, optional): list of the metrics names to log as the bar progresses output_transform (callable, optional): a function to select what you want to print from the engine's ...
ignite/contrib/handlers/tqdm_logger.py
def attach(self, engine, metric_names=None, output_transform=None, event_name=Events.ITERATION_COMPLETED, closing_event_name=Events.EPOCH_COMPLETED): """ Attaches the progress bar to an engine object. Args: engine (Engine): engine object. me...
def attach(self, engine, metric_names=None, output_transform=None, event_name=Events.ITERATION_COMPLETED, closing_event_name=Events.EPOCH_COMPLETED): """ Attaches the progress bar to an engine object. Args: engine (Engine): engine object. me...
[ "Attaches", "the", "progress", "bar", "to", "an", "engine", "object", "." ]
pytorch/ignite
python
https://github.com/pytorch/ignite/blob/a96bd07cb58822cfb39fd81765135712f1db41ca/ignite/contrib/handlers/tqdm_logger.py#L137-L167
[ "def", "attach", "(", "self", ",", "engine", ",", "metric_names", "=", "None", ",", "output_transform", "=", "None", ",", "event_name", "=", "Events", ".", "ITERATION_COMPLETED", ",", "closing_event_name", "=", "Events", ".", "EPOCH_COMPLETED", ")", ":", "desc...
a96bd07cb58822cfb39fd81765135712f1db41ca
train
create_supervised_tbptt_trainer
Create a trainer for truncated backprop through time supervised models. Training recurrent model on long sequences is computationally intensive as it requires to process the whole sequence before getting a gradient. However, when the training loss is computed over many outputs (`X to many <https://karp...
ignite/contrib/engines/tbptt.py
def create_supervised_tbptt_trainer( model, optimizer, loss_fn, tbtt_step, dim=0, device=None, non_blocking=False, prepare_batch=_prepare_batch ): """Create a trainer for truncated backprop through time supervised models. Training recurrent model on long sequences is computation...
def create_supervised_tbptt_trainer( model, optimizer, loss_fn, tbtt_step, dim=0, device=None, non_blocking=False, prepare_batch=_prepare_batch ): """Create a trainer for truncated backprop through time supervised models. Training recurrent model on long sequences is computation...
[ "Create", "a", "trainer", "for", "truncated", "backprop", "through", "time", "supervised", "models", "." ]
pytorch/ignite
python
https://github.com/pytorch/ignite/blob/a96bd07cb58822cfb39fd81765135712f1db41ca/ignite/contrib/engines/tbptt.py#L31-L109
[ "def", "create_supervised_tbptt_trainer", "(", "model", ",", "optimizer", ",", "loss_fn", ",", "tbtt_step", ",", "dim", "=", "0", ",", "device", "=", "None", ",", "non_blocking", "=", "False", ",", "prepare_batch", "=", "_prepare_batch", ")", ":", "if", "dev...
a96bd07cb58822cfb39fd81765135712f1db41ca
train
_prepare_batch
Prepare batch for training: pass to a device with options.
ignite/engine/__init__.py
def _prepare_batch(batch, device=None, non_blocking=False): """Prepare batch for training: pass to a device with options. """ x, y = batch return (convert_tensor(x, device=device, non_blocking=non_blocking), convert_tensor(y, device=device, non_blocking=non_blocking))
def _prepare_batch(batch, device=None, non_blocking=False): """Prepare batch for training: pass to a device with options. """ x, y = batch return (convert_tensor(x, device=device, non_blocking=non_blocking), convert_tensor(y, device=device, non_blocking=non_blocking))
[ "Prepare", "batch", "for", "training", ":", "pass", "to", "a", "device", "with", "options", "." ]
pytorch/ignite
python
https://github.com/pytorch/ignite/blob/a96bd07cb58822cfb39fd81765135712f1db41ca/ignite/engine/__init__.py#L7-L13
[ "def", "_prepare_batch", "(", "batch", ",", "device", "=", "None", ",", "non_blocking", "=", "False", ")", ":", "x", ",", "y", "=", "batch", "return", "(", "convert_tensor", "(", "x", ",", "device", "=", "device", ",", "non_blocking", "=", "non_blocking"...
a96bd07cb58822cfb39fd81765135712f1db41ca
train
create_supervised_trainer
Factory function for creating a trainer for supervised models. Args: model (`torch.nn.Module`): the model to train. optimizer (`torch.optim.Optimizer`): the optimizer to use. loss_fn (torch.nn loss function): the loss function to use. device (str, optional): device type specificatio...
ignite/engine/__init__.py
def create_supervised_trainer(model, optimizer, loss_fn, device=None, non_blocking=False, prepare_batch=_prepare_batch, output_transform=lambda x, y, y_pred, loss: loss.item()): """ Factory function for creating a trainer ...
def create_supervised_trainer(model, optimizer, loss_fn, device=None, non_blocking=False, prepare_batch=_prepare_batch, output_transform=lambda x, y, y_pred, loss: loss.item()): """ Factory function for creating a trainer ...
[ "Factory", "function", "for", "creating", "a", "trainer", "for", "supervised", "models", "." ]
pytorch/ignite
python
https://github.com/pytorch/ignite/blob/a96bd07cb58822cfb39fd81765135712f1db41ca/ignite/engine/__init__.py#L16-L55
[ "def", "create_supervised_trainer", "(", "model", ",", "optimizer", ",", "loss_fn", ",", "device", "=", "None", ",", "non_blocking", "=", "False", ",", "prepare_batch", "=", "_prepare_batch", ",", "output_transform", "=", "lambda", "x", ",", "y", ",", "y_pred"...
a96bd07cb58822cfb39fd81765135712f1db41ca
train
create_supervised_evaluator
Factory function for creating an evaluator for supervised models. Args: model (`torch.nn.Module`): the model to train. metrics (dict of str - :class:`~ignite.metrics.Metric`): a map of metric names to Metrics. device (str, optional): device type specification (default: None). Ap...
ignite/engine/__init__.py
def create_supervised_evaluator(model, metrics=None, device=None, non_blocking=False, prepare_batch=_prepare_batch, output_transform=lambda x, y, y_pred: (y_pred, y,)): """ Factory function for creating an evaluator ...
def create_supervised_evaluator(model, metrics=None, device=None, non_blocking=False, prepare_batch=_prepare_batch, output_transform=lambda x, y, y_pred: (y_pred, y,)): """ Factory function for creating an evaluator ...
[ "Factory", "function", "for", "creating", "an", "evaluator", "for", "supervised", "models", "." ]
pytorch/ignite
python
https://github.com/pytorch/ignite/blob/a96bd07cb58822cfb39fd81765135712f1db41ca/ignite/engine/__init__.py#L58-L101
[ "def", "create_supervised_evaluator", "(", "model", ",", "metrics", "=", "None", ",", "device", "=", "None", ",", "non_blocking", "=", "False", ",", "prepare_batch", "=", "_prepare_batch", ",", "output_transform", "=", "lambda", "x", ",", "y", ",", "y_pred", ...
a96bd07cb58822cfb39fd81765135712f1db41ca
train
create_lr_scheduler_with_warmup
Helper method to create a LR scheduler with a linear warm-up. Args: lr_scheduler (ParamScheduler or subclass of `torch.optim.lr_scheduler._LRScheduler`): LR scheduler after the warm-up. warmup_start_value (float): LR start value of the warm-up phase. warmup_end_value (float): LR...
ignite/contrib/handlers/param_scheduler.py
def create_lr_scheduler_with_warmup(lr_scheduler, warmup_start_value, warmup_end_value, warmup_duration, save_history=False, output_simulated_values=None): """ Helper method to create a LR scheduler with a linear warm-up. Args: ...
def create_lr_scheduler_with_warmup(lr_scheduler, warmup_start_value, warmup_end_value, warmup_duration, save_history=False, output_simulated_values=None): """ Helper method to create a LR scheduler with a linear warm-up. Args: ...
[ "Helper", "method", "to", "create", "a", "LR", "scheduler", "with", "a", "linear", "warm", "-", "up", "." ]
pytorch/ignite
python
https://github.com/pytorch/ignite/blob/a96bd07cb58822cfb39fd81765135712f1db41ca/ignite/contrib/handlers/param_scheduler.py#L501-L565
[ "def", "create_lr_scheduler_with_warmup", "(", "lr_scheduler", ",", "warmup_start_value", ",", "warmup_end_value", ",", "warmup_duration", ",", "save_history", "=", "False", ",", "output_simulated_values", "=", "None", ")", ":", "if", "not", "isinstance", "(", "lr_sch...
a96bd07cb58822cfb39fd81765135712f1db41ca
train
ParamScheduler.simulate_values
Method to simulate scheduled values during num_events events. Args: num_events (int): number of events during the simulation. **scheduler_kwargs : parameter scheduler configuration kwargs. Returns: list of pairs: [event_index, value] Examples: .. c...
ignite/contrib/handlers/param_scheduler.py
def simulate_values(cls, num_events, **scheduler_kwargs): """Method to simulate scheduled values during num_events events. Args: num_events (int): number of events during the simulation. **scheduler_kwargs : parameter scheduler configuration kwargs. Returns: ...
def simulate_values(cls, num_events, **scheduler_kwargs): """Method to simulate scheduled values during num_events events. Args: num_events (int): number of events during the simulation. **scheduler_kwargs : parameter scheduler configuration kwargs. Returns: ...
[ "Method", "to", "simulate", "scheduled", "values", "during", "num_events", "events", "." ]
pytorch/ignite
python
https://github.com/pytorch/ignite/blob/a96bd07cb58822cfb39fd81765135712f1db41ca/ignite/contrib/handlers/param_scheduler.py#L75-L108
[ "def", "simulate_values", "(", "cls", ",", "num_events", ",", "*", "*", "scheduler_kwargs", ")", ":", "keys_to_remove", "=", "[", "'optimizer'", ",", "'save_history'", "]", "for", "key", "in", "keys_to_remove", ":", "if", "key", "in", "scheduler_kwargs", ":", ...
a96bd07cb58822cfb39fd81765135712f1db41ca
train
CosineAnnealingScheduler.get_param
Method to get current optimizer's parameter value
ignite/contrib/handlers/param_scheduler.py
def get_param(self): """Method to get current optimizer's parameter value """ cycle_progress = self.event_index / self.cycle_size return self.start_value + ((self.end_value - self.start_value) / 2) * (1 - math.cos(math.pi * cycle_progress))
def get_param(self): """Method to get current optimizer's parameter value """ cycle_progress = self.event_index / self.cycle_size return self.start_value + ((self.end_value - self.start_value) / 2) * (1 - math.cos(math.pi * cycle_progress))
[ "Method", "to", "get", "current", "optimizer", "s", "parameter", "value" ]
pytorch/ignite
python
https://github.com/pytorch/ignite/blob/a96bd07cb58822cfb39fd81765135712f1db41ca/ignite/contrib/handlers/param_scheduler.py#L274-L278
[ "def", "get_param", "(", "self", ")", ":", "cycle_progress", "=", "self", ".", "event_index", "/", "self", ".", "cycle_size", "return", "self", ".", "start_value", "+", "(", "(", "self", ".", "end_value", "-", "self", ".", "start_value", ")", "/", "2", ...
a96bd07cb58822cfb39fd81765135712f1db41ca
train
ConcatScheduler.simulate_values
Method to simulate scheduled values during num_events events. Args: num_events (int): number of events during the simulation. schedulers (list of ParamScheduler): list of parameter schedulers. durations (list of int): list of number of events that lasts a parameter scheduler...
ignite/contrib/handlers/param_scheduler.py
def simulate_values(cls, num_events, schedulers, durations, param_names=None, **kwargs): """Method to simulate scheduled values during num_events events. Args: num_events (int): number of events during the simulation. schedulers (list of ParamScheduler): list of parameter schedu...
def simulate_values(cls, num_events, schedulers, durations, param_names=None, **kwargs): """Method to simulate scheduled values during num_events events. Args: num_events (int): number of events during the simulation. schedulers (list of ParamScheduler): list of parameter schedu...
[ "Method", "to", "simulate", "scheduled", "values", "during", "num_events", "events", "." ]
pytorch/ignite
python
https://github.com/pytorch/ignite/blob/a96bd07cb58822cfb39fd81765135712f1db41ca/ignite/contrib/handlers/param_scheduler.py#L379-L408
[ "def", "simulate_values", "(", "cls", ",", "num_events", ",", "schedulers", ",", "durations", ",", "param_names", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "param_names", "is", "not", "None", "and", "not", "isinstance", "(", "param_names", ",",...
a96bd07cb58822cfb39fd81765135712f1db41ca
train
LRScheduler.get_param
Method to get current optimizer's parameter value
ignite/contrib/handlers/param_scheduler.py
def get_param(self): """Method to get current optimizer's parameter value """ lr_list = self.lr_scheduler.get_lr() if len(lr_list) > 1: raise ValueError("Optimizer passed to lr_scheduler should have a single param group, " "but currently there are...
def get_param(self): """Method to get current optimizer's parameter value """ lr_list = self.lr_scheduler.get_lr() if len(lr_list) > 1: raise ValueError("Optimizer passed to lr_scheduler should have a single param group, " "but currently there are...
[ "Method", "to", "get", "current", "optimizer", "s", "parameter", "value" ]
pytorch/ignite
python
https://github.com/pytorch/ignite/blob/a96bd07cb58822cfb39fd81765135712f1db41ca/ignite/contrib/handlers/param_scheduler.py#L450-L457
[ "def", "get_param", "(", "self", ")", ":", "lr_list", "=", "self", ".", "lr_scheduler", ".", "get_lr", "(", ")", "if", "len", "(", "lr_list", ")", ">", "1", ":", "raise", "ValueError", "(", "\"Optimizer passed to lr_scheduler should have a single param group, \"",...
a96bd07cb58822cfb39fd81765135712f1db41ca
train
LRScheduler.simulate_values
Method to simulate scheduled values during num_events events. Args: num_events (int): number of events during the simulation. lr_scheduler (subclass of `torch.optim.lr_scheduler._LRScheduler`): lr_scheduler object to wrap. Returns: list of pairs: [event_index, value...
ignite/contrib/handlers/param_scheduler.py
def simulate_values(cls, num_events, lr_scheduler, **kwargs): """Method to simulate scheduled values during num_events events. Args: num_events (int): number of events during the simulation. lr_scheduler (subclass of `torch.optim.lr_scheduler._LRScheduler`): lr_scheduler object ...
def simulate_values(cls, num_events, lr_scheduler, **kwargs): """Method to simulate scheduled values during num_events events. Args: num_events (int): number of events during the simulation. lr_scheduler (subclass of `torch.optim.lr_scheduler._LRScheduler`): lr_scheduler object ...
[ "Method", "to", "simulate", "scheduled", "values", "during", "num_events", "events", "." ]
pytorch/ignite
python
https://github.com/pytorch/ignite/blob/a96bd07cb58822cfb39fd81765135712f1db41ca/ignite/contrib/handlers/param_scheduler.py#L460-L481
[ "def", "simulate_values", "(", "cls", ",", "num_events", ",", "lr_scheduler", ",", "*", "*", "kwargs", ")", ":", "# This scheduler uses `torch.optim.lr_scheduler._LRScheduler` which", "# should be replicated in order to simulate LR values and", "# not perturb original scheduler.", ...
a96bd07cb58822cfb39fd81765135712f1db41ca
train
check_manual_seed
If manual seed is not specified, choose a random one and communicate it to the user.
examples/gan/dcgan.py
def check_manual_seed(seed): """ If manual seed is not specified, choose a random one and communicate it to the user. """ seed = seed or random.randint(1, 10000) random.seed(seed) torch.manual_seed(seed) print('Using manual seed: {seed}'.format(seed=seed))
def check_manual_seed(seed): """ If manual seed is not specified, choose a random one and communicate it to the user. """ seed = seed or random.randint(1, 10000) random.seed(seed) torch.manual_seed(seed) print('Using manual seed: {seed}'.format(seed=seed))
[ "If", "manual", "seed", "is", "not", "specified", "choose", "a", "random", "one", "and", "communicate", "it", "to", "the", "user", "." ]
pytorch/ignite
python
https://github.com/pytorch/ignite/blob/a96bd07cb58822cfb39fd81765135712f1db41ca/examples/gan/dcgan.py#L146-L155
[ "def", "check_manual_seed", "(", "seed", ")", ":", "seed", "=", "seed", "or", "random", ".", "randint", "(", "1", ",", "10000", ")", "random", ".", "seed", "(", "seed", ")", "torch", ".", "manual_seed", "(", "seed", ")", "print", "(", "'Using manual se...
a96bd07cb58822cfb39fd81765135712f1db41ca
train
BaseLogger.attach
Attach the logger to the engine and execute `log_handler` function at `event_name` events. Args: engine (Engine): engine object. log_handler (callable): a logging handler to execute event_name: event to attach the logging handler to. Valid events are from :class:`~ignite.eng...
ignite/contrib/handlers/base_logger.py
def attach(self, engine, log_handler, event_name): """Attach the logger to the engine and execute `log_handler` function at `event_name` events. Args: engine (Engine): engine object. log_handler (callable): a logging handler to execute event_name: event to attach the...
def attach(self, engine, log_handler, event_name): """Attach the logger to the engine and execute `log_handler` function at `event_name` events. Args: engine (Engine): engine object. log_handler (callable): a logging handler to execute event_name: event to attach the...
[ "Attach", "the", "logger", "to", "the", "engine", "and", "execute", "log_handler", "function", "at", "event_name", "events", "." ]
pytorch/ignite
python
https://github.com/pytorch/ignite/blob/a96bd07cb58822cfb39fd81765135712f1db41ca/ignite/contrib/handlers/base_logger.py#L16-L29
[ "def", "attach", "(", "self", ",", "engine", ",", "log_handler", ",", "event_name", ")", ":", "if", "event_name", "not", "in", "State", ".", "event_to_attr", ":", "raise", "RuntimeError", "(", "\"Unknown event name '{}'\"", ".", "format", "(", "event_name", ")...
a96bd07cb58822cfb39fd81765135712f1db41ca
train
BaseOutputHandler._setup_output_metrics
Helper method to setup metrics to log
ignite/contrib/handlers/base_logger.py
def _setup_output_metrics(self, engine): """Helper method to setup metrics to log """ metrics = {} if self.metric_names is not None: for name in self.metric_names: if name not in engine.state.metrics: warnings.warn("Provided metric name '{}...
def _setup_output_metrics(self, engine): """Helper method to setup metrics to log """ metrics = {} if self.metric_names is not None: for name in self.metric_names: if name not in engine.state.metrics: warnings.warn("Provided metric name '{}...
[ "Helper", "method", "to", "setup", "metrics", "to", "log" ]
pytorch/ignite
python
https://github.com/pytorch/ignite/blob/a96bd07cb58822cfb39fd81765135712f1db41ca/ignite/contrib/handlers/base_logger.py#L89-L108
[ "def", "_setup_output_metrics", "(", "self", ",", "engine", ")", ":", "metrics", "=", "{", "}", "if", "self", ".", "metric_names", "is", "not", "None", ":", "for", "name", "in", "self", ".", "metric_names", ":", "if", "name", "not", "in", "engine", "."...
a96bd07cb58822cfb39fd81765135712f1db41ca
train
Timer.attach
Register callbacks to control the timer. Args: engine (Engine): Engine that this timer will be attached to. start (Events): Event which should start (reset) the timer. pause (Events): Event which should pause the timer. ...
ignite/handlers/timing.py
def attach(self, engine, start=Events.STARTED, pause=Events.COMPLETED, resume=None, step=None): """ Register callbacks to control the timer. Args: engine (Engine): Engine that this timer will be attached to. start (Events): Event which should star...
def attach(self, engine, start=Events.STARTED, pause=Events.COMPLETED, resume=None, step=None): """ Register callbacks to control the timer. Args: engine (Engine): Engine that this timer will be attached to. start (Events): Event which should star...
[ "Register", "callbacks", "to", "control", "the", "timer", "." ]
pytorch/ignite
python
https://github.com/pytorch/ignite/blob/a96bd07cb58822cfb39fd81765135712f1db41ca/ignite/handlers/timing.py#L87-L116
[ "def", "attach", "(", "self", ",", "engine", ",", "start", "=", "Events", ".", "STARTED", ",", "pause", "=", "Events", ".", "COMPLETED", ",", "resume", "=", "None", ",", "step", "=", "None", ")", ":", "engine", ".", "add_event_handler", "(", "start", ...
a96bd07cb58822cfb39fd81765135712f1db41ca
train
_BaseVisDrawer.add_scalar
Helper method to log a scalar with VisdomLogger. Args: logger (VisdomLogger): visdom logger k (str): scalar name which is used to set window title and y-axis label v (int or float): scalar value, y-axis value event_name: Event name which is used to setup x-axis l...
ignite/contrib/handlers/visdom_logger.py
def add_scalar(self, logger, k, v, event_name, global_step): """ Helper method to log a scalar with VisdomLogger. Args: logger (VisdomLogger): visdom logger k (str): scalar name which is used to set window title and y-axis label v (int or float): scalar value...
def add_scalar(self, logger, k, v, event_name, global_step): """ Helper method to log a scalar with VisdomLogger. Args: logger (VisdomLogger): visdom logger k (str): scalar name which is used to set window title and y-axis label v (int or float): scalar value...
[ "Helper", "method", "to", "log", "a", "scalar", "with", "VisdomLogger", "." ]
pytorch/ignite
python
https://github.com/pytorch/ignite/blob/a96bd07cb58822cfb39fd81765135712f1db41ca/ignite/contrib/handlers/visdom_logger.py#L21-L60
[ "def", "add_scalar", "(", "self", ",", "logger", ",", "k", ",", "v", ",", "event_name", ",", "global_step", ")", ":", "if", "k", "not", "in", "self", ".", "windows", ":", "self", ".", "windows", "[", "k", "]", "=", "{", "'win'", ":", "None", ",",...
a96bd07cb58822cfb39fd81765135712f1db41ca
train
_to_hours_mins_secs
Convert seconds to hours, mins, and seconds.
ignite/_utils.py
def _to_hours_mins_secs(time_taken): """Convert seconds to hours, mins, and seconds.""" mins, secs = divmod(time_taken, 60) hours, mins = divmod(mins, 60) return hours, mins, secs
def _to_hours_mins_secs(time_taken): """Convert seconds to hours, mins, and seconds.""" mins, secs = divmod(time_taken, 60) hours, mins = divmod(mins, 60) return hours, mins, secs
[ "Convert", "seconds", "to", "hours", "mins", "and", "seconds", "." ]
pytorch/ignite
python
https://github.com/pytorch/ignite/blob/a96bd07cb58822cfb39fd81765135712f1db41ca/ignite/_utils.py#L6-L10
[ "def", "_to_hours_mins_secs", "(", "time_taken", ")", ":", "mins", ",", "secs", "=", "divmod", "(", "time_taken", ",", "60", ")", "hours", ",", "mins", "=", "divmod", "(", "mins", ",", "60", ")", "return", "hours", ",", "mins", ",", "secs" ]
a96bd07cb58822cfb39fd81765135712f1db41ca
train
parse_args
Parse the arguments/options passed to the program on the command line.
coursera/commandline.py
def parse_args(args=None): """ Parse the arguments/options passed to the program on the command line. """ parse_kwargs = { "description": 'Download Coursera.org lecture material and resources.' } conf_file_path = os.path.join(os.getcwd(), LOCAL_CONF_FILE_NAME) if os.path.isfile(co...
def parse_args(args=None): """ Parse the arguments/options passed to the program on the command line. """ parse_kwargs = { "description": 'Download Coursera.org lecture material and resources.' } conf_file_path = os.path.join(os.getcwd(), LOCAL_CONF_FILE_NAME) if os.path.isfile(co...
[ "Parse", "the", "arguments", "/", "options", "passed", "to", "the", "program", "on", "the", "command", "line", "." ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/commandline.py#L33-L504
[ "def", "parse_args", "(", "args", "=", "None", ")", ":", "parse_kwargs", "=", "{", "\"description\"", ":", "'Download Coursera.org lecture material and resources.'", "}", "conf_file_path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "getcwd", "(", ")", ...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
random_string
Return a pseudo-random string of specified length.
coursera/utils.py
def random_string(length): """ Return a pseudo-random string of specified length. """ valid_chars = string_ascii_letters + string_digits return ''.join(random.choice(valid_chars) for i in range(length))
def random_string(length): """ Return a pseudo-random string of specified length. """ valid_chars = string_ascii_letters + string_digits return ''.join(random.choice(valid_chars) for i in range(length))
[ "Return", "a", "pseudo", "-", "random", "string", "of", "specified", "length", "." ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/utils.py#L81-L87
[ "def", "random_string", "(", "length", ")", ":", "valid_chars", "=", "string_ascii_letters", "+", "string_digits", "return", "''", ".", "join", "(", "random", ".", "choice", "(", "valid_chars", ")", "for", "i", "in", "range", "(", "length", ")", ")" ]
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
clean_filename
Sanitize a string to be used as a filename. If minimal_change is set to true, then we only strip the bare minimum of characters that are problematic for filesystems (namely, ':', '/' and '\x00', '\n').
coursera/utils.py
def clean_filename(s, minimal_change=False): """ Sanitize a string to be used as a filename. If minimal_change is set to true, then we only strip the bare minimum of characters that are problematic for filesystems (namely, ':', '/' and '\x00', '\n'). """ # First, deal with URL encoded stri...
def clean_filename(s, minimal_change=False): """ Sanitize a string to be used as a filename. If minimal_change is set to true, then we only strip the bare minimum of characters that are problematic for filesystems (namely, ':', '/' and '\x00', '\n'). """ # First, deal with URL encoded stri...
[ "Sanitize", "a", "string", "to", "be", "used", "as", "a", "filename", "." ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/utils.py#L107-L148
[ "def", "clean_filename", "(", "s", ",", "minimal_change", "=", "False", ")", ":", "# First, deal with URL encoded strings", "h", "=", "html_parser", ".", "HTMLParser", "(", ")", "s", "=", "h", ".", "unescape", "(", "s", ")", "s", "=", "unquote_plus", "(", ...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
normalize_path
Normalizes path on Windows OS. This means prepending <backslash><backslash>?<backslash> to the path to get access to Win32 device namespace instead of Win32 file namespace. See https://msdn.microsoft.com/en-us/library/aa365247%28v=vs.85%29.aspx#maxpath @param path: Path to normalize. @type path: st...
coursera/utils.py
def normalize_path(path): """ Normalizes path on Windows OS. This means prepending <backslash><backslash>?<backslash> to the path to get access to Win32 device namespace instead of Win32 file namespace. See https://msdn.microsoft.com/en-us/library/aa365247%28v=vs.85%29.aspx#maxpath @param path:...
def normalize_path(path): """ Normalizes path on Windows OS. This means prepending <backslash><backslash>?<backslash> to the path to get access to Win32 device namespace instead of Win32 file namespace. See https://msdn.microsoft.com/en-us/library/aa365247%28v=vs.85%29.aspx#maxpath @param path:...
[ "Normalizes", "path", "on", "Windows", "OS", ".", "This", "means", "prepending", "<backslash", ">", "<backslash", ">", "?<backslash", ">", "to", "the", "path", "to", "get", "access", "to", "Win32", "device", "namespace", "instead", "of", "Win32", "file", "na...
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/utils.py#L151-L170
[ "def", "normalize_path", "(", "path", ")", ":", "if", "sys", ".", "platform", "!=", "'win32'", ":", "return", "path", "if", "path", ".", "startswith", "(", "WINDOWS_UNC_PREFIX", ")", ":", "return", "path", "return", "WINDOWS_UNC_PREFIX", "+", "os", ".", "p...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
get_anchor_format
Extract the resource file-type format from the anchor.
coursera/utils.py
def get_anchor_format(a): """ Extract the resource file-type format from the anchor. """ # (. or format=) then (file_extension) then (? or $) # e.g. "...format=txt" or "...download.mp4?..." fmt = re.search(r"(?:\.|format=)(\w+)(?:\?.*)?$", a) return fmt.group(1) if fmt else None
def get_anchor_format(a): """ Extract the resource file-type format from the anchor. """ # (. or format=) then (file_extension) then (? or $) # e.g. "...format=txt" or "...download.mp4?..." fmt = re.search(r"(?:\.|format=)(\w+)(?:\?.*)?$", a) return fmt.group(1) if fmt else None
[ "Extract", "the", "resource", "file", "-", "type", "format", "from", "the", "anchor", "." ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/utils.py#L173-L181
[ "def", "get_anchor_format", "(", "a", ")", ":", "# (. or format=) then (file_extension) then (? or $)", "# e.g. \"...format=txt\" or \"...download.mp4?...\"", "fmt", "=", "re", ".", "search", "(", "r\"(?:\\.|format=)(\\w+)(?:\\?.*)?$\"", ",", "a", ")", "return", "fmt", ".", ...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
clean_url
Remove params, query and fragment parts from URL so that `os.path.basename` and `os.path.splitext` can work correctly. @param url: URL to clean. @type url: str @return: Cleaned URL. @rtype: str
coursera/utils.py
def clean_url(url): """ Remove params, query and fragment parts from URL so that `os.path.basename` and `os.path.splitext` can work correctly. @param url: URL to clean. @type url: str @return: Cleaned URL. @rtype: str """ parsed = urlparse(url.strip()) reconstructed = ParseResu...
def clean_url(url): """ Remove params, query and fragment parts from URL so that `os.path.basename` and `os.path.splitext` can work correctly. @param url: URL to clean. @type url: str @return: Cleaned URL. @rtype: str """ parsed = urlparse(url.strip()) reconstructed = ParseResu...
[ "Remove", "params", "query", "and", "fragment", "parts", "from", "URL", "so", "that", "os", ".", "path", ".", "basename", "and", "os", ".", "path", ".", "splitext", "can", "work", "correctly", "." ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/utils.py#L198-L213
[ "def", "clean_url", "(", "url", ")", ":", "parsed", "=", "urlparse", "(", "url", ".", "strip", "(", ")", ")", "reconstructed", "=", "ParseResult", "(", "parsed", ".", "scheme", ",", "parsed", ".", "netloc", ",", "parsed", ".", "path", ",", "params", ...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
fix_url
Strip whitespace characters from the beginning and the end of the url and add a default scheme.
coursera/utils.py
def fix_url(url): """ Strip whitespace characters from the beginning and the end of the url and add a default scheme. """ if url is None: return None url = url.strip() if url and not urlparse(url).scheme: url = "http://" + url return url
def fix_url(url): """ Strip whitespace characters from the beginning and the end of the url and add a default scheme. """ if url is None: return None url = url.strip() if url and not urlparse(url).scheme: url = "http://" + url return url
[ "Strip", "whitespace", "characters", "from", "the", "beginning", "and", "the", "end", "of", "the", "url", "and", "add", "a", "default", "scheme", "." ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/utils.py#L216-L229
[ "def", "fix_url", "(", "url", ")", ":", "if", "url", "is", "None", ":", "return", "None", "url", "=", "url", ".", "strip", "(", ")", "if", "url", "and", "not", "urlparse", "(", "url", ")", ".", "scheme", ":", "url", "=", "\"http://\"", "+", "url"...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
is_course_complete
Determine is the course is likely to have been terminated or not. We return True if the timestamp given by last_update is 30 days or older than today's date. Otherwise, we return True. The intended use case for this is to detect if a given courses has not seen any update in the last 30 days or more. ...
coursera/utils.py
def is_course_complete(last_update): """ Determine is the course is likely to have been terminated or not. We return True if the timestamp given by last_update is 30 days or older than today's date. Otherwise, we return True. The intended use case for this is to detect if a given courses has not ...
def is_course_complete(last_update): """ Determine is the course is likely to have been terminated or not. We return True if the timestamp given by last_update is 30 days or older than today's date. Otherwise, we return True. The intended use case for this is to detect if a given courses has not ...
[ "Determine", "is", "the", "course", "is", "likely", "to", "have", "been", "terminated", "or", "not", "." ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/utils.py#L232-L249
[ "def", "is_course_complete", "(", "last_update", ")", ":", "rv", "=", "False", "if", "last_update", ">=", "0", ":", "delta", "=", "time", ".", "time", "(", ")", "-", "last_update", "max_delta", "=", "total_seconds", "(", "datetime", ".", "timedelta", "(", ...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
make_coursera_absolute_url
If given url is relative adds coursera netloc, otherwise returns it without any changes.
coursera/utils.py
def make_coursera_absolute_url(url): """ If given url is relative adds coursera netloc, otherwise returns it without any changes. """ if not bool(urlparse(url).netloc): return urljoin(COURSERA_URL, url) return url
def make_coursera_absolute_url(url): """ If given url is relative adds coursera netloc, otherwise returns it without any changes. """ if not bool(urlparse(url).netloc): return urljoin(COURSERA_URL, url) return url
[ "If", "given", "url", "is", "relative", "adds", "coursera", "netloc", "otherwise", "returns", "it", "without", "any", "changes", "." ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/utils.py#L262-L271
[ "def", "make_coursera_absolute_url", "(", "url", ")", ":", "if", "not", "bool", "(", "urlparse", "(", "url", ")", ".", "netloc", ")", ":", "return", "urljoin", "(", "COURSERA_URL", ",", "url", ")", "return", "url" ]
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
extend_supplement_links
Extends (merges) destination dictionary with supplement_links from source dictionary. Values are expected to be lists, or any data structure that has `extend` method. @param destination: Destination dictionary that will be extended. @type destination: @see CourseraOnDemand._extract_links_from_text ...
coursera/utils.py
def extend_supplement_links(destination, source): """ Extends (merges) destination dictionary with supplement_links from source dictionary. Values are expected to be lists, or any data structure that has `extend` method. @param destination: Destination dictionary that will be extended. @type de...
def extend_supplement_links(destination, source): """ Extends (merges) destination dictionary with supplement_links from source dictionary. Values are expected to be lists, or any data structure that has `extend` method. @param destination: Destination dictionary that will be extended. @type de...
[ "Extends", "(", "merges", ")", "destination", "dictionary", "with", "supplement_links", "from", "source", "dictionary", ".", "Values", "are", "expected", "to", "be", "lists", "or", "any", "data", "structure", "that", "has", "extend", "method", "." ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/utils.py#L274-L291
[ "def", "extend_supplement_links", "(", "destination", ",", "source", ")", ":", "for", "key", ",", "value", "in", "iteritems", "(", "source", ")", ":", "if", "key", "not", "in", "destination", ":", "destination", "[", "key", "]", "=", "value", "else", ":"...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
print_ssl_error_message
Print SSLError message with URL to instructions on how to fix it.
coursera/utils.py
def print_ssl_error_message(exception): """ Print SSLError message with URL to instructions on how to fix it. """ message = """ ##################################################################### # ATTENTION! PLEASE READ THIS! # # The following error has just occurred: # %s %s # # Please read instruct...
def print_ssl_error_message(exception): """ Print SSLError message with URL to instructions on how to fix it. """ message = """ ##################################################################### # ATTENTION! PLEASE READ THIS! # # The following error has just occurred: # %s %s # # Please read instruct...
[ "Print", "SSLError", "message", "with", "URL", "to", "instructions", "on", "how", "to", "fix", "it", "." ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/utils.py#L294-L309
[ "def", "print_ssl_error_message", "(", "exception", ")", ":", "message", "=", "\"\"\"\n#####################################################################\n# ATTENTION! PLEASE READ THIS!\n#\n# The following error has just occurred:\n# %s %s\n#\n# Please read instructions on how to fix this error h...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
list_courses
List enrolled courses. @param args: Command-line arguments. @type args: namedtuple
coursera/coursera_dl.py
def list_courses(args): """ List enrolled courses. @param args: Command-line arguments. @type args: namedtuple """ session = get_session() login(session, args.username, args.password) extractor = CourseraExtractor(session) courses = extractor.list_courses() logging.info('Found %...
def list_courses(args): """ List enrolled courses. @param args: Command-line arguments. @type args: namedtuple """ session = get_session() login(session, args.username, args.password) extractor = CourseraExtractor(session) courses = extractor.list_courses() logging.info('Found %...
[ "List", "enrolled", "courses", "." ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/coursera_dl.py#L100-L113
[ "def", "list_courses", "(", "args", ")", ":", "session", "=", "get_session", "(", ")", "login", "(", "session", ",", "args", ".", "username", ",", "args", ".", "password", ")", "extractor", "=", "CourseraExtractor", "(", "session", ")", "courses", "=", "...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
download_on_demand_class
Download all requested resources from the on-demand class given in class_name. @return: Tuple of (bool, bool), where the first bool indicates whether errors occurred while parsing syllabus, the second bool indicates whether the course appears to be completed. @rtype: (bool, bool)
coursera/coursera_dl.py
def download_on_demand_class(session, args, class_name): """ Download all requested resources from the on-demand class given in class_name. @return: Tuple of (bool, bool), where the first bool indicates whether errors occurred while parsing syllabus, the second bool indicates whether th...
def download_on_demand_class(session, args, class_name): """ Download all requested resources from the on-demand class given in class_name. @return: Tuple of (bool, bool), where the first bool indicates whether errors occurred while parsing syllabus, the second bool indicates whether th...
[ "Download", "all", "requested", "resources", "from", "the", "on", "-", "demand", "class", "given", "in", "class_name", "." ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/coursera_dl.py#L116-L181
[ "def", "download_on_demand_class", "(", "session", ",", "args", ",", "class_name", ")", ":", "error_occurred", "=", "False", "extractor", "=", "CourseraExtractor", "(", "session", ")", "cached_syllabus_filename", "=", "'%s-syllabus-parsed.json'", "%", "class_name", "i...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
download_class
Try to download on-demand class. @return: Tuple of (bool, bool), where the first bool indicates whether errors occurred while parsing syllabus, the second bool indicates whether the course appears to be completed. @rtype: (bool, bool)
coursera/coursera_dl.py
def download_class(session, args, class_name): """ Try to download on-demand class. @return: Tuple of (bool, bool), where the first bool indicates whether errors occurred while parsing syllabus, the second bool indicates whether the course appears to be completed. @rtype: (bool, bool) ...
def download_class(session, args, class_name): """ Try to download on-demand class. @return: Tuple of (bool, bool), where the first bool indicates whether errors occurred while parsing syllabus, the second bool indicates whether the course appears to be completed. @rtype: (bool, bool) ...
[ "Try", "to", "download", "on", "-", "demand", "class", "." ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/coursera_dl.py#L204-L214
[ "def", "download_class", "(", "session", ",", "args", ",", "class_name", ")", ":", "logging", ".", "debug", "(", "'Downloading new style (on demand) class %s'", ",", "class_name", ")", "return", "download_on_demand_class", "(", "session", ",", "args", ",", "class_na...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
main
Main entry point for execution as a program (instead of as a module).
coursera/coursera_dl.py
def main(): """ Main entry point for execution as a program (instead of as a module). """ args = parse_args() logging.info('coursera_dl version %s', __version__) completed_classes = [] classes_with_errors = [] mkdir_p(PATH_CACHE, 0o700) if args.clear_cache: shutil.rmtree(PA...
def main(): """ Main entry point for execution as a program (instead of as a module). """ args = parse_args() logging.info('coursera_dl version %s', __version__) completed_classes = [] classes_with_errors = [] mkdir_p(PATH_CACHE, 0o700) if args.clear_cache: shutil.rmtree(PA...
[ "Main", "entry", "point", "for", "execution", "as", "a", "program", "(", "instead", "of", "as", "a", "module", ")", "." ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/coursera_dl.py#L217-L283
[ "def", "main", "(", ")", ":", "args", "=", "parse_args", "(", ")", "logging", ".", "info", "(", "'coursera_dl version %s'", ",", "__version__", ")", "completed_classes", "=", "[", "]", "classes_with_errors", "=", "[", "]", "mkdir_p", "(", "PATH_CACHE", ",", ...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
prepare_auth_headers
This function prepares headers with CSRF/CAUTH tokens that can be used in POST requests such as login/get_quiz. @param session: Requests session. @type session: requests.Session @param include_cauth: Flag that indicates whether CAUTH cookies should be included as well. @type include_cauth:...
coursera/cookies.py
def prepare_auth_headers(session, include_cauth=False): """ This function prepares headers with CSRF/CAUTH tokens that can be used in POST requests such as login/get_quiz. @param session: Requests session. @type session: requests.Session @param include_cauth: Flag that indicates whether CAUTH ...
def prepare_auth_headers(session, include_cauth=False): """ This function prepares headers with CSRF/CAUTH tokens that can be used in POST requests such as login/get_quiz. @param session: Requests session. @type session: requests.Session @param include_cauth: Flag that indicates whether CAUTH ...
[ "This", "function", "prepares", "headers", "with", "CSRF", "/", "CAUTH", "tokens", "that", "can", "be", "used", "in", "POST", "requests", "such", "as", "login", "/", "get_quiz", "." ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/cookies.py#L72-L108
[ "def", "prepare_auth_headers", "(", "session", ",", "include_cauth", "=", "False", ")", ":", "# csrftoken is simply a 20 char random string.", "csrftoken", "=", "random_string", "(", "20", ")", "# Now make a call to the authenticator url.", "csrf2cookie", "=", "'csrf2_token_%...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
login
Login on coursera.org with the given credentials. This adds the following cookies to the session: sessionid, maestro_login, maestro_login_flag
coursera/cookies.py
def login(session, username, password, class_name=None): """ Login on coursera.org with the given credentials. This adds the following cookies to the session: sessionid, maestro_login, maestro_login_flag """ logging.debug('Initiating login.') try: session.cookies.clear('.course...
def login(session, username, password, class_name=None): """ Login on coursera.org with the given credentials. This adds the following cookies to the session: sessionid, maestro_login, maestro_login_flag """ logging.debug('Initiating login.') try: session.cookies.clear('.course...
[ "Login", "on", "coursera", ".", "org", "with", "the", "given", "credentials", "." ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/cookies.py#L111-L157
[ "def", "login", "(", "session", ",", "username", ",", "password", ",", "class_name", "=", "None", ")", ":", "logging", ".", "debug", "(", "'Initiating login.'", ")", "try", ":", "session", ".", "cookies", ".", "clear", "(", "'.coursera.org'", ")", "logging...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
down_the_wabbit_hole
Authenticate on class.coursera.org
coursera/cookies.py
def down_the_wabbit_hole(session, class_name): """ Authenticate on class.coursera.org """ auth_redirector_url = AUTH_REDIRECT_URL.format(class_name=class_name) r = session.get(auth_redirector_url) logging.debug('Following %s to authenticate on class.coursera.org.', auth_redir...
def down_the_wabbit_hole(session, class_name): """ Authenticate on class.coursera.org """ auth_redirector_url = AUTH_REDIRECT_URL.format(class_name=class_name) r = session.get(auth_redirector_url) logging.debug('Following %s to authenticate on class.coursera.org.', auth_redir...
[ "Authenticate", "on", "class", ".", "coursera", ".", "org" ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/cookies.py#L160-L177
[ "def", "down_the_wabbit_hole", "(", "session", ",", "class_name", ")", ":", "auth_redirector_url", "=", "AUTH_REDIRECT_URL", ".", "format", "(", "class_name", "=", "class_name", ")", "r", "=", "session", ".", "get", "(", "auth_redirector_url", ")", "logging", "....
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
get_authentication_cookies
Get the necessary cookies to authenticate on class.coursera.org. To access the class pages we need two cookies on class.coursera.org: csrf_token, session
coursera/cookies.py
def get_authentication_cookies(session, class_name, username, password): """ Get the necessary cookies to authenticate on class.coursera.org. To access the class pages we need two cookies on class.coursera.org: csrf_token, session """ # First, check if we already have the .coursera.org coo...
def get_authentication_cookies(session, class_name, username, password): """ Get the necessary cookies to authenticate on class.coursera.org. To access the class pages we need two cookies on class.coursera.org: csrf_token, session """ # First, check if we already have the .coursera.org coo...
[ "Get", "the", "necessary", "cookies", "to", "authenticate", "on", "class", ".", "coursera", ".", "org", "." ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/cookies.py#L180-L206
[ "def", "get_authentication_cookies", "(", "session", ",", "class_name", ",", "username", ",", "password", ")", ":", "# First, check if we already have the .coursera.org cookies.", "if", "session", ".", "cookies", ".", "get", "(", "'CAUTH'", ",", "domain", "=", "\".cou...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
do_we_have_enough_cookies
Check whether we have all the required cookies to authenticate on class.coursera.org.
coursera/cookies.py
def do_we_have_enough_cookies(cj, class_name): """ Check whether we have all the required cookies to authenticate on class.coursera.org. """ domain = 'class.coursera.org' path = "/" + class_name return cj.get('csrf_token', domain=domain, path=path) is not None
def do_we_have_enough_cookies(cj, class_name): """ Check whether we have all the required cookies to authenticate on class.coursera.org. """ domain = 'class.coursera.org' path = "/" + class_name return cj.get('csrf_token', domain=domain, path=path) is not None
[ "Check", "whether", "we", "have", "all", "the", "required", "cookies", "to", "authenticate", "on", "class", ".", "coursera", ".", "org", "." ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/cookies.py#L209-L217
[ "def", "do_we_have_enough_cookies", "(", "cj", ",", "class_name", ")", ":", "domain", "=", "'class.coursera.org'", "path", "=", "\"/\"", "+", "class_name", "return", "cj", ".", "get", "(", "'csrf_token'", ",", "domain", "=", "domain", ",", "path", "=", "path...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
validate_cookies
Checks whether we have all the required cookies to authenticate on class.coursera.org. Also check for and remove stale session.
coursera/cookies.py
def validate_cookies(session, class_name): """ Checks whether we have all the required cookies to authenticate on class.coursera.org. Also check for and remove stale session. """ if not do_we_have_enough_cookies(session.cookies, class_name): return False url = CLASS_URL.format(class...
def validate_cookies(session, class_name): """ Checks whether we have all the required cookies to authenticate on class.coursera.org. Also check for and remove stale session. """ if not do_we_have_enough_cookies(session.cookies, class_name): return False url = CLASS_URL.format(class...
[ "Checks", "whether", "we", "have", "all", "the", "required", "cookies", "to", "authenticate", "on", "class", ".", "coursera", ".", "org", ".", "Also", "check", "for", "and", "remove", "stale", "session", "." ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/cookies.py#L220-L240
[ "def", "validate_cookies", "(", "session", ",", "class_name", ")", ":", "if", "not", "do_we_have_enough_cookies", "(", "session", ".", "cookies", ",", "class_name", ")", ":", "return", "False", "url", "=", "CLASS_URL", ".", "format", "(", "class_name", "=", ...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
make_cookie_values
Makes a string of cookie keys and values. Can be used to set a Cookie header.
coursera/cookies.py
def make_cookie_values(cj, class_name): """ Makes a string of cookie keys and values. Can be used to set a Cookie header. """ path = "/" + class_name cookies = [c.name + '=' + c.value for c in cj if c.domain == "class.coursera.org" and c.path == path...
def make_cookie_values(cj, class_name): """ Makes a string of cookie keys and values. Can be used to set a Cookie header. """ path = "/" + class_name cookies = [c.name + '=' + c.value for c in cj if c.domain == "class.coursera.org" and c.path == path...
[ "Makes", "a", "string", "of", "cookie", "keys", "and", "values", ".", "Can", "be", "used", "to", "set", "a", "Cookie", "header", "." ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/cookies.py#L243-L255
[ "def", "make_cookie_values", "(", "cj", ",", "class_name", ")", ":", "path", "=", "\"/\"", "+", "class_name", "cookies", "=", "[", "c", ".", "name", "+", "'='", "+", "c", ".", "value", "for", "c", "in", "cj", "if", "c", ".", "domain", "==", "\"clas...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
find_cookies_for_class
Return a RequestsCookieJar containing the cookies for .coursera.org and class.coursera.org found in the given cookies_file.
coursera/cookies.py
def find_cookies_for_class(cookies_file, class_name): """ Return a RequestsCookieJar containing the cookies for .coursera.org and class.coursera.org found in the given cookies_file. """ path = "/" + class_name def cookies_filter(c): return c.domain == ".coursera.org" \ or (...
def find_cookies_for_class(cookies_file, class_name): """ Return a RequestsCookieJar containing the cookies for .coursera.org and class.coursera.org found in the given cookies_file. """ path = "/" + class_name def cookies_filter(c): return c.domain == ".coursera.org" \ or (...
[ "Return", "a", "RequestsCookieJar", "containing", "the", "cookies", "for", ".", "coursera", ".", "org", "and", "class", ".", "coursera", ".", "org", "found", "in", "the", "given", "cookies_file", "." ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/cookies.py#L258-L276
[ "def", "find_cookies_for_class", "(", "cookies_file", ",", "class_name", ")", ":", "path", "=", "\"/\"", "+", "class_name", "def", "cookies_filter", "(", "c", ")", ":", "return", "c", ".", "domain", "==", "\".coursera.org\"", "or", "(", "c", ".", "domain", ...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
load_cookies_file
Load cookies file. We pre-pend the file with the special Netscape header because the cookie loader is very particular about this string.
coursera/cookies.py
def load_cookies_file(cookies_file): """ Load cookies file. We pre-pend the file with the special Netscape header because the cookie loader is very particular about this string. """ logging.debug('Loading cookie file %s into memory.', cookies_file) cookies = StringIO() cookies.write('...
def load_cookies_file(cookies_file): """ Load cookies file. We pre-pend the file with the special Netscape header because the cookie loader is very particular about this string. """ logging.debug('Loading cookie file %s into memory.', cookies_file) cookies = StringIO() cookies.write('...
[ "Load", "cookies", "file", "." ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/cookies.py#L279-L294
[ "def", "load_cookies_file", "(", "cookies_file", ")", ":", "logging", ".", "debug", "(", "'Loading cookie file %s into memory.'", ",", "cookies_file", ")", "cookies", "=", "StringIO", "(", ")", "cookies", ".", "write", "(", "'# Netscape HTTP Cookie File'", ")", "coo...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
get_cookies_from_cache
Returns a RequestsCookieJar containing the cached cookies for the given user.
coursera/cookies.py
def get_cookies_from_cache(username): """ Returns a RequestsCookieJar containing the cached cookies for the given user. """ logging.debug('Trying to get cookies from the cache.') path = get_cookies_cache_path(username) cj = requests.cookies.RequestsCookieJar() try: cached_cj = ...
def get_cookies_from_cache(username): """ Returns a RequestsCookieJar containing the cached cookies for the given user. """ logging.debug('Trying to get cookies from the cache.') path = get_cookies_cache_path(username) cj = requests.cookies.RequestsCookieJar() try: cached_cj = ...
[ "Returns", "a", "RequestsCookieJar", "containing", "the", "cached", "cookies", "for", "the", "given", "user", "." ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/cookies.py#L313-L332
[ "def", "get_cookies_from_cache", "(", "username", ")", ":", "logging", ".", "debug", "(", "'Trying to get cookies from the cache.'", ")", "path", "=", "get_cookies_cache_path", "(", "username", ")", "cj", "=", "requests", ".", "cookies", ".", "RequestsCookieJar", "(...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
write_cookies_to_cache
Save RequestsCookieJar to disk in Mozilla's cookies.txt file format. This prevents us from repeated authentications on the accounts.coursera.org and class.coursera.org/class_name sites.
coursera/cookies.py
def write_cookies_to_cache(cj, username): """ Save RequestsCookieJar to disk in Mozilla's cookies.txt file format. This prevents us from repeated authentications on the accounts.coursera.org and class.coursera.org/class_name sites. """ mkdir_p(PATH_COOKIES, 0o700) path = get_cookies_cache_p...
def write_cookies_to_cache(cj, username): """ Save RequestsCookieJar to disk in Mozilla's cookies.txt file format. This prevents us from repeated authentications on the accounts.coursera.org and class.coursera.org/class_name sites. """ mkdir_p(PATH_COOKIES, 0o700) path = get_cookies_cache_p...
[ "Save", "RequestsCookieJar", "to", "disk", "in", "Mozilla", "s", "cookies", ".", "txt", "file", "format", "." ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/cookies.py#L335-L347
[ "def", "write_cookies_to_cache", "(", "cj", ",", "username", ")", ":", "mkdir_p", "(", "PATH_COOKIES", ",", "0o700", ")", "path", "=", "get_cookies_cache_path", "(", "username", ")", "cached_cj", "=", "cookielib", ".", "MozillaCookieJar", "(", ")", "for", "coo...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
get_cookies_for_class
Get the cookies for the given class. We do not validate the cookies if they are loaded from a cookies file because this is intended for debugging purposes or if the coursera authentication process has changed.
coursera/cookies.py
def get_cookies_for_class(session, class_name, cookies_file=None, username=None, password=None): """ Get the cookies for the given class. We do not validate the cookies if they are loaded from a cookies file because this is i...
def get_cookies_for_class(session, class_name, cookies_file=None, username=None, password=None): """ Get the cookies for the given class. We do not validate the cookies if they are loaded from a cookies file because this is i...
[ "Get", "the", "cookies", "for", "the", "given", "class", "." ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/cookies.py#L350-L372
[ "def", "get_cookies_for_class", "(", "session", ",", "class_name", ",", "cookies_file", "=", "None", ",", "username", "=", "None", ",", "password", "=", "None", ")", ":", "if", "cookies_file", ":", "cookies", "=", "find_cookies_for_class", "(", "cookies_file", ...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
get_reply
Download an HTML page using the requests session. Low-level function that allows for flexible request configuration. @param session: Requests session. @type session: requests.Session @param url: URL pattern with optional keywords to format. @type url: str @param post: Flag that indicates whet...
coursera/network.py
def get_reply(session, url, post=False, data=None, headers=None, quiet=False): """ Download an HTML page using the requests session. Low-level function that allows for flexible request configuration. @param session: Requests session. @type session: requests.Session @param url: URL pattern with...
def get_reply(session, url, post=False, data=None, headers=None, quiet=False): """ Download an HTML page using the requests session. Low-level function that allows for flexible request configuration. @param session: Requests session. @type session: requests.Session @param url: URL pattern with...
[ "Download", "an", "HTML", "page", "using", "the", "requests", "session", ".", "Low", "-", "level", "function", "that", "allows", "for", "flexible", "request", "configuration", "." ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/network.py#L12-L58
[ "def", "get_reply", "(", "session", ",", "url", ",", "post", "=", "False", ",", "data", "=", "None", ",", "headers", "=", "None", ",", "quiet", "=", "False", ")", ":", "request_headers", "=", "{", "}", "if", "headers", "is", "None", "else", "headers"...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
get_page
Download an HTML page using the requests session. @param session: Requests session. @type session: requests.Session @param url: URL pattern with optional keywords to format. @type url: str @param post: Flag that indicates whether POST request should be sent. @type post: bool @param data:...
coursera/network.py
def get_page(session, url, json=False, post=False, data=None, headers=None, quiet=False, **kwargs): """ Download an HTML page using the requests session. @param session: Requests session. @type session: requests....
def get_page(session, url, json=False, post=False, data=None, headers=None, quiet=False, **kwargs): """ Download an HTML page using the requests session. @param session: Requests session. @type session: requests....
[ "Download", "an", "HTML", "page", "using", "the", "requests", "session", "." ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/network.py#L61-L93
[ "def", "get_page", "(", "session", ",", "url", ",", "json", "=", "False", ",", "post", "=", "False", ",", "data", "=", "None", ",", "headers", "=", "None", ",", "quiet", "=", "False", ",", "*", "*", "kwargs", ")", ":", "url", "=", "url", ".", "...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
get_page_and_url
Download an HTML page using the requests session and return the final URL after following redirects.
coursera/network.py
def get_page_and_url(session, url): """ Download an HTML page using the requests session and return the final URL after following redirects. """ reply = get_reply(session, url) return reply.text, reply.url
def get_page_and_url(session, url): """ Download an HTML page using the requests session and return the final URL after following redirects. """ reply = get_reply(session, url) return reply.text, reply.url
[ "Download", "an", "HTML", "page", "using", "the", "requests", "session", "and", "return", "the", "final", "URL", "after", "following", "redirects", "." ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/network.py#L96-L102
[ "def", "get_page_and_url", "(", "session", ",", "url", ")", ":", "reply", "=", "get_reply", "(", "session", ",", "url", ")", "return", "reply", ".", "text", ",", "reply", ".", "url" ]
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
skip_format_url
Checks whether a give format/url should be skipped and not downloaded. @param format_: Filename format (extension). @type format_: str (e.g. html, txt, zip, pdf) @param url: URL. @type url: str @return: True if format/url should be skipped, False otherwise. @rtype bool
coursera/filtering.py
def skip_format_url(format_, url): """ Checks whether a give format/url should be skipped and not downloaded. @param format_: Filename format (extension). @type format_: str (e.g. html, txt, zip, pdf) @param url: URL. @type url: str @return: True if format/url should be skipped, False oth...
def skip_format_url(format_, url): """ Checks whether a give format/url should be skipped and not downloaded. @param format_: Filename format (extension). @type format_: str (e.g. html, txt, zip, pdf) @param url: URL. @type url: str @return: True if format/url should be skipped, False oth...
[ "Checks", "whether", "a", "give", "format", "/", "url", "should", "be", "skipped", "and", "not", "downloaded", "." ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/filtering.py#L41-L81
[ "def", "skip_format_url", "(", "format_", ",", "url", ")", ":", "# Do not download empty formats", "if", "format_", "==", "''", ":", "return", "True", "# Do not download email addresses", "if", "(", "'mailto:'", "in", "url", ")", "and", "(", "'@'", "in", "url", ...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
find_resources_to_get
Select formats to download.
coursera/filtering.py
def find_resources_to_get(lecture, file_formats, resource_filter, ignored_formats=None): """ Select formats to download. """ resources_to_get = [] if ignored_formats is None: ignored_formats = [] if len(ignored_formats): logging.info("The following file formats will be ignored:...
def find_resources_to_get(lecture, file_formats, resource_filter, ignored_formats=None): """ Select formats to download. """ resources_to_get = [] if ignored_formats is None: ignored_formats = [] if len(ignored_formats): logging.info("The following file formats will be ignored:...
[ "Select", "formats", "to", "download", "." ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/filtering.py#L84-L117
[ "def", "find_resources_to_get", "(", "lecture", ",", "file_formats", ",", "resource_filter", ",", "ignored_formats", "=", "None", ")", ":", "resources_to_get", "=", "[", "]", "if", "ignored_formats", "is", "None", ":", "ignored_formats", "=", "[", "]", "if", "...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
generate_readme_rst
Generate README.rst from README.md via pandoc. In case of errors, we show a message having the error that we got and exit the program.
setup.py
def generate_readme_rst(): """ Generate README.rst from README.md via pandoc. In case of errors, we show a message having the error that we got and exit the program. """ pandoc_cmd = [ 'pandoc', '--from=markdown', '--to=rst', '--output=README.rst', 'READ...
def generate_readme_rst(): """ Generate README.rst from README.md via pandoc. In case of errors, we show a message having the error that we got and exit the program. """ pandoc_cmd = [ 'pandoc', '--from=markdown', '--to=rst', '--output=README.rst', 'READ...
[ "Generate", "README", ".", "rst", "from", "README", ".", "md", "via", "pandoc", "." ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/setup.py#L21-L43
[ "def", "generate_readme_rst", "(", ")", ":", "pandoc_cmd", "=", "[", "'pandoc'", ",", "'--from=markdown'", ",", "'--to=rst'", ",", "'--output=README.rst'", ",", "'README.md'", "]", "if", "os", ".", "path", ".", "exists", "(", "'README.rst'", ")", ":", "return"...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
read_file
Read the contents of filename or give an alternative result instead.
setup.py
def read_file(filename, alt=None): """ Read the contents of filename or give an alternative result instead. """ lines = None try: with open(filename, encoding='utf-8') as f: lines = f.read() except IOError: lines = [] if alt is None else alt return lines
def read_file(filename, alt=None): """ Read the contents of filename or give an alternative result instead. """ lines = None try: with open(filename, encoding='utf-8') as f: lines = f.read() except IOError: lines = [] if alt is None else alt return lines
[ "Read", "the", "contents", "of", "filename", "or", "give", "an", "alternative", "result", "instead", "." ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/setup.py#L46-L57
[ "def", "read_file", "(", "filename", ",", "alt", "=", "None", ")", ":", "lines", "=", "None", "try", ":", "with", "open", "(", "filename", ",", "encoding", "=", "'utf-8'", ")", "as", "f", ":", "lines", "=", "f", ".", "read", "(", ")", "except", "...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
release_check
Check if there is a Git tag already in place
fabfile.py
def release_check(): """Check if there is a Git tag already in place""" tags = local("git tag", capture=True) tags = set(tags.splitlines()) if env.version in tags: raise Exception("Already released v. %r" % env.version)
def release_check(): """Check if there is a Git tag already in place""" tags = local("git tag", capture=True) tags = set(tags.splitlines()) if env.version in tags: raise Exception("Already released v. %r" % env.version)
[ "Check", "if", "there", "is", "a", "Git", "tag", "already", "in", "place" ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/fabfile.py#L75-L80
[ "def", "release_check", "(", ")", ":", "tags", "=", "local", "(", "\"git tag\"", ",", "capture", "=", "True", ")", "tags", "=", "set", "(", "tags", ".", "splitlines", "(", ")", ")", "if", "env", ".", "version", "in", "tags", ":", "raise", "Exception"...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
release
Release a new version
fabfile.py
def release(): """Release a new version""" release_check() build() print("Releasing %s version %s." % (env.projname, env.version)) local("git tag %s" % env.version) local('gpg --detach-sign --armor dist/coursera-*.tar.gz*') local('twine upload dist/coursera-*.tar.gz*') local("git push") ...
def release(): """Release a new version""" release_check() build() print("Releasing %s version %s." % (env.projname, env.version)) local("git tag %s" % env.version) local('gpg --detach-sign --armor dist/coursera-*.tar.gz*') local('twine upload dist/coursera-*.tar.gz*') local("git push") ...
[ "Release", "a", "new", "version" ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/fabfile.py#L84-L93
[ "def", "release", "(", ")", ":", "release_check", "(", ")", "build", "(", ")", "print", "(", "\"Releasing %s version %s.\"", "%", "(", "env", ".", "projname", ",", "env", ".", "version", ")", ")", "local", "(", "\"git tag %s\"", "%", "env", ".", "version...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
expand_specializations
Checks whether any given name is not a class but a specialization. If it's a specialization, expand the list of class names with the child class names.
coursera/api.py
def expand_specializations(session, class_names): """ Checks whether any given name is not a class but a specialization. If it's a specialization, expand the list of class names with the child class names. """ result = [] for class_name in class_names: specialization = Specializatio...
def expand_specializations(session, class_names): """ Checks whether any given name is not a class but a specialization. If it's a specialization, expand the list of class names with the child class names. """ result = [] for class_name in class_names: specialization = Specializatio...
[ "Checks", "whether", "any", "given", "name", "is", "not", "a", "class", "but", "a", "specialization", "." ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/api.py#L545-L563
[ "def", "expand_specializations", "(", "session", ",", "class_names", ")", ":", "result", "=", "[", "]", "for", "class_name", "in", "class_names", ":", "specialization", "=", "SpecializationV1", ".", "create", "(", "session", ",", "class_name", ")", "if", "spec...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
MarkupToHTMLConverter._convert_markup_basic
Perform basic conversion of instructions markup. This includes replacement of several textual markup tags with their HTML equivalents. @param soup: BeautifulSoup instance. @type soup: BeautifulSoup
coursera/api.py
def _convert_markup_basic(self, soup): """ Perform basic conversion of instructions markup. This includes replacement of several textual markup tags with their HTML equivalents. @param soup: BeautifulSoup instance. @type soup: BeautifulSoup """ # Inject meta char...
def _convert_markup_basic(self, soup): """ Perform basic conversion of instructions markup. This includes replacement of several textual markup tags with their HTML equivalents. @param soup: BeautifulSoup instance. @type soup: BeautifulSoup """ # Inject meta char...
[ "Perform", "basic", "conversion", "of", "instructions", "markup", ".", "This", "includes", "replacement", "of", "several", "textual", "markup", "tags", "with", "their", "HTML", "equivalents", "." ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/api.py#L186-L223
[ "def", "_convert_markup_basic", "(", "self", ",", "soup", ")", ":", "# Inject meta charset tag", "meta", "=", "soup", ".", "new_tag", "(", "'meta'", ",", "charset", "=", "'UTF-8'", ")", "soup", ".", "insert", "(", "0", ",", "meta", ")", "# 1. Inject basic CS...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
MarkupToHTMLConverter._convert_markup_images
Convert images of instructions markup. Images are downloaded, base64-encoded and inserted into <img> tags. @param soup: BeautifulSoup instance. @type soup: BeautifulSoup
coursera/api.py
def _convert_markup_images(self, soup): """ Convert images of instructions markup. Images are downloaded, base64-encoded and inserted into <img> tags. @param soup: BeautifulSoup instance. @type soup: BeautifulSoup """ # 6. Replace <img> assets with actual image c...
def _convert_markup_images(self, soup): """ Convert images of instructions markup. Images are downloaded, base64-encoded and inserted into <img> tags. @param soup: BeautifulSoup instance. @type soup: BeautifulSoup """ # 6. Replace <img> assets with actual image c...
[ "Convert", "images", "of", "instructions", "markup", ".", "Images", "are", "downloaded", "base64", "-", "encoded", "and", "inserted", "into", "<img", ">", "tags", "." ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/api.py#L225-L249
[ "def", "_convert_markup_images", "(", "self", ",", "soup", ")", ":", "# 6. Replace <img> assets with actual image contents", "images", "=", "[", "image", "for", "image", "in", "soup", ".", "find_all", "(", "'img'", ")", "if", "image", ".", "attrs", ".", "get", ...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
MarkupToHTMLConverter._convert_markup_audios
Convert audios of instructions markup. Audios are downloaded, base64-encoded and inserted as <audio controls> <source> tag. @param soup: BeautifulSoup instance. @type soup: BeautifulSoup
coursera/api.py
def _convert_markup_audios(self, soup): """ Convert audios of instructions markup. Audios are downloaded, base64-encoded and inserted as <audio controls> <source> tag. @param soup: BeautifulSoup instance. @type soup: BeautifulSoup """ # 7. Replace <asset> audio a...
def _convert_markup_audios(self, soup): """ Convert audios of instructions markup. Audios are downloaded, base64-encoded and inserted as <audio controls> <source> tag. @param soup: BeautifulSoup instance. @type soup: BeautifulSoup """ # 7. Replace <asset> audio a...
[ "Convert", "audios", "of", "instructions", "markup", ".", "Audios", "are", "downloaded", "base64", "-", "encoded", "and", "inserted", "as", "<audio", "controls", ">", "<source", ">", "tag", "." ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/api.py#L251-L284
[ "def", "_convert_markup_audios", "(", "self", ",", "soup", ")", ":", "# 7. Replace <asset> audio assets with actual audio contents", "audios", "=", "[", "audio", "for", "audio", "in", "soup", ".", "find_all", "(", "'asset'", ")", "if", "audio", ".", "attrs", ".", ...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
OnDemandCourseMaterialItemsV1.create
Create an instance using a session and a course_name. @param session: Requests session. @type session: requests.Session @param course_name: Course name (slug) from course json. @type course_name: str @return: Instance of OnDemandCourseMaterialItems @rtype: OnDemandCour...
coursera/api.py
def create(session, course_name): """ Create an instance using a session and a course_name. @param session: Requests session. @type session: requests.Session @param course_name: Course name (slug) from course json. @type course_name: str @return: Instance of On...
def create(session, course_name): """ Create an instance using a session and a course_name. @param session: Requests session. @type session: requests.Session @param course_name: Course name (slug) from course json. @type course_name: str @return: Instance of On...
[ "Create", "an", "instance", "using", "a", "session", "and", "a", "course_name", "." ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/api.py#L304-L322
[ "def", "create", "(", "session", ",", "course_name", ")", ":", "dom", "=", "get_page", "(", "session", ",", "OPENCOURSE_ONDEMAND_COURSE_MATERIALS", ",", "json", "=", "True", ",", "class_name", "=", "course_name", ")", "return", "OnDemandCourseMaterialItemsV1", "("...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
CourseraOnDemand.list_courses
List enrolled courses. @return: List of enrolled courses. @rtype: [str]
coursera/api.py
def list_courses(self): """ List enrolled courses. @return: List of enrolled courses. @rtype: [str] """ reply = get_page(self._session, OPENCOURSE_MEMBERSHIPS, json=True) course_list = reply['linked']['courses.v1'] slugs = [element['slug'] for element in ...
def list_courses(self): """ List enrolled courses. @return: List of enrolled courses. @rtype: [str] """ reply = get_page(self._session, OPENCOURSE_MEMBERSHIPS, json=True) course_list = reply['linked']['courses.v1'] slugs = [element['slug'] for element in ...
[ "List", "enrolled", "courses", "." ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/api.py#L628-L638
[ "def", "list_courses", "(", "self", ")", ":", "reply", "=", "get_page", "(", "self", ".", "_session", ",", "OPENCOURSE_MEMBERSHIPS", ",", "json", "=", "True", ")", "course_list", "=", "reply", "[", "'linked'", "]", "[", "'courses.v1'", "]", "slugs", "=", ...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
CourseraOnDemand.extract_links_from_lecture
Return the download URLs of on-demand course video. @param video_id: Video ID. @type video_id: str @param subtitle_language: Subtitle language. @type subtitle_language: str @param resolution: Preferred video resolution. @type resolution: str @return: @see Cour...
coursera/api.py
def extract_links_from_lecture(self, course_id, video_id, subtitle_language='en', resolution='540p'): """ Return the download URLs of on-demand course video. @param video_id: Video ID. @type video_id: str @pa...
def extract_links_from_lecture(self, course_id, video_id, subtitle_language='en', resolution='540p'): """ Return the download URLs of on-demand course video. @param video_id: Video ID. @type video_id: str @pa...
[ "Return", "the", "download", "URLs", "of", "on", "-", "demand", "course", "video", "." ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/api.py#L863-L896
[ "def", "extract_links_from_lecture", "(", "self", ",", "course_id", ",", "video_id", ",", "subtitle_language", "=", "'en'", ",", "resolution", "=", "'540p'", ")", ":", "try", ":", "links", "=", "self", ".", "_extract_videos_and_subtitles_from_lecture", "(", "cours...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
CourseraOnDemand._get_lecture_asset_ids
Obtain a list of asset ids from a lecture.
coursera/api.py
def _get_lecture_asset_ids(self, course_id, video_id): """ Obtain a list of asset ids from a lecture. """ dom = get_page(self._session, OPENCOURSE_ONDEMAND_LECTURE_ASSETS_URL, json=True, course_id=course_id, video_id=video_id) # Note that we extract here "i...
def _get_lecture_asset_ids(self, course_id, video_id): """ Obtain a list of asset ids from a lecture. """ dom = get_page(self._session, OPENCOURSE_ONDEMAND_LECTURE_ASSETS_URL, json=True, course_id=course_id, video_id=video_id) # Note that we extract here "i...
[ "Obtain", "a", "list", "of", "asset", "ids", "from", "a", "lecture", "." ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/api.py#L898-L907
[ "def", "_get_lecture_asset_ids", "(", "self", ",", "course_id", ",", "video_id", ")", ":", "dom", "=", "get_page", "(", "self", ".", "_session", ",", "OPENCOURSE_ONDEMAND_LECTURE_ASSETS_URL", ",", "json", "=", "True", ",", "course_id", "=", "course_id", ",", "...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
CourseraOnDemand._normalize_assets
Perform asset normalization. For some reason, assets that are sometimes present in lectures, have "@1" at the end of their id. Such "uncut" asset id when fed to OPENCOURSE_ASSETS_URL results in error that says: "Routing error: 'get-all' not implemented". To avoid that, the last two chara...
coursera/api.py
def _normalize_assets(self, assets): """ Perform asset normalization. For some reason, assets that are sometimes present in lectures, have "@1" at the end of their id. Such "uncut" asset id when fed to OPENCOURSE_ASSETS_URL results in error that says: "Routing error: 'get-all' no...
def _normalize_assets(self, assets): """ Perform asset normalization. For some reason, assets that are sometimes present in lectures, have "@1" at the end of their id. Such "uncut" asset id when fed to OPENCOURSE_ASSETS_URL results in error that says: "Routing error: 'get-all' no...
[ "Perform", "asset", "normalization", ".", "For", "some", "reason", "assets", "that", "are", "sometimes", "present", "in", "lectures", "have", "@1", "at", "the", "end", "of", "their", "id", ".", "Such", "uncut", "asset", "id", "when", "fed", "to", "OPENCOUR...
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/api.py#L909-L933
[ "def", "_normalize_assets", "(", "self", ",", "assets", ")", ":", "new_assets", "=", "[", "]", "for", "asset", "in", "assets", ":", "# For example: giAxucdaEeWJTQ5WTi8YJQ@1", "if", "len", "(", "asset", ")", "==", "24", ":", "# Turn it into: giAxucdaEeWJTQ5WTi8YJQ"...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
CourseraOnDemand._extract_links_from_lecture_assets
Extract links to files of the asset ids. @param asset_ids: List of asset ids. @type asset_ids: [str] @return: @see CourseraOnDemand._extract_links_from_text
coursera/api.py
def _extract_links_from_lecture_assets(self, asset_ids): """ Extract links to files of the asset ids. @param asset_ids: List of asset ids. @type asset_ids: [str] @return: @see CourseraOnDemand._extract_links_from_text """ links = {} def _add_asset(name,...
def _extract_links_from_lecture_assets(self, asset_ids): """ Extract links to files of the asset ids. @param asset_ids: List of asset ids. @type asset_ids: [str] @return: @see CourseraOnDemand._extract_links_from_text """ links = {} def _add_asset(name,...
[ "Extract", "links", "to", "files", "of", "the", "asset", "ids", "." ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/api.py#L935-L967
[ "def", "_extract_links_from_lecture_assets", "(", "self", ",", "asset_ids", ")", ":", "links", "=", "{", "}", "def", "_add_asset", "(", "name", ",", "url", ",", "destination", ")", ":", "filename", ",", "extension", "=", "os", ".", "path", ".", "splitext",...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
CourseraOnDemand._get_asset_urls
Get list of asset urls and file names. This method may internally use AssetRetriever to extract `asset` element types. @param asset_id: Asset ID. @type asset_id: str @return List of dictionaries with asset file names and urls. @rtype [{ 'name': '<filename.ext>' ...
coursera/api.py
def _get_asset_urls(self, asset_id): """ Get list of asset urls and file names. This method may internally use AssetRetriever to extract `asset` element types. @param asset_id: Asset ID. @type asset_id: str @return List of dictionaries with asset file names and urls. ...
def _get_asset_urls(self, asset_id): """ Get list of asset urls and file names. This method may internally use AssetRetriever to extract `asset` element types. @param asset_id: Asset ID. @type asset_id: str @return List of dictionaries with asset file names and urls. ...
[ "Get", "list", "of", "asset", "urls", "and", "file", "names", ".", "This", "method", "may", "internally", "use", "AssetRetriever", "to", "extract", "asset", "element", "types", "." ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/api.py#L969-L1029
[ "def", "_get_asset_urls", "(", "self", ",", "asset_id", ")", ":", "dom", "=", "get_page", "(", "self", ".", "_session", ",", "OPENCOURSE_ASSETS_URL", ",", "json", "=", "True", ",", "id", "=", "asset_id", ")", "logging", ".", "debug", "(", "'Parsing JSON fo...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
CourseraOnDemand.extract_links_from_peer_assignment
Return a dictionary with links to supplement files (pdf, csv, zip, ipynb, html and so on) extracted from peer assignment. @param element_id: Element ID to extract files from. @type element_id: str @return: @see CourseraOnDemand._extract_links_from_text
coursera/api.py
def extract_links_from_peer_assignment(self, element_id): """ Return a dictionary with links to supplement files (pdf, csv, zip, ipynb, html and so on) extracted from peer assignment. @param element_id: Element ID to extract files from. @type element_id: str @return: @s...
def extract_links_from_peer_assignment(self, element_id): """ Return a dictionary with links to supplement files (pdf, csv, zip, ipynb, html and so on) extracted from peer assignment. @param element_id: Element ID to extract files from. @type element_id: str @return: @s...
[ "Return", "a", "dictionary", "with", "links", "to", "supplement", "files", "(", "pdf", "csv", "zip", "ipynb", "html", "and", "so", "on", ")", "extracted", "from", "peer", "assignment", "." ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/api.py#L1204-L1236
[ "def", "extract_links_from_peer_assignment", "(", "self", ",", "element_id", ")", ":", "logging", ".", "debug", "(", "'Gathering supplement URLs for element_id <%s>.'", ",", "element_id", ")", "try", ":", "# Assignment text (instructions) contains asset tags which describe", "#...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
CourseraOnDemand.extract_links_from_supplement
Return a dictionary with supplement files (pdf, csv, zip, ipynb, html and so on) extracted from supplement page. @return: @see CourseraOnDemand._extract_links_from_text
coursera/api.py
def extract_links_from_supplement(self, element_id): """ Return a dictionary with supplement files (pdf, csv, zip, ipynb, html and so on) extracted from supplement page. @return: @see CourseraOnDemand._extract_links_from_text """ logging.debug( 'Gathering sup...
def extract_links_from_supplement(self, element_id): """ Return a dictionary with supplement files (pdf, csv, zip, ipynb, html and so on) extracted from supplement page. @return: @see CourseraOnDemand._extract_links_from_text """ logging.debug( 'Gathering sup...
[ "Return", "a", "dictionary", "with", "supplement", "files", "(", "pdf", "csv", "zip", "ipynb", "html", "and", "so", "on", ")", "extracted", "from", "supplement", "page", "." ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/api.py#L1238-L1282
[ "def", "extract_links_from_supplement", "(", "self", ",", "element_id", ")", ":", "logging", ".", "debug", "(", "'Gathering supplement URLs for element_id <%s>.'", ",", "element_id", ")", "try", ":", "dom", "=", "get_page", "(", "self", ".", "_session", ",", "OPEN...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
CourseraOnDemand._extract_asset_tags
Extract asset tags from text into a convenient form. @param text: Text to extract asset tags from. This text contains HTML code that is parsed by BeautifulSoup. @type text: str @return: Asset map. @rtype: { '<id>': { 'name': '<name>', ...
coursera/api.py
def _extract_asset_tags(self, text): """ Extract asset tags from text into a convenient form. @param text: Text to extract asset tags from. This text contains HTML code that is parsed by BeautifulSoup. @type text: str @return: Asset map. @rtype: { ...
def _extract_asset_tags(self, text): """ Extract asset tags from text into a convenient form. @param text: Text to extract asset tags from. This text contains HTML code that is parsed by BeautifulSoup. @type text: str @return: Asset map. @rtype: { ...
[ "Extract", "asset", "tags", "from", "text", "into", "a", "convenient", "form", "." ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/api.py#L1284-L1308
[ "def", "_extract_asset_tags", "(", "self", ",", "text", ")", ":", "soup", "=", "BeautifulSoup", "(", "text", ")", "asset_tags_map", "=", "{", "}", "for", "asset", "in", "soup", ".", "find_all", "(", "'asset'", ")", ":", "asset_tags_map", "[", "asset", "[...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
CourseraOnDemand._extract_asset_urls
Extract asset URLs along with asset ids. @param asset_ids: List of ids to get URLs for. @type assertn: [str] @return: List of dictionaries with asset URLs and ids. @rtype: [{ 'id': '<id>', 'url': '<url>' }]
coursera/api.py
def _extract_asset_urls(self, asset_ids): """ Extract asset URLs along with asset ids. @param asset_ids: List of ids to get URLs for. @type assertn: [str] @return: List of dictionaries with asset URLs and ids. @rtype: [{ 'id': '<id>', 'url': '<ur...
def _extract_asset_urls(self, asset_ids): """ Extract asset URLs along with asset ids. @param asset_ids: List of ids to get URLs for. @type assertn: [str] @return: List of dictionaries with asset URLs and ids. @rtype: [{ 'id': '<id>', 'url': '<ur...
[ "Extract", "asset", "URLs", "along", "with", "asset", "ids", "." ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/api.py#L1310-L1329
[ "def", "_extract_asset_urls", "(", "self", ",", "asset_ids", ")", ":", "dom", "=", "get_page", "(", "self", ".", "_session", ",", "OPENCOURSE_ASSET_URL", ",", "json", "=", "True", ",", "ids", "=", "quote_plus", "(", "','", ".", "join", "(", "asset_ids", ...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
CourseraOnDemand.extract_links_from_reference
Return a dictionary with supplement files (pdf, csv, zip, ipynb, html and so on) extracted from supplement page. @return: @see CourseraOnDemand._extract_links_from_text
coursera/api.py
def extract_links_from_reference(self, short_id): """ Return a dictionary with supplement files (pdf, csv, zip, ipynb, html and so on) extracted from supplement page. @return: @see CourseraOnDemand._extract_links_from_text """ logging.debug('Gathering resource URLs for s...
def extract_links_from_reference(self, short_id): """ Return a dictionary with supplement files (pdf, csv, zip, ipynb, html and so on) extracted from supplement page. @return: @see CourseraOnDemand._extract_links_from_text """ logging.debug('Gathering resource URLs for s...
[ "Return", "a", "dictionary", "with", "supplement", "files", "(", "pdf", "csv", "zip", "ipynb", "html", "and", "so", "on", ")", "extracted", "from", "supplement", "page", "." ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/api.py#L1349-L1392
[ "def", "extract_links_from_reference", "(", "self", ",", "short_id", ")", ":", "logging", ".", "debug", "(", "'Gathering resource URLs for short_id <%s>.'", ",", "short_id", ")", "try", ":", "dom", "=", "get_page", "(", "self", ".", "_session", ",", "OPENCOURSE_RE...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
CourseraOnDemand._extract_programming_immediate_instructions_text
Extract assignment text (instructions). @param element_id: Element id to extract assignment instructions from. @type element_id: str @return: List of assignment text (instructions). @rtype: [str]
coursera/api.py
def _extract_programming_immediate_instructions_text(self, element_id): """ Extract assignment text (instructions). @param element_id: Element id to extract assignment instructions from. @type element_id: str @return: List of assignment text (instructions). @rtype: [str...
def _extract_programming_immediate_instructions_text(self, element_id): """ Extract assignment text (instructions). @param element_id: Element id to extract assignment instructions from. @type element_id: str @return: List of assignment text (instructions). @rtype: [str...
[ "Extract", "assignment", "text", "(", "instructions", ")", "." ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/api.py#L1394-L1410
[ "def", "_extract_programming_immediate_instructions_text", "(", "self", ",", "element_id", ")", ":", "dom", "=", "get_page", "(", "self", ".", "_session", ",", "OPENCOURSE_PROGRAMMING_IMMEDIATE_INSTRUCTIOINS_URL", ",", "json", "=", "True", ",", "course_id", "=", "self...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
CourseraOnDemand._extract_notebook_text
Extract notebook text (instructions). @param element_id: Element id to extract notebook links. @type element_id: str @return: Notebook URL. @rtype: [str]
coursera/api.py
def _extract_notebook_text(self, element_id): """ Extract notebook text (instructions). @param element_id: Element id to extract notebook links. @type element_id: str @return: Notebook URL. @rtype: [str] """ headers = self._auth_headers_with_json() ...
def _extract_notebook_text(self, element_id): """ Extract notebook text (instructions). @param element_id: Element id to extract notebook links. @type element_id: str @return: Notebook URL. @rtype: [str] """ headers = self._auth_headers_with_json() ...
[ "Extract", "notebook", "text", "(", "instructions", ")", "." ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/api.py#L1412-L1436
[ "def", "_extract_notebook_text", "(", "self", ",", "element_id", ")", ":", "headers", "=", "self", ".", "_auth_headers_with_json", "(", ")", "data", "=", "{", "'courseId'", ":", "self", ".", "_course_id", ",", "'learnerId'", ":", "self", ".", "_user_id", ","...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
CourseraOnDemand._extract_assignment_text
Extract assignment text (instructions). @param element_id: Element id to extract assignment instructions from. @type element_id: str @return: List of assignment text (instructions). @rtype: [str]
coursera/api.py
def _extract_assignment_text(self, element_id): """ Extract assignment text (instructions). @param element_id: Element id to extract assignment instructions from. @type element_id: str @return: List of assignment text (instructions). @rtype: [str] """ do...
def _extract_assignment_text(self, element_id): """ Extract assignment text (instructions). @param element_id: Element id to extract assignment instructions from. @type element_id: str @return: List of assignment text (instructions). @rtype: [str] """ do...
[ "Extract", "assignment", "text", "(", "instructions", ")", "." ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/api.py#L1438-L1455
[ "def", "_extract_assignment_text", "(", "self", ",", "element_id", ")", ":", "dom", "=", "get_page", "(", "self", ".", "_session", ",", "OPENCOURSE_PROGRAMMING_ASSIGNMENTS_URL", ",", "json", "=", "True", ",", "course_id", "=", "self", ".", "_course_id", ",", "...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
CourseraOnDemand._extract_peer_assignment_text
Extract peer assignment text (instructions). @param element_id: Element id to extract peer assignment instructions from. @type element_id: str @return: List of peer assignment text (instructions). @rtype: [str]
coursera/api.py
def _extract_peer_assignment_text(self, element_id): """ Extract peer assignment text (instructions). @param element_id: Element id to extract peer assignment instructions from. @type element_id: str @return: List of peer assignment text (instructions). @rtype: [str] ...
def _extract_peer_assignment_text(self, element_id): """ Extract peer assignment text (instructions). @param element_id: Element id to extract peer assignment instructions from. @type element_id: str @return: List of peer assignment text (instructions). @rtype: [str] ...
[ "Extract", "peer", "assignment", "text", "(", "instructions", ")", "." ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/api.py#L1457-L1492
[ "def", "_extract_peer_assignment_text", "(", "self", ",", "element_id", ")", ":", "dom", "=", "get_page", "(", "self", ".", "_session", ",", "OPENCOURSE_PEER_ASSIGNMENT_INSTRUCTIONS", ",", "json", "=", "True", ",", "user_id", "=", "self", ".", "_user_id", ",", ...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
CourseraOnDemand._extract_links_from_text
Extract supplement links from the html text. Links may be provided in two ways: 1. <a> tags with href attribute 2. <asset> tags with id attribute (requires additional request to get the direct URL to the asset file) @param text: HTML text. @type text: str ...
coursera/api.py
def _extract_links_from_text(self, text): """ Extract supplement links from the html text. Links may be provided in two ways: 1. <a> tags with href attribute 2. <asset> tags with id attribute (requires additional request to get the direct URL to the asset f...
def _extract_links_from_text(self, text): """ Extract supplement links from the html text. Links may be provided in two ways: 1. <a> tags with href attribute 2. <asset> tags with id attribute (requires additional request to get the direct URL to the asset f...
[ "Extract", "supplement", "links", "from", "the", "html", "text", ".", "Links", "may", "be", "provided", "in", "two", "ways", ":", "1", ".", "<a", ">", "tags", "with", "href", "attribute", "2", ".", "<asset", ">", "tags", "with", "id", "attribute", "(",...
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/api.py#L1494-L1524
[ "def", "_extract_links_from_text", "(", "self", ",", "text", ")", ":", "supplement_links", "=", "self", ".", "_extract_links_from_a_tags_in_text", "(", "text", ")", "extend_supplement_links", "(", "supplement_links", ",", "self", ".", "_extract_links_from_asset_tags_in_te...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
CourseraOnDemand._extract_links_from_asset_tags_in_text
Scan the text and extract asset tags and links to corresponding files. @param text: Page text. @type text: str @return: @see CourseraOnDemand._extract_links_from_text
coursera/api.py
def _extract_links_from_asset_tags_in_text(self, text): """ Scan the text and extract asset tags and links to corresponding files. @param text: Page text. @type text: str @return: @see CourseraOnDemand._extract_links_from_text """ # Extract asset tags fr...
def _extract_links_from_asset_tags_in_text(self, text): """ Scan the text and extract asset tags and links to corresponding files. @param text: Page text. @type text: str @return: @see CourseraOnDemand._extract_links_from_text """ # Extract asset tags fr...
[ "Scan", "the", "text", "and", "extract", "asset", "tags", "and", "links", "to", "corresponding", "files", "." ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/api.py#L1526-L1561
[ "def", "_extract_links_from_asset_tags_in_text", "(", "self", ",", "text", ")", ":", "# Extract asset tags from instructions text", "asset_tags_map", "=", "self", ".", "_extract_asset_tags", "(", "text", ")", "ids", "=", "list", "(", "iterkeys", "(", "asset_tags_map", ...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
CourseraOnDemand._extract_links_from_a_tags_in_text
Extract supplement links from the html text that contains <a> tags with href attribute. @param text: HTML text. @type text: str @return: Dictionary with supplement links grouped by extension. @rtype: { '<extension1>': [ ('<link1>', '<title1>'), ...
coursera/api.py
def _extract_links_from_a_tags_in_text(self, text): """ Extract supplement links from the html text that contains <a> tags with href attribute. @param text: HTML text. @type text: str @return: Dictionary with supplement links grouped by extension. @rtype: { ...
def _extract_links_from_a_tags_in_text(self, text): """ Extract supplement links from the html text that contains <a> tags with href attribute. @param text: HTML text. @type text: str @return: Dictionary with supplement links grouped by extension. @rtype: { ...
[ "Extract", "supplement", "links", "from", "the", "html", "text", "that", "contains", "<a", ">", "tags", "with", "href", "attribute", "." ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/api.py#L1563-L1613
[ "def", "_extract_links_from_a_tags_in_text", "(", "self", ",", "text", ")", ":", "soup", "=", "BeautifulSoup", "(", "text", ")", "links", "=", "[", "item", "[", "'href'", "]", ".", "strip", "(", ")", "for", "item", "in", "soup", ".", "find_all", "(", "...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
create_m3u_playlist
Create M3U playlist with contents of `section_dir`/*.mp4. The playlist will be created in that directory. @param section_dir: Path where to scan for *.mp4 files. @type section_dir: str
coursera/playlist.py
def create_m3u_playlist(section_dir): """ Create M3U playlist with contents of `section_dir`/*.mp4. The playlist will be created in that directory. @param section_dir: Path where to scan for *.mp4 files. @type section_dir: str """ path_to_return = os.getcwd() for (_path, subdirs, files...
def create_m3u_playlist(section_dir): """ Create M3U playlist with contents of `section_dir`/*.mp4. The playlist will be created in that directory. @param section_dir: Path where to scan for *.mp4 files. @type section_dir: str """ path_to_return = os.getcwd() for (_path, subdirs, files...
[ "Create", "M3U", "playlist", "with", "contents", "of", "section_dir", "/", "*", ".", "mp4", ".", "The", "playlist", "will", "be", "created", "in", "that", "directory", "." ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/playlist.py#L5-L25
[ "def", "create_m3u_playlist", "(", "section_dir", ")", ":", "path_to_return", "=", "os", ".", "getcwd", "(", ")", "for", "(", "_path", ",", "subdirs", ",", "files", ")", "in", "os", ".", "walk", "(", "section_dir", ")", ":", "os", ".", "chdir", "(", ...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
CourseraExtractor.list_courses
List enrolled courses. @return: List of enrolled courses. @rtype: [str]
coursera/extractors.py
def list_courses(self): """ List enrolled courses. @return: List of enrolled courses. @rtype: [str] """ course = CourseraOnDemand(session=self._session, course_id=None, course_name=None) return c...
def list_courses(self): """ List enrolled courses. @return: List of enrolled courses. @rtype: [str] """ course = CourseraOnDemand(session=self._session, course_id=None, course_name=None) return c...
[ "List", "enrolled", "courses", "." ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/extractors.py#L34-L44
[ "def", "list_courses", "(", "self", ")", ":", "course", "=", "CourseraOnDemand", "(", "session", "=", "self", ".", "_session", ",", "course_id", "=", "None", ",", "course_name", "=", "None", ")", "return", "course", ".", "list_courses", "(", ")" ]
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
CourseraExtractor._get_on_demand_syllabus
Get the on-demand course listing webpage.
coursera/extractors.py
def _get_on_demand_syllabus(self, class_name): """ Get the on-demand course listing webpage. """ url = OPENCOURSE_ONDEMAND_COURSE_MATERIALS_V2.format( class_name=class_name) page = get_page(self._session, url) logging.debug('Downloaded %s (%d bytes)', url, le...
def _get_on_demand_syllabus(self, class_name): """ Get the on-demand course listing webpage. """ url = OPENCOURSE_ONDEMAND_COURSE_MATERIALS_V2.format( class_name=class_name) page = get_page(self._session, url) logging.debug('Downloaded %s (%d bytes)', url, le...
[ "Get", "the", "on", "-", "demand", "course", "listing", "webpage", "." ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/extractors.py#L61-L71
[ "def", "_get_on_demand_syllabus", "(", "self", ",", "class_name", ")", ":", "url", "=", "OPENCOURSE_ONDEMAND_COURSE_MATERIALS_V2", ".", "format", "(", "class_name", "=", "class_name", ")", "page", "=", "get_page", "(", "self", ".", "_session", ",", "url", ")", ...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
CourseraExtractor._parse_on_demand_syllabus
Parse a Coursera on-demand course listing/syllabus page. @return: Tuple of (bool, list), where bool indicates whether there was at least on error while parsing syllabus, the list is a list of parsed modules. @rtype: (bool, list)
coursera/extractors.py
def _parse_on_demand_syllabus(self, course_name, page, reverse=False, unrestricted_filenames=False, subtitle_language='en', video_resolution=None, download_quizzes=False, ...
def _parse_on_demand_syllabus(self, course_name, page, reverse=False, unrestricted_filenames=False, subtitle_language='en', video_resolution=None, download_quizzes=False, ...
[ "Parse", "a", "Coursera", "on", "-", "demand", "course", "listing", "/", "syllabus", "page", "." ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/extractors.py#L73-L239
[ "def", "_parse_on_demand_syllabus", "(", "self", ",", "course_name", ",", "page", ",", "reverse", "=", "False", ",", "unrestricted_filenames", "=", "False", ",", "subtitle_language", "=", "'en'", ",", "video_resolution", "=", "None", ",", "download_quizzes", "=", ...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
_iter_modules
This huge function generates a hierarchy with hopefully more clear structure of modules/sections/lectures.
coursera/workflow.py
def _iter_modules(modules, class_name, path, ignored_formats, args): """ This huge function generates a hierarchy with hopefully more clear structure of modules/sections/lectures. """ file_formats = args.file_formats lecture_filter = args.lecture_filter resource_filter = args.resource_filter...
def _iter_modules(modules, class_name, path, ignored_formats, args): """ This huge function generates a hierarchy with hopefully more clear structure of modules/sections/lectures. """ file_formats = args.file_formats lecture_filter = args.lecture_filter resource_filter = args.resource_filter...
[ "This", "huge", "function", "generates", "a", "hierarchy", "with", "hopefully", "more", "clear", "structure", "of", "modules", "/", "sections", "/", "lectures", "." ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/workflow.py#L18-L97
[ "def", "_iter_modules", "(", "modules", ",", "class_name", ",", "path", ",", "ignored_formats", ",", "args", ")", ":", "file_formats", "=", "args", ".", "file_formats", "lecture_filter", "=", "args", ".", "lecture_filter", "resource_filter", "=", "args", ".", ...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
_walk_modules
Helper generator that traverses modules in returns a flattened iterator.
coursera/workflow.py
def _walk_modules(modules, class_name, path, ignored_formats, args): """ Helper generator that traverses modules in returns a flattened iterator. """ for module in _iter_modules(modules=modules, class_name=class_name, path=path, ...
def _walk_modules(modules, class_name, path, ignored_formats, args): """ Helper generator that traverses modules in returns a flattened iterator. """ for module in _iter_modules(modules=modules, class_name=class_name, path=path, ...
[ "Helper", "generator", "that", "traverses", "modules", "in", "returns", "a", "flattened", "iterator", "." ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/workflow.py#L100-L113
[ "def", "_walk_modules", "(", "modules", ",", "class_name", ",", "path", ",", "ignored_formats", ",", "args", ")", ":", "for", "module", "in", "_iter_modules", "(", "modules", "=", "modules", ",", "class_name", "=", "class_name", ",", "path", "=", "path", "...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
CourseraDownloader._handle_resource
Handle resource. This function builds up resource file name and downloads it if necessary. @param url: URL of the resource. @type url: str @param fmt: Format of the resource (pdf, csv, etc) @type fmt: str @param lecture_filename: File name of the lecture. @type...
coursera/workflow.py
def _handle_resource(self, url, fmt, lecture_filename, callback, last_update): """ Handle resource. This function builds up resource file name and downloads it if necessary. @param url: URL of the resource. @type url: str @param fmt: Format of the resource (pdf, csv, et...
def _handle_resource(self, url, fmt, lecture_filename, callback, last_update): """ Handle resource. This function builds up resource file name and downloads it if necessary. @param url: URL of the resource. @type url: str @param fmt: Format of the resource (pdf, csv, et...
[ "Handle", "resource", ".", "This", "function", "builds", "up", "resource", "file", "name", "and", "downloads", "it", "if", "necessary", "." ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/workflow.py#L195-L246
[ "def", "_handle_resource", "(", "self", ",", "url", ",", "fmt", ",", "lecture_filename", ",", "callback", ",", "last_update", ")", ":", "overwrite", "=", "self", ".", "_args", ".", "overwrite", "resume", "=", "self", ".", "_args", ".", "resume", "skip_down...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
get_lecture_filename
Prepare a destination lecture filename. @param combined_section_lectures_nums: Flag that indicates whether section lectures should have combined numbering. @type combined_section_lectures_nums: bool @param section_dir: Path to current section directory. @type section_dir: str @param secnu...
coursera/formatting.py
def get_lecture_filename(combined_section_lectures_nums, section_dir, secnum, lecnum, lecname, title, fmt): """ Prepare a destination lecture filename. @para...
def get_lecture_filename(combined_section_lectures_nums, section_dir, secnum, lecnum, lecname, title, fmt): """ Prepare a destination lecture filename. @para...
[ "Prepare", "a", "destination", "lecture", "filename", "." ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/formatting.py#L25-L76
[ "def", "get_lecture_filename", "(", "combined_section_lectures_nums", ",", "section_dir", ",", "secnum", ",", "lecnum", ",", "lecname", ",", "title", ",", "fmt", ")", ":", "# FIXME: this is a quick and dirty solution to Filename too long", "# problem. We need to think of a more...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
format_bytes
Get human readable version of given bytes. Ripped from https://github.com/rg3/youtube-dl
coursera/downloaders.py
def format_bytes(bytes): """ Get human readable version of given bytes. Ripped from https://github.com/rg3/youtube-dl """ if bytes is None: return 'N/A' if type(bytes) is str: bytes = float(bytes) if bytes == 0.0: exponent = 0 else: exponent = int(math.log...
def format_bytes(bytes): """ Get human readable version of given bytes. Ripped from https://github.com/rg3/youtube-dl """ if bytes is None: return 'N/A' if type(bytes) is str: bytes = float(bytes) if bytes == 0.0: exponent = 0 else: exponent = int(math.log...
[ "Get", "human", "readable", "version", "of", "given", "bytes", ".", "Ripped", "from", "https", ":", "//", "github", ".", "com", "/", "rg3", "/", "youtube", "-", "dl" ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/downloaders.py#L214-L229
[ "def", "format_bytes", "(", "bytes", ")", ":", "if", "bytes", "is", "None", ":", "return", "'N/A'", "if", "type", "(", "bytes", ")", "is", "str", ":", "bytes", "=", "float", "(", "bytes", ")", "if", "bytes", "==", "0.0", ":", "exponent", "=", "0", ...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
get_downloader
Decides which downloader to use.
coursera/downloaders.py
def get_downloader(session, class_name, args): """ Decides which downloader to use. """ external = { 'wget': WgetDownloader, 'curl': CurlDownloader, 'aria2': Aria2Downloader, 'axel': AxelDownloader, } for bin, class_ in iteritems(external): if getattr(ar...
def get_downloader(session, class_name, args): """ Decides which downloader to use. """ external = { 'wget': WgetDownloader, 'curl': CurlDownloader, 'aria2': Aria2Downloader, 'axel': AxelDownloader, } for bin, class_ in iteritems(external): if getattr(ar...
[ "Decides", "which", "downloader", "to", "use", "." ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/downloaders.py#L389-L406
[ "def", "get_downloader", "(", "session", ",", "class_name", ",", "args", ")", ":", "external", "=", "{", "'wget'", ":", "WgetDownloader", ",", "'curl'", ":", "CurlDownloader", ",", "'aria2'", ":", "Aria2Downloader", ",", "'axel'", ":", "AxelDownloader", ",", ...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
Downloader.download
Download the given url to the given file. When the download is aborted by the user, the partially downloaded file is also removed.
coursera/downloaders.py
def download(self, url, filename, resume=False): """ Download the given url to the given file. When the download is aborted by the user, the partially downloaded file is also removed. """ try: self._start_download(url, filename, resume) except KeyboardInterru...
def download(self, url, filename, resume=False): """ Download the given url to the given file. When the download is aborted by the user, the partially downloaded file is also removed. """ try: self._start_download(url, filename, resume) except KeyboardInterru...
[ "Download", "the", "given", "url", "to", "the", "given", "file", ".", "When", "the", "download", "is", "aborted", "by", "the", "user", "the", "partially", "downloaded", "file", "is", "also", "removed", "." ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/downloaders.py#L47-L64
[ "def", "download", "(", "self", ",", "url", ",", "filename", ",", "resume", "=", "False", ")", ":", "try", ":", "self", ".", "_start_download", "(", "url", ",", "filename", ",", "resume", ")", "except", "KeyboardInterrupt", "as", "e", ":", "# keep the fi...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
ExternalDownloader._prepare_cookies
Extract cookies from the requests session and add them to the command
coursera/downloaders.py
def _prepare_cookies(self, command, url): """ Extract cookies from the requests session and add them to the command """ req = requests.models.Request() req.method = 'GET' req.url = url cookie_values = requests.cookies.get_cookie_header( self.session....
def _prepare_cookies(self, command, url): """ Extract cookies from the requests session and add them to the command """ req = requests.models.Request() req.method = 'GET' req.url = url cookie_values = requests.cookies.get_cookie_header( self.session....
[ "Extract", "cookies", "from", "the", "requests", "session", "and", "add", "them", "to", "the", "command" ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/downloaders.py#L89-L102
[ "def", "_prepare_cookies", "(", "self", ",", "command", ",", "url", ")", ":", "req", "=", "requests", ".", "models", ".", "Request", "(", ")", "req", ".", "method", "=", "'GET'", "req", ".", "url", "=", "url", "cookie_values", "=", "requests", ".", "...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
DownloadProgress.report_progress
Report download progress.
coursera/downloaders.py
def report_progress(self): """Report download progress.""" percent = self.calc_percent() total = format_bytes(self._total) speed = self.calc_speed() total_speed_report = '{0} at {1}'.format(total, speed) report = '\r{0: <56} {1: >30}'.format(percent, total_speed_report)...
def report_progress(self): """Report download progress.""" percent = self.calc_percent() total = format_bytes(self._total) speed = self.calc_speed() total_speed_report = '{0} at {1}'.format(total, speed) report = '\r{0: <56} {1: >30}'.format(percent, total_speed_report)...
[ "Report", "download", "progress", "." ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/downloaders.py#L285-L299
[ "def", "report_progress", "(", "self", ")", ":", "percent", "=", "self", ".", "calc_percent", "(", ")", "total", "=", "format_bytes", "(", "self", ".", "_total", ")", "speed", "=", "self", ".", "calc_speed", "(", ")", "total_speed_report", "=", "'{0} at {1...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
AbstractDownloader._download_wrapper
Actual download call. Calls the underlying file downloader, catches all exceptions and returns the result.
coursera/parallel.py
def _download_wrapper(self, url, *args, **kwargs): """ Actual download call. Calls the underlying file downloader, catches all exceptions and returns the result. """ try: return url, self._file_downloader.download(url, *args, **kwargs) except Exception as e: ...
def _download_wrapper(self, url, *args, **kwargs): """ Actual download call. Calls the underlying file downloader, catches all exceptions and returns the result. """ try: return url, self._file_downloader.download(url, *args, **kwargs) except Exception as e: ...
[ "Actual", "download", "call", ".", "Calls", "the", "underlying", "file", "downloader", "catches", "all", "exceptions", "and", "returns", "the", "result", "." ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/parallel.py#L26-L35
[ "def", "_download_wrapper", "(", "self", ",", "url", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "url", ",", "self", ".", "_file_downloader", ".", "download", "(", "url", ",", "*", "args", ",", "*", "*", "kwargs", ")"...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
get_config_paths
Return a list of config files paths to try in order, given config file name and possibly a user-specified path. For Windows platforms, there are several paths that can be tried to retrieve the netrc file. There is, however, no "standard way" of doing things. A brief recap of the situation (all fil...
coursera/credentials.py
def get_config_paths(config_name): # pragma: no test """ Return a list of config files paths to try in order, given config file name and possibly a user-specified path. For Windows platforms, there are several paths that can be tried to retrieve the netrc file. There is, however, no "standard way"...
def get_config_paths(config_name): # pragma: no test """ Return a list of config files paths to try in order, given config file name and possibly a user-specified path. For Windows platforms, there are several paths that can be tried to retrieve the netrc file. There is, however, no "standard way"...
[ "Return", "a", "list", "of", "config", "files", "paths", "to", "try", "in", "order", "given", "config", "file", "name", "and", "possibly", "a", "user", "-", "specified", "path", "." ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/credentials.py#L37-L110
[ "def", "get_config_paths", "(", "config_name", ")", ":", "# pragma: no test", "if", "platform", ".", "system", "(", ")", "!=", "'Windows'", ":", "return", "[", "None", "]", "# Now, we only treat the case of Windows", "env_vars", "=", "[", "[", "\"HOME\"", "]", "...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
authenticate_through_netrc
Return the tuple user / password given a path for the .netrc file. Raises CredentialsError if no valid netrc file is found.
coursera/credentials.py
def authenticate_through_netrc(path=None): """ Return the tuple user / password given a path for the .netrc file. Raises CredentialsError if no valid netrc file is found. """ errors = [] netrc_machine = 'coursera-dl' paths = [path] if path else get_config_paths("netrc") for path in path...
def authenticate_through_netrc(path=None): """ Return the tuple user / password given a path for the .netrc file. Raises CredentialsError if no valid netrc file is found. """ errors = [] netrc_machine = 'coursera-dl' paths = [path] if path else get_config_paths("netrc") for path in path...
[ "Return", "the", "tuple", "user", "/", "password", "given", "a", "path", "for", "the", ".", "netrc", "file", "." ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/credentials.py#L113-L138
[ "def", "authenticate_through_netrc", "(", "path", "=", "None", ")", ":", "errors", "=", "[", "]", "netrc_machine", "=", "'coursera-dl'", "paths", "=", "[", "path", "]", "if", "path", "else", "get_config_paths", "(", "\"netrc\"", ")", "for", "path", "in", "...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d
train
get_credentials
Return valid username, password tuple. Raises CredentialsError if username or password is missing.
coursera/credentials.py
def get_credentials(username=None, password=None, netrc=None, use_keyring=False): """ Return valid username, password tuple. Raises CredentialsError if username or password is missing. """ if netrc: path = None if netrc is True else netrc return authenticate_through_netrc(path) ...
def get_credentials(username=None, password=None, netrc=None, use_keyring=False): """ Return valid username, password tuple. Raises CredentialsError if username or password is missing. """ if netrc: path = None if netrc is True else netrc return authenticate_through_netrc(path) ...
[ "Return", "valid", "username", "password", "tuple", "." ]
coursera-dl/coursera-dl
python
https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/credentials.py#L141-L164
[ "def", "get_credentials", "(", "username", "=", "None", ",", "password", "=", "None", ",", "netrc", "=", "None", ",", "use_keyring", "=", "False", ")", ":", "if", "netrc", ":", "path", "=", "None", "if", "netrc", "is", "True", "else", "netrc", "return"...
9b434bcf3c4011bf3181429fe674633ae5fb7d4d