text:
/*! \mainpage
 * \section intro Introduction
 * This is the documentation for the data structures, functions, variables,
 * defines, enums, and typedefs for the USART in LIN modes software driver.\n It also comes
 * bundled with an example. This example is a basic example supporting Master and Slave Mode example.\n
 * It is possible to choose between the two modes. \n
 * Example's operating mode:
 * - Connect the RX/TX lines of LIN to the transceiver.
 * - Open CANVector Tools and select  in LINANALYSER/ folder the project link to you configuration \n
 *        --> Lin Version 1.3 or 2.0 \n
 *        -->  Node configuration   Master or Slave \n
 * - Run the source code.
 * - On the bus you will see \n
 *        --> In case Of Master Configuration: The message with the ID 12 sent by UC3 and the response sent by CANVector Tools.\n
 *        The Message with the ID 0x13 is sent with the response by the UC3. \n
 *        -->  In case of Slave Configuration: The message with the ID 12 sent by CANVector Tools and the response sent by UC3.\n
 *        The Message with the ID 0x13 is sent with the response by the CANVector Tools. \n
 *
 * \section files Main Files
 * - lin.c: Service for LIN support mode;
 * - lin.h: Header file of service for LIN support mode;
 * - lin_mngt_example.c: LIN example application in slave mode.
 * - conf_lin.h: LIN example configuration file for the driver.
 *
 * \section compilinfo Compilation Information
 * This software is written for GNU GCC for AVR32 and for IAR Embedded Workbench
 * for Atmel AVR32. Other compilers may or may not work.
 *
 * \section deviceinfo Device Information
 * All AVR32 devices with USART revision 3 and above revision of the IP can be used.
 *
 * \section configinfo Configuration Information
 * This example has been tested with the following configuration:
 * - STK600 starter kit and AVR32UC3B device;
 * - CPU clock: 12 MHz;
 *
 * \section contactinfo Contact Information
 * For further information, visit
 * Atmel AVR32.\n
 */
 /**
 * Support and FAQ: visit Atmel Support
 */

#include <avr32/io.h>
#include "compiler.h"
#include "board.h"
#include "power_clocks_lib.h"
#include "gpio.h"
#include "tc.h"
#include "intc.h"
#include "usart.h"
#include "lin.h"

#if BOARD == UC3C_EK
#   define TC_INSTANCE               &AVR32_TC0
#   define TC_INSTANCE_IRQ           AVR32_TC0_IRQ0
#   define TC_INSTANCE_IRQ_GROUP     AVR32_TC0_IRQ_GROUP
#elif BOARD == EVK1101
#   define TC_INSTANCE               &AVR32_TC
#   define TC_INSTANCE_IRQ           AVR32_TC_IRQ0
#   define TC_INSTANCE_IRQ_GROUP     AVR32_TC_IRQ_GROUP
#else
#error Wrong board
#endif

//#define MASTER_MODE
//! PBA Clock Reference
#define FPBA                                FOSC0

//! Timer Counter Channel Used
#define TC_CHANNEL                          0

//! Lin Master Task linked to the transmission of the message with the ID 0x12
extern void lin_master_task_ID12(void);

//! Lin Master Task linked to the transmission of the message with the ID 0x15
extern void lin_master_task_ID15(void);

//! Lin Slave Task linked to the reception of the message with the ID 0x12
extern void lin_slave_task_ID12(U8* d_buf);

//! Lin Slave Task linked to the reception of the message with the ID 0x15
extern void lin_slave_task_ID15(U8* d_buf);

//! Local Buffer for transmission
U8  lin_data_out_node0[8];

//! Local Buffer for emission
U8  lin_data_in_node0[8];

//! Current Task Id used for the scheduled table
volatile unsigned char task_id = 0;

/*! \brief TC interrupt.
 */
#if defined (__GNUC__)
__attribute__((__interrupt__))
#elif defined (__ICCAVR32__)
#pragma handler = TC_INSTANCE_IRQ_GROUP, 1
__interrupt
#endif
static void tc_irq(void)
{
  // Clear the interrupt flag. This is a side effect of reading the TC SR.
  tc_read_sr(TC_INSTANCE, TC_CHANNEL);

  // Send message on LIN ...
  switch(task_id)
  {
    case 0 :
      lin_master_task_ID12();
      task_id=1;
      break;

     case 1 :
      lin_master_task_ID15();
      task_id=0;
      break;

    default :
      break;
  }
}

/*! \brief Start Scheduler: Configuration of dedicated timer for periodic LIN transmission.
 */
void start_scheduler(void)
{
  volatile avr32_tc_t *tc = TC_INSTANCE;

  // Options for waveform generation.
  static const tc_waveform_opt_t WAVEFORM_OPT =
  {
    .channel  = TC_CHANNEL,                        // Channel selection.

    .bswtrg   = TC_EVT_EFFECT_NOOP,                // Software trigger effect on TIOB.
    .beevt    = TC_EVT_EFFECT_NOOP,                // External event effect on TIOB.
    .bcpc     = TC_EVT_EFFECT_NOOP,                // RC compare effect on TIOB.
    .bcpb     = TC_EVT_EFFECT_NOOP,                // RB compare effect on TIOB.

    .aswtrg   = TC_EVT_EFFECT_NOOP,                // Software trigger effect on TIOA.
    .aeevt    = TC_EVT_EFFECT_NOOP,                // External event effect on TIOA.
    .acpc     = TC_EVT_EFFECT_NOOP,                // RC compare effect on TIOA: toggle.
    .acpa     = TC_EVT_EFFECT_NOOP,                // RA compare effect on TIOA: toggle (other possibilities are none, set and clear).

    .wavsel   = TC_WAVEFORM_SEL_UP_MODE_RC_TRIGGER,// Waveform selection: Up mode with automatic trigger(reset) on RC compare.
    .enetrg   = false,                             // External event trigger enable.
    .eevt     = 0,                                 // External event selection.
    .eevtedg  = TC_SEL_NO_EDGE,                    // External event edge selection.
    .cpcdis   = false,                             // Counter disable when RC compare.
    .cpcstop  = false,                             // Counter clock stopped with RC compare.

    .burst    = false,                             // Burst signal selection.
    .clki     = false,                             // Clock inversion.
    .tcclks   = TC_CLOCK_SOURCE_TC5                // Internal source clock 3, connected to fPBA / 128.
  };

  static const tc_interrupt_t TC_INTERRUPT =
  {
    .etrgs = 0,
    .ldrbs = 0,
    .ldras = 0,
    .cpcs  = 1,
    .cpbs  = 0,
    .cpas  = 0,
    .lovrs = 0,
    .covfs = 0
  };

  // Register the RTC interrupt handler to the interrupt controller.
  INTC_register_interrupt(&tc_irq, TC_INSTANCE_IRQ, AVR32_INTC_INT0);

  // Initialize the timer/counter.
  tc_init_waveform(tc, &WAVEFORM_OPT);         // Initialize the timer/counter waveform.

  // Set the compare triggers.
  // Remember TC counter is 16-bits, so counting second is not possible with fPBA = 16 MHz.
  // We configure it to count 0.5 s.
  // We want: (1/(fPBA/8)) * RC = 0.5 s, hence RC = (fPBA/128)/2 = 62500 to get an interrupt every 0.5 s.
  tc_write_rc(tc, TC_CHANNEL, (FPBA / 128)/2); // Set RC value.

  tc_configure_interrupts(tc, TC_CHANNEL, &TC_INTERRUPT);

  // Start the timer/counter.
  tc_start(tc, TC_CHANNEL);                    // And start the timer/counter.

}

/*! \brief This is an example demonstrating the LIN mode of USART IP
 *         functionalities using a dedicated USART LIN driver.
 */
int main(void)
{
   // Switch main clock to external oscillator 0 (crystal).
  pcl_switch_to_osc(PCL_OSC0, FOSC0, OSC0_STARTUP);

#if (defined AVR32_HMATRIX)
  AVR32_HMATRIX.mcfg[AVR32_HMATRIX_MASTER_CPU_INSN] = 0x1;
#endif
#if (defined AVR32_HMATRIXB)
  AVR32_HMATRIXB.mcfg[AVR32_HMATRIXB_MASTER_CPU_INSN] = 0x1;
#endif

  // The INTC driver has to be used only for GNU GCC for AVR32.
  // Initialize interrupt vectors.
  INTC_init_interrupts();

  // USART LIN options.
#ifdef MASTER_MODE
  // Node 0:  LIN_MASTER_MODE
  lin_init( true, 0, 9600, FOSC0);
#else
  // Node 0:  LIN_SLAVE_MODE
  lin_init( false, 0, 9600, FOSC0);
#endif

  // Configure lin_descriptor
  //- Init LIN data Node 0
  // Object 0
  lin_descript_list_node0[0].l_id = 0x12;
  lin_descript_list_node0[0].l_dlc = 2;
  lin_descript_list_node0[0].l_cmd = PUBLISH;
  lin_descript_list_node0[0].l_status = 0;
  lin_descript_list_node0[0].l_pt_data = lin_data_out_node0;
  lin_descript_list_node0[0].l_pt_function = lin_slave_task_ID12;

  // Configure lin_descriptor
  //- Init LIN data Node 0
  // Object 1
  lin_descript_list_node0[1].l_id = 0x15;
  lin_descript_list_node0[1].l_dlc = 2;
  lin_descript_list_node0[1].l_cmd = SUBSCRIBE;
  lin_descript_list_node0[1].l_status = 0;
  lin_descript_list_node0[1].l_pt_data = lin_data_in_node0;
  lin_descript_list_node0[1].l_pt_function = lin_slave_task_ID15;

#ifdef MASTER_MODE
  // In case of Master Mode, the timing transmission starts...
  start_scheduler();
#else
  // In case of Slave Mode, only wait until ID reception...
#endif

  Enable_global_interrupt();

  while (true);
}

//_____ M A S T E R    F U N C T I O N S _______________________________________

/*! \brief lin_master_task_ID12
 *
 */
void  lin_master_task_ID12(void)
{
  lin_send_cmd (0,lin_descript_list_node0[0].l_id, lin_descript_list_node0[0].l_dlc );
}

/*! \brief lin_master_task_ID15
 *
 */
void  lin_master_task_ID15(void)
{
  lin_send_cmd (0,lin_descript_list_node0[1].l_id, lin_descript_list_node0[1].l_dlc );
}

//_____ S L A V E   F U N C T I O N S __________________________________________

/*! \brief lin_slave_task_ID12
 *
 */
void  lin_slave_task_ID12(U8* d_buf)
{
  gpio_tgl_gpio_pin(LED0_GPIO);
  d_buf[0] = 0x77;
  d_buf[1] = 0x88;
}

/*! \brief lin_slave_task_ID15
 *
 */
void  lin_slave_task_ID15(U8* d_buf)
{
  gpio_tgl_gpio_pin(LED1_GPIO);
}


text:
import React, { PropTypes } from 'react';
import Moment from 'moment';

import Styles from './Styles/main.scss';
import Play from 'components/Assets/Icons/Play';
import Flag from 'components/Assets/Icons/Flag';
import Palette from 'components/Assets/Palette';
import Sings from 'components/Assets/Icons/Sings';

Moment.locale('ru');

