text:
package com.sealion.serviceassistant;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

import com.sealion.serviceassistant.db.CommonOrderComplishDB;
import com.sealion.serviceassistant.db.OrderDetailListDB;
import com.sealion.serviceassistant.db.OrderListDB;
import com.sealion.serviceassistant.db.QuestionListDB;
import com.sealion.serviceassistant.entity.CommonOrderComplishEntity;
import com.sealion.serviceassistant.entity.QuestionEntity;
import com.sealion.serviceassistant.print.BluetoothService;
import com.sealion.serviceassistant.tools.DateTools;
import com.sealion.serviceassistant.tools.FinalVariables;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

/**
* Íê³ÉÀ¶ÑÀ´òÓ¡¹¦ÄÜ£¬ÌṩGUI¸øÓû§²Ù×÷.
*/
public class BTPrinterActivity extends Activity
{
		// Debugging
		private static final String TAG = "BTPrinter";
		private static final boolean D = true;

		// Message types sent from the BluetoothService Handler
		public static final int MESSAGE_STATE_CHANGE = 1;
		public static final int MESSAGE_READ = 2;
		public static final int MESSAGE_WRITE = 3;
		public static final int MESSAGE_DEVICE_NAME = 4;
		public static final int MESSAGE_TOAST = 5;

		// Key names received from the BluetoothService Handler
		public static final String DEVICE_NAME = "device_name";
		public static final String TOAST = "toast";

		// Intent request codes
		private static final int REQUEST_CONNECT_DEVICE = 1;
		private static final int REQUEST_ENABLE_BT = 2;

		// Layout Views
		private TextView mTitle;
		private TextView mOutTextView;
		//private Button mSendButton;
		private Button mPrintButton;

		// Name of the connected device
		private String mConnectedDeviceName = null;
		// Local Bluetooth adapter
		private BluetoothAdapter mBluetoothAdapter = null;
		// Member object for the services
		private BluetoothService mService = null;

		private ImageView back_image = null;
		private TextView top_bar_title = null;

		private String order_num;

		StringBuilder sBuilder = null;

		@Override
		public void onCreate(Bundle savedInstanceState)
		{
			super.onCreate(savedInstanceState);
			if (D)
				Log.e(TAG, "+++ ON CREATE +++");

			// Set up the window layout
			//requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
			setContentView(R.layout.btprint);
			//getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
			order_num = this.getIntent().getExtras().getString("order_num");

			// Set up the custom title
			mTitle = (TextView) findViewById(R.id.title_left_text);
			mTitle.setText(R.string.Print);
			mTitle = (TextView) findViewById(R.id.title_right_text);

			// Get local Bluetooth adapter
			mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

			// If the adapter is null, then Bluetooth is not supported
			if (mBluetoothAdapter == null)
			{
				Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
				finish();
			}

			top_bar_title = (TextView)this.findViewById(R.id.top_bar_title);
			top_bar_title.setText(this.getResources().getString(R.string.conplete_panel_btn5));
			back_image = (ImageView)this.findViewById(R.id.back_image);
			back_image.setOnClickListener(new View.OnClickListener()
			{

				@Override
				public void onClick(View v)
				{
					finish();
				}
			});

			//³õ'»¯´òÓ¡ÐÅÏ¢----------------------------------------

			OrderDetailListDB odB = new OrderDetailListDB(this);
			String arriveDate = odB.getArriveTargetTimeByOrderNum(order_num,FinalVariables.ORDER_STATE_ARRIVE_TARGET);
			String complishDate = odB.getArriveTargetTimeByOrderNum(order_num,FinalVariables.ORDER_STATE_ORDER_COMPLISH);

			CommonOrderComplishDB cocDB = new CommonOrderComplishDB(this);
			CommonOrderComplishEntity ccEntity = cocDB.SelectById(order_num);

			QuestionListDB questionDB = new QuestionListDB(this);
			ArrayList<QuestionEntity> qList = questionDB.getQuestionByOrderNum(order_num);
			StringBuilder qBuilder = new StringBuilder();
			for (QuestionEntity qEntity : qList)
			{
				qBuilder.append(qEntity.getProductName()+",");
			}

			boolean service_or_visit = true;

			sBuilder = new StringBuilder();

			if ((ccEntity.getVisit_dispose_result() == null || ccEntity.getVisit_dispose_result().equals(""))
					||(ccEntity.getVisit_product_case() == null || ccEntity.getVisit_product_case().equals(""))
					||(ccEntity.getVisit_type() == null || ccEntity.getVisit_type().equals("")))
			{
				service_or_visit = true;
				sBuilder.append("                    º½ÌìÐÅÏ¢²úƷά»¤µ¥\n");
			}
			else
			{
				service_or_visit = false;
				sBuilder.append("                    º½ÌìÐÅÏ¢²úÆ·»Ø·Ãµ¥\n");
			}
//			sBuilder.append("Åɹ¤µ¥ID:"+ccEntity.getOrder_num());
//			sBuilder.append("\n");
			sBuilder.append("Ö½Öʵ¥¾ÝºÅ:"+ccEntity.getNumber_value());
			sBuilder.append("\n");
			sBuilder.append("¹Ë¿ÍÃû³Æ:"+ccEntity.getCustomer_name());
			sBuilder.append("\n");
			sBuilder.append("Ë°ºÅ:"+ccEntity.getCustomer_tax());
			sBuilder.append("\n");
//			sBuilder.append("Åɹ¤ËµÃ÷:"+ccEntity.getCustomer_remark());
//			sBuilder.append("\n");
			sBuilder.append("ÉÏÃŵØÖ·:"+ccEntity.getService_address());
			sBuilder.append("\n");
			sBuilder.append("ÁªÏµÈË:"+ccEntity.getContact_name());
			sBuilder.append("\n");
			sBuilder.append("¹Ì¶¨µç»°:"+FliterString(ccEntity.getCustomer_tel()));
			sBuilder.append("\n");
			sBuilder.append("Òƶ¯ÊÖ»ú:"+FliterString(ccEntity.getCustomer_mobile()));
			sBuilder.append("\n");
//			sBuilder.append("·þÎñ²úÆ·:"+);
//			sBuilder.append("\n");
			if (service_or_visit)
			{
				sBuilder.append("Ó²¼þÐͺż°±àºÅ:"+ccEntity.getSoftware_type());
				sBuilder.append("\n");
				sBuilder.append("Èí¼þ°æ±¾ºÅ:"+ccEntity.getSoftware_version());
				sBuilder.append("\n");
				sBuilder.append("ʹÓû·¾³:"+ccEntity.getSoftware_env_value()+"\n");
				sBuilder.append("·þÎñ·½Ê½:ÉÏÃÅ·þÎñ\n");
				sBuilder.append("·þÎñ²úÆ·:"+qBuilder.toString() == null?"":qBuilder.toString() +"\n");
				sBuilder.append("¹ÊÕÏÏÖÏó:\n");
				QuestionListDB qlDB = new QuestionListDB(this);
				ArrayList<QuestionEntity> qlList = qlDB.getQuestionByOrderNum(order_num);
				for (QuestionEntity qEntity : qlList)
				{
					sBuilder.append(qEntity.getQ_content());
				}
				sBuilder.append("\n");
				sBuilder.append("½â¾ö°ì·¨:\n");
				for (QuestionEntity qEntity : qlList)
				{
					sBuilder.append(qEntity.getQ_answer());
				}
				sBuilder.append("\n");

				if(ccEntity.getIs_charge() == 0)
				{
					sBuilder.append("ÊÇ·ñÊÕ·Ñ:·ñ\n");
				}
				else
				{
					sBuilder.append("ÊÇ·ñÊÕ·Ñ:ÊÇ\n");
					sBuilder.append("Êշѽð¶î:"+ccEntity.getIs_charge_value()+"\n");
				}
				sBuilder.append("µ½´ïʱ¼ä:"+arriveDate+"\n");
				if (complishDate == null || complishDate.equals(""))
				{
					sBuilder.append("Íê³Éʱ¼ä:"+complishDate+"\n");
				}
				else
				{
					sBuilder.append("Íê³Éʱ¼ä:"+DateTools.getFormatDateAndTime()+"\n");
				}

				sBuilder.append("·þÎñµ¥Î»Ãû³Æ:ºþÄϺ½ÌìÐÅÏ¢ÓÐÏÞ¹«Ë¾\n");
				sBuilder.append("ÁªÏµµç»°:400-8877-660\n");
				sBuilder.append("¼¼Êõ¹¤³ÌʦǩÃû:"+ccEntity.getTec_name());
				sBuilder.append("\n");
				sBuilder.append("¼¼Êõ·þÎñ¹¤³ÌʦÔÚά»¤¹¤×÷¿ªÊ¼Ç°£¬ÒÑÌáÐÑÄú¶Ô¸÷ÖÖÊý¾Ý½øÐб¸·Ý");
				sBuilder.append("\n");
				sBuilder.append("¿Í»§Ç©Ãû:"+ccEntity.getCustomer_sign());
				sBuilder.append("\n");
				sBuilder.append("±¸×¢:"+ccEntity.getCustomer_remark());
				sBuilder.append("\n");
			}
			else
			{
				sBuilder.append("¼¼Êõ¹¤³ÌʦǩÃû:"+ccEntity.getTec_name());
				sBuilder.append("\n");
				sBuilder.append("¿Í»§Ç©Ãû:"+ccEntity.getCustomer_sign());
				sBuilder.append("\n");
				sBuilder.append("±¸×¢:"+ccEntity.getCustomer_remark());
				sBuilder.append("\n");
//				sBuilder.append("»Ø·ÃÀàÐÍ:"+ccEntity.getVisit_type());
//				sBuilder.append("\n");
				OrderListDB orderDB = new OrderListDB(this);
				String productName = orderDB.SelectProductNameByOrderID(order_num);
				sBuilder.append("·þÎñ²úÆ·:"+FliterString(productName)+"\n");
				sBuilder.append("²úÆ·ÔËÐÐÇé¿ö:"+ccEntity.getVisit_product_case());
				sBuilder.append("\n");
				sBuilder.append("´¦Àí½á¹û:"+ccEntity.getVisit_dispose_result());
				sBuilder.append("\n");
				sBuilder.append("Äú¶ÔÎÒ¹«Ë¾µÄ·þÎñµÄ×ÜÌåÆÀ¼ÛÊÇ:");
				if (ccEntity.getService_evaluate() == 0)
				{
					sBuilder.append("ºÜÂúÒâ");
				}
				else if(ccEntity.getService_evaluate() == 1)
				{
					sBuilder.append("ÂúÒâ");
				}
				else if(ccEntity.getService_evaluate() == 2)
				{
					sBuilder.append("²»ÂúÒâ");
				}
				sBuilder.append("\n");
				sBuilder.append("Äú¶ÔÎÒ¹«Ë¾²úÆ·µÄ×ÜÌåÆÀ¼ÛÊÇ:");
				if (ccEntity.getProduct_evaluate() == 0)
				{
					sBuilder.append("ºÜÂúÒâ");
				}
				else if(ccEntity.getProduct_evaluate() == 1)
				{
					sBuilder.append("ÂúÒâ");
				}
				else if(ccEntity.getProduct_evaluate() == 2)
				{
					sBuilder.append("²»ÂúÒâ");
				}
				sBuilder.append("\n");

				sBuilder.append("»Ø·ÃÈÕÆÚ:"+arriveDate.substring(0, 10));
				sBuilder.append("\n");
				sBuilder.append("¿ªÊ¼Ê±¼ä:"+arriveDate.substring(11, arriveDate.length()));
				sBuilder.append("\n");
				sBuilder.append("½áÊøʱ¼ä:"+complishDate.substring(11, complishDate.length()));
				sBuilder.append("\n");
				sBuilder.append("·þÎñµ¥Î»Ãû³Æ:ºþÄϺ½ÌìÐÅÏ¢ÓÐÏÞ¹«Ë¾\n");
				sBuilder.append("ÁªÏµµç»°:400-8877-660\n");
			}

			sBuilder.append("º½ÌìÐÅϢȫ¹ú·þÎñ¼à¶½µç»°:400-810-6116\n");

		}

