_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q8800
not_next
train
def not_next(e): """ Create a PEG function for negative lookahead. """ def match_not_next(s, grm=None, pos=0): try: e(s, grm, pos) except PegreError as ex:
python
{ "resource": "" }
q8801
sequence
train
def sequence(*es): """ Create a PEG function to match a sequence. """ def match_sequence(s, grm=None, pos=0): data = [] start = pos for e in es: s, obj, span = e(s, grm, pos)
python
{ "resource": "" }
q8802
choice
train
def choice(*es): """ Create a PEG function to match an ordered choice. """ msg = 'Expected one of: {}'.format(', '.join(map(repr, es))) def match_choice(s, grm=None, pos=0): errs = [] for e in es: try: return e(s, grm, pos) except PegreError as ex:
python
{ "resource": "" }
q8803
optional
train
def optional(e, default=Ignore): """ Create a PEG function to optionally match an expression. """ def match_optional(s, grm=None, pos=0): try: return e(s, grm, pos) except
python
{ "resource": "" }
q8804
zero_or_more
train
def zero_or_more(e, delimiter=None): """ Create a PEG function to match zero or more expressions. Args: e: the expression to match delimiter: an optional expression to match between the primary *e* matches. """ if delimiter is None: delimiter = lambda s, grm, pos: (s, Ignore, (pos, pos)) def match_zero_or_more(s, grm=None, pos=0): start = pos try: s, obj, span = e(s, grm, pos) pos = span[1] data = [] if obj is Ignore else [obj] except PegreError: return PegreResult(s, [], (pos, pos)) try: while True: s, obj, span = delimiter(s, grm, pos) pos = span[1]
python
{ "resource": "" }
q8805
one_or_more
train
def one_or_more(e, delimiter=None): """ Create a PEG function to match one or more expressions. Args: e: the expression to match delimiter: an optional expression to match between the primary *e* matches. """ if delimiter is None: delimiter = lambda s, grm, pos: (s, Ignore, (pos, pos)) msg = 'Expected one or more of: {}'.format(repr(e)) def match_one_or_more(s, grm=None, pos=0):
python
{ "resource": "" }
q8806
_prepare_axes
train
def _prepare_axes(node, sort_key): """ Sort axes and combine those that point to the same target and go in the same direction. """ links = node.links o_links = node._overlapping_links overlap = {ax2 for ax in links for ax2 in o_links.get(ax, [])}
python
{ "resource": "" }
q8807
_lex
train
def _lex(s): """ Lex the input string according to _tsql_lex_re. Yields (gid, token, line_number) """ s += '.' # make sure there's a terminator to know when to stop parsing lines = enumerate(s.splitlines(), 1) lineno = pos = 0 try: for lineno, line in lines: matches = _tsql_lex_re.finditer(line)
python
{ "resource": "" }
q8808
Bot.get_webhook_info
train
def get_webhook_info(self, ): """ Use this method to get current webhook status. Requires no parameters. On success, returns a WebhookInfo object. If the bot is using getUpdates, will return an object with the url field empty. https://core.telegram.org/bots/api#getwebhookinfo Returns: :return: On success, returns a WebhookInfo object :rtype: pytgbot.api_types.receivable.updates.WebhookInfo """ result = self.do("getWebhookInfo", ) if self.return_python_objects: logger.debug("Trying to parse {data}".format(data=repr(result))) from pytgbot.api_types.receivable.updates import WebhookInfo
python
{ "resource": "" }
q8809
Bot.send_contact
train
def send_contact(self, chat_id, phone_number, first_name, last_name=None, vcard=None, disable_notification=None, reply_to_message_id=None, reply_markup=None): """ Use this method to send phone contacts. On success, the sent Message is returned. https://core.telegram.org/bots/api#sendcontact Parameters: :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername) :type chat_id: int | str|unicode :param phone_number: Contact's phone number :type phone_number: str|unicode :param first_name: Contact's first name :type first_name: str|unicode Optional keyword parameters: :param last_name: Contact's last name :type last_name: str|unicode :param vcard: Additional data about the contact in the form of a vCard, 0-2048 bytes :type vcard: str|unicode :param disable_notification: Sends the message silently. Users will receive a notification with no sound. :type disable_notification: bool :param reply_to_message_id: If the message is a reply, ID of the original message :type reply_to_message_id: int :param reply_markup: Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove keyboard or to force a reply from the user. :type reply_markup: pytgbot.api_types.sendable.reply_markup.InlineKeyboardMarkup | pytgbot.api_types.sendable.reply_markup.ReplyKeyboardMarkup | pytgbot.api_types.sendable.reply_markup.ReplyKeyboardRemove | pytgbot.api_types.sendable.reply_markup.ForceReply Returns: :return: On success, the sent Message is returned :rtype: pytgbot.api_types.receivable.updates.Message """ from pytgbot.api_types.sendable.reply_markup import ForceReply from pytgbot.api_types.sendable.reply_markup import InlineKeyboardMarkup from pytgbot.api_types.sendable.reply_markup import ReplyKeyboardMarkup from pytgbot.api_types.sendable.reply_markup import ReplyKeyboardRemove assert_type_or_raise(chat_id, (int, unicode_type), parameter_name="chat_id")
python
{ "resource": "" }
q8810
Bot.restrict_chat_member
train
def restrict_chat_member(self, chat_id, user_id, until_date=None, can_send_messages=None, can_send_media_messages=None, can_send_other_messages=None, can_add_web_page_previews=None): """ Use this method to restrict a user in a supergroup. The bot must be an administrator in the supergroup for this to work and must have the appropriate admin rights. Pass True for all boolean parameters to lift restrictions from a user. Returns True on success. https://core.telegram.org/bots/api#restrictchatmember Parameters: :param chat_id: Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername) :type chat_id: int | str|unicode :param user_id: Unique identifier of the target user :type user_id: int Optional keyword parameters: :param until_date: Date when restrictions will be lifted for the user, unix time. If user is restricted for more than 366 days or less than 30 seconds from the current time, they are considered to be restricted forever :type until_date: int :param can_send_messages: Pass True, if the user can send text messages, contacts, locations and venues :type can_send_messages: bool :param can_send_media_messages: Pass True, if the user can send audios, documents, photos, videos, video notes and voice notes, implies can_send_messages :type can_send_media_messages:
python
{ "resource": "" }
q8811
Bot.promote_chat_member
train
def promote_chat_member(self, chat_id, user_id, can_change_info=None, can_post_messages=None, can_edit_messages=None, can_delete_messages=None, can_invite_users=None, can_restrict_members=None, can_pin_messages=None, can_promote_members=None): """ Use this method to promote or demote a user in a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Pass False for all boolean parameters to demote a user. Returns True on success. https://core.telegram.org/bots/api#promotechatmember Parameters: :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername) :type chat_id: int | str|unicode :param user_id: Unique identifier of the target user :type user_id: int Optional keyword parameters: :param can_change_info: Pass True, if the administrator can change chat title, photo and other settings :type can_change_info: bool :param can_post_messages: Pass True, if the administrator can create channel posts, channels only :type can_post_messages: bool :param can_edit_messages: Pass True, if the administrator can edit messages of other users and can pin messages, channels only :type can_edit_messages: bool :param can_delete_messages: Pass True, if the administrator can delete messages of other users :type can_delete_messages: bool :param can_invite_users: Pass True, if the administrator can invite new users to the chat :type can_invite_users: bool :param can_restrict_members: Pass True, if the administrator can restrict, ban or unban chat members :type can_restrict_members: bool :param can_pin_messages: Pass True, if the administrator can pin messages, supergroups only :type can_pin_messages: bool :param can_promote_members: Pass True, if the administrator can add new administrators with a subset of his own privileges or demote administrators that he has promoted, directly or indirectly (promoted by administrators that were appointed by him) :type can_promote_members: bool Returns: :return: Returns True on success :rtype: bool """ assert_type_or_raise(chat_id, (int, unicode_type), parameter_name="chat_id") assert_type_or_raise(user_id, int, parameter_name="user_id") assert_type_or_raise(can_change_info, None, bool, parameter_name="can_change_info") assert_type_or_raise(can_post_messages, None, bool, parameter_name="can_post_messages") assert_type_or_raise(can_edit_messages, None, bool, parameter_name="can_edit_messages")
python
{ "resource": "" }
q8812
Bot.set_chat_photo
train
def set_chat_photo(self, chat_id, photo): """ Use this method to set a new profile photo for the chat. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success. Note: In regular groups (non-supergroups), this method will only work if the ‘All Members Are Admins’ setting is off in the target group. https://core.telegram.org/bots/api#setchatphoto Parameters: :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername) :type chat_id: int | str|unicode :param photo: New chat photo, uploaded using multipart/form-data :type photo: pytgbot.api_types.sendable.files.InputFile Returns: :return: Returns True on success :rtype: bool """ from pytgbot.api_types.sendable.files import InputFile assert_type_or_raise(chat_id, (int, unicode_type), parameter_name="chat_id") assert_type_or_raise(photo, InputFile, parameter_name="photo")
python
{ "resource": "" }
q8813
Bot.answer_callback_query
train
def answer_callback_query(self, callback_query_id, text=None, show_alert=None, url=None, cache_time=None): """ Use this method to send answers to callback queries sent from inline keyboards. The answer will be displayed to the user as a notification at the top of the chat screen or as an alert. On success, True is returned. Alternatively, the user can be redirected to the specified Game URL. For this option to work, you must first create a game for your bot via @Botfather and accept the terms. Otherwise, you may use links like t.me/your_bot?start=XXXX that open your bot with a parameter. https://core.telegram.org/bots/api#answercallbackquery Parameters: :param callback_query_id: Unique identifier for the query to be answered :type callback_query_id: str|unicode Optional keyword parameters: :param text: Text of the notification. If not specified, nothing will be shown to the user, 0-200 characters :type text: str|unicode :param show_alert: If true, an alert will be shown by the client instead of a notification at the top of the chat screen. Defaults to false. :type show_alert: bool :param url: URL that will be opened by the user's client. If you have created a Game and accepted the conditions via @Botfather, specify the URL that opens your game – note that this will only work if the query comes from a callback_game button.Otherwise, you may use links like t.me/your_bot?start=XXXX that open your bot with a parameter. :type url: str|unicode :param cache_time: The maximum amount of time in seconds that the result of the callback query may be cached client-side. Telegram apps will support caching starting in version 3.14. Defaults to 0. :type cache_time: int
python
{ "resource": "" }
q8814
Bot.get_sticker_set
train
def get_sticker_set(self, name): """ Use this method to get a sticker set. On success, a StickerSet object is returned. https://core.telegram.org/bots/api#getstickerset Parameters: :param name: Name of the sticker set :type name: str|unicode Returns: :return: On success, a StickerSet object is returned :rtype: pytgbot.api_types.receivable.stickers.StickerSet """ assert_type_or_raise(name, unicode_type, parameter_name="name") result = self.do("getStickerSet", name=name) if self.return_python_objects: logger.debug("Trying to parse {data}".format(data=repr(result))) from pytgbot.api_types.receivable.stickers import StickerSet
python
{ "resource": "" }
q8815
Bot.create_new_sticker_set
train
def create_new_sticker_set(self, user_id, name, title, png_sticker, emojis, contains_masks=None, mask_position=None): """ Use this method to create new sticker set owned by a user. The bot will be able to edit the created sticker set. Returns True on success. https://core.telegram.org/bots/api#createnewstickerset Parameters: :param user_id: User identifier of created sticker set owner :type user_id: int :param name: Short name of sticker set, to be used in t.me/addstickers/ URLs (e.g., animals). Can contain only english letters, digits and underscores. Must begin with a letter, can't contain consecutive underscores and must end in “_by_<bot username>”. <bot_username> is case insensitive. 1-64 characters. :type name: str|unicode :param title: Sticker set title, 1-64 characters :type title: str|unicode :param png_sticker: Png image with the sticker, must be up to 512 kilobytes in size, dimensions must not exceed 512px, and either width or height must be exactly 512px. Pass a file_id as a String to send a file that already exists on the Telegram servers, pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. More info on Sending Files » :type png_sticker: pytgbot.api_types.sendable.files.InputFile | str|unicode :param emojis: One or more emoji corresponding to the sticker :type emojis: str|unicode Optional keyword parameters: :param contains_masks: Pass True, if a set of mask stickers should be created :type contains_masks: bool :param mask_position: A JSON-serialized object for position where the mask should be placed on faces :type mask_position: pytgbot.api_types.receivable.stickers.MaskPosition Returns: :return: Returns True on success :rtype: bool """ from pytgbot.api_types.receivable.stickers import MaskPosition from pytgbot.api_types.sendable.files import InputFile assert_type_or_raise(user_id, int, parameter_name="user_id") assert_type_or_raise(name, unicode_type, parameter_name="name") assert_type_or_raise(title, unicode_type, parameter_name="title")
python
{ "resource": "" }
q8816
Bot.set_sticker_position_in_set
train
def set_sticker_position_in_set(self, sticker, position): """ Use this method to move a sticker in a set created by the bot to a specific position . Returns True on success. https://core.telegram.org/bots/api#setstickerpositioninset Parameters: :param sticker: File identifier of the sticker :type sticker: str|unicode :param position: New sticker position in the set, zero-based :type position: int Returns: :return: Returns True on success :rtype: bool """ assert_type_or_raise(sticker, unicode_type, parameter_name="sticker") assert_type_or_raise(position, int, parameter_name="position") result = self.do("setStickerPositionInSet", sticker=sticker, position=position)
python
{ "resource": "" }
q8817
Bot.answer_shipping_query
train
def answer_shipping_query(self, shipping_query_id, ok, shipping_options=None, error_message=None): """ If you sent an invoice requesting a shipping address and the parameter is_flexible was specified, the Bot API will send an Update with a shipping_query field to the bot. Use this method to reply to shipping queries. On success, True is returned. https://core.telegram.org/bots/api#answershippingquery Parameters: :param shipping_query_id: Unique identifier for the query to be answered :type shipping_query_id: str|unicode :param ok: Specify True if delivery to the specified address is possible and False if there are any problems (for example, if delivery to the specified address is not possible) :type ok: bool Optional keyword parameters: :param shipping_options: Required if ok is True. A JSON-serialized array of available shipping options. :type shipping_options: list of pytgbot.api_types.sendable.payments.ShippingOption :param error_message: Required if ok is False. Error message in human readable form that explains why it is impossible to complete the order (e.g. "Sorry, delivery to your desired address is unavailable'). Telegram will display this message to the user. :type error_message: str|unicode Returns: :return: On success, True is returned :rtype: bool """ from pytgbot.api_types.sendable.payments import ShippingOption
python
{ "resource": "" }
q8818
Bot.send_game
train
def send_game(self, chat_id, game_short_name, disable_notification=None, reply_to_message_id=None, reply_markup=None): """ Use this method to send a game. On success, the sent Message is returned. https://core.telegram.org/bots/api#sendgame Parameters: :param chat_id: Unique identifier for the target chat :type chat_id: int :param game_short_name: Short name of the game, serves as the unique identifier for the game. Set up your games via Botfather. :type game_short_name: str|unicode Optional keyword parameters: :param disable_notification: Sends the message silently. Users will receive a notification with no sound. :type disable_notification: bool :param reply_to_message_id: If the message is a reply, ID of the original message :type reply_to_message_id: int :param reply_markup: A JSON-serialized object for an inline keyboard. If empty, one ‘Play game_title’ button will be shown. If not empty, the first button must launch the game. :type reply_markup: pytgbot.api_types.sendable.reply_markup.InlineKeyboardMarkup Returns: :return: On success, the sent Message is returned :rtype: pytgbot.api_types.receivable.updates.Message """ from pytgbot.api_types.sendable.reply_markup import InlineKeyboardMarkup assert_type_or_raise(chat_id, int, parameter_name="chat_id") assert_type_or_raise(game_short_name, unicode_type, parameter_name="game_short_name") assert_type_or_raise(disable_notification, None, bool, parameter_name="disable_notification")
python
{ "resource": "" }
q8819
Bot.get_download_url
train
def get_download_url(self, file): """ Creates a url to download the file. Note: Contains the secret API key, so you should not share this url! :param file: The File you want to get the url to download. :type file: pytgbot.api_types.receivable.media.File :return: url
python
{ "resource": "" }
q8820
InputMediaVideo.to_array
train
def to_array(self): """ Serializes this InputMediaVideo to a dictionary. :return: dictionary representation of this object. :rtype: dict """ from .files import InputFile array = super(InputMediaVideo, self).to_array() # 'type' given by superclass # 'media' given by superclass if self.thumb is not None: if isinstance(self.thumb, InputFile): array['thumb'] = None # type InputFile elif isinstance(self.thumb, str):
python
{ "resource": "" }
q8821
InputMediaDocument.from_array
train
def from_array(array): """ Deserialize a new InputMediaDocument from a given dictionary. :return: new InputMediaDocument instance. :rtype: InputMediaDocument """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") from pytgbot.api_types.sendable.files import InputFile data = {} # 'type' is given by class type data['media'] = u(array.get('media')) if array.get('thumb') is None: data['thumb'] = None elif isinstance(array.get('thumb'), InputFile): data['thumb'] = None # will be filled later by get_request_data() elif isinstance(array.get('thumb'), str):
python
{ "resource": "" }
q8822
REPP.from_config
train
def from_config(cls, path, directory=None): """ Instantiate a REPP from a PET-style `.set` configuration file. The *path* parameter points to the configuration file. Submodules are loaded from *directory*. If *directory* is not given, it is the directory part of *path*. Args: path (str): the path to the REPP configuration file directory (str, optional): the directory in which to search for submodules """ if not exists(path): raise REPPError('REPP config file not found: {}'.format(path)) confdir = dirname(path) # TODO: can TDL parsing be repurposed for this variant? conf = io.open(path, encoding='utf-8').read() conf = re.sub(r';.*', '', conf).replace('\n',' ') m = re.search( r'repp-modules\s*:=\s*((?:[-\w]+\s+)*[-\w]+)\s*\.', conf) t = re.search( r'repp-tokenizer\s*:=\s*([-\w]+)\s*\.', conf) a = re.search( r'repp-calls\s*:=\s*((?:[-\w]+\s+)*[-\w]+)\s*\.', conf) f = re.search( r'format\s*:=\s*(\w+)\s*\.', conf) d = re.search( r'repp-directory\s*:=\s*(.*)\.\s*$', conf) if m is None: raise REPPError('repp-modules option must be set') if t is None: raise REPPError('repp-tokenizer
python
{ "resource": "" }
q8823
REPP.from_file
train
def from_file(cls, path, directory=None, modules=None, active=None): """ Instantiate a REPP from a `.rpp` file. The *path* parameter points to the top-level module. Submodules are loaded from *directory*. If *directory* is not given, it is the directory part of *path*. A REPP module may utilize external submodules, which may be defined in two ways. The first method is to map a module name to an instantiated REPP instance in *modules*. The second method assumes that an external group call `>abc` corresponds to a file `abc.rpp` in *directory* and loads that file. The
python
{ "resource": "" }
q8824
REPP.from_string
train
def from_string(cls, s, name=None, modules=None, active=None): """ Instantiate a REPP from a string. Args: name (str, optional): the name of the REPP module modules (dict, optional): a mapping from identifiers to REPP modules
python
{ "resource": "" }
q8825
TextMessage.to_array
train
def to_array(self): """ Serializes this TextMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(TextMessage, self).to_array() array['text'] = u(self.text) # py2: type unicode, py3: type str if self.receiver is not None: if isinstance(self.receiver, None): array['chat_id'] = None(self.receiver) # type Noneelif isinstance(self.receiver, str): array['chat_id'] = u(self.receiver) # py2: type unicode, py3: type str elif isinstance(self.receiver, int): array['chat_id'] = int(self.receiver) # type intelse: raise TypeError('Unknown type, must be one of None, str, int.') # end if if self.reply_id is not None: if isinstance(self.reply_id, DEFAULT_MESSAGE_ID): array['reply_to_message_id'] = DEFAULT_MESSAGE_ID(self.reply_id) # type DEFAULT_MESSAGE_IDelif isinstance(self.reply_id, int): array['reply_to_message_id'] = int(self.reply_id) # type intelse: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int.') # end if if self.parse_mode is not None: array['parse_mode'] = u(self.parse_mode) # py2: type unicode, py3: type str if self.disable_web_page_preview is not None: array['disable_web_page_preview'] = bool(self.disable_web_page_preview) # type bool if self.disable_notification is not
python
{ "resource": "" }
q8826
AudioMessage.to_array
train
def to_array(self): """ Serializes this AudioMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(AudioMessage, self).to_array() if isinstance(self.audio, InputFile): array['audio'] = self.audio.to_array() # type InputFile elif isinstance(self.audio, str): array['audio'] = u(self.audio) # py2: type unicode, py3: type str else: raise TypeError('Unknown type, must be one of InputFile, str.') # end if if self.receiver is not None: if isinstance(self.receiver, None): array['chat_id'] = None(self.receiver) # type Noneelif isinstance(self.receiver, str): array['chat_id'] = u(self.receiver) # py2: type unicode, py3: type str elif isinstance(self.receiver, int): array['chat_id'] = int(self.receiver) # type intelse: raise TypeError('Unknown type, must be one of None, str, int.') # end if if self.reply_id is not None: if isinstance(self.reply_id, DEFAULT_MESSAGE_ID): array['reply_to_message_id'] = DEFAULT_MESSAGE_ID(self.reply_id) # type DEFAULT_MESSAGE_IDelif isinstance(self.reply_id, int): array['reply_to_message_id'] = int(self.reply_id) # type intelse: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int.') # end if if self.caption is not None: array['caption'] = u(self.caption) # py2: type unicode, py3: type str if self.parse_mode is not None: array['parse_mode'] = u(self.parse_mode) # py2: type unicode, py3: type str if self.duration is not None: array['duration'] = int(self.duration) # type int if self.performer is not None: array['performer'] = u(self.performer) # py2: type unicode, py3: type str if self.title is not None: array['title'] = u(self.title) # py2: type unicode, py3: type str if self.thumb is not None: if isinstance(self.thumb, InputFile): array['thumb'] = self.thumb.to_array() # type InputFile elif isinstance(self.thumb, str): array['thumb'] = u(self.thumb)
python
{ "resource": "" }
q8827
AnimationMessage.to_array
train
def to_array(self): """ Serializes this AnimationMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(AnimationMessage, self).to_array() if isinstance(self.animation, InputFile): array['animation'] = self.animation.to_array() # type InputFile elif isinstance(self.animation, str): array['animation'] = u(self.animation) # py2: type unicode, py3: type str else: raise TypeError('Unknown type, must be one of InputFile, str.') # end if if self.receiver is not None: if isinstance(self.receiver, None): array['chat_id'] = None(self.receiver) # type Noneelif isinstance(self.receiver, str): array['chat_id'] = u(self.receiver) # py2: type unicode, py3: type str elif isinstance(self.receiver, int): array['chat_id'] = int(self.receiver) # type intelse: raise TypeError('Unknown type, must be one of None, str, int.') # end if if self.reply_id is not None: if isinstance(self.reply_id, DEFAULT_MESSAGE_ID): array['reply_to_message_id'] = DEFAULT_MESSAGE_ID(self.reply_id) # type DEFAULT_MESSAGE_IDelif isinstance(self.reply_id, int): array['reply_to_message_id'] = int(self.reply_id) # type intelse: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int.') # end if if self.duration is not None: array['duration'] = int(self.duration) # type int if self.width is not None: array['width'] = int(self.width) # type int if self.height is not None: array['height'] = int(self.height) # type int if self.thumb is not None: if isinstance(self.thumb, InputFile): array['thumb'] = self.thumb.to_array() # type InputFile elif isinstance(self.thumb, str): array['thumb'] = u(self.thumb) # py2: type unicode, py3: type str else: raise TypeError('Unknown type, must be one of InputFile, str.') # end if
python
{ "resource": "" }
q8828
VoiceMessage.to_array
train
def to_array(self): """ Serializes this VoiceMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(VoiceMessage, self).to_array() if isinstance(self.voice, InputFile): array['voice'] = self.voice.to_array() # type InputFile elif isinstance(self.voice, str): array['voice'] = u(self.voice) # py2: type unicode, py3: type str else: raise TypeError('Unknown type, must be one of InputFile, str.') # end if if self.receiver is not None: if isinstance(self.receiver, None): array['chat_id'] = None(self.receiver) # type Noneelif isinstance(self.receiver, str): array['chat_id'] = u(self.receiver) # py2: type unicode, py3: type str elif isinstance(self.receiver, int): array['chat_id'] = int(self.receiver) # type intelse: raise TypeError('Unknown type, must be one of None, str, int.') # end if if self.reply_id is not None: if isinstance(self.reply_id, DEFAULT_MESSAGE_ID): array['reply_to_message_id'] = DEFAULT_MESSAGE_ID(self.reply_id) # type DEFAULT_MESSAGE_IDelif isinstance(self.reply_id, int): array['reply_to_message_id'] = int(self.reply_id) # type intelse: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int.') # end if if self.caption is not None: array['caption'] = u(self.caption) # py2: type unicode, py3: type str if self.parse_mode is not None:
python
{ "resource": "" }
q8829
VideoNoteMessage.to_array
train
def to_array(self): """ Serializes this VideoNoteMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(VideoNoteMessage, self).to_array() if isinstance(self.video_note, InputFile): array['video_note'] = self.video_note.to_array() # type InputFile elif isinstance(self.video_note, str): array['video_note'] = u(self.video_note) # py2: type unicode, py3: type str else: raise TypeError('Unknown type, must be one of InputFile, str.') # end if if self.receiver is not None: if isinstance(self.receiver, None): array['chat_id'] = None(self.receiver) # type Noneelif isinstance(self.receiver, str): array['chat_id'] = u(self.receiver) # py2: type unicode, py3: type str elif isinstance(self.receiver, int): array['chat_id'] = int(self.receiver) # type intelse: raise TypeError('Unknown type, must be one of None, str, int.') # end if if self.reply_id is not None: if isinstance(self.reply_id, DEFAULT_MESSAGE_ID): array['reply_to_message_id'] = DEFAULT_MESSAGE_ID(self.reply_id) # type DEFAULT_MESSAGE_IDelif isinstance(self.reply_id, int): array['reply_to_message_id'] = int(self.reply_id) # type intelse: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int.') # end if if self.duration is not None: array['duration'] = int(self.duration) # type int if self.length is not None: array['length'] = int(self.length) # type int if self.thumb is not None: if isinstance(self.thumb, InputFile): array['thumb'] = self.thumb.to_array() # type InputFile elif isinstance(self.thumb, str): array['thumb'] = u(self.thumb) # py2: type unicode, py3: type str else: raise TypeError('Unknown type, must be one of InputFile, str.') # end if if self.disable_notification is
python
{ "resource": "" }
q8830
MediaGroupMessage.to_array
train
def to_array(self): """ Serializes this MediaGroupMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(MediaGroupMessage, self).to_array() if isinstance(self.media, InputMediaPhoto): array['media'] = self._as_array(self.media) # type list of InputMediaPhoto | list of InputMediaVideo elif isinstance(self.media, InputMediaVideo): array['media'] = self._as_array(self.media) # type list of InputMediaPhoto | list of InputMediaVideo else: raise TypeError('Unknown type, must be one of InputMediaPhoto, InputMediaVideo.') # end if if self.receiver is not None: if isinstance(self.receiver, None): array['chat_id'] = None(self.receiver) # type Noneelif isinstance(self.receiver, str): array['chat_id'] = u(self.receiver) # py2: type unicode, py3: type str elif isinstance(self.receiver, int): array['chat_id'] = int(self.receiver) # type intelse: raise TypeError('Unknown type, must be one of None, str, int.')
python
{ "resource": "" }
q8831
MediaGroupMessage.from_array
train
def from_array(array): """ Deserialize a new MediaGroupMessage from a given dictionary. :return: new MediaGroupMessage instance. :rtype: MediaGroupMessage """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") from pytgbot.api_types.sendable.input_media import InputMediaPhoto from pytgbot.api_types.sendable.input_media import InputMediaVideo data = {} if isinstance(array.get('media'), InputMediaPhoto): data['media'] = InputMediaPhoto.from_array_list(array.get('media'), list_level=1) elif isinstance(array.get('media'), InputMediaVideo): data['media'] = InputMediaVideo.from_array_list(array.get('media'), list_level=1) else: raise TypeError('Unknown type, must be one of InputMediaPhoto, InputMediaVideo.') # end if if array.get('chat_id') is None: data['receiver'] = None elif isinstance(array.get('chat_id'), None): data['receiver'] = None(array.get('chat_id')) elif isinstance(array.get('chat_id'), str): data['receiver'] = u(array.get('chat_id')) elif isinstance(array.get('chat_id'), int): data['receiver'] = int(array.get('chat_id')) else: raise TypeError('Unknown
python
{ "resource": "" }
q8832
LocationMessage.to_array
train
def to_array(self): """ Serializes this LocationMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(LocationMessage, self).to_array() array['latitude'] = float(self.latitude) # type float array['longitude'] = float(self.longitude) # type float if self.receiver is not None: if isinstance(self.receiver, None): array['chat_id'] = None(self.receiver) # type Noneelif isinstance(self.receiver, str): array['chat_id'] = u(self.receiver) # py2: type unicode, py3: type str elif isinstance(self.receiver, int): array['chat_id'] = int(self.receiver) # type intelse: raise TypeError('Unknown type, must be one of None, str, int.') # end if if self.reply_id is not None: if isinstance(self.reply_id, DEFAULT_MESSAGE_ID): array['reply_to_message_id'] = DEFAULT_MESSAGE_ID(self.reply_id) # type DEFAULT_MESSAGE_IDelif isinstance(self.reply_id, int): array['reply_to_message_id'] = int(self.reply_id) # type intelse: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int.') # end if if self.live_period is not None: array['live_period'] = int(self.live_period) # type int if self.disable_notification is not None: array['disable_notification'] = bool(self.disable_notification) # type bool
python
{ "resource": "" }
q8833
VenueMessage.to_array
train
def to_array(self): """ Serializes this VenueMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(VenueMessage, self).to_array() array['latitude'] = float(self.latitude) # type float array['longitude'] = float(self.longitude) # type float array['title'] = u(self.title) # py2: type unicode, py3: type str array['address'] = u(self.address) # py2: type unicode, py3: type str if self.receiver is not None: if isinstance(self.receiver, None): array['chat_id'] = None(self.receiver) # type Noneelif isinstance(self.receiver, str): array['chat_id'] = u(self.receiver) # py2: type unicode, py3: type str elif isinstance(self.receiver, int): array['chat_id'] = int(self.receiver) # type intelse: raise TypeError('Unknown type, must be one of None, str, int.') # end if if self.reply_id is not None: if isinstance(self.reply_id, DEFAULT_MESSAGE_ID): array['reply_to_message_id'] = DEFAULT_MESSAGE_ID(self.reply_id) # type DEFAULT_MESSAGE_IDelif isinstance(self.reply_id, int): array['reply_to_message_id'] = int(self.reply_id) # type intelse: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int.') # end if if self.foursquare_id is not None: array['foursquare_id'] = u(self.foursquare_id) # py2: type unicode, py3: type str if self.foursquare_type is not None:
python
{ "resource": "" }
q8834
ContactMessage.to_array
train
def to_array(self): """ Serializes this ContactMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(ContactMessage, self).to_array() array['phone_number'] = u(self.phone_number) # py2: type unicode, py3: type str array['first_name'] = u(self.first_name) # py2: type unicode, py3: type str if self.receiver is not None: if isinstance(self.receiver, None): array['chat_id'] = None(self.receiver) # type Noneelif isinstance(self.receiver, str): array['chat_id'] = u(self.receiver) # py2: type unicode, py3: type str elif isinstance(self.receiver, int): array['chat_id'] = int(self.receiver) # type intelse: raise TypeError('Unknown type, must be one of None, str, int.') # end if if self.reply_id is not None: if isinstance(self.reply_id, DEFAULT_MESSAGE_ID): array['reply_to_message_id'] = DEFAULT_MESSAGE_ID(self.reply_id) # type DEFAULT_MESSAGE_IDelif isinstance(self.reply_id, int): array['reply_to_message_id'] = int(self.reply_id) # type intelse: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int.') # end if if self.last_name is not None: array['last_name'] = u(self.last_name) # py2: type unicode, py3: type str if self.vcard is not None: array['vcard'] = u(self.vcard) # py2: type unicode, py3: type str
python
{ "resource": "" }
q8835
ChatActionMessage.to_array
train
def to_array(self): """ Serializes this ChatActionMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(ChatActionMessage, self).to_array() array['action'] = u(self.action) # py2: type unicode, py3: type str if self.receiver is not None:
python
{ "resource": "" }
q8836
ChatActionMessage.from_array
train
def from_array(array): """ Deserialize a new ChatActionMessage from a given dictionary. :return: new ChatActionMessage instance. :rtype: ChatActionMessage """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") data = {} data['action'] = u(array.get('action')) if array.get('chat_id') is None: data['receiver'] = None elif isinstance(array.get('chat_id'), None): data['receiver'] = None(array.get('chat_id')) elif isinstance(array.get('chat_id'), str):
python
{ "resource": "" }
q8837
StickerMessage.to_array
train
def to_array(self): """ Serializes this StickerMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(StickerMessage, self).to_array() if isinstance(self.sticker, InputFile): array['sticker'] = self.sticker.to_array() # type InputFile elif isinstance(self.sticker, str): array['sticker'] = u(self.sticker) # py2: type unicode, py3: type str else: raise TypeError('Unknown type, must be one of InputFile, str.') # end if if self.receiver is not None: if isinstance(self.receiver, None): array['chat_id'] = None(self.receiver) # type Noneelif isinstance(self.receiver, str): array['chat_id'] = u(self.receiver) # py2: type unicode, py3: type str elif isinstance(self.receiver, int): array['chat_id'] = int(self.receiver) # type intelse: raise TypeError('Unknown type, must be one of None, str, int.') # end if if self.reply_id is not None: if isinstance(self.reply_id, DEFAULT_MESSAGE_ID): array['reply_to_message_id'] = DEFAULT_MESSAGE_ID(self.reply_id) # type DEFAULT_MESSAGE_IDelif isinstance(self.reply_id, int): array['reply_to_message_id'] = int(self.reply_id) # type intelse: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int.') # end if
python
{ "resource": "" }
q8838
InvoiceMessage.to_array
train
def to_array(self): """ Serializes this InvoiceMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(InvoiceMessage, self).to_array() array['title'] = u(self.title) # py2: type unicode, py3: type str array['description'] = u(self.description) # py2: type unicode, py3: type str array['payload'] = u(self.payload) # py2: type unicode, py3: type str array['provider_token'] = u(self.provider_token) # py2: type unicode, py3: type str array['start_parameter'] = u(self.start_parameter) # py2: type unicode, py3: type str array['currency'] = u(self.currency) # py2: type unicode, py3: type str array['prices'] = self._as_array(self.prices) # type list of LabeledPrice if self.receiver is not None: if isinstance(self.receiver, None): array['chat_id'] = None(self.receiver) # type Noneelif isinstance(self.receiver, str): array['chat_id'] = u(self.receiver) # py2: type unicode, py3: type str elif isinstance(self.receiver, int): array['chat_id'] = int(self.receiver) # type intelse: raise TypeError('Unknown type, must be one of None, str, int.') # end if if self.reply_id is not None: if isinstance(self.reply_id, DEFAULT_MESSAGE_ID): array['reply_to_message_id'] = DEFAULT_MESSAGE_ID(self.reply_id) # type DEFAULT_MESSAGE_IDelif isinstance(self.reply_id, int): array['reply_to_message_id'] = int(self.reply_id) # type intelse: raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int.') # end if if self.provider_data is not None: array['provider_data'] = u(self.provider_data) # py2: type unicode, py3: type str if self.photo_url is not None: array['photo_url'] = u(self.photo_url) # py2: type unicode, py3: type str if self.photo_size is not None: array['photo_size'] = int(self.photo_size) # type int if self.photo_width is not None: array['photo_width'] = int(self.photo_width) # type int if self.photo_height is not None: array['photo_height'] = int(self.photo_height) # type int if self.need_name is not None: array['need_name'] = bool(self.need_name) # type bool
python
{ "resource": "" }
q8839
GameMessage.to_array
train
def to_array(self): """ Serializes this GameMessage to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(GameMessage, self).to_array() array['game_short_name'] = u(self.game_short_name) # py2: type unicode, py3: type str if self.receiver is not None: if isinstance(self.receiver, None): array['chat_id'] = None(self.receiver) # type Noneelif isinstance(self.receiver, str): array['chat_id'] = u(self.receiver) # py2: type unicode, py3: type str elif isinstance(self.receiver, int):
python
{ "resource": "" }
q8840
GameMessage.from_array
train
def from_array(array): """ Deserialize a new GameMessage from a given dictionary. :return: new GameMessage instance. :rtype: GameMessage """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") from pytgbot.api_types.sendable.reply_markup import InlineKeyboardMarkup data = {} data['game_short_name'] = u(array.get('game_short_name')) if array.get('chat_id') is None: data['receiver'] = None elif isinstance(array.get('chat_id'), None): data['receiver'] = None(array.get('chat_id')) elif isinstance(array.get('chat_id'), str): data['receiver'] = u(array.get('chat_id')) elif isinstance(array.get('chat_id'), int): data['receiver'] = int(array.get('chat_id')) else: raise TypeError('Unknown type, must be one of None, str, int or None.') # end if if array.get('reply_to_message_id') is None: data['reply_id'] = None elif isinstance(array.get('reply_to_message_id'), DEFAULT_MESSAGE_ID): data['reply_id'] = DEFAULT_MESSAGE_ID(array.get('reply_to_message_id'))
python
{ "resource": "" }
q8841
find_subgraphs_by_preds
train
def find_subgraphs_by_preds(xmrs, preds, connected=None): """ Yield subgraphs matching a list of predicates. Predicates may match multiple EPs/nodes in the *xmrs*, meaning that more than one subgraph is possible. Also, predicates in *preds* match in number, so if a predicate appears twice in *preds*, there will be two matching EPs/nodes in each subgraph. Args: xmrs (:class:`~delphin.mrs.xmrs.Xmrs`): semantic structure to use preds: iterable of predicates to include in subgraphs connected (bool, optional): if `True`, all yielded subgraphs must be connected, as determined by :meth:`Xmrs.is_connected() <delphin.mrs.xmrs.Xmrs.is_connected>`. Yields: A :class:`~delphin.mrs.xmrs.Xmrs` object for each subgraphs found. """
python
{ "resource": "" }
q8842
in_labelset
train
def in_labelset(xmrs, nodeids, label=None): """ Test if all nodeids share a label. Args: nodeids: iterable of nodeids label (str, optional): the label that all nodeids must share Returns: bool: `True` if all nodeids share a label, otherwise `False` """
python
{ "resource": "" }
q8843
InputFile.factory
train
def factory( cls, file_id=None, path=None, url=None, blob=None, mime=None, prefer_local_download=True, prefer_str=False, create_instance=True ): """ Creates a new InputFile subclass instance fitting the given parameters. :param prefer_local_download: If `True`, we download the file and send it to telegram. This is the default. If `False`, we send Telegram just the URL, and they'll try to download it. :type prefer_local_download: bool :param prefer_str: Return just the `str` instead of a `InputFileUseFileID` or `InputFileUseUrl` object. :type prefer_str: bool :param create_instance: If we should return a instance ready to use (default), or the building parts being a tuple of `(class, args_tuple, kwargs_dict)`. Setting this to `False` is probably only ever required for internal usage by the :class:`InputFile` constructor which uses this very factory. :type create_instance: bool :returns: if `create_instance=True` it returns a instance of some InputFile subclass or a string, if `create_instance=False` it returns a tuple of the needed class, args and kwargs needed to create a instance. :rtype: InputFile|InputFileFromBlob|InputFileFromDisk|InputFileFromURL|str|tuple """ if create_instance: clazz, args, kwargs = cls.factory( file_id=file_id, path=path, url=url, blob=blob, mime=mime, create_instance=False, ) return clazz(*args, **kwargs) if file_id: if prefer_str: assert_type_or_raise(file_id, str, parameter_name='file_id') return str, (file_id,), dict() # end if return InputFileUseFileID, (file_id,), dict() if blob: name = "file" suffix = ".blob" if path:
python
{ "resource": "" }
q8844
PassportData.to_array
train
def to_array(self): """ Serializes this PassportData to a dictionary. :return: dictionary representation of this object. :rtype: dict
python
{ "resource": "" }
q8845
PassportFile.to_array
train
def to_array(self): """ Serializes this PassportFile to a dictionary. :return: dictionary representation of this object. :rtype: dict """
python
{ "resource": "" }
q8846
EncryptedPassportElement.to_array
train
def to_array(self): """ Serializes this EncryptedPassportElement to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(EncryptedPassportElement, self).to_array() array['type'] = u(self.type) # py2: type unicode, py3: type str array['hash'] = u(self.hash) # py2: type unicode, py3: type str if self.data is not None: array['data'] = u(self.data) # py2: type unicode, py3: type str if self.phone_number is not None: array['phone_number'] = u(self.phone_number) # py2: type unicode, py3: type str if self.email is not None: array['email'] = u(self.email) # py2: type unicode, py3: type str if self.files is not None:
python
{ "resource": "" }
q8847
EncryptedCredentials.to_array
train
def to_array(self): """ Serializes this EncryptedCredentials to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(EncryptedCredentials,
python
{ "resource": "" }
q8848
EncryptedCredentials.from_array
train
def from_array(array): """ Deserialize a new EncryptedCredentials from a given dictionary. :return: new EncryptedCredentials instance. :rtype: EncryptedCredentials """ if array is None or not array: return None # end if
python
{ "resource": "" }
q8849
Bot.get_updates
train
def get_updates(self, offset=None, limit=100, poll_timeout=0, allowed_updates=None, request_timeout=None, delta=timedelta(milliseconds=100), error_as_empty=False): """ Use this method to receive incoming updates using long polling. An Array of Update objects is returned. You can choose to set `error_as_empty` to `True` or `False`. If `error_as_empty` is set to `True`, it will log that exception as warning, and fake an empty result, intended for use in for loops. In case of such error (and only in such case) it contains an "exception" field. Ìt will look like this: `{"result": [], "exception": e}` This is useful if you want to use a for loop, but ignore Network related burps. If `error_as_empty` is set to `False` however, all `requests.RequestException` exceptions are normally raised. :keyword offset: (Optional) Identifier of the first update to be returned. Must be greater by one than the highest among the identifiers of previously received updates. By default, updates starting with the earliest unconfirmed update are returned. An update is considered confirmed as soon as :func:`get_updates` is called with an offset higher than its `update_id`. :type offset: int :param limit: Limits the number of updates to be retrieved. Values between 1—100 are accepted. Defaults to 100 :type limit: int :param poll_timeout: Timeout in seconds for long polling, e.g. how long we want to wait maximum. Defaults to 0, i.e. usual short polling. :type poll_timeout: int :param allowed_updates: List the types of updates you want your bot to receive. For example, specify [“message”, “edited_channel_post”, “callback_query”] to only receive updates of these types. See Update for a complete list of available update types. Specify an empty list to receive all updates regardless of type (default). If not specified, the previous setting will be used. Please note that this parameter doesn't affect updates created before the call to the get_updates,
python
{ "resource": "" }
q8850
Bot.set_game_score
train
def set_game_score(self, user_id, score, force=False, disable_edit_message=False, chat_id=None, message_id=None, inline_message_id=None): """ Use this method to set the score of the specified user in a game. On success, if the message was sent by the bot, returns the edited Message, otherwise returns True. Returns an error, if the new score is not greater than the user's current score in the chat and force is False. https://core.telegram.org/bots/api#setgamescore Parameters: :param user_id: User identifier :type user_id: int :param score: New score, must be non-negative :type score: int Optional keyword parameters: :param force: Pass True, if the high score is allowed to decrease. This can be useful when fixing mistakes or banning cheaters :type force: bool :param disable_edit_message: Pass True, if the game message should not be automatically edited to include the current scoreboard :type disable_edit_message: bool :param chat_id: Required if inline_message_id is not specified. Unique identifier for the target chat (or username of the target channel in the format @channelusername) :type chat_id: int :param message_id: Required if inline_message_id is not specified. Identifier of the sent message :type message_id: int :param inline_message_id: Required if chat_id and message_id are not specified. Identifier of the inline message :type inline_message_id: str|unicode Returns: :return: On success, if the message was sent by the bot, returns the edited Message, otherwise returns True :rtype: pytgbot.api_types.receivable.updates.Message | bool """ assert_type_or_raise(user_id, int, parameter_name="user_id") assert_type_or_raise(score, int, parameter_name="score")
python
{ "resource": "" }
q8851
LabeledPrice.to_array
train
def to_array(self): """ Serializes this LabeledPrice to a dictionary. :return: dictionary representation of this object. :rtype: dict
python
{ "resource": "" }
q8852
LabeledPrice.from_array
train
def from_array(array): """ Deserialize a new LabeledPrice from a given dictionary. :return: new LabeledPrice instance. :rtype: LabeledPrice """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array")
python
{ "resource": "" }
q8853
ShippingOption.to_array
train
def to_array(self): """ Serializes this ShippingOption to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(ShippingOption,
python
{ "resource": "" }
q8854
_prepare_target
train
def _prepare_target(ts, tables, buffer_size): """Clear tables affected by the processing.""" for tablename in tables:
python
{ "resource": "" }
q8855
_prepare_source
train
def _prepare_source(selector, source): """Normalize source rows and selectors.""" tablename, fields = get_data_specifier(selector) if len(fields) != 1: raise ItsdbError( 'Selector must specify exactly one data column: {}' .format(selector) ) if isinstance(source, TestSuite):
python
{ "resource": "" }
q8856
_add_record
train
def _add_record(table, data, buffer_size): """ Prepare and append a Record into its Table; flush to disk if necessary. """ fields = table.fields # remove any keys that aren't relation fields for invalid_key in set(data).difference([f.name for f in fields]): del data[invalid_key] table.append(Record.from_dict(fields, data)) # write if requested and possible if buffer_size is
python
{ "resource": "" }
q8857
decode_row
train
def decode_row(line, fields=None): """ Decode a raw line from a profile into a list of column values. Decoding involves splitting the line by the field delimiter (`"@"` by default) and unescaping special characters. If *fields* is given, cast the values into the datatype given by their respective Field object. Args: line: a raw line from a [incr tsdb()] profile. fields: a list or Relation object of Fields for the row Returns: A list of column values. """ cols = line.rstrip('\n').split(_field_delimiter) cols = list(map(unescape, cols)) if fields is not None: if len(cols) != len(fields):
python
{ "resource": "" }
q8858
_table_filename
train
def _table_filename(tbl_filename): """ Determine if the table path should end in .gz or not and return it. A .gz path is preferred only if it exists and is newer than any regular text file path. Raises: :class:`delphin.exceptions.ItsdbError`: when neither the .gz nor text file exist. """ tbl_filename = str(tbl_filename) # convert any
python
{ "resource": "" }
q8859
_open_table
train
def _open_table(tbl_filename, encoding): """ Transparently open the compressed or text table file. Can be used as a context manager in a 'with' statement. """ path = _table_filename(tbl_filename) if path.endswith('.gz'): # gzip.open() cannot use mode='rt' until Python2.7 support # is gone; until then use TextIOWrapper
python
{ "resource": "" }
q8860
select_rows
train
def select_rows(cols, rows, mode='list', cast=True): """ Yield data selected from rows. It is sometimes useful to select a subset of data from a profile. This function selects the data in *cols* from *rows* and yields it in a form specified by *mode*. Possible values of *mode* are: ================== ================= ========================== mode description example `['i-id', 'i-wf']` ================== ================= ========================== `'list'` (default) a list of values `[10, 1]` `'dict'` col to value map `{'i-id': 10,'i-wf': 1}` `'row'` [incr tsdb()] row `'10@1'` ================== ================= ========================== Args: cols: an iterable of column names to select data for rows: the rows to select column data from mode: the form yielded data should take cast: if `True`, cast column values to their datatype (requires *rows* to be :class:`Record` objects) Yields: Selected data in the form specified by *mode*. """ mode = mode.lower() if mode == 'list': modecast =
python
{ "resource": "" }
q8861
join
train
def join(table1, table2, on=None, how='inner', name=None): """ Join two tables and return the resulting Table object. Fields in the resulting table have their names prefixed with their corresponding table name. For example, when joining `item` and `parse` tables, the `i-input` field of the `item` table will be named `item:i-input` in the resulting Table. Pivot fields (those in *on*) are only stored once without the prefix. Both inner and left joins are possible by setting the *how* parameter to `inner` and `left`, respectively. .. warning:: Both *table2* and the resulting joined table will exist in memory for this operation, so it is not recommended for very large tables on low-memory systems. Args: table1 (:class:`Table`): the left table to join table2 (:class:`Table`): the right table to join on (str): the shared key to use for joining; if `None`, find shared keys using the schemata of the tables how (str): the method used for joining (`"inner"` or `"left"`) name (str): the name assigned to the resulting table """ if how not in ('inner', 'left'): ItsdbError('Only \'inner\' and \'left\' join methods are allowed.') # validate and normalize the pivot on = _join_pivot(on, table1, table2) # the fields of the joined table fields
python
{ "resource": "" }
q8862
default_value
train
def default_value(fieldname, datatype): """ Return the default value for a column. If the column name (e.g. *i-wf*) is defined to have an idiosyncratic value, that value is returned. Otherwise the default value for the column's datatype is returned. Args: fieldname: the column name (e.g. `i-wf`) datatype: the datatype of the column (e.g.
python
{ "resource": "" }
q8863
filter_rows
train
def filter_rows(filters, rows): """ Yield rows matching all applicable filters. Filter functions have binary arity (e.g. `filter(row, col)`) where the first parameter is the dictionary of row data, and the second parameter is the data at one particular column. Args: filters: a tuple of (cols, filter_func) where filter_func will be tested (filter_func(row, col)) for each col in cols where col exists in the row rows: an iterable of rows to filter Yields: Rows matching
python
{ "resource": "" }
q8864
apply_rows
train
def apply_rows(applicators, rows): """ Yield rows after applying the applicator functions to them. Applicators are simple unary functions that return a value, and that value is stored in the yielded row. E.g. `row[col] = applicator(row[col])`. These are useful to, e.g., cast strings to numeric datatypes, to convert formats stored in a cell, extract features for machine learning, and so on. Args: applicators: a tuple of (cols, applicator) where the applicator will be applied to each col in cols rows: an iterable of rows for applicators to be called on Yields:
python
{ "resource": "" }
q8865
Field.default_value
train
def default_value(self): """Get the default value of the field.""" if self.name in tsdb_coded_attributes: return tsdb_coded_attributes[self.name]
python
{ "resource": "" }
q8866
Relation.keys
train
def keys(self): """Return the tuple of field names of key fields.""" keys = self._keys if keys is None:
python
{ "resource": "" }
q8867
Relations.from_file
train
def from_file(cls, source): """Instantiate Relations from a relations file.""" if hasattr(source, 'read'): relations = cls.from_string(source.read()) else:
python
{ "resource": "" }
q8868
Relations.from_string
train
def from_string(cls, s): """Instantiate Relations from a relations string.""" tables = [] seen = set() current_table = None lines = list(reversed(s.splitlines())) # to pop() in right order while lines: line = lines.pop().strip() table_m = re.match(r'^(?P<table>\w.+):$', line) field_m = re.match(r'\s*(?P<name>\S+)' r'(\s+(?P<attrs>[^#]+))?' r'(\s*#\s*(?P<comment>.*)$)?', line) if table_m is not None: table_name = table_m.group('table') if table_name in seen: raise ItsdbError( 'Table {} already defined.'.format(table_name) ) current_table = (table_name, []) tables.append(current_table)
python
{ "resource": "" }
q8869
Relations.path
train
def path(self, source, target): """ Find the path of id fields connecting two tables. This is just a basic breadth-first-search. The relations file should be small enough to not be a problem. Returns: list: (table, fieldname) pairs describing the path from the source to target tables Raises: :class:`delphin.exceptions.ItsdbError`: when no path is found Example: >>> relations.path('item', 'result') [('parse', 'i-id'), ('result', 'parse-id')] >>> relations.path('parse', 'item') [('item', 'i-id')] >>> relations.path('item', 'item') [] """ visited = set(source.split('+')) # split on + for joins targets = set(target.split('+')) - visited # ensure sources and targets exists for tablename in visited.union(targets): self[tablename] # base case; nothing to do if len(targets) == 0: return [] paths = [[(tablename, None)] for tablename in visited]
python
{ "resource": "" }
q8870
Record.from_dict
train
def from_dict(cls, fields, mapping): """ Create a Record from a dictionary of field mappings. The *fields* object is used to determine the column indices of fields in the mapping. Args: fields: the Relation schema for the table of this record mapping: a dictionary or other mapping from field names to column values Returns: a :class:`Record` object """ iterable = [None] * len(fields)
python
{ "resource": "" }
q8871
Table.from_file
train
def from_file(cls, path, fields=None, encoding='utf-8'): """ Instantiate a Table from a database file. This method instantiates a table attached to the file at *path*. The file will be opened and traversed to determine the number of records, but the contents will not be stored in memory unless they are modified. Args: path: the path to the table file fields: the Relation schema for the table (loaded from the relations file in the same directory
python
{ "resource": "" }
q8872
Table.write
train
def write(self, records=None, path=None, fields=None, append=False, gzip=None): """ Write the table to disk. The basic usage has no arguments and writes the table's data to the attached file. The parameters accommodate a variety of use cases, such as using *fields* to refresh a table to a new schema or *records* and *append* to incrementally build a table. Args: records: an iterable of :class:`Record` objects to write; if `None` the table's existing data is used path: the destination file path; if `None` use the path of the file attached to the table fields (:class:`Relation`): table schema to use for writing, otherwise use the current one append: if `True`, append rather than overwrite gzip: compress with gzip if non-empty Examples: >>> table.write() >>> table.write(results, path='new/path/result') """ if path is None: if not self.is_attached():
python
{ "resource": "" }
q8873
Table.commit
train
def commit(self): """ Commit changes to disk if attached. This method helps normalize the interface for detached and attached tables and makes writing attached tables a bit more efficient. For detached tables nothing is done, as there is no notion of changes, but neither is an error raised (unlike with :meth:`write`). For attached tables, if all changes are new records, the changes are appended to the existing file, and otherwise the whole file is rewritten. """ if not self.is_attached():
python
{ "resource": "" }
q8874
Table.detach
train
def detach(self): """ Detach the table from a file. Detaching a table reads all data from the file and places it in memory. This is useful when constructing or significantly manipulating table data, or when more speed is needed. Tables created by the default constructor are detached. When detaching, only unmodified records are loaded from the file; any uncommited changes in the Table are left as-is. .. warning:: Very large tables may consume all available RAM when detached. Expect the in-memory table to take up about twice the space
python
{ "resource": "" }
q8875
Table.list_changes
train
def list_changes(self): """ Return a list of modified records. This is only applicable for attached tables. Returns: A list of `(row_index, record)` tuples of modified records Raises:
python
{ "resource": "" }
q8876
Table._sync_with_file
train
def _sync_with_file(self): """Clear in-memory structures so table is synced with the file."""
python
{ "resource": "" }
q8877
Table._enum_lines
train
def _enum_lines(self): """Enumerate lines from the attached file.""" with
python
{ "resource": "" }
q8878
Table._enum_attached_rows
train
def _enum_attached_rows(self, indices): """Enumerate on-disk and in-memory records.""" records = self._records i = 0 # first rows covered by the file for i, line in self._enum_lines(): if i in indices: row = records[i] if row is None: row = decode_row(line)
python
{ "resource": "" }
q8879
Table._iterslice
train
def _iterslice(self, slice): """Yield records from a slice index.""" indices = range(*slice.indices(len(self._records))) if self.is_attached(): rows = self._enum_attached_rows(indices) if slice.step is not None and slice.step < 0:
python
{ "resource": "" }
q8880
Table._getitem
train
def _getitem(self, index): """Get a single non-slice index.""" row = self._records[index] if row is not None: pass elif self.is_attached(): # need to handle negative indices manually if index < 0: index = len(self._records) + index row = next((decode_row(line) for i, line in self._enum_lines() if i ==
python
{ "resource": "" }
q8881
Table.select
train
def select(self, cols, mode='list'): """ Select columns from each row in the table. See :func:`select_rows` for a description of how to use the *mode* parameter. Args: cols: an iterable of Field (column) names mode: how to return the
python
{ "resource": "" }
q8882
ItsdbProfile.exists
train
def exists(self, table=None): """ Return True if the profile or a table exist. If *table* is `None`, this function returns True if the root directory exists and contains a valid relations file. If *table* is given, the function returns True if the table exists as a
python
{ "resource": "" }
q8883
_calculate_crc_ccitt
train
def _calculate_crc_ccitt(data): """ All CRC stuff ripped from PyCRC, GPLv3 licensed """ global CRC_CCITT_TABLE if not CRC_CCITT_TABLE: crc_ccitt_table = [] for i in range(0, 256): crc = 0 c = i << 8 for j in range(0, 8): if (crc ^ c) & 0x8000: crc = c_ushort(crc << 1).value ^ 0x1021 else: crc = c_ushort(crc << 1).value c
python
{ "resource": "" }
q8884
GRF.to_zpl
train
def to_zpl( self, quantity=1, pause_and_cut=0, override_pause=False, print_mode='C', print_orientation='N', media_tracking='Y', **kwargs ): """ The most basic ZPL to print the GRF. Since ZPL printers are stateful this may not work and you may need to build your own. """ zpl = [ self.to_zpl_line(**kwargs), # Download image to printer '^XA', # Start Label Format
python
{ "resource": "" }
q8885
GRF._optimise_barcodes
train
def _optimise_barcodes( self, data, min_bar_height=20, min_bar_count=100, max_gap_size=30, min_percent_white=0.2, max_percent_white=0.8, **kwargs ): """ min_bar_height = Minimum height of black bars in px. Set this too low and it might pick up text and data matrices, too high and it might pick up borders, tables, etc. min_bar_count = Minimum number of parallel black bars before a pattern is considered a potential barcode. max_gap_size = Biggest white gap in px allowed between black bars. This is only important if you have multiple barcodes next to each other. min_percent_white = Minimum percentage of white bars between black bars. This helps to ignore solid rectangles. max_percent_white = Maximum percentage of white bars between black bars. This helps to ignore solid rectangles. """ re_bars = re.compile(r'1{%s,}' % min_bar_height) bars = {} for i, line in enumerate(data): for match in re_bars.finditer(line): try: bars[match.span()].append(i) except KeyError: bars[match.span()] = [i] grouped_bars = [] for span, seen_at in bars.items(): group = [] for coords in seen_at: if group and coords - group[-1] > max_gap_size: grouped_bars.append((span, group)) group = [] group.append(coords) grouped_bars.append((span, group)) suspected_barcodes = []
python
{ "resource": "" }
q8886
convert_to_underscore
train
def convert_to_underscore(name): """ "someFunctionWhatever" -> "some_function_whatever"
python
{ "resource": "" }
q8887
User.to_array
train
def to_array(self): """ Serializes this User to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(User, self).to_array() array['id'] = int(self.id) # type int array['is_bot'] = bool(self.is_bot) # type bool array['first_name'] = u(self.first_name)
python
{ "resource": "" }
q8888
User.from_array
train
def from_array(array): """ Deserialize a new User from a given dictionary. :return: new User instance. :rtype: User """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") data = {} data['id'] = int(array.get('id')) data['is_bot'] = bool(array.get('is_bot')) data['first_name'] = u(array.get('first_name')) data['last_name'] = u(array.get('last_name')) if
python
{ "resource": "" }
q8889
Chat.to_array
train
def to_array(self): """ Serializes this Chat to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(Chat, self).to_array() array['id'] = int(self.id) # type int array['type'] = u(self.type) # py2: type unicode, py3: type str if self.title is not None: array['title'] = u(self.title) # py2: type unicode, py3: type str if self.username is not None: array['username'] = u(self.username) # py2: type unicode, py3: type str if self.first_name is not None: array['first_name'] = u(self.first_name) # py2: type unicode, py3: type str if self.last_name is not None:
python
{ "resource": "" }
q8890
Chat.from_array
train
def from_array(array): """ Deserialize a new Chat from a given dictionary. :return: new Chat instance. :rtype: Chat """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array") from pytgbot.api_types.receivable.media import ChatPhoto from pytgbot.api_types.receivable.updates import Message data = {} data['id'] = int(array.get('id')) data['type'] = u(array.get('type')) data['title'] = u(array.get('title')) if array.get('title') is not None else None data['username'] = u(array.get('username')) if array.get('username') is not None else None data['first_name'] = u(array.get('first_name')) if array.get('first_name') is not None else None data['last_name'] = u(array.get('last_name')) if array.get('last_name') is not None else None data['all_members_are_administrators'] = bool(array.get('all_members_are_administrators')) if array.get('all_members_are_administrators') is not None else None data['photo'] = ChatPhoto.from_array(array.get('photo')) if array.get('photo') is not None else None data['description'] =
python
{ "resource": "" }
q8891
ChatMember.to_array
train
def to_array(self): """ Serializes this ChatMember to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(ChatMember, self).to_array() array['user'] = self.user.to_array() # type User array['status'] = u(self.status) # py2: type unicode, py3: type str if self.until_date is not None: array['until_date'] = int(self.until_date) # type int if self.can_be_edited is not None: array['can_be_edited'] = bool(self.can_be_edited) # type bool if self.can_change_info is not None: array['can_change_info'] = bool(self.can_change_info) # type bool if self.can_post_messages is not None: array['can_post_messages'] = bool(self.can_post_messages) # type bool if self.can_edit_messages is not None: array['can_edit_messages'] = bool(self.can_edit_messages) # type bool if self.can_delete_messages is not None: array['can_delete_messages'] = bool(self.can_delete_messages) # type bool if self.can_invite_users is not None: array['can_invite_users'] = bool(self.can_invite_users) # type bool if self.can_restrict_members is not None: array['can_restrict_members'] = bool(self.can_restrict_members) # type bool if self.can_pin_messages is not None: array['can_pin_messages'] = bool(self.can_pin_messages) # type bool
python
{ "resource": "" }
q8892
loads
train
def loads(s, single=False): """ Deserialize MRX string representations Args: s (str): a MRX string single (bool): if `True`, only return the first Xmrs object Returns: a generator of Xmrs objects (unless *single* is `True`) """ corpus = etree.fromstring(s)
python
{ "resource": "" }
q8893
InlineQueryResultArticle.to_array
train
def to_array(self): """ Serializes this InlineQueryResultArticle to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(InlineQueryResultArticle, self).to_array() # 'type' and 'id' given by superclass array['title'] = u(self.title) # py2: type unicode, py3: type str array['input_message_content'] = self.input_message_content.to_array() # type InputMessageContent if self.reply_markup is not None: array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup if self.url is not None: array['url'] = u(self.url) # py2: type unicode, py3: type str if self.hide_url is not None:
python
{ "resource": "" }
q8894
InlineQueryResultGif.to_array
train
def to_array(self): """ Serializes this InlineQueryResultGif to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(InlineQueryResultGif, self).to_array() # 'type' and 'id' given by superclass array['gif_url'] = u(self.gif_url) # py2: type unicode, py3: type str array['thumb_url'] = u(self.thumb_url) # py2: type unicode, py3: type str if self.gif_width is not None: array['gif_width'] = int(self.gif_width) # type int if self.gif_height is not None:
python
{ "resource": "" }
q8895
InlineQueryResultAudio.to_array
train
def to_array(self): """ Serializes this InlineQueryResultAudio to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(InlineQueryResultAudio, self).to_array() # 'type' and 'id' given by superclass array['audio_url'] = u(self.audio_url) # py2: type unicode, py3: type str array['title'] = u(self.title) # py2: type unicode, py3: type str if self.caption is not None: array['caption'] = u(self.caption) # py2: type unicode, py3: type str if self.parse_mode is not None: array['parse_mode'] = u(self.parse_mode) # py2: type unicode, py3: type str if self.performer is not None: array['performer'] =
python
{ "resource": "" }
q8896
InlineQueryResultLocation.to_array
train
def to_array(self): """ Serializes this InlineQueryResultLocation to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(InlineQueryResultLocation, self).to_array() # 'type' and 'id' given by superclass array['latitude'] = float(self.latitude) # type float array['longitude'] = float(self.longitude) # type float array['title'] = u(self.title) # py2: type unicode, py3: type str if self.live_period is not None: array['live_period'] = int(self.live_period) # type int if self.reply_markup is not None: array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup if self.input_message_content is not None:
python
{ "resource": "" }
q8897
InlineQueryResultContact.to_array
train
def to_array(self): """ Serializes this InlineQueryResultContact to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(InlineQueryResultContact, self).to_array() # 'type' and 'id' given by superclass array['phone_number'] = u(self.phone_number) # py2: type unicode, py3: type str array['first_name'] = u(self.first_name) # py2: type unicode, py3: type str if self.last_name is not None: array['last_name'] = u(self.last_name) # py2: type unicode, py3: type str if self.reply_markup is not None: array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup if self.input_message_content is not None:
python
{ "resource": "" }
q8898
InlineQueryResultCachedGif.to_array
train
def to_array(self): """ Serializes this InlineQueryResultCachedGif to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(InlineQueryResultCachedGif, self).to_array() # 'type' and 'id' given by superclass array['gif_file_id'] = u(self.gif_file_id) # py2: type unicode, py3: type str if self.title is not None: array['title'] = u(self.title) # py2: type unicode, py3: type str if self.caption is not None: array['caption'] = u(self.caption) # py2: type unicode, py3: type str if self.parse_mode is not None:
python
{ "resource": "" }
q8899
InlineQueryResultCachedDocument.to_array
train
def to_array(self): """ Serializes this InlineQueryResultCachedDocument to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(InlineQueryResultCachedDocument, self).to_array() # 'type' and 'id' given by superclass array['title'] = u(self.title) # py2: type unicode, py3: type str array['document_file_id'] = u(self.document_file_id) # py2: type unicode, py3: type str if self.description is not None: array['description'] = u(self.description) # py2: type unicode, py3: type str if self.caption is not None: array['caption'] = u(self.caption) # py2: type unicode, py3: type
python
{ "resource": "" }