text:
/**============================================================
 * 版权:kelvem 版权所有 (c) 2010 - 2012
 * 文件:com.kelvem.common.base.Hibernate4DaoBase.java
 * 所含类: Hibernate4DaoBase.java
 * 修改记录:
 * 日期                           	作者                            内容
 * =============================================================
 * 2012-06-16     zhaobai       创建文件,实现基本功能
 * ============================================================*/

package com.smartssh.hibernatestudy.base;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.ProjectionList;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Property;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;

/**
 *
Hibernate4DaoBase

 *
 *
所有Dao的基类

 *
 *
Copyright: 版权所有 (c) 2010 - 2012

 *
Company: kelvem

 *
 * @ClassName Hibernate4DaoBase
 * @author kelvem
 * @version 1.0
 *
 */
public class Hibernate4DaoBase<T extends Serializable,PK extends Serializable> {
	/**
	 * Log4J Logger for this class
	 */
	private static final Log logger = LogFactory.getLog(Hibernate4DaoBase.class);

	private SessionFactory sessionFactory;

	/**
	 *
根据序列名称获取序列值

	 *
	 * @param seqName
	 * @return Integer
	 */
	public Long getSequenceNextvalBySeqName(String seqName){
		StringBuffer sql = new StringBuffer("Select ")
									.append(seqName)
									.append(".nextval ")
									.append("from dual");
		java.math.BigDecimal id = (java.math.BigDecimal)getSession().createSQLQuery(sql.toString()).uniqueResult();
		return id.longValue();
	}

	/**
	 *
取得数据库服务器当前时间

	 *
	 * @return Date
	 * @see
	 */
	protected Date getCurrentSysDate(){
		return (Date)this.getSession().createSQLQuery("select now()").uniqueResult();
	}

	/**
	 *
保存实体对象

	 *
	 * @param object
	 * @return 单主键Long类型
	 * @see 其他相关
	 */
	public Serializable save(T object) {
		return getSession().save(object);
	}

	/**
	 *
保存或更新实体对象

	 *
	 * @param object 实体T
	 * @see public Long save(T object)
	 */
	public void saveOrUpdate(T object) {
		getSession().saveOrUpdate(object);
	}

	/**
	 *
保存实体对象

	 *
	 * @param objectlist 实体对象列表
	 * @return int 实体数
	 */
	public int save(List<T> objectlist) {
		for (int i = 0; i < objectlist.size(); i++) {
			getSession().save(objectlist.get(i));
			if (i % 30 == 0) {
				this.getSession().flush();
				this.getSession().clear();
			}
		}
		return objectlist.size();
	}

	/**
	 *
删除实体

	 *
	 * @param object 实体
	 */
	public void delete(T object) {
		this.getSession().delete(object);
	}

	/**
	 *
删除实体对象

	 *
	 * @param objectlist 实体对象列表
	 * @return int 实体数
	 */
	public int delete(List<T> objectlist) {
		for (int i = 0; i < objectlist.size(); i++) {
			getSession().delete(objectlist.get(i));
			if (i % 30 == 0) {
				this.getSession().flush();
				this.getSession().clear();
			}
		}
		return objectlist.size();
	}

	/**
	 *
更新实体

	 *
	 * @param object 实体
	 */
	public void update(T object) {
		this.getSession().update(object);
	}

	/**
	 *
根据实体对象查询实体列表

	 *
	 * @param object 实体对象
	 * @return List<T> 满足查询条件的实体列表
	 * @see 其他相关
	 */
	@SuppressWarnings("unchecked")
	public List<T> findByExample(final T object) {
		List<T> list = this.getSession().createCriteria(object.getClass()).add(Example.create(object)).list();
		return list;
	}

	/**
	 *
根据实体属性查询实体列表

	 *
	 * @param className 实体类
	 * @param propertyName 属性名
	 * @param value 属性值班
	 * @return  List<T> 满足查询条件的实体列表
	 */
	@SuppressWarnings("unchecked")
	public List<T> findByProperty(Class<T> className, String propertyName, Object value) {
		String querysql = "from " + className.getName()	+ " as model where model." + propertyName + "=?";
		return this.getSession().createQuery(querysql).setEntity(0, value).list();
	}

	/**
	 *
根据实体ID查询单个的实体对象

	 *
	 * @param className
	 * @param id
	 * @return T 实体
	 * @see public List<T> findByLikedPropertys(final Class<T> className,final String[] props, final Object[] vals)
	 */
	@SuppressWarnings("unchecked")
	public T  getById(Class<T> className, PK id) {
		return (T)this.getSession().get(className, id);
	}

	/**
	 *
根据实体属性列表及值模糊查询实体列表

	 *
	 * @param className 实体类
	 * @param props[] 属性数据
	 * @param vals[] 属性值
	 * @return List<T> 满足查询条件的实体列表
	 * @see public List<T> findByProperty(Class<T> className, String propertyName,Object value)
	 */
	@SuppressWarnings("unchecked")
	public List<T> findByLikedPropertys(final Class<T> className,
			final String[] props, final Object[] vals) {
		if (logger.isDebugEnabled()) {
			logger.debug("findByLikedPropertys(Class, String[], Object[]) - start");
		}

		if (logger.isDebugEnabled()) {
			logger.debug("doInHibernate(Session) - start");
		}

		List<T> list = null;

		Criteria criteria = this.getSession().createCriteria(className);
		for (int i = 0; i < props.length; i++) {
			if (vals[i] != null) {
				criteria.add(Restrictions.like(props[i], "%" + vals[i] + "%"));

			}
		}
		list = criteria.list();

		if (logger.isDebugEnabled()) {
			logger.debug("return result size is =" + list.size());
			logger.debug("doInHibernate(Session) - end");
		}

		if (logger.isDebugEnabled()) {
			logger.debug("findByLikedPropertys(Class, String[], Object[]) - end");
		}
		return list;
	}

	/**
	 *
根据实体对象查询实体列表

	 *
	 * @param example
	 * @param orderPropertyName 排序属性DESC
	 * @return List<T>
	 */
	@SuppressWarnings("unchecked")
	public List<T> findByExampleForOrder(final T example,final String orderPropertyName) {
		return this.getSession()
				.createCriteria(example.getClass())
				.add(Example.create(example))
//				.add(Restrictions.eq("tblquestion", inobject))
				.addOrder(Property.forName(orderPropertyName).desc())
				.list();
	}

	/**
	 *
查询实体数

	 *
	 * @param t 实体
	 * @return Integer 实体数
	 */
	protected Integer CountRowByExample(final T t) {
		Criteria criteria = this.getSession().createCriteria(t.getClass()).add(Example.create(t));
		Integer totalCountObject = Integer.valueOf(criteria.setProjection(Projections.rowCount()).uniqueResult().toString());
		return totalCountObject;
	}

	/**
	 *
条件查询所有的实体列表

	 *
	 * @param detachedCriteria
	 * @return
	 * @see 其他相关
	 */
	@SuppressWarnings("unchecked")
	protected List<T> findAllByCriteria(final DetachedCriteria detachedCriteria) {
		Criteria criteria = detachedCriteria.getExecutableCriteria(this.getSession());
		return criteria.list();
	}

	/**
	 *
根据DetachedCriteria条件查询实体数量

	 *
	 * @param detachedCriteria
	 * @return  实体数
	 * @see 其他相关
	 */
	protected int findCountByCriteria(final DetachedCriteria detachedCriteria) {
		Criteria criteria = detachedCriteria.getExecutableCriteria(this.getSession());
		return (Integer) criteria.setProjection(Projections.rowCount()).uniqueResult();
	}

	/**
	 *
根据DetachedCriteria条件查询实体列表

	 *
	 * @param detachedCriteria
	 * @return  实体列表
	 */
	@SuppressWarnings("unchecked")
	protected List<T> findCountByGroup(final DetachedCriteria detachedCriteria) {
		final ProjectionList projectionList = Projections.projectionList();
		projectionList.add(Projections.groupProperty("groupState"));
		projectionList.add(Projections.rowCount());
		Criteria criteria = detachedCriteria.getExecutableCriteria(this.getSession());
		criteria.setProjection(projectionList);
		List<T> list = criteria.list();
		return list;
	}

	/**
	 *
判断对象是否为null,字段串"",null返回false,其它null返回false

	 *
	 * @param obj
	 * @return
	 * @see 其他相关
	 */
	protected boolean isNotEmpty(Object obj) {
		if (obj == null) {
			return false;
		}
		if (obj instanceof String) {
			if (((String) obj).trim().length() == 0) {
				return false;
			} else {
				return true;
			}
		}
		return true;
	}

	/**
	 *
判断对象是否为null,字段串"",null返回false,其它null返回false,如果是小于0返回false

	 *
	 * @param obj
	 * @return
	 * @see 其他相关
	 */
	protected boolean isValidate(Object obj) {
		boolean result = true;
		if (obj == null) {
			result = false;
		}
		if (obj instanceof String) {
			if (((String) obj).trim().length() == 0) {
				result = false;
			} else if(((String) obj).trim().startsWith("-")){
				result = false;
			}else{
				return true;
			}
		}else if(obj instanceof Integer){
			if(((Integer)obj).intValue() < 0 ){
				result =  false;
			}
		}
		return result;
	}

	private Session getSession(){
		return this.getSessionFactory().getCurrentSession();
	}

	private SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
}


text:
import { Injectable } from '@angular/core';
import { WindowRef } from '../ref/window.ref';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';

declare const webkitSpeechRecognition: any;

@Injectable()
export class SpeechService {

  private recognition;
  private speechSubject = new Subject<string>();
  private speechObserver = this.speechSubject.asObservable();
  private recording = false;

  constructor(private windowRef: WindowRef) {
  }

  hasSpeechSupport() {
    try {
      return this.windowRef.nativeWindow.hasOwnProperty('webkitSpeechRecognition');
    } catch (e) {
      return false;
    }
  }

  getObserver(): Observable<string> {
    return this.speechObserver;
  }

  startRecording(): void {
    this.recording = true;
    this.record();
  }

  stopRecording() {
    this.recording = false;
    if (!this.recognition) {
      return;
    }
    this.recognition.stop();
  }

  sendResult(result: string) {
    this.speechSubject.next(result);
  }