		@Override
		public void onStart()
		{
			super.onStart();
			if (D)
				Log.e(TAG, "++ ON START ++");

			// If BT is not on, request that it be enabled.
			// setupChat() will then be called during onActivityResult
			if (!mBluetoothAdapter.isEnabled())
			{
				Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
				startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
				// Otherwise, setup the session
			}
			else
			{
				if (mService == null)
					init();
			}
		}

		@Override
		public synchronized void onResume()
		{
			super.onResume();
			if (D)
				Log.e(TAG, "+ ON RESUME +");

			// Performing this check in onResume() covers the case in which BT was
			// not enabled during onStart(), so we were paused to enable it...
			// onResume() will be called when ACTION_REQUEST_ENABLE activity
			// returns.
			if (mService != null)
			{
				// Only if the state is STATE_NONE, do we know that we haven't
				// started already
				if (mService.getState() == BluetoothService.STATE_NONE)
				{
					// Start the Bluetooth services
					Log.d(TAG, "start service....");
					mService.start();
				}
			}
		}

		private void init()
		{
			Log.d(TAG, "setupChat()");

			// Initialize the compose field with a listener for the return key
			mOutTextView = (TextView) findViewById(R.id.edit_text_out);
			if (sBuilder != null)
			{
				mOutTextView.setText(sBuilder.toString());
			}

			// Initialize the send button with a listener that for click events
//			mSendButton = (Button) findViewById(R.id.button_send);
//			mSendButton.setOnClickListener(new View.OnClickListener()
//			{
//				@Override
//				public void onClick(View v)
//				{
//					// Send a message using content of the edit text widget
//					// TextView fontGrayView = (TextView)
//					// findViewById(R.id.fontGrayscaleValue);
//					// String message = mOutEditText.getText().toString();
//					String message = "ºþÄϺ½ÌìÐÅÏ¢¼¼ÊõÓÐÏÞ¹«Ë¾´òÓ¡²âÊÔÐÅÏ¢\r\n";
//					sendMessage(message);
//				}
//			});
			// Initialize the print button with a listener that for click events
			mPrintButton = (Button) findViewById(R.id.button_print);
			mPrintButton.setOnClickListener(new View.OnClickListener()
			{
				@Override
				public void onClick(View v)
				{
					// TextView fontGrayView = (TextView)
					// findViewById(R.id.fontGrayscaleValue);
					String message = mOutTextView.getText().toString();
					sendMessage(message);

				}
			});

			// Initialize the BluetoothService to perform bluetooth connections
			mService = new BluetoothService(this, mHandler);
		}

		@Override
		public synchronized void onPause()
		{
			super.onPause();
			if (D)
				Log.e(TAG, "- ON PAUSE -");
		}

		@Override
		public void onStop()
		{
			super.onStop();
			if (D)
				Log.e(TAG, "-- ON STOP --");
		}

		@Override
		public void onDestroy()
		{
			super.onDestroy();
			// Stop the Bluetooth services
			if (mService != null)
				mService.stop();
			if (D)
				Log.e(TAG, "--- ON DESTROY ---");
		}

		/**
		 * Sends a message.
		 *
		 * @param message
		 *            A string of text to send.
		 *
		 */
		private void sendMessage(String message)
		{
			// Check that we're actually connected before trying anything
			if (mService.getState() != BluetoothService.STATE_CONNECTED)
			{
				Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT).show();
				return;
			}

			// Check that there's actually something to send
			if (message.length() > 0)
			{
				// Get the message bytes and tell the BluetoothService to write
				byte[] send;
				try
				{
					send = message.getBytes("GBK");
				}
				catch (UnsupportedEncodingException e)
				{
					send = message.getBytes();
				}

				mService.write(send);
				//
				// // Reset out string buffer to zero and clear the edit text field
				// mOutStringBuffer.setLength(0);
				// mOutEditText.setText(mOutStringBuffer);
			}
		}

		// The Handler that gets information back from the BluetoothService
		private final Handler mHandler = new Handler()
		{
			@Override
			public void handleMessage(Message msg)
			{
				switch (msg.what)
				{
				case MESSAGE_STATE_CHANGE:
					if (D)
						Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
					switch (msg.arg1)
					{
					case BluetoothService.STATE_CONNECTED:
						mTitle.setText(R.string.title_connected_to);
						mTitle.append(mConnectedDeviceName);
						break;
					case BluetoothService.STATE_CONNECTING:
						mTitle.setText(R.string.title_connecting);
						break;
					case BluetoothService.STATE_LISTEN:
					case BluetoothService.STATE_NONE:
						mTitle.setText(R.string.title_not_connected);
						break;
					}
					break;
				case MESSAGE_WRITE:
					// byte[] writeBuf = (byte[]) msg.obj;
					// construct a string from the buffer
					// String writeMessage = new String(writeBuf);
					break;
				case MESSAGE_READ:
					// byte[] readBuf = (byte[]) msg.obj;
					// construct a string from the valid bytes in the buffer
					// String readMessage = new String(readBuf, 0, msg.arg1);
					break;
				case MESSAGE_DEVICE_NAME:
					// save the connected device's name
					mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
					Toast.makeText(getApplicationContext(), "Connected to " + mConnectedDeviceName, Toast.LENGTH_SHORT).show();
					break;
				case MESSAGE_TOAST:
					Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST), Toast.LENGTH_SHORT).show();
					break;
				}
			}
		};

		@Override
		public void onActivityResult(int requestCode, int resultCode, Intent data)
		{
			if (D)
				Log.d(TAG, "onActivityResult " + resultCode);
			switch (requestCode)
			{
			case REQUEST_CONNECT_DEVICE:
				// When DeviceListActivity returns with a device to connect
				if (resultCode == Activity.RESULT_OK)
				{
					// Get the device MAC address
					String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
					// Get the BLuetoothDevice object
					if (BluetoothAdapter.checkBluetoothAddress(address))
					{
						BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
						// Attempt to connect to the device
						mService.connect(device);
					}
				}
				break;
			case REQUEST_ENABLE_BT:
				// When the request to enable Bluetooth returns
				if (resultCode == Activity.RESULT_OK)
				{
					// Bluetooth is now enabled, so set up a session
					init();
				}
				else
				{
					// User did not enable Bluetooth or an error occured
					Log.d(TAG, "BT not enabled");
					Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show();
					finish();
				}
			}
		}

		@Override
		public boolean onCreateOptionsMenu(Menu menu)
		{
			MenuInflater inflater = getMenuInflater();
			inflater.inflate(R.menu.option_menu, menu);
			return true;
		}

		@Override
		public boolean onOptionsItemSelected(MenuItem item)
		{
			switch (item.getItemId())
			{
			case R.id.scan:
				// Launch the DeviceListActivity to see devices and do scan
				Intent serverIntent = new Intent(this, DeviceListActivity.class);
				startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
				return true;
			case R.id.disconnect:
				// disconnect
				mService.stop();
				return true;
			}
			return false;
		}

		public String FliterString(String str)
		{
			if (str == null || str.trim().equals("") || str.trim().equals("null"))
			{
				return "";
			}
			else
			{
				return str;
			}
		}
}


text:
package com.planet_ink.coffee_mud.MOBS;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

import java.util.*;

public class GardenSnake extends StdMOB
{
	@Override public String ID(){return "GardenSnake";}
	public GardenSnake()
	{
		super();
		username="a garden snake";
		setDescription("A harmless little green string.");
		setDisplayText("A little garden snake slithers around looking for bugs.");
		CMLib.factions().setAlignment(this,Faction.Align.NEUTRAL);
		setMoney(0);

		basePhyStats().setDamage(1);

		baseCharStats().setStat(CharStats.STAT_INTELLIGENCE,1);

		basePhyStats().setAbility(0);
		basePhyStats().setLevel(1);
		basePhyStats().setArmor(90);

		baseCharStats().setMyRace(CMClass.getRace("GardenSnake"));
		baseCharStats().getMyRace().startRacing(this,false);
		baseState.setHitPoints(CMLib.dice().roll(basePhyStats().level(),20,basePhyStats().level()));

		recoverMaxState();
		resetToMaxState();
		recoverPhyStats();
		recoverCharStats();
	}

}

redpajama_set_name: RedPajamaGithub


text:
require_relative 'token'
require_relative 'token_type'

class GreaterThanToken < Token
  def initialize(index)
    @index = index
    @content = '>'
    @type = TokenType::GreaterThan
  end
end


text:
package com.t3hh4xx0r.uberverification;

import android.app.Application;

import com.t3hh4xx0r.uberverification.library.Verifier;

import org.joda.time.DateTimeConstants;

public class MyApplication extends Application {
    private final static String APPLICATION_KEY = "XsH2zp29fq8kLl3BVpWQO1D5fjn4voTujjx2t0gi"; //
    private final static String CLIENT_KEY = "M0eZ7hKyccAmlQVmKxVGWuC4yx6HatIP2MaggukQ"; //

    @Override
    public void onCreate() {
        super.onCreate();
        Verifier.setup(this, APPLICATION_KEY, CLIENT_KEY, DateTimeConstants.MILLIS_PER_MINUTE);
    }
}


text:
package org.apache.spark.mllib.feature

import org.apache.spark.annotation.Experimental
import org.apache.spark.mllib.linalg._

/**
 * :: Experimental ::
 * Outputs the Hadamard product (i.e., the element-wise product) of each input vector with a
 * provided "weight" vector. In other words, it scales each column of the dataset by a scalar
 * multiplier.
 * @param scalingVec The values used to scale the reference vector's individual components.
 */
@Experimental
class ElementwiseProduct(val scalingVec: Vector) extends VectorTransformer {

  /**
   * Does the hadamard product transformation.
   *
   * @param vector vector to be transformed.
   * @return transformed vector.
   */
  override def transform(vector: Vector): Vector = {
    require(vector.size == scalingVec.size,
      s"vector sizes do not match: Expected ${scalingVec.size} but found ${vector.size}")
    vector match {
      case dv: DenseVector =>
        val values: Array[Double] = dv.values.clone()
        val dim = scalingVec.size
        var i = 0
        while (i < dim) {
          values(i) *= scalingVec(i)
          i += 1
        }
        Vectors.dense(values)
      case SparseVector(size, indices, vs) =>
        val values = vs.clone()
        val dim = values.length
        var i = 0
        while (i < dim) {
          values(i) *= scalingVec(indices(i))
          i += 1
        }
        Vectors.sparse(size, indices, values)
      case v => throw new IllegalArgumentException("Does not support vector type " + v.getClass)
    }
  }
}


text:
class CreateNutritionCategories < ActiveRecord::Migration
  def change
    create_table :nutrition_categories do |t|
      t.string :title
      t.string :page_title
      t.string :url
      t.text :text
      t.integer :order
      t.has_attached_file :lead_image

      t.timestamps
    end
  end
end


text:
class AddReportInfoToReports < ActiveRecord::Migration
  def change
    add_column :reports, :reported_at, :datetime
    add_column :reports, :financial_year, :datetime
    add_column :reports, :region_number, :string

    add_index :reports, :region_number
  end
end


text:
// Copyright (c) 2012 Ecma International.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/*---
es5id: 15.4.4.14-9-b-i-26
description: >
    Array.prototype.indexOf applied to Arguments object which
    implements its own property get method (number of arguments equals
    to number of parameters)
---*/

        var func = function (a, b) {
            return 0 === Array.prototype.indexOf.call(arguments, arguments[0]) &&
            1 === Array.prototype.indexOf.call(arguments, arguments[1]) &&
            -1 === Array.prototype.indexOf.call(arguments, arguments[2]);
        };

assert(func(0, true), 'func(0, true) !== true');


text:
require 'chefspec'
require 'chefspec/berkshelf'

