uid
stringlengths
24
24
split
stringclasses
1 value
category
stringclasses
2 values
content
stringlengths
5
482k
signature
stringlengths
1
14k
suffix
stringlengths
1
482k
prefix
stringlengths
9
14k
prefix_token_count
int64
3
5.01k
prefix_token_budget
int64
64
256
element_token_count
int64
1
292k
signature_token_count
int64
1
5.01k
prefix_context_token_count
int64
0
255
repo
stringlengths
7
112
path
stringlengths
4
208
language
stringclasses
1 value
name
stringlengths
1
218
qualname
stringlengths
1
218
start_line
int64
1
26.7k
end_line
int64
1
26.7k
signature_start_line
int64
1
26.7k
signature_end_line
int64
1
26.7k
source_hash
stringlengths
40
40
source_dataset
stringclasses
1 value
source_split
stringclasses
1 value
c7cd3ef8f75f079a48b53965
train
function
def test_get_aperture_no_lazy(): """Tests if the lazy=False feature in getSpaxels works.""" cube = marvin.tools.Cube('8485-1901') aperture = cube.getAperture((17, 17), 1) assert aperture.getSpaxels(lazy=False)[0].loaded is True
def test_get_aperture_no_lazy():
"""Tests if the lazy=False feature in getSpaxels works.""" cube = marvin.tools.Cube('8485-1901') aperture = cube.getAperture((17, 17), 1) assert aperture.getSpaxels(lazy=False)[0].loaded is True
(spaxels) == n_spaxels assert spaxels[0].loaded is False # Check that we can load the spaxel spaxels[0].load() assert spaxels[0].loaded is True def test_get_aperture_no_lazy():
64
64
73
9
54
margudo/marvin
python/marvin/tests/tools/test_aperture.py
Python
test_get_aperture_no_lazy
test_get_aperture_no_lazy
106
113
106
106
5f45cc54a121bd36b98401187b21f8ca9e7d5aad
bigcode/the-stack
train
258fbc987ca4291985faffd8
train
function
def test_get_spaxels_custom_mask(): """Tests the mask parameter in getSpaxels.""" cube = marvin.tools.Cube('8485-1901') aperture = cube.getAperture((17, 17), 2) my_mask = aperture.mask.copy() my_mask[0:5, 0:5] = 1 assert len(aperture.getSpaxels(mask=my_mask)) == 34
def test_get_spaxels_custom_mask():
"""Tests the mask parameter in getSpaxels.""" cube = marvin.tools.Cube('8485-1901') aperture = cube.getAperture((17, 17), 2) my_mask = aperture.mask.copy() my_mask[0:5, 0:5] = 1 assert len(aperture.getSpaxels(mask=my_mask)) == 34
getSpaxels works.""" cube = marvin.tools.Cube('8485-1901') aperture = cube.getAperture((17, 17), 1) assert aperture.getSpaxels(lazy=False)[0].loaded is True def test_get_spaxels_custom_mask():
64
64
96
9
54
margudo/marvin
python/marvin/tests/tools/test_aperture.py
Python
test_get_spaxels_custom_mask
test_get_spaxels_custom_mask
116
126
116
116
2fe23417f0d9859dfe2c9a04729ba541b1945b58
bigcode/the-stack
train
07e9300907fd13ceaa289e9b
train
function
@pytest.mark.parametrize('inputs, outputs', test_params) def test_get_aperture(inputs, outputs): class_name, plateifu, release, coords, \ aperture_params, aperture_type, coord_type, threshold = inputs set_the_config(release) aperture_params = numpy.atleast_1d(aperture_params) n_pixels_mask, ...
@pytest.mark.parametrize('inputs, outputs', test_params) def test_get_aperture(inputs, outputs):
class_name, plateifu, release, coords, \ aperture_params, aperture_type, coord_type, threshold = inputs set_the_config(release) aperture_params = numpy.atleast_1d(aperture_params) n_pixels_mask, n_spaxels = outputs ToolClass = getattr(marvin.tools, class_name) instance = ToolClass(pl...
, 17), 3, 'circular', 'pixel', 0.5], [21, 25]], [['Maps', '8485-1901', 'MPL-6', (232.5447, 48.690201), 1, 'circular', 'sky', 0.8], [5, 9]], [['Maps', '8485-1901', 'MPL-6', [(5, 5), (20, 20)], (4, 4, 0), 'rectangular', 'pixel', 0.5], [18, 42]], [['Maps', '8485-1901', 'MPL-6', (5, 5), (4, 4, 45), 'ell...
209
209
698
21
188
margudo/marvin
python/marvin/tests/tools/test_aperture.py
Python
test_get_aperture
test_get_aperture
39
103
39
41
c42e4e349347fdf0c4425013aba9157518c0ad68
bigcode/the-stack
train
5dc4bee7d0e16aaefb0e36f8
train
function
@click.command() @click.argument('config_path', type=click.Path(exists=True)) def main(config_path): """ UNet2D pretrained on binary classification with the RSNA dataset and finetuned with the public data. """ # load the config file cfg = AttrDict.from_json_path(config_path) # Make Outputs dire...
@click.command() @click.argument('config_path', type=click.Path(exists=True)) def main(config_path):
""" UNet2D pretrained on binary classification with the RSNA dataset and finetuned with the public data. """ # load the config file cfg = AttrDict.from_json_path(config_path) # Make Outputs directories out_path = os.path.join(cfg.path.output, cfg.exp_name) out_path_selfsup = os.path.joi...
""" author: Antoine Spahr date : 03.12.2020 ---------- TO DO : """ import sys sys.path.append('../../') import click import os import logging import json import random import torch import torch.cuda import numpy as np import pandas as pd from datetime import datetime from prettytable import PrettyTable from sklearn...
210
256
3,565
22
187
antoine-spahr/Label-Efficient-Volumetric-Deep-Semantic-Segmentation-of-ICH
code/scripts/binary_classification_pretraining/BinaryClassification_UNet2D_scripts.py
Python
main
main
35
273
35
37
9ec3182628943943f8003a66786e9d7e0bf6ef18
bigcode/the-stack
train
6539d57eed023561cde35e56
train
function
def get_available_device(): """ return the avialable device. """ if torch.cuda.is_available(): free_mem, device_idx = 0.0, 0 for d in range(torch.cuda.device_count()): mem = torch.cuda.get_device_properties(d).total_memory - torch.cuda.memory_allocated(d) if mem >...
def get_available_device():
""" return the avialable device. """ if torch.cuda.is_available(): free_mem, device_idx = 0.0, 0 for d in range(torch.cuda.device_count()): mem = torch.cuda.get_device_properties(d).total_memory - torch.cuda.memory_allocated(d) if mem > free_mem: d...
logger.setLevel(logging.INFO) file_handler = logging.FileHandler(logger_fn) file_handler.setLevel(logging.INFO) file_handler.setFormatter(logging.Formatter('%(asctime)s | %(levelname)s | %(message)s')) logger.addHandler(file_handler) return logger def get_available_device():
64
64
109
5
58
antoine-spahr/Label-Efficient-Volumetric-Deep-Semantic-Segmentation-of-ICH
code/scripts/binary_classification_pretraining/BinaryClassification_UNet2D_scripts.py
Python
get_available_device
get_available_device
294
307
294
294
ec63fdd3337284de299587e47d398c3573df9eed
bigcode/the-stack
train
f1343115306c2de989995788
train
function
def save_mean_fold_dice(out_path, n_fold): """ Save the mean dice over folds in a txt file. """ # recover mean Fold Dice scores_list = [] for k in range(n_fold): with open(os.path.join(out_path, f'Fold_{k+1}/outputs.json'), 'r') as f: out = json.load(f) scores_list.ap...
def save_mean_fold_dice(out_path, n_fold):
""" Save the mean dice over folds in a txt file. """ # recover mean Fold Dice scores_list = [] for k in range(n_fold): with open(os.path.join(out_path, f'Fold_{k+1}/outputs.json'), 'r') as f: out = json.load(f) scores_list.append([out['eval']['dice']['all'], out['eval...
orrhage == 1]), f'{len(df[df.Hemorrhage == 0])/len(df):.3%}', f'{len(df[df.Hemorrhage == 1])/len(df):.3%}']) return table def save_mean_fold_dice(out_path, n_fold):
64
64
216
12
51
antoine-spahr/Label-Efficient-Volumetric-Deep-Semantic-Segmentation-of-ICH
code/scripts/binary_classification_pretraining/BinaryClassification_UNet2D_scripts.py
Python
save_mean_fold_dice
save_mean_fold_dice
320
336
320
320
fb47a7143a4aba2b008858b053809522830bbc81
bigcode/the-stack
train
2c86bacd4d47afa116d5e920
train
function
def initialize_logger(logger_fn): """ Initialize a logger with given file name. It will start a new logger. """ logging.basicConfig(level=logging.INFO) logger = logging.getLogger() try: logger.handlers[1].stream.close() logger.removeHandler(logger.handlers[1]) except IndexErr...
def initialize_logger(logger_fn):
""" Initialize a logger with given file name. It will start a new logger. """ logging.basicConfig(level=logging.INFO) logger = logging.getLogger() try: logger.handlers[1].stream.close() logger.removeHandler(logger.handlers[1]) except IndexError: pass logger.setLev...
vised_overview.pdf')) analyse_representation_exp(out_path_selfsup, save_fn=os.path.join(out_path, 'results_self-supervised_overview.pdf')) logger.info('Results overview figure saved at ' + os.path.join(out_path, 'results_self-supervised_overview.pdf')) def initialize_logger(logger_fn):
64
64
129
6
58
antoine-spahr/Label-Efficient-Volumetric-Deep-Semantic-Segmentation-of-ICH
code/scripts/binary_classification_pretraining/BinaryClassification_UNet2D_scripts.py
Python
initialize_logger
initialize_logger
275
292
275
275
2c1eab2c15f8502ccdf4f12dfbe7114a588f6a68
bigcode/the-stack
train
3ff623e3b8682b94c8f368a6
train
function
def get_split_summary_table(all_df, train_df, test_df): """ return a table summarising the data split. """ table = PrettyTable() table.field_names = ['set', 'N total', 'N non-ICH', 'N ICH', 'frac non-ICH', 'frac ICH'] for df, name in zip([all_df, train_df, test_df],['All', 'Train', 'Test']): ...
def get_split_summary_table(all_df, train_df, test_df):
""" return a table summarising the data split. """ table = PrettyTable() table.field_names = ['set', 'N total', 'N non-ICH', 'N ICH', 'frac non-ICH', 'frac ICH'] for df, name in zip([all_df, train_df, test_df],['All', 'Train', 'Test']): table.add_row([name, len(df), len(df[df.Hemorrhage ...
total_memory - torch.cuda.memory_allocated(d) if mem > free_mem: device_idx = d free_mem = mem return torch.device(f'cuda:{device_idx}') else: return torch.device('cpu') def get_split_summary_table(all_df, train_df, test_df):
64
64
172
14
50
antoine-spahr/Label-Efficient-Volumetric-Deep-Semantic-Segmentation-of-ICH
code/scripts/binary_classification_pretraining/BinaryClassification_UNet2D_scripts.py
Python
get_split_summary_table
get_split_summary_table
309
318
309
309
88231965ad599ab015c5fcc24f95b114e4d6164e
bigcode/the-stack
train
a33a34f951fb039276dc3cad
train
function
def _poll_operator_resource(client, operator_type, tracker): if operator_type == events_constants.Operator.KUBERUN: client.PollKubeRunResource(tracker) else: client.PollCloudRunResource(tracker)
def _poll_operator_resource(client, operator_type, tracker):
if operator_type == events_constants.Operator.KUBERUN: client.PollKubeRunResource(tracker) else: client.PollCloudRunResource(tracker)
.') def _update_operator_with_eventing_enabled(client, operator_type): if operator_type == events_constants.Operator.KUBERUN: client.UpdateKubeRunWithEventingEnabled() else: client.UpdateCloudRunWithEventingEnabled() def _poll_operator_resource(client, operator_type, tracker):
64
64
49
12
52
google-cloud-sdk-unofficial/google-cloud-sdk
lib/googlecloudsdk/command_lib/kuberun/core/events/operator.py
Python
_poll_operator_resource
_poll_operator_resource
105
109
105
105
bf4ff4acece839914ca7d8eafe79061ed3b96d46
bigcode/the-stack
train
47203117ded2b89b56a03825
train
function
def _update_operator_with_eventing_enabled(client, operator_type): if operator_type == events_constants.Operator.KUBERUN: client.UpdateKubeRunWithEventingEnabled() else: client.UpdateCloudRunWithEventingEnabled()
def _update_operator_with_eventing_enabled(client, operator_type):
if operator_type == events_constants.Operator.KUBERUN: client.UpdateKubeRunWithEventingEnabled() else: client.UpdateCloudRunWithEventingEnabled()
for Operator to enable eventing _poll_operator_resource(client, operator_type, tracker) if operator_obj.eventing_enabled: log.status.Print('Eventing already enabled.') else: log.status.Print('Enabled eventing successfully.') def _update_operator_with_eventing_enabled(client, operator_type):
63
64
50
13
50
google-cloud-sdk-unofficial/google-cloud-sdk
lib/googlecloudsdk/command_lib/kuberun/core/events/operator.py
Python
_update_operator_with_eventing_enabled
_update_operator_with_eventing_enabled
98
102
98
98
753cbfd571d7e01a89c3ec0d142f5101b4c1df61
bigcode/the-stack
train
43ec38a660b93c51ebdc13bf
train
function
def install_eventing_via_operator(client, track): """Install eventing cluster by enabling it via the KubeRun operator. Attempt to determine whether KubeRun or CloudRun operator is installed by presence of the corresponding operator resource or namespace. Args: client: An api_tools client. track: bas...
def install_eventing_via_operator(client, track):
"""Install eventing cluster by enabling it via the KubeRun operator. Attempt to determine whether KubeRun or CloudRun operator is installed by presence of the corresponding operator resource or namespace. Args: client: An api_tools client. track: base.ReleaseTrack, the release (ga, beta, alpha) the ...
# See the License for the specific language governing permissions and # limitations under the License. """Provides functions for installing Eventing with the CloudRun operator.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode...
160
160
535
11
148
google-cloud-sdk-unofficial/google-cloud-sdk
lib/googlecloudsdk/command_lib/kuberun/core/events/operator.py
Python
install_eventing_via_operator
install_eventing_via_operator
33
95
33
33
b45048b1dbf246442ab9c41d3325efb816acb873
bigcode/the-stack
train
c48e6ac7691a1a5ab47d30fa
train
class
class UserAdmin(BaseUserAdmin): ordering = ['id'] list_display = ['email', 'name'] fieldsets = ( (None, {'fields': ('email', 'password')}), (_('Personal info'), {'fields': ('name',)}), ( _('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser')} ...
class UserAdmin(BaseUserAdmin):
ordering = ['id'] list_display = ['email', 'name'] fieldsets = ( (None, {'fields': ('email', 'password')}), (_('Personal info'), {'fields': ('name',)}), ( _('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser')} ), (_('Important ...
from django.contrib import admin from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from django.utils.translation import gettext as _ from core import models class UserAdmin(BaseUserAdmin):
40
64
135
7
32
clicktravel-chau/recipe-app-api
app/core/admin.py
Python
UserAdmin
UserAdmin
8
25
8
8
8472b08c464b5b96c021e05ac339b26b54ebfec4
bigcode/the-stack
train
9ca562df18dacfbb4754eb97
train
class
class TestCommonDirname(TestCase): def test_all_match(self): self.assertEqual(NavigationMeta._common_dirname([ 'a/1.md', 'a/2.md' ]), 'a') def test_some_match(self): self.assertEqual(NavigationMeta._common_dirname([ 'a/1.md', 'a/2.md', ...
class TestCommonDirname(TestCase):
def test_all_match(self): self.assertEqual(NavigationMeta._common_dirname([ 'a/1.md', 'a/2.md' ]), 'a') def test_some_match(self): self.assertEqual(NavigationMeta._common_dirname([ 'a/1.md', 'a/2.md', 'b/3.md' ]), None)...
from typing import Optional from unittest import TestCase from .base import NavigationTestCase from ...meta import Meta, MetaNavRestItem, RestType from ...navigation import NavigationMeta from ...options import Options from ...utils import normpath class TestCommonDirname(TestCase):
61
64
216
8
52
lukasgeiter/mkdocs-awesome-pages-plugin
mkdocs_awesome_pages_plugin/tests/navigation/test_meta.py
Python
TestCommonDirname
TestCommonDirname
11
45
11
12
d110fc01571c94e240248daa3ed492d17a4b2fd5
bigcode/the-stack
train
61e7d9c3165345354f49c4ee
train
class
class TestRestParsing(NavigationTestCase): def test_all(self): item = MetaNavRestItem('...') self.assertIsNone(item.pattern) self.assertEqual(item.type, RestType.ALL) self.assertFalse(item.flat) def test_all_flat(self): item = MetaNavRestItem('...|flat') self....
class TestRestParsing(NavigationTestCase):
def test_all(self): item = MetaNavRestItem('...') self.assertIsNone(item.pattern) self.assertEqual(item.type, RestType.ALL) self.assertFalse(item.flat) def test_all_flat(self): item = MetaNavRestItem('...|flat') self.assertIsNone(item.pattern) self.asse...
.assertMeta(meta.root, path='.index') def test_links(self): meta = NavigationMeta([ self.page('Page', 'page.md'), self.link('Link') ], self.options, docs_dir='', explicit_sections=set()) self.assertEqual(len(meta.sections), 0) self.assertMeta(meta.root, path...
256
256
1,325
9
247
lukasgeiter/mkdocs-awesome-pages-plugin
mkdocs_awesome_pages_plugin/tests/navigation/test_meta.py
Python
TestRestParsing
TestRestParsing
176
351
176
177
a8401ac149a949c55f7a55f513fa87ba20f9d462
bigcode/the-stack
train
c04738874e7c6f3ef94a8921
train
class
class TestMeta(NavigationTestCase): def assertMeta(self, actual: Meta, expected: Optional[Meta] = None, *, path: Optional[str] = None): if expected is None: expected = Meta( path=path ) self.assertEqual(actual.collapse_single_pages, expected.collapse_single_...
class TestMeta(NavigationTestCase):
def assertMeta(self, actual: Meta, expected: Optional[Meta] = None, *, path: Optional[str] = None): if expected is None: expected = Meta( path=path ) self.assertEqual(actual.collapse_single_pages, expected.collapse_single_pages) self.assertEqual(actua...
meta import Meta, MetaNavRestItem, RestType from ...navigation import NavigationMeta from ...options import Options from ...utils import normpath class TestCommonDirname(TestCase): def test_all_match(self): self.assertEqual(NavigationMeta._common_dirname([ 'a/1.md', 'a/2.md' ...
256
256
943
8
248
lukasgeiter/mkdocs-awesome-pages-plugin
mkdocs_awesome_pages_plugin/tests/navigation/test_meta.py
Python
TestMeta
TestMeta
48
173
48
49
a27d315416e17848750a02f5971510a7c78dd210
bigcode/the-stack
train
e2fb40b71cecf021db2f2d22
train
class
class TestSitesData(unittest.TestCase): def test_all_categories_are_valid(self): for site, category in iterate_site_categories(): self.assertIsNotNone(site) self.assertTrue('.' in site) self.assertIn(category, VALID_CATEGORIES) def test_no_repeated_sites(self): ...
class TestSitesData(unittest.TestCase):
def test_all_categories_are_valid(self): for site, category in iterate_site_categories(): self.assertIsNotNone(site) self.assertTrue('.' in site) self.assertIn(category, VALID_CATEGORIES) def test_no_repeated_sites(self): sites = set([]) for site, ca...
iterate_site_categories(): with open('./whotracksme/data/assets/site_categories.csv', 'r') as fp: reader = csv.reader(fp, delimiter=',') for line in reader: if reader.line_num == 1: continue yield line class TestSitesData(unittest.TestCase):
64
64
103
8
55
philipp-classen/whotracks.me
tests/test_site_categories.py
Python
TestSitesData
TestSitesData
26
40
26
27
cbc7157d24bfd03617dfb96c23e37621b61c98ba
bigcode/the-stack
train
ba7b7ac9045d4764ea1ea037
train
function
def iterate_site_categories(): with open('./whotracksme/data/assets/site_categories.csv', 'r') as fp: reader = csv.reader(fp, delimiter=',') for line in reader: if reader.line_num == 1: continue yield line
def iterate_site_categories():
with open('./whotracksme/data/assets/site_categories.csv', 'r') as fp: reader = csv.reader(fp, delimiter=',') for line in reader: if reader.line_num == 1: continue yield line
import unittest import csv VALID_CATEGORIES = set([ "Adult", "Banking", "Business", "E-Commerce", "Entertainment", "Government", "News and Portals", "Political", "Recreation", "Reference" ]) def iterate_site_categories():
64
64
57
5
59
philipp-classen/whotracks.me
tests/test_site_categories.py
Python
iterate_site_categories
iterate_site_categories
17
23
17
17
8824c1e1bf90421b44708175488aab5d2c35ece5
bigcode/the-stack
train
1134fe60b45d10a5e4e8d76c
train
function
def blue(string): return c_blue + string + c_reset
def blue(string):
return c_blue + string + c_reset
[49;0;36m' c_yellow = '\033[49;1;33m' c_reset = '\033[0m' def green(string): return c_green + string + c_reset def red(string): return c_red + string + c_reset def blue(string):
64
64
14
4
59
MalteSchledjewski/cadet
scripts/reporting.py
Python
blue
blue
16
17
16
16
f315caf4618dfe7daad630312b9489034cb5de75
bigcode/the-stack
train
cacd88f2431f12b30053fa82
train
function
def yellow(string): return c_yellow + string + c_reset
def yellow(string):
return c_yellow + string + c_reset
[49;1;33m' c_reset = '\033[0m' def green(string): return c_green + string + c_reset def red(string): return c_red + string + c_reset def blue(string): return c_blue + string + c_reset def yellow(string):
64
64
15
4
59
MalteSchledjewski/cadet
scripts/reporting.py
Python
yellow
yellow
19
20
19
19
77f4200abc681e57165f78cec4c1359a83d96060
bigcode/the-stack
train
fe8ac2ac02e790fcf02ba9b8
train
function
def fatal(msg): print(red('Fatal Error: ' + msg)) exit(1)
def fatal(msg):
print(red('Fatal Error: ' + msg)) exit(1)
): return c_yellow + string + c_reset def cyan(string): return c_cyan + string + c_reset def log(msg): print(msg) def log_progress(msg): sys.stdout.write(msg) def error(msg): print(red('Error: ' + msg)) def fatal(msg):
64
64
20
4
60
MalteSchledjewski/cadet
scripts/reporting.py
Python
fatal
fatal
34
36
34
34
56548387e8fb5d208ac4e2279265e8e10ce2cee4
bigcode/the-stack
train
622fce04f1f22d62f6979209
train
function
def log_progress(msg): sys.stdout.write(msg)
def log_progress(msg):
sys.stdout.write(msg)
_red + string + c_reset def blue(string): return c_blue + string + c_reset def yellow(string): return c_yellow + string + c_reset def cyan(string): return c_cyan + string + c_reset def log(msg): print(msg) def log_progress(msg):
64
64
11
5
59
MalteSchledjewski/cadet
scripts/reporting.py
Python
log_progress
log_progress
28
29
28
28
db4cda3ca2ecfa7f58ea2dff10672eb4cd8acac7
bigcode/the-stack
train
bca6123229de4190ef206871
train
function
def red(string): return c_red + string + c_reset
def red(string):
return c_red + string + c_reset
49;0;32m' c_cyan = '\033[49;0;36m' c_yellow = '\033[49;1;33m' c_reset = '\033[0m' def green(string): return c_green + string + c_reset def red(string):
64
64
14
4
59
MalteSchledjewski/cadet
scripts/reporting.py
Python
red
red
13
14
13
13
546dec993de1a31d616482e529af365a71805152
bigcode/the-stack
train
58d73df2cc387058fcccaa8c
train
function
def cyan(string): return c_cyan + string + c_reset
def cyan(string):
return c_cyan + string + c_reset
0m' def green(string): return c_green + string + c_reset def red(string): return c_red + string + c_reset def blue(string): return c_blue + string + c_reset def yellow(string): return c_yellow + string + c_reset def cyan(string):
64
64
15
4
59
MalteSchledjewski/cadet
scripts/reporting.py
Python
cyan
cyan
22
23
22
22
1fc8f36ee15b8254d67cff832de9206f0a058449
bigcode/the-stack
train
340f35da6262f0b96eb220fc
train
function
def error(msg): print(red('Error: ' + msg))
def error(msg):
print(red('Error: ' + msg))
): return c_blue + string + c_reset def yellow(string): return c_yellow + string + c_reset def cyan(string): return c_cyan + string + c_reset def log(msg): print(msg) def log_progress(msg): sys.stdout.write(msg) def error(msg):
64
64
14
4
60
MalteSchledjewski/cadet
scripts/reporting.py
Python
error
error
31
32
31
31
5fe25eba139b1f0fe8c38559a724e0ff77354ed2
bigcode/the-stack
train
b34350434faac8875d1bccc3
train
function
def green(string): return c_green + string + c_reset
def green(string):
return c_green + string + c_reset
49;0;31m' c_green = '\033[49;0;32m' c_cyan = '\033[49;0;36m' c_yellow = '\033[49;1;33m' c_reset = '\033[0m' def green(string):
64
64
14
4
60
MalteSchledjewski/cadet
scripts/reporting.py
Python
green
green
10
11
10
10
6bfeb9f8d6eea67367d7eecedc6d0bef318257cf
bigcode/the-stack
train
c3f12b822da578904f5ac2f6
train
function
def log(msg): print(msg)
def log(msg):
print(msg)
_reset def red(string): return c_red + string + c_reset def blue(string): return c_blue + string + c_reset def yellow(string): return c_yellow + string + c_reset def cyan(string): return c_cyan + string + c_reset def log(msg):
64
64
8
4
59
MalteSchledjewski/cadet
scripts/reporting.py
Python
log
log
25
26
25
25
308c4e3567718984b8bc6389c9775ac36e08161f
bigcode/the-stack
train
4642ddbd53b2559e625a0958
train
function
def test_load(): """Test schema loading.""" schema = load_schema("weblate-memory.schema.json") assert isinstance(schema, dict)
def test_load():
"""Test schema loading.""" schema = load_schema("weblate-memory.schema.json") assert isinstance(schema, dict)
# SOFTWARE. # """Test schemas loader.""" from weblate_schemas import get_path, load_schema def test_filename(): """Test filename calculation.""" filename = get_path("weblate-memory.schema.json") assert "weblate-memory.schema.json" in filename.parts def test_load():
64
64
30
4
59
WeblateOrg/weblate_schemas
weblate_schemas/test_loader.py
Python
test_load
test_load
36
39
36
36
77b60525ccb7e96500dc70693033c19cb6e53bec
bigcode/the-stack
train
9699d1279e63d9dd3491e915
train
function
def test_filename(): """Test filename calculation.""" filename = get_path("weblate-memory.schema.json") assert "weblate-memory.schema.json" in filename.parts
def test_filename():
"""Test filename calculation.""" filename = get_path("weblate-memory.schema.json") assert "weblate-memory.schema.json" in filename.parts
OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # """Test schemas loader.""" from weblate_schemas import get_path, load_schema def test_filename():
64
64
37
4
59
WeblateOrg/weblate_schemas
weblate_schemas/test_loader.py
Python
test_filename
test_filename
30
33
30
30
37b60715cdc860550cc0b15ddff6a369b791f60e
bigcode/the-stack
train
b6cc2c835d3dad4ee50eea7d
train
class
class ArtifactTest(BaseTest): def test_validation(self): repo = Repository(name="myRepo", url="myUrl", push_db_basedir="myPushDb") Artifact(org="testOrg", name="testName", repo=repo, description="Test") with self.assertRaises(ValueError): Artifact(org=1,...
class ArtifactTest(BaseTest):
def test_validation(self): repo = Repository(name="myRepo", url="myUrl", push_db_basedir="myPushDb") Artifact(org="testOrg", name="testName", repo=repo, description="Test") with self.assertRaises(ValueError): Artifact(org=1, name="testName", repo=repo, de...
0 (see LICENSE). from __future__ import (nested_scopes, generators, division, absolute_import, with_statement, print_function, unicode_literals) from pants.backend.jvm.artifact import Artifact from pants.backend.jvm.repository import Repository from pants_test.base_test import BaseTest class ...
64
64
167
6
57
hythloday/pants
tests/python/pants_test/jvm/test_artifact.py
Python
ArtifactTest
ArtifactTest
14
32
14
15
89157248fc0ef590f3d38d0c2994a27735c8d523
bigcode/the-stack
train
e584a650ebc5edb779b3f48e
train
class
class ResourceProviderServicer(object): """ResourceProvider is a service that understands how to create, read, update, or delete resources for types defined within a single package. It is driven by the overall planning engine in response to resource diffs. """ def Configure(self, request, context): """Con...
class ResourceProviderServicer(object):
"""ResourceProvider is a service that understands how to create, read, update, or delete resources for types defined within a single package. It is driven by the overall planning engine in response to resource diffs. """ def Configure(self, request, context): """Configure configures the resource provider ...
, ) self.Read = channel.unary_unary( '/pulumirpc.ResourceProvider/Read', request_serializer=provider__pb2.ReadRequest.SerializeToString, response_deserializer=provider__pb2.ReadResponse.FromString, ) self.Update = channel.unary_unary( '/pulumirpc.ResourceProvider/...
224
224
749
7
217
hausdorff/pulumi
sdk/python/lib/pulumi/runtime/proto/provider_pb2_grpc.py
Python
ResourceProviderServicer
ResourceProviderServicer
67
139
67
67
0b2b82074e40081010fc67faf7aa4e039ff4c8ce
bigcode/the-stack
train
001e1670e6734ec52b5697bc
train
class
class ResourceProviderStub(object): """ResourceProvider is a service that understands how to create, read, update, or delete resources for types defined within a single package. It is driven by the overall planning engine in response to resource diffs. """ def __init__(self, channel): """Constructor. ...
class ResourceProviderStub(object):
"""ResourceProvider is a service that understands how to create, read, update, or delete resources for types defined within a single package. It is driven by the overall planning engine in response to resource diffs. """ def __init__(self, channel): """Constructor. Args: channel: A grpc.Channel...
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! import grpc from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2 from . import plugin_pb2 as plugin__pb2 from . import provider_pb2 as provider__pb2 class ResourceProviderStub(object):
66
166
554
6
59
hausdorff/pulumi
sdk/python/lib/pulumi/runtime/proto/provider_pb2_grpc.py
Python
ResourceProviderStub
ResourceProviderStub
9
64
9
9
eb91584662b7a9d593ea9bf59dbff6a64f2ad9f3
bigcode/the-stack
train
af871cca3c21b61e9a71ae4a
train
function
def add_ResourceProviderServicer_to_server(servicer, server): rpc_method_handlers = { 'Configure': grpc.unary_unary_rpc_method_handler( servicer.Configure, request_deserializer=provider__pb2.ConfigureRequest.FromString, response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.S...
def add_ResourceProviderServicer_to_server(servicer, server):
rpc_method_handlers = { 'Configure': grpc.unary_unary_rpc_method_handler( servicer.Configure, request_deserializer=provider__pb2.ConfigureRequest.FromString, response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, ), 'Invoke': grpc.unary_unary_rp...
Error('Method not implemented!') def Delete(self, request, context): """Delete tears down an existing resource with the given ID. If it fails, the resource is assumed to still exist. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImple...
150
151
506
14
137
hausdorff/pulumi
sdk/python/lib/pulumi/runtime/proto/provider_pb2_grpc.py
Python
add_ResourceProviderServicer_to_server
add_ResourceProviderServicer_to_server
142
192
142
142
fa8ce6b4bae4a63587ddc88d6d5d26bde8311a4e
bigcode/the-stack
train
b047c9c48c337269542f041c
train
function
def dfs(x): vis[x] = 1 for node in adj[x]: if vis[node] == 0: dfs(node) res.insert(0,x)
def dfs(x):
vis[x] = 1 for node in adj[x]: if vis[node] == 0: dfs(node) res.insert(0,x)
#Uses python3 import sys vis = [0] * 100001 result = [] res = [] adj = [] def dfs(x):
31
64
41
4
27
sngvahmed/Algorithm-Coursera
AlgorithmOnGraph/week2/graph_decomposition_starter_files_2/toposort/toposort.py
Python
dfs
dfs
10
17
10
10
d3c54007d40783ce01303334f81f08037627901b
bigcode/the-stack
train
d10f41f1685fd067ab91aa2a
train
function
def toposort(adj): for v in range(adj.__len__()): if(vis[v] == 0): dfs(v)
def toposort(adj):
for v in range(adj.__len__()): if(vis[v] == 0): dfs(v)
0] * 100001 result = [] res = [] adj = [] def dfs(x): vis[x] = 1 for node in adj[x]: if vis[node] == 0: dfs(node) res.insert(0,x) def toposort(adj):
63
64
29
6
57
sngvahmed/Algorithm-Coursera
AlgorithmOnGraph/week2/graph_decomposition_starter_files_2/toposort/toposort.py
Python
toposort
toposort
20
23
20
20
4570bb0c05c2621d566a38a1e7dd65cd238a1062
bigcode/the-stack
train
dbc0c5e8f7ce20fe9856ecc7
train
class
class EditDistance(object): def __init__(self, algorithm): self._algorithm = algorithm if algorithm == DistanceAlgorithm.DAMERUAUOSA: self._distance_comparer = DamerauOsa() else: raise ValueError("Unknown distance algorithm") def compare(self, string_1, string_2,...
class EditDistance(object):
def __init__(self, algorithm): self._algorithm = algorithm if algorithm == DistanceAlgorithm.DAMERUAUOSA: self._distance_comparer = DamerauOsa() else: raise ValueError("Unknown distance algorithm") def compare(self, string_1, string_2, max_distance): """C...
import symspellpy.helpers as helpers class DistanceAlgorithm(Enum): """Supported edit distance algorithms""" # Levenshtein algorithm. LEVENSHTEIN = 0 # Damerau optimal string alignment algorithm DAMERUAUOSA = 1 class EditDistance(object):
64
64
164
5
58
hnikana/symspellpy
symspellpy/editdistance.py
Python
EditDistance
EditDistance
14
34
14
14
28c371c62e2cb54a6061b64894e30963f8e196ae
bigcode/the-stack
train
f06e92607d5b725e89803d32
train
class
class DamerauOsa(AbstractDistanceComparer): def __init__(self): self._base_char = 0 self._base_char_1_costs = np.zeros(0, dtype=np.int32) self._base_prev_char_1_costs = np.zeros(0, dtype=np.int32) def distance(self, string_1, string_2, max_distance): if string_1 is None or strin...
class DamerauOsa(AbstractDistanceComparer):
def __init__(self): self._base_char = 0 self._base_char_1_costs = np.zeros(0, dtype=np.int32) self._base_prev_char_1_costs = np.zeros(0, dtype=np.int32) def distance(self, string_1, string_2, max_distance): if string_1 is None or string_2 is None: return helpers.null...
sa() else: raise ValueError("Unknown distance algorithm") def compare(self, string_1, string_2, max_distance): """Compare a string to the base string to determine the edit distance, using the previously selected algorithm. Keyword arguments: string_1 -- Base str...
256
256
1,488
9
247
hnikana/symspellpy
symspellpy/editdistance.py
Python
DamerauOsa
DamerauOsa
52
177
52
52
280dc690494fe4502f73e3752e3e1c37b579477c
bigcode/the-stack
train
1d213d6cccadf22b5bc8fe7c
train
class
class AbstractDistanceComparer(object): def distance(self, string_1, string_2, max_distance): """Return a measure of the distance between two strings. Keyword arguments: string_1 -- One of the strings to compare. string_2 -- The other string to compare. max_distance -- The m...
class AbstractDistanceComparer(object):
def distance(self, string_1, string_2, max_distance): """Return a measure of the distance between two strings. Keyword arguments: string_1 -- One of the strings to compare. string_2 -- The other string to compare. max_distance -- The maximum distance that is of interest. ...
string. string_2 -- The string to compare. max_distance -- The maximum distance allowed. Return: The edit distance (or -1 if max_distance exceeded). """ return self._distance_comparer.distance(string_1, string_2, max_distance) class AbstractDistanceComparer(object):
64
64
127
6
58
hnikana/symspellpy
symspellpy/editdistance.py
Python
AbstractDistanceComparer
AbstractDistanceComparer
36
50
36
36
f10eb9de9826fa1c1c97070ba3dbbb80b987fff1
bigcode/the-stack
train
3ae91f9af70cdfc2ef3224e7
train
class
class DistanceAlgorithm(Enum): """Supported edit distance algorithms""" # Levenshtein algorithm. LEVENSHTEIN = 0 # Damerau optimal string alignment algorithm DAMERUAUOSA = 1
class DistanceAlgorithm(Enum):
"""Supported edit distance algorithms""" # Levenshtein algorithm. LEVENSHTEIN = 0 # Damerau optimal string alignment algorithm DAMERUAUOSA = 1
from enum import Enum import numpy as np import symspellpy.helpers as helpers class DistanceAlgorithm(Enum):
23
64
50
5
17
hnikana/symspellpy
symspellpy/editdistance.py
Python
DistanceAlgorithm
DistanceAlgorithm
7
12
7
7
74efbc1df0dbcf7683ea8dee18a65f67ffb5f348
bigcode/the-stack
train
d65de46575cdff6dab53de07
train
class
class Tilemap(object): def __init__(self): self.player = Player() self.paper = Paper() self.score = 0 self.status = 0 self.stages = Stages(self.player) self.infobar = Infobar(self.score, 1, "Training", 20) def render(self, event, screen): # render infob...
class Tilemap(object):
def __init__(self): self.player = Player() self.paper = Paper() self.score = 0 self.status = 0 self.stages = Stages(self.player) self.infobar = Infobar(self.score, 1, "Training", 20) def render(self, event, screen): # render infobar self.infobar...
__author__ = 'marcman' from data.components.player import Player from data.components.paper import Paper from pygame.locals import * from data.stages import Stages from data.components.infobar import Infobar class Tilemap(object):
50
109
366
5
44
marcelh89/BowAndArrow-python
data/tilemap.py
Python
Tilemap
Tilemap
10
66
10
10
38949da1f47fd191a170af64bb4a75851497db44
bigcode/the-stack
train
660bc518317b6ec080daa08f
train
class
class TestDay6(unittest.TestCase): def test_orbits_dictionary_can_be_generated_correctly(self): test_array = ['COM)A', 'A)B', 'B)C'] expected_result = { 'COM': {'orbits': [], 'orbitted_by': ['A']}, 'A': {'orbits': ['COM'], 'orbitted_by': ['B']}, 'B...
class TestDay6(unittest.TestCase):
def test_orbits_dictionary_can_be_generated_correctly(self): test_array = ['COM)A', 'A)B', 'B)C'] expected_result = { 'COM': {'orbits': [], 'orbitted_by': ['A']}, 'A': {'orbits': ['COM'], 'orbitted_by': ['B']}, 'B': {'orbits': ['A'], 'orbitted_by':...
import unittest from . import day06 class TestDay6(unittest.TestCase):
17
256
937
8
8
kiriappeee/advent-of-code-2019
python/test-day06.py
Python
TestDay6
TestDay6
4
85
4
4
f1f39919883077d54e415d23c45f4622208cbaaf
bigcode/the-stack
train
ea230b9aa05a9139f510195c
train
class
class Review(db.Model): __tablename__ = 'reviews' # Columns id = db.Column(db.Integer, primary_key=True) userId = db.Column(db.Integer, db.ForeignKey('users.id')) review = db.Column(db.Text()) date=db.Column(db.DateTime()) def __repr__(self): return '<Review: %r>' % self.id...
class Review(db.Model):
__tablename__ = 'reviews' # Columns id = db.Column(db.Integer, primary_key=True) userId = db.Column(db.Integer, db.ForeignKey('users.id')) review = db.Column(db.Text()) date=db.Column(db.DateTime()) def __repr__(self): return '<Review: %r>' % self.id def serialize(self...
going in. Currently letting JS handle formatting 'post': self.post, # native property 'requestType': self.requestType, # native property 'helpType': self.helpType, # native property 'status': self.status, # native property } class Review(db.Model):
64
64
185
5
59
QTIM-Lab/okta-pysaml2-example
models.py
Python
Review
Review
84
104
84
84
f2414de4ae0136cedec52711b4aed3c2b814499f
bigcode/the-stack
train
39aaa6498997f2a01b9acaf2
train
class
class Post(db.Model): __tablename__ = 'posts' # Columns id = db.Column(db.Integer, primary_key=True) userId = db.Column(db.Integer, db.ForeignKey('users.id')) post = db.Column(db.Text()) address = db.Column(db.String(64), index=True) lat = db.Column(db.Float) lng = db.Column(db.Float) ...
class Post(db.Model):
__tablename__ = 'posts' # Columns id = db.Column(db.Integer, primary_key=True) userId = db.Column(db.Integer, db.ForeignKey('users.id')) post = db.Column(db.Text()) address = db.Column(db.String(64), index=True) lat = db.Column(db.Float) lng = db.Column(db.Float) date=db.Column(db.Da...
all, delete-orphan" , lazy='dynamic') def __repr__(self): return '<User: %r>' % self.name def serialize(self): """Return object data in easily serializable format""" return { 'id' : self.id, # native property 'name': self.name, # native property 'partners...
104
104
347
5
99
QTIM-Lab/okta-pysaml2-example
models.py
Python
Post
Post
48
81
48
48
6c52adbac72ec071cb3afac788752442d98feeaf
bigcode/the-stack
train
d249e349afdb21b10f5ba903
train
class
class User(db.Model, UserMixin): #UserMixin, when ready __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.String(64), index=True) partnersID = db.Column(db.String(64), unique=True, index=True) email = db.Column(db.String(64), index=True) ...
class User(db.Model, UserMixin): #UserMixin, when ready
__tablename__ = 'users' id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.String(64), index=True) partnersID = db.Column(db.String(64), unique=True, index=True) email = db.Column(db.String(64), index=True) # Relatoinships post = db.relationship('Post',...
app import db, UserMixin # ### Note: ### # Example of running recreate_db() and using line [2] below: # $ . venv/bin/activate # $ python # >>> import app # >>> app.recreate_db(app) class User(db.Model, UserMixin): #UserMixin, when ready
69
69
231
15
54
QTIM-Lab/okta-pysaml2-example
models.py
Python
User
User
24
45
24
24
6fa5261c1b57484903004178585f28f0c598c197
bigcode/the-stack
train
883a573cb0dbf665eb35268c
train
class
class SIL(SVM): """ Single-Instance Learning applied to MI data """ def __init__(self, **kwargs): """ @param kernel : the desired kernel function; can be linear, quadratic, polynomial, or rbf [default: linear] @param C : the loss/regularization tradeoff c...
class SIL(SVM):
""" Single-Instance Learning applied to MI data """ def __init__(self, **kwargs): """ @param kernel : the desired kernel function; can be linear, quadratic, polynomial, or rbf [default: linear] @param C : the loss/regularization tradeoff constant [default...
""" Implements Single Instance Learning SVM """ from __future__ import print_function, division import numpy as np import inspect from misvm.svm import SVM from misvm.util import slices class SIL(SVM):
49
195
652
5
43
lvkd84/misvm
misvm/sil.py
Python
SIL
SIL
11
77
11
11
cbf7b654ff27a732bdd73f2bbdc16df3ed5f1561
bigcode/the-stack
train
f18ceeb90c527bbe45006950
train
function
def _inst_to_bag_preds(inst_preds, bags): return np.array([np.max(inst_preds[slice(*bidx)]) for bidx in slices(map(len, bags))])
def _inst_to_bag_preds(inst_preds, bags):
return np.array([np.max(inst_preds[slice(*bidx)]) for bidx in slices(map(len, bags))])
=True): """ return params """ args, _, _, _ = inspect.getargspec(super(SIL, self).__init__) args.pop(0) return {key: getattr(self, key, None) for key in args} def _inst_to_bag_preds(inst_preds, bags):
64
64
39
12
52
lvkd84/misvm
misvm/sil.py
Python
_inst_to_bag_preds
_inst_to_bag_preds
80
82
80
80
787cbe254a07389c2b083c724b79b44604cfb208
bigcode/the-stack
train
b1bf84ed39af4afc47f6ec3d
train
function
def dump(stream, path=None, f=None): logging.debug(f"dump {path} {f}") if not f: f = open(path, "w", newline="") writer = csv.writer(f) for block in stream: writer.writerow(block["line"])
def dump(stream, path=None, f=None):
logging.debug(f"dump {path} {f}") if not f: f = open(path, "w", newline="") writer = csv.writer(f) for block in stream: writer.writerow(block["line"])
import csv import logging import itertools from .phase import Phase def dump(stream, path=None, f=None):
25
64
58
10
14
digital-land/pipeline
digital_land/phase/dump.py
Python
dump
dump
7
15
7
7
ef9ce1df8016118ed2d0ca82830d11c75d3367d3
bigcode/the-stack
train
d2cf2c228832b8ff168dc56c
train
class
class DumpPhase(Phase): """ dump stream lines to a file """ def __init__( self, path=None, f=None, enabled=True, ): self.path = path self.f = f self.enabled = enabled def process(self, stream): if self.enabled: stream,...
class DumpPhase(Phase):
""" dump stream lines to a file """ def __init__( self, path=None, f=None, enabled=True, ): self.path = path self.f = f self.enabled = enabled def process(self, stream): if self.enabled: stream, dump_stream = itertools...
dump(stream, path=None, f=None): logging.debug(f"dump {path} {f}") if not f: f = open(path, "w", newline="") writer = csv.writer(f) for block in stream: writer.writerow(block["line"]) class DumpPhase(Phase):
63
64
105
6
57
digital-land/pipeline
digital_land/phase/dump.py
Python
DumpPhase
DumpPhase
18
42
18
18
d9faddf604882eb1e3a2a02a93f64ba8c1ab12b1
bigcode/the-stack
train
2435e04fda95c3511a504467
train
class
class Time(Enum): Relative = "relative" Absolute = "absolute"
class Time(Enum):
Relative = "relative" Absolute = "absolute"
course of action, such as a command line to execute. This can be used with custom notification messages. It can be referenced using the {{tip}} template var. """ util.assert_valid(tip) self.options.update({'tip': tip}) return self class Time(Enum):
64
64
16
4
59
agilefall/signal_analog
signal_analog/detectors.py
Python
Time
Time
319
321
319
319
024507ef39883fa3375ed8047424a8f0cdcb8d41
bigcode/the-stack
train
5e46f773ad1aa65425f0ffa8
train
class
class ServiceNowNotification(Notification): """A ServiceNow notifiction for detector rules.""" def __init__(self, sn_id): """Initializes a new ServiceNow notification. This does not setup a ServiceNow integration for you, one must already exist before using this notification type. No v...
class ServiceNowNotification(Notification):
"""A ServiceNow notifiction for detector rules.""" def __init__(self, sn_id): """Initializes a new ServiceNow notification. This does not setup a ServiceNow integration for you, one must already exist before using this notification type. No validation is done to ensure that a S...
: the HipChat room name to post integrations to """ util.assert_valid(hp_id) util.assert_valid(room_name) self.options = { 'type': 'HipChat', 'credentialId': hp_id, 'room': room_name } class ServiceNowNotification(Notification):
64
64
125
6
58
agilefall/signal_analog
signal_analog/detectors.py
Python
ServiceNowNotification
ServiceNowNotification
114
132
114
114
8c3d50b4ef53b89eaa10e4f75a73573f991cbb25
bigcode/the-stack
train
9d40f2960fe39e77b150e980
train
class
class SlackNotification(Notification): """A slack notification for detector rules.""" def __init__(self, slack_id, channel_name): """Initializes a new Slack notification rule. This does not setup a Slack integration for you, one must already exist before using this notification type. N...
class SlackNotification(Notification):
"""A slack notification for detector rules.""" def __init__(self, slack_id, channel_name): """Initializes a new Slack notification rule. This does not setup a Slack integration for you, one must already exist before using this notification type. No validation is done to ensure ...
.signalfx.com/v2/reference#pagerduty-integration-model Arguments: pd_id: the id of the PagerDuty integration to include. """ util.assert_valid(pd_id) self.options = {'type': 'PagerDuty', 'credentialId': pd_id} class SlackNotification(Notification):
64
64
177
5
59
agilefall/signal_analog
signal_analog/detectors.py
Python
SlackNotification
SlackNotification
59
83
59
59
8e58561d60b0671c572cbe2493421816d97d4366
bigcode/the-stack
train
c7becbdc899f3aae148e10cc
train
class
class VisualizationOptions(object): """Visualization options for detectors.""" def __init__(self): self.options = {} def with_time_config(self, config): if not isinstance(config, TimeConfig): msg = 'Attempting to set "{0}" to a time config for this ' +\ 'visua...
class VisualizationOptions(object):
"""Visualization options for detectors.""" def __init__(self): self.options = {} def with_time_config(self, config): if not isinstance(config, TimeConfig): msg = 'Attempting to set "{0}" to a time config for this ' +\ 'visualization when we expected a "{1}"' ...
valid for Time.absolute configs. """ if self.options.get('type', None) == Time.Relative.value: msg = 'An end time can only be set on absolute time configs.' raise ValueError(msg) return self.__add_millis__(millis, 'end') class VisualizationOptions(object):
64
64
157
5
59
agilefall/signal_analog
signal_analog/detectors.py
Python
VisualizationOptions
VisualizationOptions
376
396
376
376
b83798de7e01c4e60488d2760d992f2e70953393
bigcode/the-stack
train
38d87d799d9800f3dab19724
train
class
class Rule(object): """Determines who/what is notified when a detector fires.""" def __init__(self): """Initializes a new rule.""" self.options = {} def for_label(self, label): """A label matching a `detect` label within the program text.""" util.assert_valid(label) ...
class Rule(object):
"""Determines who/what is notified when a detector fires.""" def __init__(self): """Initializes a new rule.""" self.options = {} def for_label(self, label): """A label matching a `detect` label within the program text.""" util.assert_valid(label) self.options.update...
""" util.assert_valid(team_id) self.options = { 'type': 'Team', 'team': team_id } class TeamEmailNotification(Notification): """A team e-mail notification for detector rules.""" def __init__(self, team_id): """Initializes a new team e-mail noti...
178
178
595
4
174
agilefall/signal_analog
signal_analog/detectors.py
Python
Rule
Rule
231
316
231
231
25b3539ecd0cc56e6defea20c8158e84e8691f39
bigcode/the-stack
train
ceb12d9154ae6472338fdde0
train
class
class TimeConfig(object): """Controls the time span visualized for a detector.""" def __init__(self): self.options = {} def with_type(self, time_type): """The type of time span defined.""" util.in_given_enum(time_type, Time) self.options.update({'type': time_type.value}) ...
class TimeConfig(object):
"""Controls the time span visualized for a detector.""" def __init__(self): self.options = {} def with_type(self, time_type): """The type of time span defined.""" util.in_given_enum(time_type, Time) self.options.update({'type': time_type.value}) return self def...
self.options.update({'runbookUrl': url}) return self def with_tip(self, tip): """Plain text suggested first course of action, such as a command line to execute. This can be used with custom notification messages. It can be referenced using the {{tip}} template var. ...
110
110
368
5
105
agilefall/signal_analog
signal_analog/detectors.py
Python
TimeConfig
TimeConfig
324
373
324
324
e1d328b479f6c81a012310f65544a40a8846417e
bigcode/the-stack
train
dc9c2271cd1be4ac97acb693
train
class
class Detector(Resource): """Resource encapsulating Detectors in the SignalFx API. A detector is a collection of rules that define who should be notified when certain detect functions within SignalFlow fire alerts. Each rule maps a detect label to a severity and a list of notifications. When the condit...
class Detector(Resource):
"""Resource encapsulating Detectors in the SignalFx API. A detector is a collection of rules that define who should be notified when certain detect functions within SignalFlow fire alerts. Each rule maps a detect label to a severity and a list of notifications. When the conditions within the given ...
return self.__add_millis__(millis, 'start') def with_end(self, millis): """Milliseconds since epoch to stop a visualization. NOTE: only valid for Time.absolute configs. """ if self.options.get('type', None) == Time.Relative.value: msg = 'An end time can only be ...
256
256
1,082
4
251
agilefall/signal_analog
signal_analog/detectors.py
Python
Detector
Detector
399
548
399
399
b1bc305c622b3d5d4ca2cd5064ec7ac39c6a412f
bigcode/the-stack
train
0d9a6d3e2db24ab3967ed4d4
train
class
class Notification(object): """A notification model to be attached to a detector.""" pass
class Notification(object):
"""A notification model to be attached to a detector.""" pass
.charts import Chart from signal_analog.flow import Program from six import string_types import signal_analog.util as util from email_validator import validate_email from signal_analog.errors import ResourceMatchNotFoundError, \ ResourceHasMultipleExactMatchesError, ResourceAlreadyExistsError class Notification...
64
64
19
4
59
agilefall/signal_analog
signal_analog/detectors.py
Python
Notification
Notification
16
18
16
16
d08aa7672973f9f58f71430e48edf38af1360c73
bigcode/the-stack
train
2de170bc08df6a68ab73df06
train
class
class TeamEmailNotification(Notification): """A team e-mail notification for detector rules.""" def __init__(self, team_id): """Initializes a new team e-mail notification. No validation is done to verify that a team id exists in SignalFx. Arguments: team_id: the id of the ...
class TeamEmailNotification(Notification):
"""A team e-mail notification for detector rules.""" def __init__(self, team_id): """Initializes a new team e-mail notification. No validation is done to verify that a team id exists in SignalFx. Arguments: team_id: the id of the team to e-mail. """ util.as...
is done to verify that a team id exists in SignalFx. Arguments: team_id: the id of the team to message. """ util.assert_valid(team_id) self.options = { 'type': 'Team', 'team': team_id } class TeamEmailNotification(Notification):
64
64
101
6
58
agilefall/signal_analog
signal_analog/detectors.py
Python
TeamEmailNotification
TeamEmailNotification
202
218
202
202
012a34cfe8a301ad0fb4bada22ece8af6f860921
bigcode/the-stack
train
9325e827074b59fbd5dfad10
train
class
class TeamNotification(Notification): """A team notification for detector rules.""" def __init__(self, team_id): """Initializes a team notification. No validation is done to verify that a team id exists in SignalFx. Arguments: team_id: the id of the team to message. ...
class TeamNotification(Notification):
"""A team notification for detector rules.""" def __init__(self, team_id): """Initializes a team notification. No validation is done to verify that a team id exists in SignalFx. Arguments: team_id: the id of the team to message. """ util.assert_valid(team_i...
HMAC-SHA1 digest of the request body using the shared secret. """ util.assert_valid(url) self.options = { 'type': 'Webhook', 'url': url } if secret: self.options.update({'secret': secret}) class TeamNot...
64
64
93
5
59
agilefall/signal_analog
signal_analog/detectors.py
Python
TeamNotification
TeamNotification
183
199
183
183
034d07bca6186dd22b2ad1de930786fc1d6b5828
bigcode/the-stack
train
d5314cbb1865733ed3463645
train
class
class EmailNotification(Notification): """An email notification for detector rules.""" def __init__(self, email): """Initialize a new Email notification. Arguments: email: the email to notify. This value is validated a little stricter than other notification valu...
class EmailNotification(Notification):
"""An email notification for detector rules.""" def __init__(self, email): """Initialize a new Email notification. Arguments: email: the email to notify. This value is validated a little stricter than other notification values to prevent unwanted ...
signal_analog.util as util from email_validator import validate_email from signal_analog.errors import ResourceMatchNotFoundError, \ ResourceHasMultipleExactMatchesError, ResourceAlreadyExistsError class Notification(object): """A notification model to be attached to a detector.""" pass class EmailNo...
64
64
102
5
58
agilefall/signal_analog
signal_analog/detectors.py
Python
EmailNotification
EmailNotification
21
33
21
21
1bfb4bff998b5f289e8a0efffba1b9b1ea061ef8
bigcode/the-stack
train
52f6a977520e46f086f9173b
train
class
class HipChatNotification(Notification): """A HipChat notification for detector rules.""" def __init__(self, hp_id, room_name): """Initializes a new HipChat notification. This does not setup a Slack integration for you, one must already exist before using this notification type. No val...
class HipChatNotification(Notification):
"""A HipChat notification for detector rules.""" def __init__(self, hp_id, room_name): """Initializes a new HipChat notification. This does not setup a Slack integration for you, one must already exist before using this notification type. No validation is done to ensure that a ...
_name: the name of the channel to send alerts to """ util.assert_valid(slack_id) util.assert_valid(channel_name) self.options = { 'type': 'Slack', 'credentialId': slack_id, 'channel': channel_name } class HipChatNotification(Notification):
64
64
182
6
58
agilefall/signal_analog
signal_analog/detectors.py
Python
HipChatNotification
HipChatNotification
86
111
86
86
dee57ab81de234b25ea9de7d2f0ae54e40085e03
bigcode/the-stack
train
bcaae5e8fa7c87529b58dab5
train
class
class VictorOpsNotification(Notification): """A VictorOps notification for detector rules.""" def __init__(self, vo_id, routing_key): """Initializes a new VictorOps notification. This does not setup a VictorOps integration for you, one must already exist before using this notification ...
class VictorOpsNotification(Notification):
"""A VictorOps notification for detector rules.""" def __init__(self, vo_id, routing_key): """Initializes a new VictorOps notification. This does not setup a VictorOps integration for you, one must already exist before using this notification type. No validation is done to ensu...
ensure that a ServiceNow integration id is valid. Arguments: sn_id: the ServiceNow integration id to use """ util.assert_valid(sn_id) self.options = { 'type': 'ServiceNow', 'credentialId': sn_id } class VictorOpsNotification(Notificat...
64
64
153
6
58
agilefall/signal_analog
signal_analog/detectors.py
Python
VictorOpsNotification
VictorOpsNotification
135
156
135
135
6902dfc17ab9e6f61b7b129e431ef495e3edacf8
bigcode/the-stack
train
ab0f9f9c619a35a8d75eacef
train
class
class WebhookNotification(Notification): """A Webhook notification for detector rules.""" def __init__(self, url, secret=None): """Initializes a new webhook notification. Arguments: url: the URL to call back secret: optional, when provided the request will contain a ...
class WebhookNotification(Notification):
"""A Webhook notification for detector rules.""" def __init__(self, url, secret=None): """Initializes a new webhook notification. Arguments: url: the URL to call back secret: optional, when provided the request will contain a `X-SFX-Signature` header...
routing_key: a VictorOps routing key """ util.assert_valid(vo_id) util.assert_valid(routing_key) self.options = { 'type': 'VictorOps', 'credentialId': vo_id, 'routingKey': routing_key } class WebhookNotification(Notification):
64
64
137
6
58
agilefall/signal_analog
signal_analog/detectors.py
Python
WebhookNotification
WebhookNotification
159
180
159
159
455ba7daddaa4238989b02a2b183d4a43d7bd9b1
bigcode/the-stack
train
cfdb229246457afcf49380f7
train
class
class PagerDutyNotification(Notification): """A PagerDuty notification for detector rules.""" def __init__(self, pd_id): """Initializes a new PagerDuty notification. This does not setup a PagerDuty integration for you, one must already exist before using this notification type. No vali...
class PagerDutyNotification(Notification):
"""A PagerDuty notification for detector rules.""" def __init__(self, pd_id): """Initializes a new PagerDuty notification. This does not setup a PagerDuty integration for you, one must already exist before using this notification type. No validation is done to ensure that a PD ...
validated a little stricter than other notification values to prevent unwanted behavior when a detector actually fires. """ valid_email = validate_email(email, check_deliverability=False) self.options = {'type': 'Email', 'email': valid_email['email']} class...
63
64
170
6
57
agilefall/signal_analog
signal_analog/detectors.py
Python
PagerDutyNotification
PagerDutyNotification
36
56
36
36
6a17740f3adbc1d83ce1477ccacd601184af3d6b
bigcode/the-stack
train
55677f9b238b56b29e6edf72
train
class
class Severity(Enum): """Available severity levels for detector rules.""" Critical = "Critical" Warning = "Warning" Major = "Major" Minor = "Minor" Info = "Info"
class Severity(Enum):
"""Available severity levels for detector rules.""" Critical = "Critical" Warning = "Warning" Major = "Major" Minor = "Minor" Info = "Info"
is done to verify that a team id exists in SignalFx. Arguments: team_id: the id of the team to e-mail. """ util.assert_valid(team_id) self.options = { 'type': 'TeamEmail', 'team': team_id } class Severity(Enum):
64
64
43
4
60
agilefall/signal_analog
signal_analog/detectors.py
Python
Severity
Severity
221
228
221
221
3b9a275104892d488ea2dedf7fb899f9a12744f2
bigcode/the-stack
train
ce1283032239e1380d87882b
train
function
def createPDF(image_filename, text, output_filename): A4_WIDTH = 210.0 #mm A4_HEIGHT = 297.0 A4_HALF_HEIGHT = A4_HEIGHT / 2.0 IMAGE_SIZE = A4_HALF_HEIGHT * 0.8 FONT_SIZE = 16 pdf = FPDF(format = 'A4') pdf.add_page() # add image on top half pdf.set_xy( (A4_WIDTH - IMAGE_SIZE) / 2.0,...
def createPDF(image_filename, text, output_filename):
A4_WIDTH = 210.0 #mm A4_HEIGHT = 297.0 A4_HALF_HEIGHT = A4_HEIGHT / 2.0 IMAGE_SIZE = A4_HALF_HEIGHT * 0.8 FONT_SIZE = 16 pdf = FPDF(format = 'A4') pdf.add_page() # add image on top half pdf.set_xy( (A4_WIDTH - IMAGE_SIZE) / 2.0, (A4_HALF_HEIGHT - IMAGE_SIZE) / 2.0) ...
from fpdf import FPDF def createPDF(image_filename, text, output_filename):
18
68
228
11
6
kgaitanis/BeYourOwnBank
internal/createPDF.py
Python
createPDF
createPDF
3
24
3
3
8a328de6242ac2a506ef7978b39638acce43b18a
bigcode/the-stack
train
16c95da60cb57266903ce496
train
function
def format_hex_text(text): output = '' chars_per_block = 4 blocks_per_line = 10 i = 0 while i*chars_per_block < len(text): output += text[i*chars_per_block:(i+1)*chars_per_block] + ' ' i += 1 if i % blocks_per_line == 0: output += '\n' return output
def format_hex_text(text):
output = '' chars_per_block = 4 blocks_per_line = 10 i = 0 while i*chars_per_block < len(text): output += text[i*chars_per_block:(i+1)*chars_per_block] + ' ' i += 1 if i % blocks_per_line == 0: output += '\n' return output
, A4_HALF_HEIGHT) pdf.set_font('Courier', '', FONT_SIZE) pdf.multi_cell(w=A4_WIDTH*0.9, h=10, align='C', txt=format_hex_text(text)) # save to file pdf.output(output_filename,'F') def format_hex_text(text):
64
64
91
6
58
kgaitanis/BeYourOwnBank
internal/createPDF.py
Python
format_hex_text
format_hex_text
26
37
26
26
39cfd962642f3c0efd564efa9f1589002d58600b
bigcode/the-stack
train
af10cdd6e7e17740d15de316
train
function
def chromatic_adaptation_Fairchild1990(XYZ_1, XYZ_n, XYZ_r, Y_n, discount_illuminant=False): """ Adapts given stimulus *CIE XYZ_1* tristimulus values from t...
def chromatic_adaptation_Fairchild1990(XYZ_1, XYZ_n, XYZ_r, Y_n, discount_illuminant=False):
""" Adapts given stimulus *CIE XYZ_1* tristimulus values from test viewing conditions to reference viewing conditions using *Fairchild (1990)* chromatic adaptation model. Parameters ---------- XYZ_1 : array_like *CIE XYZ_1* tristimulus values of test sample / stimulus. XYZ_n : a...
status__ = 'Production' __all__ = [ 'MATRIX_XYZ_TO_RGB_FAIRCHILD1990', 'MATRIX_RGB_TO_XYZ_FAIRCHILD1990', 'chromatic_adaptation_Fairchild1990', 'XYZ_to_RGB_Fairchild1990', 'RGB_to_XYZ_Fairchild1990', 'degrees_of_adaptation' ] MATRIX_XYZ_TO_RGB_FAIRCHILD1990 = CAT_VON_KRIES """ *Fairchild (1990)* colour ap...
256
256
962
35
221
wenh06/colour
colour/adaptation/fairchild1990.py
Python
chromatic_adaptation_Fairchild1990
chromatic_adaptation_Fairchild1990
58
150
58
62
cf215a339a82420d440b77c1044148874fd09f1f
bigcode/the-stack
train
c57ad52158ecdcd20ed822ac
train
function
def XYZ_to_RGB_Fairchild1990(XYZ): """ Converts from *CIE XYZ* tristimulus values to cone responses. Parameters ---------- XYZ : array_like *CIE XYZ* tristimulus values. Returns ------- ndarray Cone responses. Examples -------- >>> XYZ = np.array([19.53, 23...
def XYZ_to_RGB_Fairchild1990(XYZ):
""" Converts from *CIE XYZ* tristimulus values to cone responses. Parameters ---------- XYZ : array_like *CIE XYZ* tristimulus values. Returns ------- ndarray Cone responses. Examples -------- >>> XYZ = np.array([19.53, 23.07, 24.97]) >>> XYZ_to_RGB_Fai...
_a) LMS_c = vector_dot(np.linalg.inv(A_2), LMSp_2) XYZ_c = vector_dot(MATRIX_RGB_TO_XYZ_FAIRCHILD1990, LMS_c) return from_range_100(XYZ_c) def XYZ_to_RGB_Fairchild1990(XYZ):
64
64
162
12
52
wenh06/colour
colour/adaptation/fairchild1990.py
Python
XYZ_to_RGB_Fairchild1990
XYZ_to_RGB_Fairchild1990
153
174
153
153
2b33374c3cf5ddbce972f68566f69cc63723b33d
bigcode/the-stack
train
a46ca24fae6ab0b1521b5b96
train
function
def RGB_to_XYZ_Fairchild1990(RGB): """ Converts from cone responses to *CIE XYZ* tristimulus values. Parameters ---------- RGB : array_like Cone responses. Returns ------- ndarray *CIE XYZ* tristimulus values. Examples -------- >>> RGB = np.array([22.123193...
def RGB_to_XYZ_Fairchild1990(RGB):
""" Converts from cone responses to *CIE XYZ* tristimulus values. Parameters ---------- RGB : array_like Cone responses. Returns ------- ndarray *CIE XYZ* tristimulus values. Examples -------- >>> RGB = np.array([22.12319350, 23.60542240, 22.92795340]) ...
IPSIS array([ 22.1231935..., 23.6054224..., 22.9279534...]) """ return vector_dot(MATRIX_XYZ_TO_RGB_FAIRCHILD1990, XYZ) def RGB_to_XYZ_Fairchild1990(RGB):
64
64
163
13
51
wenh06/colour
colour/adaptation/fairchild1990.py
Python
RGB_to_XYZ_Fairchild1990
RGB_to_XYZ_Fairchild1990
177
198
177
177
37b8b72254aa9c93ea1bc55f71fee93d8604418f
bigcode/the-stack
train
d00ec298bccdec973dc53564
train
function
def degrees_of_adaptation(LMS, Y_n, v=1 / 3, discount_illuminant=False): """ Computes the degrees of adaptation :math:`p_L`, :math:`p_M` and :math:`p_S`. Parameters ---------- LMS : array_like Cone responses. Y_n : numeric or array_like Luminance :math:`Y_n` of test adapting...
def degrees_of_adaptation(LMS, Y_n, v=1 / 3, discount_illuminant=False):
""" Computes the degrees of adaptation :math:`p_L`, :math:`p_M` and :math:`p_S`. Parameters ---------- LMS : array_like Cone responses. Y_n : numeric or array_like Luminance :math:`Y_n` of test adapting stimulus in :math:`cd/m^2`. v : numeric or array_like, optional ...
Converts from cone responses to *CIE XYZ* tristimulus values. Parameters ---------- RGB : array_like Cone responses. Returns ------- ndarray *CIE XYZ* tristimulus values. Examples -------- >>> RGB = np.array([22.12319350, 23.60542240, 22.92795340]) >>> RGB_to_...
172
172
575
25
147
wenh06/colour
colour/adaptation/fairchild1990.py
Python
degrees_of_adaptation
degrees_of_adaptation
201
267
201
201
9b1b1d316dcd10b8119a73f1b712564bfa65737f
bigcode/the-stack
train
c641dcbc6638016af67a2c7a
train
function
def compute_diff(path, found_line, replace_or_add, state, key): diff = { 'before_header': path, 'after_header': path, 'before': '', 'after': '', } try: inf = open(path, "r") except IOError: e = get_exception() if e.errno == errno.ENOENT: ...
def compute_diff(path, found_line, replace_or_add, state, key):
diff = { 'before_header': path, 'after_header': path, 'before': '', 'after': '', } try: inf = open(path, "r") except IOError: e = get_exception() if e.errno == errno.ENOENT: diff['before_header'] = '/dev/null' else: diff['be...
']=k[2] d['key']=k[3] else: d['host']=k[0] d['type']=k[1] d['key']=k[2] return d def compute_diff(path, found_line, replace_or_add, state, key):
64
64
194
16
47
EnjoyLifeFund/py36pkgs
ansible/modules/system/known_hosts.py
Python
compute_diff
compute_diff
301
323
301
301
8a4b1245c932f045d8f25e093af0a5f859838e9b
bigcode/the-stack
train
088f10dbb8833f73b43f263b
train
function
def sanity_check(module,host,key,sshkeygen): '''Check supplied key is sensible host and key are parameters provided by the user; If the host provided is inconsistent with the key supplied, then this function quits, providing an error to the user. sshkeygen is the path to ssh-keygen, found earlier w...
def sanity_check(module,host,key,sshkeygen):
'''Check supplied key is sensible host and key are parameters provided by the user; If the host provided is inconsistent with the key supplied, then this function quits, providing an error to the user. sshkeygen is the path to ssh-keygen, found earlier with get_bin_path ''' #If no key suppl...
present': outf.write(key) outf.flush() module.atomic_move(outf.name,path) except (IOError,OSError): e = get_exception() module.fail_json(msg="Failed to write to file %s: %s" % \ (path,str(e))) try: ...
96
96
323
12
83
EnjoyLifeFund/py36pkgs
ansible/modules/system/known_hosts.py
Python
sanity_check
sanity_check
177
211
177
177
a53f7683ecee40c404762eee2a8368a45708f436
bigcode/the-stack
train
b44646e98e604d9eb9000d1a
train
function
def enforce_state(module, params): """ Add or remove key. """ host = params["name"] key = params.get("key",None) port = params.get("port",None) path = params.get("path") hash_host = params.get("hash_host") state = params.get("state") #Find the ssh-keygen binary sshkeygen = m...
def enforce_state(module, params):
""" Add or remove key. """ host = params["name"] key = params.get("key",None) port = params.get("port",None) path = params.get("path") hash_host = params.get("hash_host") state = params.get("state") #Find the ssh-keygen binary sshkeygen = module.get_bin_path("ssh-keygen",Tru...
/etc/ssh/ssh_known_hosts name: foo.com.invalid key: "{{ lookup('file', 'pubkeys/foo.com.invalid') }}" ''' # Makes sure public host keys are present or absent in the given known_hosts # file. # # Arguments # ========= # name = hostname whose key should be added (alias: host) # key = line(s) to add to kno...
187
187
625
7
179
EnjoyLifeFund/py36pkgs
ansible/modules/system/known_hosts.py
Python
enforce_state
enforce_state
98
175
98
98
c070d744addc3d2cdf0857580f870e1dd5be8bcc
bigcode/the-stack
train
a25ad55578ade38c09c9af9f
train
function
def search_for_host_key(module, host, key, hash_host, path, sshkeygen): '''search_for_host_key(module,host,key,path,sshkeygen) -> (found,replace_or_add,found_line) Looks up host and keytype in the known_hosts file path; if it's there, looks to see if one of those entries matches key. Returns: found (Bo...
def search_for_host_key(module, host, key, hash_host, path, sshkeygen):
'''search_for_host_key(module,host,key,path,sshkeygen) -> (found,replace_or_add,found_line) Looks up host and keytype in the known_hosts file path; if it's there, looks to see if one of those entries matches key. Returns: found (Boolean): is host found in path? replace_or_add (Boolean): is the key ...
if key is None: return #Rather than parsing the key ourselves, get ssh-keygen to do it #(this is essential for hashed keys, but otherwise useful, as the #key question is whether ssh-keygen thinks the key matches the host). #The approach is to write the key to a temporary file, #and then at...
244
244
814
20
224
EnjoyLifeFund/py36pkgs
ansible/modules/system/known_hosts.py
Python
search_for_host_key
search_for_host_key
213
275
213
213
3f085454eab0066c649f5ebe9485d80c7dd9b92d
bigcode/the-stack
train
eea0ba0707f1322c2482c131
train
function
def main(): module = AnsibleModule( argument_spec = dict( name = dict(required=True, type='str', aliases=['host']), key = dict(required=False, type='str'), path = dict(default="~/.ssh/known_hosts", type='path'), hash_host = dict(required=Fal...
def main():
module = AnsibleModule( argument_spec = dict( name = dict(required=True, type='str', aliases=['host']), key = dict(required=False, type='str'), path = dict(default="~/.ssh/known_hosts", type='path'), hash_host = dict(required=False, type='boo...
_line is not None and 1 <= found_line <= len(lines): del lines[found_line - 1] if state == 'present' and (replace_or_add or found_line is None): lines.append(key) diff['after'] = ''.join(lines) return diff def main():
64
64
123
3
60
EnjoyLifeFund/py36pkgs
ansible/modules/system/known_hosts.py
Python
main
main
325
339
325
326
ad9235bfef8b2657999c88d9621d7c14f674568b
bigcode/the-stack
train
a1f01d4ac94368b03ee4b064
train
function
def normalize_known_hosts_key(key): ''' Transform a key, either taken from a known_host file or provided by the user, into a normalized form. The host part (which might include multiple hostnames or be hashed) gets replaced by the provided host. Also, any spurious information gets removed from t...
def normalize_known_hosts_key(key):
''' Transform a key, either taken from a known_host file or provided by the user, into a normalized form. The host part (which might include multiple hostnames or be hashed) gets replaced by the provided host. Also, any spurious information gets removed from the end (like the username@host tag u...
_key['type'] == found_key['type']: # found a different key for the same key type return True, True, found_line, key # No match found, return found and replace, but no line return True, True, None, key def normalize_known_hosts_key(key):
65
65
219
7
57
EnjoyLifeFund/py36pkgs
ansible/modules/system/known_hosts.py
Python
normalize_known_hosts_key
normalize_known_hosts_key
277
299
277
277
a2bdda55486b704a1a191d1d846897fa9eb564d8
bigcode/the-stack
train
7d1cba0514e9a7d1d7283dc5
train
class
class SFTPSensor(BaseSensorOperator): """ Waits for a file or directory to be present on SFTP. :param path: Remote file or directory path :type path: str :param sftp_conn_id: The connection to run the sensor against :type sftp_conn_id: str """ template_fields = ('path',) @apply_def...
class SFTPSensor(BaseSensorOperator):
""" Waits for a file or directory to be present on SFTP. :param path: Remote file or directory path :type path: str :param sftp_conn_id: The connection to run the sensor against :type sftp_conn_id: str """ template_fields = ('path',) @apply_defaults def __init__(self, *, path, ...
under the License. """ This module contains SFTP sensor. """ from paramiko import SFTP_NO_SUCH_FILE from airflow.providers.sftp.hooks.sftp import SFTPHook from airflow.sensors.base_sensor_operator import BaseSensorOperator from airflow.utils.decorators import apply_defaults class SFTPSensor(BaseSensorOperator):
68
68
228
9
58
troywinter/airflow
airflow/providers/sftp/sensors/sftp.py
Python
SFTPSensor
SFTPSensor
28
56
28
28
39f5f814aea7bce958180ee7923cc62b59962095
bigcode/the-stack
train
4d379c21c15a7b58c4f47fbb
train
function
def cleanup_one(line): line = re.sub(r"\b(?<![\\])u[0-9]+\b", "u[...]", line) try: js = json.loads(line) if js.get("kind") == "protocol-info": js = {"kind": "[...]"} # Drop entire message cleanup_json(js) return json.dumps(js, ensure_ascii=False, sort_keys=True) + "\n...
def cleanup_one(line):
line = re.sub(r"\b(?<![\\])u[0-9]+\b", "u[...]", line) try: js = json.loads(line) if js.get("kind") == "protocol-info": js = {"kind": "[...]"} # Drop entire message cleanup_json(js) return json.dumps(js, ensure_ascii=False, sort_keys=True) + "\n" except Exception ...
): if "fname" in js: js["fname"] = os.path.basename(js["fname"].replace('\\', '/')) for v in js.itervalues(): cleanup_json(v) elif isinstance(js, list): for v in js: cleanup_json(v) def cleanup_one(line):
64
64
102
5
59
kkohbrok/FStar
src/tests/interactive/cleanup.py
Python
cleanup_one
cleanup_one
26
35
26
26
510d6c209a429a373477ec034b14e106eb7088af
bigcode/the-stack
train
ef9b6aaaccb28d78bd1514fc
train
function
def cleanup_json(js): if isinstance(js, dict): if "fname" in js: js["fname"] = os.path.basename(js["fname"].replace('\\', '/')) for v in js.itervalues(): cleanup_json(v) elif isinstance(js, list): for v in js: cleanup_json(v)
def cleanup_json(js):
if isinstance(js, dict): if "fname" in js: js["fname"] = os.path.basename(js["fname"].replace('\\', '/')) for v in js.itervalues(): cleanup_json(v) elif isinstance(js, list): for v in js: cleanup_json(v)
"""Cleanup interactive transcript received on standard input. This mostly consists in pretty-pretting JSON messages and sorting their fields, to permit text-based comparisons against reference transcripts. Usage: python cleanup.py fname.clean < fname.dirty """ import json import sys import re import os def cleanup...
64
64
70
5
58
kkohbrok/FStar
src/tests/interactive/cleanup.py
Python
cleanup_json
cleanup_json
16
24
16
16
1b5938b457b396eb6da80079c61f25e526d46678
bigcode/the-stack
train
2efcca1fda4aff08a8a72842
train
function
def main(): # Writing to stdout converts newlines, which confuses diff on Windows, so # write to a file instead. There's no reasonable way to do this in a Python # 2/3 compatible way, so the following is Python-2 only. lines = [line.decode("utf-8") for line in sys.stdin] with open(sys.argv[1], mode...
def main(): # Writing to stdout converts newlines, which confuses diff on Windows, so # write to a file instead. There's no reasonable way to do this in a Python # 2/3 compatible way, so the following is Python-2 only.
lines = [line.decode("utf-8") for line in sys.stdin] with open(sys.argv[1], mode="wb") as out: for line in lines: out.write(cleanup_one(line).encode("utf-8")) out.flush()
: return line def main(): # Writing to stdout converts newlines, which confuses diff on Windows, so # write to a file instead. There's no reasonable way to do this in a Python # 2/3 compatible way, so the following is Python-2 only.
64
64
115
59
4
kkohbrok/FStar
src/tests/interactive/cleanup.py
Python
main
main
37
45
37
40
0d41cae311423ec543aa1d0efb182455f6c5dbb9
bigcode/the-stack
train
4dc13ebdc851d68f69b059c1
train
function
def getModuleObjects(modules): objects = {} lookup = {} for mName in modules: try: NS = {} rl_exec("import %s as module" % mName,NS) except ImportError: continue else: module = NS['module'] if module in lookup: continue ...
def getModuleObjects(modules):
objects = {} lookup = {} for mName in modules: try: NS = {} rl_exec("import %s as module" % mName,NS) except ImportError: continue else: module = NS['module'] if module in lookup: continue lookup[module] = 1 obj...
append((mName,obj)) elif typ=='class': if obj.__module__==mName: lookup[obj] = 1 objects.setdefault(typ,[]).append((mName,obj)) getObjects(objects,lookup,mName,modBn,obj) def getModuleObjects(modules):
64
64
125
7
57
steingabelgaard/reportlab
tests/test_docstrings.py
Python
getModuleObjects
getModuleObjects
108
125
108
108
e28a0c063924d7ce1fb46b9b58c8d8ce10646d27
bigcode/the-stack
train
e091d6794c5e5faae9c00ebd
train
function
def obj2typ(obj): for typ in ('function','module','class','method'): if typ2is(typ)(obj): return typ return None
def obj2typ(obj):
for typ in ('function','module','class','method'): if typ2is(typ)(obj): return typ return None
'function':lambda x: (x[0],getattr(x[1],'__name__',''),'???' if isPyPy else x[1].__code__.co_filename), } def typ2key(typ): return _typ2key[typ] def obj2typ(obj):
64
64
36
6
58
steingabelgaard/reportlab
tests/test_docstrings.py
Python
obj2typ
obj2typ
30
33
30
30
fa17d9e2860095b190924f99217a5230852b7eb2
bigcode/the-stack
train
9c4bd03b782857cb26e102e2
train
function
def makeSuite(): suite = unittest.TestSuite() loader = unittest.TestLoader() if sys.platform[:4] != 'java': suite.addTest(loader.loadTestsFromTestCase(DocstringTestCase)) return suite
def makeSuite():
suite = unittest.TestSuite() loader = unittest.TestLoader() if sys.platform[:4] != 'java': suite.addTest(loader.loadTestsFromTestCase(DocstringTestCase)) return suite
." self._writeLogFile('class') def test2(self): "Test if methods have a doc string." self._writeLogFile('method') def test3(self): "Test if modules have a doc string." self._writeLogFile('module') def makeSuite():
64
64
48
4
60
steingabelgaard/reportlab
tests/test_docstrings.py
Python
makeSuite
makeSuite
189
193
189
189
101712e5a0cc0f62a40739f1e48c220dec74295d
bigcode/the-stack
train
6af4fb8e695f787c5527e400
train
function
def rl_module(i,name,pkg): return name=='reportlab' or name.startswith('reportlab.')
def rl_module(i,name,pkg):
return name=='reportlab' or name.startswith('reportlab.')
.modules[name], '__path__', None) or [] # don't traverse path items we've seen before path = [p for p in path if not seen(p)] for item in walk_packages_ex(path, name+'.', onerror, cond): yield item def rl_module(i,name,pkg):
64
64
22
8
55
steingabelgaard/reportlab
tests/test_docstrings.py
Python
rl_module
rl_module
76
77
76
76
e8b8e76dc21f73dd7bbbf6af9a2a6b277167ea34
bigcode/the-stack
train
f45cb23e5adcb7dcf54c8ed9
train
function
def getRLModules(): "Get a list of all objects defined *somewhere* in a package." global rl_modules if rl_modules is None: rl_modules = [] for _,name,_ in walk_packages_ex(cond=rl_module): rl_modules.append(name) return rl_modules
def getRLModules():
"Get a list of all objects defined *somewhere* in a package." global rl_modules if rl_modules is None: rl_modules = [] for _,name,_ in walk_packages_ex(cond=rl_module): rl_modules.append(name) return rl_modules
[p for p in path if not seen(p)] for item in walk_packages_ex(path, name+'.', onerror, cond): yield item def rl_module(i,name,pkg): return name=='reportlab' or name.startswith('reportlab.') rl_modules = None def getRLModules():
64
64
64
5
58
steingabelgaard/reportlab
tests/test_docstrings.py
Python
getRLModules
getRLModules
80
87
80
80
0e68024ad3cef097b84265433163558c0b813cc9
bigcode/the-stack
train
98f68dc7f414547d81dbe1fd
train
function
def getClass(obj): try: return obj.__self__.__class__ except: try: return obj.im_class except: return None
def getClass(obj):
try: return obj.__self__.__class__ except: try: return obj.im_class except: return None
code__.co_filename), } def typ2key(typ): return _typ2key[typ] def obj2typ(obj): for typ in ('function','module','class','method'): if typ2is(typ)(obj): return typ return None def getClass(obj):
64
64
35
5
58
steingabelgaard/reportlab
tests/test_docstrings.py
Python
getClass
getClass
36
43
36
36
b08c469c8379b825879fd51aeff2a9f96785471a
bigcode/the-stack
train
9c2b27c136ae8f875139ae85
train
function
def typ2is(typ): return getattr(inspect,'is'+typ)
def typ2is(typ):
return getattr(inspect,'is'+typ)
OutDir,SecureTestCase, GlobDirectoryWalker, outputfile, printLocation setOutDir(__name__) import os, sys, glob, re, unittest, inspect import reportlab from reportlab.lib.utils import rl_exec, isPy3, isPyPy def typ2is(typ):
64
64
17
7
56
steingabelgaard/reportlab
tests/test_docstrings.py
Python
typ2is
typ2is
18
19
18
18
37f2df3d3bae55cd14be5d94af68715fbee4fac4
bigcode/the-stack
train
84c0af771a848748c9b4ae1d
train
function
def typ2key(typ): return _typ2key[typ]
def typ2key(typ):
return _typ2key[typ]
name__',''),getattr(x[1],'__module__','')), 'function':lambda x: (x[0],getattr(x[1],'__name__',''),'???' if isPyPy else x[1].__code__.co_filename), } def typ2key(typ):
64
64
16
7
57
steingabelgaard/reportlab
tests/test_docstrings.py
Python
typ2key
typ2key
27
28
27
27
ab6f4f448b427c61f3c2ad338be41c0a92bba18d
bigcode/the-stack
train
3c7e6bc3e0d4ad19419a5139
train
function
def walk_packages_ex(path=None, prefix='', onerror=None, cond=None): def seen(p, m={}): if p in m: return True m[p] = True for importer, name, ispkg in iter_modules(path, prefix): if cond and not cond(importer,name,ispkg): continue yield importer, name, ispkg ...
def walk_packages_ex(path=None, prefix='', onerror=None, cond=None):
def seen(p, m={}): if p in m: return True m[p] = True for importer, name, ispkg in iter_modules(path, prefix): if cond and not cond(importer,name,ispkg): continue yield importer, name, ispkg if ispkg: try: __import__(name) ...
typ return None def getClass(obj): try: return obj.__self__.__class__ except: try: return obj.im_class except: return None from pkgutil import iter_modules def walk_packages_ex(path=None, prefix='', onerror=None, cond=None):
64
64
199
16
47
steingabelgaard/reportlab
tests/test_docstrings.py
Python
walk_packages_ex
walk_packages_ex
46
74
46
46
9687a11dab90e482ec256f8ffaaf5fa0551c3f38
bigcode/the-stack
train
a00a6037563d11d180cc848f
train
class
class DocstringTestCase(SecureTestCase): "Testing if objects in the ReportLab package have docstrings." def setUp(self): SecureTestCase.setUp(self) self.modules = getRLModules() self.objects = getModuleObjects(self.modules) def _writeLogFile(self, typ): "Write log file for ...
class DocstringTestCase(SecureTestCase):
"Testing if objects in the ReportLab package have docstrings." def setUp(self): SecureTestCase.setUp(self) self.modules = getRLModules() self.objects = getModuleObjects(self.modules) def _writeLogFile(self, typ): "Write log file for different kind of documentable objects." ...
Name,modBn,obj) def getModuleObjects(modules): objects = {} lookup = {} for mName in modules: try: NS = {} rl_exec("import %s as module" % mName,NS) except ImportError: continue else: module = NS['module'] if module in lookup: ...
141
141
473
10
130
steingabelgaard/reportlab
tests/test_docstrings.py
Python
DocstringTestCase
DocstringTestCase
127
187
127
127
0bf1a34aae23c55f2c9b523b1490c0387f5628b2
bigcode/the-stack
train
add1338e785ee5e81762cc0d
train
function
def getObjects(objects,lookup,mName,modBn,tobj): ttyp = obj2typ(tobj) for n in dir(tobj): obj = getattr(tobj,n,None) try: if obj in lookup: continue except: continue typ = obj2typ(obj) if typ in ('function','method'): if not isPyPy and ...
def getObjects(objects,lookup,mName,modBn,tobj):
ttyp = obj2typ(tobj) for n in dir(tobj): obj = getattr(tobj,n,None) try: if obj in lookup: continue except: continue typ = obj2typ(obj) if typ in ('function','method'): if not isPyPy and os.path.splitext(obj.__code__.co_filename)[0]==mo...
*somewhere* in a package." global rl_modules if rl_modules is None: rl_modules = [] for _,name,_ in walk_packages_ex(cond=rl_module): rl_modules.append(name) return rl_modules def getObjects(objects,lookup,mName,modBn,tobj):
64
64
184
14
49
steingabelgaard/reportlab
tests/test_docstrings.py
Python
getObjects
getObjects
89
106
89
89
5572a8193fb95668910433cedd47061b3ddd6531
bigcode/the-stack
train
cfa93a1edf7370ccb19ddd8c
train
function
def migrate_registry( name, value, registry, args, overrides, deletes, use_name_as_val=False ): if value in registry: overrides.append("{}={}".format(name, value)) overrides.append("{}._name={}".format(name, value)) overrides.extend(_override_attr(name, registry[value], args)) elif u...
def migrate_registry( name, value, registry, args, overrides, deletes, use_name_as_val=False ):
if value in registry: overrides.append("{}={}".format(name, value)) overrides.append("{}._name={}".format(name, value)) overrides.extend(_override_attr(name, registry[value], args)) elif use_name_as_val and value is not None: overrides.append("{}={}".format(name, value)) else...
in sub_overrides: overrides.append(f"{sub_node}.{k}.{so}") else: overrides.append("{}.{}={}".format(sub_node, k, val)) return overrides def migrate_registry( name, value, registry, args, overrides, deletes, use_name_as_val=False ):
64
64
98
24
39
houshengyuan/Parsing_enhanced_NMT
fairseq/dataclass/utils.py
Python
migrate_registry
migrate_registry
271
281
271
273
e2288b3bed501cf3c978e20a291c0cb679c6467b
bigcode/the-stack
train
9d36fd573287edfd4524451a
train
function
def override_module_args(args: Namespace) -> Tuple[List[str], List[str]]: """use the field in args to overrides those in cfg""" overrides = [] deletes = [] for k in FairseqConfig.__dataclass_fields__.keys(): overrides.extend( _override_attr(k, FairseqConfig.__dataclass_fields__[k].t...
def override_module_args(args: Namespace) -> Tuple[List[str], List[str]]:
"""use the field in args to overrides those in cfg""" overrides = [] deletes = [] for k in FairseqConfig.__dataclass_fields__.keys(): overrides.extend( _override_attr(k, FairseqConfig.__dataclass_fields__[k].type, args) ) if args is not None: if hasattr(args, "t...
}".format(sub_node, k, val)) return overrides def migrate_registry( name, value, registry, args, overrides, deletes, use_name_as_val=False ): if value in registry: overrides.append("{}={}".format(name, value)) overrides.append("{}._name={}".format(name, value)) overrides.extend(_o...
127
127
425
16
111
houshengyuan/Parsing_enhanced_NMT
fairseq/dataclass/utils.py
Python
override_module_args
override_module_args
284
341
284
284
d80a07d2cacfd9ebab97727ff2e1f156e4c9a43a
bigcode/the-stack
train
1763a6ca1b508f0ad58eb2ac
train
function
def gen_parser_from_dataclass( parser: ArgumentParser, dataclass_instance: FairseqDataclass, delete_default: bool = False, ) -> None: """convert a dataclass instance to tailing parser arguments""" def argparse_name(name: str): if name == "data": # normally data is positional arg...
def gen_parser_from_dataclass( parser: ArgumentParser, dataclass_instance: FairseqDataclass, delete_default: bool = False, ) -> None:
"""convert a dataclass instance to tailing parser arguments""" def argparse_name(name: str): if name == "data": # normally data is positional args return name if name == "_name": # private member, skip return None return "--" + name.replac...
aclass.configs import FairseqConfig from hydra.core.global_hydra import GlobalHydra from hydra.experimental import compose, initialize from omegaconf import DictConfig, OmegaConf, open_dict, _utils logger = logging.getLogger(__name__) def eval_str_list(x, x_type=float): if x is None: return None if i...
256
256
923
35
220
houshengyuan/Parsing_enhanced_NMT
fairseq/dataclass/utils.py
Python
gen_parser_from_dataclass
gen_parser_from_dataclass
53
172
53
57
ae8446c9896fc7aedf09767df9cb924f88ad3496
bigcode/the-stack
train
4bc69f8fc1200452d0bf13ff
train
function
def interpret_dc_type(field_type): if isinstance(field_type, str): raise RuntimeError("field should be a type") if field_type == Any: return str typestring = str(field_type) if re.match( r"(typing.|^)Union\[(.*), NoneType\]$", typestring ) or typestring.startswith("typing.O...
def interpret_dc_type(field_type):
if isinstance(field_type, str): raise RuntimeError("field should be a type") if field_type == Any: return str typestring = str(field_type) if re.match( r"(typing.|^)Union\[(.*), NoneType\]$", typestring ) or typestring.startswith("typing.Optional"): return field_typ...
: return None if isinstance(x, str): if len(x) == 0: return [] x = ast.literal_eval(x) try: return list(map(x_type, x)) except TypeError: return [x_type(x)] def interpret_dc_type(field_type):
63
64
93
7
56
houshengyuan/Parsing_enhanced_NMT
fairseq/dataclass/utils.py
Python
interpret_dc_type
interpret_dc_type
38
50
38
38
d719674658ece76b41daf093e884cb59e7032306
bigcode/the-stack
train
14f4cfba40b6b52816008964
train
function
def _override_attr( sub_node: str, data_class: Type[FairseqDataclass], args: Namespace ) -> List[str]: overrides = [] if not inspect.isclass(data_class) or not issubclass(data_class, FairseqDataclass): return overrides def get_default(f): if not isinstance(f.default_factory, _MISSING_T...
def _override_attr( sub_node: str, data_class: Type[FairseqDataclass], args: Namespace ) -> List[str]:
overrides = [] if not inspect.isclass(data_class) or not issubclass(data_class, FairseqDataclass): return overrides def get_default(f): if not isinstance(f.default_factory, _MISSING_TYPE): return f.default_factory() return f.default for k, v in data_class.__datacla...
arguments based on *add_args*.""" if not hasattr(cls, "add_args"): return import argparse parser = argparse.ArgumentParser( argument_default=argparse.SUPPRESS, allow_abbrev=False ) cls.add_args(parser) # copied from argparse.py: defaults = argparse.Namespace() for acti...
179
179
598
30
149
houshengyuan/Parsing_enhanced_NMT
fairseq/dataclass/utils.py
Python
_override_attr
_override_attr
198
268
198
200
1df5fb7611857e18e8aed2e4538c36b494fa9352
bigcode/the-stack
train
1da9186e5ee0b37cae258396
train
function
def merge_with_parent(dc: FairseqDataclass, cfg: DictConfig, remove_missing=True): if remove_missing: if is_dataclass(dc): target_keys = set(dc.__dataclass_fields__.keys()) else: target_keys = set(dc.keys()) with open_dict(cfg): for k in list(cfg.keys())...
def merge_with_parent(dc: FairseqDataclass, cfg: DictConfig, remove_missing=True):
if remove_missing: if is_dataclass(dc): target_keys = set(dc.__dataclass_fields__.keys()) else: target_keys = set(dc.keys()) with open_dict(cfg): for k in list(cfg.keys()): if k not in target_keys: del cfg[k] merg...
ISTRIES[k]["dataclass_registry"][overrides[k]] ) overwrite_args_by_name(cfg[k], overrides) cfg[k]._name = overrides[k] else: cfg[k] = overrides[k] def merge_with_parent(dc: FairseqDataclass, cfg: DictConfig, remove_missing=T...
64
64
127
20
44
houshengyuan/Parsing_enhanced_NMT
fairseq/dataclass/utils.py
Python
merge_with_parent
merge_with_parent
467
483
467
467
61e4f8da2a1f9733aeba4fa03e6a6c97d1a724ae
bigcode/the-stack
train
db75851230204d7f10e9ec61
train
function
def eval_str_list(x, x_type=float): if x is None: return None if isinstance(x, str): if len(x) == 0: return [] x = ast.literal_eval(x) try: return list(map(x_type, x)) except TypeError: return [x_type(x)]
def eval_str_list(x, x_type=float):
if x is None: return None if isinstance(x, str): if len(x) == 0: return [] x = ast.literal_eval(x) try: return list(map(x_type, x)) except TypeError: return [x_type(x)]
s import FairseqConfig from hydra.core.global_hydra import GlobalHydra from hydra.experimental import compose, initialize from omegaconf import DictConfig, OmegaConf, open_dict, _utils logger = logging.getLogger(__name__) def eval_str_list(x, x_type=float):
64
64
71
10
54
houshengyuan/Parsing_enhanced_NMT
fairseq/dataclass/utils.py
Python
eval_str_list
eval_str_list
25
35
25
25
faa7315c8d1ac90cecc0e932019ccbf58ee1ec69
bigcode/the-stack
train
c3823c9ed2acaa9879a2b963
train
function
def populate_dataclass( dataclass: FairseqDataclass, args: Namespace, ) -> FairseqDataclass: for k in dataclass.__dataclass_fields__.keys(): if k.startswith("_"): # private member, skip continue if hasattr(args, k): setattr(dataclass, k, getattr(args, k)) ...
def populate_dataclass( dataclass: FairseqDataclass, args: Namespace, ) -> FairseqDataclass:
for k in dataclass.__dataclass_fields__.keys(): if k.startswith("_"): # private member, skip continue if hasattr(args, k): setattr(dataclass, k, getattr(args, k)) return dataclass
(cfg.criterion, CRITERION_REGISTRY[args.criterion]) cfg.criterion._name = args.criterion OmegaConf.set_struct(cfg, True) return cfg def populate_dataclass( dataclass: FairseqDataclass, args: Namespace, ) -> FairseqDataclass:
64
64
79
26
37
houshengyuan/Parsing_enhanced_NMT
fairseq/dataclass/utils.py
Python
populate_dataclass
populate_dataclass
419
430
419
422
20b4dc01bdeea3a2d57b91d967b01d664dd9b3fd
bigcode/the-stack
train
4c86535a478464f6e67b69fc
train
class
class omegaconf_no_object_check: def __init__(self): self.old_is_primitive = _utils.is_primitive_type def __enter__(self): _utils.is_primitive_type = lambda _: True def __exit__(self, type, value, traceback): _utils.is_primitive_type = self.old_is_primitive
class omegaconf_no_object_check:
def __init__(self): self.old_is_primitive = _utils.is_primitive_type def __enter__(self): _utils.is_primitive_type = lambda _: True def __exit__(self, type, value, traceback): _utils.is_primitive_type = self.old_is_primitive
._name={}".format(args.arch)) # override model params with those exist in args overrides.extend(_override_attr("model", dc, args)) no_dc = False if no_dc: deletes.append("model") return overrides, deletes class omegaconf_no_object_chec...
64
64
76
9
54
houshengyuan/Parsing_enhanced_NMT
fairseq/dataclass/utils.py
Python
omegaconf_no_object_check
omegaconf_no_object_check
343
351
343
343
d04052638d749f6c866a88c538ea3dbcbaa252d7
bigcode/the-stack
train
33bf8dfd8381d621da60999b
train
function
def overwrite_args_by_name(cfg: DictConfig, overrides: Dict[str, any]): # this will be deprecated when we get rid of argparse and model_overrides logic from fairseq.registry import REGISTRIES with open_dict(cfg): for k in cfg.keys(): # "k in cfg" will return false if its a "mandatory v...
def overwrite_args_by_name(cfg: DictConfig, overrides: Dict[str, any]): # this will be deprecated when we get rid of argparse and model_overrides logic
from fairseq.registry import REGISTRIES with open_dict(cfg): for k in cfg.keys(): # "k in cfg" will return false if its a "mandatory value (e.g. ???)" if k in cfg and isinstance(cfg[k], DictConfig): if k in overrides and isinstance(overrides[k], dict): ...
for k in dataclass.__dataclass_fields__.keys(): if k.startswith("_"): # private member, skip continue if hasattr(args, k): setattr(dataclass, k, getattr(args, k)) return dataclass def overwrite_args_by_name(cfg: DictConfig, overrides: Dict[str, any]): # this...
87
87
291
35
51
houshengyuan/Parsing_enhanced_NMT
fairseq/dataclass/utils.py
Python
overwrite_args_by_name
overwrite_args_by_name
433
464
433
435
6ab149c01df83924e25001c084423d2b3da7aabd
bigcode/the-stack
train