text:
package io.fouad.jtb.core;

import io.fouad.jtb.core.beans.BooleanOrMessageResult;
import io.fouad.jtb.core.beans.Chat;
import io.fouad.jtb.core.beans.ChatIdentifier;
import io.fouad.jtb.core.beans.ChatMember;
import io.fouad.jtb.core.beans.InlineKeyboardMarkup;
import io.fouad.jtb.core.beans.InlineQueryResult;
import io.fouad.jtb.core.beans.MediaIdentifier;
import io.fouad.jtb.core.beans.Message;
import io.fouad.jtb.core.beans.ReplyMarkup;
import io.fouad.jtb.core.beans.TelegramFile;
import io.fouad.jtb.core.beans.User;
import io.fouad.jtb.core.beans.UserProfilePhotos;
import io.fouad.jtb.core.enums.ChatAction;
import io.fouad.jtb.core.enums.ParseMode;
import io.fouad.jtb.core.exceptions.NegativeResponseException;

import java.io.IOException;

/**
 * This interface represents Telegram Bot APIs.
 */
public interface TelegramBotApi
{
	String API_URL_PREFIX = "https://api.telegram.org/bot";
	String FILE_API_URL_PREFIX = "https://api.telegram.org/file/bot";

	/**
	 * @return token used to authenticate with bot API
	 */
	String getApiToken();

	/**
	 * A simple method for testing the bot's authentication token.
	 *
	 * @return basic information about the bot in form of a User object
	 *
	 * @throws IOException if an I/O exception occurs
	 * @throws NegativeResponseException if 4xx-5xx HTTP response is received from Telegram server
	 */
	User getMe() throws IOException, NegativeResponseException;

	/**
	 * Sends text messages.
	 *
	 * @param targetChatIdentifier unique identifier for the target chat or username of the target channel
	 * @param text text of the message to be sent
	 * @param parseMode send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width
	 *                  text or inline URLs in your bot's message
	 * @param disableLinkPreviews disables link previews for links in this message
	 * @param silentMessage sends the message silently. iOS users will not receive a notification, Android
	 *                      users will receive a notification with no sound
	 * @param replyToMessageId if the message is a reply, id of the original message
	 * @param replyMarkup additional instructions to create inline keyboard, create/hide custom keyboard,
	 *                    or to force a reply from the user
	 *
	 * @return the sent Message
	 *
	 * @throws IOException if an I/O exception occurs
	 * @throws NegativeResponseException if 4xx-5xx HTTP response is received from Telegram server
	 */
	Message sendMessage(ChatIdentifier targetChatIdentifier, String text, ParseMode parseMode,
	                    Boolean disableLinkPreviews, Boolean silentMessage, Integer replyToMessageId,
	                    ReplyMarkup replyMarkup) throws IOException, NegativeResponseException;

	/**
	 * Forwards messages of any kind.
	 *
	 * @param targetChatIdentifier unique identifier for the target chat or username of the target channel
	 * @param sourceChatIdentifier unique identifier for the chat or username of the channel where the original
	 *                             message was sent
	 * @param silentMessage sends the message silently. iOS users will not receive a notification, Android
	 *                      users will receive a notification with no sound
	 * @param messageId unique identifier for the message to be forwarded
	 *
	 * @return the forwarded Message
	 *
	 * @throws IOException if an I/O exception occurs
	 * @throws NegativeResponseException if 4xx-5xx HTTP response is received from Telegram server
	 */
	Message forwardMessage(ChatIdentifier targetChatIdentifier, ChatIdentifier sourceChatIdentifier,
	                       Boolean silentMessage, Integer messageId) throws IOException, NegativeResponseException;

	/**
	 * Sends photos.
	 *
	 * @param targetChatIdentifier unique identifier for the target chat or username of the target channel
	 * @param mediaIdentifier photo to be sent
	 * @param photoCaption photo caption, 0-200 characters
	 * @param silentMessage sends the message silently. iOS users will not receive a notification, Android
	 *                      users will receive a notification with no sound
	 * @param replyToMessageId if the message is a reply, id of the original message
	 * @param replyMarkup additional instructions to create inline keyboard, create/hide custom keyboard,
	 *                    or to force a reply from the user
	 *
	 * @return the sent Message
	 *
	 * @throws IOException if an I/O exception occurs
	 * @throws NegativeResponseException if 4xx-5xx HTTP response is received from Telegram server
	 */
	Message sendPhoto(ChatIdentifier targetChatIdentifier, MediaIdentifier mediaIdentifier, String photoCaption,
	                  Boolean silentMessage, Integer replyToMessageId, ReplyMarkup replyMarkup) throws IOException,
			NegativeResponseException;

	/**
	 * Sends audio files that Telegram clients will display them in the music player. Your audio must be in the
	 * .mp3 format. Bots can currently send audio files of up to 50 MB in size, this limit may be changed in
	 * the future.
	 *
	 * @param targetChatIdentifier unique identifier for the target chat or username of the target channel
	 * @param mediaIdentifier audio file to be sent
	 * @param duration duration of the audio in seconds
	 * @param performer the performer
	 * @param trackTitle the track name
	 * @param silentMessage sends the message silently. iOS users will not receive a notification, Android
	 *                      users will receive a notification with no sound
	 * @param replyToMessageId if the message is a reply, id of the original message
	 * @param replyMarkup additional instructions to create inline keyboard, create/hide custom keyboard,
	 *                    or to force a reply from the user
	 *
	 * @return the sent Message
	 *
	 * @throws IOException if an I/O exception occurs
	 * @throws NegativeResponseException if 4xx-5xx HTTP response is received from Telegram server
	 */
	Message sendAudio(ChatIdentifier targetChatIdentifier, MediaIdentifier mediaIdentifier, Integer duration,
	                  String performer, String trackTitle, Boolean silentMessage, Integer replyToMessageId,
	                  ReplyMarkup replyMarkup) throws IOException, NegativeResponseException;

	/**
	 * Sends general files. Bots can currently send files of any type of up to 50 MB in size, this limit may be
	 * changed in the future.
	 *
	 * @param targetChatIdentifier unique identifier for the target chat or username of the target channel
	 * @param mediaIdentifier file to be sent
	 * @param documentCaption document caption, 0-200 characters
	 * @param silentMessage sends the message silently. iOS users will not receive a notification, Android
	 *                      users will receive a notification with no sound
	 * @param replyToMessageId if the message is a reply, id of the original message
	 * @param replyMarkup additional instructions to create inline keyboard, create/hide custom keyboard,
	 *                    or to force a reply from the user
	 *
	 * @return the sent Message
	 *
	 * @throws IOException if an I/O exception occurs
	 * @throws NegativeResponseException if 4xx-5xx HTTP response is received from Telegram server
	 */
	Message sendDocument(ChatIdentifier targetChatIdentifier, MediaIdentifier mediaIdentifier, String documentCaption,
	                     Boolean silentMessage, Integer replyToMessageId, ReplyMarkup replyMarkup) throws IOException,
			NegativeResponseException;

	/**
	 * Sends .webp stickers.
	 *
	 * @param targetChatIdentifier unique identifier for the target chat or username of the target channel
	 * @param mediaIdentifier sticker to be sent
	 * @param silentMessage sends the message silently. iOS users will not receive a notification, Android
	 *                      users will receive a notification with no sound
	 * @param replyToMessageId if the message is a reply, id of the original message
	 * @param replyMarkup additional instructions to create inline keyboard, create/hide custom keyboard,
	 *                    or to force a reply from the user
	 *
	 * @return the sent Message
	 *
	 * @throws IOException if an I/O exception occurs
	 * @throws NegativeResponseException if 4xx-5xx HTTP response is received from Telegram server
	 */
	Message sendSticker(ChatIdentifier targetChatIdentifier, MediaIdentifier mediaIdentifier, Boolean silentMessage,
	                    Integer replyToMessageId, ReplyMarkup replyMarkup) throws IOException,
			NegativeResponseException;

