text:
$copyrightNotice = @"
//Copyright (c) 2015 Christopher Johnstone(meson800) and Benedict Haefeli(jedidia)
//The MIT License - See ../../LICENSE for more info
"@

$hFiles = Get-ChildItem -filter *.h
$cppFiles = Get-ChildItem -filter *.cpp
$files = $hFiles + $cppFiles
ForEach ($file in $files)
{
	$content = Get-Content $file
	if ($content | Select-String -simplematch '//Copyright (c) ' )
	{
		#this file already has the header
		echo ($file.Name + " has the header, updating")
		#deleting first two lines
		$content = ($content | select -Skip 2)
		$copyrightNotice | out-file temp.txt -encoding ASCII
		$content | out-file temp.txt -append -encoding ASCII
		mv -Force temp.txt $file.Name
	}
	else
	{
		echo ($file.Name + " does not have a header, adding")
		$copyrightNotice | out-file temp.txt -encoding ASCII
		$content | out-file temp.txt -append -encoding ASCII
		mv -Force temp.txt $file.Name
	}
}

redpajama_set_name: RedPajamaGithub


text:
import { TestBed, inject } from '@angular/core/testing';

import { <%= classify(name) %>Service } from './<%= dasherize(name) %>.service';

describe('<%= classify(name) %>Service', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [<%= classify(name) %>Service]
    });
  });

  it('should be created', inject([<%= classify(name) %>Service], (service: <%= classify(name) %>Service) => {
    expect(service).toBeTruthy();
  }));
});


text:
// Copyright (c) 2010 Romain Vallet
// Licensed under the MIT license, read license.txt

var hoverZoomPlugins = hoverZoomPlugins || [];
hoverZoomPlugins.push( {
	name: 'Vie de merde',
	version: '0.1',
	prepareImgLinks: function(callback) {
		var res = [];
		$('img.avatar').each(function() {
			var img = $(this),
				url = img.attr('original') || img.attr('src');
			img.data().hoverZoomSrc = [
				url.replace(/\/(icon|mid)\//, '/original/'),
				url.replace('/icon/', '/mid/')
			];
			res.push(img);
		});
		callback($(res));
	}
});


text:
package com.amazonaws.services.codepipeline.model.transform;

import java.util.Map;
import java.util.List;

import com.amazonaws.AmazonClientException;
import com.amazonaws.services.codepipeline.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.BinaryUtils;
import com.amazonaws.util.StringUtils;
import com.amazonaws.util.IdempotentUtils;
import com.amazonaws.util.StringInputStream;
import com.amazonaws.protocol.json.*;

/**
 * ActionContextMarshaller
 */
public class ActionContextJsonMarshaller {

    /**
     * Marshall the given parameter object, and output to a SdkJsonGenerator
     */
    public void marshall(ActionContext actionContext,
            StructuredJsonGenerator jsonGenerator) {

        if (actionContext == null) {
            throw new AmazonClientException(
                    "Invalid argument passed to marshall(...)");
        }

        try {
            jsonGenerator.writeStartObject();

            if (actionContext.getName() != null) {
                jsonGenerator.writeFieldName("name").writeValue(
                        actionContext.getName());
            }

            jsonGenerator.writeEndObject();
        } catch (Throwable t) {
            throw new AmazonClientException(
                    "Unable to marshall request to JSON: " + t.getMessage(), t);
        }
    }

    private static ActionContextJsonMarshaller instance;

    public static ActionContextJsonMarshaller getInstance() {
        if (instance == null)
            instance = new ActionContextJsonMarshaller();
        return instance;
    }

}


text:
import requests_mock

from tests.fixture_data import EXECUTION_DATA, PROJECT_DATA
from valohai_cli.commands.project.commits import commits

def test_commits(runner, logged_in_and_linked):
    with requests_mock.mock() as m:
        commit_data = EXECUTION_DATA['commit']
        m.get(
            f"https://app.valohai.com/api/v0/projects/{PROJECT_DATA['id']}/commits/",
            json=[commit_data],
        )
        result = runner.invoke(commits)
        assert commit_data['ref'] in result.output
        assert commit_data['identifier'] in result.output


text:
use std::marker::PhantomData;

use tidb_query_codegen::AggrFunction;
use tidb_query_common::Result;
use tidb_query_datatype::{codec::data_type::*, expr::EvalContext, EvalType};
use tidb_query_expr::RpnExpression;
use tipb::{Expr, ExprType, FieldType};

use super::*;

/// The parser for FIRST aggregate function.
pub struct AggrFnDefinitionParserFirst;

impl super::AggrDefinitionParser for AggrFnDefinitionParserFirst {
    fn check_supported(&self, aggr_def: &Expr) -> Result<()> {
        assert_eq!(aggr_def.get_tp(), ExprType::First);
        super::util::check_aggr_exp_supported_one_child(aggr_def)
    }

    #[inline]
    fn parse_rpn(
        &self,
        mut root_expr: Expr,
        exp: RpnExpression,
        _ctx: &mut EvalContext,
        src_schema: &[FieldType],
        out_schema: &mut Vec<FieldType>,
        out_exp: &mut Vec<RpnExpression>,
    ) -> Result<Box<dyn AggrFunction>> {
        use std::convert::TryFrom;

        use tidb_query_datatype::FieldTypeAccessor;

        assert_eq!(root_expr.get_tp(), ExprType::First);

        let eval_type =
            EvalType::try_from(exp.ret_field_type(src_schema).as_accessor().tp()).unwrap();

        let out_ft = root_expr.take_field_type();

        let out_et = box_try!(EvalType::try_from(out_ft.as_accessor().tp()));

        if out_et != eval_type {
            return Err(other_err!(
                "Unexpected return field type {}",
                out_ft.as_accessor().tp()
            ));
        }

        // FIRST outputs one column with the same type as its child
        out_schema.push(out_ft);
        out_exp.push(exp);

        match_template::match_template! {
            TT = [
                Int => &'static Int,
                Real => &'static Real,
                Duration => &'static Duration,
                Decimal => &'static Decimal,
                DateTime => &'static DateTime,
                Json => JsonRef<'static>,
                Bytes => BytesRef<'static>,
                Enum => EnumRef<'static>,
                Set => SetRef<'static>,
            ],
            match eval_type {
                EvalType::TT => Ok(Box::new(AggrFnFirst::<TT>::new())),
            }
        }
    }
}

/// The FIRST aggregate function.
#[derive(Debug, AggrFunction)]
#[aggr_function(state = AggrFnStateFirst::<T>::new())]
pub struct AggrFnFirst<T>(PhantomData<T>)
where
    T: EvaluableRef<'static> + 'static,
    VectorValue: VectorValueExt<T::EvaluableType>;

impl<T> AggrFnFirst<T>
where
    T: EvaluableRef<'static> + 'static,
    VectorValue: VectorValueExt<T::EvaluableType>,
{
    fn new() -> Self {
        AggrFnFirst(PhantomData)
    }
}

/// The state of the FIRST aggregate function.
#[derive(Debug)]
pub enum AggrFnStateFirst<T>
where
    T: EvaluableRef<'static> + 'static,
    VectorValue: VectorValueExt<T::EvaluableType>,
{
    Empty,
    Valued(Option<T::EvaluableType>),
}

impl<T> AggrFnStateFirst<T>
where
    T: EvaluableRef<'static> + 'static,
    VectorValue: VectorValueExt<T::EvaluableType>,
{
    pub fn new() -> Self {
        AggrFnStateFirst::Empty
    }

    #[inline]
    fn update<'a, TT>(&mut self, _ctx: &mut EvalContext, value: Option<TT>) -> Result<()>
    where
        TT: EvaluableRef<'a, EvaluableType = T::EvaluableType>,
    {
        if let AggrFnStateFirst::Empty = self {
            // TODO: avoid this clone
            *self = AggrFnStateFirst::Valued(value.map(|x| x.into_owned_value()));
        }
        Ok(())
    }

    #[inline]
    fn update_repeat<'a, TT>(
        &mut self,
        ctx: &mut EvalContext,
        value: Option<TT>,
        repeat_times: usize,
    ) -> Result<()>
    where
        TT: EvaluableRef<'a, EvaluableType = T::EvaluableType>,
    {
        assert!(repeat_times > 0);
        self.update(ctx, value)
    }

    #[inline]
    fn update_vector<'a, TT, CC>(
        &mut self,
        ctx: &mut EvalContext,
        _phantom_data: Option<TT>,
        physical_values: CC,
        logical_rows: &[usize],
    ) -> Result<()>
    where
        TT: EvaluableRef<'a, EvaluableType = T::EvaluableType>,
        CC: ChunkRef<'a, TT>,
    {
        if let Some(physical_index) = logical_rows.first() {
            self.update(ctx, physical_values.get_option_ref(*physical_index))?;
        }
        Ok(())
    }
}

// Here we manually implement `AggrFunctionStateUpdatePartial` instead of implementing
// `ConcreteAggrFunctionState` so that `update_repeat` and `update_vector` can be faster.
impl<T> super::AggrFunctionStateUpdatePartial<T> for AggrFnStateFirst<T>
where
    T: EvaluableRef<'static> + 'static,
    VectorValue: VectorValueExt<T::EvaluableType>,
{
    // ChunkedType has been implemented in AggrFunctionStateUpdatePartial<T1> for AggrFnStateFirst<T2>
    impl_state_update_partial! { T }
}

// In order to make `AggrFnStateFirst` satisfy the `AggrFunctionState` trait, we default impl all
// `AggrFunctionStateUpdatePartial` of `Evaluable` for all `AggrFnStateFirst`.
impl_unmatched_function_state! { AggrFnStateFirst<T> }