  private record() {
    this.recognition = new webkitSpeechRecognition();
    this.recognition.continuous = true;
    this.recognition.interimResults = false;

    this.recognition.lang = 'fi-FI';
    this.recognition.start();

    this.recognition.onresult = (e) => {
      const idx = e.results.length - 1;
      this.speechSubject.next(e.results[idx][0].transcript.trim());
    };

    this.recognition.onend = () => {
      if (this.recording) {
        this.record();
      }
    };

    this.recognition.onspeechend = () => {
      this.recognition.stop();
    };

    this.recognition.onerror = (e) => {
      this.recognition.stop();
    };
  }
}

redpajama_set_name: RedPajamaGithub


text:
package com.github.pfmiles.org.apache.velocity.util;

import com.github.pfmiles.org.apache.velocity.runtime.RuntimeServices;

/**
 * Use this interface to automatically
 * have the method setRuntimeServices called at initialization.
 * Applies to EventHandler and Uberspect implementations.
 *
 * @author Will Glass-Husain
 * @version $Id: RuntimeServicesAware.java 685685 2008-08-13 21:43:27Z nbubna $
 * @since 1.5
 */
public interface  RuntimeServicesAware
{
    /**
     * Called automatically when event cartridge is initialized.
     * @param rs RuntimeServices object assigned during initialization
     */
    public void setRuntimeServices( RuntimeServices rs );

}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Hik.Communication.Scs.Communication.EndPoints.Tcp;
using Hik.Communication.ScsServices.Client;
using YandexAPI.Maps;
using System.Globalization;

namespace TaxiDesktopClient
{
    public partial class DesktopForm : Form
    {
        Client DesktopClient= new Client();
        List<int> Extra = new List<int>();
        int Phase = 0;
        string Search;
        //int Port = 10083;
        //string IP = "127.0.0.1";
        string IP = "5.164.251.145";
        int Port = 4040;
        //string IP = "95.79.210.235";
        bool TextChange = false;
        Tuple<double, double> MapCenter = new Tuple<double,double>(56.299520, 43.982913);
        Tuple<double, double> MapMoveStart;
        bool MapMove = false;
        double kx = 0.0057;
        double ky = 0.0017;
        YandexAPI.Maps.GeoCode geoCode = new GeoCode();
        int zPos = 17;
        int MapMode = -1;
        Tuple<double, double> Start;
        Tuple<double, double> Finish;
        string sStart;
        string sFinish;
        string sDriver = "0,0";
        string SampleStart="Нижний Новгород, Гагарина, 23к2";
        string SampleFinish = "Нижний Новгород, ул. Бекетова, 69";

        public DesktopForm()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            PhoneBox.Text = "+70000000000";
            if (!DesktopClient.Connect(IP, Port))
            {
                MessageBox.Show("Не удается подключиться к серверу");
                Close();
            }
            MapCenter = new Tuple<double, double>(56.299520, 43.982913);
            Start = new Tuple<double, double>(0, 0);
            Finish = new Tuple<double, double>(0, 0);
            string ImageUrl = GetUrl(MapCenter, Start, Finish, zPos, pictureBoxYandexMap.Width, pictureBoxYandexMap.Height);
            pictureBoxYandexMap.Image = geoCode.DownloadMapImage(ImageUrl);
            pictureBoxYandexMap.Refresh();
        }

        private void buttonFromAddress_Click(object sender, EventArgs e)
        {
            FromAddressBox.Visible = true;
            FromAddressLabel.Visible = true;
            FromAddressBox.Visible = true;
        }

        private void buttonFromCoord_Click(object sender, EventArgs e)
        {
            labelFromX.Visible = true;
            labelFromY.Visible = true;
            textBoxFromX.Visible = true;
            textBoxFromY.Visible = true;
            buttonMapFrom.Visible = true;
        }

        private void buttonToAddress_Click(object sender, EventArgs e)
        {
            ToAddressBox.Visible = true;
            ToAddressLabel.Visible = true;
            ToAddressBox.Visible = true;
        }

        private void buttonToCoord_Click(object sender, EventArgs e)
        {
            labelToX.Visible = true;
            labelToY.Visible = true;
            textBoxToX.Visible = true;
            textBoxToY.Visible = true;
            buttonMapTo.Visible = true;
        }

