text:
#include "FMDisplayItem.h"
#import <OpenGL/gl.h>

#ifndef MAX
#define MAX(a, b) ((a)>(b)?(a):(b))
#endif

#ifndef MIN
#define MIN(a, b) ((a)<(b)?(a):(b))
#endif

#define kFMMaxItemHeight 768
#define kFMMaxItemWidth 1024
#define kFMDisplayItemStringMaxLength 256

struct FMDisplayItem
{
	int id;

	float x;
	float y;

	FMDisplayItemAlignmentFlags alignment;

	CFStringRef text;

	float timeToDie;
	float fadeTime;

	int bitmapWidth;
	int bitmapHeight;
	UInt8 *bitmapData;

	CGFloat textSize;
	CFMutableDictionaryRef textStyle;
	CTLineRef textLine;

	CGFloat textOffsetX, textOffsetY;

	// graphics
	Boolean graphicsSetUp;
	GLuint texName;
	Boolean textureDirty;
	CGContextRef bitmapCtx;
	CGColorSpaceRef colorSpace;

};

float FadeOutValueForTime(float timeRemaining, float fadeDuration);
int u_strncmp(UniChar *s1, UniChar *s2, int strLen);

// private API
int FMDisplayItemGetBitmapWidth(FMDisplayItemRef item);
int FMDisplayItemGetBitmapHeight(FMDisplayItemRef item);
void FMDisplayItemSetBitmapSize(FMDisplayItemRef item, int width, int height);
void FMDisplayItemRenderText(FMDisplayItemRef item);
void FMSetStyleTextSize(CFMutableDictionaryRef style, CGFloat size);

// item creation API
FMDisplayItemRef FMDisplayItemCreate()
{
	static int nextID = 0;
	FMDisplayItemRef newItem = calloc(1, sizeof(struct FMDisplayItem));

	newItem->id = nextID++;

	newItem->x = 0.0;
	newItem->y = 0.0;

	newItem->alignment = kFMDisplayItemLeft | kFMDisplayItemBottom;

	newItem->text = NULL;

	newItem->timeToDie = 0.0;
	newItem->fadeTime = 0.0;

	newItem->bitmapData = NULL;
	newItem->texName = 0;

	FMDisplayItemSetBitmapSize(newItem, 100, 20);

	newItem->graphicsSetUp = FALSE;
	newItem->colorSpace = NULL;
	newItem->textureDirty = TRUE;

	// setup style
	newItem->textSize = 12.0; // default
	CFMutableDictionaryRef style;
	style = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);

	// white text
	CFDictionarySetValue(style, kCTForegroundColorAttributeName, CGColorGetConstantColor(kCGColorWhite));

	// outlined with black
	CGFloat strokeWidthF = -1.5;
	CFNumberRef strokeWidth = CFNumberCreate(kCFAllocatorDefault, kCFNumberCGFloatType, &strokeWidthF);
	CFDictionarySetValue(style, kCTStrokeWidthAttributeName, strokeWidth);
	CFRelease(strokeWidth);

	CFDictionarySetValue(style, kCTStrokeColorAttributeName, CGColorGetConstantColor(kCGColorBlack));

	// system UI size N font
	FMSetStyleTextSize(style, newItem->textSize);

	newItem->textStyle = style;
	newItem->textLine = NULL;
	FMDisplayItemSetStringValueCFString(newItem, CFSTR("")); // will setup the text line

	return newItem;
}

void FMDisplayItemDelete(FMDisplayItemRef item)
{
	CFRelease(item->textStyle);
	if (item->graphicsSetUp) FMDisplayItemCleanupGraphics(item);
	free(item->bitmapData);
	free(item);
}

void FMDisplayItemSetPosition(FMDisplayItemRef item, float newX, float newY)
{
	item->x = newX;
	item->y = newY;
}

float FMDisplayItemGetFadeTime(FMDisplayItemRef item)
{
	return item->fadeTime;
}
void FMDisplayItemSetFadeTime(FMDisplayItemRef item, float newFadeTime)
{
	item->fadeTime = newFadeTime;
}

float FMDisplayItemGetTimeToDie(FMDisplayItemRef item)
{
	return item->timeToDie;
}
void FMDisplayItemSetTimeToDie(FMDisplayItemRef item, float newTime)
{
	item->timeToDie = newTime;
}

CGFloat FMDisplayItemGetTextSize(FMDisplayItemRef item)
{
	return item->textSize;
}

void FMDisplayItemSetTextSize(FMDisplayItemRef item, CGFloat inSize)
{
	CGFloat oldSize = FMDisplayItemGetTextSize(item);

	item->textSize = inSize;

	if (oldSize != FMDisplayItemGetTextSize(item))
	{
		FMSetStyleTextSize(item->textStyle, item->textSize);

		item->textureDirty = TRUE;
	}
}

void FMSetStyleTextSize(CFMutableDictionaryRef style, CGFloat size) {
	CTFontRef font = CTFontCreateUIFontForLanguage(kCTFontEmphasizedSystemFontType, size, NULL);

	CFDictionarySetValue(style, kCTFontAttributeName, font);
	CFRelease(font);
}

void FMDisplayItemStep(FMDisplayItemRef item, float deltaT)
{
	if (item->timeToDie > 0.0)
	{
		item->timeToDie -= deltaT;
		if (item->timeToDie < 0.0) item->timeToDie = 0.0;
	}

}

float FMDisplayItemAlpha(FMDisplayItemRef item)
{
	return FadeOutValueForTime(item->timeToDie, item->fadeTime);
}

int FMDisplayItemGetBitmapWidth(FMDisplayItemRef item)
{
	return item->bitmapWidth;
}

int FMDisplayItemGetBitmapHeight(FMDisplayItemRef item)
{
	return item->bitmapHeight;
}

void FMDisplayItemSetBitmapSize(FMDisplayItemRef item, int width, int height)
{
	height = height > kFMMaxItemHeight ? kFMMaxItemHeight : height;
	width = width > kFMMaxItemWidth ? kFMMaxItemWidth : width;

	if (width > item->bitmapWidth || height > item->bitmapHeight)
	{
		item->bitmapHeight = height;
		item->bitmapWidth = width;

		if (item->bitmapData) free(item->bitmapData);

		item->bitmapData = calloc(item->bitmapHeight * item->bitmapWidth, 4*sizeof(UInt8));

		if (item->graphicsSetUp)
		{
			CGContextRelease(item->bitmapCtx);

			item->bitmapCtx = CGBitmapContextCreate(item->bitmapData,
													item->bitmapWidth,
													item->bitmapHeight,
													8, // bits per component
													item->bitmapWidth*4,
													item->colorSpace,
													kCGImageAlphaPremultipliedLast);

			item->textureDirty = TRUE;
		}
	}
}

void FMDisplayItemSetStringValueMacRoman(FMDisplayItemRef item, const char *newText)
{
	int stringLength;

	stringLength = MIN(kFMDisplayItemStringMaxLength, strlen(newText));

	// convert from MacRoman to UTF-16
	CFStringRef uniString = CFStringCreateWithBytes(NULL, (UInt8 *)newText, stringLength, kCFStringEncodingMacRoman, TRUE);

	FMDisplayItemSetStringValueCFString(item, uniString);

	CFRelease(uniString);
}

void FMDisplayItemSetStringValueCFString(FMDisplayItemRef item, CFStringRef str)
{
	// set the text field
	if (item->text) {
		CFRelease(item->text);
		item->text = NULL;
	}

	if (str) {
		item->text = CFStringCreateCopy(kCFAllocatorDefault, str);
	}

	// set the line field
	if (item->textLine) {
		CFRelease(item->textLine);
		item->textLine = NULL;
	}

	if (item->text) {
		CFAttributedStringRef attributedString = CFAttributedStringCreate(kCFAllocatorDefault, item->text, item->textStyle);
		item->textLine = CTLineCreateWithAttributedString(attributedString);
		CFRelease(attributedString);
	}

	// mark the texture as needing to be updated
	item->textureDirty = TRUE;
}

void FMDisplayItemSetTextAlignment(FMDisplayItemRef item, FMDisplayItemAlignmentFlags flags)
{
	item->alignment = flags;

	item->textureDirty = TRUE;
}

void FMDisplayItemSetTextureDirty(FMDisplayItemRef item, Boolean flag)
{
	item->textureDirty = flag;
}

void FMDisplayItemSetupGraphics(FMDisplayItemRef item)
{
	if (!item->graphicsSetUp)
	{
		item->graphicsSetUp = TRUE;

		glGenTextures(1, &(item->texName));

		item->colorSpace = CGColorSpaceCreateDeviceRGB();
		if (item->colorSpace == NULL) fprintf(stderr, "Fountain Music Error: Could not create color space!\n");

		item->bitmapCtx = CGBitmapContextCreate(item->bitmapData,
											    item->bitmapWidth,
											    item->bitmapHeight,
											    8, // bits per component
											    item->bitmapWidth*4,
											    item->colorSpace,
											    kCGImageAlphaPremultipliedLast);
		if (item->bitmapCtx == NULL) fprintf(stderr, "Fountain Music Error: Could not create bitmap context!\n");

		item->textureDirty = TRUE;
	}
}

void FMDisplayItemCleanupGraphics(FMDisplayItemRef item)
{
	if (item->graphicsSetUp)
	{
		item->graphicsSetUp = FALSE;

		glDeleteTextures(1, &(item->texName));

		CGContextRelease(item->bitmapCtx);
		CGColorSpaceRelease(item->colorSpace);
	}
}

#define TXT_AA_PADDING (2)

void FMDisplayItemRenderText(FMDisplayItemRef item)
{
	if (item->textureDirty && item->graphicsSetUp)
	{
		CGRect textRect;
		CGFloat typoWidth, ascent, descent;

		CGContextSetTextPosition(item->bitmapCtx, 0.0, 0.0);

		// obtain text metrics
		textRect = CTLineGetImageBounds(item->textLine, item->bitmapCtx);
		typoWidth = CTLineGetTypographicBounds(item->textLine, &ascent, &descent, NULL);

		CGFloat offsetX, offsetY;
		int bitmapW, bitmapH;

		offsetX = lround(TXT_AA_PADDING + -textRect.origin.x);
		offsetY = lround(TXT_AA_PADDING + -textRect.origin.y);

		bitmapW = lround(textRect.size.width + 2*TXT_AA_PADDING);
		bitmapH = lround(textRect.size.height + 2*TXT_AA_PADDING);

		item->textOffsetX = -offsetX;
		item->textOffsetY = -offsetY;

		//printf("tf: %f, %f\n", item->textOffsetX, item->textOffsetY);

		if (bitmapW > 0 && bitmapH > 0)
		{
			//
			// first render into bitmap
			//
			// resize bitmap and backing as needed
			FMDisplayItemSetBitmapSize(item, bitmapW, bitmapH);

			// zero the bitmap
			memset(item->bitmapData, 0, item->bitmapHeight * item->bitmapWidth * 4);

			CGContextSetShadow(item->bitmapCtx, CGSizeMake(2.0, -2.0), 1.0);

			CGContextSetTextPosition(item->bitmapCtx, -item->textOffsetX, -item->textOffsetY);
			CTLineDraw(item->textLine, item->bitmapCtx);
			CGContextFlush(item->bitmapCtx);

			//
			// then load the bitmap into the GL texture
			//
			glEnable(GL_TEXTURE_RECTANGLE_EXT);
			glBindTexture(GL_TEXTURE_RECTANGLE_EXT, item->texName);

			glTexImage2D(GL_TEXTURE_RECTANGLE_EXT, 0,
						 GL_RGBA,
						 item->bitmapWidth,
						 item->bitmapHeight,
						 0,
						 GL_RGBA,
						 GL_UNSIGNED_BYTE,
						 item->bitmapData);

			glDisable(GL_TEXTURE_RECTANGLE_EXT);

			item->textureDirty = FALSE;
		}
	}
}

