text:
/**
 * Author: Alex Swanson 103706731?
 * Date started: Early Sept
 * Date Completed: IP
 * Peer Review: Anthony Sager
 * Date: 11/12/2014 (Reviewed)
 * Team members: Buddy Corp
 * Contribution: IP
 *
 *
 */

package com.comp490.studybuddy.calendar;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

import android.app.ActionBar;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.view.GestureDetectorCompat;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.TextView;

import com.comp490.studybuddy.MainActivity;
import com.comp490.studybuddy.R;
import com.comp490.studybuddy.database.DBHelper;
import com.comp490.studybuddy.flashcards.FlashMain;
import com.comp490.studybuddy.models.CalendarEvent;
import com.comp490.studybuddy.note.NoteActivity;
import com.comp490.studybuddy.todolist.ToDoMain;
import com.j256.ormlite.android.apptools.OrmLiteBaseActivity;
import com.j256.ormlite.stmt.PreparedQuery;
import com.j256.ormlite.stmt.QueryBuilder;

/**
 *
 *
 * XMLS:
 * activity_customcal_phone: 2 text views month name, header. Grid View
 * day_button
 */
public class CalenActivity extends OrmLiteBaseActivity<DBHelper> {

	private DateTime displayedDateTime;
	private DateTime todayDateTime;
    private TextView currentMonth;
    //TODO Header for Days MON --> SUN
    private TextView calHeader;
    //Calendar skeleton and adapter
    private GridView calendarGrid;
    //private GridCellAdapter adapter;
    private GridCellAdapterTest adapter;
    private final DateTimeFormatter dateFormatter =
    		DateTimeFormat.forPattern("MMMM yyyy");
    private int width;
    private static int height;
    private ActionBar actionBar;
    private GestureDetectorCompat swipeDetector;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_customcal_phone);
	    ActionBar actionBar = getActionBar();
	    actionBar.setDisplayHomeAsUpEnabled(true);

		this.todayDateTime = new DateTime();
		// Check if returning from different Cal activity goto that Date
		Intent intent = getIntent();
		String dateTimeString = intent.getStringExtra("date");
		if (dateTimeString != null)
			this.displayedDateTime = DateTime.parse(dateTimeString);
		else
			this.displayedDateTime = new DateTime();

		//Set the Name of the Month (Month Year)
        currentMonth = (TextView) this.findViewById(R.id.curr_month);
        currentMonth.setText(displayedDateTime.toString(dateFormatter));

        //TODO Unused Ideally want MON --> SUN as headers to columns
        calHeader = (TextView) this.findViewById(R.id.cal_header);

        //Apply swipe detection to calendar
        swipeDetector = new GestureDetectorCompat(this, new SwipeListener());
        calendarGrid = (GridView) this.findViewById(R.id.gridView1);

        calendarGrid.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent mEvent) {
            	swipeDetector.onTouchEvent(mEvent);
                return true;
            }
        });

        //Initial drawing of the calendar, set to the current month
        changeCalendarDisplay();
	} //End onCreate

	//Swipe Logic to move calendar back and forward
	private class SwipeListener extends GestureDetector.SimpleOnGestureListener {
		private static final String DEBUG_TAG = "Gestures";

		@Override
		public boolean onDown(MotionEvent event) {
			Log.d(DEBUG_TAG,"onDown: " + event.toString());
			   return true;
		}

		@Override
		public boolean onFling(MotionEvent event1, MotionEvent event2,
				float velocityX, float velocityY) {
			        if (velocityX < 0)
			            moveFuture(null);
			        else if (velocityX > 0)
			            movePast(null);
			        return true;
				}
		}

	//ReDraw Calendar when orientation is changed.
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
	    super.onConfigurationChanged(newConfig);
	    changeCalendarDisplay();
	}

	//Logic of how to reDraw Calendar
    private void changeCalendarDisplay()
    {
    	DisplayMetrics metrics = new DisplayMetrics();
	    getWindowManager().getDefaultDisplay().getMetrics(metrics);
        width = metrics.widthPixels;
        height = metrics.heightPixels;
        //adapter = new GridCellAdapter(getApplicationContext(), R.id.grid_day);
        adapter = new GridCellAdapterTest(getApplicationContext(), R.id.cellList);
        currentMonth.setText(displayedDateTime.toString(dateFormatter));
        adapter.notifyDataSetChanged();
        calendarGrid.setAdapter(adapter);
    }

	//Swipe Right, move the calendar back one month
	public void movePast(View v)
	{
		this.displayedDateTime = this.displayedDateTime.minusMonths(1);
		changeCalendarDisplay();
	}

	//Swipe Left, move the calendar forward one month
	public void moveFuture(View v)
	{
		this.displayedDateTime = this.displayedDateTime.plusMonths(1);
		changeCalendarDisplay();
    }

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		actionBar = getActionBar();
	    actionBar.show();
		getMenuInflater().inflate(R.menu.calen, menu);
		menu.findItem(R.id.createEvent).setVisible(false);
		menu.findItem(R.id.editEvent).setVisible(false);
		return super.onCreateOptionsMenu(menu);
	}

	//User hits "+" to create a new event
	//Pass the DateTime object for the currently viewed month
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		switch(id) {
	      	case android.R.id.home:
	      		startActivity(new Intent(this, MainActivity.class));
	      		return true;
			case R.id.addEvent:
				Intent intent = new Intent(getApplicationContext(), AddEvent.class);
				intent.putExtra("DT", displayedDateTime.toString());
				intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
			    startActivity(intent);
			    return true;
			    /*
			case R.id.action_launch_text: {
				startActivity(new Intent(this, NoteActivity.class));
				finish();
				return true;
				      }
			case R.id.action_launch_flashcards: {
				startActivity(new Intent(this, FlashMain.class));
				finish();
				return true;
				      }
			case R.id.action_launch_todo: {
				startActivity(new Intent(this, ToDoMain.class));
				finish();
				return true;
				      }
				      */
			default:
				return super.onOptionsItemSelected(item);
		}
	}

	//Begin Adapter Land, First GridCells --> Text(day) and List(events)
	public class GridCellAdapterTest extends BaseAdapter
	{
		ListView gridcell;
		TextView date;
        private final Context context;
        private final List<String> list;
        private List<CalendarEvent> eventList;

        public class ViewHolder {
        	TextView date;
        	ListView listEvents;
        }

        public GridCellAdapterTest(Context context, int cellID)
        {
                super();
                this.context = context;
                this.list = new ArrayList<String>();
                DateTime startDate = displayedDateTime.withDayOfMonth(displayedDateTime.dayOfMonth().getMinimumValue()).withDayOfWeek(displayedDateTime.dayOfWeek().getMinimumValue());
            	DateTime endDate = displayedDateTime.withDayOfMonth(displayedDateTime.dayOfMonth().getMaximumValue()).withDayOfWeek(displayedDateTime.dayOfWeek().getMaximumValue());

            	//Iterate over every date in the period (startDate --> endDate).
            	for (DateTime date = startDate; date.isBefore(endDate.plusDays(1)); date = date.plusDays(1)) {
            		list.add(date.toString());
            	}
            	getEvents();
        }

        public void getEvents() {
        	Log.d("TAG", "Called GetEVENTS");
        	//Get the previous month and next month from the displayed month
        	DateTime prevDT = new DateTime(displayedDateTime);
        	prevDT = prevDT.minusMonths(1);
        	DateTime nextDT = new DateTime(displayedDateTime);
        	nextDT = nextDT.plusMonths(1);
        	//Turn to Strings
        	String prev = prevDT.toString();
        	String curr = displayedDateTime.toString();
        	String next = nextDT.toString();
        	//Get relevant part Year and Month
        	prev = prev.substring(0,7)+"%";
        	curr = curr.substring(0,7)+"%";
        	next = next.substring(0,7)+"%";

    	    //Get Events For the Day
    		try {
    			QueryBuilder<CalendarEvent, ?> queryBuilder = getHelper().getCalendarEventDao().queryBuilder();
    			queryBuilder.where()
    				.like(CalendarEvent.CAL_EVENT_START_DATE, prev).or()
    				.like(CalendarEvent.CAL_EVENT_START_DATE, curr).or()
    				.like(CalendarEvent.CAL_EVENT_START_DATE, next);
    			PreparedQuery<CalendarEvent> preparedQuery = queryBuilder.prepare();
    			eventList = getHelper().getCalendarEventDao().query(preparedQuery);
    		} catch (SQLException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    	}

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
        	List<CalendarEvent> dayEvents = new ArrayList<CalendarEvent>();
        	View row = convertView;
            if (row == null)
            {
                LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                row = inflater.inflate(R.layout.cal_cell_list, parent, false);
                //Workingish. Should be based on number of rows...
                row.setLayoutParams(new GridView.LayoutParams(width/8, height/9));
            }
            gridcell = (ListView) row.findViewById(R.id.cellList);
            date = (TextView) row.findViewById(R.id.dayNumber);
            DateTime temp = DateTime.parse(list.get(position));
            date.setText(""+temp.getDayOfMonth());
            String thisYearMonDay = temp.toString().substring(0,10);
            //only call gird adapter if necessary
            if(eventList.isEmpty() == false) {
            	for(Iterator<CalendarEvent> i = eventList.iterator(); i.hasNext();) {
                	CalendarEvent tempEvent = i.next();
                	String dateTimeString = tempEvent.getStart().toString().substring(0,10);
                	if (dateTimeString.equals(thisYearMonDay)){
                		dayEvents.add(tempEvent);
                	}
                	if (dayEvents.isEmpty() == false) {
                		eventList.remove(dayEvents);
                		CustomListAdapter adapter = new CustomListAdapter(getBaseContext(),
                	    	R.layout.cal_day_listitem, dayEvents);
                		gridcell.setAdapter(adapter);
                	}

                }
             }

             //set a tag with the date on the views
             String tag = thisYearMonDay;
             gridcell.setTag(tag);
             row.setTag(tag);

             //Day is Touched
             row.setOnClickListener(new View.OnClickListener() {
    			@Override
    			public void onClick(View view) {
    				Log.v("TAG", view.getTag().toString());
    				launchDay( view.getTag().toString());
    			}
    		 });

             //List Item is touched
             gridcell.setClickable(true);
             gridcell.setOnItemClickListener(new OnItemClickListener() {
    			@Override
				public void onItemClick(AdapterView<?> arg0,
					View arg1, int arg2, long arg3) {
						Log.v("TAG", arg1.getTag().toString());
						launchDay(arg1.getTag().toString());

					}
    		    });

             return row;
         }

         public void launchDay(String day) {
        	 //Get the tag of the day touched. Eg. February-2-2015
        	 String year_month_day = day;
        	 //Turn into Date Time object
        	 DateTimeFormatter format = DateTimeFormat.forPattern("yyyy-MM-dd");
        	 DateTime monthDayYear = format.parseDateTime(year_month_day);
        	 //Pack information into event
        	 Intent dayLaunch = new Intent(CalenActivity.this, DayDetails.class);
        	 dayLaunch.putExtra("Day", year_month_day);
        	 dayLaunch.putExtra("DT", monthDayYear.toString());
        	 startActivity(dayLaunch);
       }

        @Override
        public int getCount()
        {
            return list.size();
        }

        @Override
        public String getItem(int position)
        {
            return list.get(position);
        }

        @Override
        public long getItemId(int position)
        {
            return position;
        }

	} //End GridAdapter

	//List Adapter to turn grid cells(days) into a List of events
	private class CustomListAdapter extends ArrayAdapter<CalendarEvent> {
		private Context mContext;
		private int id;
		private List<CalendarEvent> events;

		public CustomListAdapter(Context context, int textViewId,
				List<CalendarEvent> eventList) {
			super(context, textViewId, eventList);
			mContext = context;
			id = textViewId;
			events = eventList;

		}

		@Override
		public View getView(int position, View v, ViewGroup parent) {
			View mView = v;
			if(mView == null) {
				LayoutInflater vi = (LayoutInflater)mContext.getSystemService
						(Context.LAYOUT_INFLATER_SERVICE);
				mView = vi.inflate(R.layout.cal_day_listitem, null);
			}

			mView.setTag(((View) parent.getParent()).getTag());
			ListView list = (ListView) parent;
			Log.d("TEST", (String) list.getTag());
			TextView text = (TextView) mView.findViewById(R.id.eventItem);

			if(events.get(position) != null) {
					text.setTextColor(Color.WHITE);
					text.setText(events.get(position).getName());
					Log.d("DAYDETAIL", ""+events.get(position).getName());
					int color = colorFinder(events.get(position).getColor());
					text.setBackgroundColor(getResources().getColor(color));
			}

			return mView;
		}

		private int colorFinder(String color)
		{
			int androidColor = R.color.blue;
			if (color == null) { return androidColor;}
			switch(color) {
				case "Blue":
					break;
				case "Purple":
					androidColor = R.color.purple;
					break;
				case "Green":
					androidColor = R.color.green;
					break;
				case "Orange":
					androidColor = R.color.orange;
					break;
				case "Red":
					androidColor = R.color.red;
					break;
				default:
					break;
			}
			return androidColor;

		}
	}// End of ListAdapter

}// End CalenActivity