	/**
	 * Sends video files. Telegram clients support mp4 videos (other formats may be sent as Document). Bots can
	 * currently send video files of up to 50 MB in size, this limit may be changed in the future.
	 *
	 * @param targetChatIdentifier unique identifier for the target chat or username of the target channel
	 * @param mediaIdentifier video to be sent
	 * @param duration duration of sent video in seconds
	 * @param width video width
	 * @param height video height
	 * @param videoCaption video caption, 0-200 characters
	 * @param silentMessage sends the message silently. iOS users will not receive a notification, Android
	 *                      users will receive a notification with no sound
	 * @param replyToMessageId if the message is a reply, id of the original message
	 * @param replyMarkup additional instructions to create inline keyboard, create/hide custom keyboard,
	 *                    or to force a reply from the user
	 *
	 * @return the sent Message
	 *
	 * @throws IOException if an I/O exception occurs
	 * @throws NegativeResponseException if 4xx-5xx HTTP response is received from Telegram server
	 */
	Message sendVideo(ChatIdentifier targetChatIdentifier, MediaIdentifier mediaIdentifier, Integer duration,
	                  Integer width, Integer height, String videoCaption, Boolean silentMessage, Integer replyToMessageId,
	                  ReplyMarkup replyMarkup) throws IOException, NegativeResponseException;

	/**
	 * Sends audio files that Telegram clients will display them as playable voice messages. For this to work,
	 * your audio must be in an .ogg file encoded with OPUS (other formats may be sent as Audio or Document).
	 * Bots can currently send voice messages of up to 50 MB in size, this limit may be changed in the future.
	 *
	 * @param targetChatIdentifier unique identifier for the target chat or username of the target channel
	 * @param mediaIdentifier audio file to be sent
	 * @param duration duration of sent audio in seconds
	 * @param silentMessage sends the message silently. iOS users will not receive a notification, Android
	 *                      users will receive a notification with no sound
	 * @param replyToMessageId if the message is a reply, id of the original message
	 * @param replyMarkup additional instructions to create inline keyboard, create/hide custom keyboard,
	 *                    or to force a reply from the user
	 *
	 * @return the sent Message
	 *
	 * @throws IOException if an I/O exception occurs
	 * @throws NegativeResponseException if 4xx-5xx HTTP response is received from Telegram server
	 */
	Message sendVoice(ChatIdentifier targetChatIdentifier, MediaIdentifier mediaIdentifier, Integer duration, Boolean silentMessage,
	                  Integer replyToMessageId, ReplyMarkup replyMarkup) throws IOException, NegativeResponseException;

	/**
	 * Sends point on the map.
	 *
	 * @param targetChatIdentifier unique identifier for the target chat or username of the target channel
	 * @param latitude latitude of location
	 * @param longitude longitude of location
	 * @param silentMessage sends the message silently. iOS users will not receive a notification, Android
	 *                      users will receive a notification with no sound
	 * @param replyToMessageId if the message is a reply, id of the original message
	 * @param replyMarkup additional instructions to create inline keyboard, create/hide custom keyboard,
	 *                    or to force a reply from the user
	 *
	 * @return the sent Message
	 *
	 * @throws IOException if an I/O exception occurs
	 * @throws NegativeResponseException if 4xx-5xx HTTP response is received from Telegram server
	 */
	Message sendLocation(ChatIdentifier targetChatIdentifier, float latitude, float longitude, Boolean silentMessage,
	                     Integer replyToMessageId, ReplyMarkup replyMarkup) throws IOException,
			NegativeResponseException;

	/**
	 * Sends information about a venue.
	 *
	 * @param targetChatIdentifier unique identifier for the target chat or username of the target channel
	 * @param latitude latitude of the venue
	 * @param longitude longitude of the venue
	 * @param title name of the venue
	 * @param address address of the venue
	 * @param foursquareId Foursquare identifier of the venue
	 * @param silentMessage sends the message silently. iOS users will not receive a notification, Android
	 *                      users will receive a notification with no sound
	 * @param replyToMessageId if the message is a reply, id of the original message
	 * @param replyMarkup additional instructions to create inline keyboard, create/hide custom keyboard,
	 *                    or to force a reply from the user
	 *
	 * @return the sent Message
	 *
	 * @throws IOException if an I/O exception occurs
	 * @throws NegativeResponseException if 4xx-5xx HTTP response is received from Telegram server
	 */
	Message sendVenue(ChatIdentifier targetChatIdentifier, float latitude, float longitude, String title,
	                  String address, String foursquareId, Boolean silentMessage, Integer replyToMessageId,
	                  ReplyMarkup replyMarkup) throws IOException, NegativeResponseException;

	/**
	 * Sends phone contact.
	 *
	 * @param targetChatIdentifier unique identifier for the target chat or username of the target channel
	 * @param phoneNumber contact's phone number
	 * @param firstName contact's first name
	 * @param lastName contact's last name
	 * @param silentMessage sends the message silently. iOS users will not receive a notification, Android
	 *                      users will receive a notification with no sound
	 * @param replyToMessageId if the message is a reply, id of the original message
	 * @param replyMarkup additional instructions to create inline keyboard, create/hide custom keyboard,
	 *                    or to force a reply from the user
	 *
	 * @return the sent Message
	 *
	 * @throws IOException if an I/O exception occurs
	 * @throws NegativeResponseException if 4xx-5xx HTTP response is received from Telegram server
	 */
	Message sendContact(ChatIdentifier targetChatIdentifier, String phoneNumber, String firstName,
						String lastName, Boolean silentMessage, Integer replyToMessageId,
						ReplyMarkup replyMarkup) throws IOException, NegativeResponseException;

	/**
	 * Use this method when you need to tell the user that something is happening on the bot's side.
	 * The status is set for 5 seconds or less (when a message arrives from your bot, Telegram clients
	 * clear its typing status).
	 *
	 * @param targetChatIdentifier unique identifier for the target chat or username of the target channel
	 * @param action type of action to broadcast. Choose one, depending on what the user is about to receive
	 *
	 * @throws IOException if an I/O exception occurs
	 * @throws NegativeResponseException if 4xx-5xx HTTP response is received from Telegram server
	 */
	void sendChatAction(ChatIdentifier targetChatIdentifier, ChatAction action) throws IOException,
			NegativeResponseException;

	/**
	 * Gets a list of profile pictures for a user.
	 *
	 * @param userId unique identifier of the target user
	 * @param offset sequential number of the first photo to be returned. By default, all photos are returned
	 * @param limit limits the number of photos to be retrieved. Values between 1—100 are accepted. Defaults
	 *              to 100
	 * @return UserProfilePhotos object
	 *
	 * @throws IOException if an I/O exception occurs
	 * @throws NegativeResponseException if 4xx-5xx HTTP response is received from Telegram server
	 */
	UserProfilePhotos getUserProfilePhotos(int userId, Integer offset, Integer limit) throws IOException,
			NegativeResponseException;

	/**
	 * Gets basic info about a file and prepare it for downloading. For the moment, bots can download files
	 * of up to 20MB in size.
	 *
	 * Note: This function may not preserve original file name. Mime type of the file and its name (if available)
	 * should be saved when the File object is received.
	 *
	 * @param fileId file identifier to get info about
	 *
	 * @return TelegramFile object
	 *
	 * @throws IOException if an I/O exception occurs
	 * @throws NegativeResponseException if 4xx-5xx HTTP response is received from Telegram server
	 */
	TelegramFile getFile(String fileId) throws IOException, NegativeResponseException;

	/**
	 * Kicks a user from a group or a supergroup. In the case of supergroups, the user will not be
	 * able to return to the group on their own using invite links, etc., unless unbanned first.
	 * The bot must be an administrator in the group for this to work.
	 * Note: This will method only work if the 'All Members Are Admins' setting is off in the target
	 * group. Otherwise members may only be removed by the group's creator or by the member that
	 * added them.
	 *
	 * @param targetChatIdentifier unique identifier for the target group/supergroup or username of the target supergroup
	 * @param userId unique identifier of the target user
	 *
	 * @return true on success
	 *
	 * @throws IOException if an I/O exception occurs
	 * @throws NegativeResponseException if 4xx-5xx HTTP response is received from Telegram server
	 */
	boolean kickChatMember(ChatIdentifier targetChatIdentifier, int userId) throws IOException, NegativeResponseException;

	/**
	 * Use this method for your bot to leave a group, supergroup or channel.
	 *
	 * @param targetChatIdentifier unique identifier for the target group/supergroup or username of the target supergroup
	 *
	 * @return true on success
	 *
	 * @throws IOException if an I/O exception occurs
	 * @throws NegativeResponseException if 4xx-5xx HTTP response is received from Telegram server
	 */
	boolean leaveChat(ChatIdentifier targetChatIdentifier) throws IOException, NegativeResponseException;