RSpec.configure do |config|
  config.platform = 'ubuntu'
  config.version = '14.04'
  config.formatter = 'documentation'
  config.order = 'random'
  config.color = true
  config.fail_fast = true
  config.alias_example_group_to :describe_resource, type: :resource
  config.alias_example_group_to :describe_helpers, type: :helpers
end

# silence!!
#
# all logging
Chef::Log.init('/dev/null')
#
# 'warning: already initialized constant'
$VERBOSE = nil
#
# deprecation warnings
module Kernel
  def deprecated(*)
    # noop
  end
end

ChefSpec::Coverage.start!


text:
package com.haiegoo.commons.service;

import com.haiegoo.commons.utils.ConvertUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.support.ApplicationObjectSupport;
import org.springframework.data.redis.core.RedisTemplate;

import java.io.Serializable;
import java.util.Map;

/**
 * service基类,主要编写service公共方法
 * @author Linpn
 */
public abstract class BaseService extends ApplicationObjectSupport implements Serializable {

	private static final long serialVersionUID = -2489358585140025260L;

	/**
	 * log4j对象
	 */
	protected final Log logger = LogFactory.getLog(getClass());

	//-------------------------------------- service 公共方法 -------------------------------------------//

    /**
     * 获取Redis应用级缓存
     * @return 返回RedisTemplate对象
     */
    @SuppressWarnings("unchecked")
    public RedisTemplate<String, Object> getRedisTemplate() {
        return this.getApplicationContext().getBean("redisTemplate", RedisTemplate.class);
    }

	/**
	 * 将排序的map参数转成sql中order by所需要的格式。
	 * 还会将domain对象中的字段转成数据库字段。 如: paramsName 转成 params_name
	 * @param sorters service方法中的排序参数
	 * @return 返回sql语句中order by所需要的格式
	 */
	public String getDbSort(Map<String, String> sorters){
		if(sorters==null)
			return "";

		StringBuilder sbSort = new StringBuilder();
		for(Map.Entry<String, String> entry : sorters.entrySet()){
			if(sbSort.length()>0)
				sbSort.append(",");

			String sort = ConvertUtils.model2field(entry.getKey());
			String dir = entry.getValue();

			if(!StringUtils.isBlank(sort)){
				sbSort.append(sort);
				if(!StringUtils.isBlank(dir)){
					sbSort.append(" ");
					sbSort.append(entry.getValue());
				}
			}else{
				return "";
			}
		}

		return sbSort.toString();
	}

	/**
	 * 将排序的map参数转成sql中order by所需要的格式
	 * @param sorters service方法中的排序参数
	 * @return 返回sql语句中order by所需要的格式
	 */
	public String getDbSortNoConvert(Map<String, String> sorters){
		if(sorters==null)
			return "";

		StringBuilder sbSort = new StringBuilder();
		for(Map.Entry<String, String> entry : sorters.entrySet()){
			if(sbSort.length()>0)
				sbSort.append(",");

			String sort = entry.getKey();
			String dir = entry.getValue();

			if(!StringUtils.isBlank(sort)){
				sbSort.append(sort);
				if(!StringUtils.isBlank(dir)){
					sbSort.append(" ");
					sbSort.append(entry.getValue());
				}
			}else{
				return "";
			}
		}
		return sbSort.toString();
	}

}


text:
#ifdef PYTHON_CMD

#ifdef WIN32
    #include <cmath>
#endif

#undef _DEBUG
#include "Python.h"
#include "structmember.h"

#include "sniff_window.h"
#include "ui_sniff_window.h"
#include "EthernetPacket.h"
#include "preferences.h"

#include <QPlainTextEdit>
#include <QSettings>
#include <hs_core.h>
#include "python_thread.h"

#if PY_MAJOR_VERSION < 3
    #define GetPyString PyString_FromString

    #define GetPyBuffer_SizeString PyString_FromStringAndSize
    #define GetPyBuffer_getSize PyString_GET_SIZE
    #define GetPyBuffer_getData PyString_AS_STRING
#else
    #define GetPyString PyUnicode_FromString

    #define GetPyBuffer_SizeString PyByteArray_FromStringAndSize
    #define GetPyBuffer_getSize PyByteArray_GET_SIZE
    #define GetPyBuffer_getData PyByteArray_AS_STRING
#endif

#ifdef Q_OS_WIN
    int gettimeofday(struct timeval* tv, struct timezone*);
#endif

namespace hs {
    PyObject* addPacket(PyObject*, PyObject* args)
    {
        int size;
        const char* b;
#if PY_MAJOR_VERSION < 3
        if (!PyArg_ParseTuple(args, "s#", &b, &size))
            return NULL;
#else
        PyObject* data;
        if (!PyArg_ParseTuple(args, "Y", &data))
            return NULL;
        size = PyByteArray_GET_SIZE(data);
        b = PyByteArray_AS_STRING(data);
#endif

        DataStructure::RawPacketData raw;
        gettimeofday(&raw.time, nullptr);
        raw.setData(b, size);
        SniffWindow::window->toAdd.push(raw);
        Py_RETURN_NONE;
    }

    static PyMethodDef methods[] =
    {
        { "addPacket", (PyCFunction)addPacket, METH_VARARGS, NULL },
        { NULL, NULL, 0, NULL }
    };

#if PY_MAJOR_VERSION >= 3
    static PyModuleDef module =
    {
        PyModuleDef_HEAD_INIT, "hs", NULL, -1, methods, NULL, NULL, NULL, NULL
    };
#endif

    namespace packet {
        namespace layer {
            struct layer_obj
            {
                PyObject_HEAD
                const char* name;
                PyObject* info;
                PyObject* headers;
            };

            static void layer_dealloc(layer_obj* self)
            {
                Py_XDECREF(self->info);
                Py_DECREF(self->headers);
                Py_TYPE(self)->tp_free((PyObject*)self);
            }

            static PyMemberDef layer_members[] =
            {
                {(char*)"name", T_STRING, offsetof(layer_obj, name), READONLY, NULL},
                {(char*)"info", T_OBJECT, offsetof(layer_obj, info), READONLY, NULL},
                {(char*)"headers", T_OBJECT_EX, offsetof(layer_obj, headers), READONLY, NULL},
                {NULL, 0, 0, 0, NULL}
            };

            static PyObject* layer_repr(layer_obj* self)
            {
                if(self->info == NULL)
                {
                    return GetPyString(self->name);
                }
#if PY_MAJOR_VERSION < 3
                return PyString_FromFormat("[%s - %s]", PyString_AS_STRING(self->name), PyString_AS_STRING(self->info));
#else
                return PyUnicode_FromFormat("[%U - %U]", self->name, self->info);
#endif
            }

            static PyObject* layer_str(layer_obj* self)
            {
#if PY_MAJOR_VERSION < 3
                PyObject* res = PyString_FromFormat("%s\n%s\n", self->name, self->info ? PyString_AS_STRING(self->info) : "");
#else
                PyObject* res = PyUnicode_FromFormat("%s\n%V\n", self->name, self->info, "");
#endif
                PyObject* key, *value;
                Py_ssize_t pos = 0;
                while (PyDict_Next(self->headers, &pos, &key, &value))
                {
#if PY_MAJOR_VERSION < 3
                    PyString_ConcatAndDel(&res, PyString_FromFormat("%s : %s\n", PyString_AS_STRING(key), PyString_AS_STRING(value)));
#else
                    PyUnicode_AppendAndDel(&res, PyUnicode_FromFormat("%U : %U\n", key, value));
#endif
                }
                return res;
            }

            static Py_ssize_t layer_len(layer_obj* self)
            {
                return PyDict_Size(self->headers);
            }

            static PyObject* layer_itemAt(layer_obj* self, PyObject* key)
            {
                return PyDict_GetItem(self->headers, key);
            }

            static PyMappingMethods layer_map =
            {
                (lenfunc)layer_len,
                (binaryfunc)layer_itemAt,
                0
            };

#ifdef Q_CC_GNU
    #pragma GCC diagnostic push
    #pragma GCC diagnostic ignored "-Wmissing-field-initializers"
#endif
            static PyTypeObject type =
            {
                PyVarObject_HEAD_INIT(NULL, 0)
                "", sizeof(layer_obj), 0, (destructor)layer_dealloc, 0, 0, 0, 0,
                (reprfunc)layer_repr, 0, 0, &layer_map, 0, 0, (reprfunc)layer_str, 0, 0, 0,
                Py_TPFLAGS_DEFAULT, NULL, 0, 0, 0, 0, 0, 0, 0,
                layer_members, 0, 0, 0, 0, 0, 0, 0, 0, 0
            };

#ifdef Q_CC_GNU
    #pragma GCC diagnostic pop
#endif
        }

        struct packet_obj
        {
            PyObject_HEAD
            PyObject* data;
            PyObject* layersArr;
            unsigned num;
            unsigned len;
            float time;
            bool isShown;
        };

        static void packet_dealloc(packet_obj* self)
        {
            Py_DECREF(self->layersArr);
            Py_XDECREF(self->data);
            Py_TYPE(self)->tp_free((PyObject*)self);
        }

        static PyObject* packet_repr(packet_obj* self)
        {
#if PY_MAJOR_VERSION < 3
            PyObject* res = PyString_FromFormat("[%d - %s - [", self->num, (self->isShown ? "True" : "False"));
            Py_ssize_t len = PyList_GET_SIZE(self->layersArr);
            for(Py_ssize_t i = 0; i < len; i++)
            {
                PyObject* lay = PyList_GET_ITEM(self->layersArr, i);
                PyString_ConcatAndDel(&res, PyString_FromString(((layer::layer_obj*)lay)->name));
                if(i != len - 1)
                    PyString_ConcatAndDel(&res, PyString_FromString(", "));
            }
            PyString_ConcatAndDel(&res, PyString_FromString("]]"));
            return res;
#else
            PyObject* res = PyUnicode_FromFormat("[%d - %s - [", self->num, (self->isShown ? "True" : "False"));
            Py_ssize_t len = PyList_GET_SIZE(self->layersArr);
            for(Py_ssize_t i = 0; i < len; i++)
            {
                PyObject* lay = PyList_GET_ITEM(self->layersArr, i);
                PyUnicode_AppendAndDel(&res, GetPyString(((layer::layer_obj*)lay)->name));
                if(i != len - 1)
                    PyUnicode_AppendAndDel(&res, PyUnicode_FromString(", "));
            }
            PyUnicode_AppendAndDel(&res, PyUnicode_FromString("]]"));
            return res;
#endif
        }

        static PyObject* packet_str(packet_obj* self)
        {
#if PY_MAJOR_VERSION < 3
            PyObject* res = PyString_FromFormat("#%d\n%s\n", self->num, (self->isShown ? "True" : "False"));
            Py_ssize_t len = PyList_GET_SIZE(self->layersArr);
            for(Py_ssize_t i = 0; i < len; i++)
            {
                PyObject* lay = PyList_GET_ITEM(self->layersArr, i);
                PyString_ConcatAndDel(&res, PyString_FromString(((layer::layer_obj*)lay)->name));
                if(i != len - 1)
                    PyString_ConcatAndDel(&res, PyString_FromString(" -> "));
            }
            PyString_ConcatAndDel(&res, PyString_FromString("\n"));
            return res;
#else
            PyObject* res = PyUnicode_FromFormat("#%d\n%s\n", self->num, (self->isShown ? "Shown" : "not Shown"));
            Py_ssize_t len = PyList_GET_SIZE(self->layersArr);
            for(Py_ssize_t i = 0; i < len; i++)
            {
                PyObject* lay = PyList_GET_ITEM(self->layersArr, i);
                PyUnicode_AppendAndDel(&res, GetPyString(((layer::layer_obj*)lay)->name));
                if(i != len - 1)
                    PyUnicode_AppendAndDel(&res, PyUnicode_FromString(" -> "));
            }
            PyUnicode_AppendAndDel(&res, PyUnicode_FromString("\n"));
            return res;
#endif
        }