text:
[![NPM version](https://badge.fury.io/js/eventuate-map.png)](http://badge.fury.io/js/eventuate-map)
[![Build Status](https://travis-ci.org/Georgette/eventuate-map.svg?branch=master)](https://travis-ci.org/Georgette/eventuate-map)
[![Coverage Status](https://coveralls.io/repos/Georgette/eventuate-map/badge.png?branch=master)](https://coveralls.io/r/Georgette/eventuate-map?branch=master)

create a mapped eventuate

## example

```javascript

var eventuate = require('eventuate'),
    map       = require('eventuate-map')

var pie = eventuate()
pie(function (p) {
    console.log('%s served...', p.type)
})

var addTopping = map(pie, function (pie) {
    switch (pie.type) {
        case 'shoofly':
            pie.topping = 'vanilla ice cream'
            break
        case 'pumpkin':
            pie.topping = 'whipped cream'
            break
        case 'apple':
            pie.topping = 'maple walnut syrup'
            break
        default:
            pie.topping = 'a cherry'
    }
    return pie
})

addTopping(function (p) {
    console.log('Love %s on my %s pie', p.topping, p.type)
})

pie.produce({type: 'apple' })
pie.produce({type: 'shoofly' })
pie.produce({type: 'pumpkin' })

```

## api

```javascript
var eventuate = require('eventuate')
var map       = require('eventuate-map')

var upstreamEventuate = eventuate()
```

### var mappedEventuate = map(upstreamEventuate, mapFunc)

Returns a new eventuate which produces mapped event payloads from eventuate `upstreamEventuate` using `mapFunc` .  `mapFunc` should have the signature `function (data) { }`, and return the mapped payload. This function receives all event data from `upstreamEventuate`.

If `upstreamEventuate` is an unmonitored eventuate, `filteredEventuate` will return an unmonitored eventuate.

### mappedEventuate.unsubscribe()

Stop consuming events from `upstreamEventuate` (and thus stop producing events).

### mappedEventuate.upstreamConsumer

The function added as a consumer to the `upstreamEventuate`. Example:

```javascript
var consumerIdx = upstreamEventuate.consumers.indexOf(mappedEventuate.upstreamConsumer)
assert(consumerIdx >= 0)
```

## install

With [npm](https://npmjs.org) do:

```
npm install eventuate-map
```

## testing

`npm test [--dot | --spec] [--phantom] [--grep=pattern]`

Specifying `--dot` or `--spec` will change the output from the default TAP style.
Specifying `--phantom` will cause the tests to run in the headless phantom browser instead of node.
Specifying `--grep` will only run the test files that match the given pattern.

### browser test

`npm run browser-test`

This will run the tests in all browsers (specified in .zuul.yml). Be sure to [educate zuul](https://github.com/defunctzombie/zuul/wiki/cloud-testing#2-educate-zuul) first.

### coverage

`npm run coverage [--html]`

This will output a textual coverage report. Including `--html` will also open
an HTML coverage report in the default browser.

redpajama_set_name: RedPajamaGithub


text:
<?php
namespace Jacopo\Authentication\Middleware\Interfaces;

interface ConfigRepositoryInterface {
    public function setOption($key, $value);

    public function getOption($key);
}


text:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <gradient android:angle="90"
                android:startColor="@android:color/darker_gray"
                android:centerColor="@android:color/darker_gray"
                android:endColor="@android:color/darker_gray" />
        </shape>
    </item>
    <item android:top="2dp" android:left="2dp"
        android:right="2dp" android:bottom="2dp">
        <shape android:shape="rectangle">
            <solid android:color="@android:color/darker_gray" />
        </shape>
    </item>
</layer-list>


text:
namespace chrono {

class CH_SUBSYS_API SuspensionTest : public ChSuspensionTest
{
public:
  /// This takes a vehicle JSON file, and only keeps data
  ///  pertinent to suspension testing rig (e.g., things on the front)
  SuspensionTest(const std::string& filename);

  ~SuspensionTest();

  virtual ChCoordsys<> GetLocalDriverCoordsys() const { return m_driverCsys; }

  virtual void Initialize(const ChCoordsys<>& chassisPos);
  /// each timestep, specify the steer angle, displacement of posts and tire forces.
  /// NOTE: not using the tire_forces, constraints result in kinematically driven test rig.
  virtual void Update(double              time,
                      double              steering,
                      double              disp_L,
                      double              disp_R,
                      const ChTireForces& tire_forces);

  /// Log info to console
  void DebugLog(int console_what);

  /// Log info to data file. data types to be saved should already set in Save_DebugLog()
  void SaveLog();

  /// setup class to save the log to a file for python postprocessing.
  /// Usage: call after construction & Initialize(), else no data is saved.
  void Save_DebugLog(int what,
                     const std::string& out_filename = "log_SuspensionTest.csv");

  // Accessors
  double GetSpringForce(const ChWheelID& wheel_id) const;
  double GetSpringLength(const ChWheelID& wheel_id) const;
  double GetSpringDeformation(const ChWheelID& wheel_id) const;

  double GetShockForce(const chrono::ChWheelID& wheel_id) const;
  double GetShockLength(const chrono::ChWheelID& wheel_id) const;
  double GetShockVelocity(const chrono::ChWheelID& wheel_id) const;

  double GetActuatorDisp(const chrono::ChWheelID& wheel_id)const;
  double GetActuatorForce(const chrono::ChWheelID& wheel_id)const;
  double GetActuatorMarkerDist(const chrono::ChWheelID& wheel_id)const;

  // also sets local vars for re-use
  double Get_KingpinAng(const chrono::ChVehicleSide side);
  double Get_KingpinOffset(const chrono::ChVehicleSide side);
  double Get_CasterAng(const chrono::ChVehicleSide side);
  double Get_CasterOffset(const chrono::ChVehicleSide side);
  double Get_ToeAng(const chrono::ChVehicleSide side);
  double Get_LCArollAng();

  ChVector<> GetPostSurfacePos(const chrono::ChVehicleSide& side);

private:

  int                      m_num_axles;       // number of axles on test rig always 1

  ChVector<>               m_suspLocation;   // locations of the suspensions relative to chassis

  ChVector<>               m_steeringLoc;     // location of the steering relative to chassis
  ChQuaternion<>           m_steeringRot;     // orientation of the steering relative to chassis
  int                      m_steer_susp;      // index of the steered suspension

  ChVector<> m_groundCOM;                     // location of the chassis COM in the chassis reference frame

  ChCoordsys<> m_driverCsys;                  // driver position and orientation relative to chassis
  double m_post_height;                       // post height, for visuals
  double m_post_rad;                          // post radius, for visuals
  bool m_save_log_to_file;                    // save the DebugLog() info to file? default false
  bool m_log_file_exists;                     // written the headers for log file yet?
  std::string m_log_file_name;
  int m_log_what;

  // rig/steer inputs
  double m_steer;
  double m_postDisp[2];

  // suspension measurement data
  double m_KA[2]; // kingpin angle [rad]
  double m_Koffset[2]; // kingpin offset
  double m_CA[2]; // wheel caster angle [rad]
  double m_Coffset[2];  // wheel caster offset
  double m_TA[2]; // wheel toe angle
  double m_suspensionRoll;

  // Private functions

  void LoadSteering(const std::string& filename);
  void LoadSuspension(const std::string& filename, int axle, bool driven);
  void LoadWheel(const std::string& filename, int axle, int side);

  static void AddVisualize_post(ChSharedBodyPtr post_body,
                                ChSharedBodyPtr ground_body,
                                double height,
                                double rad,
                                const ChColor& color = ChColor(0.1f, 0.8f, 0.15f) );

  void create_fileHeader(int what);
};

} // end namespace chrono

#endif


text:
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using Microsoft.MixedReality.Toolkit.SpatialAwareness;
using Microsoft.MixedReality.Toolkit.Utilities;
using System.Collections.Generic;
using UnityEngine;

namespace Microsoft.MixedReality.Toolkit.Tests.EditMode.Services
{
    internal interface ITestSpatialAwarenessDataProvider : IMixedRealityDataProvider, ITestService, IMixedRealitySpatialAwarenessObserver, IMixedRealitySpatialAwarenessMeshObserver
    {
    }

    /// <summary>
    /// Dummy test IMixedRealitySpatialAwarenessObserver implementation only used for testing
    /// </summary>
    [MixedRealityDataProvider(
        typeof(IMixedRealitySpatialAwarenessSystem),
        (SupportedPlatforms)(-1), // All platforms supported by Unity
        "Test Spatial Awareness Data Provider",
        "Profiles/DefaultMixedRealitySpatialAwarenessMeshObserverProfile.asset",
        "MixedRealityToolkit.SDK")]
    public class TestSpatialAwarenessDataProvider : TestBaseDataProvider, ITestSpatialAwarenessDataProvider
    {
        public TestSpatialAwarenessDataProvider(
            IMixedRealitySpatialAwarenessSystem spatialAwarenessSystem,
            string name,
            uint priority,
            BaseMixedRealityProfile profile) : base(spatialAwarenessSystem, name, priority, profile) { }

        public AutoStartBehavior StartupBehavior { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); }
        public int DefaultPhysicsLayer => throw new System.NotImplementedException();
        public bool IsRunning => throw new System.NotImplementedException();
        public bool IsStationaryObserver { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); }
        public VolumeType ObserverVolumeType { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); }
        public Vector3 ObservationExtents { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); }
        public Quaternion ObserverRotation { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); }
        public Vector3 ObserverOrigin { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); }
        public float UpdateInterval { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); }
        public uint SourceId => throw new System.NotImplementedException();
        public string SourceName => throw new System.NotImplementedException();
        public SpatialAwarenessMeshDisplayOptions DisplayOption { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); }
        public SpatialAwarenessMeshLevelOfDetail LevelOfDetail { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); }
        public IReadOnlyDictionary<int, SpatialAwarenessMeshObject> Meshes => throw new System.NotImplementedException();
        public int MeshPhysicsLayer { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); }
        public int MeshPhysicsLayerMask => throw new System.NotImplementedException();
        public bool RecalculateNormals { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); }
        public int TrianglesPerCubicMeter { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); }
        public Material OcclusionMaterial { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); }
        public Material VisibleMaterial { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); }

        public void Resume() { throw new System.NotImplementedException(); }
        public void Suspend() { throw new System.NotImplementedException(); }
        public void ClearObservations() { throw new System.NotImplementedException(); }
        public new bool Equals(object x, object y) { throw new System.NotImplementedException(); }
        public int GetHashCode(object obj) { throw new System.NotImplementedException(); }
    }
}