	/**
	 * Unbans a previously kicked user in a supergroup. The user will not return to the group automatically,
	 * but will be able to join via link, etc. The bot must be an administrator in the group for this to work.
	 *
	 * @param targetChatIdentifier unique identifier for the target group/supergroup or username of the target supergroup
	 * @param userId unique identifier of the target user
	 *
	 * @return true on success
	 *
	 * @throws IOException if an I/O exception occurs
	 * @throws NegativeResponseException if 4xx-5xx HTTP response is received from Telegram server
	 */
	boolean unbanChatMember(ChatIdentifier targetChatIdentifier, int userId) throws IOException, NegativeResponseException;

	/**
	 * Use this method to get up to date information about the chat (current name of the user for one-on-one
	 * conversations, current username of a user, group or channel, etc.).
	 *
	 * @param targetChatIdentifier unique identifier for the target group/supergroup or username of the target supergroup
	 *
	 * @return a Chat object on success
	 *
	 * @throws IOException if an I/O exception occurs
	 * @throws NegativeResponseException if 4xx-5xx HTTP response is received from Telegram server
	 */
	Chat getChat(ChatIdentifier targetChatIdentifier) throws IOException, NegativeResponseException;

	/**
	 * Use this method to get a list of administrators in a chat.
	 *
	 * @param targetChatIdentifier unique identifier for the target group/supergroup or username of the target supergroup
	 *
	 * @return On success, returns an Array of ChatMember objects that contains information about all chat
	 * administrators except other bots. If the chat is a group or a supergroup and no administrators were appointed,
	 * only the creator will be returned.
	 *
	 * @throws IOException if an I/O exception occurs
	 * @throws NegativeResponseException if 4xx-5xx HTTP response is received from Telegram server
	 */
	ChatMember[] getChatAdministrators(ChatIdentifier targetChatIdentifier) throws IOException, NegativeResponseException;

	/**
	 * Use this method to get the number of members in a chat.
	 *
	 * @param targetChatIdentifier unique identifier for the target group/supergroup or username of the target supergroup
	 *
	 * @return On success, number of chat members.
	 *
	 * @throws IOException if an I/O exception occurs
	 * @throws NegativeResponseException if 4xx-5xx HTTP response is received from Telegram server
	 */
	int getChatMembersCount(ChatIdentifier targetChatIdentifier) throws IOException, NegativeResponseException;

	/**
	 * Use this method to get information about a member of a chat.
	 *
	 * @param targetChatIdentifier unique identifier for the target group/supergroup or username of the target supergroup
	 * @param userId unique identifier of the target user
	 *
	 * @return ChatMember object on success
	 *
	 * @throws IOException if an I/O exception occurs
	 * @throws NegativeResponseException if 4xx-5xx HTTP response is received from Telegram server
	 */
	ChatMember getChatMember(ChatIdentifier targetChatIdentifier, int userId) throws IOException, NegativeResponseException;

	/**
	 * Sends 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.
	 *
	 * @param callbackQueryId unique identifier for the query to be answered
	 * @param text text of the notification. If not specified, nothing will be shown to the user
	 * @param showAlert if true, an alert will be shown by the client instead of a notification at
	 *                  the top of the chat screen. Defaults to false
	 *
	 * @return true on success
	 *
	 * @throws IOException if an I/O exception occurs
	 * @throws NegativeResponseException if 4xx-5xx HTTP response is received from Telegram server
	 */
	boolean answerCallbackQuery(String callbackQueryId, String text, Boolean showAlert) throws IOException, NegativeResponseException;

	/**
	 * Edits text messages sent by the bot or via the bot (for inline bots).
	 *
	 * @param targetChatIdentifier unique identifier for the target chat or username of the target channel
	 * @param messageId unique identifier of the sent message
	 * @param inlineMessageId identifier of the inline message
	 * @param text new text of the message
	 * @param parseMode send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width
	 *                  text or inline URLs in your bot's message
	 * @param disableLinkPreviews disables link previews for links in this message
	 * @param inlineKeyboardMarkup inlineKeyboardMarkup object
	 *
	 * @return the edited Message if it is sent by the bot, otherwise true on success
	 *
	 * @throws IOException if an I/O exception occurs
	 * @throws NegativeResponseException if 4xx-5xx HTTP response is received from Telegram server
	 */
	BooleanOrMessageResult editMessageText(ChatIdentifier targetChatIdentifier, Integer messageId, String inlineMessageId,
	                                       String text, ParseMode parseMode, Boolean disableLinkPreviews,
	                                       InlineKeyboardMarkup inlineKeyboardMarkup)
			throws IOException, NegativeResponseException;

	/**
	 * Edits captions of messages sent by the bot or via the bot (for inline bots).
	 *
	 * @param targetChatIdentifier unique identifier for the target chat or username of the target channel
	 * @param messageId unique identifier of the sent message
	 * @param inlineMessageId identifier of the inline message
	 * @param caption new caption of the message
	 * @param inlineKeyboardMarkup inlineKeyboardMarkup object
	 *
	 * @return the edited Message if it is sent by the bot, otherwise true on success
	 *
	 * @throws IOException if an I/O exception occurs
	 * @throws NegativeResponseException if 4xx-5xx HTTP response is received from Telegram server
	 */
	BooleanOrMessageResult editMessageCaption(ChatIdentifier targetChatIdentifier, Integer messageId, String inlineMessageId,
	                                          String caption, InlineKeyboardMarkup inlineKeyboardMarkup)
			throws IOException, NegativeResponseException;

	/**
	 * Edits only the reply markup of messages sent by the bot or via the bot (for inline bots).
	 *
	 * @param targetChatIdentifier unique identifier for the target chat or username of the target channel
	 * @param messageId unique identifier of the sent message
	 * @param inlineMessageId identifier of the inline message
	 * @param inlineKeyboardMarkup inlineKeyboardMarkup object
	 *
	 * @return the edited Message if it is sent by the bot, otherwise true on success
	 *
	 * @throws IOException if an I/O exception occurs
	 * @throws NegativeResponseException if 4xx-5xx HTTP response is received from Telegram server
	 */
	BooleanOrMessageResult editMessageReplyMarkup(ChatIdentifier targetChatIdentifier, Integer messageId, String inlineMessageId,
	                                              InlineKeyboardMarkup inlineKeyboardMarkup)
			throws IOException, NegativeResponseException;

	/**
	 * Sends answers to an inline query. No more than 50 results per query are allowed.
	 *
	 * @param inlineQueryId unique identifier for the answered query
	 * @param results array of results for the inline query
	 * @param cacheTime the maximum amount of time in seconds that the result of the inline query
	 *                  may be cached on the server. Defaults to 300
	 * @param isPersonal pass true, if results may be cached on the server side only
	 *                   for the user that sent the query. By default, results may be returned to
	 *                   any user who sends the same query
	 * @param nextOffset the offset that a client should send in the next query with the same text
	 *                   to receive more results. Pass an empty string if there are no more results
	 *                   or if you don't support pagination. Offset length can't exceed 64 bytes
	 * @param switchPmText if passed, clients will display a button with specified text that
	 *                     switches the user to a private chat with the bot and sends the bot
	 *                     a start message with the parameter switchPmParameter
	 * @param switchPmParameter parameter for the start message sent to the bot when user presses
	 *                          the switch button.
	 *                          Example: An inline bot that sends YouTube videos can ask the user
	 *                          to connect the bot to their YouTube account to adapt search results
	 *                          accordingly. To do this, it displays a 'Connect your YouTube
	 *                          account' button above the results, or even before showing any.
	 *                          The user presses the button, switches to a private chat with the bot
	 *                          and, in doing so, passes a start parameter that instructs the bot to
	 *                          return an oauth link. Once done, the bot can offer a switch_inline
	 *                          button so that the user can easily return to the chat where they
	 *                          wanted to use the bot's inline capabilities.
	 *
	 * @return true on success
	 *
	 * @throws IOException if an I/O exception occurs
	 * @throws NegativeResponseException if 4xx-5xx HTTP response is received from Telegram server
	 */
	boolean answerInlineQuery(String inlineQueryId, InlineQueryResult[] results, Integer cacheTime, Boolean isPersonal,
	                          String nextOffset, String switchPmText, String switchPmParameter) throws IOException,
			NegativeResponseException;
}


text:
export function isColor(str: string): boolean {
	"use strict";
	return /^#[a-fA-F0-9]{6}$/.test(str);
}

export function isName(str: string): boolean {
	"use strict";
	return 1 <= str.length && str.length <= 30;
}

redpajama_set_name: RedPajamaGithub