void FMDisplayItemDraw(FMDisplayItemRef item)
{
	if (!item->graphicsSetUp) FMDisplayItemSetupGraphics(item);

	if (item->timeToDie > 0.0)
	{
		FMDisplayItemRenderText(item);

		float px, py;

		px = item->x + item->textOffsetX;
		py = item->y + item->textOffsetY;

		glEnable(GL_TEXTURE_RECTANGLE_EXT);
		glBindTexture(GL_TEXTURE_RECTANGLE_EXT, item->texName);

		// setup good blending for the text texture
		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

		glColor4f(1.0, 1.0, 1.0, FMDisplayItemAlpha(item));

		glBegin(GL_QUADS);

			glTexCoord2f(0.0, 0.0);
			glVertex2f(px, py+item->bitmapHeight);

			glTexCoord2f(item->bitmapWidth, 0.0);
			glVertex2f(px+item->bitmapWidth, py+item->bitmapHeight);

			glTexCoord2f(item->bitmapWidth, item->bitmapHeight);
			glVertex2f(px+item->bitmapWidth, py);

			glTexCoord2f(0.0, item->bitmapHeight);
			glVertex2f(px, py);

		glEnd();

		glDisable(GL_TEXTURE_RECTANGLE_EXT);
	}
}

// other
float FadeOutValueForTime(float timeRemaining, float fadeDuration)
{
    float fraction;

    if (timeRemaining < fadeDuration)
    {
		fraction = timeRemaining/fadeDuration;
    }
    else fraction = 1.0;

    return fraction;
}

int u_strncmp(UniChar *s1, UniChar *s2, int strLen)
{
	int i;
	int cmp;

	for (i=0; i<strLen; i++)
	{
		cmp = s2[i] - s1[i];
		if (cmp != 0) return cmp;
	}

	return 0;
}


text:
namespace cube {

namespace logging {

#define M_GENERATE_LOG_FUNCTION(log_level) \
    void Logger::log_level(const char *format, ...) { \
        if (LogLevel_##log_level >= LoggerLevel()) { \
            va_list args; \
            va_start(args, format); \
            Output(format, args); \
            va_end(args); \
        } \
    }

M_GENERATE_LOG_FUNCTION(Trace);
M_GENERATE_LOG_FUNCTION(Debug);
M_GENERATE_LOG_FUNCTION(Warn);
M_GENERATE_LOG_FUNCTION(Info);
M_GENERATE_LOG_FUNCTION(Error);

#undef M_GENERATE_LOG_FUNCTION

void Logger::Log(const char *format, ...) {
    va_list args;
    va_start(args, format);
    Output(format, args);
    va_end(args);
}

void StdoutLogger::Output(const char *format, va_list args) {
    vprintf(format, args);
}

#ifdef NDEBUG
LoggerPtr g_logger(new EmptyLogger);
#else
LoggerPtr g_logger(new StdoutLogger);
#endif

LogLevel g_logger_level = LogLevel_Trace;

LogLevel LoggerLevel() {
    return g_logger_level;
}

void SetLoggerLevel(LogLevel logger_level) {
    g_logger_level = logger_level;
}

LoggerPtr GetLogger() {
    return g_logger;
}

void SetLogger(LoggerPtr logger) {
    g_logger = logger;
}

}

}

redpajama_set_name: RedPajamaGithub


text:
var newsURL = 'http://www.wopg.org/en/component/foobla_rss/32-news/';
var win = Titanium.UI.currentWindow;

//function loadNews()
function loadNews(){

	var loaderImage =  Titanium.UI.createLabel({
		text:'Loading...',
		color:'#CCC',
		font:{fontWeight:'bold'},
		top:100
	});
	win.add(loaderImage);

	//empty array rowData for out tableView
	var rowData = [];

	//create HTTPClient
	var loader = Titanium.Network.createHTTPClient();

	//send Http request method,and url to get data
	loader.open("GET",newsURL)

	//runs the function when the data is ready for us to process
	loader.onload = function(){
		try{
			var document 	= this.responseXML.documentElement;
			var items		= document.getElementsByTagName("item");
			var docTitle	= document.evaluate("//channel/title/text()").item(0).nodeValue;
			for(var i = 0;i < items.length; i++)
			{
				var item 	= items.item(i);

		        var title = item.getElementsByTagName("title").item(0).text;
		        var row = Ti.UI.createTableViewRow({height:'auto'});
		        var label = Ti.UI.createLabel({
		          		text:title,
		          		left:72,
		          		top:5,
		          		bottom:5,
		          		right:5,
		          		color:'#666'
		        	});
		        	row.add(label);
		        	rowData[i] = row;
		        	row.url = item.getElementsByTagName("link").item(0).text;
		      }
		    win.remove(loaderImage);
			var tableView = Titanium.UI.createTableView({data:rowData});
			win.add(tableView);

		}
		catch(E)
		{
			alert(E);
		}
	}

	//send HTTP request
	loader.send();
}
loadNews();


text:
package com.battlelancer.seriesguide.ui;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.PopupMenu;
import android.widget.TextView;
import com.battlelancer.seriesguide.R;
import com.battlelancer.seriesguide.adapters.CalendarAdapter;
import com.battlelancer.seriesguide.enums.EpisodeFlags;
import com.battlelancer.seriesguide.provider.SeriesGuideContract.Episodes;
import com.battlelancer.seriesguide.settings.CalendarSettings;
import com.battlelancer.seriesguide.settings.DisplaySettings;
import com.battlelancer.seriesguide.ui.dialogs.CheckInDialogFragment;
import com.battlelancer.seriesguide.util.DBUtils;
import com.battlelancer.seriesguide.util.EpisodeTools;
import com.battlelancer.seriesguide.util.Utils;
import com.tonicartos.widget.stickygridheaders.StickyGridHeadersGridView;

/**
 * Displays upcoming or recent episodes in a scrollable grid, by default grouped by day.
 */
public class CalendarFragment extends Fragment implements
        LoaderManager.LoaderCallbacks<Cursor>, OnItemClickListener,
        OnSharedPreferenceChangeListener, AdapterView.OnItemLongClickListener {

    private static final String TAG = "Calendar";

    private static final int CONTEXT_FLAG_WATCHED_ID = 0;

    private static final int CONTEXT_FLAG_UNWATCHED_ID = 1;

    private static final int CONTEXT_CHECKIN_ID = 2;

    private static final int CONTEXT_COLLECTION_ADD_ID = 3;

    private static final int CONTEXT_COLLECTION_REMOVE_ID = 4;

    private StickyGridHeadersGridView mGridView;

    private CalendarAdapter mAdapter;

    private Handler mHandler;

    /**
     * Data which has to be passed when creating {@link CalendarFragment}. All Bundle extras are
     * strings, except LOADER_ID and EMPTY_STRING_ID.
     */
    public interface InitBundle {

        String TYPE = "type";

        String ANALYTICS_TAG = "analyticstag";

        String LOADER_ID = "loaderid";

        String EMPTY_STRING_ID = "emptyid";
    }

    public interface CalendarType {

        String UPCOMING = "upcoming";
        String RECENT = "recent";
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_calendar, container, false);

        TextView emptyView = (TextView) v.findViewById(R.id.emptyViewCalendar);
        emptyView.setText(getString(getArguments().getInt(InitBundle.EMPTY_STRING_ID)));

        mGridView = (StickyGridHeadersGridView) v.findViewById(R.id.gridViewCalendar);
        mGridView.setEmptyView(emptyView);
        mGridView.setAreHeadersSticky(false);

        return v;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        // setup adapter
        mAdapter = new CalendarAdapter(getActivity(), null, 0);
        boolean infiniteScrolling = CalendarSettings.isInfiniteScrolling(getActivity());
        mAdapter.setIsShowingHeaders(!infiniteScrolling);

        // setup grid view
        mGridView.setAdapter(mAdapter);
        mGridView.setOnItemClickListener(this);
        mGridView.setOnItemLongClickListener(this);
        mGridView.setFastScrollEnabled(infiniteScrolling);

        PreferenceManager.getDefaultSharedPreferences(getActivity())
                .registerOnSharedPreferenceChangeListener(this);

        setHasOptionsMenu(true);
    }

    @Override
    public void onResume() {
        super.onResume();

        // prevent stale upcoming/recent episodes, also:
        /**
         * Workaround for loader issues on config changes. For some reason the
         * CursorLoader holds on to a cursor with old data. See
         * https://github.com/UweTrottmann/SeriesGuide/issues/257.
         */
        boolean isLoaderExists = getLoaderManager().getLoader(getLoaderId()) != null;
        getLoaderManager().initLoader(getLoaderId(), null, this);
        if (isLoaderExists) {
            onRequery();
        }
    }

    @Override
    public void onPause() {
        super.onPause();

        // avoid CPU activity
        schedulePeriodicDataRefresh(false);
    }

    @Override
    public void onDestroy() {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
        prefs.unregisterOnSharedPreferenceChangeListener(this);

        super.onDestroy();
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);

        // guard against not attached to activity
        if (!isAdded()) {
            return;
        }

        inflater.inflate(R.menu.calendar_menu, menu);

        // set menu items to current values
        menu.findItem(R.id.menu_onlyfavorites)
                .setChecked(CalendarSettings.isOnlyFavorites(getActivity()));
        menu.findItem(R.id.menu_nospecials)
                .setChecked(DisplaySettings.isHidingSpecials(getActivity()));
        menu.findItem(R.id.menu_nowatched)
                .setChecked(DisplaySettings.isNoWatchedEpisodes(getActivity()));
        menu.findItem(R.id.menu_infinite_scrolling)
                .setChecked(CalendarSettings.isInfiniteScrolling(getActivity()));
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemId = item.getItemId();
        if (itemId == R.id.menu_onlyfavorites) {
            toggleFilterSetting(item, CalendarSettings.KEY_ONLY_FAVORITE_SHOWS);
            fireTrackerEvent("Only favorite shows Toggle");
            return true;
        } else if (itemId == R.id.menu_nospecials) {
            toggleFilterSetting(item, DisplaySettings.KEY_HIDE_SPECIALS);
            fireTrackerEvent("Hide specials Toggle");
            return true;
        } else if (itemId == R.id.menu_nowatched) {
            toggleFilterSetting(item, DisplaySettings.KEY_NO_WATCHED_EPISODES);
            fireTrackerEvent("Hide watched Toggle");
            return true;
        } else if (itemId == R.id.menu_infinite_scrolling) {
            toggleFilterSetting(item, CalendarSettings.KEY_INFINITE_SCROLLING);
            fireTrackerEvent("Infinite Scrolling Toggle");
            return true;
        } else {
            return super.onOptionsItemSelected(item);
        }
    }

    public void checkInEpisode(int episodeTvdbId) {
        CheckInDialogFragment f = CheckInDialogFragment.newInstance(getActivity(), episodeTvdbId);
        if (f != null) {
            f.show(getFragmentManager(), "checkin-dialog");
        }
    }

    private void updateEpisodeCollectionState(int showTvdbId, int episodeTvdbId, int seasonNumber,
            int episodeNumber, boolean addToCollection) {
        EpisodeTools.episodeCollected(getActivity(), showTvdbId, episodeTvdbId, seasonNumber,
                episodeNumber, addToCollection);
    }

    private void updateEpisodeWatchedState(int showTvdbId, int episodeTvdbId, int seasonNumber,
            int episodeNumber, boolean isWatched) {
        EpisodeTools.episodeWatched(getActivity(), showTvdbId, episodeTvdbId, seasonNumber,
                episodeNumber, isWatched ? EpisodeFlags.WATCHED : EpisodeFlags.UNWATCHED);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        int episodeId = (int) id;

        Intent intent = new Intent();
        intent.setClass(getActivity(), EpisodesActivity.class);
        intent.putExtra(EpisodesActivity.InitBundle.EPISODE_TVDBID, episodeId);

        ActivityCompat.startActivity(getActivity(), intent,
                ActivityOptionsCompat
                        .makeScaleUpAnimation(view, 0, 0, view.getWidth(), view.getHeight())
                        .toBundle()
        );
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, final int position,
            final long id) {
        PopupMenu popupMenu = new PopupMenu(view.getContext(), view);
        Menu menu = popupMenu.getMenu();

        Cursor episode = (Cursor) mAdapter.getItem(position);
        if (episode == null) {
            return false;
        }

        // only display the action appropriate for the items current state
        menu.add(0, CONTEXT_CHECKIN_ID, 0, R.string.checkin);
        if (EpisodeTools.isWatched(episode.getInt(CalendarAdapter.Query.WATCHED))) {
            menu.add(0, CONTEXT_FLAG_UNWATCHED_ID, 1, R.string.action_unwatched);
        } else {
            menu.add(0, CONTEXT_FLAG_WATCHED_ID, 1, R.string.action_watched);
        }
        if (EpisodeTools.isCollected(episode.getInt(CalendarAdapter.Query.COLLECTED))) {
            menu.add(0, CONTEXT_COLLECTION_REMOVE_ID, 2, R.string.action_collection_remove);
        } else {
            menu.add(0, CONTEXT_COLLECTION_ADD_ID, 2, R.string.action_collection_add);
        }

        final int showTvdbId = episode.getInt(CalendarAdapter.Query.SHOW_ID);
        final int episodeTvdbId = episode.getInt(CalendarAdapter.Query._ID);
        final int seasonNumber = episode.getInt(CalendarAdapter.Query.SEASON);
        final int episodeNumber = episode.getInt(CalendarAdapter.Query.NUMBER);
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case CONTEXT_CHECKIN_ID: {
                        checkInEpisode((int) id);
                        return true;
                    }
                    case CONTEXT_FLAG_WATCHED_ID: {
                        updateEpisodeWatchedState(showTvdbId, episodeTvdbId, seasonNumber,
                                episodeNumber, true);
                        return true;
                    }
                    case CONTEXT_FLAG_UNWATCHED_ID: {
                        updateEpisodeWatchedState(showTvdbId, episodeTvdbId, seasonNumber,
                                episodeNumber, false);
                        return true;
                    }
                    case CONTEXT_COLLECTION_ADD_ID: {
                        updateEpisodeCollectionState(showTvdbId, episodeTvdbId, seasonNumber,
                                episodeNumber, true);
                        return true;
                    }
                    case CONTEXT_COLLECTION_REMOVE_ID: {
                        updateEpisodeCollectionState(showTvdbId, episodeTvdbId, seasonNumber,
                                episodeNumber, false);
                        return true;
                    }
                }
                return false;
            }
        });

        popupMenu.show();

        return true;
    }

    public void onRequery() {
        getLoaderManager().restartLoader(getLoaderId(), null, this);
    }

    private int getLoaderId() {
        return getArguments().getInt("loaderid");
    }

    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        String type = getArguments().getString(InitBundle.TYPE);
        boolean isInfiniteScrolling = CalendarSettings.isInfiniteScrolling(getActivity());

        // infinite or 30 days activity stream
        String[][] queryArgs = DBUtils.buildActivityQuery(getActivity(), type,
                isInfiniteScrolling ? -1 : 30);

        // prevent upcoming/recent episodes from becoming stale
        schedulePeriodicDataRefresh(true);

        return new CursorLoader(getActivity(), Episodes.CONTENT_URI_WITHSHOW,
                CalendarAdapter.Query.PROJECTION, queryArgs[0][0], queryArgs[1], queryArgs[2][0]);
    }

    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        mAdapter.swapCursor(data);
    }

    public void onLoaderReset(Loader<Cursor> loader) {
        mAdapter.swapCursor(null);
    }

    private void schedulePeriodicDataRefresh(boolean enableRefresh) {
        if (mHandler == null) {
            mHandler = new Handler();
        }
        mHandler.removeCallbacks(mDataRefreshRunnable);
        if (enableRefresh) {
            mHandler.postDelayed(mDataRefreshRunnable, 5 * DateUtils.MINUTE_IN_MILLIS);
        }
    }

    private Runnable mDataRefreshRunnable = new Runnable() {
        @Override
        public void run() {
            if (isAdded()) {
                getLoaderManager().restartLoader(getLoaderId(), null, CalendarFragment.this);
            }
        }
    };

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
        if (CalendarSettings.KEY_INFINITE_SCROLLING.equals(key)) {
            boolean infiniteScrolling = CalendarSettings.isInfiniteScrolling(getActivity());
            mAdapter.setIsShowingHeaders(!infiniteScrolling);
            mGridView.setFastScrollEnabled(infiniteScrolling);
        }
        if (CalendarSettings.KEY_ONLY_FAVORITE_SHOWS.equals(key)
                || DisplaySettings.KEY_HIDE_SPECIALS.equals(key)
                || DisplaySettings.KEY_NO_WATCHED_EPISODES.equals(key)
                || CalendarSettings.KEY_INFINITE_SCROLLING.equals(key)) {
            onRequery();
        }
    }

    private void fireTrackerEvent(String label) {
        Utils.trackAction(getActivity(), TAG, label);
    }

    @SuppressLint("CommitPrefEdits")
    private void toggleFilterSetting(MenuItem item, String key) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
        prefs.edit().putBoolean(key, !item.isChecked()).commit();

        // refresh filter icon state
        getActivity().supportInvalidateOptionsMenu();
    }
}