text:
import json
import os, sys
import numpy as np
import pandas as pd
import SonicScrewdriver as utils
from sklearn.linear_model import LogisticRegression
from sklearn import cross_validation
from scipy.stats.stats import pearsonr
import pickle, csv

def intpart(afloat):
    ''' Given a float between 0 and 1, returns an index between 0 and 99.
    We use this to index into precision and recall curves that were calculated
    with thresholds varying through range(0, 1, 0.01).
    '''
    idx = (int(afloat*100))
    if idx < 0:
        idx = 0
    if idx > 99:
        idx = 99
    return idx

def calibrate(probability, curveset):
    ''' Simply returns the corpus precision and recall estimates appropriate
    for a given volume probability.
    '''

    idx = intpart(probability)
    precision = curveset['precision'][idx]
    recall = curveset['recall'][idx]
    return idx/100, precision, recall

def sequence_to_counts(genresequence):
    '''Converts a sequence of page-level predictions to
    a dictionary of counts reflecting the number of pages
    assigned to each genre. Also reports the largest genre.
    Note that this function cannot return "bio." If
    biography is the largest genre it returns "non"fiction.
    It counts bio, but ensures that all votes for bio are also votes
    for non.
    '''

    genrecounts = dict()

    for page in genresequence:
        utils.addtodict(page, 1, genrecounts)
        if page == 'bio':
            utils.addtodict('non', 1, genrecounts)

    # Convert the dictionary of counts into a sorted list, and take the max.
    genretuples = utils.sortkeysbyvalue(genrecounts, whethertoreverse = True)
    maxgenre = genretuples[0][1]

    if maxgenre == 'bio':
        maxgenre = 'non'

    return genrecounts, maxgenre

def count_flips(sequence):
    ''' Volumes that go back and forth a lot between genres are less reliable than
    those with a more stable sequence. So, we count flips.
    '''
    numflips = 0
    prevgenre = ""
    for genre in sequence:
        if genre != prevgenre:
            numflips += 1

        prevgenre = genre

    return numflips

def normalizearray(featurearray):
    '''Normalizes an array by centering on means and
    scaling by standard deviations.
    '''

    numinstances, numfeatures = featurearray.shape
    means = list()
    stdevs = list()
    for featureidx in range(numfeatures):
        thiscolumn = featurearray[ : , featureidx]
        thismean = np.mean(thiscolumn)
        means.append(thismean)
        thisstdev = np.std(thiscolumn)
        stdevs.append(thisstdev)
        featurearray[ : , featureidx] = (thiscolumn - thismean) / thisstdev

    return featurearray

def normalizeformodel(featurearray, modeldict):
    '''Normalizes an array by centering on means and
    scaling by standard deviations associated with the given model.
    This version of the function is designed to operate, actually, on
    a one-dimensional array for a single volume.
    '''

    numfeatures = len(featurearray)
    means = modeldict['means']
    stdevs = modeldict['stdevs']
    for featureidx in range(numfeatures):
        thiscolumn = featurearray[featureidx]
        thismean = means[featureidx]
        thisstdev = stdevs[featureidx]
        featurearray[featureidx] = (thiscolumn - thismean) / thisstdev

    return featurearray