text:
/**
 * Global Functions for work with components
 */

var org_scn_community_basics = org_scn_community_basics || {};

org_scn_community_basics.resizeContentAbsoluteLayout = function (parent, mainObject) {
	if(parent._oContentPlaced != true) {
		var jqThis = parent.$();

		parent.addContent(
				mainObject,
				{left: "0px", top: "0px"}
		);

		parent._oResize = function() {
			parent._containerWidth = jqThis.outerWidth(true) + "px";
			parent._containerHeight = jqThis.outerHeight(true) + "px";

			if(mainObject.setWidth) {
				mainObject.setWidth(parent._containerWidth);
			}

			if(mainObject.setHeight) {
				mainObject.setHeight(parent._containerHeight);
			}
		};

		// attach resize handler
		jqThis[0].onresize = parent._oResize;

		// call resize handler
		parent._oResize();

		// redefine the layout functions
		var currentWidthFunction = parent.setWidth;
		var currentHeightFunction = parent.setHeight;

		if(currentWidthFunction) {
			parent.setWidth = function (value) {
				var r = currentWidthFunction.call(parent, value);
				// always trigger resize
				parent._oResize();

				return r;
			};
		}
		if(currentHeightFunction) {
			parent.setHeight = function (value) {
				var r = currentHeightFunction.call(parent, value);
				// always trigger resize
				parent._oResize();

				return r;
			};
		}

		parent._oContentPlaced = true;
	};
};

/**
 * Formats the double value, using plain JS to avoid load of CVOM
 */
org_scn_community_basics.getFormattedValue = function (value, locale, numberOfDecimal) {
	// locale got from SAPUI5 is browser dependent, not data dependent
	if(locale == undefined) {
		locale = sap.ui.getCore().getConfiguration().getLanguage();
	}

	var decimals = "";for (var i = 0; i < numberOfDecimal; i++) {decimals += "0";}
	var formatString = "#,###." + decimals;

	var number = jQuery.formatNumber(value, {format:formatString, locale:locale});
	// in case format starts with ".", the 0 needs to be placed (manually) at the beginning
	if(number.indexOf(".") == 0) {
		number = "0" + number;
	}

	number = number.toLocaleString(numberOfDecimal);

	return number;
};

org_scn_community_basics.hideNoDataOverlay = function(componentId, includeFullSizeChild) {
	var css = "";
	css = css + "#" + componentId + "_loadingState {visibility: hidden !important;}";
	css = css + "#" + componentId + "_loadingStateBox {visibility: hidden !important;}";
	css = css + "#" + componentId + "_loadingState_message {visibility: hidden !important;}";

	if(includeFullSizeChild) {
		css = css + "#" + componentId + " > div[class=\"sapUiLayoutAbsPos\"] {width: 100% !important;height: 100% !important;}";
	}

	var style = document.createElement('style');
	style.type = 'text/css';
	style.innerHTML = css;
	document.getElementsByTagName('head')[0].appendChild(style);
};

org_scn_community_basics.readOwnScriptAccess = function(scriptSrc, componentFullName) {
	var packageAndName = componentFullName.substring("org.scn.community.".length);
	var componentName = packageAndName.substring(packageAndName.indexOf(".") + 1);
	var packageName = packageAndName.substring(0, packageAndName.indexOf("."));
	return org_scn_community_basics.readGenericScriptAccess(scriptSrc, "res/"+componentName+"/", packageName);
}

org_scn_community_basics.readGenericScriptAccess = function(scriptSrc, sctiptPath, packageName) {
	if(scriptSrc) {
		var myScriptSuffix = sctiptPath;
		var myPluginSuffix = "org.scn.community."+packageName+"/";
		var mainScriptPathIndex = scriptSrc.indexOf(myScriptSuffix);
		var mainSDKPathIndex = scriptSrc.indexOf(myPluginSuffix);
		var mainSDKPath = scriptSrc.substring(0, mainSDKPathIndex);
		var ownScriptPath = scriptSrc.substring(0, mainScriptPathIndex) + myScriptSuffix;
		return {
			myScriptPath : ownScriptPath,					// http://localhost:9091/aad/zen/mimes/sdk_include/org.scn.community.<packageName>/res/<component-name>/
			myPackagePath: mainSDKPath + myPluginSuffix, 	// http://localhost:9091/aad/zen/mimes/sdk_include/org.scn.community.<packageName>/
			mainSDKPath : mainSDKPath						// http://localhost:9091/aad/zen/mimes/sdk_include/
		};
	}
	return {
		// temporary hack for local mode in 1.5 release
		myScriptPath: "/aad/zen/mimes/sdk_include/org.scn.community."+packageName+"/" + sctiptPath + "/",
		myPackagePath: "/aad/zen/mimes/sdk_include/org.scn.community."+packageName+"/",
 		mainSDKPath: "/aad/zen/mimes/sdk_include/"
 	};
}


text:
// Copyright (c) 2014 mogoweb. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package com.mogoweb.chrome.impl;

import android.util.Log;

// TODO: remove this when all WebView APIs have been implemented.
public class UnimplementedWebViewApi {
    private static String TAG = "UnimplementedWebViewApi";

    private static class UnimplementedWebViewApiException extends UnsupportedOperationException {
        public UnimplementedWebViewApiException() {
            super();
        }
    }

    private static boolean THROW = false;
    // By default we keep the traces down to one frame to reduce noise, but for debugging it might
    // be useful to set this to true.
    private static boolean FULL_TRACE = false;

    public static void invoke() throws UnimplementedWebViewApiException {
        if (THROW) {
            throw new UnimplementedWebViewApiException();
        } else {
            if (FULL_TRACE) {
                Log.w(TAG, "Unimplemented WebView method called in: " +
                      Log.getStackTraceString(new Throwable()));
            } else {
                StackTraceElement[] trace = new Throwable().getStackTrace();
                // The stack trace [0] index is this method (invoke()).
                StackTraceElement unimplementedMethod = trace[1];
                StackTraceElement caller = trace[2];
                Log.w(TAG, "Unimplemented WebView method " + unimplementedMethod.getMethodName() +
                        " called from: " + caller.toString());
            }
        }
    }

}


text:
package it.finsiel.siged.mvc.presentation.action.amministrazione;

import it.finsiel.siged.constant.Constants;
import it.finsiel.siged.constant.ReturnValues;
import it.finsiel.siged.model.organizzazione.Organizzazione;
import it.finsiel.siged.model.organizzazione.Utente;
import it.finsiel.siged.mvc.business.UtenteDelegate;
import it.finsiel.siged.mvc.presentation.actionform.amministrazione.CambioPasswordForm;
import it.finsiel.siged.mvc.presentation.helper.NavBarElement;
import it.finsiel.siged.mvc.vo.organizzazione.UtenteVO;

import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

public final class CambioPasswordAction extends Action {

    static Logger logger = Logger.getLogger(CambioPasswordAction.class
            .getName());

    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        CambioPasswordForm cambioPasswordForm = (CambioPasswordForm) form;
        HttpSession session = request.getSession();
        Utente utente = (Utente) session.getAttribute(Constants.UTENTE_KEY);
        ActionMessages errors = new ActionMessages();

        ArrayList navBar = new ArrayList();
        // link = request.getContextPath() + link;
        NavBarElement elem = new NavBarElement();
        elem.setValue("Cambio password");
        elem.setTitle("Cambio password");
        elem.setLink(null);
        navBar.add(0, elem);
        session.setAttribute(Constants.NAV_BAR, navBar);

        if (utente == null) {
            errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
                    "error.authentication.failed"));
        } else if (request.getParameter("btnConferma") != null) {
            utente.getValueObject().setPassword(
                    cambioPasswordForm.getNewPassword());
            UtenteDelegate delegate = UtenteDelegate.getInstance();
            UtenteVO utenteAggiornato = delegate.aggionaUtenteVO(utente
                    .getValueObject());
            if (utenteAggiornato.getReturnValue() == ReturnValues.SAVED) {
                Organizzazione org = Organizzazione.getInstance();
                org.addUtente(utente);
                session.setAttribute(Constants.UTENTE_KEY, utente);
            }
            errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
                    "operazione_ok"));
            saveErrors(request, errors);
            cambioPasswordForm.reset(mapping, request);

        } else {
            cambioPasswordForm.setOldPassword(utente.getValueObject()
                    .getPassword());
            cambioPasswordForm.setUsername(utente.getValueObject()
                    .getUsername());
        }
        return (mapping.getInputForward());
    }
}