        private void OrderButton_Click(object sender, EventArgs e)
        {
            Extra.Clear();
            foreach (int s in ExtracheckedListBox.CheckedIndices)
            {
                Extra.Add(s+1);
            }
            if (!DesktopClient.CreateOrder(NameBox.Text, PhoneBox.Text, FromAddressBox.Text, textBoxFromY.Text, textBoxFromX.Text, ToAddressBox.Text, textBoxToY.Text, textBoxToX.Text, Extra))
            {
                MessageBox.Show("Введены некорректные данные");
            }
            else
            {
                OrderButton.Visible = false;
                labelPrice.Visible = true;
                labelProcessing.Visible = true;
                NameBox.Enabled = false;
                PhoneBox.Enabled = false;
                textBoxFromX.Enabled = false;
                textBoxFromY.Enabled = false;
                textBoxToX.Enabled = false;
                textBoxToY.Enabled = false;
                FromAddressBox.Enabled = false;
                ToAddressBox.Enabled = false;
                ExtracheckedListBox.Enabled = false;
                labelOperatorPhone.Visible = true;
                Phase = 1;
                buttonAbort.Visible = true;
                buttonMapFrom.Enabled = false;
                buttonMapTo.Enabled = false;
                labelOperatorPhone.Text = "Связь с оператором: " + DesktopClient.GetOperatorPhone();
                sStart = DesktopClient.GetStartPosition();
                sFinish = DesktopClient.GetFinishPosition();
                Start = new Tuple<double, double>(System.Convert.ToDouble(textBoxFromX.Text, CultureInfo.InvariantCulture), System.Convert.ToDouble(textBoxFromY.Text, CultureInfo.InvariantCulture));
                Finish = new Tuple<double, double>(System.Convert.ToDouble(textBoxToX.Text, CultureInfo.InvariantCulture), System.Convert.ToDouble(textBoxToY.Text, CultureInfo.InvariantCulture));
                string ImageUrl = GetUrl(MapCenter, Start, Finish, zPos, pictureBoxYandexMap.Width, pictureBoxYandexMap.Height);
                pictureBoxYandexMap.Image = geoCode.DownloadMapImage(ImageUrl);
                pictureBoxYandexMap.Refresh();
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (Phase == 1)
            {
                if (DesktopClient.IsTaken())
                {
                    Phase = 2;
                    DesktopClient.SetOrderDriverInfo();
                    labelProcessing.Text = "Ваш заказ принят";
                    labelDriverName.Text = "Имя водителя: " + DesktopClient.GetDriverName();
                    labelDriverPhone.Text = "Связь с водителем: " + DesktopClient.GetDriverPhone();
                    labelDriverName.Visible = true;
                    labelDriverPhone.Visible = true;
                    buttonAbort.Visible = false;
                }
            }
            if (Phase==2)
            {
                if (DesktopClient.IsCompleted())
                {
                    timer1.Stop();
                    MessageBox.Show("Заказ завершен");
                    Close();
                    return;
                }
                sDriver=DesktopClient.GetDriverPosition();
                string ImageUrl = GetUrl(MapCenter, sStart, sFinish, sDriver, zPos, pictureBoxYandexMap.Width, pictureBoxYandexMap.Height);
                pictureBoxYandexMap.Image = geoCode.DownloadMapImage(ImageUrl);
                pictureBoxYandexMap.Refresh();
            }
            if (TextChange)
            {
                if (textBoxFromX.Text != "" && textBoxFromY.Text != "" && textBoxToX.Text != "" && textBoxToY.Text != "")
                {
                    decimal Tmp = DesktopClient.GetPrice(textBoxFromX.Text, textBoxFromY.Text,textBoxToX.Text, textBoxToY.Text);
                    string PriceS = Tmp.ToString("#.##");
                    if (Tmp != (-1))
                    {
                        labelPrice.Text = "Цена: " + PriceS + " руб.";
                    }
                    else
                    {
                        labelPrice.Text = "Цена: ";
                    }
                    TextChange = false;
                }
                if (FromAddressBox.Text == "")
                {
                    try
                    {
                        Search = geoCode.SearchObject(System.Convert.ToDouble(textBoxFromY.Text, CultureInfo.InvariantCulture), System.Convert.ToDouble(textBoxFromX.Text, CultureInfo.InvariantCulture));
                        Search = geoCode.GetAddress(Search);
                        FromAddressBox.Text = Search;
                    }
                    catch
                    {
                    }
                }
                if (textBoxFromX.Text == "" || textBoxFromY.Text == "")
                {
                    try
                    {
                        Search = geoCode.SearchObject(FromAddressBox.Text);
                        Search = geoCode.GetPoint(Search);
                        int Comm = 0;
                        Comm = Search.IndexOf(",");
                        if (Comm > -1)
                        {
                            textBoxFromY.Text = Search.Substring(0, Comm);
                            textBoxFromX.Text = Search.Substring(Comm + 1);
                        }
                    }
                    catch
                    {
                    }

                }
                if (ToAddressBox.Text == "")
                {
                    try
                    {
                        Search = geoCode.SearchObject(System.Convert.ToDouble(textBoxToY.Text, CultureInfo.InvariantCulture), System.Convert.ToDouble(textBoxToX.Text, CultureInfo.InvariantCulture));
                        Search = geoCode.GetAddress(Search);
                        ToAddressBox.Text = Search;
                    }
                    catch
                    {
                    }

                }
                if (textBoxToX.Text == "" || textBoxToY.Text == "")
                {
                    try
                    {
                        Search = geoCode.SearchObject(ToAddressBox.Text);
                        Search = geoCode.GetPoint(Search);
                        int Comm = 0;
                        Comm = Search.IndexOf(",");
                        if (Comm > -1)
                        {
                            textBoxToY.Text = Search.Substring(0, Comm);
                            textBoxToX.Text = Search.Substring(Comm + 1);
                        }

                    }
                    catch
                    {
                    }
                }
            }
        }

        private void buttonAbort_Click(object sender, EventArgs e)
        {
            DesktopClient.AbortOrder();
            OrderButton.Visible = true;
            labelProcessing.Visible = false;
            NameBox.Enabled = true;
            PhoneBox.Enabled = true;
            textBoxFromX.Enabled = true;
            textBoxFromY.Enabled = true;
            textBoxToX.Enabled = true;
            textBoxToY.Enabled = true;
            FromAddressBox.Enabled = true;
            ToAddressBox.Enabled = true;
            ExtracheckedListBox.Enabled = true;
            labelOperatorPhone.Visible = false;
            Phase = 0;
            buttonAbort.Visible = false;
            buttonMapFrom.Enabled = true;
            buttonMapTo.Enabled = true;
            labelDriverName.Visible = false;
            labelDriverPhone.Visible = false;
            Start = new Tuple<double, double>(0, 0);
            Finish = new Tuple<double, double>(0, 0);
            sDriver = "0,0";
            MapMode = -1;
        }

        private void buttonMapFrom_Click(object sender, EventArgs e)
        {
            MapMode = 0;

        }

        private void buttonMapTo_Click(object sender, EventArgs e)
        {
            MapMode = 1;
        }

        private void MapMoveOn(object sender, MouseEventArgs e)
        {
            MapMove = true;
            MapMoveStart = new Tuple<double, double>(e.X, e.Y);
        }

        private void MapMoveOff(object sender, MouseEventArgs e)
        {
            MapMove = false;
        }

        private void MapMoveEvent(object sender, MouseEventArgs e)
        {
            if (MapMove)
            {
                double dx = e.X - MapMoveStart.Item1;
                double dy = e.Y - MapMoveStart.Item2;
                MapCenter = new Tuple<double, double>(MapCenter.Item1 + dy * 0.5 * ky / pictureBoxYandexMap.Height, MapCenter.Item2 - dx * 0.5 * kx / pictureBoxYandexMap.Width);
                string ImageUrl;
                if (Phase == 2)
                {
                    ImageUrl = GetUrl(MapCenter, sStart, sFinish, sDriver, zPos, pictureBoxYandexMap.Width, pictureBoxYandexMap.Height);
                }
                else
                {
                    ImageUrl = GetUrl(MapCenter, Start, Finish, zPos, pictureBoxYandexMap.Width, pictureBoxYandexMap.Height);
                }
                pictureBoxYandexMap.Image = geoCode.DownloadMapImage(ImageUrl);
                pictureBoxYandexMap.Refresh();
            }
        }

        private void MoveKey(object sender, KeyEventArgs e)
        {
        }

        private void FocusForm(object sender, EventArgs e)
        {

        }

        private string GetUrl(Tuple<double, double> Center, Tuple<double, double> Start, Tuple<double, double> Finish, int zPos, int Width, int Height)
        {

            string pCenter = Center.Item2.ToString("G", CultureInfo.InvariantCulture) + "," + Center.Item1.ToString("G", CultureInfo.InvariantCulture);
            string pStart =Start.Item2.ToString("G", CultureInfo.InvariantCulture) + "," +Start.Item1.ToString("G", CultureInfo.InvariantCulture);
            string pFinish =Finish.Item2.ToString("G", CultureInfo.InvariantCulture) + "," + Finish.Item1.ToString("G", CultureInfo.InvariantCulture);
            return String.Format("http://static-maps.yandex.ru/1.x/?ll={0}&size={3},{4}&z={5}&l=map&pt={1},pm2al~{2},pm2bl&lang=ru-RU", pCenter,pStart,pFinish, Width, Height, zPos);
        }
        private string GetUrl(Tuple<double, double> Center, string Start, string Finish, string Driver, int zPos, int Width, int Height)
        {

            string pCenter = Center.Item2.ToString("G", CultureInfo.InvariantCulture) + "," + Center.Item1.ToString("G", CultureInfo.InvariantCulture);
            return String.Format("http://static-maps.yandex.ru/1.x/?ll={0}&size={4},{5}&z={6}&l=map&pt={1},pm2al~{2},pm2bl~{3},flag&lang=ru-RU", pCenter, Start, Finish, Driver, Width, Height, zPos);
        }

        private void buttonPlus_Click(object sender, EventArgs e)
        {
            if (zPos < 19)
            {
                zPos += 1;
                kx /= 2;
                ky /= 2;
                string ImageUrl = GetUrl(MapCenter, Start, Finish, zPos, pictureBoxYandexMap.Width, pictureBoxYandexMap.Height);
                pictureBoxYandexMap.Image = geoCode.DownloadMapImage(ImageUrl);
                pictureBoxYandexMap.Refresh();
            }
        }

        private void buttonMinus_Click(object sender, EventArgs e)
        {
            if (zPos > 7)
            {
                zPos -= 1;
                kx *= 2;
                ky *= 2;
                string ImageUrl = GetUrl(MapCenter, Start, Finish, zPos, pictureBoxYandexMap.Width, pictureBoxYandexMap.Height);
                pictureBoxYandexMap.Image = geoCode.DownloadMapImage(ImageUrl);
                pictureBoxYandexMap.Refresh();
            }
        }

        private void pictureBoxYandexMap_Click(object sender, EventArgs e)
        {
            MouseEventArgs M = (MouseEventArgs)e;
            double dx = M.X - pictureBoxYandexMap.Width/2;
            double dy = M.Y - pictureBoxYandexMap.Height / 2;
            if (MapMode == 0)
            {
                Start = new Tuple<double, double>(MapCenter.Item1 - dy * ky / pictureBoxYandexMap.Height, MapCenter.Item2 + dx * kx / pictureBoxYandexMap.Width);
                MapMode = -1;
                string Search = geoCode.SearchObject(Start.Item2, Start.Item1);
                string StartAddress = geoCode.GetAddress(Search);
                textBoxFromX.Text = Start.Item1.ToString("G", CultureInfo.InvariantCulture);
                textBoxFromY.Text = Start.Item2.ToString("G", CultureInfo.InvariantCulture);
                FromAddressBox.Text = StartAddress;
                string ImageUrl = GetUrl(MapCenter, Start, Finish, zPos, pictureBoxYandexMap.Width, pictureBoxYandexMap.Height);
                pictureBoxYandexMap.Image = geoCode.DownloadMapImage(ImageUrl);
                pictureBoxYandexMap.Refresh();
            }
            if (MapMode == 1)
            {
                Finish = new Tuple<double, double>(MapCenter.Item1 - dy * ky / pictureBoxYandexMap.Height, MapCenter.Item2 + dx * kx / pictureBoxYandexMap.Width);
                MapMode = -1;
                string Search = geoCode.SearchObject(Finish.Item2, Finish.Item1);
                string FinishAddress = geoCode.GetAddress(Search);
                textBoxToX.Text = Finish.Item1.ToString("G", CultureInfo.InvariantCulture);
                textBoxToY.Text = Finish.Item2.ToString("G", CultureInfo.InvariantCulture);
                ToAddressBox.Text = FinishAddress;
                string ImageUrl = GetUrl(MapCenter, Start, Finish, zPos, pictureBoxYandexMap.Width, pictureBoxYandexMap.Height);
                pictureBoxYandexMap.Image = geoCode.DownloadMapImage(ImageUrl);
                pictureBoxYandexMap.Refresh();
            }
        }

        private void FromCoordChange(object sender, EventArgs e)
        {
            TextChange = true;
            if (textBoxFromX.Focused || textBoxFromY.Focused)
            {
                FromAddressBox.Text = "";
            }
        }

        private void ToCoordChange(object sender, EventArgs e)
        {
            TextChange = true;
            if (textBoxToX.Focused || textBoxToY.Focused)
            {
                ToAddressBox.Text = "";
            }
        }

        private void FromAddressChange(object sender, EventArgs e)
        {
            TextChange = true;
            if (FromAddressBox.Focused)
            {
                textBoxFromX.Text = "";
                textBoxFromY.Text = "";
            }
        }

        private void ToAddressChange(object sender, EventArgs e)
        {
            TextChange = true;
            if (ToAddressBox.Focused)
            {
                textBoxToX.Text = "";
                textBoxToY.Text = "";
            }
        }
    }
}


text:
package fi.uta.fsd.metka.storage.repository;

import com.fasterxml.jackson.databind.JsonNode;
import fi.uta.fsd.metka.storage.repository.enums.ReturnResult;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Transactional(readOnly = true)
public interface MiscJSONRepository {
    /**
     * Validates given JSONObject to contain misc json data and inserts or replaces it to database.
     *
     * @param misc Misc JSON data to be inserted.
     */
    @Transactional(readOnly = false) public ReturnResult insert(String key, JsonNode misc);

    /*@Transactional(readOnly = false) public ReturnResult insert(String text);*/

    /**
     * Find MiscJSON data with given key.
     * @param key Requested Misc JSON key
     * @return
     */
    public Pair<ReturnResult, JsonNode> findByKey(String key);

    public List<String> getJsonKeys();
    public Pair<ReturnResult, String> findStringByKey(String key);
}


text:
    slug) }}" title="{{ $product_category->title }}">
        {!! $product_category->title !!}
        {!! $product_category->present()->thumb(null, 200) !!}


text:
title: "Hidden tag section showcase"
thumbnailImagePosition: left
thumbnailImage: //d1u9biwaxjngwg.cloudfront.net/cover-image-showcase/city-750.jpg
date: 2014-08-16
categories:
- tranquilpeak
- features
tags:
- tags
showTags: false
---

This post is used to show how a site looks if the tag section is hidden.
<!--more-->

In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus.


text:
require 'spec_helper'
require 'fog/dnsimple'

describe 'dnsimple_test::create_record_existing_record_same_type_and_content' do
  include_context 'dnsimple'

  context 'with an existing record with the same name, ttl, type and conent' do
    it 'does not perform any operation' do
      create_record_to_update

      dnsimple_resource = chef_run.find_resource('dnsimple_record', 'existing')
      expect(dnsimple_resource.updated_by_last_action?).to be_falsy
      expect(Fog::DNS::DNSimple::Record).not_to receive(:destroy)
      record = dnsimple_zone.records.detect { |r| r.name == 'existing' }
      expect(record.value).to eq '2.2.2.2'
    end
  end
end


text:
require 'spec_helper'
require 'cucumber/runtime/hooks_examples'

