text:
#include <EGL/egl.h>
#include <GLES2/gl2.h>

#include "shader.h"
#include "JNIHelper.h"

namespace ndk_helper
{

#define DEBUG (1)

bool shader::CompileShader( GLuint *shader,
        const GLenum type,
        const char *str_file_name,
        const std::map<std::string, std::string>& map_parameters )
{
    std::vector < uint8_t > data;
    if( !JNIHelper::GetInstance()->ReadFile( str_file_name, &data ) )
    {
        LOGI( "Can not open a file:%s", str_file_name );
        return false;
    }

    const char REPLACEMENT_TAG = '*';
    //Fill-in parameters
    std::string str( data.begin(), data.end() );
    std::string str_replacement_map( data.size(), ' ' );

    std::map<std::string, std::string>::const_iterator it = map_parameters.begin();
    std::map<std::string, std::string>::const_iterator itEnd = map_parameters.end();
    while( it != itEnd )
    {
        size_t pos = 0;
        while( (pos = str.find( it->first, pos )) != std::string::npos )
        {
            //Check if the sub string is already touched

            size_t replaced_pos = str_replacement_map.find( REPLACEMENT_TAG, pos );
            if( replaced_pos == std::string::npos || replaced_pos > pos )
            {

                str.replace( pos, it->first.length(), it->second );
                str_replacement_map.replace( pos, it->first.length(), it->first.length(), REPLACEMENT_TAG );
                pos += it->second.length();
            }
            else
            {
                //The replacement target has been touched by other tag, skipping them
                pos += it->second.length();
            }
        }
        it++;
    }

    LOGI( "Patched Shdader:\n%s", str.c_str() );

    std::vector < uint8_t > v( str.begin(), str.end() );
    str.clear();
    return shader::CompileShader( shader, type, v );
}

bool shader::CompileShader( GLuint *shader,
        const GLenum type,
        const GLchar *source,
        const int32_t iSize )
{
    if( source == NULL || iSize <= 0 )
        return false;

    *shader = glCreateShader( type );
    glShaderSource( *shader, 1, &source, &iSize ); //Not specifying 3rd parameter (size) could be troublesome..

    glCompileShader( *shader );

#if defined(DEBUG)
    GLint logLength;
    glGetShaderiv( *shader, GL_INFO_LOG_LENGTH, &logLength );
    if( logLength > 0 )
    {
        GLchar *log = (GLchar *) malloc( logLength );
        glGetShaderInfoLog( *shader, logLength, &logLength, log );
        LOGI( "Shader compile log:\n%s", log );
        free( log );
    }
#endif

    GLint status;
    glGetShaderiv( *shader, GL_COMPILE_STATUS, &status );
    if( status == 0 )
    {
        glDeleteShader( *shader );
        return false;
    }

    return true;
}

bool shader::CompileShader( GLuint *shader,
        const GLenum type,
        std::vector<uint8_t>& data )
{
    if( !data.size() )
        return false;

    const GLchar *source = (GLchar *) &data[ 0 ];
    int32_t iSize = data.size();
    return shader::CompileShader( shader, type, source, iSize );
}

bool shader::CompileShader( GLuint *shader,
        const GLenum type,
        const char *strFileName )
{
    std::vector < uint8_t > data;
    bool b = JNIHelper::GetInstance()->ReadFile( strFileName, &data );
    if( !b )
    {
        LOGI( "Can not open a file:%s", strFileName );
        return false;
    }

    return shader::CompileShader( shader, type, data );
}

bool shader::LinkProgram( const GLuint prog )
{
    GLint status;

    glLinkProgram( prog );

#if defined(DEBUG)
    GLint logLength;
    glGetProgramiv( prog, GL_INFO_LOG_LENGTH, &logLength );
    if( logLength > 0 )
    {
        GLchar *log = (GLchar *) malloc( logLength );
        glGetProgramInfoLog( prog, logLength, &logLength, log );
        LOGI( "Program link log:\n%s", log );
        free( log );
    }
#endif

    glGetProgramiv( prog, GL_LINK_STATUS, &status );
    if( status == 0 )
    {
        LOGI( "Program link failed\n" );
        return false;
    }

    return true;
}

bool shader::ValidateProgram( const GLuint prog )
{
    GLint logLength, status;

    glValidateProgram( prog );
    glGetProgramiv( prog, GL_INFO_LOG_LENGTH, &logLength );
    if( logLength > 0 )
    {
        GLchar *log = (GLchar *) malloc( logLength );
        glGetProgramInfoLog( prog, logLength, &logLength, log );
        LOGI( "Program validate log:\n%s", log );
        free( log );
    }

    glGetProgramiv( prog, GL_VALIDATE_STATUS, &status );
    if( status == 0 )
        return false;

    return true;
}

} //namespace ndkHelper


text:
<!doctype html>

<meta charset="utf-8" />
<title>Katalógus</title>
<base href="{{ BASE_URI }}"></base>
<meta name="description" content="Termékkatalógus">
<meta name="author" content="Kocsis Máté">
<link href="data:image/x-icon;base64,AAABAAEAEBAQAAAAAAAoAQAAFgAAACgAAAAQAAAAIAAAAAEABAAAAAAAgAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAABMaFAAfHhwAFxoUAAgMCAAvJiQAExYQABceGAAbHhgAJyIgACsiIAA7JigAExYUAAAAAAAAAAAAAAAAAAAAAAAAAAAABEREREREREAIREREREREwCxEREREREXABERERERERIAERERERERGgCBEREREREZAFERERERERMAgRERERERHAARFBEREUEWABEUERERQRYAERQRERFDgQAABAAAAEAAAAAEQAAEQAAAAABEAEQAAAAAAABEAAAAD//wAAgAEAAIABAACAAQAAgAEAAIABAACAAQAAgAEAAIABAACAAQAAgAEAAIABAAD37wAA888AAPmfAAD+fwAA" rel="icon" type="image/x-icon" />
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1, user-scalable=0" />
{% autoescape false %}

{% endautoescape %}

Katalógus

					Termékek
					Admin

{% if USER_ID != null %}
Üdvözlet, {{ USER_NAME }}!
{% endif %}

			{% block content %}{% endblock %}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Reactive.Disposables;
using BlueMonkey.Transaction;

namespace BlueMonkey.ViewModels
{
    public static class TransactionPolicyExtensions
    {
        public static void AddTo(this ITransactionPolicy transactionPolicy, CompositeDisposable disposable)
        {
            disposable.Add(new TransactionPolicyDisposer(transactionPolicy));
        }

        private class TransactionPolicyDisposer : IDisposable
        {
            private ITransactionPolicy _transactionPolicy;
            public TransactionPolicyDisposer(ITransactionPolicy transactionPolicy)
            {
                _transactionPolicy = transactionPolicy;
            }
            public void Dispose()
            {
                _transactionPolicy?.Complete();
                _transactionPolicy = null;
            }
        }
    }
}


text:
if (!RedactorPlugins) var RedactorPlugins = {};

(function($)
{
    RedactorPlugins.selectasset = function()
    {
        return {
            init: function()
            {
                var button = this.button.addAfter('video', 'selectasset', BLCAdmin.messages.selectUploadAsset);
                this.button.addCallback(button, BLCAdmin.asset.selectButtonClickedRedactor);
                this.button.setAwesome('selectasset', 'icon-picture');
            }
        };
    };
})(jQuery);


