index int64 0 50.7k | project_path stringclasses 279
values | completion_path stringlengths 57 199 | signature_postion stringlengths 3 11 | class_position stringlengths 3 11 | function_name stringlengths 1 62 | class_name stringlengths 0 55 | body_position stringlengths 3 11 | body_position_with_comments stringlengths 3 11 | masked_class stringlengths 14 8.32k | masked_class_with_comment stringlengths 14 8.32k | func_body stringlengths 9 6.72k | func_body_with_comment stringlengths 9 6.72k | len_func_body int64 1 643 | len_input int64 10 2.02k | len_output int64 4 1.9k | total int64 20 2.05k | file_code stringlengths 14 442k | file_code_with_comment stringlengths 14 442k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
23,463 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/encoders/timm_sknet.py | 27,28 | 7,43 | forward | SkNetEncoder | 28,37 | 28,37 | class SkNetEncoder(ResNet, EncoderMixin):
def __init__(self, out_channels, depth=5, **kwargs):
super().__init__(**kwargs)
self._depth = depth
self._out_channels = out_channels
self._in_channels = 3
del self.fc
del self.global_pool
def get_stages(self):
r... | class SkNetEncoder(ResNet, EncoderMixin):
def __init__(self, out_channels, depth=5, **kwargs):
super().__init__(**kwargs)
self._depth = depth
self._out_channels = out_channels
self._in_channels = 3
del self.fc
del self.global_pool
def get_stages(self):
r... | stages = self.get_stages()
features = []
for i in range(self._depth + 1):
x = stages[i](x)
features.append(x)
return features
| stages = self.get_stages()
features = []
for i in range(self._depth + 1):
x = stages[i](x)
features.append(x)
return features
| 18 | 265 | 63 | 328 | from ._base import EncoderMixin
from timm.models.resnet import ResNet
from timm.models.sknet import SelectiveKernelBottleneck, SelectiveKernelBasic
import torch.nn as nn
class SkNetEncoder(ResNet, EncoderMixin):
def __init__(self, out_channels, depth=5, **kwargs):
super().__init__(**kwargs)
self._... | from ._base import EncoderMixin
from timm.models.resnet import ResNet
from timm.models.sknet import SelectiveKernelBottleneck, SelectiveKernelBasic
import torch.nn as nn
class SkNetEncoder(ResNet, EncoderMixin):
def __init__(self, out_channels, depth=5, **kwargs):
super().__init__(**kwargs)
self._... |
23,464 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/encoders/timm_universal.py | 29,30 | 5,43 | forward | TimmUniversalEncoder | 30,36 | 30,36 | class TimmUniversalEncoder(nn.Module):
def __init__(self, name, pretrained=True, in_channels=3, depth=5, output_stride=32):
super().__init__()
kwargs = dict(
in_chans=in_channels,
features_only=True,
output_stride=output_stride,
pretrained=pretrained,
... | class TimmUniversalEncoder(nn.Module):
def __init__(self, name, pretrained=True, in_channels=3, depth=5, output_stride=32):
super().__init__()
kwargs = dict(
in_chans=in_channels,
features_only=True,
output_stride=output_stride,
pretrained=pretrained,
... | features = self.model(x)
features = [
x,
] + features
return features
| features = self.model(x)
features = [
x,
] + features
return features
| 12 | 324 | 35 | 359 | import timm
import torch.nn as nn
class TimmUniversalEncoder(nn.Module):
def __init__(self, name, pretrained=True, in_channels=3, depth=5, output_stride=32):
super().__init__()
kwargs = dict(
in_chans=in_channels,
features_only=True,
output_stride=output_stride,... | import timm
import torch.nn as nn
class TimmUniversalEncoder(nn.Module):
def __init__(self, name, pretrained=True, in_channels=3, depth=5, output_stride=32):
super().__init__()
kwargs = dict(
in_chans=in_channels,
features_only=True,
output_stride=output_stride,... |
23,465 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/encoders/vgg.py | 75,76 | 43,83 | load_state_dict | VGGEncoder | 76,83 | 76,83 | class VGGEncoder(VGG, EncoderMixin):
def __init__(self, out_channels, config, batch_norm=False, depth=5, **kwargs):
super().__init__(make_layers(config, batch_norm=batch_norm), **kwargs)
self._out_channels = out_channels
self._depth = depth
self._in_channels = 3
del self.clas... | class VGGEncoder(VGG, EncoderMixin):
def __init__(self, out_channels, config, batch_norm=False, depth=5, **kwargs):
super().__init__(make_layers(config, batch_norm=batch_norm), **kwargs)
self._out_channels = out_channels
self._depth = depth
self._in_channels = 3
del self.clas... | keys = list(state_dict.keys())
for k in keys:
if k.startswith("classifier"):
state_dict.pop(k, None)
super().load_state_dict(state_dict, **kwargs)
| keys = list(state_dict.keys())
for k in keys:
if k.startswith("classifier"):
state_dict.pop(k, None)
super().load_state_dict(state_dict, **kwargs)
| 13 | 346 | 70 | 416 | """Each encoder should have following attributes and methods and be inherited from `_base.EncoderMixin`
Attributes:
_out_channels (list of int): specify number of channels for each encoder feature tensor
_depth (int): specify number of stages in decoder (in other words number of downsampling operations)
_... | """Each encoder should have following attributes and methods and be inherited from `_base.EncoderMixin`
Attributes:
_out_channels (list of int): specify number of channels for each encoder feature tensor
_depth (int): specify number of stages in decoder (in other words number of downsampling operations)
_... |
23,466 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/encoders/xception.py | 59,60 | 10,67 | load_state_dict | XceptionEncoder | 60,67 | 60,67 | class XceptionEncoder(Xception, EncoderMixin):
def __init__(self, out_channels, *args, depth=5, **kwargs):
super().__init__(*args, **kwargs)
self._out_channels = out_channels
self._depth = depth
self._in_channels = 3
# modify padding to maintain output shape
self.co... | class XceptionEncoder(Xception, EncoderMixin):
def __init__(self, out_channels, *args, depth=5, **kwargs):
super().__init__(*args, **kwargs)
self._out_channels = out_channels
self._depth = depth
self._in_channels = 3
# modify padding to maintain output shape
self.co... | # remove linear
state_dict.pop("fc.bias", None)
state_dict.pop("fc.weight", None)
super().load_state_dict(state_dict)
| # remove linear
state_dict.pop("fc.bias", None)
state_dict.pop("fc.weight", None)
super().load_state_dict(state_dict)
| 8 | 464 | 58 | 522 | import re
import torch.nn as nn
from pretrainedmodels.models.xception import pretrained_settings
from pretrainedmodels.models.xception import Xception
from ._base import EncoderMixin
class XceptionEncoder(Xception, EncoderMixin):
def __init__(self, out_channels, *args, depth=5, **kwargs):
super().__init... | import re
import torch.nn as nn
from pretrainedmodels.models.xception import pretrained_settings
from pretrainedmodels.models.xception import Xception
from ._base import EncoderMixin
class XceptionEncoder(Xception, EncoderMixin):
def __init__(self, out_channels, *args, depth=5, **kwargs):
super().__init... |
23,467 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/losses/dice.py | 57,58 | 12,131 | forward | DiceLoss | 58,126 | 58,126 | class DiceLoss(_Loss):
def __init__(
self,
mode: str,
classes: Optional[List[int]] = None,
log_loss: bool = False,
from_logits: bool = True,
smooth: float = 0.0,
ignore_index: Optional[int] = None,
eps: float = 1e-7,
):
"""Dice loss for ima... | class DiceLoss(_Loss):
def __init__(
self,
mode: str,
classes: Optional[List[int]] = None,
log_loss: bool = False,
from_logits: bool = True,
smooth: float = 0.0,
ignore_index: Optional[int] = None,
eps: float = 1e-7,
):
"""Dice loss for ima... |
assert y_true.size(0) == y_pred.size(0)
if self.from_logits:
# Apply activations to get [0..1] class probabilities
# Using Log-Exp as this gives more numerically stable result and does not cause vanishing gradient on
# extreme values 0 and 1
if self.mode... |
assert y_true.size(0) == y_pred.size(0)
if self.from_logits:
# Apply activations to get [0..1] class probabilities
# Using Log-Exp as this gives more numerically stable result and does not cause vanishing gradient on
# extreme values 0 and 1
if self.mode... | 276 | 661 | 938 | 1,599 | from typing import Optional, List
import torch
import torch.nn.functional as F
from torch.nn.modules.loss import _Loss
from ._functional import soft_dice_score, to_tensor
from .constants import BINARY_MODE, MULTICLASS_MODE, MULTILABEL_MODE
__all__ = ["DiceLoss"]
class DiceLoss(_Loss):
def __init__(
self... | from typing import Optional, List
import torch
import torch.nn.functional as F
from torch.nn.modules.loss import _Loss
from ._functional import soft_dice_score, to_tensor
from .constants import BINARY_MODE, MULTICLASS_MODE, MULTILABEL_MODE
__all__ = ["DiceLoss"]
class DiceLoss(_Loss):
def __init__(
self... |
23,468 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/losses/focal.py | 57,58 | 12,91 | forward | FocalLoss | 58,91 | 58,91 | class FocalLoss(_Loss):
def __init__(
self,
mode: str,
alpha: Optional[float] = None,
gamma: Optional[float] = 2.0,
ignore_index: Optional[int] = None,
reduction: Optional[str] = "mean",
normalized: bool = False,
reduced_threshold: Optional[float] = No... | class FocalLoss(_Loss):
def __init__(
self,
mode: str,
alpha: Optional[float] = None,
gamma: Optional[float] = 2.0,
ignore_index: Optional[int] = None,
reduction: Optional[str] = "mean",
normalized: bool = False,
reduced_threshold: Optional[float] = No... |
if self.mode in {BINARY_MODE, MULTILABEL_MODE}:
y_true = y_true.view(-1)
y_pred = y_pred.view(-1)
if self.ignore_index is not None:
# Filter predictions with ignore label from loss computation
not_ignored = y_true != self.ignore_index
... |
if self.mode in {BINARY_MODE, MULTILABEL_MODE}:
y_true = y_true.view(-1)
y_pred = y_pred.view(-1)
if self.ignore_index is not None:
# Filter predictions with ignore label from loss computation
not_ignored = y_true != self.ignore_index
... | 100 | 521 | 393 | 914 | from typing import Optional
from functools import partial
import torch
from torch.nn.modules.loss import _Loss
from ._functional import focal_loss_with_logits
from .constants import BINARY_MODE, MULTICLASS_MODE, MULTILABEL_MODE
__all__ = ["FocalLoss"]
class FocalLoss(_Loss):
def __init__(
self,
... | from typing import Optional
from functools import partial
import torch
from torch.nn.modules.loss import _Loss
from ._functional import focal_loss_with_logits
from .constants import BINARY_MODE, MULTICLASS_MODE, MULTILABEL_MODE
__all__ = ["FocalLoss"]
class FocalLoss(_Loss):
def __init__(
self,
... |
23,469 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/losses/jaccard.py | 55,56 | 12,112 | forward | JaccardLoss | 56,112 | 56,112 | class JaccardLoss(_Loss):
def __init__(
self,
mode: str,
classes: Optional[List[int]] = None,
log_loss: bool = False,
from_logits: bool = True,
smooth: float = 0.0,
eps: float = 1e-7,
):
"""Jaccard loss for image segmentation task.
It suppo... | class JaccardLoss(_Loss):
def __init__(
self,
mode: str,
classes: Optional[List[int]] = None,
log_loss: bool = False,
from_logits: bool = True,
smooth: float = 0.0,
eps: float = 1e-7,
):
"""Jaccard loss for image segmentation task.
It suppo... |
assert y_true.size(0) == y_pred.size(0)
if self.from_logits:
# Apply activations to get [0..1] class probabilities
# Using Log-Exp as this gives more numerically stable result and does not cause vanishing gradient on
# extreme values 0 and 1
if self.mode... |
assert y_true.size(0) == y_pred.size(0)
if self.from_logits:
# Apply activations to get [0..1] class probabilities
# Using Log-Exp as this gives more numerically stable result and does not cause vanishing gradient on
# extreme values 0 and 1
if self.mode... | 200 | 542 | 696 | 1,238 | from typing import Optional, List
import torch
import torch.nn.functional as F
from torch.nn.modules.loss import _Loss
from ._functional import soft_jaccard_score, to_tensor
from .constants import BINARY_MODE, MULTICLASS_MODE, MULTILABEL_MODE
__all__ = ["JaccardLoss"]
class JaccardLoss(_Loss):
def __init__(
... | from typing import Optional, List
import torch
import torch.nn.functional as F
from torch.nn.modules.loss import _Loss
from ._functional import soft_jaccard_score, to_tensor
from .constants import BINARY_MODE, MULTICLASS_MODE, MULTILABEL_MODE
__all__ = ["JaccardLoss"]
class JaccardLoss(_Loss):
def __init__(
... |
23,471 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/losses/lovasz.py | 216,217 | 186,226 | forward | LovaszLoss | 217,226 | 217,226 | class LovaszLoss(_Loss):
def __init__(
self,
mode: str,
per_image: bool = False,
ignore_index: Optional[int] = None,
from_logits: bool = True,
):
"""Lovasz loss for image segmentation task.
It supports binary, multiclass and multilabel cases
Args:... | class LovaszLoss(_Loss):
def __init__(
self,
mode: str,
per_image: bool = False,
ignore_index: Optional[int] = None,
from_logits: bool = True,
):
"""Lovasz loss for image segmentation task.
It supports binary, multiclass and multilabel cases
Args:... |
if self.mode in {BINARY_MODE, MULTILABEL_MODE}:
loss = _lovasz_hinge(y_pred, y_true, per_image=self.per_image, ignore=self.ignore_index)
elif self.mode == MULTICLASS_MODE:
y_pred = y_pred.softmax(dim=1)
loss = _lovasz_softmax(y_pred, y_true, per_image=self.per_image,... |
if self.mode in {BINARY_MODE, MULTILABEL_MODE}:
loss = _lovasz_hinge(y_pred, y_true, per_image=self.per_image, ignore=self.ignore_index)
elif self.mode == MULTICLASS_MODE:
y_pred = y_pred.softmax(dim=1)
loss = _lovasz_softmax(y_pred, y_true, per_image=self.per_image,... | 31 | 341 | 165 | 506 | """
Lovasz-Softmax and Jaccard hinge loss in PyTorch
Maxim Berman 2018 ESAT-PSI KU Leuven (MIT License)
"""
from __future__ import print_function, division
from typing import Optional
import torch
import torch.nn.functional as F
from torch.nn.modules.loss import _Loss
from .constants import BINARY_MODE, MULTICLASS_MO... | """
Lovasz-Softmax and Jaccard hinge loss in PyTorch
Maxim Berman 2018 ESAT-PSI KU Leuven (MIT License)
"""
from __future__ import print_function, division
from typing import Optional
import torch
import torch.nn.functional as F
from torch.nn.modules.loss import _Loss
from .constants import BINARY_MODE, MULTICLASS_MO... |
23,472 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/losses/mcc.py | 19,20 | 5,47 | forward | MCCLoss | 29,47 | 20,47 | class MCCLoss(_Loss):
def __init__(self, eps: float = 1e-5):
"""Compute Matthews Correlation Coefficient Loss for image segmentation task.
It only supports binary mode.
Args:
eps (float): Small epsilon to handle situations where all the samples in the dataset belong to one class... | class MCCLoss(_Loss):
def __init__(self, eps: float = 1e-5):
"""Compute Matthews Correlation Coefficient Loss for image segmentation task.
It only supports binary mode.
Args:
eps (float): Small epsilon to handle situations where all the samples in the dataset belong to one class... |
bs = y_true.shape[0]
y_true = y_true.view(bs, 1, -1)
y_pred = y_pred.view(bs, 1, -1)
tp = torch.sum(torch.mul(y_pred, y_true)) + self.eps
tn = torch.sum(torch.mul((1 - y_pred), (1 - y_true))) + self.eps
fp = torch.sum(torch.mul(y_pred, (1 - y_true))) + self.eps
... | """Compute MCC loss
Args:
y_pred (torch.Tensor): model prediction of shape (N, H, W) or (N, 1, H, W)
y_true (torch.Tensor): ground truth labels of shape (N, H, W) or (N, 1, H, W)
Returns:
torch.Tensor: loss value (1 - mcc)
"""
bs = y_true.sh... | 76 | 284 | 310 | 594 | import torch
from torch.nn.modules.loss import _Loss
class MCCLoss(_Loss):
def __init__(self, eps: float = 1e-5):
"""Compute Matthews Correlation Coefficient Loss for image segmentation task.
It only supports binary mode.
Args:
eps (float): Small epsilon to handle situations w... | import torch
from torch.nn.modules.loss import _Loss
class MCCLoss(_Loss):
def __init__(self, eps: float = 1e-5):
"""Compute Matthews Correlation Coefficient Loss for image segmentation task.
It only supports binary mode.
Args:
eps (float): Small epsilon to handle situations w... |
23,473 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/losses/soft_bce.py | 49,50 | 10,83 | forward | SoftBCEWithLogitsLoss | 58,83 | 50,83 | class SoftBCEWithLogitsLoss(nn.Module):
__constants__ = [
"weight",
"pos_weight",
"reduction",
"ignore_index",
"smooth_factor",
]
def __init__(
self,
weight: Optional[torch.Tensor] = None,
ignore_index: Optional[int] = -100,
reduction... | class SoftBCEWithLogitsLoss(nn.Module):
__constants__ = [
"weight",
"pos_weight",
"reduction",
"ignore_index",
"smooth_factor",
]
def __init__(
self,
weight: Optional[torch.Tensor] = None,
ignore_index: Optional[int] = -100,
reduction... |
if self.smooth_factor is not None:
soft_targets = (1 - y_true) * self.smooth_factor + y_true * (1 - self.smooth_factor)
else:
soft_targets = y_true
loss = F.binary_cross_entropy_with_logits(
y_pred,
soft_targets,
self.weight,
... | """
Args:
y_pred: torch.Tensor of shape (N, C, H, W)
y_true: torch.Tensor of shape (N, H, W) or (N, 1, H, W)
Returns:
loss: torch.Tensor
"""
if self.smooth_factor is not None:
soft_targets = (1 - y_true) * self.smooth_factor + y_... | 60 | 533 | 241 | 774 | from typing import Optional
import torch
import torch.nn.functional as F
from torch import nn, Tensor
__all__ = ["SoftBCEWithLogitsLoss"]
class SoftBCEWithLogitsLoss(nn.Module):
__constants__ = [
"weight",
"pos_weight",
"reduction",
"ignore_index",
"smooth_factor",
]... | from typing import Optional
import torch
import torch.nn.functional as F
from torch import nn, Tensor
__all__ = ["SoftBCEWithLogitsLoss"]
class SoftBCEWithLogitsLoss(nn.Module):
__constants__ = [
"weight",
"pos_weight",
"reduction",
"ignore_index",
"smooth_factor",
]... |
23,474 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/losses/soft_ce.py | 39,40 | 10,49 | forward | SoftCrossEntropyLoss | 40,49 | 40,49 | class SoftCrossEntropyLoss(nn.Module):
__constants__ = ["reduction", "ignore_index", "smooth_factor"]
def __init__(
self,
reduction: str = "mean",
smooth_factor: Optional[float] = None,
ignore_index: Optional[int] = -100,
dim: int = 1,
):
"""Drop-in replacem... | class SoftCrossEntropyLoss(nn.Module):
__constants__ = ["reduction", "ignore_index", "smooth_factor"]
def __init__(
self,
reduction: str = "mean",
smooth_factor: Optional[float] = None,
ignore_index: Optional[int] = -100,
dim: int = 1,
):
"""Drop-in replacem... | log_prob = F.log_softmax(y_pred, dim=self.dim)
return label_smoothed_nll_loss(
log_prob,
y_true,
epsilon=self.smooth_factor,
ignore_index=self.ignore_index,
reduction=self.reduction,
dim=self.dim,
)
| log_prob = F.log_softmax(y_pred, dim=self.dim)
return label_smoothed_nll_loss(
log_prob,
y_true,
epsilon=self.smooth_factor,
ignore_index=self.ignore_index,
reduction=self.reduction,
dim=self.dim,
)
| 13 | 349 | 101 | 450 | from typing import Optional
from torch import nn, Tensor
import torch
import torch.nn.functional as F
from ._functional import label_smoothed_nll_loss
__all__ = ["SoftCrossEntropyLoss"]
class SoftCrossEntropyLoss(nn.Module):
__constants__ = ["reduction", "ignore_index", "smooth_factor"]
def __init__(
... | from typing import Optional
from torch import nn, Tensor
import torch
import torch.nn.functional as F
from ._functional import label_smoothed_nll_loss
__all__ = ["SoftCrossEntropyLoss"]
class SoftCrossEntropyLoss(nn.Module):
__constants__ = ["reduction", "ignore_index", "smooth_factor"]
def __init__(
... |
23,475 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/losses/tversky.py | 58,59 | 11,60 | compute_score | TverskyLoss | 59,60 | 59,60 | class TverskyLoss(DiceLoss):
"""Tversky loss for image segmentation task.
Where FP and FN is weighted by alpha and beta params.
With alpha == beta == 0.5, this loss becomes equal DiceLoss.
It supports binary, multiclass and multilabel cases
Args:
mode: Metric mode {'binary', 'multiclass', '... | class TverskyLoss(DiceLoss):
"""Tversky loss for image segmentation task.
Where FP and FN is weighted by alpha and beta params.
With alpha == beta == 0.5, this loss becomes equal DiceLoss.
It supports binary, multiclass and multilabel cases
Args:
mode: Metric mode {'binary', 'multiclass', '... | return soft_tversky_score(output, target, self.alpha, self.beta, smooth, eps, dims)
| return soft_tversky_score(output, target, self.alpha, self.beta, smooth, eps, dims)
| 8 | 545 | 32 | 577 | from typing import List, Optional
import torch
from ._functional import soft_tversky_score
from .constants import BINARY_MODE, MULTICLASS_MODE, MULTILABEL_MODE
from .dice import DiceLoss
__all__ = ["TverskyLoss"]
class TverskyLoss(DiceLoss):
"""Tversky loss for image segmentation task.
Where FP and FN is we... | from typing import List, Optional
import torch
from ._functional import soft_tversky_score
from .constants import BINARY_MODE, MULTICLASS_MODE, MULTILABEL_MODE
from .dice import DiceLoss
__all__ = ["TverskyLoss"]
class TverskyLoss(DiceLoss):
"""Tversky loss for image segmentation task.
Where FP and FN is we... |
23,477 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/utils/functional.py | 42,43 | 1,126 | f_score | 53,66 | 43,66 | import torch
def _take_channels(*xs, ignore_channels=None):
if ignore_channels is None:
return xs
else:
channels = [channel for channel in range(xs[0].shape[1]) if channel not in ignore_channels]
xs = [torch.index_select(x, dim=1, index=torch.tensor(channels).to(x.device)) for x in xs]... | import torch
def _take_channels(*xs, ignore_channels=None):
if ignore_channels is None:
return xs
else:
channels = [channel for channel in range(xs[0].shape[1]) if channel not in ignore_channels]
xs = [torch.index_select(x, dim=1, index=torch.tensor(channels).to(x.device)) for x in xs]... |
pr = _threshold(pr, threshold=threshold)
pr, gt = _take_channels(pr, gt, ignore_channels=ignore_channels)
tp = torch.sum(gt * pr)
fp = torch.sum(pr) - tp
fn = torch.sum(gt) - tp
score = ((1 + beta**2) * tp + eps) / ((1 + beta**2) * tp + beta**2 * fn + fp + eps)
return score
| """Calculate F-score between ground truth and prediction
Args:
pr (torch.Tensor): predicted tensor
gt (torch.Tensor): ground truth tensor
beta (float): positive constant
eps (float): epsilon to avoid zero division
threshold: threshold for outputs binarization
Returns... | 50 | 1,135 | 151 | 1,286 | import torch
def _take_channels(*xs, ignore_channels=None):
if ignore_channels is None:
return xs
else:
channels = [channel for channel in range(xs[0].shape[1]) if channel not in ignore_channels]
xs = [torch.index_select(x, dim=1, index=torch.tensor(channels).to(x.device)) for x in xs]... | import torch
def _take_channels(*xs, ignore_channels=None):
if ignore_channels is None:
return xs
else:
channels = [channel for channel in range(xs[0].shape[1]) if channel not in ignore_channels]
xs = [torch.index_select(x, dim=1, index=torch.tensor(channels).to(x.device)) for x in xs]... | |
23,478 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/utils/losses.py | 34,35 | 26,46 | forward | DiceLoss | 35,46 | 35,46 | class DiceLoss(base.Loss):
def __init__(self, eps=1.0, beta=1.0, activation=None, ignore_channels=None, **kwargs):
super().__init__(**kwargs)
self.eps = eps
self.beta = beta
self.activation = Activation(activation)
self.ignore_channels = ignore_channels
def forward(self,... | class DiceLoss(base.Loss):
def __init__(self, eps=1.0, beta=1.0, activation=None, ignore_channels=None, **kwargs):
super().__init__(**kwargs)
self.eps = eps
self.beta = beta
self.activation = Activation(activation)
self.ignore_channels = ignore_channels
def forward(self,... | y_pr = self.activation(y_pr)
return 1 - F.f_score(
y_pr,
y_gt,
beta=self.beta,
eps=self.eps,
threshold=None,
ignore_channels=self.ignore_channels,
)
| y_pr = self.activation(y_pr)
return 1 - F.f_score(
y_pr,
y_gt,
beta=self.beta,
eps=self.eps,
threshold=None,
ignore_channels=self.ignore_channels,
)
| 14 | 124 | 92 | 216 | import torch.nn as nn
from . import base
from . import functional as F
from ..base.modules import Activation
class JaccardLoss(base.Loss):
def __init__(self, eps=1.0, activation=None, ignore_channels=None, **kwargs):
super().__init__(**kwargs)
self.eps = eps
self.activation = Activation(a... | import torch.nn as nn
from . import base
from . import functional as F
from ..base.modules import Activation
class JaccardLoss(base.Loss):
def __init__(self, eps=1.0, activation=None, ignore_channels=None, **kwargs):
super().__init__(**kwargs)
self.eps = eps
self.activation = Activation(a... |
23,479 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/utils/losses.py | 15,16 | 8,26 | forward | JaccardLoss | 16,26 | 16,26 | class JaccardLoss(base.Loss):
def __init__(self, eps=1.0, activation=None, ignore_channels=None, **kwargs):
super().__init__(**kwargs)
self.eps = eps
self.activation = Activation(activation)
self.ignore_channels = ignore_channels
def forward(self, y_pr, y_gt):
FILL_FUNC_BODY | class JaccardLoss(base.Loss):
def __init__(self, eps=1.0, activation=None, ignore_channels=None, **kwargs):
super().__init__(**kwargs)
self.eps = eps
self.activation = Activation(activation)
self.ignore_channels = ignore_channels
def forward(self, y_pr, y_gt):
FILL_FUNC_BODY | y_pr = self.activation(y_pr)
return 1 - F.jaccard(
y_pr,
y_gt,
eps=self.eps,
threshold=None,
ignore_channels=self.ignore_channels,
)
| y_pr = self.activation(y_pr)
return 1 - F.jaccard(
y_pr,
y_gt,
eps=self.eps,
threshold=None,
ignore_channels=self.ignore_channels,
)
| 13 | 112 | 83 | 195 | import torch.nn as nn
from . import base
from . import functional as F
from ..base.modules import Activation
class JaccardLoss(base.Loss):
def __init__(self, eps=1.0, activation=None, ignore_channels=None, **kwargs):
super().__init__(**kwargs)
self.eps = eps
self.activation = Activation(a... | import torch.nn as nn
from . import base
from . import functional as F
from ..base.modules import Activation
class JaccardLoss(base.Loss):
def __init__(self, eps=1.0, activation=None, ignore_channels=None, **kwargs):
super().__init__(**kwargs)
self.eps = eps
self.activation = Activation(a... |
23,480 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/utils/meter.py | 31,32 | 25,62 | add | AverageValueMeter | 32,50 | 32,50 | class AverageValueMeter(Meter):
def __init__(self):
super(AverageValueMeter, self).__init__()
self.reset()
self.val = 0
def add(self, value, n=1):
FILL_FUNC_BODY def value(self):
return self.mean, self.std
def reset(self):
self.n = 0
self.sum = 0.0
... | class AverageValueMeter(Meter):
def __init__(self):
super(AverageValueMeter, self).__init__()
self.reset()
self.val = 0
def add(self, value, n=1):
FILL_FUNC_BODY def value(self):
return self.mean, self.std
def reset(self):
self.n = 0
self.sum = 0.0
... | self.val = value
self.sum += value
self.var += value * value
self.n += n
if self.n == 0:
self.mean, self.std = np.nan, np.nan
elif self.n == 1:
self.mean = 0.0 + self.sum # This is to force a copy in torch/numpy
self.std = np.inf
... | self.val = value
self.sum += value
self.var += value * value
self.n += n
if self.n == 0:
self.mean, self.std = np.nan, np.nan
elif self.n == 1:
self.mean = 0.0 + self.sum # This is to force a copy in torch/numpy
self.std = np.inf
... | 81 | 171 | 240 | 411 | import numpy as np
class Meter(object):
"""Meters provide a way to keep track of important statistics in an online manner.
This class is abstract, but provides a standard interface for all meters to follow.
"""
def reset(self):
"""Reset the meter to default settings."""
pass
def ... | import numpy as np
class Meter(object):
"""Meters provide a way to keep track of important statistics in an online manner.
This class is abstract, but provides a standard interface for all meters to follow.
"""
def reset(self):
"""Reset the meter to default settings."""
pass
def ... |
23,481 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/utils/metrics.py | 55,56 | 48,65 | forward | Accuracy | 56,65 | 56,65 | class Accuracy(base.Metric):
def __init__(self, threshold=0.5, activation=None, ignore_channels=None, **kwargs):
super().__init__(**kwargs)
self.threshold = threshold
self.activation = Activation(activation)
self.ignore_channels = ignore_channels
def forward(self, y_pr, y_gt):
F... | class Accuracy(base.Metric):
def __init__(self, threshold=0.5, activation=None, ignore_channels=None, **kwargs):
super().__init__(**kwargs)
self.threshold = threshold
self.activation = Activation(activation)
self.ignore_channels = ignore_channels
def forward(self, y_pr, y_gt):
F... | y_pr = self.activation(y_pr)
return F.accuracy(
y_pr,
y_gt,
threshold=self.threshold,
ignore_channels=self.ignore_channels,
)
| y_pr = self.activation(y_pr)
return F.accuracy(
y_pr,
y_gt,
threshold=self.threshold,
ignore_channels=self.ignore_channels,
)
| 10 | 109 | 72 | 181 | from . import base
from . import functional as F
from ..base.modules import Activation
class IoU(base.Metric):
__name__ = "iou_score"
def __init__(self, eps=1e-7, threshold=0.5, activation=None, ignore_channels=None, **kwargs):
super().__init__(**kwargs)
self.eps = eps
self.threshold ... | from . import base
from . import functional as F
from ..base.modules import Activation
class IoU(base.Metric):
__name__ = "iou_score"
def __init__(self, eps=1e-7, threshold=0.5, activation=None, ignore_channels=None, **kwargs):
super().__init__(**kwargs)
self.eps = eps
self.threshold ... |
23,482 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/utils/metrics.py | 36,37 | 27,48 | forward | Fscore | 37,48 | 37,48 | class Fscore(base.Metric):
def __init__(self, beta=1, eps=1e-7, threshold=0.5, activation=None, ignore_channels=None, **kwargs):
super().__init__(**kwargs)
self.eps = eps
self.beta = beta
self.threshold = threshold
self.activation = Activation(activation)
self.ignore_... | class Fscore(base.Metric):
def __init__(self, beta=1, eps=1e-7, threshold=0.5, activation=None, ignore_channels=None, **kwargs):
super().__init__(**kwargs)
self.eps = eps
self.beta = beta
self.threshold = threshold
self.activation = Activation(activation)
self.ignore_... | y_pr = self.activation(y_pr)
return F.f_score(
y_pr,
y_gt,
eps=self.eps,
beta=self.beta,
threshold=self.threshold,
ignore_channels=self.ignore_channels,
)
| y_pr = self.activation(y_pr)
return F.f_score(
y_pr,
y_gt,
eps=self.eps,
beta=self.beta,
threshold=self.threshold,
ignore_channels=self.ignore_channels,
)
| 12 | 135 | 92 | 227 | from . import base
from . import functional as F
from ..base.modules import Activation
class IoU(base.Metric):
__name__ = "iou_score"
def __init__(self, eps=1e-7, threshold=0.5, activation=None, ignore_channels=None, **kwargs):
super().__init__(**kwargs)
self.eps = eps
self.threshold ... | from . import base
from . import functional as F
from ..base.modules import Activation
class IoU(base.Metric):
__name__ = "iou_score"
def __init__(self, eps=1e-7, threshold=0.5, activation=None, ignore_channels=None, **kwargs):
super().__init__(**kwargs)
self.eps = eps
self.threshold ... |
23,483 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/utils/metrics.py | 16,17 | 6,27 | forward | IoU | 17,27 | 17,27 | class IoU(base.Metric):
__name__ = "iou_score"
def __init__(self, eps=1e-7, threshold=0.5, activation=None, ignore_channels=None, **kwargs):
super().__init__(**kwargs)
self.eps = eps
self.threshold = threshold
self.activation = Activation(activation)
self.ignore_channels... | class IoU(base.Metric):
__name__ = "iou_score"
def __init__(self, eps=1e-7, threshold=0.5, activation=None, ignore_channels=None, **kwargs):
super().__init__(**kwargs)
self.eps = eps
self.threshold = threshold
self.activation = Activation(activation)
self.ignore_channels... | y_pr = self.activation(y_pr)
return F.iou(
y_pr,
y_gt,
eps=self.eps,
threshold=self.threshold,
ignore_channels=self.ignore_channels,
)
| y_pr = self.activation(y_pr)
return F.iou(
y_pr,
y_gt,
eps=self.eps,
threshold=self.threshold,
ignore_channels=self.ignore_channels,
)
| 11 | 137 | 82 | 219 | from . import base
from . import functional as F
from ..base.modules import Activation
class IoU(base.Metric):
__name__ = "iou_score"
def __init__(self, eps=1e-7, threshold=0.5, activation=None, ignore_channels=None, **kwargs):
super().__init__(**kwargs)
self.eps = eps
self.threshold ... | from . import base
from . import functional as F
from ..base.modules import Activation
class IoU(base.Metric):
__name__ = "iou_score"
def __init__(self, eps=1e-7, threshold=0.5, activation=None, ignore_channels=None, **kwargs):
super().__init__(**kwargs)
self.eps = eps
self.threshold ... |
23,484 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/utils/metrics.py | 92,93 | 84,101 | forward | Precision | 93,101 | 93,101 | class Precision(base.Metric):
def __init__(self, eps=1e-7, threshold=0.5, activation=None, ignore_channels=None, **kwargs):
super().__init__(**kwargs)
self.eps = eps
self.threshold = threshold
self.activation = Activation(activation)
self.ignore_channels = ignore_channels
... | class Precision(base.Metric):
def __init__(self, eps=1e-7, threshold=0.5, activation=None, ignore_channels=None, **kwargs):
super().__init__(**kwargs)
self.eps = eps
self.threshold = threshold
self.activation = Activation(activation)
self.ignore_channels = ignore_channels
... | y_pr = self.activation(y_pr)
return F.precision(
y_pr,
y_gt,
eps=self.eps,
threshold=self.threshold,
ignore_channels=self.ignore_channels,
)
| y_pr = self.activation(y_pr)
return F.precision(
y_pr,
y_gt,
eps=self.eps,
threshold=self.threshold,
ignore_channels=self.ignore_channels,
)
| 11 | 124 | 78 | 202 | from . import base
from . import functional as F
from ..base.modules import Activation
class IoU(base.Metric):
__name__ = "iou_score"
def __init__(self, eps=1e-7, threshold=0.5, activation=None, ignore_channels=None, **kwargs):
super().__init__(**kwargs)
self.eps = eps
self.threshold ... | from . import base
from . import functional as F
from ..base.modules import Activation
class IoU(base.Metric):
__name__ = "iou_score"
def __init__(self, eps=1e-7, threshold=0.5, activation=None, ignore_channels=None, **kwargs):
super().__init__(**kwargs)
self.eps = eps
self.threshold ... |
23,485 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/utils/metrics.py | 73,74 | 65,84 | forward | Recall | 74,84 | 74,84 | class Recall(base.Metric):
def __init__(self, eps=1e-7, threshold=0.5, activation=None, ignore_channels=None, **kwargs):
super().__init__(**kwargs)
self.eps = eps
self.threshold = threshold
self.activation = Activation(activation)
self.ignore_channels = ignore_channels
d... | class Recall(base.Metric):
def __init__(self, eps=1e-7, threshold=0.5, activation=None, ignore_channels=None, **kwargs):
super().__init__(**kwargs)
self.eps = eps
self.threshold = threshold
self.activation = Activation(activation)
self.ignore_channels = ignore_channels
d... | y_pr = self.activation(y_pr)
return F.recall(
y_pr,
y_gt,
eps=self.eps,
threshold=self.threshold,
ignore_channels=self.ignore_channels,
)
| y_pr = self.activation(y_pr)
return F.recall(
y_pr,
y_gt,
eps=self.eps,
threshold=self.threshold,
ignore_channels=self.ignore_channels,
)
| 11 | 124 | 82 | 206 | from . import base
from . import functional as F
from ..base.modules import Activation
class IoU(base.Metric):
__name__ = "iou_score"
def __init__(self, eps=1e-7, threshold=0.5, activation=None, ignore_channels=None, **kwargs):
super().__init__(**kwargs)
self.eps = eps
self.threshold ... | from . import base
from . import functional as F
from ..base.modules import Activation
class IoU(base.Metric):
__name__ = "iou_score"
def __init__(self, eps=1e-7, threshold=0.5, activation=None, ignore_channels=None, **kwargs):
super().__init__(**kwargs)
self.eps = eps
self.threshold ... |
23,486 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/utils/train.py | 24,25 | 7,73 | _format_logs | Epoch | 25,29 | 25,29 | class Epoch:
def __init__(self, model, loss, metrics, stage_name, device="cpu", verbose=True):
self.model = model
self.loss = loss
self.metrics = metrics
self.stage_name = stage_name
self.verbose = verbose
self.device = device
self._to_device()
def _to_d... | class Epoch:
def __init__(self, model, loss, metrics, stage_name, device="cpu", verbose=True):
self.model = model
self.loss = loss
self.metrics = metrics
self.stage_name = stage_name
self.verbose = verbose
self.device = device
self._to_device()
def _to_d... | str_logs = ["{} - {:.4}".format(k, v) for k, v in logs.items()]
s = ", ".join(str_logs)
return s
| str_logs = ["{} - {:.4}".format(k, v) for k, v in logs.items()]
s = ", ".join(str_logs)
return s
| 17 | 593 | 53 | 646 | import sys
import torch
from tqdm import tqdm as tqdm
from .meter import AverageValueMeter
class Epoch:
def __init__(self, model, loss, metrics, stage_name, device="cpu", verbose=True):
self.model = model
self.loss = loss
self.metrics = metrics
self.stage_name = stage_name
... | import sys
import torch
from tqdm import tqdm as tqdm
from .meter import AverageValueMeter
class Epoch:
def __init__(self, model, loss, metrics, stage_name, device="cpu", verbose=True):
self.model = model
self.loss = loss
self.metrics = metrics
self.stage_name = stage_name
... |
23,487 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/utils/train.py | 88,89 | 73,97 | batch_update | TrainEpoch | 89,97 | 89,97 | class TrainEpoch(Epoch):
def __init__(self, model, loss, metrics, optimizer, device="cpu", verbose=True):
super().__init__(
model=model,
loss=loss,
metrics=metrics,
stage_name="train",
device=device,
verbose=verbose,
)
s... | class TrainEpoch(Epoch):
def __init__(self, model, loss, metrics, optimizer, device="cpu", verbose=True):
super().__init__(
model=model,
loss=loss,
metrics=metrics,
stage_name="train",
device=device,
verbose=verbose,
)
s... | self.optimizer.zero_grad()
prediction = self.model.forward(x)
loss = self.loss(prediction, y)
loss.backward()
self.optimizer.step()
return loss, prediction
| self.optimizer.zero_grad()
prediction = self.model.forward(x)
loss = self.loss(prediction, y)
loss.backward()
self.optimizer.step()
return loss, prediction
| 13 | 142 | 68 | 210 | import sys
import torch
from tqdm import tqdm as tqdm
from .meter import AverageValueMeter
class Epoch:
def __init__(self, model, loss, metrics, stage_name, device="cpu", verbose=True):
self.model = model
self.loss = loss
self.metrics = metrics
self.stage_name = stage_name
... | import sys
import torch
from tqdm import tqdm as tqdm
from .meter import AverageValueMeter
class Epoch:
def __init__(self, model, loss, metrics, stage_name, device="cpu", verbose=True):
self.model = model
self.loss = loss
self.metrics = metrics
self.stage_name = stage_name
... |
23,488 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/segmentation_models_pytorch/utils/train.py | 111,112 | 97,116 | batch_update | ValidEpoch | 112,116 | 112,116 | class ValidEpoch(Epoch):
def __init__(self, model, loss, metrics, device="cpu", verbose=True):
super().__init__(
model=model,
loss=loss,
metrics=metrics,
stage_name="valid",
device=device,
verbose=verbose,
)
def on_epoch_st... | class ValidEpoch(Epoch):
def __init__(self, model, loss, metrics, device="cpu", verbose=True):
super().__init__(
model=model,
loss=loss,
metrics=metrics,
stage_name="valid",
device=device,
verbose=verbose,
)
def on_epoch_st... | with torch.no_grad():
prediction = self.model.forward(x)
loss = self.loss(prediction, y)
return loss, prediction
| with torch.no_grad():
prediction = self.model.forward(x)
loss = self.loss(prediction, y)
return loss, prediction
| 12 | 130 | 45 | 175 | import sys
import torch
from tqdm import tqdm as tqdm
from .meter import AverageValueMeter
class Epoch:
def __init__(self, model, loss, metrics, stage_name, device="cpu", verbose=True):
self.model = model
self.loss = loss
self.metrics = metrics
self.stage_name = stage_name
... | import sys
import torch
from tqdm import tqdm as tqdm
from .meter import AverageValueMeter
class Epoch:
def __init__(self, model, loss, metrics, stage_name, device="cpu", verbose=True):
self.model = model
self.loss = loss
self.metrics = metrics
self.stage_name = stage_name
... |
23,489 | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch | /home/hieuvd/dung_repo/raw/stars_01/qubvel_segmentation_models.pytorch/segmentation_models.pytorch/setup.py | 83,84 | 66,104 | run | UploadCommand | 84,104 | 84,104 | class UploadCommand(Command):
"""Support setup.py upload."""
description = "Build and publish the package."
user_options = []
@staticmethod
def status(s):
"""Prints things in bold."""
print(s)
def initialize_options(self):
pass
def finalize_options(self):
... | class UploadCommand(Command):
"""Support setup.py upload."""
description = "Build and publish the package."
user_options = []
@staticmethod
def status(s):
"""Prints things in bold."""
print(s)
def initialize_options(self):
pass
def finalize_options(self):
... | try:
self.status("Removing previous builds...")
rmtree(os.path.join(here, "dist"))
except OSError:
pass
self.status("Building Source and Wheel (universal) distribution...")
os.system("{0} setup.py sdist bdist_wheel --universal".format(sys.executable))... | try:
self.status("Removing previous builds...")
rmtree(os.path.join(here, "dist"))
except OSError:
pass
self.status("Building Source and Wheel (universal) distribution...")
os.system("{0} setup.py sdist bdist_wheel --universal".format(sys.executable))... | 45 | 109 | 204 | 313 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Note: To use the 'upload' functionality of this file, you must:
# $ pip install twine
import io
import os
import sys
from shutil import rmtree
from setuptools import find_packages, setup, Command
# Package meta-data.
NAME = "segmentation_models_pytorch"
DESCRIPTION ... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Note: To use the 'upload' functionality of this file, you must:
# $ pip install twine
import io
import os
import sys
from shutil import rmtree
from setuptools import find_packages, setup, Command
# Package meta-data.
NAME = "segmentation_models_pytorch"
DESCRIPTION ... |
23,491 | /home/hieuvd/dung_repo/raw/stars_01/ranaroussi_yfinance/yfinance | /home/hieuvd/dung_repo/raw/stars_01/ranaroussi_yfinance/yfinance/yfinance/scrapers/analysis.py | 33,35 | 7,50 | analyst_price_target | Analysis | 35,39 | 35,39 | class Analysis:
def __init__(self, data: YfData, symbol: str, proxy=None):
self._data = data
self._symbol = symbol
self.proxy = proxy
self._earnings_trend = None
self._analyst_trend_details = None
self._analyst_price_target = None
self._rev_est = None
... | class Analysis:
def __init__(self, data: YfData, symbol: str, proxy=None):
self._data = data
self._symbol = symbol
self.proxy = proxy
self._earnings_trend = None
self._analyst_trend_details = None
self._analyst_price_target = None
self._rev_est = None
... | if self._analyst_price_target is None:
raise YFNotImplementedError('analyst_price_target')
return self._analyst_price_target
| if self._analyst_price_target is None:
raise YFNotImplementedError('analyst_price_target')
return self._analyst_price_target
| 8 | 403 | 51 | 454 | import pandas as pd
from yfinance.data import YfData
from yfinance.exceptions import YFNotImplementedError
class Analysis:
def __init__(self, data: YfData, symbol: str, proxy=None):
self._data = data
self._symbol = symbol
self.proxy = proxy
self._earnings_trend = None
se... | import pandas as pd
from yfinance.data import YfData
from yfinance.exceptions import YFNotImplementedError
class Analysis:
def __init__(self, data: YfData, symbol: str, proxy=None):
self._data = data
self._symbol = symbol
self.proxy = proxy
self._earnings_trend = None
se... |
23,492 | /home/hieuvd/dung_repo/raw/stars_01/ranaroussi_yfinance/yfinance | /home/hieuvd/dung_repo/raw/stars_01/ranaroussi_yfinance/yfinance/yfinance/scrapers/fundamentals.py | 105,106 | 44,150 | get_financials_time_series | Financials | 106,150 | 106,150 | class Financials:
def __init__(self, data: YfData, symbol: str):
self._data = data
self._symbol = symbol
self._income_time_series = {}
self._balance_sheet_time_series = {}
self._cash_flow_time_series = {}
def get_income_time_series(self, freq="yearly", proxy=None) -> pd.... | class Financials:
def __init__(self, data: YfData, symbol: str):
self._data = data
self._symbol = symbol
self._income_time_series = {}
self._balance_sheet_time_series = {}
self._cash_flow_time_series = {}
def get_income_time_series(self, freq="yearly", proxy=None) -> pd.... | timescale_translation = {"yearly": "annual", "quarterly": "quarterly"}
timescale = timescale_translation[timescale]
# Step 2: construct url:
ts_url_base = f"https://query2.finance.yahoo.com/ws/fundamentals-timeseries/v1/finance/timeseries/{self._symbol}?symbol={self._symbol}"
ur... | timescale_translation = {"yearly": "annual", "quarterly": "quarterly"}
timescale = timescale_translation[timescale]
# Step 2: construct url:
ts_url_base = f"https://query2.finance.yahoo.com/ws/fundamentals-timeseries/v1/finance/timeseries/{self._symbol}?symbol={self._symbol}"
ur... | 196 | 795 | 701 | 1,496 | import datetime
import json
import pandas as pd
from yfinance import utils, const
from yfinance.data import YfData
from yfinance.exceptions import YFinanceException, YFNotImplementedError
class Fundamentals:
def __init__(self, data: YfData, symbol: str, proxy=None):
self._data = data
self._symb... | import datetime
import json
import pandas as pd
from yfinance import utils, const
from yfinance.data import YfData
from yfinance.exceptions import YFinanceException, YFNotImplementedError
class Fundamentals:
def __init__(self, data: YfData, symbol: str, proxy=None):
self._data = data
self._symb... |
23,493 | /home/hieuvd/dung_repo/raw/stars_01/ranaroussi_yfinance/yfinance | /home/hieuvd/dung_repo/raw/stars_01/ranaroussi_yfinance/yfinance/yfinance/scrapers/fundamentals.py | 27,29 | 11,44 | financials | Fundamentals | 29,31 | 29,31 | class Fundamentals:
def __init__(self, data: YfData, symbol: str, proxy=None):
self._data = data
self._symbol = symbol
self.proxy = proxy
self._earnings = None
self._financials = None
self._shares = None
self._financials_data = None
self._fin_data_q... | class Fundamentals:
def __init__(self, data: YfData, symbol: str, proxy=None):
self._data = data
self._symbol = symbol
self.proxy = proxy
self._earnings = None
self._financials = None
self._shares = None
self._financials_data = None
self._fin_data_q... | return self._financials
| return self._financials
| 2 | 260 | 11 | 271 | import datetime
import json
import pandas as pd
from yfinance import utils, const
from yfinance.data import YfData
from yfinance.exceptions import YFinanceException, YFNotImplementedError
class Fundamentals:
def __init__(self, data: YfData, symbol: str, proxy=None):
self._data = data
self._symb... | import datetime
import json
import pandas as pd
from yfinance import utils, const
from yfinance.data import YfData
from yfinance.exceptions import YFinanceException, YFNotImplementedError
class Fundamentals:
def __init__(self, data: YfData, symbol: str, proxy=None):
self._data = data
self._symb... |
23,496 | /home/hieuvd/dung_repo/raw/stars_01/ranaroussi_yfinance/yfinance | /home/hieuvd/dung_repo/raw/stars_01/ranaroussi_yfinance/yfinance/yfinance/scrapers/quote.py | 75,76 | 28,79 | _keytransform | InfoDictWrapper | 76,79 | 76,79 | class InfoDictWrapper(MutableMapping):
""" Simple wrapper around info dict, intercepting 'gets' to
print how-to-migrate messages for specific keys. Requires
override dict API"""
def __init__(self, info):
self.info = info
def keys(self):
return self.info.keys()
def __str__(self... | class InfoDictWrapper(MutableMapping):
""" Simple wrapper around info dict, intercepting 'gets' to
print how-to-migrate messages for specific keys. Requires
override dict API"""
def __init__(self, info):
self.info = info
def keys(self):
return self.info.keys()
def __str__(self... | return k
| return k
| 2 | 510 | 9 | 519 | import datetime
import json
import warnings
from collections.abc import MutableMapping
import numpy as _np
import pandas as pd
import requests
from yfinance import utils
from yfinance.data import YfData
from yfinance.const import quote_summary_valid_modules, _BASE_URL_
from yfinance.exceptions import YFNotImplemented... | import datetime
import json
import warnings
from collections.abc import MutableMapping
import numpy as _np
import pandas as pd
import requests
from yfinance import utils
from yfinance.data import YfData
from yfinance.const import quote_summary_valid_modules, _BASE_URL_
from yfinance.exceptions import YFNotImplemented... |
23,499 | /home/hieuvd/dung_repo/raw/stars_01/ranaroussi_yfinance/yfinance | /home/hieuvd/dung_repo/raw/stars_01/ranaroussi_yfinance/yfinance/yfinance/tickers.py | 60,66 | 30,93 | download | Tickers | 66,91 | 66,91 | class Tickers:
def __repr__(self):
return f"yfinance.Tickers object <{','.join(self.symbols)}>"
def __init__(self, tickers, session=None):
tickers = tickers if isinstance(
tickers, list) else tickers.replace(',', ' ').split()
self.symbols = [ticker.upper() for ticker in tic... | class Tickers:
def __repr__(self):
return f"yfinance.Tickers object <{','.join(self.symbols)}>"
def __init__(self, tickers, session=None):
tickers = tickers if isinstance(
tickers, list) else tickers.replace(',', ' ').split()
self.symbols = [ticker.upper() for ticker in tic... |
data = multi.download(self.symbols,
start=start, end=end,
actions=actions,
auto_adjust=auto_adjust,
repair=repair,
period=period,
i... |
data = multi.download(self.symbols,
start=start, end=end,
actions=actions,
auto_adjust=auto_adjust,
repair=repair,
period=period,
i... | 38 | 460 | 222 | 682 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# yfinance - market data downloader
# https://github.com/ranaroussi/yfinance
#
# Copyright 2017-2019 Ran Aroussi
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy ... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# yfinance - market data downloader
# https://github.com/ranaroussi/yfinance
#
# Copyright 2017-2019 Ran Aroussi
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy ... |
23,501 | /home/hieuvd/dung_repo/raw/stars_01/ranaroussi_yfinance/yfinance | /home/hieuvd/dung_repo/raw/stars_01/ranaroussi_yfinance/yfinance/yfinance/utils.py | 69,70 | 68,78 | process | IndentLoggerAdapter | 70,78 | 70,78 | class IndentLoggerAdapter(logging.LoggerAdapter):
def process(self, msg, kwargs):
FILL_FUNC_BODY | class IndentLoggerAdapter(logging.LoggerAdapter):
def process(self, msg, kwargs):
FILL_FUNC_BODY | if get_yf_logger().isEnabledFor(logging.DEBUG):
i = ' ' * self.extra['indent']
if not isinstance(msg, str):
msg = str(msg)
msg = '\n'.join([i + m for m in msg.split('\n')])
return msg, kwargs
| if get_yf_logger().isEnabledFor(logging.DEBUG):
i = ' ' * self.extra['indent']
if not isinstance(msg, str):
msg = str(msg)
msg = '\n'.join([i + m for m in msg.split('\n')])
return msg, kwargs
| 27 | 35 | 91 | 126 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# yfinance - market data downloader
# https://github.com/ranaroussi/yfinance
#
# Copyright 2017-2019 Ran Aroussi
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy ... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# yfinance - market data downloader
# https://github.com/ranaroussi/yfinance
#
# Copyright 2017-2019 Ran Aroussi
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy ... |
23,502 | /home/hieuvd/dung_repo/raw/stars_01/ranaroussi_yfinance/yfinance | /home/hieuvd/dung_repo/raw/stars_01/ranaroussi_yfinance/yfinance/yfinance/utils.py | 121,122 | 111,139 | format | MultiLineFormatter | 122,139 | 122,139 | class MultiLineFormatter(logging.Formatter):
# The 'fmt' formatting further down is only applied to first line
# of log message, specifically the padding after %level%.
# For multi-line messages, need to manually copy over padding.
def __init__(self, fmt):
super().__init__(fmt)
# Extract... | class MultiLineFormatter(logging.Formatter):
# The 'fmt' formatting further down is only applied to first line
# of log message, specifically the padding after %level%.
# For multi-line messages, need to manually copy over padding.
def __init__(self, fmt):
super().__init__(fmt)
# Extract... | original = super().format(record)
lines = original.split('\n')
levelname = lines[0].split(' ')[0]
if len(lines) <= 1:
return original
else:
# Apply padding to all lines below first
formatted = [lines[0]]
if self.level_length == 0:
... | original = super().format(record)
lines = original.split('\n')
levelname = lines[0].split(' ')[0]
if len(lines) <= 1:
return original
else:
# Apply padding to all lines below first
formatted = [lines[0]]
if self.level_length == 0:
... | 66 | 155 | 175 | 330 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# yfinance - market data downloader
# https://github.com/ranaroussi/yfinance
#
# Copyright 2017-2019 Ran Aroussi
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy ... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# yfinance - market data downloader
# https://github.com/ranaroussi/yfinance
#
# Copyright 2017-2019 Ran Aroussi
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy ... |
23,503 | /home/hieuvd/dung_repo/raw/stars_01/ranaroussi_yfinance/yfinance | /home/hieuvd/dung_repo/raw/stars_01/ranaroussi_yfinance/yfinance/yfinance/utils.py | 876,877 | 847,893 | update_iteration | ProgressBar | 877,881 | 877,881 | class ProgressBar:
def __init__(self, iterations, text='completed'):
self.text = text
self.iterations = iterations
self.prog_bar = '[]'
self.fill_char = '*'
self.width = 50
self.__update_amount(0)
self.elapsed = 1
def completed(self):
if self.elap... | class ProgressBar:
def __init__(self, iterations, text='completed'):
self.text = text
self.iterations = iterations
self.prog_bar = '[]'
self.fill_char = '*'
self.width = 50
self.__update_amount(0)
self.elapsed = 1
def completed(self):
if self.elap... | val = val if val is not None else self.elapsed / float(self.iterations)
self.__update_amount(val * 100.0)
self.prog_bar += f" {self.elapsed} of {self.iterations} {self.text}"
| val = val if val is not None else self.elapsed / float(self.iterations)
self.__update_amount(val * 100.0)
self.prog_bar += f" {self.elapsed} of {self.iterations} {self.text}"
| 22 | 531 | 75 | 606 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# yfinance - market data downloader
# https://github.com/ranaroussi/yfinance
#
# Copyright 2017-2019 Ran Aroussi
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy ... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# yfinance - market data downloader
# https://github.com/ranaroussi/yfinance
#
# Copyright 2017-2019 Ran Aroussi
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy ... |
23,663 | /home/hieuvd/dung_repo/raw/stars_01/saulpw_visidata/visidata | /home/hieuvd/dung_repo/raw/stars_01/saulpw_visidata/visidata/dev/zsh-completion.py | 18,19 | 1,57 | generate_completion | 19,48 | 19,48 | #!/usr/bin/env python
from __future__ import unicode_literals
import os
from os.path import dirname as dirn
import sys
import re
sys.path.insert(0, dirn(dirn((os.path.abspath(__file__)))))
from visidata import vd
ZSH_COMPLETION_FILE = "_visidata"
ZSH_COMPLETION_TEMPLATE = "dev/zsh-completion.in"
pat_class = re.compi... | #!/usr/bin/env python
from __future__ import unicode_literals
import os
from os.path import dirname as dirn
import sys
import re
sys.path.insert(0, dirn(dirn((os.path.abspath(__file__)))))
from visidata import vd
ZSH_COMPLETION_FILE = "_visidata"
ZSH_COMPLETION_TEMPLATE = "dev/zsh-completion.in"
pat_class = re.compi... | prefix = "--" + opt.name
shortnames = [
key for key, value in vd.option_aliases.items() if value[0] == opt.name
]
if len(shortnames):
if len(shortnames[0]) == 1:
shortname = "-" + shortnames[0]
else:
shortname = "--" + shortnames[0]
prefix = "{" + ... | prefix = "--" + opt.name
shortnames = [
key for key, value in vd.option_aliases.items() if value[0] == opt.name
]
if len(shortnames):
if len(shortnames[0]) == 1:
shortname = "-" + shortnames[0]
else:
shortname = "--" + shortnames[0]
prefix = "{" + ... | 115 | 273 | 399 | 672 | #!/usr/bin/env python
from __future__ import unicode_literals
import os
from os.path import dirname as dirn
import sys
import re
sys.path.insert(0, dirn(dirn((os.path.abspath(__file__)))))
from visidata import vd
ZSH_COMPLETION_FILE = "_visidata"
ZSH_COMPLETION_TEMPLATE = "dev/zsh-completion.in"
pat_class = re.compi... | #!/usr/bin/env python
from __future__ import unicode_literals
import os
from os.path import dirname as dirn
import sys
import re
sys.path.insert(0, dirn(dirn((os.path.abspath(__file__)))))
from visidata import vd
ZSH_COMPLETION_FILE = "_visidata"
ZSH_COMPLETION_TEMPLATE = "dev/zsh-completion.in"
pat_class = re.compi... | |
23,664 | /home/hieuvd/dung_repo/raw/stars_01/saulpw_visidata/visidata | /home/hieuvd/dung_repo/raw/stars_01/saulpw_visidata/visidata/snippets/geolocate.py | 8,10 | 1,14 | geolocate | 10,14 | 10,14 | 'geolocate(ip): Fetch geolocation info by IP address from hostip.info service.'
import urllib.request
import functools
import json
@functools.lru_cache(10240) # should actually cache semi-permanently in visidata_dir
def geolocate(ip):
FILL_FUNC_BODY | 'geolocate(ip): Fetch geolocation info by IP address from hostip.info service.'
import urllib.request
import functools
import json
@functools.lru_cache(10240) # should actually cache semi-permanently in visidata_dir
def geolocate(ip):
FILL_FUNC_BODY | url = 'http://api.hostip.info/get_json.php?position=true&ip=' + ip
with urllib.request.urlopen(url) as fp:
contents = fp.read().decode('utf-8').strip()
return json.loads(contents)
| url = 'http://api.hostip.info/get_json.php?position=true&ip=' + ip
with urllib.request.urlopen(url) as fp:
contents = fp.read().decode('utf-8').strip()
return json.loads(contents)
| 14 | 95 | 78 | 173 | 'geolocate(ip): Fetch geolocation info by IP address from hostip.info service.'
import urllib.request
import functools
import json
@functools.lru_cache(10240) # should actually cache semi-permanently in visidata_dir
def geolocate(ip):
FILL_FUNC_BODY | 'geolocate(ip): Fetch geolocation info by IP address from hostip.info service.'
import urllib.request
import functools
import json
@functools.lru_cache(10240) # should actually cache semi-permanently in visidata_dir
def geolocate(ip):
FILL_FUNC_BODY | |
23,665 | /home/hieuvd/dung_repo/raw/stars_01/saulpw_visidata/visidata | /home/hieuvd/dung_repo/raw/stars_01/saulpw_visidata/visidata/visidata/bezier.py | 11,12 | 1,64 | _recursive_bezier | 13,64 | 12,64 | import math
def bezier(x1, y1, x2, y2, x3, y3):
'Generate (x,y) coordinates on quadratic curve from (x1,y1) to (x3,y3) with control point at (x2,y2).'
yield (x1, y1)
yield from _recursive_bezier(x1, y1, x2, y2, x3, y3)
yield (x3, y3)
def _recursive_bezier(x1, y1, x2, y2, x3, y3, level=0):
FILL_FUNC_... | import math
def bezier(x1, y1, x2, y2, x3, y3):
'Generate (x,y) coordinates on quadratic curve from (x1,y1) to (x3,y3) with control point at (x2,y2).'
yield (x1, y1)
yield from _recursive_bezier(x1, y1, x2, y2, x3, y3)
yield (x3, y3)
def _recursive_bezier(x1, y1, x2, y2, x3, y3, level=0):
'from ... | m_approximation_scale = 10.0
m_distance_tolerance = (0.5 / m_approximation_scale) ** 2
m_angle_tolerance = 1 * 2*math.pi/360 # 15 degrees in rads
curve_angle_tolerance_epsilon = 0.01
curve_recursion_limit = 32
curve_collinearity_epsilon = 1e-30
if level > curve_recursion_limit:
ret... | 'from http://www.antigrain.com/research/adaptive_bezier/'
m_approximation_scale = 10.0
m_distance_tolerance = (0.5 / m_approximation_scale) ** 2
m_angle_tolerance = 1 * 2*math.pi/360 # 15 degrees in rads
curve_angle_tolerance_epsilon = 0.01
curve_recursion_limit = 32
curve_collinearity_epsi... | 242 | 188 | 740 | 928 | import math
def bezier(x1, y1, x2, y2, x3, y3):
'Generate (x,y) coordinates on quadratic curve from (x1,y1) to (x3,y3) with control point at (x2,y2).'
yield (x1, y1)
yield from _recursive_bezier(x1, y1, x2, y2, x3, y3)
yield (x3, y3)
def _recursive_bezier(x1, y1, x2, y2, x3, y3, level=0):
FILL_FUNC_... | import math
def bezier(x1, y1, x2, y2, x3, y3):
'Generate (x,y) coordinates on quadratic curve from (x1,y1) to (x3,y3) with control point at (x2,y2).'
yield (x1, y1)
yield from _recursive_bezier(x1, y1, x2, y2, x3, y3)
yield (x3, y3)
def _recursive_bezier(x1, y1, x2, y2, x3, y3, level=0):
'from ... | |
23,666 | /home/hieuvd/dung_repo/raw/stars_01/saulpw_visidata/visidata | /home/hieuvd/dung_repo/raw/stars_01/saulpw_visidata/visidata/visidata/extensible.py | 144,145 | 1,159 | cache | 146,155 | 145,155 | from functools import wraps, lru_cache
__all__ = ['Extensible', 'cache', 'drawcache', 'drawcache_property']
class Extensible:
_cache_clearers = [] # list of func() to call in clearCaches()
@classmethod
def init(cls, membername, initfunc=lambda: None, copy=False):
'Prepend equivalent of ``self.<... | from functools import wraps, lru_cache
__all__ = ['Extensible', 'cache', 'drawcache', 'drawcache_property']
class Extensible:
_cache_clearers = [] # list of func() to call in clearCaches()
@classmethod
def init(cls, membername, initfunc=lambda: None, copy=False):
'Prepend equivalent of ``self.<... | @wraps(func)
@lru_cache(maxsize=None)
def call_if_not(self, *args, **kwargs):
return func(self, *args, **kwargs)
Extensible._cache_clearers.append(call_if_not.cache_clear)
return call_if_not
# @drawcache is vd alias for @cache, since vd clears it every frame
| 'Return func(...) on first access, and cache result; return cached result until clearCaches().'
@wraps(func)
@lru_cache(maxsize=None)
def call_if_not(self, *args, **kwargs):
return func(self, *args, **kwargs)
Extensible._cache_clearers.append(call_if_not.cache_clear)
return call_if_not
... | 26 | 1,565 | 115 | 1,680 | from functools import wraps, lru_cache
__all__ = ['Extensible', 'cache', 'drawcache', 'drawcache_property']
class Extensible:
_cache_clearers = [] # list of func() to call in clearCaches()
@classmethod
def init(cls, membername, initfunc=lambda: None, copy=False):
'Prepend equivalent of ``self.<... | from functools import wraps, lru_cache
__all__ = ['Extensible', 'cache', 'drawcache', 'drawcache_property']
class Extensible:
_cache_clearers = [] # list of func() to call in clearCaches()
@classmethod
def init(cls, membername, initfunc=lambda: None, copy=False):
'Prepend equivalent of ``self.<... | |
23,667 | /home/hieuvd/dung_repo/raw/stars_01/saulpw_visidata/visidata | /home/hieuvd/dung_repo/raw/stars_01/saulpw_visidata/visidata/visidata/extensible.py | 9,11 | 6,144 | init | Extensible | 12,37 | 11,37 | class Extensible:
_cache_clearers = [] # list of func() to call in clearCaches()
@classmethod
def init(cls, membername, initfunc=lambda: None, copy=False):
FILL_FUNC_BODY @classmethod
def superclasses(cls):
yield cls
yield from cls.__bases__
for b in cls.__bases__:
... | class Extensible:
_cache_clearers = [] # list of func() to call in clearCaches()
@classmethod
def init(cls, membername, initfunc=lambda: None, copy=False):
'Prepend equivalent of ``self.<membername> = initfunc()`` to ``<cls>.__init__``. If *copy* is True, <membername> will be copied when object i... |
def thisclass_hasattr(cls, k):
return getattr(cls, k, None) is not getattr(cls.__bases__[0], k, None)
# must check hasattr first or else this might be parent's __init__
oldinit = thisclass_hasattr(cls, '__init__') and getattr(cls, '__init__')
def newinit(self, *args, **kwar... | 'Prepend equivalent of ``self.<membername> = initfunc()`` to ``<cls>.__init__``. If *copy* is True, <membername> will be copied when object is copied.'
def thisclass_hasattr(cls, k):
return getattr(cls, k, None) is not getattr(cls.__bases__[0], k, None)
# must check hasattr first ... | 109 | 1,117 | 379 | 1,496 | from functools import wraps, lru_cache
__all__ = ['Extensible', 'cache', 'drawcache', 'drawcache_property']
class Extensible:
_cache_clearers = [] # list of func() to call in clearCaches()
@classmethod
def init(cls, membername, initfunc=lambda: None, copy=False):
FILL_FUNC_BODY @classmethod
def ... | from functools import wraps, lru_cache
__all__ = ['Extensible', 'cache', 'drawcache', 'drawcache_property']
class Extensible:
_cache_clearers = [] # list of func() to call in clearCaches()
@classmethod
def init(cls, membername, initfunc=lambda: None, copy=False):
'Prepend equivalent of ``self.<... |
23,668 | /home/hieuvd/dung_repo/raw/stars_01/saulpw_visidata/visidata | /home/hieuvd/dung_repo/raw/stars_01/saulpw_visidata/visidata/visidata/features/currency_to_usd.py | 60,61 | 1,71 | USD | 61,70 | 61,70 | '''Provide USD(s) function to convert string like '£300' or '205 AUD' to equivalent US$ as float.
Uses data from api.apilayer.com/fixer. Requires an API key for apilayer.com.
'''
from visidata import vd
import functools
import json
vd.option('fixer_api_key', '', 'API Key for api.apilayer.com/fixer')
vd.option('fixer_... | '''Provide USD(s) function to convert string like '£300' or '205 AUD' to equivalent US$ as float.
Uses data from api.apilayer.com/fixer. Requires an API key for apilayer.com.
'''
from visidata import vd
import functools
import json
vd.option('fixer_api_key', '', 'API Key for api.apilayer.com/fixer')
vd.option('fixer_... | for currency_symbol, currency_code in currency_symbols.items():
if currency_symbol in s:
amt = float(s.replace(currency_symbol, ''))
return amt*currency_multiplier(currency_code, 'USD')
amtstr, currcode = s.split(' ')
return float(amtstr) * currency_multiplier(currcode, 'USD... | for currency_symbol, currency_code in currency_symbols.items():
if currency_symbol in s:
amt = float(s.replace(currency_symbol, ''))
return amt*currency_multiplier(currency_code, 'USD')
amtstr, currcode = s.split(' ')
return float(amtstr) * currency_multiplier(currcode, 'USD... | 26 | 817 | 116 | 933 | '''Provide USD(s) function to convert string like '£300' or '205 AUD' to equivalent US$ as float.
Uses data from api.apilayer.com/fixer. Requires an API key for apilayer.com.
'''
from visidata import vd
import functools
import json
vd.option('fixer_api_key', '', 'API Key for api.apilayer.com/fixer')
vd.option('fixer_... | '''Provide USD(s) function to convert string like '£300' or '205 AUD' to equivalent US$ as float.
Uses data from api.apilayer.com/fixer. Requires an API key for apilayer.com.
'''
from visidata import vd
import functools
import json
vd.option('fixer_api_key', '', 'API Key for api.apilayer.com/fixer')
vd.option('fixer_... | |
23,669 | /home/hieuvd/dung_repo/raw/stars_01/saulpw_visidata/visidata | /home/hieuvd/dung_repo/raw/stars_01/saulpw_visidata/visidata/visidata/features/status_source.py | 6,8 | 1,21 | getStatusSource | 8,21 | 8,21 | import inspect
import visidata
from visidata import VisiData
@VisiData.api
def getStatusSource(vd):
FILL_FUNC_BODY | import inspect
import visidata
from visidata import VisiData
@VisiData.api
def getStatusSource(vd):
FILL_FUNC_BODY | stack = inspect.stack()
for i, sf in enumerate(stack):
if sf.function in 'status aside'.split():
if stack[i+1].function in 'error fail warning debug'.split():
sf = stack[i+2]
else:
sf = stack[i+1]
break
fn = sf.filename
if fn.s... | stack = inspect.stack()
for i, sf in enumerate(stack):
if sf.function in 'status aside'.split():
if stack[i+1].function in 'error fail warning debug'.split():
sf = stack[i+2]
else:
sf = stack[i+1]
break
fn = sf.filename
if fn.s... | 40 | 44 | 169 | 213 | import inspect
import visidata
from visidata import VisiData
@VisiData.api
def getStatusSource(vd):
FILL_FUNC_BODY | import inspect
import visidata
from visidata import VisiData
@VisiData.api
def getStatusSource(vd):
FILL_FUNC_BODY | |
23,670 | /home/hieuvd/dung_repo/raw/stars_01/saulpw_visidata/visidata | /home/hieuvd/dung_repo/raw/stars_01/saulpw_visidata/visidata/visidata/features/term_extras.py | 6,8 | 1,14 | ansi | 8,11 | 8,11 | import os
from visidata import VisiData
@VisiData.api
def ansi(*args):
FILL_FUNC_BODY@VisiData.api
def set_titlebar(vd, title:str):
ansi(']2;', title, '\x07')
| import os
from visidata import VisiData
@VisiData.api
def ansi(*args):
FILL_FUNC_BODY@VisiData.api
def set_titlebar(vd, title:str):
ansi(']2;', title, '\x07')
| os.write(1, b'\x1b'+b''.join([str(x).encode('utf-8') for x in args]))
| os.write(1, b'\x1b'+b''.join([str(x).encode('utf-8') for x in args]))
| 6 | 75 | 40 | 115 | import os
from visidata import VisiData
@VisiData.api
def ansi(*args):
FILL_FUNC_BODY@VisiData.api
def set_titlebar(vd, title:str):
ansi(']2;', title, '\x07')
| import os
from visidata import VisiData
@VisiData.api
def ansi(*args):
FILL_FUNC_BODY@VisiData.api
def set_titlebar(vd, title:str):
ansi(']2;', title, '\x07')
| |
23,671 | /home/hieuvd/dung_repo/raw/stars_01/saulpw_visidata/visidata | /home/hieuvd/dung_repo/raw/stars_01/saulpw_visidata/visidata/visidata/features/type_ipaddr.py | 30,32 | 1,74 | selectSupernets | 37,54 | 32,54 | """
Column types and utility commands related to IP addresses.
"""
from ipaddress import ip_address, ip_network, _BaseNetwork
from visidata import vd
from visidata.sheets import Column, TableSheet
vd.addType(ip_address, icon=":", formatter=lambda fmt, ip: str(ip))
vd.addType(ip_network, icon="/", formatter=lambda fm... | """
Column types and utility commands related to IP addresses.
"""
from ipaddress import ip_address, ip_network, _BaseNetwork
from visidata import vd
from visidata.sheets import Column, TableSheet
vd.addType(ip_address, icon=":", formatter=lambda fmt, ip: str(ip))
vd.addType(ip_network, icon="/", formatter=lambda fm... | if not ip:
return
sheet = col.sheet
network = ip_network(ip.strip())
isNull = sheet.isNullFunc()
vd.status(f'selecting rows where {col.name} is a supernet of "{str(network)}"')
sheet.select(
[
row
for row in sheet.rows
if isSupernet(col.getTy... | """Select rows based on network containment
Given an IP address (e.g. 10.0.0.0) or network (e.g. 10.0.0.0/8) as input,
select rows whose network address space completely contains the input network.
"""
if not ip:
return
sheet = col.sheet
network = ip_network(ip.strip())
isNull ... | 35 | 511 | 139 | 650 | """
Column types and utility commands related to IP addresses.
"""
from ipaddress import ip_address, ip_network, _BaseNetwork
from visidata import vd
from visidata.sheets import Column, TableSheet
vd.addType(ip_address, icon=":", formatter=lambda fmt, ip: str(ip))
vd.addType(ip_network, icon="/", formatter=lambda fm... | """
Column types and utility commands related to IP addresses.
"""
from ipaddress import ip_address, ip_network, _BaseNetwork
from visidata import vd
from visidata.sheets import Column, TableSheet
vd.addType(ip_address, icon=":", formatter=lambda fmt, ip: str(ip))
vd.addType(ip_network, icon="/", formatter=lambda fm... | |
23,673 | /home/hieuvd/dung_repo/raw/stars_01/saulpw_visidata/visidata | /home/hieuvd/dung_repo/raw/stars_01/saulpw_visidata/visidata/visidata/hint.py | 11,13 | 1,40 | getHint | 13,39 | 13,39 | import collections
from visidata import vd, BaseSheet
@BaseSheet.lazy_property
def prevHints(sheet):
return collections.defaultdict(int)
@BaseSheet.api
def getHint(sheet, *args, **kwargs) -> str:
FILL_FUNC_BODYvd.addCommand('', 'help-hint', 'status(getHint() or pressMenu("Help"))', 'get context-dependent hint ... | import collections
from visidata import vd, BaseSheet
@BaseSheet.lazy_property
def prevHints(sheet):
return collections.defaultdict(int)
@BaseSheet.api
def getHint(sheet, *args, **kwargs) -> str:
FILL_FUNC_BODYvd.addCommand('', 'help-hint', 'status(getHint() or pressMenu("Help"))', 'get context-dependent hint ... | funcs = [getattr(sheet, x) for x in dir(sheet) if x.startswith('hint_')]
results = []
hints = sheet.prevHints
for f in funcs:
try:
r = f(*args, **kwargs)
if r:
if isinstance(r, dict):
n = r.get('_relevance', 1)
v = r... | funcs = [getattr(sheet, x) for x in dir(sheet) if x.startswith('hint_')]
results = []
hints = sheet.prevHints
for f in funcs:
try:
r = f(*args, **kwargs)
if r:
if isinstance(r, dict):
n = r.get('_relevance', 1)
v = r... | 72 | 122 | 245 | 367 | import collections
from visidata import vd, BaseSheet
@BaseSheet.lazy_property
def prevHints(sheet):
return collections.defaultdict(int)
@BaseSheet.api
def getHint(sheet, *args, **kwargs) -> str:
FILL_FUNC_BODYvd.addCommand('', 'help-hint', 'status(getHint() or pressMenu("Help"))', 'get context-dependent hint ... | import collections
from visidata import vd, BaseSheet
@BaseSheet.lazy_property
def prevHints(sheet):
return collections.defaultdict(int)
@BaseSheet.api
def getHint(sheet, *args, **kwargs) -> str:
FILL_FUNC_BODYvd.addCommand('', 'help-hint', 'status(getHint() or pressMenu("Help"))', 'get context-dependent hint ... | |
23,674 | /home/hieuvd/dung_repo/raw/stars_01/saulpw_visidata/visidata | /home/hieuvd/dung_repo/raw/stars_01/saulpw_visidata/visidata/visidata/keys.py | 76,78 | 1,91 | prettykeys | 78,91 | 78,91 | import string
import visidata
visidata.vd.prettykeys_trdict = {
' ': 'Space', # must be first
'^[': 'Alt+',
'^J': 'Enter',
'^M': 'Enter',
'^I': 'Tab',
'KEY_BTAB': 'Shift+Tab',
'^@': 'Ctrl+Space',
'KEY_UP': 'Up',
'KEY_DOWN': 'Down',
'... | import string
import visidata
visidata.vd.prettykeys_trdict = {
' ': 'Space', # must be first
'^[': 'Alt+',
'^J': 'Enter',
'^M': 'Enter',
'^I': 'Tab',
'KEY_BTAB': 'Shift+Tab',
'^@': 'Ctrl+Space',
'KEY_UP': 'Up',
'KEY_DOWN': 'Down',
'... | if not key or '+' in key[:-1]:
return key
for k, v in vd.prettykeys_trdict.items():
key = key.replace(k, v)
# replace ^ with Ctrl but not if ^ is last char
key = key[:-1].replace('^', 'Ctrl+')+key[-1]
# 1497: allow Shift+ for Alt keys
if key[-1] in string.ascii_uppercase and ('... | if not key or '+' in key[:-1]:
return key
for k, v in vd.prettykeys_trdict.items():
key = key.replace(k, v)
# replace ^ with Ctrl but not if ^ is last char
key = key[:-1].replace('^', 'Ctrl+')+key[-1]
# 1497: allow Shift+ for Alt keys
if key[-1] in string.ascii_uppercase and ('... | 68 | 955 | 181 | 1,136 | import string
import visidata
visidata.vd.prettykeys_trdict = {
' ': 'Space', # must be first
'^[': 'Alt+',
'^J': 'Enter',
'^M': 'Enter',
'^I': 'Tab',
'KEY_BTAB': 'Shift+Tab',
'^@': 'Ctrl+Space',
'KEY_UP': 'Up',
'KEY_DOWN': 'Down',
'... | import string
import visidata
visidata.vd.prettykeys_trdict = {
' ': 'Space', # must be first
'^[': 'Alt+',
'^J': 'Enter',
'^M': 'Enter',
'^I': 'Tab',
'KEY_BTAB': 'Shift+Tab',
'^@': 'Ctrl+Space',
'KEY_UP': 'Up',
'KEY_DOWN': 'Down',
'... | |
23,675 | /home/hieuvd/dung_repo/raw/stars_01/saulpw_visidata/visidata | /home/hieuvd/dung_repo/raw/stars_01/saulpw_visidata/visidata/visidata/text_source.py | 46,48 | 1,54 | open_text_source | 49,54 | 48,54 | import re
from visidata import vd, BaseSheet
vd.option('regex_skip', '', 'regex of lines to skip in text sources', help='regex', replay=True)
vd.option('regex_flags', 'I', 'flags to pass to re.compile() [AILMSUX]', replay=True)
@BaseSheet.api
def regex_flags(sheet):
'Return flags to pass to regex functions from ... | import re
from visidata import vd, BaseSheet
vd.option('regex_skip', '', 'regex of lines to skip in text sources', help='regex', replay=True)
vd.option('regex_flags', 'I', 'flags to pass to re.compile() [AILMSUX]', replay=True)
@BaseSheet.api
def regex_flags(sheet):
'Return flags to pass to regex functions from ... | fp = sheet.source.open(encoding=sheet.options.encoding, encoding_errors=sheet.options.encoding_errors)
regex_skip = sheet.options.regex_skip
if regex_skip:
return FilterFile(fp, regex_skip, sheet.regex_flags())
return fp
| 'Open sheet source as text, using sheet options for encoding and regex_skip.'
fp = sheet.source.open(encoding=sheet.options.encoding, encoding_errors=sheet.options.encoding_errors)
regex_skip = sheet.options.regex_skip
if regex_skip:
return FilterFile(fp, regex_skip, sheet.regex_flags())
ret... | 15 | 405 | 79 | 484 | import re
from visidata import vd, BaseSheet
vd.option('regex_skip', '', 'regex of lines to skip in text sources', help='regex', replay=True)
vd.option('regex_flags', 'I', 'flags to pass to re.compile() [AILMSUX]', replay=True)
@BaseSheet.api
def regex_flags(sheet):
'Return flags to pass to regex functions from ... | import re
from visidata import vd, BaseSheet
vd.option('regex_skip', '', 'regex of lines to skip in text sources', help='regex', replay=True)
vd.option('regex_flags', 'I', 'flags to pass to re.compile() [AILMSUX]', replay=True)
@BaseSheet.api
def regex_flags(sheet):
'Return flags to pass to regex functions from ... | |
23,676 | /home/hieuvd/dung_repo/raw/stars_01/saulpw_visidata/visidata | /home/hieuvd/dung_repo/raw/stars_01/saulpw_visidata/visidata/visidata/text_source.py | 20,21 | 14,46 | readline | FilterFile | 21,27 | 21,27 | class FilterFile:
def __init__(self, fp, regex:str, regex_flags:int=0):
import re
self._fp = fp
self._regex_skip = re.compile(regex, regex_flags)
def readline(self) -> str:
FILL_FUNC_BODY def __getattr__(self, k):
return getattr(self._fp, k)
def __iter__(self):
r... | class FilterFile:
def __init__(self, fp, regex:str, regex_flags:int=0):
import re
self._fp = fp
self._regex_skip = re.compile(regex, regex_flags)
def readline(self) -> str:
FILL_FUNC_BODY def __getattr__(self, k):
return getattr(self._fp, k)
def __iter__(self):
r... | while True:
line = self._fp.readline()
if self._regex_skip.match(line):
continue
return line
| while True:
line = self._fp.readline()
if self._regex_skip.match(line):
continue
return line
| 10 | 196 | 43 | 239 | import re
from visidata import vd, BaseSheet
vd.option('regex_skip', '', 'regex of lines to skip in text sources', help='regex', replay=True)
vd.option('regex_flags', 'I', 'flags to pass to re.compile() [AILMSUX]', replay=True)
@BaseSheet.api
def regex_flags(sheet):
'Return flags to pass to regex functions from ... | import re
from visidata import vd, BaseSheet
vd.option('regex_skip', '', 'regex of lines to skip in text sources', help='regex', replay=True)
vd.option('regex_flags', 'I', 'flags to pass to re.compile() [AILMSUX]', replay=True)
@BaseSheet.api
def regex_flags(sheet):
'Return flags to pass to regex functions from ... |
23,677 | /home/hieuvd/dung_repo/raw/stars_01/saulpw_visidata/visidata | /home/hieuvd/dung_repo/raw/stars_01/saulpw_visidata/visidata/visidata/tuiwin.py | 6,8 | 1,27 | subwindow | 9,14 | 8,14 | from visidata import VisiData, vd, BaseSheet
vd._parentscrs = {} # scr -> parentscr
@VisiData.api
def subwindow(vd, scr, x, y, w, h):
FILL_FUNC_BODY@VisiData.api
def getrootxy(vd, scr): # like scr.getparyx() but for all ancestor scrs
px, py = 0, 0
while scr in vd._parentscrs:
dy, dx = scr.getparyx(... | from visidata import VisiData, vd, BaseSheet
vd._parentscrs = {} # scr -> parentscr
@VisiData.api
def subwindow(vd, scr, x, y, w, h):
'Return subwindow with its (0,0) at (x,y) relative to parent scr. Replacement for scr.derwin() to track parent scr.'
FILL_FUNC_BODY@VisiData.api
def getrootxy(vd, scr): # like ... | newscr = scr.derwin(h, w, y, x)
vd._parentscrs[newscr] = scr
return newscr
| 'Return subwindow with its (0,0) at (x,y) relative to parent scr. Replacement for scr.derwin() to track parent scr.'
newscr = scr.derwin(h, w, y, x)
vd._parentscrs[newscr] = scr
return newscr
| 11 | 269 | 44 | 313 | from visidata import VisiData, vd, BaseSheet
vd._parentscrs = {} # scr -> parentscr
@VisiData.api
def subwindow(vd, scr, x, y, w, h):
FILL_FUNC_BODY@VisiData.api
def getrootxy(vd, scr): # like scr.getparyx() but for all ancestor scrs
px, py = 0, 0
while scr in vd._parentscrs:
dy, dx = scr.getparyx(... | from visidata import VisiData, vd, BaseSheet
vd._parentscrs = {} # scr -> parentscr
@VisiData.api
def subwindow(vd, scr, x, y, w, h):
'Return subwindow with its (0,0) at (x,y) relative to parent scr. Replacement for scr.derwin() to track parent scr.'
FILL_FUNC_BODY@VisiData.api
def getrootxy(vd, scr): # like ... | |
23,678 | /home/hieuvd/dung_repo/raw/stars_01/saulpw_visidata/visidata | /home/hieuvd/dung_repo/raw/stars_01/saulpw_visidata/visidata/visidata/vdobj.py | 16,17 | 1,189 | asyncthread | 18,27 | 17,27 | from functools import wraps
import curses
import visidata
__all__ = ['ENTER', 'ALT', 'ESC', 'asyncthread', 'VisiData']
ENTER='Enter'
ALT=ESC='^['
import threading
# define @asyncthread for potentially long-running functions
# when function is called, instead launches a thread
def asyncthread(func):
FILL_FUNC_BO... | from functools import wraps
import curses
import visidata
__all__ = ['ENTER', 'ALT', 'ESC', 'asyncthread', 'VisiData']
ENTER='Enter'
ALT=ESC='^['
import threading
# define @asyncthread for potentially long-running functions
# when function is called, instead launches a thread
def asyncthread(func):
'Functio... | @wraps(func)
def _execAsync(*args, **kwargs):
if args and isinstance(args[0], visidata.BaseSheet): #1136: allow cancel of async methods on Sheet
if 'sheet' not in kwargs:
kwargs['sheet'] = args[0]
return visidata.vd.execAsync(func, *args, **kwargs)
return _execAs... | 'Function decorator, to make calls to `func()` spawn a separate thread if available.'
@wraps(func)
def _execAsync(*args, **kwargs):
if args and isinstance(args[0], visidata.BaseSheet): #1136: allow cancel of async methods on Sheet
if 'sheet' not in kwargs:
kwargs['sheet'... | 31 | 1,815 | 117 | 1,932 | from functools import wraps
import curses
import visidata
__all__ = ['ENTER', 'ALT', 'ESC', 'asyncthread', 'VisiData']
ENTER='Enter'
ALT=ESC='^['
import threading
# define @asyncthread for potentially long-running functions
# when function is called, instead launches a thread
def asyncthread(func):
FILL_FUNC_BO... | from functools import wraps
import curses
import visidata
__all__ = ['ENTER', 'ALT', 'ESC', 'asyncthread', 'VisiData']
ENTER='Enter'
ALT=ESC='^['
import threading
# define @asyncthread for potentially long-running functions
# when function is called, instead launches a thread
def asyncthread(func):
'Functio... | |
23,679 | /home/hieuvd/dung_repo/raw/stars_01/saulpw_visidata/visidata | /home/hieuvd/dung_repo/raw/stars_01/saulpw_visidata/visidata/visidata/vdobj.py | 93,95 | 27,189 | init | VisiData | 96,103 | 95,103 | class VisiData(visidata.Extensible):
allPrefixes = ['g', 'z', 'gz', 'Alt+', 'Alt+['] # embig'g'en, 'z'mallify, Alt/Esc=User
@classmethod
def global_api(cls, func):
'Make global func() and identical vd.func()'
def _vdfunc(*args, **kwargs):
return getattr(visidata.vd, func.__name... | class VisiData(visidata.Extensible):
allPrefixes = ['g', 'z', 'gz', 'Alt+', 'Alt+['] # embig'g'en, 'z'mallify, Alt/Esc=User
@classmethod
def global_api(cls, func):
'Make global func() and identical vd.func()'
def _vdfunc(*args, **kwargs):
return getattr(visidata.vd, func.__name... | oldinit = cls.finalInit
def newinit(self, *args, **kwargs):
oldinit(self, *args, **kwargs)
setattr(self, membername, initfunc())
cls.finalInit = newinit
super().init(membername, lambda: None, **kwargs)
| 'Overload Extensible.init() to call finalInit instead of __init__'
oldinit = cls.finalInit
def newinit(self, *args, **kwargs):
oldinit(self, *args, **kwargs)
setattr(self, membername, initfunc())
cls.finalInit = newinit
super().init(membername, lambda: Non... | 20 | 1,604 | 85 | 1,689 | from functools import wraps
import curses
import visidata
__all__ = ['ENTER', 'ALT', 'ESC', 'asyncthread', 'VisiData']
ENTER='Enter'
ALT=ESC='^['
import threading
# define @asyncthread for potentially long-running functions
# when function is called, instead launches a thread
def asyncthread(func):
'Functio... | from functools import wraps
import curses
import visidata
__all__ = ['ENTER', 'ALT', 'ESC', 'asyncthread', 'VisiData']
ENTER='Enter'
ALT=ESC='^['
import threading
# define @asyncthread for potentially long-running functions
# when function is called, instead launches a thread
def asyncthread(func):
'Functio... |
23,771 | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/answerers/random/answerer.py | 29,30 | 1,79 | random_int | 30,33 | 30,33 | # SPDX-License-Identifier: AGPL-3.0-or-later
import hashlib
import random
import string
import uuid
from flask_babel import gettext
# required answerer attribute
# specifies which search query keywords triggers this answerer
keywords = ('random',)
random_int_max = 2**31
random_string_letters = string.ascii_lowercase... | # SPDX-License-Identifier: AGPL-3.0-or-later
import hashlib
import random
import string
import uuid
from flask_babel import gettext
# required answerer attribute
# specifies which search query keywords triggers this answerer
keywords = ('random',)
random_int_max = 2**31
random_string_letters = string.ascii_lowercase... | return str(random.randint(-random_int_max, random_int_max))
| return str(random.randint(-random_int_max, random_int_max))
| 3 | 555 | 27 | 582 | # SPDX-License-Identifier: AGPL-3.0-or-later
import hashlib
import random
import string
import uuid
from flask_babel import gettext
# required answerer attribute
# specifies which search query keywords triggers this answerer
keywords = ('random',)
random_int_max = 2**31
random_string_letters = string.ascii_lowercase... | # SPDX-License-Identifier: AGPL-3.0-or-later
import hashlib
import random
import string
import uuid
from flask_babel import gettext
# required answerer attribute
# specifies which search query keywords triggers this answerer
keywords = ('random',)
random_int_max = 2**31
random_string_letters = string.ascii_lowercase... | |
23,772 | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/answerers/statistics/answerer.py | 13,14 | 1,52 | answer | 14,46 | 14,46 | # SPDX-License-Identifier: AGPL-3.0-or-later
from functools import reduce
from operator import mul
from flask_babel import gettext
keywords = ('min', 'max', 'avg', 'sum', 'prod')
# required answerer function
# can return a list of results (any result type) for a given query
def answer(query):
FILL_FUNC_BODYdef sel... | # SPDX-License-Identifier: AGPL-3.0-or-later
from functools import reduce
from operator import mul
from flask_babel import gettext
keywords = ('min', 'max', 'avg', 'sum', 'prod')
# required answerer function
# can return a list of results (any result type) for a given query
def answer(query):
FILL_FUNC_BODYdef sel... | parts = query.query.split()
if len(parts) < 2:
return []
try:
args = list(map(float, parts[1:]))
except:
return []
func = parts[0]
answer = None
if func == 'min':
answer = min(args)
elif func == 'max':
answer = max(args)
elif func == 'avg':... | parts = query.query.split()
if len(parts) < 2:
return []
try:
args = list(map(float, parts[1:]))
except:
return []
func = parts[0]
answer = None
if func == 'min':
answer = min(args)
elif func == 'max':
answer = max(args)
elif func == 'avg':... | 81 | 187 | 233 | 420 | # SPDX-License-Identifier: AGPL-3.0-or-later
from functools import reduce
from operator import mul
from flask_babel import gettext
keywords = ('min', 'max', 'avg', 'sum', 'prod')
# required answerer function
# can return a list of results (any result type) for a given query
def answer(query):
FILL_FUNC_BODYdef sel... | # SPDX-License-Identifier: AGPL-3.0-or-later
from functools import reduce
from operator import mul
from flask_babel import gettext
keywords = ('min', 'max', 'avg', 'sum', 'prod')
# required answerer function
# can return a list of results (any result type) for a given query
def answer(query):
FILL_FUNC_BODYdef sel... | |
23,774 | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/babel_extract.py | 30,37 | 1,51 | extract | 42,51 | 37,51 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""This module implements the :origin:`searxng_msg <babel.cfg>` extractor to
extract messages from:
- :origin:`searx/searxng.msg`
The ``searxng.msg`` files are selected by Babel_, see Babel's configuration in
:origin:`babel.cfg`::
searxng_msg = searx.babel_extract.ext... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""This module implements the :origin:`searxng_msg <babel.cfg>` extractor to
extract messages from:
- :origin:`searx/searxng.msg`
The ``searxng.msg`` files are selected by Babel_, see Babel's configuration in
:origin:`babel.cfg`::
searxng_msg = searx.babel_extract.ext... | if fileobj.name not in _MSG_FILES:
raise RuntimeError("don't know how to extract messages from %s" % fileobj.name)
namespace = {}
exec(fileobj.read(), {}, namespace) # pylint: disable=exec-used
for name in namespace['__all__']:
for k, v in namespace[name].items():
yield 0,... | """Extract messages from ``searxng.msg`` files by a custom extractor_.
.. _extractor:
https://babel.pocoo.org/en/latest/messages.html#writing-extraction-methods
"""
if fileobj.name not in _MSG_FILES:
raise RuntimeError("don't know how to extract messages from %s" % fileobj.name)
nam... | 42 | 446 | 128 | 574 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""This module implements the :origin:`searxng_msg <babel.cfg>` extractor to
extract messages from:
- :origin:`searx/searxng.msg`
The ``searxng.msg`` files are selected by Babel_, see Babel's configuration in
:origin:`babel.cfg`::
searxng_msg = searx.babel_extract.ext... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""This module implements the :origin:`searxng_msg <babel.cfg>` extractor to
extract messages from:
- :origin:`searx/searxng.msg`
The ``searxng.msg`` files are selected by Babel_, see Babel's configuration in
:origin:`babel.cfg`::
searxng_msg = searx.babel_extract.ext... | |
23,775 | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/botdetection/_helpers.py | 21,22 | 1,129 | dump_request | 22,37 | 22,37 | # SPDX-License-Identifier: AGPL-3.0-or-later
# pylint: disable=missing-module-docstring, invalid-name
from __future__ import annotations
from ipaddress import (
IPv4Network,
IPv6Network,
IPv4Address,
IPv6Address,
ip_network,
)
import flask
import werkzeug
from searx import logger
from . import con... | # SPDX-License-Identifier: AGPL-3.0-or-later
# pylint: disable=missing-module-docstring, invalid-name
from __future__ import annotations
from ipaddress import (
IPv4Network,
IPv6Network,
IPv4Address,
IPv6Address,
ip_network,
)
import flask
import werkzeug
from searx import logger
from . import con... | return (
request.path
+ " || X-Forwarded-For: %s" % request.headers.get('X-Forwarded-For')
+ " || X-Real-IP: %s" % request.headers.get('X-Real-IP')
+ " || form: %s" % request.form
+ " || Accept: %s" % request.headers.get('Accept')
+ " || Accept-Language: %s" % request... | return (
request.path
+ " || X-Forwarded-For: %s" % request.headers.get('X-Forwarded-For')
+ " || X-Real-IP: %s" % request.headers.get('X-Real-IP')
+ " || form: %s" % request.form
+ " || Accept: %s" % request.headers.get('Accept')
+ " || Accept-Language: %s" % request... | 74 | 1,372 | 257 | 1,629 | # SPDX-License-Identifier: AGPL-3.0-or-later
# pylint: disable=missing-module-docstring, invalid-name
from __future__ import annotations
from ipaddress import (
IPv4Network,
IPv6Network,
IPv4Address,
IPv6Address,
ip_network,
)
import flask
import werkzeug
from searx import logger
from . import con... | # SPDX-License-Identifier: AGPL-3.0-or-later
# pylint: disable=missing-module-docstring, invalid-name
from __future__ import annotations
from ipaddress import (
IPv4Network,
IPv6Network,
IPv4Address,
IPv6Address,
ip_network,
)
import flask
import werkzeug
from searx import logger
from . import con... | |
23,777 | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/botdetection/config.py | 151,152 | 64,185 | _get_parent_dict | Config | 152,161 | 152,161 | class Config:
"""Base class used for configuration"""
UNSET = UNSET
@classmethod
def from_toml(cls, schema_file: pathlib.Path, cfg_file: pathlib.Path, deprecated: dict) -> Config:
# init schema
log.debug("load schema file: %s", schema_file)
cfg = cls(cfg_schema=toml_load(sche... | class Config:
"""Base class used for configuration"""
UNSET = UNSET
@classmethod
def from_toml(cls, schema_file: pathlib.Path, cfg_file: pathlib.Path, deprecated: dict) -> Config:
# init schema
log.debug("load schema file: %s", schema_file)
cfg = cls(cfg_schema=toml_load(sche... | parent_name = '.'.join(name.split('.')[:-1])
if parent_name:
parent = value(parent_name, self.cfg)
else:
parent = self.cfg
if (parent is UNSET) or (not isinstance(parent, dict)):
raise KeyError(parent_name)
return parent
| parent_name = '.'.join(name.split('.')[:-1])
if parent_name:
parent = value(parent_name, self.cfg)
else:
parent = self.cfg
if (parent is UNSET) or (not isinstance(parent, dict)):
raise KeyError(parent_name)
return parent
| 25 | 1,123 | 96 | 1,219 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Configuration class :py:class:`Config` with deep-update, schema validation
and deprecated names.
The :py:class:`Config` class implements a configuration that is based on
structured dictionaries. The configuration schema is defined in a dictionary
structure and the confi... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Configuration class :py:class:`Config` with deep-update, schema validation
and deprecated names.
The :py:class:`Config` class implements a configuration that is based on
structured dictionaries. The configuration schema is defined in a dictionary
structure and the confi... |
23,778 | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/botdetection/http_accept.py | 30,35 | 1,39 | filter_request | 35,39 | 35,39 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""
Method ``http_accept``
----------------------
The ``http_accept`` method evaluates a request as the request of a bot if the
Accept_ header ..
- did not contain ``text/html``
.. _Accept:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept
"""
# pylint:... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""
Method ``http_accept``
----------------------
The ``http_accept`` method evaluates a request as the request of a bot if the
Accept_ header ..
- did not contain ``text/html``
.. _Accept:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept
"""
# pylint:... |
if 'text/html' not in request.accept_mimetypes:
return too_many_requests(network, "HTTP header Accept did not contain text/html")
return None
|
if 'text/html' not in request.accept_mimetypes:
return too_many_requests(network, "HTTP header Accept did not contain text/html")
return None
| 16 | 235 | 51 | 286 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""
Method ``http_accept``
----------------------
The ``http_accept`` method evaluates a request as the request of a bot if the
Accept_ header ..
- did not contain ``text/html``
.. _Accept:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept
"""
# pylint:... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""
Method ``http_accept``
----------------------
The ``http_accept`` method evaluates a request as the request of a bot if the
Accept_ header ..
- did not contain ``text/html``
.. _Accept:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept
"""
# pylint:... | |
23,779 | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/botdetection/http_accept_encoding.py | 31,36 | 1,41 | filter_request | 36,41 | 36,41 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""
Method ``http_accept_encoding``
-------------------------------
The ``http_accept_encoding`` method evaluates a request as the request of a
bot if the Accept-Encoding_ header ..
- did not contain ``gzip`` AND ``deflate`` (if both values are missed)
- did not contain ``... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""
Method ``http_accept_encoding``
-------------------------------
The ``http_accept_encoding`` method evaluates a request as the request of a
bot if the Accept-Encoding_ header ..
- did not contain ``gzip`` AND ``deflate`` (if both values are missed)
- did not contain ``... |
accept_list = [l.strip() for l in request.headers.get('Accept-Encoding', '').split(',')]
if not ('gzip' in accept_list or 'deflate' in accept_list):
return too_many_requests(network, "HTTP header Accept-Encoding did not contain gzip nor deflate")
return None
|
accept_list = [l.strip() for l in request.headers.get('Accept-Encoding', '').split(',')]
if not ('gzip' in accept_list or 'deflate' in accept_list):
return too_many_requests(network, "HTTP header Accept-Encoding did not contain gzip nor deflate")
return None
| 30 | 268 | 91 | 359 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""
Method ``http_accept_encoding``
-------------------------------
The ``http_accept_encoding`` method evaluates a request as the request of a
bot if the Accept-Encoding_ header ..
- did not contain ``gzip`` AND ``deflate`` (if both values are missed)
- did not contain ``... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""
Method ``http_accept_encoding``
-------------------------------
The ``http_accept_encoding`` method evaluates a request as the request of a
bot if the Accept-Encoding_ header ..
- did not contain ``gzip`` AND ``deflate`` (if both values are missed)
- did not contain ``... | |
23,780 | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/botdetection/http_accept_language.py | 27,32 | 1,35 | filter_request | 32,35 | 32,35 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""
Method ``http_accept_language``
-------------------------------
The ``http_accept_language`` method evaluates a request as the request of a bot
if the Accept-Language_ header is unset.
.. _Accept-Language:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Us... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""
Method ``http_accept_language``
-------------------------------
The ``http_accept_language`` method evaluates a request as the request of a bot
if the Accept-Language_ header is unset.
.. _Accept-Language:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Us... | if request.headers.get('Accept-Language', '').strip() == '':
return too_many_requests(network, "missing HTTP header Accept-Language")
return None
| if request.headers.get('Accept-Language', '').strip() == '':
return too_many_requests(network, "missing HTTP header Accept-Language")
return None
| 13 | 238 | 49 | 287 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""
Method ``http_accept_language``
-------------------------------
The ``http_accept_language`` method evaluates a request as the request of a bot
if the Accept-Language_ header is unset.
.. _Accept-Language:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Us... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""
Method ``http_accept_language``
-------------------------------
The ``http_accept_language`` method evaluates a request as the request of a bot
if the Accept-Language_ header is unset.
.. _Accept-Language:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Us... | |
23,781 | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/botdetection/http_connection.py | 28,33 | 1,37 | filter_request | 33,37 | 33,37 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""
Method ``http_connection``
--------------------------
The ``http_connection`` method evaluates a request as the request of a bot if
the Connection_ header is set to ``close``.
.. _Connection:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Connection
"""
... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""
Method ``http_connection``
--------------------------
The ``http_connection`` method evaluates a request as the request of a bot if
the Connection_ header is set to ``close``.
.. _Connection:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Connection
"""
... |
if request.headers.get('Connection', '').strip() == 'close':
return too_many_requests(network, "HTTP header 'Connection=close")
return None
|
if request.headers.get('Connection', '').strip() == 'close':
return too_many_requests(network, "HTTP header 'Connection=close")
return None
| 12 | 230 | 48 | 278 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""
Method ``http_connection``
--------------------------
The ``http_connection`` method evaluates a request as the request of a bot if
the Connection_ header is set to ``close``.
.. _Connection:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Connection
"""
... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""
Method ``http_connection``
--------------------------
The ``http_connection`` method evaluates a request as the request of a bot if
the Connection_ header is set to ``close``.
.. _Connection:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Connection
"""
... | |
23,782 | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/botdetection/http_user_agent.py | 50,51 | 1,67 | regexp_user_agent | 51,57 | 51,57 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""
Method ``http_user_agent``
--------------------------
The ``http_user_agent`` method evaluates a request as the request of a bot if
the User-Agent_ header is unset or matches the regular expression
:py:obj:`USER_AGENT`.
.. _User-Agent:
https://developer.mozilla.org/... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""
Method ``http_user_agent``
--------------------------
The ``http_user_agent`` method evaluates a request as the request of a bot if
the User-Agent_ header is unset or matches the regular expression
:py:obj:`USER_AGENT`.
.. _User-Agent:
https://developer.mozilla.org/... | global _regexp # pylint: disable=global-statement
if not _regexp:
_regexp = re.compile(USER_AGENT)
return _regexp
| global _regexp # pylint: disable=global-statement
if not _regexp:
_regexp = re.compile(USER_AGENT)
return _regexp
| 13 | 721 | 54 | 775 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""
Method ``http_user_agent``
--------------------------
The ``http_user_agent`` method evaluates a request as the request of a bot if
the User-Agent_ header is unset or matches the regular expression
:py:obj:`USER_AGENT`.
.. _User-Agent:
https://developer.mozilla.org/... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""
Method ``http_user_agent``
--------------------------
The ``http_user_agent`` method evaluates a request as the request of a bot if
the User-Agent_ header is unset or matches the regular expression
:py:obj:`USER_AGENT`.
.. _User-Agent:
https://developer.mozilla.org/... | |
23,783 | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/botdetection/ip_limit.py | 92,97 | 1,147 | filter_request | 97,147 | 97,147 | # SPDX-License-Identifier: AGPL-3.0-or-later
""".. _botdetection.ip_limit:
Method ``ip_limit``
-------------------
The ``ip_limit`` method counts request from an IP in *sliding windows*. If
there are to many requests in a sliding window, the request is evaluated as a
bot request. This method requires a redis DB and... | # SPDX-License-Identifier: AGPL-3.0-or-later
""".. _botdetection.ip_limit:
Method ``ip_limit``
-------------------
The ``ip_limit`` method counts request from an IP in *sliding windows*. If
there are to many requests in a sliding window, the request is evaluated as a
bot request. This method requires a redis DB and... |
# pylint: disable=too-many-return-statements
redis_client = redisdb.client()
if network.is_link_local and not cfg['botdetection.ip_limit.filter_link_local']:
logger.debug("network %s is link-local -> not monitored by ip_limit method", network.compressed)
return None
if request.args.ge... |
# pylint: disable=too-many-return-statements
redis_client = redisdb.client()
if network.is_link_local and not cfg['botdetection.ip_limit.filter_link_local']:
logger.debug("network %s is link-local -> not monitored by ip_limit method", network.compressed)
return None
if request.args.ge... | 207 | 1,046 | 894 | 1,940 | # SPDX-License-Identifier: AGPL-3.0-or-later
""".. _botdetection.ip_limit:
Method ``ip_limit``
-------------------
The ``ip_limit`` method counts request from an IP in *sliding windows*. If
there are to many requests in a sliding window, the request is evaluated as a
bot request. This method requires a redis DB and... | # SPDX-License-Identifier: AGPL-3.0-or-later
""".. _botdetection.ip_limit:
Method ``ip_limit``
-------------------
The ``ip_limit`` method counts request from an IP in *sliding windows*. If
there are to many requests in a sliding window, the request is evaluated as a
bot request. This method requires a redis DB and... | |
23,784 | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/botdetection/ip_lists.py | 48,49 | 1,85 | pass_ip | 52,61 | 49,61 | # SPDX-License-Identifier: AGPL-3.0-or-later
""".. _botdetection.ip_lists:
Method ``ip_lists``
-------------------
The ``ip_lists`` method implements IP :py:obj:`block- <block_ip>` and
:py:obj:`pass-lists <pass_ip>`.
.. code:: toml
[botdetection.ip_lists]
pass_ip = [
'167.235.158.251', # IPv4 of check.se... | # SPDX-License-Identifier: AGPL-3.0-or-later
""".. _botdetection.ip_lists:
Method ``ip_lists``
-------------------
The ``ip_lists`` method implements IP :py:obj:`block- <block_ip>` and
:py:obj:`pass-lists <pass_ip>`.
.. code:: toml
[botdetection.ip_lists]
pass_ip = [
'167.235.158.251', # IPv4 of check.se... |
if cfg.get('botdetection.ip_lists.pass_searxng_org', default=True):
for net in SEARXNG_ORG:
net = ip_network(net, strict=False)
if real_ip.version == net.version and real_ip in net:
return True, f"IP matches {net.compressed} in SEARXNG_ORG list."
return ip_is_sub... | """Checks if the IP on the subnet is in one of the members of the
``botdetection.ip_lists.pass_ip`` list.
"""
if cfg.get('botdetection.ip_lists.pass_searxng_org', default=True):
for net in SEARXNG_ORG:
net = ip_network(net, strict=False)
if real_ip.version == net.version... | 31 | 898 | 150 | 1,048 | # SPDX-License-Identifier: AGPL-3.0-or-later
""".. _botdetection.ip_lists:
Method ``ip_lists``
-------------------
The ``ip_lists`` method implements IP :py:obj:`block- <block_ip>` and
:py:obj:`pass-lists <pass_ip>`.
.. code:: toml
[botdetection.ip_lists]
pass_ip = [
'167.235.158.251', # IPv4 of check.se... | # SPDX-License-Identifier: AGPL-3.0-or-later
""".. _botdetection.ip_lists:
Method ``ip_lists``
-------------------
The ``ip_lists`` method implements IP :py:obj:`block- <block_ip>` and
:py:obj:`pass-lists <pass_ip>`.
.. code:: toml
[botdetection.ip_lists]
pass_ip = [
'167.235.158.251', # IPv4 of check.se... | |
23,785 | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/botdetection/link_token.py | 72,73 | 1,155 | is_suspicious | 79,95 | 73,95 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""
Method ``link_token``
---------------------
The ``link_token`` method evaluates a request as :py:obj:`suspicious
<is_suspicious>` if the URL ``/client<token>.css`` is not requested by the
client. By adding a random component (the token) in the URL, a bot can not send
a... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""
Method ``link_token``
---------------------
The ``link_token`` method evaluates a request as :py:obj:`suspicious
<is_suspicious>` if the URL ``/client<token>.css`` is not requested by the
client. By adding a random component (the token) in the URL, a bot can not send
a... | redis_client = redisdb.client()
if not redis_client:
return False
ping_key = get_ping_key(network, request)
if not redis_client.get(ping_key):
logger.info("missing ping (IP: %s) / request: %s", network.compressed, ping_key)
return True
if renew:
redis_client.set(pin... | """Checks whether a valid ping is exists for this (client) network, if not
this request is rated as *suspicious*. If a valid ping exists and argument
``renew`` is ``True`` the expire time of this ping is reset to
:py:obj:`PING_LIVE_TIME`.
"""
redis_client = redisdb.client()
if not redis_cl... | 43 | 1,439 | 176 | 1,615 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""
Method ``link_token``
---------------------
The ``link_token`` method evaluates a request as :py:obj:`suspicious
<is_suspicious>` if the URL ``/client<token>.css`` is not requested by the
client. By adding a random component (the token) in the URL, a bot can not send
a... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""
Method ``link_token``
---------------------
The ``link_token`` method evaluates a request as :py:obj:`suspicious
<is_suspicious>` if the URL ``/client<token>.css`` is not requested by the
client. By adding a random component (the token) in the URL, a bot can not send
a... | |
23,786 | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/enginelib/traits.py | 119,120 | 36,193 | is_locale_supported | EngineTraits | 127,132 | 120,132 | @dataclasses.dataclass
class EngineTraits:
"""The class is intended to be instantiated for each engine."""
regions: Dict[str, str] = dataclasses.field(default_factory=dict)
"""Maps SearXNG's internal representation of a region to the one of the engine.
SearXNG's internal representation can be parsed b... | @dataclasses.dataclass
class EngineTraits:
"""The class is intended to be instantiated for each engine."""
regions: Dict[str, str] = dataclasses.field(default_factory=dict)
"""Maps SearXNG's internal representation of a region to the one of the engine.
SearXNG's internal representation can be parsed b... | if self.data_type == 'traits_v1':
return bool(self.get_region(searxng_locale) or self.get_language(searxng_locale))
raise TypeError('engine traits of type %s is unknown' % self.data_type)
| """A *locale* (SearXNG's internal representation) is considered to be
supported by the engine if the *region* or the *language* is supported
by the engine.
For verification the functions :py:func:`EngineTraits.get_region` and
:py:func:`EngineTraits.get_language` are used.
... | 18 | 1,671 | 77 | 1,748 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Engine's traits are fetched from the origin engines and stored in a JSON file
in the *data folder*. Most often traits are languages and region codes and
their mapping from SearXNG's representation to the representation in the origin
search engine. For new traits new pro... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Engine's traits are fetched from the origin engines and stored in a JSON file
in the *data folder*. Most often traits are languages and region codes and
their mapping from SearXNG's representation to the representation in the origin
search engine. For new traits new pro... |
23,787 | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/enginelib/traits.py | 29,30 | 25,36 | default | EngineTraitsEncoder | 31,36 | 30,36 | class EngineTraitsEncoder(json.JSONEncoder):
"""Encodes :class:`EngineTraits` to a serializable object, see
:class:`json.JSONEncoder`."""
def default(self, o):
FILL_FUNC_BODY | class EngineTraitsEncoder(json.JSONEncoder):
"""Encodes :class:`EngineTraits` to a serializable object, see
:class:`json.JSONEncoder`."""
def default(self, o):
"""Return dictionary of a :class:`EngineTraits` object."""
FILL_FUNC_BODY | if isinstance(o, EngineTraits):
return o.__dict__
return super().default(o)
| """Return dictionary of a :class:`EngineTraits` object."""
if isinstance(o, EngineTraits):
return o.__dict__
return super().default(o)
| 7 | 84 | 35 | 119 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Engine's traits are fetched from the origin engines and stored in a JSON file
in the *data folder*. Most often traits are languages and region codes and
their mapping from SearXNG's representation to the representation in the origin
search engine. For new traits new pro... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Engine's traits are fetched from the origin engines and stored in a JSON file
in the *data folder*. Most often traits are languages and region codes and
their mapping from SearXNG's representation to the representation in the origin
search engine. For new traits new pro... |
23,788 | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/enginelib/traits.py | 231,232 | 193,251 | set_traits | EngineTraitsMap | 236,251 | 232,251 | class EngineTraitsMap(Dict[str, EngineTraits]):
"""A python dictionary to map :class:`EngineTraits` by engine name."""
ENGINE_TRAITS_FILE = (data_dir / 'engine_traits.json').resolve()
"""File with persistence of the :py:obj:`EngineTraitsMap`."""
def save_data(self):
"""Store EngineTraitsMap in... | class EngineTraitsMap(Dict[str, EngineTraits]):
"""A python dictionary to map :class:`EngineTraits` by engine name."""
ENGINE_TRAITS_FILE = (data_dir / 'engine_traits.json').resolve()
"""File with persistence of the :py:obj:`EngineTraitsMap`."""
def save_data(self):
"""Store EngineTraitsMap in... |
engine_traits = EngineTraits(data_type='traits_v1')
if engine.name in self.keys():
engine_traits = self[engine.name]
elif engine.engine in self.keys():
# The key of the dictionary traits_map is the *engine name*
# configured in settings.xml. When multiple e... | """Set traits in a :py:obj:`Engine` namespace.
:param engine: engine instance build by :py:func:`searx.engines.load_engine`
"""
engine_traits = EngineTraits(data_type='traits_v1')
if engine.name in self.keys():
engine_traits = self[engine.name]
elif engine.... | 72 | 580 | 189 | 769 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Engine's traits are fetched from the origin engines and stored in a JSON file
in the *data folder*. Most often traits are languages and region codes and
their mapping from SearXNG's representation to the representation in the origin
search engine. For new traits new pro... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Engine's traits are fetched from the origin engines and stored in a JSON file
in the *data folder*. Most often traits are languages and region codes and
their mapping from SearXNG's representation to the representation in the origin
search engine. For new traits new pro... |
23,789 | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/engines/1337x.py | 33,34 | 1,59 | response | 34,59 | 34,59 | # SPDX-License-Identifier: AGPL-3.0-or-later
# pylint: disable=invalid-name
"""1337x
"""
from urllib.parse import quote, urljoin
from lxml import html
from searx.utils import extract_text, get_torrent_size, eval_xpath, eval_xpath_list, eval_xpath_getindex
# about
about = {
"website": 'https://1337x.to/',
"wi... | # SPDX-License-Identifier: AGPL-3.0-or-later
# pylint: disable=invalid-name
"""1337x
"""
from urllib.parse import quote, urljoin
from lxml import html
from searx.utils import extract_text, get_torrent_size, eval_xpath, eval_xpath_list, eval_xpath_getindex
# about
about = {
"website": 'https://1337x.to/',
"wi... | results = []
dom = html.fromstring(resp.text)
for result in eval_xpath_list(dom, '//table[contains(@class, "table-list")]/tbody//tr'):
href = urljoin(url, eval_xpath_getindex(result, './td[contains(@class, "name")]/a[2]/@href', 0))
title = extract_text(eval_xpath(result, './td[contains(@cl... | results = []
dom = html.fromstring(resp.text)
for result in eval_xpath_list(dom, '//table[contains(@class, "table-list")]/tbody//tr'):
href = urljoin(url, eval_xpath_getindex(result, './td[contains(@class, "name")]/a[2]/@href', 0))
title = extract_text(eval_xpath(result, './td[contains(@cl... | 65 | 306 | 355 | 661 | # SPDX-License-Identifier: AGPL-3.0-or-later
# pylint: disable=invalid-name
"""1337x
"""
from urllib.parse import quote, urljoin
from lxml import html
from searx.utils import extract_text, get_torrent_size, eval_xpath, eval_xpath_list, eval_xpath_getindex
# about
about = {
"website": 'https://1337x.to/',
"wi... | # SPDX-License-Identifier: AGPL-3.0-or-later
# pylint: disable=invalid-name
"""1337x
"""
from urllib.parse import quote, urljoin
from lxml import html
from searx.utils import extract_text, get_torrent_size, eval_xpath, eval_xpath_list, eval_xpath_getindex
# about
about = {
"website": 'https://1337x.to/',
"wi... | |
23,790 | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/engines/9gag.py | 33,34 | 1,77 | response | 34,77 | 34,77 | # SPDX-License-Identifier: AGPL-3.0-or-later
# pylint: disable=invalid-name
"""9GAG (social media)"""
from json import loads
from datetime import datetime
from urllib.parse import urlencode
about = {
"website": 'https://9gag.com/',
"wikidata_id": 'Q277421',
"official_api_documentation": None,
"use_off... | # SPDX-License-Identifier: AGPL-3.0-or-later
# pylint: disable=invalid-name
"""9GAG (social media)"""
from json import loads
from datetime import datetime
from urllib.parse import urlencode
about = {
"website": 'https://9gag.com/',
"wikidata_id": 'Q277421',
"official_api_documentation": None,
"use_off... | results = []
json_results = loads(resp.text)['data']
for result in json_results['posts']:
result_type = result['type']
# Get the not cropped version of the thumbnail when the image height is not too important
if result['images']['image700']['height'] > 400:
thumbnail =... | results = []
json_results = loads(resp.text)['data']
for result in json_results['posts']:
result_type = result['type']
# Get the not cropped version of the thumbnail when the image height is not too important
if result['images']['image700']['height'] > 400:
thumbnail =... | 98 | 276 | 443 | 719 | # SPDX-License-Identifier: AGPL-3.0-or-later
# pylint: disable=invalid-name
"""9GAG (social media)"""
from json import loads
from datetime import datetime
from urllib.parse import urlencode
about = {
"website": 'https://9gag.com/',
"wikidata_id": 'Q277421',
"official_api_documentation": None,
"use_off... | # SPDX-License-Identifier: AGPL-3.0-or-later
# pylint: disable=invalid-name
"""9GAG (social media)"""
from json import loads
from datetime import datetime
from urllib.parse import urlencode
about = {
"website": 'https://9gag.com/',
"wikidata_id": 'Q277421',
"official_api_documentation": None,
"use_off... | |
23,791 | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/engines/ahmia.py | 48,49 | 1,81 | response | 49,81 | 49,81 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""
Ahmia (Onions)
"""
from urllib.parse import urlencode, urlparse, parse_qs
from lxml.html import fromstring
from searx.engines.xpath import extract_url, extract_text, eval_xpath_list, eval_xpath
# about
about = {
"website": 'http://juhanurmihxlp77nkq76byazcldy2hlmo... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""
Ahmia (Onions)
"""
from urllib.parse import urlencode, urlparse, parse_qs
from lxml.html import fromstring
from searx.engines.xpath import extract_url, extract_text, eval_xpath_list, eval_xpath
# about
about = {
"website": 'http://juhanurmihxlp77nkq76byazcldy2hlmo... | results = []
dom = fromstring(resp.text)
# trim results so there's not way too many at once
first_result_index = page_size * (resp.search_params.get('pageno', 1) - 1)
all_results = eval_xpath_list(dom, results_xpath)
trimmed_results = all_results[first_result_index : first_result_index + page_s... | results = []
dom = fromstring(resp.text)
# trim results so there's not way too many at once
first_result_index = page_size * (resp.search_params.get('pageno', 1) - 1)
all_results = eval_xpath_list(dom, results_xpath)
trimmed_results = all_results[first_result_index : first_result_index + page_s... | 113 | 551 | 456 | 1,007 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""
Ahmia (Onions)
"""
from urllib.parse import urlencode, urlparse, parse_qs
from lxml.html import fromstring
from searx.engines.xpath import extract_url, extract_text, eval_xpath_list, eval_xpath
# about
about = {
"website": 'http://juhanurmihxlp77nkq76byazcldy2hlmo... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""
Ahmia (Onions)
"""
from urllib.parse import urlencode, urlparse, parse_qs
from lxml.html import fromstring
from searx.engines.xpath import extract_url, extract_text, eval_xpath_list, eval_xpath
# about
about = {
"website": 'http://juhanurmihxlp77nkq76byazcldy2hlmo... | |
23,792 | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/engines/apple_app_store.py | 39,40 | 1,57 | response | 40,57 | 40,57 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Apple App Store
"""
from json import loads
from urllib.parse import urlencode
from dateutil.parser import parse
about = {
"website": 'https://www.apple.com/app-store/',
"wikidata_id": 'Q368215',
"official_api_documentation": (
'https://developer.app... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Apple App Store
"""
from json import loads
from urllib.parse import urlencode
from dateutil.parser import parse
about = {
"website": 'https://www.apple.com/app-store/',
"wikidata_id": 'Q368215',
"official_api_documentation": (
'https://developer.app... | results = []
json_result = loads(resp.text)
for result in json_result['results']:
results.append(
{
'url': result['trackViewUrl'],
'title': result['trackName'],
'content': result['description'],
'img_src': result['artworkU... | results = []
json_result = loads(resp.text)
for result in json_result['results']:
results.append(
{
'url': result['trackViewUrl'],
'title': result['trackName'],
'content': result['description'],
'img_src': result['artworkU... | 28 | 348 | 141 | 489 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Apple App Store
"""
from json import loads
from urllib.parse import urlencode
from dateutil.parser import parse
about = {
"website": 'https://www.apple.com/app-store/',
"wikidata_id": 'Q368215',
"official_api_documentation": (
'https://developer.app... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Apple App Store
"""
from json import loads
from urllib.parse import urlencode
from dateutil.parser import parse
about = {
"website": 'https://www.apple.com/app-store/',
"wikidata_id": 'Q368215',
"official_api_documentation": (
'https://developer.app... | |
23,793 | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/engines/apple_maps.py | 57,58 | 1,113 | response | 58,113 | 58,113 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Apple Maps"""
from json import loads
from time import time
from urllib.parse import urlencode
from searx.network import get as http_get
from searx.engines.openstreetmap import get_key_label
about = {
"website": 'https://www.apple.com/maps/',
"wikidata_id": 'Q27... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Apple Maps"""
from json import loads
from time import time
from urllib.parse import urlencode
from searx.network import get as http_get
from searx.engines.openstreetmap import get_key_label
about = {
"website": 'https://www.apple.com/maps/',
"wikidata_id": 'Q27... | results = []
resp_json = loads(resp.text)
user_language = resp.search_params['language']
for result in resp_json['results']:
boundingbox = None
if 'displayMapRegion' in result:
box = result['displayMapRegion']
boundingbox = [box['southLat'], box['northLat'], bo... | results = []
resp_json = loads(resp.text)
user_language = resp.search_params['language']
for result in resp_json['results']:
boundingbox = None
if 'displayMapRegion' in result:
box = result['displayMapRegion']
boundingbox = [box['southLat'], box['northLat'], bo... | 111 | 571 | 534 | 1,105 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Apple Maps"""
from json import loads
from time import time
from urllib.parse import urlencode
from searx.network import get as http_get
from searx.engines.openstreetmap import get_key_label
about = {
"website": 'https://www.apple.com/maps/',
"wikidata_id": 'Q27... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Apple Maps"""
from json import loads
from time import time
from urllib.parse import urlencode
from searx.network import get as http_get
from searx.engines.openstreetmap import get_key_label
about = {
"website": 'https://www.apple.com/maps/',
"wikidata_id": 'Q27... | |
23,794 | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/engines/arxiv.py | 61,62 | 1,111 | response | 62,111 | 62,111 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""ArXiV (Scientific preprints)
"""
from datetime import datetime
from lxml import etree
from lxml.etree import XPath
from searx.utils import eval_xpath, eval_xpath_list, eval_xpath_getindex
# about
about = {
"website": 'https://arxiv.org',
"wikidata_id": 'Q11839... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""ArXiV (Scientific preprints)
"""
from datetime import datetime
from lxml import etree
from lxml.etree import XPath
from searx.utils import eval_xpath, eval_xpath_list, eval_xpath_getindex
# about
about = {
"website": 'https://arxiv.org',
"wikidata_id": 'Q11839... | results = []
dom = etree.fromstring(resp.content)
for entry in eval_xpath_list(dom, xpath_entry):
title = eval_xpath_getindex(entry, xpath_title, 0).text
url = eval_xpath_getindex(entry, xpath_id, 0).text
abstract = eval_xpath_getindex(entry, xpath_summary, 0).text
authors ... | results = []
dom = etree.fromstring(resp.content)
for entry in eval_xpath_list(dom, xpath_entry):
title = eval_xpath_getindex(entry, xpath_title, 0).text
url = eval_xpath_getindex(entry, xpath_id, 0).text
abstract = eval_xpath_getindex(entry, xpath_summary, 0).text
authors ... | 150 | 737 | 618 | 1,355 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""ArXiV (Scientific preprints)
"""
from datetime import datetime
from lxml import etree
from lxml.etree import XPath
from searx.utils import eval_xpath, eval_xpath_list, eval_xpath_getindex
# about
about = {
"website": 'https://arxiv.org',
"wikidata_id": 'Q11839... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""ArXiV (Scientific preprints)
"""
from datetime import datetime
from lxml import etree
from lxml.etree import XPath
from searx.utils import eval_xpath, eval_xpath_list, eval_xpath_getindex
# about
about = {
"website": 'https://arxiv.org',
"wikidata_id": 'Q11839... | |
23,795 | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/engines/ask.py | 39,40 | 1,75 | response | 40,75 | 40,75 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Ask.com"""
from urllib.parse import urlencode
import dateutil
from lxml import html
from searx import utils
# Metadata
about = {
"website": "https://www.ask.com/",
"wikidata_id": 'Q847564',
"official_api_documentation": None,
"use_official_api": False,
... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Ask.com"""
from urllib.parse import urlencode
import dateutil
from lxml import html
from searx import utils
# Metadata
about = {
"website": "https://www.ask.com/",
"wikidata_id": 'Q847564',
"official_api_documentation": None,
"use_official_api": False,
... |
start_tag = 'window.MESON.initialState = {'
end_tag = '}};'
dom = html.fromstring(resp.text)
script = utils.eval_xpath_getindex(dom, '//script', 0, default=None).text
pos = script.index(start_tag) + len(start_tag) - 1
script = script[pos:]
pos = script.index(end_tag) + len(end_tag) - 1
... |
start_tag = 'window.MESON.initialState = {'
end_tag = '}};'
dom = html.fromstring(resp.text)
script = utils.eval_xpath_getindex(dom, '//script', 0, default=None).text
pos = script.index(start_tag) + len(start_tag) - 1
script = script[pos:]
pos = script.index(end_tag) + len(end_tag) - 1
... | 96 | 276 | 397 | 673 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Ask.com"""
from urllib.parse import urlencode
import dateutil
from lxml import html
from searx import utils
# Metadata
about = {
"website": "https://www.ask.com/",
"wikidata_id": 'Q847564',
"official_api_documentation": None,
"use_official_api": False,
... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Ask.com"""
from urllib.parse import urlencode
import dateutil
from lxml import html
from searx import utils
# Metadata
about = {
"website": "https://www.ask.com/",
"wikidata_id": 'Q847564',
"official_api_documentation": None,
"use_official_api": False,
... | |
23,796 | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/engines/bandcamp.py | 46,47 | 1,82 | response | 47,82 | 47,82 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Bandcamp (Music)
@website https://bandcamp.com/
@provide-api no
@results HTML
@parse url, title, content, publishedDate, iframe_src, thumbnail
"""
from urllib.parse import urlencode, urlparse, parse_qs
from dateutil.parser import parse as dateparse
from l... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Bandcamp (Music)
@website https://bandcamp.com/
@provide-api no
@results HTML
@parse url, title, content, publishedDate, iframe_src, thumbnail
"""
from urllib.parse import urlencode, urlparse, parse_qs
from dateutil.parser import parse as dateparse
from l... |
results = []
dom = html.fromstring(resp.text)
for result in eval_xpath_list(dom, '//li[contains(@class, "searchresult")]'):
link = eval_xpath_getindex(result, './/div[@class="itemurl"]/a', 0, default=None)
if link is None:
continue
title = result.xpath('.//div[@class=... |
results = []
dom = html.fromstring(resp.text)
for result in eval_xpath_list(dom, '//li[contains(@class, "searchresult")]'):
link = eval_xpath_getindex(result, './/div[@class="itemurl"]/a', 0, default=None)
if link is None:
continue
title = result.xpath('.//div[@class=... | 85 | 418 | 498 | 916 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Bandcamp (Music)
@website https://bandcamp.com/
@provide-api no
@results HTML
@parse url, title, content, publishedDate, iframe_src, thumbnail
"""
from urllib.parse import urlencode, urlparse, parse_qs
from dateutil.parser import parse as dateparse
from l... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Bandcamp (Music)
@website https://bandcamp.com/
@provide-api no
@results HTML
@parse url, title, content, publishedDate, iframe_src, thumbnail
"""
from urllib.parse import urlencode, urlparse, parse_qs
from dateutil.parser import parse as dateparse
from l... | |
23,797 | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/engines/bilibili.py | 67,68 | 1,100 | response | 68,100 | 68,100 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Bilibili is a Chinese video sharing website.
.. _Bilibili: https://www.bilibili.com
"""
import random
import string
from urllib.parse import urlencode
from datetime import datetime, timedelta
# Engine metadata
about = {
"website": "https://www.bilibili.com",
"w... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Bilibili is a Chinese video sharing website.
.. _Bilibili: https://www.bilibili.com
"""
import random
import string
from urllib.parse import urlencode
from datetime import datetime, timedelta
# Engine metadata
about = {
"website": "https://www.bilibili.com",
"w... | search_res = resp.json()
results = []
for item in search_res.get("data", {}).get("result", []):
title = item["title"]
url = item["arcurl"]
thumbnail = item["pic"]
description = item["description"]
author = item["author"]
video_id = item["aid"]
unix_d... | search_res = resp.json()
results = []
for item in search_res.get("data", {}).get("result", []):
title = item["title"]
url = item["arcurl"]
thumbnail = item["pic"]
description = item["description"]
author = item["author"]
video_id = item["aid"]
unix_d... | 66 | 570 | 319 | 889 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Bilibili is a Chinese video sharing website.
.. _Bilibili: https://www.bilibili.com
"""
import random
import string
from urllib.parse import urlencode
from datetime import datetime, timedelta
# Engine metadata
about = {
"website": "https://www.bilibili.com",
"w... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Bilibili is a Chinese video sharing website.
.. _Bilibili: https://www.bilibili.com
"""
import random
import string
from urllib.parse import urlencode
from datetime import datetime, timedelta
# Engine metadata
about = {
"website": "https://www.bilibili.com",
"w... | |
23,798 | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/engines/bpb.py | 37,38 | 1,68 | response | 38,68 | 38,68 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""BPB refers to ``Bundeszentrale für poltische Bildung``, which is a German
governmental institution aiming to reduce misinformation by providing resources
about politics and history.
"""
from datetime import datetime
from urllib.parse import urlencode
about = {
'webs... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""BPB refers to ``Bundeszentrale für poltische Bildung``, which is a German
governmental institution aiming to reduce misinformation by providing resources
about politics and history.
"""
from datetime import datetime
from urllib.parse import urlencode
about = {
'webs... | results = []
json_resp = resp.json()
for result in json_resp['teaser']:
img_src = None
if result['teaser']['image']:
img_src = base_url + result['teaser']['image']['sources'][-1]['url']
metadata = result['extension']['overline']
authors = ', '.join(author['name... | results = []
json_resp = resp.json()
for result in json_resp['teaser']:
img_src = None
if result['teaser']['image']:
img_src = base_url + result['teaser']['image']['sources'][-1]['url']
metadata = result['extension']['overline']
authors = ', '.join(author['name... | 67 | 314 | 287 | 601 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""BPB refers to ``Bundeszentrale für poltische Bildung``, which is a German
governmental institution aiming to reduce misinformation by providing resources
about politics and history.
"""
from datetime import datetime
from urllib.parse import urlencode
about = {
'webs... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""BPB refers to ``Bundeszentrale für poltische Bildung``, which is a German
governmental institution aiming to reduce misinformation by providing resources
about politics and history.
"""
from datetime import datetime
from urllib.parse import urlencode
about = {
'webs... | |
23,799 | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/engines/bt4g.py | 93,94 | 1,124 | response | 94,124 | 94,124 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""BT4G_ (bt4g.com) is not a tracker and doesn't store any content and only
collects torrent metadata (such as file names and file sizes) and a magnet link
(torrent identifier).
This engine does not parse the HTML page because there is an API in XML (RSS).
The RSS feed prov... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""BT4G_ (bt4g.com) is not a tracker and doesn't store any content and only
collects torrent metadata (such as file names and file sizes) and a magnet link
(torrent identifier).
This engine does not parse the HTML page because there is an API in XML (RSS).
The RSS feed prov... | results = []
search_results = etree.XML(resp.content)
# return empty array if nothing is found
if len(search_results) == 0:
return []
for entry in search_results.xpath('./channel/item'):
title = entry.find("title").text
link = entry.find("guid").text
fullDescriptio... | results = []
search_results = etree.XML(resp.content)
# return empty array if nothing is found
if len(search_results) == 0:
return []
for entry in search_results.xpath('./channel/item'):
title = entry.find("title").text
link = entry.find("guid").text
fullDescriptio... | 74 | 775 | 339 | 1,114 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""BT4G_ (bt4g.com) is not a tracker and doesn't store any content and only
collects torrent metadata (such as file names and file sizes) and a magnet link
(torrent identifier).
This engine does not parse the HTML page because there is an API in XML (RSS).
The RSS feed prov... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""BT4G_ (bt4g.com) is not a tracker and doesn't store any content and only
collects torrent metadata (such as file names and file sizes) and a magnet link
(torrent identifier).
This engine does not parse the HTML page because there is an API in XML (RSS).
The RSS feed prov... | |
23,800 | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/engines/btdigg.py | 38,39 | 1,91 | response | 39,91 | 39,91 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""
BTDigg (Videos, Music, Files)
"""
from urllib.parse import quote, urljoin
from lxml import html
from searx.utils import extract_text, get_torrent_size
# about
about = {
"website": 'https://btdig.com',
"wikidata_id": 'Q4836698',
"official_api_documentation... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""
BTDigg (Videos, Music, Files)
"""
from urllib.parse import quote, urljoin
from lxml import html
from searx.utils import extract_text, get_torrent_size
# about
about = {
"website": 'https://btdig.com',
"wikidata_id": 'Q4836698',
"official_api_documentation... | results = []
dom = html.fromstring(resp.text)
search_res = dom.xpath('//div[@class="one_result"]')
# return empty array if nothing is found
if not search_res:
return []
# parse results
for result in search_res:
link = result.xpath('.//div[@class="torrent_name"]//a')[0]
... | results = []
dom = html.fromstring(resp.text)
search_res = dom.xpath('//div[@class="one_result"]')
# return empty array if nothing is found
if not search_res:
return []
# parse results
for result in search_res:
link = result.xpath('.//div[@class="torrent_name"]//a')[0]
... | 145 | 325 | 611 | 936 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""
BTDigg (Videos, Music, Files)
"""
from urllib.parse import quote, urljoin
from lxml import html
from searx.utils import extract_text, get_torrent_size
# about
about = {
"website": 'https://btdig.com',
"wikidata_id": 'Q4836698',
"official_api_documentation... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""
BTDigg (Videos, Music, Files)
"""
from urllib.parse import quote, urljoin
from lxml import html
from searx.utils import extract_text, get_torrent_size
# about
about = {
"website": 'https://btdig.com',
"wikidata_id": 'Q4836698',
"official_api_documentation... | |
23,801 | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/engines/ccc_media.py | 29,30 | 1,60 | response | 30,60 | 30,60 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""media.ccc.de"""
import datetime
from urllib.parse import urlencode
from dateutil import parser
about = {
'website': 'https://media.ccc.de',
'official_api_documentation': 'https://github.com/voc/voctoweb',
'use_official_api': True,
'require_api_key': Fal... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""media.ccc.de"""
import datetime
from urllib.parse import urlencode
from dateutil import parser
about = {
'website': 'https://media.ccc.de',
'official_api_documentation': 'https://github.com/voc/voctoweb',
'use_official_api': True,
'require_api_key': Fal... | results = []
for item in resp.json()['events']:
publishedDate = None
if item.get('date'):
publishedDate = parser.parse(item['date'])
iframe_src = None
for rec in item['recordings']:
if rec['mime_type'].startswith('video'):
if not iframe_s... | results = []
for item in resp.json()['events']:
publishedDate = None
if item.get('date'):
publishedDate = parser.parse(item['date'])
iframe_src = None
for rec in item['recordings']:
if rec['mime_type'].startswith('video'):
if not iframe_s... | 65 | 237 | 295 | 532 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""media.ccc.de"""
import datetime
from urllib.parse import urlencode
from dateutil import parser
about = {
'website': 'https://media.ccc.de',
'official_api_documentation': 'https://github.com/voc/voctoweb',
'use_official_api': True,
'require_api_key': Fal... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""media.ccc.de"""
import datetime
from urllib.parse import urlencode
from dateutil import parser
about = {
'website': 'https://media.ccc.de',
'official_api_documentation': 'https://github.com/voc/voctoweb',
'use_official_api': True,
'require_api_key': Fal... | |
23,802 | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/engines/chefkoch.py | 34,35 | 1,72 | response | 35,72 | 35,72 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Chefkoch is a German database of recipes.
"""
from datetime import datetime
from urllib.parse import urlencode
about = {
'website': "https://www.chefkoch.de",
'official_api_documentation': None,
'use_official_api': False,
'require_api_key': False,
'r... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Chefkoch is a German database of recipes.
"""
from datetime import datetime
from urllib.parse import urlencode
about = {
'website': "https://www.chefkoch.de",
'official_api_documentation': None,
'use_official_api': False,
'require_api_key': False,
'r... | results = []
json = resp.json()
for result in json['results']:
recipe = result['recipe']
if skip_premium and (recipe['isPremium'] or recipe['isPlus']):
continue
publishedDate = None
if recipe['submissionDate']:
publishedDate = datetime.strptime(res... | results = []
json = resp.json()
for result in json['results']:
recipe = result['recipe']
if skip_premium and (recipe['isPremium'] or recipe['isPlus']):
continue
publishedDate = None
if recipe['submissionDate']:
publishedDate = datetime.strptime(res... | 77 | 297 | 341 | 638 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Chefkoch is a German database of recipes.
"""
from datetime import datetime
from urllib.parse import urlencode
about = {
'website': "https://www.chefkoch.de",
'official_api_documentation': None,
'use_official_api': False,
'require_api_key': False,
'r... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Chefkoch is a German database of recipes.
"""
from datetime import datetime
from urllib.parse import urlencode
about = {
'website': "https://www.chefkoch.de",
'official_api_documentation': None,
'use_official_api': False,
'require_api_key': False,
'r... | |
23,804 | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/engines/core.py | 46,47 | 1,116 | response | 47,116 | 47,116 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""CORE (science)
"""
from datetime import datetime
from urllib.parse import urlencode
from searx.exceptions import SearxEngineAPIException
about = {
"website": 'https://core.ac.uk',
"wikidata_id": 'Q22661180',
"official_api_documentation": 'https://core.ac.u... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""CORE (science)
"""
from datetime import datetime
from urllib.parse import urlencode
from searx.exceptions import SearxEngineAPIException
about = {
"website": 'https://core.ac.uk',
"wikidata_id": 'Q22661180',
"official_api_documentation": 'https://core.ac.u... | results = []
json_data = resp.json()
for result in json_data['data']:
source = result['_source']
url = None
if source.get('urls'):
url = source['urls'][0].replace('http://', 'https://', 1)
if url is None and source.get('doi'):
# use the DOI reference... | results = []
json_data = resp.json()
for result in json_data['data']:
source = result['_source']
url = None
if source.get('urls'):
url = source['urls'][0].replace('http://', 'https://', 1)
if url is None and source.get('doi'):
# use the DOI reference... | 225 | 396 | 775 | 1,171 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""CORE (science)
"""
from datetime import datetime
from urllib.parse import urlencode
from searx.exceptions import SearxEngineAPIException
about = {
"website": 'https://core.ac.uk',
"wikidata_id": 'Q22661180',
"official_api_documentation": 'https://core.ac.u... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""CORE (science)
"""
from datetime import datetime
from urllib.parse import urlencode
from searx.exceptions import SearxEngineAPIException
about = {
"website": 'https://core.ac.uk',
"wikidata_id": 'Q22661180',
"official_api_documentation": 'https://core.ac.u... | |
23,805 | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/engines/cppreference.py | 28,29 | 1,39 | response | 29,39 | 29,39 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Cppreference
"""
from lxml import html
from searx.utils import eval_xpath
about = {
"website": "https://en.cppreference.com/",
"wikidata_id": None,
"official_api_documentation": None,
"use_official_api": False,
"require_api_key": False,
"results"... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Cppreference
"""
from lxml import html
from searx.utils import eval_xpath
about = {
"website": "https://en.cppreference.com/",
"wikidata_id": None,
"official_api_documentation": None,
"use_official_api": False,
"require_api_key": False,
"results"... | results = []
dom = html.fromstring(resp.text)
for result in eval_xpath(dom, '//div[contains(@class, "mw-search-result-heading")]'):
results.append(
{
'url': url + eval_xpath(result, './/a/@href')[0],
'title': eval_xpath(result, './/a/text()')[0],
... | results = []
dom = html.fromstring(resp.text)
for result in eval_xpath(dom, '//div[contains(@class, "mw-search-result-heading")]'):
results.append(
{
'url': url + eval_xpath(result, './/a/@href')[0],
'title': eval_xpath(result, './/a/text()')[0],
... | 26 | 227 | 128 | 355 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Cppreference
"""
from lxml import html
from searx.utils import eval_xpath
about = {
"website": "https://en.cppreference.com/",
"wikidata_id": None,
"official_api_documentation": None,
"use_official_api": False,
"require_api_key": False,
"results"... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Cppreference
"""
from lxml import html
from searx.utils import eval_xpath
about = {
"website": "https://en.cppreference.com/",
"wikidata_id": None,
"official_api_documentation": None,
"use_official_api": False,
"require_api_key": False,
"results"... | |
23,806 | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/engines/crossref.py | 26,27 | 1,64 | response | 27,64 | 27,64 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""CrossRef"""
from urllib.parse import urlencode
from datetime import datetime
about = {
"website": "https://www.crossref.org/",
"wikidata_id": "Q5188229",
"official_api_documentation": "https://api.crossref.org",
"use_official_api": False,
"require_ap... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""CrossRef"""
from urllib.parse import urlencode
from datetime import datetime
about = {
"website": "https://www.crossref.org/",
"wikidata_id": "Q5188229",
"official_api_documentation": "https://api.crossref.org",
"use_official_api": False,
"require_ap... | results = []
for record in resp.json()["message"]["items"]:
if record["type"] == "component":
# These seem to be files published along with papers. Not something you'd search for
continue
result = {
"template": "paper.html",
"content": record.get(... | results = []
for record in resp.json()["message"]["items"]:
if record["type"] == "component":
# These seem to be files published along with papers. Not something you'd search for
continue
result = {
"template": "paper.html",
"content": record.get(... | 163 | 244 | 590 | 834 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""CrossRef"""
from urllib.parse import urlencode
from datetime import datetime
about = {
"website": "https://www.crossref.org/",
"wikidata_id": "Q5188229",
"official_api_documentation": "https://api.crossref.org",
"use_official_api": False,
"require_ap... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""CrossRef"""
from urllib.parse import urlencode
from datetime import datetime
about = {
"website": "https://www.crossref.org/",
"wikidata_id": "Q5188229",
"official_api_documentation": "https://api.crossref.org",
"use_official_api": False,
"require_ap... | |
23,807 | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/engines/currency_convert.py | 31,32 | 1,51 | response | 32,51 | 32,51 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Currency convert (DuckDuckGo)
"""
import json
# about
about = {
"website": 'https://duckduckgo.com/',
"wikidata_id": 'Q12805',
"official_api_documentation": 'https://duckduckgo.com/api',
"use_official_api": False,
"require_api_key": False,
"resul... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Currency convert (DuckDuckGo)
"""
import json
# about
about = {
"website": 'https://duckduckgo.com/',
"wikidata_id": 'Q12805',
"official_api_documentation": 'https://duckduckgo.com/api',
"use_official_api": False,
"require_api_key": False,
"resul... | # remove first and last lines to get only json
json_resp = resp.text[resp.text.find('\n') + 1 : resp.text.rfind('\n') - 2]
try:
conversion_rate = float(json.loads(json_resp)["to"][0]["mid"])
except IndexError:
return []
answer = '{0} {1} = {2} {3}, 1 {1} ({5}) = {4} {3} ({6})'.format... | # remove first and last lines to get only json
json_resp = resp.text[resp.text.find('\n') + 1 : resp.text.rfind('\n') - 2]
try:
conversion_rate = float(json.loads(json_resp)["to"][0]["mid"])
except IndexError:
return []
answer = '{0} {1} = {2} {3}, 1 {1} ({5}) = {4} {3} ({6})'.format... | 59 | 266 | 285 | 551 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Currency convert (DuckDuckGo)
"""
import json
# about
about = {
"website": 'https://duckduckgo.com/',
"wikidata_id": 'Q12805',
"official_api_documentation": 'https://duckduckgo.com/api',
"use_official_api": False,
"require_api_key": False,
"resul... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Currency convert (DuckDuckGo)
"""
import json
# about
about = {
"website": 'https://duckduckgo.com/',
"wikidata_id": 'Q12805',
"official_api_documentation": 'https://duckduckgo.com/api',
"use_official_api": False,
"require_api_key": False,
"resul... | |
23,808 | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/engines/deepl.py | 42,43 | 1,57 | response | 43,57 | 43,57 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Deepl translation engine"""
from json import loads
about = {
"website": 'https://deepl.com',
"wikidata_id": 'Q43968444',
"official_api_documentation": 'https://www.deepl.com/docs-api',
"use_official_api": True,
"require_api_key": True,
"results":... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Deepl translation engine"""
from json import loads
about = {
"website": 'https://deepl.com',
"wikidata_id": 'Q43968444',
"official_api_documentation": 'https://www.deepl.com/docs-api',
"use_official_api": True,
"require_api_key": True,
"results":... | results = []
result = loads(resp.text)
translations = result['translations']
infobox = "<dl>"
for translation in translations:
infobox += f"<dd>{translation['text']}</dd>"
infobox += "</dl>"
results.append({'answer': infobox})
return results
| results = []
result = loads(resp.text)
translations = result['translations']
infobox = "<dl>"
for translation in translations:
infobox += f"<dd>{translation['text']}</dd>"
infobox += "</dl>"
results.append({'answer': infobox})
return results
| 26 | 361 | 115 | 476 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Deepl translation engine"""
from json import loads
about = {
"website": 'https://deepl.com',
"wikidata_id": 'Q43968444',
"official_api_documentation": 'https://www.deepl.com/docs-api',
"use_official_api": True,
"require_api_key": True,
"results":... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Deepl translation engine"""
from json import loads
about = {
"website": 'https://deepl.com',
"wikidata_id": 'Q43968444',
"official_api_documentation": 'https://www.deepl.com/docs-api',
"use_official_api": True,
"require_api_key": True,
"results":... | |
23,809 | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/engines/deezer.py | 39,40 | 1,62 | response | 40,62 | 40,62 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""
Deezer (Music)
"""
from json import loads
from urllib.parse import urlencode
# about
about = {
"website": 'https://deezer.com',
"wikidata_id": 'Q602243',
"official_api_documentation": 'https://developers.deezer.com/',
"use_official_api": True,
"req... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""
Deezer (Music)
"""
from json import loads
from urllib.parse import urlencode
# about
about = {
"website": 'https://deezer.com',
"wikidata_id": 'Q602243',
"official_api_documentation": 'https://developers.deezer.com/',
"use_official_api": True,
"req... | results = []
search_res = loads(resp.text)
# parse results
for result in search_res.get('data', []):
if result['type'] == 'track':
title = result['title']
url = result['link'] # pylint: disable=redefined-outer-name
if url.startswith('http://'):
... | results = []
search_res = loads(resp.text)
# parse results
for result in search_res.get('data', []):
if result['type'] == 'track':
title = result['title']
url = result['link'] # pylint: disable=redefined-outer-name
if url.startswith('http://'):
... | 61 | 330 | 224 | 554 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""
Deezer (Music)
"""
from json import loads
from urllib.parse import urlencode
# about
about = {
"website": 'https://deezer.com',
"wikidata_id": 'Q602243',
"official_api_documentation": 'https://developers.deezer.com/',
"use_official_api": True,
"req... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""
Deezer (Music)
"""
from json import loads
from urllib.parse import urlencode
# about
about = {
"website": 'https://deezer.com',
"wikidata_id": 'Q602243',
"official_api_documentation": 'https://developers.deezer.com/',
"use_official_api": True,
"req... | |
23,810 | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/engines/demo_offline.py | 51,52 | 1,73 | search | 58,73 | 52,73 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Within this module we implement a *demo offline engine*. Do not look to
close to the implementation, its just a simple example. To get in use of this
*demo* engine add the following entry to your engines list in ``settings.yml``:
.. code:: yaml
- name: my offline en... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Within this module we implement a *demo offline engine*. Do not look to
close to the implementation, its just a simple example. To get in use of this
*demo* engine add the following entry to your engines list in ``settings.yml``:
.. code:: yaml
- name: my offline en... | ret_val = []
result_list = json.loads(_my_offline_engine)
for row in result_list:
entry = {
'query': query,
'language': request_params['searxng_locale'],
'value': row.get("value"),
# choose a result template or comment out to use the *default*
... | """Query (offline) engine and return results. Assemble the list of results from
your local engine. In this demo engine we ignore the 'query' term, usual
you would pass the 'query' term to your local engine to filter out the
results.
"""
ret_val = []
result_list = json.loads(_my_offline_e... | 37 | 476 | 138 | 614 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Within this module we implement a *demo offline engine*. Do not look to
close to the implementation, its just a simple example. To get in use of this
*demo* engine add the following entry to your engines list in ``settings.yml``:
.. code:: yaml
- name: my offline en... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Within this module we implement a *demo offline engine*. Do not look to
close to the implementation, its just a simple example. To get in use of this
*demo* engine add the following entry to your engines list in ``settings.yml``:
.. code:: yaml
- name: my offline en... | |
23,811 | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/engines/demo_online.py | 73,74 | 1,99 | response | 79,99 | 74,99 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Within this module we implement a *demo online engine*. Do not look to
close to the implementation, its just a simple example which queries `The Art
Institute of Chicago <https://www.artic.edu>`_
To get in use of this *demo* engine add the following entry to your engine... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Within this module we implement a *demo online engine*. Do not look to
close to the implementation, its just a simple example which queries `The Art
Institute of Chicago <https://www.artic.edu>`_
To get in use of this *demo* engine add the following entry to your engine... | results = []
json_data = loads(resp.text)
for result in json_data['data']:
if not result['image_id']:
continue
results.append(
{
'url': 'https://artic.edu/artworks/%(id)s' % result,
'title': result['title'] + " (%(date_display)s) // ... | """Parse out the result items from the response. In this example we parse the
response from `api.artic.edu <https://artic.edu>`__ and filter out all
images.
"""
results = []
json_data = loads(resp.text)
for result in json_data['data']:
if not result['image_id']:
conti... | 50 | 677 | 231 | 908 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Within this module we implement a *demo online engine*. Do not look to
close to the implementation, its just a simple example which queries `The Art
Institute of Chicago <https://www.artic.edu>`_
To get in use of this *demo* engine add the following entry to your engine... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Within this module we implement a *demo online engine*. Do not look to
close to the implementation, its just a simple example which queries `The Art
Institute of Chicago <https://www.artic.edu>`_
To get in use of this *demo* engine add the following entry to your engine... | |
23,812 | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/engines/destatis.py | 34,35 | 1,68 | request | 35,43 | 35,43 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""DeStatis
"""
from urllib.parse import urlencode
from lxml import html
from searx.utils import eval_xpath, eval_xpath_list, extract_text
about = {
'website': 'https://www.destatis.de',
'official_api_documentation': 'https://destatis.api.bund.dev/',
'use_offic... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""DeStatis
"""
from urllib.parse import urlencode
from lxml import html
from searx.utils import eval_xpath, eval_xpath_list, extract_text
about = {
'website': 'https://www.destatis.de',
'official_api_documentation': 'https://destatis.api.bund.dev/',
'use_offic... | args = {
'templateQueryString': query,
'gtp': f"474_list%3D{params['pageno']}",
}
params['url'] = f"{search_url}?{urlencode(args)}"
return params
| args = {
'templateQueryString': query,
'gtp': f"474_list%3D{params['pageno']}",
}
params['url'] = f"{search_url}?{urlencode(args)}"
return params
| 13 | 729 | 78 | 807 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""DeStatis
"""
from urllib.parse import urlencode
from lxml import html
from searx.utils import eval_xpath, eval_xpath_list, extract_text
about = {
'website': 'https://www.destatis.de',
'official_api_documentation': 'https://destatis.api.bund.dev/',
'use_offic... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""DeStatis
"""
from urllib.parse import urlencode
from lxml import html
from searx.utils import eval_xpath, eval_xpath_list, extract_text
about = {
'website': 'https://www.destatis.de',
'official_api_documentation': 'https://destatis.api.bund.dev/',
'use_offic... | |
23,813 | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/engines/deviantart.py | 52,53 | 1,88 | response | 53,88 | 53,88 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Deviantart (Images)
"""
import urllib.parse
from lxml import html
from searx.utils import extract_text, eval_xpath, eval_xpath_list
# about
about = {
"website": 'https://www.deviantart.com/',
"wikidata_id": 'Q46523',
"official_api_documentation": 'https://... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Deviantart (Images)
"""
import urllib.parse
from lxml import html
from searx.utils import extract_text, eval_xpath, eval_xpath_list
# about
about = {
"website": 'https://www.deviantart.com/',
"wikidata_id": 'Q46523',
"official_api_documentation": 'https://... |
results = []
dom = html.fromstring(resp.text)
for result in eval_xpath_list(dom, results_xpath):
# skip images that are blurred
_text = extract_text(eval_xpath(result, premium_xpath))
if _text and premium_keytext in _text:
continue
img_src = extract_text(eval_xp... |
results = []
dom = html.fromstring(resp.text)
for result in eval_xpath_list(dom, results_xpath):
# skip images that are blurred
_text = extract_text(eval_xpath(result, premium_xpath))
if _text and premium_keytext in _text:
continue
img_src = extract_text(eval_xp... | 78 | 518 | 409 | 927 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Deviantart (Images)
"""
import urllib.parse
from lxml import html
from searx.utils import extract_text, eval_xpath, eval_xpath_list
# about
about = {
"website": 'https://www.deviantart.com/',
"wikidata_id": 'Q46523',
"official_api_documentation": 'https://... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Deviantart (Images)
"""
import urllib.parse
from lxml import html
from searx.utils import extract_text, eval_xpath, eval_xpath_list
# about
about = {
"website": 'https://www.deviantart.com/',
"wikidata_id": 'Q46523',
"official_api_documentation": 'https://... | |
23,814 | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/engines/dictzone.py | 35,36 | 1,61 | response | 36,61 | 36,61 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""
Dictzone
"""
from urllib.parse import urljoin
from lxml import html
from searx.utils import eval_xpath
# about
about = {
"website": 'https://dictzone.com/',
"wikidata_id": None,
"official_api_documentation": None,
"use_official_api": False,
"requir... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""
Dictzone
"""
from urllib.parse import urljoin
from lxml import html
from searx.utils import eval_xpath
# about
about = {
"website": 'https://dictzone.com/',
"wikidata_id": None,
"official_api_documentation": None,
"use_official_api": False,
"requir... | results = []
dom = html.fromstring(resp.text)
for k, result in enumerate(eval_xpath(dom, results_xpath)[1:]):
try:
from_result, to_results_raw = eval_xpath(result, './td')
except: # pylint: disable=bare-except
continue
to_results = []
for to_result... | results = []
dom = html.fromstring(resp.text)
for k, result in enumerate(eval_xpath(dom, results_xpath)[1:]):
try:
from_result, to_results_raw = eval_xpath(result, './td')
except: # pylint: disable=bare-except
continue
to_results = []
for to_result... | 53 | 306 | 254 | 560 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""
Dictzone
"""
from urllib.parse import urljoin
from lxml import html
from searx.utils import eval_xpath
# about
about = {
"website": 'https://dictzone.com/',
"wikidata_id": None,
"official_api_documentation": None,
"use_official_api": False,
"requir... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""
Dictzone
"""
from urllib.parse import urljoin
from lxml import html
from searx.utils import eval_xpath
# about
about = {
"website": 'https://dictzone.com/',
"wikidata_id": None,
"official_api_documentation": None,
"use_official_api": False,
"requir... | |
23,815 | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/engines/digbt.py | 35,36 | 1,65 | response | 36,65 | 36,65 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""
DigBT (Videos, Music, Files)
"""
from urllib.parse import urljoin
from lxml import html
from searx.utils import extract_text, get_torrent_size
# about
about = {
"website": 'https://digbt.org',
"wikidata_id": None,
"official_api_documentation": None,
"u... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""
DigBT (Videos, Music, Files)
"""
from urllib.parse import urljoin
from lxml import html
from searx.utils import extract_text, get_torrent_size
# about
about = {
"website": 'https://digbt.org',
"wikidata_id": None,
"official_api_documentation": None,
"u... | dom = html.fromstring(resp.text)
search_res = dom.xpath('.//td[@class="x-item"]')
if not search_res:
return []
results = []
for result in search_res:
url = urljoin(URL, result.xpath('.//a[@title]/@href')[0])
title = extract_text(result.xpath('.//a[@title]'))
content... | dom = html.fromstring(resp.text)
search_res = dom.xpath('.//td[@class="x-item"]')
if not search_res:
return []
results = []
for result in search_res:
url = urljoin(URL, result.xpath('.//a[@title]/@href')[0])
title = extract_text(result.xpath('.//a[@title]'))
content... | 60 | 280 | 351 | 631 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""
DigBT (Videos, Music, Files)
"""
from urllib.parse import urljoin
from lxml import html
from searx.utils import extract_text, get_torrent_size
# about
about = {
"website": 'https://digbt.org',
"wikidata_id": None,
"official_api_documentation": None,
"u... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""
DigBT (Videos, Music, Files)
"""
from urllib.parse import urljoin
from lxml import html
from searx.utils import extract_text, get_torrent_size
# about
about = {
"website": 'https://digbt.org',
"wikidata_id": None,
"official_api_documentation": None,
"u... | |
23,816 | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/engines/docker_hub.py | 26,27 | 1,60 | request | 27,34 | 27,34 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Docker Hub (IT)
"""
# pylint: disable=use-dict-literal
from urllib.parse import urlencode
from dateutil import parser
about = {
"website": 'https://hub.docker.com',
"wikidata_id": 'Q100769064',
"official_api_documentation": 'https://docs.docker.com/registry... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Docker Hub (IT)
"""
# pylint: disable=use-dict-literal
from urllib.parse import urlencode
from dateutil import parser
about = {
"website": 'https://hub.docker.com',
"wikidata_id": 'Q100769064',
"official_api_documentation": 'https://docs.docker.com/registry... |
params['url'] = search_url.format(query=urlencode(dict(q=query, page=params["pageno"])))
params["headers"]["Search-Version"] = "v3"
return params
|
params['url'] = search_url.format(query=urlencode(dict(q=query, page=params["pageno"])))
params["headers"]["Search-Version"] = "v3"
return params
| 9 | 556 | 64 | 620 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Docker Hub (IT)
"""
# pylint: disable=use-dict-literal
from urllib.parse import urlencode
from dateutil import parser
about = {
"website": 'https://hub.docker.com',
"wikidata_id": 'Q100769064',
"official_api_documentation": 'https://docs.docker.com/registry... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Docker Hub (IT)
"""
# pylint: disable=use-dict-literal
from urllib.parse import urlencode
from dateutil import parser
about = {
"website": 'https://hub.docker.com',
"wikidata_id": 'Q100769064',
"official_api_documentation": 'https://docs.docker.com/registry... | |
23,817 | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/engines/doku.py | 47,48 | 1,87 | response | 48,87 | 48,87 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""
Doku Wiki
"""
from urllib.parse import urlencode
from lxml.html import fromstring
from searx.utils import extract_text, eval_xpath
# about
about = {
"website": 'https://www.dokuwiki.org/',
"wikidata_id": 'Q851864',
"official_api_documentation": 'https://ww... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""
Doku Wiki
"""
from urllib.parse import urlencode
from lxml.html import fromstring
from searx.utils import extract_text, eval_xpath
# about
about = {
"website": 'https://www.dokuwiki.org/',
"wikidata_id": 'Q851864',
"official_api_documentation": 'https://ww... | results = []
doc = fromstring(resp.text)
# parse results
# Quickhits
for r in eval_xpath(doc, '//div[@class="search_quickresult"]/ul/li'):
try:
res_url = eval_xpath(r, './/a[@class="wikilink1"]/@href')[-1]
except: # pylint: disable=bare-except
continue
... | results = []
doc = fromstring(resp.text)
# parse results
# Quickhits
for r in eval_xpath(doc, '//div[@class="search_quickresult"]/ul/li'):
try:
res_url = eval_xpath(r, './/a[@class="wikilink1"]/@href')[-1]
except: # pylint: disable=bare-except
continue
... | 99 | 380 | 454 | 834 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""
Doku Wiki
"""
from urllib.parse import urlencode
from lxml.html import fromstring
from searx.utils import extract_text, eval_xpath
# about
about = {
"website": 'https://www.dokuwiki.org/',
"wikidata_id": 'Q851864',
"official_api_documentation": 'https://ww... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""
Doku Wiki
"""
from urllib.parse import urlencode
from lxml.html import fromstring
from searx.utils import extract_text, eval_xpath
# about
about = {
"website": 'https://www.dokuwiki.org/',
"wikidata_id": 'Q851864',
"official_api_documentation": 'https://ww... | |
23,818 | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/engines/duden.py | 46,47 | 1,72 | response | 47,72 | 47,72 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Duden
"""
import re
from urllib.parse import quote, urljoin
from lxml import html
from searx.utils import extract_text, eval_xpath, eval_xpath_list, eval_xpath_getindex
from searx.network import raise_for_httperror
# about
about = {
"website": 'https://www.duden.de... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Duden
"""
import re
from urllib.parse import quote, urljoin
from lxml import html
from searx.utils import extract_text, eval_xpath, eval_xpath_list, eval_xpath_getindex
from searx.network import raise_for_httperror
# about
about = {
"website": 'https://www.duden.de... | results = []
if resp.status_code == 404:
return results
raise_for_httperror(resp)
dom = html.fromstring(resp.text)
number_of_results_element = eval_xpath_getindex(
dom, '//a[@class="active" and contains(@href,"/suchen/dudenonline")]/span/text()', 0, default=None
)
if numb... | results = []
if resp.status_code == 404:
return results
raise_for_httperror(resp)
dom = html.fromstring(resp.text)
number_of_results_element = eval_xpath_getindex(
dom, '//a[@class="active" and contains(@href,"/suchen/dudenonline")]/span/text()', 0, default=None
)
if numb... | 69 | 452 | 355 | 807 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Duden
"""
import re
from urllib.parse import quote, urljoin
from lxml import html
from searx.utils import extract_text, eval_xpath, eval_xpath_list, eval_xpath_getindex
from searx.network import raise_for_httperror
# about
about = {
"website": 'https://www.duden.de... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Duden
"""
import re
from urllib.parse import quote, urljoin
from lxml import html
from searx.utils import extract_text, eval_xpath, eval_xpath_list, eval_xpath_getindex
from searx.network import raise_for_httperror
# about
about = {
"website": 'https://www.duden.de... | |
23,819 | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/engines/dummy-offline.py | 18,19 | 1,24 | search | 19,24 | 19,24 | # SPDX-License-Identifier: AGPL-3.0-or-later
# pylint: disable=invalid-name
"""Dummy Offline
"""
# about
about = {
"wikidata_id": None,
"official_api_documentation": None,
"use_official_api": False,
"require_api_key": False,
"results": 'HTML',
}
def search(query, request_params): # pylint: dis... | # SPDX-License-Identifier: AGPL-3.0-or-later
# pylint: disable=invalid-name
"""Dummy Offline
"""
# about
about = {
"wikidata_id": None,
"official_api_documentation": None,
"use_official_api": False,
"require_api_key": False,
"results": 'HTML',
}
def search(query, request_params): # pylint: dis... | return [
{
'result': 'this is what you get',
}
]
| return [
{
'result': 'this is what you get',
}
]
| 11 | 141 | 30 | 171 | # SPDX-License-Identifier: AGPL-3.0-or-later
# pylint: disable=invalid-name
"""Dummy Offline
"""
# about
about = {
"wikidata_id": None,
"official_api_documentation": None,
"use_official_api": False,
"require_api_key": False,
"results": 'HTML',
}
def search(query, request_params): # pylint: dis... | # SPDX-License-Identifier: AGPL-3.0-or-later
# pylint: disable=invalid-name
"""Dummy Offline
"""
# about
about = {
"wikidata_id": None,
"official_api_documentation": None,
"use_official_api": False,
"require_api_key": False,
"results": 'HTML',
}
def search(query, request_params): # pylint: dis... | |
23,820 | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/engines/dummy.py | 18,19 | 1,25 | request | 19,23 | 19,23 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Dummy
"""
# about
about = {
"website": None,
"wikidata_id": None,
"official_api_documentation": None,
"use_official_api": False,
"require_api_key": False,
"results": 'empty array',
}
# do search-request
def request(query, params): # pylint: di... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Dummy
"""
# about
about = {
"website": None,
"wikidata_id": None,
"official_api_documentation": None,
"use_official_api": False,
"require_api_key": False,
"results": 'empty array',
}
# do search-request
def request(query, params): # pylint: di... | return params
# get response from search-request
| return params
# get response from search-request
| 7 | 162 | 18 | 180 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Dummy
"""
# about
about = {
"website": None,
"wikidata_id": None,
"official_api_documentation": None,
"use_official_api": False,
"require_api_key": False,
"results": 'empty array',
}
# do search-request
def request(query, params): # pylint: di... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Dummy
"""
# about
about = {
"website": None,
"wikidata_id": None,
"official_api_documentation": None,
"use_official_api": False,
"require_api_key": False,
"results": 'empty array',
}
# do search-request
def request(query, params): # pylint: di... | |
23,821 | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/engines/ebay.py | 44,45 | 1,78 | response | 45,78 | 45,78 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""
Ebay (Videos, Music, Files)
"""
from urllib.parse import quote
from lxml import html
from searx.engines.xpath import extract_text
# about
about = {
"website": 'https://www.ebay.com',
"wikidata_id": 'Q58024',
"official_api_documentation": 'https://develope... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""
Ebay (Videos, Music, Files)
"""
from urllib.parse import quote
from lxml import html
from searx.engines.xpath import extract_text
# about
about = {
"website": 'https://www.ebay.com',
"wikidata_id": 'Q58024',
"official_api_documentation": 'https://develope... | results = []
dom = html.fromstring(resp.text)
results_dom = dom.xpath(results_xpath)
if not results_dom:
return []
for result_dom in results_dom:
url = extract_text(result_dom.xpath(url_xpath))
title = extract_text(result_dom.xpath(title_xpath))
content = extract_te... | results = []
dom = html.fromstring(resp.text)
results_dom = dom.xpath(results_xpath)
if not results_dom:
return []
for result_dom in results_dom:
url = extract_text(result_dom.xpath(url_xpath))
title = extract_text(result_dom.xpath(title_xpath))
content = extract_te... | 66 | 518 | 337 | 855 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""
Ebay (Videos, Music, Files)
"""
from urllib.parse import quote
from lxml import html
from searx.engines.xpath import extract_text
# about
about = {
"website": 'https://www.ebay.com',
"wikidata_id": 'Q58024',
"official_api_documentation": 'https://develope... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""
Ebay (Videos, Music, Files)
"""
from urllib.parse import quote
from lxml import html
from searx.engines.xpath import extract_text
# about
about = {
"website": 'https://www.ebay.com',
"wikidata_id": 'Q58024',
"official_api_documentation": 'https://develope... | |
23,822 | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/engines/elasticsearch.py | 82,83 | 1,179 | _match_query | 88,97 | 83,97 | # SPDX-License-Identifier: AGPL-3.0-or-later
""".. sidebar:: info
- :origin:`elasticsearch.py <searx/engines/elasticsearch.py>`
- `Elasticsearch <https://www.elastic.co/elasticsearch/>`_
- `Elasticsearch Guide
<https://www.elastic.co/guide/en/elasticsearch/reference/current/index.html>`_
- `Install El... | # SPDX-License-Identifier: AGPL-3.0-or-later
""".. sidebar:: info
- :origin:`elasticsearch.py <searx/engines/elasticsearch.py>`
- `Elasticsearch <https://www.elastic.co/elasticsearch/>`_
- `Elasticsearch Guide
<https://www.elastic.co/guide/en/elasticsearch/reference/current/index.html>`_
- `Install El... |
try:
key, value = query.split(':')
except Exception as e:
raise ValueError('query format must be "key:value"') from e
return {"query": {"match": {key: {'query': value}}}}
| """
The standard for full text queries.
searx format: "key:value" e.g. city:berlin
REF: https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-match-query.html
"""
try:
key, value = query.split(':')
except Exception as e:
raise ValueError('query format mus... | 23 | 1,609 | 72 | 1,681 | # SPDX-License-Identifier: AGPL-3.0-or-later
""".. sidebar:: info
- :origin:`elasticsearch.py <searx/engines/elasticsearch.py>`
- `Elasticsearch <https://www.elastic.co/elasticsearch/>`_
- `Elasticsearch Guide
<https://www.elastic.co/guide/en/elasticsearch/reference/current/index.html>`_
- `Install El... | # SPDX-License-Identifier: AGPL-3.0-or-later
""".. sidebar:: info
- :origin:`elasticsearch.py <searx/engines/elasticsearch.py>`
- `Elasticsearch <https://www.elastic.co/elasticsearch/>`_
- `Elasticsearch Guide
<https://www.elastic.co/guide/en/elasticsearch/reference/current/index.html>`_
- `Install El... | |
23,823 | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/engines/emojipedia.py | 41,42 | 1,54 | response | 42,54 | 42,54 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Emojipedia
Emojipedia is an emoji reference website which documents the meaning and
common usage of emoji characters in the Unicode Standard. It is owned by Zedge
since 2021. Emojipedia is a voting member of The Unicode Consortium.[1]
[1] https://en.wikipedia.org/wiki/... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Emojipedia
Emojipedia is an emoji reference website which documents the meaning and
common usage of emoji characters in the Unicode Standard. It is owned by Zedge
since 2021. Emojipedia is a voting member of The Unicode Consortium.[1]
[1] https://en.wikipedia.org/wiki/... | results = []
dom = html.fromstring(resp.text)
for result in eval_xpath_list(dom, '//div[starts-with(@class, "EmojisList")]/a'):
url = base_url + result.attrib.get('href')
res = {'url': url, 'title': extract_text(result), 'content': ''}
results.append(res)
return results
| results = []
dom = html.fromstring(resp.text)
for result in eval_xpath_list(dom, '//div[starts-with(@class, "EmojisList")]/a'):
url = base_url + result.attrib.get('href')
res = {'url': url, 'title': extract_text(result), 'content': ''}
results.append(res)
return results
| 28 | 346 | 124 | 470 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Emojipedia
Emojipedia is an emoji reference website which documents the meaning and
common usage of emoji characters in the Unicode Standard. It is owned by Zedge
since 2021. Emojipedia is a voting member of The Unicode Consortium.[1]
[1] https://en.wikipedia.org/wiki/... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""Emojipedia
Emojipedia is an emoji reference website which documents the meaning and
common usage of emoji characters in the Unicode Standard. It is owned by Zedge
since 2021. Emojipedia is a voting member of The Unicode Consortium.[1]
[1] https://en.wikipedia.org/wiki/... | |
23,824 | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng | /home/hieuvd/dung_repo/raw/stars_01/searxng_searxng/searxng/searx/engines/fdroid.py | 30,31 | 1,55 | request | 31,37 | 31,37 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""
F-Droid (a repository of FOSS applications for Android)
"""
from urllib.parse import urlencode
from lxml import html
from searx.utils import extract_text
# about
about = {
"website": 'https://f-droid.org/',
"wikidata_id": 'Q1386210',
"official_api_document... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""
F-Droid (a repository of FOSS applications for Android)
"""
from urllib.parse import urlencode
from lxml import html
from searx.utils import extract_text
# about
about = {
"website": 'https://f-droid.org/',
"wikidata_id": 'Q1386210',
"official_api_document... | query = urlencode({'q': query, 'page': params['pageno'], 'lang': ''})
params['url'] = search_url.format(query=query)
return params
# get response from search-request
| query = urlencode({'q': query, 'page': params['pageno'], 'lang': ''})
params['url'] = search_url.format(query=query)
return params
# get response from search-request
| 18 | 495 | 63 | 558 | # SPDX-License-Identifier: AGPL-3.0-or-later
"""
F-Droid (a repository of FOSS applications for Android)
"""
from urllib.parse import urlencode
from lxml import html
from searx.utils import extract_text
# about
about = {
"website": 'https://f-droid.org/',
"wikidata_id": 'Q1386210',
"official_api_document... | # SPDX-License-Identifier: AGPL-3.0-or-later
"""
F-Droid (a repository of FOSS applications for Android)
"""
from urllib.parse import urlencode
from lxml import html
from searx.utils import extract_text
# about
about = {
"website": 'https://f-droid.org/',
"wikidata_id": 'Q1386210',
"official_api_document... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.