        static PyMemberDef packet_members[] =
        {
            {(char*)"num", T_UINT, offsetof(packet_obj, num), READONLY, NULL},
            {(char*)"isShown", T_BOOL, offsetof(packet_obj, isShown), READONLY, NULL},
            {(char*)"time", T_FLOAT, offsetof(packet_obj, time), READONLY, NULL},
            {(char*)"len", T_UINT, offsetof(packet_obj, len), READONLY, NULL},
            {(char*)"layersArr", T_OBJECT, offsetof(packet_obj, layersArr), READONLY, NULL},
            {NULL, 0, 0, 0, NULL}
        };

        static PyObject* packet_getData(packet_obj* self, void*)
        {
            if(self->data == NULL)
            {
                const auto& all = SniffWindow::window->model.local;
                if(all.size() <= self->num)
                    return NULL;
                const DataStructure::localPacket& pack = all[self->num];
                self->data = GetPyBuffer_SizeString((const char*)pack.rawPacket.data, pack.rawPacket.len);
            }
            Py_INCREF(self->data);
            return self->data;
        }

        static int packet_setData(packet_obj* self, PyObject* value, void*)
        {
            if (value == NULL)
            {
                PyErr_SetString(PyExc_TypeError, "Cannot delete the last attribute");
                return -1;
            }

#if PY_MAJOR_VERSION < 3
            if (!PyString_Check(value))
            {
                PyErr_SetString(PyExc_TypeError, "The last attribute value must be a string");
                return -1;
            }
#else
            if (!PyByteArray_Check(value))
            {
                PyErr_SetString(PyExc_TypeError, "The last attribute value must be a bytearray");
                return -1;
            }
#endif

            Py_XDECREF(self->data);
            Py_INCREF(value);
            self->data = value;
            self->len = GetPyBuffer_getSize(self->data);
            return 0;
        }

        static PyGetSetDef packet_getset[] = {
            {(char*)"data", (getter)packet_getData, (setter)packet_setData, NULL, NULL},
            {NULL, NULL, NULL, NULL, NULL}
        };

        static PyObject* packet_remove(packet_obj* self)
        {
            SniffWindow::window->model.remove(self->num);
            SniffWindow::window->ui->statusBar->updateText();
            Py_RETURN_NONE;
        }

        static PyObject* packet_save(packet_obj* self)
        {
            if(self->data == NULL)
                Py_RETURN_NONE;
            Py_ssize_t size = 0;
            char* b = NULL;
            size = GetPyBuffer_getSize(self->data);
            b = GetPyBuffer_getData(self->data);
            auto& all = SniffWindow::window->model.local;
            if(all.size() <= self->num)
                return NULL;
            DataStructure::localPacket& pack = all[self->num];
            DataStructure::RawPacketData& raw = pack.rawPacket;
            free(raw.data);
            raw.setData(b, size);

            delete pack.decodedPacket;
            pack.decodedPacket = new hungry_sniffer::EthernetPacket(raw.data, size, &HungrySniffer_Core::core->base);

            SniffWindow::window->updateTableShown();
            Py_RETURN_NONE;
        }

        static PyMethodDef packet_methods[] =
        {
            {"remove", (PyCFunction)packet_remove, METH_NOARGS, NULL},
            {"save", (PyCFunction)packet_save, METH_VARARGS, NULL},
            { NULL, NULL, 0, NULL }
        };

        static Py_ssize_t packet_len(packet_obj* self)
        {
            return PyList_GET_SIZE(self->layersArr);
        }

        static PyObject* packet_itemAt(packet_obj* self, PyObject* key)
        {
            PyObject* res = NULL;
#if PY_MAJOR_VERSION < 3
            if(PyInt_CheckExact(key))
                res = PyList_GET_ITEM(self->layersArr, PyInt_AsSsize_t(key));
            else if(PyString_CheckExact(key))
#else
            if(PyLong_CheckExact(key))
                res = PyList_GET_ITEM(self->layersArr, PyLong_AsSsize_t(key));
            else if(PyUnicode_CheckExact(key))
#endif
            {
                Py_ssize_t len = PyList_GET_SIZE(self->layersArr);
                for(Py_ssize_t i = 0; i < len; i++)
                {
                    PyObject* lay = PyList_GET_ITEM(self->layersArr, i);
#if PY_MAJOR_VERSION < 3
                    if(strcmp(PyString_AS_STRING(key), ((layer::layer_obj*)lay)->name) == 0)
#else
                    if(PyUnicode_CompareWithASCIIString(key, ((layer::layer_obj*)lay)->name) == 0)
#endif
                    {
                        res = lay;
                        break;
                    }
                }
                if(res == NULL)
                {
                    PyErr_SetString(PyExc_KeyError, "protocol name not found");
                    return NULL;
                }
            }
            Py_XINCREF(res);
            return res;
        }

        static PyMappingMethods packet_map =
        {
            (lenfunc)packet_len,
            (binaryfunc)packet_itemAt,
            0
        };

#ifdef Q_CC_GNU
    #pragma GCC diagnostic push
    #pragma GCC diagnostic ignored "-Wmissing-field-initializers"
#endif
        static PyTypeObject type =
        {
            PyVarObject_HEAD_INIT(NULL, 0)
            "", sizeof(packet_obj), 0, (destructor)packet_dealloc, 0, 0, 0,
            0, (reprfunc)packet_repr, 0, 0, &packet_map, 0, 0, (reprfunc)packet_str, 0, 0, 0,
            Py_TPFLAGS_DEFAULT, NULL, 0, 0, 0, 0, 0, 0,
            packet_methods, packet_members, packet_getset
        };

#ifdef Q_CC_GNU
    #pragma GCC diagnostic pop
#endif
        static void init()
        {
            PyType_Ready(&layer::type);
            PyType_Ready(&type);
            Py_INCREF(&layer::type);
            Py_INCREF(&type);
        }

        static PyObject* buildPacket(int row)
        {
            packet_obj* obj = PyObject_New(packet_obj, &type);
            if(obj == NULL)
                return PyErr_NoMemory();

            const DataStructure::localPacket& pack = SniffWindow::window->model.local[row];
            obj->num = row;
            obj->isShown = pack.isShown;
            obj->time = pack.rawPacket.time.tv_sec + (float)pack.rawPacket.time.tv_usec * 0.000001f;
            obj->data = NULL;

            obj->layersArr = PyList_New(0);
            int i = 0;
            for(const hungry_sniffer::Packet* layer = pack.decodedPacket; layer != nullptr; layer = layer->getNext(), i++)
            {
                layer::layer_obj* layer_obj = PyObject_New(layer::layer_obj, &layer::type);
                if(layer_obj == NULL)
                    return PyErr_NoMemory();

                layer_obj->name = layer->getProtocol()->getName().c_str();
                const std::string& info = layer->getInfo();
                if(info.length())
                {
                    if((layer_obj->info = GetPyString(info.c_str())) == NULL)
                        return PyErr_NoMemory();
                }
                else
                    layer_obj->info = NULL;

                if((layer_obj->headers = PyDict_New()) == NULL)
                    return PyErr_NoMemory();
                for(auto& i : layer->getHeaders())
                {
                    PyObject* key = GetPyString(i.key.c_str());
                    if(key == NULL)
                        return PyErr_NoMemory();
                    PyObject* value = GetPyString(i.key.c_str());
                    if(value == NULL)
                        return PyErr_NoMemory();
                    PyDict_SetItem(layer_obj->headers, key, value);
                }

                PyList_Append(obj->layersArr, (PyObject*)layer_obj);
                Py_DECREF(layer_obj);
            }

            return (PyObject*)obj;
        }
    }

    namespace all_packets {

        struct iter_obj
        {
            PyObject_HEAD
            unsigned current;
        };

        PyObject* all_iter_iter(PyObject* self)
        {
            Py_INCREF(self);
            return self;
        }

        static PyObject* all_iter_iternext(iter_obj* self)
        {
            unsigned row = (self->current++);
            if(row < SniffWindow::window->model.local.size())
            {
                return hs::packet::buildPacket(row);
            }
            PyErr_SetNone(PyExc_StopIteration);
            return NULL;
        }

#ifdef Q_CC_GNU
    #pragma GCC diagnostic push
    #pragma GCC diagnostic ignored "-Wmissing-field-initializers"
#endif
        static PyTypeObject iter_type =
        {
            PyVarObject_HEAD_INIT(NULL, 0)
            "", sizeof(iter_obj), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            Py_TPFLAGS_DEFAULT, NULL, 0, 0, 0, 0, (getiterfunc)all_iter_iter, (getiterfunc)all_iter_iternext,
        };
#ifdef Q_CC_GNU
    #pragma GCC diagnostic pop
#endif

        iter_obj* all_iter(PyObject*)
        {
            iter_obj* iter = PyObject_New(iter_obj, &iter_type);
            if(iter != NULL)
                iter->current = 0;
            return iter;
        }

        Py_ssize_t all_len(PyObject*)
        {
            return SniffWindow::window->model.local.size();
        }

        PyObject* all_item(PyObject*, Py_ssize_t index)
        {
            if(index >= (Py_ssize_t)SniffWindow::window->model.local.size())
            {
                PyErr_SetString(PyExc_IndexError, "index out of range");
                return NULL;
            }
            return hs::packet::buildPacket(index);
        }

#ifdef Q_CC_GNU
    #pragma GCC diagnostic push
    #pragma GCC diagnostic ignored "-Wmissing-field-initializers"
#endif
        static PySequenceMethods seq_methods =
        {
            all_len,
            0,
            0,
            all_item
        };

        static PyTypeObject all_type =
        {
            PyVarObject_HEAD_INIT(NULL, 0)
            "", sizeof(PyObject), 0, 0, 0, 0, 0, 0, 0, 0,
            &seq_methods, 0, 0, 0, 0, 0, 0, 0, Py_TPFLAGS_DEFAULT,
            NULL, 0, 0, 0, 0, (getiterfunc)all_iter
        };
#ifdef Q_CC_GNU
    #pragma GCC diagnostic pop
#endif
        static void init(PyObject* hsModule)
        {
            PyType_Ready(&iter_type);
            PyType_Ready(&all_type);

            Py_INCREF(&iter_type);
            Py_INCREF(&all_type);

            PyModule_AddObject(hsModule, "all", PyObject_New(PyObject, &all_type));
        }
    }

    namespace shown_packets {

        struct iter_obj
        {
            PyObject_HEAD
            unsigned current;
        };

        PyObject* shown_iter_iter(PyObject* self)
        {
            Py_INCREF(self);
            return self;
        }

        static PyObject* shown_iter_iternext(iter_obj* self)
        {
            unsigned row = (self->current++);
            const auto& shown = SniffWindow::window->model.shownPerRow;
            if(row < shown.size())
            {
                return hs::packet::buildPacket(shown[row]);
            }
            PyErr_SetNone(PyExc_StopIteration);
            return NULL;
        }

#ifdef Q_CC_GNU
    #pragma GCC diagnostic push
    #pragma GCC diagnostic ignored "-Wmissing-field-initializers"
#endif
        static PyTypeObject iter_type =
        {
            PyVarObject_HEAD_INIT(NULL, 0)
            "", sizeof(iter_obj), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            Py_TPFLAGS_DEFAULT, NULL, 0, 0, 0, 0, (getiterfunc)shown_iter_iter, (getiterfunc)shown_iter_iternext
        };
#ifdef Q_CC_GNU
    #pragma GCC diagnostic pop
#endif

        PyObject* shown_iter(PyObject*)
        {
            iter_obj* iter;
            iter = PyObject_New(iter_obj, &iter_type);
            if(iter == NULL)
                return NULL;
            iter->current = 0;
            return (PyObject*)iter;
        }

        Py_ssize_t shown_len(PyObject*)
        {
            return SniffWindow::window->model.shownPerRow.size();
        }