require 'cucumber/runtime/before_hooks'

module Cucumber
  class Runtime
    describe BeforeHooks do
      let(:subject) { BeforeHooks.new(id_generator, hooks, scenario, event_bus) }

      describe '#apply_to' do
        include_examples 'events are fired when applying hooks'
      end
    end
  end
end


text:
module Locomotive
  class Purposes < Locomotive::Application

    before :init_menu
    before :find_associated_server

  #  # GET /purposes
  #  # GET /purposes.xml
    def index
      @purposes = @system.purposes
      display @purposes
    end

  #  TODO: remove this action when no longer debugging
  #  # GET /purposes/1
  #  # GET /purposes/1.xml
    def show(id)
      @purpose = Locomotive::Purpose.get(id)
      raise NotFound unless @purpose
      display @purpose
    end

    # GET /purposes/new
    def new
      only_provides :html
      @purpose = Locomotive::Purpose.new
      @purpose.system_id = @system.id
      display @purpose
    end

  #  # GET /purposes/1/edit
  #  def edit(id)
  #    only_provides :html
  #    @purpose = Locomotive::Purpose.get(id)
  #    raise NotFound unless @purpose
  #  end

    # POST /purposes
    # POST /purposes.xml
    def create(purpose)
      @purpose = Locomotive::Purpose.new(purpose)

      if @purpose.save
        redirect resource(@system), :message => {:notice => "Role was successfully created"}
      else
        render :new
      end
    end

    # PUT /purposes/1
    # PUT /purposes/1.xml
    def update(id, purpose)
      @purpose = Locomotive::Purpose.get(id)
      raise NotFound unless @purpose
      if @purpose.update_attributes(purpose)
        redirect resource(@system), :message => {:notice => 'Role was successfully updated'}
      else
        render :edit
      end
    end

    def delete(id)
      @purpose = Locomotive::Purpose.get(id)
      raise NotFound unless @purpose
      display @purpose
    end

    # DELETE /purposes/1
    # DELETE /purposes/1.xml
    def destroy(id)
      @purpose = Locomotive::Purpose.get(id)
      raise NotFound unless @purpose
      if @purpose.destroy
        redirect resource(@system)
      else
        raise InternalServerError
      end
    end

    # attempt to find the corresponding server if we're accessed
    # through a route containing a server, like
    # /servers/1/purposes/x
    def find_associated_server
      @system = nil
      system_id = params[:system_id]

      unless system_id.nil?
        @system = Locomotive::System.get(system_id)
      end
    end

    # attempt to find the corresponding server if we're accessed
    # through a route containing a server, like
    # /servers/1/roles
    def find_associated_server
      @system = nil
      system_id = params[:system_id]

      unless system_id.nil?
        @system = Locomotive::System.get(system_id)
      end
    end

    def init_menu
      @menu = ["Administration", "Systems"]
    end

  end
end


text:
require 'spec_helper'

describe DroneCiService, models: true, caching: true do
  include ReactiveCachingHelpers

  describe 'associations' do
    it { is_expected.to belong_to(:project) }
    it { is_expected.to have_one(:service_hook) }
  end

  describe 'validations' do
    context 'active' do
      before { subject.active = true }

      it { is_expected.to validate_presence_of(:token) }
      it { is_expected.to validate_presence_of(:drone_url) }
      it_behaves_like 'issue tracker service URL attribute', :drone_url
    end

    context 'inactive' do
      before { subject.active = false }

      it { is_expected.not_to validate_presence_of(:token) }
      it { is_expected.not_to validate_presence_of(:drone_url) }
    end
  end

  shared_context :drone_ci_service do
    let(:drone)      { DroneCiService.new }
    let(:project)    { create(:project, :repository, name: 'project') }
    let(:path)       { project.full_path }
    let(:drone_url)  { 'http://drone.example.com' }
    let(:sha)        { '2ab7834c' }
    let(:branch)     { 'dev' }
    let(:token)      { 'secret' }
    let(:iid)        { rand(1..9999) }

    # URL's
    let(:build_page) { "#{drone_url}/gitlab/#{path}/redirect/commits/#{sha}?branch=#{branch}" }
    let(:commit_status_path) { "#{drone_url}/gitlab/#{path}/commits/#{sha}?branch=#{branch}&access_token=#{token}" }

    before(:each) do
      allow(drone).to receive_messages(
        project_id: project.id,
        project: project,
        active: true,
        drone_url: drone_url,
        token: token
      )
    end

    def stub_request(status: 200, body: nil)
      body ||= %q({"status":"success"})

      WebMock.stub_request(:get, commit_status_path).to_return(
        status: status,
        headers: { 'Content-Type' => 'application/json' },
        body: body
      )
    end
  end

  describe "service page/path methods" do
    include_context :drone_ci_service

    it { expect(drone.build_page(sha, branch)).to eq(build_page) }
    it { expect(drone.commit_status_path(sha, branch)).to eq(commit_status_path) }
  end

  describe '#commit_status' do
    include_context :drone_ci_service

    it 'returns the contents of the reactive cache' do
      stub_reactive_cache(drone, { commit_status: 'foo' }, 'sha', 'ref')

      expect(drone.commit_status('sha', 'ref')).to eq('foo')
    end
  end

  describe '#calculate_reactive_cache' do
    include_context :drone_ci_service

    context '#commit_status' do
      subject { drone.calculate_reactive_cache(sha, branch)[:commit_status] }

      it 'sets commit status to :error when status is 500' do
        stub_request(status: 500)

        is_expected.to eq(:error)
      end

      it 'sets commit status to :error when status is 404' do
        stub_request(status: 404)

        is_expected.to eq(:error)
      end

      {
        "killed"  => :canceled,
        "failure" => :failed,
        "error"   => :failed,
        "success" => "success"
      }.each do |drone_status, our_status|
        it "sets commit status to #{our_status.inspect} when returned status is #{drone_status.inspect}" do
          stub_request(body: %Q({"status":"#{drone_status}"}))

          is_expected.to eq(our_status)
        end
      end
    end
  end

  describe "execute" do
    include_context :drone_ci_service

    let(:user)    { create(:user, username: 'username') }
    let(:push_sample_data) do
      Gitlab::DataBuilder::Push.build_sample(project, user)
    end

    it do
      service_hook = double
      expect(service_hook).to receive(:execute)
      expect(drone).to receive(:service_hook).and_return(service_hook)

      drone.execute(push_sample_data)
    end
  end
end


text:
Tous les objets du modèle devront être modélisés avec des familles qui soient affectées à une catégorie Revit cohérente avec la fonction de l'élément même:

* Luminaires
* Terminaux horizontaux et verticaux
* Mobilier
* Equipements spécialisés
* Murs, sols, plafonds

Aucun objet ne devra être modélisé en "Modèle Générique".

### Utilisation des références

De manière générale, dans les modèles Décorateur les éléments de structure (dalles, poteaux, voiles ...), d'architecture (cloisons, plafonds, ...) éventuellement importés comme référence de dessin, devront être positionnées sur un sous-projet à part de manière à pouvoir les isoler facilement.
Ce principe s'appliquera aussi aux terminaux horizontaux et verticaux (luminaires, trappes ...) qui seront en interface avec les lots techniques.

### Modélisation avec les masses volumétriques

Les masses volumétriques qui seront éventuellement utilisé comme support à la modélisation (par exemple pour des murs avec des formes libres), devront être supprimés avant l'export et la diffusion des modèles, afin de ne pas gêner la modélisation des autres intervenants.

 ---

Image credits [here](/CREDITS.md)


text:
<?
//Copyright (c) 2012, Fedor Borshev <fedor9@gmail.com>
//
//Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

require_once('../_includes/core.php');
require_once('_includes/auth.php');

require_once('_includes/started_functions.php');
require_once('_includes/request_functions.php');

if(defined(RESULTS_KPS_PER_ROW) and RESULTS_KPS_PER_ROW>0)
	$kps_per_row=RESULTS_KPS_PER_ROW;
else
	$kps_per_row=8;

if(empty($_GET['comp_id']) and empty($_POST['comp_id']))
	die('Не указан id соревнования!');

if($_POST['comp_id'])
	$comp_id=(int)$_POST['comp_id'];
else
	$comp_id=(int)$_GET['comp_id'];

$res=query_eval("SELECT cat_id FROM $compcatvar_dbt WHERE comp_id=$comp_id AND type='legend';");
if(!mysql_num_rows($res))
	die('для заданного соревнования не задано ни одной категории учатсников с Легендой!');
$start_number=(int)$_GET['start_number'];
//получаем список бортовых номеров участников, которые стартовали по легенде
$res=query_eval("SELECT start_number FROM $complegres_dbt WHERE comp_id=$comp_id;");
$valid_numbers=array();
$valid_numbers_str="";
while($row=mysql_fetch_row($res)){
	$valid_numbers[]=(int)$row[0];
	$valid_numbers_str.="'{$row[0]}',";
}
$valid_numbers_str=trim($valid_numbers_str,',');
if($start_number and !in_array($start_number,$valid_numbers))
	die('указан несуществующий или нестартовавший бортовой номер!');

if($start_number){ //cразу получаем категорию участника
	$cat_id=get_cat($comp_id,$start_number);
	//если указан номер, сразу узнаем максимальное кол-во КП в категории
	$max_kp=_cat_var($comp_id,$cat_id,'max_kp');
	if(!$max_kp)
		die("ошибка получения количетства КП для категории ($cat_id). Возможна ошибка в свойствах соревнования");
	if($detailed_legend_cat and in_array($cat_id,$detailed_legend_cat)){ //если работаем с легендой "подробно"
		//получаем список возможных в категории точек
		$res=query_eval("SELECT name,comment FROM $complegpoints_dbt WHERE comp_id=$comp_id AND cat_id=$cat_id AND active='yes';");
		$valid_names=array();
		$valid_names_str="";
		while($row=mysql_fetch_row($res)){
			$valid_names[]=(int)$row[0];
			$valid_names_str.="'{$row[0]}',";
		}
		$valid_ids=$valid_names;
		$valid_names_str=trim($valid_names_str,',');

		$res=query_eval("SELECT point_name FROM $complegdetails_dbt WHERE comp_id=$comp_id AND start_number=$start_number;");
		$taken_names=$taken_ids=array();
		$taken_names_str="";
		while($row=mysql_fetch_row($res)){
			$cur_id=$taken_names[]=(int)$row[0];
			$taken_names_str.="'$cur_id',";
		}
		$taken_names_str=trim($taken_names_str,',');
		$taken_ids=$taken_names;
		$item['legend_kps']=sizeof($taken_names);
	}

}