export default function Common() {
    // в episodeProgress нужно передать, начало программы, текущее время и конец программы

    // const episodeProgress = (100 / (Moment(next.date).unix() - Moment(current.date).unix())
    // * (Moment(currentTime).unix() - Moment(current.date).unix()));
    //
    // const progressStile = {
    //     width: `${episodeProgress}%`
    // };

    const progressStile = {
        width: '76%'
    };

    return (

                <Play className={ Styles.play } color={ Palette.tempColor39 }/>

                        <Flag language={ 'uk' } className={ Styles.flag }/>
                        українська

                        <Flag language={ 'ru' } className={ Styles.flag }/>
                        русский

                        <Flag language={ 'uk' } className={ Styles.flag }/>
                        українська

                        <Flag language={ 'usa' } className={ Styles.flag }/>
                        english

                        <Sings className={ Styles.sings }/>
                        сурдоперевод

Ник Вуйчич: День благодаренья

Хліб щоденний

                    16:30

                    17:30

                    Австралийский мотивационный оратор, меценат, писатель и певец, рождённый с
                    редким наследственным заболеванием, приводящим к отсутствию всех четырёх конечностей.
                    «Моя миссия — помочь людям найти свой путь в жизни», — говорит он.

    );
}

Common.propTypes = {
    mediaType: PropTypes.string.isRequired
};

redpajama_set_name: RedPajamaGithub


text:
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')

# These tests iterate through all known types (see Sizes#STRING_COPIES) and compile a small C program
# for each; the C program prints out the size of the type for this machine, and the test passes
# if the sizes match.

describe "Sizes" do
  # inline hashes the method names so that they aren't double-compiled -- but this sucks if
  # we want to reuse the same method name, so instead we'll tack a global counter onto
  # the end of the method name to ensure they're all unique.
  $inline_counter = 0

  begin
    require "inline"
    include Sizes

    def real_sizeof(type_name)
      sizeof_test = Class.new do
        inline :C do |builder|
          builder.include "<stdint.h>"
          builder.c <<-end_c_code
            int size#{$inline_counter += 1}()
            {
              int size = sizeof(#{type_name});
              return size;
            }
          end_c_code
        end
      end

      sizeof_test.new.send(:"size#{$inline_counter}")
    end

    (Sizes::STRING_COPIES.keys - Sizes::C99_TYPES).each do |type_name|
      it "should generate correct size for :#{type_name}" do
        sizeof(type_name).should == real_sizeof(type_name.gsub(/_/, ' '))
      end
    end

    Sizes::C99_TYPES.each do |type_name|
      it "should generate correct size for C99 type :#{type_name}" do
        sizeof(type_name).should == real_sizeof("#{type_name}_t")
      end
    end
  rescue LoadError
    it "doesn't have RubyInline" do
      fail "Can't run dynamic test suite without the RubyInline gem"
    end
  end
end


text:
dev-env
=======

My terminal-based development environment


text:
layout: page
title: Remap
search_omit: true
---


text:
<?xml version="1.0" encoding="UTF-8"?>
<!-- This sample file contains the list of order options identified for the following products: Envisat MERIS RR -->
<!-- The reported values are just examples and are not the actual values. -->
<GetOptionsResponse xsi:schemaLocation="http://www.opengis.net/oseo/1.0 http://schemas.opengis.net/oseo/1.0/oseo.xsd" xmlns="http://www.opengis.net/oseo/1.0" xmlns:sps="http://www.opengis.net/sps/2.0" xmlns:swe="http://www.opengis.net/swe/2.0" xmlns:gml="http://www.opengis.net/gml/3.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<status>success</status>
	<orderOptions>
		<productOrderOptionsId>options_001</productOrderOptionsId>
		<description>Order Options for producing MERIS RR</description>
		<orderType>PRODUCT_ORDER</orderType>
		<option>
			<swe:DataRecord>
				<swe:field name="productType">
					<swe:Category updatable="false" optional="true" definition="http://www.opengis.net/def/parameter/ESA/1.0/productType">
						<swe:identifier>productType</swe:identifier>
						<swe:description>productType for ENVISAT MERIS RR</swe:description>
						<swe:constraint>
							<swe:AllowedTokens>
								<swe:value>MER_CA__0P</swe:value>
								<swe:value>MER_RV__0P</swe:value>
								<swe:value>MER_LRC_2P</swe:value>
								<swe:value>MER_RRC_2P</swe:value>
								<swe:value>MER_RRV_2P</swe:value>
							</swe:AllowedTokens>
						</swe:constraint>
					</swe:Category>
				</swe:field>
			</swe:DataRecord>
			<grouping>Processing Option</grouping>
		</option>
		<productDeliveryOptions>
			<mediaDelivery>
				<packageMedium>DVD</packageMedium>
			</mediaDelivery>
		</productDeliveryOptions>
		<productDeliveryOptions>
			<onlineDataDelivery>
				<protocol>ftp</protocol>
			</onlineDataDelivery>
		</productDeliveryOptions>
	</orderOptions>
	<orderOptions>
		<productOrderOptionsId>options_002</productOrderOptionsId>
		<description>Order Options for producing MERIS RR with consolidation</description>
		<orderType>PRODUCT_ORDER</orderType>
		<option>
			<swe:DataRecord>
				<swe:field name="productType">
					<swe:Category updatable="false" optional="true" definition="http://www.opengis.net/def/parameter/ESA/1.0/productType">
						<swe:identifier>productType</swe:identifier>
						<swe:description>productType for ENVISAT MERIS RR</swe:description>
						<swe:constraint>
							<swe:AllowedTokens>
								<swe:value>MER_RR__0P</swe:value>
								<swe:value>MER_RR__1P</swe:value>
								<swe:value>MER_RR__2P</swe:value>
							</swe:AllowedTokens>
						</swe:constraint>
					</swe:Category>
				</swe:field>
			</swe:DataRecord>
			<grouping>Processing Option</grouping>
		</option>
		<option>
			<swe:DataRecord>
				<swe:field name="consolidation">
					<swe:Category updatable="false" optional="true" definition="http://www.opengis.net/def/parameter/ESA/1.0/consolidation">
						<swe:identifier>consolidation</swe:identifier>
						<swe:description>Consolidation</swe:description>
						<swe:constraint>
							<swe:AllowedTokens>
								<swe:value>MER_RR__0P</swe:value>
								<swe:value>MER_RR__1P</swe:value>
								<swe:value>MER_RR__2P</swe:value>
							</swe:AllowedTokens>
						</swe:constraint>
					</swe:Category>
				</swe:field>
			</swe:DataRecord>
			<grouping>Processing Option</grouping>
		</option>
		<productDeliveryOptions>
			<mediaDelivery>
				<packageMedium>DVD</packageMedium>
			</mediaDelivery>
		</productDeliveryOptions>
		<productDeliveryOptions>
			<onlineDataDelivery>
				<protocol>ftp</protocol>
			</onlineDataDelivery>
		</productDeliveryOptions>
	</orderOptions>
</GetOptionsResponse>


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.facebook.presto.failureDetector;

import com.google.inject.Binder;
import com.google.inject.Module;
import com.google.inject.Scopes;
import org.weakref.jmx.guice.ExportBinder;

import static io.airlift.configuration.ConfigurationModule.bindConfig;
import static io.airlift.http.client.HttpClientBinder.httpClientBinder;

public class FailureDetectorModule
        implements Module
{
    @Override
    public void configure(Binder binder)
    {
        httpClientBinder(binder)
                .bindHttpClient("failure-detector", ForFailureDetector.class)
                .withPrivateIoThreadPool()
                .withTracing();

        bindConfig(binder).to(FailureDetectorConfig.class);

        binder.bind(HeartbeatFailureDetector.class).in(Scopes.SINGLETON);

        binder.bind(FailureDetector.class)
                .to(HeartbeatFailureDetector.class)
                .in(Scopes.SINGLETON);

        ExportBinder.newExporter(binder)
                .export(HeartbeatFailureDetector.class)
                .withGeneratedName();
    }
}


text:
module VideoWrapper

  # Renders a responsive iframe with a video embedded.
  #
  # Example usage:
  #
  # {% video //www.youtube.com/embed/hy7IMGVUHps %} {% endvideo %}
  #
  # or:
  # {% video %}
  #
  #
  # {% endvideo %}
  class Tag < Liquid::Block

    def initialize(tag_name, src, tokens)
      super
      @src = src
    end

    def render(context)
      out = '
'
      if not @src.empty?
        out += ''
      else
        contents = super
        out += contents
      end
      out += "
"
    end

  end
end

Liquid::Template.register_tag('video', VideoWrapper::Tag)


text:
this.addEventListener('fetch', function(event) {
  console.log('fetch', event);
  // event.respondWith(fetch(event.request));
});


text:
using System;
using System.Drawing;
using System.Windows.Forms;
using ULib;
using ULib.Controls;
using ULib.Exceptions;
using Utilities.Components;
using Utilities.Components.Deployment;
using Utilities.Components.HA;
using Utilities.Components.Launchers;
using Utilities.Settings;
using Utilities.Components.DBPartitioning;

namespace Utilities
{
    public partial class MainForm : Form
    {
        private ActionTreeViewNode prevSelectedNode;
        public MainForm()
        {
            InitializeComponent();
            Load += new EventHandler(MainForm_Load);
            KeyUp += new KeyEventHandler(MainForm_KeyUp);
            FormClosing += new FormClosingEventHandler(MainForm_FormClosing);
            AppSettings.Instance.Initialize(AppSettings.KeyDeploySettings);
        }

        protected override void WndProc(ref Message m)
        {
            base.WndProc(ref m);
        }

        void MainForm_KeyUp(object sender, KeyEventArgs e)
        {

        }

        void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            foreach (ActionTreeViewNode node in tv.Nodes)
            {
                node.Unload();
            }
        }

        void MainForm_Load(object sender, EventArgs e)
        {
            this.BackColor = Color.White;
            tv.Nodes.Clear();

            tabs.SelectedIndexChanged += new EventHandler(tabs_SelectedIndexChanged);

            ActionTreeViewNode node;

			node = new ActionTreeViewNode
			{
				Name = "dbp",
				Text = "DB Partitioning",
				ActivateCallback = delegate(ActionTreeViewNode n)
				{
					ClearModules();
					return true;
				}
			};
			tv.Nodes.Add(node);

			//node = new ActionTreeViewNode
			//{
			//    Name = "ham",
			//    Text = "Plan Designer",
			//    ActivateCallback = delegate(ActionTreeViewNode n)
			//    {
			//        ClearModules();
			//        AddModule(typeof(PlanForm), n);
			//        return true;
			//    }
			//};
			//tv.Nodes.Add(node);

            //node = new ActionTreeViewNode
            //{
            //    Name = "utl",
            //    Text = "Utilities",
            //    ActivateCallback = delegate(ActionTreeViewNode n)
            //    {
            //        ClearModules();
            //        AddModule(typeof(PID), n);
            //        return true;
            //    }
            //};
            //tv.Nodes.Add(node);

            //node = new ActionTreeViewNode
            //{
            //    Name = "lch",
            //    Text = "Launcher",
            //    ActivateCallback = delegate(ActionTreeViewNode n)
            //    {
            //        ClearModules();
            //        AddModule(typeof(P1Launcher), n);
            //        return true;
            //    }
            //};
            //tv.Nodes.Add(node);

            //node = new ActionTreeViewNode
            //{
            //    Name = "dpl",
            //    Text = "Deployment",
            //    ActivateCallback = delegate(ActionTreeViewNode n)
            //    {
            //        ClearModules();
            //        AddModule(typeof(MsiSeekerForm), n);
            //        return true;
            //    }
            //};
            //tv.Nodes.Add(node);

            tv.NodeMouseClick += new TreeNodeMouseClickEventHandler(tv_NodeMouseClick);

            tabs.TabPages.Clear();
            ActivateNode(node);
            tv.SelectedNode = node;
            ExceptionHandler.Handlers.Add(HandleException);
        }

        void tabs_SelectedIndexChanged(object sender, EventArgs e)
        {
        }

        private void tv_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            ActionTreeViewNode node = e.Node as ActionTreeViewNode;
            if (prevSelectedNode != node)
            {
                ActivateNode(node);
                prevSelectedNode = node;
            }
        }

        private void ActivateNode(ActionTreeViewNode node)
        {
            if (node != null && node.ActivateCallback != null)
            {
                node.ActivateCallback(node);
                prevSelectedNode = node;
            }
        }

        private bool HandleException(Exception error)
        {
            MessageBox.Show(error.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            return true;
        }

        protected void ClearModules()
        {
            tabs.TabPages.Clear();
        }

        protected IEmbededModule AddModule(Type moduleType, ActionTreeViewNode node = null)
        {
            IEmbededModule instance = moduleType.GetConstructor(Type.EmptyTypes).Invoke(null) as IEmbededModule;
            TabPage page = CreateTab();
            instance.EmbedInto(page);
            if (node != null)
            {
                node.AddModule(instance);
            }
            return instance;
        }

        protected TabPage CreateTab()
        {
            TabPage page = new TabPage();
            tabs.TabPages.Add(page);
            return page;
        }

        private ActionTreeView tv;

        #region UI
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
            this.tabs = new System.Windows.Forms.TabControl();
            this.tbModule = new System.Windows.Forms.TabPage();
            this.tv = new ULib.Controls.ActionTreeView();
            this.tabs.SuspendLayout();
            this.SuspendLayout();
            //
            // tabs
            //
            resources.ApplyResources(this.tabs, "tabs");
            this.tabs.Controls.Add(this.tbModule);
            this.tabs.Multiline = true;
            this.tabs.Name = "tabs";
            this.tabs.SelectedIndex = 0;
            this.tabs.SizeMode = System.Windows.Forms.TabSizeMode.FillToRight;
            //
            // tbModule
            //
            this.tbModule.BackColor = System.Drawing.SystemColors.ButtonHighlight;
            resources.ApplyResources(this.tbModule, "tbModule");
            this.tbModule.Name = "tbModule";
            //
            // tv
            //
            resources.ApplyResources(this.tv, "tv");
            this.tv.Name = "tv";
            //
            // MainForm
            //
            resources.ApplyResources(this, "$this");
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.Controls.Add(this.tv);
            this.Controls.Add(this.tabs);
            this.KeyPreview = true;
            this.Name = "MainForm";
            this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
            this.tabs.ResumeLayout(false);
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.TabControl tabs;
        private System.Windows.Forms.TabPage tbModule;

        #endregion
    }
}