text:
'Asynchronous distributed Redis-powered lock tests.'

import asyncio
import unittest.mock

import pytest
from redis.asyncio import Redis as AIORedis  # type: ignore
from redis.commands.core import AsyncScript  # type: ignore
from redis.exceptions import TimeoutError

from pottery import AIORedlock
from pottery import ExtendUnlockedLock
from pottery import QuorumNotAchieved
from pottery import Redlock
from pottery import ReleaseUnlockedLock
from pottery.exceptions import TooManyExtensions

@pytest.fixture
def aioredlock(aioredis: AIORedis) -> AIORedlock:  # type: ignore
    return AIORedlock(masters={aioredis}, key='shower')

async def test_locked_acquire_and_release(aioredlock: AIORedlock) -> None:
    assert not await aioredlock.locked()
    assert await aioredlock.acquire()
    assert await aioredlock.locked()
    await aioredlock.release()
    assert not await aioredlock.locked()
    with pytest.raises(ReleaseUnlockedLock):
        await aioredlock.release()

async def test_extend(aioredlock: AIORedlock) -> None:
    with pytest.raises(ExtendUnlockedLock):
        await aioredlock.extend()
    assert await aioredlock.acquire()
    for extension_num in range(Redlock._NUM_EXTENSIONS):
        await aioredlock.extend()
    with pytest.raises(TooManyExtensions):
        await aioredlock.extend()

async def test_context_manager(aioredlock: AIORedlock) -> None:
    assert not await aioredlock.locked()
    async with aioredlock:
        assert await aioredlock.locked()
    assert not await aioredlock.locked()

async def test_context_manager_extend(aioredlock: AIORedlock) -> None:
    with pytest.raises(ExtendUnlockedLock):
        await aioredlock.extend()
    async with aioredlock:
        for extension_num in range(Redlock._NUM_EXTENSIONS):
            await aioredlock.extend()
        with pytest.raises(TooManyExtensions):
            await aioredlock.extend()

async def test_acquire_fails_within_auto_release_time(aioredlock: AIORedlock) -> None:
    aioredlock.auto_release_time = .001
    assert not await aioredlock.acquire(blocking=False)

async def test_context_manager_fails_within_auto_release_time(aioredlock: AIORedlock) -> None:
    aioredlock.auto_release_time = .001
    aioredlock.context_manager_blocking = False
    with pytest.raises(QuorumNotAchieved):
        async with aioredlock:  # pragma: no cover
            ...

async def test_acquire_and_time_out(aioredlock: AIORedlock) -> None:
    aioredlock.auto_release_time = 1
    assert not await aioredlock.locked()
    assert await aioredlock.acquire()
    assert await aioredlock.locked()
    await asyncio.sleep(aioredlock.auto_release_time)
    assert not await aioredlock.locked()

async def test_context_manager_time_out_before_exit(aioredlock: AIORedlock) -> None:
    aioredlock.auto_release_time = 1
    with pytest.raises(ReleaseUnlockedLock):
        async with aioredlock:
            await asyncio.sleep(aioredlock.auto_release_time)
            assert not await aioredlock.locked()

async def test_context_manager_release_before_exit(aioredlock: AIORedlock) -> None:
    with pytest.raises(ReleaseUnlockedLock):
        async with aioredlock:
            await aioredlock.release()

def test_context_manager_nonblocking_with_timeout(aioredis: AIORedis) -> None:  # type: ignore
    with pytest.raises(ValueError):
        AIORedlock(
            masters={aioredis},
            key='shower',
            auto_release_time=.2,
            context_manager_blocking=False,
            context_manager_timeout=.1
        )

async def test_acquire_nonblocking_with_timeout(aioredlock: AIORedlock) -> None:
    with pytest.raises(ValueError):
        await aioredlock.acquire(blocking=False, timeout=.1)

async def test_acquire_rediserror(aioredlock: AIORedlock) -> None:
    aioredis = next(iter(aioredlock.masters))
    with unittest.mock.patch.object(aioredis, 'set') as set:
        set.side_effect = TimeoutError
        assert not await aioredlock.acquire(blocking=False)

async def test_locked_rediserror(aioredlock: AIORedlock) -> None:
    async with aioredlock:
        assert await aioredlock.locked()
        with unittest.mock.patch.object(AsyncScript, '__call__') as __call__:
            __call__.side_effect = TimeoutError
            assert not await aioredlock.locked()

async def test_extend_rediserror(aioredlock: AIORedlock) -> None:
    async with aioredlock:
        await aioredlock.extend()
        with unittest.mock.patch.object(AsyncScript, '__call__') as __call__:
            __call__.side_effect = TimeoutError
            with pytest.raises(ExtendUnlockedLock):
                await aioredlock.extend()

async def test_release_rediserror(aioredlock: AIORedlock) -> None:
    with unittest.mock.patch.object(AsyncScript, '__call__') as __call__:
        __call__.side_effect = TimeoutError
        await aioredlock.acquire()
        with pytest.raises(ReleaseUnlockedLock):
            await aioredlock.release()

async def test_enqueued(aioredlock: AIORedlock) -> None:
    aioredlock.auto_release_time = .2
    aioredis = next(iter(aioredlock.masters))
    aioredlock2 = AIORedlock(masters={aioredis}, key='shower', auto_release_time=.2)

    await aioredlock.acquire()
    # aioredlock2 is enqueued until self.aioredlock is automatically released:
    assert await aioredlock2.acquire()

    await aioredlock.acquire()
    # aioredlock2 is enqueued until the acquire timeout has expired:
    assert not await aioredlock2.acquire(timeout=0.1)

@pytest.mark.parametrize('num_locks', range(1, 11))
async def test_contention(num_locks: int) -> None:
    dbs = range(1, 6)
    urls = [f'redis://localhost:6379/{db}' for db in dbs]
    masters = [AIORedis.from_url(url, socket_timeout=1) for url in urls]
    locks = [AIORedlock(key='shower', masters=masters, auto_release_time=.2) for _ in range(num_locks)]

    try:
        coros = [lock.acquire(blocking=False) for lock in locks]
        tasks = [asyncio.create_task(coro) for coro in coros]
        done, _ = await asyncio.wait(tasks)
        results = [task.result() for task in done]
        num_unlocked = results.count(False)
        num_locked = results.count(True)
        assert num_locks-1 <= num_unlocked <= num_locks
        assert 0 <= num_locked <= 1
        # To see the following output, issue:
        # $ source venv/bin/activate; pytest -rP tests/test_aioredlock.py::test_contention; deactivate
        print(f'{num_locks} locks, {num_unlocked} unlocked, {num_locked} locked')

    finally:
        # Clean up for the next unit test run.
        coros = [lock.release() for lock in locks]  # type: ignore
        tasks = [asyncio.create_task(coro) for coro in coros]
        done, _ = await asyncio.wait(tasks)
        [task.exception() for task in done]

def test_slots(aioredlock: AIORedlock) -> None:
    with pytest.raises(AttributeError):
        aioredlock.__dict__