class Prediction:
    ''' Holds information about a single volume, or technically about the
    page-level genre predictions we have made for the volume.
    '''

    def __init__(self, filepath):
        with open(filepath, encoding='utf-8') as f:
            filelines = f.readlines()
        jsonobject = json.loads(filelines[0])
        self.dirtyid = jsonobject['volID']
        self.rawPredictions = jsonobject['rawPredictions']
        self.smoothPredictions = jsonobject['smoothedPredictions']
        self.probabilities = jsonobject['smoothedProbabilities']
        self.avggap = jsonobject['avgGap']
        self.maxprob = jsonobject['avgMaxProb']
        self.pagelen = len(self.smoothPredictions)

        self.genrecounts, self.maxgenre = sequence_to_counts(self.smoothPredictions)
        pagesinmax = self.genrecounts[self.maxgenre]
        self.maxratio = pagesinmax / self.pagelen

        self.rawflipratio = (count_flips(self.rawPredictions) / self.pagelen)
        self.smoothflips = count_flips(self.smoothPredictions)

        if 'bio' in self.genrecounts and self.genrecounts['bio'] > (self.pagelen / 2):
            self.bioflag = True
            print("BIO: " + self.dirtyid)
        else:
            self.bioflag = False

    def addmetadata(self, row, table):
        self.author = table['author'][row]
        self.title = table['title'][row]
        self.date = utils.simple_date(row, table)
        genrelist = table['genres'][row].split(';')
        self.genres = set(genrelist)

        varietiesofnon = ['Bibliographies', 'Catalog', 'Dictionary', 'Encyclopedia', 'Handbooks', 'Indexes', 'Legislation', 'Directories', 'Statistics', 'Legal cases', 'Legal articles', 'Calendars', 'Autobiography', 'Biography', 'Letters', 'Essays', 'Speeches']

        self.nonmetaflag = False
        for genre in varietiesofnon:
            if genre in self.genres:
                self.nonmetaflag = True

    def missingmetadata(self):
        self.author = ''
        self.title = ''
        self.date = ''
        self.genres = set()
        self.nonmetaflag = False

    def getfeatures(self):
        ''' Returns features used for an overall accuracy prediction. There are more of
        these (13) than we use for genre-specific predictions. See logisticconfidence.py
        for more information about features.
        '''

        features = np.zeros(13)

        if self.maxgenre == 'fic':

            if 'Fiction' in self.genres or 'Novel' in self.genres or 'Short stories' in self.genres:
                features[0] = 1

            if 'Drama' in self.genres or 'Poetry' in self.genres or self.nonmetaflag:
                features[1] = 1

        if self.maxgenre == 'poe':

            if 'Poetry' in self.genres or 'poems' in self.title.lower():
                features[2] = 1

            if 'Drama' in self.genres or 'Fiction' in self.genres or self.nonmetaflag:
                features[3] = 1

        if self.maxgenre == 'dra':
            if 'Drama' in self.genres or 'plays' in self.title.lower():
                features[4] = 1

            if 'Fiction' in self.genres or 'Poetry' in self.genres or self.nonmetaflag:
                features[5] = 1

        if self.maxgenre == 'non':

            if self.nonmetaflag:
                features[6] = 1

            if 'Fiction' in self.genres or 'Poetry' in self.genres or 'Drama' in self.genres or 'Novel' in self.genres or 'Short stories' in self.genres:
                features[7] = 1

        features[8] = self.maxratio
        features[9] = self.rawflipratio
        features[10] = self.smoothflips
        features[11] = self.avggap
        features[12] = self.maxprob

        return features

    def genrefeatures(self, agenre):
        ''' Extracts features to characterize the likelihood of accuracy in a
        particular genre.
        '''

        if agenre in self.genrecounts:
            pagesingenre = self.genrecounts[agenre]
        else:
            pagesingenre = 0

        genreproportion = pagesingenre / self.pagelen

        features = np.zeros(8)

        if agenre == 'fic':

            if 'Fiction' in self.genres or 'Novel' in self.genres or 'Short stories' in self.genres:
                features[0] = 1

            if 'Drama' in self.genres or 'Poetry' in self.genres or self.nonmetaflag:
                features[1] = 1

        if agenre == 'poe':

            if 'Poetry' in self.genres or 'poems' in self.title.lower():
                features[0] = 1

            if 'Drama' in self.genres or 'Fiction' in self.genres or self.nonmetaflag:
                features[1] = 1

        if agenre == 'dra':

            if 'Drama' in self.genres or 'plays' in self.title.lower():
                features[0] = 1

            if 'Fiction' in self.genres or 'Poetry' in self.genres or self.nonmetaflag:
                features[1] = 1

        features[2] = genreproportion
        features[3] = self.rawflipratio
        features[4] = self.smoothflips
        features[5] = self.avggap
        features[6] = self.maxprob
        features[7] = self.maxratio

        return features

    def getpredictions(self):
        ''' A getter function that transforms a list of page predictions into a dictionary. It's
        debatable whether we should be representing pages as a dictionary, since our sequencing logic
        not in fact allow skipped pages! But I'm doing it this way because it will be more flexible
        in the long run, in case something happens that I can't anticipate.
        '''
        pagedict = dict()
        for idx, genre in enumerate(self.smoothPredictions):
            pagedict[idx] = genre
        return pagedict

    def getmetadata(self):
        ''' Basically just a getter function for metadata in a Prediction object. Only thing
        interesting is that it filters out certain genre tags known to be unreliable or convey
        little information.
        '''
        metadict = dict()
        metadict['htid'] = self.dirtyid
        metadict['author'] = self.author
        metadict['title'] = self.title
        metadict['inferred_date'] = self.date
        genrelist = []
        for genre in self.genres:
            if genre == "NotFiction":
                continue
            if genre == "UnknownGenre":
                continue
            if genre == "ContainsBiogMaterial":
                continue

            # In my experience, none of those tags are informative in my Hathi dataset.

            genrelist.append(genre.lower())

        metadict['genre_tags'] = ", ".join(genrelist)
        return metadict

# Begin main script.

args = sys.argv

sourcedirfile = args[1]
with open(sourcedirfile, encoding = 'utf-8') as f:
    filelines = f.readlines()

directorylist = [x.strip() for x in filelines]

modeldir = args[2]

genrestocheck = ['fic', 'poe', 'dra']
genrepath = dict()
genremodel = dict()

overallpath = os.path.join(modeldir, 'overallmodel.p')
genrepath['fic'] = os.path.join(modeldir, 'ficmodel.p')
genrepath['dra'] = os.path.join(modeldir, 'dramodel.p')
genrepath['poe'] = os.path.join(modeldir, 'poemodel.p')

with open(overallpath, mode='rb') as f:
    overallmodel = pickle.load(f)

for genre in genrestocheck:
    with open(genrepath[genre], mode='rb') as f:
        genremodel[genre] = pickle.load(f)

fullnames = {'fic': 'fiction', 'poe': 'poetry', 'dra': 'drama'}

# The logistic models we train on volumes are technically
# predicting the probability that an individual volume will
# cross a particular accuracy threshold. For the overall model
# it's .95, for the genres it's .8.

# This doesn't tell us what we really want to know, which is,
# if we construct a corpus of volumes like this, what will our
# precision and recall be? To infer that, we calculate precision
# and recall in the test set using different probability-thresholds,
# smooth the curve, and then use it empiricially to map a
# threshold-probability to a corpus level prediction for precision and recall.

genrestocalibrate = ['overall', 'fic', 'poe', 'dra']

calibration = dict()
for genre in genrestocalibrate:
    calibration[genre] = dict()
    calibration[genre]['precision'] = list()
    calibration[genre]['recall'] = list()

calipath = os.path.join(modeldir, 'calibration.csv')
with open(calipath, encoding = 'utf-8') as f:
    reader = csv.reader(f)
    next(reader, None)
    for row in reader:
        for idx, genre in enumerate(genrestocalibrate):
            calibration[genre]['precision'].append(float(row[idx * 2]))
            calibration[genre]['recall'].append(float(row[(idx * 2) + 1]))

outputdir = args[3]

metadatapath = '/projects/ichass/usesofscale/hathimeta/MergedMonographs.tsv'
# metadatapath = '/Volumes/TARDIS/work/metadata/MergedMonographs.tsv'
# if you run it locally

rows, columns, table = utils.readtsv(metadatapath)