text:
namespace XMap.Test.TestTypes
{
    public class Agency
    {
        public string Name { get; set; }
        public Country Country { get; set; }
    }

    public enum Country
    {
        Belgium,
        China,
        USA,
    }
}


text:
package org.eclipse.swt.snippets;

/*
 * TreeEditor example snippet: edit the text of a tree item (in place, fancy)
 *
 * For a list of all SWT example snippets see
 * http://www.eclipse.org/swt/snippets/
 */
import org.eclipse.swt.*;
import org.eclipse.swt.graphics.*;
import org.eclipse.swt.widgets.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.custom.*;

public class Snippet111 {

public static void main (String [] args) {
	final Display display = new Display ();
	final Color black = display.getSystemColor (SWT.COLOR_BLACK);
	Shell shell = new Shell (display);
	shell.setLayout (new FillLayout ());
	final Tree tree = new Tree (shell, SWT.BORDER);
	for (int i=0; i<16; i++) {
		TreeItem itemI = new TreeItem (tree, SWT.NONE);
		itemI.setText ("Item " + i);
		for (int j=0; j<16; j++) {
			TreeItem itemJ = new TreeItem (itemI, SWT.NONE);
			itemJ.setText ("Item " + j);
		}
	}
	final TreeItem [] lastItem = new TreeItem [1];
	final TreeEditor editor = new TreeEditor (tree);
	tree.addListener (SWT.Selection, new Listener () {
		@Override
		public void handleEvent (Event event) {
			final TreeItem item = (TreeItem) event.item;
			if (item != null && item == lastItem [0]) {
				boolean showBorder = true;
				final Composite composite = new Composite (tree, SWT.NONE);
				if (showBorder) composite.setBackground (black);
				final Text text = new Text (composite, SWT.NONE);
				final int inset = showBorder ? 1 : 0;
				composite.addListener (SWT.Resize, new Listener () {
					@Override
					public void handleEvent (Event e) {
						Rectangle rect = composite.getClientArea ();
						text.setBounds (rect.x + inset, rect.y + inset, rect.width - inset * 2, rect.height - inset * 2);
					}
				});
				Listener textListener = new Listener () {
					@Override
					public void handleEvent (final Event e) {
						switch (e.type) {
							case SWT.FocusOut:
								item.setText (text.getText ());
								composite.dispose ();
								break;
							case SWT.Verify:
								String newText = text.getText ();
								String leftText = newText.substring (0, e.start);
								String rightText = newText.substring (e.end, newText.length ());
								GC gc = new GC (text);
								Point size = gc.textExtent (leftText + e.text + rightText);
								gc.dispose ();
								size = text.computeSize (size.x, SWT.DEFAULT);
								editor.horizontalAlignment = SWT.LEFT;
								Rectangle itemRect = item.getBounds (), rect = tree.getClientArea ();
								editor.minimumWidth = Math.max (size.x, itemRect.width) + inset * 2;
								int left = itemRect.x, right = rect.x + rect.width;
								editor.minimumWidth = Math.min (editor.minimumWidth, right - left);
								editor.minimumHeight = size.y + inset * 2;
								editor.layout ();
								break;
							case SWT.Traverse:
								switch (e.detail) {
									case SWT.TRAVERSE_RETURN:
										item.setText (text.getText ());
										//FALL THROUGH
									case SWT.TRAVERSE_ESCAPE:
										composite.dispose ();
										e.doit = false;
								}
								break;
						}
					}
				};
				text.addListener (SWT.FocusOut, textListener);
				text.addListener (SWT.Traverse, textListener);
				text.addListener (SWT.Verify, textListener);
				editor.setEditor (composite, item);
				text.setText (item.getText ());
				text.selectAll ();
				text.setFocus ();
			}
			lastItem [0] = item;
		}
	});
	shell.pack ();
	shell.open ();
	while (!shell.isDisposed()) {
		if (!display.readAndDispatch ()) display.sleep ();
	}
	display.dispose ();
}
}


text:
package controllers

import play.api.mvc._

object Application extends Controller {
  def index = TODO
}


text:
<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Cart extends CI_Controller {
    public function index(){

       if (isset($_SESSION['cartData'])) {
            $cartdata = $this->load_cartData();
            $cartdata = json_decode(json_encode($cartdata), True);
            $data['r'] = $cartdata;

       }

        $data['empty'] = true;

        $this->load->view('cart', $data);
    }

    private function load_cartData(){
        $pids = $this->session->userdata('cartData');

        $this->load->model('product');
        //$this->product->getRecord($pids, 'id');

        $result = array();
        foreach($pids as $pid){
            $result[] = $this->product->getRecord($pid, 'id');
        }

        return $result;
    }

}


text:
<?php
declare(strict_types=1);

namespace ManaPHP\Exception;

use ManaPHP\Exception;

class RuntimeException extends Exception
{

}


text:
package edu.northwestern.at.utils.math.distributions;

/*	Please see the license information at the end of this file. */

import edu.northwestern.at.utils.math.*;
import edu.northwestern.at.utils.math.rootfinders.*;

/**	Fisher's F distribution functions.
 */

public class FishersF
{
	/** Compute probability for Fisher's F distribution.
	 *
	 *	@param	f		Percentage point of Fisher's F distribution
	 *	@param	dfn		Numerator degrees of freedom
	 *	@param	dfd		Denominator degrees of freedom
	 *
	 *	@return			The corresponding probabiity for
	 *					Fisher's F distribution.
	 *
	 *	@throws		    IllegalArgumentException
	 *                  	if dfn <= 0 or dfd <= 0 .
	 *
	 *

	 *	fprob(f) = incompleteBeta( dfd/(dfd*f*dfn), df/2, dfn/2 )
	 *

	 *
	 *

	 *	The result is accurate to about 14 decimal digits.
	 *

	 */

	public static double f( double f , double dfn , double dfd )
		throws IllegalArgumentException
	{
		double result = 0.0D;

		if ( ( dfn > 0.0D ) && ( dfd > 0.0D ) )
		{
			result	=
				Beta.incompleteBeta
				(
					dfd / ( dfd + f * dfn ) ,
					dfd / 2.0D ,
					dfn / 2.0D ,
					Constants.MAXPREC
				);
		}
		else
		{
			throw new IllegalArgumentException( "dfn or dfd <= 0" );
		}

		return result;
	}

	/** Compute percentage point for Fisher's F distribution.
	 *
	 *	@param	p		Probability level for percentage point.
	 *	@param	dfn		Numerator degrees of freedom.
	 *	@param	dfd		Denominator degrees of freedom.
	 *
	 *	@return			The corresponding probabiity for Fisher's F
	 *					distribution.
	 *
	 *	@throws			IllegalArgumentException
	 *                  	if p < 0 or p > 1 or dfn <= 0 or dfd <= 0 .
	 *
	 *	@throws			ArithmeticException
	 *						if incomplete beta evaluation fails
	 */

	public static double fInverse( double p, double dfn, double dfd )
		throws IllegalArgumentException
	{
		double result	= 0.0D;

		if ( ( dfn > 0.0D ) && ( dfd > 0.0D ) )
		{
			if ( ( p >= 0.0D ) && ( p <= 1.0D ) )
			{
	            result	=
	            	Beta.incompleteBetaInverse( 1.0D - p , dfn / 2.0D , dfd / 2.0D );

				if ( ( result >= 0.0D ) && ( result < 1.0D ) )
				{
					result  = result * dfd / ( dfn * ( 1.0D - result ) );
				}
				else
				{
					throw new ArithmeticException(
						"inverse incomplete beta evaluation failed" );
				}
			}
			else
			{
				throw new IllegalArgumentException( "p < 0 or p > 1" );
			}
		}
		else
		{
			throw new IllegalArgumentException( "dfn or dfd <= 0" );
		}

		return result;
	}

	/**	Make class non-instantiable but inheritable.
	 */

	protected FishersF()
	{
	}
}

/*
 *

 * Copyright © 2004-2011 Northwestern University.
 *

 *

 * This program is free software; you can redistribute it
 * and/or modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *

 *

 * This program is distributed in the hope that it will be
 * useful, but WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
 * PURPOSE. See the GNU General Public License for more
 * details.
 *

 *

 * You should have received a copy of the GNU General Public
 * License along with this program; if not, write to the Free
 * Software Foundation, Inc., 59 Temple Place, Suite 330,
 * Boston, MA 02111-1307 USA.
 *

 */


text:
package org.apache.flink.streaming.tests.artificialstate;

import org.apache.flink.streaming.tests.DataStreamAllroundTestProgram;
import org.apache.flink.streaming.tests.Event;

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

/**
 * A state type used in the {@link DataStreamAllroundTestProgram}. Wraps an {@link Event} as state.
 */
public class ComplexPayload implements Serializable {
    private static final long serialVersionUID = 233624606545704853L;

    private final long eventTime;
    private final List<String> stringList;
    private final String strPayload;
    private final InnerPayLoad innerPayLoad;

    public ComplexPayload(Event event, String strPayload) {
        this.eventTime = event.getEventTime();
        this.innerPayLoad = new InnerPayLoad(event.getSequenceNumber());
        this.strPayload = strPayload;
        this.stringList = Arrays.asList(String.valueOf(event.getKey()), event.getPayload());
    }