        PyObject* shown_item(PyObject*, Py_ssize_t index)
        {
            const auto& shown = SniffWindow::window->model.shownPerRow;
            if(index >= (Py_ssize_t)shown.size())
            {
                PyErr_SetString(PyExc_IndexError, "index out of range");
                return NULL;
            }
            return hs::packet::buildPacket(shown[index]);
        }

#ifdef Q_CC_GNU
    #pragma GCC diagnostic push
    #pragma GCC diagnostic ignored "-Wmissing-field-initializers"
#endif
        static PySequenceMethods seq_methods =
        {
            shown_len,
            0,
            0,
            shown_item
        };

        static PyTypeObject shown_type =
        {
            PyVarObject_HEAD_INIT(NULL, 0)
            "", sizeof(PyObject), 0, 0, 0, 0, 0, 0, 0, 0, &seq_methods, 0, 0, 0, 0,
            0, 0, 0, Py_TPFLAGS_DEFAULT, NULL, 0, 0, 0, 0, (getiterfunc)shown_iter
        };
#ifdef Q_CC_GNU
    #pragma GCC diagnostic pop
#endif
        static void init(PyObject* hsModule)
        {
            PyType_Ready(&iter_type);
            PyType_Ready(&shown_type);

            Py_INCREF(&iter_type);
            Py_INCREF(&shown_type);

            PyModule_AddObject(hsModule, "shown", PyObject_New(PyObject, &shown_type));
        }
    }

    namespace filter {

        static PyObject* filter_get(PyObject*)
        {
            return GetPyString(SniffWindow::window->ui->tb_filter->text().toUtf8().data());
        }

        static PyObject* filter_clear(PyObject*)
        {
            SniffWindow::window->ui->tb_filter->clear();
            SniffWindow::window->on_bt_filter_apply_clicked();
            Py_RETURN_NONE;
        }

        static PyObject* filter_set(PyObject*, PyObject* args)
        {
            const char* str = "";
            if (!PyArg_ParseTuple(args, "|z", &str))
            {
                return NULL;
            }
            SniffWindow::window->ui->tb_filter->setText(QString(str));
            SniffWindow::window->on_bt_filter_apply_clicked();
            Py_RETURN_NONE;
        }

        static PyMethodDef hs_filter_methods[] =
        {
            {"get", (PyCFunction)filter_get, METH_NOARGS | METH_CLASS, NULL},
            {"clear", (PyCFunction)filter_clear, METH_NOARGS | METH_CLASS, NULL},
            {"set", (PyCFunction)filter_set, METH_VARARGS | METH_CLASS, NULL},
            { NULL, NULL, 0, NULL }
        };

#ifdef Q_CC_GNU
    #pragma GCC diagnostic push
    #pragma GCC diagnostic ignored "-Wmissing-field-initializers"
#endif
        static PyTypeObject type =
        {
            PyVarObject_HEAD_INIT(NULL, 0)
            "", sizeof(PyObject), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, Py_TPFLAGS_DEFAULT, NULL, 0, 0, 0, 0, 0, 0, hs_filter_methods
        };
#ifdef Q_CC_GNU
    #pragma GCC diagnostic pop
#endif
        static void init(PyObject* hsModule)
        {
            PyType_Ready(&type);
            Py_INCREF(&type);
            PyModule_AddObject(hsModule, "filter", (PyObject*)&type);
        }
    }
}

namespace ui {
    PyObject* reset(PyObject*)
    {
        emit SniffWindow::window->sig_clearCmd();
        Py_RETURN_NONE;
    }

    PyObject* open(PyObject*, PyObject* args)
    {
        const char* str;
        if (!PyArg_ParseTuple(args, "s", &str))
        {
            return NULL;
        }
        SniffWindow::window->runOfflineFile(str);
        Py_RETURN_NONE;
    }

    PyObject* stop(PyObject*)
    {
        emit SniffWindow::window->ui->actionStop->triggered();
        Py_RETURN_NONE;
    }

    PyObject* exit(PyObject*)
    {
        emit SniffWindow::window->ui->actionQuit->triggered();
        Py_RETURN_NONE;
    }

    static PyMethodDef methods[] =
    {
        { "reset", (PyCFunction)reset, METH_NOARGS, NULL },
        { "open", (PyCFunction)open, METH_VARARGS, NULL },
        { "stop", (PyCFunction)stop, METH_NOARGS, NULL },
        { "exit", (PyCFunction)exit, METH_NOARGS, NULL },
        { NULL, NULL, 0, NULL }
    };

#if PY_MAJOR_VERSION >= 3
    static PyModuleDef module =
    {
        PyModuleDef_HEAD_INIT, "__main__", NULL, -1, methods, NULL, NULL, NULL, NULL
    };
#endif
}

namespace catchOutErr {

    struct catch_obj
    {
        PyObject_HEAD
        const char* color;
    };

    static PyObject* CatchOutErr_write(catch_obj* self, PyObject* args)
    {
        const char* str;
        if (!PyArg_ParseTuple(args, "s", &str))
        {
            return NULL;
        }
        emit SniffWindow::window->sig_appendToCmd(QStringLiteral("<font color=\"%1\">%2</font>").arg(self->color).arg(str).replace("\n", "<br/>"));
        Py_RETURN_NONE;
    }

    static PyMethodDef CatchOutErr_methods[] =
    {
        {"write", (PyCFunction)CatchOutErr_write, METH_VARARGS, NULL},
        { NULL, NULL, 0, NULL }
    };

#ifdef Q_CC_GNU
    #pragma GCC diagnostic push
    #pragma GCC diagnostic ignored "-Wmissing-field-initializers"
#endif
    static PyTypeObject type =
    {
        PyVarObject_HEAD_INIT(NULL, 0)
        "", sizeof(catch_obj), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, Py_TPFLAGS_DEFAULT, NULL, 0, 0, 0, 0, 0, 0, CatchOutErr_methods
    };
#ifdef Q_CC_GNU
    #pragma GCC diagnostic pop
#endif

    static void redirect(PyObject* sys)
    {
        PyType_Ready(&type);
        Py_INCREF(&type);

        catch_obj* t = PyObject_New(catch_obj, &type);
        t->color = "blue";
        PyObject_SetAttrString(sys, "stdout", (PyObject*)t);
        Py_DECREF(t);

        t = PyObject_New(catch_obj, &type);
        t->color = "red";
        PyObject_SetAttrString(sys, "stderr", (PyObject*)t);
        Py_DECREF(t);
    }
}

static void addDirToPath(PyObject* sys)
{
    PyObject* sys_path = PyObject_GetAttrString(sys, "path");

    QSettings& settings = *Preferences::settings;
    settings.beginGroup(QStringLiteral("General"));
    settings.beginGroup(QStringLiteral("Modules"));
    QVariant var = settings.value(QStringLiteral("python_dir"));
    if(!var.isNull())
    {
        for(const QString& p : var.toStringList())
        {
            PyObject* folder_path = GetPyString(p.toUtf8().constData());
            PyList_Append(sys_path, folder_path);
            Py_DECREF(folder_path);
        }
    }
    settings.endGroup();
    settings.endGroup();
}

QString PythonThread::getVersionString()
{
#ifdef Q_CC_MSVC
    return QStringLiteral("Python ").append(PY_VERSION);
#else
    return QStringLiteral("Python " PY_VERSION);
#endif
}

PythonThread::PythonThread()
{
    moveToThread(this);
    connect(this, SIGNAL(finished()), this, SLOT(stopPython()));
    connect(this, SIGNAL(sendCommand(QString)), this, SLOT(runCommand(QString)));
}

void PythonThread::runCommand(QString command)
{
    PyRun_String(command.toUtf8().constData(), Py_single_input, (PyObject*)pyGlobals, (PyObject*)pyGlobals);
    if (PyErr_Occurred())
    {
        PyErr_Print();
        PyErr_Clear();
    }
}

void PythonThread::stopPython()
{
    Py_Finalize();
}

void PythonThread::run()
{
    Py_Initialize();

    PyObject* sys = PyImport_ImportModule("sys");
    addDirToPath(sys);
    catchOutErr::redirect(sys);

#if PY_MAJOR_VERSION < 3
    PyObject* mainModule = Py_InitModule("__main__", ui::methods);
    PyObject* hsModule = Py_InitModule("hs", hs::methods);
#else
    PyObject* mainModule = PyModule_Create(&ui::module);
    PyModule_AddObject(mainModule, "__builtins__", PyEval_GetBuiltins());
    PyObject* hsModule = PyModule_Create(&hs::module);
#endif

    hs::filter::init(hsModule);
    hs::packet::init();
    hs::all_packets::init(hsModule);
    hs::shown_packets::init(hsModule);
    PyModule_AddObject(mainModule, "hs", hsModule);
    this->pyGlobals = PyModule_GetDict(mainModule);
    exec();
}

#endif


text:
package at.tuwien.ase.tripidude;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.content.res.Configuration;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.FragmentTransaction;
import android.view.Menu;
import android.view.MenuItem;
import at.tuwien.ase.tripidude.api.APIException;
import at.tuwien.ase.tripidude.api.UserAPI;
import at.tuwien.ase.tripidude.core.App;
import at.tuwien.ase.tripidude.core.BaseActivity;
import at.tuwien.ase.tripidude.core.FragmentController;
import at.tuwien.ase.tripidude.fragments.CreateMapItemFragment;
import at.tuwien.ase.tripidude.fragments.CreateRouteFragment;
import at.tuwien.ase.tripidude.fragments.EventsFragment;
import at.tuwien.ase.tripidude.fragments.HighscoresFragment;
import at.tuwien.ase.tripidude.fragments.LoginFragment;
import at.tuwien.ase.tripidude.fragments.LoginFragment.OnLoginFragmentListener;
import at.tuwien.ase.tripidude.fragments.MapFragment;
import at.tuwien.ase.tripidude.fragments.RegisterFragment;
import at.tuwien.ase.tripidude.fragments.RegisterFragment.OnRegisterFragmentListener;
import at.tuwien.ase.tripidude.fragments.SearchMapitemFragment;
import at.tuwien.ase.tripidude.fragments.UserProfileFragment;
import at.tuwien.ase.tripidude.models.DrawerMenuItem;
import at.tuwien.ase.tripidude.models.MapItem;
import at.tuwien.ase.tripidude.utils.DrawerMenuItemClickListener;
import at.tuwien.ase.tripidude.utils.Log;
import at.tuwien.ase.tripidude.utils.Utils;
import at.tuwien.ase.tripidude.views.MenuDrawer;

public class MainActivity extends BaseActivity implements OnLoginFragmentListener, OnRegisterFragmentListener {

	public static final String MAPFRAGMENT_TAG = "mapfragment_tag";
	//For tutorial
	private static final int SHOW_TUTORIAL_LOGIN = 99;
	private static final int SHOW_TUTORIAL_ACTION = 98;

	public interface OnActivityResultListener {
		public void onActivityResultFromActivity(int requestCode, int resultCode, Intent data);
	}

	private MenuDrawer drawer;
	private boolean isLoginView;
	private boolean isSearchView;

	private FragmentController registerFragmentController = null;
	private FragmentController loginFragmentController = null;

	private List<OnActivityResultListener> onActivityResultListener;

	private MapItem currentMapItem; //for Event
	private MapFragment mapFragment = null;

	public void addActivityResultListener(OnActivityResultListener listener) {
		if (Utils.isNullOrEmpty(onActivityResultListener))
			onActivityResultListener = new ArrayList<MainActivity.OnActivityResultListener>();
		onActivityResultListener.add(listener);
	}

	public void addActivityResultListener(OnActivityResultListener listener, int code) {
		if (Utils.isNullOrEmpty(onActivityResultListener))
			onActivityResultListener = new ArrayList<MainActivity.OnActivityResultListener>();
		onActivityResultListener.add(listener);
	}

	public void removeActivityResultListener(OnActivityResultListener listener) {
		if (Utils.isNullOrEmpty(onActivityResultListener))
			return;
		onActivityResultListener.remove(listener);
	}