def test_repr(aioredlock: AIORedlock) -> None:
    assert repr(aioredlock) == '<AIORedlock key=redlock:shower>'


text:
package convert

import (
	"fmt"

	"github.com/spf13/cobra"
	"k8s.io/klog"

	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/runtime/schema"
	"k8s.io/cli-runtime/pkg/genericclioptions"
	"k8s.io/cli-runtime/pkg/printers"
	"k8s.io/cli-runtime/pkg/resource"
	scheme "k8s.io/kubernetes/pkg/api/legacyscheme"
	api "k8s.io/kubernetes/pkg/apis/core"
	cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
	"k8s.io/kubernetes/pkg/kubectl/util/i18n"
	"k8s.io/kubernetes/pkg/kubectl/util/templates"
	"k8s.io/kubernetes/pkg/kubectl/validation"
)

var (
	convertLong = templates.LongDesc(i18n.T(`
		Convert config files between different API versions. Both YAML
		and JSON formats are accepted.

		The command takes filename, directory, or URL as input, and convert it into format
		of version specified by --output-version flag. If target version is not specified or
		not supported, convert to latest version.

		The default output will be printed to stdout in YAML format. One can use -o option
		to change to output destination.`))

	convertExample = templates.Examples(i18n.T(`
		# Convert 'pod.yaml' to latest version and print to stdout.
		kubectl convert -f pod.yaml

		# Convert the live state of the resource specified by 'pod.yaml' to the latest version
		# and print to stdout in JSON format.
		kubectl convert -f pod.yaml --local -o json

		# Convert all files under current directory to latest version and create them all.
		kubectl convert -f . | kubectl create -f -`))
)

// ConvertOptions have the data required to perform the convert operation
type ConvertOptions struct {
	PrintFlags *genericclioptions.PrintFlags
	Printer    printers.ResourcePrinter

	OutputVersion string
	Namespace     string

	builder   func() *resource.Builder
	local     bool
	validator func() (validation.Schema, error)

	resource.FilenameOptions
	genericclioptions.IOStreams
}

func NewConvertOptions(ioStreams genericclioptions.IOStreams) *ConvertOptions {
	return &ConvertOptions{
		PrintFlags: genericclioptions.NewPrintFlags("converted").WithTypeSetter(scheme.Scheme).WithDefaultOutput("yaml"),
		local:      true,
		IOStreams:  ioStreams,
	}
}