text:
package com.example1.locationapp;

import com.example1.locationapp.R;

import Controller.LocalFileLoder;
import Model.CommentUser;
import Model.UserModel;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * for user owner or other user to watch the information of the user.
 * @author zuo2
 */

public class ProfileActivity extends Activity {
	private CommentUser goduser;
	private TextView textview1,textview2,textview3,textview4,textview5,textview6,textview7;
	private ImageView imageview;
	private Bitmap bitmap;
	private String uuid="";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fragment_profile);
		ActionBar bar = getActionBar();
		bar.setTitle("My Profile");
		Intent intent = getIntent();
		goduser= (CommentUser) intent.getSerializableExtra("name");
		textview1 = (TextView) findViewById(R.id.textView188);
		textview2 = (TextView) findViewById(R.id.textView388);
		textview3 = (TextView) findViewById(R.id.textView288);
		textview4 = (TextView) findViewById(R.id.textView588);
		textview5 = (TextView) findViewById(R.id.textView488);
		textview6 = (TextView) findViewById(R.id.textView688);
		textview7 = (TextView) findViewById(R.id.textView8);
		uuid = goduser.getUudi();
		textview1.setText(goduser.getName());
		textview2.setText(goduser.getAge());
		textview3.setText(goduser.getFacebook());
		textview4.setText(goduser.getLinkedIn());
		textview5.setText(goduser.getPhone());
		textview6.setText(goduser.getEmail());
		textview7.setText(goduser.getBio());
		imageview = (ImageView) findViewById(R.id.imageimage11);
		if(goduser.getImageEncode()!=null)
		{
		byte[] imageAsBytes = Base64.decode(goduser.getImageEncode().getBytes(),Base64.NO_WRAP);
    	bitmap = BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length);
    	imageview.setImageBitmap(bitmap);
    	bitmap=null;
		}
	}

	/**
	 * Inflate the menu; this adds items to the action bar if it is present.
	 * @param menu
	 * @return
	 * true
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.profile, menu);
		return true;
	}

	/**
	 * Handle action bar item clicks here. The action bar will
	 * automatically handle clicks on the Home/Up button, so long
	 * as you specify a parent activity in AndroidManifest.xml.
	 * @param item -- selected item
	 * @return
	 * boolean
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			LocalFileLoder loader = new LocalFileLoder(getApplicationContext());
			UserModel user = loader.loadFromFile();
			String username = user.getUser_name();
			if(username.equals(textview1.getText()))
			{
				Intent intent = new Intent();
				intent.setClass(getApplicationContext(), NewProfileActivity.class);
				intent.putExtra("username",user.getUser_name());
				intent.putExtra("uuid",uuid);
				intent.putExtra("object", goduser);
				startActivity(intent);
				ProfileActivity.this.finish();
			}
			else
			{
				Toast.makeText(getApplicationContext(), "Can't edit other people's profile", Toast.LENGTH_SHORT).show();
			}
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	/**
	 * A placeholder fragment containing a simple view.
	 */
	public static class PlaceholderFragment extends Fragment {

		public PlaceholderFragment() {
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.fragment_profile,
					container, false);
			return rootView;
		}
	}

}


text:
import assert = require('assert');
import {ReplHistory} from 'vs/workbench/parts/debug/common/replHistory';

suite('Debug - Repl History', () => {
	var history: ReplHistory;

	setup(() => {
		history = new ReplHistory(['one', 'two', 'three', 'four', 'five']);
	});

	teardown(() => {
		history = null;
	});

	test('previous and next', () => {
		assert.equal(history.previous(), 'five');
		assert.equal(history.previous(), 'four');
		assert.equal(history.previous(), 'three');
		assert.equal(history.previous(), 'two');
		assert.equal(history.previous(), 'one');
		assert.equal(history.previous(), null);
		assert.equal(history.next(), 'two');
		assert.equal(history.next(), 'three');
		assert.equal(history.next(), 'four');
		assert.equal(history.next(), 'five');
	});

	test('evaluated and remember', () => {
		history.evaluated('six');
		assert.equal(history.previous(), 'six');
		assert.equal(history.previous(), 'five');
		assert.equal(history.next(), 'six');

		history.remember('six++', true);
		assert.equal(history.next(), 'six++');
		assert.equal(history.previous(), 'six');

		history.evaluated('seven');
		assert.equal(history.previous(), 'seven');
		assert.equal(history.previous(), 'six');
	});
});


text:
namespace NPOI.SS.Format
{
    using System;
    using System.Collections.Generic;
    using static NPOI.SS.Format.CellNumberFormatter;

    /**
* Internal helper class for CellNumberFormatter
*
* This class represents a single modification to a result string.  The way
* this works is complicated, but so is numeric formatting.  In general, for
* most formats, we use a DecimalFormat object that will Put the string out
* in a known format, usually with all possible leading and trailing zeros.
* We then walk through the result and the original format, and note any
* modifications that need to be made.  Finally, we go through and apply
* them all, dealing with overlapping modifications.
*/

    public class CellNumberStringMod : IComparable<CellNumberStringMod>
    {
        public const int BEFORE = 1;
        public const int AFTER = 2;
        public const int REPLACE = 3;

        private Special special;
        private int op;
        //private CharSequence toAdd;
        private string toAdd;
        private Special end;
        private bool startInclusive;
        private bool endInclusive;

        public CellNumberStringMod(Special special, string toAdd, int op)
        {
            this.special = special;
            this.toAdd = toAdd;
            this.op = op;
        }

        public CellNumberStringMod(Special start, bool startInclusive, Special end, bool endInclusive, char toAdd)
                : this(start, startInclusive, end, endInclusive)
        {
            ;
            this.toAdd = toAdd + "";
        }

        public CellNumberStringMod(Special start, bool startInclusive, Special end, bool endInclusive)
        {
            special = start;
            this.startInclusive = startInclusive;
            this.end = end;
            this.endInclusive = endInclusive;
            op = REPLACE;
            toAdd = "";
        }

        public int CompareTo(CellNumberStringMod that)
        {
            int diff = special.pos - that.special.pos;
            return (diff != 0) ? diff : (op - that.op);
        }

        public override bool Equals(Object that)
        {
            try
            {
                return CompareTo((CellNumberStringMod)that) == 0;
            }
            catch (Exception)
            {
                // NullPointerException or CastException
                return false;
            }
        }

        public override int GetHashCode()
        {
            return special.GetHashCode() + op;
        }

        public Special GetSpecial()
        {
            return special;
        }

        public int Op
        {
            get
            {
                return op;
            }
        }

        public string ToAdd
        {
            get
            {
                return toAdd;
            }
        }

        public Special End
        {
            get
            {
                return end;
            }
        }

        public bool IsStartInclusive
        {
            get
            {
                return startInclusive;
            }
        }

        public bool IsEndInclusive
        {
            get
            {
                return endInclusive;
            }
        }
    }

}


text:
package net.christophermerrill.FancyFxTree.example;

import javafx.application.*;
import javafx.collections.*;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.*;
import net.christophermerrill.FancyFxTree.*;

import java.net.*;

/**
 * @author Christopher L Merrill (see LICENSE.txt for license details)
 */