    public ComplexPayload(Event event) {
        this(event, event.getPayload());
    }

    /** Nested class in state type. Wraps an {@link Event}'s sequence number. */
    public static class InnerPayLoad implements Serializable {

        private static final long serialVersionUID = 3986298180012117883L;

        private final long sequenceNumber;

        public InnerPayLoad(long sequenceNumber) {
            this.sequenceNumber = sequenceNumber;
        }

        public long getSequenceNumber() {
            return sequenceNumber;
        }
    }

    public long getEventTime() {
        return eventTime;
    }

    public List<String> getStringList() {
        return stringList;
    }

    public String getStrPayload() {
        return strPayload;
    }

    public InnerPayLoad getInnerPayLoad() {
        return innerPayLoad;
    }
}


text:
package com.gespofin.dao;

import com.gespofin.vo.ResultadoSpGespofin;

public interface Dao{

	public ResultadoSpGespofin actualizaCif();

	public ResultadoSpGespofin cargaArchivo(String nombreArchivo);

	public ResultadoSpGespofin cargaLetrasyBonos();

	public ResultadoSpGespofin copiaArchivosFilialInicioDia();

	public ResultadoSpGespofin copiaArchivosFilialInicioDiaAGV();

	public ResultadoSpGespofin correoInicioProcesoInicioDia();

	public ResultadoSpGespofin creaConversores();

	public ResultadoSpGespofin creaParaFecInicioDia();

	public ResultadoSpGespofin descargaPatrimonioEfectivo();
}


text:
/**********************
*** PARAMETERS FILE ***
**********************/

var parameters = new Object();
// SPARQL
// set user and password in case that the SPARQL endpoint requires them
//parameters.user = "";
//parameters.password = "";
// SPARQL endpoint
parameters.sparqlBase = "http://data.computas.com:3030/sparql";
parameters.sparqlLIMIT = 200;
parameters.sparqlLIMITinstance = 50;
// if greater, send the query with POST
parameters.maxSparqlLength = 6000;
// control the maximum field length in the results table
parameters.maxResultFieldLength = 120;
// if true, properties are hidden and thus forms are simplified
parameters.hidePropertiesMode = false;
// required or optional behavior in query building
parameters.optional = false;
// strategy for inclusion of literals in the query:
//  "limited": only the ones that form part of the query
//  "searchable": "limited" + the literals with the attribute "searchable"
//  "all":	every possible literal of an instance (not recommended)
parameters.literalQueryInclusion = "searchable";
// text engine
// NOTE: needs to be adjusted for each endpoint
parameters.autocompleteService = "http://sws.ifi.uio.no/solr/semicolon/suggest/";
// language
parameters.userlang = (window.navigator.userLanguage || window.navigator.language).substring(0,2);
parameters.deflang = "nb";
// logging (see http://docs.shopify.com/manual/configuration/store-customization/get-a-visitors-location)
parameters.geoipservice = "http://freegeoip.net/json/";
parameters.locallog = true;
// NOTE: remote logging needs a logging service
//parameters.logservice = "";
parameters.remotelog = false;


text:
<?php

namespace OC\Files\Storage;

/**
 * Storage backend class for providing common filesystem operation methods
 * which are not storage-backend specific.
 *
 * \OC\Files\Storage\Common is never used directly; it is extended by all other
 * storage backends, where its methods may be overridden, and additional
 * (backend-specific) methods are defined.
 *
 * Some \OC\Files\Storage\Common methods call functions which are first defined
 * in classes which extend it, e.g. $this->stat() .
 */

abstract class Common implements \OC\Files\Storage\Storage {
	protected $cache;
	protected $scanner;
	protected $permissioncache;
	protected $watcher;
	protected $storageCache;

	public function __construct($parameters) {
	}

	public function is_dir($path) {
		return $this->filetype($path) == 'dir';
	}

	public function is_file($path) {
		return $this->filetype($path) == 'file';
	}

	public function filesize($path) {
		if ($this->is_dir($path)) {
			return 0; //by definition
		} else {
			$stat = $this->stat($path);
			if (isset($stat['size'])) {
				return $stat['size'];
			} else {
				return 0;
			}
		}
	}

	public function isReadable($path) {
		// at least check whether it exists
		// subclasses might want to implement this more thoroughly
		return $this->file_exists($path);
	}

	public function isUpdatable($path) {
		// at least check whether it exists
		// subclasses might want to implement this more thoroughly
		// a non-existing file/folder isn't updatable
		return $this->file_exists($path);
	}

	public function isCreatable($path) {
		if ($this->is_dir($path) && $this->isUpdatable($path)) {
			return true;
		}
		return false;
	}

	public function isDeletable($path) {
		return $this->isUpdatable($path);
	}

	public function isSharable($path) {
		return $this->isReadable($path);
	}

	public function getPermissions($path) {
		$permissions = 0;
		if ($this->isCreatable($path)) {
			$permissions |= \OCP\PERMISSION_CREATE;
		}
		if ($this->isReadable($path)) {
			$permissions |= \OCP\PERMISSION_READ;
		}
		if ($this->isUpdatable($path)) {
			$permissions |= \OCP\PERMISSION_UPDATE;
		}
		if ($this->isDeletable($path)) {
			$permissions |= \OCP\PERMISSION_DELETE;
		}
		if ($this->isSharable($path)) {
			$permissions |= \OCP\PERMISSION_SHARE;
		}
		return $permissions;
	}

	public function filemtime($path) {
		$stat = $this->stat($path);
		if (isset($stat['mtime'])) {
			return $stat['mtime'];
		} else {
			return 0;
		}
	}

	public function file_get_contents($path) {
		$handle = $this->fopen($path, "r");
		if (!$handle) {
			return false;
		}
		$size = $this->filesize($path);
		if ($size == 0) {
			return '';
		}
		return fread($handle, $size);
	}

	public function file_put_contents($path, $data) {
		$handle = $this->fopen($path, "w");
		return fwrite($handle, $data);
	}

	public function rename($path1, $path2) {
		if ($this->copy($path1, $path2)) {
			return $this->unlink($path1);
		} else {
			return false;
		}
	}

	public function copy($path1, $path2) {
		$source = $this->fopen($path1, 'r');
		$target = $this->fopen($path2, 'w');
		list($count, $result) = \OC_Helper::streamCopy($source, $target);
		return $result;
	}

	/**
	 * @brief Deletes all files and folders recursively within a directory
	 * @param string $directory The directory whose contents will be deleted
	 * @param bool $empty Flag indicating whether directory will be emptied
	 * @returns bool
	 *
	 * @note By default the directory specified by $directory will be
	 * deleted together with its contents. To avoid this set $empty to true
	 */
	public function deleteAll($directory, $empty = false) {
		$directory = trim($directory, '/');
		if (!$this->is_dir($directory) || !$this->isReadable($directory)) {
			return false;
		} else {
			$directoryHandle = $this->opendir($directory);
			if (is_resource($directoryHandle)) {
				while (($contents = readdir($directoryHandle)) !== false) {
					if (!\OC\Files\Filesystem::isIgnoredDir($contents)) {
						$path = $directory . '/' . $contents;
						if ($this->is_dir($path)) {
							$this->deleteAll($path);
						} else {
							$this->unlink($path);
						}
					}
				}
			}
			if ($empty === false) {
				if (!$this->rmdir($directory)) {
					return false;
				}
			}
			return true;
		}

	}

	public function getMimeType($path) {
		if ($this->is_dir($path)) {
			return 'httpd/unix-directory';
		} elseif ($this->file_exists($path)) {
			return \OC_Helper::getFileNameMimeType($path);
		} else {
			return false;
		}
	}

	public function hash($type, $path, $raw = false) {
		$tmpFile = $this->getLocalFile($path);
		$hash = hash($type, $tmpFile, $raw);
		unlink($tmpFile);
		return $hash;
	}

	public function search($query) {
		return $this->searchInDir($query);
	}

	public function getLocalFile($path) {
		return $this->toTmpFile($path);
	}

	private function toTmpFile($path) { //no longer in the storage api, still useful here
		$source = $this->fopen($path, 'r');
		if (!$source) {
			return false;
		}
		if ($pos = strrpos($path, '.')) {
			$extension = substr($path, $pos);
		} else {
			$extension = '';
		}
		$tmpFile = \OC_Helper::tmpFile($extension);
		$target = fopen($tmpFile, 'w');
		\OC_Helper::streamCopy($source, $target);
		return $tmpFile;
	}

	public function getLocalFolder($path) {
		$baseDir = \OC_Helper::tmpFolder();
		$this->addLocalFolder($path, $baseDir);
		return $baseDir;
	}

	private function addLocalFolder($path, $target) {
		$dh = $this->opendir($path);
		if (is_resource($dh)) {
			while (($file = readdir($dh)) !== false) {
				if ($file !== '.' and $file !== '..') {
					if ($this->is_dir($path . '/' . $file)) {
						mkdir($target . '/' . $file);
						$this->addLocalFolder($path . '/' . $file, $target . '/' . $file);
					} else {
						$tmp = $this->toTmpFile($path . '/' . $file);
						rename($tmp, $target . '/' . $file);
					}
				}
			}
		}
	}

	protected function searchInDir($query, $dir = '') {
		$files = array();
		$dh = $this->opendir($dir);
		if (is_resource($dh)) {
			while (($item = readdir($dh)) !== false) {
				if ($item == '.' || $item == '..') continue;
				if (strstr(strtolower($item), strtolower($query)) !== false) {
					$files[] = $dir . '/' . $item;
				}
				if ($this->is_dir($dir . '/' . $item)) {
					$files = array_merge($files, $this->searchInDir($query, $dir . '/' . $item));
				}
			}
		}
		return $files;
	}

	/**
	 * check if a file or folder has been updated since $time
	 *
	 * @param string $path
	 * @param int $time
	 * @return bool
	 */
	public function hasUpdated($path, $time) {
		return $this->filemtime($path) > $time;
	}

	public function getCache($path = '') {
		if (!isset($this->cache)) {
			$this->cache = new \OC\Files\Cache\Cache($this);
		}
		return $this->cache;
	}

	public function getScanner($path = '') {
		if (!isset($this->scanner)) {
			$this->scanner = new \OC\Files\Cache\Scanner($this);
		}
		return $this->scanner;
	}

	public function getPermissionsCache($path = '') {
		if (!isset($this->permissioncache)) {
			$this->permissioncache = new \OC\Files\Cache\Permissions($this);
		}
		return $this->permissioncache;
	}

	public function getWatcher($path = '') {
		if (!isset($this->watcher)) {
			$this->watcher = new \OC\Files\Cache\Watcher($this);
		}
		return $this->watcher;
	}

	public function getStorageCache() {
		if (!isset($this->storageCache)) {
			$this->storageCache = new \OC\Files\Cache\Storage($this);
		}
		return $this->storageCache;
	}

	/**
	 * get the owner of a path
	 *
	 * @param string $path The path to get the owner
	 * @return string uid or false
	 */
	public function getOwner($path) {
		return \OC_User::getUser();
	}

	/**
	 * get the ETag for a file or folder
	 *
	 * @param string $path
	 * @return string
	 */
	public function getETag($path) {
		$ETagFunction = \OC_Connector_Sabre_Node::$ETagFunction;
		if ($ETagFunction) {
			$hash = call_user_func($ETagFunction, $path);
			return $hash;
		} else {
			return uniqid();
		}
	}