// NewCmdConvert creates a command object for the generic "convert" action, which
// translates the config file into a given version.
func NewCmdConvert(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {
	o := NewConvertOptions(ioStreams)

	cmd := &cobra.Command{
		Use:                   "convert -f FILENAME",
		DisableFlagsInUseLine: true,
		Short:                 i18n.T("Convert config files between different API versions"),
		Long:                  convertLong,
		Example:               convertExample,
		Run: func(cmd *cobra.Command, args []string) {
			cmdutil.CheckErr(o.Complete(f, cmd))
			cmdutil.CheckErr(o.RunConvert())
		},
	}

	cmd.Flags().BoolVar(&o.local, "local", o.local, "If true, convert will NOT try to contact api-server but run locally.")
	cmd.Flags().StringVar(&o.OutputVersion, "output-version", o.OutputVersion, i18n.T("Output the formatted object with the given group version (for ex: 'extensions/v1beta1')."))
	o.PrintFlags.AddFlags(cmd)

	cmdutil.AddValidateFlags(cmd)
	cmdutil.AddFilenameOptionFlags(cmd, &o.FilenameOptions, "to need to get converted.")
	return cmd
}

// Complete collects information required to run Convert command from command line.
func (o *ConvertOptions) Complete(f cmdutil.Factory, cmd *cobra.Command) (err error) {
	err = o.FilenameOptions.RequireFilenameOrKustomize()
	if err != nil {
		return err
	}
	o.builder = f.NewBuilder

	o.Namespace, _, err = f.ToRawKubeConfigLoader().Namespace()
	if err != nil {
		return err
	}

	o.validator = func() (validation.Schema, error) {
		return f.Validator(cmdutil.GetFlagBool(cmd, "validate"))
	}

	// build the printer
	o.Printer, err = o.PrintFlags.ToPrinter()
	if err != nil {
		return err
	}
	return nil
}

// RunConvert implements the generic Convert command
func (o *ConvertOptions) RunConvert() error {

	// Convert must be removed from kubectl, since kubectl can not depend on
	// Kubernetes "internal" dependencies. These "internal" dependencies can
	// not be removed from convert. Another way to convert a resource is to
	// "kubectl apply" it to the cluster, then "kubectl get" at the desired version.
	// Another possible solution is to make convert a plugin.
	fmt.Fprintf(o.ErrOut, "kubectl convert is DEPRECATED and will be removed in a future version.\nIn order to convert, kubectl apply the object to the cluster, then kubectl get at the desired version.\n")

	b := o.builder().
		WithScheme(scheme.Scheme).
		LocalParam(o.local)
	if !o.local {
		schema, err := o.validator()
		if err != nil {
			return err
		}
		b.Schema(schema)
	}

	r := b.NamespaceParam(o.Namespace).
		ContinueOnError().
		FilenameParam(false, &o.FilenameOptions).
		Flatten().
		Do()

	err := r.Err()
	if err != nil {
		return err
	}

	singleItemImplied := false
	infos, err := r.IntoSingleItemImplied(&singleItemImplied).Infos()
	if err != nil {
		return err
	}

	if len(infos) == 0 {
		return fmt.Errorf("no objects passed to convert")
	}

	var specifiedOutputVersion schema.GroupVersion
	if len(o.OutputVersion) > 0 {
		specifiedOutputVersion, err = schema.ParseGroupVersion(o.OutputVersion)
		if err != nil {
			return err
		}
	}

	internalEncoder := scheme.Codecs.LegacyCodec(scheme.Scheme.PrioritizedVersionsAllGroups()...)
	internalVersionJSONEncoder := unstructured.JSONFallbackEncoder{Encoder: internalEncoder}
	objects, err := asVersionedObject(infos, !singleItemImplied, specifiedOutputVersion, internalVersionJSONEncoder)
	if err != nil {
		return err
	}

	return o.Printer.PrintObj(objects, o.Out)
}

// asVersionedObject converts a list of infos into a single object - either a List containing
// the objects as children, or if only a single Object is present, as that object. The provided
// version will be preferred as the conversion target, but the Object's mapping version will be
// used if that version is not present.
func asVersionedObject(infos []*resource.Info, forceList bool, specifiedOutputVersion schema.GroupVersion, encoder runtime.Encoder) (runtime.Object, error) {
	objects, err := asVersionedObjects(infos, specifiedOutputVersion, encoder)
	if err != nil {
		return nil, err
	}

	var object runtime.Object
	if len(objects) == 1 && !forceList {
		object = objects[0]
	} else {
		object = &api.List{Items: objects}
		targetVersions := []schema.GroupVersion{}
		if !specifiedOutputVersion.Empty() {
			targetVersions = append(targetVersions, specifiedOutputVersion)
		}
		targetVersions = append(targetVersions, schema.GroupVersion{Group: "", Version: "v1"})

		converted, err := tryConvert(scheme.Scheme, object, targetVersions...)
		if err != nil {
			return nil, err
		}
		object = converted
	}

	actualVersion := object.GetObjectKind().GroupVersionKind()
	if actualVersion.Version != specifiedOutputVersion.Version {
		defaultVersionInfo := ""
		if len(actualVersion.Version) > 0 {
			defaultVersionInfo = fmt.Sprintf("Defaulting to %q", actualVersion.Version)
		}
		klog.V(1).Infof("info: the output version specified is invalid. %s\n", defaultVersionInfo)
	}
	return object, nil
}

// asVersionedObjects converts a list of infos into versioned objects. The provided
// version will be preferred as the conversion target, but the Object's mapping version will be
// used if that version is not present.
func asVersionedObjects(infos []*resource.Info, specifiedOutputVersion schema.GroupVersion, encoder runtime.Encoder) ([]runtime.Object, error) {
	objects := []runtime.Object{}
	for _, info := range infos {
		if info.Object == nil {
			continue
		}

		targetVersions := []schema.GroupVersion{}
		// objects that are not part of api.Scheme must be converted to JSON
		// TODO: convert to map[string]interface{}, attach to runtime.Unknown?
		if !specifiedOutputVersion.Empty() {
			if _, _, err := scheme.Scheme.ObjectKinds(info.Object); runtime.IsNotRegisteredError(err) {
				// TODO: ideally this would encode to version, but we don't expose multiple codecs here.
				data, err := runtime.Encode(encoder, info.Object)
				if err != nil {
					return nil, err
				}
				// TODO: Set ContentEncoding and ContentType.
				objects = append(objects, &runtime.Unknown{Raw: data})
				continue
			}
			targetVersions = append(targetVersions, specifiedOutputVersion)
		} else {
			gvks, _, err := scheme.Scheme.ObjectKinds(info.Object)
			if err == nil {
				for _, gvk := range gvks {
					for _, version := range scheme.Scheme.PrioritizedVersionsForGroup(gvk.Group) {
						targetVersions = append(targetVersions, version)
					}
				}
			}
		}

		converted, err := tryConvert(scheme.Scheme, info.Object, targetVersions...)
		if err != nil {
			return nil, err
		}
		objects = append(objects, converted)
	}
	return objects, nil
}

// tryConvert attempts to convert the given object to the provided versions in order. This function assumes
// the object is in internal version.
func tryConvert(converter runtime.ObjectConvertor, object runtime.Object, versions ...schema.GroupVersion) (runtime.Object, error) {
	var last error
	for _, version := range versions {
		if version.Empty() {
			return object, nil
		}
		obj, err := converter.ConvertToVersion(object, version)
		if err != nil {
			last = err
			continue
		}
		return obj, nil
	}
	return nil, last
}


text:
/**
 * @fileoverview Restrict file extensions that may contain JSX
 * @author Joe Lencioni
 */
'use strict';

// ------------------------------------------------------------------------------
// Requirements
// ------------------------------------------------------------------------------

const rule = require('../../../lib/rules/jsx-filename-extension');
const RuleTester = require('eslint').RuleTester;

const parserOptions = {
  ecmaVersion: 8,
  sourceType: 'module',
  ecmaFeatures: {
    experimentalObjectRestSpread: true,
    jsx: true
  }
};

// ------------------------------------------------------------------------------
// Code Snippets
// ------------------------------------------------------------------------------

const withJSX = 'module.exports = function MyComponent() { return <div>\n<div />\n</div>; }';
const withoutJSX = 'module.exports = {}';

// ------------------------------------------------------------------------------
// Tests
// ------------------------------------------------------------------------------

const ruleTester = new RuleTester({parserOptions});
ruleTester.run('jsx-filename-extension', rule, {

  valid: [
    {
      filename: '<text>',
      code: withJSX
    },
    {
      filename: 'MyComponent.jsx',
      code: withJSX
    }, {
      filename: 'MyComponent.js',
      options: [{extensions: ['.js', '.jsx']}],
      code: withJSX
    }, {
      filename: 'notAComponent.js',
      code: withoutJSX
    }
  ],

  invalid: [
    {
      filename: 'MyComponent.js',
      code: withJSX,
      errors: [{message: 'JSX not allowed in files with extension \'.js\''}]
    }, {
      filename: 'MyComponent.jsx',
      code: withJSX,
      options: [{extensions: ['.js']}],
      errors: [{message: 'JSX not allowed in files with extension \'.jsx\''}]
    }
  ]

});


text:
% IPN - ESCOM
% Pattern Recognition
% ww ww ww - wwwwww.com/pattern-recognition

clc % Limpiar pantalla

% Variables del programa
centroides = {};
www_imagen = imread('imagen_pattern-recognition.jpg'); % Obtenida de https://pixabay.com/en/pier-tropical-beach-summer-ocean-440339/
imshow(www_imagen)

[x, y, rgb] = impixel(www_imagen);
for c=1:size(x, 1)-1
    centroides{end+1} = [x(c), y(c)];
    representantes = input('Cantidad de representantes: ');
    dispersion = input('Dispersión: ');
    PR_drawPuntosFromCentroide(x(c), y(c), representantes, dispersion);
end

vector_desconocido = [x(size(x, 1)), y(size(y, 1))];

plot(vector_desconocido(1), vector_desconocido(2), 'r>');

clase_padre = PR_distanciaEuclideana(centroides, vector_desconocido, size(x, 1) - 1);
fprintf('El vector pertenece a la clase %d\n', clase_padre)


text:
var b2BodyDef = Class.create();
b2BodyDef.prototype =
{
	initialize: function()
	{
		// initialize instance variables for references
		this.shapes = new Array();
		//

		this.userData = null;
		for (var i = 0; i < b2Settings.b2_maxShapesPerBody; i++){
			this.shapes[i] = null;
		}
		this.position = new b2Vec2(0.0, 0.0);
		this.rotation = 0.0;
		this.linearVelocity = new b2Vec2(0.0, 0.0);
		this.angularVelocity = 0.0;
		this.linearDamping = 0.0;
		this.angularDamping = 0.0;
		this.allowSleep = true;
		this.isSleeping = false;
		this.preventRotation = false;
	},

	userData: null,
	shapes: new Array(),
	position: null,
	rotation: null,
	linearVelocity: null,
	angularVelocity: null,
	linearDamping: null,
	angularDamping: null,
	allowSleep: null,
	isSleeping: null,
	preventRotation: null,

	AddShape: function(shape)
	{
		for (var i = 0; i < b2Settings.b2_maxShapesPerBody; ++i)
		{
			if (this.shapes[i] == null)
			{
				this.shapes[i] = shape;
				break;
			}
		}
	}};


text:
[demo](http://danielhusar.github.io/grid-cells/)

![readme](readme.jpg)

## License

MIT © Daniel Husar


text:
package org.apache.commons.math3.linear;

import java.io.Serializable;

import org.apache.commons.math3.exception.DimensionMismatchException;
import org.apache.commons.math3.exception.MathArithmeticException;
import org.apache.commons.math3.exception.NotPositiveException;
import org.apache.commons.math3.exception.OutOfRangeException;
import org.apache.commons.math3.exception.util.LocalizedFormats;
import org.apache.commons.math3.util.FastMath;
import org.apache.commons.math3.util.OpenIntToDoubleHashMap;
import org.apache.commons.math3.util.OpenIntToDoubleHashMap.Iterator;

/**
 * This class implements the {@link RealVector} interface with a
 * {@link OpenIntToDoubleHashMap} backing store.
 * @version $Id: OpenMapRealVector.java 1416643 2012-12-03 19:37:14Z tn $
 * @since 2.0
 * @deprecated As of version 3.1, this class is deprecated, for reasons exposed
 * in this JIRA
 * ticket. This
 * class will be removed in version 4.0.
 */
@Deprecated
public class OpenMapRealVector extends SparseRealVector
    implements Serializable {
    /** Default Tolerance for having a value considered zero. */
    public static final double DEFAULT_ZERO_TOLERANCE = 1.0e-12;
    /** Serializable version identifier. */
    private static final long serialVersionUID = 8772222695580707260L;
    /** Entries of the vector. */
    private final OpenIntToDoubleHashMap entries;
    /** Dimension of the vector. */
    private final int virtualSize;
    /** Tolerance for having a value considered zero. */
    private final double epsilon;

    /**
     * Build a 0-length vector.
     * Zero-length vectors may be used to initialized construction of vectors
     * by data gathering. We start with zero-length and use either the {@link
     * #OpenMapRealVector(OpenMapRealVector, int)} constructor
     * or one of the {@code append} method ({@link #append(double)},
     * {@link #append(RealVector)}) to gather data into this vector.
     */
    public OpenMapRealVector() {
        this(0, DEFAULT_ZERO_TOLERANCE);
    }

    /**
     * Construct a vector of zeroes.
     *
     * @param dimension Size of the vector.
     */
    public OpenMapRealVector(int dimension) {
        this(dimension, DEFAULT_ZERO_TOLERANCE);
    }

    /**
     * Construct a vector of zeroes, specifying zero tolerance.
     *
     * @param dimension Size of the vector.
     * @param epsilon Tolerance below which a value considered zero.
     */
    public OpenMapRealVector(int dimension, double epsilon) {
        virtualSize = dimension;
        entries = new OpenIntToDoubleHashMap(0.0);
        this.epsilon = epsilon;
    }

    /**
     * Build a resized vector, for use with append.
     *
     * @param v Original vector.
     * @param resize Amount to add.
     */
    protected OpenMapRealVector(OpenMapRealVector v, int resize) {
        virtualSize = v.getDimension() + resize;
        entries = new OpenIntToDoubleHashMap(v.entries);
        epsilon = v.epsilon;
    }

    /**
     * Build a vector with known the sparseness (for advanced use only).
     *
     * @param dimension Size of the vector.
     * @param expectedSize The expected number of non-zero entries.
     */
    public OpenMapRealVector(int dimension, int expectedSize) {
        this(dimension, expectedSize, DEFAULT_ZERO_TOLERANCE);
    }

    /**
     * Build a vector with known the sparseness and zero tolerance
     * setting (for advanced use only).
     *
     * @param dimension Size of the vector.
     * @param expectedSize Expected number of non-zero entries.
     * @param epsilon Tolerance below which a value is considered zero.
     */
    public OpenMapRealVector(int dimension, int expectedSize, double epsilon) {
        virtualSize = dimension;
        entries = new OpenIntToDoubleHashMap(expectedSize, 0.0);
        this.epsilon = epsilon;
    }

    /**
     * Create from an array.
     * Only non-zero entries will be stored.
     *
     * @param values Set of values to create from.
     */
    public OpenMapRealVector(double[] values) {
        this(values, DEFAULT_ZERO_TOLERANCE);
    }

    /**
     * Create from an array, specifying zero tolerance.
     * Only non-zero entries will be stored.
     *
     * @param values Set of values to create from.
     * @param epsilon Tolerance below which a value is considered zero.
     */
    public OpenMapRealVector(double[] values, double epsilon) {
        virtualSize = values.length;
        entries = new OpenIntToDoubleHashMap(0.0);
        this.epsilon = epsilon;
        for (int key = 0; key < values.length; key++) {
            double value = values[key];
            if (!isDefaultValue(value)) {
                entries.put(key, value);
            }
        }
    }

    /**
     * Create from an array.
     * Only non-zero entries will be stored.
     *
     * @param values The set of values to create from
     */
    public OpenMapRealVector(Double[] values) {
        this(values, DEFAULT_ZERO_TOLERANCE);
    }

    /**
     * Create from an array.
     * Only non-zero entries will be stored.
     *
     * @param values Set of values to create from.
     * @param epsilon Tolerance below which a value is considered zero.
     */
    public OpenMapRealVector(Double[] values, double epsilon) {
        virtualSize = values.length;
        entries = new OpenIntToDoubleHashMap(0.0);
        this.epsilon = epsilon;
        for (int key = 0; key < values.length; key++) {
            double value = values[key].doubleValue();
            if (!isDefaultValue(value)) {
                entries.put(key, value);
            }
        }
    }

    /**
     * Copy constructor.
     *
     * @param v Instance to copy from.
     */
    public OpenMapRealVector(OpenMapRealVector v) {
        virtualSize = v.getDimension();
        entries = new OpenIntToDoubleHashMap(v.getEntries());
        epsilon = v.epsilon;
    }

    /**
     * Generic copy constructor.
     *
     * @param v Instance to copy from.
     */
    public OpenMapRealVector(RealVector v) {
        virtualSize = v.getDimension();
        entries = new OpenIntToDoubleHashMap(0.0);
        epsilon = DEFAULT_ZERO_TOLERANCE;
        for (int key = 0; key < virtualSize; key++) {
            double value = v.getEntry(key);
            if (!isDefaultValue(value)) {
                entries.put(key, value);
            }
        }
    }

    /**
     * Get the entries of this instance.
     *
     * @return the entries of this instance.
     */
    private OpenIntToDoubleHashMap getEntries() {
        return entries;
    }

    /**
     * Determine if this value is within epsilon of zero.
     *
     * @param value Value to test
     * @return {@code true} if this value is within epsilon to zero,
     * {@code false} otherwise.
     * @since 2.1
     */
    protected boolean isDefaultValue(double value) {
        return FastMath.abs(value) < epsilon;
    }

    /** {@inheritDoc} */
    @Override
    public RealVector add(RealVector v)
        throws DimensionMismatchException {
        checkVectorDimensions(v.getDimension());
        if (v instanceof OpenMapRealVector) {
            return add((OpenMapRealVector) v);
        } else {
            return super.add(v);
        }
    }

    /**
     * Optimized method to add two OpenMapRealVectors.
     * It copies the larger vector, then iterates over the smaller.
     *
     * @param v Vector to add.
     * @return the sum of {@code this} and {@code v}.
     * @throws DimensionMismatchException if the dimensions do not match.
     */
    public OpenMapRealVector add(OpenMapRealVector v)
        throws DimensionMismatchException {
        checkVectorDimensions(v.getDimension());
        boolean copyThis = entries.size() > v.entries.size();
        OpenMapRealVector res = copyThis ? this.copy() : v.copy();
        Iterator iter = copyThis ? v.entries.iterator() : entries.iterator();
        OpenIntToDoubleHashMap randomAccess = copyThis ? entries : v.entries;
        while (iter.hasNext()) {
            iter.advance();
            int key = iter.key();
            if (randomAccess.containsKey(key)) {
                res.setEntry(key, randomAccess.get(key) + iter.value());
            } else {
                res.setEntry(key, iter.value());
            }
        }
        return res;
    }

    /**
     * Optimized method to append a OpenMapRealVector.
     * @param v vector to append
     * @return The result of appending {@code v} to self
     */
    public OpenMapRealVector append(OpenMapRealVector v) {
        OpenMapRealVector res = new OpenMapRealVector(this, v.getDimension());
        Iterator iter = v.entries.iterator();
        while (iter.hasNext()) {
            iter.advance();
            res.setEntry(iter.key() + virtualSize, iter.value());
        }
        return res;
    }

    /** {@inheritDoc} */
    @Override
    public OpenMapRealVector append(RealVector v) {
        if (v instanceof OpenMapRealVector) {
            return append((OpenMapRealVector) v);
        } else {
            final OpenMapRealVector res = new OpenMapRealVector(this, v.getDimension());
            for (int i = 0; i < v.getDimension(); i++) {
                res.setEntry(i + virtualSize, v.getEntry(i));
            }
            return res;
        }
    }

    /** {@inheritDoc} */
    @Override
    public OpenMapRealVector append(double d) {
        OpenMapRealVector res = new OpenMapRealVector(this, 1);
        res.setEntry(virtualSize, d);
        return res;
    }

    /**
     * {@inheritDoc}
     * @since 2.1
     */
    @Override
    public OpenMapRealVector copy() {
        return new OpenMapRealVector(this);
    }

    /**
     * Computes the dot product.
     * Note that the computation is now performed in the parent class: no
     * performance improvement is to be expected from this overloaded
     * method.
     * The previous implementation was buggy and cannot be easily fixed
     * (see MATH-795).
     *
     * @param v Vector.
     * @return the dot product of this vector with {@code v}.
     * @throws DimensionMismatchException if {@code v} is not the same size as
     * {@code this} vector.
     *
     * @deprecated as of 3.1 (to be removed in 4.0). The computation is
     * performed by the parent class. The method must be kept to maintain
     * backwards compatibility.
     */
    @Deprecated
    public double dotProduct(OpenMapRealVector v)
        throws DimensionMismatchException {
        return dotProduct((RealVector) v);
    }

    /** {@inheritDoc} */
    @Override
    public OpenMapRealVector ebeDivide(RealVector v)
        throws DimensionMismatchException {
        checkVectorDimensions(v.getDimension());
        OpenMapRealVector res = new OpenMapRealVector(this);
        /*
         * MATH-803: it is not sufficient to loop through non zero entries of
         * this only. Indeed, if this[i] = 0d and v[i] = 0d, then
         * this[i] / v[i] = NaN, and not 0d.
         */
        final int n = getDimension();
        for (int i = 0; i < n; i++) {
            res.setEntry(i, this.getEntry(i) / v.getEntry(i));
        }
        return res;
    }

    /** {@inheritDoc} */
    @Override
    public OpenMapRealVector ebeMultiply(RealVector v)
        throws DimensionMismatchException {
        checkVectorDimensions(v.getDimension());
        OpenMapRealVector res = new OpenMapRealVector(this);
        Iterator iter = entries.iterator();
        while (iter.hasNext()) {
            iter.advance();
            res.setEntry(iter.key(), iter.value() * v.getEntry(iter.key()));
        }
        /*
         * MATH-803: the above loop assumes that 0d * x  = 0d for any double x,
         * which allows to consider only the non-zero entries of this. However,
         * this fails if this[i] == 0d and (v[i] = NaN or v[i] = Infinity).
         *
         * These special cases are handled below.
         */
        if (v.isNaN() || v.isInfinite()) {
            final int n = getDimension();
            for (int i = 0; i < n; i++) {
                final double y = v.getEntry(i);
                if (Double.isNaN(y)) {
                    res.setEntry(i, Double.NaN);
                } else if (Double.isInfinite(y)) {
                    final double x = this.getEntry(i);
                    res.setEntry(i, x * y);
                }
            }
        }
        return res;
    }

    /** {@inheritDoc} */
    @Override
    public OpenMapRealVector getSubVector(int index, int n)
        throws NotPositiveException, OutOfRangeException {
        checkIndex(index);
        if (n < 0) {
            throw new NotPositiveException(LocalizedFormats.NUMBER_OF_ELEMENTS_SHOULD_BE_POSITIVE, n);
        }
        checkIndex(index + n - 1);
        OpenMapRealVector res = new OpenMapRealVector(n);
        int end = index + n;
        Iterator iter = entries.iterator();
        while (iter.hasNext()) {
            iter.advance();
            int key = iter.key();
            if (key >= index && key < end) {
                res.setEntry(key - index, iter.value());
            }
        }
        return res;
    }

    /** {@inheritDoc} */
    @Override
    public int getDimension() {
        return virtualSize;
    }

    /**
     * Optimized method to compute distance.
     *
     * @param v Vector to compute distance to.
     * @return the distance from {@code this} and {@code v}.
     * @throws DimensionMismatchException if the dimensions do not match.
     */
    public double getDistance(OpenMapRealVector v)
        throws DimensionMismatchException {
        checkVectorDimensions(v.getDimension());
        Iterator iter = entries.iterator();
        double res = 0;
        while (iter.hasNext()) {
            iter.advance();
            int key = iter.key();
            double delta;
            delta = iter.value() - v.getEntry(key);
            res += delta * delta;
        }
        iter = v.getEntries().iterator();
        while (iter.hasNext()) {
            iter.advance();
            int key = iter.key();
            if (!entries.containsKey(key)) {
                final double value = iter.value();
                res += value * value;
            }
        }
        return FastMath.sqrt(res);
    }

    /** {@inheritDoc} */
    @Override
    public double getDistance(RealVector v) throws DimensionMismatchException {
        checkVectorDimensions(v.getDimension());
        if (v instanceof OpenMapRealVector) {
            return getDistance((OpenMapRealVector) v);
        } else {
            return super.getDistance(v);
        }
    }

    /** {@inheritDoc} */
    @Override
    public double getEntry(int index) throws OutOfRangeException {
        checkIndex(index);
        return entries.get(index);
    }

    /**
     * Distance between two vectors.
     * This method computes the distance consistent with
     * L1 norm, i.e. the sum of the absolute values of
     * elements differences.
     *
     * @param v Vector to which distance is requested.
     * @return distance between this vector and {@code v}.
     * @throws DimensionMismatchException if the dimensions do not match.
     */
    public double getL1Distance(OpenMapRealVector v)
        throws DimensionMismatchException {
        checkVectorDimensions(v.getDimension());
        double max = 0;
        Iterator iter = entries.iterator();
        while (iter.hasNext()) {
            iter.advance();
            double delta = FastMath.abs(iter.value() - v.getEntry(iter.key()));
            max += delta;
        }
        iter = v.getEntries().iterator();
        while (iter.hasNext()) {
            iter.advance();
            int key = iter.key();
            if (!entries.containsKey(key)) {
                double delta = FastMath.abs(iter.value());
                max +=  FastMath.abs(delta);
            }
        }
        return max;
    }

    /** {@inheritDoc} */
    @Override
    public double getL1Distance(RealVector v)
        throws DimensionMismatchException {
        checkVectorDimensions(v.getDimension());
        if (v instanceof OpenMapRealVector) {
            return getL1Distance((OpenMapRealVector) v);
        } else {
            return super.getL1Distance(v);
        }
    }

    /**
     * Optimized method to compute LInfDistance.
     *
     * @param v Vector to compute distance from.
     * @return the LInfDistance.
     * @throws DimensionMismatchException if the dimensions do not match.
     */
    private double getLInfDistance(OpenMapRealVector v)
        throws DimensionMismatchException {
        checkVectorDimensions(v.getDimension());
        double max = 0;
        Iterator iter = entries.iterator();
        while (iter.hasNext()) {
            iter.advance();
            double delta = FastMath.abs(iter.value() - v.getEntry(iter.key()));
            if (delta > max) {
                max = delta;
            }
        }
        iter = v.getEntries().iterator();
        while (iter.hasNext()) {
            iter.advance();
            int key = iter.key();
            if (!entries.containsKey(key)) {
                if (iter.value() > max) {
                    max = iter.value();
                }
            }
        }
        return max;
    }

    /** {@inheritDoc} */
    @Override
    public double getLInfDistance(RealVector v)
        throws DimensionMismatchException {
        checkVectorDimensions(v.getDimension());
        if (v instanceof OpenMapRealVector) {
            return getLInfDistance((OpenMapRealVector) v);
        } else {
            return super.getLInfDistance(v);
        }
    }

    /** {@inheritDoc} */
    @Override
    public boolean isInfinite() {
        boolean infiniteFound = false;
        Iterator iter = entries.iterator();
        while (iter.hasNext()) {
            iter.advance();
            final double value = iter.value();
            if (Double.isNaN(value)) {
                return false;
            }
            if (Double.isInfinite(value)) {
                infiniteFound = true;
            }
        }
        return infiniteFound;
    }

    /** {@inheritDoc} */
    @Override
    public boolean isNaN() {
        Iterator iter = entries.iterator();
        while (iter.hasNext()) {
            iter.advance();
            if (Double.isNaN(iter.value())) {
                return true;
            }
        }
        return false;
    }

    /** {@inheritDoc} */
    @Override
    public OpenMapRealVector mapAdd(double d) {
        return copy().mapAddToSelf(d);
    }

    /** {@inheritDoc} */
    @Override
    public OpenMapRealVector mapAddToSelf(double d) {
        for (int i = 0; i < virtualSize; i++) {
            setEntry(i, getEntry(i) + d);
        }
        return this;
    }

    /** {@inheritDoc} */
    @Override
    public void setEntry(int index, double value)
        throws OutOfRangeException {
        checkIndex(index);
        if (!isDefaultValue(value)) {
            entries.put(index, value);
        } else if (entries.containsKey(index)) {
            entries.remove(index);
        }
    }

    /** {@inheritDoc} */
    @Override
    public void setSubVector(int index, RealVector v)
        throws OutOfRangeException {
        checkIndex(index);
        checkIndex(index + v.getDimension() - 1);
        for (int i = 0; i < v.getDimension(); i++) {
            setEntry(i + index, v.getEntry(i));
        }
    }

    /** {@inheritDoc} */
    @Override
    public void set(double value) {
        for (int i = 0; i < virtualSize; i++) {
            setEntry(i, value);
        }
    }

    /**
     * Optimized method to subtract OpenMapRealVectors.
     *
     * @param v Vector to subtract from {@code this}.
     * @return the difference of {@code this} and {@code v}.
     * @throws DimensionMismatchException if the dimensions do not match.
     */
    public OpenMapRealVector subtract(OpenMapRealVector v)
        throws DimensionMismatchException {
        checkVectorDimensions(v.getDimension());
        OpenMapRealVector res = copy();
        Iterator iter = v.getEntries().iterator();
        while (iter.hasNext()) {
            iter.advance();
            int key = iter.key();
            if (entries.containsKey(key)) {
                res.setEntry(key, entries.get(key) - iter.value());
            } else {
                res.setEntry(key, -iter.value());
            }
        }
        return res;
    }

    /** {@inheritDoc} */
    @Override
    public RealVector subtract(RealVector v)
        throws DimensionMismatchException {
        checkVectorDimensions(v.getDimension());
        if (v instanceof OpenMapRealVector) {
            return subtract((OpenMapRealVector) v);
        } else {
            return super.subtract(v);
        }
    }

    /** {@inheritDoc} */
    @Override
    public OpenMapRealVector unitVector() throws MathArithmeticException {
        OpenMapRealVector res = copy();
        res.unitize();
        return res;
    }

    /** {@inheritDoc} */
    @Override
    public void unitize() throws MathArithmeticException {
        double norm = getNorm();
        if (isDefaultValue(norm)) {
            throw new MathArithmeticException(LocalizedFormats.ZERO_NORM);
        }
        Iterator iter = entries.iterator();
        while (iter.hasNext()) {
            iter.advance();
            entries.put(iter.key(), iter.value() / norm);
        }
    }

    /** {@inheritDoc} */
    @Override
    public double[] toArray() {
        double[] res = new double[virtualSize];
        Iterator iter = entries.iterator();
        while (iter.hasNext()) {
            iter.advance();
            res[iter.key()] = iter.value();
        }
        return res;
    }

    /**
     * {@inheritDoc}
     * Implementation Note: This works on exact values, and as a result
     * it is possible for {@code a.subtract(b)} to be the zero vector, while
     * {@code a.hashCode() != b.hashCode()}.
     */
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        long temp;
        temp = Double.doubleToLongBits(epsilon);
        result = prime * result + (int) (temp ^ (temp >>> 32));
        result = prime * result + virtualSize;
        Iterator iter = entries.iterator();
        while (iter.hasNext()) {
            iter.advance();
            temp = Double.doubleToLongBits(iter.value());
            result = prime * result + (int) (temp ^ (temp >>32));
        }
        return result;
    }

    /**
     * {@inheritDoc}
     * Implementation Note: This performs an exact comparison, and as a result
     * it is possible for {@code a.subtract(b}} to be the zero vector, while
     * {@code  a.equals(b) == false}.
     */
    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (!(obj instanceof OpenMapRealVector)) {
            return false;
        }
        OpenMapRealVector other = (OpenMapRealVector) obj;
        if (virtualSize != other.virtualSize) {
            return false;
        }
        if (Double.doubleToLongBits(epsilon) !=
            Double.doubleToLongBits(other.epsilon)) {
            return false;
        }
        Iterator iter = entries.iterator();
        while (iter.hasNext()) {
            iter.advance();
            double test = other.getEntry(iter.key());
            if (Double.doubleToLongBits(test) != Double.doubleToLongBits(iter.value())) {
                return false;
            }
        }
        iter = other.getEntries().iterator();
        while (iter.hasNext()) {
            iter.advance();
            double test = iter.value();
            if (Double.doubleToLongBits(test) != Double.doubleToLongBits(getEntry(iter.key()))) {
                return false;
            }
        }
        return true;
    }

    /**
     *
     * @return the percentage of none zero elements as a decimal percent.
     * @since 2.2
     */
    public double getSparsity() {
        return (double)entries.size()/(double)getDimension();
    }

    /** {@inheritDoc} */
    @Override
    public java.util.Iterator<Entry> sparseIterator() {
        return new OpenMapSparseIterator();
    }

    /**
     * Implementation of {@code Entry} optimized for OpenMap.
     * This implementation does not allow arbitrary calls to {@code setIndex}
     * since the order in which entries are returned is undefined.
     */
    protected class OpenMapEntry extends Entry {
        /** Iterator pointing to the entry. */
        private final Iterator iter;

        /**
         * Build an entry from an iterator point to an element.
         *
         * @param iter Iterator pointing to the entry.
         */
        protected OpenMapEntry(Iterator iter) {
            this.iter = iter;
        }

        /** {@inheritDoc} */
        @Override
        public double getValue() {
            return iter.value();
        }

        /** {@inheritDoc} */
        @Override
        public void setValue(double value) {
            entries.put(iter.key(), value);
        }

        /** {@inheritDoc} */
        @Override
        public int getIndex() {
            return iter.key();
        }

    }

    /**
     * Iterator class to do iteration over just the non-zero elements.
     * This implementation is fail-fast, so cannot be used to modify
     * any zero element.
     */
    protected class OpenMapSparseIterator implements java.util.Iterator<Entry> {
        /** Underlying iterator. */
        private final Iterator iter;
        /** Current entry. */
        private final Entry current;

        /** Simple constructor. */
        protected OpenMapSparseIterator() {
            iter = entries.iterator();
            current = new OpenMapEntry(iter);
        }

        /** {@inheritDoc} */
        public boolean hasNext() {
            return iter.hasNext();
        }

        /** {@inheritDoc} */
        public Entry next() {
            iter.advance();
            return current;
        }

        /** {@inheritDoc} */
        public void remove() {
            throw new UnsupportedOperationException("Not supported");
        }
    }
}