text:
function initiateViima(iframeUrl, tabImgUrl, heightFactor, widthFactor, side, tabOffsetFromBottom, headerText, smallScreenTreshold, tabOpacity){

  //Initializing variables
  if(!iframeUrl){
    iframeUrl = 'https://app.viima.com/viima/viima/'
  }

  if(!tabImgUrl){
    tabImgUrl = 'http://viima.github.io/hovering-tab-iframe-container/images/feedback-tab-redheart.png'
  }

  if(side !== 'right'){
    side = 'left';
  }

  if(!heightFactor){
    heightFactor = 0.8;
  }

  if(!widthFactor){
    widthFactor = 0.8;
  }

  if(!tabOffsetFromBottom){
    tabOffsetFromBottom = 0.4;
  }

  if(!smallScreenTreshold){
    smallScreenTreshold = 600;
  }

  //If visible window size is smaller than the specified treshold, don't show the tool at all
  if(window.innerWidth < smallScreenTreshold){
    return false;
  }

  //Calculate width, height and offsets based on visible screen size
  var height = heightFactor * window.innerHeight;
  var width = widthFactor * window.innerWidth;
  var containerOffset = (1-heightFactor)/2 * window.innerHeight;
  var tabOffset = tabOffsetFromBottom * window.innerHeight;

  //Appending tab to body
  document.body.insertAdjacentHTML('beforeend', '

');

  //Append header text if it was input
  if(headerText) {
    document.getElementById('feedback-inner').insertAdjacentHTML('afterbegin', '
'+ headerText +'
');
    document.getElementById('feedback-header').addEventListener('click', (function (e){
      e.stopPropagation();
      return false;
    }));
  }

  //Setting Basic CSS
  document.getElementById("feedback-tab").style.cssText = 'position: fixed; bottom: ' + tabOffset + 'px; ' + side + ': 0; cursor: pointer; -webkit-transition-duration: 0.3s; -moz-transition-duration: 0.3s; -o-transition-duration: 0.3s; transition-duration: 0.3s; z-index: 100000;';
  document.getElementById("feedback-inner").style.cssText = 'position: fixed; bottom: ' + containerOffset + 'px; ' + side + ': -' + width + 'px; -webkit-transition-duration: 0.3s; -moz-transition-duration: 0.3s; -o-transition-duration: 0.3s; transition-duration: 0.3s;  height: ' + height + 'px; width: ' + width +'px; overflow: hidden; z-index: 100000;';
  document.getElementById("feedback-inner").getElementsByTagName('iframe')[0].style.cssText = 'height: 100%; width: 100%; z-index: 100001;';

  if(tabOpacity){
     document.getElementById('feedback-tab').getElementsByTagName('img')[0].style.opacity = tabOpacity;
  }

  document.getElementById('feedback-tab').addEventListener('click', toggleViima);

  function toggleViima(){
    //If the feedback tab is hidden, show it, otherwise hide it
    if(side === 'left' && document.getElementById('feedback-inner').style.left.indexOf('-') != -1){
      document.getElementById('feedback-tab').style.left = width + 'px';
      document.getElementById('feedback-tab').style.bottom = containerOffset + 'px';
      document.getElementById('feedback-inner').style.left = '0px';
      document.getElementById('feedback-inner').style.bottom = containerOffset + 'px';
      document.body.insertAdjacentHTML('beforeend', '

');
    } else if (side === 'right' && document.getElementById('feedback-inner').style.right.indexOf('-') != -1){
      document.getElementById('feedback-tab').style.right = width + 'px';
      document.getElementById('feedback-tab').style.bottom = containerOffset + 'px';
      document.getElementById('feedback-inner').style.right = '0px';
      document.getElementById('feedback-inner').style.bottom = containerOffset + 'px';
      document.body.insertAdjacentHTML('beforeend', '

');
    } else {
      closeViima();
    }
  }

  function closeViima() {
    if(side === 'left' && document.getElementById('feedback-inner').style.left.indexOf('-') == -1){
      document.getElementById('feedback-tab').style.left =  '0px';
      document.getElementById('feedback-inner').style.left = '-' + width + 'px';
    } else if(side === 'right' && document.getElementById('feedback-inner').style.right.indexOf('-') == -1){
      document.getElementById('feedback-tab').style.right =  '0px';
      document.getElementById('feedback-inner').style.right = '-' + width + 'px';
    }
    var backdrop = document.getElementById('feedback-backdrop');
    document.body.removeChild(backdrop);
    document.getElementById('feedback-tab').style.bottom = tabOffset + 'px';
  }

  //Hide the feedback widget on clicks outside the container
  document.addEventListener('click', (function (e)
  {
      var backdrop = document.getElementById('feedback-backdrop');
       // if the target of the click is outside the container, it has to be the backdrop..
      if (e.target === backdrop){
          closeViima();
      }
  }));
}


text:
==================================================
Redis Datastore Example
==================================================

.. literalinclude:: ../../../examples/contrib/redis-datastore.py


text:
package coachdetoni.nfldata.stats;

import org.json.JSONObject;

public class Play {
    private int quarter;
    private int down;
    private String time;
    private String yardLine;
    private int yardsToGo;
    private String team;
    private String description;
    private String note;

    public Play(JSONObject play) {
        quarter = play.getInt("qtr");
        down = play.getInt("down");
        time = play.getString("time");
        yardLine = play.getString("yrdln");
        yardsToGo = play.getInt("ydstogo");
        team = play.getString("posteam");
        description = play.getString("desc");
        if(!play.isNull("note")) note = play.getString("note");
        else note = "";
    }

    public int getQuarter() {
        return quarter;
    }

    public int getDown() {
        return down;
    }

    public String getTime() {
        return time;
    }

    public String getYardLine() {
        return yardLine;
    }

    public int getYardsToGo() {
        return yardsToGo;
    }

    public String getTeam() {
        return team;
    }

    public String getDescription() {
        return description;
    }

    public String getNote() {
        return note;
    }
}


text:
from __future__ import print_function
import sys
sys.path.insert(1,"../../../")
from tests import pyunit_utils
import h2o
from h2o.utils.typechecks import assert_is_type
from h2o.backend.connection import H2OConnection

def h2oconnection():
    """
    Python API test: h2o.connection()
    """
    # call with no arguments
    temp = h2o.connection()
    assert_is_type(temp, H2OConnection)

if __name__ == "__main__":
    pyunit_utils.standalone_test(h2oconnection)
else:
    h2oconnection()


text:
<?php

class CM_FormField_Url extends CM_FormField_Text {

    public function validate(CM_Frontend_Environment $environment, $userInput) {
        $userInput = parent::validate($environment, $userInput);

        if (false === filter_var($userInput, FILTER_VALIDATE_URL)) {
            throw new CM_Exception_FormFieldValidation('Invalid url');
        }

        return $userInput;
    }
}


text:
namespace AnimalHierarchy
{
    public class Cat : Animal, ISound
    {
        public Cat(int age, string name, Gender gender)
            : base(age, name, gender)
        {
        }

        public override string MySound()
        {
            return "Meow! Meow! Meow!";
        }
    }
}


text:
//
//  MLSUpdateProtocol.h
//  MinLison
//
//  Created by MinLison on 2017/10/10.
//  Copyright © 2017年 minlison. All rights reserved.
//

#ifndef MLSUpdateProtocol_h
#define MLSUpdateProtocol_h
#import "BaseServiceProtocol.h"
#import "MLSUpdateEnum.h"

NS_ASSUME_NONNULL_BEGIN
@protocol MLSUpdateProtocol <BaseServiceProtocol>

/**
 显示升级控制器

 @param vc 在哪个控制器里显示
 @param completion 完成回调
 */
- (void)showInViewController:(UIViewController *)vc completion:(nullable WGUpdateActionBlock)completion;

/**
 检测是否有更新
 */
- (void)checkUpdate;
@end
NS_ASSUME_NONNULL_END
#endif /* MLSUpdateProtocol_h */


text:
package com.github.sbouclier.jaads.math;

import java.math.BigInteger;

/**
 * In mathematics, the factorial of a non-negative integer n, denoted by n!, is
 * the product of all positive integers less than or equal to n.
 *
 * @author Stéphane Bouclier
 * @see https://en.wikipedia.org/wiki/Factorial
 */
public final class Factorial {

	private Factorial() {
		throw new UnsupportedOperationException();
	}

	public static BigInteger computeRecursively(long n) {
		return computeRecursivelyWithLargeValue(BigInteger.valueOf(n));
	}

	private static BigInteger computeRecursivelyWithLargeValue(BigInteger n) {
		// f(0) => 1
		// f(n) => n * f(n - 1)
		return BigInteger.ZERO.equals(n) ? BigInteger.ONE
				: n.multiply(computeRecursivelyWithLargeValue(n.subtract(BigInteger.ONE)));
	}

	public static BigInteger computeIteratively(long n) {
		BigInteger fact = BigInteger.ONE;

		for (long i = 1; i <= n; i++) {
			fact = fact.multiply(BigInteger.valueOf(i));
		}

		return fact;
	}
}


text:
oeinfra_secrets  = Chef::EncryptedDataBagItem.load("oeinfra", "secrets")

# this is supposed to only work on production, since it's the only environment
# monitored with datadog, for that reason only in the production section of the
# data bag are defined the datadog attributes

node.default['datadog']['api_key'] = oeinfra_secrets["datadog"][node.chef_environment.to_s.split("-").last]["api_key"]
node.default['datadog']['application_key'] = oeinfra_secrets["datadog"][node.chef_environment.to_s.split("-").last]['application_key']

include_recipe 'datadog::dd-agent'

#to-do: retrive jmx port from an attribute
node.normal['datadog']['tomcat']['instances'] = [
  {
    :server => 'localhost',
    :port => '39193',
    :name => node.name.downcase.gsub(/_/, '-')
  }
]

include_recipe 'datadog::tomcat'

node.normal['datadog']['apache']['instances'] = [
  {
    'status_url' => 'http://localhost:81/server-status?auto'
  }
]

include_recipe 'datadog::apache'


text:
Sky::Sky (std::ifstream &in) : Object (){
   std::string attribute;
   // loop 3 times for 3 attributes
   for (int i=0; i < 3; ++i) {
      in >> attribute;
      if (attribute == "horizon") {
         in >> horizon;
      } else if (attribute == "base") {
         in >> base;
      } else if (attribute == "blue") {
         in >> blue;
      }
   }
}

Sky::Sky (double hor, double ba, double bl) : Object (),
          base (ba), horizon (hor), blue (bl){
}

Color Sky::get_ambient (const Point &spot) const {
   double redgreen = (1-spot[Y])*horizon + base;
   return Color(redgreen, redgreen, blue);
}

bool Sky::get_intersect(const Point &sp, const Point &dp,
                        intersection &intersect) {
   intersect.t = Point::MAX;
   intersect.spot = sp.get_unit_vector(dp);
   intersect.obj = this;
   return true;
}


text:
package org.pepstock.charba.client.callbacks;

import java.util.Collections;
import java.util.List;

import org.pepstock.charba.client.Defaults;
import org.pepstock.charba.client.IsChart;
import org.pepstock.charba.client.colors.IsColor;
import org.pepstock.charba.client.items.TooltipItem;
import org.pepstock.charba.client.items.TooltipLabelColor;
import org.pepstock.charba.client.items.TooltipLabelPointStyle;

/**
 * The tooltip label configuration is nested below the tooltip configuration using the callbacks key.

 * The tooltip has the following callbacks for providing text.

 * All functions must return either a string or an array of strings. Arrays of strings are treated as multiple lines of text. This interface takes care about labels.
 *
 * @author Andrea "Stock" Stocchero
 */
public interface TooltipLabelCallback {

	/**
	 * Returns text to render before an individual label.

	 * This will be called for each item in the tooltip.

	 * If returns null or empty list, it will be ignored.
	 *
	 * @param chart chart instance
	 * @param item tooltip item
	 * @return list of labels to be applied.
	 */
	default List<String> onBeforeLabel(IsChart chart, TooltipItem item) {
		return Collections.emptyList();
	}

	/**
	 * Returns text to render for an individual item in the tooltip.

	 * If returns null or empty list, it will be ignored.
	 *
	 * @param chart chart instance
	 * @param item tooltip item
	 * @return label to be applied.
	 */
	default List<String> onLabel(IsChart chart, TooltipItem item) {
		return Defaults.get().invokeTooltipsCallbackOnLabel(chart, item);
	}

	/**
	 * Returns the colors and borders to render for the tooltip item.

	 * If returns null, it will be ignored.
	 *
	 * @param chart chart instance
	 * @param item tooltip item
	 * @return label color to be applied.
	 */
	default TooltipLabelColor onLabelColor(IsChart chart, TooltipItem item) {
		return Defaults.get().invokeTooltipsCallbackOnLabelColor(chart, item);
	}

	/**
	 * Returns the point style to use instead of color boxes if usePointStyle is true.

	 * Default implementation uses the point style from the data set points.
	 *
	 * @param chart chart instance
	 * @param item tooltip item
	 * @return point style to be applied.
	 */
	default TooltipLabelPointStyle onLabelPointStyle(IsChart chart, TooltipItem item) {
		return Defaults.get().invokeTooltipsCallbackOnLabelPointStyle(chart, item);
	}

	/**
	 * Returns the colors for the text of the label for the tooltip item.

	 * If returns null, it will be ignored.
	 *
	 * @param chart chart instance
	 * @param item tooltip item
	 * @return label text color to be applied.
	 */
	default IsColor onLabelTextColor(IsChart chart, TooltipItem item) {
		return chart.getOptions().getTooltips().getBodyColor();
	}

	/**
	 * Returns text to render after an individual label.

	 * If returns null or empty list, it will be ignored.
	 *
	 * @param chart chart instance
	 * @param item tooltip item
	 * @return label to be applied.
	 */
	default List<String> onAfterLabel(IsChart chart, TooltipItem item) {
		return Collections.emptyList();
	}

}


text:
module Parliaments
  module Houses
    class PartiesController < ApplicationController
      before_action :data_check, :build_request

      ROUTE_MAP = {
        index: proc { |params| ParliamentHelper.parliament_request.parliament_house_parties.set_url_params({ parliament_id: params[:parliament_id], house_id: params[:house_id] }) },
        show:  proc { |params| ParliamentHelper.parliament_request.parliament_house_party.set_url_params({ parliament_id: params[:parliament_id], house_id: params[:house_id], party_id: params[:party_id] }) }
      }.freeze

      def index
        @parliament, @house, @parties, @letters = RequestHelper.filter_response_data(
          @request,
          'http://id.ukpds.org/schema/ParliamentPeriod',
          'http://id.ukpds.org/schema/House',
          'http://id.ukpds.org/schema/Party',
          ::Grom::Node::BLANK
        )

        @parliament = @parliament.first
        @house      = @house.first
        @parties    = @parties = @parties.multi_direction_sort({ member_count: :desc, name: :asc })
        @letters    = @letters.map(&:values)
      end

      def show
        @parliament, @house, @party = RequestHelper.filter_response_data(
          @request,
          'http://id.ukpds.org/schema/ParliamentPeriod',
          'http://id.ukpds.org/schema/House',
          'http://id.ukpds.org/schema/Party'
        )

        raise ActionController::RoutingError, 'Not Found' if @party.empty?

        @parliament = @parliament.first
        @house      = @house.first
        @party      = @party.first
      end
    end
  end
end


text:
@implementation NSURLComponents (CRLUtils)

-(NSURLQueryItem *)crl_firstQueryItemNamed:(NSString *)name
{
    NSArray<NSURLQueryItem *> *queryItems = self.queryItems;
    for(NSURLQueryItem *queryItem in queryItems) {
        if([queryItem.name isEqualToString:name])
            return queryItem;
    }

    return nil;
}

@end


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.11"/>
<title>Dynamic Array: dynarray< T > Class Template Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

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

Dynamic Array

Main Page

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Members

Public Member Functions |
Private Member Functions |
Private Attributes |
List of all members

dynarray< T > Class Template Reference

The dynarray class manages an automatically re-sizing collection of elements.
 More...

#include <dynarray.hpp>

Public Member Functions

 	dynarray (size_t size=0)

 	Construct a dynamic array with initial size.  More...

 	~dynarray ()

 	Deallocates memory allocated for the dynamic array.  More...

T 	get_element (size_t index)

 	Returns the element at the specified index.  More...

bool 	set_element (size_t index, T element)

 	Sets the element at the specified index.  More...

bool 	insert_element (size_t index, T element)

 	Insert the specified element at the specified index.  More...

bool 	delete_element (size_t index)

 	Delete the element at the specified index.  More...

size_t 	array_capacity ()

 	Returns the capacity of the backing array.  More...

size_t 	array_size ()

 	Returns the logical size of the backing array.  More...

bool 	is_empty ()

 	Returns whether or not the array is empty.  More...

Private Member Functions

bool 	resize_array (size_t newsize)

Private Attributes

T * 	mp_array

size_t 	m_capacity

size_t 	m_logical_size

Detailed Description

template<class T>

class dynarray< T >

The dynarray class manages an automatically re-sizing collection of elements.

Constructor & Destructor Documentation

template<class T >

          dynarray< T >::dynarray
          (
          size_t
          size = 0	)

Construct a dynamic array with initial size.

Parameters

[in]	size	- Amount of space to allocate for the dynamic array. By default a 0 size array is created if no arguments are specified.

Exceptions

bad_alloc	exception if allocation fails

template<class T >

          dynarray< T >::~dynarray
          (
          	)

Deallocates memory allocated for the dynamic array.

Member Function Documentation

template<class T >

          size_t dynarray< T >::array_capacity
          (
          	)

Returns the capacity of the backing array.

Returns

capacity of backing array

template<class T >

          size_t dynarray< T >::array_size
          (
          	)

Returns the logical size of the backing array.

Returns

logical size of the backing array

template<class T >

          bool dynarray< T >::delete_element
          (
          size_t
          index	)

Delete the element at the specified index.

Parameters

[in]	index	- A zero-based index ranging from from 0 to the size of the array - 1.

template<class T >

          T dynarray< T >::get_element
          (
          size_t
          index	)

Returns the element at the specified index.

Parameters

[in]	index	- A zero-based index ranging from from 0 to the size of the array - 1.

template<class T >

          bool dynarray< T >::insert_element
          (
          size_t
          index,

          T
          element

          )

Insert the specified element at the specified index.

Parameters

[in]	index	- A zero-based index ranging from from 0 to the size of the array. If the index is equal to the size of the dynamic array, the element is added to the end of the dynamic array.

[in]	element	- The item to be inserted into the dynamic array.

Exceptions

bad_alloc	exception if allocation fails

template<class T >

          bool dynarray< T >::is_empty
          (
          	)

Returns whether or not the array is empty.

Returns

TRUE - array is empty, FALSE otherwise

template<class T >

          bool dynarray< T >::resize_array
          (
          size_t
          newsize	)

private

template<class T >

          bool dynarray< T >::set_element
          (
          size_t
          index,

          T
          element

          )

Sets the element at the specified index.

The index needs to be within the capacity of the array. If not the function will return a failure code.

Parameters

[in]	index	- A zero-based index ranging from from 0 to the size of the array - 1.

[in]	element	- The element to be stored at the specified index

Returns

true if successful, false otherwise

Member Data Documentation

template<class T >

          size_t dynarray< T >::m_capacity

private

template<class T >

          size_t dynarray< T >::m_logical_size

private

template<class T >

          T* dynarray< T >::mp_array

private

The documentation for this class was generated from the following file:

inc/dynarray.hpp

<address class="footer">
Generated by

 1.8.11
</address>


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Quic;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Server.IntegrationTesting;
using Microsoft.AspNetCore.Server.IIS.FunctionalTests;
using Microsoft.AspNetCore.Server.IntegrationTesting.Common;
using Microsoft.AspNetCore.Server.IntegrationTesting.IIS;
using Microsoft.AspNetCore.Testing;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Net.Http.Headers;
using Microsoft.Win32;
using Xunit;

namespace Microsoft.AspNetCore.Server.IIS.FunctionalTests;

[MsQuicSupported]
[HttpSysHttp3Supported]
[Collection(IISHttpsTestSiteCollection.Name)]
public class Http3Tests : FunctionalTestsBase
{
    public Http3Tests(IISTestSiteFixture fixture)
    {
        var port = TestPortHelper.GetNextSSLPort();
        fixture.DeploymentParameters.ApplicationBaseUriHint = $"https://localhost:{port}/";
        fixture.DeploymentParameters.AddHttpsToServerConfig();
        fixture.DeploymentParameters.SetWindowsAuth(false);
        Fixture = fixture;
    }

    public IISTestSiteFixture Fixture { get; }

    [ConditionalFact]
    public async Task Http3_Direct()
    {
        using var client = SetUpClient();
        client.DefaultRequestVersion = HttpVersion.Version30;
        client.DefaultVersionPolicy = HttpVersionPolicy.RequestVersionExact;
        var response = await client.GetAsync(Fixture.Client.BaseAddress.ToString() + "Http3_Direct");

        response.EnsureSuccessStatusCode();
        Assert.Equal(HttpVersion.Version30, response.Version);
        Assert.Equal("HTTP/3", await response.Content.ReadAsStringAsync());
    }

    [ConditionalFact]
    public async Task Http3_AltSvcHeader_UpgradeFromHttp1()
    {
        var address = Fixture.Client.BaseAddress.ToString() + "Http3_AltSvcHeader_UpgradeFromHttp1";

        var altsvc = $@"h3="":{new Uri(address).Port}""";
        using var client = SetUpClient();
        client.DefaultVersionPolicy = HttpVersionPolicy.RequestVersionOrHigher;

        // First request is HTTP/1.1, gets an alt-svc response
        var request = new HttpRequestMessage(HttpMethod.Get, address);
        request.Version = HttpVersion.Version11;
        request.VersionPolicy = HttpVersionPolicy.RequestVersionExact;
        var response1 = await client.SendAsync(request);
        response1.EnsureSuccessStatusCode();
        Assert.Equal("HTTP/1.1", await response1.Content.ReadAsStringAsync());
        Assert.Equal(altsvc, response1.Headers.GetValues(HeaderNames.AltSvc).SingleOrDefault());

        // Second request is HTTP/3
        var response3 = await client.GetAsync(address);
        Assert.Equal(HttpVersion.Version30, response3.Version);
        Assert.Equal("HTTP/3", await response3.Content.ReadAsStringAsync());
    }

    [ConditionalFact]
    public async Task Http3_AltSvcHeader_UpgradeFromHttp2()
    {
        var address = Fixture.Client.BaseAddress.ToString() + "Http3_AltSvcHeader_UpgradeFromHttp2";

        var altsvc = $@"h3="":{new Uri(address).Port}""";
        using var client = SetUpClient();
        client.DefaultRequestVersion = HttpVersion.Version20;
        client.DefaultVersionPolicy = HttpVersionPolicy.RequestVersionOrHigher;

        // First request is HTTP/2, gets an alt-svc response
        var response2 = await client.GetAsync(address);
        response2.EnsureSuccessStatusCode();
        Assert.Equal(altsvc, response2.Headers.GetValues(HeaderNames.AltSvc).SingleOrDefault());
        Assert.Equal("HTTP/2", await response2.Content.ReadAsStringAsync());

        // Second request is HTTP/3
        var response3 = await client.GetStringAsync(address);
        Assert.Equal("HTTP/3", response3);
    }

    [ConditionalFact]
    public async Task Http3_ResponseTrailers()
    {
        var address = Fixture.Client.BaseAddress.ToString() + "Http3_ResponseTrailers";
        using var client = SetUpClient();
        client.DefaultRequestVersion = HttpVersion.Version30;
        client.DefaultVersionPolicy = HttpVersionPolicy.RequestVersionExact;
        var response = await client.GetAsync(address);
        response.EnsureSuccessStatusCode();
        var result = await response.Content.ReadAsStringAsync();
        Assert.Equal("HTTP/3", result);
        Assert.Equal("value", response.TrailingHeaders.GetValues("custom").SingleOrDefault());
    }

    [ConditionalFact]
    public async Task Http3_ResetBeforeHeaders()
    {
        var address = Fixture.Client.BaseAddress.ToString() + "Http3_ResetBeforeHeaders";
        using var client = SetUpClient();
        client.DefaultRequestVersion = HttpVersion.Version30;
        client.DefaultVersionPolicy = HttpVersionPolicy.RequestVersionExact;
        var ex = await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(address));
        var qex = Assert.IsType<QuicException>(ex.InnerException);
        Assert.Equal(QuicError.StreamAborted, qex.QuicError);
        Assert.Equal(0x010b, qex.ApplicationErrorCode.Value);
    }

    [ConditionalFact]
    public async Task Http3_ResetAfterHeaders()
    {
        var address = Fixture.Client.BaseAddress.ToString() + "Http3_ResetAfterHeaders";
        using var client = SetUpClient();
        client.DefaultRequestVersion = HttpVersion.Version30;
        client.DefaultVersionPolicy = HttpVersionPolicy.RequestVersionExact;
        var response = await client.GetAsync(address, HttpCompletionOption.ResponseHeadersRead);
        await client.GetAsync(Fixture.Client.BaseAddress.ToString() + "Http3_ResetAfterHeaders_SetResult");
        response.EnsureSuccessStatusCode();
        var ex = await Assert.ThrowsAsync<HttpRequestException>(() => response.Content.ReadAsStringAsync());
        var qex = Assert.IsType<QuicException>(ex.InnerException?.InnerException?.InnerException);
        Assert.Equal(QuicError.StreamAborted, qex.QuicError);
        Assert.Equal(0x010c, qex.ApplicationErrorCode.Value); // H3_REQUEST_CANCELLED
    }

    [ConditionalFact]
    public async Task Http3_AppExceptionAfterHeaders_InternalError()
    {
        var address = Fixture.Client.BaseAddress.ToString() + "Http3_AppExceptionAfterHeaders_InternalError";
        using var client = SetUpClient();
        client.DefaultRequestVersion = HttpVersion.Version30;
        client.DefaultVersionPolicy = HttpVersionPolicy.RequestVersionExact;

        var response = await client.GetAsync(address, HttpCompletionOption.ResponseHeadersRead);
        await client.GetAsync(Fixture.Client.BaseAddress.ToString() + "Http3_AppExceptionAfterHeaders_InternalError_SetResult");
        response.EnsureSuccessStatusCode();
        var ex = await Assert.ThrowsAsync<HttpRequestException>(() => response.Content.ReadAsStringAsync());
        var qex = Assert.IsType<QuicException>(ex.InnerException?.InnerException?.InnerException);
        Assert.Equal(QuicError.StreamAborted, qex.QuicError);
        Assert.Equal(0x0102, qex.ApplicationErrorCode.Value); // H3_INTERNAL_ERROR
    }

    [ConditionalFact]
    public async Task Http3_Abort_Cancel()
    {
        var address = Fixture.Client.BaseAddress.ToString() + "Http3_Abort_Cancel";
        using var client = SetUpClient();
        client.DefaultRequestVersion = HttpVersion.Version30;
        client.DefaultVersionPolicy = HttpVersionPolicy.RequestVersionExact;

        var ex = await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(address));
        var qex = Assert.IsType<QuicException>(ex.InnerException);
        Assert.Equal(QuicError.StreamAborted, qex.QuicError);
        Assert.Equal(0x010c, qex.ApplicationErrorCode.Value); // H3_REQUEST_CANCELLED
    }

    private HttpClient SetUpClient()
    {
        var handler = new HttpClientHandler();
        // Needed on CI, the IIS Express cert we use isn't trusted there.
        handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
        return new HttpClient(handler) { Timeout = TimeSpan.FromSeconds(200) };
    }
}


text:
import {NgModule, CUSTOM_ELEMENTS_SCHEMA} from '@angular/core';
import {CommonModule} from '@angular/common';
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
import {ComposeComponent} from './compose.component';

@NgModule({
    imports: [
        CommonModule,
        FormsModule,
        ReactiveFormsModule
    ],
    declarations: [
        ComposeComponent
    ],
    bootstrap: [
        ComposeComponent
    ],
    exports: [ComposeComponent],
    entryComponents :[ComposeComponent],
    schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
export class ComposeModule {
}


text:
'use strict';

module.exports = function base(app, options) {
  if (!isObject(app) && typeof app !== 'function') {
    throw new TypeError('expected an object or function');
  }

  var opts = isObject(options) ? options : {};
  var prop = typeof opts.prop === 'string' ? opts.prop : 'fns';
  if (!Array.isArray(app[prop])) {
    define(app, prop, []);
  }

  /**
   * Define a plugin function to be passed to use. The only
   * parameter exposed to the plugin is `app`, the object or function.
   * passed to `use(app)`. `app` is also exposed as `this` in plugins.
   *
   * Additionally, **if a plugin returns a function, the function will
   * be pushed onto the `fns` array**, allowing the plugin to be
   * called at a later point by the `run` method.
   *
   * ```js
   * var use = require('use');
   *
   * // define a plugin
   * function foo(app) {
   *   // do stuff
   * }
   *
   * var app = function(){};
   * use(app);
   *
   * // register plugins
   * app.use(foo);
   * app.use(bar);
   * app.use(baz);
   * ```
   * @name .use
   * @param {Function} `fn` plugin function to call
   * @api public
   */

  define(app, 'use', use);

  /**
   * Run all plugins on `fns`. Any plugin that returns a function
   * when called by `use` is pushed onto the `fns` array.
   *
   * ```js
   * var config = {};
   * app.run(config);
   * ```
   * @name .run
   * @param {Object} `value` Object to be modified by plugins.
   * @return {Object} Returns the object passed to `run`
   * @api public
   */

  define(app, 'run', function(val) {
    if (!isObject(val)) return;

    if (!val.use || !val.run) {
      define(val, prop, val[prop] || []);
      define(val, 'use', use);
    }

    if (!val[prop] || val[prop].indexOf(base) === -1) {
      val.use(base);
    }

    var self = this || app;
    var fns = self[prop];
    var len = fns.length;
    var idx = -1;

    while (++idx < len) {
      val.use(fns[idx]);
    }
    return val;
  });

  /**
   * Call plugin `fn`. If a function is returned push it into the
   * `fns` array to be called by the `run` method.
   */

  function use(type, fn, options) {
    var offset = 1;

    if (typeof type === 'string' || Array.isArray(type)) {
      fn = wrap(type, fn);
      offset++;
    } else {
      options = fn;
      fn = type;
    }

    if (typeof fn !== 'function') {
      throw new TypeError('expected a function');
    }

    var self = this || app;
    var fns = self[prop];

    var args = [].slice.call(arguments, offset);
    args.unshift(self);

    if (typeof opts.hook === 'function') {
      opts.hook.apply(self, args);
    }

    var val = fn.apply(self, args);
    if (typeof val === 'function' && fns.indexOf(val) === -1) {
      fns.push(val);
    }
    return self;
  }

  /**
   * Wrap a named plugin function so that it's only called on objects of the
   * given `type`
   *
   * @param {String} `type`
   * @param {Function} `fn` Plugin function
   * @return {Function}
   */

  function wrap(type, fn) {
    return function plugin() {
      return this.type === type ? fn.apply(this, arguments) : plugin;
    };
  }

  return app;
};

function isObject(val) {
  return val && typeof val === 'object' && !Array.isArray(val);
}

function define(obj, key, val) {
  Object.defineProperty(obj, key, {
    configurable: true,
    writable: true,
    value: val
  });
}


text:
module Mongoid
  module Matchers

    # Performs size checking.
    class Size < Default

      # Return true if the attribute size is equal to the first value.
      #
      # @example Do the values match?
      #   matcher.matches?({ :key => 10 })
      #
      # @param [ Hash ] value The values to check.
      #
      # @return [ true, false ] If a value exists.
      def matches?(value)
        @attribute.size == value.values.first
      end
    end
  end
end


text:
package models

import (
	"bufio"
	"bytes"
	"encoding/base64"
	"image/gif"
	"mime/multipart"
	"regexp"

	"github.com/hico-horiuchi/yosage/yosage"
)

type Lgtm struct {
	Filename string `json:"filename"`
	Data     string `json:"data"`
}

func NewLgtm(file *multipart.File, header *multipart.FileHeader) (*Lgtm, error) {
	input, err := gif.DecodeAll(*file)
	if err != nil {
		return nil, err
	}

	output, err := yosage.Generate(input)
	if err != nil {
		return nil, err
	}

	var b bytes.Buffer
	writer := bufio.NewWriter(&b)

	err = gif.EncodeAll(writer, output)
	if err != nil {
		return nil, err
	}
	writer.Flush()

	re := regexp.MustCompile(`\.(gif|GIF)$`)
	return &Lgtm{
		Filename: re.ReplaceAllString(header.Filename, "") + "_lgtm.gif",
		Data:     base64.StdEncoding.EncodeToString(b.Bytes()),
	}, nil
}


text:
<?php

namespace Nokaut\ApiKit\Ext\Data\Converter\Filters\Callback\Producers;

use Nokaut\ApiKit\Collection\Products;
use Nokaut\ApiKit\Ext\Data\Collection\Filters\Producers;
use Nokaut\ApiKit\Ext\Data\Entity\Filter\Producer;
use Nokaut\ApiKit\Ext\Lib\ProductsAnalyzer;

class SetIsNofollow implements CallbackInterface
{
    /**
     * @param Producers $producers
     * @param Products $products
     */
    public function __invoke(Producers $producers, Products $products)
    {
        $this->setProducersIsNofollow($producers, $products);
    }

    /**
     * @param Producers $producers
     * @param Products $products
     */
    protected function setProducersIsNofollow(Producers $producers, Products $products)
    {
        if (ProductsAnalyzer::filtersNofollow($products, $producers)) {
            /** @var Producer $producer */
            foreach ($producers as $producer) {
                $producer->setIsNofollow(true);
            }

            return;
        }

        $selectedProducerEntitiesCount = count($this->getSelectedProducerEntities($producers));
        if ($selectedProducerEntitiesCount >= 1) {
            /** @var Producer $producer */
            foreach ($producers as $producer) {
                if ($producer->getIsFilter()) {
                    if ($selectedProducerEntitiesCount <= 2) {
                        $producer->setIsNofollow(false);
                    } else {
                        $producer->setIsNofollow(true);
                    }
                } else {
                    $producer->setIsNofollow(true);
                }
            }

            return;
        }
    }

    /**
     * @param Producers $producers
     * @return Producer[]
     */
    protected function getSelectedProducerEntities(Producers $producers)
    {
        return array_filter($producers->getEntities(), function ($entity) {
            return $entity->getIsFilter();
        });
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/item_settings"
        android:icon="@drawable/ic_baseline_settings_24"
        android:title="@string/item_settings"
        app:showAsAction="always" />
</menu>


text:
Zake
====

.. image:: https://travis-ci.org/yahoo/Zake.png?branch=master
   :target: https://travis-ci.org/yahoo/Zake

A python package that works to provide a nice set of testing utilities for the `kazoo`_ library.

It includes the following functionality:

* Storage access (for viewing what was saved/created).
* Kazoo *mostly* compatible client API.
* Sync/transaction/create/get/delete... commands.
* Listener support.
* And more...

It simplifies testing by providing a client that has a similar API as the kazoo
client so that your tests (or applications/libraries that use kazoo) do not
require a real zookeeper server to be  tested with (since this is not available
in all testing environments).

.. _kazoo: https://kazoo.readthedocs.org/en/latest/


text:
package com.github.jinahya.verbose.hello;

import static java.util.concurrent.ThreadLocalRandom.current;
import javax.inject.Named;
import org.slf4j.Logger;
import static org.slf4j.LoggerFactory.getLogger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 *
 * @author Jin Kwon <jinahya_at_gmail.com>
 */
@Configuration
public class HelloWorldSpringConfiguration {

    @Bean
    HelloWorld any() {
        return current().nextBoolean()
               ? new HelloWorldImpl() : new HelloWorldDemo();
    }

    @Named("impl")
    @Bean
    HelloWorld namedAsImpl() {
        return new HelloWorldImpl();
    }

    @Named("demo")
    @Bean
    HelloWorld namedAsDemo() {
        return new HelloWorldDemo();
    }

    @QualifiedImpl
    @Bean
    HelloWorld qualifiedWithImpl() {
        return new HelloWorldImpl();
    }

    @QualifiedDemo
    @Bean
    HelloWorld qualifiedWithDemo() {
        return new HelloWorldDemo();
    }

    private transient final Logger logger = getLogger(getClass());
}


text:
'use strict';

// Declare app level module which depends on views, and components
angular.module('goRemote', [
  'ngRoute'])


text:
package com.facebook.buck.json;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import com.fasterxml.jackson.databind.DeserializationContext;

import com.facebook.buck.util.MapWrapperForNullValues;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;

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

/**
 * JSON deserializer specialized to parse the output of {@code buck.py}
 * into {@link BuildFilePythonResult}.
 *
 * Uses Guava {@link ImmutableMap} and {@link ImmutableList} to reduce
 * memory pressure, along with {@link MapWrapperForNullValues} to allow
 * {@code null} values in the maps.
 */
final class BuildFilePythonResultDeserializer
  extends StdDeserializer<BuildFilePythonResult> {

  public BuildFilePythonResultDeserializer() {
    super(BuildFilePythonResult.class);
  }

  @Override
  public BuildFilePythonResult deserialize(
      JsonParser jp,
      DeserializationContext ctxt)
    throws IOException, JsonParseException {
    if (jp.getCurrentToken() != JsonToken.START_OBJECT) {
      throw new JsonParseException(jp, "Missing expected START_OBJECT");
    }
    ImmutableList<Map<String, Object>> values = ImmutableList.of();
    ImmutableList<Map<String, Object>> diagnostics = ImmutableList.of();
    Optional<String> profile = Optional.empty();
    String fieldName;
    while ((fieldName = jp.nextFieldName()) != null) {
      switch (fieldName) {
        case "values":
          values = deserializeObjectList(jp);
          break;
        case "diagnostics":
          diagnostics = deserializeObjectList(jp);
          break;
        case "profile":
          profile = Optional.of(jp.nextTextValue());
          break;
        default:
          throw new JsonParseException(jp, "Unexpected field name: " + fieldName);
      }
    }
    if (jp.getCurrentToken() != JsonToken.END_OBJECT) {
      throw new JsonParseException(jp, "Missing expected END_OBJECT");
    }
    return BuildFilePythonResult.of(values, diagnostics, profile);
  }

  private static ImmutableList<Map<String, Object>> deserializeObjectList(JsonParser jp)
    throws IOException, JsonParseException {
    JsonToken token = jp.nextToken();
    if (token != JsonToken.START_ARRAY) {
      throw new JsonParseException(jp, "Missing expected START_ARRAY, got: " + token);
    }
    ImmutableList.Builder<Map<String, Object>> result = ImmutableList.builder();
    while ((token = jp.nextToken()) == JsonToken.START_OBJECT) {
      result.add(deserializeObject(jp));
    }
    if (token != JsonToken.END_ARRAY) {
      throw new JsonParseException(jp, "Missing expected END_ARRAY");
    }
    return result.build();
  }

  private static Map<String, Object> deserializeObject(
      JsonParser jp)
    throws IOException, JsonParseException {
    ImmutableMap.Builder<String, Object> builder = ImmutableMap.builder();
    String fieldName;
    while ((fieldName = jp.nextFieldName()) != null) {
      builder.put(fieldName, deserializeRecursive(jp, jp.nextToken()));
    }
    if (jp.getCurrentToken() != JsonToken.END_OBJECT) {
      throw new JsonParseException(jp, "Missing expected END_OBJECT");
    }
    return new MapWrapperForNullValues<>(builder.build());
  }

  private static List<Object> deserializeList(
      JsonParser jp)
    throws IOException, JsonParseException {
    ImmutableList.Builder<Object> builder = ImmutableList.builder();
    JsonToken token;
    while ((token = jp.nextToken()) != JsonToken.END_ARRAY) {
      builder.add(deserializeRecursive(jp, token));
    }
    if (token != JsonToken.END_ARRAY) {
      throw new JsonParseException(jp, "Missing expected END_ARRAY");
    }
    return builder.build();
  }

  private static Object deserializeRecursive(
      JsonParser jp,
      JsonToken token)
    throws IOException, JsonParseException {
    switch (token) {
      case START_OBJECT:
        return deserializeObject(jp);
      case START_ARRAY:
        return deserializeList(jp);
      case VALUE_TRUE:
        return true;
      case VALUE_FALSE:
        return false;
      case VALUE_NULL:
        return MapWrapperForNullValues.NULL;
      case VALUE_NUMBER_FLOAT:
        return jp.getDoubleValue();
      case VALUE_NUMBER_INT:
        return jp.getLongValue();
      case VALUE_STRING:
        return jp.getText();
      // $CASES-OMITTED$
      default:
        throw new JsonParseException(jp, "Unexpected token: " + token.toString());
    }
  }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
com.google.gxp.compiler.bind (GXP Compiler 0.2.4-beta (BETA))
</TITLE>

<META NAME="date" CONTENT="2008-12-12">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

com.google.gxp.compiler.bind

Classes

BadParameterError

Binder

BoundTree

CallableNotFoundError

ImplementableNotFoundError

InvalidParameterFailedRegexError


text:
module.exports = function(grunt) {
  'use strict';

  var _ = require('lodash'),
      fs = require('fs'),
      path = require('path'),
      crypto = require('crypto'),
      taskName = 'copyChanged',
      options, done, timerid, restartTimer, tryCount, firstExecute =  true,
      watchers = [], tasks = [], dict = {};

  grunt.registerTask(taskName, 'task description', function(){

    var executedThisTime = false;

    options = this.options({
      src: ['.'],
      dest: '__modified',
      checksum: false,
      watchTask: false
    });

    grunt.log.ok('Waiting...');
    done = this.async();

    function onDirChange(event, filename, dir) {
      var filepath = path.join(dir || '', filename || '').replace(/\\/g, '/');

      if( !fs.existsSync(filepath) ) return;

      if (fs.statSync(filepath).isDirectory()) {
        startWatch = _.debounce(startWatch, 1000);
      } else {
        onFileChange(filepath);
      }
    }

    function onFileChange(filepath){
      if(! executedThisTime ) {
        grunt.log.writeln('');
        grunt.log.ok('"copyChanged" File changed.'.yellow);
        executedThisTime = true;
      }
      grunt.verbose.writeln('File Changed: ' + filepath);
      waitFileUnlock(filepath);
    }

    function startWatch(dirs) {
      return dirs.map(function(dir){
        return fs.watch(dir, function(e, p){ onDirChange(e, p, dir); });
      });
    }

    function restart(){
      if( restartTimer ) clearTimeout(restartTimer);

      restartTimer = setTimeout(function(){
        done();
        grunt.task.run([taskName]);
        executedThisTime = false;
        restartTimer = null;
      }, 2000);
    }

    function storeChecksum(dirs) {
      var memo = {},
          dirs = _.isArray(dirs) ? dirs : [dirs];

      dirs = dirs.map(function(dir){
        return dir.replace(/\/$/, '');
      });

      grunt.file.expand(dirs).map( function(path){
        var stat = fs.statSync( path ),
            hash = crypto.createHash('md5', path);

        if( stat.isDirectory() ) return;

        try {
          hash = require('crypto').createHash('md5').update( fs.readFileSync( path ) ).digest('hex');
          memo[ path ] = hash;
          grunt.verbose.ok(path + " -> " + hash);
        } catch(e) {
          grunt.log.error(e.message);
        }
      });
      return memo;
    }

    function closeWatch(watchers) {
      watchers.forEach(function(watcher){
        watcher.close();
      });
      return (watchers = []);
    }

    var waitTryCount = 0;
    function waitFileUnlock(filepath){
      var checksum, content = false, flg = true, isLocked = false;
      waitTryCount++;

      try {
        content = fs.readFileSync(filepath);
      } catch (e) {
        isLocked = true;
      }

      if(!isLocked || waitTryCount > 50) {
        if ( options.checksum && content ) {
          checksum = require('crypto').createHash('md5').update(content).digest('hex');

          grunt.verbose.ok(dict[filepath] +"  "+ checksum);

          flg = typeof dict[filepath] == "undefined" || dict[filepath] !== checksum;
          dict[filepath] = checksum;
        }
        if ( flg ) {
          var fp = path.join(options.dest|| '', filepath || '');
          grunt.file.copy(filepath, fp);
          grunt.log.ok('file copied to '+fp.blue);
        }

        return restart();

      } else {
        grunt.verbose.writeln('Waiting for file to unlock (' + waitTryCount + '): ' + filepath);
        clearTimeout(timerid);
        timerid = setTimeout(waitFileUnlock, 20);
      }
    }

    if( firstExecute ) {
      closeWatch(watchers);
      watchers = startWatch( grunt.file.expand(options.dirs) );

      firstExecute = false;
      if(options.checksum)  dict = storeChecksum( options.dirs );
      if(options.watchTask || options.watchtask)  done();
    }

  });
}


text:
import unittest
from io import BytesIO

from pyrake.mail import MailSender

class MailSenderTest(unittest.TestCase):

    def test_send(self):
        mailsender = MailSender(debug=True)
        mailsender.send(to=['test@pyrake.org'], subject='subject', body='body', _callback=self._catch_mail_sent)

        assert self.catched_msg

        self.assertEqual(self.catched_msg['to'], ['test@pyrake.org'])
        self.assertEqual(self.catched_msg['subject'], 'subject')
        self.assertEqual(self.catched_msg['body'], 'body')

        msg = self.catched_msg['msg']
        self.assertEqual(msg['to'], 'test@pyrake.org')
        self.assertEqual(msg['subject'], 'subject')
        self.assertEqual(msg.get_payload(), 'body')
        self.assertEqual(msg.get('Content-Type'), 'text/plain')

    def test_send_html(self):
        mailsender = MailSender(debug=True)
        mailsender.send(to=['test@pyrake.org'], subject='subject', body='
body
', mimetype='text/html', _callback=self._catch_mail_sent)

        msg = self.catched_msg['msg']
        self.assertEqual(msg.get_payload(), '
body
')
        self.assertEqual(msg.get('Content-Type'), 'text/html')

    def test_send_attach(self):
        attach = BytesIO()
        attach.write(b'content')
        attach.seek(0)
        attachs = [('attachment', 'text/plain', attach)]

        mailsender = MailSender(debug=True)
        mailsender.send(to=['test@pyrake.org'], subject='subject', body='body',
                       attachs=attachs, _callback=self._catch_mail_sent)

        assert self.catched_msg
        self.assertEqual(self.catched_msg['to'], ['test@pyrake.org'])
        self.assertEqual(self.catched_msg['subject'], 'subject')
        self.assertEqual(self.catched_msg['body'], 'body')

        msg = self.catched_msg['msg']
        self.assertEqual(msg['to'], 'test@pyrake.org')
        self.assertEqual(msg['subject'], 'subject')

        payload = msg.get_payload()
        assert isinstance(payload, list)
        self.assertEqual(len(payload), 2)

        text, attach = payload
        self.assertEqual(text.get_payload(decode=True), 'body')
        self.assertEqual(attach.get_payload(decode=True), 'content')

    def _catch_mail_sent(self, **kwargs):
        self.catched_msg = dict(**kwargs)

if __name__ == "__main__":
    unittest.main()


text:
Welcome! This is Quark, a chess engine with the main aim of not beating Magnus, or even an amateur, but being able to play by itself. Currently it is a one-man-show running as a hobby project.

The engine is split up into two main components: the front-end and the back-end.

### The Front-End
The front end is what the user interacts with. In the front end there is currently a ASCII art GUI which renders the board plus a UI so that the user isn't manually changing the board state themselves. The UI will eventually work solely on traditional chess notation rules but currently it works on a special set of notational rules, which are outlined later on in this README.

### The Back-End
In the back-end there is a complete chessboard, with rules, built from scratch. This engine uses a mailbox approach to storing the board state with 64 holes, each representing a single square on the board like so:

<!-- language: lang-none -->
    +---------------------------------------+
    | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 |
    +---------------------------------------+
    | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 |
    +---------------------------------------+
    | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 |
    +---------------------------------------+
    | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 |
    +---------------------------------------+
    | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 |
    +---------------------------------------+
    | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 |
    +---------------------------------------+
    | 08 | 09 | 10 | 11 | 12 | 13 | 14 | 15 |
    +---------------------------------------+
    | 00 | 01 | 02 | 03 | 04 | 05 | 06 | 07 |
    +---------------------------------------+

However the engine is not required to work in indices.

Auxiliary to the engine, a class for vectors have been defined and used extensively in the methods and calculations of the engine. They behave mostly as 2D mathematical vectors, with sutble changes to methods to make them applicable to the engine. One example of this behaviour is in determing unit vectors; for a vector at a 45 degree bearing instead of making the unit vector (1/sqrt(2), 1/sqrt(2)) it is scaled up by sqrt(2) so that the indices are only integers, making it (1, 1).

The chess pieces are all individual classes that have their own specialised methods. They determine their moves using [vector attack](https://chessprogramming.wikispaces.com/Vector+Attacks) logic and uses the vector class for its mathematical grounding.

The search-and-evaluate part of the engine is currently being developed, and as such has no information pertaining to its inner workings yet.

## Why bother? Isn't there already lots of chess engines, ones that are better then yours?

My response to that question is why bother ever doing anything? It is done half as a hobby and half as a way to learn how large-scale projects behave. I am yet to write a program larger then 500 lines of code so I do not know yet what goes wrong when doing so.

Don't expect this engine to ever beat anyone with half a brain in chess. I am hoping at best that it can play a game without breaking any rules.

## Examples

The GUI currently looks like so:
<!-- language: lang-none -->
      +----------+
    8 | rnbqkbnr |
    7 | pppppppp |
    6 | ........ |
    5 | ........ |
    4 | ........ |
    3 | ........ |
    2 | PPPPPPPP |
    1 | RNBQKBNR |
      +----------+
        abcdefgh

where the capitalised pieces are on white while the lowercase pieces are on black.

The notational rules follow a format similar to traditional chess notation but with a bit more detail. Two examples of moves under the special notation would be "Qd1>a4" or "Pe4xd5" if this helps to make a bit more sense. A concrete set of rules are as follows:
  - Start with the symbol for the piece being moved. So the queen has "Q", the king has "K", the knight "N", the bishop "B", the rook "R" and the pawns have 'P'.
  - Add on the current position of the piece (e.g. e3)
  - If just moving, write '>'. If capturing write 'x'
  - Finish the notation with the final position.

The special symbols being used are identical to traditional chess. You are only required to specify the castling notation: the engine does the notation for checks, checkmates and promotions. So the rules are:
  - If the piece has caused check, end the move with '+'
  - If the piece has caused checkmate, end the move with '#'
  - If castling, use either 0-0 for kingside or 0-0-0 for queenside.
  - Pawn promotions add to the end of the note '=?' where the ? symbol represents the symbol of the newly promoted piece.

## How to Play
To play with the engine in its current state, simply run the main execution script 'QuarkPlay.py' as a module or script. To do this, in your terminal of choice type 'python -m QuarkPlay' or 'python QuarkPlay.py' while having the terminal's working directory in the repository to run.

## API Reference

Currently there is no API, but it will be added as the project progresses further.

## Tests

Under each individual method, class and function there are both unit tests and integrated tests to make sure that they are behaving in a sane manner. For more details of the tests written, please see the python scripts in the "tests" directory.

## Contributors

If you would like to contribute to the project, please visit one of the main contributor's accounts and send them and email. We are always happy for more help.

## License

This project is covered under the MIT license.


text:
var Cassanova = require('../../index');

exports.options = options = {
    hosts:["localhost"],
    port:9042,
    keyspace:"cassanova_test"
};

exports.createUserModel = function(){
    var userSchema = Cassanova.Schema({
        username : Cassanova.SchemaType.TEXT().PRIMARY_KEY(),
        firstname : Cassanova.SchemaType.TEXT(),
        birthdate : Cassanova.SchemaType.TIMESTAMP(),
        lastname : Cassanova.SchemaType.TEXT(),
        password : Cassanova.SchemaType.TEXT(),
        email : Cassanova.SchemaType.TEXT(),
        session_token : Cassanova.SchemaType.TEXT()
    }),
    userTable = Cassanova.Table("users", userSchema),
    userModel = Cassanova.Model("userModel", userTable);

    return userModel;
};

exports.testCollectionModel = function(){
    var testCollectionSchema = Cassanova.Schema({
            username : Cassanova.SchemaType.TEXT().PRIMARY_KEY(),
            test_map : Cassanova.SchemaType.MAP(Cassanova.SchemaType.TEXT(),Cassanova.SchemaType.TEXT()),
            test_set : Cassanova.SchemaType.SET(Cassanova.SchemaType.TEXT()),
            test_list : Cassanova.SchemaType.LIST(Cassanova.SchemaType.TEXT())
        }),
        testCollectionTable = Cassanova.Table("test_collections", testCollectionSchema),
        testCollectionModel = Cassanova.Model("testCollectionModel", testCollectionTable);

    return testCollectionModel;
};
exports.createCassanovaClient = function(){
    return Cassanova.createClient(options);
};

exports.connectCassanovaClient = function(callback){
    Cassanova.connect(options, callback);
};

exports.disconnectCassanovaClient = function(callback){
    Cassanova.disconnect(callback);
};