for sourcedir in directorylist:
    predicts = os.listdir(sourcedir)
    predicts = [x for x in predicts if not x.startswith('.')]

    for filename in predicts:
        cleanid = utils.pairtreelabel(filename.replace('.predict', ''))
        fileid = filename.replace('.predict', '')
        filepath = os.path.join(sourcedir, filename)

        try:
            predicted = Prediction(filepath)
        except:
            print("Failure to load prediction from " + filepath)
            continue

        if cleanid in rows:
            predicted.addmetadata(cleanid, table)
        else:
            print('Missing metadata for ' + cleanid)
            predicted.missingmetadata()

        overallfeatures = predicted.getfeatures()
        featurearray = normalizeformodel(np.array(overallfeatures), overallmodel)
        featureframe = pd.DataFrame(featurearray)
        thismodel = overallmodel['model']
        overall95proba = thismodel.predict_proba(featureframe.T)[0][1]

        genreprobs = dict()

        for genre in genrestocheck:
            features = predicted.genrefeatures(genre)
            featurearray = normalizeformodel(np.array(features), genremodel[genre])
            featureframe = pd.DataFrame(featurearray)
            thismodel = genremodel[genre]['model']
            genreprobs[genre] = thismodel.predict_proba(featureframe.T)[0][1]

        jsontemplate = dict()

        jsontemplate['page_genres'] = predicted.getpredictions()
        jsontemplate['hathi_metadata'] = predicted.getmetadata()
        jsontemplate['added_metadata'] = dict()
        jsontemplate['added_metadata']['totalpages'] = predicted.pagelen
        jsontemplate['added_metadata']['maxgenre'] = predicted.maxgenre
        jsontemplate['added_metadata']['genre_counts'] = predicted.genrecounts

        overallprob, overallprecision, overallrecall = calibrate(overall95proba, calibration['overall'])

        overallaccuracy = dict()
        overallaccuracy['prob>95acc'] = overallprob
        overallaccuracy['precision@prob'] = overallprecision
        overallaccuracy['recall@prob'] = overallrecall

        jsontemplate['volume_accuracy'] = overallaccuracy

        for genre in genrestocheck:
            if genre in predicted.genrecounts:
                gpages = predicted.genrecounts[genre]
                gpercent = round((gpages / predicted.pagelen) * 100) / 100
                gprob, gprecision, grecall = calibrate(genreprobs[genre], calibration[genre])
                name = fullnames[genre]
                newdict = dict()
                newdict['prob_' + genre + '>80precise'] = gprob
                newdict['pages_' + genre] = gpages
                newdict['pct_' + genre] = gpercent
                newdict[genre+ '_precision@prob'] = gprecision
                newdict[genre + '_recall@prob'] = grecall
                jsontemplate[name] = newdict

        prefix = filename.split('.')[0]

        subdirectory = os.path.join(outputdir, prefix)
        if not os.path.isdir(subdirectory):
            os.mkdir(subdirectory)

        outpath = os.path.join(subdirectory, fileid + ".json")
        with open(outpath, mode = 'w', encoding = 'utf-8') as f:
            f.write(json.dumps(jsontemplate, sort_keys = True))


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.slender.service.crud.impl;

import com.slender.domain.Company;
import com.slender.hibernate.HibernateUtil;
import com.slender.service.crud.CompanyCrud;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

public class CompanyCrudImpl implements CompanyCrud{
    private Session session;
    private Query query;

    @Override
    public Company findById(Integer id) {
        session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();
        Company company = (Company) session.get(Company.class, id);
        session.close();
        return company;
    }

    @Override
    public List<Company> findAll() {
        session = HibernateUtil.getSessionFactory().openSession();
        query = session.createQuery("from Company");
        List<Company> companys;
        companys = query.list();
        return companys;
    }

    @Override
    public Company persist(Company entity) {
        session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();
        session.save(entity);
        session.flush();
        query = session.createSQLQuery("select last_insert_id() from Company");
        int id = Integer.parseInt(query.list().get(0).toString());
        session.getTransaction().commit();
        session.close();
        return findById(id);
    }

    @Override
    public void merge(Company entity) {
        session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();
        session.merge(entity);
        session.getTransaction().commit();
        session.close();
    }

    @Override
    public void remove(Company entity) {
        session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();
        session.delete(entity);
        session.getTransaction().commit();
        session.close();
    }

    @Override
    public void removeById(int entityId) {
        session = HibernateUtil.getSessionFactory().openSession();
        Company entity = new Company();
        entity.setId(entityId);
        session.beginTransaction();
        session.delete(entity);
        session.getTransaction().commit();
        session.close();
    }

    @Override
    public int count() {
        session = HibernateUtil.getSessionFactory().openSession();
        query = session.createQuery("from Company");
        List<Company> companys = query.list();
        int count = companys.size();
        return count;
    }

    @Override
    public Company getByPropertyName(String name, String value) {
        session = HibernateUtil.getSessionFactory().openSession();
        Criteria criteria = session.createCriteria(Company.class);
        Company entity = (Company) criteria.add(Restrictions.eq(name, value)).uniqueResult();
        session.close();
        return entity;
    }

    @Override
    public Company getByPropertyName(String name, int value) {
        session = HibernateUtil.getSessionFactory().openSession();
        Criteria criteria = session.createCriteria(Company.class);
        Company entity = (Company) criteria.add(Restrictions.eq(name, value)).uniqueResult();
        session.close();
        return entity;
    }

    @Override
    public List<Company> getEntitiesByProperName(String name, String value) {
        session = HibernateUtil.getSessionFactory().openSession();
        Criteria criteria = session.createCriteria(Company.class);
        List<Company> entities = (List) criteria.add(Restrictions.eq(name, value)).list();
        session.close();
        return entities;
    }

    @Override
    public List<Company> getEntitiesByProperName(String name, int value) {
        session = HibernateUtil.getSessionFactory().openSession();
        Criteria criteria = session.createCriteria(Company.class);
        List<Company> entities = (List) criteria.add(Restrictions.eq(name, value)).list();
        session.close();
        return entities;
    }
}


text:
import {Injectable, Optional} from '../di';
import {global} from '../facade/lang';

import {AppModuleFactory} from './app_module_factory';
import {AppModuleFactoryLoader} from './app_module_factory_loader';
import {Compiler} from './compiler';

const _SEPARATOR = '#';

const FACTORY_MODULE_SUFFIX = '.ngfactory';
const FACTORY_CLASS_SUFFIX = 'NgFactory';

/**
 * AppModuleFactoryLoader that uses SystemJS to load AppModuleFactory
 * @experimental
 */
@Injectable()
export class SystemJsAppModuleLoader implements AppModuleFactoryLoader {
  constructor(@Optional() private _compiler: Compiler) {}

  load(path: string): Promise<AppModuleFactory<any>> {
    return this._compiler ? this.loadAndCompile(path) : this.loadFactory(path);
  }

  private loadAndCompile(path: string): Promise<AppModuleFactory<any>> {
    let [module, exportName] = path.split(_SEPARATOR);
    if (exportName === undefined) exportName = 'default';

    return (<any>global)
        .System.import(module)
        .then((module: any) => module[exportName])
        .then((type: any) => checkNotEmpty(type, module, exportName))
        .then((type: any) => this._compiler.compileAppModuleAsync(type));
  }

  private loadFactory(path: string): Promise<AppModuleFactory<any>> {
    let [module, exportName] = path.split(_SEPARATOR);
    if (exportName === undefined) exportName = 'default';

    return (<any>global)
        .System.import(module + FACTORY_MODULE_SUFFIX)
        .then((module: any) => module[exportName + FACTORY_CLASS_SUFFIX])
        .then((factory: any) => checkNotEmpty(factory, module, exportName));
  }
}

function checkNotEmpty(value: any, modulePath: string, exportName: string): any {
  if (!value) {
    throw new Error(`Cannot find '${exportName}' in '${modulePath}'`);
  }
  return value;
}


text:
#if !defined(__VIBRATION_H__)
#define __VIBRATION_H__

#include "scene.h"

/*
	Vibration class to manage vibration
*/
class Vibration
{
public:
	// Constructor & Destructor
	Vibration(int vibrateIntensity, int vibrateTime) : intensity(vibrateIntensity), time(vibrateTime) {}
	~Vibration();

	// Member functions
	void Vibrate();

	bool getVibration() { return changeVibration; }
	void setVibrationMode(bool vibrationOn){ changeVibration = vibrationOn; }
private:
	// Member variables
	int time;
	int intensity;
	bool changeVibration;
};

extern Vibration* g_pVibration;

#endif  // __VIBRATION_H__


text:
import os
import uuid
import json
import argparse

import boto3

TABLES = {
    'app': {
        'prefix': 'todo-app',
        'env_var': 'APP_TABLE_NAME',
        'hash_key': 'username',
        'range_key': 'uid'
    },
    'users': {
        'prefix': 'users-app',
        'env_var': 'USERS_TABLE_NAME',
        'hash_key': 'username',
    }
}

def create_table(table_name_prefix, hash_key, range_key=None):
    table_name = '%s-%s' % (table_name_prefix, str(uuid.uuid4()))
    client = boto3.client('dynamodb')
    key_schema = [
        {
            'AttributeName': hash_key,
            'KeyType': 'HASH',
        }
    ]
    attribute_definitions = [
        {
            'AttributeName': hash_key,
            'AttributeType': 'S',
        }
    ]
    if range_key is not None:
        key_schema.append({'AttributeName': range_key, 'KeyType': 'RANGE'})
        attribute_definitions.append(
            {'AttributeName': range_key, 'AttributeType': 'S'})
    client.create_table(
        TableName=table_name,
        KeySchema=key_schema,
        AttributeDefinitions=attribute_definitions,
        ProvisionedThroughput={
            'ReadCapacityUnits': 5,
            'WriteCapacityUnits': 5,
        }
    )
    waiter = client.get_waiter('table_exists')
    waiter.wait(TableName=table_name, WaiterConfig={'Delay': 1})
    return table_name