text:
<?php

/**
 * Test case
 *
 * @category   Enlight
 * @package    Enlight_Tests
 * @copyright  Copyright (c) 2011, shopware AG (http://www.shopware.de)
 * @license    http://enlight.de/license/new-bsd     New BSD License
 */
class Enlight_Tests_Config_AdapterTest extends Enlight_Components_Test_TestCase
{
    /**
     * @var Enlight_Config_Adapter
     */
    protected $adapterTester;

    /**
     * @var Enlight_Config
     */
    protected $configTester;

    /**
     * Set up the test case
     */
    public function setUp()
    {
        parent::setUp();

        $path = Enlight_TestHelper::Instance()->TestPath('TempFiles');
        $this->adapterTester = new Enlight_Config_Adapter_File(array(
            'configType' => 'ini',
            'configDir' => $path
        ));

        $this->configTester = new Enlight_Config('test', array(
            'adapter' => $this->adapterTester,
            'section' => 'test'
        ));
        $this->configTester
             ->setAllowModifications()
             ->set('test', true)
             ->setReadOnly();
        $this->configTester->write();
    }

    /**
     * Test case
     */
    public function testConfigName()
    {
    	$config = new Enlight_Config('test');
		$this->assertEquals('test', $config->getName());
    }

    /**
	 * Test case
	 */
	public function testSetAdapter()
    {
        $config = new Enlight_Config('test', array('adapter' => $this->adapterTester));
        $this->assertEquals($this->adapterTester, $config->getAdapter());
    }