public class FancyTreeExample extends Application
    {
    public static void main(String[] args)
        {
        launch(args);
        }

    @Override
    public void start(Stage stage) throws Exception
        {
        stage.setTitle(getClass().getSimpleName());
        BorderPane root = new BorderPane();

        FlowPane button_bar = new FlowPane();
        button_bar.getChildren().add(createNodeChangeButton());
        _add_node_button = createAddNodeButton();
        button_bar.getChildren().add(_add_node_button);
        button_bar.getChildren().add(createAddLeafNodeButton());
        button_bar.getChildren().add(createStyleNodeButton());
        button_bar.getChildren().add(createExpandAllButton());
        button_bar.getChildren().add(createCollapseAllButton());
        root.setTop(button_bar);

        _model_root = ExampleDataNodeBuilder.create(new int[] {4,1,3,2});
        _tree = new FancyTreeView(new ExampleOperationHandler(_model_root)
            {
            @Override
            public void selectionChanged(ObservableList<TreeItem<ExampleTreeNodeFacade>> selected_items)
                {
                super.selectionChanged(selected_items);
                _status.setText(String.format("%d items selected", selected_items.size()));
                _add_node_button.setDisable(selected_items.size() != 1);
                }
            });
        _tree.setRoot(new ExampleTreeNodeFacade(_model_root));
        _tree.expandAll();
        _tree.setEditable(true);
        root.setCenter(_tree);

        _status = new Label();
        root.setBottom(_status);

        URL resource = getClass().getResource("FancyTreeExample.css");
        _tree.getStylesheets().add(resource.toExternalForm());

        stage.setScene(new Scene(root, 300, 250));
        stage.show();
        }

    private Button createNodeChangeButton()
        {
        Button button = new Button();
        button.setText("Change a node");
        button.setOnAction(event ->
            {
            ExampleDataNode node = _model_root.pickRandom();
            if (node.getExtraData() == null)
                node.setExtraData("modified");
            else
                node.setExtraData(null);
            });
        return button;
        }

    private Button createAddNodeButton()
        {
        Button button = new Button();
        button.setText("Add a node");
        button.setOnAction(event ->
            {
            MultipleSelectionModel<TreeItem<ExampleTreeNodeFacade>> selectionModel = _tree.getSelectionModel();
            ExampleDataNode node = selectionModel.getSelectedItem().getValue().getModelNode();
            ExampleDataNode parent = _model_root.findParentFor(node);
            parent.addAfter(new ExampleDataNode("after " + node.getName()), node);
            });
        button.setDisable(true);
        return button;
        }

    private Button createAddLeafNodeButton()
        {
        Button button = new Button();
        button.setText("Add a leaf");
        button.setOnAction(event ->
            {
            ExampleDataNode leaf = ExampleDataNodeBuilder.createRandomLeaf(_model_root);
            _tree.expandScrollToAndSelect(leaf);
            });
        return button;
        }

    private Button createStyleNodeButton()
        {
        Button button = new Button();
        button.setText("Style the node");
        button.setOnAction(event ->
	        Platform.runLater(() ->
		        {
		        final ObservableList items = _tree.getSelectionModel().getSelectedItems();
		        for (Object item : items)
			        {
			        ExampleTreeNodeFacade node = ((TreeItem<ExampleTreeNodeFacade>) item).getValue();
			        ExampleDataNode data = node.getModelNode();
			        if (data.getStyles().isEmpty())
				        data.addStyle(STYLE1);
			        else
				        {
				        String current_style = data.getStyles().get(0);
				        switch (current_style)
					        {
					        case STYLE1:
						        data.addStyle(STYLE2);
						        break;
					        case STYLE2:
						        data.addStyle(STYLE3);
						        break;
					        }
				        data.removeStyle(current_style);
				        }
			        }
		        }));
        return button;
        }

    private Button createExpandAllButton()
        {
        Button button = new Button();
        button.setText("Expand All");
        button.setOnAction(event -> _tree.expandAll());
        return button;
        }

    private Button createCollapseAllButton()
        {
        Button button = new Button();
        button.setText("Collapse All");
        button.setOnAction(event -> _tree.collapseAll());
        return button;
        }

    private ExampleDataNode _model_root;
    private Button _add_node_button;
    private FancyTreeView<ExampleTreeNodeFacade> _tree;
    private Label _status;

    private final static String STYLE1 = "customstyle1";
    private final static String STYLE2 = "customstyle2";
    private final static String STYLE3 = "customstyle3";
    }


text:
TEST_CASE("Tests the scanner with Pattern (new version)", "[sigscanner]") {
    auto readFile = MPSig::Utils::ReadFileBinary("test_data/example.bin");
    char* ptr = &readFile[0];
    gsl::span<const char> data(readFile);
    MPSig::SigScannerMemoryData emulatedMemData(data);

    MPSig::SigScanner scanner(emulatedMemData);
    std::intptr_t offset = reinterpret_cast<std::intptr_t>(ptr);

    scanner.SetFunctionStartPattern(MPSig::SearchPatternBuilder().HasHexPattern("55 8B EC").Compile());

    // Single start function signature, single normal signature
    MPSig::SearchPattern movEntry =
        MPSig::SearchPatternBuilder()
            .HasHexPattern(gsl::ensure_z("68 ?? ?? ?? ??")).Compile();
    std::pair<std::intptr_t, std::intptr_t> scanResult = scanner.Scan(movEntry);
    REQUIRE(scanResult.first == 8u + offset);
    REQUIRE(scanResult.second == 2u + offset);

    // Single start function signature, multiple normal signature
    MPSig::SearchPattern nopEntry1 =
        MPSig::SearchPatternBuilder()
            .HasHexPattern(gsl::ensure_z("90 68")).Compile();
    MPSig::SearchPattern nopEntry2 =
        MPSig::SearchPatternBuilder()
            .HasHexPattern(gsl::ensure_z("90 C9")).Compile();
    std::pair<std::intptr_t, std::intptr_t> nopScanResult = scanner.Scan({ nopEntry1, nopEntry2 });
    REQUIRE(nopScanResult.first == 7u + offset);
    REQUIRE(nopScanResult.second == 2u + offset);

    // Function signature which does not exist in the example
    MPSig::SearchPattern notExistingEntry =
        MPSig::SearchPatternBuilder()
            .HasHexPattern(gsl::ensure_z("01 02 03 04")).Compile();
    std::pair<std::intptr_t, std::intptr_t> invalidResult = scanner.Scan(notExistingEntry);
    REQUIRE(invalidResult.first == 0);
    REQUIRE(invalidResult.second == 0);

}


text:
!> @brief   Functions and types for string manipulation
module fplus_strings
    use, intrinsic :: iso_c_binding
    use fplus_object
    use fplus_hashcode
    implicit none

    !> @brief   A simple container for character strings
    type, extends(object) :: string
        !> @brief   the actual string content
        character (len=1000), public :: chars
    contains
        !> @brief   copy a c-string to this string object
        procedure, public :: set_cstr => string_set_cstr
        !> @brief   Returns a string representation of this object
        procedure, public :: to_string => string_to_string
        !> @brief   Calculate the hash code for this object
        procedure, public :: hashcode => string_hashcode
    end type

contains

    !> @public
    !> @brief       Calculate the hash code for this object
    function string_hashcode(this) result (res)
        class (string) :: this
        integer (kind=8) :: res

        ! local variables
        character (len=:), allocatable :: str
        integer (kind=1), dimension(:), allocatable :: chars
        integer :: l

        str = "String" // trim(this%chars)

        l = len(str)
        allocate(chars(l))
        chars = transfer(str, chars)
        call C_sdbm(chars, l, res)
    end function

    !> @public
    !> @brief       Returns a string representation of this object
    function string_to_string(this) result (res)
        class(string) :: this
        character (len=:), allocatable :: res
        res = trim(this%chars)
    end function

    !> @brief   determine the number of digits in a number, a negative number has one digit more
    function ndigits_of_integer(number) result(ndigits)
        integer :: ndigits
        class(*) :: number
        select type (number)
            type is (integer (kind=4))
                if (number > 0) then
                    ndigits = floor(log10(real(number)))+1
                else if (number == 0) then
                    ndigits = 1
                else if (number < 0) then
                    ndigits = floor(log10(real(abs(number))))+2
                end if
            type is (integer (kind=8))
                if (number > 0) then
                    ndigits = floor(log10(real(number)))+1
                else if (number == 0) then
                    ndigits = 1
                else if (number < 0) then
                    ndigits = floor(log10(real(abs(number))))+2
                end if
            class default
                ndigits = 0
        end select
    end function

    !> @brief   Convert all number typs to strings
    function number_to_string(number, format) result(res)
        character (len=:), allocatable :: res
        character (len=*), intent(in), optional :: format
        class(*) :: number

        ! local variables
        character (len=100) :: temp
        integer :: ndigits

        ! create the number string depending on the format
        select type (number)
            type is (real (kind=4))
                if (present(format)) then
                    write(temp, format) number
                else
                    write(temp, *) number
                end if
            type is (real (kind=8))
                if (present(format)) then
                    write(temp, format) number
                else
                    write(temp, *) number
                end if
            type is (integer (kind=4))
                if (present(format)) then
                    write(temp, format) number
                else
                    write(temp, *) number
                end if
            type is (integer (kind=8))
                if (present(format)) then
                    write(temp, format) number
                else
                    write(temp, *) number
                end if
            class default
                res = "unknown type in number_to_string"
        end select
        res = trim(adjustl(temp))
    end function

    !> @brief   Returns a string representation of intrinsic types and types that extend
    !>          the abstract type object with the to_string method
    function type_to_string(val) result(res)
        character (len=:), allocatable :: res
        class(*) :: val

        select type (val)
            type is (real (kind=4))
                res = number_to_string(val)
            type is (real (kind=8))
                res = number_to_string(val)
            type is (integer (kind=4))
                res = number_to_string(val)
            type is (integer (kind=8))
                res = number_to_string(val)
            type is (character (len=*))
                res = val
            type is (logical)
                if (val .eqv. .true.) then
                    res = "T"
                else
                    res = "F"
                end if
            class is (object)
                res = val%to_string()
            class default
                res = "unknown type in type_to_string"
        end select
    end function

    !> @brief   copy a c-string to this string object
    subroutine string_set_cstr(this, cstr)
        class(string) :: this
        character (kind=C_char) :: cstr(*)

        ! local variables
        integer :: i
        logical :: in_cstr

        ! loop over the length of this string
        in_cstr = .true.
        do i = 1, len(this%chars)
            if (cstr(i) == C_null_char) then
                in_cstr = .false.
            end if
            if (in_cstr) then
                this%chars(i:i) = cstr(i)
            else
                this%chars(i:i) = ' '
            end if
        end do
    end subroutine