	/**
	 * clean a path, i.e. remove all redundant '.' and '..'
	 * making sure that it can't point to higher than '/'
	 *
	 * @param $path The path to clean
	 * @return string cleaned path
	 */
	public function cleanPath($path) {
		if (strlen($path) == 0 or $path[0] != '/') {
			$path = '/' . $path;
		}

		$output = array();
		foreach (explode('/', $path) as $chunk) {
			if ($chunk == '..') {
				array_pop($output);
			} else if ($chunk == '.') {
			} else {
				$output[] = $chunk;
			}
		}
		return implode('/', $output);
	}

	public function test() {
		if ($this->stat('')) {
			return true;
		}
		return false;
	}

	/**
	 * get the free space in the storage
	 *
	 * @param $path
	 * @return int
	 */
	public function free_space($path) {
		return \OC\Files\SPACE_UNKNOWN;
	}
}


text:
MathJax.Localization.addTranslation("diq","FontWarnings",{
        version: "2.7.1",
        isLoaded: true,
        strings: {

        }
});

MathJax.Ajax.loadComplete("[MathJax]/localization/diq/FontWarnings.js");


text:
<?php
namespace Joah\Forum;

/**
 * Model for Votes.
 *
 */
class Vote extends \Anax\MVC\CDatabaseModel
{

    /*
    *  Fetch vote sum
    *
    */
    public function showVoteSum($type, $id)
    {
        // $this->db->setVerbose();
        // fetch sum
        $sql = "SELECT sum(points) AS vote_sum
                FROM {$this->getSource()}
                WHERE points IS NOT NULL AND vote_type = ? AND vote_on = ?";

        $params = [$type, $id];

        $res = $this->db->executeFetchAll($sql, $params);

        // set empty to 0
        $res[0]->vote_sum = empty($res[0]->vote_sum) ? 0 :$res[0]->vote_sum;

        return $res[0]->vote_sum;
    }

    /*
    *  Vote
    *
    *  @param array $values, with keys vote_type, vote_on and user_id. Ex ['vote_type' => 1, 'vote_on' => 1, 'user_id' => 1, 'points' => 1]
    *
    *  @return void
    *
    */
    public function vote($values)
    {

        // fetch pervious vote if any
        $this->fetchVote($values);

        // replace with voting new info
        $this->setProperties($values);

        // fetch values, if there was a previous vote info from there was fetched and replaced with new
        $values = $this->getProperties();

        // update or create a new vote
        if (isset($values['id'])) {
            return $this->update($values);
        } else {
            return $this->create($values);
        }
    }

    /*
    *  fetch vote
    *
    * $param array $values, with keys vote_type, vote_on and user_id. Example ['vote_type' => 1, 'vote_on' => 1, 'user_id' => 1]
    *
    * @return void
    */
    public function fetchVote($values)
    {
        // fetch vote
        $sql = "SELECT *
                FROM {$this->getSource()}
                WHERE vote_type = ? AND vote_on = ? AND user_id = ?";

        $params = [$values['vote_type'], $values['vote_on'], $values['user_id']];

        // $res = $this->db->executeFetchAll($sql, $params);
        $this->db->execute($sql, $params);
        $this->db->fetchInto($this);
    }

    /*
    *  Fetch votes by user
    *
    * $param int user_id
    *
    * @return array
    */
    public function fetchVotesByUser($user_id)
    {
        // count votes
        $sql = "SELECT count(user_id) AS vote_count
                FROM {$this->getSource()}
                WHERE user_id = ?";

        $params = [$user_id];

        $res = $this->db->executeFetchAll($sql, $params);
        return $res;
    }

    /*
    *  Fetch votes by user divided into positive, negative, and sum.
    *
    * $param int user_id
    *
    * @return array
    */
    public function countPosNegVotesByUser($user_id)
    {
        // count positive and negative votes separately
        $sql = "SELECT sum(CASE WHEN points = 1 THEN 1 ELSE 0 END) AS pos_votes,
                sum(CASE WHEN points = -1 THEN 1 ELSE 0 END) AS neg_votes,
                sum(points) AS sum
                FROM vote
                WHERE user_id = ?";

        $params = [$user_id];

        $res = $this->db->executeFetchAll($sql, $params);
        return $res;
    }

    /*
    *  Fetch votes on question/answer/comment
    *
    * $params int vote_type, int vote_on
    *
    * @return array int
    */
    public function fetchVotesOn($vote_type, $vote_on)
    {
        // count votes
        $sql = "SELECT points
                FROM {$this->getSource()}
                WHERE vote_type = ? AND vote_on = ?";

        $params = [$vote_type, $vote_on];

        $res = $this->db->executeFetchAll($sql, $params);
        return $res;
    }

}


text:
package ro.gov.ithub.infotranspub.tools.transcoder.metrorex.decode;

import java.util.HashMap;
import java.util.Vector;

public class TableHeader {

    public static final String FIRST_COLUMN = "First";
    public static final String LAST_COLUMN = "Last";

    public static final int FIRST_COLUMN_POSITION = 1000;
    public static final int LAST_COLUMN_POSITION = -1000;

    private Vector<Node> columns = null;
    private HashMap<String, String>  columnPositions;
    private HashMap<String, String>  reverseColumnPositions;

    private int firstColumn = FIRST_COLUMN_POSITION;
    private int lastColumn = LAST_COLUMN_POSITION;

    {
        columns = new Vector<Node>();
        columnPositions = new HashMap<String, String>();
        reverseColumnPositions = new HashMap<String,String>();
    }

    public TableHeader(){
    }

    public void add(Node column, int columnPosition){
        columns.add(column);
        columnPositions.put(column.getValue(), Integer.toString(columnPosition));
        reverseColumnPositions.put(Integer.toString(columnPosition),column.getValue());
    }

    public void recalcColumnPositions(){
        Node firstNode = null;
        Node lastNode = null;

        for  (Node node:columns){
            if ( node.getPosition().getCol() < firstColumn){
                firstColumn = node.getPosition().getCol();
                firstNode = node;
                firstNode.setValue(FIRST_COLUMN);
            }

            if ( node.getPosition().getCol() > lastColumn) {
                lastColumn = node.getPosition().getCol();
                lastNode = node;
                lastNode.setValue(LAST_COLUMN);
            }
        }

        columnPositions = new HashMap<String, String>();
        reverseColumnPositions = new HashMap<String,String>();

        columnPositions.put(FIRST_COLUMN, Integer.toString(firstNode.getPosition().getCol()));
        columnPositions.put(LAST_COLUMN, Integer.toString(lastNode.getPosition().getCol()));

        reverseColumnPositions.put(Integer.toString(firstNode.getPosition().getCol()),FIRST_COLUMN);
        reverseColumnPositions.put(Integer.toString(lastNode.getPosition().getCol()),LAST_COLUMN);

    }

    public int getFirstColumn(){ return firstColumn; }
    public int getLastColumn() { return lastColumn; }

    public Vector<Node> getColumns(){
        return columns;
    }
    public int positionByName(String name){
        return Integer.parseInt(columnPositions.get(name));
    }
    public String nameByPosition(int position){
        return reverseColumnPositions.get(Integer.toString(position));
    }

    public boolean isValidColumn( int columnPosition){
        if ( columnPosition == firstColumn || columnPosition == lastColumn)
            return true;
        return false;
    }
}


text: Generates a feed of aggregated news items in JSON format from a list of RSS feed URLs


text:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class TestServerSocket {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try{
			ServerSocket serv = new ServerSocket(1468);
			Socket client = serv.accept();
			//client accepts input, do nothing and close on the 5th input
			BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
			int i = 0;
			String in = br.readLine();
			while(in != null){
				if(i++ ==50){
					break;
				}
				in = br.readLine();
				System.out.println("Server: " + in);
			}
			System.out.println("Server exiting");
			client.close();
			serv.close();

		}catch (Exception e) {
			e.printStackTrace();
		}

	}

}


text:
!< FOODIE utils: module of (possible) unrelated utilities of FOODIE library.

module foodie_utils
!< FOODIE utils: module of (possible) unrelated utilities of FOODIE library.

use penf, only : I_P

implicit none
private
public :: is_admissible

contains
  ! public procedures
  elemental function is_admissible(n, adm_range)
  !< Check if the queried number *n* is admitted by the *admissible* range list *adm_range*.
  !<
  !< The admissible range list must be formatted as string containing admissible numbers; valid list are:
  !<+ `adm_range = '1-5'` => 1, 2, 3, 4, 5 are admissible numbers;
  !<+ `adm_range = '1,3,5,10-12'` => 1, 3, 5, 10, 11, 12 are admissible numbers;
  !<+ `adm_range = '1-4,8,21-22'` => 1, 2, 3, 4, 8, 21, 22 are admissible numbers;
  !<
  !< You can mix any number of range (`min-max` format) and/or single number (`,` comma separated) entries.
  integer(I_P), intent(IN)               :: n             !< Number queried.
  character(*), intent(IN)               :: adm_range     !< Admissible range string.
  logical                                :: is_admissible !< Is true is the number is in *adm_range*.
  character(len(adm_range)), allocatable :: tokens(:)     !< Tokens for parsing *adm_range* string.
  character(len(adm_range)), allocatable :: subtokens(:)  !< Tokens for parsing *adm_range* string.
  integer(I_P)                           :: t             !< Counter.
  integer(I_P)                           :: n_parsed(1:2) !< Values parsed from *adm_range*..

  is_admissible = .false.
  call tokenize(string=adm_range, delimiter=',', toks=tokens)
  search_me : do t=1, size(tokens)
    if (index(tokens(t), '-')>0) then
      call tokenize(string=tokens(t), delimiter='-', toks=subtokens)
      read(subtokens(1), *) n_parsed(1)
      read(subtokens(2), *) n_parsed(2)
      is_admissible = (n_parsed(1)<=n.and.n<=n_parsed(2))
    else
      read(tokens(t), *) n_parsed(1)
      is_admissible = (n_parsed(1)==n)
    endif
    if (is_admissible) exit search_me
  enddo search_me
  endfunction is_admissible

  ! private procedures
  pure subroutine tokenize(string, delimiter, toks, Nt)
  !< Tokenize a string in order to parse it.
  !<
  !< @note The dummy array containing tokens must be allocatable and its character elements must have the same length of the input
  !< string. If the length of the delimiter is higher than the input string one then the output tokens array is allocated with
  !< only one element set to char(0).
  character(len=*),                        intent(IN)  :: string    !< String to be tokenized.
  character(len=*),                        intent(IN)  :: delimiter !< Delimiter of tokens.
  character(len=len(string)), allocatable, intent(OUT) :: toks(:)   !< Tokens.
  integer(I_P), optional,                  intent(OUT) :: Nt        !< Number of tokens.
  character(len=len(string))                           :: strsub    !< Temporary string.
  integer(I_P)                                         :: dlen      !< Delimiter length.
  integer(I_P)                                         :: c         !< Counter.
  integer(I_P)                                         :: n         !< Counter.
  integer(I_P)                                         :: t         !< Counter.

  ! initialize
  if (allocated(toks)) deallocate(toks)
  strsub = string
  dlen = len(delimiter)
  if (dlen>len(string)) then
    allocate(toks(1:1))
    toks(1) = char(0)
    if (present(Nt)) Nt = 1
    return
  endif

  ! compute the number of tokens
  n = 1
  do c=1, len(strsub) - dlen ! loop over string characters
    if (strsub(c:c+dlen-1)==delimiter) n = n + 1
  enddo
  allocate(toks(1:n))

  ! tokenize
  do t=1, n ! loop over tokens
    c = index(strsub, delimiter)
    if (c>0) then
      toks(t) = strsub(1:c-1)
      strsub = strsub(c+dlen:)
    else
      toks(t) = strsub
    endif
  enddo
  if (present(Nt)) Nt = n
  endsubroutine tokenize
endmodule foodie_utils


