text:
title: Two.Anchor
pageClass: docs
lang: en-US
---

# Two.Anchor

Extends: [Two.Vector](/docs/vector/)

An object that holds 3 [Two.Vector](/docs/vector/)s, the anchor point and its corresponding handles: `left` and `right`. In order to properly describe the bezier curve about the point there is also a command property to describe what type of drawing should occur when Two.js renders the anchors.

  <custom-button text="Source" type="source" href="https://github.com/jonobr1/two.js/blob/main/src/anchor.js" />

<carbon-ads />

### Constructor

| Argument | Description |
| ---- | ----------- |
|  x  | The x position of the root anchor point. |
|  y  | The y position of the root anchor point. |
|  lx  | The x position of the left handle point. |
|  ly  | The y position of the left handle point. |
|  rx  | The x position of the right handle point. |
|  ry  | The y position of the right handle point. |
|  command  | The command to describe how to render. Applicable commands are [Two.Commands]() |

## copy

Two.Anchor.copy

| Argument | Description |
| ---- | ----------- |
|  v  | The anchor to apply values to. |

Copy the properties of one [Two.Anchor](/docs/anchor/) onto another.

    anchor.js:62

## clone

Two.Anchor.clone

__Returns__: Two.Anchor

Create a new [Two.Anchor](/docs/anchor/), set all its values to the current instance and return it for use.

    anchor.js:110

## toObject

Two.Anchor.toObject

__Returns__: Object

- An object with properties filled out to mirror [Two.Anchor](/docs/anchor/).

Create a JSON compatible plain object of the current instance. Intended for use with storing values in a database.

    anchor.js:120

## toString

Two.Anchor.toString

__Returns__: String

- A String with comma-separated values reflecting the various values on the current instance.

Create a string form of the current instance. Intended for use with storing values in a database. This is lighter to store than the JSON compatible [Two.Anchor.toObject](/docs/anchor/#toobject).

    anchor.js:144


text:
namespace NRepository.Core.Tests
{
    public abstract class Animal
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package easy;

class MyDivision
{
	//now we create a test case
	public static void main(String[] args)
	{
		//let's use a large number to see the diff of two methods
		System.out.println("Naive: 1000000/2="+NaiveDiv(1000000, 2));
		System.out.println("Opt: 1000000/2="+OptDiv(1000000, 2));
	}

	//now let's compare the performance by comparing how many loops each method is using

	//first let's implement the naive div method
	public static int NaiveDiv(int divident, int divisor)
	{
		int quotient = 0;//return result
		int loopTime = 0;
		while(divident>=divisor)
		{
			loopTime++;
			divident -= divisor;//while the remainder is larger than divisor, we keep subtracting
			quotient++;//do not forget update quotient!
		}
		System.out.println("Naive loop time: "+loopTime);
		return quotient;
	}

	//now we implement the optimized div method
	public static int OptDiv(int divident, int divisor)
	{
		int quotient = 0;
		int loopTime = 0;
		java.util.List<Integer> divisors = new java.util.ArrayList<Integer>();
		java.util.List<Integer> quotients = new java.util.ArrayList<Integer>();
		//now we need some supporting variables to keep track of the increased/decreased divisor and base
		quotients.add(1);
		divisors.add(divisor);
		//now we start our loop, we will use the same criterial as naive div to determine continue or stop
		int currentDivisorIndex = 0;
		while(divident>=divisor)
		{
			loopTime++;
			//instead of use divisor as in naive method, we play with the currentDivisor which is a key to our method
			if(divident>=divisors.get(currentDivisorIndex))//there is space we substract and increase the divisor by doubling!
			{
				//firstly update quotient
				divident -= divisors.get(currentDivisorIndex);
				quotient += quotients.get(currentDivisorIndex);//notice it is not 1 but base
				//also double the current divisor and quotient and add to lists
				divisors.add(divisors.get(currentDivisorIndex)+divisors.get(currentDivisorIndex));
				quotients.add(quotients.get(currentDivisorIndex)+quotients.get(currentDivisorIndex));
				currentDivisorIndex++;
			}
			else//the current divisor may be too large now thus we need decrease it by halving
			{
				currentDivisorIndex--;//do not forget the update base quotient
			}
		}
		System.out.println("Optimized method loop time: "+loopTime);
		return quotient;
	}
}


text:
package smtp

import (
	"crypto/tls"
	"errors"
	"fmt"
	"io"
	"log"
	"net"
	"strings"

	"github.com/mailhog/data"
	"github.com/mailhog/smtp"
)

// session represents a SMTP session using net.TCPConn
type session struct {
	conn             io.ReadWriteCloser
	proto            *smtp.Protocol
	handler          Handler
	authenticate     Authenticate
	remoteAddress    string
	isTLS            bool
	line             string
	tlsConfig        *tls.Config
	logf             func(message string, args ...interface{})
	hasAuthenticated bool
}

func blackholeLogger(message string, args ...interface{}) {}

// Accept starts a new SMTP session using io.ReadWriteCloser
func accept(
	remoteAddress string,
	conn io.ReadWriteCloser,
	handler Handler,
	authenticate Authenticate,
	hostname string,
	tlsConfig *tls.Config,
	debug bool,
) {
	defer conn.Close()

	proto := smtp.NewProtocol()
	proto.Hostname = hostname

	s := &session{conn, proto, handler, authenticate, remoteAddress, false, "", tlsConfig, blackholeLogger, false}
	if debug {
		s.logf = s.debugLogger
	}

	proto.LogHandler = s.logf
	proto.MessageReceivedHandler = s.acceptMessage
	proto.SMTPVerbFilter = s.verbFilter
	if s.authenticate != nil {
		proto.GetAuthenticationMechanismsHandler = func() []string { return []string{"PLAIN"} }
		proto.ValidateAuthenticationHandler = s.plainAuthHandler
	}
	if tlsConfig != nil {
		proto.TLSHandler = s.tlsHandler
	}

	s.logf("Starting session")
	s.write(proto.Start())
	for s.read() == true {
	}
	s.logf("Session ended")
}

func (s *session) tlsHandler(done func(ok bool)) (errorReply *smtp.Reply, callback func(), ok bool) {
	s.logf("Returning TLS handler")
	return nil, func() {
		s.logf("Upgrading session to TLS")
		tConn := tls.Server(s.conn.(net.Conn), s.tlsConfig)
		err := tConn.Handshake()
		if err != nil {
			s.logf("handshake error in TLS connection: %s", err)
			done(false)
			return
		}
		s.conn = tConn
		s.isTLS = true
		s.logf("Session upgrade complete")
		done(true)
	}, true
}

func (s *session) acceptMessage(msg *data.SMTPMessage) (id string, err error) {
	m := msg.Parse(s.proto.Hostname)
	s.logf("Storing message %s", m.ID)
	return string(m.ID), s.handler(m)
}

func (s *session) verbFilter(verb string, args ...string) *smtp.Reply {
	if s.authenticate != nil && !s.hasAuthenticated {
		switch verb {
		case "MAIL":
			return smtp.ReplyError(errors.New("must be authenticated"))
		default:
			return nil
		}
	}
	return nil
}

func (s *session) plainAuthHandler(mechanism string, args ...string) (*smtp.Reply, bool) {
	if mechanism != "PLAIN" {
		return smtp.ReplyError(errors.New(fmt.Sprintf(
			"%q is not a supported AUTH mechanism",
			mechanism,
		))), false
	}
	if len(args) < 2 {
		return smtp.ReplyError(errors.New(
			"must provide a username and password",
		)), false
	}
	err := s.authenticate(args[0], args[1])
	if err != nil {
		return smtp.ReplyError(err), false
	}
	s.hasAuthenticated = true
	return nil, true
}

func (s *session) debugLogger(message string, args ...interface{}) {
	message = strings.Join([]string{"[SMTP %s]", message}, " ")
	args = append([]interface{}{s.remoteAddress}, args...)
	log.Printf(message, args...)
}

// read reads from the underlying net.TCPConn
func (s *session) read() bool {
	buf := make([]byte, 1024)
	n, err := s.conn.Read(buf)

	if n == 0 {
		s.logf("Connection closed by remote host\n")
		s.conn.Close() // not sure this is necessary?
		return false
	}

	if err != nil {
		s.logf("Error reading from socket: %s\n", err)
		return false
	}

	text := string(buf[0:n])
	logText := strings.Replace(text, "\n", "\\n", -1)
	logText = strings.Replace(logText, "\r", "\\r", -1)
	s.logf("Received %d bytes: '%s'\n", n, logText)

	s.line += text

	for strings.Contains(s.line, "\r\n") {
		line, reply := s.proto.Parse(s.line)
		s.line = line

		if reply != nil {
			s.write(reply)
			if reply.Status == 221 {
				io.Closer(s.conn).Close()
				return false
			}
		}
	}

	return true
}

// Write writes a reply to the underlying net.TCPConn
func (s *session) write(reply *smtp.Reply) {
	lines := reply.Lines()
	for _, l := range lines {
		logText := strings.Replace(l, "\n", "\\n", -1)
		logText = strings.Replace(logText, "\r", "\\r", -1)
		s.logf("Sent %d bytes: '%s'", len(l), logText)
		s.conn.Write([]byte(l))
	}
	if reply.Done != nil {
		reply.Done()
	}
}


text:
Craft.Net-powered local server for playing singleplayer games on Craft.Net. Craft.Local supports Minecraft 1.5.1.

## Usage

    Craft.Local.exe path-to-level.dat [port]

Starts up a local server on 127.0.0.1:port with the specified world.  If you don't specify a port, the first
available port will be used and output to stdout as a string (i.e. "12345"). You can also use a relative path
and Craft.Local will use ~/.minecraft/[relative path].

## Plugin channels

### Craft.Local.Open

Used to open the server to the LAN.

**Payload**:

*byte*: Game mode (0 - survival, 1 - creative, 2 - adventure mode)

*bool*: Allow cheats

### Craft.Local.Exit

Exits the server.

**Payload**:

*none*

## Commands

Craft.Local has certain commands available to players:

* /exit: Exits the server. Only usable by the first player to connect.

* /publish: Publishes the server for LAN play. Only usable by the first player to connect.

The commands from [this page](http://www.minecraftwiki.net/wiki/Cheats) are available if cheats are enabled in level.dat or
when enabled by Craft.Local.Open. *Note: None of these commands have been added, but they are planned*

## Building from Source

On Windows, add "C:\Windows\Microsoft.NET\Framework\v4.0.30319" to your %PATH% and run this:

    msbuild.exe

From the root of the repository.  This will build it in DEBUG mode. If you want to build in RELEASE mode
(which uses an ILMerge-like tool to consolidate binary files into one), use this:

    msbuild.exe /p:Configuration=RELEASE

On other platforms, install Mono and run "xbuild" from the root of the repository. For RELEASE mode:

    xbuild /property:Configuration=RELEASE


text:
require 'rails_helper'

RSpec.describe SleepingKingStudios::Shinkansen::Namespaces do
  shared_examples 'should define the namespaces' do
    include_examples 'should have constant', :Controllers, ->() { an_instance_of Module }

    include_examples 'should have constant', :Models, ->() { an_instance_of Module }
  end # describe

  describe '::NAMESPACES' do
    include_examples 'should have immutable constant', :NAMESPACES, ->() { contain_exactly :Controllers, :Models }
  end # describe

  describe '::included' do
    mock_module Spec, :NamespacesExample, :scope => :context do |mod|
      mod.send :include, SleepingKingStudios::Shinkansen::Namespaces
    end # create_test_constant

    let(:described_class) { Spec::NamespacesExample }

    include_examples 'should define the namespaces'

    context 'when included in a Rails root namespace' do
      let(:described_class) { ExampleApplication }

      include_examples 'should define the namespaces'
    end # describe
  end # describe

  describe '::namespaces_for_application' do
    mock_module Spec, :ExampleApplication, :scope => :context

    mock_class :'Spec::ExampleApplication', :Application, :scope => :context

    let(:application) { Spec::ExampleApplication::Application.new }
    let(:expected) do
      described_class::NAMESPACES.map { |namespace| "Spec::ExampleApplication::#{namespace}" }
    end # let

    it { expect(described_class).to respond_to(:namespaces_for_application).with(1).argument }

    it 'should return an array of namespaces' do
      expect(described_class.namespaces_for_application application).to contain_exactly(*expected)
    end # it

    describe 'with a Rails application' do
      let(:application) { Rails.application }
      let(:expected) do
        described_class::NAMESPACES.map { |namespace| "ExampleApplication::#{namespace}" }
      end # let

      it 'should return an array of namespaces' do
        expect(described_class.namespaces_for_application application).to contain_exactly(*expected)
      end # it
    end # describe
  end # describe
end # describe


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package clase.pkg20.y.pico;

import java.util.ArrayList;
import java.util.Random;
import javax.swing.JOptionPane;

/**
 *
 * @author alumno
 */
public class FrmAhorcado extends javax.swing.JFrame {

    ArrayList <palabra> MisPalabras;//sin instanciar

    palabra palabraActual;

    public FrmAhorcado() {

        initComponents();

        MisPalabras = new ArrayList<palabra>();//instanciado

        palabra p1=new palabra("celular", "dispositivo electronico de ubicacion");

        MisPalabras.add(p1);

        palabra p2=new palabra("casa", "lugar donde viven las personas");

        MisPalabras.add(p2);

        palabra p3=new palabra("cuaderno", "para tomar anotaciones");

        MisPalabras.add(p3);

        palabra p4=new palabra("silla", "sirve para sentarte");

        MisPalabras.add(p4);

    }

    private void seleccionarPalabra(){

    Random R=new Random();

    int Ra = R.nextInt(MisPalabras.size());

     //palabra unaPalabra;

    palabraActual = MisPalabras.get(Ra);

    System.out.println(Ra);

    //return unaPalabra;
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        lblIimagen = new javax.swing.JLabel();
        txtIngreso = new javax.swing.JTextField();
        btnIngresarLetra = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("lbl palabra");

        jLabel2.setText("lbl erradas");

        jLabel3.setText("lbl ayudas");

        lblIimagen.setText("lbl imagen");

        txtIngreso.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtIngresoActionPerformed(evt);
            }
        });

        btnIngresarLetra.setText("ingresar letra");

        jMenu1.setText("juego");
        jMenu1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenu1ActionPerformed(evt);
            }
        });

        jMenuItem1.setText("nuevoJuego");
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem1);

        jMenuBar1.add(jMenu1);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(73, 73, 73)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel3)
                    .addComponent(jLabel2)
                    .addComponent(jLabel1))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtIngreso, javax.swing.GroupLayout.PREFERRED_SIZE, 287, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 20, Short.MAX_VALUE)
                        .addComponent(btnIngresarLetra)
                        .addGap(49, 49, 49))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(lblIimagen)
                        .addGap(107, 107, 107))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(43, 43, 43)
                        .addComponent(jLabel1))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(34, 34, 34)
                        .addComponent(lblIimagen)))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(70, 70, 70)
                        .addComponent(jLabel2)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(28, 28, 28)
                                .addComponent(btnIngresarLetra))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(47, 47, 47)
                                .addComponent(jLabel3))))
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(txtIngreso, javax.swing.GroupLayout.PREFERRED_SIZE, 144, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(197, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void txtIngresoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtIngresoActionPerformed

    }//GEN-LAST:event_txtIngresoActionPerformed

    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
       this.seleccionarPalabra();

        JOptionPane.showMessageDialog(rootPane, palabraActual.getPalabra());
    }//GEN-LAST:event_jMenuItem1ActionPerformed

    private void jMenu1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenu1ActionPerformed

    }//GEN-LAST:event_jMenu1ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(FrmAhorcado.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FrmAhorcado.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FrmAhorcado.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FrmAhorcado.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new FrmAhorcado().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnIngresarLetra;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JLabel lblIimagen;
    private javax.swing.JTextField txtIngreso;
    // End of variables declaration//GEN-END:variables
}