end module fplus_strings


text:
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Dummy</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    {{content-for "head"}}
    <link href='https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,300' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="assets/vendor.css">
    <link rel="stylesheet" href="styles/app.css">

    {{content-for "head-footer"}}
  </head>
  <body>
    {{content-for "body"}}

    <script src="assets/vendor.js"></script>
    <script src="assets/dummy.js"></script>

    {{content-for "body-footer"}}
  </body>
</html>


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="p1.p3">
    <application android:icon="@drawable/icon">
    </application>
</manifest>


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>The GNU C Library: Obstack Chunks</title>

<meta name="description" content="The GNU C Library: Obstack Chunks">
<meta name="keywords" content="The GNU C Library: Obstack Chunks">
<meta name="resource-type" content="document">
<meta name="distribution" content="global">
<meta name="Generator" content="makeinfo">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link href="index.html#Top" rel="start" title="Top">
<link href="Concept-Index.html#Concept-Index" rel="index" title="Concept Index">
<link href="index.html#SEC_Contents" rel="contents" title="Table of Contents">
<link href="Obstacks.html#Obstacks" rel="up" title="Obstacks">
<link href="Summary-of-Obstacks.html#Summary-of-Obstacks" rel="next" title="Summary of Obstacks">
<link href="Obstacks-Data-Alignment.html#Obstacks-Data-Alignment" rel="prev" title="Obstacks Data Alignment">

Next: Summary of Obstacks, Previous: Obstacks Data Alignment, Up: Obstacks   [Contents][Index]

3.2.4.10 Obstack Chunks

Obstacks work by allocating space for themselves in large chunks, and
then parceling out space in the chunks to satisfy your requests.  Chunks
are normally 4096 bytes long unless you specify a different chunk size.
The chunk size includes 8 bytes of overhead that are not actually used
for storing objects.  Regardless of the specified size, longer chunks
will be allocated when necessary for long objects.

The obstack library allocates chunks by calling the function
obstack_chunk_alloc, which you must define.  When a chunk is no
longer needed because you have freed all the objects in it, the obstack
library frees the chunk by calling obstack_chunk_free, which you
must also define.

These two must be defined (as macros) or declared (as functions) in each
source file that uses obstack_init (see Creating Obstacks).
Most often they are defined as macros like this:

#define obstack_chunk_alloc malloc
#define obstack_chunk_free free

Note that these are simple macros (no arguments).  Macro definitions with
arguments will not work!  It is necessary that obstack_chunk_alloc
or obstack_chunk_free, alone, expand into a function name if it is
not itself a function name.

If you allocate chunks with malloc, the chunk size should be a
power of 2.  The default chunk size, 4096, was chosen because it is long
enough to satisfy many typical requests on the obstack yet short enough
not to waste too much memory in the portion of the last chunk not yet used.

Macro: int obstack_chunk_size (struct obstack *<var>obstack-ptr</var>)

Preliminary:
| MT-Safe
| AS-Safe
| AC-Safe
| See POSIX Safety Concepts.

This returns the chunk size of the given obstack.

Since this macro expands to an lvalue, you can specify a new chunk size by
assigning it a new value.  Doing so does not affect the chunks already
allocated, but will change the size of chunks allocated for that particular
obstack in the future.  It is unlikely to be useful to make the chunk size
smaller, but making it larger might improve efficiency if you are
allocating many objects whose size is comparable to the chunk size.  Here
is how to do so cleanly:

if (obstack_chunk_size (obstack_ptr) < <var>new-chunk-size</var>)
  obstack_chunk_size (obstack_ptr) = <var>new-chunk-size</var>;

Next: Summary of Obstacks, Previous: Obstacks Data Alignment, Up: Obstacks   [Contents][Index]


text:
<?php

namespace IronBound\DB\Query;

/**
 * Interface Scope
 *
 * @package IronBound\DB\Query
 */
interface Scope {

	/**
	 * Apply this global scope to a given query.
	 *
	 * @since 2.0
	 *
	 * @param FluentQuery $query
	 */
	public function apply( FluentQuery $query );
}


text:
comments: true
date: 2009-07-27 13:04:57
layout: post
slug: smarter-than-the-average-bear
title: Smarter Than The Average Bear
wordpress_id: 190
tags:
- bears
- nytimes
---

> It was built to be impenetrable, from its "super rugged transparent polycarbonate housing" to its intricate double-tabbed lid that would keep campers' food in and bears' paws out.