def record_as_env_var(key, value, stage):
    with open(os.path.join('.chalice', 'config.json')) as f:
        data = json.load(f)
        data['stages'].setdefault(stage, {}).setdefault(
            'environment_variables', {}
        )[key] = value
    with open(os.path.join('.chalice', 'config.json'), 'w') as f:
        serialized = json.dumps(data, indent=2, separators=(',', ': '))
        f.write(serialized + '\n')

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-s', '--stage', default='dev')
    # app - stores the todo items
    # users - stores the user data.
    parser.add_argument('-t', '--table-type', default='app',
                        choices=['app', 'users'],
                        help='Specify which type to create')
    args = parser.parse_args()
    table_config = TABLES[args.table_type]
    table_name = create_table(
        table_config['prefix'], table_config['hash_key'],
        table_config.get('range_key')
    )
    record_as_env_var(table_config['env_var'], table_name, args.stage)

if __name__ == '__main__':
    main()


text:
({
next: "Siguiente",
previous: "Anterior",
done: "Terminado"
})


text:
package org.red5.server.api;

import org.red5.server.api.event.IEventDispatcher;
import org.red5.server.api.event.IEventHandler;
import org.red5.server.api.event.IEventListener;

/**
 * Base marker interface for all core objects.
 *
 * @author The Red5 Project
 * @author Luke Hubbard (luke@codegent.com)
 *
 */
public interface ICoreObject extends IEventDispatcher, IEventHandler, IEventListener {

}


text:
<?php

namespace Ibw\JobeetBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\HttpFoundation\Request;

class DefaultController extends Controller
{
    public function indexAction($name = 'Jobeet')
    {
        return $this->render('IbwJobeetBundle:Default:index.html.twig', array('name' => $name));
    }

    public function loginAction(Request $request)
    {

        $session = $request->getSession();

        // get the login error if there is one
        if ($request->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) {
            $error = $request->attributes->get(SecurityContext::AUTHENTICATION_ERROR);
        } else {
            $error = $session->get(SecurityContext::AUTHENTICATION_ERROR);
            $session->remove(SecurityContext::AUTHENTICATION_ERROR);
        }

        return $this->render('IbwJobeetBundle:Default:login.html.twig', array(
            // last username entered by the user
            'last_username' => $session->get(SecurityContext::LAST_USERNAME),
            'error'         => $error,
        ));
    }

    public function changeLanguageAction(Request $request)
    {
        $language = $request->get('language');
        return $this->redirect($this->generateUrl('ibw_jobeet_homepage', array('_locale' => $language)));
    }
}


text:
require "spec_helper"

describe Mongoid::Errors do

  describe Mongoid::Errors::DocumentNotFound do

    describe "#message" do

      context "default" do

        before do
          @error = Mongoid::Errors::DocumentNotFound.new(Person, "3")
        end

        it "contains document not found" do
          @error.message.should include("Document not found")
        end
      end
    end
  end

  describe Mongoid::Errors::InvalidOptions do

    describe "#message" do

      context "default" do

        before do
          @error = Mongoid::Errors::InvalidOptions.new
        end

        it "returns the class name" do
          @error.message.should == @error.class.name
        end
      end
    end
  end

  describe Mongoid::Errors::InvalidDatabase do

    describe "#message" do

      before do
        @error = Mongoid::Errors::InvalidDatabase.new("Test")
      end

      it "returns a message with the bad db object class" do
        @error.message.should include("String")
      end
    end
  end

  describe Mongoid::Errors::UnsupportedVersion do

    describe "#message" do

      before do
        @version = Mongo::ServerVersion.new("1.2.4")
        @error = Mongoid::Errors::UnsupportedVersion.new(@version)
      end

      it "returns a message with the bad version and good version" do
        @error.message.should ==
          "MongoDB 1.2.4 not supported, please upgrade to #{Mongoid::MONGODB_VERSION}"
      end
    end
  end

  describe Mongoid::Errors::Validations do

    describe "#message" do

      context "default" do

        before do
          @errors = stub(:full_messages => [ "Error 1", "Error 2" ], :empty? => false)
          @document = stub(:errors => @errors)
          @error = Mongoid::Errors::Validations.new(@document)
        end

        it "contains the errors' full messages" do
          @error.message.should == "Validation Failed: Error 1, Error 2"
        end

        it "allows access to the invalid document" do
          @error.document.should == @document
        end
      end
    end
  end

  describe Mongoid::Errors::InvalidCollection do

    describe "#message" do

      context "default" do

        before do
          @klass = Address
          @error = Mongoid::Errors::InvalidCollection.new(@klass)
        end

        it "contains class is not allowed" do
          @error.message.should include("Address is not allowed")
        end
      end
    end
  end

  describe Mongoid::Errors::InvalidField do

    describe "#message" do

      context "default" do

        before do
          @error = Mongoid::Errors::InvalidField.new("collection")
        end

        it "contains class is not allowed" do
          @error.message.should include("field named 'collection' is not allowed")
        end
      end
    end
  end

  describe Mongoid::Errors::TooManyNestedAttributeRecords do
    describe "#message" do
      context "default" do
        before do
          @error = Mongoid::Errors::TooManyNestedAttributeRecords.new('Favorites', 5)
        end

        it "contains error message" do
          @error.message.should include("Accept Nested Attributes for Favorites is limited to 5 records")
        end
      end
    end
  end
end


text:
from django.contrib import admin

from .models import Profile, Message

@admin.register(Profile)
class ProfileAdmin(admin.ModelAdmin):
    list_display = ('user', 'token', 'age', 'gender', 'city', 'country',)
    list_filter = ('age', 'gender', 'city', 'country',)
    search_fields = ('user__username', 'user__email', 'token', 'religion', 'family', 'selfx', 'community', 'career',)

@admin.register(Message)
class MessageAdmin(admin.ModelAdmin):
    list_display = ('sender', 'recipient', 'timestamp', 'body',)
    list_filter = ('timestamp',)
    search_fields = ('sender__user__username', 'recipient__user__username', 'body',)


text:
#include <aws/imagebuilder/model/ImagePackage.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace imagebuilder
{
namespace Model
{

ImagePackage::ImagePackage() :
    m_packageNameHasBeenSet(false),
    m_packageVersionHasBeenSet(false)
{
}

ImagePackage::ImagePackage(JsonView jsonValue) :
    m_packageNameHasBeenSet(false),
    m_packageVersionHasBeenSet(false)
{
  *this = jsonValue;
}

ImagePackage& ImagePackage::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("packageName"))
  {
    m_packageName = jsonValue.GetString("packageName");

    m_packageNameHasBeenSet = true;
  }

  if(jsonValue.ValueExists("packageVersion"))
  {
    m_packageVersion = jsonValue.GetString("packageVersion");

    m_packageVersionHasBeenSet = true;
  }

  return *this;
}

JsonValue ImagePackage::Jsonize() const
{
  JsonValue payload;

  if(m_packageNameHasBeenSet)
  {
   payload.WithString("packageName", m_packageName);

  }

  if(m_packageVersionHasBeenSet)
  {
   payload.WithString("packageVersion", m_packageVersion);

  }

  return payload;
}

} // namespace Model
} // namespace imagebuilder
} // namespace Aws


text:
@implementation FSTableViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStyleBordered target:nil action:nil];

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {

        // Storyboard Example
        return;

    } else if (indexPath.row == 1) {

        // LoadView Example
        LoadViewExampleViewController *viewController = [[LoadViewExampleViewController alloc] init];
        viewController.title = @"FSCalendar";
        [self.navigationController pushViewController:viewController animated:YES];

    } else if (indexPath.row == 2) {

        // ViewDidLoad Example
        ViewDidLoadExampleViewController *viewController = [[ViewDidLoadExampleViewController alloc] init];
        viewController.title = @"FSCalendar";
        [self.navigationController pushViewController:viewController animated:YES];
    }
}

@end


text:
package org.yellowbinary.server.security.basic.dao;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.yellowbinary.server.security.basic.model.BasicAuthorization;

@Repository
@Transactional
public interface BasicAuthorizationDao extends JpaRepository<BasicAuthorization, Long> {

    @Query("select ba from BasicAuthorization ba where ba.key=?1")
    public BasicAuthorization findByKey(String key);

}


text:
<?php

class Twig_Tests_LexerTest extends PHPUnit_Framework_TestCase
{
    public function testBracketsNesting()
    {
        $template = '{{ {"a":{"b":"c"}} }}';

        $this->assertEquals(2, $this->countToken($template, Twig_Token::PUNCTUATION_TYPE, '{'));
        $this->assertEquals(2, $this->countToken($template, Twig_Token::PUNCTUATION_TYPE, '}'));
    }

