body_hash
stringlengths
64
64
body
stringlengths
23
109k
docstring
stringlengths
1
57k
path
stringlengths
4
198
name
stringlengths
1
115
repository_name
stringlengths
7
111
repository_stars
float64
0
191k
lang
stringclasses
1 value
body_without_docstring
stringlengths
14
108k
unified
stringlengths
45
133k
7f540c8e0b628f358d4ee247631ba313c40dd5bce54ea74af917367b765b7c15
async def _request_action_from_user(predictions: List[Dict[(Text, Any)]], sender_id: Text, endpoint: EndpointConfig) -> (Text, bool): 'Ask the user to correct an action prediction.' (await _print_history(sender_id, endpoint)) choices = [{'name': '{:03.2f} {:40}'.format(a.get('score'), a.get('action')), 'value': a.get('action')} for a in predictions] choices = ([{'name': '<create new action>', 'value': OTHER_ACTION}] + choices) question = questionary.select('What is the next action of the bot?', choices) action_name = (await _ask_questions(question, sender_id, endpoint)) is_new_action = (action_name == OTHER_ACTION) if is_new_action: action_name = (await _request_free_text_action(sender_id, endpoint)) print('Thanks! The bot will now run {}.\n'.format(action_name)) return (action_name, is_new_action)
Ask the user to correct an action prediction.
rasa/core/training/interactive.py
_request_action_from_user
LaudateCorpus1/rasa_core
2,433
python
async def _request_action_from_user(predictions: List[Dict[(Text, Any)]], sender_id: Text, endpoint: EndpointConfig) -> (Text, bool): (await _print_history(sender_id, endpoint)) choices = [{'name': '{:03.2f} {:40}'.format(a.get('score'), a.get('action')), 'value': a.get('action')} for a in predictions] choices = ([{'name': '<create new action>', 'value': OTHER_ACTION}] + choices) question = questionary.select('What is the next action of the bot?', choices) action_name = (await _ask_questions(question, sender_id, endpoint)) is_new_action = (action_name == OTHER_ACTION) if is_new_action: action_name = (await _request_free_text_action(sender_id, endpoint)) print('Thanks! The bot will now run {}.\n'.format(action_name)) return (action_name, is_new_action)
async def _request_action_from_user(predictions: List[Dict[(Text, Any)]], sender_id: Text, endpoint: EndpointConfig) -> (Text, bool): (await _print_history(sender_id, endpoint)) choices = [{'name': '{:03.2f} {:40}'.format(a.get('score'), a.get('action')), 'value': a.get('action')} for a in predictions] choices = ([{'name': '<create new action>', 'value': OTHER_ACTION}] + choices) question = questionary.select('What is the next action of the bot?', choices) action_name = (await _ask_questions(question, sender_id, endpoint)) is_new_action = (action_name == OTHER_ACTION) if is_new_action: action_name = (await _request_free_text_action(sender_id, endpoint)) print('Thanks! The bot will now run {}.\n'.format(action_name)) return (action_name, is_new_action)<|docstring|>Ask the user to correct an action prediction.<|endoftext|>
d09f00a2cdce3b62ea688f2539efd55e3769692f55e867d55495fd07c384c16e
def _request_export_info() -> Tuple[(Text, Text, Text)]: 'Request file path and export stories & nlu data to that path' questions = questionary.form(export_stories=questionary.text(message='Export stories to (if file exists, this will append the stories)', default=PATHS['stories']), export_nlu=questionary.text(message='Export NLU data to (if file exists, this will merge learned data with previous training examples)', default=PATHS['nlu']), export_domain=questionary.text(message='Export domain file to (if file exists, this will be overwritten)', default=PATHS['domain'])) answers = questions.ask() if (not answers): raise Abort() return (answers['export_stories'], answers['export_nlu'], answers['export_domain'])
Request file path and export stories & nlu data to that path
rasa/core/training/interactive.py
_request_export_info
LaudateCorpus1/rasa_core
2,433
python
def _request_export_info() -> Tuple[(Text, Text, Text)]: questions = questionary.form(export_stories=questionary.text(message='Export stories to (if file exists, this will append the stories)', default=PATHS['stories']), export_nlu=questionary.text(message='Export NLU data to (if file exists, this will merge learned data with previous training examples)', default=PATHS['nlu']), export_domain=questionary.text(message='Export domain file to (if file exists, this will be overwritten)', default=PATHS['domain'])) answers = questions.ask() if (not answers): raise Abort() return (answers['export_stories'], answers['export_nlu'], answers['export_domain'])
def _request_export_info() -> Tuple[(Text, Text, Text)]: questions = questionary.form(export_stories=questionary.text(message='Export stories to (if file exists, this will append the stories)', default=PATHS['stories']), export_nlu=questionary.text(message='Export NLU data to (if file exists, this will merge learned data with previous training examples)', default=PATHS['nlu']), export_domain=questionary.text(message='Export domain file to (if file exists, this will be overwritten)', default=PATHS['domain'])) answers = questions.ask() if (not answers): raise Abort() return (answers['export_stories'], answers['export_nlu'], answers['export_domain'])<|docstring|>Request file path and export stories & nlu data to that path<|endoftext|>
9a30ad29c4a0e46ef15fd3b582c61902dec517ed106884be649907a69ab25e2d
def _split_conversation_at_restarts(evts: List[Dict[(Text, Any)]]) -> List[List[Dict[(Text, Any)]]]: 'Split a conversation at restart events.\n\n Returns an array of event lists, without the restart events.' sub_conversations = [] current = [] for e in evts: if (e.get('event') == 'restart'): if current: sub_conversations.append(current) current = [] else: current.append(e) if current: sub_conversations.append(current) return sub_conversations
Split a conversation at restart events. Returns an array of event lists, without the restart events.
rasa/core/training/interactive.py
_split_conversation_at_restarts
LaudateCorpus1/rasa_core
2,433
python
def _split_conversation_at_restarts(evts: List[Dict[(Text, Any)]]) -> List[List[Dict[(Text, Any)]]]: 'Split a conversation at restart events.\n\n Returns an array of event lists, without the restart events.' sub_conversations = [] current = [] for e in evts: if (e.get('event') == 'restart'): if current: sub_conversations.append(current) current = [] else: current.append(e) if current: sub_conversations.append(current) return sub_conversations
def _split_conversation_at_restarts(evts: List[Dict[(Text, Any)]]) -> List[List[Dict[(Text, Any)]]]: 'Split a conversation at restart events.\n\n Returns an array of event lists, without the restart events.' sub_conversations = [] current = [] for e in evts: if (e.get('event') == 'restart'): if current: sub_conversations.append(current) current = [] else: current.append(e) if current: sub_conversations.append(current) return sub_conversations<|docstring|>Split a conversation at restart events. Returns an array of event lists, without the restart events.<|endoftext|>
a2a2e0981fd035b6cce8d38f76e81eb1ce33c1d4f99428f09fcc6e0774a9312d
def _collect_messages(evts: List[Dict[(Text, Any)]]) -> List[Message]: 'Collect the message text and parsed data from the UserMessage events\n into a list' from rasa_nlu.extractors.duckling_http_extractor import DucklingHTTPExtractor from rasa_nlu.extractors.mitie_entity_extractor import MitieEntityExtractor from rasa_nlu.extractors.spacy_entity_extractor import SpacyEntityExtractor msgs = [] for evt in evts: if (evt.get('event') == UserUttered.type_name): data = evt.get('parse_data') for entity in data.get('entities', []): excluded_extractors = [DucklingHTTPExtractor.__name__, SpacyEntityExtractor.__name__, MitieEntityExtractor.__name__] logger.debug('Exclude entity marking of following extractors {} when writing nlu data to file.'.format(excluded_extractors)) if (entity.get('extractor') in excluded_extractors): data['entities'].remove(entity) msg = Message.build(data['text'], data['intent']['name'], data['entities']) msgs.append(msg) return msgs
Collect the message text and parsed data from the UserMessage events into a list
rasa/core/training/interactive.py
_collect_messages
LaudateCorpus1/rasa_core
2,433
python
def _collect_messages(evts: List[Dict[(Text, Any)]]) -> List[Message]: 'Collect the message text and parsed data from the UserMessage events\n into a list' from rasa_nlu.extractors.duckling_http_extractor import DucklingHTTPExtractor from rasa_nlu.extractors.mitie_entity_extractor import MitieEntityExtractor from rasa_nlu.extractors.spacy_entity_extractor import SpacyEntityExtractor msgs = [] for evt in evts: if (evt.get('event') == UserUttered.type_name): data = evt.get('parse_data') for entity in data.get('entities', []): excluded_extractors = [DucklingHTTPExtractor.__name__, SpacyEntityExtractor.__name__, MitieEntityExtractor.__name__] logger.debug('Exclude entity marking of following extractors {} when writing nlu data to file.'.format(excluded_extractors)) if (entity.get('extractor') in excluded_extractors): data['entities'].remove(entity) msg = Message.build(data['text'], data['intent']['name'], data['entities']) msgs.append(msg) return msgs
def _collect_messages(evts: List[Dict[(Text, Any)]]) -> List[Message]: 'Collect the message text and parsed data from the UserMessage events\n into a list' from rasa_nlu.extractors.duckling_http_extractor import DucklingHTTPExtractor from rasa_nlu.extractors.mitie_entity_extractor import MitieEntityExtractor from rasa_nlu.extractors.spacy_entity_extractor import SpacyEntityExtractor msgs = [] for evt in evts: if (evt.get('event') == UserUttered.type_name): data = evt.get('parse_data') for entity in data.get('entities', []): excluded_extractors = [DucklingHTTPExtractor.__name__, SpacyEntityExtractor.__name__, MitieEntityExtractor.__name__] logger.debug('Exclude entity marking of following extractors {} when writing nlu data to file.'.format(excluded_extractors)) if (entity.get('extractor') in excluded_extractors): data['entities'].remove(entity) msg = Message.build(data['text'], data['intent']['name'], data['entities']) msgs.append(msg) return msgs<|docstring|>Collect the message text and parsed data from the UserMessage events into a list<|endoftext|>
04e5e03c6609d1676a06d57b415f367ff823bc08a81fc96fa2b7f3870dc5c0cf
def _collect_actions(evts: List[Dict[(Text, Any)]]) -> List[Dict[(Text, Any)]]: 'Collect all the `ActionExecuted` events into a list.' return [evt for evt in evts if (evt.get('event') == ActionExecuted.type_name)]
Collect all the `ActionExecuted` events into a list.
rasa/core/training/interactive.py
_collect_actions
LaudateCorpus1/rasa_core
2,433
python
def _collect_actions(evts: List[Dict[(Text, Any)]]) -> List[Dict[(Text, Any)]]: return [evt for evt in evts if (evt.get('event') == ActionExecuted.type_name)]
def _collect_actions(evts: List[Dict[(Text, Any)]]) -> List[Dict[(Text, Any)]]: return [evt for evt in evts if (evt.get('event') == ActionExecuted.type_name)]<|docstring|>Collect all the `ActionExecuted` events into a list.<|endoftext|>
467478f860e0823821065180c0d640c7e8ac11e087b8845c722cccf46cebe880
async def _write_stories_to_file(export_story_path: Text, evts: List[Dict[(Text, Any)]]) -> None: 'Write the conversation of the sender_id to the file paths.' sub_conversations = _split_conversation_at_restarts(evts) with open(export_story_path, 'a', encoding='utf-8') as f: for conversation in sub_conversations: parsed_events = events.deserialise_events(conversation) s = Story.from_events(parsed_events) f.write((s.as_story_string(flat=True) + '\n'))
Write the conversation of the sender_id to the file paths.
rasa/core/training/interactive.py
_write_stories_to_file
LaudateCorpus1/rasa_core
2,433
python
async def _write_stories_to_file(export_story_path: Text, evts: List[Dict[(Text, Any)]]) -> None: sub_conversations = _split_conversation_at_restarts(evts) with open(export_story_path, 'a', encoding='utf-8') as f: for conversation in sub_conversations: parsed_events = events.deserialise_events(conversation) s = Story.from_events(parsed_events) f.write((s.as_story_string(flat=True) + '\n'))
async def _write_stories_to_file(export_story_path: Text, evts: List[Dict[(Text, Any)]]) -> None: sub_conversations = _split_conversation_at_restarts(evts) with open(export_story_path, 'a', encoding='utf-8') as f: for conversation in sub_conversations: parsed_events = events.deserialise_events(conversation) s = Story.from_events(parsed_events) f.write((s.as_story_string(flat=True) + '\n'))<|docstring|>Write the conversation of the sender_id to the file paths.<|endoftext|>
0ee52fad92db77de32fa8c9743e99ca774b6cc12a3a2ba1a5610237bbb316f0e
async def _write_nlu_to_file(export_nlu_path: Text, evts: List[Dict[(Text, Any)]]) -> None: 'Write the nlu data of the sender_id to the file paths.' from rasa_nlu.training_data import TrainingData msgs = _collect_messages(evts) try: previous_examples = load_data(export_nlu_path) except Exception as e: logger.exception('An exception occurred while trying to load the NLU data.') export_nlu_path = questionary.text(message='Could not load existing NLU data, please specify where to store NLU data learned in this session (this will overwrite any existing file). {}'.format(str(e)), default=PATHS['backup']).ask() if (export_nlu_path is None): return previous_examples = TrainingData() nlu_data = previous_examples.merge(TrainingData(msgs)) if (_guess_format(export_nlu_path) in {'md', 'unk'}): fformat = 'md' else: fformat = 'json' with open(export_nlu_path, 'w', encoding='utf-8') as f: if (fformat == 'md'): f.write(nlu_data.as_markdown()) else: f.write(nlu_data.as_json())
Write the nlu data of the sender_id to the file paths.
rasa/core/training/interactive.py
_write_nlu_to_file
LaudateCorpus1/rasa_core
2,433
python
async def _write_nlu_to_file(export_nlu_path: Text, evts: List[Dict[(Text, Any)]]) -> None: from rasa_nlu.training_data import TrainingData msgs = _collect_messages(evts) try: previous_examples = load_data(export_nlu_path) except Exception as e: logger.exception('An exception occurred while trying to load the NLU data.') export_nlu_path = questionary.text(message='Could not load existing NLU data, please specify where to store NLU data learned in this session (this will overwrite any existing file). {}'.format(str(e)), default=PATHS['backup']).ask() if (export_nlu_path is None): return previous_examples = TrainingData() nlu_data = previous_examples.merge(TrainingData(msgs)) if (_guess_format(export_nlu_path) in {'md', 'unk'}): fformat = 'md' else: fformat = 'json' with open(export_nlu_path, 'w', encoding='utf-8') as f: if (fformat == 'md'): f.write(nlu_data.as_markdown()) else: f.write(nlu_data.as_json())
async def _write_nlu_to_file(export_nlu_path: Text, evts: List[Dict[(Text, Any)]]) -> None: from rasa_nlu.training_data import TrainingData msgs = _collect_messages(evts) try: previous_examples = load_data(export_nlu_path) except Exception as e: logger.exception('An exception occurred while trying to load the NLU data.') export_nlu_path = questionary.text(message='Could not load existing NLU data, please specify where to store NLU data learned in this session (this will overwrite any existing file). {}'.format(str(e)), default=PATHS['backup']).ask() if (export_nlu_path is None): return previous_examples = TrainingData() nlu_data = previous_examples.merge(TrainingData(msgs)) if (_guess_format(export_nlu_path) in {'md', 'unk'}): fformat = 'md' else: fformat = 'json' with open(export_nlu_path, 'w', encoding='utf-8') as f: if (fformat == 'md'): f.write(nlu_data.as_markdown()) else: f.write(nlu_data.as_json())<|docstring|>Write the nlu data of the sender_id to the file paths.<|endoftext|>
fdb3e1351a86914291fd247a72a3db3e440e653b645540d6febf01ccc1570db5
def _entities_from_messages(messages): 'Return all entities that occur in atleast one of the messages.' return list({e['entity'] for m in messages for e in m.data.get('entities', [])})
Return all entities that occur in atleast one of the messages.
rasa/core/training/interactive.py
_entities_from_messages
LaudateCorpus1/rasa_core
2,433
python
def _entities_from_messages(messages): return list({e['entity'] for m in messages for e in m.data.get('entities', [])})
def _entities_from_messages(messages): return list({e['entity'] for m in messages for e in m.data.get('entities', [])})<|docstring|>Return all entities that occur in atleast one of the messages.<|endoftext|>
a10cc6c670604180f7628f61523f5e623253628c0823349984a9540b44336178
def _intents_from_messages(messages): 'Return all intents that occur in at least one of the messages.' intents = {m.data['intent'] for m in messages if ('intent' in m.data)} return [{i: {'use_entities': True}} for i in intents]
Return all intents that occur in at least one of the messages.
rasa/core/training/interactive.py
_intents_from_messages
LaudateCorpus1/rasa_core
2,433
python
def _intents_from_messages(messages): intents = {m.data['intent'] for m in messages if ('intent' in m.data)} return [{i: {'use_entities': True}} for i in intents]
def _intents_from_messages(messages): intents = {m.data['intent'] for m in messages if ('intent' in m.data)} return [{i: {'use_entities': True}} for i in intents]<|docstring|>Return all intents that occur in at least one of the messages.<|endoftext|>
62f296525559f704da0bc7b103c136e0b46514273f0608d11033f77121fcdbb1
async def _write_domain_to_file(domain_path: Text, evts: List[Dict[(Text, Any)]], endpoint: EndpointConfig) -> None: 'Write an updated domain file to the file path.' domain = (await retrieve_domain(endpoint)) old_domain = Domain.from_dict(domain) messages = _collect_messages(evts) actions = _collect_actions(evts) intent_properties = Domain.collect_intent_properties(_intents_from_messages(messages)) collected_actions = list({e['name'] for e in actions if (e['name'] not in default_action_names())}) new_domain = Domain(intent_properties=intent_properties, entities=_entities_from_messages(messages), slots=[], templates={}, action_names=collected_actions, form_names=[]) old_domain.merge(new_domain).persist_clean(domain_path)
Write an updated domain file to the file path.
rasa/core/training/interactive.py
_write_domain_to_file
LaudateCorpus1/rasa_core
2,433
python
async def _write_domain_to_file(domain_path: Text, evts: List[Dict[(Text, Any)]], endpoint: EndpointConfig) -> None: domain = (await retrieve_domain(endpoint)) old_domain = Domain.from_dict(domain) messages = _collect_messages(evts) actions = _collect_actions(evts) intent_properties = Domain.collect_intent_properties(_intents_from_messages(messages)) collected_actions = list({e['name'] for e in actions if (e['name'] not in default_action_names())}) new_domain = Domain(intent_properties=intent_properties, entities=_entities_from_messages(messages), slots=[], templates={}, action_names=collected_actions, form_names=[]) old_domain.merge(new_domain).persist_clean(domain_path)
async def _write_domain_to_file(domain_path: Text, evts: List[Dict[(Text, Any)]], endpoint: EndpointConfig) -> None: domain = (await retrieve_domain(endpoint)) old_domain = Domain.from_dict(domain) messages = _collect_messages(evts) actions = _collect_actions(evts) intent_properties = Domain.collect_intent_properties(_intents_from_messages(messages)) collected_actions = list({e['name'] for e in actions if (e['name'] not in default_action_names())}) new_domain = Domain(intent_properties=intent_properties, entities=_entities_from_messages(messages), slots=[], templates={}, action_names=collected_actions, form_names=[]) old_domain.merge(new_domain).persist_clean(domain_path)<|docstring|>Write an updated domain file to the file path.<|endoftext|>
a3fffe283883da54617424c39b4f06203b594d011f87a4bc8cdd9f488e185ed7
async def _predict_till_next_listen(endpoint: EndpointConfig, sender_id: Text, finetune: bool, sender_ids: List[Text], plot_file: Optional[Text]) -> None: 'Predict and validate actions until we need to wait for a user msg.' listen = False while (not listen): result = (await request_prediction(endpoint, sender_id)) predictions = result.get('scores') probabilities = [prediction['score'] for prediction in predictions] pred_out = int(np.argmax(probabilities)) action_name = predictions[pred_out].get('action') policy = result.get('policy') confidence = result.get('confidence') (await _print_history(sender_id, endpoint)) (await _plot_trackers(sender_ids, plot_file, endpoint, unconfirmed=[ActionExecuted(action_name)])) listen = (await _validate_action(action_name, policy, confidence, predictions, endpoint, sender_id, finetune=finetune)) (await _plot_trackers(sender_ids, plot_file, endpoint))
Predict and validate actions until we need to wait for a user msg.
rasa/core/training/interactive.py
_predict_till_next_listen
LaudateCorpus1/rasa_core
2,433
python
async def _predict_till_next_listen(endpoint: EndpointConfig, sender_id: Text, finetune: bool, sender_ids: List[Text], plot_file: Optional[Text]) -> None: listen = False while (not listen): result = (await request_prediction(endpoint, sender_id)) predictions = result.get('scores') probabilities = [prediction['score'] for prediction in predictions] pred_out = int(np.argmax(probabilities)) action_name = predictions[pred_out].get('action') policy = result.get('policy') confidence = result.get('confidence') (await _print_history(sender_id, endpoint)) (await _plot_trackers(sender_ids, plot_file, endpoint, unconfirmed=[ActionExecuted(action_name)])) listen = (await _validate_action(action_name, policy, confidence, predictions, endpoint, sender_id, finetune=finetune)) (await _plot_trackers(sender_ids, plot_file, endpoint))
async def _predict_till_next_listen(endpoint: EndpointConfig, sender_id: Text, finetune: bool, sender_ids: List[Text], plot_file: Optional[Text]) -> None: listen = False while (not listen): result = (await request_prediction(endpoint, sender_id)) predictions = result.get('scores') probabilities = [prediction['score'] for prediction in predictions] pred_out = int(np.argmax(probabilities)) action_name = predictions[pred_out].get('action') policy = result.get('policy') confidence = result.get('confidence') (await _print_history(sender_id, endpoint)) (await _plot_trackers(sender_ids, plot_file, endpoint, unconfirmed=[ActionExecuted(action_name)])) listen = (await _validate_action(action_name, policy, confidence, predictions, endpoint, sender_id, finetune=finetune)) (await _plot_trackers(sender_ids, plot_file, endpoint))<|docstring|>Predict and validate actions until we need to wait for a user msg.<|endoftext|>
0946fb9968bc5fd4f8b2f037c04ae439f78e681589a005630e3f8d524e44e744
async def _correct_wrong_nlu(corrected_nlu: Dict[(Text, Any)], evts: List[Dict[(Text, Any)]], endpoint: EndpointConfig, sender_id: Text) -> None: "A wrong NLU prediction got corrected, update core's tracker." latest_message = latest_user_message(evts) corrected_events = all_events_before_latest_user_msg(evts) latest_message['parse_data'] = corrected_nlu (await replace_events(endpoint, sender_id, corrected_events)) (await send_message(endpoint, sender_id, latest_message.get('text'), latest_message.get('parse_data')))
A wrong NLU prediction got corrected, update core's tracker.
rasa/core/training/interactive.py
_correct_wrong_nlu
LaudateCorpus1/rasa_core
2,433
python
async def _correct_wrong_nlu(corrected_nlu: Dict[(Text, Any)], evts: List[Dict[(Text, Any)]], endpoint: EndpointConfig, sender_id: Text) -> None: latest_message = latest_user_message(evts) corrected_events = all_events_before_latest_user_msg(evts) latest_message['parse_data'] = corrected_nlu (await replace_events(endpoint, sender_id, corrected_events)) (await send_message(endpoint, sender_id, latest_message.get('text'), latest_message.get('parse_data')))
async def _correct_wrong_nlu(corrected_nlu: Dict[(Text, Any)], evts: List[Dict[(Text, Any)]], endpoint: EndpointConfig, sender_id: Text) -> None: latest_message = latest_user_message(evts) corrected_events = all_events_before_latest_user_msg(evts) latest_message['parse_data'] = corrected_nlu (await replace_events(endpoint, sender_id, corrected_events)) (await send_message(endpoint, sender_id, latest_message.get('text'), latest_message.get('parse_data')))<|docstring|>A wrong NLU prediction got corrected, update core's tracker.<|endoftext|>
d461cb1dc238581b9ba62c29b2adbca133bbb2c38826a5bde60a60f309cab863
async def _correct_wrong_action(corrected_action: Text, endpoint: EndpointConfig, sender_id: Text, finetune: bool=False, is_new_action: bool=False) -> None: "A wrong action prediction got corrected, update core's tracker." result = (await send_action(endpoint, sender_id, corrected_action, is_new_action=is_new_action)) if finetune: (await send_finetune(endpoint, result.get('tracker', {}).get('events', [])))
A wrong action prediction got corrected, update core's tracker.
rasa/core/training/interactive.py
_correct_wrong_action
LaudateCorpus1/rasa_core
2,433
python
async def _correct_wrong_action(corrected_action: Text, endpoint: EndpointConfig, sender_id: Text, finetune: bool=False, is_new_action: bool=False) -> None: result = (await send_action(endpoint, sender_id, corrected_action, is_new_action=is_new_action)) if finetune: (await send_finetune(endpoint, result.get('tracker', {}).get('events', [])))
async def _correct_wrong_action(corrected_action: Text, endpoint: EndpointConfig, sender_id: Text, finetune: bool=False, is_new_action: bool=False) -> None: result = (await send_action(endpoint, sender_id, corrected_action, is_new_action=is_new_action)) if finetune: (await send_finetune(endpoint, result.get('tracker', {}).get('events', [])))<|docstring|>A wrong action prediction got corrected, update core's tracker.<|endoftext|>
2c7a48d64d9009075b801ad28361a3a3f01dfdebbc0d652bec5c7b26ced5da3b
def _form_is_rejected(action_name, tracker): 'Check if the form got rejected with the most recent action name.' return (tracker.get('active_form', {}).get('name') and (action_name != tracker['active_form']['name']) and (action_name != ACTION_LISTEN_NAME))
Check if the form got rejected with the most recent action name.
rasa/core/training/interactive.py
_form_is_rejected
LaudateCorpus1/rasa_core
2,433
python
def _form_is_rejected(action_name, tracker): return (tracker.get('active_form', {}).get('name') and (action_name != tracker['active_form']['name']) and (action_name != ACTION_LISTEN_NAME))
def _form_is_rejected(action_name, tracker): return (tracker.get('active_form', {}).get('name') and (action_name != tracker['active_form']['name']) and (action_name != ACTION_LISTEN_NAME))<|docstring|>Check if the form got rejected with the most recent action name.<|endoftext|>
0f43190c7913ca415cf72ea6c4f1db9d862ab909a93db4a7a4781549646afb45
def _form_is_restored(action_name, tracker): 'Check whether the form is called again after it was rejected.' return (tracker.get('active_form', {}).get('rejected') and (tracker.get('latest_action_name') == ACTION_LISTEN_NAME) and (action_name == tracker.get('active_form', {}).get('name')))
Check whether the form is called again after it was rejected.
rasa/core/training/interactive.py
_form_is_restored
LaudateCorpus1/rasa_core
2,433
python
def _form_is_restored(action_name, tracker): return (tracker.get('active_form', {}).get('rejected') and (tracker.get('latest_action_name') == ACTION_LISTEN_NAME) and (action_name == tracker.get('active_form', {}).get('name')))
def _form_is_restored(action_name, tracker): return (tracker.get('active_form', {}).get('rejected') and (tracker.get('latest_action_name') == ACTION_LISTEN_NAME) and (action_name == tracker.get('active_form', {}).get('name')))<|docstring|>Check whether the form is called again after it was rejected.<|endoftext|>
cf95d3f9f64a510cd7939254b534ae67b892addd53ed31f3032aa87eaff4b55f
async def _confirm_form_validation(action_name, tracker, endpoint, sender_id): 'Ask a user whether an input for a form should be validated.\n\n Previous to this call, the active form was chosen after it was rejected.' requested_slot = tracker.get('slots', {}).get(REQUESTED_SLOT) validation_questions = questionary.confirm("Should '{}' validate user input to fill the slot '{}'?".format(action_name, requested_slot)) validate_input = (await _ask_questions(validation_questions, sender_id, endpoint)) if (not validate_input): (await send_event(endpoint, sender_id, {'event': 'form_validation', 'validate': False})) elif (not tracker.get('active_form', {}).get('validate')): warning_question = questionary.confirm('ERROR: FormPolicy predicted no form validation based on previous training stories. Make sure to remove contradictory stories from training data. Otherwise predicting no form validation will not work as expected.') (await _ask_questions(warning_question, sender_id, endpoint)) (await send_event(endpoint, sender_id, {'event': 'form_validation', 'validate': True}))
Ask a user whether an input for a form should be validated. Previous to this call, the active form was chosen after it was rejected.
rasa/core/training/interactive.py
_confirm_form_validation
LaudateCorpus1/rasa_core
2,433
python
async def _confirm_form_validation(action_name, tracker, endpoint, sender_id): 'Ask a user whether an input for a form should be validated.\n\n Previous to this call, the active form was chosen after it was rejected.' requested_slot = tracker.get('slots', {}).get(REQUESTED_SLOT) validation_questions = questionary.confirm("Should '{}' validate user input to fill the slot '{}'?".format(action_name, requested_slot)) validate_input = (await _ask_questions(validation_questions, sender_id, endpoint)) if (not validate_input): (await send_event(endpoint, sender_id, {'event': 'form_validation', 'validate': False})) elif (not tracker.get('active_form', {}).get('validate')): warning_question = questionary.confirm('ERROR: FormPolicy predicted no form validation based on previous training stories. Make sure to remove contradictory stories from training data. Otherwise predicting no form validation will not work as expected.') (await _ask_questions(warning_question, sender_id, endpoint)) (await send_event(endpoint, sender_id, {'event': 'form_validation', 'validate': True}))
async def _confirm_form_validation(action_name, tracker, endpoint, sender_id): 'Ask a user whether an input for a form should be validated.\n\n Previous to this call, the active form was chosen after it was rejected.' requested_slot = tracker.get('slots', {}).get(REQUESTED_SLOT) validation_questions = questionary.confirm("Should '{}' validate user input to fill the slot '{}'?".format(action_name, requested_slot)) validate_input = (await _ask_questions(validation_questions, sender_id, endpoint)) if (not validate_input): (await send_event(endpoint, sender_id, {'event': 'form_validation', 'validate': False})) elif (not tracker.get('active_form', {}).get('validate')): warning_question = questionary.confirm('ERROR: FormPolicy predicted no form validation based on previous training stories. Make sure to remove contradictory stories from training data. Otherwise predicting no form validation will not work as expected.') (await _ask_questions(warning_question, sender_id, endpoint)) (await send_event(endpoint, sender_id, {'event': 'form_validation', 'validate': True}))<|docstring|>Ask a user whether an input for a form should be validated. Previous to this call, the active form was chosen after it was rejected.<|endoftext|>
16b034ec07196df188d8d03176d9ab8686db658f9beb9b6f6b6601652925e295
async def _validate_action(action_name: Text, policy: Text, confidence: float, predictions: List[Dict[(Text, Any)]], endpoint: EndpointConfig, sender_id: Text, finetune: bool=False) -> bool: 'Query the user to validate if an action prediction is correct.\n\n Returns `True` if the prediction is correct, `False` otherwise.' question = questionary.confirm("The bot wants to run '{}', correct?".format(action_name)) is_correct = (await _ask_questions(question, sender_id, endpoint)) if (not is_correct): (action_name, is_new_action) = (await _request_action_from_user(predictions, sender_id, endpoint)) else: is_new_action = False tracker = (await retrieve_tracker(endpoint, sender_id, EventVerbosity.AFTER_RESTART)) if _form_is_rejected(action_name, tracker): (await send_event(endpoint, sender_id, {'event': 'action_execution_rejected', 'name': tracker['active_form']['name']})) elif _form_is_restored(action_name, tracker): (await _confirm_form_validation(action_name, tracker, endpoint, sender_id)) if (not is_correct): (await _correct_wrong_action(action_name, endpoint, sender_id, finetune=finetune, is_new_action=is_new_action)) else: (await send_action(endpoint, sender_id, action_name, policy, confidence)) return (action_name == ACTION_LISTEN_NAME)
Query the user to validate if an action prediction is correct. Returns `True` if the prediction is correct, `False` otherwise.
rasa/core/training/interactive.py
_validate_action
LaudateCorpus1/rasa_core
2,433
python
async def _validate_action(action_name: Text, policy: Text, confidence: float, predictions: List[Dict[(Text, Any)]], endpoint: EndpointConfig, sender_id: Text, finetune: bool=False) -> bool: 'Query the user to validate if an action prediction is correct.\n\n Returns `True` if the prediction is correct, `False` otherwise.' question = questionary.confirm("The bot wants to run '{}', correct?".format(action_name)) is_correct = (await _ask_questions(question, sender_id, endpoint)) if (not is_correct): (action_name, is_new_action) = (await _request_action_from_user(predictions, sender_id, endpoint)) else: is_new_action = False tracker = (await retrieve_tracker(endpoint, sender_id, EventVerbosity.AFTER_RESTART)) if _form_is_rejected(action_name, tracker): (await send_event(endpoint, sender_id, {'event': 'action_execution_rejected', 'name': tracker['active_form']['name']})) elif _form_is_restored(action_name, tracker): (await _confirm_form_validation(action_name, tracker, endpoint, sender_id)) if (not is_correct): (await _correct_wrong_action(action_name, endpoint, sender_id, finetune=finetune, is_new_action=is_new_action)) else: (await send_action(endpoint, sender_id, action_name, policy, confidence)) return (action_name == ACTION_LISTEN_NAME)
async def _validate_action(action_name: Text, policy: Text, confidence: float, predictions: List[Dict[(Text, Any)]], endpoint: EndpointConfig, sender_id: Text, finetune: bool=False) -> bool: 'Query the user to validate if an action prediction is correct.\n\n Returns `True` if the prediction is correct, `False` otherwise.' question = questionary.confirm("The bot wants to run '{}', correct?".format(action_name)) is_correct = (await _ask_questions(question, sender_id, endpoint)) if (not is_correct): (action_name, is_new_action) = (await _request_action_from_user(predictions, sender_id, endpoint)) else: is_new_action = False tracker = (await retrieve_tracker(endpoint, sender_id, EventVerbosity.AFTER_RESTART)) if _form_is_rejected(action_name, tracker): (await send_event(endpoint, sender_id, {'event': 'action_execution_rejected', 'name': tracker['active_form']['name']})) elif _form_is_restored(action_name, tracker): (await _confirm_form_validation(action_name, tracker, endpoint, sender_id)) if (not is_correct): (await _correct_wrong_action(action_name, endpoint, sender_id, finetune=finetune, is_new_action=is_new_action)) else: (await send_action(endpoint, sender_id, action_name, policy, confidence)) return (action_name == ACTION_LISTEN_NAME)<|docstring|>Query the user to validate if an action prediction is correct. Returns `True` if the prediction is correct, `False` otherwise.<|endoftext|>
caa31db6788253f77ea63e13a48e88bd4f05a94b4be0e7d84b23cafe56718b5c
def _as_md_message(parse_data: Dict[(Text, Any)]) -> Text: 'Display the parse data of a message in markdown format.' from rasa_nlu.training_data.formats import MarkdownWriter if parse_data.get('text', '').startswith(INTENT_MESSAGE_PREFIX): return parse_data.get('text') if (not parse_data.get('entities')): parse_data['entities'] = [] return MarkdownWriter()._generate_message_md(parse_data)
Display the parse data of a message in markdown format.
rasa/core/training/interactive.py
_as_md_message
LaudateCorpus1/rasa_core
2,433
python
def _as_md_message(parse_data: Dict[(Text, Any)]) -> Text: from rasa_nlu.training_data.formats import MarkdownWriter if parse_data.get('text', ).startswith(INTENT_MESSAGE_PREFIX): return parse_data.get('text') if (not parse_data.get('entities')): parse_data['entities'] = [] return MarkdownWriter()._generate_message_md(parse_data)
def _as_md_message(parse_data: Dict[(Text, Any)]) -> Text: from rasa_nlu.training_data.formats import MarkdownWriter if parse_data.get('text', ).startswith(INTENT_MESSAGE_PREFIX): return parse_data.get('text') if (not parse_data.get('entities')): parse_data['entities'] = [] return MarkdownWriter()._generate_message_md(parse_data)<|docstring|>Display the parse data of a message in markdown format.<|endoftext|>
602710f725d7aea1c6398759ec7d99bbde2c18d4eefe77523ac966dc0a9f3b62
def _validate_user_regex(latest_message: Dict[(Text, Any)], intents: List[Text]) -> bool: 'Validate if a users message input is correct.\n\n This assumes the user entered an intent directly, e.g. using\n `/greet`. Return `True` if the intent is a known one.' parse_data = latest_message.get('parse_data', {}) intent = parse_data.get('intent', {}).get('name') if (intent in intents): return True else: return False
Validate if a users message input is correct. This assumes the user entered an intent directly, e.g. using `/greet`. Return `True` if the intent is a known one.
rasa/core/training/interactive.py
_validate_user_regex
LaudateCorpus1/rasa_core
2,433
python
def _validate_user_regex(latest_message: Dict[(Text, Any)], intents: List[Text]) -> bool: 'Validate if a users message input is correct.\n\n This assumes the user entered an intent directly, e.g. using\n `/greet`. Return `True` if the intent is a known one.' parse_data = latest_message.get('parse_data', {}) intent = parse_data.get('intent', {}).get('name') if (intent in intents): return True else: return False
def _validate_user_regex(latest_message: Dict[(Text, Any)], intents: List[Text]) -> bool: 'Validate if a users message input is correct.\n\n This assumes the user entered an intent directly, e.g. using\n `/greet`. Return `True` if the intent is a known one.' parse_data = latest_message.get('parse_data', {}) intent = parse_data.get('intent', {}).get('name') if (intent in intents): return True else: return False<|docstring|>Validate if a users message input is correct. This assumes the user entered an intent directly, e.g. using `/greet`. Return `True` if the intent is a known one.<|endoftext|>
adcdfbba409f479bdd0636218d5fe03209e9619aad137f1a4d6073c84dcf3efd
async def _validate_user_text(latest_message: Dict[(Text, Any)], endpoint: EndpointConfig, sender_id: Text) -> bool: 'Validate a user message input as free text.\n\n This assumes the user message is a text message (so NOT `/greet`).' parse_data = latest_message.get('parse_data', {}) text = _as_md_message(parse_data) intent = parse_data.get('intent', {}).get('name') entities = parse_data.get('entities', []) if entities: message = "Is the intent '{}' correct for '{}' and are all entities labeled correctly?".format(text, intent) else: message = "Your NLU model classified '{}' with intent '{}' and there are no entities, is this correct?".format(text, intent) if (intent is None): print("The NLU classification for '{}' returned '{}'".format(text, intent)) return False else: question = questionary.confirm(message) return (await _ask_questions(question, sender_id, endpoint))
Validate a user message input as free text. This assumes the user message is a text message (so NOT `/greet`).
rasa/core/training/interactive.py
_validate_user_text
LaudateCorpus1/rasa_core
2,433
python
async def _validate_user_text(latest_message: Dict[(Text, Any)], endpoint: EndpointConfig, sender_id: Text) -> bool: 'Validate a user message input as free text.\n\n This assumes the user message is a text message (so NOT `/greet`).' parse_data = latest_message.get('parse_data', {}) text = _as_md_message(parse_data) intent = parse_data.get('intent', {}).get('name') entities = parse_data.get('entities', []) if entities: message = "Is the intent '{}' correct for '{}' and are all entities labeled correctly?".format(text, intent) else: message = "Your NLU model classified '{}' with intent '{}' and there are no entities, is this correct?".format(text, intent) if (intent is None): print("The NLU classification for '{}' returned '{}'".format(text, intent)) return False else: question = questionary.confirm(message) return (await _ask_questions(question, sender_id, endpoint))
async def _validate_user_text(latest_message: Dict[(Text, Any)], endpoint: EndpointConfig, sender_id: Text) -> bool: 'Validate a user message input as free text.\n\n This assumes the user message is a text message (so NOT `/greet`).' parse_data = latest_message.get('parse_data', {}) text = _as_md_message(parse_data) intent = parse_data.get('intent', {}).get('name') entities = parse_data.get('entities', []) if entities: message = "Is the intent '{}' correct for '{}' and are all entities labeled correctly?".format(text, intent) else: message = "Your NLU model classified '{}' with intent '{}' and there are no entities, is this correct?".format(text, intent) if (intent is None): print("The NLU classification for '{}' returned '{}'".format(text, intent)) return False else: question = questionary.confirm(message) return (await _ask_questions(question, sender_id, endpoint))<|docstring|>Validate a user message input as free text. This assumes the user message is a text message (so NOT `/greet`).<|endoftext|>
10f45bd63d738f603967b4d3b25458a039ee0ef1dd5f2d871ab01af61b38dff4
async def _validate_nlu(intents: List[Text], endpoint: EndpointConfig, sender_id: Text) -> None: 'Validate if a user message, either text or intent is correct.\n\n If the prediction of the latest user message is incorrect,\n the tracker will be corrected with the correct intent / entities.' tracker = (await retrieve_tracker(endpoint, sender_id, EventVerbosity.AFTER_RESTART)) latest_message = latest_user_message(tracker.get('events', [])) if latest_message.get('text').startswith(INTENT_MESSAGE_PREFIX): valid = _validate_user_regex(latest_message, intents) else: valid = (await _validate_user_text(latest_message, endpoint, sender_id)) if (not valid): corrected_intent = (await _request_intent_from_user(latest_message, intents, sender_id, endpoint)) evts = tracker.get('events', []) entities = (await _correct_entities(latest_message, endpoint, sender_id)) corrected_nlu = {'intent': corrected_intent, 'entities': entities, 'text': latest_message.get('text')} (await _correct_wrong_nlu(corrected_nlu, evts, endpoint, sender_id))
Validate if a user message, either text or intent is correct. If the prediction of the latest user message is incorrect, the tracker will be corrected with the correct intent / entities.
rasa/core/training/interactive.py
_validate_nlu
LaudateCorpus1/rasa_core
2,433
python
async def _validate_nlu(intents: List[Text], endpoint: EndpointConfig, sender_id: Text) -> None: 'Validate if a user message, either text or intent is correct.\n\n If the prediction of the latest user message is incorrect,\n the tracker will be corrected with the correct intent / entities.' tracker = (await retrieve_tracker(endpoint, sender_id, EventVerbosity.AFTER_RESTART)) latest_message = latest_user_message(tracker.get('events', [])) if latest_message.get('text').startswith(INTENT_MESSAGE_PREFIX): valid = _validate_user_regex(latest_message, intents) else: valid = (await _validate_user_text(latest_message, endpoint, sender_id)) if (not valid): corrected_intent = (await _request_intent_from_user(latest_message, intents, sender_id, endpoint)) evts = tracker.get('events', []) entities = (await _correct_entities(latest_message, endpoint, sender_id)) corrected_nlu = {'intent': corrected_intent, 'entities': entities, 'text': latest_message.get('text')} (await _correct_wrong_nlu(corrected_nlu, evts, endpoint, sender_id))
async def _validate_nlu(intents: List[Text], endpoint: EndpointConfig, sender_id: Text) -> None: 'Validate if a user message, either text or intent is correct.\n\n If the prediction of the latest user message is incorrect,\n the tracker will be corrected with the correct intent / entities.' tracker = (await retrieve_tracker(endpoint, sender_id, EventVerbosity.AFTER_RESTART)) latest_message = latest_user_message(tracker.get('events', [])) if latest_message.get('text').startswith(INTENT_MESSAGE_PREFIX): valid = _validate_user_regex(latest_message, intents) else: valid = (await _validate_user_text(latest_message, endpoint, sender_id)) if (not valid): corrected_intent = (await _request_intent_from_user(latest_message, intents, sender_id, endpoint)) evts = tracker.get('events', []) entities = (await _correct_entities(latest_message, endpoint, sender_id)) corrected_nlu = {'intent': corrected_intent, 'entities': entities, 'text': latest_message.get('text')} (await _correct_wrong_nlu(corrected_nlu, evts, endpoint, sender_id))<|docstring|>Validate if a user message, either text or intent is correct. If the prediction of the latest user message is incorrect, the tracker will be corrected with the correct intent / entities.<|endoftext|>
79af590e30b759710f08cf6f2118af11682007de937d6969a648ad3a74c6a92b
async def _correct_entities(latest_message: Dict[(Text, Any)], endpoint: EndpointConfig, sender_id: Text) -> List[Dict[(Text, Any)]]: 'Validate the entities of a user message.\n\n Returns the corrected entities' from rasa_nlu.training_data.formats import MarkdownReader parse_original = latest_message.get('parse_data', {}) entity_str = _as_md_message(parse_original) question = questionary.text('Please mark the entities using [value](type) notation', default=entity_str) annotation = (await _ask_questions(question, sender_id, endpoint)) parse_annotated = MarkdownReader()._parse_training_example(annotation) corrected_entities = _merge_annotated_and_original_entities(parse_annotated, parse_original) return corrected_entities
Validate the entities of a user message. Returns the corrected entities
rasa/core/training/interactive.py
_correct_entities
LaudateCorpus1/rasa_core
2,433
python
async def _correct_entities(latest_message: Dict[(Text, Any)], endpoint: EndpointConfig, sender_id: Text) -> List[Dict[(Text, Any)]]: 'Validate the entities of a user message.\n\n Returns the corrected entities' from rasa_nlu.training_data.formats import MarkdownReader parse_original = latest_message.get('parse_data', {}) entity_str = _as_md_message(parse_original) question = questionary.text('Please mark the entities using [value](type) notation', default=entity_str) annotation = (await _ask_questions(question, sender_id, endpoint)) parse_annotated = MarkdownReader()._parse_training_example(annotation) corrected_entities = _merge_annotated_and_original_entities(parse_annotated, parse_original) return corrected_entities
async def _correct_entities(latest_message: Dict[(Text, Any)], endpoint: EndpointConfig, sender_id: Text) -> List[Dict[(Text, Any)]]: 'Validate the entities of a user message.\n\n Returns the corrected entities' from rasa_nlu.training_data.formats import MarkdownReader parse_original = latest_message.get('parse_data', {}) entity_str = _as_md_message(parse_original) question = questionary.text('Please mark the entities using [value](type) notation', default=entity_str) annotation = (await _ask_questions(question, sender_id, endpoint)) parse_annotated = MarkdownReader()._parse_training_example(annotation) corrected_entities = _merge_annotated_and_original_entities(parse_annotated, parse_original) return corrected_entities<|docstring|>Validate the entities of a user message. Returns the corrected entities<|endoftext|>
753bd9e6da23ea5020800172082a3fb3b585bd4e10b356284651a0f3dcb0f642
async def _enter_user_message(sender_id: Text, endpoint: EndpointConfig) -> None: 'Request a new message from the user.' question = questionary.text('Your input ->') message = (await _ask_questions(question, sender_id, endpoint, (lambda a: (not a)))) if (message == (INTENT_MESSAGE_PREFIX + constants.USER_INTENT_RESTART)): raise RestartConversation() (await send_message(endpoint, sender_id, message))
Request a new message from the user.
rasa/core/training/interactive.py
_enter_user_message
LaudateCorpus1/rasa_core
2,433
python
async def _enter_user_message(sender_id: Text, endpoint: EndpointConfig) -> None: question = questionary.text('Your input ->') message = (await _ask_questions(question, sender_id, endpoint, (lambda a: (not a)))) if (message == (INTENT_MESSAGE_PREFIX + constants.USER_INTENT_RESTART)): raise RestartConversation() (await send_message(endpoint, sender_id, message))
async def _enter_user_message(sender_id: Text, endpoint: EndpointConfig) -> None: question = questionary.text('Your input ->') message = (await _ask_questions(question, sender_id, endpoint, (lambda a: (not a)))) if (message == (INTENT_MESSAGE_PREFIX + constants.USER_INTENT_RESTART)): raise RestartConversation() (await send_message(endpoint, sender_id, message))<|docstring|>Request a new message from the user.<|endoftext|>
cd463d08e6ef89a6f875c7e7af52dd6251fb6f124464b2dde667be2e741525bf
async def is_listening_for_message(sender_id: Text, endpoint: EndpointConfig) -> bool: 'Check if the conversation is in need for a user message.' tracker = (await retrieve_tracker(endpoint, sender_id, EventVerbosity.APPLIED)) for (i, e) in enumerate(reversed(tracker.get('events', []))): if (e.get('event') == UserUttered.type_name): return False elif (e.get('event') == ActionExecuted.type_name): return (e.get('name') == ACTION_LISTEN_NAME) return False
Check if the conversation is in need for a user message.
rasa/core/training/interactive.py
is_listening_for_message
LaudateCorpus1/rasa_core
2,433
python
async def is_listening_for_message(sender_id: Text, endpoint: EndpointConfig) -> bool: tracker = (await retrieve_tracker(endpoint, sender_id, EventVerbosity.APPLIED)) for (i, e) in enumerate(reversed(tracker.get('events', []))): if (e.get('event') == UserUttered.type_name): return False elif (e.get('event') == ActionExecuted.type_name): return (e.get('name') == ACTION_LISTEN_NAME) return False
async def is_listening_for_message(sender_id: Text, endpoint: EndpointConfig) -> bool: tracker = (await retrieve_tracker(endpoint, sender_id, EventVerbosity.APPLIED)) for (i, e) in enumerate(reversed(tracker.get('events', []))): if (e.get('event') == UserUttered.type_name): return False elif (e.get('event') == ActionExecuted.type_name): return (e.get('name') == ACTION_LISTEN_NAME) return False<|docstring|>Check if the conversation is in need for a user message.<|endoftext|>
3fccb025667a269b36bf5fecedf0552bb022077aa9651877fa940ad5cc1740e9
async def _undo_latest(sender_id: Text, endpoint: EndpointConfig) -> None: 'Undo either the latest bot action or user message, whatever is last.' tracker = (await retrieve_tracker(endpoint, sender_id, EventVerbosity.ALL)) cutoff_index = None for (i, e) in enumerate(reversed(tracker.get('events', []))): if (e.get('event') in {ActionExecuted.type_name, UserUttered.type_name}): cutoff_index = i break elif (e.get('event') == Restarted.type_name): break if (cutoff_index is not None): events_to_keep = tracker['events'][:(- (cutoff_index + 1))] (await replace_events(endpoint, sender_id, events_to_keep))
Undo either the latest bot action or user message, whatever is last.
rasa/core/training/interactive.py
_undo_latest
LaudateCorpus1/rasa_core
2,433
python
async def _undo_latest(sender_id: Text, endpoint: EndpointConfig) -> None: tracker = (await retrieve_tracker(endpoint, sender_id, EventVerbosity.ALL)) cutoff_index = None for (i, e) in enumerate(reversed(tracker.get('events', []))): if (e.get('event') in {ActionExecuted.type_name, UserUttered.type_name}): cutoff_index = i break elif (e.get('event') == Restarted.type_name): break if (cutoff_index is not None): events_to_keep = tracker['events'][:(- (cutoff_index + 1))] (await replace_events(endpoint, sender_id, events_to_keep))
async def _undo_latest(sender_id: Text, endpoint: EndpointConfig) -> None: tracker = (await retrieve_tracker(endpoint, sender_id, EventVerbosity.ALL)) cutoff_index = None for (i, e) in enumerate(reversed(tracker.get('events', []))): if (e.get('event') in {ActionExecuted.type_name, UserUttered.type_name}): cutoff_index = i break elif (e.get('event') == Restarted.type_name): break if (cutoff_index is not None): events_to_keep = tracker['events'][:(- (cutoff_index + 1))] (await replace_events(endpoint, sender_id, events_to_keep))<|docstring|>Undo either the latest bot action or user message, whatever is last.<|endoftext|>
a14fa7d25969541909b5c10b25cedbf7875c1221a63540e43bffaa111f6a89e4
async def _fetch_events(sender_ids: List[Union[(Text, List[Event])]], endpoint: EndpointConfig) -> List[List[Event]]: 'Retrieve all event trackers from the endpoint for all sender ids.' event_sequences = [] for sender_id in sender_ids: if isinstance(sender_id, str): tracker = (await retrieve_tracker(endpoint, sender_id)) evts = tracker.get('events', []) for conversation in _split_conversation_at_restarts(evts): parsed_events = events.deserialise_events(conversation) event_sequences.append(parsed_events) else: event_sequences.append(sender_id) return event_sequences
Retrieve all event trackers from the endpoint for all sender ids.
rasa/core/training/interactive.py
_fetch_events
LaudateCorpus1/rasa_core
2,433
python
async def _fetch_events(sender_ids: List[Union[(Text, List[Event])]], endpoint: EndpointConfig) -> List[List[Event]]: event_sequences = [] for sender_id in sender_ids: if isinstance(sender_id, str): tracker = (await retrieve_tracker(endpoint, sender_id)) evts = tracker.get('events', []) for conversation in _split_conversation_at_restarts(evts): parsed_events = events.deserialise_events(conversation) event_sequences.append(parsed_events) else: event_sequences.append(sender_id) return event_sequences
async def _fetch_events(sender_ids: List[Union[(Text, List[Event])]], endpoint: EndpointConfig) -> List[List[Event]]: event_sequences = [] for sender_id in sender_ids: if isinstance(sender_id, str): tracker = (await retrieve_tracker(endpoint, sender_id)) evts = tracker.get('events', []) for conversation in _split_conversation_at_restarts(evts): parsed_events = events.deserialise_events(conversation) event_sequences.append(parsed_events) else: event_sequences.append(sender_id) return event_sequences<|docstring|>Retrieve all event trackers from the endpoint for all sender ids.<|endoftext|>
e879a7f584e1499e14a358eb69c65ba8985ee8e1aefd0879440afca55f8e3eb0
async def _plot_trackers(sender_ids: List[Union[(Text, List[Event])]], output_file: Optional[Text], endpoint: EndpointConfig, unconfirmed: Optional[List[Event]]=None): 'Create a plot of the trackers of the passed sender ids.\n\n This assumes that the last sender id is the conversation we are currently\n working on. If there are events that are not part of this active tracker\n yet, they can be passed as part of `unconfirmed`. They will be appended\n to the currently active conversation.' if ((not output_file) or (not sender_ids)): return None event_sequences = (await _fetch_events(sender_ids, endpoint)) if unconfirmed: event_sequences[(- 1)].extend(unconfirmed) graph = (await visualize_neighborhood(event_sequences[(- 1)], event_sequences, output_file=None, max_history=2)) from networkx.drawing.nx_pydot import write_dot write_dot(graph, output_file)
Create a plot of the trackers of the passed sender ids. This assumes that the last sender id is the conversation we are currently working on. If there are events that are not part of this active tracker yet, they can be passed as part of `unconfirmed`. They will be appended to the currently active conversation.
rasa/core/training/interactive.py
_plot_trackers
LaudateCorpus1/rasa_core
2,433
python
async def _plot_trackers(sender_ids: List[Union[(Text, List[Event])]], output_file: Optional[Text], endpoint: EndpointConfig, unconfirmed: Optional[List[Event]]=None): 'Create a plot of the trackers of the passed sender ids.\n\n This assumes that the last sender id is the conversation we are currently\n working on. If there are events that are not part of this active tracker\n yet, they can be passed as part of `unconfirmed`. They will be appended\n to the currently active conversation.' if ((not output_file) or (not sender_ids)): return None event_sequences = (await _fetch_events(sender_ids, endpoint)) if unconfirmed: event_sequences[(- 1)].extend(unconfirmed) graph = (await visualize_neighborhood(event_sequences[(- 1)], event_sequences, output_file=None, max_history=2)) from networkx.drawing.nx_pydot import write_dot write_dot(graph, output_file)
async def _plot_trackers(sender_ids: List[Union[(Text, List[Event])]], output_file: Optional[Text], endpoint: EndpointConfig, unconfirmed: Optional[List[Event]]=None): 'Create a plot of the trackers of the passed sender ids.\n\n This assumes that the last sender id is the conversation we are currently\n working on. If there are events that are not part of this active tracker\n yet, they can be passed as part of `unconfirmed`. They will be appended\n to the currently active conversation.' if ((not output_file) or (not sender_ids)): return None event_sequences = (await _fetch_events(sender_ids, endpoint)) if unconfirmed: event_sequences[(- 1)].extend(unconfirmed) graph = (await visualize_neighborhood(event_sequences[(- 1)], event_sequences, output_file=None, max_history=2)) from networkx.drawing.nx_pydot import write_dot write_dot(graph, output_file)<|docstring|>Create a plot of the trackers of the passed sender ids. This assumes that the last sender id is the conversation we are currently working on. If there are events that are not part of this active tracker yet, they can be passed as part of `unconfirmed`. They will be appended to the currently active conversation.<|endoftext|>
cfce989bb4b052dbe892842d0023474f05137670cdb2a95bbfe0c0bc8339ea74
def _print_help(skip_visualization: bool) -> None: 'Print some initial help message for the user.' if (not skip_visualization): visualization_url = DEFAULT_SERVER_FORMAT.format((DEFAULT_SERVER_PORT + 1)) visualization_help = 'Visualisation at {}/visualization.html.'.format(visualization_url) else: visualization_help = '' rasa.cli.utils.print_success("Bot loaded. {}\nType a message and press enter (press 'Ctr-c' to exit). ".format(visualization_help))
Print some initial help message for the user.
rasa/core/training/interactive.py
_print_help
LaudateCorpus1/rasa_core
2,433
python
def _print_help(skip_visualization: bool) -> None: if (not skip_visualization): visualization_url = DEFAULT_SERVER_FORMAT.format((DEFAULT_SERVER_PORT + 1)) visualization_help = 'Visualisation at {}/visualization.html.'.format(visualization_url) else: visualization_help = rasa.cli.utils.print_success("Bot loaded. {}\nType a message and press enter (press 'Ctr-c' to exit). ".format(visualization_help))
def _print_help(skip_visualization: bool) -> None: if (not skip_visualization): visualization_url = DEFAULT_SERVER_FORMAT.format((DEFAULT_SERVER_PORT + 1)) visualization_help = 'Visualisation at {}/visualization.html.'.format(visualization_url) else: visualization_help = rasa.cli.utils.print_success("Bot loaded. {}\nType a message and press enter (press 'Ctr-c' to exit). ".format(visualization_help))<|docstring|>Print some initial help message for the user.<|endoftext|>
5799b1995d299dc2948474e8263ec3892920e660e82896aff9da192a2a63a42a
async def record_messages(endpoint: EndpointConfig, sender_id: Text=UserMessage.DEFAULT_SENDER_ID, max_message_limit: Optional[int]=None, finetune: bool=False, stories: Optional[Text]=None, skip_visualization: bool=False): 'Read messages from the command line and print bot responses.' from rasa.core import training try: _print_help(skip_visualization) try: domain = (await retrieve_domain(endpoint)) except ClientError: logger.exception("Failed to connect to Rasa Core server at '{}'. Is the server running?".format(endpoint.url)) return trackers = (await training.load_data(stories, Domain.from_dict(domain), augmentation_factor=0, use_story_concatenation=False)) intents = [next(iter(i)) for i in (domain.get('intents') or [])] num_messages = 0 sender_ids = ([t.events for t in trackers] + [sender_id]) if (not skip_visualization): plot_file = 'story_graph.dot' (await _plot_trackers(sender_ids, plot_file, endpoint)) else: plot_file = None while (not utils.is_limit_reached(num_messages, max_message_limit)): try: if (await is_listening_for_message(sender_id, endpoint)): (await _enter_user_message(sender_id, endpoint)) (await _validate_nlu(intents, endpoint, sender_id)) (await _predict_till_next_listen(endpoint, sender_id, finetune, sender_ids, plot_file)) num_messages += 1 except RestartConversation: (await send_event(endpoint, sender_id, Restarted().as_dict())) (await send_event(endpoint, sender_id, ActionExecuted(ACTION_LISTEN_NAME).as_dict())) logger.info('Restarted conversation, starting a new one.') except UndoLastStep: (await _undo_latest(sender_id, endpoint)) (await _print_history(sender_id, endpoint)) except ForkTracker: (await _print_history(sender_id, endpoint)) evts_fork = (await _request_fork_from_user(sender_id, endpoint)) (await send_event(endpoint, sender_id, Restarted().as_dict())) if evts_fork: for evt in evts_fork: (await send_event(endpoint, sender_id, evt)) logger.info('Restarted conversation at fork.') (await _print_history(sender_id, endpoint)) (await _plot_trackers(sender_ids, plot_file, endpoint)) except Abort: return except Exception: logger.exception('An exception occurred while recording messages.') raise
Read messages from the command line and print bot responses.
rasa/core/training/interactive.py
record_messages
LaudateCorpus1/rasa_core
2,433
python
async def record_messages(endpoint: EndpointConfig, sender_id: Text=UserMessage.DEFAULT_SENDER_ID, max_message_limit: Optional[int]=None, finetune: bool=False, stories: Optional[Text]=None, skip_visualization: bool=False): from rasa.core import training try: _print_help(skip_visualization) try: domain = (await retrieve_domain(endpoint)) except ClientError: logger.exception("Failed to connect to Rasa Core server at '{}'. Is the server running?".format(endpoint.url)) return trackers = (await training.load_data(stories, Domain.from_dict(domain), augmentation_factor=0, use_story_concatenation=False)) intents = [next(iter(i)) for i in (domain.get('intents') or [])] num_messages = 0 sender_ids = ([t.events for t in trackers] + [sender_id]) if (not skip_visualization): plot_file = 'story_graph.dot' (await _plot_trackers(sender_ids, plot_file, endpoint)) else: plot_file = None while (not utils.is_limit_reached(num_messages, max_message_limit)): try: if (await is_listening_for_message(sender_id, endpoint)): (await _enter_user_message(sender_id, endpoint)) (await _validate_nlu(intents, endpoint, sender_id)) (await _predict_till_next_listen(endpoint, sender_id, finetune, sender_ids, plot_file)) num_messages += 1 except RestartConversation: (await send_event(endpoint, sender_id, Restarted().as_dict())) (await send_event(endpoint, sender_id, ActionExecuted(ACTION_LISTEN_NAME).as_dict())) logger.info('Restarted conversation, starting a new one.') except UndoLastStep: (await _undo_latest(sender_id, endpoint)) (await _print_history(sender_id, endpoint)) except ForkTracker: (await _print_history(sender_id, endpoint)) evts_fork = (await _request_fork_from_user(sender_id, endpoint)) (await send_event(endpoint, sender_id, Restarted().as_dict())) if evts_fork: for evt in evts_fork: (await send_event(endpoint, sender_id, evt)) logger.info('Restarted conversation at fork.') (await _print_history(sender_id, endpoint)) (await _plot_trackers(sender_ids, plot_file, endpoint)) except Abort: return except Exception: logger.exception('An exception occurred while recording messages.') raise
async def record_messages(endpoint: EndpointConfig, sender_id: Text=UserMessage.DEFAULT_SENDER_ID, max_message_limit: Optional[int]=None, finetune: bool=False, stories: Optional[Text]=None, skip_visualization: bool=False): from rasa.core import training try: _print_help(skip_visualization) try: domain = (await retrieve_domain(endpoint)) except ClientError: logger.exception("Failed to connect to Rasa Core server at '{}'. Is the server running?".format(endpoint.url)) return trackers = (await training.load_data(stories, Domain.from_dict(domain), augmentation_factor=0, use_story_concatenation=False)) intents = [next(iter(i)) for i in (domain.get('intents') or [])] num_messages = 0 sender_ids = ([t.events for t in trackers] + [sender_id]) if (not skip_visualization): plot_file = 'story_graph.dot' (await _plot_trackers(sender_ids, plot_file, endpoint)) else: plot_file = None while (not utils.is_limit_reached(num_messages, max_message_limit)): try: if (await is_listening_for_message(sender_id, endpoint)): (await _enter_user_message(sender_id, endpoint)) (await _validate_nlu(intents, endpoint, sender_id)) (await _predict_till_next_listen(endpoint, sender_id, finetune, sender_ids, plot_file)) num_messages += 1 except RestartConversation: (await send_event(endpoint, sender_id, Restarted().as_dict())) (await send_event(endpoint, sender_id, ActionExecuted(ACTION_LISTEN_NAME).as_dict())) logger.info('Restarted conversation, starting a new one.') except UndoLastStep: (await _undo_latest(sender_id, endpoint)) (await _print_history(sender_id, endpoint)) except ForkTracker: (await _print_history(sender_id, endpoint)) evts_fork = (await _request_fork_from_user(sender_id, endpoint)) (await send_event(endpoint, sender_id, Restarted().as_dict())) if evts_fork: for evt in evts_fork: (await send_event(endpoint, sender_id, evt)) logger.info('Restarted conversation at fork.') (await _print_history(sender_id, endpoint)) (await _plot_trackers(sender_ids, plot_file, endpoint)) except Abort: return except Exception: logger.exception('An exception occurred while recording messages.') raise<|docstring|>Read messages from the command line and print bot responses.<|endoftext|>
729c046370ab8bbb53e9d991d7e944106d1655b66253a7863926e179ddff73a5
def _serve_application(app, stories, finetune, skip_visualization): 'Start a core server and attach the interactive learning IO.' endpoint = EndpointConfig(url=DEFAULT_SERVER_URL) async def run_interactive_io(running_app: Sanic): 'Small wrapper to shut down the server once cmd io is done.' (await record_messages(endpoint=endpoint, stories=stories, finetune=finetune, skip_visualization=skip_visualization, sender_id=uuid.uuid4().hex)) logger.info('Killing Sanic server now.') running_app.stop() app.add_task(run_interactive_io) app.run(host='0.0.0.0', port=DEFAULT_SERVER_PORT, access_log=True) return app
Start a core server and attach the interactive learning IO.
rasa/core/training/interactive.py
_serve_application
LaudateCorpus1/rasa_core
2,433
python
def _serve_application(app, stories, finetune, skip_visualization): endpoint = EndpointConfig(url=DEFAULT_SERVER_URL) async def run_interactive_io(running_app: Sanic): 'Small wrapper to shut down the server once cmd io is done.' (await record_messages(endpoint=endpoint, stories=stories, finetune=finetune, skip_visualization=skip_visualization, sender_id=uuid.uuid4().hex)) logger.info('Killing Sanic server now.') running_app.stop() app.add_task(run_interactive_io) app.run(host='0.0.0.0', port=DEFAULT_SERVER_PORT, access_log=True) return app
def _serve_application(app, stories, finetune, skip_visualization): endpoint = EndpointConfig(url=DEFAULT_SERVER_URL) async def run_interactive_io(running_app: Sanic): 'Small wrapper to shut down the server once cmd io is done.' (await record_messages(endpoint=endpoint, stories=stories, finetune=finetune, skip_visualization=skip_visualization, sender_id=uuid.uuid4().hex)) logger.info('Killing Sanic server now.') running_app.stop() app.add_task(run_interactive_io) app.run(host='0.0.0.0', port=DEFAULT_SERVER_PORT, access_log=True) return app<|docstring|>Start a core server and attach the interactive learning IO.<|endoftext|>
709cad7fd9ac1e15607926417c74a25489658c1cbb413c656cb0718c62eda0ab
def start_visualization(image_path: Text=None) -> None: 'Add routes to serve the conversation visualization files.' app = Sanic(__name__) @app.exception(NotFound) async def ignore_404s(request, exception): return response.text('Not found', status=404) @app.route(VISUALIZATION_TEMPLATE_PATH, methods=['GET']) def visualisation_html(request): return response.file(visualization.visualization_html_path()) @app.route('/visualization.dot', methods=['GET']) def visualisation_png(request): try: headers = {'Cache-Control': 'no-cache'} return response.file(os.path.abspath(image_path), headers=headers) except FileNotFoundError: return response.text('', 404) app.run(host='0.0.0.0', port=(DEFAULT_SERVER_PORT + 1), access_log=False)
Add routes to serve the conversation visualization files.
rasa/core/training/interactive.py
start_visualization
LaudateCorpus1/rasa_core
2,433
python
def start_visualization(image_path: Text=None) -> None: app = Sanic(__name__) @app.exception(NotFound) async def ignore_404s(request, exception): return response.text('Not found', status=404) @app.route(VISUALIZATION_TEMPLATE_PATH, methods=['GET']) def visualisation_html(request): return response.file(visualization.visualization_html_path()) @app.route('/visualization.dot', methods=['GET']) def visualisation_png(request): try: headers = {'Cache-Control': 'no-cache'} return response.file(os.path.abspath(image_path), headers=headers) except FileNotFoundError: return response.text(, 404) app.run(host='0.0.0.0', port=(DEFAULT_SERVER_PORT + 1), access_log=False)
def start_visualization(image_path: Text=None) -> None: app = Sanic(__name__) @app.exception(NotFound) async def ignore_404s(request, exception): return response.text('Not found', status=404) @app.route(VISUALIZATION_TEMPLATE_PATH, methods=['GET']) def visualisation_html(request): return response.file(visualization.visualization_html_path()) @app.route('/visualization.dot', methods=['GET']) def visualisation_png(request): try: headers = {'Cache-Control': 'no-cache'} return response.file(os.path.abspath(image_path), headers=headers) except FileNotFoundError: return response.text(, 404) app.run(host='0.0.0.0', port=(DEFAULT_SERVER_PORT + 1), access_log=False)<|docstring|>Add routes to serve the conversation visualization files.<|endoftext|>
99a1696e53e3f7cda58c8a64b9aca470f7ee3a0040239da26846671f20a3d9f3
async def wait_til_server_is_running(endpoint, max_retries=30, sleep_between_retries=1): 'Try to reach the server, retry a couple of times and sleep in between.' while max_retries: try: r = (await retrieve_status(endpoint)) logger.info('Reached core: {}'.format(r)) if (not r.get('is_ready')): (await asyncio.sleep(sleep_between_retries)) continue else: return True except ClientError: max_retries -= 1 if max_retries: (await asyncio.sleep(sleep_between_retries)) return False
Try to reach the server, retry a couple of times and sleep in between.
rasa/core/training/interactive.py
wait_til_server_is_running
LaudateCorpus1/rasa_core
2,433
python
async def wait_til_server_is_running(endpoint, max_retries=30, sleep_between_retries=1): while max_retries: try: r = (await retrieve_status(endpoint)) logger.info('Reached core: {}'.format(r)) if (not r.get('is_ready')): (await asyncio.sleep(sleep_between_retries)) continue else: return True except ClientError: max_retries -= 1 if max_retries: (await asyncio.sleep(sleep_between_retries)) return False
async def wait_til_server_is_running(endpoint, max_retries=30, sleep_between_retries=1): while max_retries: try: r = (await retrieve_status(endpoint)) logger.info('Reached core: {}'.format(r)) if (not r.get('is_ready')): (await asyncio.sleep(sleep_between_retries)) continue else: return True except ClientError: max_retries -= 1 if max_retries: (await asyncio.sleep(sleep_between_retries)) return False<|docstring|>Try to reach the server, retry a couple of times and sleep in between.<|endoftext|>
11267bf435e4ddb2ae6568ee3cea624d01b67deba7c6605f07e0236704ceea8a
def run_interactive_learning(stories: Text=None, finetune: bool=False, skip_visualization: bool=False, server_args: Dict[(Text, Any)]=None, additional_arguments: Dict[(Text, Any)]=None): 'Start the interactive learning with the model of the agent.' server_args = (server_args or {}) if (not skip_visualization): p = Process(target=start_visualization, args=('story_graph.dot',)) p.deamon = True p.start() else: p = None app = run.configure_app(enable_api=True) endpoints = AvailableEndpoints.read_endpoints(server_args.get('endpoints')) if server_args.get('core'): app.register_listener(partial(run.load_agent_on_start, server_args.get('core'), endpoints, server_args.get('nlu')), 'before_server_start') else: app.register_listener(partial(train_agent_on_start, server_args, endpoints, additional_arguments), 'before_server_start') _serve_application(app, stories, finetune, skip_visualization) if (not skip_visualization): p.terminate() p.join()
Start the interactive learning with the model of the agent.
rasa/core/training/interactive.py
run_interactive_learning
LaudateCorpus1/rasa_core
2,433
python
def run_interactive_learning(stories: Text=None, finetune: bool=False, skip_visualization: bool=False, server_args: Dict[(Text, Any)]=None, additional_arguments: Dict[(Text, Any)]=None): server_args = (server_args or {}) if (not skip_visualization): p = Process(target=start_visualization, args=('story_graph.dot',)) p.deamon = True p.start() else: p = None app = run.configure_app(enable_api=True) endpoints = AvailableEndpoints.read_endpoints(server_args.get('endpoints')) if server_args.get('core'): app.register_listener(partial(run.load_agent_on_start, server_args.get('core'), endpoints, server_args.get('nlu')), 'before_server_start') else: app.register_listener(partial(train_agent_on_start, server_args, endpoints, additional_arguments), 'before_server_start') _serve_application(app, stories, finetune, skip_visualization) if (not skip_visualization): p.terminate() p.join()
def run_interactive_learning(stories: Text=None, finetune: bool=False, skip_visualization: bool=False, server_args: Dict[(Text, Any)]=None, additional_arguments: Dict[(Text, Any)]=None): server_args = (server_args or {}) if (not skip_visualization): p = Process(target=start_visualization, args=('story_graph.dot',)) p.deamon = True p.start() else: p = None app = run.configure_app(enable_api=True) endpoints = AvailableEndpoints.read_endpoints(server_args.get('endpoints')) if server_args.get('core'): app.register_listener(partial(run.load_agent_on_start, server_args.get('core'), endpoints, server_args.get('nlu')), 'before_server_start') else: app.register_listener(partial(train_agent_on_start, server_args, endpoints, additional_arguments), 'before_server_start') _serve_application(app, stories, finetune, skip_visualization) if (not skip_visualization): p.terminate() p.join()<|docstring|>Start the interactive learning with the model of the agent.<|endoftext|>
436a8a1c6ae1bf2cb41cb78663607bcc6a350545e439bbb8f931a39e7a23cd02
async def run_interactive_io(running_app: Sanic): 'Small wrapper to shut down the server once cmd io is done.' (await record_messages(endpoint=endpoint, stories=stories, finetune=finetune, skip_visualization=skip_visualization, sender_id=uuid.uuid4().hex)) logger.info('Killing Sanic server now.') running_app.stop()
Small wrapper to shut down the server once cmd io is done.
rasa/core/training/interactive.py
run_interactive_io
LaudateCorpus1/rasa_core
2,433
python
async def run_interactive_io(running_app: Sanic): (await record_messages(endpoint=endpoint, stories=stories, finetune=finetune, skip_visualization=skip_visualization, sender_id=uuid.uuid4().hex)) logger.info('Killing Sanic server now.') running_app.stop()
async def run_interactive_io(running_app: Sanic): (await record_messages(endpoint=endpoint, stories=stories, finetune=finetune, skip_visualization=skip_visualization, sender_id=uuid.uuid4().hex)) logger.info('Killing Sanic server now.') running_app.stop()<|docstring|>Small wrapper to shut down the server once cmd io is done.<|endoftext|>
d316230f82467dc870b6d443437854194685cdc15b0ab8caa781e40e61fef35d
def __init__(self, url=None, current_name=None, description=None, columns=None, num_records=None, bytes=None, repo=None, documentation=None, local_vars_configuration=None): 'Table - a model defined in OpenAPI' if (local_vars_configuration is None): local_vars_configuration = Configuration() self.local_vars_configuration = local_vars_configuration self._url = None self._current_name = None self._description = None self._columns = None self._num_records = None self._bytes = None self._repo = None self._documentation = None self.discriminator = None if (url is not None): self.url = url if (current_name is not None): self.current_name = current_name if (description is not None): self.description = description if (columns is not None): self.columns = columns if (num_records is not None): self.num_records = num_records if (bytes is not None): self.bytes = bytes if (repo is not None): self.repo = repo if (documentation is not None): self.documentation = documentation
Table - a model defined in OpenAPI
bitdotio/models/table.py
__init__
bitdotioinc/python-bitdotio
6
python
def __init__(self, url=None, current_name=None, description=None, columns=None, num_records=None, bytes=None, repo=None, documentation=None, local_vars_configuration=None): if (local_vars_configuration is None): local_vars_configuration = Configuration() self.local_vars_configuration = local_vars_configuration self._url = None self._current_name = None self._description = None self._columns = None self._num_records = None self._bytes = None self._repo = None self._documentation = None self.discriminator = None if (url is not None): self.url = url if (current_name is not None): self.current_name = current_name if (description is not None): self.description = description if (columns is not None): self.columns = columns if (num_records is not None): self.num_records = num_records if (bytes is not None): self.bytes = bytes if (repo is not None): self.repo = repo if (documentation is not None): self.documentation = documentation
def __init__(self, url=None, current_name=None, description=None, columns=None, num_records=None, bytes=None, repo=None, documentation=None, local_vars_configuration=None): if (local_vars_configuration is None): local_vars_configuration = Configuration() self.local_vars_configuration = local_vars_configuration self._url = None self._current_name = None self._description = None self._columns = None self._num_records = None self._bytes = None self._repo = None self._documentation = None self.discriminator = None if (url is not None): self.url = url if (current_name is not None): self.current_name = current_name if (description is not None): self.description = description if (columns is not None): self.columns = columns if (num_records is not None): self.num_records = num_records if (bytes is not None): self.bytes = bytes if (repo is not None): self.repo = repo if (documentation is not None): self.documentation = documentation<|docstring|>Table - a model defined in OpenAPI<|endoftext|>
e3d77a9ba660d05cb9acf6c48a7e830458b2fee59bd23b6c583df78147b65bdd
@property def url(self): 'Gets the url of this Table. # noqa: E501\n\n\n :return: The url of this Table. # noqa: E501\n :rtype: str\n ' return self._url
Gets the url of this Table. # noqa: E501 :return: The url of this Table. # noqa: E501 :rtype: str
bitdotio/models/table.py
url
bitdotioinc/python-bitdotio
6
python
@property def url(self): 'Gets the url of this Table. # noqa: E501\n\n\n :return: The url of this Table. # noqa: E501\n :rtype: str\n ' return self._url
@property def url(self): 'Gets the url of this Table. # noqa: E501\n\n\n :return: The url of this Table. # noqa: E501\n :rtype: str\n ' return self._url<|docstring|>Gets the url of this Table. # noqa: E501 :return: The url of this Table. # noqa: E501 :rtype: str<|endoftext|>
a3aa6e44818719df44659f8c68e707d7e708f4387ad59da451e4bbfa08d280de
@url.setter def url(self, url): 'Sets the url of this Table.\n\n\n :param url: The url of this Table. # noqa: E501\n :type: str\n ' self._url = url
Sets the url of this Table. :param url: The url of this Table. # noqa: E501 :type: str
bitdotio/models/table.py
url
bitdotioinc/python-bitdotio
6
python
@url.setter def url(self, url): 'Sets the url of this Table.\n\n\n :param url: The url of this Table. # noqa: E501\n :type: str\n ' self._url = url
@url.setter def url(self, url): 'Sets the url of this Table.\n\n\n :param url: The url of this Table. # noqa: E501\n :type: str\n ' self._url = url<|docstring|>Sets the url of this Table. :param url: The url of this Table. # noqa: E501 :type: str<|endoftext|>
91eeb1fff3fcca628696868978ef9cb0bf594ec8b00269e6fb52a2f846a11c96
@property def current_name(self): 'Gets the current_name of this Table. # noqa: E501\n\n\n :return: The current_name of this Table. # noqa: E501\n :rtype: str\n ' return self._current_name
Gets the current_name of this Table. # noqa: E501 :return: The current_name of this Table. # noqa: E501 :rtype: str
bitdotio/models/table.py
current_name
bitdotioinc/python-bitdotio
6
python
@property def current_name(self): 'Gets the current_name of this Table. # noqa: E501\n\n\n :return: The current_name of this Table. # noqa: E501\n :rtype: str\n ' return self._current_name
@property def current_name(self): 'Gets the current_name of this Table. # noqa: E501\n\n\n :return: The current_name of this Table. # noqa: E501\n :rtype: str\n ' return self._current_name<|docstring|>Gets the current_name of this Table. # noqa: E501 :return: The current_name of this Table. # noqa: E501 :rtype: str<|endoftext|>
2699ad9e55ff49446381d51586607aed91ff869dd8687c627dab0a9f3b5e4dab
@current_name.setter def current_name(self, current_name): 'Sets the current_name of this Table.\n\n\n :param current_name: The current_name of this Table. # noqa: E501\n :type: str\n ' self._current_name = current_name
Sets the current_name of this Table. :param current_name: The current_name of this Table. # noqa: E501 :type: str
bitdotio/models/table.py
current_name
bitdotioinc/python-bitdotio
6
python
@current_name.setter def current_name(self, current_name): 'Sets the current_name of this Table.\n\n\n :param current_name: The current_name of this Table. # noqa: E501\n :type: str\n ' self._current_name = current_name
@current_name.setter def current_name(self, current_name): 'Sets the current_name of this Table.\n\n\n :param current_name: The current_name of this Table. # noqa: E501\n :type: str\n ' self._current_name = current_name<|docstring|>Sets the current_name of this Table. :param current_name: The current_name of this Table. # noqa: E501 :type: str<|endoftext|>
bcf7df2a41cf9df943779c125c25bfe0662c754718cc92f23bbdb06d4485e95c
@property def description(self): 'Gets the description of this Table. # noqa: E501\n\n\n :return: The description of this Table. # noqa: E501\n :rtype: str\n ' return self._description
Gets the description of this Table. # noqa: E501 :return: The description of this Table. # noqa: E501 :rtype: str
bitdotio/models/table.py
description
bitdotioinc/python-bitdotio
6
python
@property def description(self): 'Gets the description of this Table. # noqa: E501\n\n\n :return: The description of this Table. # noqa: E501\n :rtype: str\n ' return self._description
@property def description(self): 'Gets the description of this Table. # noqa: E501\n\n\n :return: The description of this Table. # noqa: E501\n :rtype: str\n ' return self._description<|docstring|>Gets the description of this Table. # noqa: E501 :return: The description of this Table. # noqa: E501 :rtype: str<|endoftext|>
7a961da5132e108b018c6c87be1f52497264cde4baf7ca961ed4829b40342f92
@description.setter def description(self, description): 'Sets the description of this Table.\n\n\n :param description: The description of this Table. # noqa: E501\n :type: str\n ' if (self.local_vars_configuration.client_side_validation and (description is not None) and (len(description) > 400)): raise ValueError('Invalid value for `description`, length must be less than or equal to `400`') self._description = description
Sets the description of this Table. :param description: The description of this Table. # noqa: E501 :type: str
bitdotio/models/table.py
description
bitdotioinc/python-bitdotio
6
python
@description.setter def description(self, description): 'Sets the description of this Table.\n\n\n :param description: The description of this Table. # noqa: E501\n :type: str\n ' if (self.local_vars_configuration.client_side_validation and (description is not None) and (len(description) > 400)): raise ValueError('Invalid value for `description`, length must be less than or equal to `400`') self._description = description
@description.setter def description(self, description): 'Sets the description of this Table.\n\n\n :param description: The description of this Table. # noqa: E501\n :type: str\n ' if (self.local_vars_configuration.client_side_validation and (description is not None) and (len(description) > 400)): raise ValueError('Invalid value for `description`, length must be less than or equal to `400`') self._description = description<|docstring|>Sets the description of this Table. :param description: The description of this Table. # noqa: E501 :type: str<|endoftext|>
4e507d40f60ba7e51630b41658c0449ec8150569c6890ff20aa363a14d90dafb
@property def columns(self): 'Gets the columns of this Table. # noqa: E501\n\n\n :return: The columns of this Table. # noqa: E501\n :rtype: list[str]\n ' return self._columns
Gets the columns of this Table. # noqa: E501 :return: The columns of this Table. # noqa: E501 :rtype: list[str]
bitdotio/models/table.py
columns
bitdotioinc/python-bitdotio
6
python
@property def columns(self): 'Gets the columns of this Table. # noqa: E501\n\n\n :return: The columns of this Table. # noqa: E501\n :rtype: list[str]\n ' return self._columns
@property def columns(self): 'Gets the columns of this Table. # noqa: E501\n\n\n :return: The columns of this Table. # noqa: E501\n :rtype: list[str]\n ' return self._columns<|docstring|>Gets the columns of this Table. # noqa: E501 :return: The columns of this Table. # noqa: E501 :rtype: list[str]<|endoftext|>
31038337a802ccc104e5def77739b48bccd8fd529636c80106f5cefb606ed583
@columns.setter def columns(self, columns): 'Sets the columns of this Table.\n\n\n :param columns: The columns of this Table. # noqa: E501\n :type: list[str]\n ' self._columns = columns
Sets the columns of this Table. :param columns: The columns of this Table. # noqa: E501 :type: list[str]
bitdotio/models/table.py
columns
bitdotioinc/python-bitdotio
6
python
@columns.setter def columns(self, columns): 'Sets the columns of this Table.\n\n\n :param columns: The columns of this Table. # noqa: E501\n :type: list[str]\n ' self._columns = columns
@columns.setter def columns(self, columns): 'Sets the columns of this Table.\n\n\n :param columns: The columns of this Table. # noqa: E501\n :type: list[str]\n ' self._columns = columns<|docstring|>Sets the columns of this Table. :param columns: The columns of this Table. # noqa: E501 :type: list[str]<|endoftext|>
5bacabd1f9edb43c4b207858bbc9e75959e29b6c86616b8bc46cd7d414e52f79
@property def num_records(self): 'Gets the num_records of this Table. # noqa: E501\n\n\n :return: The num_records of this Table. # noqa: E501\n :rtype: int\n ' return self._num_records
Gets the num_records of this Table. # noqa: E501 :return: The num_records of this Table. # noqa: E501 :rtype: int
bitdotio/models/table.py
num_records
bitdotioinc/python-bitdotio
6
python
@property def num_records(self): 'Gets the num_records of this Table. # noqa: E501\n\n\n :return: The num_records of this Table. # noqa: E501\n :rtype: int\n ' return self._num_records
@property def num_records(self): 'Gets the num_records of this Table. # noqa: E501\n\n\n :return: The num_records of this Table. # noqa: E501\n :rtype: int\n ' return self._num_records<|docstring|>Gets the num_records of this Table. # noqa: E501 :return: The num_records of this Table. # noqa: E501 :rtype: int<|endoftext|>
9fdab535bad0ff1e5ac1acf489a90230c15b991c4b4a5b40a96a3787f23006e0
@num_records.setter def num_records(self, num_records): 'Sets the num_records of this Table.\n\n\n :param num_records: The num_records of this Table. # noqa: E501\n :type: int\n ' self._num_records = num_records
Sets the num_records of this Table. :param num_records: The num_records of this Table. # noqa: E501 :type: int
bitdotio/models/table.py
num_records
bitdotioinc/python-bitdotio
6
python
@num_records.setter def num_records(self, num_records): 'Sets the num_records of this Table.\n\n\n :param num_records: The num_records of this Table. # noqa: E501\n :type: int\n ' self._num_records = num_records
@num_records.setter def num_records(self, num_records): 'Sets the num_records of this Table.\n\n\n :param num_records: The num_records of this Table. # noqa: E501\n :type: int\n ' self._num_records = num_records<|docstring|>Sets the num_records of this Table. :param num_records: The num_records of this Table. # noqa: E501 :type: int<|endoftext|>
4ae88e28b52daff5c282c8d64c9e0f6f097e4b6d34dece99e059f815b3cb47e7
@property def bytes(self): 'Gets the bytes of this Table. # noqa: E501\n\n\n :return: The bytes of this Table. # noqa: E501\n :rtype: str\n ' return self._bytes
Gets the bytes of this Table. # noqa: E501 :return: The bytes of this Table. # noqa: E501 :rtype: str
bitdotio/models/table.py
bytes
bitdotioinc/python-bitdotio
6
python
@property def bytes(self): 'Gets the bytes of this Table. # noqa: E501\n\n\n :return: The bytes of this Table. # noqa: E501\n :rtype: str\n ' return self._bytes
@property def bytes(self): 'Gets the bytes of this Table. # noqa: E501\n\n\n :return: The bytes of this Table. # noqa: E501\n :rtype: str\n ' return self._bytes<|docstring|>Gets the bytes of this Table. # noqa: E501 :return: The bytes of this Table. # noqa: E501 :rtype: str<|endoftext|>
ec975c8d2b17179e409272e2cd9f5bf1819c2312ea35afc2eaa9d543c457f53c
@bytes.setter def bytes(self, bytes): 'Sets the bytes of this Table.\n\n\n :param bytes: The bytes of this Table. # noqa: E501\n :type: str\n ' self._bytes = bytes
Sets the bytes of this Table. :param bytes: The bytes of this Table. # noqa: E501 :type: str
bitdotio/models/table.py
bytes
bitdotioinc/python-bitdotio
6
python
@bytes.setter def bytes(self, bytes): 'Sets the bytes of this Table.\n\n\n :param bytes: The bytes of this Table. # noqa: E501\n :type: str\n ' self._bytes = bytes
@bytes.setter def bytes(self, bytes): 'Sets the bytes of this Table.\n\n\n :param bytes: The bytes of this Table. # noqa: E501\n :type: str\n ' self._bytes = bytes<|docstring|>Sets the bytes of this Table. :param bytes: The bytes of this Table. # noqa: E501 :type: str<|endoftext|>
f8a68cb38fe450bc601c36d3143d16d9c50c2b8a76c03edda4bb10cb75d05510
@property def repo(self): 'Gets the repo of this Table. # noqa: E501\n\n\n :return: The repo of this Table. # noqa: E501\n :rtype: str\n ' return self._repo
Gets the repo of this Table. # noqa: E501 :return: The repo of this Table. # noqa: E501 :rtype: str
bitdotio/models/table.py
repo
bitdotioinc/python-bitdotio
6
python
@property def repo(self): 'Gets the repo of this Table. # noqa: E501\n\n\n :return: The repo of this Table. # noqa: E501\n :rtype: str\n ' return self._repo
@property def repo(self): 'Gets the repo of this Table. # noqa: E501\n\n\n :return: The repo of this Table. # noqa: E501\n :rtype: str\n ' return self._repo<|docstring|>Gets the repo of this Table. # noqa: E501 :return: The repo of this Table. # noqa: E501 :rtype: str<|endoftext|>
264399e7422de6b89871ce95138f5e2423bf3d4d2b710e0bf40ff30ec5132005
@repo.setter def repo(self, repo): 'Sets the repo of this Table.\n\n\n :param repo: The repo of this Table. # noqa: E501\n :type: str\n ' self._repo = repo
Sets the repo of this Table. :param repo: The repo of this Table. # noqa: E501 :type: str
bitdotio/models/table.py
repo
bitdotioinc/python-bitdotio
6
python
@repo.setter def repo(self, repo): 'Sets the repo of this Table.\n\n\n :param repo: The repo of this Table. # noqa: E501\n :type: str\n ' self._repo = repo
@repo.setter def repo(self, repo): 'Sets the repo of this Table.\n\n\n :param repo: The repo of this Table. # noqa: E501\n :type: str\n ' self._repo = repo<|docstring|>Sets the repo of this Table. :param repo: The repo of this Table. # noqa: E501 :type: str<|endoftext|>
d97c93feb5f08f3dfcbc2b465dba12c7dd085d21082a4bed61f65cb6ccf362df
@property def documentation(self): 'Gets the documentation of this Table. # noqa: E501\n\n\n :return: The documentation of this Table. # noqa: E501\n :rtype: str\n ' return self._documentation
Gets the documentation of this Table. # noqa: E501 :return: The documentation of this Table. # noqa: E501 :rtype: str
bitdotio/models/table.py
documentation
bitdotioinc/python-bitdotio
6
python
@property def documentation(self): 'Gets the documentation of this Table. # noqa: E501\n\n\n :return: The documentation of this Table. # noqa: E501\n :rtype: str\n ' return self._documentation
@property def documentation(self): 'Gets the documentation of this Table. # noqa: E501\n\n\n :return: The documentation of this Table. # noqa: E501\n :rtype: str\n ' return self._documentation<|docstring|>Gets the documentation of this Table. # noqa: E501 :return: The documentation of this Table. # noqa: E501 :rtype: str<|endoftext|>
6ef6f167acdf837e54245f1ebf10d93552ae928fbeb1aeb9dc00ce175592709f
@documentation.setter def documentation(self, documentation): 'Sets the documentation of this Table.\n\n\n :param documentation: The documentation of this Table. # noqa: E501\n :type: str\n ' self._documentation = documentation
Sets the documentation of this Table. :param documentation: The documentation of this Table. # noqa: E501 :type: str
bitdotio/models/table.py
documentation
bitdotioinc/python-bitdotio
6
python
@documentation.setter def documentation(self, documentation): 'Sets the documentation of this Table.\n\n\n :param documentation: The documentation of this Table. # noqa: E501\n :type: str\n ' self._documentation = documentation
@documentation.setter def documentation(self, documentation): 'Sets the documentation of this Table.\n\n\n :param documentation: The documentation of this Table. # noqa: E501\n :type: str\n ' self._documentation = documentation<|docstring|>Sets the documentation of this Table. :param documentation: The documentation of this Table. # noqa: E501 :type: str<|endoftext|>
5a4e41bb6a0def746593298cb605df98f1366e957c4ca89b12010ea7db707963
def to_dict(self): 'Returns the model properties as a dict' result = {} for (attr, _) in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map((lambda x: (x.to_dict() if hasattr(x, 'to_dict') else x)), value)) elif hasattr(value, 'to_dict'): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map((lambda item: ((item[0], item[1].to_dict()) if hasattr(item[1], 'to_dict') else item)), value.items())) else: result[attr] = value return result
Returns the model properties as a dict
bitdotio/models/table.py
to_dict
bitdotioinc/python-bitdotio
6
python
def to_dict(self): result = {} for (attr, _) in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map((lambda x: (x.to_dict() if hasattr(x, 'to_dict') else x)), value)) elif hasattr(value, 'to_dict'): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map((lambda item: ((item[0], item[1].to_dict()) if hasattr(item[1], 'to_dict') else item)), value.items())) else: result[attr] = value return result
def to_dict(self): result = {} for (attr, _) in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map((lambda x: (x.to_dict() if hasattr(x, 'to_dict') else x)), value)) elif hasattr(value, 'to_dict'): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map((lambda item: ((item[0], item[1].to_dict()) if hasattr(item[1], 'to_dict') else item)), value.items())) else: result[attr] = value return result<|docstring|>Returns the model properties as a dict<|endoftext|>
cbb19eaa2fc8a113d9e32f924ef280a7e97563f8915f94f65dab438997af2e99
def to_str(self): 'Returns the string representation of the model' return pprint.pformat(self.to_dict())
Returns the string representation of the model
bitdotio/models/table.py
to_str
bitdotioinc/python-bitdotio
6
python
def to_str(self): return pprint.pformat(self.to_dict())
def to_str(self): return pprint.pformat(self.to_dict())<|docstring|>Returns the string representation of the model<|endoftext|>
772243a2c2b3261a9b954d07aaf295e3c1242a579a495e2d6a5679c677861703
def __repr__(self): 'For `print` and `pprint`' return self.to_str()
For `print` and `pprint`
bitdotio/models/table.py
__repr__
bitdotioinc/python-bitdotio
6
python
def __repr__(self): return self.to_str()
def __repr__(self): return self.to_str()<|docstring|>For `print` and `pprint`<|endoftext|>
ff04dcf8c85aa636696a4a1f89300238364c886ec7cd732ffaf78cc08cadd2cf
def __eq__(self, other): 'Returns true if both objects are equal' if (not isinstance(other, Table)): return False return (self.to_dict() == other.to_dict())
Returns true if both objects are equal
bitdotio/models/table.py
__eq__
bitdotioinc/python-bitdotio
6
python
def __eq__(self, other): if (not isinstance(other, Table)): return False return (self.to_dict() == other.to_dict())
def __eq__(self, other): if (not isinstance(other, Table)): return False return (self.to_dict() == other.to_dict())<|docstring|>Returns true if both objects are equal<|endoftext|>
d370ae807c5c2975f94243c04d6c048bb00a73441edba8ee13cdcf70052378c9
def __ne__(self, other): 'Returns true if both objects are not equal' if (not isinstance(other, Table)): return True return (self.to_dict() != other.to_dict())
Returns true if both objects are not equal
bitdotio/models/table.py
__ne__
bitdotioinc/python-bitdotio
6
python
def __ne__(self, other): if (not isinstance(other, Table)): return True return (self.to_dict() != other.to_dict())
def __ne__(self, other): if (not isinstance(other, Table)): return True return (self.to_dict() != other.to_dict())<|docstring|>Returns true if both objects are not equal<|endoftext|>
b38a52d83bddd9c1a8dc2e4f9d18f1c96005d1a2449294558393afd841778e18
def cipher(text, shift, encrypt=True): '\n Function to encipher or decipher the string by using different shift number.\n \n Parameters\n ----------\n text : string\n A string that you wish to encipher or decipher.\n shift : integer\n An integer that you wish to shift.\n encrypt : boolean\n A boolean that you would like to encrypt string or not.\n \n Returns\n -------\n string\n The text after being encrypted or decrypted \n \n Example\n -------\n >>> from cipher_wl2788 import cipher_wl2788\n >>> text = "happy"\n >>> shift = 1\n >>> cipher_wl2788.cipher(text, shift, encrypt = True)\n \'ibqqz\'\n \n ' alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' new_text = '' for c in text: index = alphabet.find(c) if (index == (- 1)): new_text += c else: new_index = ((index + shift) if (encrypt == True) else (index - shift)) new_index %= len(alphabet) new_text += alphabet[new_index:(new_index + 1)] return new_text
Function to encipher or decipher the string by using different shift number. Parameters ---------- text : string A string that you wish to encipher or decipher. shift : integer An integer that you wish to shift. encrypt : boolean A boolean that you would like to encrypt string or not. Returns ------- string The text after being encrypted or decrypted Example ------- >>> from cipher_wl2788 import cipher_wl2788 >>> text = "happy" >>> shift = 1 >>> cipher_wl2788.cipher(text, shift, encrypt = True) 'ibqqz'
cipher_wl2788/cipher_wl2788.py
cipher
QMSS-G5072-2020/cipher_Li_Wenyu
0
python
def cipher(text, shift, encrypt=True): '\n Function to encipher or decipher the string by using different shift number.\n \n Parameters\n ----------\n text : string\n A string that you wish to encipher or decipher.\n shift : integer\n An integer that you wish to shift.\n encrypt : boolean\n A boolean that you would like to encrypt string or not.\n \n Returns\n -------\n string\n The text after being encrypted or decrypted \n \n Example\n -------\n >>> from cipher_wl2788 import cipher_wl2788\n >>> text = "happy"\n >>> shift = 1\n >>> cipher_wl2788.cipher(text, shift, encrypt = True)\n \'ibqqz\'\n \n ' alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' new_text = for c in text: index = alphabet.find(c) if (index == (- 1)): new_text += c else: new_index = ((index + shift) if (encrypt == True) else (index - shift)) new_index %= len(alphabet) new_text += alphabet[new_index:(new_index + 1)] return new_text
def cipher(text, shift, encrypt=True): '\n Function to encipher or decipher the string by using different shift number.\n \n Parameters\n ----------\n text : string\n A string that you wish to encipher or decipher.\n shift : integer\n An integer that you wish to shift.\n encrypt : boolean\n A boolean that you would like to encrypt string or not.\n \n Returns\n -------\n string\n The text after being encrypted or decrypted \n \n Example\n -------\n >>> from cipher_wl2788 import cipher_wl2788\n >>> text = "happy"\n >>> shift = 1\n >>> cipher_wl2788.cipher(text, shift, encrypt = True)\n \'ibqqz\'\n \n ' alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' new_text = for c in text: index = alphabet.find(c) if (index == (- 1)): new_text += c else: new_index = ((index + shift) if (encrypt == True) else (index - shift)) new_index %= len(alphabet) new_text += alphabet[new_index:(new_index + 1)] return new_text<|docstring|>Function to encipher or decipher the string by using different shift number. Parameters ---------- text : string A string that you wish to encipher or decipher. shift : integer An integer that you wish to shift. encrypt : boolean A boolean that you would like to encrypt string or not. Returns ------- string The text after being encrypted or decrypted Example ------- >>> from cipher_wl2788 import cipher_wl2788 >>> text = "happy" >>> shift = 1 >>> cipher_wl2788.cipher(text, shift, encrypt = True) 'ibqqz'<|endoftext|>
c114e30dc5f4811c41eaac8587b33300aa667f8c26ce2e60ff13f7bb229da55c
def Write(self): 'Writes an appveyor.yml file.' file_content = [] file_content.extend(self._FILE_HEADER) if (self._project_definition.name in ('dfvfs', 'l2tpreg', 'plaso')): file_content.extend(self._ALLOW_FAILURES) file_content.extend(self._INSTALL) python2_dependencies = self._dependency_helper.GetL2TBinaries(python_version=2) if ('pysqlite' in python2_dependencies): file_content.extend(self._SQLITE) file_content.extend(self._L2TDEVTOOLS) python2_dependencies.extend(['funcsigs', 'mock', 'pbr']) if ('six' not in python2_dependencies): python2_dependencies.append('six') if (self._project_definition.name == 'artifacts'): python2_dependencies.append('yapf') if ('backports.lzma' in python2_dependencies): python2_dependencies.remove('backports.lzma') python2_dependencies = ' '.join(sorted(python2_dependencies)) l2tdevtools_update = self._L2TDEVTOOLS_UPDATE.format('python27', python2_dependencies) file_content.append(l2tdevtools_update) python3_dependencies = self._dependency_helper.GetL2TBinaries(python_version=3) python3_dependencies.extend(['funcsigs', 'mock', 'pbr']) if ('six' not in python3_dependencies): python3_dependencies.append('six') python3_dependencies = ' '.join(sorted(python3_dependencies)) l2tdevtools_update = self._L2TDEVTOOLS_UPDATE.format('python36', python3_dependencies) file_content.append(l2tdevtools_update) file_content.extend(self._FILE_FOOTER) file_content = '\n'.join(file_content) file_content = file_content.encode('utf-8') with open(self.PATH, 'wb') as file_object: file_object.write(file_content)
Writes an appveyor.yml file.
l2tdevtools/dependency_writers/appveyor_yml.py
Write
everestmz/l2tdevtools
0
python
def Write(self): file_content = [] file_content.extend(self._FILE_HEADER) if (self._project_definition.name in ('dfvfs', 'l2tpreg', 'plaso')): file_content.extend(self._ALLOW_FAILURES) file_content.extend(self._INSTALL) python2_dependencies = self._dependency_helper.GetL2TBinaries(python_version=2) if ('pysqlite' in python2_dependencies): file_content.extend(self._SQLITE) file_content.extend(self._L2TDEVTOOLS) python2_dependencies.extend(['funcsigs', 'mock', 'pbr']) if ('six' not in python2_dependencies): python2_dependencies.append('six') if (self._project_definition.name == 'artifacts'): python2_dependencies.append('yapf') if ('backports.lzma' in python2_dependencies): python2_dependencies.remove('backports.lzma') python2_dependencies = ' '.join(sorted(python2_dependencies)) l2tdevtools_update = self._L2TDEVTOOLS_UPDATE.format('python27', python2_dependencies) file_content.append(l2tdevtools_update) python3_dependencies = self._dependency_helper.GetL2TBinaries(python_version=3) python3_dependencies.extend(['funcsigs', 'mock', 'pbr']) if ('six' not in python3_dependencies): python3_dependencies.append('six') python3_dependencies = ' '.join(sorted(python3_dependencies)) l2tdevtools_update = self._L2TDEVTOOLS_UPDATE.format('python36', python3_dependencies) file_content.append(l2tdevtools_update) file_content.extend(self._FILE_FOOTER) file_content = '\n'.join(file_content) file_content = file_content.encode('utf-8') with open(self.PATH, 'wb') as file_object: file_object.write(file_content)
def Write(self): file_content = [] file_content.extend(self._FILE_HEADER) if (self._project_definition.name in ('dfvfs', 'l2tpreg', 'plaso')): file_content.extend(self._ALLOW_FAILURES) file_content.extend(self._INSTALL) python2_dependencies = self._dependency_helper.GetL2TBinaries(python_version=2) if ('pysqlite' in python2_dependencies): file_content.extend(self._SQLITE) file_content.extend(self._L2TDEVTOOLS) python2_dependencies.extend(['funcsigs', 'mock', 'pbr']) if ('six' not in python2_dependencies): python2_dependencies.append('six') if (self._project_definition.name == 'artifacts'): python2_dependencies.append('yapf') if ('backports.lzma' in python2_dependencies): python2_dependencies.remove('backports.lzma') python2_dependencies = ' '.join(sorted(python2_dependencies)) l2tdevtools_update = self._L2TDEVTOOLS_UPDATE.format('python27', python2_dependencies) file_content.append(l2tdevtools_update) python3_dependencies = self._dependency_helper.GetL2TBinaries(python_version=3) python3_dependencies.extend(['funcsigs', 'mock', 'pbr']) if ('six' not in python3_dependencies): python3_dependencies.append('six') python3_dependencies = ' '.join(sorted(python3_dependencies)) l2tdevtools_update = self._L2TDEVTOOLS_UPDATE.format('python36', python3_dependencies) file_content.append(l2tdevtools_update) file_content.extend(self._FILE_FOOTER) file_content = '\n'.join(file_content) file_content = file_content.encode('utf-8') with open(self.PATH, 'wb') as file_object: file_object.write(file_content)<|docstring|>Writes an appveyor.yml file.<|endoftext|>
c15af5101a5b291614d4832a9dc4f36860441399ebb2d8abca601964d12e76eb
def connect_string_value(widget, d, handler, property, finishes): 'Connects a value in the property, but also allows binding.\n\n A value means the value for the property is directly contained in the string.\n ' v = d.get(property) m = re.match('^@binding\\((.+)\\)$', (v if v else '')) if m: b = m.group(1) parts = [p.strip() for p in b.split(',')] def finish_binding(): handler_property_path = parts[0].split('.') source = handler for p in handler_property_path[:(- 1)]: source = getattr(source, p.strip()) converter = None for part in parts: if part.startswith('converter='): converter = getattr(handler, part[len('converter='):]) if hasattr(source, 'property_changed_event'): binding = Binding.PropertyBinding(source, handler_property_path[(- 1)].strip(), converter=converter) getattr(widget, ('bind_' + property))(binding) else: setattr(widget, property, getattr(source, handler_property_path[(- 1)].strip())) finishes.append(finish_binding) else: setattr(widget, property, v)
Connects a value in the property, but also allows binding. A value means the value for the property is directly contained in the string.
nion/ui/Declarative.py
connect_string_value
AEljarrat/nionui
0
python
def connect_string_value(widget, d, handler, property, finishes): 'Connects a value in the property, but also allows binding.\n\n A value means the value for the property is directly contained in the string.\n ' v = d.get(property) m = re.match('^@binding\\((.+)\\)$', (v if v else )) if m: b = m.group(1) parts = [p.strip() for p in b.split(',')] def finish_binding(): handler_property_path = parts[0].split('.') source = handler for p in handler_property_path[:(- 1)]: source = getattr(source, p.strip()) converter = None for part in parts: if part.startswith('converter='): converter = getattr(handler, part[len('converter='):]) if hasattr(source, 'property_changed_event'): binding = Binding.PropertyBinding(source, handler_property_path[(- 1)].strip(), converter=converter) getattr(widget, ('bind_' + property))(binding) else: setattr(widget, property, getattr(source, handler_property_path[(- 1)].strip())) finishes.append(finish_binding) else: setattr(widget, property, v)
def connect_string_value(widget, d, handler, property, finishes): 'Connects a value in the property, but also allows binding.\n\n A value means the value for the property is directly contained in the string.\n ' v = d.get(property) m = re.match('^@binding\\((.+)\\)$', (v if v else )) if m: b = m.group(1) parts = [p.strip() for p in b.split(',')] def finish_binding(): handler_property_path = parts[0].split('.') source = handler for p in handler_property_path[:(- 1)]: source = getattr(source, p.strip()) converter = None for part in parts: if part.startswith('converter='): converter = getattr(handler, part[len('converter='):]) if hasattr(source, 'property_changed_event'): binding = Binding.PropertyBinding(source, handler_property_path[(- 1)].strip(), converter=converter) getattr(widget, ('bind_' + property))(binding) else: setattr(widget, property, getattr(source, handler_property_path[(- 1)].strip())) finishes.append(finish_binding) else: setattr(widget, property, v)<|docstring|>Connects a value in the property, but also allows binding. A value means the value for the property is directly contained in the string.<|endoftext|>
817f3c48179f218e8ce780bd5920dd2a1e029e93f3936709b42e51f9435d256d
def connect_reference_value(widget, d, handler, property, finishes, binding_name=None, value_type=None): 'Connects a reference to the property, but also allows binding.\n\n A reference means the property specifies a property in the handler.\n ' binding_name = (binding_name if binding_name else property) v = d.get(property) m = re.match('^@binding\\((.+)\\)$', (v if v else '')) if m: b = m.group(1) parts = [p.strip() for p in b.split(',')] def finish_binding(): handler_property_path = parts[0].split('.') source = handler for p in handler_property_path[:(- 1)]: source = getattr(source, p.strip()) converter = None for part in parts: if part.startswith('converter='): converter = getattr(handler, part[len('converter='):]) if getattr(handler, 'get_object_converter', None): converter = handler.get_object_converter(converter) if (hasattr(source, 'property_changed_event') and hasattr(widget, ('bind_' + binding_name))): binding = Binding.PropertyBinding(source, handler_property_path[(- 1)].strip(), converter=converter) getattr(widget, ('bind_' + binding_name))(binding) else: setattr(widget, binding_name, getattr(source, handler_property_path[(- 1)].strip())) finishes.append(finish_binding) elif (v is not None): if ((value_type == str) and hasattr(handler, v)): setattr(widget, binding_name, getattr(handler, v)) elif (value_type and isinstance(v, value_type)): setattr(widget, binding_name, v) else: setattr(widget, binding_name, getattr(handler, v))
Connects a reference to the property, but also allows binding. A reference means the property specifies a property in the handler.
nion/ui/Declarative.py
connect_reference_value
AEljarrat/nionui
0
python
def connect_reference_value(widget, d, handler, property, finishes, binding_name=None, value_type=None): 'Connects a reference to the property, but also allows binding.\n\n A reference means the property specifies a property in the handler.\n ' binding_name = (binding_name if binding_name else property) v = d.get(property) m = re.match('^@binding\\((.+)\\)$', (v if v else )) if m: b = m.group(1) parts = [p.strip() for p in b.split(',')] def finish_binding(): handler_property_path = parts[0].split('.') source = handler for p in handler_property_path[:(- 1)]: source = getattr(source, p.strip()) converter = None for part in parts: if part.startswith('converter='): converter = getattr(handler, part[len('converter='):]) if getattr(handler, 'get_object_converter', None): converter = handler.get_object_converter(converter) if (hasattr(source, 'property_changed_event') and hasattr(widget, ('bind_' + binding_name))): binding = Binding.PropertyBinding(source, handler_property_path[(- 1)].strip(), converter=converter) getattr(widget, ('bind_' + binding_name))(binding) else: setattr(widget, binding_name, getattr(source, handler_property_path[(- 1)].strip())) finishes.append(finish_binding) elif (v is not None): if ((value_type == str) and hasattr(handler, v)): setattr(widget, binding_name, getattr(handler, v)) elif (value_type and isinstance(v, value_type)): setattr(widget, binding_name, v) else: setattr(widget, binding_name, getattr(handler, v))
def connect_reference_value(widget, d, handler, property, finishes, binding_name=None, value_type=None): 'Connects a reference to the property, but also allows binding.\n\n A reference means the property specifies a property in the handler.\n ' binding_name = (binding_name if binding_name else property) v = d.get(property) m = re.match('^@binding\\((.+)\\)$', (v if v else )) if m: b = m.group(1) parts = [p.strip() for p in b.split(',')] def finish_binding(): handler_property_path = parts[0].split('.') source = handler for p in handler_property_path[:(- 1)]: source = getattr(source, p.strip()) converter = None for part in parts: if part.startswith('converter='): converter = getattr(handler, part[len('converter='):]) if getattr(handler, 'get_object_converter', None): converter = handler.get_object_converter(converter) if (hasattr(source, 'property_changed_event') and hasattr(widget, ('bind_' + binding_name))): binding = Binding.PropertyBinding(source, handler_property_path[(- 1)].strip(), converter=converter) getattr(widget, ('bind_' + binding_name))(binding) else: setattr(widget, binding_name, getattr(source, handler_property_path[(- 1)].strip())) finishes.append(finish_binding) elif (v is not None): if ((value_type == str) and hasattr(handler, v)): setattr(widget, binding_name, getattr(handler, v)) elif (value_type and isinstance(v, value_type)): setattr(widget, binding_name, v) else: setattr(widget, binding_name, getattr(handler, v))<|docstring|>Connects a reference to the property, but also allows binding. A reference means the property specifies a property in the handler.<|endoftext|>
e7944ad57736a5c985419c0c9f7557589d9312f8454ecbda4f0f1e86f616af26
def create_column(self, *children: UIDescription, name: UIIdentifier=None, items: UIIdentifier=None, item_component_id: str=None, spacing: UIPoints=None, margin: UIPoints=None, **kwargs) -> UIDescription: 'Create a column UI description with children or dynamic items, spacing, and margin.\n\n The children can be passed as parameters or constructed from an observable list specified by `items` and\n `item_component_id`.\n\n If the children are constructed from an observable list, a component instance will be created for each item\n in the list. Adding or removing items from the list will dynamically update the children. The associated\n handler must implement the `resources` property with a value for the key `item_component_id` describing the\n component UI. It must also implement `create_handler` to create a handler for each component. The\n `create_handler` call will receive two extra keyword arguments `container` and `item` in additional to the\n `component_id`.\n\n Args:\n children: children to put into the column\n\n Keyword Args:\n items: handler observable list property from which to build child components\n item_component_id: resource identifier of component ui description for child components\n spacing: spacing between items, in points\n margin: margin, in points\n\n Returns:\n a UI description of the column\n ' d = {'type': 'column'} if (name is not None): d['name'] = name if items: d['items'] = items if item_component_id: d['item_component_id'] = item_component_id if (spacing is not None): d['spacing'] = spacing if (margin is not None): d['margin'] = margin if (len(children) > 0): d_children = d.setdefault('children', list()) for child in children: d_children.append(child) self.__process_common_properties(d, **kwargs) return d
Create a column UI description with children or dynamic items, spacing, and margin. The children can be passed as parameters or constructed from an observable list specified by `items` and `item_component_id`. If the children are constructed from an observable list, a component instance will be created for each item in the list. Adding or removing items from the list will dynamically update the children. The associated handler must implement the `resources` property with a value for the key `item_component_id` describing the component UI. It must also implement `create_handler` to create a handler for each component. The `create_handler` call will receive two extra keyword arguments `container` and `item` in additional to the `component_id`. Args: children: children to put into the column Keyword Args: items: handler observable list property from which to build child components item_component_id: resource identifier of component ui description for child components spacing: spacing between items, in points margin: margin, in points Returns: a UI description of the column
nion/ui/Declarative.py
create_column
AEljarrat/nionui
0
python
def create_column(self, *children: UIDescription, name: UIIdentifier=None, items: UIIdentifier=None, item_component_id: str=None, spacing: UIPoints=None, margin: UIPoints=None, **kwargs) -> UIDescription: 'Create a column UI description with children or dynamic items, spacing, and margin.\n\n The children can be passed as parameters or constructed from an observable list specified by `items` and\n `item_component_id`.\n\n If the children are constructed from an observable list, a component instance will be created for each item\n in the list. Adding or removing items from the list will dynamically update the children. The associated\n handler must implement the `resources` property with a value for the key `item_component_id` describing the\n component UI. It must also implement `create_handler` to create a handler for each component. The\n `create_handler` call will receive two extra keyword arguments `container` and `item` in additional to the\n `component_id`.\n\n Args:\n children: children to put into the column\n\n Keyword Args:\n items: handler observable list property from which to build child components\n item_component_id: resource identifier of component ui description for child components\n spacing: spacing between items, in points\n margin: margin, in points\n\n Returns:\n a UI description of the column\n ' d = {'type': 'column'} if (name is not None): d['name'] = name if items: d['items'] = items if item_component_id: d['item_component_id'] = item_component_id if (spacing is not None): d['spacing'] = spacing if (margin is not None): d['margin'] = margin if (len(children) > 0): d_children = d.setdefault('children', list()) for child in children: d_children.append(child) self.__process_common_properties(d, **kwargs) return d
def create_column(self, *children: UIDescription, name: UIIdentifier=None, items: UIIdentifier=None, item_component_id: str=None, spacing: UIPoints=None, margin: UIPoints=None, **kwargs) -> UIDescription: 'Create a column UI description with children or dynamic items, spacing, and margin.\n\n The children can be passed as parameters or constructed from an observable list specified by `items` and\n `item_component_id`.\n\n If the children are constructed from an observable list, a component instance will be created for each item\n in the list. Adding or removing items from the list will dynamically update the children. The associated\n handler must implement the `resources` property with a value for the key `item_component_id` describing the\n component UI. It must also implement `create_handler` to create a handler for each component. The\n `create_handler` call will receive two extra keyword arguments `container` and `item` in additional to the\n `component_id`.\n\n Args:\n children: children to put into the column\n\n Keyword Args:\n items: handler observable list property from which to build child components\n item_component_id: resource identifier of component ui description for child components\n spacing: spacing between items, in points\n margin: margin, in points\n\n Returns:\n a UI description of the column\n ' d = {'type': 'column'} if (name is not None): d['name'] = name if items: d['items'] = items if item_component_id: d['item_component_id'] = item_component_id if (spacing is not None): d['spacing'] = spacing if (margin is not None): d['margin'] = margin if (len(children) > 0): d_children = d.setdefault('children', list()) for child in children: d_children.append(child) self.__process_common_properties(d, **kwargs) return d<|docstring|>Create a column UI description with children or dynamic items, spacing, and margin. The children can be passed as parameters or constructed from an observable list specified by `items` and `item_component_id`. If the children are constructed from an observable list, a component instance will be created for each item in the list. Adding or removing items from the list will dynamically update the children. The associated handler must implement the `resources` property with a value for the key `item_component_id` describing the component UI. It must also implement `create_handler` to create a handler for each component. The `create_handler` call will receive two extra keyword arguments `container` and `item` in additional to the `component_id`. Args: children: children to put into the column Keyword Args: items: handler observable list property from which to build child components item_component_id: resource identifier of component ui description for child components spacing: spacing between items, in points margin: margin, in points Returns: a UI description of the column<|endoftext|>
926fb3530b32c73aa1a03de37f706d1ff32a85098a3b4a5e477f014f9b2a01b7
def create_row(self, *children: UIDescription, name: UIIdentifier=None, items: UIIdentifier=None, item_component_id: str=None, spacing: UIPoints=None, margin: UIPoints=None, **kwargs) -> UIDescription: 'Create a row UI description with children or dynamic items, spacing, and margin.\n\n The children can be passed as parameters or constructed from an observable list specified by `items` and\n `item_component_id`.\n\n If the children are constructed from an observable list, a component instance will be created for each item\n in the list. Adding or removing items from the list will dynamically update the children. The associated\n handler must implement the `resources` property with a value for the key `item_component_id` describing the\n component UI. It must also implement `create_handler` to create a handler for each component. The\n `create_handler` call will receive two extra keyword arguments `container` and `item` in additional to the\n `component_id`.\n\n Args:\n children: children to put into the row\n\n Keyword Args:\n items: handler observable list property from which to build child components\n item_component_id: resource identifier of component ui description for child components\n spacing: spacing between items, in points\n margin: margin, in points\n\n Returns:\n a UI description of the row\n ' d = {'type': 'row'} if (name is not None): d['name'] = name if items: d['items'] = items if item_component_id: d['item_component_id'] = item_component_id if (spacing is not None): d['spacing'] = spacing if (margin is not None): d['margin'] = margin if (len(children) > 0): d_children = d.setdefault('children', list()) for child in children: d_children.append(child) self.__process_common_properties(d, **kwargs) return d
Create a row UI description with children or dynamic items, spacing, and margin. The children can be passed as parameters or constructed from an observable list specified by `items` and `item_component_id`. If the children are constructed from an observable list, a component instance will be created for each item in the list. Adding or removing items from the list will dynamically update the children. The associated handler must implement the `resources` property with a value for the key `item_component_id` describing the component UI. It must also implement `create_handler` to create a handler for each component. The `create_handler` call will receive two extra keyword arguments `container` and `item` in additional to the `component_id`. Args: children: children to put into the row Keyword Args: items: handler observable list property from which to build child components item_component_id: resource identifier of component ui description for child components spacing: spacing between items, in points margin: margin, in points Returns: a UI description of the row
nion/ui/Declarative.py
create_row
AEljarrat/nionui
0
python
def create_row(self, *children: UIDescription, name: UIIdentifier=None, items: UIIdentifier=None, item_component_id: str=None, spacing: UIPoints=None, margin: UIPoints=None, **kwargs) -> UIDescription: 'Create a row UI description with children or dynamic items, spacing, and margin.\n\n The children can be passed as parameters or constructed from an observable list specified by `items` and\n `item_component_id`.\n\n If the children are constructed from an observable list, a component instance will be created for each item\n in the list. Adding or removing items from the list will dynamically update the children. The associated\n handler must implement the `resources` property with a value for the key `item_component_id` describing the\n component UI. It must also implement `create_handler` to create a handler for each component. The\n `create_handler` call will receive two extra keyword arguments `container` and `item` in additional to the\n `component_id`.\n\n Args:\n children: children to put into the row\n\n Keyword Args:\n items: handler observable list property from which to build child components\n item_component_id: resource identifier of component ui description for child components\n spacing: spacing between items, in points\n margin: margin, in points\n\n Returns:\n a UI description of the row\n ' d = {'type': 'row'} if (name is not None): d['name'] = name if items: d['items'] = items if item_component_id: d['item_component_id'] = item_component_id if (spacing is not None): d['spacing'] = spacing if (margin is not None): d['margin'] = margin if (len(children) > 0): d_children = d.setdefault('children', list()) for child in children: d_children.append(child) self.__process_common_properties(d, **kwargs) return d
def create_row(self, *children: UIDescription, name: UIIdentifier=None, items: UIIdentifier=None, item_component_id: str=None, spacing: UIPoints=None, margin: UIPoints=None, **kwargs) -> UIDescription: 'Create a row UI description with children or dynamic items, spacing, and margin.\n\n The children can be passed as parameters or constructed from an observable list specified by `items` and\n `item_component_id`.\n\n If the children are constructed from an observable list, a component instance will be created for each item\n in the list. Adding or removing items from the list will dynamically update the children. The associated\n handler must implement the `resources` property with a value for the key `item_component_id` describing the\n component UI. It must also implement `create_handler` to create a handler for each component. The\n `create_handler` call will receive two extra keyword arguments `container` and `item` in additional to the\n `component_id`.\n\n Args:\n children: children to put into the row\n\n Keyword Args:\n items: handler observable list property from which to build child components\n item_component_id: resource identifier of component ui description for child components\n spacing: spacing between items, in points\n margin: margin, in points\n\n Returns:\n a UI description of the row\n ' d = {'type': 'row'} if (name is not None): d['name'] = name if items: d['items'] = items if item_component_id: d['item_component_id'] = item_component_id if (spacing is not None): d['spacing'] = spacing if (margin is not None): d['margin'] = margin if (len(children) > 0): d_children = d.setdefault('children', list()) for child in children: d_children.append(child) self.__process_common_properties(d, **kwargs) return d<|docstring|>Create a row UI description with children or dynamic items, spacing, and margin. The children can be passed as parameters or constructed from an observable list specified by `items` and `item_component_id`. If the children are constructed from an observable list, a component instance will be created for each item in the list. Adding or removing items from the list will dynamically update the children. The associated handler must implement the `resources` property with a value for the key `item_component_id` describing the component UI. It must also implement `create_handler` to create a handler for each component. The `create_handler` call will receive two extra keyword arguments `container` and `item` in additional to the `component_id`. Args: children: children to put into the row Keyword Args: items: handler observable list property from which to build child components item_component_id: resource identifier of component ui description for child components spacing: spacing between items, in points margin: margin, in points Returns: a UI description of the row<|endoftext|>
82784340926deee438764c74a37eafc1e58d38fb3af99d89fd81cd94126b4c48
def create_spacing(self, size: UIPoints) -> UIDescription: 'Create a spacing UI description for a row or column.\n\n Keyword Args:\n size: spacing, in points\n\n Returns:\n a UI description of the spacing\n ' return {'type': 'spacing', 'size': size}
Create a spacing UI description for a row or column. Keyword Args: size: spacing, in points Returns: a UI description of the spacing
nion/ui/Declarative.py
create_spacing
AEljarrat/nionui
0
python
def create_spacing(self, size: UIPoints) -> UIDescription: 'Create a spacing UI description for a row or column.\n\n Keyword Args:\n size: spacing, in points\n\n Returns:\n a UI description of the spacing\n ' return {'type': 'spacing', 'size': size}
def create_spacing(self, size: UIPoints) -> UIDescription: 'Create a spacing UI description for a row or column.\n\n Keyword Args:\n size: spacing, in points\n\n Returns:\n a UI description of the spacing\n ' return {'type': 'spacing', 'size': size}<|docstring|>Create a spacing UI description for a row or column. Keyword Args: size: spacing, in points Returns: a UI description of the spacing<|endoftext|>
6a8da1f47180022e848d620033020f28f90ded0dea7ae55b2cf6248e5b3f6f50
def create_stretch(self) -> UIDescription: 'Create a stretch UI description for a row or column.\n\n Returns:\n a UI description of the stretch\n ' return {'type': 'stretch'}
Create a stretch UI description for a row or column. Returns: a UI description of the stretch
nion/ui/Declarative.py
create_stretch
AEljarrat/nionui
0
python
def create_stretch(self) -> UIDescription: 'Create a stretch UI description for a row or column.\n\n Returns:\n a UI description of the stretch\n ' return {'type': 'stretch'}
def create_stretch(self) -> UIDescription: 'Create a stretch UI description for a row or column.\n\n Returns:\n a UI description of the stretch\n ' return {'type': 'stretch'}<|docstring|>Create a stretch UI description for a row or column. Returns: a UI description of the stretch<|endoftext|>
2b4a9196bdd231be782857ec295f3d5ff536aa495423eab1edb35e0cb1ae7712
def create_tab(self, label: UILabel, content: UIDescription) -> UIDescription: 'Create a tab UI description with a label and content.\n\n Args:\n label: label for the tab\n content: UI description of the content\n\n Returns:\n a UI description of the tab\n ' return {'type': 'tab', 'label': label, 'content': content}
Create a tab UI description with a label and content. Args: label: label for the tab content: UI description of the content Returns: a UI description of the tab
nion/ui/Declarative.py
create_tab
AEljarrat/nionui
0
python
def create_tab(self, label: UILabel, content: UIDescription) -> UIDescription: 'Create a tab UI description with a label and content.\n\n Args:\n label: label for the tab\n content: UI description of the content\n\n Returns:\n a UI description of the tab\n ' return {'type': 'tab', 'label': label, 'content': content}
def create_tab(self, label: UILabel, content: UIDescription) -> UIDescription: 'Create a tab UI description with a label and content.\n\n Args:\n label: label for the tab\n content: UI description of the content\n\n Returns:\n a UI description of the tab\n ' return {'type': 'tab', 'label': label, 'content': content}<|docstring|>Create a tab UI description with a label and content. Args: label: label for the tab content: UI description of the content Returns: a UI description of the tab<|endoftext|>
b824bfe06da7c067f547fc2158910918532df0f7e32ce0b8aec5b80a8c41e565
def create_tabs(self, *tabs: UIDescription, name: UIIdentifier=None, current_index: UIIdentifier=None, on_current_index_changed: UICallableIdentifier=None, **kwargs) -> UIDescription: 'Create a tabs UI description with children, the current index and optional changed event.\n\n The children must be tabs created by :py:meth:`create_tab`.\n\n The current_index controls which tab is displayed.\n\n The on_current_index_changed callback reference takes ``widget`` and ``current_index`` parameters. The type\n signature in the handler should be ``typing.Callable[[UIWidget, int], None]``.\n\n Args:\n children: child tabs\n\n Keyword Args:\n name: handler property in which to store widget (optional)\n current_index: current index handler reference (bindable, optional)\n on_current_index_changed: callback when current index changes (optional)\n\n Returns:\n a UI description of the tabs\n ' d = {'type': 'tabs'} if (len(tabs) > 0): d_children = d.setdefault('tabs', list()) for child in tabs: d_children.append(child) if (name is not None): d['name'] = name if (current_index is not None): d['current_index'] = current_index if (on_current_index_changed is not None): d['on_current_index_changed'] = on_current_index_changed self.__process_common_properties(d, **kwargs) return d
Create a tabs UI description with children, the current index and optional changed event. The children must be tabs created by :py:meth:`create_tab`. The current_index controls which tab is displayed. The on_current_index_changed callback reference takes ``widget`` and ``current_index`` parameters. The type signature in the handler should be ``typing.Callable[[UIWidget, int], None]``. Args: children: child tabs Keyword Args: name: handler property in which to store widget (optional) current_index: current index handler reference (bindable, optional) on_current_index_changed: callback when current index changes (optional) Returns: a UI description of the tabs
nion/ui/Declarative.py
create_tabs
AEljarrat/nionui
0
python
def create_tabs(self, *tabs: UIDescription, name: UIIdentifier=None, current_index: UIIdentifier=None, on_current_index_changed: UICallableIdentifier=None, **kwargs) -> UIDescription: 'Create a tabs UI description with children, the current index and optional changed event.\n\n The children must be tabs created by :py:meth:`create_tab`.\n\n The current_index controls which tab is displayed.\n\n The on_current_index_changed callback reference takes ``widget`` and ``current_index`` parameters. The type\n signature in the handler should be ``typing.Callable[[UIWidget, int], None]``.\n\n Args:\n children: child tabs\n\n Keyword Args:\n name: handler property in which to store widget (optional)\n current_index: current index handler reference (bindable, optional)\n on_current_index_changed: callback when current index changes (optional)\n\n Returns:\n a UI description of the tabs\n ' d = {'type': 'tabs'} if (len(tabs) > 0): d_children = d.setdefault('tabs', list()) for child in tabs: d_children.append(child) if (name is not None): d['name'] = name if (current_index is not None): d['current_index'] = current_index if (on_current_index_changed is not None): d['on_current_index_changed'] = on_current_index_changed self.__process_common_properties(d, **kwargs) return d
def create_tabs(self, *tabs: UIDescription, name: UIIdentifier=None, current_index: UIIdentifier=None, on_current_index_changed: UICallableIdentifier=None, **kwargs) -> UIDescription: 'Create a tabs UI description with children, the current index and optional changed event.\n\n The children must be tabs created by :py:meth:`create_tab`.\n\n The current_index controls which tab is displayed.\n\n The on_current_index_changed callback reference takes ``widget`` and ``current_index`` parameters. The type\n signature in the handler should be ``typing.Callable[[UIWidget, int], None]``.\n\n Args:\n children: child tabs\n\n Keyword Args:\n name: handler property in which to store widget (optional)\n current_index: current index handler reference (bindable, optional)\n on_current_index_changed: callback when current index changes (optional)\n\n Returns:\n a UI description of the tabs\n ' d = {'type': 'tabs'} if (len(tabs) > 0): d_children = d.setdefault('tabs', list()) for child in tabs: d_children.append(child) if (name is not None): d['name'] = name if (current_index is not None): d['current_index'] = current_index if (on_current_index_changed is not None): d['on_current_index_changed'] = on_current_index_changed self.__process_common_properties(d, **kwargs) return d<|docstring|>Create a tabs UI description with children, the current index and optional changed event. The children must be tabs created by :py:meth:`create_tab`. The current_index controls which tab is displayed. The on_current_index_changed callback reference takes ``widget`` and ``current_index`` parameters. The type signature in the handler should be ``typing.Callable[[UIWidget, int], None]``. Args: children: child tabs Keyword Args: name: handler property in which to store widget (optional) current_index: current index handler reference (bindable, optional) on_current_index_changed: callback when current index changes (optional) Returns: a UI description of the tabs<|endoftext|>
d5233672baaa739a2c262b7d41cb9c597e5742543ab42c83ad903436067bc2e0
def create_stack(self, *children: UIDescription, items: UIIdentifier=None, item_component_id: str=None, name: UIIdentifier=None, current_index: UIIdentifier=None, on_current_index_changed: UICallableIdentifier=None, **kwargs) -> UIDescription: 'Create a stack UI description with children or dynamic items, the current index and optional changed event.\n\n The children can be passed as parameters or constructed from an observable list specified by `items` and\n `item_component_id`.\n\n If the children are constructed from an observable list, a component instance will be created for each item\n in the list. Adding or removing items from the list will dynamically update the children. The associated\n handler must implement the `resources` property with a value for the key `item_component_id` describing the\n component UI. It must also implement `create_handler` to create a handler for each component. The\n `create_handler` call will receive two extra keyword arguments `container` and `item` in additional to the\n `component_id`.\n\n The current_index controls which child is displayed.\n\n The on_current_index_changed callback reference takes ``widget`` and ``current_index`` parameters. The type\n signature in the handler should be ``typing.Callable[[UIWidget, int], None]``.\n\n Args:\n children: stack items\n\n Keyword Args:\n items: handler observable list property from which to build child components\n item_component_id: resource identifier of component ui description for child components\n name: handler property in which to store widget (optional)\n current_index: current index handler reference (bindable, optional)\n on_current_index_changed: callback when current index changes (optional)\n\n Returns:\n a UI description of the stack\n ' d = {'type': 'stack'} if (len(children) > 0): d_children = d.setdefault('children', list()) for child in children: d_children.append(child) if items: d['items'] = items if item_component_id: d['item_component_id'] = item_component_id if (name is not None): d['name'] = name if (current_index is not None): d['current_index'] = current_index if (on_current_index_changed is not None): d['on_current_index_changed'] = on_current_index_changed self.__process_common_properties(d, **kwargs) return d
Create a stack UI description with children or dynamic items, the current index and optional changed event. The children can be passed as parameters or constructed from an observable list specified by `items` and `item_component_id`. If the children are constructed from an observable list, a component instance will be created for each item in the list. Adding or removing items from the list will dynamically update the children. The associated handler must implement the `resources` property with a value for the key `item_component_id` describing the component UI. It must also implement `create_handler` to create a handler for each component. The `create_handler` call will receive two extra keyword arguments `container` and `item` in additional to the `component_id`. The current_index controls which child is displayed. The on_current_index_changed callback reference takes ``widget`` and ``current_index`` parameters. The type signature in the handler should be ``typing.Callable[[UIWidget, int], None]``. Args: children: stack items Keyword Args: items: handler observable list property from which to build child components item_component_id: resource identifier of component ui description for child components name: handler property in which to store widget (optional) current_index: current index handler reference (bindable, optional) on_current_index_changed: callback when current index changes (optional) Returns: a UI description of the stack
nion/ui/Declarative.py
create_stack
AEljarrat/nionui
0
python
def create_stack(self, *children: UIDescription, items: UIIdentifier=None, item_component_id: str=None, name: UIIdentifier=None, current_index: UIIdentifier=None, on_current_index_changed: UICallableIdentifier=None, **kwargs) -> UIDescription: 'Create a stack UI description with children or dynamic items, the current index and optional changed event.\n\n The children can be passed as parameters or constructed from an observable list specified by `items` and\n `item_component_id`.\n\n If the children are constructed from an observable list, a component instance will be created for each item\n in the list. Adding or removing items from the list will dynamically update the children. The associated\n handler must implement the `resources` property with a value for the key `item_component_id` describing the\n component UI. It must also implement `create_handler` to create a handler for each component. The\n `create_handler` call will receive two extra keyword arguments `container` and `item` in additional to the\n `component_id`.\n\n The current_index controls which child is displayed.\n\n The on_current_index_changed callback reference takes ``widget`` and ``current_index`` parameters. The type\n signature in the handler should be ``typing.Callable[[UIWidget, int], None]``.\n\n Args:\n children: stack items\n\n Keyword Args:\n items: handler observable list property from which to build child components\n item_component_id: resource identifier of component ui description for child components\n name: handler property in which to store widget (optional)\n current_index: current index handler reference (bindable, optional)\n on_current_index_changed: callback when current index changes (optional)\n\n Returns:\n a UI description of the stack\n ' d = {'type': 'stack'} if (len(children) > 0): d_children = d.setdefault('children', list()) for child in children: d_children.append(child) if items: d['items'] = items if item_component_id: d['item_component_id'] = item_component_id if (name is not None): d['name'] = name if (current_index is not None): d['current_index'] = current_index if (on_current_index_changed is not None): d['on_current_index_changed'] = on_current_index_changed self.__process_common_properties(d, **kwargs) return d
def create_stack(self, *children: UIDescription, items: UIIdentifier=None, item_component_id: str=None, name: UIIdentifier=None, current_index: UIIdentifier=None, on_current_index_changed: UICallableIdentifier=None, **kwargs) -> UIDescription: 'Create a stack UI description with children or dynamic items, the current index and optional changed event.\n\n The children can be passed as parameters or constructed from an observable list specified by `items` and\n `item_component_id`.\n\n If the children are constructed from an observable list, a component instance will be created for each item\n in the list. Adding or removing items from the list will dynamically update the children. The associated\n handler must implement the `resources` property with a value for the key `item_component_id` describing the\n component UI. It must also implement `create_handler` to create a handler for each component. The\n `create_handler` call will receive two extra keyword arguments `container` and `item` in additional to the\n `component_id`.\n\n The current_index controls which child is displayed.\n\n The on_current_index_changed callback reference takes ``widget`` and ``current_index`` parameters. The type\n signature in the handler should be ``typing.Callable[[UIWidget, int], None]``.\n\n Args:\n children: stack items\n\n Keyword Args:\n items: handler observable list property from which to build child components\n item_component_id: resource identifier of component ui description for child components\n name: handler property in which to store widget (optional)\n current_index: current index handler reference (bindable, optional)\n on_current_index_changed: callback when current index changes (optional)\n\n Returns:\n a UI description of the stack\n ' d = {'type': 'stack'} if (len(children) > 0): d_children = d.setdefault('children', list()) for child in children: d_children.append(child) if items: d['items'] = items if item_component_id: d['item_component_id'] = item_component_id if (name is not None): d['name'] = name if (current_index is not None): d['current_index'] = current_index if (on_current_index_changed is not None): d['on_current_index_changed'] = on_current_index_changed self.__process_common_properties(d, **kwargs) return d<|docstring|>Create a stack UI description with children or dynamic items, the current index and optional changed event. The children can be passed as parameters or constructed from an observable list specified by `items` and `item_component_id`. If the children are constructed from an observable list, a component instance will be created for each item in the list. Adding or removing items from the list will dynamically update the children. The associated handler must implement the `resources` property with a value for the key `item_component_id` describing the component UI. It must also implement `create_handler` to create a handler for each component. The `create_handler` call will receive two extra keyword arguments `container` and `item` in additional to the `component_id`. The current_index controls which child is displayed. The on_current_index_changed callback reference takes ``widget`` and ``current_index`` parameters. The type signature in the handler should be ``typing.Callable[[UIWidget, int], None]``. Args: children: stack items Keyword Args: items: handler observable list property from which to build child components item_component_id: resource identifier of component ui description for child components name: handler property in which to store widget (optional) current_index: current index handler reference (bindable, optional) on_current_index_changed: callback when current index changes (optional) Returns: a UI description of the stack<|endoftext|>
aca5aa8425c11ce0257625f8a231509ee2fd105c91e1c750158c1bc90705a50d
def create_scroll_area(self, content: UIDescription, name: UIIdentifier=None, **kwargs) -> UIDescription: 'Create a scroll area UI description with content and a name.\n\n Args:\n content: UI description of the content\n\n Keyword Args:\n name: handler property in which to store widget (optional)\n\n Returns:\n UI description of the scroll area\n ' d = {'type': 'scroll_area', 'content': content} if (name is not None): d['name'] = name self.__process_common_properties(d, **kwargs) return d
Create a scroll area UI description with content and a name. Args: content: UI description of the content Keyword Args: name: handler property in which to store widget (optional) Returns: UI description of the scroll area
nion/ui/Declarative.py
create_scroll_area
AEljarrat/nionui
0
python
def create_scroll_area(self, content: UIDescription, name: UIIdentifier=None, **kwargs) -> UIDescription: 'Create a scroll area UI description with content and a name.\n\n Args:\n content: UI description of the content\n\n Keyword Args:\n name: handler property in which to store widget (optional)\n\n Returns:\n UI description of the scroll area\n ' d = {'type': 'scroll_area', 'content': content} if (name is not None): d['name'] = name self.__process_common_properties(d, **kwargs) return d
def create_scroll_area(self, content: UIDescription, name: UIIdentifier=None, **kwargs) -> UIDescription: 'Create a scroll area UI description with content and a name.\n\n Args:\n content: UI description of the content\n\n Keyword Args:\n name: handler property in which to store widget (optional)\n\n Returns:\n UI description of the scroll area\n ' d = {'type': 'scroll_area', 'content': content} if (name is not None): d['name'] = name self.__process_common_properties(d, **kwargs) return d<|docstring|>Create a scroll area UI description with content and a name. Args: content: UI description of the content Keyword Args: name: handler property in which to store widget (optional) Returns: UI description of the scroll area<|endoftext|>
4693bda6b063051a056c8704d27afd7630bddc80fbbef5ee6e2957e80824dbbd
def create_group(self, content: UIDescription, name: UIIdentifier=None, title: UILabel=None, margin: UIPoints=None, **kwargs) -> UIDescription: 'Create a group UI description with content, a name, a title, and a margin.\n\n Args:\n content: UI description of the content\n\n Keyword Args:\n name: handler property in which to store widget (optional)\n title: title of the group\n margin: margin in points\n\n Returns:\n UI description of the group\n ' d = {'type': 'group', 'content': content} if (name is not None): d['name'] = name if (title is not None): d['title'] = title if (margin is not None): d['margin'] = margin self.__process_common_properties(d, **kwargs) return d
Create a group UI description with content, a name, a title, and a margin. Args: content: UI description of the content Keyword Args: name: handler property in which to store widget (optional) title: title of the group margin: margin in points Returns: UI description of the group
nion/ui/Declarative.py
create_group
AEljarrat/nionui
0
python
def create_group(self, content: UIDescription, name: UIIdentifier=None, title: UILabel=None, margin: UIPoints=None, **kwargs) -> UIDescription: 'Create a group UI description with content, a name, a title, and a margin.\n\n Args:\n content: UI description of the content\n\n Keyword Args:\n name: handler property in which to store widget (optional)\n title: title of the group\n margin: margin in points\n\n Returns:\n UI description of the group\n ' d = {'type': 'group', 'content': content} if (name is not None): d['name'] = name if (title is not None): d['title'] = title if (margin is not None): d['margin'] = margin self.__process_common_properties(d, **kwargs) return d
def create_group(self, content: UIDescription, name: UIIdentifier=None, title: UILabel=None, margin: UIPoints=None, **kwargs) -> UIDescription: 'Create a group UI description with content, a name, a title, and a margin.\n\n Args:\n content: UI description of the content\n\n Keyword Args:\n name: handler property in which to store widget (optional)\n title: title of the group\n margin: margin in points\n\n Returns:\n UI description of the group\n ' d = {'type': 'group', 'content': content} if (name is not None): d['name'] = name if (title is not None): d['title'] = title if (margin is not None): d['margin'] = margin self.__process_common_properties(d, **kwargs) return d<|docstring|>Create a group UI description with content, a name, a title, and a margin. Args: content: UI description of the content Keyword Args: name: handler property in which to store widget (optional) title: title of the group margin: margin in points Returns: UI description of the group<|endoftext|>
52f1232c02b9f31c79a77187b4bc4cf6d8cf741062cc1aa11129c11efe4922c3
def create_label(self, *, text: UILabel=None, name: UIIdentifier=None, width: int=None, min_width: int=None, **kwargs) -> UIDescription: 'Create a label UI description with text and an optional name.\n\n Keyword Args:\n text: text of the label (bindable)\n name: handler property in which to store widget (optional)\n width: width in points (optional, default None)\n\n Returns:\n UI description of the label\n ' d = {'type': 'text_label'} if (text is not None): d['text'] = text if (name is not None): d['name'] = name self.__process_common_properties(d, **kwargs) return d
Create a label UI description with text and an optional name. Keyword Args: text: text of the label (bindable) name: handler property in which to store widget (optional) width: width in points (optional, default None) Returns: UI description of the label
nion/ui/Declarative.py
create_label
AEljarrat/nionui
0
python
def create_label(self, *, text: UILabel=None, name: UIIdentifier=None, width: int=None, min_width: int=None, **kwargs) -> UIDescription: 'Create a label UI description with text and an optional name.\n\n Keyword Args:\n text: text of the label (bindable)\n name: handler property in which to store widget (optional)\n width: width in points (optional, default None)\n\n Returns:\n UI description of the label\n ' d = {'type': 'text_label'} if (text is not None): d['text'] = text if (name is not None): d['name'] = name self.__process_common_properties(d, **kwargs) return d
def create_label(self, *, text: UILabel=None, name: UIIdentifier=None, width: int=None, min_width: int=None, **kwargs) -> UIDescription: 'Create a label UI description with text and an optional name.\n\n Keyword Args:\n text: text of the label (bindable)\n name: handler property in which to store widget (optional)\n width: width in points (optional, default None)\n\n Returns:\n UI description of the label\n ' d = {'type': 'text_label'} if (text is not None): d['text'] = text if (name is not None): d['name'] = name self.__process_common_properties(d, **kwargs) return d<|docstring|>Create a label UI description with text and an optional name. Keyword Args: text: text of the label (bindable) name: handler property in which to store widget (optional) width: width in points (optional, default None) Returns: UI description of the label<|endoftext|>
5084a61528f55bdf61cdd302190aba6ddf63322f40711010e2814bb80012448f
def create_line_edit(self, *, text: UIIdentifier=None, name: UIIdentifier=None, editable: bool=None, placeholder_text: UILabel=None, clear_button_enabled: bool=None, on_editing_finished: UICallableIdentifier=None, on_escape_pressed: UICallableIdentifier=None, on_return_pressed: UICallableIdentifier=None, on_key_pressed: UICallableIdentifier=None, on_text_edited: UICallableIdentifier=None, **kwargs) -> UIDescription: 'Create a line edit UI description with text, name, placeholder, options, and events.\n\n The ``on_editing_finished`` callback is invoked when the user presses return or escape or when they change\n keyboard focus away from the line edit. The line edit widget and string are passed to the callback. The type\n signature in the handler should be ``typing.Callable[[UIWidget, str], None]``.\n\n The ``on_escape_pressed`` and ``on_return_pressed`` callbacks are invoked when the user presses escape or\n return. The line edit widget is passed and these methods must return ``True`` if they handle the key or\n ``False`` otherwise. Their type signatures in the handler should be ``typing.Callable[[UIWidget], bool]``.\n\n The ``on_key_pressed`` callback is invoked when the user types a key. The line edit widget and a key instance\n are passed. This method should return ``True`` if the key is handled (it will not go into the line edit field)\n and return ``False`` if not handled (it will be entered as regular text). The type signature in the handler\n should be ``typing.Callable[[UIWidget, UIKey], bool]``.\n\n The ``on_text_edited`` callback is invoked when the user changes the text. The line edit widget and the new text\n are passed to the callback. The type signature in the handler should be ``typing.Callable[[UIWidget, str],\n None]``.\n\n Keyword Args:\n text: handler reference to line edit text (bindable, required)\n name: handler property in which to store widget (optional)\n editable: whether the line edit text is editable (optional, default True)\n placeholder_text: text to display when line edit is empty (optional)\n clear_button_enabled: whether the clear button is enabled (optional, default False)\n width: width in points (optional, default None)\n on_editing_finished: callback when editing is finished (return or blur focus)\n on_escape_pressed: callback when escape is pressed, return true if handled\n on_return_pressed: callback when return is pressed, return true if handled\n on_key_pressed: callback when a key is pressed, return true if handled\n on_text_edited: callback when text is edited\n\n Returns:\n UI description of the line edit\n ' d = {'type': 'line_edit'} if (text is not None): d['text'] = text if (name is not None): d['name'] = name if (editable is not None): d['editable'] = editable if (placeholder_text is not None): d['placeholder_text'] = placeholder_text if (clear_button_enabled is not None): d['clear_button_enabled'] = clear_button_enabled if (on_editing_finished is not None): d['on_editing_finished'] = on_editing_finished if (on_escape_pressed is not None): d['on_escape_pressed'] = on_escape_pressed if (on_return_pressed is not None): d['on_return_pressed'] = on_return_pressed if (on_key_pressed is not None): d['on_key_pressed'] = on_key_pressed if (on_text_edited is not None): d['on_text_edited'] = on_text_edited self.__process_common_properties(d, **kwargs) return d
Create a line edit UI description with text, name, placeholder, options, and events. The ``on_editing_finished`` callback is invoked when the user presses return or escape or when they change keyboard focus away from the line edit. The line edit widget and string are passed to the callback. The type signature in the handler should be ``typing.Callable[[UIWidget, str], None]``. The ``on_escape_pressed`` and ``on_return_pressed`` callbacks are invoked when the user presses escape or return. The line edit widget is passed and these methods must return ``True`` if they handle the key or ``False`` otherwise. Their type signatures in the handler should be ``typing.Callable[[UIWidget], bool]``. The ``on_key_pressed`` callback is invoked when the user types a key. The line edit widget and a key instance are passed. This method should return ``True`` if the key is handled (it will not go into the line edit field) and return ``False`` if not handled (it will be entered as regular text). The type signature in the handler should be ``typing.Callable[[UIWidget, UIKey], bool]``. The ``on_text_edited`` callback is invoked when the user changes the text. The line edit widget and the new text are passed to the callback. The type signature in the handler should be ``typing.Callable[[UIWidget, str], None]``. Keyword Args: text: handler reference to line edit text (bindable, required) name: handler property in which to store widget (optional) editable: whether the line edit text is editable (optional, default True) placeholder_text: text to display when line edit is empty (optional) clear_button_enabled: whether the clear button is enabled (optional, default False) width: width in points (optional, default None) on_editing_finished: callback when editing is finished (return or blur focus) on_escape_pressed: callback when escape is pressed, return true if handled on_return_pressed: callback when return is pressed, return true if handled on_key_pressed: callback when a key is pressed, return true if handled on_text_edited: callback when text is edited Returns: UI description of the line edit
nion/ui/Declarative.py
create_line_edit
AEljarrat/nionui
0
python
def create_line_edit(self, *, text: UIIdentifier=None, name: UIIdentifier=None, editable: bool=None, placeholder_text: UILabel=None, clear_button_enabled: bool=None, on_editing_finished: UICallableIdentifier=None, on_escape_pressed: UICallableIdentifier=None, on_return_pressed: UICallableIdentifier=None, on_key_pressed: UICallableIdentifier=None, on_text_edited: UICallableIdentifier=None, **kwargs) -> UIDescription: 'Create a line edit UI description with text, name, placeholder, options, and events.\n\n The ``on_editing_finished`` callback is invoked when the user presses return or escape or when they change\n keyboard focus away from the line edit. The line edit widget and string are passed to the callback. The type\n signature in the handler should be ``typing.Callable[[UIWidget, str], None]``.\n\n The ``on_escape_pressed`` and ``on_return_pressed`` callbacks are invoked when the user presses escape or\n return. The line edit widget is passed and these methods must return ``True`` if they handle the key or\n ``False`` otherwise. Their type signatures in the handler should be ``typing.Callable[[UIWidget], bool]``.\n\n The ``on_key_pressed`` callback is invoked when the user types a key. The line edit widget and a key instance\n are passed. This method should return ``True`` if the key is handled (it will not go into the line edit field)\n and return ``False`` if not handled (it will be entered as regular text). The type signature in the handler\n should be ``typing.Callable[[UIWidget, UIKey], bool]``.\n\n The ``on_text_edited`` callback is invoked when the user changes the text. The line edit widget and the new text\n are passed to the callback. The type signature in the handler should be ``typing.Callable[[UIWidget, str],\n None]``.\n\n Keyword Args:\n text: handler reference to line edit text (bindable, required)\n name: handler property in which to store widget (optional)\n editable: whether the line edit text is editable (optional, default True)\n placeholder_text: text to display when line edit is empty (optional)\n clear_button_enabled: whether the clear button is enabled (optional, default False)\n width: width in points (optional, default None)\n on_editing_finished: callback when editing is finished (return or blur focus)\n on_escape_pressed: callback when escape is pressed, return true if handled\n on_return_pressed: callback when return is pressed, return true if handled\n on_key_pressed: callback when a key is pressed, return true if handled\n on_text_edited: callback when text is edited\n\n Returns:\n UI description of the line edit\n ' d = {'type': 'line_edit'} if (text is not None): d['text'] = text if (name is not None): d['name'] = name if (editable is not None): d['editable'] = editable if (placeholder_text is not None): d['placeholder_text'] = placeholder_text if (clear_button_enabled is not None): d['clear_button_enabled'] = clear_button_enabled if (on_editing_finished is not None): d['on_editing_finished'] = on_editing_finished if (on_escape_pressed is not None): d['on_escape_pressed'] = on_escape_pressed if (on_return_pressed is not None): d['on_return_pressed'] = on_return_pressed if (on_key_pressed is not None): d['on_key_pressed'] = on_key_pressed if (on_text_edited is not None): d['on_text_edited'] = on_text_edited self.__process_common_properties(d, **kwargs) return d
def create_line_edit(self, *, text: UIIdentifier=None, name: UIIdentifier=None, editable: bool=None, placeholder_text: UILabel=None, clear_button_enabled: bool=None, on_editing_finished: UICallableIdentifier=None, on_escape_pressed: UICallableIdentifier=None, on_return_pressed: UICallableIdentifier=None, on_key_pressed: UICallableIdentifier=None, on_text_edited: UICallableIdentifier=None, **kwargs) -> UIDescription: 'Create a line edit UI description with text, name, placeholder, options, and events.\n\n The ``on_editing_finished`` callback is invoked when the user presses return or escape or when they change\n keyboard focus away from the line edit. The line edit widget and string are passed to the callback. The type\n signature in the handler should be ``typing.Callable[[UIWidget, str], None]``.\n\n The ``on_escape_pressed`` and ``on_return_pressed`` callbacks are invoked when the user presses escape or\n return. The line edit widget is passed and these methods must return ``True`` if they handle the key or\n ``False`` otherwise. Their type signatures in the handler should be ``typing.Callable[[UIWidget], bool]``.\n\n The ``on_key_pressed`` callback is invoked when the user types a key. The line edit widget and a key instance\n are passed. This method should return ``True`` if the key is handled (it will not go into the line edit field)\n and return ``False`` if not handled (it will be entered as regular text). The type signature in the handler\n should be ``typing.Callable[[UIWidget, UIKey], bool]``.\n\n The ``on_text_edited`` callback is invoked when the user changes the text. The line edit widget and the new text\n are passed to the callback. The type signature in the handler should be ``typing.Callable[[UIWidget, str],\n None]``.\n\n Keyword Args:\n text: handler reference to line edit text (bindable, required)\n name: handler property in which to store widget (optional)\n editable: whether the line edit text is editable (optional, default True)\n placeholder_text: text to display when line edit is empty (optional)\n clear_button_enabled: whether the clear button is enabled (optional, default False)\n width: width in points (optional, default None)\n on_editing_finished: callback when editing is finished (return or blur focus)\n on_escape_pressed: callback when escape is pressed, return true if handled\n on_return_pressed: callback when return is pressed, return true if handled\n on_key_pressed: callback when a key is pressed, return true if handled\n on_text_edited: callback when text is edited\n\n Returns:\n UI description of the line edit\n ' d = {'type': 'line_edit'} if (text is not None): d['text'] = text if (name is not None): d['name'] = name if (editable is not None): d['editable'] = editable if (placeholder_text is not None): d['placeholder_text'] = placeholder_text if (clear_button_enabled is not None): d['clear_button_enabled'] = clear_button_enabled if (on_editing_finished is not None): d['on_editing_finished'] = on_editing_finished if (on_escape_pressed is not None): d['on_escape_pressed'] = on_escape_pressed if (on_return_pressed is not None): d['on_return_pressed'] = on_return_pressed if (on_key_pressed is not None): d['on_key_pressed'] = on_key_pressed if (on_text_edited is not None): d['on_text_edited'] = on_text_edited self.__process_common_properties(d, **kwargs) return d<|docstring|>Create a line edit UI description with text, name, placeholder, options, and events. The ``on_editing_finished`` callback is invoked when the user presses return or escape or when they change keyboard focus away from the line edit. The line edit widget and string are passed to the callback. The type signature in the handler should be ``typing.Callable[[UIWidget, str], None]``. The ``on_escape_pressed`` and ``on_return_pressed`` callbacks are invoked when the user presses escape or return. The line edit widget is passed and these methods must return ``True`` if they handle the key or ``False`` otherwise. Their type signatures in the handler should be ``typing.Callable[[UIWidget], bool]``. The ``on_key_pressed`` callback is invoked when the user types a key. The line edit widget and a key instance are passed. This method should return ``True`` if the key is handled (it will not go into the line edit field) and return ``False`` if not handled (it will be entered as regular text). The type signature in the handler should be ``typing.Callable[[UIWidget, UIKey], bool]``. The ``on_text_edited`` callback is invoked when the user changes the text. The line edit widget and the new text are passed to the callback. The type signature in the handler should be ``typing.Callable[[UIWidget, str], None]``. Keyword Args: text: handler reference to line edit text (bindable, required) name: handler property in which to store widget (optional) editable: whether the line edit text is editable (optional, default True) placeholder_text: text to display when line edit is empty (optional) clear_button_enabled: whether the clear button is enabled (optional, default False) width: width in points (optional, default None) on_editing_finished: callback when editing is finished (return or blur focus) on_escape_pressed: callback when escape is pressed, return true if handled on_return_pressed: callback when return is pressed, return true if handled on_key_pressed: callback when a key is pressed, return true if handled on_text_edited: callback when text is edited Returns: UI description of the line edit<|endoftext|>
daaa6e243b1a840db9f0e8b7a091675942a1d68ffa5ebaf68555aec075aac65e
def create_text_edit(self, *, text: UIIdentifier=None, name: UIIdentifier=None, editable: bool=None, placeholder_text: UILabel=None, clear_button_enabled: bool=None, on_escape_pressed: UICallableIdentifier=None, on_return_pressed: UICallableIdentifier=None, on_text_edited: UICallableIdentifier=None, **kwargs) -> UIDescription: 'Create a multi-line text edit UI description with text, name, placeholder, options, and events.\n\n The ``on_escape_pressed`` and ``on_return_pressed`` callbacks are invoked when the user presses escape or\n return. The text edit widget is passed and these methods must return ``True`` if they handle the key or\n ``False`` otherwise. Their type signatures in the handler should be ``typing.Callable[[UIWidget], bool]``.\n\n The ``on_text_edited`` callback is invoked when the user changes the text. The text edit widget and the new text\n are passed to the callback. The type signature in the handler should be ``typing.Callable[[UIWidget, str],\n None]``.\n\n Keyword Args:\n text: handler reference to line edit text (bindable, required)\n name: handler property in which to store widget (optional)\n editable: whether the line edit text is editable (optional, default True)\n placeholder_text: text to display when line edit is empty (optional)\n clear_button_enabled: whether the clear button is enabled (optional, default False)\n width: width in points (optional, default None)\n height: width in points (optional, default None)\n on_escape_pressed: callback when escape is pressed, return true if handled\n on_return_pressed: callback when return is pressed, return true if handled\n on_text_edited: callback when text is edited\n\n Returns:\n UI description of the text edit\n ' d = {'type': 'text_edit'} if (text is not None): d['text'] = text if (name is not None): d['name'] = name if (editable is not None): d['editable'] = editable if (placeholder_text is not None): d['placeholder_text'] = placeholder_text if (clear_button_enabled is not None): d['clear_button_enabled'] = clear_button_enabled if (on_escape_pressed is not None): d['on_escape_pressed'] = on_escape_pressed if (on_return_pressed is not None): d['on_return_pressed'] = on_return_pressed if (on_text_edited is not None): d['on_text_edited'] = on_text_edited self.__process_common_properties(d, **kwargs) return d
Create a multi-line text edit UI description with text, name, placeholder, options, and events. The ``on_escape_pressed`` and ``on_return_pressed`` callbacks are invoked when the user presses escape or return. The text edit widget is passed and these methods must return ``True`` if they handle the key or ``False`` otherwise. Their type signatures in the handler should be ``typing.Callable[[UIWidget], bool]``. The ``on_text_edited`` callback is invoked when the user changes the text. The text edit widget and the new text are passed to the callback. The type signature in the handler should be ``typing.Callable[[UIWidget, str], None]``. Keyword Args: text: handler reference to line edit text (bindable, required) name: handler property in which to store widget (optional) editable: whether the line edit text is editable (optional, default True) placeholder_text: text to display when line edit is empty (optional) clear_button_enabled: whether the clear button is enabled (optional, default False) width: width in points (optional, default None) height: width in points (optional, default None) on_escape_pressed: callback when escape is pressed, return true if handled on_return_pressed: callback when return is pressed, return true if handled on_text_edited: callback when text is edited Returns: UI description of the text edit
nion/ui/Declarative.py
create_text_edit
AEljarrat/nionui
0
python
def create_text_edit(self, *, text: UIIdentifier=None, name: UIIdentifier=None, editable: bool=None, placeholder_text: UILabel=None, clear_button_enabled: bool=None, on_escape_pressed: UICallableIdentifier=None, on_return_pressed: UICallableIdentifier=None, on_text_edited: UICallableIdentifier=None, **kwargs) -> UIDescription: 'Create a multi-line text edit UI description with text, name, placeholder, options, and events.\n\n The ``on_escape_pressed`` and ``on_return_pressed`` callbacks are invoked when the user presses escape or\n return. The text edit widget is passed and these methods must return ``True`` if they handle the key or\n ``False`` otherwise. Their type signatures in the handler should be ``typing.Callable[[UIWidget], bool]``.\n\n The ``on_text_edited`` callback is invoked when the user changes the text. The text edit widget and the new text\n are passed to the callback. The type signature in the handler should be ``typing.Callable[[UIWidget, str],\n None]``.\n\n Keyword Args:\n text: handler reference to line edit text (bindable, required)\n name: handler property in which to store widget (optional)\n editable: whether the line edit text is editable (optional, default True)\n placeholder_text: text to display when line edit is empty (optional)\n clear_button_enabled: whether the clear button is enabled (optional, default False)\n width: width in points (optional, default None)\n height: width in points (optional, default None)\n on_escape_pressed: callback when escape is pressed, return true if handled\n on_return_pressed: callback when return is pressed, return true if handled\n on_text_edited: callback when text is edited\n\n Returns:\n UI description of the text edit\n ' d = {'type': 'text_edit'} if (text is not None): d['text'] = text if (name is not None): d['name'] = name if (editable is not None): d['editable'] = editable if (placeholder_text is not None): d['placeholder_text'] = placeholder_text if (clear_button_enabled is not None): d['clear_button_enabled'] = clear_button_enabled if (on_escape_pressed is not None): d['on_escape_pressed'] = on_escape_pressed if (on_return_pressed is not None): d['on_return_pressed'] = on_return_pressed if (on_text_edited is not None): d['on_text_edited'] = on_text_edited self.__process_common_properties(d, **kwargs) return d
def create_text_edit(self, *, text: UIIdentifier=None, name: UIIdentifier=None, editable: bool=None, placeholder_text: UILabel=None, clear_button_enabled: bool=None, on_escape_pressed: UICallableIdentifier=None, on_return_pressed: UICallableIdentifier=None, on_text_edited: UICallableIdentifier=None, **kwargs) -> UIDescription: 'Create a multi-line text edit UI description with text, name, placeholder, options, and events.\n\n The ``on_escape_pressed`` and ``on_return_pressed`` callbacks are invoked when the user presses escape or\n return. The text edit widget is passed and these methods must return ``True`` if they handle the key or\n ``False`` otherwise. Their type signatures in the handler should be ``typing.Callable[[UIWidget], bool]``.\n\n The ``on_text_edited`` callback is invoked when the user changes the text. The text edit widget and the new text\n are passed to the callback. The type signature in the handler should be ``typing.Callable[[UIWidget, str],\n None]``.\n\n Keyword Args:\n text: handler reference to line edit text (bindable, required)\n name: handler property in which to store widget (optional)\n editable: whether the line edit text is editable (optional, default True)\n placeholder_text: text to display when line edit is empty (optional)\n clear_button_enabled: whether the clear button is enabled (optional, default False)\n width: width in points (optional, default None)\n height: width in points (optional, default None)\n on_escape_pressed: callback when escape is pressed, return true if handled\n on_return_pressed: callback when return is pressed, return true if handled\n on_text_edited: callback when text is edited\n\n Returns:\n UI description of the text edit\n ' d = {'type': 'text_edit'} if (text is not None): d['text'] = text if (name is not None): d['name'] = name if (editable is not None): d['editable'] = editable if (placeholder_text is not None): d['placeholder_text'] = placeholder_text if (clear_button_enabled is not None): d['clear_button_enabled'] = clear_button_enabled if (on_escape_pressed is not None): d['on_escape_pressed'] = on_escape_pressed if (on_return_pressed is not None): d['on_return_pressed'] = on_return_pressed if (on_text_edited is not None): d['on_text_edited'] = on_text_edited self.__process_common_properties(d, **kwargs) return d<|docstring|>Create a multi-line text edit UI description with text, name, placeholder, options, and events. The ``on_escape_pressed`` and ``on_return_pressed`` callbacks are invoked when the user presses escape or return. The text edit widget is passed and these methods must return ``True`` if they handle the key or ``False`` otherwise. Their type signatures in the handler should be ``typing.Callable[[UIWidget], bool]``. The ``on_text_edited`` callback is invoked when the user changes the text. The text edit widget and the new text are passed to the callback. The type signature in the handler should be ``typing.Callable[[UIWidget, str], None]``. Keyword Args: text: handler reference to line edit text (bindable, required) name: handler property in which to store widget (optional) editable: whether the line edit text is editable (optional, default True) placeholder_text: text to display when line edit is empty (optional) clear_button_enabled: whether the clear button is enabled (optional, default False) width: width in points (optional, default None) height: width in points (optional, default None) on_escape_pressed: callback when escape is pressed, return true if handled on_return_pressed: callback when return is pressed, return true if handled on_text_edited: callback when text is edited Returns: UI description of the text edit<|endoftext|>
3a9b63993ce67aaa161910a5049794be50843c2bf29c5be43ca3e0b0fe79edf5
def create_push_button(self, *, text: UILabel=None, icon: UIIdentifier=None, name: UIIdentifier=None, on_clicked: UICallableIdentifier=None, **kwargs) -> UIDescription: 'Create a push button UI description with text, name, an event.\n\n The ``on_clicked`` callback is invoked when the user clicks the button. The widget is passed to the callback.\n The type signature in the handler should be ``typing.Callable[[UIWidget], None]``.\n\n Keyword Args:\n text: text of the label (bindable)\n icon: icon, bindable to numpy uint32 bgra array\n name: handler property in which to store widget (optional)\n width: width in points (optional, default None)\n on_clicked: callback when button clicked\n\n Returns:\n UI description of the push button\n ' d = {'type': 'push_button'} if (text is not None): d['text'] = text if (icon is not None): d['icon'] = icon if (name is not None): d['name'] = name if (on_clicked is not None): d['on_clicked'] = on_clicked self.__process_common_properties(d, **kwargs) return d
Create a push button UI description with text, name, an event. The ``on_clicked`` callback is invoked when the user clicks the button. The widget is passed to the callback. The type signature in the handler should be ``typing.Callable[[UIWidget], None]``. Keyword Args: text: text of the label (bindable) icon: icon, bindable to numpy uint32 bgra array name: handler property in which to store widget (optional) width: width in points (optional, default None) on_clicked: callback when button clicked Returns: UI description of the push button
nion/ui/Declarative.py
create_push_button
AEljarrat/nionui
0
python
def create_push_button(self, *, text: UILabel=None, icon: UIIdentifier=None, name: UIIdentifier=None, on_clicked: UICallableIdentifier=None, **kwargs) -> UIDescription: 'Create a push button UI description with text, name, an event.\n\n The ``on_clicked`` callback is invoked when the user clicks the button. The widget is passed to the callback.\n The type signature in the handler should be ``typing.Callable[[UIWidget], None]``.\n\n Keyword Args:\n text: text of the label (bindable)\n icon: icon, bindable to numpy uint32 bgra array\n name: handler property in which to store widget (optional)\n width: width in points (optional, default None)\n on_clicked: callback when button clicked\n\n Returns:\n UI description of the push button\n ' d = {'type': 'push_button'} if (text is not None): d['text'] = text if (icon is not None): d['icon'] = icon if (name is not None): d['name'] = name if (on_clicked is not None): d['on_clicked'] = on_clicked self.__process_common_properties(d, **kwargs) return d
def create_push_button(self, *, text: UILabel=None, icon: UIIdentifier=None, name: UIIdentifier=None, on_clicked: UICallableIdentifier=None, **kwargs) -> UIDescription: 'Create a push button UI description with text, name, an event.\n\n The ``on_clicked`` callback is invoked when the user clicks the button. The widget is passed to the callback.\n The type signature in the handler should be ``typing.Callable[[UIWidget], None]``.\n\n Keyword Args:\n text: text of the label (bindable)\n icon: icon, bindable to numpy uint32 bgra array\n name: handler property in which to store widget (optional)\n width: width in points (optional, default None)\n on_clicked: callback when button clicked\n\n Returns:\n UI description of the push button\n ' d = {'type': 'push_button'} if (text is not None): d['text'] = text if (icon is not None): d['icon'] = icon if (name is not None): d['name'] = name if (on_clicked is not None): d['on_clicked'] = on_clicked self.__process_common_properties(d, **kwargs) return d<|docstring|>Create a push button UI description with text, name, an event. The ``on_clicked`` callback is invoked when the user clicks the button. The widget is passed to the callback. The type signature in the handler should be ``typing.Callable[[UIWidget], None]``. Keyword Args: text: text of the label (bindable) icon: icon, bindable to numpy uint32 bgra array name: handler property in which to store widget (optional) width: width in points (optional, default None) on_clicked: callback when button clicked Returns: UI description of the push button<|endoftext|>
95c37b203de6a4ba5bfd7bb841996cdb2a28e18f45b4bde3c5b2b1031b2fa209
def create_check_box(self, *, text: UILabel=None, name: UIIdentifier=None, checked: bool=None, check_state: str=None, tristate: bool=None, on_checked_changed: UICallableIdentifier=None, on_check_state_changed: UICallableIdentifier=None, **kwargs) -> UIDescription: "Create a check box UI description with text, name, state information, and events.\n\n The ``checked`` and ``check_state`` both refer to the check state. Some callers may choose to use the simpler\n ``checked`` which is a simple boolean. ``check_state`` is a string and must be one of 'checked', 'unchecked', or\n 'partial'. 'partial' is only valid if ``tristate`` is ``True``.\n\n The ``on_checked_changed`` callback is invoked when the user changes the state of the check box. The widget and\n the new state of the check box are passed to the callback. The type signature in the handler should be\n ``typing.Callable[[UIWidget, bool], None]``.\n\n The ``on_check_state_changed`` callback is invoked when the user changes the state of the check box, but it also\n includes the 'partial' state if enabled. The widget and the new state of the check box are passed to the\n callback. The type signature in the handler should be ``typing.Callable[[UIWidget, str], None]``.\n\n Keyword Args:\n text: text of the label (bindable)\n name: handler property in which to store widget (optional)\n checked: checked state (bool)\n check_state: checked state (string: checked, unchecked, or partial)\n tristate: whether the check box is tristate or not\n on_checked_changed: callback when checked changes (optional)\n on_check_state_changed: callback when check state changes (optional)\n\n Returns:\n UI description of the check box\n " d = {'type': 'check_box'} if (text is not None): d['text'] = text if (checked is not None): d['checked'] = checked if (check_state is not None): d['check_state'] = check_state if (tristate is not None): d['tristate'] = tristate if (name is not None): d['name'] = name if (on_checked_changed is not None): d['on_checked_changed'] = on_checked_changed if (on_check_state_changed is not None): d['on_check_state_changed'] = on_check_state_changed self.__process_common_properties(d, **kwargs) return d
Create a check box UI description with text, name, state information, and events. The ``checked`` and ``check_state`` both refer to the check state. Some callers may choose to use the simpler ``checked`` which is a simple boolean. ``check_state`` is a string and must be one of 'checked', 'unchecked', or 'partial'. 'partial' is only valid if ``tristate`` is ``True``. The ``on_checked_changed`` callback is invoked when the user changes the state of the check box. The widget and the new state of the check box are passed to the callback. The type signature in the handler should be ``typing.Callable[[UIWidget, bool], None]``. The ``on_check_state_changed`` callback is invoked when the user changes the state of the check box, but it also includes the 'partial' state if enabled. The widget and the new state of the check box are passed to the callback. The type signature in the handler should be ``typing.Callable[[UIWidget, str], None]``. Keyword Args: text: text of the label (bindable) name: handler property in which to store widget (optional) checked: checked state (bool) check_state: checked state (string: checked, unchecked, or partial) tristate: whether the check box is tristate or not on_checked_changed: callback when checked changes (optional) on_check_state_changed: callback when check state changes (optional) Returns: UI description of the check box
nion/ui/Declarative.py
create_check_box
AEljarrat/nionui
0
python
def create_check_box(self, *, text: UILabel=None, name: UIIdentifier=None, checked: bool=None, check_state: str=None, tristate: bool=None, on_checked_changed: UICallableIdentifier=None, on_check_state_changed: UICallableIdentifier=None, **kwargs) -> UIDescription: "Create a check box UI description with text, name, state information, and events.\n\n The ``checked`` and ``check_state`` both refer to the check state. Some callers may choose to use the simpler\n ``checked`` which is a simple boolean. ``check_state`` is a string and must be one of 'checked', 'unchecked', or\n 'partial'. 'partial' is only valid if ``tristate`` is ``True``.\n\n The ``on_checked_changed`` callback is invoked when the user changes the state of the check box. The widget and\n the new state of the check box are passed to the callback. The type signature in the handler should be\n ``typing.Callable[[UIWidget, bool], None]``.\n\n The ``on_check_state_changed`` callback is invoked when the user changes the state of the check box, but it also\n includes the 'partial' state if enabled. The widget and the new state of the check box are passed to the\n callback. The type signature in the handler should be ``typing.Callable[[UIWidget, str], None]``.\n\n Keyword Args:\n text: text of the label (bindable)\n name: handler property in which to store widget (optional)\n checked: checked state (bool)\n check_state: checked state (string: checked, unchecked, or partial)\n tristate: whether the check box is tristate or not\n on_checked_changed: callback when checked changes (optional)\n on_check_state_changed: callback when check state changes (optional)\n\n Returns:\n UI description of the check box\n " d = {'type': 'check_box'} if (text is not None): d['text'] = text if (checked is not None): d['checked'] = checked if (check_state is not None): d['check_state'] = check_state if (tristate is not None): d['tristate'] = tristate if (name is not None): d['name'] = name if (on_checked_changed is not None): d['on_checked_changed'] = on_checked_changed if (on_check_state_changed is not None): d['on_check_state_changed'] = on_check_state_changed self.__process_common_properties(d, **kwargs) return d
def create_check_box(self, *, text: UILabel=None, name: UIIdentifier=None, checked: bool=None, check_state: str=None, tristate: bool=None, on_checked_changed: UICallableIdentifier=None, on_check_state_changed: UICallableIdentifier=None, **kwargs) -> UIDescription: "Create a check box UI description with text, name, state information, and events.\n\n The ``checked`` and ``check_state`` both refer to the check state. Some callers may choose to use the simpler\n ``checked`` which is a simple boolean. ``check_state`` is a string and must be one of 'checked', 'unchecked', or\n 'partial'. 'partial' is only valid if ``tristate`` is ``True``.\n\n The ``on_checked_changed`` callback is invoked when the user changes the state of the check box. The widget and\n the new state of the check box are passed to the callback. The type signature in the handler should be\n ``typing.Callable[[UIWidget, bool], None]``.\n\n The ``on_check_state_changed`` callback is invoked when the user changes the state of the check box, but it also\n includes the 'partial' state if enabled. The widget and the new state of the check box are passed to the\n callback. The type signature in the handler should be ``typing.Callable[[UIWidget, str], None]``.\n\n Keyword Args:\n text: text of the label (bindable)\n name: handler property in which to store widget (optional)\n checked: checked state (bool)\n check_state: checked state (string: checked, unchecked, or partial)\n tristate: whether the check box is tristate or not\n on_checked_changed: callback when checked changes (optional)\n on_check_state_changed: callback when check state changes (optional)\n\n Returns:\n UI description of the check box\n " d = {'type': 'check_box'} if (text is not None): d['text'] = text if (checked is not None): d['checked'] = checked if (check_state is not None): d['check_state'] = check_state if (tristate is not None): d['tristate'] = tristate if (name is not None): d['name'] = name if (on_checked_changed is not None): d['on_checked_changed'] = on_checked_changed if (on_check_state_changed is not None): d['on_check_state_changed'] = on_check_state_changed self.__process_common_properties(d, **kwargs) return d<|docstring|>Create a check box UI description with text, name, state information, and events. The ``checked`` and ``check_state`` both refer to the check state. Some callers may choose to use the simpler ``checked`` which is a simple boolean. ``check_state`` is a string and must be one of 'checked', 'unchecked', or 'partial'. 'partial' is only valid if ``tristate`` is ``True``. The ``on_checked_changed`` callback is invoked when the user changes the state of the check box. The widget and the new state of the check box are passed to the callback. The type signature in the handler should be ``typing.Callable[[UIWidget, bool], None]``. The ``on_check_state_changed`` callback is invoked when the user changes the state of the check box, but it also includes the 'partial' state if enabled. The widget and the new state of the check box are passed to the callback. The type signature in the handler should be ``typing.Callable[[UIWidget, str], None]``. Keyword Args: text: text of the label (bindable) name: handler property in which to store widget (optional) checked: checked state (bool) check_state: checked state (string: checked, unchecked, or partial) tristate: whether the check box is tristate or not on_checked_changed: callback when checked changes (optional) on_check_state_changed: callback when check state changes (optional) Returns: UI description of the check box<|endoftext|>
7b24fbd7b1e5001853698bd52112761cd503f9e6eafd0e5b1cc91d2cc335d0e3
def create_combo_box(self, *, name: UIIdentifier=None, items: typing.List[UILabel]=None, items_ref: UIIdentifier=None, current_index: UIIdentifier=None, on_current_index_changed: UICallableIdentifier=None, **kwargs): 'Create a combo box UI description with name, items, current index, and events.\n\n The ``on_current_index_changed`` callback is invoked when the user changes the selected item in the combo box.\n The widget and the new index of the selected item are passed to the callback. The type signature in the handler\n should be ``typing.Callable[[UIWidget, int], None]``.\n\n Keyword Args:\n name: handler property in which to store widget (optional)\n items: list combo box items (strings, optional)\n items_ref: handler reference of combo box items (bindable, optional)\n current_index: current index handler reference (bindable, optional)\n on_current_index_changed: callback when current index changes (optional)\n\n Returns:\n UI description of the combo box\n ' d = {'type': 'combo_box'} if (name is not None): d['name'] = name if (items is not None): d['items'] = items if (items_ref is not None): d['items_ref'] = items_ref if (current_index is not None): d['current_index'] = current_index if (on_current_index_changed is not None): d['on_current_index_changed'] = on_current_index_changed self.__process_common_properties(d, **kwargs) return d
Create a combo box UI description with name, items, current index, and events. The ``on_current_index_changed`` callback is invoked when the user changes the selected item in the combo box. The widget and the new index of the selected item are passed to the callback. The type signature in the handler should be ``typing.Callable[[UIWidget, int], None]``. Keyword Args: name: handler property in which to store widget (optional) items: list combo box items (strings, optional) items_ref: handler reference of combo box items (bindable, optional) current_index: current index handler reference (bindable, optional) on_current_index_changed: callback when current index changes (optional) Returns: UI description of the combo box
nion/ui/Declarative.py
create_combo_box
AEljarrat/nionui
0
python
def create_combo_box(self, *, name: UIIdentifier=None, items: typing.List[UILabel]=None, items_ref: UIIdentifier=None, current_index: UIIdentifier=None, on_current_index_changed: UICallableIdentifier=None, **kwargs): 'Create a combo box UI description with name, items, current index, and events.\n\n The ``on_current_index_changed`` callback is invoked when the user changes the selected item in the combo box.\n The widget and the new index of the selected item are passed to the callback. The type signature in the handler\n should be ``typing.Callable[[UIWidget, int], None]``.\n\n Keyword Args:\n name: handler property in which to store widget (optional)\n items: list combo box items (strings, optional)\n items_ref: handler reference of combo box items (bindable, optional)\n current_index: current index handler reference (bindable, optional)\n on_current_index_changed: callback when current index changes (optional)\n\n Returns:\n UI description of the combo box\n ' d = {'type': 'combo_box'} if (name is not None): d['name'] = name if (items is not None): d['items'] = items if (items_ref is not None): d['items_ref'] = items_ref if (current_index is not None): d['current_index'] = current_index if (on_current_index_changed is not None): d['on_current_index_changed'] = on_current_index_changed self.__process_common_properties(d, **kwargs) return d
def create_combo_box(self, *, name: UIIdentifier=None, items: typing.List[UILabel]=None, items_ref: UIIdentifier=None, current_index: UIIdentifier=None, on_current_index_changed: UICallableIdentifier=None, **kwargs): 'Create a combo box UI description with name, items, current index, and events.\n\n The ``on_current_index_changed`` callback is invoked when the user changes the selected item in the combo box.\n The widget and the new index of the selected item are passed to the callback. The type signature in the handler\n should be ``typing.Callable[[UIWidget, int], None]``.\n\n Keyword Args:\n name: handler property in which to store widget (optional)\n items: list combo box items (strings, optional)\n items_ref: handler reference of combo box items (bindable, optional)\n current_index: current index handler reference (bindable, optional)\n on_current_index_changed: callback when current index changes (optional)\n\n Returns:\n UI description of the combo box\n ' d = {'type': 'combo_box'} if (name is not None): d['name'] = name if (items is not None): d['items'] = items if (items_ref is not None): d['items_ref'] = items_ref if (current_index is not None): d['current_index'] = current_index if (on_current_index_changed is not None): d['on_current_index_changed'] = on_current_index_changed self.__process_common_properties(d, **kwargs) return d<|docstring|>Create a combo box UI description with name, items, current index, and events. The ``on_current_index_changed`` callback is invoked when the user changes the selected item in the combo box. The widget and the new index of the selected item are passed to the callback. The type signature in the handler should be ``typing.Callable[[UIWidget, int], None]``. Keyword Args: name: handler property in which to store widget (optional) items: list combo box items (strings, optional) items_ref: handler reference of combo box items (bindable, optional) current_index: current index handler reference (bindable, optional) on_current_index_changed: callback when current index changes (optional) Returns: UI description of the combo box<|endoftext|>
83927a484508dec897e4fbba1f5960c440ca4ddeb199462c7769522e46c184b1
def create_radio_button(self, *, name: UIIdentifier=None, text: UILabel=None, value: typing.Any=None, group_value: UIIdentifier=None, **kwargs) -> UIDescription: 'Create a radio button UI description with text, name, value, and group value.\n\n A set of radio buttons should be created such that each has a different ``value`` but shares a common\n ``group_value``. The type of ``value`` must match the type of ``group_value``.\n\n Keyword Args:\n name: handler property in which to store widget (optional)\n text: text of the label (bindable)\n value: unique value within its group (required)\n group_value: common value handler reference (bindable, required)\n\n Returns:\n UI description of the radio button\n ' d = {'type': 'radio_button'} if (name is not None): d['name'] = name if (text is not None): d['text'] = text if (value is not None): d['value'] = value if (group_value is not None): d['group_value'] = group_value self.__process_common_properties(d, **kwargs) return d
Create a radio button UI description with text, name, value, and group value. A set of radio buttons should be created such that each has a different ``value`` but shares a common ``group_value``. The type of ``value`` must match the type of ``group_value``. Keyword Args: name: handler property in which to store widget (optional) text: text of the label (bindable) value: unique value within its group (required) group_value: common value handler reference (bindable, required) Returns: UI description of the radio button
nion/ui/Declarative.py
create_radio_button
AEljarrat/nionui
0
python
def create_radio_button(self, *, name: UIIdentifier=None, text: UILabel=None, value: typing.Any=None, group_value: UIIdentifier=None, **kwargs) -> UIDescription: 'Create a radio button UI description with text, name, value, and group value.\n\n A set of radio buttons should be created such that each has a different ``value`` but shares a common\n ``group_value``. The type of ``value`` must match the type of ``group_value``.\n\n Keyword Args:\n name: handler property in which to store widget (optional)\n text: text of the label (bindable)\n value: unique value within its group (required)\n group_value: common value handler reference (bindable, required)\n\n Returns:\n UI description of the radio button\n ' d = {'type': 'radio_button'} if (name is not None): d['name'] = name if (text is not None): d['text'] = text if (value is not None): d['value'] = value if (group_value is not None): d['group_value'] = group_value self.__process_common_properties(d, **kwargs) return d
def create_radio_button(self, *, name: UIIdentifier=None, text: UILabel=None, value: typing.Any=None, group_value: UIIdentifier=None, **kwargs) -> UIDescription: 'Create a radio button UI description with text, name, value, and group value.\n\n A set of radio buttons should be created such that each has a different ``value`` but shares a common\n ``group_value``. The type of ``value`` must match the type of ``group_value``.\n\n Keyword Args:\n name: handler property in which to store widget (optional)\n text: text of the label (bindable)\n value: unique value within its group (required)\n group_value: common value handler reference (bindable, required)\n\n Returns:\n UI description of the radio button\n ' d = {'type': 'radio_button'} if (name is not None): d['name'] = name if (text is not None): d['text'] = text if (value is not None): d['value'] = value if (group_value is not None): d['group_value'] = group_value self.__process_common_properties(d, **kwargs) return d<|docstring|>Create a radio button UI description with text, name, value, and group value. A set of radio buttons should be created such that each has a different ``value`` but shares a common ``group_value``. The type of ``value`` must match the type of ``group_value``. Keyword Args: name: handler property in which to store widget (optional) text: text of the label (bindable) value: unique value within its group (required) group_value: common value handler reference (bindable, required) Returns: UI description of the radio button<|endoftext|>
b47e45ec0329a6419acb723872d41c9aa181b4aad9d51ef9cf5eb571140f12cb
def create_slider(self, *, name: UIIdentifier=None, value: UIIdentifier=None, minimum: int=None, maximum: int=None, on_value_changed: UICallableIdentifier=None, on_slider_pressed: UICallableIdentifier=None, on_slider_released: UICallableIdentifier=None, on_slider_moved: UICallableIdentifier=None, **kwargs) -> UIDescription: 'Create a slider UI description with name, value, limits, and events.\n\n The ``on_value_changed`` callback is invoked whenever the slider value changes, including if set\n programmatically. The widget and the new value are passed to the callback. The type signature in the handler\n should be ``typing.Callable[[UIWidget, int], None]``.\n\n The ``on_slider_pressed`` callback is invoked when the user begins dragging the slider. The widget is passed to\n the callback. The type signature in the handler should be ``typing.Callable[[UIWidget], None]``.\n\n The ``on_slider_released`` callback is invoked when the user stops dragging the slider. The widget is passed to\n the callback. The type signature in the handler should be ``typing.Callable[[UIWidget], None]``.\n\n The ``on_slider_moved`` callback is invoked whenever the slider value changes while the user is dragging. The\n widget and the new value are passed to the callback. The type signature in the handler should be\n ``typing.Callable[[UIWidget, int], None]``.\n\n Keyword Args:\n name: handler property in which to store widget (optional)\n value: handler reference to the current value (required, bindable)\n minimum: minimum value (default 0)\n maximum: maximum value (default 100)\n on_value_changed: callback when value changes, any source (optional)\n on_slider_pressed: callback when slider is pressed (optional)\n on_slider_released: callback when slider is released (optional)\n on_slider_moved: callback when slider moves, user initiated only (optional)\n\n Returns:\n UI description of the slider\n ' d = {'type': 'slider'} if (name is not None): d['name'] = name if (value is not None): d['value'] = value if (minimum is not None): d['minimum'] = minimum if (maximum is not None): d['maximum'] = maximum if (on_value_changed is not None): d['on_value_changed'] = on_value_changed if (on_slider_pressed is not None): d['on_slider_pressed'] = on_slider_pressed if (on_slider_released is not None): d['on_slider_released'] = on_slider_released if (on_slider_moved is not None): d['on_slider_moved'] = on_slider_moved self.__process_common_properties(d, **kwargs) return d
Create a slider UI description with name, value, limits, and events. The ``on_value_changed`` callback is invoked whenever the slider value changes, including if set programmatically. The widget and the new value are passed to the callback. The type signature in the handler should be ``typing.Callable[[UIWidget, int], None]``. The ``on_slider_pressed`` callback is invoked when the user begins dragging the slider. The widget is passed to the callback. The type signature in the handler should be ``typing.Callable[[UIWidget], None]``. The ``on_slider_released`` callback is invoked when the user stops dragging the slider. The widget is passed to the callback. The type signature in the handler should be ``typing.Callable[[UIWidget], None]``. The ``on_slider_moved`` callback is invoked whenever the slider value changes while the user is dragging. The widget and the new value are passed to the callback. The type signature in the handler should be ``typing.Callable[[UIWidget, int], None]``. Keyword Args: name: handler property in which to store widget (optional) value: handler reference to the current value (required, bindable) minimum: minimum value (default 0) maximum: maximum value (default 100) on_value_changed: callback when value changes, any source (optional) on_slider_pressed: callback when slider is pressed (optional) on_slider_released: callback when slider is released (optional) on_slider_moved: callback when slider moves, user initiated only (optional) Returns: UI description of the slider
nion/ui/Declarative.py
create_slider
AEljarrat/nionui
0
python
def create_slider(self, *, name: UIIdentifier=None, value: UIIdentifier=None, minimum: int=None, maximum: int=None, on_value_changed: UICallableIdentifier=None, on_slider_pressed: UICallableIdentifier=None, on_slider_released: UICallableIdentifier=None, on_slider_moved: UICallableIdentifier=None, **kwargs) -> UIDescription: 'Create a slider UI description with name, value, limits, and events.\n\n The ``on_value_changed`` callback is invoked whenever the slider value changes, including if set\n programmatically. The widget and the new value are passed to the callback. The type signature in the handler\n should be ``typing.Callable[[UIWidget, int], None]``.\n\n The ``on_slider_pressed`` callback is invoked when the user begins dragging the slider. The widget is passed to\n the callback. The type signature in the handler should be ``typing.Callable[[UIWidget], None]``.\n\n The ``on_slider_released`` callback is invoked when the user stops dragging the slider. The widget is passed to\n the callback. The type signature in the handler should be ``typing.Callable[[UIWidget], None]``.\n\n The ``on_slider_moved`` callback is invoked whenever the slider value changes while the user is dragging. The\n widget and the new value are passed to the callback. The type signature in the handler should be\n ``typing.Callable[[UIWidget, int], None]``.\n\n Keyword Args:\n name: handler property in which to store widget (optional)\n value: handler reference to the current value (required, bindable)\n minimum: minimum value (default 0)\n maximum: maximum value (default 100)\n on_value_changed: callback when value changes, any source (optional)\n on_slider_pressed: callback when slider is pressed (optional)\n on_slider_released: callback when slider is released (optional)\n on_slider_moved: callback when slider moves, user initiated only (optional)\n\n Returns:\n UI description of the slider\n ' d = {'type': 'slider'} if (name is not None): d['name'] = name if (value is not None): d['value'] = value if (minimum is not None): d['minimum'] = minimum if (maximum is not None): d['maximum'] = maximum if (on_value_changed is not None): d['on_value_changed'] = on_value_changed if (on_slider_pressed is not None): d['on_slider_pressed'] = on_slider_pressed if (on_slider_released is not None): d['on_slider_released'] = on_slider_released if (on_slider_moved is not None): d['on_slider_moved'] = on_slider_moved self.__process_common_properties(d, **kwargs) return d
def create_slider(self, *, name: UIIdentifier=None, value: UIIdentifier=None, minimum: int=None, maximum: int=None, on_value_changed: UICallableIdentifier=None, on_slider_pressed: UICallableIdentifier=None, on_slider_released: UICallableIdentifier=None, on_slider_moved: UICallableIdentifier=None, **kwargs) -> UIDescription: 'Create a slider UI description with name, value, limits, and events.\n\n The ``on_value_changed`` callback is invoked whenever the slider value changes, including if set\n programmatically. The widget and the new value are passed to the callback. The type signature in the handler\n should be ``typing.Callable[[UIWidget, int], None]``.\n\n The ``on_slider_pressed`` callback is invoked when the user begins dragging the slider. The widget is passed to\n the callback. The type signature in the handler should be ``typing.Callable[[UIWidget], None]``.\n\n The ``on_slider_released`` callback is invoked when the user stops dragging the slider. The widget is passed to\n the callback. The type signature in the handler should be ``typing.Callable[[UIWidget], None]``.\n\n The ``on_slider_moved`` callback is invoked whenever the slider value changes while the user is dragging. The\n widget and the new value are passed to the callback. The type signature in the handler should be\n ``typing.Callable[[UIWidget, int], None]``.\n\n Keyword Args:\n name: handler property in which to store widget (optional)\n value: handler reference to the current value (required, bindable)\n minimum: minimum value (default 0)\n maximum: maximum value (default 100)\n on_value_changed: callback when value changes, any source (optional)\n on_slider_pressed: callback when slider is pressed (optional)\n on_slider_released: callback when slider is released (optional)\n on_slider_moved: callback when slider moves, user initiated only (optional)\n\n Returns:\n UI description of the slider\n ' d = {'type': 'slider'} if (name is not None): d['name'] = name if (value is not None): d['value'] = value if (minimum is not None): d['minimum'] = minimum if (maximum is not None): d['maximum'] = maximum if (on_value_changed is not None): d['on_value_changed'] = on_value_changed if (on_slider_pressed is not None): d['on_slider_pressed'] = on_slider_pressed if (on_slider_released is not None): d['on_slider_released'] = on_slider_released if (on_slider_moved is not None): d['on_slider_moved'] = on_slider_moved self.__process_common_properties(d, **kwargs) return d<|docstring|>Create a slider UI description with name, value, limits, and events. The ``on_value_changed`` callback is invoked whenever the slider value changes, including if set programmatically. The widget and the new value are passed to the callback. The type signature in the handler should be ``typing.Callable[[UIWidget, int], None]``. The ``on_slider_pressed`` callback is invoked when the user begins dragging the slider. The widget is passed to the callback. The type signature in the handler should be ``typing.Callable[[UIWidget], None]``. The ``on_slider_released`` callback is invoked when the user stops dragging the slider. The widget is passed to the callback. The type signature in the handler should be ``typing.Callable[[UIWidget], None]``. The ``on_slider_moved`` callback is invoked whenever the slider value changes while the user is dragging. The widget and the new value are passed to the callback. The type signature in the handler should be ``typing.Callable[[UIWidget, int], None]``. Keyword Args: name: handler property in which to store widget (optional) value: handler reference to the current value (required, bindable) minimum: minimum value (default 0) maximum: maximum value (default 100) on_value_changed: callback when value changes, any source (optional) on_slider_pressed: callback when slider is pressed (optional) on_slider_released: callback when slider is released (optional) on_slider_moved: callback when slider moves, user initiated only (optional) Returns: UI description of the slider<|endoftext|>
89eccb25eb4738868d5c01566d625d346117a850c9009e68f7e341282a9b7189
def create_progress_bar(self, *, name: UIIdentifier=None, value: UIIdentifier=None, minimum: int=None, maximum: int=None, **kwargs) -> UIDescription: 'Create a progress bar UI description with name, value, and limits.\n\n Keyword Args:\n name: handler property in which to store widget (optional)\n value: handler reference to the current value (required, bindable)\n minimum: minimum value (default 0)\n maximum: maximum value (default 100)\n\n Returns:\n UI description of the progress bar\n ' d = {'type': 'progress_bar'} if (name is not None): d['name'] = name if (value is not None): d['value'] = value if (minimum is not None): d['minimum'] = minimum if (maximum is not None): d['maximum'] = maximum self.__process_common_properties(d, **kwargs) return d
Create a progress bar UI description with name, value, and limits. Keyword Args: name: handler property in which to store widget (optional) value: handler reference to the current value (required, bindable) minimum: minimum value (default 0) maximum: maximum value (default 100) Returns: UI description of the progress bar
nion/ui/Declarative.py
create_progress_bar
AEljarrat/nionui
0
python
def create_progress_bar(self, *, name: UIIdentifier=None, value: UIIdentifier=None, minimum: int=None, maximum: int=None, **kwargs) -> UIDescription: 'Create a progress bar UI description with name, value, and limits.\n\n Keyword Args:\n name: handler property in which to store widget (optional)\n value: handler reference to the current value (required, bindable)\n minimum: minimum value (default 0)\n maximum: maximum value (default 100)\n\n Returns:\n UI description of the progress bar\n ' d = {'type': 'progress_bar'} if (name is not None): d['name'] = name if (value is not None): d['value'] = value if (minimum is not None): d['minimum'] = minimum if (maximum is not None): d['maximum'] = maximum self.__process_common_properties(d, **kwargs) return d
def create_progress_bar(self, *, name: UIIdentifier=None, value: UIIdentifier=None, minimum: int=None, maximum: int=None, **kwargs) -> UIDescription: 'Create a progress bar UI description with name, value, and limits.\n\n Keyword Args:\n name: handler property in which to store widget (optional)\n value: handler reference to the current value (required, bindable)\n minimum: minimum value (default 0)\n maximum: maximum value (default 100)\n\n Returns:\n UI description of the progress bar\n ' d = {'type': 'progress_bar'} if (name is not None): d['name'] = name if (value is not None): d['value'] = value if (minimum is not None): d['minimum'] = minimum if (maximum is not None): d['maximum'] = maximum self.__process_common_properties(d, **kwargs) return d<|docstring|>Create a progress bar UI description with name, value, and limits. Keyword Args: name: handler property in which to store widget (optional) value: handler reference to the current value (required, bindable) minimum: minimum value (default 0) maximum: maximum value (default 100) Returns: UI description of the progress bar<|endoftext|>
c149cb6bfe34e460ad18860da293e8d70e48842b52303bc49331c0672bf655db
def create_list_box(self, *, name: UIIdentifier=None, items: typing.List[UILabel]=None, items_ref: UIIdentifier=None, current_index: UIIdentifier=None, on_item_changed: UICallableIdentifier=None, on_item_selected: UICallableIdentifier=None, **kwargs) -> UIDescription: 'Create a list box UI description with name, items, current index, and events.\n\n The ``on_current_index_changed`` callback is invoked when the user changes the selected item in the list box.\n The widget and the new index of the selected item are passed to the callback. The type signature in the handler\n should be ``typing.Callable[[UIWidget, int], None]``.\n\n Keyword Args:\n name: handler property in which to store widget (optional)\n items: list list box items (strings, optional)\n items_ref: handler reference of list box items (bindable, optional)\n current_index: current index handler reference (bindable, optional)\n on_item_changed: callback when current item changes (optional)\n on_item_selected: callback when current item changes (optional)\n\n Returns:\n UI description of the list box\n ' d = {'type': 'list_box'} if (name is not None): d['name'] = name if (items is not None): d['items'] = items if (items_ref is not None): d['items_ref'] = items_ref if (current_index is not None): d['current_index'] = current_index if (on_item_changed is not None): d['on_item_changed'] = on_item_changed if (on_item_selected is not None): d['on_item_selected'] = on_item_selected self.__process_common_properties(d, **kwargs) return d
Create a list box UI description with name, items, current index, and events. The ``on_current_index_changed`` callback is invoked when the user changes the selected item in the list box. The widget and the new index of the selected item are passed to the callback. The type signature in the handler should be ``typing.Callable[[UIWidget, int], None]``. Keyword Args: name: handler property in which to store widget (optional) items: list list box items (strings, optional) items_ref: handler reference of list box items (bindable, optional) current_index: current index handler reference (bindable, optional) on_item_changed: callback when current item changes (optional) on_item_selected: callback when current item changes (optional) Returns: UI description of the list box
nion/ui/Declarative.py
create_list_box
AEljarrat/nionui
0
python
def create_list_box(self, *, name: UIIdentifier=None, items: typing.List[UILabel]=None, items_ref: UIIdentifier=None, current_index: UIIdentifier=None, on_item_changed: UICallableIdentifier=None, on_item_selected: UICallableIdentifier=None, **kwargs) -> UIDescription: 'Create a list box UI description with name, items, current index, and events.\n\n The ``on_current_index_changed`` callback is invoked when the user changes the selected item in the list box.\n The widget and the new index of the selected item are passed to the callback. The type signature in the handler\n should be ``typing.Callable[[UIWidget, int], None]``.\n\n Keyword Args:\n name: handler property in which to store widget (optional)\n items: list list box items (strings, optional)\n items_ref: handler reference of list box items (bindable, optional)\n current_index: current index handler reference (bindable, optional)\n on_item_changed: callback when current item changes (optional)\n on_item_selected: callback when current item changes (optional)\n\n Returns:\n UI description of the list box\n ' d = {'type': 'list_box'} if (name is not None): d['name'] = name if (items is not None): d['items'] = items if (items_ref is not None): d['items_ref'] = items_ref if (current_index is not None): d['current_index'] = current_index if (on_item_changed is not None): d['on_item_changed'] = on_item_changed if (on_item_selected is not None): d['on_item_selected'] = on_item_selected self.__process_common_properties(d, **kwargs) return d
def create_list_box(self, *, name: UIIdentifier=None, items: typing.List[UILabel]=None, items_ref: UIIdentifier=None, current_index: UIIdentifier=None, on_item_changed: UICallableIdentifier=None, on_item_selected: UICallableIdentifier=None, **kwargs) -> UIDescription: 'Create a list box UI description with name, items, current index, and events.\n\n The ``on_current_index_changed`` callback is invoked when the user changes the selected item in the list box.\n The widget and the new index of the selected item are passed to the callback. The type signature in the handler\n should be ``typing.Callable[[UIWidget, int], None]``.\n\n Keyword Args:\n name: handler property in which to store widget (optional)\n items: list list box items (strings, optional)\n items_ref: handler reference of list box items (bindable, optional)\n current_index: current index handler reference (bindable, optional)\n on_item_changed: callback when current item changes (optional)\n on_item_selected: callback when current item changes (optional)\n\n Returns:\n UI description of the list box\n ' d = {'type': 'list_box'} if (name is not None): d['name'] = name if (items is not None): d['items'] = items if (items_ref is not None): d['items_ref'] = items_ref if (current_index is not None): d['current_index'] = current_index if (on_item_changed is not None): d['on_item_changed'] = on_item_changed if (on_item_selected is not None): d['on_item_selected'] = on_item_selected self.__process_common_properties(d, **kwargs) return d<|docstring|>Create a list box UI description with name, items, current index, and events. The ``on_current_index_changed`` callback is invoked when the user changes the selected item in the list box. The widget and the new index of the selected item are passed to the callback. The type signature in the handler should be ``typing.Callable[[UIWidget, int], None]``. Keyword Args: name: handler property in which to store widget (optional) items: list list box items (strings, optional) items_ref: handler reference of list box items (bindable, optional) current_index: current index handler reference (bindable, optional) on_item_changed: callback when current item changes (optional) on_item_selected: callback when current item changes (optional) Returns: UI description of the list box<|endoftext|>
e9a1762862e148f99d7162be9f8f1b389a0b5ae7febca49b5bd398b73da473f4
def create_modeless_dialog(self, content: UIDescription, *, title: str=None, resources: UIResources=None, margin: UIPoints=None) -> UIDescription: 'Create a modeless dialog UI description with content, title, resources, and margin.\n\n Args:\n content: UI description of the content\n\n Keyword Args:\n title: title of the window\n resources: additional resources\n margin: margin in points\n\n Returns:\n a UI description of the dialog\n ' d = {'type': 'modeless_dialog', 'content': content} if (title is not None): d['title'] = title if (margin is not None): d['margin'] = margin if (resources is not None): d['resources'] = resources return d
Create a modeless dialog UI description with content, title, resources, and margin. Args: content: UI description of the content Keyword Args: title: title of the window resources: additional resources margin: margin in points Returns: a UI description of the dialog
nion/ui/Declarative.py
create_modeless_dialog
AEljarrat/nionui
0
python
def create_modeless_dialog(self, content: UIDescription, *, title: str=None, resources: UIResources=None, margin: UIPoints=None) -> UIDescription: 'Create a modeless dialog UI description with content, title, resources, and margin.\n\n Args:\n content: UI description of the content\n\n Keyword Args:\n title: title of the window\n resources: additional resources\n margin: margin in points\n\n Returns:\n a UI description of the dialog\n ' d = {'type': 'modeless_dialog', 'content': content} if (title is not None): d['title'] = title if (margin is not None): d['margin'] = margin if (resources is not None): d['resources'] = resources return d
def create_modeless_dialog(self, content: UIDescription, *, title: str=None, resources: UIResources=None, margin: UIPoints=None) -> UIDescription: 'Create a modeless dialog UI description with content, title, resources, and margin.\n\n Args:\n content: UI description of the content\n\n Keyword Args:\n title: title of the window\n resources: additional resources\n margin: margin in points\n\n Returns:\n a UI description of the dialog\n ' d = {'type': 'modeless_dialog', 'content': content} if (title is not None): d['title'] = title if (margin is not None): d['margin'] = margin if (resources is not None): d['resources'] = resources return d<|docstring|>Create a modeless dialog UI description with content, title, resources, and margin. Args: content: UI description of the content Keyword Args: title: title of the window resources: additional resources margin: margin in points Returns: a UI description of the dialog<|endoftext|>
69e79f4ab03bdd82439727e856c838e9a99cb91de29473e4e49c469a21b9abef
def create_window(self, content: UIDescription, *, title: str=None, resources: UIResources=None, margin: UIPoints=None, window_style: str=None) -> UIDescription: 'Create a window UI description with content, title, resources, and margin.\n\n Args:\n content: UI description description of the content\n\n Keyword Args:\n title: title of the window\n resources: additional resources\n margin: margin in points\n\n Returns:\n a UI description of the window\n ' d = {'type': 'window', 'content': content} if (title is not None): d['title'] = title if (margin is not None): d['margin'] = margin if (resources is not None): d['resources'] = resources if (window_style is not None): d['window_style'] = window_style return d
Create a window UI description with content, title, resources, and margin. Args: content: UI description description of the content Keyword Args: title: title of the window resources: additional resources margin: margin in points Returns: a UI description of the window
nion/ui/Declarative.py
create_window
AEljarrat/nionui
0
python
def create_window(self, content: UIDescription, *, title: str=None, resources: UIResources=None, margin: UIPoints=None, window_style: str=None) -> UIDescription: 'Create a window UI description with content, title, resources, and margin.\n\n Args:\n content: UI description description of the content\n\n Keyword Args:\n title: title of the window\n resources: additional resources\n margin: margin in points\n\n Returns:\n a UI description of the window\n ' d = {'type': 'window', 'content': content} if (title is not None): d['title'] = title if (margin is not None): d['margin'] = margin if (resources is not None): d['resources'] = resources if (window_style is not None): d['window_style'] = window_style return d
def create_window(self, content: UIDescription, *, title: str=None, resources: UIResources=None, margin: UIPoints=None, window_style: str=None) -> UIDescription: 'Create a window UI description with content, title, resources, and margin.\n\n Args:\n content: UI description description of the content\n\n Keyword Args:\n title: title of the window\n resources: additional resources\n margin: margin in points\n\n Returns:\n a UI description of the window\n ' d = {'type': 'window', 'content': content} if (title is not None): d['title'] = title if (margin is not None): d['margin'] = margin if (resources is not None): d['resources'] = resources if (window_style is not None): d['window_style'] = window_style return d<|docstring|>Create a window UI description with content, title, resources, and margin. Args: content: UI description description of the content Keyword Args: title: title of the window resources: additional resources margin: margin in points Returns: a UI description of the window<|endoftext|>
dad6cd55eb6f1660dcb66c0d46a71444a18a12e14ef84104937e93700f07e154
def _index_external(to_index, index_type: IndexType, lang='en'): '\n Creates TweetExIndex objects for a list of TweetEx objects.\n\n !!! DOES NOT CHECK FOR ALREADY INDEXED TWEETS. FILTERING MUST BE DONE BEFORE CALLING THE FUNCTION !!!\n Call "index_for_users" instead of calling this directly! Pre-selection / filtering is done there!\n\n :param to_index: A list of TweetEx objects to be indexed.\n :param lang: Optional. Default: "en". The language of the Tweets. TODO: Do language per Tweet\n ' nlp = get_spacy_model(lang=lang) create = [] np_check = defaultdict(int) for (i, elem) in enumerate(to_index): if ((i % 100) == 0): print(f'--> Indexing Element {(i + 1)} out of {len(to_index)} ({str(index_type)}) <--') if (index_type == IndexType.TWEET): text = elem.text else: raise Exception('this should never print and if it does then that means that something has gone catastrophically wrong: ERROR CODE: #123pleaseno') sents = pos_tag_spacy(text, nlp) freqs = defaultdict(int) for sent in sents: sent_data = [(token, tag) for (token, tag) in sent.tokens.items()] for (token, tag) in sent_data: if ((tag == 'NOUN') or (tag == 'PROPN')): np_check[token] += 2 (nps, terms) = extract_nps_from_sent(sent_data) for (_start, _end, np) in nps: np_check[np] += 1 for (_start, _end, t) in terms: np_check[t] -= 1 nps.extend(terms) for (_start, _end, term) in nps: freqs[term] += 1 for (term, freq) in freqs.items(): noun = False if (np_check[term] > 0): noun = True if (index_type == IndexType.TWEET): create.append(TweetExIndex(term=term, tweet=elem, count=freq, day=elem.created_at.day, month=elem.created_at.month, year=elem.created_at.year, noun=noun)) if (index_type == IndexType.TWEET): TweetExIndex.objects.bulk_create(create)
Creates TweetExIndex objects for a list of TweetEx objects. !!! DOES NOT CHECK FOR ALREADY INDEXED TWEETS. FILTERING MUST BE DONE BEFORE CALLING THE FUNCTION !!! Call "index_for_users" instead of calling this directly! Pre-selection / filtering is done there! :param to_index: A list of TweetEx objects to be indexed. :param lang: Optional. Default: "en". The language of the Tweets. TODO: Do language per Tweet
index/index_tweets.py
_index_external
Madjura/klang-thesis
0
python
def _index_external(to_index, index_type: IndexType, lang='en'): '\n Creates TweetExIndex objects for a list of TweetEx objects.\n\n !!! DOES NOT CHECK FOR ALREADY INDEXED TWEETS. FILTERING MUST BE DONE BEFORE CALLING THE FUNCTION !!!\n Call "index_for_users" instead of calling this directly! Pre-selection / filtering is done there!\n\n :param to_index: A list of TweetEx objects to be indexed.\n :param lang: Optional. Default: "en". The language of the Tweets. TODO: Do language per Tweet\n ' nlp = get_spacy_model(lang=lang) create = [] np_check = defaultdict(int) for (i, elem) in enumerate(to_index): if ((i % 100) == 0): print(f'--> Indexing Element {(i + 1)} out of {len(to_index)} ({str(index_type)}) <--') if (index_type == IndexType.TWEET): text = elem.text else: raise Exception('this should never print and if it does then that means that something has gone catastrophically wrong: ERROR CODE: #123pleaseno') sents = pos_tag_spacy(text, nlp) freqs = defaultdict(int) for sent in sents: sent_data = [(token, tag) for (token, tag) in sent.tokens.items()] for (token, tag) in sent_data: if ((tag == 'NOUN') or (tag == 'PROPN')): np_check[token] += 2 (nps, terms) = extract_nps_from_sent(sent_data) for (_start, _end, np) in nps: np_check[np] += 1 for (_start, _end, t) in terms: np_check[t] -= 1 nps.extend(terms) for (_start, _end, term) in nps: freqs[term] += 1 for (term, freq) in freqs.items(): noun = False if (np_check[term] > 0): noun = True if (index_type == IndexType.TWEET): create.append(TweetExIndex(term=term, tweet=elem, count=freq, day=elem.created_at.day, month=elem.created_at.month, year=elem.created_at.year, noun=noun)) if (index_type == IndexType.TWEET): TweetExIndex.objects.bulk_create(create)
def _index_external(to_index, index_type: IndexType, lang='en'): '\n Creates TweetExIndex objects for a list of TweetEx objects.\n\n !!! DOES NOT CHECK FOR ALREADY INDEXED TWEETS. FILTERING MUST BE DONE BEFORE CALLING THE FUNCTION !!!\n Call "index_for_users" instead of calling this directly! Pre-selection / filtering is done there!\n\n :param to_index: A list of TweetEx objects to be indexed.\n :param lang: Optional. Default: "en". The language of the Tweets. TODO: Do language per Tweet\n ' nlp = get_spacy_model(lang=lang) create = [] np_check = defaultdict(int) for (i, elem) in enumerate(to_index): if ((i % 100) == 0): print(f'--> Indexing Element {(i + 1)} out of {len(to_index)} ({str(index_type)}) <--') if (index_type == IndexType.TWEET): text = elem.text else: raise Exception('this should never print and if it does then that means that something has gone catastrophically wrong: ERROR CODE: #123pleaseno') sents = pos_tag_spacy(text, nlp) freqs = defaultdict(int) for sent in sents: sent_data = [(token, tag) for (token, tag) in sent.tokens.items()] for (token, tag) in sent_data: if ((tag == 'NOUN') or (tag == 'PROPN')): np_check[token] += 2 (nps, terms) = extract_nps_from_sent(sent_data) for (_start, _end, np) in nps: np_check[np] += 1 for (_start, _end, t) in terms: np_check[t] -= 1 nps.extend(terms) for (_start, _end, term) in nps: freqs[term] += 1 for (term, freq) in freqs.items(): noun = False if (np_check[term] > 0): noun = True if (index_type == IndexType.TWEET): create.append(TweetExIndex(term=term, tweet=elem, count=freq, day=elem.created_at.day, month=elem.created_at.month, year=elem.created_at.year, noun=noun)) if (index_type == IndexType.TWEET): TweetExIndex.objects.bulk_create(create)<|docstring|>Creates TweetExIndex objects for a list of TweetEx objects. !!! DOES NOT CHECK FOR ALREADY INDEXED TWEETS. FILTERING MUST BE DONE BEFORE CALLING THE FUNCTION !!! Call "index_for_users" instead of calling this directly! Pre-selection / filtering is done there! :param to_index: A list of TweetEx objects to be indexed. :param lang: Optional. Default: "en". The language of the Tweets. TODO: Do language per Tweet<|endoftext|>
27c8702ead9ad9439715345cb271d22df44565d63ac084d0fb80accdd2927c4f
@pytest.mark.wig def test_wig_indexer(): '\n Function to test Kallisto indexer\n ' resource_path = os.path.join(os.path.dirname(__file__), 'data/') f_check = h5py.File((resource_path + 'file_index.hdf5'), 'a') f_check.close() input_files = {'wig': (resource_path + 'sample.wig'), 'chrom_file': (resource_path + 'chrom_GRCh38.size'), 'hdf5_file': (resource_path + 'file_index.hdf5')} output_files = {'bw_file': (resource_path + 'sample.bw')} metadata = {'wig': Metadata('data_rnaseq', 'wig', 'test_wig_location', [], {'assembly': 'test'}), 'hdf5_file': Metadata('data_file', 'hdf5', 'test_location', [], {})} bw_handle = wigIndexerTool({'bed_type': 'bed6+4'}) bw_handle.run(input_files, metadata, output_files) assert (os.path.isfile((resource_path + 'sample.bw')) is True) assert (os.path.getsize((resource_path + 'sample.bw')) > 0)
Function to test Kallisto indexer
mg_process_files/tests/test_wig_functions.py
test_wig_indexer
Multiscale-Genomics/mg-process-tsv
0
python
@pytest.mark.wig def test_wig_indexer(): '\n \n ' resource_path = os.path.join(os.path.dirname(__file__), 'data/') f_check = h5py.File((resource_path + 'file_index.hdf5'), 'a') f_check.close() input_files = {'wig': (resource_path + 'sample.wig'), 'chrom_file': (resource_path + 'chrom_GRCh38.size'), 'hdf5_file': (resource_path + 'file_index.hdf5')} output_files = {'bw_file': (resource_path + 'sample.bw')} metadata = {'wig': Metadata('data_rnaseq', 'wig', 'test_wig_location', [], {'assembly': 'test'}), 'hdf5_file': Metadata('data_file', 'hdf5', 'test_location', [], {})} bw_handle = wigIndexerTool({'bed_type': 'bed6+4'}) bw_handle.run(input_files, metadata, output_files) assert (os.path.isfile((resource_path + 'sample.bw')) is True) assert (os.path.getsize((resource_path + 'sample.bw')) > 0)
@pytest.mark.wig def test_wig_indexer(): '\n \n ' resource_path = os.path.join(os.path.dirname(__file__), 'data/') f_check = h5py.File((resource_path + 'file_index.hdf5'), 'a') f_check.close() input_files = {'wig': (resource_path + 'sample.wig'), 'chrom_file': (resource_path + 'chrom_GRCh38.size'), 'hdf5_file': (resource_path + 'file_index.hdf5')} output_files = {'bw_file': (resource_path + 'sample.bw')} metadata = {'wig': Metadata('data_rnaseq', 'wig', 'test_wig_location', [], {'assembly': 'test'}), 'hdf5_file': Metadata('data_file', 'hdf5', 'test_location', [], {})} bw_handle = wigIndexerTool({'bed_type': 'bed6+4'}) bw_handle.run(input_files, metadata, output_files) assert (os.path.isfile((resource_path + 'sample.bw')) is True) assert (os.path.getsize((resource_path + 'sample.bw')) > 0)<|docstring|>Function to test Kallisto indexer<|endoftext|>
ca34de924c988c47efbd30b4f9c9e6f07de509c34575cd76885e8001210944db
def encode_run_length(string): "I'm aware this is a dirty solution." encoded = '' count = 1 for (char, next_char) in zip(string, (string[1:] + '\n')): if (char == next_char): count += 1 else: encoded += f'{count}{char}' count = 1 return encoded
I'm aware this is a dirty solution.
src/practice_problems/solutions/run_length_encoding.py
encode_run_length
tarasivashchuk/practice-problems
1
python
def encode_run_length(string): encoded = count = 1 for (char, next_char) in zip(string, (string[1:] + '\n')): if (char == next_char): count += 1 else: encoded += f'{count}{char}' count = 1 return encoded
def encode_run_length(string): encoded = count = 1 for (char, next_char) in zip(string, (string[1:] + '\n')): if (char == next_char): count += 1 else: encoded += f'{count}{char}' count = 1 return encoded<|docstring|>I'm aware this is a dirty solution.<|endoftext|>
9f08decb7ab955d4f6346e41ac77da2fc63942e082ac5e168dde9c41cdfc5b84
def decode_run_length(encoded_string): 'Again, aware this could be much cleaner. In a hurry right now.' string = '' for x in range(0, len(encoded_string), 2): (num, char) = (encoded_string[x], encoded_string[(x + 1)]) string += ''.join(([char] * int(num))) return string
Again, aware this could be much cleaner. In a hurry right now.
src/practice_problems/solutions/run_length_encoding.py
decode_run_length
tarasivashchuk/practice-problems
1
python
def decode_run_length(encoded_string): string = for x in range(0, len(encoded_string), 2): (num, char) = (encoded_string[x], encoded_string[(x + 1)]) string += .join(([char] * int(num))) return string
def decode_run_length(encoded_string): string = for x in range(0, len(encoded_string), 2): (num, char) = (encoded_string[x], encoded_string[(x + 1)]) string += .join(([char] * int(num))) return string<|docstring|>Again, aware this could be much cleaner. In a hurry right now.<|endoftext|>
b5bb066835cbe379c76c091f75b2a0df6ac7a9c1b2b810cfca9b13510aee11b0
def addTest(self, test): 'This will filter out "private" classes that begin with an underscore' add_it = True if isinstance(test, TestCase): add_it = (not test.__class__.__name__.startswith('_')) if add_it: super(TestSuite, self).addTest(test)
This will filter out "private" classes that begin with an underscore
pyt/tester.py
addTest
jayvdb/pyt
1
python
def addTest(self, test): add_it = True if isinstance(test, TestCase): add_it = (not test.__class__.__name__.startswith('_')) if add_it: super(TestSuite, self).addTest(test)
def addTest(self, test): add_it = True if isinstance(test, TestCase): add_it = (not test.__class__.__name__.startswith('_')) if add_it: super(TestSuite, self).addTest(test)<|docstring|>This will filter out "private" classes that begin with an underscore<|endoftext|>
19fb11e56e97067a10c8181505cd91b21a5e2177337137c02662eef1c6e00334
@nox.session(python=UNIT_TEST_PYTHON_VERSIONS) def unit(session): 'Run the unit test suite.' constraints_path = str(((CURRENT_DIRECTORY / 'testing') / f'constraints-{session.python}.txt')) session.install('mock', 'pytest', 'pytest-cov', 'pytest-asyncio<=0.14.0') session.install(GOOGLE_AUTH, '-c', constraints_path) session.install('-e', '.[requests,aiohttp]', '-c', constraints_path) line_coverage = '--cov-fail-under=0' session.run('py.test', '--cov=google.resumable_media', '--cov=google._async_resumable_media', '--cov=tests.unit', '--cov=tests_async.unit', '--cov-append', '--cov-config=.coveragerc', '--cov-report=', line_coverage, os.path.join('tests', 'unit'), os.path.join('tests_async', 'unit'), *session.posargs)
Run the unit test suite.
noxfile.py
unit
Breathtender/google-resumable-media-python
34
python
@nox.session(python=UNIT_TEST_PYTHON_VERSIONS) def unit(session): constraints_path = str(((CURRENT_DIRECTORY / 'testing') / f'constraints-{session.python}.txt')) session.install('mock', 'pytest', 'pytest-cov', 'pytest-asyncio<=0.14.0') session.install(GOOGLE_AUTH, '-c', constraints_path) session.install('-e', '.[requests,aiohttp]', '-c', constraints_path) line_coverage = '--cov-fail-under=0' session.run('py.test', '--cov=google.resumable_media', '--cov=google._async_resumable_media', '--cov=tests.unit', '--cov=tests_async.unit', '--cov-append', '--cov-config=.coveragerc', '--cov-report=', line_coverage, os.path.join('tests', 'unit'), os.path.join('tests_async', 'unit'), *session.posargs)
@nox.session(python=UNIT_TEST_PYTHON_VERSIONS) def unit(session): constraints_path = str(((CURRENT_DIRECTORY / 'testing') / f'constraints-{session.python}.txt')) session.install('mock', 'pytest', 'pytest-cov', 'pytest-asyncio<=0.14.0') session.install(GOOGLE_AUTH, '-c', constraints_path) session.install('-e', '.[requests,aiohttp]', '-c', constraints_path) line_coverage = '--cov-fail-under=0' session.run('py.test', '--cov=google.resumable_media', '--cov=google._async_resumable_media', '--cov=tests.unit', '--cov=tests_async.unit', '--cov-append', '--cov-config=.coveragerc', '--cov-report=', line_coverage, os.path.join('tests', 'unit'), os.path.join('tests_async', 'unit'), *session.posargs)<|docstring|>Run the unit test suite.<|endoftext|>
755c7456152a24aea1999300c348796c9e05b994ea8464ca7f4e43624cf57c50
@nox.session(python=DEFAULT_PYTHON_VERSION) def docs(session): 'Build the docs for this library.' session.install('-e', '.') session.install('sphinx==4.0.1', 'alabaster', 'recommonmark') shutil.rmtree(os.path.join('docs', '_build'), ignore_errors=True) session.run('sphinx-build', '-W', '-T', '-N', '-b', 'html', '-d', os.path.join('docs', '_build', 'doctrees', ''), os.path.join('docs', ''), os.path.join('docs', '_build', 'html', ''))
Build the docs for this library.
noxfile.py
docs
Breathtender/google-resumable-media-python
34
python
@nox.session(python=DEFAULT_PYTHON_VERSION) def docs(session): session.install('-e', '.') session.install('sphinx==4.0.1', 'alabaster', 'recommonmark') shutil.rmtree(os.path.join('docs', '_build'), ignore_errors=True) session.run('sphinx-build', '-W', '-T', '-N', '-b', 'html', '-d', os.path.join('docs', '_build', 'doctrees', ), os.path.join('docs', ), os.path.join('docs', '_build', 'html', ))
@nox.session(python=DEFAULT_PYTHON_VERSION) def docs(session): session.install('-e', '.') session.install('sphinx==4.0.1', 'alabaster', 'recommonmark') shutil.rmtree(os.path.join('docs', '_build'), ignore_errors=True) session.run('sphinx-build', '-W', '-T', '-N', '-b', 'html', '-d', os.path.join('docs', '_build', 'doctrees', ), os.path.join('docs', ), os.path.join('docs', '_build', 'html', ))<|docstring|>Build the docs for this library.<|endoftext|>
e8c5087cf8ed9c590d416cf6f7a2c8eeed3418a67fac720e0c31b1f695bc66c5
@nox.session(python=DEFAULT_PYTHON_VERSION) def docfx(session): 'Build the docfx yaml files for this library.' session.install('-e', '.') session.install('sphinx==4.0.1', 'alabaster', 'recommonmark', 'gcp-sphinx-docfx-yaml==0.2.0') shutil.rmtree(os.path.join('docs', '_build'), ignore_errors=True) session.run('sphinx-build', '-T', '-N', '-D', 'extensions=sphinx.ext.autodoc,sphinx.ext.autosummary,docfx_yaml.extension,sphinx.ext.intersphinx,sphinx.ext.coverage,sphinx.ext.napoleon,sphinx.ext.todo,sphinx.ext.viewcode,recommonmark', '-b', 'html', '-d', os.path.join('docs', '_build', 'doctrees', ''), os.path.join('docs', ''), os.path.join('docs', '_build', 'html', ''))
Build the docfx yaml files for this library.
noxfile.py
docfx
Breathtender/google-resumable-media-python
34
python
@nox.session(python=DEFAULT_PYTHON_VERSION) def docfx(session): session.install('-e', '.') session.install('sphinx==4.0.1', 'alabaster', 'recommonmark', 'gcp-sphinx-docfx-yaml==0.2.0') shutil.rmtree(os.path.join('docs', '_build'), ignore_errors=True) session.run('sphinx-build', '-T', '-N', '-D', 'extensions=sphinx.ext.autodoc,sphinx.ext.autosummary,docfx_yaml.extension,sphinx.ext.intersphinx,sphinx.ext.coverage,sphinx.ext.napoleon,sphinx.ext.todo,sphinx.ext.viewcode,recommonmark', '-b', 'html', '-d', os.path.join('docs', '_build', 'doctrees', ), os.path.join('docs', ), os.path.join('docs', '_build', 'html', ))
@nox.session(python=DEFAULT_PYTHON_VERSION) def docfx(session): session.install('-e', '.') session.install('sphinx==4.0.1', 'alabaster', 'recommonmark', 'gcp-sphinx-docfx-yaml==0.2.0') shutil.rmtree(os.path.join('docs', '_build'), ignore_errors=True) session.run('sphinx-build', '-T', '-N', '-D', 'extensions=sphinx.ext.autodoc,sphinx.ext.autosummary,docfx_yaml.extension,sphinx.ext.intersphinx,sphinx.ext.coverage,sphinx.ext.napoleon,sphinx.ext.todo,sphinx.ext.viewcode,recommonmark', '-b', 'html', '-d', os.path.join('docs', '_build', 'doctrees', ), os.path.join('docs', ), os.path.join('docs', '_build', 'html', ))<|docstring|>Build the docfx yaml files for this library.<|endoftext|>
c5e5fc012a99e154045460922c799ded442d5ce5740e9cee57d5d34ffe1cac39
@nox.session(python=DEFAULT_PYTHON_VERSION) def doctest(session): 'Run the doctests.' session.install('-e', '.[requests]') session.install('sphinx', 'alabaster', 'recommonmark') session.install('sphinx', 'sphinx_rtd_theme', 'sphinx-docstring-typing >= 0.0.3', 'mock', GOOGLE_AUTH) session.run('sphinx-build', '-W', '-b', 'doctest', '-d', os.path.join('docs', '_build', 'doctrees'), os.path.join('docs', ''), os.path.join('docs', '_build', 'doctest'))
Run the doctests.
noxfile.py
doctest
Breathtender/google-resumable-media-python
34
python
@nox.session(python=DEFAULT_PYTHON_VERSION) def doctest(session): session.install('-e', '.[requests]') session.install('sphinx', 'alabaster', 'recommonmark') session.install('sphinx', 'sphinx_rtd_theme', 'sphinx-docstring-typing >= 0.0.3', 'mock', GOOGLE_AUTH) session.run('sphinx-build', '-W', '-b', 'doctest', '-d', os.path.join('docs', '_build', 'doctrees'), os.path.join('docs', ), os.path.join('docs', '_build', 'doctest'))
@nox.session(python=DEFAULT_PYTHON_VERSION) def doctest(session): session.install('-e', '.[requests]') session.install('sphinx', 'alabaster', 'recommonmark') session.install('sphinx', 'sphinx_rtd_theme', 'sphinx-docstring-typing >= 0.0.3', 'mock', GOOGLE_AUTH) session.run('sphinx-build', '-W', '-b', 'doctest', '-d', os.path.join('docs', '_build', 'doctrees'), os.path.join('docs', ), os.path.join('docs', '_build', 'doctest'))<|docstring|>Run the doctests.<|endoftext|>
3a46e570645535046c9542b0cfe32bb779c13e8ead784683697137facd43deb2
@nox.session(python=DEFAULT_PYTHON_VERSION) def lint(session): 'Run flake8.\n\n Returns a failure if flake8 finds linting errors or sufficiently\n serious code quality issues.\n ' session.install('flake8', BLACK_VERSION) session.install('-e', '.') session.run('flake8', os.path.join('google', 'resumable_media'), 'tests', os.path.join('google', '_async_resumable_media'), 'tests_async') session.run('black', '--check', os.path.join('google', 'resumable_media'), 'tests', os.path.join('google', '_async_resumable_media'), 'tests_async')
Run flake8. Returns a failure if flake8 finds linting errors or sufficiently serious code quality issues.
noxfile.py
lint
Breathtender/google-resumable-media-python
34
python
@nox.session(python=DEFAULT_PYTHON_VERSION) def lint(session): 'Run flake8.\n\n Returns a failure if flake8 finds linting errors or sufficiently\n serious code quality issues.\n ' session.install('flake8', BLACK_VERSION) session.install('-e', '.') session.run('flake8', os.path.join('google', 'resumable_media'), 'tests', os.path.join('google', '_async_resumable_media'), 'tests_async') session.run('black', '--check', os.path.join('google', 'resumable_media'), 'tests', os.path.join('google', '_async_resumable_media'), 'tests_async')
@nox.session(python=DEFAULT_PYTHON_VERSION) def lint(session): 'Run flake8.\n\n Returns a failure if flake8 finds linting errors or sufficiently\n serious code quality issues.\n ' session.install('flake8', BLACK_VERSION) session.install('-e', '.') session.run('flake8', os.path.join('google', 'resumable_media'), 'tests', os.path.join('google', '_async_resumable_media'), 'tests_async') session.run('black', '--check', os.path.join('google', 'resumable_media'), 'tests', os.path.join('google', '_async_resumable_media'), 'tests_async')<|docstring|>Run flake8. Returns a failure if flake8 finds linting errors or sufficiently serious code quality issues.<|endoftext|>
8b4e929b85dd7c91945d6bd1362dd5d44ed02a97004db5de48d69498f0d83105
@nox.session(python=DEFAULT_PYTHON_VERSION) def lint_setup_py(session): 'Verify that setup.py is valid (including RST check).' session.install('docutils', 'Pygments') session.run('python', 'setup.py', 'check', '--restructuredtext', '--strict')
Verify that setup.py is valid (including RST check).
noxfile.py
lint_setup_py
Breathtender/google-resumable-media-python
34
python
@nox.session(python=DEFAULT_PYTHON_VERSION) def lint_setup_py(session): session.install('docutils', 'Pygments') session.run('python', 'setup.py', 'check', '--restructuredtext', '--strict')
@nox.session(python=DEFAULT_PYTHON_VERSION) def lint_setup_py(session): session.install('docutils', 'Pygments') session.run('python', 'setup.py', 'check', '--restructuredtext', '--strict')<|docstring|>Verify that setup.py is valid (including RST check).<|endoftext|>
929c3c6f02e64af61fd5c58a02c147490aeba7f11e05399cf92dd28b69094b71
@nox.session(python=DEFAULT_PYTHON_VERSION) def mypy(session): 'Verify type hints are mypy compatible.' session.install('-e', '.') session.install('mypy', 'types-setuptools', 'types-requests', 'types-mock') session.run('mypy', 'google/', 'tests/', 'tests_async/')
Verify type hints are mypy compatible.
noxfile.py
mypy
Breathtender/google-resumable-media-python
34
python
@nox.session(python=DEFAULT_PYTHON_VERSION) def mypy(session): session.install('-e', '.') session.install('mypy', 'types-setuptools', 'types-requests', 'types-mock') session.run('mypy', 'google/', 'tests/', 'tests_async/')
@nox.session(python=DEFAULT_PYTHON_VERSION) def mypy(session): session.install('-e', '.') session.install('mypy', 'types-setuptools', 'types-requests', 'types-mock') session.run('mypy', 'google/', 'tests/', 'tests_async/')<|docstring|>Verify type hints are mypy compatible.<|endoftext|>
40dac7b257933342d4079ed0439a392fdfc1a9af94c4e6077906f96f7850b961
@nox.session(python=SYSTEM_TEST_PYTHON_VERSIONS) def system(session): 'Run the system test suite.' constraints_path = str(((CURRENT_DIRECTORY / 'testing') / f'constraints-{session.python}.txt')) missing = [] for env_var in SYSTEM_TEST_ENV_VARS: if (env_var not in os.environ): missing.append(env_var) if missing: all_vars = ', '.join(missing) msg = 'Environment variable(s) unset: {}'.format(all_vars) session.skip(msg) session.install('mock', 'pytest', 'google-cloud-testutils') session.install(GOOGLE_AUTH, '-c', constraints_path) session.install('-e', '.[requests,aiohttp]', '-c', constraints_path) if session.python.startswith('3'): session.install('pytest-asyncio<=0.14.0') session.run('py.test', '-s', os.path.join('tests_async', 'system'), *session.posargs) session.run('py.test', '-s', os.path.join('tests', 'system'), *session.posargs)
Run the system test suite.
noxfile.py
system
Breathtender/google-resumable-media-python
34
python
@nox.session(python=SYSTEM_TEST_PYTHON_VERSIONS) def system(session): constraints_path = str(((CURRENT_DIRECTORY / 'testing') / f'constraints-{session.python}.txt')) missing = [] for env_var in SYSTEM_TEST_ENV_VARS: if (env_var not in os.environ): missing.append(env_var) if missing: all_vars = ', '.join(missing) msg = 'Environment variable(s) unset: {}'.format(all_vars) session.skip(msg) session.install('mock', 'pytest', 'google-cloud-testutils') session.install(GOOGLE_AUTH, '-c', constraints_path) session.install('-e', '.[requests,aiohttp]', '-c', constraints_path) if session.python.startswith('3'): session.install('pytest-asyncio<=0.14.0') session.run('py.test', '-s', os.path.join('tests_async', 'system'), *session.posargs) session.run('py.test', '-s', os.path.join('tests', 'system'), *session.posargs)
@nox.session(python=SYSTEM_TEST_PYTHON_VERSIONS) def system(session): constraints_path = str(((CURRENT_DIRECTORY / 'testing') / f'constraints-{session.python}.txt')) missing = [] for env_var in SYSTEM_TEST_ENV_VARS: if (env_var not in os.environ): missing.append(env_var) if missing: all_vars = ', '.join(missing) msg = 'Environment variable(s) unset: {}'.format(all_vars) session.skip(msg) session.install('mock', 'pytest', 'google-cloud-testutils') session.install(GOOGLE_AUTH, '-c', constraints_path) session.install('-e', '.[requests,aiohttp]', '-c', constraints_path) if session.python.startswith('3'): session.install('pytest-asyncio<=0.14.0') session.run('py.test', '-s', os.path.join('tests_async', 'system'), *session.posargs) session.run('py.test', '-s', os.path.join('tests', 'system'), *session.posargs)<|docstring|>Run the system test suite.<|endoftext|>
610dd41554f315a14f72a6449abf54c63a56062968ea4b3707ee16c4c01481bd
@nox.session(python=DEFAULT_PYTHON_VERSION) def cover(session): 'Run the final coverage report.\n\n This outputs the coverage report aggregating coverage from the unit\n test runs (not system test runs), and then erases coverage data.\n ' session.install('coverage', 'pytest-cov') session.run('coverage', 'report', '--show-missing', '--fail-under=100') session.run('coverage', 'erase')
Run the final coverage report. This outputs the coverage report aggregating coverage from the unit test runs (not system test runs), and then erases coverage data.
noxfile.py
cover
Breathtender/google-resumable-media-python
34
python
@nox.session(python=DEFAULT_PYTHON_VERSION) def cover(session): 'Run the final coverage report.\n\n This outputs the coverage report aggregating coverage from the unit\n test runs (not system test runs), and then erases coverage data.\n ' session.install('coverage', 'pytest-cov') session.run('coverage', 'report', '--show-missing', '--fail-under=100') session.run('coverage', 'erase')
@nox.session(python=DEFAULT_PYTHON_VERSION) def cover(session): 'Run the final coverage report.\n\n This outputs the coverage report aggregating coverage from the unit\n test runs (not system test runs), and then erases coverage data.\n ' session.install('coverage', 'pytest-cov') session.run('coverage', 'report', '--show-missing', '--fail-under=100') session.run('coverage', 'erase')<|docstring|>Run the final coverage report. This outputs the coverage report aggregating coverage from the unit test runs (not system test runs), and then erases coverage data.<|endoftext|>
15567fd10f8e2dd2899fee7fb5cba279e0fa82967807f0ad660bbed6cf2c0e43
def transfer_function(self, dirname, filename, namespace, uuid, disposal_timeout, is_input, client_paths=None): ' Default function: use raw filename\n ' return os.path.join(dirname, filename)
Default function: use raw filename
python/soma_workflow/test/workflow_tests/workflow_examples/workflow_local.py
transfer_function
denisri/soma-workflow
0
python
def transfer_function(self, dirname, filename, namespace, uuid, disposal_timeout, is_input, client_paths=None): ' \n ' return os.path.join(dirname, filename)
def transfer_function(self, dirname, filename, namespace, uuid, disposal_timeout, is_input, client_paths=None): ' \n ' return os.path.join(dirname, filename)<|docstring|>Default function: use raw filename<|endoftext|>
842c99b5fb1394fc25639057802f23af25b20dd280b1ac8c4daebca9f64930eb
def shared_function(self, dirname, filename, namespace, uuid, disposal_timeout, is_input, client_paths=None): ' Default function: use raw filename\n ' return os.path.join(dirname, filename)
Default function: use raw filename
python/soma_workflow/test/workflow_tests/workflow_examples/workflow_local.py
shared_function
denisri/soma-workflow
0
python
def shared_function(self, dirname, filename, namespace, uuid, disposal_timeout, is_input, client_paths=None): ' \n ' return os.path.join(dirname, filename)
def shared_function(self, dirname, filename, namespace, uuid, disposal_timeout, is_input, client_paths=None): ' \n ' return os.path.join(dirname, filename)<|docstring|>Default function: use raw filename<|endoftext|>
fd735275beabcd4ccb0be248cf3eca11bd3ae097bdc72de4575a13f10359066c
def parse_photo_link(photo_url): '\n Extracts the base URL (URL without query parameters) and the photo name from a Onedrive photo URL\n :param photo_url: photo URL\n :return: base URL and photo name\n ' base_url = photo_url.split('=')[0] name = base_url.split('/')[(- 1)] return (base_url, name)
Extracts the base URL (URL without query parameters) and the photo name from a Onedrive photo URL :param photo_url: photo URL :return: base URL and photo name
simplegallery/logic/variants/google_gallery_logic.py
parse_photo_link
kroesche/simple-photo-gallery
94
python
def parse_photo_link(photo_url): '\n Extracts the base URL (URL without query parameters) and the photo name from a Onedrive photo URL\n :param photo_url: photo URL\n :return: base URL and photo name\n ' base_url = photo_url.split('=')[0] name = base_url.split('/')[(- 1)] return (base_url, name)
def parse_photo_link(photo_url): '\n Extracts the base URL (URL without query parameters) and the photo name from a Onedrive photo URL\n :param photo_url: photo URL\n :return: base URL and photo name\n ' base_url = photo_url.split('=')[0] name = base_url.split('/')[(- 1)] return (base_url, name)<|docstring|>Extracts the base URL (URL without query parameters) and the photo name from a Onedrive photo URL :param photo_url: photo URL :return: base URL and photo name<|endoftext|>
7d284dbc105ed41fb404f817066155c9a9e63429d24df982aae1a0714bc17102
def create_thumbnails(self, force=False): "\n This function doesn't do anything, because the thumbnails are links to OneDrive\n :param force: Forces generation of thumbnails if set to true\n " pass
This function doesn't do anything, because the thumbnails are links to OneDrive :param force: Forces generation of thumbnails if set to true
simplegallery/logic/variants/google_gallery_logic.py
create_thumbnails
kroesche/simple-photo-gallery
94
python
def create_thumbnails(self, force=False): "\n This function doesn't do anything, because the thumbnails are links to OneDrive\n :param force: Forces generation of thumbnails if set to true\n " pass
def create_thumbnails(self, force=False): "\n This function doesn't do anything, because the thumbnails are links to OneDrive\n :param force: Forces generation of thumbnails if set to true\n " pass<|docstring|>This function doesn't do anything, because the thumbnails are links to OneDrive :param force: Forces generation of thumbnails if set to true<|endoftext|>
0d8a1afd29442f1b33a99be599a9623f6e9562afd6f7687e880307d34fff850d
def generate_images_data(self, images_data): '\n Parse the remote link and extract link to the images and the thumbnails\n :param images_data: Images data dictionary containing the existing metadata of the images and which will be\n updated by this function\n :return updated images data dictionary\n ' webdriver_path = pkg_resources.resource_filename('simplegallery', 'bin/geckodriver') options = Options() options.headless = True spg_common.log(f'Starting Firefox webdriver...') driver = webdriver.Firefox(options=options, executable_path=webdriver_path) spg_common.log(f"Loading album from {self.gallery_config['remote_link']}...") driver.get(self.gallery_config['remote_link']) loading_start = time.time() last_image_count = 0 while True: image_count = len(driver.find_elements_by_xpath('//div[@data-latest-bg]')) if ((image_count > 1) and (image_count == last_image_count)): break last_image_count = image_count if ((time.time() - loading_start) > 30): raise spg_common.SPGException('Loading the page took too long.') time.sleep(5) spg_common.log('Finding photos...') photos = driver.find_elements_by_xpath('//div[@data-latest-bg]') spg_common.log(f'Photos found: {len(photos)}') current_photo = 1 for photo in photos: photo_url = photo.get_attribute('data-latest-bg') (photo_base_url, photo_name) = parse_photo_link(photo_url) spg_common.log(f'{current_photo}/{len(photos)} Processing photo {photo_name}: {photo_url}') current_photo += 1 photo_link_max_size = f'{photo_base_url}=w9999-h9999-no' size = spg_media.get_remote_image_size(photo_link_max_size) thumbnail_size = spg_media.get_thumbnail_size(size, self.gallery_config['thumbnail_height']) images_data[photo_name] = dict(description='', mtime=time.time(), size=size, src=f'{photo_base_url}=w{size[0]}-h{size[1]}-no', thumbnail=f'{photo_base_url}=w{thumbnail_size[0]}-h{thumbnail_size[1]}-no', thumbnail_size=thumbnail_size, type='image') spg_common.log(f'All photos processed!') driver.quit() return images_data
Parse the remote link and extract link to the images and the thumbnails :param images_data: Images data dictionary containing the existing metadata of the images and which will be updated by this function :return updated images data dictionary
simplegallery/logic/variants/google_gallery_logic.py
generate_images_data
kroesche/simple-photo-gallery
94
python
def generate_images_data(self, images_data): '\n Parse the remote link and extract link to the images and the thumbnails\n :param images_data: Images data dictionary containing the existing metadata of the images and which will be\n updated by this function\n :return updated images data dictionary\n ' webdriver_path = pkg_resources.resource_filename('simplegallery', 'bin/geckodriver') options = Options() options.headless = True spg_common.log(f'Starting Firefox webdriver...') driver = webdriver.Firefox(options=options, executable_path=webdriver_path) spg_common.log(f"Loading album from {self.gallery_config['remote_link']}...") driver.get(self.gallery_config['remote_link']) loading_start = time.time() last_image_count = 0 while True: image_count = len(driver.find_elements_by_xpath('//div[@data-latest-bg]')) if ((image_count > 1) and (image_count == last_image_count)): break last_image_count = image_count if ((time.time() - loading_start) > 30): raise spg_common.SPGException('Loading the page took too long.') time.sleep(5) spg_common.log('Finding photos...') photos = driver.find_elements_by_xpath('//div[@data-latest-bg]') spg_common.log(f'Photos found: {len(photos)}') current_photo = 1 for photo in photos: photo_url = photo.get_attribute('data-latest-bg') (photo_base_url, photo_name) = parse_photo_link(photo_url) spg_common.log(f'{current_photo}/{len(photos)} Processing photo {photo_name}: {photo_url}') current_photo += 1 photo_link_max_size = f'{photo_base_url}=w9999-h9999-no' size = spg_media.get_remote_image_size(photo_link_max_size) thumbnail_size = spg_media.get_thumbnail_size(size, self.gallery_config['thumbnail_height']) images_data[photo_name] = dict(description=, mtime=time.time(), size=size, src=f'{photo_base_url}=w{size[0]}-h{size[1]}-no', thumbnail=f'{photo_base_url}=w{thumbnail_size[0]}-h{thumbnail_size[1]}-no', thumbnail_size=thumbnail_size, type='image') spg_common.log(f'All photos processed!') driver.quit() return images_data
def generate_images_data(self, images_data): '\n Parse the remote link and extract link to the images and the thumbnails\n :param images_data: Images data dictionary containing the existing metadata of the images and which will be\n updated by this function\n :return updated images data dictionary\n ' webdriver_path = pkg_resources.resource_filename('simplegallery', 'bin/geckodriver') options = Options() options.headless = True spg_common.log(f'Starting Firefox webdriver...') driver = webdriver.Firefox(options=options, executable_path=webdriver_path) spg_common.log(f"Loading album from {self.gallery_config['remote_link']}...") driver.get(self.gallery_config['remote_link']) loading_start = time.time() last_image_count = 0 while True: image_count = len(driver.find_elements_by_xpath('//div[@data-latest-bg]')) if ((image_count > 1) and (image_count == last_image_count)): break last_image_count = image_count if ((time.time() - loading_start) > 30): raise spg_common.SPGException('Loading the page took too long.') time.sleep(5) spg_common.log('Finding photos...') photos = driver.find_elements_by_xpath('//div[@data-latest-bg]') spg_common.log(f'Photos found: {len(photos)}') current_photo = 1 for photo in photos: photo_url = photo.get_attribute('data-latest-bg') (photo_base_url, photo_name) = parse_photo_link(photo_url) spg_common.log(f'{current_photo}/{len(photos)} Processing photo {photo_name}: {photo_url}') current_photo += 1 photo_link_max_size = f'{photo_base_url}=w9999-h9999-no' size = spg_media.get_remote_image_size(photo_link_max_size) thumbnail_size = spg_media.get_thumbnail_size(size, self.gallery_config['thumbnail_height']) images_data[photo_name] = dict(description=, mtime=time.time(), size=size, src=f'{photo_base_url}=w{size[0]}-h{size[1]}-no', thumbnail=f'{photo_base_url}=w{thumbnail_size[0]}-h{thumbnail_size[1]}-no', thumbnail_size=thumbnail_size, type='image') spg_common.log(f'All photos processed!') driver.quit() return images_data<|docstring|>Parse the remote link and extract link to the images and the thumbnails :param images_data: Images data dictionary containing the existing metadata of the images and which will be updated by this function :return updated images data dictionary<|endoftext|>