The [BearVault 500](http://www.bearvault.com/bearvault_details.php) withstood the ravages of the test bears at the Folsom City Zoo in California. It has stymied mighty grizzlies weighing up to 1,000 pounds in the backcountry of Yellowstone National Park.

But in one corner of the Adirondacks, campers started to notice that the BearVault, a popular canister designed to keep food and other necessities safe, was being compromised. First through circumstantial evidence, then from witness reports, it became clear that in most cases, the conqueror was a relatively tiny, extremely shy middle-aged black bear named Yellow-Yellow.

...

Ben Tabor, a state wildlife technician who has tracked Yellow-Yellow, said the evidence on the canister supports that theory. He watched her tackle a BearVault two years ago, although he was too far away to determine her method.  He doubts, however, that she has out-of-the-ordinary intelligence. "I don't think she's smarter than most bears," he said. "I think she's had more time to learn."

via [Bears in the Adirondacks Defeat BearVault Food-Protection Container - NYTimes.com](http://www.nytimes.com/2009/07/25/nyregion/25bear.html?em=&pagewanted=print).

Where there's a will, there's a way.  A good lesson in persistence.


text:
require 'spec_helper'

describe Shoulda::Matchers::ActionController::RouteMatcher, type: :controller do
  context 'given a controller with a defined glob url' do
    it 'accepts glob route' do
      controller = define_controller('Examples').new

      define_routes do
        get 'examples/*id', to: 'examples#example'
      end

      expect(controller).to route(:get, '/examples/foo/bar').
        to(action: 'example', id: 'foo/bar')
    end
  end

  context 'given a controller with a defined route' do

    it 'accepts routing the correct path to the correct parameters' do
      expect(route_examples_to_examples).to route(:get, '/examples/1').
        to(action: 'example', id: '1')
    end

    it 'accepts a symbol controller' do
      route_examples_to_examples
      expect(Object.new).to route(:get, '/examples/1').
        to(controller: :examples, action: 'example', id: '1')
    end

    it 'accepts a symbol action' do
      expect(route_examples_to_examples).to route(:get, '/examples/1').
        to(action: :example, id: '1')
    end

    it 'accepts a non-string parameter' do
      expect(route_examples_to_examples).to route(:get, '/examples/1').
        to(action: 'example', id: 1)
    end

    it 'rejects an undefined route' do
      expect(route_examples_to_examples).
        not_to route(:get, '/bad_route').to(var: 'value')
    end

    it 'rejects a route for another controller' do
      route_examples_to_examples
      other = define_controller('Other').new
      expect(other).not_to route(:get, '/examples/1').
        to(action: 'example', id: '1')
    end

    it 'rejects a route for different parameters' do
      expect(route_examples_to_examples).not_to route(:get, '/examples/1').
        to(action: 'other', id: '1')
    end

    it "accepts a string as first parameter" do
      expect(route_examples_to_examples).to route(:get, '/examples/1').
        to("examples#example", id: '1')
    end

    def route_examples_to_examples
      define_routes do
        get 'examples/:id', to: 'examples#example'
      end

      define_controller('Examples').new
    end
  end
end


text:
class Lights::Pattern::Fade < Lights::Pattern

	def run
		while true
			client.set_pixels(pixels.map{|i| [rand(255), rand(255), rand(255)] }.flatten, 0)
			sleep 2
		end
	end

end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Prim. fl. holsat. (Kiliae) 106 (1780)

#### Original name
Patella stercorea F.H. Wigg.

### Remarks
null


text:
ICON_SRC=../../src/qt/res/icons/barnacoin.png
ICON_DST=../../src/qt/res/icons/barnacoin.ico
convert ${ICON_SRC} -resize 16x16 barnacoin-16.png
convert ${ICON_SRC} -resize 32x32 barnacoin-32.png
convert ${ICON_SRC} -resize 48x48 barnacoin-48.png
convert barnacoin-16.png barnacoin-32.png barnacoin-48.png ${ICON_DST}


text:
(function() {
  'use strict';

  angular.module('horizon.framework.conf')

  .factory('horizon.framework.conf.resource-type-registry.service', registryService);

  registryService.$inject = [
    'horizon.framework.util.extensible.service'
  ];

  /*
   * @ngdoc service
   * @name horizon.framework.conf.resource-type-registry.service
   * @description
   * This service provides a registry which allows for registration of
   * configurations for resource types.  The purpose of these registrations
   * is to make it easy for modules to register a variety of common features
   * that are used both in display and behavior related to resource types.
   * Ideally the primary members of a resource type are decided on by
   * the community; however it is possible using a configuration to add
   * all kinds of members to the resource type.
   * Common elements in resource type configurations include things like
   * batch and item actions, which are associated with the resource type
   * via a key.  The key follows the format: OS::Glance::Image.
   * The functions that are exposed both assist with registration and also
   * provide utilities relevant for their consumption.
   * This service uses the extensibility service to decorate the individual
   * containers for the actions, so they may be best manipulated via its
   * decorated methods.
   * The concept for use is to register actions with the resource types at
   * the Angular module level, using the .run() function.  This allows
   * actions to be configured by any module.
   * Actions should not perform complex actions in their construction, for
   * example API calls, because as injectables their constructor is run
   * during injection, meaning API calls would be executed as the module
   * is initialized.  This would mean those calls would be executed on any
   * Angular context initialization, such as going to the login page.  Actions
   * should instead place such code in their initScope() functions.
   */
  function registryService(extensibleService) {

    function ResourceType() {
      // 'properties' contains information about properties associated with
      // this resource type.  The expectation is that the key is the 'code'
      // name of the property and the value conforms to the standard
      // described in the setProperty() function below.
      var properties = {};
      this.setProperty = setProperty;
      this.getName = getName;
      this.label = label;
      this.format = format;

      // itemActions is a list of actions that can be executed upon a single
      // item.  The list is made extensible so it can be added to independently.
      this.itemActions = [];
      extensibleService(this.itemActions, this.itemActions);

      // batchActions is a list of actions that can be executed upon multiple
      // items.  The list is made extensible so it can be added to independently.
      this.batchActions = [];
      extensibleService(this.batchActions, this.batchActions);

      /**
       * @ngdoc function
       * @name setProperty
       * @description
       * Adds a property to the resource type object.  Replaces any existing
       * definition.  These calls can be chained to other ResourceType
       * functions.  Specific information about the logic and evaluation of
       * the property attributes is more fully described in the
       * format() function.
       * @example
       ```
       resourceType.setProperty("kernel_id", {
         label: gettext("Kernel ID")  // just provides the label.
                                      // values will be shown directly
       })
         .setproperty("disk_size", {
           label: gettext("disk size"),
           value_function: function(size) {      // uses function to
             return interpolate("%s GiB", size); // display values.
           }
         })
         .setproperty("disk_size", {
           label: gettext("disk size"),
           value_function: [
             function(size) {                      // uses multiple
               return input.replace(/-/, ' ');     // functions in sequence
             },                                    // to display values.
             function(input) {
               return input.toUpperCase();
             }
           ]
         })
         .setProperty("status", {
           label: gettext("Status"),
           value_mapping: {                  // uses mapping to
             ready: gettext("Ready"),        // look up values
             waiting: gettext("Waiting")
           },
           default_value: gettext("Unknown") // uses default if no match
         })
         .setProperty("state", {
           label: gettext("State"),
           value_mapping: {                  // uses mapping to
             initial: gettext("Initial"),    // look up values
             running: gettext("Running")
           },
           default_function: function(input) { // uses function if no match
             return input.toUpperCase();
           }
         })
          )
       ```
       */
      function setProperty(name, prop) {
        properties[name] = prop;
        return this;
      }

      /**
       * @ngdoc function
       * @name getName
       * @description
       * Given a count, returns the appropriate name (e.g. singular or plural)
       * @example
       ```
       var resourceType = getResourceType('thing', {
         names: [gettext('Thing'), gettext('Things')]
       });

       var singleName = resourceType.getName(1); // returns singular
       ```
       */
      function getName(count) {
        if (this.names) {
          return ngettext.apply(null, this.names.concat([count]));
        }
      }

      /**
       * @ngdoc function
       * @name label
       * @description
       * Returns a human-appropriate label for the given name.
       * @example
       ```
       var name = resourceType.propLabel('disk_format'); // Yields 'Disk Format'
       ```
       */
      function label(name) {
        var prop = properties[name];
        if (angular.isDefined(prop) && angular.isDefined(prop.label)) {
          return prop.label;
        }
        return name;
      }

      /**
       * @ngdoc function
       * @name format
       * @description
       * Returns a well-formatted value given a property name and an
       * associated value.
       * The formatting is determined by evaluating various options on the
       * property.
       *
       * 'value_function' provides a single or a list of functions that will
       * evaluate the source value as input and return output; or in the case
       * of multiple functions, will chain the output of one to the input of
       * the next.
       *
       * 'value_mapping' provides a hash where, if a matching key is found,
       * the value is returned.  If no matching key is found, then if
       * 'value_mapping_default_function' is present, the value is passed
       * to the function and the result is returned.  Finally, if there was
       * no matching key and no default function, 'value_mapping_default_value'
       * provides a string to be returned.
       *
       * If these options are not present, the original value is returned.
       * value.
       * @example
       ```
       var value = resourceType.format('disk_size', 12); // Yields '12 GiB'
       ```
       */
      function format(name, value) {
        var prop = properties[name];
        if (angular.isUndefined(prop)) {
          // no property definition; return the original value.
          return value;
        } else if (prop.value_function) {
          if (angular.isArray(prop.value_function)) {
            return prop.value_function.reduce(function execEach(prev, func) {
              return func(prev);
            }, value);
          } else {
            return prop.value_function(value);
          }
        } else if (prop.value_mapping) {
          if (angular.isDefined(prop.value_mapping[value])) {
            return prop.value_mapping[value];
          } else if (angular.isDefined(prop.value_mapping_default_function)) {
            return prop.value_mapping_default_function(value);
          } else if (angular.isDefined(prop.value_mapping_default_value)) {
            return prop.value_mapping_default_value;
          }
        }
        // defaults to simply returning the original value.
        return value;
      }
    }

    var resourceTypes = {};
    var registry = {
      getResourceType: getResourceType,
      initActions: initActions
    };

    /*
     * @ngdoc function
     * @name getResourceType
     * @description
     * Retrieves all information about a resource type.  If the resource
     * type doesn't exist in the registry, this creates a new entry.
     * If a configuration is supplied, the resource type is extended to
     * use the configuration's properties.
     */
    function getResourceType(type, config) {
      if (!resourceTypes.hasOwnProperty(type)) {
        resourceTypes[type] = new ResourceType();
      }
      if (angular.isDefined(config)) {
        angular.extend(resourceTypes[type], config);
      }
      return resourceTypes[type];
    }

    /*
     * @ngdoc function
     * @name initActions
     * @description
     * Performs initialization (namely, scope-setting) of all actions
     * for the given type.  This requires the proper scope be passed.
     * If an action does not have an initScope() function, it is ignored.
     */
    function initActions(type, scope) {
      angular.forEach(resourceTypes[type].itemActions, setActionScope);
      angular.forEach(resourceTypes[type].batchActions, setActionScope);

      function setActionScope(action) {
        if (action.service.initScope) {
          action.service.initScope(scope.$new());
        }
      }
    }

    return registry;
  }

})();