    protected function countToken($template, $type, $value = null)
    {
        $lexer = new Twig_Lexer(new Twig_Environment());
        $stream = $lexer->tokenize($template);

        $count = 0;
        $tokens = array();
        while (!$stream->isEOF()) {
            $token = $stream->next();
            if ($type === $token->getType()) {
                if (null === $value || $value === $token->getValue()) {
                    ++$count;
                }
            }
        }

        return $count;
    }

    public function testLineDirective()
    {
        $template = "foo\n"
            . "bar\n"
            . "{% line 10 %}\n"
            . "{{\n"
            . "baz\n"
            . "}}\n";

        $lexer = new Twig_Lexer(new Twig_Environment());
        $stream = $lexer->tokenize($template);

        // foo\nbar\n
        $this->assertSame(1, $stream->expect(Twig_Token::TEXT_TYPE)->getLine());
        // \n (after {% line %})
        $this->assertSame(10, $stream->expect(Twig_Token::TEXT_TYPE)->getLine());
        // {{
        $this->assertSame(11, $stream->expect(Twig_Token::VAR_START_TYPE)->getLine());
        // baz
        $this->assertSame(12, $stream->expect(Twig_Token::NAME_TYPE)->getLine());
    }

    public function testLineDirectiveInline()
    {
        $template = "foo\n"
            . "bar{% line 10 %}{{\n"
            . "baz\n"
            . "}}\n";

        $lexer = new Twig_Lexer(new Twig_Environment());
        $stream = $lexer->tokenize($template);

        // foo\nbar
        $this->assertSame(1, $stream->expect(Twig_Token::TEXT_TYPE)->getLine());
        // {{
        $this->assertSame(10, $stream->expect(Twig_Token::VAR_START_TYPE)->getLine());
        // baz
        $this->assertSame(11, $stream->expect(Twig_Token::NAME_TYPE)->getLine());
    }

    public function testLongComments()
    {
        $template = '{# '.str_repeat('*', 100000).' #}';

        $lexer = new Twig_Lexer(new Twig_Environment());
        $lexer->tokenize($template);

        // should not throw an exception
    }

    public function testLongRaw()
    {
        $template = '{% raw %}'.str_repeat('*', 100000).'{% endraw %}';

        $lexer = new Twig_Lexer(new Twig_Environment());
        $stream = $lexer->tokenize($template);

        // should not throw an exception
    }

    public function testLongBlock()
    {
        $template = '{{ '.str_repeat('*', 100000).' }}';

        $lexer = new Twig_Lexer(new Twig_Environment());
        $stream = $lexer->tokenize($template);

        // should not throw an exception
    }

    public function testLongBlock1()
    {
        $template = '{% '.str_repeat('*', 100000).' %}';

        $lexer = new Twig_Lexer(new Twig_Environment());
        $stream = $lexer->tokenize($template);

        // should not throw an exception
    }
}


text:
/**
 */
package person.zhoujg.feature.impl;

import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;

import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;

import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.impl.MinimalEObjectImpl;

import person.zhoujg.feature.AttributeType;
import person.zhoujg.feature.Feature;
import person.zhoujg.feature.FeatureBody;
import person.zhoujg.feature.FeaturePackage;

/**
 *
 * An implementation of the model object 'Feature'.
 *
 *

 * The following features are implemented:
 *

 *
{@link person.zhoujg.feature.impl.FeatureImpl#getName Name}

 *
{@link person.zhoujg.feature.impl.FeatureImpl#getInCard In Card}

 *
{@link person.zhoujg.feature.impl.FeatureImpl#getBody Body}

 *
{@link person.zhoujg.feature.impl.FeatureImpl#getOutCard Out Card}

 *
{@link person.zhoujg.feature.impl.FeatureImpl#getRef Ref}

 *
{@link person.zhoujg.feature.impl.FeatureImpl#getType Type}

 *

 *

 *
 * @generated
 */
public class FeatureImpl extends MinimalEObjectImpl.Container implements Feature
{
  /**
   * The default value of the '{@link #getName() Name}' attribute.
   *
   *
   * @see #getName()
   * @generated
   * @ordered
   */
  protected static final String NAME_EDEFAULT = null;

  /**
   * The cached value of the '{@link #getName() Name}' attribute.
   *
   *
   * @see #getName()
   * @generated
   * @ordered
   */
  protected String name = NAME_EDEFAULT;

  /**
   * The default value of the '{@link #getInCard() In Card}' attribute.
   *
   *
   * @see #getInCard()
   * @generated
   * @ordered
   */
  protected static final String IN_CARD_EDEFAULT = null;

  /**
   * The cached value of the '{@link #getInCard() In Card}' attribute.
   *
   *
   * @see #getInCard()
   * @generated
   * @ordered
   */
  protected String inCard = IN_CARD_EDEFAULT;

  /**
   * The cached value of the '{@link #getBody() Body}' containment reference.
   *
   *
   * @see #getBody()
   * @generated
   * @ordered
   */
  protected FeatureBody body;

  /**
   * The default value of the '{@link #getOutCard() Out Card}' attribute.
   *
   *
   * @see #getOutCard()
   * @generated
   * @ordered
   */
  protected static final String OUT_CARD_EDEFAULT = null;

  /**
   * The cached value of the '{@link #getOutCard() Out Card}' attribute.
   *
   *
   * @see #getOutCard()
   * @generated
   * @ordered
   */
  protected String outCard = OUT_CARD_EDEFAULT;

  /**
   * The cached value of the '{@link #getRef() Ref}' reference.
   *
   *
   * @see #getRef()
   * @generated
   * @ordered
   */
  protected Feature ref;

  /**
   * The default value of the '{@link #getType() Type}' attribute.
   *
   *
   * @see #getType()
   * @generated
   * @ordered
   */
  protected static final AttributeType TYPE_EDEFAULT = AttributeType.INT;

  /**
   * The cached value of the '{@link #getType() Type}' attribute.
   *
   *
   * @see #getType()
   * @generated
   * @ordered
   */
  protected AttributeType type = TYPE_EDEFAULT;

  /**
   *
   *
   * @generated
   */
  protected FeatureImpl()
  {
    super();
  }

  /**
   *
   *
   * @generated
   */
  @Override
  protected EClass eStaticClass()
  {
    return FeaturePackage.Literals.FEATURE;
  }

  /**
   *
   *
   * @generated
   */
  public String getName()
  {
    return name;
  }

  /**
   *
   *
   * @generated
   */
  public void setName(String newName)
  {
    String oldName = name;
    name = newName;
    if (eNotificationRequired())
      eNotify(new ENotificationImpl(this, Notification.SET, FeaturePackage.FEATURE__NAME, oldName, name));
  }

  /**
   *
   *
   * @generated
   */
  public String getInCard()
  {
    return inCard;
  }

  /**
   *
   *
   * @generated
   */
  public void setInCard(String newInCard)
  {
    String oldInCard = inCard;
    inCard = newInCard;
    if (eNotificationRequired())
      eNotify(new ENotificationImpl(this, Notification.SET, FeaturePackage.FEATURE__IN_CARD, oldInCard, inCard));
  }

  /**
   *
   *
   * @generated
   */
  public FeatureBody getBody()
  {
    return body;
  }