$flag=(int)$_GET['flag'];
if($flag and !$start_number)
	die('указан номер действия, но не указан стартовый номер!');
switch($flag){
case 1: //указание времени финиша
	list($h,$m,$s)=parse_user_time($_GET['finish_time']);
	$finish_time=$h*3600+$m*60+$s;
	update_finish_time($comp_id,$finish_time,$start_number);
	header("Location: ".append_rnd("legend-results.php?comp_id=$comp_id&start_number=$start_number"));
	die();
	break;
case 2: //указание кол-ва КП
	$kp=(int)$_GET['kp'];
	if(!$kp or $kp<0 or $kp>$max_kp)
		die('указано некорректное количество КП!');
	query_eval("UPDATE $complegres_dbt SET `kps`=$kp WHERE `comp_id`=$comp_id AND `start_number`=$start_number LIMIT 1;");
	header("Location: ".append_rnd("legend-results.php?comp_id=$comp_id&start_number=$start_number"));
	die();
	break;
case 3: //при подробной работе с легендой - сабмит формы с галочками
	$item_id=(int)$_GET['item_id'];
	if(!$item_id)
		die('не указано имя точки!');
	if(!in_array($item_id,$valid_names))
		die('указан id несуществующей точки!');
	$taken=false;
	if($_GET['taken']=='1')
		$taken=true;
	if($taken and in_array($item_id,$taken_ids))
		die('Точка уже взята!');
	if($taken)
		add_item($complegdetails_dbt,array(
			'comp_id'=>$comp_id,
			'start_number'=>$start_number,
			'point_name'=>$item_id,
			'author'=>$admin_user,
		));
	else
		query_eval("DELETE FROM $complegdetails_dbt WHERE comp_id=$comp_id AND start_number=$start_number AND point_name=$item_id LIMIT 1;");
	recount_legend_results_from_detailed($comp_id,$start_number);
	header("Location: ".append_rnd("legend-results.php?comp_id=$comp_id&start_number=$start_number"));
	die();
	break;

case 4: //изменение времени старта
	list($h,$m,$s)=parse_user_time($_GET['start_time']);
	$time=$h*3600+$m*60+$s;
	update_start_time($comp_id,$time,$start_number);
	header("Location: ".append_rnd("legend-results.php?comp_id=$comp_id&start_number=$start_number"));
	die();
	break;
case 5: //сабмит взятой точки текстом
	$num=(int)$_GET['num'];
	if(!in_array($num,$valid_names))
		die('указана несущствующаяя точка!');
	if(in_array($num,$taken_names))
		die('заданная точка уже взята!');
	//нужно определить категорию участника, для правильного поиска id точки по ее номеру. Потому что если встретятся точки с одинаковыми названиями, но в разных категориях, то может зачислится первая попавшаяся.
	$cat_id=get_cat($comp_id,$start_number);

	$res=query_eval("SELECT name FROM $complegpoints_dbt WHERE `comp_id`=$comp_id AND `cat_id`=$cat_id AND `name`=$num;");
	if(!mysql_num_rows($res))
		die('указана несущствующаяя точка (SQL)');
	$row=mysql_fetch_row($res);
	$id=(int)$row[0];
	add_item($complegdetails_dbt,array(
		'comp_id'=>$comp_id,
		'start_number'=>$start_number,
		'point_name'=>$id,
		'author'=>$admin_user,
	));
	recount_legend_results_from_detailed($comp_id,$start_number);
	header("Location: ".append_rnd("legend-results.php?comp_id=$comp_id&start_number=$start_number"));
	die();
	break;

}

if($start_number){
	$res=query_eval("SELECT * FROM $compres_dbt WHERE `start_number`=$start_number AND `comp_id`=$comp_id;");
	if(!mysql_num_rows($res))
		die('заданный номер отсутсвует в таблице результатов. Возможно это ошибка при создании стартовой ведомости.');
	$row=mysql_fetch_assoc($res);
	$cat_id=$item['cat_id']=(int)$row['cat_id'];
	$item['cat_name']=$cat_name[$item['cat_id']];
	//list($item['start_time_h'],$item['start_time_m'])=explode(':',format_hm_time(get_start_time($comp_id,$start_number)*60));
	$item['start_time']=format_hms_time(get_start_time($comp_id,$start_number),$_null_sec_bool);
	$request_id=(int)$row['request_id'];
	$item=get_brief_request_data($comp_id,$request_id,$item);
	if(defined('CA_TRACK_PORTAL') and CA_TRACK_PORTAL)
		$item['have_portal']=has_portal($comp_id,$start_number);
	$tpl_have_finish=false;
	$finish_time=get_finish_time($comp_id,$start_number);
	if($finish_time){
		$item['finish_time']=format_user_hms_time($finish_time,false);
		$tpl_have_finish=true;
		$res=query_eval("SELECT kps FROM $complegres_dbt WHERE `comp_id`=$comp_id AND `start_number`=$start_number;");
		if(mysql_num_rows($res)){
			$row=mysql_fetch_row($res);
			if((int)$row[0])
				$item['legend_kps_results']=(int)$row[0];
		}
		$kp_detailed=false;
		if($detailed_legend_cat and in_array($cat_id,$detailed_legend_cat)){
			$kp_detailed=true;
			$res=query_eval("SELECT name,comment FROM $complegpoints_dbt WHERE comp_id=$comp_id AND cat_id=$cat_id AND active='yes' ORDER BY name ASC;");
			$x=0;
			$y=0;
			while($row=mysql_fetch_assoc($res)){
				$id=(int)$row['name'];
				$kp_output[$y][$id]['cost']=(int)$row['cost'];
				$kp_output[$y][$id]['name']=stripslashes($row['name']);
				$kp_output[$y][$id]['comment']=stripslashes($row['comment']);

				if(strlen($kp_output[$y][$id]['name'])==1) //добавляем нолик ко всем точкам, дабы ровно было
					$kp_output[$y][$id]['name']="0".$kp_output[$y][$id]['name'];
				if((strlen($kp_output[$y][$id]['name'])==2) and $max_num>=100) //ежели у нас точек больше ста, тогда добавляем еще один нолик
					$kp_output[$y][$id]['name']="0".$kp_output[$y][$id]['name'];

				if(in_array($id,$taken_ids))
					$kp_output[$y][$id]['taken']=true;
				else
					$kp_output[$y][$id]['taken']=false;
				if($x==$kps_per_row-1){
					$x=0;
					$y++;
					continue;
				}
				$x++;

			}
			$item['legend_kps']=sizeof($taken_ids);
		}else{
			$item['legend_kps']=$item['legend_kps_results'];

		}
	}
}
$tpl_max_kp=$max_kp;
if(!$tpl_max_kp)
	$tpl_max_kp=0;

if(!$start_number)
	$start_number=''; //чтобы ноль юзера не пугал
$title="Ввод результатов линейной гонки";

$change_start_form_url='legend-results.php';

require('admin_header.php');
require('_templates/legend-results.phtml');

function recount_legend_results_from_detailed($comp_id,$start_number){
	global $complegres_dbt,$complegdetails_dbt;
	if(!$comp_id or !$start_number)
		return false;
	$comp_id=(int)$comp_id;
	$start_number=(int)$start_number;

	$res=query_eval("SELECT COUNT(point_name) FROM $complegdetails_dbt WHERE comp_id=$comp_id AND start_number=$start_number;");
	if(!mysql_num_rows($res))
		die("Пересчет количества КП в результат: ошибка запроса");
	$row=mysql_fetch_row($res);

	$count=(int)$row[0];

	query_eval("UPDATE $complegres_dbt SET `kps`=$count WHERE `comp_id`=$comp_id AND `start_number`=$start_number LIMIT 1;");
	return true;

}

function tpl_check_max_kp($comp_id){
	global $complegres_dbt;
	global $cat_name;
	if(!$comp_id)
		return;
	//получаем список категорий, которые проверяем, берем все категории которые есть в complegres, следовательно есть и в стартовой ведомости
	$res=query_eval("SELECT DISTINCT(cat_id) FROM $complegres_dbt WHERE comp_id=$comp_id");
	$checking_cats=array();
	while($row=mysql_fetch_row($res))
		$checking_cats[]=(int)$row[0];

	$results='';
	foreach($checking_cats as $cat_id){
		if(!$cat_name[$cat_id])
			continue;
		if($cat_id>_CATEGORIES)
			continue;
		$max_kp=_cat_var($comp_id,$cat_id,'max_kp');
		if(!$max_kp or $max_kp<0)
			$results.=$cat_name[$cat_id].',';
	}
	$results=trim($results,',');
	if($results)
		return "
Внимание! Возможно ошибка в свойствах соревнования - не задано максимальное количество КП для следующих категорий: $results
";
}


text:
@interface ChangeAndDiscardCommand : CommandBase
{
}

@end


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>Statistics of AUX in UD_Sanskrit</title>
    <link rel="root" href=""/>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="../../css/jquery-ui-redmond.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/style.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/style-vis.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/hint.css"/>

          home

          edit page
          issue tracker

          <gcse:search></gcse:search>

        This page pertains to UD version 2.

            It appears that you have Javascript disabled.
            Please consider enabling Javascript for this page to see the visualizations.

Treebank Statistics: UD_Sanskrit: POS Tags: AUX

There are 1 AUX lemmas (0%), 4 AUX types (0%) and 13 AUX tokens (1%).
Out of 16 observed tags, the rank of AUX is: 16 in number of lemmas, 12 in number of types and 12 in number of tokens.

The 10 most frequent AUX lemmas: अस्

The 10 most frequent AUX types:  अस्ति, अस्मि, सत्त्वम्, स्यात्

The 10 most frequent ambiguous lemmas: अस् (<tt>AUX</tt> 13, <tt>VERB</tt> 6)