text:
/* LCM type definition class file
 * This file was automatically generated by lcm-gen
 * DO NOT MODIFY BY HAND!!!!
 */

package abblcm;

import java.io.*;
import java.util.*;
import lcm.lcm.*;

public final class abb_irb140cartesian implements lcm.lcm.LCMEncodable
{
    public long utime;
    public double pos[];
    public double quat[];

    public abb_irb140cartesian()
    {
        pos = new double[3];
        quat = new double[4];
    }

    public static final long LCM_FINGERPRINT;
    public static final long LCM_FINGERPRINT_BASE = 0x9ba71fd48cb530d2L;

    static {
        LCM_FINGERPRINT = _hashRecursive(new ArrayList<Class<?>>());
    }

    public static long _hashRecursive(ArrayList<Class<?>> classes)
    {
        if (classes.contains(abblcm.abb_irb140cartesian.class))
            return 0L;

        classes.add(abblcm.abb_irb140cartesian.class);
        long hash = LCM_FINGERPRINT_BASE
            ;
        classes.remove(classes.size() - 1);
        return (hash<<1) + ((hash>>63)&1);
    }

    public void encode(DataOutput outs) throws IOException
    {
        outs.writeLong(LCM_FINGERPRINT);
        _encodeRecursive(outs);
    }

    public void _encodeRecursive(DataOutput outs) throws IOException
    {
        outs.writeLong(this.utime);

        for (int a = 0; a < 3; a++) {
            outs.writeDouble(this.pos[a]);
        }

        for (int a = 0; a < 4; a++) {
            outs.writeDouble(this.quat[a]);
        }

    }

    public abb_irb140cartesian(byte[] data) throws IOException
    {
        this(new LCMDataInputStream(data));
    }

    public abb_irb140cartesian(DataInput ins) throws IOException
    {
        if (ins.readLong() != LCM_FINGERPRINT)
            throw new IOException("LCM Decode error: bad fingerprint");

        _decodeRecursive(ins);
    }

    public static abblcm.abb_irb140cartesian _decodeRecursiveFactory(DataInput ins) throws IOException
    {
        abblcm.abb_irb140cartesian o = new abblcm.abb_irb140cartesian();
        o._decodeRecursive(ins);
        return o;
    }

    public void _decodeRecursive(DataInput ins) throws IOException
    {
        this.utime = ins.readLong();

        this.pos = new double[(int) 3];
        for (int a = 0; a < 3; a++) {
            this.pos[a] = ins.readDouble();
        }

        this.quat = new double[(int) 4];
        for (int a = 0; a < 4; a++) {
            this.quat[a] = ins.readDouble();
        }

    }

    public abblcm.abb_irb140cartesian copy()
    {
        abblcm.abb_irb140cartesian outobj = new abblcm.abb_irb140cartesian();
        outobj.utime = this.utime;

        outobj.pos = new double[(int) 3];
        System.arraycopy(this.pos, 0, outobj.pos, 0, 3);
        outobj.quat = new double[(int) 4];
        System.arraycopy(this.quat, 0, outobj.quat, 0, 4);
        return outobj;
    }

}


text:
#ifndef h2o__hpack_h
#define h2o__hpack_h

#include <stddef.h>
#include <stdint.h>
#include "h2o/header.h"
#include "h2o/url.h"
#include "h2o/cache_digests.h"

#define H2O_HPACK_ENCODE_INT_MAX_LENGTH 10 /* first byte + 9 bytes (7*9==63 bits to hold positive numbers of int64_t) */

extern const char h2o_hpack_err_found_upper_case_in_header_name[];
extern const char h2o_hpack_soft_err_found_invalid_char_in_header_name[];
extern const char h2o_hpack_soft_err_found_invalid_char_in_header_value[];

/**
 * encodes an integer (maximum size of the output excluding the first octet is H2O_HTTP2_ENCODE_INT_MAX_LENGTH bytes)
 */
uint8_t *h2o_hpack_encode_int(uint8_t *dst, int64_t value, unsigned prefix_bits);
/**
 * encodes a huffman string and returns its length, or returns SIZE_MAX if the resulting string would be longer than the input
 */
size_t h2o_hpack_encode_huffman(uint8_t *dst, const uint8_t *src, size_t len);
/**
 * decodes an integer, or returns an error code (either H2O_HTTP2_ERROR_COMPRESSION or H2O_HTTP2_ERROR_INCOMPLETE)
 */
int64_t h2o_hpack_decode_int(const uint8_t **src, const uint8_t *src_end, unsigned prefix_bits);
/**
 * decodes a huffman string and returns its length, or SIZE_MAX if fails. The destination buffer must be at least double the size
 * of the input.
 */
size_t h2o_hpack_decode_huffman(char *dst, const uint8_t *src, size_t len, int is_name, const char **err_desc);
/**
 * validates header name and returns a boolean. Result will be true and *err_desc will be set to non-NULL if a soft error is
 * detected.
 */
int h2o_hpack_validate_header_name(const char *s, size_t len, const char **err_desc);
/**
 * see h2o_http2_validate_header_name. The function only returns soft errors hence declared void.
 */
void h2o_hpack_validate_header_value(const char *s, size_t len, const char **err_desc);