impl<T> super::AggrFunctionState for AggrFnStateFirst<T>
where
    T: EvaluableRef<'static> + 'static,
    VectorValue: VectorValueExt<T::EvaluableType>,
{
    fn push_result(&self, _ctx: &mut EvalContext, target: &mut [VectorValue]) -> Result<()> {
        assert_eq!(target.len(), 1);
        let res = if let AggrFnStateFirst::Valued(v) = self {
            v.clone()
        } else {
            None
        };
        target[0].push(res);
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;

    use tidb_query_datatype::FieldTypeTp;
    use tikv_util::buffer_vec::BufferVec;
    use tipb_helper::ExprDefBuilder;

    use super::{super::AggrFunction, *};
    use crate::AggrDefinitionParser;

    #[test]
    fn test_update() {
        let mut ctx = EvalContext::default();
        let function = AggrFnFirst::<&'static Int>::new();
        let mut state = function.create_state();

        let mut result = [VectorValue::with_capacity(0, EvalType::Int)];
        state.push_result(&mut ctx, &mut result[..]).unwrap();
        assert_eq!(result[0].to_int_vec(), &[None]);

        update!(state, &mut ctx, Some(&1)).unwrap();
        state.push_result(&mut ctx, &mut result[..]).unwrap();
        assert_eq!(result[0].to_int_vec(), &[None, Some(1)]);

        update!(state, &mut ctx, Some(&2)).unwrap();
        state.push_result(&mut ctx, &mut result[..]).unwrap();
        assert_eq!(result[0].to_int_vec(), &[None, Some(1), Some(1)]);
    }

    #[test]
    fn test_update_enum() {
        let mut ctx = EvalContext::default();
        let function = AggrFnFirst::<EnumRef<'static>>::new();
        let mut state = function.create_state();

        let mut result = [VectorValue::with_capacity(0, EvalType::Enum)];

        update!(state, &mut ctx, Some(EnumRef::new("bbb".as_bytes(), &1))).unwrap();
        state.push_result(&mut ctx, &mut result[..]).unwrap();
        assert_eq!(
            result[0].to_enum_vec(),
            vec![Some(Enum::new("bbb".as_bytes().to_vec(), 1))]
        );

        update!(state, &mut ctx, Some(EnumRef::new("aaa".as_bytes(), &2))).unwrap();
        state.push_result(&mut ctx, &mut result[..]).unwrap();
        assert_eq!(
            result[0].to_enum_vec(),
            vec![
                Some(Enum::new("bbb".as_bytes().to_vec(), 1)),
                Some(Enum::new("bbb".as_bytes().to_vec(), 1))
            ]
        );
    }

    #[test]
    fn test_update_set() {
        let mut ctx = EvalContext::default();
        let function = AggrFnFirst::<SetRef<'static>>::new();
        let mut state = function.create_state();

        let mut result = [VectorValue::with_capacity(0, EvalType::Set)];

        let mut buf = BufferVec::new();
        buf.push("我好强啊");
        buf.push("我太强啦");
        let buf = Arc::new(buf);

        update!(state, &mut ctx, Some(SetRef::new(&buf, 0b11))).unwrap();
        state.push_result(&mut ctx, &mut result[..]).unwrap();
        assert_eq!(
            result[0].to_set_vec(),
            vec![Some(Set::new(buf.clone(), 0b11))]
        );

        update!(state, &mut ctx, Some(SetRef::new(&buf, 0b10))).unwrap();
        state.push_result(&mut ctx, &mut result[..]).unwrap();
        assert_eq!(
            result[0].to_set_vec(),
            vec![Some(Set::new(buf.clone(), 0b11)), Some(Set::new(buf, 0b11))]
        );
    }

    #[test]
    fn test_update_repeat() {
        let mut ctx = EvalContext::default();
        let function = AggrFnFirst::<BytesRef<'static>>::new();
        let mut state = function.create_state();

        let mut result = [VectorValue::with_capacity(0, EvalType::Bytes)];

        update_repeat!(state, &mut ctx, Some(&[1u8] as BytesRef<'_>), 2).unwrap();
        state.push_result(&mut ctx, &mut result[..]).unwrap();
        assert_eq!(result[0].to_bytes_vec(), &[Some(vec![1])]);

        update_repeat!(state, &mut ctx, Some(&[2u8] as BytesRef<'_>), 3).unwrap();
        state.push_result(&mut ctx, &mut result[..]).unwrap();
        assert_eq!(result[0].to_bytes_vec(), &[Some(vec![1]), Some(vec![1])]);
    }

    #[test]
    fn test_update_vector() {
        let mut ctx = EvalContext::default();
        let function = AggrFnFirst::<&'static Int>::new();
        let mut state = function.create_state();
        let mut result = [VectorValue::with_capacity(0, EvalType::Int)];

        update_vector!(
            state,
            &mut ctx,
            ChunkedVecSized::from_slice(&[Some(0); 0]),
            &[]
        )
        .unwrap();
        state.push_result(&mut ctx, &mut result[..]).unwrap();
        assert_eq!(result[0].to_int_vec(), &[None]);

        result[0].clear();
        update_vector!(
            state,
            &mut ctx,
            ChunkedVecSized::from_slice(&[Some(1)]),
            &[]
        )
        .unwrap();
        state.push_result(&mut ctx, &mut result[..]).unwrap();
        assert_eq!(result[0].to_int_vec(), &[None]);

        result[0].clear();
        update_vector!(
            state,
            &mut ctx,
            ChunkedVecSized::from_slice(&[None, Some(2)]),
            &[0, 1]
        )
        .unwrap();
        state.push_result(&mut ctx, &mut result[..]).unwrap();
        assert_eq!(result[0].to_int_vec(), &[None]);

        result[0].clear();
        update_vector!(
            state,
            &mut ctx,
            ChunkedVecSized::from_slice(&[Some(1)]),
            &[0]
        )
        .unwrap();
        state.push_result(&mut ctx, &mut result[..]).unwrap();
        assert_eq!(result[0].to_int_vec(), &[None]);

        // Reset state
        let mut state = function.create_state();

        result[0].clear();
        update_vector!(
            state,
            &mut ctx,
            ChunkedVecSized::from_slice(&[None, Some(2)]),
            &[1, 0]
        )
        .unwrap();
        state.push_result(&mut ctx, &mut result[..]).unwrap();
        assert_eq!(result[0].to_int_vec(), &[Some(2)]);
    }

    #[test]
    fn test_illegal_request() {
        let expr = ExprDefBuilder::aggr_func(ExprType::First, FieldTypeTp::Double) // Expect LongLong but give Double
            .push_child(ExprDefBuilder::column_ref(0, FieldTypeTp::LongLong))
            .build();
        AggrFnDefinitionParserFirst.check_supported(&expr).unwrap();

        let src_schema = [FieldTypeTp::LongLong.into()];
        let mut schema = vec![];
        let mut exp = vec![];
        let mut ctx = EvalContext::default();
        AggrFnDefinitionParserFirst
            .parse(expr, &mut ctx, &src_schema, &mut schema, &mut exp)
            .unwrap_err();
    }
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Threading;
using Xunit;

namespace System.Diagnostics.Tests
{
    public class EventLogEntryEventWrittenTest
    {
        static AutoResetEvent signal;
        private const string message = "EventLogEntryEventWrittenTestMessage";
        private int eventCounter;

        public void RaisingEvent(string log, string methodName, bool waitOnEvent = true)
        {
            signal = new AutoResetEvent(false);
            eventCounter = 0;
            string source = "Source_" + methodName;

            try
            {
                EventLog.CreateEventSource(source, log);
                using (EventLog eventLog = new EventLog())
                {
                    eventLog.Source = source;
                    eventLog.EntryWritten += new EntryWrittenEventHandler((object sourceObject, EntryWrittenEventArgs e) =>
                    {
                        eventCounter += 1;
                        signal.Set();
                    });
                    Helpers.RetryOnWin7(() => eventLog.EnableRaisingEvents = waitOnEvent);
                    Helpers.RetryOnWin7(() => eventLog.WriteEntry(message, EventLogEntryType.Information));
                    if (waitOnEvent)
                    {
                        if (!signal.WaitOne(6000))
                        {
                            eventLog.WriteEntry(message, EventLogEntryType.Information);
                            Assert.True(signal.WaitOne(6000));
                        }
                        // The system responds to WriteEntry only if the last write event occurred at least six seconds previously.
                        // This implies that the system will only receive one EntryWritten event notification within a six-second interval, even if more than one event log change occurs.
                        // For more information https://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog.entrywritten(v=vs.110).aspx
                    }
                }
            }
            finally
            {
                EventLog.DeleteEventSource(source);
                Helpers.RetryOnWin7(() => EventLog.Delete(log));
            }
        }

        [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndSupportsEventLogs))]
        public void EntryWrittenEventRaised()
        {
            RaisingEvent("EnableEvent", nameof(EntryWrittenEventRaised));
            Assert.NotEqual(0, eventCounter);
        }

        [ConditionalFact(typeof(Helpers), nameof(Helpers.IsElevatedAndSupportsEventLogs))]
        public void EntryWrittenEventRaiseDisable()
        {
            RaisingEvent("DisableEvent", nameof(EntryWrittenEventRaiseDisable), waitOnEvent: false);
            Assert.Equal(0, eventCounter);
        }
    }
}


text:
<?php defined('SYSPATH') or die('No direct script access.');
/**
 * All the base Request method actions return
 *    $this->error_response(405, 'GET method not allowed');
 * To have your controller support a given HTTP verb, override that method
 * in the concrete class
 */
abstract class Api_Controller extends Kohana_Controller {

    /**
     * @var string Meant to be overridden in Concrete
     * Controller init() implementation
     */
    protected static $table_name = '';
    /**
     * @var array These are defined in the concrete class
     */
    static $fields = array();
    /**
     * @var array For POST,PUT,PATCH, this is the array of valid
     * field_name => values that will be used for query construction.
     * @see $this->post|put|patch_validate()
     */
    protected $validated_input = array();
    /**
     * @see http://kohanaframework.org/3.2/guide/kohana/security/validation
     * @see http://kohanaframework.org/3.2/guide/api/Validation
     * @var Validation
     */
    protected $validator;
    /**
     * @var string Meant to be overridden in Concrete
     * Controller init() implementation
     */
    protected static $primary_key_field = 'id';

    private $known_request_methods = array(
        'GET',
        'PUT',
        'PATCH',
        'POST',
        'DELETE',
        'OPTIONS',
    );
    /**
     * @var array These are the only HTTP verbs for which we will
     * parse an entity body and assign to $request->post().
     */
    private $payload_allowed_methods = array('POST', 'PUT', 'PATCH');

    /**
     * Sets response Content-Type to 'application/json' and checks that
     * the request method is one of the supported HTTP request
     * methods ($this->known_request_methods).  If it is, sets
     * $this->action to Request::method()
     *
     * @param Request $request
     * @param Response $response
     */
    function __construct(Request $request, Response $response)
    {
        /*
         * Set the Response HTTP Header 'Content-Type' to application/json
         */
        $response->headers('Content-Type', 'application/json');
        if(in_array(strtoupper($request->method()), $this->known_request_methods))
        {
            $request->action(strtolower($request->method()));
        }
        else
        {
            $message = "HTTP Method {$request->method()} not known."
                . "Known method: " . implode(', ', $this->known_request_methods);
            $this->route_to_error($request, $response, 400, $message);
        }
        /*
         * Only POSTs with Content-Type = form-encode are 'auto' parsed to an array()
         * and set to $request->post().  So for the other HTTP verbs with payloads (and
         * POST with JSON content type), parse and set to $request->post().
         *
         * Easiest way to get access to that data WITHOUT overriding the Kohana
         * Request class.
         */
        $this->parse_payload($request, $response);
        return parent::__construct($request, $response);
    }

    /**
     * Default GET controller for API, override in concrete /api/<controller> to
     * provide support for GET in that controller
     *
     * Default action, throw 405 with supported methods header
     */
    function action_get()
    {
        return $this->error_response(405, "GET method not allowed for Resource: '{$this->request->controller()}'");
    }

    /**
     * Default behavior for GET requests.
     *
     * Usage in concrete Controllers
     *
     *
     *  function action_get()
     *  {
     *    return parent::fulfill_get_request();
     *  }
     *
     */
    protected function fulfill_get_request()
    {
        $requested_resource_identifier = $this->request->param('resource_id');
        $results = $this->get_persisted_resource(static::$table_name, $requested_resource_identifier);
        if( ! $results->count() && $requested_resource_identifier)
        {
            $this->error_response(404, "Resource with identifier [{$requested_resource_identifier}] Not Found");
        }
        else
        {
            $this->response->body(
                json_encode($results->as_array())
            );
        }
    }

    /**
     * @param $table_name
     * @param string|null $requested_resource_identifier If null, this is a get all
     * @return Database_MySQL_Result
     */
    private function get_persisted_resource($table_name, $requested_resource_identifier=null)
    {
        $query = DB::select()->from($table_name);
        if($requested_resource_identifier)
        {
            $query->where(static::$primary_key_field, '=', $requested_resource_identifier);
        }
        return $query->execute();
    }

    /**
     * Default PUT controller for API, override in concrete /api/<controller> to
     * provide support for PUT in that controller
     *
     * Default action, throw 405 with supported methods header
     */
    function action_put()
    {
        return $this->error_response(405, "PUT method not allowed for Resource: '{$this->request->controller()}'");
    }

    /**
     * Default PATCH controller for API, override in concrete /api/<controller> to
     * provide support for PATCH in that controller
     *
     * Default action, throw 405 with supported methods header
     */
    function action_patch()
    {
        return $this->error_response(405, "PATCH method not allowed for Resource: '{$this->request->controller()}'");
    }

    /**
     * Default POST controller for API, override in concrete /api/<controller> to
     * provide support for POST in that controller
     *
     * Default action, throw 405 with supported methods header
     */
    function action_post()
    {
        return $this->error_response(405, "POST method not allowed for Resource: '{$this->request->controller()}'");
    }

    /**
     * Default implementation for the validation of POST input. Override
     * in Concrete Controller as needed.
     * The ultimate effect of this method is that $this->validated_input is
     * populated to be used in query creation.  It ONLY will include keys that
     * are known to self::$fields.
     * If you need to add/subtract/mutate $this->validated_input, do that after this call
     * in your controller.
     *
     * i.e.
     *
     * function action_post()
     * {
     *   if( ! $this->post_validate($this->request->post()))
     *   {
     *     $this->end_with_validation_error();
     *   }
     *   else
     *   {
     *     // be sure you validate this key/val in some way
     *     $this->validated_fields['some_other_key'] = 'baz';
     *     return $this->fulfill_post_request();
     *   }
     * }
     *
     *
     * @param $input
     * @return bool
     */
    protected function post_validate(array $input = array())
    {
        $valid = false;
        /*
         * trim off unknown fields
         */
        $input = array_intersect_key($input, static::$fields);
        $this->init_validations($input);
        $valid = $this->validator->check();
        if($valid)
        {
            $this->validated_input = $this->validator->data();
        }
        return $valid;
    }

    /**
     * For PATCH, only need to validate the supplied fields
     *
     * @param string $resource_identifier (the pk for the Resource)
     * @param array $input
     * @return bool
     */
    protected function patch_validate($resource_identifier, array $input = array())
    {
        $valid = false;
        /*
         * trim off unknown fields
         */
        $input = array_intersect_key($input, static::$fields);
        $this->init_validations($input, 'PATCH');
        // Identifier in URI required for patch
        if( ! $resource_identifier)
        {
            $this->validator->error(static::$primary_key_field,
                "PATCH.missing_identifier");
            return $valid;
        }
        $valid = $this->validator->check();
        if($valid)
        {
            $this->validated_input = $this->validator->data();
        }
        return $valid;
    }

    /**
     * Default behavior for POST request.  Override in Concrete Controller
     * as needed.
     *
     * Usage:
     *
     * function action_post()
     * {
     *   if( ! $this->post_validate($this->request->post()))
     *   {
     *     $this->end_with_validation_error();
     *   }
     *   else
     *   {
     *     return $this->fulfill_post_request();
     *   }
     * }
     *
     */
    protected function fulfill_post_request()
    {
        $data = $this->validated_input;
        // identifier should not be in $data
        unset($data[static::$primary_key_field]);
        if( ! $data)
        {
            $this->error_response(400, 'There was no POST data');
            return;
        }
        $sql   = Util_Sql::build_insert(static::$table_name, $data);
        $query = DB::query(
            Database::INSERT,
            $sql
        );
        $query->parameters(Util_Arr::prefix_array_key(':', $data));
        try
        {
            list($identifier, $rows_affected) = $query->execute();
            $base_url = Kohana::$base_url;
            $protocol = $this->request->secure() ? 'https' : 'http';
            $this->response->headers('HTTP/1.1', '201 Created');
            echo json_encode(
                array(
                    static::$primary_key_field => $identifier,
                    'link' => array(
                        "href" => "{$protocol}://{$_SERVER['HTTP_HOST']}{$base_url}{$this->request->uri()}/{$identifier}"
                    )
                )
            );
        }
        catch(Database_Exception $e)
        {
            $this->response->headers('HTTP/1.1', '500 Server Error');
        }
    }

    protected function delete_validate($resource_identifier)
    {
        $valid = false;
        // Identifier in URI required for patch
        if( ! $resource_identifier)
        {
            $this->validator->error(static::$primary_key_field,
                "DELETE.missing_identifier");
            return $valid;
        }
        // no validation to speak of here, still have delete_validate for consistencey
        $valid = true;
        return $valid;
    }

    /**
     * Default behavior for PATCH request.  Override in Concrete Controller
     * as needed.
     *
     * NOTE: as a simplification (and to keep from overriding too much Kohana
     * code), we use request->post() to store to entity payload data for PATCH
     *
     * Usage:
     *
     * function action_patch()
     * {
     *   if( ! $this->patch_validate($this->request->post()))
     *   {
     *     $this->end_with_validation_error();
     *   }
     *   else
     *   {
     *     return $this->fulfill_patch_request();
     *   }
     * }
     *
     */
    protected function fulfill_patch_request($primary_key_value)
    {
        $data = $this->validated_input;
        if( ! $data)
        {
            $this->error_response(400, 'There was no PATCH data');
            return;
        }
        $existing_resource = $this->get_persisted_resource(static::$table_name, $primary_key_value);
        if( ! $existing_resource->count())
        {
            $this->error_response(404, "Resource: '{$this->request->controller()}', with identifier: '{$primary_key_value}' was not found");
            return;
        }
        // at this point the identifier should not be in $data
        unset($data[static::$primary_key_field]);
        $sql   = Util_Sql::build_update(static::$table_name, static::$primary_key_field, $data);
        $query = DB::query(
            Database::UPDATE,
            $sql
        );
        $data[static::$primary_key_field] = $primary_key_value;
        $query->parameters(Util_Arr::prefix_array_key(':', $data));
        try
        {
            $rows_affected = $query->execute();
            $this->response->headers('HTTP/1.1', '204 No Content');
        }
        catch(Database_Exception $e)
        {
            $this->response->headers('HTTP/1.1', '500 Server Error');
        }
    }

    /**
     * @param $primary_key_value
     */
    protected function fulfill_delete_request($primary_key_value)
    {
        /**
         * first get the existing resource from persistence
         */
        $existing_resource = $this->get_persisted_resource(static::$table_name, $primary_key_value);
        if($existing_resource->count())
        {
            $sql   = Util_Sql::build_delete(static::$table_name, static::$primary_key_field);
            $query = DB::query(
                Database::DELETE,
                $sql
            );
            $query->parameters(Util_Arr::prefix_array_key(':', array(static::$primary_key_field => $primary_key_value)));
            try
            {
                $rows_affected = $query->execute();
                $this->response->headers('HTTP/1.1', '204 No Content');
            }
            catch(Database_Exception $e)
            {
                $this->response->headers('HTTP/1.1', '500 Server Error');
            }
        }
        else // nothing to delete
        {
            $this->response->headers('HTTP/1.1', '204 No Content');
        }
    }

    /**
     * default implementation of sending a validation error to client
     */
    protected function validation_error_response()
    {
        /*
         * 'api' is the validation message translation file
         * @see http://kohanaframework.org/3.2/guide/kohana/files/messages
         */
        $errors = $this->validator->errors('api');
        return $this->error_response(400, 'There was validation error', array('__validation' => $errors));
    }

    /**
     * default implementation of sending a validation error to client
     */
    protected function error_response($code, $message, array $additional=array())
    {
        $error_values = array_merge(
            array(
                '__code'    => $code,
                '__message' => $message,
            ),
            $additional
        );
        $this->response->body(json_encode(array('__error' => $error_values)));
        $this->response->headers('HTTP/1.1', $code . Util_Http::$code_labels[$code]);

    }

    /**
     * Default DELETE controller for API, override in concrete /api/<controller> to
     * provide support for DELETE in that controller
     *
     * Default action, throw 405 with supported methods header
     */
    function action_delete()
    {
        return $this->error_response(405, 'DELETE method not allowed for this Resource');
    }

    /**
     * Default OPTIONS controller for API, override in concrete /api/<controller> to
     * provide support for OPTIONS in that controller
     *
     * Default action, throw 405 with supported methods header
     */
    function action_options()
    {
        return $this->error_response(405, "OPTIONS method not allowed for Resource: '{$this->request->controller()}'");
    }

    /**
     * hack do to the way Kohana handles responses.
     * Only used in $this->__construct() for HTTP method unknown
     */
    function action_error()
    {
        return;
    }

    /**
     * Apply validation rules defined in Concrete class's $fields array
     *
     * @see http://kohanaframework.org/3.2/guide/kohana/security/validation
     * @see http://kohanaframework.org/3.2/guide/api/Validation
     * @param array $input
     * @param string $http_request_method
     */
    private function init_validations(array $input = array(), $http_request_method='POST')
    {
        $this->validator = Validation::factory((array)$input);
        /*
         * add labels for system controller fields
         */
        $fields_to_check = (array)static::$fields;
        if(strtoupper($http_request_method) == 'PATCH')
        {
            $fields_to_check = array_intersect_key($fields_to_check, $input);
        }

        $this->validator->label(static::$primary_key_field, static::$primary_key_field);
        foreach($fields_to_check as $field_name => $rules)
        {
            foreach((array)$rules as $index_or_rule => $rule_name_or_rule_meta)
            {
                /*
                 * Rule definitions can be in on of 2 forms,
                 *  - [Form A] Rule name with no rule parameters
                 *  - [Form B] Rule name with array of rule parameters
                 * ex:
                 * 'raw_text' => array(
                      'not_empty',                          // Form A
                      'max_length' => array(':value', 500)  // Form B
                    ),
                 */
                if( ! is_int($index_or_rule)) // true form Form B
                {
                    //                                     rule name           rule meta
                    $this->validator->rule($field_name, $index_or_rule, $rule_name_or_rule_meta);
                }
                else // Form A
                {
                    //                                         rule name
                    $this->validator->rule($field_name, $rule_name_or_rule_meta);
                }
            }
        }
    }

    /**
     * Used internally to send error responses
     *
     * @param Request $request
     * @param Response $response
     * @param int $error_code One of Util_Http::$code_labels
     * @param string $message
     */
    protected function route_to_error($request, $response, $error_code, $message)
    {
        $response->headers('HTTP/1.1', $error_code . Util_Http::$code_labels[$error_code]);
        $response->body(
            json_encode(array('__error' => array(
                '__message' => $message
            )))
        );
        $request->action('error');
    }

    /**
     * On successful parse, this method sets the resulting array to $request->post();
     * @param Request $request
     * @param Response $response
     * @return bool
     */
    private function parse_payload(Request $request, Response $response)
    {
        $successful_parse = false;
        $parsed_payload = array();
        $request_content_type = isset($_SERVER['CONTENT_TYPE']) ? $_SERVER['CONTENT_TYPE'] : null;
        $request_payload_body = $request->body();
        $request_method = $request->method();
        /*
         * If is a method that carries a payload, and the payload is not empty
         */
        if(   in_array($request_method, $this->payload_allowed_methods)
           && trim($request_payload_body)!='')
        {
            switch($request_content_type)
            {
                case Util_Http::CONTENT_TYPE_FORM_ENCODE:
                    /*
                     * if it is POST, $request->post() is already set
                     */
                    if( $request_method != 'POST')
                    {
                        parse_str($request_payload_body, $parsed_payload);
                        if( ! $parsed_payload)
                        {
                            $message = "HTTP entity body failed to parse as '" . Util_Http::CONTENT_TYPE_FORM_ENCODE
                                . "' Entity body received was: '{$request_payload_body}'";
                            $this->route_to_error($request, $response, 400, $message);
                        }
                        else
                        {
                            $request->post($parsed_payload);
                            $successful_parse = true;
                        }
                    }
                    break;
                case Util_Http::CONTENT_TYPE_JSON:
                    $parsed_payload = json_decode($request_payload_body, $as_array=true);
                    if(json_last_error())
                    {
                        $message = "HTTP entity body failed to parse as '" . Util_Http::CONTENT_TYPE_JSON
                            . "'  Check syntax and retry request";
                        $this->route_to_error($request, $response, 400, $message);
                    }
                    else
                    {
                        $request->post($parsed_payload);
                        $successful_parse = true;
                    }
                    break;
                default:
                    $header_value = is_null($request_content_type) ? "<missing>" : "'{$request_content_type}'";
                    $message = "Unknown or missing 'Content-Type' HTTP header value."
                        . "  Value found: {$header_value}  Supported Content-Type are'"
                        . Util_Http::CONTENT_TYPE_JSON . "' and '" . Util_Http::CONTENT_TYPE_FORM_ENCODE . "'";
                    $this->route_to_error($request, $response, 400, $message);
            }
        }
        return $successful_parse;
    }

}


text:
package org.apache.flink.connector.base.source.hybrid;

import org.apache.flink.api.connector.source.Source;
import org.apache.flink.api.connector.source.SourceEvent;

/**
 * Event sent from {@link HybridSourceSplitEnumerator} to {@link HybridSourceReader} to switch to
 * the indicated reader.
 */
public class SwitchSourceEvent implements SourceEvent {

    private static final long serialVersionUID = 1L;
    private final int sourceIndex;
    private final Source source;
    private final boolean finalSource;

    /**
     * Constructor.
     *
     * @param sourceIndex
     */
    public SwitchSourceEvent(int sourceIndex, Source source, boolean finalSource) {
        this.sourceIndex = sourceIndex;
        this.source = source;
        this.finalSource = finalSource;
    }

    public int sourceIndex() {
        return sourceIndex;
    }

    public Source source() {
        return source;
    }

    public boolean isFinalSource() {
        return finalSource;
    }

    @Override
    public String toString() {
        return this.getClass().getSimpleName() + '{' + "sourceIndex=" + sourceIndex + '}';
    }
}


text:
package com.jcumulus.server.rtmfp.publisher;

import com.jcumulus.server.rtmfp.packet.*;
import java.util.LinkedHashMap;
import java.util.Map;

public abstract class I
{

    public static final byte F = 0;
    public static final byte E = 8;
    public static final byte D = 9;
    public static final byte C = 20;
    public static final byte H = 15;
    private Map A;
    private boolean B;
    protected byte G[];

    protected I(boolean flag)
    {
        A = new LinkedHashMap();
        G = new byte[20000];
        B = flag;
    }

    public abstract int C();

    public Packet D()
    {
        return new Packet(G, C());
    }

    public Packet A(int i)
    {
        Packet b = new Packet(G, C());
        b.E(i);
        return b;
    }

    public Map B()
    {
        return A;
    }

    public boolean A()
    {
        return B;
    }
}


text:
<?php
/**
 * @author @jenschude <jens.schulze@commercetools.de>
 */

namespace Commercetools\Core\Model\Order;

use Commercetools\Core\Model\Channel\ChannelReference;
use Commercetools\Core\Model\Common\JsonObject;
use Commercetools\Core\Model\Common\DateTimeDecorator;
use DateTime;

/**
 * @package Commercetools\Core\Model\Order
 * @link https://docs.commercetools.com/http-api-projects-orders.html#syncinfo
 * @method ChannelReference getChannel()
 * @method SyncInfo setChannel(ChannelReference $channel = null)
 * @method string getExternalId()
 * @method SyncInfo setExternalId(string $externalId = null)
 * @method DateTimeDecorator getSyncedAt()
 * @method SyncInfo setSyncedAt(DateTime $syncedAt = null)
 */
class SyncInfo extends JsonObject
{
    public function fieldDefinitions()
    {
        return [
            'channel' => [static::TYPE => ChannelReference::class],
            'externalId' => [static::TYPE => 'string'],
            'syncedAt' => [
                static::TYPE => DateTime::class,
                static::DECORATOR => DateTimeDecorator::class
            ]
        ];
    }
}


text:
EasyTable::Config.configure do |config|
  config.table_html = { class: 'easy-table table table-bordered' }

  config.action_td_html =  { class: 'action'}
end


text:
'use strict';
var LIBRARY         = require('./$.library')
  , $def            = require('./$.def')
  , $redef          = require('./$.redef')
  , hide            = require('./$.hide')
  , has             = require('./$.has')
  , SYMBOL_ITERATOR = require('./$.wks')('iterator')
  , Iterators       = require('./$.iterators')
  , FF_ITERATOR     = '@@iterator'
  , KEYS            = 'keys'
  , VALUES          = 'values';
var returnThis = function(){ return this; };
module.exports = function(Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCE){
  require('./$.iter-create')(Constructor, NAME, next);
  var createMethod = function(kind){
    switch(kind){
      case KEYS: return function keys(){ return new Constructor(this, kind); };
      case VALUES: return function values(){ return new Constructor(this, kind); };
    } return function entries(){ return new Constructor(this, kind); };
  };
  var TAG      = NAME + ' Iterator'
    , proto    = Base.prototype
    , _native  = proto[SYMBOL_ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT]
    , _default = _native || createMethod(DEFAULT)
    , methods, key;
  // Fix native
  if(_native){
    var IteratorPrototype = require('./$').getProto(_default.call(new Base));
    // Set @@toStringTag to native iterators
    require('./$.tag')(IteratorPrototype, TAG, true);
    // FF fix
    if(!LIBRARY && has(proto, FF_ITERATOR))hide(IteratorPrototype, SYMBOL_ITERATOR, returnThis);
  }
  // Define iterator
  if(!LIBRARY || FORCE)hide(proto, SYMBOL_ITERATOR, _default);
  // Plug for library
  Iterators[NAME] = _default;
  Iterators[TAG]  = returnThis;
  if(DEFAULT){
    methods = {
      keys:    IS_SET            ? _default : createMethod(KEYS),
      values:  DEFAULT == VALUES ? _default : createMethod(VALUES),
      entries: DEFAULT != VALUES ? _default : createMethod('entries')
    };
    if(FORCE)for(key in methods){
      if(!(key in proto))$redef(proto, key, methods[key]);
    } else $def($def.P + $def.F * require('./$.iter-buggy'), NAME, methods);
  }
};


text:
Available Widget Blocks

{% for block in display.blocks_seen %}

{{block}}

{% endfor %}


text:
package org.apache.clerezza;

/**
 * A graph, modeled as a set of triples.
 * This interface does not extend java.util.Set because of the different
 * identity constraints, i.e. two Graphs may be equal (isomorphic)
 * even if the set of triples are not.
 *

 * Implementations MUST be immutable and throw respective exceptions, when
 * add/remove-methods are called.
 *
 * @author reto
 */
public interface ImmutableGraph extends Graph {

    /**
     * Returns true if two graphs are isomorphic
     *
     * @return true if two graphs are isomorphic
     */
    @Override
    public boolean equals(Object obj);

    /**
     * Return the sum of the blank-nodes independent hashes of the triples.
     * More precisely the hash of the triple is calculated as follows:
     * {@literal (hash(subject) >> 1) ^  hash(hashCode) ^ (hash(hashCode) << 1)}
     * Where the hash-function return the hashCode of the argument
     * for grounded arguments and 0 otherwise.
     *
     * @return hash code
     */
    @Override
    public int hashCode();
}


text:
<title>Python Commands - Debugging with GDB</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="Debugging with GDB">
<meta name="generator" content="makeinfo 4.13">
<link title="Top" rel="start" href="index.html#Top">
<link rel="up" href="Python.html#Python" title="Python">
<link rel="next" href="Python-API.html#Python-API" title="Python API">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">

<meta http-equiv="Content-Style-Type" content="text/css">

<link rel="stylesheet" type="text/css" href="../cs.css">

Next: Python API,
Up: Python

23.2.1 Python Commands

gdb provides two commands for accessing the Python interpreter,
and one related setting:

python-interactive [<var>command</var>]
pi [<var>command</var>]
Without an argument, the python-interactive command can be used
to start an interactive Python prompt.  To return to gdb,
type the EOF character (e.g., Ctrl-D on an empty prompt).

Alternatively, a single-line Python command can be given as an
argument and evaluated.  If the command is an expression, the result
will be printed; otherwise, nothing will be printed.  For example:

          (gdb) python-interactive 2 + 3
          5

python [<var>command</var>]
py [<var>command</var>]
The python command can be used to evaluate Python code.

If given an argument, the python command will evaluate the
argument as a Python command.  For example:

          (gdb) python print 23
          23

If you do not provide an argument to python, it will act as a
multi-line command, like define.  In this case, the Python
script is made up of subsequent command lines, given after the
python command.  This command list is terminated using a line
containing end.  For example:

          (gdb) python
          Type python script
          End with a line saying just "end".
          >print 23
          >end
          23

set python print-stack
By default, gdb will print only the message component of a
Python exception when an error occurs in a Python script.  This can be
controlled using set python print-stack: if full, then
full Python stack printing is enabled; if none, then Python stack
and message printing is disabled; if message, the default, only
the message component of the error is printed.

It is also possible to execute a Python script from the gdb
interpreter:

source <samp>script-name</samp>
The script name must end with ‘<samp>.py</samp>’ and gdb must be configured
to recognize the script language based on filename extension using
the script-extension setting.  See Extending GDB.

python execfile ("script-name")
This method is based on the execfile Python built-in function,
and thus is always available.


text:
enum
{
    OAD_CMDPROC_START  = 0x00,
    OAD_CMDPROC_IMAGE_IDENTITY,
    OAD_CMDPROC_BLOCK_REQ,
    OAD_CMDPROC_BLOCK_RESP,
    OAD_CMDPROC_UPGRD_END,
};

void oad_cmdproc_enable(cmdproc_recv_cb cb);
void oad_cmdproc_start(void);
void oad_cmdproc_image_identity(struct oad_file_info* file_info);
void oad_cmdproc_block_req(struct oad_file_info* file_info, uint32_t file_offset, uint8_t data_len);
void oad_cmdproc_upgrd_end(uint8_t status, struct oad_file_info* file_info);

#endif


text:
import java.util.List;

class A {
  public static void main(String[] args){
    List l = new List();
    Object [] objs = new Object[0];
    l.addAll(<caret>objs);
  }
}


text:
package com.amazonaws.services.iotfleethub.model;

import javax.annotation.Generated;

/**
 * Base exception for all service exceptions thrown by AWS IoT Fleet Hub
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class AWSIoTFleetHubException extends com.amazonaws.AmazonServiceException {

    private static final long serialVersionUID = 1L;

    /**
     * Constructs a new AWSIoTFleetHubException with the specified error message.
     *
     * @param message
     *        Describes the error encountered.
     */
    public AWSIoTFleetHubException(String message) {
        super(message);
    }

}


text:
using Codex.ObjectModel;
using System;
using System.IO;
using System.Runtime.CompilerServices;
using System.Web;

namespace Codex.View
{
    public static partial class ViewUtilities
    {
        //public static Visibility BoolVisibility(bool isVisible)
        //{
        //    return isVisible ? Visibility.Visible : Visibility.Collapsed;
        //}

        public static void Bind<TValue>(this Bound<TValue> bound, Action<TValue> onUpdate)
        {
            bound.OnUpdate(value => onUpdate(value));
            onUpdate(bound.Value);
        }

        public static T Increment<T>(this T value, Counter counter)
        {
            counter.Increment();
            return value;
        }

        public static T Add<T>(this T value, Func<T, int> computeCount)
            where T : IResultsStats
        {
            computeCount(value);
            return value;
        }

        public static T AddTo<T>(this T value, Counter counter)
            where T : IResultsStats
        {
            counter.Add(value.Counter.Count);
            return value;
        }

        public static T AddFrom<T>(this T value, Counter counter)
            where T : IResultsStats
        {
            value.Counter.Add(counter.Count);
            return value;
        }

        public static string Url(string value)
        {
            return HttpUtility.UrlEncode(value);
        }

        public static string Html(string value)
        {
            return HttpUtility.HtmlEncode(value);
        }

        public static void Html(string value, TextWriter writer)
        {
            HttpUtility.HtmlEncode(value, writer);
        }

        public static string Attr(string value)
        {
            return HttpUtility.HtmlAttributeEncode(value);
        }

        //public static DependencyProperty RegisterDependencyProperty<TOwner, TPropertyType>(
        //    [CallerMemberName] string dependencyPropertyName = null,
        //    Action<TOwner, TPropertyType> onPropertyChanged = null,
        //    TPropertyType defaultValue = default(TPropertyType))
        //    where TOwner : class
        //{
        //    return DependencyProperty.Register(dependencyPropertyName.Substring(0, dependencyPropertyName.Length - "Property".Length),
        //        typeof(TPropertyType),
        //        typeof(TOwner),
        //        onPropertyChanged != null ?
        //            new PropertyMetadata(defaultValue, (DependencyObject owner, DependencyPropertyChangedEventArgs args) =>
        //            {
        //                onPropertyChanged(owner as TOwner, (TPropertyType)args.NewValue);
        //            }) :
        //            new PropertyMetadata(defaultValue));
        //}

        public static string GetReferencesHeader(ReferenceKind referenceKind, int referenceCount, string symbolName)
        {
            string formatString = "";
            switch (referenceKind)
            {
                case ReferenceKind.Reference:
                    formatString = "{0} reference{1} to {2}";
                    break;
                case ReferenceKind.Definition:
                    formatString = "{0} definition{1} of {2}";
                    break;
                case ReferenceKind.Constructor:
                    formatString = "{0} constructor{1} of {2}";
                    break;
                case ReferenceKind.Instantiation:
                    formatString = "{0} instantiation{1} of {2}";
                    break;
                case ReferenceKind.DerivedType:
                    formatString = "{0} type{1} derived from {2}";
                    break;
                case ReferenceKind.InterfaceInheritance:
                    formatString = "{0} interface{1} inheriting from {2}";
                    break;
                case ReferenceKind.InterfaceImplementation:
                    formatString = "{0} implementation{1} of {2}";
                    break;
                case ReferenceKind.Override:
                    formatString = "{0} override{1} of {2}";
                    break;
                case ReferenceKind.InterfaceMemberImplementation:
                    formatString = "{0} implementation{1} of {2}";
                    break;
                case ReferenceKind.Write:
                    formatString = "{0} write{1} to {2}";
                    break;
                case ReferenceKind.Read:
                    formatString = "{0} read{1} of {2}";
                    break;
                case ReferenceKind.GuidUsage:
                    formatString = "{0} usage{1} of Guid {2}";
                    break;
                case ReferenceKind.EmptyArrayAllocation:
                    formatString = "{0} allocation{1} of empty arrays";
                    break;
                case ReferenceKind.MSBuildPropertyAssignment:
                    formatString = "{0} assignment{1} to MSBuild property {2}";
                    break;
                case ReferenceKind.MSBuildPropertyUsage:
                    formatString = "{0} usage{1} of MSBuild property {2}";
                    break;
                case ReferenceKind.MSBuildItemAssignment:
                    formatString = "{0} assignment{1} to MSBuild item {2}";
                    break;
                case ReferenceKind.MSBuildItemUsage:
                    formatString = "{0} usage{1} of MSBuild item {2}";
                    break;
                case ReferenceKind.MSBuildTargetDeclaration:
                    formatString = "{0} declaration{1} of MSBuild target {2}";
                    break;
                case ReferenceKind.MSBuildTargetUsage:
                    formatString = "{0} usage{1} of MSBuild target {2}";
                    break;
                case ReferenceKind.MSBuildTaskDeclaration:
                    formatString = "{0} import{1} of MSBuild task {2}";
                    break;
                case ReferenceKind.MSBuildTaskUsage:
                    formatString = "{0} call{1} to MSBuild task {2}";
                    break;
                case ReferenceKind.Text:
                    formatString = "{0} text search hit{1} for '{2}'";
                    break;
                default:
                    throw new NotImplementedException("Missing case for " + referenceKind);
            }

            return string.Format(formatString,
                    referenceCount,
                    referenceCount == 1 ? "" : "s",
                    symbolName);
        }

    }
}


text:
from allauth.socialaccount.tests import OAuthTestsMixin
from allauth.tests import MockedResponse, TestCase

from .provider import VimeoProvider

class VimeoTests(OAuthTestsMixin, TestCase):
    provider_id = VimeoProvider.id

    def get_mocked_response(self):
        return [MockedResponse(200, """
{"generated_in":"0.0137",
 "stat":"ok","person":{
 "created_on": "2013-04-08 14:24:47",
 "id":"17574504",
 "is_contact":"0",
 "is_plus":"0","is_pro":"0","is_staff":"0","is_subscribed_to":"0",
 "username":"user17574504","display_name":"Raymond Penners","location":"",
 "url":[""],"bio":"","number_of_contacts":"0","number_of_uploads":"0",
 "number_of_likes":"0","number_of_videos":"0",
 "number_of_videos_appears_in":"0","number_of_albums":"0",
 "number_of_channels":"0","number_of_groups":"0",
 "profileurl":"http:\\/\\/vimeo.com\\/user17574504",
 "videosurl":"http:\\/\\/vimeo.com\\/user17574504\\/videos",
 "portraits":{"portrait":[{"height":"30","width":"30",
 "_content":
 "http:\\/\\/a.vimeocdn.com\\/images_v6\\/portraits\\/portrait_30_yellow.png"},
 {"height":"75","width":"75","_content":
 "http:\\/\\/a.vimeocdn.com\\/images_v6\\/portraits\\/portrait_75_yellow.png"},
 {"height":"100","width":"100","_content":
 "http:\\/\\/a.vimeocdn.com\\/images_v6\\/portraits\\/portrait_100_yellow.png"},
 {"height":"300","width":"300","_content":
 "http:\\/\\/a.vimeocdn.com\\/images_v6\\/portraits\\/portrait_300_yellow.png"}]}}}
""")]


text:
package org.wso2.sample.jaxb.model;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

@XmlRootElement(name = "book")
@XmlType(propOrder = { "author", "name", "publisher", "isbn" })
public class Book {
    private String name;
    private String author;
    private String publisher;
    private String isbn;

    @XmlElement(name = "title")
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public String getPublisher() {
        return publisher;
    }

    public void setPublisher(String publisher) {
        this.publisher = publisher;
    }

    public String getIsbn() {
        return isbn;
    }

    public void setIsbn(String isbn) {
        this.isbn = isbn;
    }
}


text:
layout: default
title: Apache Metron Community
---

real-time big data security

Talks

News

Talks

 Talks delivered on OpenSoc and Metron at different forums

        See the Videos

News

 Follow us on ...

                 Follow @ApacheMetron

 Tweet us on ...

            Tweet to @ApacheMetron


text:
var filters = {
  id: function(post){
    return post.id || post._id;
  },
  title: function(post){
    return post.slug;
  },
  year: function(post){
    return post.date.format('YYYY');
  },
  month: function(post){
    return post.date.format('MM');
  },
  day: function(post){
    return post.date.format('DD');
  },
  i_month: function(post){
    return post.date.format('M');
  },
  i_day: function(post){
    return post.date.format('D');
  },
  category: function(post){
    var categories = post.categories;

    if (categories.length){
      var category = categories[categories.length - 1],
        Category = hexo.model('Category'),
        slug = Category.get(category).slug;

      return slug;
    } else {
      return hexo.config.default_category;
    }
  }
};

module.exports = function(data){
  return hexo.config.permalink.replace(/:(\w+)/g, function(match, name){
    if (filters.hasOwnProperty(name)){
      return filters[name](data);
    } else {
      return data[name];
    }
  });
};


text:
'''==================================================================================================
    title:              main_lwa_preset.py
    author:             Artur Mrowca
    last modified:      24/07/2015
    usage:              python main_lwa_preset.py
    python version:     3.0
    description:        this module exemplarily shows the functionality of the ECUSimulation
                        project for the Lightweight authentication environment as it is defined
                        in the paper "Lightweight Authentication for Secure Automotive Networks"
                        by Phillipp Mundhenk et al. It also describes how the API of the ECUSimulation
                        should be used. Thereby the LWASpecPresets is used to setup the project
=================================================================================================='''

import logging
import os
from api.core.api_core import TimingFunctionSet
import api.ecu_sim_api as api
from components.security.ecu.types.impl_ecu_secure import StdSecurECUTimingFunctions
from components.security.ecu.types.impl_sec_mod_lwa import StdSecurLwSecModTimingFunctions
from enums.sec_cfg_enum import CAEnum, HashMechEnum, AsymAuthMechEnum, \
    AuKeyLengthEnum, SymAuthMechEnum
from components.security.communication.stream import MessageStream
import gui.direct_view_window
from components.base.gateways.impl_can_gateway import CANGateway  # @UnusedImport
from config import can_registration
from api.core.component_specs import RegularECUSpec, SimpleECUSpec, \
    SimpleBusCouplerSpec, SimpleBusSpec
from io_processing.surveillance import Monitor
from io_processing.result_reader import ResultReader
from io_processing.result_interpreter.abst_result_interpreter import InterpreterOptions
from io_processing.result_interpreter.can_bus_interpreter import CanBusInterpreter
from io_processing.result_interpreter.eventline_interpreter import EventlineInterpreter
from io_processing.result_interpreter.checkpoint_interpreter import CheckpointInterpreter
from io_processing.result_interpreter.buffer_interpreter import BufferInterpreter
from io_processing.surveillance_handler import InputHandlerChain, EventlineHandler  # @UnusedImport
from config.specification_set import LWASpecPresets, GeneralSpecPreset
from components.base.ecu.software.impl_datalink_layers import StdDatalinkLayer, \
    RapidDatalinkLayer
from components.base.ecu.software.impl_transport_layers import StdTransportLayer, \
    FakeSegmentTransportLayer
from components.base.ecu.software.impl_physical_layers import StdPhysicalLayer
from config.timing_db_admin import TimingDBMap

#===============================================================================
#     Define predefined settings (All that are available provided here)
#===============================================================================
LWASpecPresets().preset_ecu = "Crypto_Lib_HW"
LWASpecPresets().preset_sec_mod = "Crypto_Lib_HW"

LWASpecPresets().trigger_spec = [0, 99999999]  # authentication: start time and interval

LWASpecPresets().sec_certificate_spec = [HashMechEnum.MD5, AsymAuthMechEnum.RSA, AuKeyLengthEnum.bit_512, 65537, 1, 1000]  # security module certificate info

LWASpecPresets().registration_first_part = [AsymAuthMechEnum.RSA, AuKeyLengthEnum.bit_512, 65537, 100]  # registration message first part
LWASpecPresets().registration_second_part = [HashMechEnum.MD5, AsymAuthMechEnum.RSA, AuKeyLengthEnum.bit_512, 65537]  # registration message second part
LWASpecPresets().ecu_certificate_spec = [HashMechEnum.MD5, AsymAuthMechEnum.RSA, AuKeyLengthEnum.bit_512, 65537, 1, 1000]  # ecu certificate info

LWASpecPresets().confirmation_part = [100]  # confirmation message size

LWASpecPresets().ecu_key_info = [SymAuthMechEnum.AES, AuKeyLengthEnum.bit_128, SymAuthMechEnum.ECB]  # ecu key specification
LWASpecPresets().hold_rule = [False, 10]  # hold on/off; minimal interval between two stream requests

LWASpecPresets().request_spec = [100, 9999999999]  # size of request message and timeout maximum

LWASpecPresets().deny_spec = [100]  # deny message size
LWASpecPresets().grant_spec = [100]  # grant message size

LWASpecPresets().session_key_info = [SymAuthMechEnum.AES, AuKeyLengthEnum.bit_128, SymAuthMechEnum.ECB]  # session key information

# set further layer specifications
GeneralSpecPreset().enable()
GeneralSpecPreset().physical_layer = StdPhysicalLayer
GeneralSpecPreset().datalink_layer = StdDatalinkLayer  # datalink layer that is used in all ECUs that implement this option
GeneralSpecPreset().transport_layer = FakeSegmentTransportLayer

TimingDBMap().enable_fallback_message = True

#===============================================================================
#     Setting up a project
#===============================================================================

# register ECUs that are located outside of the usual folders
# usual folders: components.base.ecu.types and components.security.ecu.types
#api.register_ecu_classes(r"C:\Users\artur.mrowca\workspace\ECUSimulation\components\base\gateways")

# setup the logging
api_log_path = os.path.join(os.path.dirname(__file__), "logs/api.log")
api.show_logging(logging.INFO, api_log_path, True)

# create an empty environment specification for the environment
sim_env = api.create_environment(200)

#===============================================================================
#     Creating ECUs
#===============================================================================

# create the ECU specification
ecu_spec = RegularECUSpec(["RegularSecureECU_15"], 20000, 20000)

# adjust the specification
ecu_spec.set_apply_jitter(0.000001)

# further settings can be found in the set_settings method of each component e.g. see RegularSecureECU class
ecu_spec.set_ecu_setting('p_stream_hold', False)
ecu_spec.set_ecu_setting('p_stream_req_min_interval', 5)
LWASpecPresets().apply_spec(ecu_spec, 'ecu')

# for a RegularECUSpec define sending actions of the ECU
ecu_spec.add_sending_actions(10, 0.25, can_registration.CAN_TEST_MSG, "TEST STRING A", 50)
ecu_spec.add_sending_actions(10, 0.5, 16, "TEST STRING B", 50)  # sends at 300, 308, 316, ...

# set the ECU already authenticated
ecu_spec.set_authenticated(True)

# generate a ECU group from the specification
ecu_group_1 = api.set_ecus(sim_env, 1, 'RegularSecureECU', ecu_spec)

# create further ECU groups
ecu_spec = RegularECUSpec(["RegularSecureECU_1", "RegularSecureECU_10"], 20000, 20000)
ecu_spec.set_apply_jitter(0.0001)
LWASpecPresets().apply_spec(ecu_spec, 'ecu')
ecu_group_3 = api.set_ecus(sim_env, 2, 'RegularSecureECU', ecu_spec)

ecu_spec = RegularECUSpec(["RegularSecureECU_18", "Any_ECU_Name"], 20000, 20000)
ecu_spec.set_apply_jitter(0.0001)
# ecu_spec.set_startup_delay(140)  # start this ecu with delay of 15

LWASpecPresets().apply_spec(ecu_spec, 'ecu')
ecu_group_4 = api.set_ecus(sim_env, 3, 'RegularSecureECU', ecu_spec)

#===============================================================================
#     Creating Security modules
#===============================================================================

# create the ECU specification
ecu_spec = SimpleECUSpec(['SEC 1'], 200000, 200000)  # 200 KB

# adjust the specification
ecu_spec.set_ecu_setting('t_ecu_auth_trigger_process', 0)
ecu_spec.set_ecu_setting('t_ecu_auth_trigger_intervall', 1000)
ecu_spec.set_apply_jitter(0.0001)
LWASpecPresets().apply_spec(ecu_spec, 'sec_mod')

# create exactly one security module
sec_mod_group = api.set_ecus(sim_env, 1, 'SecLwAuthSecurityModule', ecu_spec)
security_module = sec_mod_group[0]

#===============================================================================
#     Creating Gateways
#===============================================================================

# create the Gateway specification
ecu_spec = SimpleBusCouplerSpec([])

# set gateway delay to 2 seconds
ecu_spec.set_ecu_setting('t_transition_process', 2)

# add a jitter
# ecu_spec.set_apply_jitter(0.000001)

# set a filter
# Add a filter to the gateway. Generally blocks those ids// do not use in combination with api.gateway_filter_bus
# ecu_spec.set_filter(can_registration.AUTH_MESSAGES + [can_registration.CAN_TEST_MSG, 500, 16])

# create the gateway
gateway_group_1 = api.set_ecus(sim_env, 1, 'CANGateway', ecu_spec)

# create another gateway with same specification
gateway_group_2 = api.set_ecus(sim_env, 1, 'CANGateway', ecu_spec)

#===============================================================================
#     Creating Busses
#===============================================================================

# create the bus specifications
bus_spec = SimpleBusSpec(['CAN_0', 'CAN_1', 'CAN_2'])
bus_group = api.set_busses(sim_env, 3, 'StdCANBus', bus_spec)

# Connect ECUs and Gateways to the busses
# Connect CAN 0 via GW1 to CAN 1 // Connect CAN 1 via GW 2 to CAN 2
api.connect_bus_by_obj(sim_env, 'CAN_0', ecu_group_1 + sec_mod_group + gateway_group_1)
api.connect_bus_by_obj(sim_env, 'CAN_1', gateway_group_1 + ecu_group_3 + gateway_group_2)
api.connect_bus_by_obj(sim_env, 'CAN_2', ecu_group_4 + gateway_group_2)

#===============================================================================
#    Setting a gateway filter: 2 types
#===============================================================================

# type 1 - receive filter: only the defined message ids will be received from the defined bus
# in this example: gateway 1 will only receive message ids 1,2,3,4,5 from CAN_0 - all others are discarded
#                  analogously it only receives message ids 1,2,3,4,5,2730,511 from CAN_1 - all others are discarded
# api.gateway_filter_bus(gateway_group_1, {'CAN_0':[1,2,3,4,5], 'CAN_1':[1,2,3,4,5,2730,511]})

# type 1 - receive filter: only the defined message ids will be forwarded to the defined bus
# in this example: gateway 1 will only transmit message ids 1, 2, 3, 4, 2730, 5, 6, 7, 8, 9 to CAN_0 - all others are not forwarded to this bus
#                  analogously it only transmits message ids 1, 2, 3, 4, 5, 6, 7, 8, 9, 2730, 511 to CAN_1 - all others are not forwarded to this bus
# api.gateway_filter_sending_bus(gateway_group_1, {'CAN_0':[1, 2, 3, 4, 2730, 5, 6, 7, 8, 9], 'CAN_1':[1, 2, 3, 4, 5, 6, 7, 8, 9, 2730, 511], 'CAN_2':[1, 2, 3, 4, 5, 6, 7, 8, 9, 2730, 511]})

#==============================================================================
#    setup security values of ECUs
#==============================================================================

# register all ECUs to the security module
all_ecu_groups = [ecu_group_1 + ecu_group_3 + ecu_group_4]
api.register_ecu_groups_to_secmod(sim_env, security_module.ecu_id, all_ecu_groups)

# generate the certificates for the ECUs
# the constellation of the certificate - i.e. its organization in the CA hierarchy is set
# in the certificate_manager object
certificate_manager = api.create_cert_manager()

# create a certificate signed by CA CAEnum.CA_L313 defined in the CAHierarchy() that was defined in the
# certificate manager. A custom CAHierarchy can be passed to the api.create_cert_manager() class
all_created_ecus = api.ecu_list_from_groups([all_ecu_groups])
ecu_ids = [ecu.ecu_id for ecu in all_created_ecus]

# generate certificates for the ECUs and setting root certificates to the corresponding security module
for ecu_id in ecu_ids:
    api.generate_valid_ecu_cert_cfg(certificate_manager, ecu_id, CAEnum.CA_L313, security_module.ecu_id, 0, float('inf'))

# generate a certificate in the security module and setting root certificates to all ecus passed in the list ecu_ids
api.generate_valid_sec_mod_cert_cfg(certificate_manager, security_module.ecu_id, CAEnum.CA_L313, ecu_ids, 0, float('inf'))

# apply the certification
api.apply_certification(sim_env, certificate_manager)

#===============================================================================
#     Setup the streams
#===============================================================================

# add allowed streams to the to the security module which is responsible for managing requested streams
stream_1 = MessageStream('RegularSecureECU_15', ['RegularSecureECU_1', 'RegularSecureECU_18'], can_registration.CAN_TEST_MSG, float('inf'), 0, float('inf'))
stream_2 = MessageStream('RegularSecureECU_15', ['Any_ECU_Name'], 16, float('inf'), 0, float('inf'))

api.add_allowed_stream(sim_env, security_module.ecu_id, stream_1)
api.add_allowed_stream(sim_env, security_module.ecu_id, stream_2)

# this method defines the gateway filter in the following way
# only streams are let pass that are headed in the right direction
# so if a stream with id 60 is defined from E1 at CAN1 and headed to E2 at CAN0 via Gateway G1
# then this message would be filtered out when sent from  CAN0 to CAN1
# or if a message is heading to E2 that was not declared in the streams it will not be forwarded
# to CAN0
api.autoset_gateway_filters(sim_env, security_module.ecu_id)

#===============================================================================
#     Defining functions called when accessing the timeout values
#===============================================================================

# create mapping from functions onto timing variables
# e.g. t_ecu_auth_reg_msg_validate_cert should call function my_test_function
#      def my_test_function(*args):
#          ''' do something '''
#      -> function_set.set_mapping('RegularSecureECU_15', 't_ecu_auth_reg_msg_validate_cert', my_test_function)
function_set = TimingFunctionSet()

# create a timing function set for a Security Module
# this mapping contains all mappings from timing variables used in the security module
# to methods that are called when those timings are accessed
# i.e. set a set of functions to a set of timing variables instead of mapping each function seperately
# in this case the timing value is determined from the database by using the key word CyaSSL under
# the library column in the measurements.db database. If another set of measurements was made
# the main_library_tag can be set to the new value
ecu_func_set = StdSecurLwSecModTimingFunctions(main_library_tag=LWASpecPresets().preset_sec_mod)

# set the function set as mapping to be used
function_set.set_mapping_from_function_set(security_module.ecu_id, ecu_func_set)

# apply this function set now on the specified ECU with the defined id
api.apply_timing_functions_set(sim_env, security_module.ecu_id, function_set)

# optional: as mentioned above the function_set.set_mapping method would override the methods
#           used and defined in the function set

# analogously: do same for all ECUs
function_set_2 = TimingFunctionSet()
ecu_func_set = StdSecurECUTimingFunctions(main_library_tag=LWASpecPresets().preset_ecu)
for ecu_id in ecu_ids:
    function_set_2.set_mapping_from_function_set(ecu_id, ecu_func_set)
    api.apply_timing_functions_set(sim_env, ecu_id, function_set_2)

#===========================================================================
#     Monitoring and Export of Results
#
#    Structure:
#    environment connected to monitor object
#    monitor object connected to ResultReader object
#    ResultReader publishes data to the Interpreters
#    Interpreters pass the data to connected GUI and/or to Files
#===========================================================================

# create a Monitor and connect it to the environment
monitor = Monitor()
monitor.set_sample_time(0.48)

# connect monitor to environment
api.connect_monitor(sim_env, monitor, 0.5)

# optional: if only defined handlers should be called when the monitor receives
#           its values, it can be defined as follows which handlers are to be used
#           if not set all handlers will be called
# only information given in those handlers will be saved all other information is discarded

# input_handler = InputHandlerChain()
# # input_handler.add_handler(CheckpointHandler(monitor._tmp_db, monitor.con))
# # input_handler.add_handler(CanBusHandler(monitor._tmp_db, monitor.con))
# # input_handler.add_handler(BufferHandler(monitor._tmp_db, monitor.con))
# input_handler.add_handler(EventlineHandler(monitor._tmp_db, monitor.con))
# input_handler = input_handler.handler()
# monitor.set_handler_chain(input_handler)

# create a Result Reader that is used to export the
# simulation results to the GUI or to a file
result_reader = ResultReader()
save_path_cp = os.path.join(os.path.dirname(__file__), "logs/checkpoints.csv")
save_path_buf = os.path.join(os.path.dirname(__file__), "logs/buffer.csv")
save_path_can = os.path.join(os.path.dirname(__file__), "logs/can_bus.csv")

# enable certain handlers to define which export has to be made
# a result reader receives the interpreter to be used and the InterpreterOptions enum
# defining how the export should be performed
result_reader.enable_handler(BufferInterpreter, [InterpreterOptions.CONNECTION, InterpreterOptions.CSV_FILE], save_path_buf)
result_reader.enable_handler(CheckpointInterpreter, [ InterpreterOptions.TIMING_FILE], save_path_cp)
result_reader.enable_handler(EventlineInterpreter, [InterpreterOptions.CSV_FILE], save_path_cp)  # CSV Live Tracking
result_reader.enable_handler(CanBusInterpreter, [InterpreterOptions.CSV_MSG_FILE, InterpreterOptions.CSV_DR_FILE], save_path_can)

# connect the result reader to the monitor
api.connect_result_reader(sim_env, monitor, result_reader)

#===============================================================================
#     Using the GUI
#     ::> if the ECUInteraction project is available the GUI can be used
#         in the following way
#===============================================================================

# create the direct view
direct_view = gui.direct_view_window.DirectViewer()

# load saved views
# filepath = r"C:\Users\artur.mrowca\Desktop\aaa.tum"
# direct_view.load_show(['MessageCountViewPlugin', 'EventlineViewPlugin'], filepath)
# sys.exit()

# Create the Viewer and add it
# available Plugins: BufferViewPlugin, CanBusStateViewPlugin, CanBusViewPlugin, CheckpointViewPlugin,
#                    ConstellationViewPlugin, ECUMessagesViewPlugin, EventlineViewPlugin, MessageCountViewPlugin
sim_env.gui_lock_sync.acquire()  # optionally ensure thread synchronization
direct_view.run(result_reader, ['EventlineViewPlugin', 'MessageCountViewPlugin'], sim_env.gui_lock_sync)  # optional: sim_env.gui_lock_sync

# creates a button that makes the simulation stop calling on finish for all interpreters
api.open_simulation_stop_button(sim_env)

# build the simulation
api.build_simulation(sim_env)

# run the simulation
api.run_simulation(sim_env)


text:
/*
 * Advent of Code 2016
 * Day 8 (part 1)
 *
 * Command: clang++ --std=c++14 day08a.cpp
 *
 */

#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <unordered_map>
#include <vector>

using namespace std;

const string INPUT_FILE = "input08.txt";
const int MAX_LINE_LENGTH = 2000;
const int DISPLAY_WIDTH = 50;
const int DISPLAY_HEIGHT = 6;

void split(const std::string &s, char delim, std::vector<std::string> &elems) {
	std::stringstream ss;
	ss.str(s);
	std::string item;
	while (std::getline(ss, item, delim)) {
		elems.push_back(item);
	}
}

std::vector<std::string> split(const std::string &s, char delim) {
	std::vector<std::string> elems;
	split(s, delim, elems);
	return elems;
}

string make_coordinate(int x, int y) {
	return to_string(y) + "," + to_string(x);
}

void printDisplay(unordered_map<string, bool> display) {
	for (int x = 0; x < DISPLAY_HEIGHT; x++) {
		for (int y = 0; y < DISPLAY_WIDTH; y++) {
			string coordinate = make_coordinate(x, y);
			bool on = display[coordinate];

			if (on) {
				cout << "#";
			} else {
				cout << ".";
			}
		}

		cout << endl;
	}
}

int main(void) {
	// Open the input file
	ifstream fin(INPUT_FILE);
	if (!fin) {
		cerr << "Error reading input file " << INPUT_FILE << endl;
		return -1;
	}

	// Read the input
	vector<string> input;
	char cInput[MAX_LINE_LENGTH];
	while (fin.getline(cInput, MAX_LINE_LENGTH)) {
		input.push_back(string(cInput));
	}
	fin.close();

	// Solve the problem
	unordered_map<string, bool> display;

	// Initialize the entire display to off
	for (int x = 0; x < DISPLAY_HEIGHT; x++) {
		for (int y = 0; y < DISPLAY_WIDTH; y++) {
			string coordinate = make_coordinate(x, y);
			display[coordinate] = false;
		}
	}

	for (auto line : input) {
		if ("rect " == line.substr(0, 5)) {
			vector<string> sizes = split(line.substr(5), 'x');
			int width = stoi(sizes.at(0));
			int height = stoi(sizes.at(1));

			for (int x = 0; x < height; x++) {
				for (int y = 0; y < width; y++) {
					string coordinate = make_coordinate(x, y);
					display[coordinate] = true;
				}
			}
		} else if ("rotate column " == line.substr(0, 14)) {
			int equals = line.find("=");
			string end = line.substr(equals + 1);
			vector<string> numbers = split(end, ' ');

			int column = stoi(numbers.at(0));
			int distance = stoi(numbers.at(2));

			for (int i = 0; i < distance; i++) {
				// Save the bottom value
				bool saved = display[make_coordinate(DISPLAY_HEIGHT - 1, column)];

				// Move everything else down
				for (int row = 0; row < DISPLAY_HEIGHT; row++) {
					string coord = make_coordinate(row, column);

					bool temporary = display[coord];
					display[coord] = saved;
					saved = temporary;
				}
			}
		} else if ("rotate row " == line.substr(0, 11)) {
			int equals = line.find("=");
			string end = line.substr(equals + 1);
			vector<string> numbers = split(end, ' ');

			int row = stoi(numbers.at(0));
			int distance = stoi(numbers.at(2));

			for (int i = 0; i < distance; i++) {
				// Save the rightmost value
				bool saved = display[make_coordinate(row, DISPLAY_WIDTH - 1)];

				// Move everything else right
				for (int column = 0; column < DISPLAY_WIDTH; column++) {
					string coord = make_coordinate(row, column);

					bool temporary = display[coord];
					display[coord] = saved;
					saved = temporary;
				}
			}
		}
	}

	auto count = 0;
	for (auto element : display) {
		if (element.second) {
			count++;
		}
	}

	cout << "Count: " << count << endl;

	return 0;
}


text:
package org.elasticsearch.search.aggregations.metrics;

import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.index.SortedNumericDocValues;
import org.elasticsearch.common.lease.Releasables;
import org.elasticsearch.common.util.BigArrays;
import org.elasticsearch.common.util.LongArray;
import org.elasticsearch.index.fielddata.MultiGeoPointValues;
import org.elasticsearch.index.fielddata.SortedBinaryDocValues;
import org.elasticsearch.search.aggregations.Aggregator;
import org.elasticsearch.search.aggregations.InternalAggregation;
import org.elasticsearch.search.aggregations.LeafBucketCollector;
import org.elasticsearch.search.aggregations.LeafBucketCollectorBase;
import org.elasticsearch.search.aggregations.support.ValuesSource;
import org.elasticsearch.search.internal.SearchContext;

import java.io.IOException;
import java.util.Map;

/**
 * A field data based aggregator that counts the number of values a specific field has within the aggregation context.
 *
 * This aggregator works in a multi-bucket mode, that is, when serves as a sub-aggregator, a single aggregator instance aggregates the
 * counts for all buckets owned by the parent aggregator)
 */
class ValueCountAggregator extends NumericMetricsAggregator.SingleValue {

    final ValuesSource valuesSource;

    // a count per bucket
    LongArray counts;

    ValueCountAggregator(String name, ValuesSource valuesSource,
            SearchContext aggregationContext, Aggregator parent, Map<String, Object> metadata) throws IOException {
        super(name, aggregationContext, parent, metadata);
        this.valuesSource = valuesSource;
        if (valuesSource != null) {
            counts = context.bigArrays().newLongArray(1, true);
        }
    }

    @Override
    public LeafBucketCollector getLeafCollector(LeafReaderContext ctx,
            final LeafBucketCollector sub) throws IOException {
        if (valuesSource == null) {
            return LeafBucketCollector.NO_OP_COLLECTOR;
        }
        final BigArrays bigArrays = context.bigArrays();

        if (valuesSource instanceof ValuesSource.Numeric) {
            final SortedNumericDocValues values = ((ValuesSource.Numeric)valuesSource).longValues(ctx);
            return new LeafBucketCollectorBase(sub, values) {

                @Override
                public void collect(int doc, long bucket) throws IOException {
                    counts = bigArrays.grow(counts, bucket + 1);
                    if (values.advanceExact(doc)) {
                        counts.increment(bucket, values.docValueCount());
                    }
                }
            };
        }
        if (valuesSource instanceof ValuesSource.Bytes.GeoPoint) {
            MultiGeoPointValues values = ((ValuesSource.GeoPoint)valuesSource).geoPointValues(ctx);
            return new LeafBucketCollectorBase(sub, null) {

                @Override
                public void collect(int doc, long bucket) throws IOException {
                    counts = bigArrays.grow(counts, bucket + 1);
                    if (values.advanceExact(doc)) {
                        counts.increment(bucket, values.docValueCount());
                    }
                }
            };
        }
        // The following is default collector. Including the keyword FieldType
        final SortedBinaryDocValues values = valuesSource.bytesValues(ctx);
        return new LeafBucketCollectorBase(sub, values) {

            @Override
            public void collect(int doc, long bucket) throws IOException {
                counts = bigArrays.grow(counts, bucket + 1);
                if (values.advanceExact(doc)) {
                    counts.increment(bucket, values.docValueCount());
                }
            }

        };
    }

    @Override
    public double metric(long owningBucketOrd) {
        return (valuesSource == null || owningBucketOrd >= counts.size()) ? 0 : counts.get(owningBucketOrd);
    }

    @Override
    public InternalAggregation buildAggregation(long bucket) {
        if (valuesSource == null || bucket >= counts.size()) {
            return buildEmptyAggregation();
        }
        return new InternalValueCount(name, counts.get(bucket), metadata());
    }

    @Override
    public InternalAggregation buildEmptyAggregation() {
        return new InternalValueCount(name, 0L, metadata());
    }

    @Override
    public void doClose() {
        Releasables.close(counts);
    }

}


text:
layout: single
title: "sleepy sensate"
date: 2017-09-14
last_modified_at: 2017-09-15
tags: [poem, written, love]
excerpt: "I call to sleep, but sleep it won't come to me."
collection: poems
header:
  overlay_color: "#123456"
---
# sleepy sensate

so tired and anxious, so sleepless and

still.

my pillows no longer retain

the faintest smell

of

my love,

whose beautiful face

once slept—

> mere inches

from my lips, nose, eyes, ears,  and

fingers.

when next her head

lies sweetly next

to mine, i will

*sing her a song*

and

*kiss her lips*

and *stroke*

*her hair* and *smell*

*her neck*,

and *hear the sounds*

*she makes*

***when our skin***

***no longer***

has

***anything***

***between us.***


text: this is loading


text:
package org.opencypher.grammar;

public interface TermTransformation<P, T, EX extends Exception>
{
    T transformAlternatives( P param, Alternatives alternatives ) throws EX;

    T transformSequence( P param, Sequence sequence ) throws EX;

    T transformLiteral( P param, Literal literal ) throws EX;

    T transformNonTerminal( P param, NonTerminal nonTerminal ) throws EX;

    T transformOptional( P param, Optional optional ) throws EX;

    T transformRepetition( P param, Repetition repetition ) throws EX;

    T transformEpsilon( P param ) throws EX;

    T transformCharacters( P param, CharacterSet characters ) throws EX;
}