The 10 most frequent ambiguous types:  अस्ति (<tt>AUX</tt> 10, <tt>VERB</tt> 1), स्यात् (<tt>VERB</tt> 2, <tt>AUX</tt> 1)

अस्ति

<tt>AUX</tt> 10: अस्ति दाक्षिणात्ये जनपदे महिलारोप्यं नाम नगरम् ।

<tt>VERB</tt> 1: अस्ति दक्षिणात्ये जनपदे महिलारोप्यं नाम नगरम् ।

स्यात्

<tt>VERB</tt> 2: सर्वेषाम् अपि तेषाम् वाणिज्येना अतिरस्कृतः अर्थ लाभः स्यात् ।

<tt>AUX</tt> 1: अप्रधानः प्रधानम् स्यात् सेवते यदि पार्थिवम् ।

Morphology

The form / lemma ratio of AUX is 4.000000 (the average of all parts of speech is 1.302030).

The 1st highest number of forms (4) was observed with the lemma "अस्": अस्ति, अस्मि, सत्त्वम्, स्यात्.

AUX occurs with 8 features: <tt>Number</tt> (13; 100% instances), <tt>VerbForm</tt> (13; 100% instances), <tt>Voice</tt> (13; 100% instances), <tt>Mood</tt> (12; 92% instances), <tt>Person</tt> (12; 92% instances), <tt>Tense</tt> (12; 92% instances), <tt>Case</tt> (1; 8% instances), <tt>Gender</tt> (1; 8% instances)

AUX occurs with 11 feature-value pairs: Case=Nom, Gender=Neut, Mood=Ind, Mood=Opt, Number=Sing, Person=1, Person=3, Tense=Pres, VerbForm=Fin, VerbForm=Part, Voice=Act

AUX occurs with 4 feature combinations.
The most frequent feature combination is Mood=Ind|Number=Sing|Person=3|Tense=Pres|VerbForm=Fin|Voice=Act (10 tokens).
Examples: अस्ति

Relations

AUX nodes are attached to their parents using 1 different relations: <tt>cop</tt> (13; 100% instances)

Parents of AUX nodes belong to 4 different parts of speech: <tt>NOUN</tt> (7; 54% instances), <tt>ADV</tt> (3; 23% instances), <tt>VERB</tt> (2; 15% instances), <tt>ADJ</tt> (1; 8% instances)

13 (100%) AUX nodes are leaves.

The highest child degree of a AUX node is 0.

© 2014–2021
            Universal Dependencies contributors.
            Site powered by Annodoc and brat
.


text:
#include "CCMainWindow.h"
#include "CCViewManager.h"

CCMainWindow *CCMainWindow::instance = NULL;

CCMainWindow::CCMainWindow(QWidget *parent)
    : QMainWindow( parent )
{
    instance = this;
    viewManager = new CCViewManager();
    setWindowTitle( "2c" );
}

CCMainWindow::~CCMainWindow()
{
    viewManager->shutdown();
    children.deleteObjectsAndList();
}

void CCMainWindow::resizeEvent(QResizeEvent *event)
{
    if( children.length == 0 )
    {
        viewManager->startup();
        //children.add( gView );
        return;
    }

    const int windowWidth = width();
    const int windowHeight = height();
    for( int i=0; i<children.length; ++i )
    {
        children.list[i]->resizeView( 0, 0, windowWidth, windowHeight );
    }
}

void CCMainWindow::addChild(MainWindowChild *child)
{
    children.add( child );
    const int windowWidth = width();
    const int windowHeight = height();
    child->resizeView( 0, 0, windowWidth, windowHeight );
}

void CCMainWindow::removeChild(MainWindowChild *child)
{
    children.remove( child );
}


text:
package org.apache.syncope.fit.ui;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.fail;

import java.io.IOException;
import javax.ws.rs.core.Response;
import org.apache.syncope.common.lib.SyncopeClientException;
import org.apache.syncope.common.lib.policy.AttrReleasePolicyTO;
import org.apache.syncope.common.lib.policy.AuthPolicyTO;
import org.apache.syncope.common.lib.policy.DefaultAttrReleasePolicyConf;
import org.apache.syncope.common.lib.policy.DefaultAuthPolicyConf;
import org.apache.syncope.common.lib.types.ClientExceptionType;
import org.apache.syncope.common.lib.types.PolicyType;
import org.apache.syncope.common.rest.api.RESTHeaders;
import org.apache.syncope.fit.AbstractITCase;
import org.junit.jupiter.api.Test;

public abstract class AbstractUIITCase extends AbstractITCase {

    protected static AuthPolicyTO getAuthPolicy() {
        String syncopeAuthModule = "DefaultSyncopeAuthModule";
        String ldapAuthModule = "DefaultLDAPAuthModule";
        String description = "UI auth policy";

        return POLICY_SERVICE.list(PolicyType.AUTH).stream().
                map(AuthPolicyTO.class::cast).
                filter(policy -> description.equals(policy.getName())
                && policy.getConf() instanceof DefaultAuthPolicyConf
                && ((DefaultAuthPolicyConf) policy.getConf()).getAuthModules().contains(syncopeAuthModule)
                && ((DefaultAuthPolicyConf) policy.getConf()).getAuthModules().contains(ldapAuthModule)).
                findFirst().
                orElseGet(() -> {
                    DefaultAuthPolicyConf policyConf = new DefaultAuthPolicyConf();
                    policyConf.getAuthModules().add(syncopeAuthModule);
                    policyConf.getAuthModules().add(ldapAuthModule);

                    AuthPolicyTO policy = new AuthPolicyTO();
                    policy.setName(description);
                    policy.setConf(policyConf);

                    Response response = POLICY_SERVICE.create(PolicyType.AUTH, policy);
                    if (response.getStatusInfo().getStatusCode() != Response.Status.CREATED.getStatusCode()) {
                        fail("Could not create Test Auth Policy");
                    }

                    return POLICY_SERVICE.read(
                            PolicyType.AUTH,
                            response.getHeaderString(RESTHeaders.RESOURCE_KEY));
                });
    }

    protected static AttrReleasePolicyTO getAttrReleasePolicy() {
        String stubAttrRepo = "DefaultStubAttrRepo";
        String description = "UI attr release policy";

        return POLICY_SERVICE.list(PolicyType.ATTR_RELEASE).stream().
                map(AttrReleasePolicyTO.class::cast).
                filter(policy -> description.equals(policy.getName())
                && policy.getConf() instanceof DefaultAttrReleasePolicyConf
                && ((DefaultAttrReleasePolicyConf) policy.getConf()).getPrincipalAttrRepoConf().
                        getAttrRepos().contains(stubAttrRepo)).
                findFirst().
                orElseGet(() -> {
                    DefaultAttrReleasePolicyConf policyConf = new DefaultAttrReleasePolicyConf();
                    policyConf.getPrincipalAttrRepoConf().getAttrRepos().add(stubAttrRepo);

                    AttrReleasePolicyTO policy = new AttrReleasePolicyTO();
                    policy.setName(description);
                    policy.setConf(policyConf);

                    Response response = POLICY_SERVICE.create(PolicyType.ATTR_RELEASE, policy);
                    if (response.getStatusInfo().getStatusCode() != Response.Status.CREATED.getStatusCode()) {
                        fail("Could not create Test Attr Release Policy");
                    }

                    return POLICY_SERVICE.read(
                            PolicyType.ATTR_RELEASE,
                            response.getHeaderString(RESTHeaders.RESOURCE_KEY));
                });
    }

    protected abstract void sso(String baseURL, String username, String password) throws IOException;

    @Test
    public void sso2Console() throws IOException {
        sso(CONSOLE_ADDRESS, "bellini", "password");
    }

    @Test
    public void sso2Enduser() throws IOException {
        sso(ENDUSER_ADDRESS, "bellini", "password");
    }

    @Test
    public void createUnmatching() throws IOException {
        try {
            USER_SERVICE.delete("pullFromLDAP");
        } catch (SyncopeClientException e) {
            assertEquals(ClientExceptionType.NotFound, e.getType());
        }

        sso(CONSOLE_ADDRESS, "pullFromLDAP", "Password123");

        assertNotNull(USER_SERVICE.read("pullFromLDAP"));
    }

    protected abstract void doSelfReg(Runnable runnable);