text:
namespace capnp {

namespace _ {  // private
  class ReaderArena;
  class BuilderArena;
}

class StructSchema;
class Orphanage;
template <typename T>
class Orphan;

// =======================================================================================

struct ReaderOptions {
  // Options controlling how data is read.

  uint64_t traversalLimitInWords = 8 * 1024 * 1024;
  // Limits how many total words of data are allowed to be traversed.  Traversal is counted when
  // a new struct or list builder is obtained, e.g. from a get() accessor.  This means that calling
  // the getter for the same sub-struct multiple times will cause it to be double-counted.  Once
  // the traversal limit is reached, an error will be reported.
  //
  // This limit exists for security reasons.  It is possible for an attacker to construct a message
  // in which multiple pointers point at the same location.  This is technically invalid, but hard
  // to detect.  Using such a message, an attacker could cause a message which is small on the wire
  // to appear much larger when actually traversed, possibly exhausting server resources leading to
  // denial-of-service.
  //
  // It makes sense to set a traversal limit that is much larger than the underlying message.
  // Together with sensible coding practices (e.g. trying to avoid calling sub-object getters
  // multiple times, which is expensive anyway), this should provide adequate protection without
  // inconvenience.
  //
  // The default limit is 64 MiB.  This may or may not be a sensible number for any given use case,
  // but probably at least prevents easy exploitation while also avoiding causing problems in most
  // typical cases.

  int nestingLimit = 64;
  // Limits how deeply-nested a message structure can be, e.g. structs containing other structs or
  // lists of structs.
  //
  // Like the traversal limit, this limit exists for security reasons.  Since it is common to use
  // recursive code to traverse recursive data structures, an attacker could easily cause a stack
  // overflow by sending a very-deeply-nested (or even cyclic) message, without the message even
  // being very large.  The default limit of 64 is probably low enough to prevent any chance of
  // stack overflow, yet high enough that it is never a problem in practice.
};

class MessageReader {
  // Abstract interface for an object used to read a Cap'n Proto message.  Subclasses of
  // MessageReader are responsible for reading the raw, flat message content.  Callers should
  // usually call `messageReader.getRoot<MyStructType>()` to get a `MyStructType::Reader`
  // representing the root of the message, then use that to traverse the message content.
  //
  // Some common subclasses of `MessageReader` include `SegmentArrayMessageReader`, whose
  // constructor accepts pointers to the raw data, and `StreamFdMessageReader` (from
  // `serialize.h`), which reads the message from a file descriptor.  One might implement other
  // subclasses to handle things like reading from shared memory segments, mmap()ed files, etc.

public:
  MessageReader(ReaderOptions options);
  // It is suggested that subclasses take ReaderOptions as a constructor parameter, but give it a
  // default value of "ReaderOptions()".  The base class constructor doesn't have a default value
  // in order to remind subclasses that they really need to give the user a way to provide this.

  virtual ~MessageReader() noexcept(false);

  virtual kj::ArrayPtr<const word> getSegment(uint id) = 0;
  // Gets the segment with the given ID, or returns null if no such segment exists. This method
  // will be called at most once for each segment ID.

  inline const ReaderOptions& getOptions();
  // Get the options passed to the constructor.

  template <typename RootType>
  typename RootType::Reader getRoot();
  // Get the root struct of the message, interpreting it as the given struct type.

  template <typename RootType, typename SchemaType>
  typename RootType::Reader getRoot(SchemaType schema);
  // Dynamically interpret the root struct of the message using the given schema (a StructSchema).
  // RootType in this case must be DynamicStruct, and you must #include <capnp/dynamic.h> to
  // use this.

  bool isCanonical();
  // Returns whether the message encoded in the reader is in canonical form.

private:
  ReaderOptions options;

  // Space in which we can construct a ReaderArena.  We don't use ReaderArena directly here
  // because we don't want clients to have to #include arena.h, which itself includes a bunch of
  // big STL headers.  We don't use a pointer to a ReaderArena because that would require an
  // extra malloc on every message which could be expensive when processing small messages.
  void* arenaSpace[15 + sizeof(kj::MutexGuarded<void*>) / sizeof(void*)];
  bool allocatedArena;

  _::ReaderArena* arena() { return reinterpret_cast<_::ReaderArena*>(arenaSpace); }
  AnyPointer::Reader getRootInternal();
};

class MessageBuilder {
  // Abstract interface for an object used to allocate and build a message.  Subclasses of
  // MessageBuilder are responsible for allocating the space in which the message will be written.
  // The most common subclass is `MallocMessageBuilder`, but other subclasses may be used to do
  // tricky things like allocate messages in shared memory or mmap()ed files.
  //
  // Creating a new message ususually means allocating a new MessageBuilder (ideally on the stack)
  // and then calling `messageBuilder.initRoot<MyStructType>()` to get a `MyStructType::Builder`.
  // That, in turn, can be used to fill in the message content.  When done, you can call
  // `messageBuilder.getSegmentsForOutput()` to get a list of flat data arrays containing the
  // message.

public:
  MessageBuilder();
  virtual ~MessageBuilder() noexcept(false);
  KJ_DISALLOW_COPY(MessageBuilder);

  struct SegmentInit {
    kj::ArrayPtr<word> space;

    size_t wordsUsed;
    // Number of words in `space` which are used; the rest are free space in which additional
    // objects may be allocated.
  };

  explicit MessageBuilder(kj::ArrayPtr<SegmentInit> segments);
  // Create a MessageBuilder backed by existing memory. This is an advanced interface that most
  // people should not use. THIS METHOD IS INSECURE; see below.
  //
  // This allows a MessageBuilder to be constructed to modify an in-memory message without first
  // making a copy of the content. This is especially useful in conjunction with mmap().
  //
  // The contents of each segment must outlive the MessageBuilder, but the SegmentInit array itself
  // only need outlive the constructor.
  //
  // SECURITY: Do not use this in conjunction with untrusted data. This constructor assumes that
  //   the input message is valid. This constructor is designed to be used with data you control,
  //   e.g. an mmap'd file which is owned and accessed by only one program. When reading data you
  //   do not trust, you *must* load it into a Reader and then copy into a Builder as a means of
  //   validating the content.
  //
  // WARNING: It is NOT safe to initialize a MessageBuilder in this way from memory that is
  //   currently in use by another MessageBuilder or MessageReader. Other readers/builders will
  //   not observe changes to the segment sizes nor newly-allocated segments caused by allocating
  //   new objects in this message.

  virtual kj::ArrayPtr<word> allocateSegment(uint minimumSize) = 0;
  // Allocates an array of at least the given number of words, throwing an exception or crashing if
  // this is not possible.  It is expected that this method will usually return more space than
  // requested, and the caller should use that extra space as much as possible before allocating
  // more.  The returned space remains valid at least until the MessageBuilder is destroyed.
  //
  // Cap'n Proto will only call this once at a time, so the subclass need not worry about
  // thread-safety.

  template <typename RootType>
  typename RootType::Builder initRoot();
  // Initialize the root struct of the message as the given struct type.

  template <typename Reader>
  void setRoot(Reader&& value);
  // Set the root struct to a deep copy of the given struct.

  template <typename RootType>
  typename RootType::Builder getRoot();
  // Get the root struct of the message, interpreting it as the given struct type.

  template <typename RootType, typename SchemaType>
  typename RootType::Builder getRoot(SchemaType schema);
  // Dynamically interpret the root struct of the message using the given schema (a StructSchema).
  // RootType in this case must be DynamicStruct, and you must #include <capnp/dynamic.h> to
  // use this.

  template <typename RootType, typename SchemaType>
  typename RootType::Builder initRoot(SchemaType schema);
  // Dynamically init the root struct of the message using the given schema (a StructSchema).
  // RootType in this case must be DynamicStruct, and you must #include <capnp/dynamic.h> to
  // use this.

  template <typename T>
  void adoptRoot(Orphan<T>&& orphan);
  // Like setRoot() but adopts the orphan without copying.

  kj::ArrayPtr<const kj::ArrayPtr<const word>> getSegmentsForOutput();
  // Get the raw data that makes up the message.

  Orphanage getOrphanage();

  bool isCanonical();
  // Check whether the message builder is in canonical form

private:
  void* arenaSpace[22];
  // Space in which we can construct a BuilderArena.  We don't use BuilderArena directly here
  // because we don't want clients to have to #include arena.h, which itself includes a bunch of
  // big STL headers.  We don't use a pointer to a BuilderArena because that would require an
  // extra malloc on every message which could be expensive when processing small messages.

  bool allocatedArena = false;
  // We have to initialize the arena lazily because when we do so we want to allocate the root
  // pointer immediately, and this will allocate a segment, which requires a virtual function
  // call on the MessageBuilder.  We can't do such a call in the constructor since the subclass
  // isn't constructed yet.  This is kind of annoying because it means that getOrphanage() is
  // not thread-safe, but that shouldn't be a huge deal...

  _::BuilderArena* arena() { return reinterpret_cast<_::BuilderArena*>(arenaSpace); }
  _::SegmentBuilder* getRootSegment();
  AnyPointer::Builder getRootInternal();
};

template <typename RootType>
typename RootType::Reader readMessageUnchecked(const word* data);
// IF THE INPUT IS INVALID, THIS MAY CRASH, CORRUPT MEMORY, CREATE A SECURITY HOLE IN YOUR APP,
// MURDER YOUR FIRST-BORN CHILD, AND/OR BRING ABOUT ETERNAL DAMNATION ON ALL OF HUMANITY.  DO NOT
// USE UNLESS YOU UNDERSTAND THE CONSEQUENCES.
//
// Given a pointer to a known-valid message located in a single contiguous memory segment,
// returns a reader for that message.  No bounds-checking will be done while traversing this
// message.  Use this only if you have already verified that all pointers are valid and in-bounds,
// and there are no far pointers in the message.
//
// To create a message that can be passed to this function, build a message using a MallocAllocator
// whose preferred segment size is larger than the message size.  This guarantees that the message
// will be allocated as a single segment, meaning getSegmentsForOutput() returns a single word
// array.  That word array is your message; you may pass a pointer to its first word into
// readMessageUnchecked() to read the message.
//
// This can be particularly handy for embedding messages in generated code:  you can
// embed the raw bytes (using AlignedData) then make a Reader for it using this.  This is the way
// default values are embedded in code generated by the Cap'n Proto compiler.  E.g., if you have
// a message MyMessage, you can read its default value like so:
//    MyMessage::Reader reader = Message<MyMessage>::readMessageUnchecked(MyMessage::DEFAULT.words);
//
// To sanitize a message from an untrusted source such that it can be safely passed to
// readMessageUnchecked(), use copyToUnchecked().

template <typename Reader>
void copyToUnchecked(Reader&& reader, kj::ArrayPtr<word> uncheckedBuffer);
// Copy the content of the given reader into the given buffer, such that it can safely be passed to
// readMessageUnchecked().  The buffer's size must be exactly reader.totalSizeInWords() + 1,
// otherwise an exception will be thrown.  The buffer must be zero'd before calling.

template <typename RootType>
typename RootType::Reader readDataStruct(kj::ArrayPtr<const word> data);
// Interprets the given data as a single, data-only struct. Only primitive fields (booleans,
// numbers, and enums) will be readable; all pointers will be null. This is useful if you want
// to use Cap'n Proto as a language/platform-neutral way to pack some bits.
//
// The input is a word array rather than a byte array to enforce alignment. If you have a byte
// array which you know is word-aligned (or if your platform supports unaligned reads and you don't
// mind the performance penalty), then you can use `reinterpret_cast` to convert a byte array into
// a word array:
//
//     kj::arrayPtr(reinterpret_cast<const word*>(bytes.begin()),
//                  reinterpret_cast<const word*>(bytes.end()))

template <typename BuilderType>
typename kj::ArrayPtr<const word> writeDataStruct(BuilderType builder);
// Given a struct builder, get the underlying data section as a word array, suitable for passing
// to `readDataStruct()`.
//
// Note that you may call `.toBytes()` on the returned value to convert to `ArrayPtr<const byte>`.

template <typename Type>
static typename Type::Reader defaultValue();
// Get a default instance of the given struct or list type.
//
// TODO(cleanup):  Find a better home for this function?

// =======================================================================================

class SegmentArrayMessageReader: public MessageReader {
  // A simple MessageReader that reads from an array of word arrays representing all segments.
  // In particular you can read directly from the output of MessageBuilder::getSegmentsForOutput()
  // (although it would probably make more sense to call builder.getRoot().asReader() in that case).

public:
  SegmentArrayMessageReader(kj::ArrayPtr<const kj::ArrayPtr<const word>> segments,
                            ReaderOptions options = ReaderOptions());
  // Creates a message pointing at the given segment array, without taking ownership of the
  // segments.  All arrays passed in must remain valid until the MessageReader is destroyed.