#define H2O_HPACK_PARSE_HEADERS_METHOD_EXISTS 1
#define H2O_HPACK_PARSE_HEADERS_SCHEME_EXISTS 2
#define H2O_HPACK_PARSE_HEADERS_PATH_EXISTS 4
#define H2O_HPACK_PARSE_HEADERS_AUTHORITY_EXISTS 8

typedef int (*h2o_hpack_decode_header_cb)(h2o_mem_pool_t *pool, void *ctx, h2o_iovec_t **name, h2o_iovec_t *value,
                                          const uint8_t **const src, const uint8_t *src_end, const char **err_desc);
int h2o_hpack_decode_header(h2o_mem_pool_t *pool, void *_hpack_header_table, h2o_iovec_t **name, h2o_iovec_t *_value,
                            const uint8_t **const src, const uint8_t *src_end, const char **err_desc);
int h2o_hpack_parse_request(h2o_mem_pool_t *pool, h2o_hpack_decode_header_cb decode_cb, void *decode_ctx, h2o_iovec_t *method,
                            const h2o_url_scheme_t **scheme, h2o_iovec_t *authority, h2o_iovec_t *path, h2o_headers_t *headers,
                            int *pseudo_header_exists_map, size_t *content_length, h2o_cache_digests_t **digests,
                            const uint8_t *src, size_t len, const char **err_desc);
int h2o_hpack_parse_response(h2o_mem_pool_t *pool, h2o_hpack_decode_header_cb decode_cb, void *decode_ctx, int *status,
                             h2o_headers_t *headers, const uint8_t *src, size_t len, const char **err_desc);

#endif


text:
package com.facebook.buck.parser.cache.impl;

import static org.junit.Assert.assertEquals;

import com.facebook.buck.core.config.BuckConfig;
import com.facebook.buck.core.config.FakeBuckConfig;
import com.facebook.buck.event.BuckEventBusForTests;
import com.facebook.buck.io.filesystem.ProjectFilesystem;
import com.facebook.buck.io.filesystem.impl.FakeProjectFilesystem;
import com.facebook.buck.manifestservice.ManifestService;
import com.facebook.buck.parser.api.BuildFileManifest;
import com.facebook.buck.parser.api.ImmutableBuildFileManifest;
import com.facebook.buck.parser.api.ProjectBuildFileParser;
import com.facebook.buck.parser.exceptions.BuildFileParseException;
import com.facebook.buck.skylark.io.GlobSpecWithResult;
import com.facebook.buck.testutil.FakeFileHashCache;
import com.facebook.buck.util.ThrowingCloseableMemoizedSupplier;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSortedSet;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Optional;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

/** Tests for the {@link CachingProjectBuildFileParserDecorator} */
public class CachingProjectBuildFileParserDecoratorTest {
  @Rule public ExpectedException expectedException = ExpectedException.none();

  private ProjectFilesystem filesystem;
  private ProjectBuildFileParser fakeParser;
  private BuildFileManifest fakeParserManifest;

  private static ThrowingCloseableMemoizedSupplier<ManifestService, IOException>
      getManifestSupplier() {
    return ThrowingCloseableMemoizedSupplier.of(
        () -> new FakeManifestService(), ManifestService::close);
  }

  /** Fake parser object with fake preset values */
  class FakeProjectBuildParser implements ProjectBuildFileParser {

    @Override
    public BuildFileManifest getBuildFileManifest(Path buildFile) throws BuildFileParseException {
      ImmutableMap<String, Object> targetMap = ImmutableMap.of("foo", "foo", "bar", "bar");

      return ImmutableBuildFileManifest.of(
          ImmutableMap.of("tar1", targetMap),
          ImmutableSortedSet.of(),
          ImmutableMap.of(),
          Optional.empty(),
          ImmutableList.of());
    }

    @Override
    public void reportProfile() {}

    @Override
    public ImmutableSortedSet<String> getIncludedFiles(Path buildFile)
        throws BuildFileParseException {
      return ImmutableSortedSet.of();
    }

    @Override
    public boolean globResultsMatchCurrentState(
        Path buildFile, ImmutableList<GlobSpecWithResult> existingGlobsWithResults) {
      return false;
    }

    @Override
    public void close() throws BuildFileParseException {}
  }

  private BuckConfig getConfig(ProjectFilesystem fileSystem, String accessMode) {
    FakeBuckConfig.Builder builder = FakeBuckConfig.builder();

    builder
        .setSections(
            "[" + ParserCacheConfig.PARSER_CACHE_SECTION_NAME + "]",
            ParserCacheConfig.PARSER_CACHE_LOCAL_LOCATION_NAME + " = foobar",
            "dir_mode = " + accessMode)
        .setFilesystem(fileSystem);
    return builder.build();
  }

  @Before
  public void setUp() throws IOException, InterruptedException {
    filesystem = FakeProjectFilesystem.createRealTempFilesystem();
    fakeParser = new FakeProjectBuildParser();
    fakeParserManifest = fakeParser.getBuildFileManifest(filesystem.resolve("BUCK"));
  }

  @Test
  public void cachingParserProducesSameResultAsDelegate() throws IOException, InterruptedException {
    BuckConfig buckConfig = getConfig(filesystem, "readwrite");
    ProjectBuildFileParser cachingParser =
        CachingProjectBuildFileParserDecorator.of(
            ParserCache.of(
                buckConfig, filesystem, getManifestSupplier(), BuckEventBusForTests.newInstance()),
            fakeParser,
            buckConfig.getConfig(),
            filesystem,
            new FakeFileHashCache(ImmutableMap.of()));

    BuildFileManifest cachingParserManifest =
        cachingParser.getBuildFileManifest(filesystem.resolve("BUCK"));

    assertEquals(fakeParserManifest, cachingParserManifest);
  }

  @Test
  public void cachingParserCreationThrowsIfCacheNotDefined() {
    expectedException.expect(IllegalStateException.class);
    BuckConfig emptyBuckConfig = FakeBuckConfig.builder().build();
    CachingProjectBuildFileParserDecorator.of(
        ParserCache.of(
            emptyBuckConfig, filesystem, getManifestSupplier(), BuckEventBusForTests.newInstance()),
        fakeParser,
        emptyBuckConfig.getConfig(),
        filesystem,
        new FakeFileHashCache(ImmutableMap.of()));
  }

  @Test
  public void cachingParserProducesSameResultCacheAccessReadOnly()
      throws IOException, InterruptedException {
    BuckConfig buckConfig = getConfig(filesystem, "readonly");
    ProjectBuildFileParser cachingParser =
        CachingProjectBuildFileParserDecorator.of(
            ParserCache.of(
                buckConfig, filesystem, getManifestSupplier(), BuckEventBusForTests.newInstance()),
            fakeParser,
            buckConfig.getConfig(),
            filesystem,
            new FakeFileHashCache(ImmutableMap.of()));

    BuildFileManifest cachingParserManifest =
        cachingParser.getBuildFileManifest(filesystem.resolve("BUCK"));

    assertEquals(fakeParserManifest, cachingParserManifest);
  }

  @Test
  public void cachingParserProducesSameResultCacheAccessWriteOnly()
      throws IOException, InterruptedException {
    BuckConfig buckConfig = getConfig(filesystem, "writeonly");
    ProjectBuildFileParser cachingParser =
        CachingProjectBuildFileParserDecorator.of(
            ParserCache.of(
                buckConfig, filesystem, getManifestSupplier(), BuckEventBusForTests.newInstance()),
            fakeParser,
            buckConfig.getConfig(),
            filesystem,
            new FakeFileHashCache(ImmutableMap.of()));

    BuildFileManifest cachingParserManifest =
        cachingParser.getBuildFileManifest(filesystem.resolve("BUCK"));

    assertEquals(fakeParserManifest, cachingParserManifest);
  }
}


text:
using namespace std;
namespace bfs = boost::filesystem;

struct Config
{
    string populationFilename;
    string msFilename1;
    string msFilename2;
    bfs::path outputDirectory;
    size_t chromosomePairIndex;
    unsigned int positionBegin;
    unsigned int positionEnd;

    Config()
    :   chromosomePairIndex(0), positionBegin(0), positionEnd(0)
    {}
};

struct RelativePosition
{
    RelativePosition(unsigned int begin, unsigned int end)
    :   begin_(begin), end_(end)
    {
        if (begin > end)
            throw runtime_error("[RelativePosition] I am insane.");
    }

    double operator()(unsigned int position) const
    {
        if (position <= begin_) return 0;
        if (position >= end_) return 1;
        return double(position-begin_)/(end_-begin_);
    }

    private:
    unsigned int begin_;
    unsigned int end_;
};

string getSequence(const Chromosome& chromosome, const MSFormat& ms1,
                   const MSFormat& ms2, const RelativePosition& relativePosition)
{
    string sequence;

    for (vector<DNABlock>::const_iterator it=chromosome.blocks().begin();
         it!=chromosome.blocks().end(); ++it)
    {
        double begin = relativePosition(it->position);
        double end = (it+1 == chromosome.blocks().end()) ? 1 : relativePosition((it+1)->position);

        Chromosome::ID id(it->id);
        const MSFormat* ms = id.population == 1 ? &ms1 : &ms2;

        sequence += ms->sequence(id.individual, begin, end);

        // cout << id << " " << it->position << " " << begin << " " << end << endl;
    }

    return sequence;
}

void recombineData(const Config& config)
{
    Random random;

    cout << "Reading population data.\n";
    //Population population(config.populationFilename);
    Population population;
    ifstream is(config.populationFilename.c_str());
    if (!is) throw runtime_error(("[Population] Unable to open file " + config.populationFilename).c_str());
    is >> population;
    if (population.organisms().empty())
        cerr << "[Population] Warning: no population data read from file " << config.populationFilename << endl;

    cout << "Population size: " << population.organisms().size() << endl;

    MSFormat ms1(config.msFilename1);
    MSFormat ms2(config.msFilename2);

    MSFormat result;
    result.positions = ms1.positions;

    MSFormat check;
    check.positions = ms2.positions;

    if (result != check)
        throw runtime_error("[recombineData] Segsites don't match.");

    RelativePosition relativePosition(config.positionBegin, config.positionEnd);

    for (vector<Organism>::const_iterator it=population.organisms().begin();
         it!=population.organisms().end(); ++it)
    {
        if (config.chromosomePairIndex >= it->chromosomePairs().size())
            throw runtime_error("[recombineData()] Bad chromosomePairIndex.");

        const ChromosomePair& cp = it->chromosomePairs()[config.chromosomePairIndex];

        result.sequences.push_back(getSequence(cp.first, ms1, ms2, relativePosition));
        result.sequences.push_back(getSequence(cp.second, ms1, ms2, relativePosition));
    }

    bfs::ofstream os(config.outputDirectory / "sequences.txt");
    os << result;
}