    @Test
    public void selfRegUnmatching() throws IOException {
        try {
            USER_SERVICE.delete("pullFromLDAP");
        } catch (SyncopeClientException e) {
            assertEquals(ClientExceptionType.NotFound, e.getType());
        }

        doSelfReg(() -> {
            try {
                sso(ENDUSER_ADDRESS, "pullFromLDAP", "Password123");
            } catch (IOException e) {
                fail(e);
            }
        });

        try {
            USER_SERVICE.read("pullFromLDAP");
            fail();
        } catch (SyncopeClientException e) {
            assertEquals(ClientExceptionType.NotFound, e.getType());
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="divide_color">#EAEFF4</color>
</resources>


text:
This is the beggining of Gutter2

Gutter2 wil be a web based mobile application for managing the cleanouts of Clifton Park Gutter Cleaners


text:
#if defined (WIN32)

#ifdef max
#undef max
#endif

#ifdef min
#undef min
#endif

#ifdef far
#undef far
#endif

#ifdef near
#undef near
#endif

#ifdef ERROR
#undef ERROR
#endif

#ifdef OPAQUE
#undef OPAQUE
#endif

#ifdef TRANSPARENT
#undef TRANSPARENT
#endif

#ifdef PURE
#undef PURE
#endif

#endif


text:
drop table if exists noticias cascade;

create table noticias (
    id_noticia    bigserial     constraint pk_noticias primary key,
    id_usuario    bigint        constraint fk_noticias_usuarios
                                references public.user (id)
                                on delete no action on update cascade,
    titulo        varchar(55)   not null,
    cuerpo        varchar(500)  not null,
    url           varchar(200)  not null,
    id_categoria  bigint        constraint fk_noticias_categorias_categoria
                                references categorias (id_categoria)
                                on delete no action on update cascade,
    created_at    timestamptz   default current_timestamp
);

create index idx_noticias_titulo on noticias (titulo);
create index idx_noticias_create_at on noticias (create_at);

drop table if exists categorias cascade;

create table categorias (
    id_categoria  bigserial     constraint pk_categorias primary key,
    nombre        varchar(20)   not null
);

create index idx_categorias_nombre on categorias (nombre);

drop table if exists comentarios cascade;

create table comentarios (
    id_comentario  bigserial     constraint pk_comentarios primary key,
    id_usuario     bigint        constraint fk_noticias_usuarios
                                 references public.user (id)
                                 on delete no action on update cascade,
    votos          numeric(6)    default 0,
    cuerpo         varchar(500)  not null,
    created_at     timestamptz   default current_timestamp
);

create index idx_comentarios_votos on comentarios (votos);
create index idx_comentarios_create_at on comentarios (create_at);

drop table if exists comentarios_noticias cascade;

create table comentarios_noticias (
    id_comentario_noticia   bigserial constraint pk_comentarios_noticias primary key,
    id_comentario           bigint    constraint fk_comentarios_comentarios
                                      references comentarios (id_comentario)
                                      on delete no action on update cascade,
    id_noticia              bigint    constraint fk_noticias_noticias
                                      references noticias (id_noticia)
                                      on delete no action on update cascade
);

drop table if exists meneos cascade;

create table meneos (
    id_meneo       bigserial constraint pk_meneos primary key,
    id_usuario     bigint    constraint fk_meneos_usuarios
                             references public.user (id)
                             on delete no action on update cascade,
    id_noticia     bigint    constraint fk_meneos_noticias
                             references noticias (id_noticia)
                             on delete no action on update cascade
)


text:
use factotum::parser::*;
use rustc_serialize::json::{self, Json};

#[inline]
fn resource(name: &str) -> String {
    format!("./tests/resources/{}", name)
}

#[test]
fn invalid_files_err() {
    let res = parse("asdhf;asdjhfasdf", None, OverrideResultMappings::None);
    if let Err(msg) = res {
        assert_eq!(msg,
                   "Couldn't open 'asdhf;asdjhfasdf' for reading: No such file or directory (os \
                    error 2)"
                       .to_string())
    } else {
        panic!("the file doesn't exist - the test should have failed");
    }
}

#[test]
fn invalid_json_err() {
    let res = parse(&resource("invalid_json.factfile"),
                    None,
                    OverrideResultMappings::None);
    if let Err(msg) = res {
        assert_eq!(msg,
                   format!("'{}' is not a valid factotum factfile: invalid JSON - invalid syntax \
                            at line 1, column 3",
                           resource("invalid_json.factfile"))
                       .to_string())
    } else {
        panic!("the file is invalid json - the test should have failed");
    }
}

#[test]
fn invalid_against_schema_err() {
    let invalid = resource("example_invalid_no_name.factfile");
    let res = parse(&invalid, None, OverrideResultMappings::None);
    if let Err(msg) = res {
        assert_eq!(msg,
                   format!("'{}' is not a valid factotum factfile: '/data/name' - This property \
                            is required",
                           invalid)
                       .to_string())
    } else {
        panic!("the file is invalid json - the test should have failed");
    }
}

#[test]
fn invalid_against_schema_wrong_type() {
    let invalid = resource("example_wrong_type.factfile");
    let res = parse(&invalid, None, OverrideResultMappings::None);
    if let Err(msg) = res {
        assert_eq!(msg,
                   format!("'{}' is not a valid factotum factfile: \
                            '/data/tasks/0/onResult/terminateJobWithSuccess/0' - Type of the \
                            value is wrong (The value must be integer)",
                           invalid)
                       .to_string())
    } else {
        panic!("the file is invalid json - the test should have failed");
    }
}

#[test]
fn invalid_ambiguous_on_result() {
    let invalid = resource("example_invalid_terminate_continue_same.factfile");
    let res = parse(&invalid, None, OverrideResultMappings::None);
    if let Err(msg) = res {
        assert_eq!(msg,
                   format!("'{}' is not a valid factotum factfile: the task 'ambi' has \
                            conflicting actions.",
                           invalid))
    } else {
        panic!("conflicting actions in onResult should fail");
    }
}

#[test]
fn invalid_must_continue() {
    let invalid = resource("example_invalid_no_continue.factfile");
    let res = parse(&invalid, None, OverrideResultMappings::None);
    if let Err(msg) = res {
        assert_eq!(msg,
                   format!("'{}' is not a valid factotum factfile: the task 'continue' has no \
                            way to continue successfully.",
                           invalid))
    } else {
        panic!("having no values in continue should fail");
    }
}

#[test]
fn valid_generates_factfile() {
    use factotum::parser::SelfDescribingJson;
    let valid = resource("example_ok.factfile");

    if let Ok(factfile) = parse(&valid, None, OverrideResultMappings::None) {
        let tasks = factfile.get_tasks_in_order();
        assert_eq!(factfile.name, "My First DAG");

        let task_one = tasks.get(0).unwrap().get(0).unwrap();
        assert_eq!(task_one.name, "EmrEtlRunner");
        assert_eq!(task_one.depends_on, Vec::<&str>::new());

        let task_two = tasks.get(1).unwrap().get(0).unwrap();
        assert_eq!(task_two.name, "StorageLoader");
        assert_eq!(task_two.depends_on, vec!["EmrEtlRunner"]);

        let task_three = tasks.get(2).unwrap().get(0).unwrap();
        assert_eq!(task_three.name, "SQL Runner");
        assert_eq!(task_three.depends_on, vec!["StorageLoader"]);

        let expected_raw = include_str!("../../../tests/resources/example_ok.factfile");
        // convert it into "compact" form
        let inflated: SelfDescribingJson = json::decode(expected_raw).unwrap();
        let compacted: String = json::encode(&inflated).unwrap();
        print!("raw:\n\n{}", &factfile.raw);
        print!("\n\ncompacted:\n\n{}", &compacted);
        assert_eq!(factfile.raw, compacted);
    } else {
        panic!("valid factfile example_ok.factfile should have parsed but didn't");
    }
}

#[test]
fn overrides_set_noop_values() {
    let valid = resource("example_ok.factfile");

    let new_map = TaskReturnCodeMapping {
        continue_job: vec![12],
        terminate_early: vec![34],
    };

    if let Ok(factfile) = parse(&valid, None, OverrideResultMappings::All(new_map)) {
        let tasks = factfile.get_tasks_in_order();
        assert_eq!(factfile.name, "My First DAG");

        let task_one = tasks.get(0).unwrap().get(0).unwrap();
        assert_eq!(task_one.name, "EmrEtlRunner");
        assert_eq!(task_one.depends_on, Vec::<&str>::new());
        assert_eq!(task_one.on_result.terminate_job, vec![34]);
        assert_eq!(task_one.on_result.continue_job, vec![12]);

        let task_two = tasks.get(1).unwrap().get(0).unwrap();
        assert_eq!(task_two.name, "StorageLoader");
        assert_eq!(task_two.depends_on, vec!["EmrEtlRunner"]);
        assert_eq!(task_two.on_result.terminate_job, vec![34]);
        assert_eq!(task_two.on_result.continue_job, vec![12]);

        let task_three = tasks.get(2).unwrap().get(0).unwrap();
        assert_eq!(task_three.name, "SQL Runner");
        assert_eq!(task_three.depends_on, vec!["StorageLoader"]);
        assert_eq!(task_three.on_result.terminate_job, vec![34]);
        assert_eq!(task_three.on_result.continue_job, vec![12]);
    } else {
        panic!("valid factfile example_ok.factfile should have parsed but didn't");
    }

}


text:
/**
 * Parses an XML Texture Atlas object and adds all the Frames into a Texture.
 *
 * @function Phaser.Textures.Parsers.AtlasXML
 * @memberOf Phaser.Textures.Parsers
 * @private
 * @since 3.7.0
 *
 * @param {Phaser.Textures.Texture} texture - The Texture to add the Frames to.
 * @param {integer} sourceIndex - The index of the TextureSource.
 * @param {*} xml - The XML data.
 *
 * @return {Phaser.Textures.Texture} The Texture modified by this parser.
 */
var AtlasXML = function (texture, sourceIndex, xml)
{
    //  Malformed?
    if (!xml.getElementsByTagName('TextureAtlas'))
    {
        console.warn('Invalid Texture Atlas XML given');
        return;
    }

    //  Add in a __BASE entry (for the entire atlas)
    var source = texture.source[sourceIndex];

    texture.add('__BASE', sourceIndex, 0, 0, source.width, source.height);

    //  By this stage frames is a fully parsed array
    var frames = xml.getElementsByTagName('SubTexture');

    var newFrame;

    for (var i = 0; i < frames.length; i++)
    {
        var frame = frames[i].attributes;

        var name = frame.name.value;
        var x = parseInt(frame.x.value, 10);
        var y = parseInt(frame.y.value, 10);
        var width = parseInt(frame.width.value, 10);
        var height = parseInt(frame.height.value, 10);

        //  The frame values are the exact coordinates to cut the frame out of the atlas from
        newFrame = texture.add(name, sourceIndex, x, y, width, height);

        //  These are the original (non-trimmed) sprite values
        if (frame.frameX)
        {
            var frameX = Math.abs(parseInt(frame.frameX.value, 10));
            var frameY = Math.abs(parseInt(frame.frameY.value, 10));
            var frameWidth = parseInt(frame.frameWidth.value, 10);
            var frameHeight = parseInt(frame.frameHeight.value, 10);

            newFrame.setTrim(
                width,
                height,
                frameX,
                frameY,
                frameWidth,
                frameHeight
            );
        }
    }

    return texture;
};

module.exports = AtlasXML;


text:
Infrastructure provides simple, middleware-like infrastructure for your
application startup.

## Installation

    npm install infra --save

## Usage

Define initializers

1.  Initialize the database

        exports.description = "Postgres";
        exports.init = function(container, cb) {
            var pg = require('pg')
            // sanity check, ensure database can be connected
            pg.connect(container.config.postgres, cb);
        };

2.  Initialize express

        exports.description = "Express web server";
        exports.init = function(container, cb) {
                var app = require('express')();
                app.use(bodyParser.json());
                // register app with container
                container.app = app;
                cb();
            }
        };

3.  Initialize routes

        exports.description = "Express routes";
        exports.init = function(container, cb) {
            var app = container.app;
            app.get('/', function(req, res, next) {
                res.render('index');
            })
            cb();
        };

Use the initializers and start the app

    var starter = require("infra")();
    var container = {
        config: {
            postgres: "postgres://localhost/dev"
        }
    };

    starter.use(require("./database"));
    starter.use(require("./expressPre"));
    starter.use(require("./handlebars"));
    starter.use(require("./expressPost"));
    starter.use(require("./routes"));
    starter.use(require("./processHandlers"));

    starter.start(container, function(err) {
        if (err) trow err;
        container.app.listen(3000);
    });

## Tips

1.  Use your own logger

        var infra = require("infrastructure")(log.info.bind(log))


text:
<?php

defined('_JEXEC') or die;

/**
 * Methods supporting a list of banner records.
 *
 * @package     Joomla.Administrator
 * @subpackage  com_banners
 * @since       1.6
 */
class BannersModelClients extends JModelList
{
	/**
	 * Constructor.
	 *
	 * @param   array  $config  An optional associative array of configuration settings.
	 *
	 * @see     JController
	 * @since   1.6
	 */
	public function __construct($config = array())
	{
		if (empty($config['filter_fields']))
		{
			$config['filter_fields'] = array(
				'id', 'a.id',
				'name', 'a.name',
				'contact', 'a.contact',
				'state', 'a.state',
				'checked_out', 'a.checked_out',
				'checked_out_time', 'a.checked_out_time',
				'nbanners',
				'purchase_type'
			);
		}

		parent::__construct($config);
	}

	/**
	 * Method to auto-populate the model state.
	 *
	 * Note. Calling getState in this method will result in recursion.
	 *
	 * @param   string  $ordering   An optional ordering field.
	 * @param   string  $direction  An optional direction (asc|desc).
	 *
	 * @return  void
	 *
	 * @since   1.6
	 */
	protected function populateState($ordering = null, $direction = null)
	{
		// Load the filter state.
		$search = $this->getUserStateFromRequest($this->context . '.filter.search', 'filter_search');
		$this->setState('filter.search', $search);

		$state = $this->getUserStateFromRequest($this->context . '.filter.state', 'filter_state', '', 'string');
		$this->setState('filter.state', $state);

		// Load the parameters.
		$params = JComponentHelper::getParams('com_banners');
		$this->setState('params', $params);

		// List state information.
		parent::populateState('a.name', 'asc');
	}

	/**
	 * Method to get a store id based on model configuration state.
	 *
	 * This is necessary because the model is used by the component and
	 * different modules that might need different sets of data or different
	 * ordering requirements.
	 *
	 * @param   string  $id  A prefix for the store id.
	 *
	 * @return  string  A store id.
	 */
	protected function getStoreId($id = '')
	{
		// Compile the store id.
		$id .= ':' . $this->getState('filter.search');
		$id .= ':' . $this->getState('filter.access');
		$id .= ':' . $this->getState('filter.state');

		return parent::getStoreId($id);
	}

	/**
	 * Build an SQL query to load the list data.
	 *
	 * @return  JDatabaseQuery
	 */
	protected function getListQuery()
	{
		// Create a new query object.
		$db = $this->getDbo();
		$query = $db->getQuery(true);

		$params = JComponentHelper::getParams('com_banners');
		$defaultPurchase = $params->get('purchase_type', 3);

		// Select the required fields from the table.
		$query->select(
			$this->getState(
				'list.select',
				'a.id AS id,' .
					'a.name AS name,' .
					'a.contact AS contact,' .
					'a.checked_out AS checked_out,' .
					'a.checked_out_time AS checked_out_time, ' .
					'a.state AS state,' .
					'a.metakey AS metakey,' .
					'a.purchase_type as purchase_type'
			)
		);

		$query->from($db->quoteName('#__banner_clients') . ' AS a');

		// Join over the banners for counting
		$query->select('COUNT(b.id) as nbanners')
			->join('LEFT', '#__banners AS b ON a.id = b.cid');

		// Join over the users for the checked out user.
		$query->select('uc.name AS editor')
			->join('LEFT', '#__users AS uc ON uc.id=a.checked_out');

		// Filter by published state
		$published = $this->getState('filter.state');

		if (is_numeric($published))
		{
			$query->where('a.state = ' . (int) $published);
		}
		elseif ($published === '')
		{
			$query->where('(a.state IN (0, 1))');
		}

		$query->group('a.id, a.name, a.contact, a.checked_out, a.checked_out_time, a.state, a.metakey, a.purchase_type, uc.name');

		// Filter by search in title
		$search = $this->getState('filter.search');

		if (!empty($search))
		{
			if (stripos($search, 'id:') === 0)
			{
				$query->where('a.id = ' . (int) substr($search, 3));
			}
			else
			{
				$search = $db->quote('%' . $db->escape($search, true) . '%');
				$query->where('a.name LIKE ' . $search);
			}
		}

		// Filter by purchase type
		$purchaseType = $this->getState('filter.purchase_type');

		if (!empty($purchaseType))
		{
			if ($defaultPurchase == $purchaseType)
			{
				$query->where('(a.purchase_type = ' . (int) $purchaseType . ' OR a.purchase_type = -1)');
			}
			else
			{
				$query->where('a.purchase_type = ' . (int) $purchaseType);
			}
		}

		$ordering = $this->getState('list.ordering', 'ordering');

		if ($ordering == 'nbanners')
		{
			$ordering = 'COUNT(b.id)';
		}

		// Add the list ordering clause.
		$query->order($db->escape($ordering) . ' ' . $db->escape($this->getState('list.direction', 'ASC')));

		return $query;
	}
}


text:
console.log("HELLO EXTENSION!");

// CROSSFADER MESSAGES
var crossfaderInput = document.querySelector( '#crossfader' );

crossfaderInput.addEventListener( 'input', function(event) {
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
        chrome.tabs.sendMessage(tabs[0].id, {
                                                message: "crossfaderChange",
                                                newValueLeftSection: 1 - crossfaderInput.value/100,
                                                newValueRightSection: crossfaderInput.value/100
                                            });
    });
});