  KJ_DISALLOW_COPY(SegmentArrayMessageReader);
  ~SegmentArrayMessageReader() noexcept(false);

  virtual kj::ArrayPtr<const word> getSegment(uint id) override;

private:
  kj::ArrayPtr<const kj::ArrayPtr<const word>> segments;
};

enum class AllocationStrategy: uint8_t {
  FIXED_SIZE,
  // The builder will prefer to allocate the same amount of space for each segment with no
  // heuristic growth.  It will still allocate larger segments when the preferred size is too small
  // for some single object.  This mode is generally not recommended, but can be particularly useful
  // for testing in order to force a message to allocate a predictable number of segments.  Note
  // that you can force every single object in the message to be located in a separate segment by
  // using this mode with firstSegmentWords = 0.

  GROW_HEURISTICALLY
  // The builder will heuristically decide how much space to allocate for each segment.  Each
  // allocated segment will be progressively larger than the previous segments on the assumption
  // that message sizes are exponentially distributed.  The total number of segments that will be
  // allocated for a message of size n is O(log n).
};

constexpr uint SUGGESTED_FIRST_SEGMENT_WORDS = 1024;
constexpr AllocationStrategy SUGGESTED_ALLOCATION_STRATEGY = AllocationStrategy::GROW_HEURISTICALLY;

class MallocMessageBuilder: public MessageBuilder {
  // A simple MessageBuilder that uses malloc() (actually, calloc()) to allocate segments.  This
  // implementation should be reasonable for any case that doesn't require writing the message to
  // a specific location in memory.

public:
  explicit MallocMessageBuilder(uint firstSegmentWords = SUGGESTED_FIRST_SEGMENT_WORDS,
      AllocationStrategy allocationStrategy = SUGGESTED_ALLOCATION_STRATEGY);
  // Creates a BuilderContext which allocates at least the given number of words for the first
  // segment, and then uses the given strategy to decide how much to allocate for subsequent
  // segments.  When choosing a value for firstSegmentWords, consider that:
  // 1) Reading and writing messages gets slower when multiple segments are involved, so it's good
  //    if most messages fit in a single segment.
  // 2) Unused bytes will not be written to the wire, so generally it is not a big deal to allocate
  //    more space than you need.  It only becomes problematic if you are allocating many messages
  //    in parallel and thus use lots of memory, or if you allocate so much extra space that just
  //    zeroing it out becomes a bottleneck.
  // The defaults have been chosen to be reasonable for most people, so don't change them unless you
  // have reason to believe you need to.

  explicit MallocMessageBuilder(kj::ArrayPtr<word> firstSegment,
      AllocationStrategy allocationStrategy = SUGGESTED_ALLOCATION_STRATEGY);
  // This version always returns the given array for the first segment, and then proceeds with the
  // allocation strategy.  This is useful for optimization when building lots of small messages in
  // a tight loop:  you can reuse the space for the first segment.
  //
  // firstSegment MUST be zero-initialized.  MallocMessageBuilder's destructor will write new zeros
  // over any space that was used so that it can be reused.

  KJ_DISALLOW_COPY(MallocMessageBuilder);
  virtual ~MallocMessageBuilder() noexcept(false);

  virtual kj::ArrayPtr<word> allocateSegment(uint minimumSize) override;

private:
  uint nextSize;
  AllocationStrategy allocationStrategy;

  bool ownFirstSegment;
  bool returnedFirstSegment;

  void* firstSegment;

  struct MoreSegments;
  kj::Maybe<kj::Own<MoreSegments>> moreSegments;
};

class FlatMessageBuilder: public MessageBuilder {
  // THIS IS NOT THE CLASS YOU'RE LOOKING FOR.
  //
  // If you want to write a message into already-existing scratch space, use `MallocMessageBuilder`
  // and pass the scratch space to its constructor.  It will then only fall back to malloc() if
  // the scratch space is not large enough.
  //
  // Do NOT use this class unless you really know what you're doing.  This class is problematic
  // because it requires advance knowledge of the size of your message, which is usually impossible
  // to determine without actually building the message.  The class was created primarily to
  // implement `copyToUnchecked()`, which itself exists only to support other internal parts of
  // the Cap'n Proto implementation.

public:
  explicit FlatMessageBuilder(kj::ArrayPtr<word> array);
  KJ_DISALLOW_COPY(FlatMessageBuilder);
  virtual ~FlatMessageBuilder() noexcept(false);

  void requireFilled();
  // Throws an exception if the flat array is not exactly full.

  virtual kj::ArrayPtr<word> allocateSegment(uint minimumSize) override;

private:
  kj::ArrayPtr<word> array;
  bool allocated;
};

// =======================================================================================
// implementation details

inline const ReaderOptions& MessageReader::getOptions() {
  return options;
}

template <typename RootType>
inline typename RootType::Reader MessageReader::getRoot() {
  return getRootInternal().getAs<RootType>();
}

template <typename RootType>
inline typename RootType::Builder MessageBuilder::initRoot() {
  return getRootInternal().initAs<RootType>();
}

template <typename Reader>
inline void MessageBuilder::setRoot(Reader&& value) {
  getRootInternal().setAs<FromReader<Reader>>(value);
}

template <typename RootType>
inline typename RootType::Builder MessageBuilder::getRoot() {
  return getRootInternal().getAs<RootType>();
}

template <typename T>
void MessageBuilder::adoptRoot(Orphan<T>&& orphan) {
  return getRootInternal().adopt(kj::mv(orphan));
}

template <typename RootType, typename SchemaType>
typename RootType::Reader MessageReader::getRoot(SchemaType schema) {
  return getRootInternal().getAs<RootType>(schema);
}

template <typename RootType, typename SchemaType>
typename RootType::Builder MessageBuilder::getRoot(SchemaType schema) {
  return getRootInternal().getAs<RootType>(schema);
}

template <typename RootType, typename SchemaType>
typename RootType::Builder MessageBuilder::initRoot(SchemaType schema) {
  return getRootInternal().initAs<RootType>(schema);
}

template <typename RootType>
typename RootType::Reader readMessageUnchecked(const word* data) {
  return AnyPointer::Reader(_::PointerReader::getRootUnchecked(data)).getAs<RootType>();
}

template <typename Reader>
void copyToUnchecked(Reader&& reader, kj::ArrayPtr<word> uncheckedBuffer) {
  FlatMessageBuilder builder(uncheckedBuffer);
  builder.setRoot(kj::fwd<Reader>(reader));
  builder.requireFilled();
}

template <typename RootType>
typename RootType::Reader readDataStruct(kj::ArrayPtr<const word> data) {
  return typename RootType::Reader(_::StructReader(data));
}

template <typename BuilderType>
typename kj::ArrayPtr<const word> writeDataStruct(BuilderType builder) {
  auto bytes = _::PointerHelpers<FromBuilder<BuilderType>>::getInternalBuilder(kj::mv(builder))
      .getDataSectionAsBlob();
  return kj::arrayPtr(reinterpret_cast<word*>(bytes.begin()),
                      reinterpret_cast<word*>(bytes.end()));
}

template <typename Type>
static typename Type::Reader defaultValue() {
  return typename Type::Reader(_::StructReader());
}

template <typename T>
kj::Array<word> canonicalize(T&& reader) {
    return _::PointerHelpers<FromReader<T>>::getInternalReader(reader).canonicalize();
}

}  // namespace capnp

#endif  // CAPNP_MESSAGE_H_


text:
Add category scope of work

      <?php echo $this->session->flashdata('message'); ?>
      <form class="form-horizontal" action="/insert_add_scopework" method="post">

            scope of work

              <input type="text" name="scopework" value="" class="form-control">

                  <button type="submit" class="btn btn-success" name="button">Save</button>
                  Cancel

      </form>

         Scope of Work
         Action

         <?php foreach ($this->common->select_scopework() as $key => $value):
           extract ($value);
           ?>

            <?php echo $scopework ?>

              Edit
                <a  class="a-table label label-danger" href="/del_scope_work/<?php echo $id ?>">Delete

         <?php endforeach; ?>


text:
const mongoose = require('mongoose'),
TimeSlot = require('./TimeSlot'),
Schema = mongoose.Schema

const slotSchema = new Schema({
id: {
  type: Schema.ObjectId
},
key: {
  type: String,
  required: true,
  unique: true,
  index: {
    unique: true
  }
},
date: Date,
startTime: Number,
endTime: Number,
clubId: Number,
clubName: String,
price: Number,
courtNumber: Number,
surface: String,
link: String,
type: String
})

slotSchema.methods = {
timeSlot() {
  return new TimeSlot(Number(this.startTime, this.endTime))
},
isOnWeekend() {
  return (this.date.getDay() === 6) || (this.date.getDay() === 0)
},
isMorningSlot() {
  return (!this.isOnWeekend() && this.startTime >= 7 && this.endTime <= 9)
},
isLunchtimeSlot() {
  return (!this.isOnWeekend() && this.startTime >= 11 && this.endTime <= 13)
},
isWeekdayNightSlot() {
  return (!this.isOnWeekend() && this.startTime >= 17)
},
getSlotKey() {
  return this.date.getFullYear() + '_' + (this.date.getMonth() + 1) + '_' + this.date.getDate() + '_' + this.clubId + '_' + this.startTime.toFixed(2).toString() + '-' + this.endTime.toFixed(2).toString() + '_' + (this.surface ? this.surface : 'uknownsurface') + '_' + this.courtNumber + '_' + this.type
},
getSlotKeyExcludingCourtNumber() {
  return this.date.getFullYear() + '_' + (this.date.getMonth() + 1) + '_' + this.date.getDate() + '_' + this.clubId + '_' + this.startTime.toFixed(2).toString() + '-' + this.endTime.toFixed(2).toString() + '_' + (this.surface ? this.surface : 'uknownsurface') + '_' + this.type
},
daysFromToday() {
  const ONE_DAY = 1000 * 60 * 60 * 24
  const date1ms = new Date().getTime()
  const date2ms = this.date.getTime()
  const differencems = Math.abs(date1ms - date2ms)

  return Math.round(differencems / ONE_DAY)
},
getKey(userId) {
  return userId + '_' + this.getSlotKey()
},
toString() {
  return this.toSwedishDay() + ' ' + this.date.getDate() + '/' + (this.date.getMonth() + 1) + ' kl ' + this.startTime.toFixed(2).toString() + '-' + this.endTime.toFixed(2).toString() + ' ' + (this.surface ? this.surface : '')
},
toSwedishDay() {
  switch (this.date.getDay()) {
    case 1:
      return 'måndag'
    case 2:
      return 'tisdag'
    case 3:
      return 'onsdag'
    case 4:
      return 'torsdag'
    case 5:
      return 'fredag'
    case 6:
      return 'lördag'
    case 0:
      return 'söndag'
    default:
      return ''
  }
}
}