void checkExistence(const string& filename)
{
    if (!bfs::exists(filename))
    {
        ostringstream oss;
        oss << "File not found: " << filename;
        throw runtime_error(oss.str());
    }
}

Config parseCommandLine(int argc, char* argv[])
{
    if (argc != 8)
    {
        cout << "Usage: recombine_data <populationFile> <msFile1> <msFile2> <outdir> <chromosome> <begin> <end>\n";
        cout << "\n";
        cout << "  populationFile :  population file output from simrecomb\n";
        cout << "  msFile1        :  ancestral population 1 in ms format\n";
        cout << "  msFile2        :  ancestral population 2 in ms format\n";
        cout << "  chromosome     :  chromosome pair index (0-based)\n";
        cout << "  begin          :  chromosome position mapped to 0\n";
        cout << "  end            :  chromosome position mapped to 1\n";
        cout << "\n";
        cout << "Darren Kessner\n";
        cout << "John Novembre Lab, UCLA\n";
        throw runtime_error("");
    }

    Config config;
    config.populationFilename = argv[1];
    config.msFilename1 = argv[2];
    config.msFilename2 = argv[3];
    config.outputDirectory = argv[4];
    config.chromosomePairIndex = atoi(argv[5]);
    config.positionBegin = atoi(argv[6]);
    config.positionEnd = atoi(argv[7]);

    checkExistence(config.populationFilename);
    checkExistence(config.msFilename1);
    checkExistence(config.msFilename2);

    if (bfs::exists(config.outputDirectory))
    {
        ostringstream oss;
        oss << "File/directory already exists: " << config.outputDirectory;
        throw runtime_error(oss.str());
    }

    bfs::create_directories(config.outputDirectory);

    return config;
}

int main(int argc, char* argv[])
{
    try
    {
        Config config = parseCommandLine(argc, argv);
        recombineData(config);
        return 0;
    }
    catch(exception& e)
    {
        cerr << e.what() << endl;
        return 1;
    }
    catch(...)
    {
        cerr << "Caught unknown exception.\n";
        return 1;
    }
}


text:
package org.jetbrains.kotlin.testframework.editor;

import java.io.File;

import org.jetbrains.kotlin.testframework.utils.KotlinTestUtils;
import org.jetbrains.kotlin.testframework.utils.SourceFileData;
import org.junit.Rule;
import org.junit.rules.TestName;

public abstract class KotlinEditorAutoTestCase extends KotlinProjectTestCase {

    protected abstract static class EditorSourceFileData extends SourceFileData {
        public EditorSourceFileData(File file) {
            super(file.getName(), KotlinTestUtils.getText(file.getAbsolutePath()));
        }
    }

    @Rule
    public TestName name = new TestName();

    private static final String TEST_DATA_PATH = "testData";

    private static String fileExtension;

    private static final String KT_FILE_EXTENSION = ".kt";
    private static final String KT_SCRIPT_FILE_EXTENSION = ".kts";
    protected static final String AFTER_FILE_EXTENSION = ".after";
    protected static final String BEFORE_FILE_EXTENSION = ".before";

    protected static final String FILE_DEPENDENCY_SUFFIX = ".dependency";

    protected final void doAutoTest() {
        String testPath = TEST_DATA_PATH + "/" + getTestDataRelativePath() + "/" + name.getMethodName();
        File testFolder = new File(testPath);

        File testFile = new File(testPath + KT_FILE_EXTENSION);
        File scriptTestFile = new File(testPath + KT_SCRIPT_FILE_EXTENSION);
        if (testFile.exists()) {
            fileExtension = KT_FILE_EXTENSION;
        } else {
            testFile = scriptTestFile;
            fileExtension = KT_SCRIPT_FILE_EXTENSION;
        }

        File dependencyFile = new File(testPath + FILE_DEPENDENCY_SUFFIX + getExtension());

        if (testFolder.exists() && testFolder.isDirectory()) {
            doMultiFileAutoTest(testFolder);
        } else if (testFile.exists() && testFile.isFile() && dependencyFile.exists()) {
            doAutoTestWithDependencyFile(testPath + getExtension(), dependencyFile);
        } else if (testFile.exists() && testFile.isFile() && !dependencyFile.exists()) {
            doSingleFileAutoTest(testPath + getExtension());
        } else {
            throw new RuntimeException(String.format("Neither file \'%s\' nor directory \'%s\' was found", testFile.getAbsolutePath(), testFolder.getAbsolutePath()));
        }
    }

    protected abstract void doSingleFileAutoTest(String testPath);

    protected abstract void doMultiFileAutoTest(File testFolder);

    protected void doAutoTestWithDependencyFile(String mainTestPath, File dependencyFile) {
        throw new UnsupportedOperationException("Auto test with dependency file is not supported");
    }

    protected abstract String getTestDataRelativePath();

    protected String getExtension() {
        return fileExtension;
    }
}


text:
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
Object.defineProperty(exports, "replaceValueSymbols", {
  enumerable: true,
  get: function get() {
    return _replaceValueSymbols.default;
  }
});
Object.defineProperty(exports, "replaceSymbols", {
  enumerable: true,
  get: function get() {
    return _replaceSymbols.default;
  }
});
Object.defineProperty(exports, "extractICSS", {
  enumerable: true,
  get: function get() {
    return _extractICSS.default;
  }
});
Object.defineProperty(exports, "createICSSRules", {
  enumerable: true,
  get: function get() {
    return _createICSSRules.default;
  }
});

var _replaceValueSymbols = _interopRequireDefault(require("./replaceValueSymbols.js"));

var _replaceSymbols = _interopRequireDefault(require("./replaceSymbols.js"));

var _extractICSS = _interopRequireDefault(require("./extractICSS.js"));

var _createICSSRules = _interopRequireDefault(require("./createICSSRules.js"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }


text:
package com.CrowdFoodWeb;

//import com.google.appengine.api.users.User;
import com.googlecode.objectify.annotation.Entity;
import com.googlecode.objectify.annotation.Id;

@Entity
public class User {
	private Double rating;
	private String userName;
	private String paymentOption;
	@Id private String id;
	private String[] friendIDs;
	private String token;

	////Constructor
	public User(){
	}

	public User(String id, String name, String token){ //Pass in ID from Facebook API - Should be a numeric string
		this.id = id;
		this.userName = name;
		this.token = token;
	}

	//////getters and Setters
	public Double getRating() {
		return rating;
	}

	public void setRating(Double rating) {
		rating = rating;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPaymentOption() {
		return paymentOption;
	}

	public void setPaymentOption(String paymentOption) {
		this.paymentOption = paymentOption;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getToken() {
		return token;
	}

	/////Other functions
	public void initiateTransaction(){

	}
	public void terminateTransaction(){

	}

}


text:
The following methods can be used to do actions on specific events.

## Events for models

#### Validating

[!!] These methods receive the **model object** and the **validation object** in their params.

[!!] The events' return value has no effect on the workings of Jelly.

- `model_before_validate($params, $event_data)`
- `model_after_validate($params, $event_data)`

#### Saving

[!!] These methods receive the **model object** in their params.

[!!] If `model_before_save()` event's return value is `FALSE`, then saving is skipped.

- `model_before_save($params, $event_data)`
- `model_after_save($params, $event_data)`

#### Deleting

[!!] If `model_before_delete()` event's return value isn't `NULL`, then deleting is skipped, but `model_after_delete()` is still run.

- `model_before_delete($params, $event_data)`
- `model_after_delete($params, $event_data)`

***

## Events for builders

[!!] These methods receive the **builder object** in their params.

#### Selecting

[!!] The events' return value has no effect on the workings of Jelly.

- `builder_before_select($params, $event_data)`
- `builder_after_select($params, $event_data)`

#### Inserting

[!!] The events' return value has no effect on the workings of Jelly.

- `builder_before_insert($params, $event_data)`
- `builder_after_insert($params, $event_data)`

#### Updating

[!!] The events' return value has no effect on the workings of Jelly.

- `builder_before_update($params, $event_data)`
- `builder_after_update($params, $event_data)`

#### Deleting

[!!] If `builder_before_delete()` event's return value isn't `NULL`, then deleting is skipped, but `builder_after_delete()` is still run.

- `builder_before_delete($params, $event_data)`
- `builder_after_delete($params, $event_data)`

***

## Events for meta

[!!] These methods receive the **meta object** in their params.

[!!] The events' return value has no effect on the workings of Jelly.

- `meta_before_finalize($params, $event_data)`
- `meta_after_finalize($params, $event_data)`


text:
<?php

namespace App\Controller\admin;

use App\Entity\OrderProduct;
use App\Entity\Product;
use App\Repository\OrdersRepository;
use Knp\Component\Pager\PaginatorInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use App\Entity\Orders;

/**
 * Orders controller.
 *
 * @Route("/admin/orders")
 */
class OrdersController extends AbstractController
{
    /**
     * Lists all Orders entities.
     *
     * @Route("/", methods={"GET"}, name="admin_orders")
     * @param Request $request
     * @param OrdersRepository $ordersRepository
     * @param PaginatorInterface $paginator
     * @return Response
     */
    public function index(
        Request $request,
        OrdersRepository $ordersRepository,
        PaginatorInterface $paginator
    ): Response {
        $qb = $ordersRepository->getAllOrdersAdminQB();
        $limit = $this->getParameter('admin_manufacturers_pagination_count');

        $orders = $paginator->paginate(
            $qb,
            $request->query->getInt('page', 1),
            $limit
        );

        return $this->render('admin/orders/index.html.twig', [
            'orders' => $orders
        ]);
    }

    /**
     * Finds and displays a Orders entity.
     *
     * @Route("/{id}", methods={"GET"}, name="admin_order_show")
     * @param int $id
     * @param OrdersRepository $ordersRepository
     * @return Response
     */
    public function show(int $id, OrdersRepository $ordersRepository): Response
    {
        $order = $ordersRepository->find($id);

        if (!$order) {
            throw $this->createNotFoundException('Unable to find Order entity.');
        }

        $deleteForm = $this->createDeleteForm($id);
        $orderProducts = $order->getOrderProducts();
        $productsArray = [];

        foreach ($orderProducts as $orderProduct) {
            $productPosition = [];
            /**
             * @var Product $product
             * @var OrderProduct $orderProduct
             */
            $product = $orderProduct->getProduct();
            $price = $orderProduct->getPrice();
            $quantity = $orderProduct->getQuantity();
            $sum = $price * $quantity;

            $productPosition['product'] = $product;
            $productPosition['quantity'] = $quantity;
            $productPosition['price'] = $price;
            $productPosition['sum'] = $sum;

            $productsArray[] = $productPosition;
        }

        return $this->render('admin/orders/show.html.twig', [
            'order' => $order,
            'delete_form' => $deleteForm->createView(),
            'products' => $productsArray
        ]);
    }

    /**
     * Deletes a Orders entity.
     *
     * @Route("/{id}", methods={"DELETE"}, name="admin_order_delete")
     * @param Request $request
     * @param int $id
     * @param OrdersRepository $ordersRepository
     * @return Response
     */
    public function delete(Request $request, int $id, OrdersRepository $ordersRepository): Response
    {
        $form = $this->createDeleteForm($id);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $ordersRepository->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find Order entity.');
            }

            $em->remove($entity);
            $em->flush();
        }

        return $this->redirect($this->generateUrl('admin_orders'));
    }

    /**
     * Creates a form to delete a Orders entity by id.
     *
     * @param int $id The entity id
     * @return FormInterface
     */
    private function createDeleteForm(int $id): FormInterface
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('admin_order_delete', ['id' => $id]))
            ->setMethod('DELETE')
            ->getForm();
    }
}