    /**
	 * Test case
	 */
	public function testSetDefaultAdapter()
    {
        Enlight_Config::setDefaultAdapter($this->adapterTester);
        $this->assertEquals($this->adapterTester, Enlight_Config::getDefaultAdapter());
    }

    /**
	 * Test case
	 */
	public function testForeach()
    {
        $config = new Enlight_Config('test', array(
            'adapter' => $this->adapterTester,
            'section' => 'test'
        ));
        foreach($config as $value) {
            $this->assertNotEmpty($value);
        }
    }

    /**
     * Test case
     */
    public function testConfigNameSuffix()
    {
        $dir = Enlight_TestHelper::Instance()->TestPath('TempFiles');
        $adapter = new Enlight_Config_Adapter_File(array(
            'configDir' => $dir,
            'nameSuffix' => '.txt',
            'skipExtends' => false,
            'configType' => 'ini'
        ));

        $config = new Enlight_Config('test', array('adapter' => $adapter));
        $config->setData(array('test' => true));
        $config->setSection('test');
        $config->write();

        $this->assertFileExists($dir . 'test' . '.txt');
    }

    /**
     * Test case
     */
    public function testConfigNamePrefix()
    {
        $dir = Enlight_TestHelper::Instance()->TestPath('TempFiles');
        $adapter = new Enlight_Config_Adapter_File(array(
            'configDir' => $dir,
            'namePrefix' => 's_',
            'skipExtends' => false,
            'configType' => 'ini'
        ));

        $config = new Enlight_Config('test', array('adapter' => $adapter));
        $config->setData(array('test' => true));
        $config->write();

        $this->assertFileExists($dir . 's_test' . '.ini');
    }
}


text:
'use strict';

define(['angular', 'app'], function(angular, app) {

	return app.config(['$routeProvider', function($routeProvider) {
		$routeProvider.when('/view1', {
			templateUrl: 'app/partials/partial1.html',
			controller: 'MyCtrl1'
		});
		$routeProvider.when('/view2', {
			templateUrl: 'app/partials/partial2.html',
			controller: 'MyCtrl2'
		});
        $routeProvider.when('/view3', {
            templateUrl: 'app/partials/partial3.html',
            controller: 'MyCtrl3'
        });
        $routeProvider.when('/home', {
            templateUrl: 'app/partials/partial3.html',
            controller: 'MyCtrl3'
        });
        $routeProvider.when('/about', {
            templateUrl: 'app/templates/about.html',
            controller: 'MyCtrl3'
        });
		$routeProvider.otherwise({redirectTo: '/view1'});
	}]);

});


text:
__version__ = '2.0'
__author__  = ['Andrew Kuchling', 'Ralph Heinkel']

from PIL import Image

import _sane
from _sane import *

TYPE_STR = { TYPE_BOOL:   "TYPE_BOOL",   TYPE_INT:    "TYPE_INT",
             TYPE_FIXED:  "TYPE_FIXED",  TYPE_STRING: "TYPE_STRING",
             TYPE_BUTTON: "TYPE_BUTTON", TYPE_GROUP:  "TYPE_GROUP" }

UNIT_STR = { UNIT_NONE:        "UNIT_NONE",
             UNIT_PIXEL:       "UNIT_PIXEL",
             UNIT_BIT:         "UNIT_BIT",
             UNIT_MM:          "UNIT_MM",
             UNIT_DPI:         "UNIT_DPI",
             UNIT_PERCENT:     "UNIT_PERCENT",
             UNIT_MICROSECOND: "UNIT_MICROSECOND" }

class Option:
    """Class representing a SANE option.
    Attributes:
    index -- number from 0 to n, giving the option number
    name -- a string uniquely identifying the option
    title -- single-line string containing a title for the option
    desc -- a long string describing the option; useful as a help message
    type -- type of this option.  Possible values: TYPE_BOOL,
            TYPE_INT, TYPE_STRING, and so forth.
    unit -- units of this option.  Possible values: UNIT_NONE,
            UNIT_PIXEL, etc.
    size -- size of the value in bytes
    cap -- capabilities available; CAP_EMULATED, CAP_SOFT_SELECT, etc.
    constraint -- constraint on values.  Possible values:
        None : No constraint
        (min,max,step)  Integer values, from min to max, stepping by
        list of integers or strings: only the listed values are allowed
    """

    def __init__(self, args, scanDev):
        import string
        self.scanDev = scanDev # needed to get current value of this option
        self.index, self.name = args[0], args[1]
        self.title, self.desc = args[2], args[3]
        self.type, self.unit  = args[4], args[5]
        self.size, self.cap   = args[6], args[7]
        self.constraint = args[8]
        def f(x):
            if x=='-': return '_'
            else: return x
        if type(self.name)!=type(''): self.py_name=str(self.name)
        else: self.py_name=string.join(map(f, self.name), '')

    def is_active(self):
        return _sane.OPTION_IS_ACTIVE(self.cap)
    def is_settable(self):
        return _sane.OPTION_IS_SETTABLE(self.cap)
    def __repr__(self):
        if self.is_settable():
            settable = 'yes'
        else:
            settable = 'no'
        if self.is_active():
            active = 'yes'
            curValue = repr(getattr(self.scanDev, self.py_name))
        else:
            active = 'no'
            curValue = '<not available, inactive option>'
        s = """\nName:      %s
Cur value: %s
Index:     %d
Title:     %s
Desc:      %s
Type:      %s
Unit:      %s
Constr:    %s
active:    %s
settable:  %s\n""" % (self.py_name, curValue,
                      self.index, self.title, self.desc,
                      TYPE_STR[self.type], UNIT_STR[self.unit],
                      `self.constraint`, active, settable)
        return s

class _SaneIterator:
    """ intended for ADF scans.
    """

    def __init__(self, device):
        self.device = device

    def __iter__(self):
        return self

    def __del__(self):
        self.device.cancel()

    def next(self):
        try:
            self.device.start()
        except error, v:
            if v == 'Document feeder out of documents':
                raise StopIteration
            else:
                raise
        return self.device.snap(1)

class SaneDev:
    """Class representing a SANE device.
    Methods:
    start()    -- initiate a scan, using the current settings
    snap()     -- snap a picture, returning an Image object
    arr_snap() -- snap a picture, returning a numarray object
    cancel()   -- cancel an in-progress scanning operation
    fileno()   -- return the file descriptor for the scanner (handy for select)

    Also available, but rather low-level:
    get_parameters() -- get the current parameter settings of the device
    get_options()    -- return a list of tuples describing all the options.

    Attributes:
    optlist -- list of option names

    You can also access an option name to retrieve its value, and to
    set it.  For example, if one option has a .name attribute of
    imagemode, and scanner is a SaneDev object, you can do:
         print scanner.imagemode
         scanner.imagemode = 'Full frame'
         scanner.['imagemode'] returns the corresponding Option object.
    """
    def __init__(self, devname):
        d=self.__dict__
        d['sane_signature'] = self._getSaneSignature(devname)
        d['scanner_model']  = d['sane_signature'][1:3]
        d['dev'] = _sane._open(devname)
        self.__load_option_dict()

    def _getSaneSignature(self, devname):
        devices = get_devices()
        if not devices:
            raise RuntimeError('no scanner available')
        for dev in devices:
            if devname == dev[0]:
                return dev
        raise RuntimeError('no such scan device "%s"' % devname)

    def __load_option_dict(self):
        d=self.__dict__
        d['opt']={}
        optlist=d['dev'].get_options()
        for t in optlist:
            o=Option(t, self)
            if o.type!=TYPE_GROUP:
                d['opt'][o.py_name]=o

    def __setattr__(self, key, value):
        dev=self.__dict__['dev']
        optdict=self.__dict__['opt']
        if not optdict.has_key(key):
            self.__dict__[key]=value ; return
        opt=optdict[key]
        if opt.type==TYPE_GROUP:
            raise AttributeError, "Groups can't be set: "+key
        if not _sane.OPTION_IS_ACTIVE(opt.cap):
            raise AttributeError, 'Inactive option: '+key
        if not _sane.OPTION_IS_SETTABLE(opt.cap):
            raise AttributeError, "Option can't be set by software: "+key
        if type(value) == int and opt.type == TYPE_FIXED:
            # avoid annoying errors of backend if int is given instead float:
            value = float(value)
        self.last_opt = dev.set_option(opt.index, value)
        # do binary AND to find if we have to reload options:
        if self.last_opt & INFO_RELOAD_OPTIONS:
            self.__load_option_dict()

    def __getattr__(self, key):
        dev=self.__dict__['dev']
        optdict=self.__dict__['opt']
        if key=='optlist':
            return self.opt.keys()
        if key=='area':
            return (self.tl_x, self.tl_y),(self.br_x, self.br_y)
        if not optdict.has_key(key):
            raise AttributeError, 'No such attribute: '+key
        opt=optdict[key]
        if opt.type==TYPE_BUTTON:
            raise AttributeError, "Buttons don't have values: "+key
        if opt.type==TYPE_GROUP:
            raise AttributeError, "Groups don't have values: "+key
        if not _sane.OPTION_IS_ACTIVE(opt.cap):
            raise AttributeError, 'Inactive option: '+key
        value = dev.get_option(opt.index)
        return value

    def __getitem__(self, key):
        return self.opt[key]

    def get_parameters(self):
        """Return a 5-tuple holding all the current device settings:
   (format, last_frame, (pixels_per_line, lines), depth, bytes_per_line)

- format is one of 'L' (grey), 'RGB', 'R' (red), 'G' (green), 'B' (blue).
- last_frame [bool] indicates if this is the last frame of a multi frame image
- (pixels_per_line, lines) specifies the size of the scanned image (x,y)
- lines denotes the number of scanlines per frame
- depth gives number of pixels per sample
"""
        return self.dev.get_parameters()

    def get_options(self):
        "Return a list of tuples describing all the available options"
        return self.dev.get_options()

    def start(self):
        "Initiate a scanning operation"
        return self.dev.start()

    def cancel(self):
        "Cancel an in-progress scanning operation"
        return self.dev.cancel()

    def snap(self, no_cancel=0):
        "Snap a picture, returning a PIL image object with the results"
        (mode, last_frame,
         (xsize, ysize), depth, bytes_per_line) = self.get_parameters()
        if mode in ['gray', 'red', 'green', 'blue']:
            format = 'L'
        elif mode == 'color':
            format = 'RGB'
        else:
            raise ValueError('got unknown "mode" from self.get_parameters()')
        im=Image.new(format, (xsize,ysize))
        self.dev.snap( im.im.id, no_cancel )
        return im

    def scan(self):
        self.start()
        return self.snap()

    def multi_scan(self):
        return _SaneIterator(self)

    def arr_snap(self, multipleOf=1):
        """Snap a picture, returning a numarray object with the results.
        By default the resulting array has the same number of pixels per
        line as specified in self.get_parameters()[2][0]
        However sometimes it is necessary to obtain arrays where
        the number of pixels per line is e.g. a multiple of 4. This can then
        be achieved with the option 'multipleOf=4'. So if the scanner
        scanned 34 pixels per line, you will obtain an array with 32 pixels
        per line.
        """
        (mode, last_frame, (xsize, ysize), depth, bpl) = self.get_parameters()
        if not mode in ['gray', 'red', 'green', 'blue']:
            raise RuntimeError('arr_snap() only works with monochrome images')
        if multipleOf < 1:
            raise ValueError('option "multipleOf" must be a positive number')
        elif multipleOf > 1:
            pixels_per_line = xsize - divmod(xsize, 4)[1]
        else:
            pixels_per_line = xsize
        return self.dev.arr_snap(pixels_per_line)

    def arr_scan(self, multipleOf=1):
        self.start()
        return self.arr_snap(multipleOf=multipleOf)

    def fileno(self):
        "Return the file descriptor for the scanning device"
        return self.dev.fileno()

    def close(self):
        self.dev.close()