	@Override
	public int rootLayoutId() {
		return R.id.drawer_layout;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_main);
		isSearchView = false;

		App.resources = getResources();
		App.preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
		App.context = getApplicationContext();

		getActionBar().setDisplayHomeAsUpEnabled(true);
		drawer = new MenuDrawer(this, ui, getMenuItemList(), new DrawerMenuItemClickListener() {
			@Override
			public void onItemSelected(DrawerMenuItem item) {
				if (item.getId() == R.string.map) {
					showMap(true);
				} else {
					FragmentController mfragment = getFragmentByStringId(item.getId());
					addFragmentController(mfragment, R.id.content_frame, false);
				}
				drawer.close();
			}
		});

		// add the map fragment
		mapFragment = new MapFragment();
		App.mapListener = mapFragment;
		FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
		ft.add(R.id.map_frame, mapFragment, MAPFRAGMENT_TAG);
		ft.commit();

		IsLoggedInOperation op = new IsLoggedInOperation();
		op.execute(new String[] {});
	}

	protected FragmentController getFragmentByStringId(int id) {
		FragmentController mfragment = null;
		switch (id) {
		case R.string.events:
			mfragment = EventsFragment.newInstance("x/y");
			getActionBar().setIcon(R.drawable.ic_menu);
			getActionBar().setTitle(getResources().getString(R.string.events));
			break;
		case R.string.hotspot:
			mfragment = new CreateMapItemFragment();
			getActionBar().setTitle(getResources().getString(R.string.hotspot));
			break;
		case R.string.search_button:
			mfragment = new SearchMapitemFragment();
			getActionBar().setTitle(getResources().getString(R.string.search_button));
			break;
		case R.string.create_route:
			mfragment = new CreateRouteFragment();
			getActionBar().setTitle(getResources().getString(R.string.create_route));
			break;
		case R.string.user_profile:
			mfragment = new UserProfileFragment();
			getActionBar().setTitle(getResources().getString(R.string.user_profile));
			break;
		case R.string.highscores:
			mfragment = new HighscoresFragment();
			getActionBar().setTitle(getResources().getString(R.string.highscores));
			break;
		}
		return mfragment;
	}

	private List<DrawerMenuItem> getMenuItemList() {
		List<DrawerMenuItem> list = new ArrayList<DrawerMenuItem>();
		list.add(new DrawerMenuItem(0, R.string.map));
		list.add(new DrawerMenuItem(0, R.string.search_button));
		list.add(new DrawerMenuItem(0, R.string.create_route));
		list.add(new DrawerMenuItem(0, R.string.user_profile));
		list.add(new DrawerMenuItem(0, R.string.highscores));
		return list;
	}

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

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		drawer.onSyncState();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		drawer.onConfigurationChanged(newConfig);
	}

	@Override
	public void onBackPressed() {
		if (isLoginView)
			return;

		if(getCurrentFragment() != null) { //check needed for tutorial
			Log.info(this, "removing fragment: " + getCurrentFragment().getTag());
		}
		if(isSearchView && getCurrentFragment() instanceof SearchMapitemFragment) {
			Log.info(this, "removing search");
			isSearchView = false;
			App.mapListener.setSearchForMapItems(false);
		}

		if (getFragmentBackStackEntryCount() < 2) {
			showMap(false);
			return;
		}

		addFragmentController(null, backStackFragmentContainerId, true, false, 0);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (!drawer.onOptionsItemSelected(item)) {
			switch (item.getItemId()) {
			case R.id.action_logout:
				//logout
				LogoutOperation op = new LogoutOperation();
				op.execute(new String[]{});
				return true;
			case R.id.action_search:
				//show and hide search
				if(isSearchView) {
					App.mapListener.setSearchForMapItems(false);
					isSearchView = false;
					this.onBackPressed();
					//Refresh Mapitems
					App.mapListener.searchForNewMapItems();
				} else {
					App.mapListener.setSearchForMapItems(true);
					isSearchView = true;
					addFragmentController(new SearchMapitemFragment(), R.id.content_frame);
				}
				return true;
			case R.id.action_tutorial:
				//show the tutorial again
				//start tutorial
				for (OnActivityResultListener listener : onActivityResultListener) {
					listener.onActivityResultFromActivity(SHOW_TUTORIAL_ACTION, -1, null);
					Log.debug(this, "Called listener to start tutorial");
				}
				return true;
			default:
				return super.onOptionsItemSelected(item);
			}
		} else {
			return true;
		}
	}

	public void showMap(boolean reset) {
		emptyFragmentBackStackUntil(0);
		getActionBar().setTitle(getResources().getString(R.string.app_name));
		if (reset)
			App.mapListener.reset();
	}

	/**
	 * Show login view
	 */
	private void showLoginView() {
		isLoginView = true;
		getActionBar().hide();

		loginFragmentController = new LoginFragment();
		addFragmentController(loginFragmentController , R.id.content_frame);
	}

	@Override
	public void onLoginSuccess() {
		isLoginView = false;

		FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
		if (loginFragmentController != null)
			ft.remove(loginFragmentController);
		if (registerFragmentController != null)
			ft.remove(registerFragmentController);
		ft.commit();

		getActionBar().show();

		// start tutorial
		for (OnActivityResultListener listener : onActivityResultListener) {
			listener.onActivityResultFromActivity(SHOW_TUTORIAL_LOGIN, -1, null);
		}

		// addFragmentController(new MapFragment(), R.id.content_frame);
	}

	@Override
	public void onGoToRegistration() {
		isLoginView = true;
		getActionBar().hide();
		registerFragmentController = new RegisterFragment();
		addFragmentController(registerFragmentController, R.id.content_frame);
	}

	@Override
	public void onRegisterSuccess() {
		onLoginSuccess();
	}

	private class IsLoggedInOperation extends AsyncTask<String, Void, Boolean>  {

		@Override
		protected Boolean doInBackground(String... params) {
			try {
				if (UserAPI.getInstance().isLoggedIn()) {
					return true;
				} else {
					//try auto login
					return UserAPI.getInstance().doAutoLogin();
				}
			} catch (APIException e) {
				return false;
			}
		}

		@Override
		protected void onPostExecute(Boolean result) {
			if (result) {
				onLoginSuccess();
			} else {
				showLoginView();
			}
		}
	}

	private class LogoutOperation extends AsyncTask<String, Void, String>  {

		@Override
		protected String doInBackground(String... params) {
			UserAPI.getInstance().doLogout();
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			showLoginView();
		}
	}

	public void addFragmentController(FragmentController mfragment) {
		addFragmentController(mfragment, R.id.content_frame, false);

	}

	public void addFragmentController(FragmentController mfragment, int numberOfItemsToKeepOnBackStack) {
		addFragmentController(mfragment, R.id.content_frame, false, numberOfItemsToKeepOnBackStack);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(resultCode != RESULT_CANCELED){
			if (!Utils.isNullOrEmpty(onActivityResultListener)) {
				Log.info(MainActivity.this, "Activity result for listners");
				for (OnActivityResultListener listener : onActivityResultListener) {
					listener.onActivityResultFromActivity(requestCode, resultCode, data);
				}
				return;
			}
		}
		else{
			Log.info(this, "Result was canceled or data were null");
			return;
		}
	}

	public MapFragment getMapFragment() {
		return mapFragment;
	}

	public void setCurrentMapItem(MapItem mi){
		currentMapItem = mi;
	}

	public MapItem getCurrentMapItem(){
		return currentMapItem;
	}
}


text:
<!DOCTYPE html>

Release Note - WSO2 IoT Server Version 3.1.0

We are pleased to announce WSO2 IoT Server 3.1.0.

WSO2 IoT Server is one of the most adaptive Apache licensed open source IoT platforms available today. It provides best of breed technologies for device manufacturers to develop connected products as well as rich integration and smart analytics capabilities for system integrators to adopt devices into systems they build.

These capabilities involve device management, smart analytics, API and app management for devices, transport extensions for MQTT, XMPP and many more.

What's new in WSO2 IoTS 3.1.0

A complete API-driven device type definition eliminating the necessity to create deployable plugins

Support for location based services such as Geofencing and alerting as a reusable functionality

A redesigned device overview page for better user experience

Improved product profiles for scalable deployment

Performance enhancements

Enhancements to prebuilt agents

Documentation

Documentations:  WSO2 IoT Server Documentation

Known Issues

The known set of issues this version can be found  here.

Engaging with Community

Mailing Lists

Join our mailing list and correspondence with the developers directly.

Developer list: dev@wso2.org | Subscribe | Mail Archive

Reporting Issues

We encourage you to report issues, documentation faults and feature requests regarding WSO2 IoT Server through WSO2 IoT GIT Issues.

Discussion Forums

We encourage you to use stackoverflow to engage with developers as well as other users.

For more information about WSO2 IoT Server, please see http://wso2.com/products/iot-server or visit the WSO2 Oxygen Tank developer portal for additional resources.

Thank you for your interest in WSO2 IoT Server.

The WSO2 IoT Server Team


text:
This Ruby project has starting source code and tests
for the katas along with a description markdown file.

It saves all RubyMine workplace, project and dependencies locally.

#### Getting started
Make sure you have cloned the training repo.
```
git clone https://github.com/dwhelan/training.git
```

or

```
git clone git@github.com:dwhelan/training.git
```

Setup ...

```
cd ruby
bundle install
rake test
```

If all goes well you should see something like:

```
Run options: --seed 15196

# Running:

.

Fabulous run in 0.000851s, 1175.0882 runs/s, 1175.0882 assertions/s.

1 runs, 1 assertions, 0 failures, 0 errors, 0 skips

```
#### RubyMine
Select menu `File` | `Open...`
and choose the `training/ruby` folder created above.

Select menu `Run` | `Run...` | `All`.
You should see that all tests passed.

You should also see a run configuration for each kata that
you can use to run individual kata tests.

#### VS Code
Select menu `File` | `Open...`
and choose the `training/ruby` folder created above.