text:
from sqlalchemy import (
    Column,
    Index,
    Integer,
    Text,
    LargeBinary,
    Unicode,
    ForeignKey,
    Table
)
from sqlalchemy.orm import relationship

from .meta import Base

class User(Base):
    """This class defines a User model."""
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    username = Column(Unicode, unique=True)
    password = Column(Unicode)
    sub_user = Column(Unicode)
    address_rel = relationship('AddressBook')
    attr_assoc_rel = relationship('UserAttributeLink')

class AddressBook(Base):
    __tablename__ = 'addresses'
    id = Column(Integer, primary_key=True)
    name = Column(Unicode)
    phone = Column(Unicode)
    email = Column(Unicode)
    picture = Column(LargeBinary)
    pic_mime = Column(Text)
    user = Column(Integer, ForeignKey('users.id'))

class Category(Base):
    __tablename__ = 'categories'
    id = Column(Integer, primary_key=True)
    label = Column(Unicode)
    desc = Column(Unicode)
    picture = Column(LargeBinary)
    pic_mime = Column(Text)
    children = relationship('Attribute')

class Attribute(Base):
    __tablename__ = 'attributes'
    id = Column(Integer, primary_key=True)
    label = Column(Unicode)
    desc = Column(Unicode)
    picture = Column(LargeBinary)
    pic_mime = Column(Text)
    cat_id = Column(Integer, ForeignKey('categories.id'))
    user_assoc_rel = relationship('UserAttributeLink')

class UserAttributeLink(Base):
    __tablename__ = "users_attributes_link"
    user_id = Column(Integer, ForeignKey('users.id'), nullable=False, primary_key=True)
    attr_id = Column(Integer, ForeignKey('attributes.id'), nullable=False, primary_key=True)
    priority = Column(Integer, default=1, nullable=False)
    num_hits = Column(Integer, default=0, nullable=False)
    user_rel = relationship("User")
    attr_rel = relationship("Attribute")


