code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def get_rules(self):
""" Retruns list of detection rules for usecase
"""
dr_list_per_usecase = [rules_by_title.get(dr_title)[0]
for dr_title in self.detection_rules]
return dr_list_per_usecase | Retruns list of detection rules for usecase
| get_rules | python | atc-project/atomic-threat-coverage | scripts/usecases.py | https://github.com/atc-project/atomic-threat-coverage/blob/master/scripts/usecases.py | Apache-2.0 |
def __init__(self, id, field, enabled=None):
"""field - field name which should be averaged"""
super().__init__(
id=id, enabled=enabled, type="avg", schema="metric", params={
"field": field
}
) | field - field name which should be averaged | __init__ | python | atc-project/atomic-threat-coverage | scripts/atc_visualizations/aggs.py | https://github.com/atc-project/atomic-threat-coverage/blob/master/scripts/atc_visualizations/aggs.py | Apache-2.0 |
def __init__(self, id, field, aggregate_with, size, sort_order, sort_field,
enabled=None):
"""aggregate_with - can be average, max, min or sum
size - integer
sort_order - can be asc or dsc
"""
super().__init__(
id=id, enabled=enabled, params={
"aggregate": ag... | aggregate_with - can be average, max, min or sum
size - integer
sort_order - can be asc or dsc
| __init__ | python | atc-project/atomic-threat-coverage | scripts/atc_visualizations/aggs.py | https://github.com/atc-project/atomic-threat-coverage/blob/master/scripts/atc_visualizations/aggs.py | Apache-2.0 |
def validate(self):
# TODO: Write custom validate (validate every required field)
"""
sort_order - either `asc` or `desc`
size - int positive number
aggregate_with - ["average", "concat", "min", "max", "sum"]
"""
return super().validate() |
sort_order - either `asc` or `desc`
size - int positive number
aggregate_with - ["average", "concat", "min", "max", "sum"]
| validate | python | atc-project/atomic-threat-coverage | scripts/atc_visualizations/aggs.py | https://github.com/atc-project/atomic-threat-coverage/blob/master/scripts/atc_visualizations/aggs.py | Apache-2.0 |
def search_id_of_title_by_type(cls, search_type, search_title):
"""Returns an ID (string) of an object searched using object title
search_type - string in ["index-pattern", "search"]
search_title - string
"""
search_type = search_type.lower()
if search_type not in ["index-pattern", "search"]:
... | Returns an ID (string) of an object searched using object title
search_type - string in ["index-pattern", "search"]
search_title - string
| search_id_of_title_by_type | python | atc-project/atomic-threat-coverage | scripts/atc_visualizations/base.py | https://github.com/atc-project/atomic-threat-coverage/blob/master/scripts/atc_visualizations/base.py | Apache-2.0 |
def get_all(self):
"""Get all saved objects and put them into visualization/dashboards"""
r = self.es.search(
index='.kibana*', doc_type='',
body={'query': {'match_all': {}}},
size=self.search_limit_size,
)
for obj in r['hits']['hits']:
i... | Get all saved objects and put them into visualization/dashboards | get_all | python | atc-project/atomic-threat-coverage | scripts/atc_visualizations/kibana_api.py | https://github.com/atc-project/atomic-threat-coverage/blob/master/scripts/atc_visualizations/kibana_api.py | Apache-2.0 |
def json_export_gui(self, return_dict=False, uuid_=None):
"""visState has to be a string with escaped doublequotes"""
if self.validate():
# self.updated_at = datetime.datetime.today().isoformat() + "Z"
# TODO: Find proper way to do below line :))
tmp_dictionary = lite... | visState has to be a string with escaped doublequotes | json_export_gui | python | atc-project/atomic-threat-coverage | scripts/atc_visualizations/visualisation.py | https://github.com/atc-project/atomic-threat-coverage/blob/master/scripts/atc_visualizations/visualisation.py | Apache-2.0 |
def set_saved_search(self, saved_search_name=None, saved_search_id=None):
"""Provide ID if you know it and don't want to engage kibana"""
if not saved_search_name and not saved_search_id:
raise Exception(
"What's the point of running this method without arguments?"
... | Provide ID if you know it and don't want to engage kibana | set_saved_search | python | atc-project/atomic-threat-coverage | scripts/atc_visualizations/visualisation.py | https://github.com/atc-project/atomic-threat-coverage/blob/master/scripts/atc_visualizations/visualisation.py | Apache-2.0 |
def validate(opts, model, loader, device, metrics, ret_samples_ids=None):
"""Do validation and return specified samples"""
metrics.reset()
ret_samples = []
if opts.save_val_results:
if not os.path.exists('results'):
os.mkdir('results')
denorm = utils.Denormalize(mean=[0.485, ... | Do validation and return specified samples | validate | python | VainF/DeepLabV3Plus-Pytorch | main.py | https://github.com/VainF/DeepLabV3Plus-Pytorch/blob/master/main.py | MIT |
def __getitem__(self, index):
"""
Args:
index (int): Index
Returns:
tuple: (image, target) where target is a tuple of all target types if target_type is a list with more
than one item. Otherwise target is a json object if target_type="polygon", else the image ... |
Args:
index (int): Index
Returns:
tuple: (image, target) where target is a tuple of all target types if target_type is a list with more
than one item. Otherwise target is a json object if target_type="polygon", else the image segmentation.
| __getitem__ | python | VainF/DeepLabV3Plus-Pytorch | datasets/cityscapes.py | https://github.com/VainF/DeepLabV3Plus-Pytorch/blob/master/datasets/cityscapes.py | MIT |
def download_url(url, root, filename=None, md5=None):
"""Download a file from a url and place it in root.
Args:
url (str): URL to download file from
root (str): Directory to place downloaded file in
filename (str): Name to save the file under. If None, use the basename of the URL
... | Download a file from a url and place it in root.
Args:
url (str): URL to download file from
root (str): Directory to place downloaded file in
filename (str): Name to save the file under. If None, use the basename of the URL
md5 (str): MD5 checksum of the download. If None, do not che... | download_url | python | VainF/DeepLabV3Plus-Pytorch | datasets/utils.py | https://github.com/VainF/DeepLabV3Plus-Pytorch/blob/master/datasets/utils.py | MIT |
def list_dir(root, prefix=False):
"""List all directories at a given root
Args:
root (str): Path to directory whose folders need to be listed
prefix (bool, optional): If true, prepends the path to each result, otherwise
only returns the name of the directories found
"""
root ... | List all directories at a given root
Args:
root (str): Path to directory whose folders need to be listed
prefix (bool, optional): If true, prepends the path to each result, otherwise
only returns the name of the directories found
| list_dir | python | VainF/DeepLabV3Plus-Pytorch | datasets/utils.py | https://github.com/VainF/DeepLabV3Plus-Pytorch/blob/master/datasets/utils.py | MIT |
def list_files(root, suffix, prefix=False):
"""List all files ending with a suffix at a given root
Args:
root (str): Path to directory whose folders need to be listed
suffix (str or tuple): Suffix of the files to match, e.g. '.png' or ('.jpg', '.png').
It uses the Python "str.endswit... | List all files ending with a suffix at a given root
Args:
root (str): Path to directory whose folders need to be listed
suffix (str or tuple): Suffix of the files to match, e.g. '.png' or ('.jpg', '.png').
It uses the Python "str.endswith" method and is passed directly
prefix (bo... | list_files | python | VainF/DeepLabV3Plus-Pytorch | datasets/utils.py | https://github.com/VainF/DeepLabV3Plus-Pytorch/blob/master/datasets/utils.py | MIT |
def __getitem__(self, index):
"""
Args:
index (int): Index
Returns:
tuple: (image, target) where target is the image segmentation.
"""
img = Image.open(self.images[index]).convert('RGB')
target = Image.open(self.masks[index])
if self.transf... |
Args:
index (int): Index
Returns:
tuple: (image, target) where target is the image segmentation.
| __getitem__ | python | VainF/DeepLabV3Plus-Pytorch | datasets/voc.py | https://github.com/VainF/DeepLabV3Plus-Pytorch/blob/master/datasets/voc.py | MIT |
def get_results(self):
"""Returns accuracy score evaluation result.
- overall accuracy
- mean accuracy
- mean IU
- fwavacc
"""
hist = self.confusion_matrix
acc = np.diag(hist).sum() / hist.sum()
acc_cls = np.diag(hist) / hist.sum(ax... | Returns accuracy score evaluation result.
- overall accuracy
- mean accuracy
- mean IU
- fwavacc
| get_results | python | VainF/DeepLabV3Plus-Pytorch | metrics/stream_metrics.py | https://github.com/VainF/DeepLabV3Plus-Pytorch/blob/master/metrics/stream_metrics.py | MIT |
def _make_divisible(v, divisor, min_value=None):
"""
This function is taken from the original tf repo.
It ensures that all layers have a channel number that is divisible by 8
It can be seen here:
https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py
:param v:... |
This function is taken from the original tf repo.
It ensures that all layers have a channel number that is divisible by 8
It can be seen here:
https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py
:param v:
:param divisor:
:param min_value:
:return:
... | _make_divisible | python | VainF/DeepLabV3Plus-Pytorch | network/backbone/mobilenetv2.py | https://github.com/VainF/DeepLabV3Plus-Pytorch/blob/master/network/backbone/mobilenetv2.py | MIT |
def __init__(self, num_classes=1000, output_stride=8, width_mult=1.0, inverted_residual_setting=None, round_nearest=8):
"""
MobileNet V2 main class
Args:
num_classes (int): Number of classes
width_mult (float): Width multiplier - adjusts number of channels in each layer ... |
MobileNet V2 main class
Args:
num_classes (int): Number of classes
width_mult (float): Width multiplier - adjusts number of channels in each layer by this amount
inverted_residual_setting: Network structure
round_nearest (int): Round the number of channe... | __init__ | python | VainF/DeepLabV3Plus-Pytorch | network/backbone/mobilenetv2.py | https://github.com/VainF/DeepLabV3Plus-Pytorch/blob/master/network/backbone/mobilenetv2.py | MIT |
def mobilenet_v2(pretrained=False, progress=True, **kwargs):
"""
Constructs a MobileNetV2 architecture from
`"MobileNetV2: Inverted Residuals and Linear Bottlenecks" <https://arxiv.org/abs/1801.04381>`_.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress ... |
Constructs a MobileNetV2 architecture from
`"MobileNetV2: Inverted Residuals and Linear Bottlenecks" <https://arxiv.org/abs/1801.04381>`_.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): If True, displays a progress bar of the download to stderr
... | mobilenet_v2 | python | VainF/DeepLabV3Plus-Pytorch | network/backbone/mobilenetv2.py | https://github.com/VainF/DeepLabV3Plus-Pytorch/blob/master/network/backbone/mobilenetv2.py | MIT |
def resnext50_32x4d(pretrained=False, progress=True, **kwargs):
r"""ResNeXt-50 32x4d model from
`"Aggregated Residual Transformation for Deep Neural Networks" <https://arxiv.org/pdf/1611.05431.pdf>`_
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): ... | ResNeXt-50 32x4d model from
`"Aggregated Residual Transformation for Deep Neural Networks" <https://arxiv.org/pdf/1611.05431.pdf>`_
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): If True, displays a progress bar of the download to stderr
| resnext50_32x4d | python | VainF/DeepLabV3Plus-Pytorch | network/backbone/resnet.py | https://github.com/VainF/DeepLabV3Plus-Pytorch/blob/master/network/backbone/resnet.py | MIT |
def resnext101_32x8d(pretrained=False, progress=True, **kwargs):
r"""ResNeXt-101 32x8d model from
`"Aggregated Residual Transformation for Deep Neural Networks" <https://arxiv.org/pdf/1611.05431.pdf>`_
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool)... | ResNeXt-101 32x8d model from
`"Aggregated Residual Transformation for Deep Neural Networks" <https://arxiv.org/pdf/1611.05431.pdf>`_
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): If True, displays a progress bar of the download to stderr
| resnext101_32x8d | python | VainF/DeepLabV3Plus-Pytorch | network/backbone/resnet.py | https://github.com/VainF/DeepLabV3Plus-Pytorch/blob/master/network/backbone/resnet.py | MIT |
def wide_resnet50_2(pretrained=False, progress=True, **kwargs):
r"""Wide ResNet-50-2 model from
`"Wide Residual Networks" <https://arxiv.org/pdf/1605.07146.pdf>`_
The model is the same as ResNet except for the bottleneck number of channels
which is twice larger in every block. The number of channels in... | Wide ResNet-50-2 model from
`"Wide Residual Networks" <https://arxiv.org/pdf/1605.07146.pdf>`_
The model is the same as ResNet except for the bottleneck number of channels
which is twice larger in every block. The number of channels in outer 1x1
convolutions is the same, e.g. last block in ResNet-50 ha... | wide_resnet50_2 | python | VainF/DeepLabV3Plus-Pytorch | network/backbone/resnet.py | https://github.com/VainF/DeepLabV3Plus-Pytorch/blob/master/network/backbone/resnet.py | MIT |
def wide_resnet101_2(pretrained=False, progress=True, **kwargs):
r"""Wide ResNet-101-2 model from
`"Wide Residual Networks" <https://arxiv.org/pdf/1605.07146.pdf>`_
The model is the same as ResNet except for the bottleneck number of channels
which is twice larger in every block. The number of channels ... | Wide ResNet-101-2 model from
`"Wide Residual Networks" <https://arxiv.org/pdf/1605.07146.pdf>`_
The model is the same as ResNet except for the bottleneck number of channels
which is twice larger in every block. The number of channels in outer 1x1
convolutions is the same, e.g. last block in ResNet-50 h... | wide_resnet101_2 | python | VainF/DeepLabV3Plus-Pytorch | network/backbone/resnet.py | https://github.com/VainF/DeepLabV3Plus-Pytorch/blob/master/network/backbone/resnet.py | MIT |
def __call__(self, img, lbl):
"""
Args:
img (PIL Image): Image to be flipped.
Returns:
PIL Image: Randomly flipped image.
"""
if random.random() < self.p:
return F.hflip(img), F.hflip(lbl)
return img, lbl |
Args:
img (PIL Image): Image to be flipped.
Returns:
PIL Image: Randomly flipped image.
| __call__ | python | VainF/DeepLabV3Plus-Pytorch | utils/ext_transforms.py | https://github.com/VainF/DeepLabV3Plus-Pytorch/blob/master/utils/ext_transforms.py | MIT |
def __call__(self, img, lbl):
"""
Args:
img (PIL Image): Image to be scaled.
lbl (PIL Image): Label to be scaled.
Returns:
PIL Image: Rescaled image.
PIL Image: Rescaled label.
"""
assert img.size == lbl.size
scale = random.... |
Args:
img (PIL Image): Image to be scaled.
lbl (PIL Image): Label to be scaled.
Returns:
PIL Image: Rescaled image.
PIL Image: Rescaled label.
| __call__ | python | VainF/DeepLabV3Plus-Pytorch | utils/ext_transforms.py | https://github.com/VainF/DeepLabV3Plus-Pytorch/blob/master/utils/ext_transforms.py | MIT |
def __call__(self, img, lbl):
"""
img (PIL Image): Image to be rotated.
lbl (PIL Image): Label to be rotated.
Returns:
PIL Image: Rotated image.
PIL Image: Rotated label.
"""
angle = self.get_params(self.degrees)
return F.rotate(i... |
img (PIL Image): Image to be rotated.
lbl (PIL Image): Label to be rotated.
Returns:
PIL Image: Rotated image.
PIL Image: Rotated label.
| __call__ | python | VainF/DeepLabV3Plus-Pytorch | utils/ext_transforms.py | https://github.com/VainF/DeepLabV3Plus-Pytorch/blob/master/utils/ext_transforms.py | MIT |
def __call__(self, img, lbl):
"""
Args:
img (PIL Image): Image to be flipped.
lbl (PIL Image): Label to be flipped.
Returns:
PIL Image: Randomly flipped image.
PIL Image: Randomly flipped label.
"""
if random.random() < self.p:
... |
Args:
img (PIL Image): Image to be flipped.
lbl (PIL Image): Label to be flipped.
Returns:
PIL Image: Randomly flipped image.
PIL Image: Randomly flipped label.
| __call__ | python | VainF/DeepLabV3Plus-Pytorch | utils/ext_transforms.py | https://github.com/VainF/DeepLabV3Plus-Pytorch/blob/master/utils/ext_transforms.py | MIT |
def __call__(self, pic, lbl):
"""
Note that labels will not be normalized to [0, 1].
Args:
pic (PIL Image or numpy.ndarray): Image to be converted to tensor.
lbl (PIL Image or numpy.ndarray): Label to be converted to tensor.
Returns:
Tensor: Converted... |
Note that labels will not be normalized to [0, 1].
Args:
pic (PIL Image or numpy.ndarray): Image to be converted to tensor.
lbl (PIL Image or numpy.ndarray): Label to be converted to tensor.
Returns:
Tensor: Converted image and label
| __call__ | python | VainF/DeepLabV3Plus-Pytorch | utils/ext_transforms.py | https://github.com/VainF/DeepLabV3Plus-Pytorch/blob/master/utils/ext_transforms.py | MIT |
def get_params(img, output_size):
"""Get parameters for ``crop`` for a random crop.
Args:
img (PIL Image): Image to be cropped.
output_size (tuple): Expected output size of the crop.
Returns:
tuple: params (i, j, h, w) to be passed to ``crop`` for random crop.... | Get parameters for ``crop`` for a random crop.
Args:
img (PIL Image): Image to be cropped.
output_size (tuple): Expected output size of the crop.
Returns:
tuple: params (i, j, h, w) to be passed to ``crop`` for random crop.
| get_params | python | VainF/DeepLabV3Plus-Pytorch | utils/ext_transforms.py | https://github.com/VainF/DeepLabV3Plus-Pytorch/blob/master/utils/ext_transforms.py | MIT |
def __call__(self, img, lbl):
"""
Args:
img (PIL Image): Image to be cropped.
lbl (PIL Image): Label to be cropped.
Returns:
PIL Image: Cropped image.
PIL Image: Cropped label.
"""
assert img.size == lbl.size, 'size of img and lbl s... |
Args:
img (PIL Image): Image to be cropped.
lbl (PIL Image): Label to be cropped.
Returns:
PIL Image: Cropped image.
PIL Image: Cropped label.
| __call__ | python | VainF/DeepLabV3Plus-Pytorch | utils/ext_transforms.py | https://github.com/VainF/DeepLabV3Plus-Pytorch/blob/master/utils/ext_transforms.py | MIT |
def get_params(brightness, contrast, saturation, hue):
"""Get a randomized transform to be applied on image.
Arguments are same as that of __init__.
Returns:
Transform which randomly adjusts brightness, contrast and
saturation in a random order.
"""
transf... | Get a randomized transform to be applied on image.
Arguments are same as that of __init__.
Returns:
Transform which randomly adjusts brightness, contrast and
saturation in a random order.
| get_params | python | VainF/DeepLabV3Plus-Pytorch | utils/ext_transforms.py | https://github.com/VainF/DeepLabV3Plus-Pytorch/blob/master/utils/ext_transforms.py | MIT |
def __call__(self, img, lbl):
"""
Args:
img (PIL Image): Input image.
Returns:
PIL Image: Color jittered image.
"""
transform = self.get_params(self.brightness, self.contrast,
self.saturation, self.hue)
return tr... |
Args:
img (PIL Image): Input image.
Returns:
PIL Image: Color jittered image.
| __call__ | python | VainF/DeepLabV3Plus-Pytorch | utils/ext_transforms.py | https://github.com/VainF/DeepLabV3Plus-Pytorch/blob/master/utils/ext_transforms.py | MIT |
def test_geosearch(self):
"""Test parsing a Wikipedia location request result."""
self.assertEqual(
wikipedia.geosearch(Decimal('40.67693'), Decimal('117.23193')),
mock_data['data']["great_wall_of_china.geo_seach"]
) | Test parsing a Wikipedia location request result. | test_geosearch | python | goldsmith/Wikipedia | tests/geosearch_test.py | https://github.com/goldsmith/Wikipedia/blob/master/tests/geosearch_test.py | MIT |
def test_missing(self):
"""Test that page raises a PageError for a nonexistant page."""
# Callicarpa?
purpleberry = lambda: wikipedia.page("purpleberry", auto_suggest=False)
self.assertRaises(wikipedia.PageError, purpleberry) | Test that page raises a PageError for a nonexistant page. | test_missing | python | goldsmith/Wikipedia | tests/page_test.py | https://github.com/goldsmith/Wikipedia/blob/master/tests/page_test.py | MIT |
def test_redirect_true(self):
"""Test that a page successfully redirects a query."""
# no error should be raised if redirect is test_redirect_true
mp = wikipedia.page("Menlo Park, New Jersey")
self.assertEqual(mp.title, "Edison, New Jersey")
self.assertEqual(mp.url, "http://en.wikipedia.org/wiki/Ed... | Test that a page successfully redirects a query. | test_redirect_true | python | goldsmith/Wikipedia | tests/page_test.py | https://github.com/goldsmith/Wikipedia/blob/master/tests/page_test.py | MIT |
def test_redirect_no_normalization(self):
"""Test that a page with redirects but no normalization query loads correctly"""
the_party = wikipedia.page("Communist Party", auto_suggest=False)
self.assertIsInstance(the_party, wikipedia.WikipediaPage)
self.assertEqual(the_party.title, "Communist party") | Test that a page with redirects but no normalization query loads correctly | test_redirect_no_normalization | python | goldsmith/Wikipedia | tests/page_test.py | https://github.com/goldsmith/Wikipedia/blob/master/tests/page_test.py | MIT |
def test_redirect_with_normalization(self):
"""Test that a page redirect with a normalized query loads correctly"""
the_party = wikipedia.page("communist Party", auto_suggest=False)
self.assertIsInstance(the_party, wikipedia.WikipediaPage)
self.assertEqual(the_party.title, "Communist party") | Test that a page redirect with a normalized query loads correctly | test_redirect_with_normalization | python | goldsmith/Wikipedia | tests/page_test.py | https://github.com/goldsmith/Wikipedia/blob/master/tests/page_test.py | MIT |
def test_redirect_normalization(self):
"""Test that a page redirect loads correctly with or without a query normalization"""
capital_party = wikipedia.page("Communist Party", auto_suggest=False)
lower_party = wikipedia.page("communist Party", auto_suggest=False)
self.assertIsInstance(capital_party, wik... | Test that a page redirect loads correctly with or without a query normalization | test_redirect_normalization | python | goldsmith/Wikipedia | tests/page_test.py | https://github.com/goldsmith/Wikipedia/blob/master/tests/page_test.py | MIT |
def test_disambiguate(self):
"""Test that page raises an error when a disambiguation page is reached."""
try:
ram = wikipedia.page("Dodge Ram (disambiguation)", auto_suggest=False, redirect=False)
error_raised = False
except wikipedia.DisambiguationError as e:
error_raised = True
opt... | Test that page raises an error when a disambiguation page is reached. | test_disambiguate | python | goldsmith/Wikipedia | tests/page_test.py | https://github.com/goldsmith/Wikipedia/blob/master/tests/page_test.py | MIT |
def test_suggestion(self):
"""Test getting a suggestion as well as search results."""
search, suggestion = wikipedia.search("hallelulejah", suggestion=True)
self.assertEqual(search, [])
self.assertEqual(suggestion, u'hallelujah') | Test getting a suggestion as well as search results. | test_suggestion | python | goldsmith/Wikipedia | tests/search_test.py | https://github.com/goldsmith/Wikipedia/blob/master/tests/search_test.py | MIT |
def test_suggestion_none(self):
"""Test getting a suggestion when there is no suggestion."""
search, suggestion = wikipedia.search("qmxjsudek", suggestion=True)
self.assertEqual(search, [])
self.assertEqual(suggestion, None) | Test getting a suggestion when there is no suggestion. | test_suggestion_none | python | goldsmith/Wikipedia | tests/search_test.py | https://github.com/goldsmith/Wikipedia/blob/master/tests/search_test.py | MIT |
def set_lang(prefix):
'''
Change the language of the API being requested.
Set `prefix` to one of the two letter prefixes found on the `list of all Wikipedias <http://meta.wikimedia.org/wiki/List_of_Wikipedias>`_.
After setting the language, the cache for ``search``, ``suggest``, and ``summary`` will be cleared... |
Change the language of the API being requested.
Set `prefix` to one of the two letter prefixes found on the `list of all Wikipedias <http://meta.wikimedia.org/wiki/List_of_Wikipedias>`_.
After setting the language, the cache for ``search``, ``suggest``, and ``summary`` will be cleared.
.. note:: Make sure yo... | set_lang | python | goldsmith/Wikipedia | wikipedia/wikipedia.py | https://github.com/goldsmith/Wikipedia/blob/master/wikipedia/wikipedia.py | MIT |
def set_user_agent(user_agent_string):
'''
Set the User-Agent string to be used for all requests.
Arguments:
* user_agent_string - (string) a string specifying the User-Agent header
'''
global USER_AGENT
USER_AGENT = user_agent_string |
Set the User-Agent string to be used for all requests.
Arguments:
* user_agent_string - (string) a string specifying the User-Agent header
| set_user_agent | python | goldsmith/Wikipedia | wikipedia/wikipedia.py | https://github.com/goldsmith/Wikipedia/blob/master/wikipedia/wikipedia.py | MIT |
def search(query, results=10, suggestion=False):
'''
Do a Wikipedia search for `query`.
Keyword arguments:
* results - the maxmimum number of results returned
* suggestion - if True, return results and suggestion (if any) in a tuple
'''
search_params = {
'list': 'search',
'srprop': '',
'srl... |
Do a Wikipedia search for `query`.
Keyword arguments:
* results - the maxmimum number of results returned
* suggestion - if True, return results and suggestion (if any) in a tuple
| search | python | goldsmith/Wikipedia | wikipedia/wikipedia.py | https://github.com/goldsmith/Wikipedia/blob/master/wikipedia/wikipedia.py | MIT |
def geosearch(latitude, longitude, title=None, results=10, radius=1000):
'''
Do a wikipedia geo search for `latitude` and `longitude`
using HTTP API described in http://www.mediawiki.org/wiki/Extension:GeoData
Arguments:
* latitude (float or decimal.Decimal)
* longitude (float or decimal.Decimal)
Keywo... |
Do a wikipedia geo search for `latitude` and `longitude`
using HTTP API described in http://www.mediawiki.org/wiki/Extension:GeoData
Arguments:
* latitude (float or decimal.Decimal)
* longitude (float or decimal.Decimal)
Keyword arguments:
* title - The title of an article to search for
* results -... | geosearch | python | goldsmith/Wikipedia | wikipedia/wikipedia.py | https://github.com/goldsmith/Wikipedia/blob/master/wikipedia/wikipedia.py | MIT |
def suggest(query):
'''
Get a Wikipedia search suggestion for `query`.
Returns a string or None if no suggestion was found.
'''
search_params = {
'list': 'search',
'srinfo': 'suggestion',
'srprop': '',
}
search_params['srsearch'] = query
raw_result = _wiki_request(search_params)
if raw_... |
Get a Wikipedia search suggestion for `query`.
Returns a string or None if no suggestion was found.
| suggest | python | goldsmith/Wikipedia | wikipedia/wikipedia.py | https://github.com/goldsmith/Wikipedia/blob/master/wikipedia/wikipedia.py | MIT |
def random(pages=1):
'''
Get a list of random Wikipedia article titles.
.. note:: Random only gets articles from namespace 0, meaning no Category, User talk, or other meta-Wikipedia pages.
Keyword arguments:
* pages - the number of random pages returned (max of 10)
'''
#http://en.wikipedia.org/w/api.ph... |
Get a list of random Wikipedia article titles.
.. note:: Random only gets articles from namespace 0, meaning no Category, User talk, or other meta-Wikipedia pages.
Keyword arguments:
* pages - the number of random pages returned (max of 10)
| random | python | goldsmith/Wikipedia | wikipedia/wikipedia.py | https://github.com/goldsmith/Wikipedia/blob/master/wikipedia/wikipedia.py | MIT |
def summary(title, sentences=0, chars=0, auto_suggest=True, redirect=True):
'''
Plain text summary of the page.
.. note:: This is a convenience wrapper - auto_suggest and redirect are enabled by default
Keyword arguments:
* sentences - if set, return the first `sentences` sentences (can be no greater than ... |
Plain text summary of the page.
.. note:: This is a convenience wrapper - auto_suggest and redirect are enabled by default
Keyword arguments:
* sentences - if set, return the first `sentences` sentences (can be no greater than 10).
* chars - if set, return only the first `chars` characters (actual text re... | summary | python | goldsmith/Wikipedia | wikipedia/wikipedia.py | https://github.com/goldsmith/Wikipedia/blob/master/wikipedia/wikipedia.py | MIT |
def page(title=None, pageid=None, auto_suggest=True, redirect=True, preload=False):
'''
Get a WikipediaPage object for the page with title `title` or the pageid
`pageid` (mutually exclusive).
Keyword arguments:
* title - the title of the page to load
* pageid - the numeric pageid of the page to load
* a... |
Get a WikipediaPage object for the page with title `title` or the pageid
`pageid` (mutually exclusive).
Keyword arguments:
* title - the title of the page to load
* pageid - the numeric pageid of the page to load
* auto_suggest - let Wikipedia find a valid page title for the query
* redirect - allow re... | page | python | goldsmith/Wikipedia | wikipedia/wikipedia.py | https://github.com/goldsmith/Wikipedia/blob/master/wikipedia/wikipedia.py | MIT |
def __load(self, redirect=True, preload=False):
'''
Load basic information from Wikipedia.
Confirm that page exists and is not a disambiguation/redirect.
Does not need to be called manually, should be called automatically during __init__.
'''
query_params = {
'prop': 'info|pageprops',
... |
Load basic information from Wikipedia.
Confirm that page exists and is not a disambiguation/redirect.
Does not need to be called manually, should be called automatically during __init__.
| __load | python | goldsmith/Wikipedia | wikipedia/wikipedia.py | https://github.com/goldsmith/Wikipedia/blob/master/wikipedia/wikipedia.py | MIT |
def __continued_query(self, query_params):
'''
Based on https://www.mediawiki.org/wiki/API:Query#Continuing_queries
'''
query_params.update(self.__title_query_param)
last_continue = {}
prop = query_params.get('prop', None)
while True:
params = query_params.copy()
params.update(... |
Based on https://www.mediawiki.org/wiki/API:Query#Continuing_queries
| __continued_query | python | goldsmith/Wikipedia | wikipedia/wikipedia.py | https://github.com/goldsmith/Wikipedia/blob/master/wikipedia/wikipedia.py | MIT |
def html(self):
'''
Get full page HTML.
.. warning:: This can get pretty slow on long pages.
'''
if not getattr(self, '_html', False):
query_params = {
'prop': 'revisions',
'rvprop': 'content',
'rvlimit': 1,
'rvparse': '',
'titles': self.title
}
... |
Get full page HTML.
.. warning:: This can get pretty slow on long pages.
| html | python | goldsmith/Wikipedia | wikipedia/wikipedia.py | https://github.com/goldsmith/Wikipedia/blob/master/wikipedia/wikipedia.py | MIT |
def content(self):
'''
Plain text content of the page, excluding images, tables, and other data.
'''
if not getattr(self, '_content', False):
query_params = {
'prop': 'extracts|revisions',
'explaintext': '',
'rvprop': 'ids'
}
if not getattr(self, 'title', None)... |
Plain text content of the page, excluding images, tables, and other data.
| content | python | goldsmith/Wikipedia | wikipedia/wikipedia.py | https://github.com/goldsmith/Wikipedia/blob/master/wikipedia/wikipedia.py | MIT |
def revision_id(self):
'''
Revision ID of the page.
The revision ID is a number that uniquely identifies the current
version of the page. It can be used to create the permalink or for
other direct API calls. See `Help:Page history
<http://en.wikipedia.org/wiki/Wikipedia:Revision>`_ for more
... |
Revision ID of the page.
The revision ID is a number that uniquely identifies the current
version of the page. It can be used to create the permalink or for
other direct API calls. See `Help:Page history
<http://en.wikipedia.org/wiki/Wikipedia:Revision>`_ for more
information.
| revision_id | python | goldsmith/Wikipedia | wikipedia/wikipedia.py | https://github.com/goldsmith/Wikipedia/blob/master/wikipedia/wikipedia.py | MIT |
def parent_id(self):
'''
Revision ID of the parent version of the current revision of this
page. See ``revision_id`` for more information.
'''
if not getattr(self, '_parentid', False):
# fetch the content (side effect is loading the revid)
self.content
return self._parent_id |
Revision ID of the parent version of the current revision of this
page. See ``revision_id`` for more information.
| parent_id | python | goldsmith/Wikipedia | wikipedia/wikipedia.py | https://github.com/goldsmith/Wikipedia/blob/master/wikipedia/wikipedia.py | MIT |
def summary(self):
'''
Plain text summary of the page.
'''
if not getattr(self, '_summary', False):
query_params = {
'prop': 'extracts',
'explaintext': '',
'exintro': '',
}
if not getattr(self, 'title', None) is None:
query_params['titles'] = self.titl... |
Plain text summary of the page.
| summary | python | goldsmith/Wikipedia | wikipedia/wikipedia.py | https://github.com/goldsmith/Wikipedia/blob/master/wikipedia/wikipedia.py | MIT |
def images(self):
'''
List of URLs of images on the page.
'''
if not getattr(self, '_images', False):
self._images = [
page['imageinfo'][0]['url']
for page in self.__continued_query({
'generator': 'images',
'gimlimit': 'max',
'prop': 'imageinfo',
... |
List of URLs of images on the page.
| images | python | goldsmith/Wikipedia | wikipedia/wikipedia.py | https://github.com/goldsmith/Wikipedia/blob/master/wikipedia/wikipedia.py | MIT |
def coordinates(self):
'''
Tuple of Decimals in the form of (lat, lon) or None
'''
if not getattr(self, '_coordinates', False):
query_params = {
'prop': 'coordinates',
'colimit': 'max',
'titles': self.title,
}
request = _wiki_request(query_params)
if 'qu... |
Tuple of Decimals in the form of (lat, lon) or None
| coordinates | python | goldsmith/Wikipedia | wikipedia/wikipedia.py | https://github.com/goldsmith/Wikipedia/blob/master/wikipedia/wikipedia.py | MIT |
def references(self):
'''
List of URLs of external links on a page.
May include external links within page that aren't technically cited anywhere.
'''
if not getattr(self, '_references', False):
def add_protocol(url):
return url if url.startswith('http') else 'http:' + url
self... |
List of URLs of external links on a page.
May include external links within page that aren't technically cited anywhere.
| references | python | goldsmith/Wikipedia | wikipedia/wikipedia.py | https://github.com/goldsmith/Wikipedia/blob/master/wikipedia/wikipedia.py | MIT |
def links(self):
'''
List of titles of Wikipedia page links on a page.
.. note:: Only includes articles from namespace 0, meaning no Category, User talk, or other meta-Wikipedia pages.
'''
if not getattr(self, '_links', False):
self._links = [
link['title']
for link in self._... |
List of titles of Wikipedia page links on a page.
.. note:: Only includes articles from namespace 0, meaning no Category, User talk, or other meta-Wikipedia pages.
| links | python | goldsmith/Wikipedia | wikipedia/wikipedia.py | https://github.com/goldsmith/Wikipedia/blob/master/wikipedia/wikipedia.py | MIT |
def sections(self):
'''
List of section titles from the table of contents on the page.
'''
if not getattr(self, '_sections', False):
query_params = {
'action': 'parse',
'prop': 'sections',
}
if not getattr(self, 'title', None) is None:
query_params["page"] = ... |
List of section titles from the table of contents on the page.
| sections | python | goldsmith/Wikipedia | wikipedia/wikipedia.py | https://github.com/goldsmith/Wikipedia/blob/master/wikipedia/wikipedia.py | MIT |
def section(self, section_title):
'''
Get the plain text content of a section from `self.sections`.
Returns None if `section_title` isn't found, otherwise returns a whitespace stripped string.
This is a convenience method that wraps self.content.
.. warning:: Calling `section` on a section that ha... |
Get the plain text content of a section from `self.sections`.
Returns None if `section_title` isn't found, otherwise returns a whitespace stripped string.
This is a convenience method that wraps self.content.
.. warning:: Calling `section` on a section that has subheadings will NOT return
... | section | python | goldsmith/Wikipedia | wikipedia/wikipedia.py | https://github.com/goldsmith/Wikipedia/blob/master/wikipedia/wikipedia.py | MIT |
def languages():
'''
List all the currently supported language prefixes (usually ISO language code).
Can be inputted to `set_lang` to change the Mediawiki that `wikipedia` requests
results from.
Returns: dict of <prefix>: <local_lang_name> pairs. To get just a list of prefixes,
use `wikipedia.languages().... |
List all the currently supported language prefixes (usually ISO language code).
Can be inputted to `set_lang` to change the Mediawiki that `wikipedia` requests
results from.
Returns: dict of <prefix>: <local_lang_name> pairs. To get just a list of prefixes,
use `wikipedia.languages().keys()`.
| languages | python | goldsmith/Wikipedia | wikipedia/wikipedia.py | https://github.com/goldsmith/Wikipedia/blob/master/wikipedia/wikipedia.py | MIT |
def _wiki_request(params):
'''
Make a request to the Wikipedia API using the given search parameters.
Returns a parsed dict of the JSON response.
'''
global RATE_LIMIT_LAST_CALL
global USER_AGENT
params['format'] = 'json'
if not 'action' in params:
params['action'] = 'query'
headers = {
'Use... |
Make a request to the Wikipedia API using the given search parameters.
Returns a parsed dict of the JSON response.
| _wiki_request | python | goldsmith/Wikipedia | wikipedia/wikipedia.py | https://github.com/goldsmith/Wikipedia/blob/master/wikipedia/wikipedia.py | MIT |
def __init__(self, guid, text, label=None):
"""Constructs a InputExample.
Args:
guid: Unique id for the example.
text_a: string. The untokenized text of the first sequence. For single
sequence tasks, only this sequence must be specified.
label: (Optional) strin... | Constructs a InputExample.
Args:
guid: Unique id for the example.
text_a: string. The untokenized text of the first sequence. For single
sequence tasks, only this sequence must be specified.
label: (Optional) string. The label of the example. This should be
... | __init__ | python | ProHiryu/bert-chinese-ner | BERT_NER.py | https://github.com/ProHiryu/bert-chinese-ner/blob/master/BERT_NER.py | MIT |
def precision(labels, predictions, num_classes, pos_indices=None,
weights=None, average='micro'):
"""Multi-class precision metric for Tensorflow
Parameters
----------
labels : Tensor of tf.int32 or tf.int64
The true labels
predictions : Tensor of tf.int32 or tf.int64
Th... | Multi-class precision metric for Tensorflow
Parameters
----------
labels : Tensor of tf.int32 or tf.int64
The true labels
predictions : Tensor of tf.int32 or tf.int64
The predictions, same shape as labels
num_classes : int
The number of classes
pos_indices : list of int, ... | precision | python | ProHiryu/bert-chinese-ner | tf_metrics.py | https://github.com/ProHiryu/bert-chinese-ner/blob/master/tf_metrics.py | MIT |
def recall(labels, predictions, num_classes, pos_indices=None, weights=None,
average='micro'):
"""Multi-class recall metric for Tensorflow
Parameters
----------
labels : Tensor of tf.int32 or tf.int64
The true labels
predictions : Tensor of tf.int32 or tf.int64
The predict... | Multi-class recall metric for Tensorflow
Parameters
----------
labels : Tensor of tf.int32 or tf.int64
The true labels
predictions : Tensor of tf.int32 or tf.int64
The predictions, same shape as labels
num_classes : int
The number of classes
pos_indices : list of int, opt... | recall | python | ProHiryu/bert-chinese-ner | tf_metrics.py | https://github.com/ProHiryu/bert-chinese-ner/blob/master/tf_metrics.py | MIT |
def fbeta(labels, predictions, num_classes, pos_indices=None, weights=None,
average='micro', beta=1):
"""Multi-class fbeta metric for Tensorflow
Parameters
----------
labels : Tensor of tf.int32 or tf.int64
The true labels
predictions : Tensor of tf.int32 or tf.int64
The pr... | Multi-class fbeta metric for Tensorflow
Parameters
----------
labels : Tensor of tf.int32 or tf.int64
The true labels
predictions : Tensor of tf.int32 or tf.int64
The predictions, same shape as labels
num_classes : int
The number of classes
pos_indices : list of int, opti... | fbeta | python | ProHiryu/bert-chinese-ner | tf_metrics.py | https://github.com/ProHiryu/bert-chinese-ner/blob/master/tf_metrics.py | MIT |
def safe_div(numerator, denominator):
"""Safe division, return 0 if denominator is 0"""
numerator, denominator = tf.to_float(numerator), tf.to_float(denominator)
zeros = tf.zeros_like(numerator, dtype=numerator.dtype)
denominator_is_zero = tf.equal(denominator, zeros)
return tf.where(denominator_is_... | Safe division, return 0 if denominator is 0 | safe_div | python | ProHiryu/bert-chinese-ner | tf_metrics.py | https://github.com/ProHiryu/bert-chinese-ner/blob/master/tf_metrics.py | MIT |
def pr_re_fbeta(cm, pos_indices, beta=1):
"""Uses a confusion matrix to compute precision, recall and fbeta"""
num_classes = cm.shape[0]
neg_indices = [i for i in range(num_classes) if i not in pos_indices]
cm_mask = np.ones([num_classes, num_classes])
cm_mask[neg_indices, neg_indices] = 0
diag_... | Uses a confusion matrix to compute precision, recall and fbeta | pr_re_fbeta | python | ProHiryu/bert-chinese-ner | tf_metrics.py | https://github.com/ProHiryu/bert-chinese-ner/blob/master/tf_metrics.py | MIT |
def metrics_from_confusion_matrix(cm, pos_indices=None, average='micro',
beta=1):
"""Precision, Recall and F1 from the confusion matrix
Parameters
----------
cm : tf.Tensor of type tf.int32, of shape (num_classes, num_classes)
The streaming confusion matrix.
... | Precision, Recall and F1 from the confusion matrix
Parameters
----------
cm : tf.Tensor of type tf.int32, of shape (num_classes, num_classes)
The streaming confusion matrix.
pos_indices : list of int, optional
The indices of the positive classes
beta : int, optional
Weight of... | metrics_from_confusion_matrix | python | ProHiryu/bert-chinese-ner | tf_metrics.py | https://github.com/ProHiryu/bert-chinese-ner/blob/master/tf_metrics.py | MIT |
def run_external_command(command: List[str], print_output: bool = True) -> str:
"""Wrapper to ease the use of calling external programs"""
process = subprocess.Popen(command, text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output, _ = process.communicate()
ret = process.wait()
if (outpu... | Wrapper to ease the use of calling external programs | run_external_command | python | Syncplay/syncplay | ci/macos_app_arch_check.py | https://github.com/Syncplay/syncplay/blob/master/ci/macos_app_arch_check.py | Apache-2.0 |
def _isURITrustableAndTrusted(self, URIToTest):
"""Returns a tuple of booleans: (trustable, trusted).
A given URI is "trustable" if it uses HTTP or HTTPS (constants.TRUSTABLE_WEB_PROTOCOLS).
A given URI is "trusted" if it matches an entry in the trustedDomains config.
Such an en... | Returns a tuple of booleans: (trustable, trusted).
A given URI is "trustable" if it uses HTTP or HTTPS (constants.TRUSTABLE_WEB_PROTOCOLS).
A given URI is "trusted" if it matches an entry in the trustedDomains config.
Such an entry is considered matching if the domain is the same and th... | _isURITrustableAndTrusted | python | Syncplay/syncplay | syncplay/client.py | https://github.com/Syncplay/syncplay/blob/master/syncplay/client.py | Apache-2.0 |
def retry(ExceptionToCheck, tries=4, delay=3, backoff=2, logger=None):
"""Retry calling the decorated function using an exponential backoff.
http://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/
original from: http://wiki.python.org/moin/PythonDecoratorLibrary#Retry
:param Exceptio... | Retry calling the decorated function using an exponential backoff.
http://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/
original from: http://wiki.python.org/moin/PythonDecoratorLibrary#Retry
:param ExceptionToCheck: the exception to check. may be a tuple of
excpetions to chec... | retry | python | Syncplay/syncplay | syncplay/utils.py | https://github.com/Syncplay/syncplay/blob/master/syncplay/utils.py | Apache-2.0 |
def write(self, fp):
"""Write an .ini-format representation of the configuration state."""
if self._defaults:
fp.write("[%s]\n" % DEFAULTSECT)
for (key, value) in list(self._defaults.items()):
fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t')))
... | Write an .ini-format representation of the configuration state. | write | python | Syncplay/syncplay | syncplay/ui/ConfigurationGetter.py | https://github.com/Syncplay/syncplay/blob/master/syncplay/ui/ConfigurationGetter.py | Apache-2.0 |
def _qInstallMessageHandler(handler):
"""Install a message handler that works in all bindings
Args:
handler: A function that takes 3 arguments, or None
"""
def messageOutputHandler(*args):
# In Qt4 bindings, message handlers are passed 2 arguments
# In Qt5 bindings, message hand... | Install a message handler that works in all bindings
Args:
handler: A function that takes 3 arguments, or None
| _qInstallMessageHandler | python | Syncplay/syncplay | syncplay/vendor/Qt.py | https://github.com/Syncplay/syncplay/blob/master/syncplay/vendor/Qt.py | Apache-2.0 |
def _wrapinstance(ptr, base=None):
"""Enable implicit cast of pointer to most suitable class
This behaviour is available in sip per default.
Based on http://nathanhorne.com/pyqtpyside-wrap-instance
Usage:
This mechanism kicks in under these circumstances.
1. Qt.py is using PySide 1 or... | Enable implicit cast of pointer to most suitable class
This behaviour is available in sip per default.
Based on http://nathanhorne.com/pyqtpyside-wrap-instance
Usage:
This mechanism kicks in under these circumstances.
1. Qt.py is using PySide 1 or 2.
2. A `base` argument is not pr... | _wrapinstance | python | Syncplay/syncplay | syncplay/vendor/Qt.py | https://github.com/Syncplay/syncplay/blob/master/syncplay/vendor/Qt.py | Apache-2.0 |
def _isvalid(object):
"""Check if the object is valid to use in Python runtime.
Usage:
See :func:`QtCompat.isValid()`
Arguments:
object (QObject): QObject to check the validity of.
"""
if hasattr(Qt, "_shiboken2"):
return getattr(Qt, "_shiboken2").isValid(object)
elif... | Check if the object is valid to use in Python runtime.
Usage:
See :func:`QtCompat.isValid()`
Arguments:
object (QObject): QObject to check the validity of.
| _isvalid | python | Syncplay/syncplay | syncplay/vendor/Qt.py | https://github.com/Syncplay/syncplay/blob/master/syncplay/vendor/Qt.py | Apache-2.0 |
def _loadUi(uifile, baseinstance=None):
"""Dynamically load a user interface from the given `uifile`
This function calls `uic.loadUi` if using PyQt bindings,
else it implements a comparable binding for PySide.
Documentation:
http://pyqt.sourceforge.net/Docs/PyQt5/designer.html#PyQt5.uic.loadUi... | Dynamically load a user interface from the given `uifile`
This function calls `uic.loadUi` if using PyQt bindings,
else it implements a comparable binding for PySide.
Documentation:
http://pyqt.sourceforge.net/Docs/PyQt5/designer.html#PyQt5.uic.loadUi
Arguments:
uifile (str): Absolute... | _loadUi | python | Syncplay/syncplay | syncplay/vendor/Qt.py | https://github.com/Syncplay/syncplay/blob/master/syncplay/vendor/Qt.py | Apache-2.0 |
def _loadCustomWidgets(self, etree):
"""
Workaround to pyside-77 bug.
From QUiLoader doc we should use registerCustomWidget method.
But this causes a segfault on some platforms.
Instead we fetch from customwidgets DOM node the python clas... |
Workaround to pyside-77 bug.
From QUiLoader doc we should use registerCustomWidget method.
But this causes a segfault on some platforms.
Instead we fetch from customwidgets DOM node the python class
objects. Then we can directly use them... | _loadCustomWidgets | python | Syncplay/syncplay | syncplay/vendor/Qt.py | https://github.com/Syncplay/syncplay/blob/master/syncplay/vendor/Qt.py | Apache-2.0 |
def headerToModule(header):
"""
Translate a header file to python module path
foo/bar.h => foo.bar
"""
# Remove header extension
module = os.path.splitext(header)[0]
# Replace os ... |
Translate a header file to python module path
foo/bar.h => foo.bar
| headerToModule | python | Syncplay/syncplay | syncplay/vendor/Qt.py | https://github.com/Syncplay/syncplay/blob/master/syncplay/vendor/Qt.py | Apache-2.0 |
def createWidget(self, class_name, parent=None, name=""):
"""Called for each widget defined in ui file
Overridden here to populate `baseinstance` instead.
"""
if parent is None and self.baseinstance:
# Supposed to create the top-leve... | Called for each widget defined in ui file
Overridden here to populate `baseinstance` instead.
| createWidget | python | Syncplay/syncplay | syncplay/vendor/Qt.py | https://github.com/Syncplay/syncplay/blob/master/syncplay/vendor/Qt.py | Apache-2.0 |
def _import_sub_module(module, name):
"""import_sub_module will mimic the function of importlib.import_module"""
module = __import__(module.__name__ + "." + name)
for level in name.split("."):
module = getattr(module, level)
return module | import_sub_module will mimic the function of importlib.import_module | _import_sub_module | python | Syncplay/syncplay | syncplay/vendor/Qt.py | https://github.com/Syncplay/syncplay/blob/master/syncplay/vendor/Qt.py | Apache-2.0 |
def _reassign_misplaced_members(binding):
"""Apply misplaced members from `binding` to Qt.py
Arguments:
binding (dict): Misplaced members
"""
for src, dst in _misplaced_members[binding].items():
dst_value = None
src_parts = src.split(".")
src_module = src_parts[0]
... | Apply misplaced members from `binding` to Qt.py
Arguments:
binding (dict): Misplaced members
| _reassign_misplaced_members | python | Syncplay/syncplay | syncplay/vendor/Qt.py | https://github.com/Syncplay/syncplay/blob/master/syncplay/vendor/Qt.py | Apache-2.0 |
def _build_compatibility_members(binding, decorators=None):
"""Apply `binding` to QtCompat
Arguments:
binding (str): Top level binding in _compatibility_members.
decorators (dict, optional): Provides the ability to decorate the
original Qt methods when needed by a binding. This can ... | Apply `binding` to QtCompat
Arguments:
binding (str): Top level binding in _compatibility_members.
decorators (dict, optional): Provides the ability to decorate the
original Qt methods when needed by a binding. This can be used
to change the returned value to a standard valu... | _build_compatibility_members | python | Syncplay/syncplay | syncplay/vendor/Qt.py | https://github.com/Syncplay/syncplay/blob/master/syncplay/vendor/Qt.py | Apache-2.0 |
def _pyside6():
"""Initialise PySide6
These functions serve to test the existence of a binding
along with set it up in such a way that it aligns with
the final step; adding members from the original binding
to Qt.py
"""
import PySide6 as module
extras = ["QtUiTools"]
try:
... | Initialise PySide6
These functions serve to test the existence of a binding
along with set it up in such a way that it aligns with
the final step; adding members from the original binding
to Qt.py
| _pyside6 | python | Syncplay/syncplay | syncplay/vendor/Qt.py | https://github.com/Syncplay/syncplay/blob/master/syncplay/vendor/Qt.py | Apache-2.0 |
def _pyside2():
"""Initialise PySide2
These functions serve to test the existence of a binding
along with set it up in such a way that it aligns with
the final step; adding members from the original binding
to Qt.py
"""
import PySide2 as module
extras = ["QtUiTools"]
try:
... | Initialise PySide2
These functions serve to test the existence of a binding
along with set it up in such a way that it aligns with
the final step; adding members from the original binding
to Qt.py
| _pyside2 | python | Syncplay/syncplay | syncplay/vendor/Qt.py | https://github.com/Syncplay/syncplay/blob/master/syncplay/vendor/Qt.py | Apache-2.0 |
def _standardizeQFileDialog(some_function):
"""Decorator that makes PyQt4 return conform to other bindings"""
def wrapper(*args, **kwargs):
ret = (some_function(*args, **kwargs))
# PyQt4 only returns the selected filename, force it to a
# standard return of the selec... | Decorator that makes PyQt4 return conform to other bindings | _standardizeQFileDialog | python | Syncplay/syncplay | syncplay/vendor/Qt.py | https://github.com/Syncplay/syncplay/blob/master/syncplay/vendor/Qt.py | Apache-2.0 |
def _convert(lines):
"""Convert compiled .ui file from PySide2 to Qt.py
Arguments:
lines (list): Each line of of .ui file
Usage:
>> with open("myui.py") as f:
.. lines = _convert(f.readlines())
"""
def parse(line):
line = line.replace("from PySide2 import", "fro... | Convert compiled .ui file from PySide2 to Qt.py
Arguments:
lines (list): Each line of of .ui file
Usage:
>> with open("myui.py") as f:
.. lines = _convert(f.readlines())
| _convert | python | Syncplay/syncplay | syncplay/vendor/Qt.py | https://github.com/Syncplay/syncplay/blob/master/syncplay/vendor/Qt.py | Apache-2.0 |
def _add(self, xer, primary, type):
"""
Private method for adding a descriptor from the event loop.
It takes care of adding it if new or modifying it if already added
for another state (read -> read/write for example).
"""
if xer not in primary:
primary[xer]... |
Private method for adding a descriptor from the event loop.
It takes care of adding it if new or modifying it if already added
for another state (read -> read/write for example).
| _add | python | Syncplay/syncplay | syncplay/vendor/qt5reactor.py | https://github.com/Syncplay/syncplay/blob/master/syncplay/vendor/qt5reactor.py | Apache-2.0 |
def _remove(self, xer, primary):
"""
Private method for removing a descriptor from the event loop.
It does the inverse job of _add, and also add a check in case of the fd
has gone away.
"""
if xer in primary:
notifier = primary.pop(xer)
notifier.s... |
Private method for removing a descriptor from the event loop.
It does the inverse job of _add, and also add a check in case of the fd
has gone away.
| _remove | python | Syncplay/syncplay | syncplay/vendor/qt5reactor.py | https://github.com/Syncplay/syncplay/blob/master/syncplay/vendor/qt5reactor.py | Apache-2.0 |
def doIteration(self, delay=None, fromqt=False):
"""This method is called by a Qt timer or by network activity on a file descriptor"""
if not self.running and self._blockApp:
self._blockApp.quit()
self._timer.stop()
if delay is None:
delay = 0
delay = max(... | This method is called by a Qt timer or by network activity on a file descriptor | doIteration | python | Syncplay/syncplay | syncplay/vendor/qt5reactor.py | https://github.com/Syncplay/syncplay/blob/master/syncplay/vendor/qt5reactor.py | Apache-2.0 |
def iterate(self, delay=None, fromqt=False):
"""See twisted.internet.interfaces.IReactorCore.iterate."""
self.runUntilCurrent()
self.doEvents()
self.doIteration(delay, fromqt=fromqt) | See twisted.internet.interfaces.IReactorCore.iterate. | iterate | python | Syncplay/syncplay | syncplay/vendor/qt5reactor.py | https://github.com/Syncplay/syncplay/blob/master/syncplay/vendor/qt5reactor.py | Apache-2.0 |
def theme():
""" Uses the Windows Registry to detect if the user is using Dark Mode """
# Registry will return 0 if Windows is in Dark Mode and 1 if Windows is in Light Mode. This dictionary converts that output into the text that the program is expecting.
valueMeaning = {0: "Dark", 1: "Light"}
# In HKE... | Uses the Windows Registry to detect if the user is using Dark Mode | theme | python | Syncplay/syncplay | syncplay/vendor/darkdetect/_windows_detect.py | https://github.com/Syncplay/syncplay/blob/master/syncplay/vendor/darkdetect/_windows_detect.py | Apache-2.0 |
def __init__(self, ipc_socket, callback=None, quit_callback=None):
"""Create the wrapper.
*ipc_socket* is the pipe name. (Not including \\\\.\\pipe\\)
*callback(json_data)* is the function for recieving events.
*quit_callback* is called when the socket connection dies.
"""
... | Create the wrapper.
*ipc_socket* is the pipe name. (Not including \\.\pipe\)
*callback(json_data)* is the function for recieving events.
*quit_callback* is called when the socket connection dies.
| __init__ | python | Syncplay/syncplay | syncplay/vendor/python_mpv_jsonipc/python_mpv_jsonipc.py | https://github.com/Syncplay/syncplay/blob/master/syncplay/vendor/python_mpv_jsonipc/python_mpv_jsonipc.py | Apache-2.0 |
def send(self, data):
"""Send *data* to the pipe, encoded as JSON."""
try:
self.socket.send_bytes(json.dumps(data).encode('utf-8') + b'\n')
except OSError as ex:
raise ex | Send *data* to the pipe, encoded as JSON. | send | python | Syncplay/syncplay | syncplay/vendor/python_mpv_jsonipc/python_mpv_jsonipc.py | https://github.com/Syncplay/syncplay/blob/master/syncplay/vendor/python_mpv_jsonipc/python_mpv_jsonipc.py | Apache-2.0 |
def run(self):
"""Process pipe events. Do not run this directly. Use *start*."""
data = b''
try:
while True:
current_data = self.socket.recv_bytes(2048)
if current_data == b'':
break
data += current_data
... | Process pipe events. Do not run this directly. Use *start*. | run | python | Syncplay/syncplay | syncplay/vendor/python_mpv_jsonipc/python_mpv_jsonipc.py | https://github.com/Syncplay/syncplay/blob/master/syncplay/vendor/python_mpv_jsonipc/python_mpv_jsonipc.py | Apache-2.0 |
def __init__(self, ipc_socket, callback=None, quit_callback=None):
"""Create the wrapper.
*ipc_socket* is the path to the socket.
*callback(json_data)* is the function for recieving events.
*quit_callback* is called when the socket connection dies.
"""
self.ipc_socket = ... | Create the wrapper.
*ipc_socket* is the path to the socket.
*callback(json_data)* is the function for recieving events.
*quit_callback* is called when the socket connection dies.
| __init__ | python | Syncplay/syncplay | syncplay/vendor/python_mpv_jsonipc/python_mpv_jsonipc.py | https://github.com/Syncplay/syncplay/blob/master/syncplay/vendor/python_mpv_jsonipc/python_mpv_jsonipc.py | Apache-2.0 |
def send(self, data):
"""Send *data* to the socket, encoded as JSON."""
if self.socket is None:
raise BrokenPipeError("socket is closed")
self.socket.send(json.dumps(data).encode('utf-8') + b'\n') | Send *data* to the socket, encoded as JSON. | send | python | Syncplay/syncplay | syncplay/vendor/python_mpv_jsonipc/python_mpv_jsonipc.py | https://github.com/Syncplay/syncplay/blob/master/syncplay/vendor/python_mpv_jsonipc/python_mpv_jsonipc.py | Apache-2.0 |
def run(self):
"""Process socket events. Do not run this directly. Use *start*."""
data = b''
try:
while True:
current_data = self.socket.recv(1024)
if current_data == b'':
break
data += current_data
... | Process socket events. Do not run this directly. Use *start*. | run | python | Syncplay/syncplay | syncplay/vendor/python_mpv_jsonipc/python_mpv_jsonipc.py | https://github.com/Syncplay/syncplay/blob/master/syncplay/vendor/python_mpv_jsonipc/python_mpv_jsonipc.py | Apache-2.0 |
def __init__(self, ipc_socket, mpv_location=None, env=None, **kwargs):
"""
Create and start the MPV process. Will block until socket/pipe is available.
*ipc_socket* is the path to the Unix/Linux socket or name of the Windows pipe.
*mpv_location* is the path to mpv. If left unset it trie... |
Create and start the MPV process. Will block until socket/pipe is available.
*ipc_socket* is the path to the Unix/Linux socket or name of the Windows pipe.
*mpv_location* is the path to mpv. If left unset it tries the one in the PATH.
All other arguments are forwarded to MPV as comman... | __init__ | python | Syncplay/syncplay | syncplay/vendor/python_mpv_jsonipc/python_mpv_jsonipc.py | https://github.com/Syncplay/syncplay/blob/master/syncplay/vendor/python_mpv_jsonipc/python_mpv_jsonipc.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.