def open(devname):
    "Open a device for scanning"
    new=SaneDev(devname)
    return new


text:
LLEVM
====================
llevm is an erlang wrapper to the C API functions of llvm.
The documentation of the functions can be found at the official
[llvm website]( http://llvm.org/doxygen/dir_ba5bdc16f452288d1429bb9e178a5965.html ).
Unfortunately the documentation of the C functions seem to be very
sparse, so when looking for what functions do one should try to find
the corresponding C++ class function and read the documentation for it
instead.

For examples on how to use llevm see the testcases, especially
`tests/kaleidoscope_SUITE.erl` and `tests/kaleidoscope_SUITE_data/kal_gen.erl`
contain lots of basics in how to generate llvm code and use the JIT
execution engine from Erlang.

Most functions are converted to erlang and hopefully work as well :)
There is a list of which functions are not as yet converted in
`api_gen/llvm_api.hrl`. The functions are listed in the LIMIT macro.

Compiling
--------------------
You should only have to run

    ./configure && make

to compile llevm. Make sure that the correct llvm version is in the
path.

Some possible issues when compiling are:

 * The erlang vm and llvm has to have the same arch (i.e. 64 vs 32 bit)
 * You have to have the correct version of llvm.
   As of this writing that is 2.9. If you need another version you have
   to regenerate all the erlang and nif files.

Generating a new llevm
--------------------
If you are not happy with the generated API you can regenerate it
to suite your needs. To do this you have to have doxygen in your path then run:

    ./configure && (cd api_gen && make)

then new `src/llevm.erl`, `csrc/llevm.c` and `include/llevm.hrl` should be
regerated. The code which generated the llevm interface is in the api_gen
folder and divided into the different files that they generate.

Running test
---------------------
llevm comes with a set of test which tests that everything works as it should.
To run the tests type:

    make test

The tests are very basic and are more there to provide examples than to test
the actual interface. So just because they pass don't trust that llevm does
what it should :)

Debugging
---------------------
It is possible to enable lots of debug printouts in `api_gen/llvm_api_nif.erl`.
Just search for printf and uncomment those lines and then regenerate llevm.
It is also helpful to use gdb to step through execution, there are some
example commands in `os_lathund` to show how I do it on my mac.


text:
import Component from '@ember/component';
import { computed } from '@ember/object';
import { isNone } from '@ember/utils';
import layout from '../templates/components/em-form-submit';

/*
Form Submit Button

Syntax:
{{em-form-submit text="Submit"}}
 */
export default Component.extend({
  layout: layout,
  classes: 'btn btn-default',
  classNames: ['form-group'],
  text: 'Submit',
  type: 'submit',
  horiClass: 'col-sm-offset-2 col-sm-10',
  disabled: computed('model.isValid', {
    get() {
      if (this.get('form.showErrorsOnSubmit') && !this.get('form.isSubmitted')) {
        return false;
      }

      if (!isNone(this.get('model.isValid'))) {
        return !this.get('model.isValid');
      } else {
        return false;
      }
    }
  }),

  actions: {
    submit() {
      if(typeof this.submitAction === 'function'){
        this.submitAction(this.get('form.model'));
      }
    }
  }
});


text:
/**
 * ngTable: Table + Angular JS
 *
 * @author Vitalii Savchuk <esvit666@gmail.com>
 * @url https://github.com/esvit/ng-table/
 * @license New BSD License <http://creativecommons.org/licenses/BSD/>
 */
import * as ng1 from 'angular';
/**
 * The angular provider used to configure the behaviour of the `NgTableFilterConfig` service.
 */
export var NgTableFilterConfigProvider = (function () {
    function NgTableFilterConfigProvider($injector) {
        var _this = this;
        this.defaultConfig = {
            defaultBaseUrl: 'ng-table/filters/',
            defaultExt: '.html',
            aliasUrls: {}
        };
        this.$get = function () {
            return $injector.instantiate(NgTableFilterConfig, { config: ng1.copy(_this.config) });
        };
        this.$get.$inject = [];
        this.resetConfigs();
    }
    /**
     * Reset back to factory defaults the config values that `NgTableFilterConfig` service will use
     */
    NgTableFilterConfigProvider.prototype.resetConfigs = function () {
        this.config = this.defaultConfig;
    };
    /**
     * Set the config values used by `NgTableFilterConfig` service
     */
    NgTableFilterConfigProvider.prototype.setConfig = function (customConfig) {
        var mergeConfig = ng1.extend({}, this.config, customConfig);
        mergeConfig.aliasUrls = ng1.extend({}, this.config.aliasUrls, customConfig.aliasUrls);
        this.config = mergeConfig;
    };
    NgTableFilterConfigProvider.$inject = ['$injector'];
    return NgTableFilterConfigProvider;
}());
/**
 * Exposes configuration values and methods used to return the location of the html
 * templates used to render the filter row of an ng-table directive
 */
export var NgTableFilterConfig = (function () {
    function NgTableFilterConfig(
        /**
         * Readonly copy of the final values used to configure the service.
         */
        config) {
        this.config = config;
    }
    /**
     * Return the url of the html filter template registered with the alias supplied
     */
    NgTableFilterConfig.prototype.getUrlForAlias = function (aliasName, filterKey) {
        return this.config.aliasUrls[aliasName] || this.config.defaultBaseUrl + aliasName + this.config.defaultExt;
    };
    /**
     * Return the url of the html filter template for the supplied definition and key.
     * For more information see the documentation for {@link IFilterTemplateMap}
     */
    NgTableFilterConfig.prototype.getTemplateUrl = function (filterDef, filterKey) {
        var filterName;
        if (typeof filterDef !== 'string') {
            filterName = filterDef.id;
        }
        else {
            filterName = filterDef;
        }
        if (filterName.indexOf('/') !== -1) {
            return filterName;
        }
        return this.getUrlForAlias(filterName, filterKey);
    };
    NgTableFilterConfig.$inject = ['config'];
    return NgTableFilterConfig;
}());
//# sourceMappingURL=ngTableFilterConfig.js.map


text:
package org.teavm.flavour.regex;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 *
 * @author Alexey Andreev
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Regex {
    String[] value();
}


text:
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution:
    # @param root, a tree node
    # @return a list of integers
    def preorderTraversal(self, root):
        if not root: return []
        s = []
        s.append(root.val)
        s.extend(self.preorderTraversal(root.left))
        s.extend(self.preorderTraversal(root.right))
        return s

if __name__ == '__main__':
    s = Solution()
    root = TreeNode(1)
    root.right = TreeNode(2)
    root.right.left = TreeNode(3)

    assert [1,2,3] == s.preorderTraversal(root)


text:
package servlets;
import helperClasses.Const;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import database.dto.Bruger;
import database.interfaces.IDatabaseController;

/**@author Christian, Martin, Magnus
 * refactor og update: Rúni
 * Servlet implementation class LoginServlet
 *
 */
@SuppressWarnings("serial")
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet
{
	public LoginServlet()
	{
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		IDatabaseController databaseController =(IDatabaseController) request.getSession().getAttribute(Const.DATABASE_CONTROLLER);
		//Check for login
		if(databaseController == null){
			response.sendRedirect(Const.MAIN_SERVLET);
		}else if (request.getSession().getAttribute(Const.ACTIVE_USER)!= null)
			response.sendRedirect(Const.MAIN_SERVLET + "?page=" + "loggingIn");
		else
			request.getRequestDispatcher(Const.LOGIN_PAGE).forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		IDatabaseController databaseController =(IDatabaseController) request.getSession().getAttribute(Const.DATABASE_CONTROLLER);
		//User posts login data
		String username = request.getParameter(Const.USERNAME);
		String password = request.getParameter(Const.PASSWORD);
		if(databaseController == null){
			response.sendRedirect(Const.MAIN_SERVLET);
		}
		else if (username != null && password != null)
		{
			boolean loginSuccess = false;

			loginSuccess = databaseController.getBrugerDao().validate(username, password);
			System.out.println(loginSuccess);
			if (loginSuccess)
			{
					Bruger loggedInUser= databaseController.getBrugerDao().findByUserName(username, password);

					if(loggedInUser.getErAktiv())
					{
						request.getSession().setAttribute(Const.ACTIVE_USER, loggedInUser );
						response.sendRedirect(Const.MAIN_SERVLET + "?page=loggingIn");
					}
					else
					{
						request.setAttribute(Const.LOGIN_FAILED, true);
						request.getRequestDispatcher(Const.LOGIN_PAGE).forward(request, response);
					}
			}
			else
			{
				request.setAttribute(Const.LOGIN_FAILED, true);
				request.getRequestDispatcher(Const.LOGIN_PAGE).forward(request, response);
			}

		}
		else
		{
			if (request.getParameter(Const.USERNAME) != null)
				request.setAttribute(Const.LOGIN_FAILED, true);
			request.getRequestDispatcher(Const.LOGIN_PAGE).forward(request, response);
		}
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.etiyaprogressview.MainActivity">

    <com.etiya.progressview.EtiyaProgressView
        android:id="@+id/etiyaProgressView"
        android:layout_width="190dp"
        android:layout_height="190dp"
        android:layout_centerInParent="true"
        android:layout_gravity="center" />

</RelativeLayout>