text:
This is demo project for my article on [GitBook](https://valentinmk.gitbooks.io/python-tarantool-benchmark/) and [Medium](https://medium.com/@valentinmk/python-and-tarantool-races-in-the-loop-f496b6467ea4).

## Live demo
* [stickers.teslarnd.ru](http://stickers.teslarnd.ru) hosted on AWS.

## Purpose
* The main goal of the project was benchmark Tarantool and Python async web servers performance.
* Minor task was to show how you could write solution with Tarantool and aiohttp, sanic and japronto libraries.

## Installation
You can install the project on your own server by reproducing bash commands described in [install.md](https://github.com/valentinmk/python-tarantool-benchmark-and-bootstrap/blob/master/install.md).

Main steps to setup project is:
* install Python (pyenv used)
* install Python libs (`requerments.txt`)
* install Tarantool
* configure Tarantool (`pygbu.lua` configuration script provided)
* get some stickers' data into you Tarantool (`tests/externalapitotarantool.py`) from API hosted at [stickers.teslarnd.ru/stickers](http://stickers.teslarnd.ru/stickers)
* (optional) install PostgreSQL
* (optional) configure PostgreSQL
* (optional) migrate data from Tarantool to PostgreSQL (`tests/pgtotarantool.py`)

## This is not
* good example of programming style (everything could be code better)
* only one possible way to solve problem, read code comments (there are hints how to make code better)
* well-tested software (there are known errors and issues)

## How it works
Our web site consists of 5 sections.

* `Index` is making the votes and shows 2 images for us to choose one.
We have 9 requests to Tarantool for index page:
  * 2 selects for getting a random picture (2 select, 1 insert for each):
    * select from Tarantool random number (call build in function)
    * select from Tarantool token (eval md5 calculation for previously selected number)
    * insert token in space `secret`
  * create and insert uuid for user session (1 select, 1 upsert):
    * select from Tarantool uuid for session (eval uuid calculation)
    * upsert user information with uuid in `session` space
  * update server statistics (1 update)
* `Good` section showing 9 top rated stickers. We have 3 requests for `Good` page:
  * select top 9 stickers from 16k records (table) space it Tarantool (it like
    `select top(9) from stickers order by rating ASC`)
  * create and insert uuid for user session (1 select, 1 upsert):
    * select from Tarantool uuid for session (eval uuid calculation)
    * upsert user information with uuid in `session` space
* `Bad` section showing us 9 worst rated stickers. `Bad` runs the same as `Good` section. 3 requests in total.
* `Ugly` section writes text "Ugly", there're no calculations here. So we can benchmark how fast the web server is.
* `About` section renders the template, pastes Title and generates HTML response.

We have stickers api at `http://hostname:port/stickers`.

## License MIT
Project License can be found [here](https://github.com/valentinmk/python-tarantool-benchmark-and-bootstrap/blob/master/LICENSE).


text:
#include <include/ownership.h>

/* ownership
 *
 * Ownership is a simple mechanism where each object has an 'owner', which
 * represents the source of an object. Typically, the source of an object is a
 * mount (connector). For example, if an object has been inserted into the store
 * by a mysql connector, the owner will be the mysql connector object.
 *
 * Corto uses ownership in many ways to ensure the correct and seamless distribution
 * of data between different connectors. A few examples:
 * - Prevent updates from sources that are not the owner of an object
 * - Prevent delivering notifications from an owner to the owner (feedback)
 * - Forward method calls to the process that owns the object (RMI)
 * - Set 'target' or 'actual', based on who is updating a target object
 * - Determine whether objects are remote, and should be cached
 *
 * To ensure that all these mechanisms work smoothly, it is important that code
 * written for corto implements ownership correctly. While application developers
 * will rarely (if ever) see ownership in practice, it is an important concept
 * to understand for connector developers.
 *
 * This example creates two dummy mounts (connectors) that will both own one object.
 * The example demonstrates that when mount A updates its object, only mount B
 * will receive an update, and vice versa. In addition, the application will also
 * create an object it owns, which when updated triggers both mounts.
 *
 * The example creates a mount class with just the Core API. There are easier
 * ways to accomplish this with definition files and the c-binding. See the
 * c-binding examples for more details.
 */

void onNotify(corto_mount this, corto_eventMask event, corto_result *object) {
    if (event == CORTO_UPDATE) {
        corto_info("%s: received update for '%s'",
            corto_idof(this), object->id);
    }
}

int ownershipMain(int argc, char *argv[]) {

    /* Create a mount class */
    corto_class myMount = corto_declareChild(root_o, "MyMount", corto_class_o);
    if (!myMount) {
        goto error;
    }

    if (!corto_checkState(myMount, CORTO_VALID)) {
        /* Inherit from the corto mount class */
        corto_ptr_setref(&corto_interface(myMount)->base, corto_mount_o);

        /* Create onNotify method (called when the mount receives an update) */
        corto_method onNotifyMethod = corto_declareChild(
            myMount,
            "onNotify(vstore/eventMask event,vstore/result object)",
            corto_method_o);
        if (!onNotifyMethod) {
            goto error;
        }

        corto_function(onNotifyMethod)->kind = CORTO_PROCEDURE_CDECL;
        corto_function(onNotifyMethod)->fptr = (corto_word)onNotify;
        if (corto_define(onNotifyMethod)) {
            goto error;
        }

        /* Finalize class */
        if (corto_define(myMount)) {
            goto error;
        }
    }

    /* Create a new object which will act as the "mount point" for both mounts.
     * The mounts will automatically subscribe for updates from this object. */
    corto_object mount = corto_createChild(root_o, "mount", corto_void_o);
    if (!mount) {
        goto error;
    }

    /* Create two instances of the mount class.  */
    corto_mount connectorA = corto_declareChild(root_o, "connectorA", myMount);
    if (!connectorA) {
        goto error;
    }

    /* Mount connectorA on /mount */
    /* Set 'parent' member of the baseclass of mount (subscriber) */
    corto_ptr_setstr(&corto_subscriber(connectorA)->query.from, "/mount");
    if (corto_define(connectorA)) {
        goto error;
    }

    corto_mount connectorB = corto_declareChild(root_o, "connectorB", myMount);
    if (!connectorB) {
        goto error;
    }

    /* Also mount connectorB on /mount */
    /* Set 'parent' member of the baseclass of mount (subscriber) */
    corto_ptr_setstr(&corto_subscriber(connectorB)->query.from, "/mount");
    if (corto_define(connectorB)) {
        goto error;
    }

    /* The corto_setOwner call sets the owner for the current thread. First we'll
     * set the owner to mountA. The object that is subsequently created will be
     * owned by connectorA */
    corto_setOwner(connectorA);

    /* Create an object that is owned by connectorA */
    corto_object *a = corto_createChild(mount, "a", corto_void_o);
    if (!a) {
        goto error;
    }

    /* Show that the owner of a is connectorA */
    corto_info("The owner of a = '%s'", corto_idof(corto_ownerof(a)));

    /* Now we'll set the owner to mountB and create another object */
    corto_setOwner(connectorB);

    corto_object *b = corto_createChild(mount, "b", corto_void_o);
    if (!b) {
        goto error;
    }

    /* Show that the owner of b is connectorB */
    corto_info("The owner of b = '%s'", corto_idof(corto_ownerof(b)));

    /* Set ownership to no owner (this application) */
    corto_setOwner(NULL);

    /* Create an application owned object */
    corto_object *c = corto_createChild(mount, "c", corto_void_o);
    if (!c) {
        goto error;
    }

    /* Show that the owner of c is null */
    corto_info("The owner of c = '%p'", corto_ownerof(c));

    /* Now update the objects from their respective owners. This will trigger all
     * observers but the one from the current owner. */

    corto_info("Update object 'a' from 'connectorA'");
    corto_setOwner(connectorA);
    if (corto_update(a)) {
        goto error;
    }

    corto_info("Update object 'b' from 'connectorB'");
    corto_setOwner(connectorB);
    if (corto_update(b)) {
        goto error;
    }

    corto_info("Update object 'c' from the application");
    corto_setOwner(NULL);
    if (corto_update(c)) {
        goto error;
    }

    return 0;
error:
    corto_error("error: %s", corto_lasterr());
    return -1;
}


text:
module SmashAndGrab::Abilities
  # @abstract
  class Ability
    attr_reader :skill, :owner
    NON_SKILL = 0
    SKILL_LEVEL_DESCRIPTIONS = %w[Fair Good Excellent Heroic Legendary]

    def use?
      @cost.all? do |points, required|
        @owner.send(points) >= required
      end
    end

    def can_be_undone?; true; end
    def action_cost; @cost[:action_points] || 0; end
    def type; Inflector.underscore(Inflector.demodulize(self.class.name)).to_sym; end

    def tip
      if skill > NON_SKILL
       "#{SKILL_LEVEL_DESCRIPTIONS[skill - 1]} #{type.capitalize} #{skill_pips}"
      else
        type.capitalize
      end
    end

    # Used in tip to show what dice will be rolled (or just indication of skill for a skill not based on dice).
    def skill_pips
      # TODO: use a nicer symbol for this.
      "*" * skill
    end

    protected
    def initialize(owner, data)
      @owner = owner

      @skill = data[:skill] || raise(ArgumentError ,"No skill value for #{owner} #{self.class.name}")
      @cost = data[:cost] || {} # Defaults to being a free skill.
    end

    public
    # Data saved with the character.
    def to_json(*a)
      to_hash.to_json(*a)
    end

    def to_hash
      {
          type: type,
          skill: skill,
          cost: @cost,
      }
    end

    public
    # Data saved in the action list for a particular use of the ability (unless passive).
    def action_data
      {
          ability: type,
          skill: skill,
          cost: @cost,
          owner_id: owner.id
      }
    end

    def do(data)
      owner_spend data[:cost]
    end

    def undo(data)
      owner_refund data[:cost]
    end

    def to_s
      "<#{self.class.name} owner=#{owner} skill=#{skill} cost=#{@cost.inspect}>"
    end

    protected
    def owner_spend(cost)
      return unless cost
      cost.each do |point_type, amount|
        owner.send(:"#{point_type}=", owner.send(point_type) - amount)
      end
    end

    protected
    def owner_refund(cost)
      return unless cost
      cost.each do |point_type, amount|
        owner.send(:"#{point_type}=", owner.send(point_type) + amount)
      end
    end
  end

  # Ability that has an effect every turn.
  # @abstract
  class ContinuousAbility < Ability
    def active?; @active; end

    def initialize(owner, data)
      @active = data[:active]
      super(owner, data)
    end
  end

  # Ability that gives a permanent effect of some kind.
  # @abstract
  class PassiveAbility < ContinuousAbility
    def initialize(owner, data)
      super(owner, { active: true }.merge!(data))
    end
  end

  # An ability that has an effect, but the player can turn it on and off. e.g. Invisibility.
  # @abstract
  class ToggleAbility < ContinuousAbility
    def activate?; owner.action_points >= action_cost and not active?; end
    def deactivate?; owner.movement_points >= movement_bonus and active?; end

    def initialize(owner, data)
      super(owner, { active: false }.merge!(data))
    end

    def do(data)
      if active?
        deactivate data
      else
        activate data
      end
    end

    def undo(data)
      self.do data # Effect is based on current state, not on whether it is done or undone.
    end

    protected
    def activate(data)
      owner_spend data[:cost]
      @active = true
    end

    protected
    def deactivate(data)
      owner_refund data[:cost]
      @active = false
    end
  end

  # Ability that can be activated, but only on oneself.
  # @abstract
  class SelfAbility < Ability
  end

  # Ability that targets a particular tile.
  # @abstract
  class TargetedAbility < Ability
    def requires_line_of_sight?; true; end
    def target_valid?(tile); true; end

    def action_data(target_tile)
      target = target_tile.object ? target_tile.object.id : nil
      super().merge!(
          target_id: target,
          target_position: target_tile.grid_position
      )
    end

    protected
    def target(data); owner.map.object_by_id(data[:target_id]); end
  end

  # An ability that requires that the actor be adjacent to the target
  # and will move them if necessary. E.g. Melee or PickUp.
  # @abstract
  class TouchAbility < TargetedAbility
  end
end


text:
<?php

final class DrydockConsoleController extends DrydockController {

  public function shouldAllowPublic() {
    return true;
  }

  public function buildSideNavView() {
    $nav = new AphrontSideNavFilterView();
    $nav->setBaseURI(new PhutilURI($this->getApplicationURI()));

    // These are only used on mobile.

    $nav->addFilter('blueprint', pht('Blueprints'));
    $nav->addFilter('resource', pht('Resources'));
    $nav->addFilter('lease', pht('Leases'));

    $nav->selectFilter(null);

    return $nav;
  }

  public function handleRequest(AphrontRequest $request) {
    $viewer = $request->getViewer();

    $menu = id(new PHUIObjectItemListView())
      ->setUser($viewer);

    $menu->addItem(
      id(new PHUIObjectItemView())
        ->setHeader(pht('Blueprints'))
        ->setFontIcon('fa-map-o')
        ->setHref($this->getApplicationURI('blueprint/'))
        ->addAttribute(
          pht(
            'Configure blueprints so Drydock can build resources, like '.
            'hosts and working copies.')));

    $menu->addItem(
      id(new PHUIObjectItemView())
        ->setHeader(pht('Resources'))
        ->setFontIcon('fa-map')
        ->setHref($this->getApplicationURI('resource/'))
        ->addAttribute(
          pht('View and manage resources Drydock has built, like hosts.')));

    $menu->addItem(
      id(new PHUIObjectItemView())
        ->setHeader(pht('Leases'))
        ->setFontIcon('fa-link')
        ->setHref($this->getApplicationURI('lease/'))
        ->addAttribute(pht('Manage leases on resources.')));

    $crumbs = $this->buildApplicationCrumbs();
    $crumbs->addTextCrumb(pht('Console'));

    $box = id(new PHUIObjectBoxView())
      ->setHeaderText(pht('Drydock Console'))
      ->setObjectList($menu);

    return $this->buildApplicationPage(
      array(
        $crumbs,
        $box,
      ),
      array(
        'title'  => pht('Drydock Console'),
      ));
  }

}


text:
#ifndef LADSPA_BASE_H
#define LADSPA_BASE_H

#include "LadspaManager.h"
#include "Plugin.h"

class LadspaControl;

typedef enum BufferRates
{
	CHANNEL_IN,
	CHANNEL_OUT,
	AUDIO_RATE_INPUT,
	AUDIO_RATE_OUTPUT,
	CONTROL_RATE_INPUT,
	CONTROL_RATE_OUTPUT
} buffer_rate_t;

typedef enum BufferData
{
	TOGGLED,
	INTEGER,
	FLOATING,
	TIME,
	NONE
} buffer_data_t;

//! This struct is used to hold port descriptions internally
//! which where received from the ladspa plugin
typedef struct PortDescription
{
	QString name;
	ch_cnt_t proc;
	uint16_t port_id;
	uint16_t control_id;
	buffer_rate_t rate;
	buffer_data_t data_type;
	float scale;
	LADSPA_Data max;
	LADSPA_Data min;
	LADSPA_Data def;
	LADSPA_Data value;
	//! This is true iff ladspa suggests logscale
	//! Note however that the model can still decide to use a linear scale
	bool suggests_logscale;
	LADSPA_Data * buffer;
	LadspaControl * control;
} port_desc_t;

inline Plugin::Descriptor::SubPluginFeatures::Key ladspaKeyToSubPluginKey(
						const Plugin::Descriptor * _desc,
						const QString & _name,
						const ladspa_key_t & _key )
{
	Plugin::Descriptor::SubPluginFeatures::Key::AttributeMap m;
	QString file = _key.first;
	m["file"] = file.remove( QRegExp( "\\.so$" ) ).remove( QRegExp( "\\.dll$" ) );
	m["plugin"] = _key.second;
	return Plugin::Descriptor::SubPluginFeatures::Key( _desc, _name, m );
}

#endif


text:
<?php

class Lja_Weixin_Message_Handler_Text extends Lja_Weixin_Message_Handler_Base {
	protected $type = 'text';

	public function process() {
		switch (trim($this->msg->Content)) {
			case '1':
				$this->getShopAddress();
				break;
			case '2':
				$this->getGalleryAddress();
				break;
			default:
				$this->helpResponse();
				break;
		}

		$this->structure->CreateTime = time();

		parent::process();
	}

	protected function helpResponse()
	{
		$content = "发送 1 获取店铺地址\n";
		$content .= "发送 2 获取相册地址\n";

		$this->structure->Content = $content;
	}

	protected function getShopAddress()
	{
		$this->structure->Content = '一路妖娆的淘宝店铺地址是: http://shop33487592.taobao.com/';
	}

	protected function getGalleryAddress()
	{
		$this->structure->Content = '一路妖娆的相册地址是: http://mara.ipbfans.org/';
	}
}


text:
<?php

namespace Orchestra\Http\Concerns;

trait PassThrough
{
    /**
     * The application implementation.
     *
     * @var \Orchestra\Contracts\Foundation\Foundation
     */
    protected $foundation;

    /**
     * Determine if the request has a URI that should pass through CSRF verification.
     *
     * @param  \Illuminate\Http\Request  $request
     *
     * @return bool
     */
    protected function shouldPassThrough($request, array $routesToExclude)
    {
        foreach ($routesToExclude as $except) {
            if ($this->foundation->is($except)) {
                return true;
            }
        }

        return false;
    }
}


text:
import logging

from flask_bouncer import Bouncer, requires, ensure, skip_authorization  # type: ignore
from bouncer.models import RuleList  # type: ignore
from bouncer.constants import ALL, MANAGE, READ  # type: ignore
from werkzeug.exceptions import Forbidden

from data.models.user import User

__all__ = ["skip_authorization", "bouncer", "requires", "ensure"]

bouncer = Bouncer()
log = logging.getLogger(__name__)

@bouncer.authorization_method
def authorize(user: User, they: RuleList):
    def per_role(cls):
        """Reads _permissions from the given class and creates rules from it."""
        perms = getattr(cls, "_permissions")
        if perms is None or user is None:
            return

        # normalize role data type
        perms = {str(role): p for role, p in perms.items()}
        for role in user.roles:
            role_perms = perms.get(role.name)
            if role_perms is None:
                continue

            for action, check in role_perms.items():
                # accept all
                if check == ALL or check is True:
                    they.can(action, cls)
                # based on attribute values
                elif isinstance(check, dict):
                    they.can(action, cls, **check)
                # based on check function
                elif hasattr(check, "__call__"):

                    def gen_wrapper(check):
                        def wrapper(subject):
                            return check(subject, user)

                        return wrapper

                    they.can(action, cls, gen_wrapper(check))
                else:
                    they.can(action, cls, check)

    if user is not None:
        they.can(MANAGE, User, id=user.id)
        they.can(READ, User)
        they.can("READ_OWN", "Proposal")
        if user.is_reviewer():
            # reviewers can see the list of proposals
            they.can(READ, "Proposal")
        if user.is_admin():
            # admins can do everything
            they.can(MANAGE, ALL)

    # pylint: disable=import-outside-toplevel
    # import locally to avoid import cycle
    from data.models.vulnerability import Vulnerability

    # pylint: enable=import-outside-toplevel

    per_role(Vulnerability)

    log.debug("%s can %s", user, they)

def login_required(do_redirect=True):
    def decorator(func):
        return func

    del do_redirect
    return decorator

def admin_required(do_redirect=False):
    del do_redirect
    try:
        return requires(MANAGE, ALL)
    except Forbidden as ex:
        log.warning("Denied admin access: %s", ex.description)
        raise


text:
<?php
final class Front {
	protected $registry;
	protected $pre_action = array();
	protected $error;

	/* Journal2 Theme modification */
	public static $IS_INSTALLER = false;
	public static $IS_JOURNAL   = false;
	public static $IS_OC2       = false;
	public static $IS_ADMIN     = false;
	/* End of Journal2 Theme modification */

	public function __construct($registry) {
		$this->registry = $registry;
	}

	public function addPreAction($pre_action) {
		$this->pre_action[] = $pre_action;
	}

	public function dispatch($action, $error) {
		$this->error = $error;

		foreach ($this->pre_action as $pre_action) {
			$result = $this->execute($pre_action);

			if ($result) {
				$action = $result;

				break;
			}
		}

		/* Journal2 Theme modification */
		if (defined('HTTP_OPENCART')) {
			self::$IS_INSTALLER = true;
		} else if (defined('VERSION')) {
			global $config;
			self::$IS_OC2 = version_compare(VERSION, '2', '>=');
			if (file_exists(DIR_APPLICATION . 'model/journal2/journal2.php')) {
				require_once DIR_APPLICATION . 'model/journal2/journal2.php';
			}
			self::$IS_ADMIN = defined('JOURNAL_IS_ADMIN');
			self::$IS_JOURNAL = $config->get('config_template') === 'journal2' || $config->get('theme_default_directory') === 'journal2';
		}

		require_once(\VQMod::modCheck(DIR_SYSTEM . 'journal2/startup.php'));
		/* End of Journal2 Theme modification */

		while ($action) {
			$action = $this->execute($action);
		}
	}

	private function execute($action) {
	    // oc22 fix
        if (defined('VERSION') && version_compare(VERSION, '2.2', '>=')) {
            $result = $action->execute($this->registry);

            if ($result instanceof Action) {
                return $result;
            }

            if ($result instanceof Exception) {
                $action = $this->error;

                $this->error = null;

                return $action;
            }

            return;
        }

		if (method_exists($action, 'getFile')) {
			if (file_exists($action->getFile())) {
				require_once(\VQMod::modCheck($action->getFile()));

				$class = $action->getClass();

				$controller = new $class($this->registry);

				if (is_callable(array($controller, $action->getMethod()))) {
					$action = call_user_func_array(array($controller, $action->getMethod()), $action->getArgs());
				} else {
					$action = $this->error;

					$this->error = '';
				}
			} else {
				$action = $this->error;

				$this->error = '';
			}
		} else {
			$result = $action->execute($this->registry);

			if (is_object($result)) {
				$action = $result;
			} elseif ($result === false) {
				$action = $this->error;

				$this->error = '';
			} else {
				$action = false;
			}
		}

		return $action;
	}
}
?>


text:
#ifndef DDK750_POWER_H__
#define DDK750_POWER_H__

typedef enum _DPMS_t {
	crtDPMS_ON = 0x0,
	crtDPMS_STANDBY = 0x1,
	crtDPMS_SUSPEND = 0x2,
	crtDPMS_OFF = 0x3,
}
DPMS_t;

#define setDAC(off) {							\
	POKE32(MISC_CTRL,						\
	       (PEEK32(MISC_CTRL) & ~MISC_CTRL_DAC_POWER_OFF) | (off)); \
}

void ddk750_setDPMS(DPMS_t);

/*
 * This function sets the current power mode
 */
void setPowerMode(unsigned int powerMode);

/*
 * This function sets current gate
 */
void setCurrentGate(unsigned int gate);

/*
 * This function enable/disable the 2D engine.
 */
void enable2DEngine(unsigned int enable);

/*
 * This function enable/disable the DMA Engine
 */
void enableDMA(unsigned int enable);

/*
 * This function enable/disable the GPIO Engine
 */
void enableGPIO(unsigned int enable);

/*
 * This function enable/disable the I2C Engine
 */
void enableI2C(unsigned int enable);

#endif


text:
module.exports = function() {

  return {
    scripts: [
      'bower_components/angular/angular.min.js',
      'bower_components/ng-lodash/build/ng-lodash.min.js',
      'bower_components/momentum-actions/dist/actions.js',
      'bower_components/momentum-actions/dist/actions-tpl.js',
      // 'bower_components/angular-animate/angular-animate.min.js',
      // 'bower_components/angular-messages/angular-messages.min.js',
      // 'bower_components/angular-resource/angular-resource.min.js',
      // 'bower_components/angular-sanitize/angular-sanitize.min.js',
      // 'bower_components/angular-ui-router/release/angular-ui-router.min.js',
      // 'bower_components/angular-strap/dist/angular-strap.min.js',
      // 'bower_components/angular-strap/dist/angular-strap.tpl.min.js',
      // 'bower_components/satellizer/satellizer.min.js',
      // 'bower_components/angular-loading-bar/build/loading-bar.min.js',
      'app/app.js',
      'app/templates.js',
    ],
    less: [
      "bower_components/base/less/base.less",
      // "bower_components/base/less/desktop.less",
      // "bower_components/base/less/tablet.less",
      // "bower_components/base/less/mobile.less",
      'app/**/*.less'
    ],
    template_index: 'app/index.jade',
    templates: 'app/pages/**/*.jade',
    root: 'example/',
    testing: ['../tests/api/**/*.js'],
    fonts: ['bower_components/ionicons/fonts/*.*']
  };

}


text: Our Team


text:
<?php
/*
 * We are taking the advantage of wordpress allowing us to have wp-config.php one folder below the wordpress folder.
 * Now we can do anything we want, e.g: linking to our custom config files and also adding composer autoloader
 *
 * REF: https://codex.wordpress.org/Hardening_WordPress (see section: Securing wp-config.php)
 */

/** Location of your WordPress configuration. */
require_once dirname(__DIR__) . '/' . 'config.php';

/** Sets up WordPress vars and included files. */
require_once ABSPATH . 'wp-settings.php';

/**
 * Handle MAINTENANCE Mode
 */
if (defined('IN_MAINTENANCE') && (IN_MAINTENANCE == 'ON')) {
    header('Content-Type: text/html; charset=utf-8');
    if (file_exists(WP_CONTENT_DIR . '/maintenance.php')) {
        require_once WP_CONTENT_DIR . '/maintenance.php';
    }
    die();
}


text:
module.exports = function (app, passport) {
  app.get('/auth/github', passport.authenticate('github', { scope: ['user:email'] }),
    function(req, res) {
      // will never be called
    }
  );

  app.get('/auth/github/callback', passport.authenticate('github'),
    function(req, res) {
      res.redirect('/#/user/' + req.user.username);
    }
  );

  // signup/login only used for local auth
  // app.post('/signup', authController.signup);
  // app.post('/login', function(req, res) {});

  app.get('/logout', function(req, res) {
    req.logout();
    res.redirect('/');
    }
  );
};


text:
namespace we
{
    struct GrayscaleTerrain::GrayscaleTerrainImpl
    {
        GrayscaleTerrainImpl()
            : _scale(1.0f),
              _heightScale(1.0f)
        {}

        float _scale;
        float _heightScale;

        std::unique_ptr<Mesh3D> terrainMesh_;
        std::unique_ptr<sf::Image> grayscaleImage_;
    };

    GrayscaleTerrain::GrayscaleTerrain() noexcept
        : grayscaleTerrainImpl_(new GrayscaleTerrainImpl)
    {
    }

    GrayscaleTerrain::~GrayscaleTerrain() noexcept
    {
    }

    const std::unique_ptr<Mesh3D>& GrayscaleTerrain::getTerrainMesh() const noexcept
    {
        return grayscaleTerrainImpl_->terrainMesh_;
    }
    void GrayscaleTerrain::loadFromGrayscale(std::unique_ptr<sf::Image> image, std::unique_ptr<Material> material, const float heightScale, const float scale) noexcept
    {
        grayscaleTerrainImpl_->_scale = scale;
        grayscaleTerrainImpl_->_heightScale = heightScale;
        grayscaleTerrainImpl_->grayscaleImage_ = std::move(image);
        sf::Vector2u imageDimensions = grayscaleTerrainImpl_->grayscaleImage_->getSize();
        std::vector<glm::vec3> terrainVertices, terrainNormals;
        std::vector<glm::vec2> terrainUVs;
        for(unsigned int rowCounter = 0; rowCounter < imageDimensions.x - 1; ++ rowCounter)
        {
            for(unsigned int columnCounter = 0; columnCounter < imageDimensions.y - 1; ++ columnCounter)
            {
                sf::Color leftTriangleTopLeftColor = grayscaleTerrainImpl_->grayscaleImage_->getPixel(columnCounter, rowCounter + 1);
                sf::Color leftTriangleBottomLeftColor = grayscaleTerrainImpl_->grayscaleImage_->getPixel(columnCounter, rowCounter);
                sf::Color leftTriangleBottomRightColor = grayscaleTerrainImpl_->grayscaleImage_->getPixel(columnCounter + 1, rowCounter);

                sf::Color rightTriangleBottomLeftColor = grayscaleTerrainImpl_->grayscaleImage_->getPixel(columnCounter + 1, rowCounter);
                sf::Color rightTriangleTopRightColor = grayscaleTerrainImpl_->grayscaleImage_->getPixel(columnCounter + 1, rowCounter + 1);
                sf::Color rightTriangleTopLeftColor = grayscaleTerrainImpl_->grayscaleImage_->getPixel(columnCounter, rowCounter + 1);

                const float leftTriangleTopLeftHeight = static_cast<float>(grayscaleTerrainImpl_->_scale * leftTriangleTopLeftColor.r * grayscaleTerrainImpl_->_heightScale);
                const float leftTriangleBottomLeftHeight = static_cast<float>(grayscaleTerrainImpl_->_scale * leftTriangleBottomLeftColor.r * grayscaleTerrainImpl_->_heightScale);
                const float leftTriangleBottomRightHeight = static_cast<float>(grayscaleTerrainImpl_->_scale * leftTriangleBottomRightColor.r * grayscaleTerrainImpl_->_heightScale);

                const float rightTriangleBottomLeftHeight = static_cast<float>(grayscaleTerrainImpl_->_scale * rightTriangleBottomLeftColor.r * grayscaleTerrainImpl_->_heightScale);
                const float rightTriangleTopRightHeight = static_cast<float>(grayscaleTerrainImpl_->_scale * rightTriangleTopRightColor.r * grayscaleTerrainImpl_->_heightScale);
                const float rightTriangleTopLeftHeight = static_cast<float>(grayscaleTerrainImpl_->_scale * rightTriangleTopLeftColor.r * grayscaleTerrainImpl_->_heightScale);

                static const std::vector<glm::vec3> leftTriangleOrigin = { grayscaleTerrainImpl_->_scale * glm::vec3(-1.0f, 0.0f, 1.0f), //Top left
                                                                           grayscaleTerrainImpl_->_scale * glm::vec3(-1.0f, 0.0f, -1.0f), //Bottom left
                                                                           grayscaleTerrainImpl_->_scale * glm::vec3(1.0f, 0.0f, -1.0f) }; //Bottom right
                static const std::vector<glm::vec3> rightTriangleOrigin = { grayscaleTerrainImpl_->_scale * glm::vec3(1.0f, 0.0f, -1.0f), //Bottom left
                                                                            grayscaleTerrainImpl_->_scale * glm::vec3(1.0f, 0.0f, 1.0f), //Top right
                                                                            grayscaleTerrainImpl_->_scale * glm::vec3(-1.0f, 0.0f, 1.0f) }; //Top left

                std::vector<glm::vec3> leftTriangleOffset = leftTriangleOrigin;
                std::vector<glm::vec3> rightTriangleOffset = rightTriangleOrigin;

                for(glm::vec3& leftTriangleVertex : leftTriangleOffset)
                {
                    leftTriangleVertex += glm::vec3(columnCounter * 2, 0.0f, rowCounter * 2) * grayscaleTerrainImpl_->_scale;
                }
                for(glm::vec3& rightTriangleVertex : rightTriangleOffset)
                {
                    rightTriangleVertex += glm::vec3(columnCounter * 2, 0.0f, rowCounter * 2) * grayscaleTerrainImpl_->_scale;
                }

                leftTriangleOffset[0].y = leftTriangleTopLeftHeight;
                leftTriangleOffset[1].y = leftTriangleBottomLeftHeight;
                leftTriangleOffset[2].y = leftTriangleBottomRightHeight;

                rightTriangleOffset[0].y = rightTriangleBottomLeftHeight;
                rightTriangleOffset[1].y = rightTriangleTopRightHeight;
                rightTriangleOffset[2].y = rightTriangleTopLeftHeight;

                terrainVertices.insert(terrainVertices.end(), leftTriangleOffset.begin(), leftTriangleOffset.end());
                terrainVertices.insert(terrainVertices.end(), rightTriangleOffset.begin(), rightTriangleOffset.end());

                const glm::vec3& leftTriangleFirstEdge = leftTriangleOffset[0] - leftTriangleOffset[1];
                const glm::vec3& leftTriangleSecondEdge = leftTriangleOffset[2] - leftTriangleOffset[1];
                const glm::vec3& leftTriangleNormal = glm::normalize(glm::cross(leftTriangleFirstEdge, leftTriangleSecondEdge));

                const glm::vec3& rightTriangleFirstEdge = rightTriangleOffset[0] - rightTriangleOffset[1];
                const glm::vec3& rightTriangleSecondEdge = rightTriangleOffset[2] - rightTriangleOffset[1];
                const glm::vec3& rightTriangleNormal = glm::normalize(glm::cross(rightTriangleFirstEdge, rightTriangleSecondEdge));

                terrainNormals.push_back(leftTriangleNormal);
                terrainNormals.push_back(rightTriangleNormal);

                const std::shared_ptr<we::Texture>& texture = material->getTexture();
                if(texture)
                {
                    const float uvWidth = 1.0f / (grayscaleTerrainImpl_->_scale * imageDimensions.x);
                    const float uvHeight = 1.0f / (grayscaleTerrainImpl_->_scale * imageDimensions.y);

                    const glm::vec2 leftTriangleTopLeftUV(columnCounter * uvWidth, (rowCounter + 1) * uvHeight);
                    const glm::vec2 leftTriangleBottomLeftUV(columnCounter * uvWidth, rowCounter * uvHeight);
                    const glm::vec2 leftTriangleBottomRightUV((columnCounter + 1) * uvWidth, rowCounter * uvHeight);

                    const glm::vec2 rightTriangleBottomRightUV((columnCounter + 1) * uvWidth, rowCounter * uvHeight);
                    const glm::vec2 rightTriangleTopRightUV((columnCounter + 1) * uvWidth, (rowCounter + 1) * uvHeight);
                    const glm::vec2 rightTriangleTopLeftUV(columnCounter * uvWidth, (rowCounter + 1) * uvHeight);

                    terrainUVs.push_back(leftTriangleTopLeftUV);
                    terrainUVs.push_back(leftTriangleBottomLeftUV);
                    terrainUVs.push_back(leftTriangleBottomRightUV);

                    terrainUVs.push_back(rightTriangleBottomRightUV);
                    terrainUVs.push_back(rightTriangleTopRightUV);
                    terrainUVs.push_back(rightTriangleTopLeftUV);
                }
            }
        }

        std::vector<glm::vec4> colors;
        for(const glm::vec3& currentVertex : terrainVertices)
        {
            colors.push_back(glm::vec4(0.0f, cos(currentVertex.x) * sin(currentVertex.y), 0.0f, 0.0f));
        }

        grayscaleTerrainImpl_->terrainMesh_.reset(new Mesh3D(terrainVertices, terrainNormals,
                                                    colors, terrainUVs));
        grayscaleTerrainImpl_->terrainMesh_->setScale(grayscaleTerrainImpl_->_scale);
        grayscaleTerrainImpl_->terrainMesh_->setMaterial(std::move(material));
    }
}


text:
export class Controller {
  readonly name: string;
  readonly clusterName: string;
  readonly liveInstance: string;
  readonly sessionId: string;
  readonly helixVersion: string;

  constructor(name, cluster, liveInstance, sessionId, version) {
    this.name = name;
    this.clusterName = cluster;
    this.liveInstance = liveInstance;
    this.sessionId = sessionId;
    this.helixVersion = version;
  }
}


text:
package edu.wustl.catissuecore.action;

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import edu.wustl.catissuecore.actionForm.CTRPEntityForm;
import edu.wustl.catissuecore.ctrp.COPPAServiceClient;
import edu.wustl.catissuecore.ctrp.COPPAUtil;
import edu.wustl.catissuecore.domain.User;
import edu.wustl.catissuecore.util.global.AppUtility;
import edu.wustl.common.action.BaseAction;
import edu.wustl.common.util.logger.Logger;
import gov.nih.nci.coppa.po.Person;

public class CTRPUserAction extends BaseAction {

	/**
	 * logger.
	 */
	private transient final Logger logger = Logger
			.getCommonLogger(CTRPUserAction.class);

	/**
	 * Overrides the executeSecureAction method of SecureAction class.
	 *
	 * @param mapping
	 *            object of ActionMapping
	 * @param form
	 *            object of ActionForm
	 * @param request
	 *            object of HttpServletRequest
	 * @param response
	 *            : response obj
	 * @throws Exception
	 *             generic exception
	 * @return ActionForward : ActionForward
	 */
	@Override
	public ActionForward executeAction(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		CTRPEntityForm ctrpEntityForm = (CTRPEntityForm) form;
		COPPAServiceClient client = new COPPAServiceClient();

		Enumeration<String> names;
		names = request.getAttributeNames();
		while (names.hasMoreElements()) {
			String name = names.nextElement();
			System.out.println("RequestAttribute-" + name + ":"
					+ request.getAttribute(name));
		}
		names = request.getHeaderNames();
		while (names.hasMoreElements()) {
			String name = names.nextElement();
			System.out.println("RequestHeader-" + name + ":"
					+ request.getAttribute(name));
		}
		names = request.getParameterNames();
		while (names.hasMoreElements()) {
			String name = names.nextElement();
			System.out.println("RequestParam-" + name + ":"
					+ request.getAttribute(name));
		}

        String emailAddress = StringUtils.isBlank(request
                .getParameter("emailAddress")) ? "" : request
                .getParameter("emailAddress");
		String firstName = request.getParameter("firstName");
		String lastName = request.getParameter("lastName");
		System.out.println("Form Variables:" + ctrpEntityForm.getEmailAddress()
				+ ":" + ctrpEntityForm.getFirstName() + ":"
				+ ctrpEntityForm.getLastName());
		if (StringUtils.isNotBlank(ctrpEntityForm.getEmailAddress())) {
			//Use email address from search form
			emailAddress = ctrpEntityForm.getEmailAddress();
		}
		emailAddress = StringUtils.trim(emailAddress);
		User searchUser = new User();
		// searchUser.setEmailAddress(ctrpEntityForm.getEntityName());
		searchUser.setEmailAddress(emailAddress);
		searchUser.setFirstName(firstName);
		searchUser.setLastName(lastName);
		Person[] userList = null;
		userList = new COPPAServiceClient().searchPerson(searchUser);
		if (userList != null && userList.length > 0) {
			request.setAttribute("COPPA_MATCH_FOUND", "true");
			request.setAttribute("COPPA_USERS", userList);
		}

		return mapping.findForward("displayMatches");
	}
}