// LEFT SECTION
var leftSectionFilterCutoffInput = document.querySelector( '#filter-cutoff-left-section' );

leftSectionFilterCutoffInput.addEventListener( 'input', function(event) {
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
        chrome.tabs.sendMessage(tabs[0].id, {
                                                message: "leftSectionFilterCutoffChanged",
                                                newValue: leftSectionFilterCutoffInput.value
                                            });
    });
});

// RIGHT SECTION
var rightSectionFilterCutoffInput = document.querySelector( '#filter-cutoff-right-section' );

rightSectionFilterCutoffInput.addEventListener( 'input', function(event) {
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
        chrome.tabs.sendMessage(tabs[0].id, {
                                                message: "rightSectionFilterCutoffChanged",
                                                newValue: rightSectionFilterCutoffInput.value
                                            });
    });
});

// MIDI STUFF

window.addEventListener('load', function() {
  navigator.requestMIDIAccess().then(
    onMIDIInit,
    onMIDISystemError );
});

// function onMIDIInit( midi ) {
//   var list=midi.outputs();
//   console.log("onMIDIInit");

//   for (var i=0; i<list.length; i++) {
//     list[i].send( [0x90, 3, 32] );
//   }
// }

function onMIDISystemError( midi ) {
    console.log("onMIDISystemError");
}

// function onMIDIInit( midi ) {
//   for (var input of midiAccess.outputs.values())
//     input.send( [0x90, 3, 32] );
// }

// function onMIDIInit( midi ) {
//   for (var input of midiAccess.inputs.values())
//     input.onmidimessage = midiMessageReceived;
// }

function onMIDIInit( midi ) {
  var list=midi.inputs();
    console.log("onMIDIInit");

    console.log(list[0]);
    list[0].onmidimessage = midiMessageReceived;
    console.log(list[0]);
}

function midiMessageReceived( ev ) {
    // console.log(ev);
    var cmd = ev.data[0] >> 4;
    // console.log(cmd);
    var channel = ev.data[0] & 0xf;
    var noteNumber = ev.data[1];
    var velocity = 0;
    if (ev.data.length > 2)
      velocity = ev.data[2];

    // MIDI noteon with velocity=0 is the same as noteoff
    if ( cmd==8 || ((cmd==9)&&(velocity==0)) ) { // noteoff
      noteOff( noteNumber );
    } else if (cmd == 9) { // note on
      noteOn( noteNumber, velocity);
    } else if (cmd == 11) { // controller message
      controller( noteNumber, velocity);
    } else {
      // probably sysex!
    }
}

function controller(controllerNumber, value) {
    if (controllerNumber === 1) {
        crossfaderInput.value = value / 127 * 100;
        var event = new MouseEvent('input');
        crossfaderInput.dispatchEvent(event);

    } else if (controllerNumber === 5) {
        leftSectionFilterCutoffInput.value = (value > 126) ? 20000: value * 50;
        var event = new MouseEvent('input');
        leftSectionFilterCutoffInput.dispatchEvent(event);
    } else if (controllerNumber === 6) {
        rightSectionFilterCutoffInput.value = (value > 126) ? 20000: value * 50;
        var event = new MouseEvent('input');
        rightSectionFilterCutoffInput.dispatchEvent(event);
    }
}

function noteOn( noteNumber, velocity ) {
    console.log("noteON: " + noteNumber + "   " + velocity);
}

function noteOff( noteNumber ) {
    console.log("noteOFF: " + noteNumber);
}

function getFrequencyForNoteNumber( noteNumber ) {

}


text:
class MainController < ApplicationController

  # GET /about
  def about
    respond_to do |format|
      format.html
    end
  end

  # GET /terms
  def terms
    respond_to do |format|
      format.html
    end
  end

end


text:
package org.broadleafcommerce.openadmin.security;

/**
 *
 * @author jfischer
 *
 */
public class SecurityUserRoles {

    public static final String MERCHANDISER = "ROLE_MERCHANDISER";
    public static final String PROMOTION_CONTROLLER = "ROLE_PROMOTION_CONTROLLER";
    public static final String USER_ADMINISTRATOR = "ROLE_USER_ADMINISTRATOR";
    public static final String USER = "ROLE_USER";

}