slotSchema.statics = {
getAll: () => {
  return new Promise((resolve, reject) => {
    Slot.find({ date: { $gte: new Date() } }, function (err, slots) {
      if (err) {
        reject(err)
      } else {
        resolve(slots)
      }
    })
  })
}
}

const Slot = mongoose.model('slot', slotSchema)

module.exports = Slot


text:
#pragma once

#include <kitBase/robotModel/robotParts/speaker.h>

namespace nxt {
namespace robotModel {
namespace parts {

class NxtSpeaker : public kitBase::robotModel::robotParts::Speaker
{
	Q_OBJECT

public:
	NxtSpeaker(const kitBase::robotModel::DeviceInfo &info
			, const kitBase::robotModel::PortInfo &port);

	void beep(unsigned time);
	virtual void playTone(unsigned freq, unsigned time) = 0;
};

}
}
}


text:
Kinvey-OAuth2-DI-Sample
=======================

Sample Application that uses Instagram's API through OAuth 2.0 and Data Integration. This sample uses Core Location to obtain the user's location, gtm-oauth2 to obtain an access_token for connecting to Instagram, and Kinvey's Data Integration feature to load nearby images.

![Screen Shot 1](https://github.com/KinveyApps/Kinvey-OAuth2-DI-Sample/raw/master/images/OAuth2Example_screen1.png)
![Screen Shot 2](https://github.com/KinveyApps/Kinvey-OAuth2-DI-Sample/raw/master/images/OAuth2Example_screen2.png)

### KinveyKit
This sample application requires a minimum of iOS 5.0 and KinveyKit 1.17.2. To use the sample app, go to [Kinvey](http://console.kinvey.com) and create a new App. You'll need the App id and App secret to set in `AppDelegate.m` in order to run this sample.

### OAuth2
This project uses Google's [gtm-oauth2](http://code.google.com/p/gtm-oauth2/) library to obtain an acess token from Instagram. It's your responsiblity to log in to [Instragram's API](http://instagram.com/developer/), create an application with them and obtain the client id and secret.

### Data Integration
There are two ql.io collections used by this sample app
* `instagram-locations` : provides a list of Instagram locations near a given latitude & longitude
* `instagram-imagesAtLoc` : provides a list of recent images at a given Instagram location

This repo contains `instagram-locations_qlio_script.txt` and `instagram-imagesAtLoc_qlio_script.txt` which provide the ql.io script to use if you create these collections on your app backend.

## License

Copyright (c) 2013 Kinvey, Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.


text:
#pragma once

#include "DocumentRuleSets.h"
#include "StyleResolver.h"
#include <wtf/Forward.h>

namespace WebCore {

class StyleRulePage;

class PageRuleCollector {
public:
    PageRuleCollector(StyleResolver::State& state, DocumentRuleSets& ruleSets)
        : m_state(state)
        , m_ruleSets(ruleSets) { }

    void matchAllPageRules(int pageIndex);
    StyleResolver::MatchResult& matchedResult() { return m_result; }

private:
    bool isLeftPage(int pageIndex) const;
    bool isRightPage(int pageIndex) const { return !isLeftPage(pageIndex); }
    bool isFirstPage(int pageIndex) const;
    String pageName(int pageIndex) const;

    void matchPageRules(RuleSet* rules, bool isLeftPage, bool isFirstPage, const String& pageName);
    void matchPageRulesForList(Vector<StyleRulePage*>& matchedRules, const Vector<StyleRulePage*>& rules, bool isLeftPage, bool isFirstPage, const String& pageName);

    const StyleResolver::State& m_state;
    DocumentRuleSets& m_ruleSets;

    StyleResolver::MatchResult m_result;
};

} // namespace WebCore


text:
package com.google.android.media.tv.companionlibrary.sync;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import com.google.android.media.tv.companionlibrary.model.Channel;

/**
 * Receives broadcasts from a {@link EpgSyncJobService}.
 *
 *
This a single use receiver. No events are handled after the scan is complete.
 */
public final class SyncStatusBroadcastReceiver extends BroadcastReceiver {

    private static final boolean DEBUG = false;
    private static final String TAG = "SyncStatusBroadcastRcvr";

    /** Listens for sync events broadcast by a @{link {@link EpgSyncJobService}. */
    public interface SyncListener {

        /**
         * This method is used to display progress to the user.
         *
         *
Before this method is called for the first time amount of progress is considered
         * indeterminate.
         *
         * @param completedStep The number scanning steps that have been completed.
         * @param totalSteps The total number scanning steps.
         */
        void onScanStepCompleted(int completedStep, int totalSteps);

        /**
         * This method will be called when a channel has been completely scanned. It can be
         * overridden to display custom information about this channel to the user.
         *
         * @param displayName {@link Channel#getDisplayName()} for the scanned channel.
         * @param displayNumber {@link Channel#getDisplayNumber()} ()} for the scanned channel.
         */
        void onScannedChannel(CharSequence displayName, CharSequence displayNumber);

        /**
         * This method will be called when scanning ends. Developers may want to notify the user
         * that scanning has completed and allow them to exit the activity.
         */
        void onScanFinished();

        /**
         * Update the description that will be displayed underneath the progress bar. This could be
         * used to state the current progress of the scan.
         *
         * @param errorCode The error code causing the scan to fail.
         */
        void onScanError(int errorCode);
    }

    private final String mInputId;
    private final SyncListener mSyncListener;

    private boolean mFinishedScan = false;

    public SyncStatusBroadcastReceiver(String inputId, SyncListener syncListener) {
        this.mInputId = inputId;
        this.mSyncListener = syncListener;
    }

    @Override
    public void onReceive(Context context, final Intent intent) {
        if (mFinishedScan) {
            return;
        }
        String syncStatusChangedInputId =
                intent.getStringExtra(EpgSyncJobService.BUNDLE_KEY_INPUT_ID);
        if (syncStatusChangedInputId != null && syncStatusChangedInputId.equals(mInputId)) {
            String syncStatus = intent.getStringExtra(EpgSyncJobService.SYNC_STATUS);
            if (syncStatus.equals(EpgSyncJobService.SYNC_STARTED)) {
                if (DEBUG) {
                    Log.d(TAG, "Sync status: Started");
                }
            } else if (syncStatus.equals(EpgSyncJobService.SYNC_SCANNED)) {
                int channelsScanned =
                        intent.getIntExtra(EpgSyncJobService.BUNDLE_KEY_CHANNELS_SCANNED, 0);
                int channelCount =
                        intent.getIntExtra(EpgSyncJobService.BUNDLE_KEY_CHANNEL_COUNT, 0);
                mSyncListener.onScanStepCompleted(channelsScanned, channelCount);
                String channelDisplayName =
                        intent.getStringExtra(
                                EpgSyncJobService.BUNDLE_KEY_SCANNED_CHANNEL_DISPLAY_NAME);
                String channelDisplayNumber =
                        intent.getStringExtra(
                                EpgSyncJobService.BUNDLE_KEY_SCANNED_CHANNEL_DISPLAY_NUMBER);
                if (DEBUG) {
                    Log.d(TAG, "Sync status: Channel Scanned");
                    Log.d(TAG, "Scanned " + channelsScanned + " out of " + channelCount);
                }
                mSyncListener.onScannedChannel(channelDisplayName, channelDisplayNumber);
            } else if (syncStatus.equals(EpgSyncJobService.SYNC_FINISHED)) {
                if (DEBUG) {
                    Log.d(TAG, "Sync status: Finished");
                }
                mFinishedScan = true;
                mSyncListener.onScanFinished();
            } else if (syncStatus.equals(EpgSyncJobService.SYNC_ERROR)) {
                int errorCode = intent.getIntExtra(EpgSyncJobService.BUNDLE_KEY_ERROR_REASON, 0);
                if (DEBUG) {
                    Log.d(TAG, "Error occurred: " + errorCode);
                }
                mSyncListener.onScanError(errorCode);
            }
        }
    }
}


text:
/* tslint:disable:max-line-length */

import { Directive, ElementRef, OnInit, OnDestroy } from '@angular/core';
import { BackgroundService } from '../providers/background';

@Directive({
	selector: '[mymicds-blur]' // tslint:disable-line
})
export class BlurDirective implements OnInit, OnDestroy {

	subscription: any;

	constructor(
		private el: ElementRef,
		private backgroundService: BackgroundService
	) { }

	ngOnInit() {
		this.el.nativeElement.style.background = 'linear-gradient(rgba(0, 0, 0, 0.6), rgba(0, 0, 0, 0.6)), url("'
			+ this.backgroundService.variants.blur + '")';
		this.el.nativeElement.style.backgroundSize = 'cover';
		this.el.nativeElement.style.backgroundAttachment = 'fixed';
		this.subscription = this.backgroundService.backgroundChange$.subscribe(
			(variants: any) => {
				this.el.nativeElement.style.background = 'linear-gradient(rgba(0, 0, 0, 0.6), rgba(0, 0, 0, 0.6)), url("' + variants.blur + '")';
				this.el.nativeElement.style.backgroundSize = 'cover';
				this.el.nativeElement.style.backgroundAttachment = 'fixed';
			}
		);
	}

	ngOnDestroy() {
		this.subscription.unsubscribe();
	}

}

@Directive({
	selector: '[mymicds-blur--dark]' // tslint:disable-line
})
export class DarkBlurDirective implements OnInit, OnDestroy {

	subscription: any;

	constructor(
		private el: ElementRef,
		private backgroundService: BackgroundService
	) { }

	ngOnInit() {
		this.el.nativeElement.style.background = 'linear-gradient(rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8)), url("'
			+ this.backgroundService.variants.blur + '")';
		this.el.nativeElement.style.backgroundSize = 'cover';
		this.el.nativeElement.style.backgroundAttachment = 'fixed';
		this.subscription = this.backgroundService.backgroundChange$.subscribe(
			(variants: any) => {
				this.el.nativeElement.style.background = 'linear-gradient(rgba(0, 0, 0, 0.6), rgba(0, 0, 0, 0.6)), url("' + variants.blur + '")';
				this.el.nativeElement.style.backgroundSize = 'cover';
				this.el.nativeElement.style.backgroundAttachment = 'fixed';
			}
		);
	}

	ngOnDestroy() {
		this.subscription.unsubscribe();
	}
}

@Directive({
	selector: '[mymicds-blur--white]' // tslint:disable-line
})
export class WhiteBlurDirective implements OnInit, OnDestroy {

	subscription: any;

	constructor(
		private el: ElementRef,
		private backgroundService: BackgroundService
	) { }

	ngOnInit() {
		this.el.nativeElement.style.background = 'linear-gradient(rgba(255, 255, 255, 0.5), rgba(255, 255, 255, 0.5)), url("'
			+ this.backgroundService.variants.blur + '")';
		this.el.nativeElement.style.backgroundSize = 'cover';
		this.el.nativeElement.style.backgroundAttachment = 'fixed';
		this.subscription = this.backgroundService.backgroundChange$.subscribe(
			(variants: any) => {
				this.el.nativeElement.style.background = 'linear-gradient(rgba(0, 0, 0, 0.6), rgba(0, 0, 0, 0.6)), url("' + variants.blur + '")';
				this.el.nativeElement.style.backgroundSize = 'cover';
				this.el.nativeElement.style.backgroundAttachment = 'fixed';
			}
		);
	}

	ngOnDestroy() {
		this.subscription.unsubscribe();
	}
}