You may want to install the [Ruby Test Explorer plugin](https://marketplace.visualstudio.com/items?itemName=connorshea.vscode-ruby-test-adapter).


text:
using Casanova.Prelude;
using System.Linq;
using System;
using System.Collections.Generic;
using UnityEngine;
public class World : MonoBehaviour
{
  public static int frame;
  void Update()
  {
    Update(Time.deltaTime, this);
    frame++;
  }
  public bool JustEntered = true;

  public void Start()
  {
    Velocity = new UnityEngine.Vector3(3f, 0.5f, 1f);
    UnityBall = UnityBall.Find();
    Gravity = new UnityEngine.Vector3(0f, -9.81f, 0f);
    FrictionCoefficient = 0.9f;
  }
  public System.Single FrictionCoefficient;
  public UnityEngine.Vector3 Gravity;
  public UnityEngine.Vector3 Position
  {
    get { return UnityBall.Position; }
    set { UnityBall.Position = value; }
  }
  public System.Boolean Quit
  {
    set { UnityBall.Quit = value; }
  }
  public UnityBall UnityBall;
  public UnityEngine.Vector3 Velocity;
  public UnityEngine.Animation animation
  {
    get { return UnityBall.animation; }
  }
  public UnityEngine.AudioSource audio
  {
    get { return UnityBall.audio; }
  }
  public UnityEngine.Camera camera
  {
    get { return UnityBall.camera; }
  }
  public UnityEngine.Collider collider
  {
    get { return UnityBall.collider; }
  }
  public UnityEngine.Collider2D collider2D
  {
    get { return UnityBall.collider2D; }
  }
  public UnityEngine.ConstantForce constantForce
  {
    get { return UnityBall.constantForce; }
  }
  public System.Boolean enabled
  {
    get { return UnityBall.enabled; }
    set { UnityBall.enabled = value; }
  }
  public UnityEngine.GameObject gameObject
  {
    get { return UnityBall.gameObject; }
  }
  public UnityEngine.GUIElement guiElement
  {
    get { return UnityBall.guiElement; }
  }
  public UnityEngine.GUIText guiText
  {
    get { return UnityBall.guiText; }
  }
  public UnityEngine.GUITexture guiTexture
  {
    get { return UnityBall.guiTexture; }
  }
  public UnityEngine.HideFlags hideFlags
  {
    get { return UnityBall.hideFlags; }
    set { UnityBall.hideFlags = value; }
  }
  public UnityEngine.HingeJoint hingeJoint
  {
    get { return UnityBall.hingeJoint; }
  }
  public UnityEngine.Light light
  {
    get { return UnityBall.light; }
  }
  public System.String name
  {
    get { return UnityBall.name; }
    set { UnityBall.name = value; }
  }
  public UnityEngine.ParticleEmitter particleEmitter
  {
    get { return UnityBall.particleEmitter; }
  }
  public UnityEngine.ParticleSystem particleSystem
  {
    get { return UnityBall.particleSystem; }
  }
  public UnityEngine.Renderer renderer
  {
    get { return UnityBall.renderer; }
  }
  public UnityEngine.Rigidbody rigidbody
  {
    get { return UnityBall.rigidbody; }
  }
  public UnityEngine.Rigidbody2D rigidbody2D
  {
    get { return UnityBall.rigidbody2D; }
  }
  public System.String tag
  {
    get { return UnityBall.tag; }
    set { UnityBall.tag = value; }
  }
  public UnityEngine.Transform transform
  {
    get { return UnityBall.transform; }
  }
  public System.Boolean useGUILayout
  {
    get { return UnityBall.useGUILayout; }
    set { UnityBall.useGUILayout = value; }
  }
  public System.Single count_down1;
  public void Update(float dt, World world)
  {
    this.Rule1(dt, world);

    this.Rule0(dt, world);
    this.Rule2(dt, world);
    this.Rule3(dt, world);
  }
  public void Rule1(float dt, World world)
  {
    Position = (Position) + ((Velocity) * (dt));
  }

  int s0 = -1;
  public void Rule0(float dt, World world)
  {
    switch (s0)
    {

      case -1:
        if (!(((0f) > (Position.y))))
        {

          s0 = -1;
          return;
        }
        else
        {

          goto case 0;
        }
      case 0:
        Position = new UnityEngine.Vector3(Position.x, 0f, Position.z);
        Velocity = ((new UnityEngine.Vector3(Velocity.x, (Velocity.y) * (-1f), Velocity.z)) * (FrictionCoefficient));
        s0 = -1;
        return;
      default: return;
    }
  }

  int s2 = -1;
  public void Rule2(float dt, World world)
  {
    switch (s2)
    {

      case -1:
        count_down1 = 1f;
        goto case 2;
      case 2:
        if (((count_down1) > (0f)))
        {

          count_down1 = ((count_down1) - (dt));
          s2 = 2;
          return;
        }
        else
        {

          goto case 0;
        }
      case 0:
        Velocity = ((Velocity) + (((Gravity) * (dt))));
        s2 = -1;
        return;
      default: return;
    }
  }

  int s3 = -1;
  public void Rule3(float dt, World world)
  {
    switch (s3)
    {

      case -1:
        if (!(UnityEngine.Input.GetKey(KeyCode.Escape)))
        {

          s3 = -1;
          return;
        }
        else
        {

          goto case 0;
        }
      case 0:
        Quit = true;
        s3 = -1;
        return;
      default: return;
    }
  }

}


text:
layout: post
title:  "VIDEO: Hrana na Novi Zelandiji"
date:   2019-04-02
published: true
author: Ana in Primož
---

K
	malu bo že dve leti od kar sva prišla iz Nove Zelandije in odkar sva nazaj naju je že kar nekaj ljudi vprašalo: "Kakšna pa je hrana na Novi Zelandiji? Kaj oni jejo? Kaj je tam tradicionalno?"

Video, ki ga objavljava malo v šali, ampak brez preveč pretiravanja prestavi, kako se Novozelandci prehranjuejo. Hvala **How to DAD** za super video.


text:
/*!
 * jQuery Textarea AutoSize plugin
 * Author: Javier Julio
 * Licensed under the MIT license
 */
;(function ($, window, document, undefined) {

  var pluginName = "textareaAutoSize";
  var pluginDataName = "plugin_" + pluginName;

  var containsText = function (value) {
    return (value.replace(/\s/g, '').length > 0);
  };

  function Plugin(element, options) {
    this.element = element;
    this.$element = $(element);
    this.init();
  }

  Plugin.prototype = {
    init: function() {
      var height = this.$element.outerHeight();
      var diff = parseInt(this.$element.css('paddingBottom')) +
                  parseInt(this.$element.css('paddingTop'));

      // Firefox: scrollHeight isn't full height on border-box
      if (this.element.scrollHeight + diff <= height) {
        diff = 0;
      }

      if (containsText(this.element.value)) {
        this.$element.height(this.element.scrollHeight);
      }

      // keyup is required for IE to properly reset height when deleting text
      this.$element.on('input keyup', function(event) {
        $(this)
          .height('auto')
          .height(this.scrollHeight - diff);
      });
    }
  };

  $.fn[pluginName] = function (options) {
    this.each(function() {
      if (!$.data(this, pluginDataName)) {
        $.data(this, pluginDataName, new Plugin(this, options));
      }
    });
    return this;
  };

})(jQuery, window, document);


text:
describe('usersService', () => {
    describe('allUsers', () => {
        it('Should invoke requester.get method once.', () => {
            const mockRequester = sinon.mock(requester);
            mockRequester.expects('get').once();

            usersService.allUsers();

            mockRequester.verify();
        });

        it('Should invoke requester.get method with correct url.', () => {
            const mockRequester = sinon.mock(requester);
            mockRequester.expects('get').withArgs('api/users').once();

            usersService.allUsers();

            mockRequester.verify();
        });

        it('Should invoke requester.get method with correct header.', () => {
            const stubLocalStorage = sinon.stub(localStorage, 'getItem');
            stubLocalStorage.returns('auth-key');

            const stubIsLoggedIn = sinon.stub(usersService, 'isLoggedIn');
            stubIsLoggedIn.returns(true);

            const mockRequester = sinon.mock(requester);
            mockRequester.expects('get').withArgs('api/users', { 'x-auth-key': 'auth-key' }).once();

            usersService.allUsers();

            mockRequester.verify();
        });
    });

    describe('login', () => {
        it('Should invoke requester.putJSON method.', () => {
            const mockRequester = sinon.mock(requester);
            mockRequester.expects('putJSON').once();

            try {
                usersService.login();
            } catch (err) {

            }

            mockRequester.verify();
        });

        it('Should invoke requester.putJSON method with correct url.', () => {
            const mockRequester = sinon.mock(requester);
            mockRequester
                .expects('putJSON')
                .withArgs('api/auth')
                .once();

            try {
                usersService.login();
            } catch (err) {

            }

            mockRequester.verify();
        });

        it('Should invoke window.localStorage.setItem 2 times.', (done) => {
            const requesterPutJSON = sinon.stub(requester, 'putJSON');
            requesterPutJSON.returns(new Promise((resolve, reject) => {
                const fakeResponse = {};
                fakeResponse.result = {
                    username: 'me',
                    authKey: 'key'
                };

                resolve(fakeResponse);
            }));

            const mockStorage = sinon.mock(window.localStorage);
            mockStorage.expects('setItem').twice();

            usersService.login()
                .then(() => {
                    mockStorage.verify();
                })
                .then(() => {
                    mockStorage.restore();
                    requesterPutJSON.restore();
                })
                .then(done, done);
        });

        it('Should invoke.localStorage.setItem with correct values.', (done) => {
            const requesterPutJSON = sinon.stub(requester, 'putJSON');
            requesterPutJSON.returns(new Promise((resolve, reject) => {
                const fakeResponse = {};
                fakeResponse.result = {
                    username: 'me',
                    authKey: 'key'
                };

                resolve(fakeResponse);
            }));

            const mockStorage = sinon.mock(window.localStorage);
            mockStorage.expects('setItem').withArgs('username', 'me').once();
            mockStorage.expects('setItem').withArgs('authKey', 'key').once();

            usersService.login()
                .then(() => {
                    mockStorage.verify();
                })
                .then(() => {
                    mockStorage.restore();
                    requesterPutJSON.restore();
                })
                .then(done, done);
        });
    });

    describe('register', () => {
        it('Should invoke requester.postJSON method', () => {
            const mockRequester = sinon.mock(requester);
            mockRequester.expects('postJSON').once();

            usersService.register();

            mockRequester.verify();
        });

        it('Should invoke requester.postJSON method with correct url.', () => {
            const mockRequester = sinon.mock(requester);
            mockRequester.expects('postJSON').withArgs('api/users').once();

            usersService.register();

            mockRequester.verify();
        });
    });
});


text:
"use strict";
var AuthorizationService = (function () {
    function AuthorizationService($http, $q, config, $httpParamSerializer) {
        this.$http = $http;
        this.$q = $q;
        this.config = config;
        this.$httpParamSerializer = $httpParamSerializer;
        this.defaultHeaders = {};
    }
    AuthorizationService.prototype.Authorize = function (api, userName, password) {
        var deffer = this.$q.defer();
        this.getToken(userName, password).then(function (response) {
            api.authentications.oauth2.accessToken = response.access_token;
            deffer.resolve();
        }, function (params) {
            deffer.reject(params);
        });
        return deffer.promise;
    };
    AuthorizationService.prototype.getToken = function (userName, password) {
        var deffer = this.$q.defer();
        var localVarPath = this.config.basePath + '/Token';
        var headerParams = { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' };
        var value = {
            username: userName,
            password: password,
            grant_type: 'password'
        };
        var httpRequestParams = {
            method: 'POST',
            url: localVarPath,
            json: true,
            data: this.$httpParamSerializer(value),
            headers: headerParams
        };
        this.$http(httpRequestParams).then(function (response) {
            deffer.resolve(response.data);
        }, function (err) {
            deffer.reject(err);
        });
        return deffer.promise;
    };
    ;
    AuthorizationService.$inject = ['$http', '$q', 'IApiConfig', '$httpParamSerializer'];
    return AuthorizationService;
}());
exports.AuthorizationService = AuthorizationService;
//# sourceMappingURL=AuthorizationService.js.map


text:
require "spec_helper"

describe Notifications do
  prepare_scope :tenant
  let(:account) { FactoryGirl.create :account }

  describe "account_reset" do
    let(:mail) { Notifications.account_reset account }

    it "renders the headers" do
      mail.subject.should eq(I18n.t("notifications.account_reset.subject."))
      mail.to.should eq([account.email])
      mail.from.should eq([account.tenant.from_email])
    end

    it "puts the response url in the body" do
      mail.body.encoded.should include(account_response_session_url(account.authentication_token, :host => account.tenant.host))
    end
  end

  shared_examples_for "a_tenant_creation_body" do
    subject { mail.body.encoded }

    it { should match("td.*#{tenant.name}") }
    it { should match("Stad.*#{tenant.name}") }

    it { should match("td.*#{tenant.representative_name}") }
    it { should match("Naam.*#{tenant.representative_name}") }

    it { should match("td.*#{tenant.representative_email}") }
    it { should match("Email.*#{tenant.representative_email}") }

    it { should match("td.*#{tenant.representative_telephone}") }
    it { should match("Telefoon.*#{tenant.representative_telephone}") }

    it { should match("td.*#{tenant.invoice_address}") }
    it { should match("Factuuradres.*#{tenant.invoice_address}") }

    it { should match("td.*#{tenant.site_url}") }
    it { should match("Dialoogsite.*#{tenant.site_url}") }

    it { should match("td.*#{tenant.host}") }
    it { should match("Dialoogtafels url.*#{tenant.host}") }

    it { should match("td.*#{tenant.info_email}") }
    it { should match("Info email.*#{tenant.info_email}") }

    it { should match("td.*#{tenant.from_email}") }
    it { should match("Afzender email.*#{tenant.from_email}") }

    it { should match("td.*#{tenant.public_style_sheet}") }
    it { should match("Stylesheet.*#{tenant.public_style_sheet}") }

    it { should match("td.*#{tenant.top_image}") }
    it { should match("Header plaatje.*#{tenant.top_image}") }

    it { should match("td.*#{tenant.right_image}") }
    it { should match("Rechter kantlijn.*#{tenant.right_image}") }

    it { should have_selector("a[href='#{root_url(:host => tenant.host)}']") }

    it { should have_selector("a[href='#{new_registration_organizer_url(:host => tenant.host)}']") }
  end

  shared_examples_for "an_application_confirmation_mail_body" do
    subject { mail.body.encoded }
    it { should include(applicant.name) }
    it { should include(applicant.email) }
    it { should include(applicant.telephone) }

    context "when Profile field exists" do
      let!(:profile_field) { FactoryGirl.create :profile_string_field, field_name: 'address' }
      before { applicant.update_attribute :profile_address, 'adres' }
      it { should_not include(profile_field.label) }
      it { should_not include(applicant.profile_address) }

      context "and is in form" do
        before { profile_field.update_attribute :on_form, true }
        it { should include(profile_field.label) }
        it { should include(applicant.profile_address) }
      end

    end
  end

  describe "tenant_creation" do
    let(:tenant) { FactoryGirl.create :tenant }
    let(:mail) { Notifications.tenant_creation tenant }
    let(:addressee) { tenant.representative_email }

    it "renders the headers" do
      mail.subject.should eq(I18n.t("notifications.tenant_creation.subject."))
      mail.to.should eq([addressee])
      mail.from.should eq([Notifications::DialoogTafelsMail])
    end
    it_should_behave_like "a_tenant_creation_body"
  end

  describe "migration_completed_for_organizer" do
    let(:organizer) { FactoryGirl.create :person }
    let(:mail) { Notifications.migration_completed_for_organizer organizer }
    let(:tenant) { organizer.tenant }

    it "renders the headers" do
      mail.subject.should eq(I18n.t("notifications.migration_completed_for_organizer.subject."))
      mail.to.should eq([organizer.email])
      mail.cc.should eq([tenant.info_email])
      mail.from.should eq([Notifications::DialoogTafelsMail])
    end

    it "should render the account confirmation link" do
      mail.body.encoded.should include(account_response_session_url(organizer.account.authentication_token, :host => tenant.host))
    end

    it_should_behave_like "an_application_confirmation_mail_body" do
      let(:applicant) { organizer }
    end
  end

  describe "migration_completed_for_coordinator" do
    let(:coordinator) { FactoryGirl.create :coordinator_account }
    let(:mail) { Notifications.migration_completed_for_coordinator coordinator }
    let(:tenant) { coordinator.tenant }

    it "renders the headers" do
      mail.subject.should eq(I18n.t("notifications.migration_completed_for_coordinator.subject."))
      mail.to.should eq([coordinator.email])
      mail.from.should eq([Notifications::DialoogTafelsMail])
    end

    it "should render the account confirmation link" do
      mail.body.encoded.should include(account_response_session_url(coordinator.authentication_token, :host => tenant.host))
    end

    it_should_behave_like "a_tenant_creation_body"
  end

  describe "participant_confirmation" do
    let(:participant) { FactoryGirl.create :person }
    let(:mail) { Notifications.participant_confirmation participant, active_project }
    before { active_project.participant_confirmation_subject = "welcome participant" }

    it "renders the headers" do
      mail.subject.should eq(active_project.participant_confirmation_subject)
      mail.to.should eq([participant.email])
      mail.from.should eq([participant.tenant.from_email])
    end

    it "puts the confirmation text in the body" do
      mail.body.encoded.should include_marked_up(active_project.participant_confirmation_text)
    end

    it "puts the confirmation plain text in the body" do
      mail.body.encoded.should include_plain(active_project.participant_confirmation_text)
    end

    it_should_behave_like "an_application_confirmation_mail_body" do
      let(:applicant) { participant }
    end

  end

  describe "conversation_leader_confirmation" do
    let(:conversation_leader) { FactoryGirl.create :person }
    let(:mail) { Notifications.conversation_leader_confirmation conversation_leader, active_project }
    before { active_project.participant_confirmation_subject = "welcome conversation_leader" }

    it "renders the headers" do
      mail.subject.should eq(active_project.conversation_leader_confirmation_subject)
      mail.to.should eq([conversation_leader.email])
      mail.from.should eq([conversation_leader.tenant.from_email])
    end

    it "puts the confirmation text in the body" do
      mail.body.encoded.should include_marked_up(active_project.conversation_leader_confirmation_text)
    end

    it "puts the confirmation plain text in the body" do
      mail.body.encoded.should include_plain(active_project.conversation_leader_confirmation_text)
    end

    it_should_behave_like "an_application_confirmation_mail_body" do
      let(:applicant) { conversation_leader }
    end

  end

  describe "organizer_confirmation" do
    let(:organizer) { FactoryGirl.create :person }
    let(:mail) { Notifications.organizer_confirmation organizer, active_project }
    before { active_project.participant_confirmation_subject = "welcome organizer" }

    it "renders the headers" do
      mail.subject.should eq(active_project.organizer_confirmation_subject)
      mail.to.should eq([organizer.email])
      mail.from.should eq([organizer.tenant.from_email])
    end

    it "should render the account confirmation link" do
      mail.body.encoded.should include(account_response_session_url(organizer.account.authentication_token, :host => current_tenant.host))
    end

    it "puts the confirmation text in the body" do
      mail.body.encoded.should include_marked_up(active_project.organizer_confirmation_text)
    end

    it "puts the confirmation plain text in the body" do
      mail.body.encoded.should include_plain(active_project.organizer_confirmation_text)
    end

    it_should_behave_like "an_application_confirmation_mail_body" do
      let(:applicant) { organizer }
    end
  end

  describe "coordinator_confirmation" do
    let(:coordinator) { FactoryGirl.create :coordinator_account }
    let(:mail) { Notifications.coordinator_confirmation coordinator }

    it "renders the headers" do
      mail.subject.should eq(I18n.t("notifications.coordinator_confirmation.subject"))
      mail.to.should eq([coordinator.email])
      mail.from.should eq([coordinator.tenant.from_email])
    end

    it "should render the account confirmation link" do
      mail.body.encoded.should include(account_response_session_url(coordinator.authentication_token, :host => current_tenant.host))
    end
  end

  describe "comment notification" do
    let(:location_comment) { FactoryGirl.create :location_comment, subject: "my comment", body: "#Header\nbody" }
    let(:person) { FactoryGirl.create :person, email: "addressee@example.com"  }
    let(:mail) { Notifications.new_comment location_comment, person }

    it "renders the headers" do
      mail.subject.should eq(location_comment.subject)
      mail.from.should eq([ person.tenant.from_email ])
      mail.to.should eq([ person.email ])
    end

    it "puts the body marked up in the bdy" do
      mail.body.encoded.should have_selector("h1")
      mail.body.encoded.should include("Header")
      mail.body.encoded.should include("body")
    end

    it "has a link to the comment" do
      mail.body.encoded.should have_selector("a[href='#{city_location_comment_url(location_comment.to_param, :location_id => location_comment.reference_id, :host => current_tenant.host)}']")
    end

  end

  describe "training invitation" do
    let(:training_invitation) { FactoryGirl.create :training_invitation, subject: "invitation", body: "#Header\nbody" }
    let(:person) { FactoryGirl.create :person, email: "addressee@example.com"  }
    let(:mail) { Notifications.new_training_invitation training_invitation, person }

    it "renders the headers" do
      mail.subject.should eq(training_invitation.subject)
      mail.from.should eq([ person.tenant.from_email ])
      mail.to.should eq([ person.email ])
    end

    it "puts the body marked up in the bdy" do
      mail.body.encoded.should have_selector("h1")
      mail.body.encoded.should include("Header")
      mail.body.encoded.should include("body")
    end
  end

  describe "new_participant" do
    let(:conversation) { FactoryGirl.create :conversation }
    let(:organizer) { conversation.organizer }
    let(:person) { FactoryGirl.build :person }
    let(:mail) { Notifications.new_participant organizer, person, conversation }

    it "renders the headers" do
      mail.subject.should eq(I18n.t("notifications.new_participant.subject"))
      mail.to.should eq([organizer.email])
      mail.from.should eq([organizer.tenant.from_email])
    end
    it "renders the organizer and person names in the body" do
      mail.body.encoded.should include(organizer.name)
      mail.body.encoded.should include(person.name)
    end
    it "renders a link to the location" do
      mail.body.encoded.should include(city_location_url(conversation.location.to_param, :host => organizer.tenant.host))
    end

  end

  describe "new conversation_leader" do
    let(:conversation) { FactoryGirl.create :conversation }
    let(:organizer) { conversation.organizer }
    let(:person) { FactoryGirl.build :person }
    let(:mail) { Notifications.new_conversation_leader organizer, person, conversation }

    it "renders the headers" do
      mail.subject.should eq(I18n.t("notifications.new_conversation_leader.subject"))
      mail.to.should eq([organizer.email])
      mail.from.should eq([organizer.tenant.from_email])
    end

    it "renders the organizer and conversation_leader names in the body" do
      mail.body.encoded.should include(organizer.name)
      mail.body.encoded.should include(person.name)
    end

    it "renders a ling to the location" do
      mail.body.encoded.should include(city_location_url(conversation.location.to_param, :host => organizer.tenant.host))
    end
  end

  describe "mailing_message" do
    let(:mailing_message) { MailingMessage.new subject: "my comment", body: "#Header\nbody" }
    let(:person) { FactoryGirl.create :person, email: "addressee@example.com"  }
    let(:mail) { Notifications.mailing_message mailing_message, person }

    it "renders the headers" do
      mail.subject.should eq(mailing_message.subject)
      mail.from.should eq([ person.tenant.from_email ])
      mail.to.should eq([ person.email ])
    end

    it "puts the body marked up in the bdy" do
      mail.body.encoded.should have_selector("h1")
      mail.body.encoded.should include("Header")
      mail.body.encoded.should include("body")
    end

  end

  describe "notify_new_registration" do
    let(:recepient) { 'email@mail.com' }
    let(:person) { FactoryGirl.build :person }
    let(:project) { current_tenant.active_project }
    let(:mail) { Notifications.notify_new_registration recepient, person, project, :organizer }
    subject { mail }

    its(:subject)  { should eq(I18n.t("notifications.notify_new_registration.subject.")) }
    its(:from)     { should eq([ project.tenant.from_email ]) }
    its(:to)       { should eq([ recepient ]) }

    context "to is a a mail list" do
      let(:recepient) { 'recepient@mail.com, recepient2@mail.com'  }
      its(:to)        { should eq( recepient.split(',').map { |r| r.strip }  ) }
    end

    describe "body" do
      subject { mail.body.encoded }
      it { should include("Er is een #{I18n.t('organizer')} aangemeld") }

      it_should_behave_like "an_application_confirmation_mail_body" do
        let(:applicant) { person }
      end
    end
  end

  RSpec::Matchers.define :include_marked_up do |expected|
    match do |actual|
      actual.gsub("\r\n", '').include?(marked_up(expected).gsub("\n", ''))
    end
    failure_message_for_should do |actual|
      "expected that #{actual} matches #{marked_up(expected)}"
    end
  end

  RSpec::Matchers.define :include_plain do |expected|
    match do |actual|
      actual.gsub("\r\n", '').include?(expected.gsub("\n", ''))
    end
    failure_message_for_should do |actual|
      "expected that #{actual} matches #{marked_up(expected)}"
    end
  end

  def marked_up(text)
    BlueCloth.new(text).to_html
  end

  def current_tenant
    Tenant.current
  end
  def active_project
    current_tenant.active_project
  end
end