  /**
   *
   *
   * @generated
   */
  public NotificationChain basicSetBody(FeatureBody newBody, NotificationChain msgs)
  {
    FeatureBody oldBody = body;
    body = newBody;
    if (eNotificationRequired())
    {
      ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, FeaturePackage.FEATURE__BODY, oldBody, newBody);
      if (msgs == null) msgs = notification; else msgs.add(notification);
    }
    return msgs;
  }

  /**
   *
   *
   * @generated
   */
  public void setBody(FeatureBody newBody)
  {
    if (newBody != body)
    {
      NotificationChain msgs = null;
      if (body != null)
        msgs = ((InternalEObject)body).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - FeaturePackage.FEATURE__BODY, null, msgs);
      if (newBody != null)
        msgs = ((InternalEObject)newBody).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - FeaturePackage.FEATURE__BODY, null, msgs);
      msgs = basicSetBody(newBody, msgs);
      if (msgs != null) msgs.dispatch();
    }
    else if (eNotificationRequired())
      eNotify(new ENotificationImpl(this, Notification.SET, FeaturePackage.FEATURE__BODY, newBody, newBody));
  }

  /**
   *
   *
   * @generated
   */
  public String getOutCard()
  {
    return outCard;
  }

  /**
   *
   *
   * @generated
   */
  public void setOutCard(String newOutCard)
  {
    String oldOutCard = outCard;
    outCard = newOutCard;
    if (eNotificationRequired())
      eNotify(new ENotificationImpl(this, Notification.SET, FeaturePackage.FEATURE__OUT_CARD, oldOutCard, outCard));
  }

  /**
   *
   *
   * @generated
   */
  public Feature getRef()
  {
    if (ref != null && ref.eIsProxy())
    {
      InternalEObject oldRef = (InternalEObject)ref;
      ref = (Feature)eResolveProxy(oldRef);
      if (ref != oldRef)
      {
        if (eNotificationRequired())
          eNotify(new ENotificationImpl(this, Notification.RESOLVE, FeaturePackage.FEATURE__REF, oldRef, ref));
      }
    }
    return ref;
  }

  /**
   *
   *
   * @generated
   */
  public Feature basicGetRef()
  {
    return ref;
  }

  /**
   *
   *
   * @generated
   */
  public void setRef(Feature newRef)
  {
    Feature oldRef = ref;
    ref = newRef;
    if (eNotificationRequired())
      eNotify(new ENotificationImpl(this, Notification.SET, FeaturePackage.FEATURE__REF, oldRef, ref));
  }

  /**
   *
   *
   * @generated
   */
  public AttributeType getType()
  {
    return type;
  }

  /**
   *
   *
   * @generated
   */
  public void setType(AttributeType newType)
  {
    AttributeType oldType = type;
    type = newType == null ? TYPE_EDEFAULT : newType;
    if (eNotificationRequired())
      eNotify(new ENotificationImpl(this, Notification.SET, FeaturePackage.FEATURE__TYPE, oldType, type));
  }

  /**
   *
   *
   * @generated
   */
  @Override
  public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs)
  {
    switch (featureID)
    {
      case FeaturePackage.FEATURE__BODY:
        return basicSetBody(null, msgs);
    }
    return super.eInverseRemove(otherEnd, featureID, msgs);
  }

  /**
   *
   *
   * @generated
   */
  @Override
  public Object eGet(int featureID, boolean resolve, boolean coreType)
  {
    switch (featureID)
    {
      case FeaturePackage.FEATURE__NAME:
        return getName();
      case FeaturePackage.FEATURE__IN_CARD:
        return getInCard();
      case FeaturePackage.FEATURE__BODY:
        return getBody();
      case FeaturePackage.FEATURE__OUT_CARD:
        return getOutCard();
      case FeaturePackage.FEATURE__REF:
        if (resolve) return getRef();
        return basicGetRef();
      case FeaturePackage.FEATURE__TYPE:
        return getType();
    }
    return super.eGet(featureID, resolve, coreType);
  }

  /**
   *
   *
   * @generated
   */
  @Override
  public void eSet(int featureID, Object newValue)
  {
    switch (featureID)
    {
      case FeaturePackage.FEATURE__NAME:
        setName((String)newValue);
        return;
      case FeaturePackage.FEATURE__IN_CARD:
        setInCard((String)newValue);
        return;
      case FeaturePackage.FEATURE__BODY:
        setBody((FeatureBody)newValue);
        return;
      case FeaturePackage.FEATURE__OUT_CARD:
        setOutCard((String)newValue);
        return;
      case FeaturePackage.FEATURE__REF:
        setRef((Feature)newValue);
        return;
      case FeaturePackage.FEATURE__TYPE:
        setType((AttributeType)newValue);
        return;
    }
    super.eSet(featureID, newValue);
  }

  /**
   *
   *
   * @generated
   */
  @Override
  public void eUnset(int featureID)
  {
    switch (featureID)
    {
      case FeaturePackage.FEATURE__NAME:
        setName(NAME_EDEFAULT);
        return;
      case FeaturePackage.FEATURE__IN_CARD:
        setInCard(IN_CARD_EDEFAULT);
        return;
      case FeaturePackage.FEATURE__BODY:
        setBody((FeatureBody)null);
        return;
      case FeaturePackage.FEATURE__OUT_CARD:
        setOutCard(OUT_CARD_EDEFAULT);
        return;
      case FeaturePackage.FEATURE__REF:
        setRef((Feature)null);
        return;
      case FeaturePackage.FEATURE__TYPE:
        setType(TYPE_EDEFAULT);
        return;
    }
    super.eUnset(featureID);
  }

  /**
   *
   *
   * @generated
   */
  @Override
  public boolean eIsSet(int featureID)
  {
    switch (featureID)
    {
      case FeaturePackage.FEATURE__NAME:
        return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name);
      case FeaturePackage.FEATURE__IN_CARD:
        return IN_CARD_EDEFAULT == null ? inCard != null : !IN_CARD_EDEFAULT.equals(inCard);
      case FeaturePackage.FEATURE__BODY:
        return body != null;
      case FeaturePackage.FEATURE__OUT_CARD:
        return OUT_CARD_EDEFAULT == null ? outCard != null : !OUT_CARD_EDEFAULT.equals(outCard);
      case FeaturePackage.FEATURE__REF:
        return ref != null;
      case FeaturePackage.FEATURE__TYPE:
        return type != TYPE_EDEFAULT;
    }
    return super.eIsSet(featureID);
  }

  /**
   *
   *
   * @generated
   */
  @Override
  public String toString()
  {
    if (eIsProxy()) return super.toString();

    StringBuffer result = new StringBuffer(super.toString());
    result.append(" (name: ");
    result.append(name);
    result.append(", inCard: ");
    result.append(inCard);
    result.append(", outCard: ");
    result.append(outCard);
    result.append(", type: ");
    result.append(type);
    result.append(')');
    return result.toString();
  }

} //FeatureImpl


text:
package org.kaazing.messaging.example;

import org.kaazing.messaging.discovery.service.discoverabletransport.dynamic.DynamicConsumerDiscoveryService;
import org.kaazing.messaging.client.message.Message;
import org.kaazing.messaging.client.MessageProducer;
import org.kaazing.messaging.client.destination.Topic;
import org.kaazing.messaging.discovery.service.DiscoveryService;
import org.kaazing.messaging.discovery.DiscoverableTransport;
import org.kaazing.messaging.discovery.service.discoverabletransport.file.PropertiesConfiguredDiscoveryService;
import org.kaazing.messaging.driver.MessagingDriver;

import java.io.IOException;

public class TopicProducerExample
{
    public static void main(String[] args) throws IOException, InterruptedException
    {
        MessagingDriver driver = new MessagingDriver();
        DiscoveryService<DiscoverableTransport> discoveryService = new DynamicConsumerDiscoveryService("aeron:udp?remote=127.0.0.1:40001");
        //DiscoveryService<DiscoverableTransport> discoveryService = new ZooKeeperDiscoveryService("127.0.0.1:2181");
        //DiscoveryService<DiscoverableTransport> discoveryService = new PropertiesConfiguredDiscoveryService("topics.properties");
        driver.setDiscoveryService(discoveryService);
        discoveryService.start();

        Topic topic = new Topic("STOCKS.ABC");

        MessageProducer messageProducer = new MessageProducer(driver, topic);

        for(int i = 0; i < 5; i++)
        {
            Message message = new Message(1024);
            message.getUnsafeBuffer().putInt(0, 567);
            message.setBufferOffset(0);
            message.setBufferLength(4);

            boolean result = messageProducer.offer(message);
            System.out.println("Sent message with result: " + result);

            Thread.sleep(10000);
        }
        messageProducer.close();
        driver.close();
    }
}


text:
using Mle.Audio;
using Mle.MusicPimp.Beam;
using Mle.MusicPimp.Local;
using Mle.MusicPimp.Network;
using Mle.MusicPimp.ViewModels;
using System.Threading.Tasks;

namespace Mle.MusicPimp.Pimp {
    public class StorePimpSession : PimpSession {

        public StorePimpSession(MusicEndpoint e)
            : base(e) {
        }
        protected override LocalMusicLibrary LocalLibrary {
            get { return MultiFolderLibrary.Instance; }
        }
        public override IDownloader BackgroundDownloader {
            get { return PimpStoreDownloader.Instance; }
        }
        protected override async Task EnsureHasDuration(MusicItem track) {
            var uri = await LocalLibrary.LocalUriIfExists(track);
            if(uri != null) {
                track.Duration = await StoreBeamPlayer.MediaElement.UriDuration(uri);
            }
        }

    }
}


text:
require 'spec_helper'
#Capybara.default_wait_time=10
describe "NewCarForm" do
  describe "GET /cars/new" do
    it "works!" do
      # Run the generator again with the --webrat flag if you want to use webrat methods/matchers
      visit '/cars/new'
      page.should have_content("New car")
    end

    it "Has name label" do
    	visit '/cars/new'
    	page.should have_content("Name")
      page.should have_content("Engine type")
    end

    it "should give error", js: true do
      visit "/cars/new"
      page.should have_selector("[name=commit]")
      click_button "Create Car"
      page.should have_selector(".tooltip")

    end

  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="vertical"
	android:layout_width="fill_parent"
	android:layout_height="fill_parent"
	>
<LinearLayout
	android:orientation="horizontal"
	android:layout_width="fill_parent"
	android:layout_height="wrap_content"
	android:gravity="center_horizontal"
	>
<Button
	android:id="@+id/add"
	android:layout_width="wrap_content"
	android:layout_height="wrap_content"
	android:text="@string/add"
	/>
<Button
	android:id="@+id/view"
	android:layout_width="wrap_content"
	android:layout_height="wrap_content"
	android:text="@string/view"
	/>
</LinearLayout>
<ListView
	android:id="@+id/show"
	android:layout_width="fill_parent"
	android:layout_height="fill_parent"
	/>
</LinearLayout>