body
stringlengths
26
98.2k
body_hash
int64
-9,222,864,604,528,158,000
9,221,803,474B
docstring
stringlengths
1
16.8k
path
stringlengths
5
230
name
stringlengths
1
96
repository_name
stringlengths
7
89
lang
stringclasses
1 value
body_without_docstring
stringlengths
20
98.2k
def generator_fn(words_file, tags_file): 'Enumerator to enumerate through words_file and associated tags_file one line at a time\n\n :param words_file: file path of the words file (one sentence per line)\n :param tags_file: file path of tags file (tags corresponding to words file)\n :return enumerator that...
-4,083,911,911,165,067,300
Enumerator to enumerate through words_file and associated tags_file one line at a time :param words_file: file path of the words file (one sentence per line) :param tags_file: file path of tags file (tags corresponding to words file) :return enumerator that enumerates over the format (words, len(words)), tags one line...
src/model/lstm_crf/main.py
generator_fn
vikasbahirwani/SequenceTagging
python
def generator_fn(words_file, tags_file): 'Enumerator to enumerate through words_file and associated tags_file one line at a time\n\n :param words_file: file path of the words file (one sentence per line)\n :param tags_file: file path of tags file (tags corresponding to words file)\n :return enumerator that...
def input_fn(words_file, tags_file, params=None, shuffle_and_repeat=False): "Creates tensorflow dataset using the generator_fn\n\n :param words_file: file path of the words file (one sentence per line)\n :param tags_file: file path of tags file (tags corresponding to words file)\n :param params: if not Non...
-139,622,785,079,150,910
Creates tensorflow dataset using the generator_fn :param words_file: file path of the words file (one sentence per line) :param tags_file: file path of tags file (tags corresponding to words file) :param params: if not None then model hyperparameters expected - 'buffer' (as in buffer size) and 'epochs' :param shuffle_...
src/model/lstm_crf/main.py
input_fn
vikasbahirwani/SequenceTagging
python
def input_fn(words_file, tags_file, params=None, shuffle_and_repeat=False): "Creates tensorflow dataset using the generator_fn\n\n :param words_file: file path of the words file (one sentence per line)\n :param tags_file: file path of tags file (tags corresponding to words file)\n :param params: if not Non...
def model_fn(features, labels, mode, params): '\n\n :param features: words from sentence and number of words per sentence\n :param labels: One tag per word\n :param mode: tf.estimator.ModeKeys.TRAIN or tf.estimator.ModeKeys.PREDICT or tf.estimator.ModeKeys.EVAL\n :param params: dictionary of hyper pa...
8,180,957,206,196,648,000
:param features: words from sentence and number of words per sentence :param labels: One tag per word :param mode: tf.estimator.ModeKeys.TRAIN or tf.estimator.ModeKeys.PREDICT or tf.estimator.ModeKeys.EVAL :param params: dictionary of hyper parameters for the model :return:
src/model/lstm_crf/main.py
model_fn
vikasbahirwani/SequenceTagging
python
def model_fn(features, labels, mode, params): '\n\n :param features: words from sentence and number of words per sentence\n :param labels: One tag per word\n :param mode: tf.estimator.ModeKeys.TRAIN or tf.estimator.ModeKeys.PREDICT or tf.estimator.ModeKeys.EVAL\n :param params: dictionary of hyper pa...
def __virtual__(): '\n Load this state if the reg module exists\n ' if ('reg.read_value' not in __utils__): return (False, 'reg state module failed to load: missing module function: reg.read_value') if ('reg.set_value' not in __utils__): return (False, 'reg state module failed to load:...
8,883,516,520,131,150,000
Load this state if the reg module exists
salt/states/reg.py
__virtual__
Feeeenng/salt
python
def __virtual__(): '\n \n ' if ('reg.read_value' not in __utils__): return (False, 'reg state module failed to load: missing module function: reg.read_value') if ('reg.set_value' not in __utils__): return (False, 'reg state module failed to load: missing module function: reg.set_value'...
def _parse_key(key): '\n split the hive from the key\n ' splt = key.split('\\') hive = splt.pop(0) key = '\\'.join(splt) return (hive, key)
-1,644,809,154,807,784,400
split the hive from the key
salt/states/reg.py
_parse_key
Feeeenng/salt
python
def _parse_key(key): '\n \n ' splt = key.split('\\') hive = splt.pop(0) key = '\\'.join(splt) return (hive, key)
def present(name, vname=None, vdata=None, vtype='REG_SZ', use_32bit_registry=False): "\n Ensure a registry key or value is present.\n\n :param str name: A string value representing the full path of the key to\n include the HIVE, Key, and all Subkeys. For example:\n\n ``HKEY_LOCAL_MACHINE\\SOFTWARE\\Salt...
-3,619,361,012,449,428,500
Ensure a registry key or value is present. :param str name: A string value representing the full path of the key to include the HIVE, Key, and all Subkeys. For example: ``HKEY_LOCAL_MACHINE\SOFTWARE\Salt`` Valid hive values include: - HKEY_CURRENT_USER or HKCU - HKEY_LOCAL_MACHINE or HKLM - HKEY_USERS or HKU :param...
salt/states/reg.py
present
Feeeenng/salt
python
def present(name, vname=None, vdata=None, vtype='REG_SZ', use_32bit_registry=False): "\n Ensure a registry key or value is present.\n\n :param str name: A string value representing the full path of the key to\n include the HIVE, Key, and all Subkeys. For example:\n\n ``HKEY_LOCAL_MACHINE\\SOFTWARE\\Salt...
def absent(name, vname=None, use_32bit_registry=False): "\n Ensure a registry value is removed. To remove a key use key_absent.\n\n :param str name: A string value representing the full path of the key to\n include the HIVE, Key, and all Subkeys. For example:\n\n ``HKEY_LOCAL_MACHINE\\SOFTWARE\\Salt``\n...
8,684,500,273,568,656,000
Ensure a registry value is removed. To remove a key use key_absent. :param str name: A string value representing the full path of the key to include the HIVE, Key, and all Subkeys. For example: ``HKEY_LOCAL_MACHINE\SOFTWARE\Salt`` Valid hive values include: - HKEY_CURRENT_USER or HKCU - HKEY_LOCAL_MACHINE or HKLM -...
salt/states/reg.py
absent
Feeeenng/salt
python
def absent(name, vname=None, use_32bit_registry=False): "\n Ensure a registry value is removed. To remove a key use key_absent.\n\n :param str name: A string value representing the full path of the key to\n include the HIVE, Key, and all Subkeys. For example:\n\n ``HKEY_LOCAL_MACHINE\\SOFTWARE\\Salt``\n...
def key_absent(name, use_32bit_registry=False): "\n .. versionadded:: 2015.5.4\n\n Ensure a registry key is removed. This will remove a key and all value\n entries it contains. It will fail if the key contains subkeys.\n\n :param str name: A string representing the full path to the key to be\n remove...
7,864,107,645,527,735,000
.. versionadded:: 2015.5.4 Ensure a registry key is removed. This will remove a key and all value entries it contains. It will fail if the key contains subkeys. :param str name: A string representing the full path to the key to be removed to include the hive and the keypath. The hive can be any of the following: - H...
salt/states/reg.py
key_absent
Feeeenng/salt
python
def key_absent(name, use_32bit_registry=False): "\n .. versionadded:: 2015.5.4\n\n Ensure a registry key is removed. This will remove a key and all value\n entries it contains. It will fail if the key contains subkeys.\n\n :param str name: A string representing the full path to the key to be\n remove...
def test_authenticate_username_superuser(self): 'Test to authenticate as superuser.' self.user.is_superuser = True self.user.validated_by_email = False self.user.validated_by_manager = False self.user.save() backend = DakaraModelBackend() self.assertEqual(backend.authenticate(MagicMock(), us...
8,255,383,177,069,123,000
Test to authenticate as superuser.
dakara_server/users/tests/test_backends.py
test_authenticate_username_superuser
DakaraProject/dakara-server
python
def test_authenticate_username_superuser(self): self.user.is_superuser = True self.user.validated_by_email = False self.user.validated_by_manager = False self.user.save() backend = DakaraModelBackend() self.assertEqual(backend.authenticate(MagicMock(), username='TestUser', password='pass'),...
def test_authenticate_username_not_active(self): 'Test to authenticate an inactive user.' self.user.is_active = False self.user.save() backend = DakaraModelBackend() self.assertIsNone(backend.authenticate(MagicMock(), username='TestUser', password='pass'))
-5,009,936,732,395,484,000
Test to authenticate an inactive user.
dakara_server/users/tests/test_backends.py
test_authenticate_username_not_active
DakaraProject/dakara-server
python
def test_authenticate_username_not_active(self): self.user.is_active = False self.user.save() backend = DakaraModelBackend() self.assertIsNone(backend.authenticate(MagicMock(), username='TestUser', password='pass'))
def test_authenticate_username_not_validated_by_email(self): 'Test to authenticate when not validated by email.' self.user.validated_by_email = False self.user.validated_by_manager = True self.user.save() backend = DakaraModelBackend() with self.assertRaisesRegex(ValidationError, 'This user emai...
7,254,216,078,541,471,000
Test to authenticate when not validated by email.
dakara_server/users/tests/test_backends.py
test_authenticate_username_not_validated_by_email
DakaraProject/dakara-server
python
def test_authenticate_username_not_validated_by_email(self): self.user.validated_by_email = False self.user.validated_by_manager = True self.user.save() backend = DakaraModelBackend() with self.assertRaisesRegex(ValidationError, 'This user email has not been validated'): backend.authent...
@config_email_disabled def test_authenticate_username_not_validated_by_email_no_email(self): 'Test to authenticate when not validated by email and emails disabled.' self.user.validated_by_email = False self.user.validated_by_manager = True self.user.save() backend = DakaraModelBackend() self.ass...
-7,744,552,453,736,005,000
Test to authenticate when not validated by email and emails disabled.
dakara_server/users/tests/test_backends.py
test_authenticate_username_not_validated_by_email_no_email
DakaraProject/dakara-server
python
@config_email_disabled def test_authenticate_username_not_validated_by_email_no_email(self): self.user.validated_by_email = False self.user.validated_by_manager = True self.user.save() backend = DakaraModelBackend() self.assertEqual(backend.authenticate(MagicMock(), username='TestUser', passwor...
def test_authenticate_username_not_validated_by_manager(self): 'Test to authenticate when not validated by manager.' self.user.validated_by_email = True self.user.validated_by_manager = False self.user.save() backend = DakaraModelBackend() with self.assertRaisesRegex(ValidationError, 'This user ...
8,615,451,956,186,013,000
Test to authenticate when not validated by manager.
dakara_server/users/tests/test_backends.py
test_authenticate_username_not_validated_by_manager
DakaraProject/dakara-server
python
def test_authenticate_username_not_validated_by_manager(self): self.user.validated_by_email = True self.user.validated_by_manager = False self.user.save() backend = DakaraModelBackend() with self.assertRaisesRegex(ValidationError, 'This user account has not been validated by a manager'): ...
def test_authenticate_username_ok(self): 'Test to authenticate.' self.user.validated_by_email = True self.user.validated_by_manager = True self.user.save() backend = DakaraModelBackend() self.assertEqual(backend.authenticate(MagicMock(), username='TestUser', password='pass'), self.user)
6,897,010,371,461,581,000
Test to authenticate.
dakara_server/users/tests/test_backends.py
test_authenticate_username_ok
DakaraProject/dakara-server
python
def test_authenticate_username_ok(self): self.user.validated_by_email = True self.user.validated_by_manager = True self.user.save() backend = DakaraModelBackend() self.assertEqual(backend.authenticate(MagicMock(), username='TestUser', password='pass'), self.user)
def new_admissions_chart(alt, projection_admits: pd.DataFrame, parameters: Parameters) -> Chart: 'docstring' plot_projection_days = (parameters.n_days - 10) max_y_axis = parameters.max_y_axis as_date = parameters.as_date y_scale = alt.Scale() if (max_y_axis is not None): y_scale.domain =...
8,149,229,652,189,678,000
docstring
src/penn_chime/charts.py
new_admissions_chart
degerli/chime-1
python
def new_admissions_chart(alt, projection_admits: pd.DataFrame, parameters: Parameters) -> Chart: plot_projection_days = (parameters.n_days - 10) max_y_axis = parameters.max_y_axis as_date = parameters.as_date y_scale = alt.Scale() if (max_y_axis is not None): y_scale.domain = (0, max_y_...
def admitted_patients_chart(alt, census: pd.DataFrame, parameters: Parameters) -> Chart: 'docstring' plot_projection_days = (parameters.n_days - 10) max_y_axis = parameters.max_y_axis as_date = parameters.as_date if as_date: census = add_date_column(census) x_kwargs = {'shorthand': '...
5,839,135,649,114,293,000
docstring
src/penn_chime/charts.py
admitted_patients_chart
degerli/chime-1
python
def admitted_patients_chart(alt, census: pd.DataFrame, parameters: Parameters) -> Chart: plot_projection_days = (parameters.n_days - 10) max_y_axis = parameters.max_y_axis as_date = parameters.as_date if as_date: census = add_date_column(census) x_kwargs = {'shorthand': 'date:T', 't...
def chart_descriptions(chart: Chart, labels, suffix: str=''): '\n\n :param chart: Chart: The alt chart to be used in finding max points\n :param suffix: str: The assumption is that the charts have similar column names.\n The census chart adds " Census" to the column names.\n ...
-3,031,882,789,968,356,000
:param chart: Chart: The alt chart to be used in finding max points :param suffix: str: The assumption is that the charts have similar column names. The census chart adds " Census" to the column names. Make sure to include a space or underscore as appropriate :return: str: Returns a multi-...
src/penn_chime/charts.py
chart_descriptions
degerli/chime-1
python
def chart_descriptions(chart: Chart, labels, suffix: str=): '\n\n :param chart: Chart: The alt chart to be used in finding max points\n :param suffix: str: The assumption is that the charts have similar column names.\n The census chart adds " Census" to the column names.\n ...
@classmethod def setup(cls: Type[Dataclass], arguments: Optional[str]='', dest: Optional[str]=None, default: Optional[Dataclass]=None, conflict_resolution_mode: ConflictResolution=ConflictResolution.AUTO, add_option_string_dash_variants: DashVariant=DashVariant.AUTO, parse_known_args: bool=False, attempt_to_reorder: bo...
5,784,539,640,100,981,000
Basic setup for a test. Keyword Arguments: arguments {Optional[str]} -- The arguments to pass to the parser (default: {""}) dest {Optional[str]} -- the attribute where the argument should be stored. (default: {None}) Returns: {cls}} -- the class's type.
test/testutils.py
setup
idoby/SimpleParsing
python
@classmethod def setup(cls: Type[Dataclass], arguments: Optional[str]=, dest: Optional[str]=None, default: Optional[Dataclass]=None, conflict_resolution_mode: ConflictResolution=ConflictResolution.AUTO, add_option_string_dash_variants: DashVariant=DashVariant.AUTO, parse_known_args: bool=False, attempt_to_reorder: bool...
@classmethod def required_components(cls) -> List[Type]: 'Components that should be included in the pipeline before this component.' return [Featurizer]
-3,653,919,952,852,145,000
Components that should be included in the pipeline before this component.
rasa/nlu/classifiers/diet_classifier.py
required_components
Adarshsng/rasa
python
@classmethod def required_components(cls) -> List[Type]: return [Featurizer]
@staticmethod def get_default_config() -> Dict[(Text, Any)]: "The component's default config (see parent class for full docstring)." return {HIDDEN_LAYERS_SIZES: {TEXT: [], LABEL: []}, SHARE_HIDDEN_LAYERS: False, TRANSFORMER_SIZE: DEFAULT_TRANSFORMER_SIZE, NUM_TRANSFORMER_LAYERS: 2, NUM_HEADS: 4, KEY_RELATIVE_A...
-3,262,418,372,835,260,400
The component's default config (see parent class for full docstring).
rasa/nlu/classifiers/diet_classifier.py
get_default_config
Adarshsng/rasa
python
@staticmethod def get_default_config() -> Dict[(Text, Any)]: return {HIDDEN_LAYERS_SIZES: {TEXT: [], LABEL: []}, SHARE_HIDDEN_LAYERS: False, TRANSFORMER_SIZE: DEFAULT_TRANSFORMER_SIZE, NUM_TRANSFORMER_LAYERS: 2, NUM_HEADS: 4, KEY_RELATIVE_ATTENTION: False, VALUE_RELATIVE_ATTENTION: False, MAX_RELATIVE_POSITION...
def __init__(self, config: Dict[(Text, Any)], model_storage: ModelStorage, resource: Resource, execution_context: ExecutionContext, index_label_id_mapping: Optional[Dict[(int, Text)]]=None, entity_tag_specs: Optional[List[EntityTagSpec]]=None, model: Optional[RasaModel]=None, sparse_feature_sizes: Optional[Dict[(Text, ...
-106,568,300,991,616,510
Declare instance variables with default values.
rasa/nlu/classifiers/diet_classifier.py
__init__
Adarshsng/rasa
python
def __init__(self, config: Dict[(Text, Any)], model_storage: ModelStorage, resource: Resource, execution_context: ExecutionContext, index_label_id_mapping: Optional[Dict[(int, Text)]]=None, entity_tag_specs: Optional[List[EntityTagSpec]]=None, model: Optional[RasaModel]=None, sparse_feature_sizes: Optional[Dict[(Text, ...
@classmethod def create(cls, config: Dict[(Text, Any)], model_storage: ModelStorage, resource: Resource, execution_context: ExecutionContext) -> DIETClassifier: 'Creates a new untrained component (see parent class for full docstring).' return cls(config, model_storage, resource, execution_context)
3,003,322,216,744,029,000
Creates a new untrained component (see parent class for full docstring).
rasa/nlu/classifiers/diet_classifier.py
create
Adarshsng/rasa
python
@classmethod def create(cls, config: Dict[(Text, Any)], model_storage: ModelStorage, resource: Resource, execution_context: ExecutionContext) -> DIETClassifier: return cls(config, model_storage, resource, execution_context)
@property def label_key(self) -> Optional[Text]: 'Return key if intent classification is activated.' return (LABEL_KEY if self.component_config[INTENT_CLASSIFICATION] else None)
1,831,871,081,288,990,200
Return key if intent classification is activated.
rasa/nlu/classifiers/diet_classifier.py
label_key
Adarshsng/rasa
python
@property def label_key(self) -> Optional[Text]: return (LABEL_KEY if self.component_config[INTENT_CLASSIFICATION] else None)
@property def label_sub_key(self) -> Optional[Text]: 'Return sub key if intent classification is activated.' return (LABEL_SUB_KEY if self.component_config[INTENT_CLASSIFICATION] else None)
7,158,035,865,042,439,000
Return sub key if intent classification is activated.
rasa/nlu/classifiers/diet_classifier.py
label_sub_key
Adarshsng/rasa
python
@property def label_sub_key(self) -> Optional[Text]: return (LABEL_SUB_KEY if self.component_config[INTENT_CLASSIFICATION] else None)
@staticmethod def _label_id_index_mapping(training_data: TrainingData, attribute: Text) -> Dict[(Text, int)]: 'Create label_id dictionary.' distinct_label_ids = ({example.get(attribute) for example in training_data.intent_examples} - {None}) return {label_id: idx for (idx, label_id) in enumerate(sorted(dist...
4,189,876,990,410,381,300
Create label_id dictionary.
rasa/nlu/classifiers/diet_classifier.py
_label_id_index_mapping
Adarshsng/rasa
python
@staticmethod def _label_id_index_mapping(training_data: TrainingData, attribute: Text) -> Dict[(Text, int)]: distinct_label_ids = ({example.get(attribute) for example in training_data.intent_examples} - {None}) return {label_id: idx for (idx, label_id) in enumerate(sorted(distinct_label_ids))}
def _create_entity_tag_specs(self, training_data: TrainingData) -> List[EntityTagSpec]: 'Create entity tag specifications with their respective tag id mappings.' _tag_specs = [] for tag_name in POSSIBLE_TAGS: if self.component_config[BILOU_FLAG]: tag_id_index_mapping = bilou_utils.build_...
-2,915,100,119,132,239,000
Create entity tag specifications with their respective tag id mappings.
rasa/nlu/classifiers/diet_classifier.py
_create_entity_tag_specs
Adarshsng/rasa
python
def _create_entity_tag_specs(self, training_data: TrainingData) -> List[EntityTagSpec]: _tag_specs = [] for tag_name in POSSIBLE_TAGS: if self.component_config[BILOU_FLAG]: tag_id_index_mapping = bilou_utils.build_tag_id_dict(training_data, tag_name) else: tag_id_ind...
@staticmethod def _tag_id_index_mapping_for(tag_name: Text, training_data: TrainingData) -> Optional[Dict[(Text, int)]]: 'Create mapping from tag name to id.' if (tag_name == ENTITY_ATTRIBUTE_ROLE): distinct_tags = training_data.entity_roles elif (tag_name == ENTITY_ATTRIBUTE_GROUP): distinc...
-7,342,428,663,700,129,000
Create mapping from tag name to id.
rasa/nlu/classifiers/diet_classifier.py
_tag_id_index_mapping_for
Adarshsng/rasa
python
@staticmethod def _tag_id_index_mapping_for(tag_name: Text, training_data: TrainingData) -> Optional[Dict[(Text, int)]]: if (tag_name == ENTITY_ATTRIBUTE_ROLE): distinct_tags = training_data.entity_roles elif (tag_name == ENTITY_ATTRIBUTE_GROUP): distinct_tags = training_data.entity_groups ...
def _check_labels_features_exist(self, labels_example: List[Message], attribute: Text) -> bool: 'Checks if all labels have features set.' return all((label_example.features_present(attribute, self.component_config[FEATURIZERS]) for label_example in labels_example))
7,485,533,832,181,726,000
Checks if all labels have features set.
rasa/nlu/classifiers/diet_classifier.py
_check_labels_features_exist
Adarshsng/rasa
python
def _check_labels_features_exist(self, labels_example: List[Message], attribute: Text) -> bool: return all((label_example.features_present(attribute, self.component_config[FEATURIZERS]) for label_example in labels_example))
def _check_input_dimension_consistency(self, model_data: RasaModelData) -> None: 'Checks if features have same dimensionality if hidden layers are shared.' if self.component_config.get(SHARE_HIDDEN_LAYERS): num_text_sentence_features = model_data.number_of_units(TEXT, SENTENCE) num_label_sentenc...
-2,929,522,057,481,884,700
Checks if features have same dimensionality if hidden layers are shared.
rasa/nlu/classifiers/diet_classifier.py
_check_input_dimension_consistency
Adarshsng/rasa
python
def _check_input_dimension_consistency(self, model_data: RasaModelData) -> None: if self.component_config.get(SHARE_HIDDEN_LAYERS): num_text_sentence_features = model_data.number_of_units(TEXT, SENTENCE) num_label_sentence_features = model_data.number_of_units(LABEL, SENTENCE) num_text_...
def _extract_labels_precomputed_features(self, label_examples: List[Message], attribute: Text=INTENT) -> Tuple[(List[FeatureArray], List[FeatureArray])]: 'Collects precomputed encodings.' features = defaultdict(list) for e in label_examples: label_features = self._extract_features(e, attribute) ...
-1,011,031,399,489,427,300
Collects precomputed encodings.
rasa/nlu/classifiers/diet_classifier.py
_extract_labels_precomputed_features
Adarshsng/rasa
python
def _extract_labels_precomputed_features(self, label_examples: List[Message], attribute: Text=INTENT) -> Tuple[(List[FeatureArray], List[FeatureArray])]: features = defaultdict(list) for e in label_examples: label_features = self._extract_features(e, attribute) for (feature_key, feature_val...
@staticmethod def _compute_default_label_features(labels_example: List[Message]) -> List[FeatureArray]: 'Computes one-hot representation for the labels.' logger.debug('No label features found. Computing default label features.') eye_matrix = np.eye(len(labels_example), dtype=np.float32) return [FeatureA...
8,457,130,274,428,411,000
Computes one-hot representation for the labels.
rasa/nlu/classifiers/diet_classifier.py
_compute_default_label_features
Adarshsng/rasa
python
@staticmethod def _compute_default_label_features(labels_example: List[Message]) -> List[FeatureArray]: logger.debug('No label features found. Computing default label features.') eye_matrix = np.eye(len(labels_example), dtype=np.float32) return [FeatureArray(np.array([np.expand_dims(a, 0) for a in eye_...
def _create_label_data(self, training_data: TrainingData, label_id_dict: Dict[(Text, int)], attribute: Text) -> RasaModelData: 'Create matrix with label_ids encoded in rows as bag of words.\n\n Find a training example for each label and get the encoded features\n from the corresponding Message object....
-1,096,988,557,676,506,600
Create matrix with label_ids encoded in rows as bag of words. Find a training example for each label and get the encoded features from the corresponding Message object. If the features are already computed, fetch them from the message object else compute a one hot encoding for the label as the feature vector.
rasa/nlu/classifiers/diet_classifier.py
_create_label_data
Adarshsng/rasa
python
def _create_label_data(self, training_data: TrainingData, label_id_dict: Dict[(Text, int)], attribute: Text) -> RasaModelData: 'Create matrix with label_ids encoded in rows as bag of words.\n\n Find a training example for each label and get the encoded features\n from the corresponding Message object....
def _create_model_data(self, training_data: List[Message], label_id_dict: Optional[Dict[(Text, int)]]=None, label_attribute: Optional[Text]=None, training: bool=True) -> RasaModelData: 'Prepare data for training and create a RasaModelData object.' from rasa.utils.tensorflow import model_data_utils attribute...
1,932,037,351,382,631,700
Prepare data for training and create a RasaModelData object.
rasa/nlu/classifiers/diet_classifier.py
_create_model_data
Adarshsng/rasa
python
def _create_model_data(self, training_data: List[Message], label_id_dict: Optional[Dict[(Text, int)]]=None, label_attribute: Optional[Text]=None, training: bool=True) -> RasaModelData: from rasa.utils.tensorflow import model_data_utils attributes_to_consider = [TEXT] if (training and self.component_con...
def preprocess_train_data(self, training_data: TrainingData) -> RasaModelData: 'Prepares data for training.\n\n Performs sanity checks on training data, extracts encodings for labels.\n ' if self.component_config[BILOU_FLAG]: bilou_utils.apply_bilou_schema(training_data) label_id_index...
557,687,017,003,223,200
Prepares data for training. Performs sanity checks on training data, extracts encodings for labels.
rasa/nlu/classifiers/diet_classifier.py
preprocess_train_data
Adarshsng/rasa
python
def preprocess_train_data(self, training_data: TrainingData) -> RasaModelData: 'Prepares data for training.\n\n Performs sanity checks on training data, extracts encodings for labels.\n ' if self.component_config[BILOU_FLAG]: bilou_utils.apply_bilou_schema(training_data) label_id_index...
def train(self, training_data: TrainingData) -> Resource: 'Train the embedding intent classifier on a data set.' model_data = self.preprocess_train_data(training_data) if model_data.is_empty(): logger.debug(f"Cannot train '{self.__class__.__name__}'. No data was provided. Skipping training of the cl...
-3,389,418,153,500,108,300
Train the embedding intent classifier on a data set.
rasa/nlu/classifiers/diet_classifier.py
train
Adarshsng/rasa
python
def train(self, training_data: TrainingData) -> Resource: model_data = self.preprocess_train_data(training_data) if model_data.is_empty(): logger.debug(f"Cannot train '{self.__class__.__name__}'. No data was provided. Skipping training of the classifier.") return self._resource if ((not...
def _predict_label(self, predict_out: Optional[Dict[(Text, tf.Tensor)]]) -> Tuple[(Dict[(Text, Any)], List[Dict[(Text, Any)]])]: 'Predicts the intent of the provided message.' label: Dict[(Text, Any)] = {'name': None, 'confidence': 0.0} label_ranking = [] if (predict_out is None): return (label,...
5,663,114,333,651,413,000
Predicts the intent of the provided message.
rasa/nlu/classifiers/diet_classifier.py
_predict_label
Adarshsng/rasa
python
def _predict_label(self, predict_out: Optional[Dict[(Text, tf.Tensor)]]) -> Tuple[(Dict[(Text, Any)], List[Dict[(Text, Any)]])]: label: Dict[(Text, Any)] = {'name': None, 'confidence': 0.0} label_ranking = [] if (predict_out is None): return (label, label_ranking) message_sim = predict_out[...
def process(self, messages: List[Message]) -> List[Message]: 'Augments the message with intents, entities, and diagnostic data.' for message in messages: out = self._predict(message) if self.component_config[INTENT_CLASSIFICATION]: (label, label_ranking) = self._predict_label(out) ...
109,263,573,167,095,840
Augments the message with intents, entities, and diagnostic data.
rasa/nlu/classifiers/diet_classifier.py
process
Adarshsng/rasa
python
def process(self, messages: List[Message]) -> List[Message]: for message in messages: out = self._predict(message) if self.component_config[INTENT_CLASSIFICATION]: (label, label_ranking) = self._predict_label(out) message.set(INTENT, label, add_to_output=True) ...
def persist(self) -> None: 'Persist this model into the passed directory.' if (self.model is None): return None with self._model_storage.write_to(self._resource) as model_path: file_name = self.__class__.__name__ tf_model_file = (model_path / f'{file_name}.tf_model') rasa.sha...
211,940,360,593,332,900
Persist this model into the passed directory.
rasa/nlu/classifiers/diet_classifier.py
persist
Adarshsng/rasa
python
def persist(self) -> None: if (self.model is None): return None with self._model_storage.write_to(self._resource) as model_path: file_name = self.__class__.__name__ tf_model_file = (model_path / f'{file_name}.tf_model') rasa.shared.utils.io.create_directory_for_file(tf_model...
@classmethod def load(cls, config: Dict[(Text, Any)], model_storage: ModelStorage, resource: Resource, execution_context: ExecutionContext, **kwargs: Any) -> DIETClassifier: 'Loads a policy from the storage (see parent class for full docstring).' try: with model_storage.read_from(resource) as model_path...
2,106,258,776,940,941,800
Loads a policy from the storage (see parent class for full docstring).
rasa/nlu/classifiers/diet_classifier.py
load
Adarshsng/rasa
python
@classmethod def load(cls, config: Dict[(Text, Any)], model_storage: ModelStorage, resource: Resource, execution_context: ExecutionContext, **kwargs: Any) -> DIETClassifier: try: with model_storage.read_from(resource) as model_path: return cls._load(model_path, config, model_storage, resour...
@classmethod def _load(cls, model_path: Path, config: Dict[(Text, Any)], model_storage: ModelStorage, resource: Resource, execution_context: ExecutionContext) -> 'DIETClassifier': 'Loads the trained model from the provided directory.' (index_label_id_mapping, entity_tag_specs, label_data, data_example, sparse_f...
1,848,851,608,624,442,400
Loads the trained model from the provided directory.
rasa/nlu/classifiers/diet_classifier.py
_load
Adarshsng/rasa
python
@classmethod def _load(cls, model_path: Path, config: Dict[(Text, Any)], model_storage: ModelStorage, resource: Resource, execution_context: ExecutionContext) -> 'DIETClassifier': (index_label_id_mapping, entity_tag_specs, label_data, data_example, sparse_feature_sizes) = cls._load_from_files(model_path) c...
@staticmethod def _ordered_tag_specs(entity_tag_specs: Optional[List[EntityTagSpec]]) -> List[EntityTagSpec]: 'Ensure that order of entity tag specs matches CRF layer order.' if (entity_tag_specs is None): return [] crf_order = [ENTITY_ATTRIBUTE_TYPE, ENTITY_ATTRIBUTE_ROLE, ENTITY_ATTRIBUTE_GROUP] ...
7,247,348,547,029,321,000
Ensure that order of entity tag specs matches CRF layer order.
rasa/nlu/classifiers/diet_classifier.py
_ordered_tag_specs
Adarshsng/rasa
python
@staticmethod def _ordered_tag_specs(entity_tag_specs: Optional[List[EntityTagSpec]]) -> List[EntityTagSpec]: if (entity_tag_specs is None): return [] crf_order = [ENTITY_ATTRIBUTE_TYPE, ENTITY_ATTRIBUTE_ROLE, ENTITY_ATTRIBUTE_GROUP] ordered_tag_spec = [] for tag_name in crf_order: ...
def batch_loss(self, batch_in: Union[(Tuple[tf.Tensor], Tuple[np.ndarray])]) -> tf.Tensor: 'Calculates the loss for the given batch.\n\n Args:\n batch_in: The batch.\n\n Returns:\n The loss of the given batch.\n ' tf_batch_data = self.batch_to_model_data_format(batch_i...
1,193,514,375,686,330,000
Calculates the loss for the given batch. Args: batch_in: The batch. Returns: The loss of the given batch.
rasa/nlu/classifiers/diet_classifier.py
batch_loss
Adarshsng/rasa
python
def batch_loss(self, batch_in: Union[(Tuple[tf.Tensor], Tuple[np.ndarray])]) -> tf.Tensor: 'Calculates the loss for the given batch.\n\n Args:\n batch_in: The batch.\n\n Returns:\n The loss of the given batch.\n ' tf_batch_data = self.batch_to_model_data_format(batch_i...
def prepare_for_predict(self) -> None: 'Prepares the model for prediction.' if self.config[INTENT_CLASSIFICATION]: (_, self.all_labels_embed) = self._create_all_labels()
1,332,386,574,597,657,600
Prepares the model for prediction.
rasa/nlu/classifiers/diet_classifier.py
prepare_for_predict
Adarshsng/rasa
python
def prepare_for_predict(self) -> None: if self.config[INTENT_CLASSIFICATION]: (_, self.all_labels_embed) = self._create_all_labels()
def batch_predict(self, batch_in: Union[(Tuple[tf.Tensor], Tuple[np.ndarray])]) -> Dict[(Text, tf.Tensor)]: 'Predicts the output of the given batch.\n\n Args:\n batch_in: The batch.\n\n Returns:\n The output to predict.\n ' tf_batch_data = self.batch_to_model_data_form...
1,617,009,859,647,779,300
Predicts the output of the given batch. Args: batch_in: The batch. Returns: The output to predict.
rasa/nlu/classifiers/diet_classifier.py
batch_predict
Adarshsng/rasa
python
def batch_predict(self, batch_in: Union[(Tuple[tf.Tensor], Tuple[np.ndarray])]) -> Dict[(Text, tf.Tensor)]: 'Predicts the output of the given batch.\n\n Args:\n batch_in: The batch.\n\n Returns:\n The output to predict.\n ' tf_batch_data = self.batch_to_model_data_form...
def _create_dictionary(self, document): 'Creates mapping key = word, value = row index' words = map(self.normalize_word, document.words) unique_words = frozenset((self.stem_word(w) for w in words if (w not in self._stop_words))) return dict(((w, i) for (i, w) in enumerate(unique_words)))
2,916,173,340,952,540,000
Creates mapping key = word, value = row index
util_common/nlp/Sumy/summarizers/lsa.py
_create_dictionary
Sohone-Guo/Pointer-Generator
python
def _create_dictionary(self, document): words = map(self.normalize_word, document.words) unique_words = frozenset((self.stem_word(w) for w in words if (w not in self._stop_words))) return dict(((w, i) for (i, w) in enumerate(unique_words)))
def _create_matrix(self, document, dictionary): '\n Creates matrix of shape |unique words|×|sentences| where cells\n contains number of occurences of words (rows) in senteces (cols).\n ' sentences = document.sentences words_count = len(dictionary) sentences_count = len(sentences) ...
-3,011,865,140,669,539,300
Creates matrix of shape |unique words|×|sentences| where cells contains number of occurences of words (rows) in senteces (cols).
util_common/nlp/Sumy/summarizers/lsa.py
_create_matrix
Sohone-Guo/Pointer-Generator
python
def _create_matrix(self, document, dictionary): '\n Creates matrix of shape |unique words|×|sentences| where cells\n contains number of occurences of words (rows) in senteces (cols).\n ' sentences = document.sentences words_count = len(dictionary) sentences_count = len(sentences) ...
def _compute_term_frequency(self, matrix, smooth=0.4): '\n Computes TF metrics for each sentence (column) in the given matrix.\n You can read more about smoothing parameter at URL below:\n http://nlp.stanford.edu/IR-book/html/htmledition/maximum-tf-normalization-1.html\n ' assert (0....
1,475,393,266,677,919,200
Computes TF metrics for each sentence (column) in the given matrix. You can read more about smoothing parameter at URL below: http://nlp.stanford.edu/IR-book/html/htmledition/maximum-tf-normalization-1.html
util_common/nlp/Sumy/summarizers/lsa.py
_compute_term_frequency
Sohone-Guo/Pointer-Generator
python
def _compute_term_frequency(self, matrix, smooth=0.4): '\n Computes TF metrics for each sentence (column) in the given matrix.\n You can read more about smoothing parameter at URL below:\n http://nlp.stanford.edu/IR-book/html/htmledition/maximum-tf-normalization-1.html\n ' assert (0....
@skipIfReproducer def test_read_memory(self): 'Test Python SBProcess.ReadMemory() API.' self.build() exe = self.getBuildArtifact('a.out') target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) breakpoint = target.BreakpointCreateByLocation('main.cpp', self.line) self.asser...
-3,021,106,652,205,118,500
Test Python SBProcess.ReadMemory() API.
lldb/test/API/python_api/process/TestProcessAPI.py
test_read_memory
AaronBallman/llvm
python
@skipIfReproducer def test_read_memory(self): self.build() exe = self.getBuildArtifact('a.out') target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) breakpoint = target.BreakpointCreateByLocation('main.cpp', self.line) self.assertTrue(breakpoint, VALID_BREAKPOINT) p...
@skipIfReproducer def test_write_memory(self): 'Test Python SBProcess.WriteMemory() API.' self.build() exe = self.getBuildArtifact('a.out') target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) breakpoint = target.BreakpointCreateByLocation('main.cpp', self.line) self.ass...
-1,242,185,819,707,027,200
Test Python SBProcess.WriteMemory() API.
lldb/test/API/python_api/process/TestProcessAPI.py
test_write_memory
AaronBallman/llvm
python
@skipIfReproducer def test_write_memory(self): self.build() exe = self.getBuildArtifact('a.out') target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) breakpoint = target.BreakpointCreateByLocation('main.cpp', self.line) self.assertTrue(breakpoint, VALID_BREAKPOINT) ...
@skipIfReproducer def test_access_my_int(self): "Test access 'my_int' using Python SBProcess.GetByteOrder() and other APIs." self.build() exe = self.getBuildArtifact('a.out') target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) breakpoint = target.BreakpointCreateByLocation(...
2,923,101,617,713,456,000
Test access 'my_int' using Python SBProcess.GetByteOrder() and other APIs.
lldb/test/API/python_api/process/TestProcessAPI.py
test_access_my_int
AaronBallman/llvm
python
@skipIfReproducer def test_access_my_int(self): self.build() exe = self.getBuildArtifact('a.out') target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) breakpoint = target.BreakpointCreateByLocation('main.cpp', self.line) self.assertTrue(breakpoint, VALID_BREAKPOINT) ...
def test_remote_launch(self): 'Test SBProcess.RemoteLaunch() API with a process not in eStateConnected, and it should fail.' self.build() exe = self.getBuildArtifact('a.out') target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) process = target.LaunchSimple(None, None, self....
323,723,085,478,817,100
Test SBProcess.RemoteLaunch() API with a process not in eStateConnected, and it should fail.
lldb/test/API/python_api/process/TestProcessAPI.py
test_remote_launch
AaronBallman/llvm
python
def test_remote_launch(self): self.build() exe = self.getBuildArtifact('a.out') target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) process = target.LaunchSimple(None, None, self.get_process_working_directory()) if self.TraceOn(): print('process state:', state_...
def test_get_num_supported_hardware_watchpoints(self): 'Test SBProcess.GetNumSupportedHardwareWatchpoints() API with a process.' self.build() exe = self.getBuildArtifact('a.out') self.runCmd(('file ' + exe), CURRENT_EXECUTABLE_SET) target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALI...
-8,014,264,649,563,344,000
Test SBProcess.GetNumSupportedHardwareWatchpoints() API with a process.
lldb/test/API/python_api/process/TestProcessAPI.py
test_get_num_supported_hardware_watchpoints
AaronBallman/llvm
python
def test_get_num_supported_hardware_watchpoints(self): self.build() exe = self.getBuildArtifact('a.out') self.runCmd(('file ' + exe), CURRENT_EXECUTABLE_SET) target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) breakpoint = target.BreakpointCreateByLocation('main.cpp', ...
@no_debug_info_test def test_get_process_info(self): 'Test SBProcess::GetProcessInfo() API with a locally launched process.' self.build() exe = self.getBuildArtifact('a.out') self.runCmd(('file ' + exe), CURRENT_EXECUTABLE_SET) target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TA...
7,278,161,170,177,846,000
Test SBProcess::GetProcessInfo() API with a locally launched process.
lldb/test/API/python_api/process/TestProcessAPI.py
test_get_process_info
AaronBallman/llvm
python
@no_debug_info_test def test_get_process_info(self): self.build() exe = self.getBuildArtifact('a.out') self.runCmd(('file ' + exe), CURRENT_EXECUTABLE_SET) target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) launch_info = target.GetLaunchInfo() launch_info.SetWorki...
def test_allocate_deallocate_memory(self): 'Test Python SBProcess.AllocateMemory() and SBProcess.DeallocateMemory() APIs.' self.build() (target, process, main_thread, main_breakpoint) = lldbutil.run_to_source_breakpoint(self, '// Set break point at this line', lldb.SBFileSpec('main.cpp')) error = lldb.S...
-1,831,053,923,018,552,000
Test Python SBProcess.AllocateMemory() and SBProcess.DeallocateMemory() APIs.
lldb/test/API/python_api/process/TestProcessAPI.py
test_allocate_deallocate_memory
AaronBallman/llvm
python
def test_allocate_deallocate_memory(self): self.build() (target, process, main_thread, main_breakpoint) = lldbutil.run_to_source_breakpoint(self, '// Set break point at this line', lldb.SBFileSpec('main.cpp')) error = lldb.SBError() addr = process.AllocateMemory(16384, lldb.ePermissionsReadable, er...
def plot_gll(x, y, z): ' Plots values on 2D unstructured GLL mesh\n ' r = ((max(x) - min(x)) / (max(y) - min(y))) rx = (r / np.sqrt((1 + (r ** 2)))) ry = (1 / np.sqrt((1 + (r ** 2)))) f = plt.figure(figsize=((10 * rx), (10 * ry))) p = plt.tricontourf(x, y, z, 125) plt.axis('image') re...
-6,270,445,130,626,942,000
Plots values on 2D unstructured GLL mesh
seisflows/tools/graphics.py
plot_gll
fanwu8/SeisFlowsQ
python
def plot_gll(x, y, z): ' \n ' r = ((max(x) - min(x)) / (max(y) - min(y))) rx = (r / np.sqrt((1 + (r ** 2)))) ry = (1 / np.sqrt((1 + (r ** 2)))) f = plt.figure(figsize=((10 * rx), (10 * ry))) p = plt.tricontourf(x, y, z, 125) plt.axis('image') return (f, p)
def plot_vector(t, v, xlabel='', ylabel='', title=''): ' Plots a vector or time series.\n\n Parameters\n ----------\n v: ndarray, ndims = 1/2\n Vector or time series to plot\n xlabel: str\n x axis label\n ylabel: str\n y axis label\n title: str\n plot title\n\n Raise...
8,343,828,763,393,565,000
Plots a vector or time series. Parameters ---------- v: ndarray, ndims = 1/2 Vector or time series to plot xlabel: str x axis label ylabel: str y axis label title: str plot title Raises ------ ValueError If dimensions of v are greater than 2
seisflows/tools/graphics.py
plot_vector
fanwu8/SeisFlowsQ
python
def plot_vector(t, v, xlabel=, ylabel=, title=): ' Plots a vector or time series.\n\n Parameters\n ----------\n v: ndarray, ndims = 1/2\n Vector or time series to plot\n xlabel: str\n x axis label\n ylabel: str\n y axis label\n title: str\n plot title\n\n Raises\n ...
def plot_section(stream, ax=None, cmap='seismic', clip=100, title='', x_interval=1.0, y_interval=1.0): ' Plots a seismic section from an obspy stream.\n\n Parameters\n ----------\n stream: Obspy stream object\n Obspy stream object created from a SU data file\n ax: Matplotlib Axes object\n ...
-203,811,772,725,341,600
Plots a seismic section from an obspy stream. Parameters ---------- stream: Obspy stream object Obspy stream object created from a SU data file ax: Matplotlib Axes object Optional axis object cmap: str Matplotlib colormap option. clip: float Percentage value (0-100) for amplitude clipping title: str ...
seisflows/tools/graphics.py
plot_section
fanwu8/SeisFlowsQ
python
def plot_section(stream, ax=None, cmap='seismic', clip=100, title=, x_interval=1.0, y_interval=1.0): ' Plots a seismic section from an obspy stream.\n\n Parameters\n ----------\n stream: Obspy stream object\n Obspy stream object created from a SU data file\n ax: Matplotlib Axes object\n O...
def _convert_to_array(stream): ' Extracts trace data from an obspy stream and returns a 2D array.\n\n Parameters\n ----------\n stream: Obspy stream object\n Stream storing trace data\n\n Returns\n -------\n output: ndarray, ndim=2\n Returns an (nt*nr) array. nt and nr are the number...
5,514,239,679,669,107,000
Extracts trace data from an obspy stream and returns a 2D array. Parameters ---------- stream: Obspy stream object Stream storing trace data Returns ------- output: ndarray, ndim=2 Returns an (nt*nr) array. nt and nr are the number of sample points and number of traces respectively. Assumes trace lengths ...
seisflows/tools/graphics.py
_convert_to_array
fanwu8/SeisFlowsQ
python
def _convert_to_array(stream): ' Extracts trace data from an obspy stream and returns a 2D array.\n\n Parameters\n ----------\n stream: Obspy stream object\n Stream storing trace data\n\n Returns\n -------\n output: ndarray, ndim=2\n Returns an (nt*nr) array. nt and nr are the number...
def _cscale(v, clip=100): ' Return limits for colormap.\n ' perc = (clip / 100.0) return (((- perc) * abs(v).max()), (perc * abs(v).max()))
1,486,020,659,555,331,300
Return limits for colormap.
seisflows/tools/graphics.py
_cscale
fanwu8/SeisFlowsQ
python
def _cscale(v, clip=100): ' \n ' perc = (clip / 100.0) return (((- perc) * abs(v).max()), (perc * abs(v).max()))
def _get_time(stream): ' Get fixed time vector for stream object.\n ' dt = stream[0].stats.delta nt = len(stream[0].data) return np.arange(0, (nt * dt), dt)
3,518,869,647,590,698,500
Get fixed time vector for stream object.
seisflows/tools/graphics.py
_get_time
fanwu8/SeisFlowsQ
python
def _get_time(stream): ' \n ' dt = stream[0].stats.delta nt = len(stream[0].data) return np.arange(0, (nt * dt), dt)
def _get_offsets(stream): ' Return offsets.\n ' nr = len(stream) offsets = np.zeros(nr) scalco = stream[0].stats.su.trace_header.scalar_to_be_applied_to_all_coordinates if (scalco == 0): scalco = 0.001 else: scalco = (0.001 / scalco) for (i, tr) in enumerate(stream): ...
8,875,202,697,701,741,000
Return offsets.
seisflows/tools/graphics.py
_get_offsets
fanwu8/SeisFlowsQ
python
def _get_offsets(stream): ' \n ' nr = len(stream) offsets = np.zeros(nr) scalco = stream[0].stats.su.trace_header.scalar_to_be_applied_to_all_coordinates if (scalco == 0): scalco = 0.001 else: scalco = (0.001 / scalco) for (i, tr) in enumerate(stream): offsets[i] =...
def get_regular_ticks(v, interval): ' Returns regular tick intervals.\n ' f = interp1d(v, list(range(len(v)))) begin = (int((v[0] / interval)) * interval) end = v[(- 1)] tick_labels = np.arange(begin, end, interval) ticks = f(tick_labels) return (ticks, tick_labels)
-4,995,927,191,784,999,000
Returns regular tick intervals.
seisflows/tools/graphics.py
get_regular_ticks
fanwu8/SeisFlowsQ
python
def get_regular_ticks(v, interval): ' \n ' f = interp1d(v, list(range(len(v)))) begin = (int((v[0] / interval)) * interval) end = v[(- 1)] tick_labels = np.arange(begin, end, interval) ticks = f(tick_labels) return (ticks, tick_labels)
def generate_kernel_pod_yaml(keywords): 'Return the kubernetes pod spec as a yaml string.\n\n - load jinja2 template from this file directory.\n - substitute template variables with keywords items.\n ' j_env = Environment(loader=FileSystemLoader(os.path.dirname(__file__)), trim_blocks=True, lstrip_bloc...
5,852,460,280,651,974,000
Return the kubernetes pod spec as a yaml string. - load jinja2 template from this file directory. - substitute template variables with keywords items.
tools/kernelspecs/kernels/R_kubernetes/scripts/launch_kubernetes.py
generate_kernel_pod_yaml
spotinst/wave-operator
python
def generate_kernel_pod_yaml(keywords): 'Return the kubernetes pod spec as a yaml string.\n\n - load jinja2 template from this file directory.\n - substitute template variables with keywords items.\n ' j_env = Environment(loader=FileSystemLoader(os.path.dirname(__file__)), trim_blocks=True, lstrip_bloc...
def error_run(arguments: list[str], message: bytes) -> None: 'Run command that should fail and check error message.' with Popen((['map-machine'] + arguments), stderr=PIPE) as pipe: (_, error) = pipe.communicate() assert (pipe.returncode != 0) assert (error == message)
8,372,083,281,896,209,000
Run command that should fail and check error message.
tests/test_command_line.py
error_run
LaoshuBaby/map-machine
python
def error_run(arguments: list[str], message: bytes) -> None: with Popen((['map-machine'] + arguments), stderr=PIPE) as pipe: (_, error) = pipe.communicate() assert (pipe.returncode != 0) assert (error == message)
def run(arguments: list[str], message: bytes) -> None: 'Run command that should fail and check error message.' with Popen((['map-machine'] + arguments), stderr=PIPE) as pipe: (_, error) = pipe.communicate() assert (pipe.returncode == 0) assert (error == message)
1,844,572,730,295,534,300
Run command that should fail and check error message.
tests/test_command_line.py
run
LaoshuBaby/map-machine
python
def run(arguments: list[str], message: bytes) -> None: with Popen((['map-machine'] + arguments), stderr=PIPE) as pipe: (_, error) = pipe.communicate() assert (pipe.returncode == 0) assert (error == message)
def test_wrong_render_arguments() -> None: 'Test `render` command with wrong arguments.' error_run(['render', '-z', '17'], b'CRITICAL Specify either --input, or --boundary-box, or --coordinates and --size.\n')
5,530,455,509,936,444,000
Test `render` command with wrong arguments.
tests/test_command_line.py
test_wrong_render_arguments
LaoshuBaby/map-machine
python
def test_wrong_render_arguments() -> None: error_run(['render', '-z', '17'], b'CRITICAL Specify either --input, or --boundary-box, or --coordinates and --size.\n')
def test_render() -> None: 'Test `render` command.' run((COMMAND_LINES['render'] + ['--cache', 'tests/data']), (LOG + b'INFO Writing output SVG to out/map.svg...\n')) with Path('out/map.svg').open(encoding='utf-8') as output_file: root: Element = ElementTree.parse(output_file).getroot() assert (...
-8,102,067,962,734,609,000
Test `render` command.
tests/test_command_line.py
test_render
LaoshuBaby/map-machine
python
def test_render() -> None: run((COMMAND_LINES['render'] + ['--cache', 'tests/data']), (LOG + b'INFO Writing output SVG to out/map.svg...\n')) with Path('out/map.svg').open(encoding='utf-8') as output_file: root: Element = ElementTree.parse(output_file).getroot() assert (len(root) == 8) asse...
def test_render_with_tooltips() -> None: 'Test `render` command.' run((COMMAND_LINES['render_with_tooltips'] + ['--cache', 'tests/data']), (LOG + b'INFO Writing output SVG to out/map.svg...\n')) with Path('out/map.svg').open(encoding='utf-8') as output_file: root: Element = ElementTree.parse(output_...
-3,097,467,188,967,107,000
Test `render` command.
tests/test_command_line.py
test_render_with_tooltips
LaoshuBaby/map-machine
python
def test_render_with_tooltips() -> None: run((COMMAND_LINES['render_with_tooltips'] + ['--cache', 'tests/data']), (LOG + b'INFO Writing output SVG to out/map.svg...\n')) with Path('out/map.svg').open(encoding='utf-8') as output_file: root: Element = ElementTree.parse(output_file).getroot() asse...
def test_icons() -> None: 'Test `icons` command.' run(COMMAND_LINES['icons'], b'INFO Icons are written to out/icons_by_name and out/icons_by_id.\nINFO Icon grid is written to out/icon_grid.svg.\nINFO Icon grid is written to doc/grid.svg.\n') assert (Path('out') / 'icon_grid.svg').is_file() assert (Path(...
-1,171,357,103,594,110,700
Test `icons` command.
tests/test_command_line.py
test_icons
LaoshuBaby/map-machine
python
def test_icons() -> None: run(COMMAND_LINES['icons'], b'INFO Icons are written to out/icons_by_name and out/icons_by_id.\nINFO Icon grid is written to out/icon_grid.svg.\nINFO Icon grid is written to doc/grid.svg.\n') assert (Path('out') / 'icon_grid.svg').is_file() assert (Path('out') / 'icons_by_name...
def test_mapcss() -> None: 'Test `mapcss` command.' run(COMMAND_LINES['mapcss'], b'INFO MapCSS 0.2 scheme is written to out/map_machine_mapcss.\n') assert (Path('out') / 'map_machine_mapcss').is_dir() assert ((Path('out') / 'map_machine_mapcss') / 'icons').is_dir() assert (((Path('out') / 'map_machi...
-34,753,347,926,657,268
Test `mapcss` command.
tests/test_command_line.py
test_mapcss
LaoshuBaby/map-machine
python
def test_mapcss() -> None: run(COMMAND_LINES['mapcss'], b'INFO MapCSS 0.2 scheme is written to out/map_machine_mapcss.\n') assert (Path('out') / 'map_machine_mapcss').is_dir() assert ((Path('out') / 'map_machine_mapcss') / 'icons').is_dir() assert (((Path('out') / 'map_machine_mapcss') / 'icons') /...
def test_element() -> None: 'Test `element` command.' run(COMMAND_LINES['element'], b'INFO Element is written to out/element.svg.\n') assert (Path('out') / 'element.svg').is_file()
3,954,329,336,101,989,000
Test `element` command.
tests/test_command_line.py
test_element
LaoshuBaby/map-machine
python
def test_element() -> None: run(COMMAND_LINES['element'], b'INFO Element is written to out/element.svg.\n') assert (Path('out') / 'element.svg').is_file()
def test_tile() -> None: 'Test `tile` command.' run((COMMAND_LINES['tile'] + ['--cache', 'tests/data']), (LOG + b'INFO Tile is drawn to out/tiles/tile_18_160199_88904.svg.\nINFO SVG file is rasterized to out/tiles/tile_18_160199_88904.png.\n')) assert ((Path('out') / 'tiles') / 'tile_18_160199_88904.svg').i...
-5,938,328,673,918,745,000
Test `tile` command.
tests/test_command_line.py
test_tile
LaoshuBaby/map-machine
python
def test_tile() -> None: run((COMMAND_LINES['tile'] + ['--cache', 'tests/data']), (LOG + b'INFO Tile is drawn to out/tiles/tile_18_160199_88904.svg.\nINFO SVG file is rasterized to out/tiles/tile_18_160199_88904.png.\n')) assert ((Path('out') / 'tiles') / 'tile_18_160199_88904.svg').is_file() assert ((...
def run(path: str, output_file: str='', mongo=False) -> Union[(None, List[dict])]: 'Invoca o utilitário `isis2json` com os parâmetros adaptados para a\n leitura de arquivos MST de acordo com as definições padrões utilizadas\n pelo __main__ da ferramenta `isis2json`.\n\n O resultado de saída pode ser escrit...
5,417,742,210,112,840,000
Invoca o utilitário `isis2json` com os parâmetros adaptados para a leitura de arquivos MST de acordo com as definições padrões utilizadas pelo __main__ da ferramenta `isis2json`. O resultado de saída pode ser escrito diretamente para um arquivo em disco ou retornará uma lista contento as linhas passíveis de conversão ...
documentstore_migracao/utils/extract_isis.py
run
patymori/document-store-migracao
python
def run(path: str, output_file: str=, mongo=False) -> Union[(None, List[dict])]: 'Invoca o utilitário `isis2json` com os parâmetros adaptados para a\n leitura de arquivos MST de acordo com as definições padrões utilizadas\n pelo __main__ da ferramenta `isis2json`.\n\n O resultado de saída pode ser escrito ...
def __init__(__self__, *, host_account_names: pulumi.Input[Sequence[pulumi.Input[str]]], host_group_id: pulumi.Input[str], instance_id: pulumi.Input[str], user_group_id: pulumi.Input[str]): '\n The set of arguments for constructing a HostGroupAccountUserGroupAttachment resource.\n :param pulumi.Input[...
8,620,752,537,416,545,000
The set of arguments for constructing a HostGroupAccountUserGroupAttachment resource. :param pulumi.Input[Sequence[pulumi.Input[str]]] host_account_names: A list names of the host account. :param pulumi.Input[str] host_group_id: The ID of the host group. :param pulumi.Input[str] instance_id: The ID of the Bastionhost i...
sdk/python/pulumi_alicloud/bastionhost/host_group_account_user_group_attachment.py
__init__
pulumi/pulumi-alicloud
python
def __init__(__self__, *, host_account_names: pulumi.Input[Sequence[pulumi.Input[str]]], host_group_id: pulumi.Input[str], instance_id: pulumi.Input[str], user_group_id: pulumi.Input[str]): '\n The set of arguments for constructing a HostGroupAccountUserGroupAttachment resource.\n :param pulumi.Input[...
@property @pulumi.getter(name='hostAccountNames') def host_account_names(self) -> pulumi.Input[Sequence[pulumi.Input[str]]]: '\n A list names of the host account.\n ' return pulumi.get(self, 'host_account_names')
8,201,247,303,138,980,000
A list names of the host account.
sdk/python/pulumi_alicloud/bastionhost/host_group_account_user_group_attachment.py
host_account_names
pulumi/pulumi-alicloud
python
@property @pulumi.getter(name='hostAccountNames') def host_account_names(self) -> pulumi.Input[Sequence[pulumi.Input[str]]]: '\n \n ' return pulumi.get(self, 'host_account_names')
@property @pulumi.getter(name='hostGroupId') def host_group_id(self) -> pulumi.Input[str]: '\n The ID of the host group.\n ' return pulumi.get(self, 'host_group_id')
3,970,179,039,349,197,000
The ID of the host group.
sdk/python/pulumi_alicloud/bastionhost/host_group_account_user_group_attachment.py
host_group_id
pulumi/pulumi-alicloud
python
@property @pulumi.getter(name='hostGroupId') def host_group_id(self) -> pulumi.Input[str]: '\n \n ' return pulumi.get(self, 'host_group_id')
@property @pulumi.getter(name='instanceId') def instance_id(self) -> pulumi.Input[str]: '\n The ID of the Bastionhost instance where you want to authorize the user to manage the specified hosts and host accounts.\n ' return pulumi.get(self, 'instance_id')
-3,452,605,385,748,844,000
The ID of the Bastionhost instance where you want to authorize the user to manage the specified hosts and host accounts.
sdk/python/pulumi_alicloud/bastionhost/host_group_account_user_group_attachment.py
instance_id
pulumi/pulumi-alicloud
python
@property @pulumi.getter(name='instanceId') def instance_id(self) -> pulumi.Input[str]: '\n \n ' return pulumi.get(self, 'instance_id')
@property @pulumi.getter(name='userGroupId') def user_group_id(self) -> pulumi.Input[str]: '\n The ID of the user group that you want to authorize to manage the specified hosts and host accounts.\n ' return pulumi.get(self, 'user_group_id')
-8,345,498,789,096,243,000
The ID of the user group that you want to authorize to manage the specified hosts and host accounts.
sdk/python/pulumi_alicloud/bastionhost/host_group_account_user_group_attachment.py
user_group_id
pulumi/pulumi-alicloud
python
@property @pulumi.getter(name='userGroupId') def user_group_id(self) -> pulumi.Input[str]: '\n \n ' return pulumi.get(self, 'user_group_id')
def __init__(__self__, *, host_account_names: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]=None, host_group_id: Optional[pulumi.Input[str]]=None, instance_id: Optional[pulumi.Input[str]]=None, user_group_id: Optional[pulumi.Input[str]]=None): '\n Input properties used for looking up and filtering Host...
4,413,283,507,895,842,300
Input properties used for looking up and filtering HostGroupAccountUserGroupAttachment resources. :param pulumi.Input[Sequence[pulumi.Input[str]]] host_account_names: A list names of the host account. :param pulumi.Input[str] host_group_id: The ID of the host group. :param pulumi.Input[str] instance_id: The ID of the B...
sdk/python/pulumi_alicloud/bastionhost/host_group_account_user_group_attachment.py
__init__
pulumi/pulumi-alicloud
python
def __init__(__self__, *, host_account_names: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]=None, host_group_id: Optional[pulumi.Input[str]]=None, instance_id: Optional[pulumi.Input[str]]=None, user_group_id: Optional[pulumi.Input[str]]=None): '\n Input properties used for looking up and filtering Host...
@property @pulumi.getter(name='hostAccountNames') def host_account_names(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]: '\n A list names of the host account.\n ' return pulumi.get(self, 'host_account_names')
-6,218,258,946,766,746,000
A list names of the host account.
sdk/python/pulumi_alicloud/bastionhost/host_group_account_user_group_attachment.py
host_account_names
pulumi/pulumi-alicloud
python
@property @pulumi.getter(name='hostAccountNames') def host_account_names(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]: '\n \n ' return pulumi.get(self, 'host_account_names')
@property @pulumi.getter(name='hostGroupId') def host_group_id(self) -> Optional[pulumi.Input[str]]: '\n The ID of the host group.\n ' return pulumi.get(self, 'host_group_id')
-1,706,495,266,037,631,500
The ID of the host group.
sdk/python/pulumi_alicloud/bastionhost/host_group_account_user_group_attachment.py
host_group_id
pulumi/pulumi-alicloud
python
@property @pulumi.getter(name='hostGroupId') def host_group_id(self) -> Optional[pulumi.Input[str]]: '\n \n ' return pulumi.get(self, 'host_group_id')
@property @pulumi.getter(name='instanceId') def instance_id(self) -> Optional[pulumi.Input[str]]: '\n The ID of the Bastionhost instance where you want to authorize the user to manage the specified hosts and host accounts.\n ' return pulumi.get(self, 'instance_id')
1,680,588,397,272,546,600
The ID of the Bastionhost instance where you want to authorize the user to manage the specified hosts and host accounts.
sdk/python/pulumi_alicloud/bastionhost/host_group_account_user_group_attachment.py
instance_id
pulumi/pulumi-alicloud
python
@property @pulumi.getter(name='instanceId') def instance_id(self) -> Optional[pulumi.Input[str]]: '\n \n ' return pulumi.get(self, 'instance_id')
@property @pulumi.getter(name='userGroupId') def user_group_id(self) -> Optional[pulumi.Input[str]]: '\n The ID of the user group that you want to authorize to manage the specified hosts and host accounts.\n ' return pulumi.get(self, 'user_group_id')
-1,121,814,425,541,299,700
The ID of the user group that you want to authorize to manage the specified hosts and host accounts.
sdk/python/pulumi_alicloud/bastionhost/host_group_account_user_group_attachment.py
user_group_id
pulumi/pulumi-alicloud
python
@property @pulumi.getter(name='userGroupId') def user_group_id(self) -> Optional[pulumi.Input[str]]: '\n \n ' return pulumi.get(self, 'user_group_id')
@overload def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions]=None, host_account_names: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]=None, host_group_id: Optional[pulumi.Input[str]]=None, instance_id: Optional[pulumi.Input[str]]=None, user_group_id: Optional[pulumi.Input[str]]=None,...
8,111,317,736,864,197,000
Provides a Bastion Host Host Account Attachment resource to add list host accounts into one user group and one host group. > **NOTE:** Available in v1.135.0+. ## Example Usage Basic Usage ```python import pulumi import pulumi_alicloud as alicloud default_host = alicloud.bastionhost.Host("defaultHost", instance...
sdk/python/pulumi_alicloud/bastionhost/host_group_account_user_group_attachment.py
__init__
pulumi/pulumi-alicloud
python
@overload def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions]=None, host_account_names: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]=None, host_group_id: Optional[pulumi.Input[str]]=None, instance_id: Optional[pulumi.Input[str]]=None, user_group_id: Optional[pulumi.Input[str]]=None,...
@overload def __init__(__self__, resource_name: str, args: HostGroupAccountUserGroupAttachmentArgs, opts: Optional[pulumi.ResourceOptions]=None): '\n Provides a Bastion Host Host Account Attachment resource to add list host accounts into one user group and one host group.\n\n > **NOTE:** Available in ...
8,345,629,500,227,280,000
Provides a Bastion Host Host Account Attachment resource to add list host accounts into one user group and one host group. > **NOTE:** Available in v1.135.0+. ## Example Usage Basic Usage ```python import pulumi import pulumi_alicloud as alicloud default_host = alicloud.bastionhost.Host("defaultHost", instance...
sdk/python/pulumi_alicloud/bastionhost/host_group_account_user_group_attachment.py
__init__
pulumi/pulumi-alicloud
python
@overload def __init__(__self__, resource_name: str, args: HostGroupAccountUserGroupAttachmentArgs, opts: Optional[pulumi.ResourceOptions]=None): '\n Provides a Bastion Host Host Account Attachment resource to add list host accounts into one user group and one host group.\n\n > **NOTE:** Available in ...
@staticmethod def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions]=None, host_account_names: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]=None, host_group_id: Optional[pulumi.Input[str]]=None, instance_id: Optional[pulumi.Input[str]]=None, user_group_id: Optional[pulumi.Input...
-4,569,158,122,378,688,500
Get an existing HostGroupAccountUserGroupAttachment resource's state with the given name, id, and optional extra properties used to qualify the lookup. :param str resource_name: The unique name of the resulting resource. :param pulumi.Input[str] id: The unique provider ID of the resource to lookup. :param pulumi.Resou...
sdk/python/pulumi_alicloud/bastionhost/host_group_account_user_group_attachment.py
get
pulumi/pulumi-alicloud
python
@staticmethod def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions]=None, host_account_names: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]=None, host_group_id: Optional[pulumi.Input[str]]=None, instance_id: Optional[pulumi.Input[str]]=None, user_group_id: Optional[pulumi.Input...
@property @pulumi.getter(name='hostAccountNames') def host_account_names(self) -> pulumi.Output[Sequence[str]]: '\n A list names of the host account.\n ' return pulumi.get(self, 'host_account_names')
8,301,108,355,006,178,000
A list names of the host account.
sdk/python/pulumi_alicloud/bastionhost/host_group_account_user_group_attachment.py
host_account_names
pulumi/pulumi-alicloud
python
@property @pulumi.getter(name='hostAccountNames') def host_account_names(self) -> pulumi.Output[Sequence[str]]: '\n \n ' return pulumi.get(self, 'host_account_names')
@property @pulumi.getter(name='hostGroupId') def host_group_id(self) -> pulumi.Output[str]: '\n The ID of the host group.\n ' return pulumi.get(self, 'host_group_id')
-2,142,794,302,333,448,700
The ID of the host group.
sdk/python/pulumi_alicloud/bastionhost/host_group_account_user_group_attachment.py
host_group_id
pulumi/pulumi-alicloud
python
@property @pulumi.getter(name='hostGroupId') def host_group_id(self) -> pulumi.Output[str]: '\n \n ' return pulumi.get(self, 'host_group_id')
@property @pulumi.getter(name='instanceId') def instance_id(self) -> pulumi.Output[str]: '\n The ID of the Bastionhost instance where you want to authorize the user to manage the specified hosts and host accounts.\n ' return pulumi.get(self, 'instance_id')
6,237,722,831,590,990,000
The ID of the Bastionhost instance where you want to authorize the user to manage the specified hosts and host accounts.
sdk/python/pulumi_alicloud/bastionhost/host_group_account_user_group_attachment.py
instance_id
pulumi/pulumi-alicloud
python
@property @pulumi.getter(name='instanceId') def instance_id(self) -> pulumi.Output[str]: '\n \n ' return pulumi.get(self, 'instance_id')
@property @pulumi.getter(name='userGroupId') def user_group_id(self) -> pulumi.Output[str]: '\n The ID of the user group that you want to authorize to manage the specified hosts and host accounts.\n ' return pulumi.get(self, 'user_group_id')
-7,346,775,687,300,818,000
The ID of the user group that you want to authorize to manage the specified hosts and host accounts.
sdk/python/pulumi_alicloud/bastionhost/host_group_account_user_group_attachment.py
user_group_id
pulumi/pulumi-alicloud
python
@property @pulumi.getter(name='userGroupId') def user_group_id(self) -> pulumi.Output[str]: '\n \n ' return pulumi.get(self, 'user_group_id')
def is_start_piece(piece): 'Check if the current word piece is the starting piece (BERT).' return (not piece.startswith('##'))
6,410,489,472,930,046,000
Check if the current word piece is the starting piece (BERT).
libai/data/datasets/bert_dataset.py
is_start_piece
Oneflow-Inc/libai
python
def is_start_piece(piece): return (not piece.startswith('##'))
def truncate_seq_pair(self, tokens_a, tokens_b, max_num_tokens, np_rng): 'Truncate sequence pair to a maximum sequence length.' (len_a, len_b) = (len(tokens_a), len(tokens_b)) while True: total_length = (len_a + len_b) if (total_length <= max_num_tokens): break if (len_a ...
-3,613,704,199,210,650,000
Truncate sequence pair to a maximum sequence length.
libai/data/datasets/bert_dataset.py
truncate_seq_pair
Oneflow-Inc/libai
python
def truncate_seq_pair(self, tokens_a, tokens_b, max_num_tokens, np_rng): (len_a, len_b) = (len(tokens_a), len(tokens_b)) while True: total_length = (len_a + len_b) if (total_length <= max_num_tokens): break if (len_a > len_b): trunc_tokens = tokens_a ...
def create_tokens_and_token_types(self, tokens_a, tokens_b): 'Merge segments A and B, add [CLS] and [SEP] and build token types.' tokens = (([self.cls_id] + tokens_a) + [self.sep_id]) token_types = ([0] * (len(tokens_a) + 2)) if (len(tokens_b) > 0): tokens = ((tokens + tokens_b) + [self.sep_id])...
-7,094,127,822,114,704,000
Merge segments A and B, add [CLS] and [SEP] and build token types.
libai/data/datasets/bert_dataset.py
create_tokens_and_token_types
Oneflow-Inc/libai
python
def create_tokens_and_token_types(self, tokens_a, tokens_b): tokens = (([self.cls_id] + tokens_a) + [self.sep_id]) token_types = ([0] * (len(tokens_a) + 2)) if (len(tokens_b) > 0): tokens = ((tokens + tokens_b) + [self.sep_id]) token_types = (token_types + ([1] * (len(tokens_b) + 1))) ...
def mask_token(self, idx, tokens, np_rng): '\n Helper function to mask `idx` token from `tokens` according to\n section 3.3.1 of https://arxiv.org/pdf/1810.04805.pdf\n ' label = tokens[idx] if (np_rng.random() < 0.8): new_label = self.mask_id elif (np_rng.random() < 0.5): ...
5,268,266,264,196,588,000
Helper function to mask `idx` token from `tokens` according to section 3.3.1 of https://arxiv.org/pdf/1810.04805.pdf
libai/data/datasets/bert_dataset.py
mask_token
Oneflow-Inc/libai
python
def mask_token(self, idx, tokens, np_rng): '\n Helper function to mask `idx` token from `tokens` according to\n section 3.3.1 of https://arxiv.org/pdf/1810.04805.pdf\n ' label = tokens[idx] if (np_rng.random() < 0.8): new_label = self.mask_id elif (np_rng.random() < 0.5): ...
def create_masked_lm_predictions(self, tokens, np_rng, max_ngrams=3, do_whole_word_mask=True, favor_longer_ngram=False, geometric_dist=False): 'Creates the predictions for the masked LM objective.\n Note: Tokens here are vocab ids and not text tokens.' cand_indexes = [] token_boundary = ([0] * len(to...
-3,165,146,543,570,706,400
Creates the predictions for the masked LM objective. Note: Tokens here are vocab ids and not text tokens.
libai/data/datasets/bert_dataset.py
create_masked_lm_predictions
Oneflow-Inc/libai
python
def create_masked_lm_predictions(self, tokens, np_rng, max_ngrams=3, do_whole_word_mask=True, favor_longer_ngram=False, geometric_dist=False): 'Creates the predictions for the masked LM objective.\n Note: Tokens here are vocab ids and not text tokens.' cand_indexes = [] token_boundary = ([0] * len(to...
def pad_and_convert_to_tensor(self, tokens, token_types, masked_positions, masked_labels): 'Pad sequences and convert them to tensor.' num_tokens = len(tokens) num_pad = (self.max_seq_length - num_tokens) assert (num_pad >= 0) assert (len(token_types) == num_tokens) assert (len(masked_positions)...
-7,624,780,470,859,637,000
Pad sequences and convert them to tensor.
libai/data/datasets/bert_dataset.py
pad_and_convert_to_tensor
Oneflow-Inc/libai
python
def pad_and_convert_to_tensor(self, tokens, token_types, masked_positions, masked_labels): num_tokens = len(tokens) num_pad = (self.max_seq_length - num_tokens) assert (num_pad >= 0) assert (len(token_types) == num_tokens) assert (len(masked_positions) == len(masked_labels)) filler = ([self...
def escape(s): '\n Do the standard xml escapes, and replace newlines and tabs.\n ' return saxutils.escape(s, {'\n': '<br />', '\t': '&nbsp;&nbsp;&nbsp;&nbsp;'})
776,089,565,378,620,500
Do the standard xml escapes, and replace newlines and tabs.
leo/plugins/leowapp.py
escape
Anu082000/leo-editor
python
def escape(s): '\n \n ' return saxutils.escape(s, {'\n': '<br />', '\t': '&nbsp;&nbsp;&nbsp;&nbsp;'})
def init(): 'Return True if the plugin has loaded successfully.' if (not websockets): return False g.plugin_signon(__name__) return True
1,146,193,736,146,613,200
Return True if the plugin has loaded successfully.
leo/plugins/leowapp.py
init
Anu082000/leo-editor
python
def init(): if (not websockets): return False g.plugin_signon(__name__) return True
def __getattr__(self, attr): 'Handle an missing attribute.' if (attr in ('frameFactory', 'set_minibuffer_label')): raise AttributeError return self.message(attr)
-3,310,694,605,964,671,000
Handle an missing attribute.
leo/plugins/leowapp.py
__getattr__
Anu082000/leo-editor
python
def __getattr__(self, attr): if (attr in ('frameFactory', 'set_minibuffer_label')): raise AttributeError return self.message(attr)
def message(self, func): '\n Send a message to the framework.\n ' g.trace('=====', func, g.callers())
1,021,533,959,370,079,700
Send a message to the framework.
leo/plugins/leowapp.py
message
Anu082000/leo-editor
python
def message(self, func): '\n \n ' g.trace('=====', func, g.callers())