text:
title: "Rank Scores"
description: "Some description ..."
authors: ["lek-tin"]
tags: ["leetcode", "sql"]
categories: ["database"]
date: 2020-03-03T16:56:09-08:00
lastmod: 2020-03-03T16:56:09-08:00
draft: false
archive: false
---
Write a SQL query to rank scores. If there is a tie between two scores, both should have the same ranking. Note that after a tie, the next ranking number should be the next consecutive integer value. In other words, there should be no "holes" between ranks.

```
+----+-------+
| Id | Score |
+----+-------+
| 1  | 3.50  |
| 2  | 3.65  |
| 3  | 4.00  |
| 4  | 3.85  |
| 5  | 4.00  |
| 6  | 3.65  |
+----+-------+
```

For example, given the above `Scores` table, your query should generate the following report (order by highest score):

```
+-------+------+
| Score | Rank |
+-------+------+
| 4.00  | 1    |
| 4.00  | 1    |
| 3.85  | 2    |
| 3.65  | 3    |
| 3.65  | 3    |
| 3.50  | 4    |
+-------+------+
```

### Solution (COUNT)

For each score in Scores, count how many scores in t are larger than or equal to it:
```sql
SELECT s.Score,
        COUNT(t.Score) AS Rank
FROM
  (SELECT DISTINCT Score FROM Scores) AS t, Scores AS s
    WHERE
      s.Score <= t.Score
    GROUP BY
      s.Id, s.Score
    ORDER BY
      s.Score DESC
```

### Solution (row variable)

```sql
--  Subquery 2: Generate row_number
SELECT s.Score, r.Rank
FROM (
    -- Subquery 1: Generate unique scores and ranks
    SELECT Score, (@row_number:=@row_number + 1) AS `Rank`
    FROM (
        SELECT Score
        FROM Scores
        GROUP BY Score
        ORDER BY Score DESC
    ) AS s,
    (SELECT @row_number:=0) AS dummy
) AS r
RIGHT JOIN
    Scores AS s
    ON s.Score = r.Score
ORDER BY r.Rank;
```

### Solution

```sql
SELECT Score, CASE
WHEN @pre = Score THEN @rk + 0
WHEN @pre := Score THEN @rk := @rk + 1
ELSE @rk := @rk + 1
END AS Rank
FROM Scores, (SELECT @pre := NULL, @rk := 0) AS init
ORDER BY Score DESC;
```

If we have version 8, we can use ROW_NUMBER() OVER() to solve this easily.


text:
module Pruefung160304 where

{-
Aufgabe 2
Erstellen sie einen polymorphen algebraischen Datentyp BTree der einem Binärbaum entspricht.
Jeder Knoten enthält ein polymorphes Element und zwei Unterbäume. Ein Knoten bzw. die Unterbäume können auch leer sein.
-}

data BTree a = Nil | Node a (BTree a) (BTree a)

{-
Aufgabe 3
Geben Sie einen konkreten Wert für folgenden Typ in Haskell-Syntax inklusive Zeichnung an: BTree (BTree Integer, String).
Die Bäume sollen die Werte 1,2 und "ab" enthalten.
-}

btree3 = Node ((Node 2 (Node 1 Nil Nil) Nil),"ab") Nil Nil

{-
Aufgabe 4
Definieren Sie eine Funktion jdif die für einen BTree genau dann True liefert, wenn
für jeden Knoten gilt, dass das Element des Knotens nicht öfters als einmal in den
Unterbäumen des Knotens vorkommt. (Typklasse!)
-}

jdif :: (Eq a) => BTree a -> Bool -- (Eq a) wird benötigt damit elem funktioniert
jdif btree = jdif2 btree []

jdif2 :: (Eq a) => BTree a -> [a] -> Bool
jdif2 Nil _ = True
jdif2 (Node a t1 t2) l
  | elem a l = False
  | otherwise = jdif2 t1 l2 && jdif2 t2 l2
  where l2 = l ++ [a]

{- Aufgabe 5
Definieren Sie ftx, das eine einstellige boolsche Funktion und einen BTree erwartet und
eine Liste mit Tripeln in beliebiger Reihenfolge zurückliefert, bei denen die Funktion für
den Knoten True ist. Das erste Element des Tripels soll den Knoten enhalten,
das zweite und dritten den linken bzw. rechten Unterbaum.
Geben Sie auch hier eine möglichst allgemeine Typdeklaration für ftx an!
-}

ftx :: (a -> Bool) -> BTree a -> [(BTree a, BTree a, BTree a)]
ftx _ Nil = []
ftx f n@(Node a t1 t2) = [(n,t1,t2) | f a] ++ ftx f t1 ++ ftx f t2

redpajama_set_name: RedPajamaGithub


text:
package io.github.avatarhurden.tribalwarsengine.ferramentas.simulador;

import io.github.avatarhurden.tribalwarsengine.enums.Cores;
import io.github.avatarhurden.tribalwarsengine.ferramentas.simulador.SimuladorPanel.OutputInfo;
import io.github.avatarhurden.tribalwarsengine.objects.unit.Army;
import io.github.avatarhurden.tribalwarsengine.objects.unit.Unit;

import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.text.NumberFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;

import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.LineBorder;

import config.Lang;

@SuppressWarnings("serial")
public class ResultTroopDisplay extends JPanel {

	private OutputInfo output;

	private Map<Unit, JLabel> tropasAtacantesPerdidas = new HashMap<Unit, JLabel>();

	private Map<Unit, JLabel> tropasDefensorasPerdidas = new HashMap<Unit, JLabel>();

	private JLabel muralha, edifício;

	public ResultTroopDisplay(OutputInfo output) {

		this.output = output;

		setOpaque(false);

		GridBagLayout layout = new GridBagLayout();
		layout.columnWidths = new int[] {};
		layout.rowHeights = new int[] { 0 };
		layout.columnWeights = new double[] { 1.0, Double.MIN_VALUE };
		layout.rowWeights = new double[] { 0.0, 0.0, 0.0, 0.0, 0.0 };
		setLayout(layout);

		GridBagConstraints c = new GridBagConstraints();
		c.gridx = 0;
		c.gridy = 0;

		// Panel that says that the shown units are lost units
		JPanel identificationPanel = new JPanel();
		identificationPanel.setBackground(Cores.FUNDO_ESCURO);
		identificationPanel.setBorder(new LineBorder(Cores.SEPARAR_ESCURO));

		identificationPanel.add(new JLabel(Lang.UnidadesPerdidas.toString()));

		identificationPanel.setPreferredSize(new Dimension(
				identificationPanel.getPreferredSize().width-2, identificationPanel.getPreferredSize().height-3));

		c.insets = new Insets(0, 5, 1, 0);
		c.fill = GridBagConstraints.HORIZONTAL;
		c.gridwidth = 3;
		add(identificationPanel, c);

		c.gridwidth = 1;
		c.gridy++;
		c.insets = new Insets(2, 5, 5, 5);
		add(addUnitNames(), c);

		c.gridx++;
		c.anchor = GridBagConstraints.NORTH;
		c.insets = new Insets(5, 5, 5, 0);
		add(addAttackUnitPanel(), c);

		c.gridx++;
		add(addDefenseUnitPanel(), c);

		// Panel to store the wall and building panels, so they center nicely
		JPanel bottomPanels = new JPanel();
		bottomPanels.setOpaque(false);

		bottomPanels.add(addWall());
		bottomPanels.add(addBuilding());

		c.gridy++;
		c.gridx = 0;
		c.gridwidth = 3;
		add(bottomPanels, c);

	}

	public JPanel addUnitNames() {
		return new Army().getEditPanelNoInputs(26);
	}

	private JPanel addHeaderPanel(String name) {
		JPanel panel = new JPanel();
		panel.setBackground(Cores.FUNDO_ESCURO);
		panel.setBorder(new LineBorder(Cores.SEPARAR_ESCURO));

		panel.add(new JLabel(name));

		panel.setPreferredSize(new Dimension(panel.getPreferredSize().width, 28));

		return panel;
	}

	public JPanel addAttackUnitPanel() {
		JPanel panel = new JPanel();
		panel.setOpaque(false);

		panel.setLayout(new GridBagLayout());

		GridBagConstraints c = new GridBagConstraints();
		c.insets = new Insets(0, 0, 5, 0);
		c.fill = GridBagConstraints.HORIZONTAL;
		c.gridx = 0;
		c.gridy = 0;
		c.gridwidth = 1;

		panel.add(addHeaderPanel("Atacante"), c);

		c.gridy++;
		panel.add(makeUnitPanel(Army.getAttackingUnits(), tropasAtacantesPerdidas), c);

		return panel;
	}

	public JPanel addDefenseUnitPanel() {
		JPanel panel = new JPanel();
		panel.setOpaque(false);

		panel.setLayout(new GridBagLayout());

		GridBagConstraints c = new GridBagConstraints();
		c.insets = new Insets(0, 0, 5, 0);
		c.fill = GridBagConstraints.HORIZONTAL;
		c.gridx = 0;
		c.gridy = 0;

		panel.add(addHeaderPanel("Defensor"), c);

		c.gridy++;
		panel.add(makeUnitPanel(Army.getAvailableUnits(), tropasDefensorasPerdidas), c);

		return panel;
	}

	private JPanel makeUnitPanel(List<Unit> list, Map<Unit, JLabel> map) {

		JPanel panel = new JPanel();
		panel.setBorder(new LineBorder(Cores.SEPARAR_ESCURO));
		panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
		panel.setOpaque(false);

		int loop = 1;
		for (Unit i : list) {

			JPanel tropaPanel = new JPanel();
			tropaPanel.setPreferredSize(new Dimension(60, 26));
			tropaPanel.setBackground(Cores.getAlternar(loop));

			// Creating the TextField for the quantity of troops
			JLabel lbl = new JLabel(" ");
			// Adding the text to a map with the units
			map.put(i, lbl);

			tropaPanel.add(lbl);

			loop++;
			panel.add(tropaPanel);

		}

		return panel;
	}

	public JPanel addWall() {

		// Setting the background and borders for the panel
		JPanel panel = new JPanel();
		// Define a cor do panel com base no número de tropas do mundo
		panel.setBackground(Cores.getAlternar(1));
		panel.setBorder(new LineBorder(Cores.SEPARAR_ESCURO, 1, false));

		GridBagLayout layout = new GridBagLayout();
		layout.columnWidths = new int[] { 80, 30 };
		layout.rowHeights = new int[] { 0 };
		layout.columnWeights = new double[] { 1.0, Double.MIN_VALUE };
		layout.rowWeights = new double[] { 0.0, 0.0, 0.0, 0.0, 0.0 };
		panel.setLayout(layout);

		GridBagConstraints c = new GridBagConstraints();
		c.insets = new Insets(5, 5, 5, 5);
		c.gridx = 0;
		c.gridy = 0;

		panel.add(new JLabel(Lang.Muralha.toString()), c);

		muralha = new JLabel(" ");

		c.gridx++;
		panel.add(muralha, c);

		return panel;

	}

	public JPanel addBuilding() {

		// Setting the background and borders for the panel
		JPanel panel = new JPanel();
		// Define a cor do panel com base no número de tropas do mundo
		panel.setBackground(Cores.getAlternar(1));
		panel.setBorder(new LineBorder(Cores.SEPARAR_ESCURO, 1, false));

		GridBagLayout layout = new GridBagLayout();
		layout.columnWidths = new int[] { 80, 30 };
		layout.rowHeights = new int[] { 0 };
		layout.columnWeights = new double[] { 1.0, Double.MIN_VALUE };
		layout.rowWeights = new double[] { 0.0, 0.0, 0.0, 0.0, 0.0 };
		panel.setLayout(layout);

		GridBagConstraints c = new GridBagConstraints();
		c.insets = new Insets(5, 5, 5, 5);
		c.gridx = 0;
		c.gridy = 0;

		panel.add(new JLabel(Lang.Edificio.toString()), c);

		edifício = new JLabel(" ");

		c.gridx++;
		panel.add(edifício, c);

		return panel;

	}

	public void setValues() {

		NumberFormat numberFormat = NumberFormat
				.getNumberInstance(Locale.GERMANY);

		for (Entry<Unit, JLabel> i : tropasAtacantesPerdidas.entrySet())
			i.getValue().setText(numberFormat.format(
					output.getLostAttacker().getQuantidade(i.getKey())));

		for (Entry<Unit, JLabel> i : tropasDefensorasPerdidas.entrySet())
			i.getValue().setText(numberFormat.format(
					output.getLostDefender().getQuantidade(i.getKey())));

		muralha.setText(String.valueOf(output.getMuralha()));

		edifício.setText(String.valueOf(output.getEdifício()));

	}

	public void resetValues() {

		for (Entry<Unit, JLabel> i : tropasAtacantesPerdidas.entrySet())
			i.getValue().setText(" ");

		for (Entry<Unit, JLabel> i : tropasDefensorasPerdidas.entrySet())
			i.getValue().setText(" ");

		muralha.setText(" ");

		edifício.setText(" ");

	}

}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/llSettings"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/tvSettingsLabel"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="40dp"
        android:gravity="center"
        android:padding="15dp"
        android:text="@string/tv_settings_label"
        android:textSize="40sp"
        android:textColor="#ffffff"
        android:textStyle="bold" />

    <ScrollView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >

        <LinearLayout
            android:id="@+id/llSettingsScrollView"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" >

                <RelativeLayout
                    android:id="@+id/rlSettingsScrollView1"
                    android:layout_width="fill_parent"
                    android:layout_height="fill_parent"
                    android:paddingBottom="15dp"
                    android:paddingTop="15dp" >

                    <TextView
                        android:id="@+id/tvSettingsTextSizeLabel"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_alignParentLeft="true"
                        android:layout_centerVertical="true"
                        android:layout_marginLeft="60dp"
                        android:text="@string/tv_settings_text_size_label"
                        android:textColor="#ffffff"
                        android:textSize="30sp" />

                    <Spinner
                        android:id="@+id/spSettingsTextSize"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_alignParentRight="true"
                        android:layout_centerVertical="true"
                        android:layout_marginRight="60dp" />
                </RelativeLayout>

                <RelativeLayout
                    android:id="@+id/rlSettingsScrollView2"
                    android:layout_width="fill_parent"
                    android:layout_height="fill_parent"
                    android:paddingBottom="15dp"
                    android:paddingTop="15dp" >

                    <TextView
                        android:id="@+id/tvSettingsShopLabel"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_alignParentLeft="true"
                        android:layout_centerVertical="true"
                        android:layout_marginLeft="60dp"
                        android:text="@string/tv_settings_shop_label"
                        android:textColor="#ffffff"
                        android:textSize="30sp" />

                    <ImageButton
                        android:contentDescription="@string/ib_settings_shop_content_description"
                        android:id="@+id/ibSettingsShop"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_alignParentRight="true"
                        android:layout_centerVertical="true"
                        android:layout_marginRight="60dp"
                        android:background="@null"
                        android:src="@drawable/button_shop" />
                </RelativeLayout>

                <RelativeLayout
                    android:id="@+id/rlSettingsScrollView3"
                    android:layout_width="fill_parent"
                    android:layout_height="fill_parent"
                    android:paddingBottom="15dp"
                    android:paddingTop="15dp" >

                    <TextView
                        android:id="@+id/tvSettingsCreditsLabel"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_alignParentLeft="true"
                        android:layout_centerVertical="true"
                        android:layout_marginLeft="60dp"
                        android:textColor="#ffffff"
                        android:text="@string/tv_settings_credits_label"
                        android:textSize="30sp" />

                    <ImageButton
                        android:contentDescription="@string/ib_settings_credits_content_description"
                        android:id="@+id/ibSettingsCredits"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_alignParentRight="true"
                        android:layout_centerVertical="true"
                        android:layout_marginRight="60dp"
                        android:background="@null"
                        android:src="@drawable/button_next" />
                </RelativeLayout>
        </LinearLayout>
    </ScrollView>

</LinearLayout>


text:
var utils = require('./utils');
var templates = require('./templates');
var PassportProfileMapper = require('./claims/PassportProfileMapper');
var URL_PATH = '/FederationMetadata/2007-06/FederationMetadata.xml';
var encoders = require('./encoders');

function getEndpointAddress (req, endpointPath) {
  endpointPath = endpointPath ||
    (req.originalUrl.substr(0, req.originalUrl.length - URL_PATH.length));

  return utils.getBaseUrl(req) + endpointPath;
}

/**
 * WSFederation metadata endpoint
 *
 * This endpoint returns a wsfederation metadata document.
 *
 * You should expose this endpoint in an address like:
 *
 * 'https://your-wsfederation-server.com/FederationMetadata/2007-06/FederationMetadata.xml
 *
 * options:
 * - issuer string
 * - cert the public certificate
 * - profileMapper a function that given a user returns a claim based identity, also contains the metadata. By default maps from Passport.js user schema (PassportProfile).
 * - endpointPath optional, defaults to the root of the fed metadata document.
 * - mexEndpoint optional, url of the wsfederation MEX endpoint metadata document.
 *
 * @param  {[type]} options [description]
 * @return {[type]}         [description]
 */
function metadataMiddleware (options) {
  //claimTypes, issuer, pem, endpointPath
  options = options || {};

  if(!options.issuer) {
    throw new Error('options.issuer is required');
  }

  if(!options.cert) {
    throw new Error('options.cert is required');
  }

  var claimTypes = (options.profileMapper || PassportProfileMapper).prototype.metadata;
  var issuer = options.issuer;
  var pem = encoders.removeHeaders(options.cert);

  return function (req, res) {
    var endpoint = getEndpointAddress(req, options.endpointPath);
    var mexEndpoint = options.mexEndpoint ? getEndpointAddress(req, options.mexEndpoint) : '';

    res.set('Content-Type', 'application/xml');

    res.send(templates.metadata({
      claimTypes:   claimTypes,
      pem:          pem,
      issuer:       issuer,
      endpoint:     endpoint,
      mexEndpoint:  mexEndpoint
    }).replace(/\n/g, ''));
  };
}

module.exports = metadataMiddleware;


text:
CREATE TABLE abc(a, b);
INSERT INTO abc VALUES(1, 2);
INSERT INTO abc VALUES(3, 4);
INSERT INTO abc VALUES(5, 6);


text:
import Helper from '@ember/component/helper';
import RSVP from 'rsvp';

export default class extends Helper {
  compute(params) {
    const args = Array.isArray(params[0]) ? params[0] : params;

    return RSVP.all(args);
  }
}


text:
package com.amazonaws.services.dynamodbv2.metrics;

import com.amazonaws.metrics.RequestMetricType;

/**
 * DynamoDB specific request metric type.
 */
public enum DynamoDBRequestMetric implements RequestMetricType {
    /** Number of capacity units consumed. */
    DynamoDBConsumedCapacity,
    ;
}


text:
import * as types from 'constants/MovieDataActionTypes';
import { MOVIES_ENDPOINT } from 'constants/Endpoints';
import { authenticatedFetch } from 'utils/api';

export function asyncCreateMovie({ movie, watchListId }) {
  return (dispatch, getState) => {
    authenticatedFetch(MOVIES_ENDPOINT, getState, {
      method: 'POST',
      body: Object.assign(movie, { watch_list_id: watchListId })
    })
    .then(json => dispatch(createMovie(movie)));
  };
}

export function asyncDeleteMovie({ movie }) {
	return (dispatch, getState) => {
		authenticatedFetch(`${MOVIES_ENDPOINT}/${movie.id}`, getState, { method: 'DELETE' })
      .then(json => dispatch(deleteMovie(movie)));
	};
}

export function asyncUpdateMovie({ movie }) {
	return (dispatch, getState) => {
    authenticatedFetch(`${MOVIES_ENDPOINT}/${movie.id}`, getState, {
      method: 'PATCH',
      body: JSON.stringify(movie)
    })
    .then(json => dispatch(updateMovie(json.movie)));
	};
}

export function getMovies() {
  return (dispatch, getState) => {
    authenticatedFetch(MOVIES_ENDPOINT, getState).then(json => dispatch(updateMovies(json.movies)));
  };
}

export function createMovie(movie) {
  return { type: types.CREATE_MOVIE, movie };
}

export function deleteMovie(movie) {
	return { type: types.DELETE_MOVIE, movie };
}

export function updateMovie(movie) {
  return { type: types.UPDATE_MOVIE, movie };
}

export function updateMovies(movies) {
  return { type: types.UPDATE_MOVIES, movies };
}


text:
package org.springframework.cloud.dataflow.server.service.impl.validation;

import java.io.File;
import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.boot.loader.archive.Archive;
import org.springframework.boot.loader.archive.ExplodedArchive;
import org.springframework.boot.loader.archive.JarFileArchive;
import org.springframework.cloud.dataflow.configuration.metadata.BootClassLoaderFactory;
import org.springframework.cloud.dataflow.core.AppRegistration;
import org.springframework.cloud.dataflow.core.ApplicationType;
import org.springframework.cloud.dataflow.registry.service.AppRegistryService;
import org.springframework.cloud.dataflow.server.DockerValidatorProperties;
import org.springframework.cloud.dataflow.server.service.ValidationService;
import org.springframework.cloud.deployer.resource.docker.DockerResource;
import org.springframework.core.io.Resource;
import org.springframework.util.Assert;

/**
 * Implementation of Validation Service that delegates to the application registry.
 *
 * @author Glenn Renfo
 * @author Mark Pollack
 */
public class DefaultValidationService implements ValidationService {

	private static final Logger logger = LoggerFactory.getLogger(DefaultValidationService.class);

	/**
	 * The urls and credentials to required to validate access docker resources.
	 */
	private final DockerValidatorProperties dockerValidatorProperties;

	private final AppRegistryService appRegistry;

	public DefaultValidationService(AppRegistryService appRegistry,
			DockerValidatorProperties dockerValidatorProperties) {
		Assert.notNull(dockerValidatorProperties, "DockerValidatorProperties must not be null");
		Assert.notNull(appRegistry, "AppRegistryService must not be null");
		this.dockerValidatorProperties = dockerValidatorProperties;
		this.appRegistry = appRegistry;
	}

	@Override
	public boolean isRegistered(String name, ApplicationType applicationType) {
		return appRegistry.appExist(name, applicationType);
	}

	@Override
	public boolean validate(String name, ApplicationType appType) {
		Assert.hasText(name, "name must not be null or empty");
		Assert.notNull(appType, "ApplicationType must not be null");
		boolean result = false;
		AppRegistration registration = appRegistry.find(name, appType);

		if (registration != null) {
			result = validateResource(appRegistry.getAppResource(registration));

		}
		return result;
	}

	private boolean validateResource(Resource resource) {
		boolean result = false;
		if(resource != null) {
			try {
				if ((resource instanceof DockerResource)) {
					result = validateDockerResource(dockerValidatorProperties, (DockerResource) resource);
				}
				else {
					new BootClassLoaderFactory(resolveAsArchive(resource), null)
							.createClassLoader();
					result = true;
				}
			}
			catch (Exception ex) {
				logger.info("The app was marked invalid because: ", ex);
			}
		}
		return result;
	}

	private static boolean validateDockerResource(DockerValidatorProperties dockerValidatorProperties,
			DockerResource resource) throws Exception {
		DockerRegistryValidator info = new DockerRegistryValidator(dockerValidatorProperties, resource);
		return info.isImagePresent();
	}

	private static Archive resolveAsArchive(Resource app) throws IOException {
		Assert.notNull(app, "The resource specified for the app must not be null");
		File moduleFile = app.getFile();
		return moduleFile.isDirectory() ? new ExplodedArchive(moduleFile) : new JarFileArchive(moduleFile);
	}

}


text:
#pragma once

#include <cstdint>
#include <cmath>

#include <Eigen/Sparse>
#include <Eigen/Dense>

#include <crest/geometry/indexed_mesh.hpp>
#include <crest/util/eigen_extensions.hpp>
#include <crest/quadrature/triquad.hpp>
#include <crest/basis/basis.hpp>

namespace crest
{
    /**
     * A standard linear Lagrangian basis
     */
    template <typename Scalar>
    class LagrangeBasis2d : public Basis<Scalar, LagrangeBasis2d<Scalar>>
    {
    public:
        explicit LagrangeBasis2d(const IndexedMesh<Scalar, int> & mesh) : _mesh(mesh) {}

        virtual std::vector<int> boundary_nodes() const override { return _mesh.boundary_vertices(); }
        virtual std::vector<int> interior_nodes() const override { return _mesh.compute_interior_vertices(); }

        virtual Assembly<Scalar> assemble() const override;

        virtual int num_dof() const override { return _mesh.num_vertices(); }

        template <typename Function2d>
        VectorX<Scalar> interpolate(const Function2d &f) const;

        template <typename Function2d>
        VectorX<Scalar> interpolate_boundary(const Function2d &f) const;

        template <int QuadStrength, typename Function2d>
        VectorX<Scalar> load(const Function2d &f) const;

        template <int QuadStrength, typename Function2d>
        Scalar error_l2(const Function2d &f, const VectorX<Scalar> & weights) const;

        template <int QuadStrength, typename Function2d_x, typename Function2d_y>
        Scalar error_h1_semi(const Function2d_x & f_x,
                             const Function2d_y & f_y,
                             const VectorX<Scalar> & weights) const;

    private:
        const IndexedMesh<double, int> & _mesh;
    };

    namespace detail
    {
        template <typename Scalar>
        struct assembly_triplets {
            std::vector<Eigen::Triplet<Scalar>> stiffness_triplets;
            std::vector<Eigen::Triplet<Scalar>> mass_triplets;
        };

        template <typename Scalar>
        assembly_triplets<Scalar> assemble_linear_lagrangian_system_triplets(
                const crest::IndexedMesh<Scalar, int> & mesh);
    }

    /*
     * IMPLEMENTATION BELOW
     */

    template <typename Scalar>
    detail::assembly_triplets<Scalar> detail::assemble_linear_lagrangian_system_triplets(
            const crest::IndexedMesh<Scalar, int> & mesh)
    {
        const static Eigen::Matrix<Scalar, 3, 3> M_LOCAL_REF = (1.0 / 24.0) * (Eigen::Matrix3d()
                <<
                2.0, 1.0, 1.0,
                1.0, 2.0, 1.0,
                1.0, 1.0, 2.0
        ).finished().cast<Scalar>();

        const static Eigen::Matrix<Scalar, 3, 3> A11 = (1.0 / 2.0) * (Eigen::Matrix3d()
                <<
                1.0, 0.0, -1.0,
                0.0, 0.0, 0.0,
                -1.0, 0.0, 1.0
        ).finished().cast<Scalar>();

        const static Eigen::Matrix<Scalar, 3, 3> A12 = (1.0 / 2.0) * (Eigen::Matrix3d()
                <<
                0.0, 1.0, -1.0,
                1.0, 0.0, -1.0,
                -1.0, -1.0, 2.0
        ).finished().cast<Scalar>();

        const static Eigen::Matrix<Scalar, 3, 3> A22 = (1.0 / 2.0) * (Eigen::Matrix3d()
                <<
                0.0, 0.0, 0.0,
                0.0, 1.0, -1.0,
                0.0, -1.0, 1.0
        ).finished().cast<Scalar>();

        std::vector<Eigen::Triplet<Scalar>> mass_triplets;
        std::vector<Eigen::Triplet<Scalar>> stiffness_triplets;
        mass_triplets.reserve(3 * mesh.num_elements());
        stiffness_triplets.reserve(3 * mesh.num_elements());

        for (const auto & element : mesh.elements())
        {
            const auto a = mesh.vertices()[element.vertex_indices[0]];
            const auto b = mesh.vertices()[element.vertex_indices[1]];
            const auto c = mesh.vertices()[element.vertex_indices[2]];

            const auto v1 = a - c;
            const auto v2 = b - c;

            const Eigen::Matrix2d jacobian = (Eigen::Matrix2d() << v1.x, v2.x, v1.y, v2.y).finished();
            const Eigen::Matrix2d jacobian_inverse = jacobian.inverse();
            const Eigen::Matrix2d C = jacobian_inverse * jacobian_inverse.transpose();
            const auto abs_det_jacobian = std::abs(jacobian.determinant());

            const Eigen::Matrix<Scalar, 3, 3> A_local = abs_det_jacobian * (C(0, 0) * A11 + C(0, 1) * A12 + C(1, 1) * A22);
            const Eigen::Matrix<Scalar, 3, 3> M_local = abs_det_jacobian * M_LOCAL_REF;

            typedef Eigen::Triplet<Scalar> T;
            for (size_t i = 0; i < 3; ++i)
            {
                for (size_t j = 0; j < 3; ++j)
                {
                    const auto I = element.vertex_indices[i];
                    const auto J = element.vertex_indices[j];
                    mass_triplets.emplace_back(T(I, J, M_local(i, j)));
                    stiffness_triplets.emplace_back(T(I, J, A_local(i, j)));
                }
            }
        }

        return detail::assembly_triplets<Scalar> {
                std::move(stiffness_triplets),
                std::move(mass_triplets)
        };
    }

    template <typename Scalar>
    Assembly<Scalar> LagrangeBasis2d<Scalar>::assemble() const
    {
        const auto triplets = detail::assemble_linear_lagrangian_system_triplets(_mesh);

        Assembly<Scalar> assembly;

        // Stiffness
        assembly.stiffness = Eigen::SparseMatrix<Scalar>(num_dof(), num_dof());
        assembly.stiffness.setFromTriplets(triplets.stiffness_triplets.cbegin(), triplets.stiffness_triplets.cend());

        // Mass
        assembly.mass = Eigen::SparseMatrix<Scalar>(num_dof(), num_dof());
        assembly.mass.setFromTriplets(triplets.mass_triplets.cbegin(), triplets.mass_triplets.cend());

        return assembly;
    }

    template <typename Scalar>
    template <int QuadStrength, typename Function2d>
    VectorX<Scalar> LagrangeBasis2d<Scalar>::load(const Function2d & f) const
    {
        Eigen::VectorXd load(_mesh.num_vertices());
        load.setZero();

        // See triquad.hpp for the mapping used here
        const auto a_basis = [] (auto x, auto  ) { return Scalar(0.5) * x + Scalar(0.5); };
        const auto b_basis = [] (auto  , auto y) { return Scalar(0.5) * y + Scalar(0.5); };
        const auto c_basis = [] (auto x, auto y) { return Scalar(0.5) * (-x - y); };

        for (const auto element : _mesh.elements())
        {
            const auto z0 = element.vertex_indices[0];
            const auto z1 = element.vertex_indices[1];
            const auto z2 = element.vertex_indices[2];

            const auto & a = _mesh.vertices()[z0];
            const auto & b = _mesh.vertices()[z1];
            const auto & c = _mesh.vertices()[z2];
            const auto transform = triquad_transform(a, b, c);
            const auto transformed_f = [&f, &transform] (auto x, auto y)
            {
                const auto coords = transform.transform_from_reference(x, y);
                return f(coords.x, coords.y);
            };

            const auto absdet = transform.absolute_determinant();

            load(z0) += absdet * triquad_ref<QuadStrength, Scalar>(
                    [&] (auto x, auto y) { return transformed_f(x, y) * a_basis(x, y); }
            );
            load(z1) += absdet * triquad_ref<QuadStrength, Scalar>(
                    [&] (auto x, auto y) { return transformed_f(x, y) * b_basis(x, y); }
            );
            load(z2) += absdet * triquad_ref<QuadStrength, Scalar>(
                    [&] (auto x, auto y) { return transformed_f(x, y) * c_basis(x, y); }
            );
        }

        return load;
    }

    template <typename Scalar>
    template <typename Function2d>
    VectorX<Scalar> LagrangeBasis2d<Scalar>::interpolate(const Function2d & f) const
    {
        // Simple nodal interpolation
        auto result = VectorX<Scalar>(_mesh.num_vertices());
        for (int i = 0; i < _mesh.num_vertices(); ++i)
        {
            const auto vertex = _mesh.vertices()[i];
            result(i) = f(vertex.x, vertex.y);
        }
        return result;
    }

    template <typename Scalar>
    template <typename Function2d>
    VectorX<Scalar> LagrangeBasis2d<Scalar>::interpolate_boundary(const Function2d & f) const
    {
        // Simple nodal interpolation
        auto result = VectorX<Scalar>(_mesh.num_boundary_vertices());
        const auto & boundary_indices = _mesh.boundary_vertices();
        for (int i = 0; i < _mesh.num_boundary_vertices(); ++i)
        {
            const auto vertex_index = boundary_indices[i];
            const auto vertex = _mesh.vertices()[vertex_index];
            result(i) = f(vertex.x, vertex.y);
        }
        return result;
    }

    template <typename Scalar>
    template <int QuadStrength, typename Function2d>
    Scalar LagrangeBasis2d<Scalar>::error_l2(const Function2d &f, const VectorX<Scalar> & weights) const
    {
        Scalar error_squared = Scalar(0);

        // See triquad.hpp for the mapping used here
        const auto basis0 = [] (auto x, auto  ) { return Scalar(0.5) * x + Scalar(0.5); };
        const auto basis1 = [] (auto  , auto y) { return Scalar(0.5) * y + Scalar(0.5); };
        const auto basis2 = [] (auto x, auto y) { return Scalar(0.5) * (-x - y); };

#pragma omp parallel for reduction(+:error_squared)
        for (int element_index = 0; element_index < _mesh.num_elements(); ++element_index)
        {
            const auto element = _mesh.elements()[element_index];
            const auto z0 = element.vertex_indices[0];
            const auto z1 = element.vertex_indices[1];
            const auto z2 = element.vertex_indices[2];

            const auto w0 = weights(z0);
            const auto w1 = weights(z1);
            const auto w2 = weights(z2);

            const auto & a = _mesh.vertices()[z0];
            const auto & b = _mesh.vertices()[z1];
            const auto & c = _mesh.vertices()[z2];
            const auto transform = triquad_transform(a, b, c);
            const auto f_ref = [&f, &transform] (auto x, auto y)
            {
                const auto coords = transform.transform_from_reference(x, y);
                return f(coords.x, coords.y);
            };

            // Computes the square of the difference of f and f_h in the reference triangle
            const auto diff_ref_squared = [&] (auto x, auto y)
            {
                const auto f_h_ref = w0 * basis0(x, y) +
                                     w1 * basis1(x, y) +
                                     w2 * basis2(x, y);

                const auto diff = f_ref(x, y) - f_h_ref;
                return diff * diff;
            };

            const auto absdet = transform.absolute_determinant();
            error_squared += absdet * triquad_ref<QuadStrength, Scalar>(diff_ref_squared);
        }

        return std::sqrt(error_squared);
    };

    template <typename Scalar>
    template <int QuadStrength, typename Function2d_x, typename Function2d_y>
    Scalar LagrangeBasis2d<Scalar>::error_h1_semi(const Function2d_x & f_x,
                                                  const Function2d_y & f_y,
                                                  const VectorX<Scalar> & weights) const
    {
        Scalar error_squared = Scalar(0);

        // See triquad.hpp for the mapping used here
        const auto basis0_x = Scalar(0.5);
        const auto basis0_y = Scalar(0.0);
        const auto basis1_x = Scalar(0.0);
        const auto basis1_y = Scalar(0.5);
        const auto basis2_x = Scalar(-0.5);
        const auto basis2_y = Scalar(-0.5);

#pragma omp parallel for reduction(+:error_squared)
        for (int element_index = 0; element_index < _mesh.num_elements(); ++element_index)
        {
            const auto element = _mesh.elements()[element_index];
            const auto z0 = element.vertex_indices[0];
            const auto z1 = element.vertex_indices[1];
            const auto z2 = element.vertex_indices[2];

            const auto w0 = weights(z0);
            const auto w1 = weights(z1);
            const auto w2 = weights(z2);

            const auto & a = _mesh.vertices()[z0];
            const auto & b = _mesh.vertices()[z1];
            const auto & c = _mesh.vertices()[z2];
            const auto transform = triquad_transform(a, b, c);

            const auto f_grad_ref = [&f_x, &f_y, &transform] (auto x, auto y)
            {
                const auto coords = transform.transform_from_reference(x, y);
                Eigen::Matrix<Scalar, 2, 1> grad;
                grad(0) = f_x(coords.x, coords.y);
                grad(1) = f_y(coords.x, coords.y);
                return grad;
            };

            // Since we have linear elements, the gradients are constants
            Eigen::Matrix<Scalar, 2, 1> f_h_grad_ref;
            f_h_grad_ref(0) = w0 * basis0_x +
                              w1 * basis1_x +
                              w2 * basis2_x;
            f_h_grad_ref(1) = w0 * basis0_y +
                              w1 * basis1_y +
                              w2 * basis2_y;

            // Due to change of variables, we have to left-apply J^-T
            const Eigen::Matrix<Scalar, 2, 2> J_inv_t = transform.jacobian().inverse().transpose();
            const Eigen::Matrix<Scalar, 2, 1> f_h_grad_ref_transformed = J_inv_t * f_h_grad_ref;

            // Computes the square of the difference of grad(f) and grad(f_h)
            // in the reference triangle
            const auto diff_squared = [&] (auto x, auto y)
            {
                // Note that J_inv_t cancels with J_t for f_grad_ref
                const Eigen::Matrix<Scalar, 2, 1> diff = f_grad_ref(x, y) - f_h_grad_ref_transformed;
                return diff.dot(diff);
            };

            const auto absdet = transform.absolute_determinant();
            error_squared += absdet * triquad_ref<QuadStrength, Scalar>(diff_squared);
        }

        return std::sqrt(error_squared);
    };
}


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

#include <emmintrin.h>

#include "qcmsint.h"

/* pre-shuffled: just load these into XMM reg instead of load-scalar/shufps sequence */
#define FLOATSCALE  (float)(PRECACHE_OUTPUT_SIZE)
#define CLAMPMAXVAL ( ((float) (PRECACHE_OUTPUT_SIZE - 1)) / PRECACHE_OUTPUT_SIZE )
static const ALIGN float floatScaleX4[4] =
    { FLOATSCALE, FLOATSCALE, FLOATSCALE, FLOATSCALE};
static const ALIGN float clampMaxValueX4[4] =
    { CLAMPMAXVAL, CLAMPMAXVAL, CLAMPMAXVAL, CLAMPMAXVAL};

void qcms_transform_data_rgb_out_lut_sse2(qcms_transform *transform,
                                          unsigned char *src,
                                          unsigned char *dest,
                                          size_t length)
{
    unsigned int i;
    float (*mat)[4] = transform->matrix;
    char input_back[32];
    /* Ensure we have a buffer that's 16 byte aligned regardless of the original
     * stack alignment. We can't use __attribute__((aligned(16))) or __declspec(align(32))
     * because they don't work on stack variables. gcc 4.4 does do the right thing
     * on x86 but that's too new for us right now. For more info: gcc bug #16660 */
    float const * input = (float*)(((uintptr_t)&input_back[16]) & ~0xf);
    /* share input and output locations to save having to keep the
     * locations in separate registers */
    uint32_t const * output = (uint32_t*)input;

    /* deref *transform now to avoid it in loop */
    const float *igtbl_r = transform->input_gamma_table_r;
    const float *igtbl_g = transform->input_gamma_table_g;
    const float *igtbl_b = transform->input_gamma_table_b;

    /* deref *transform now to avoid it in loop */
    const uint8_t *otdata_r = &transform->output_table_r->data[0];
    const uint8_t *otdata_g = &transform->output_table_g->data[0];
    const uint8_t *otdata_b = &transform->output_table_b->data[0];

    /* input matrix values never change */
    const __m128 mat0  = _mm_load_ps(mat[0]);
    const __m128 mat1  = _mm_load_ps(mat[1]);
    const __m128 mat2  = _mm_load_ps(mat[2]);

    /* these values don't change, either */
    const __m128 max   = _mm_load_ps(clampMaxValueX4);
    const __m128 min   = _mm_setzero_ps();
    const __m128 scale = _mm_load_ps(floatScaleX4);

    /* working variables */
    __m128 vec_r, vec_g, vec_b, result;

    /* CYA */
    if (!length)
        return;

    /* one pixel is handled outside of the loop */
    length--;

    /* setup for transforming 1st pixel */
    vec_r = _mm_load_ss(&igtbl_r[src[0]]);
    vec_g = _mm_load_ss(&igtbl_g[src[1]]);
    vec_b = _mm_load_ss(&igtbl_b[src[2]]);
    src += 3;

    /* transform all but final pixel */

    for (i=0; i<length; i++)
    {
        /* position values from gamma tables */
        vec_r = _mm_shuffle_ps(vec_r, vec_r, 0);
        vec_g = _mm_shuffle_ps(vec_g, vec_g, 0);
        vec_b = _mm_shuffle_ps(vec_b, vec_b, 0);

        /* gamma * matrix */
        vec_r = _mm_mul_ps(vec_r, mat0);
        vec_g = _mm_mul_ps(vec_g, mat1);
        vec_b = _mm_mul_ps(vec_b, mat2);

        /* crunch, crunch, crunch */
        vec_r  = _mm_add_ps(vec_r, _mm_add_ps(vec_g, vec_b));
        vec_r  = _mm_max_ps(min, vec_r);
        vec_r  = _mm_min_ps(max, vec_r);
        result = _mm_mul_ps(vec_r, scale);

        /* store calc'd output tables indices */
        _mm_store_si128((__m128i*)output, _mm_cvtps_epi32(result));

        /* load for next loop while store completes */
        vec_r = _mm_load_ss(&igtbl_r[src[0]]);
        vec_g = _mm_load_ss(&igtbl_g[src[1]]);
        vec_b = _mm_load_ss(&igtbl_b[src[2]]);
        src += 3;

        /* use calc'd indices to output RGB values */
        dest[0] = otdata_r[output[0]];
        dest[1] = otdata_g[output[1]];
        dest[2] = otdata_b[output[2]];
        dest += 3;
    }

    /* handle final (maybe only) pixel */

    vec_r = _mm_shuffle_ps(vec_r, vec_r, 0);
    vec_g = _mm_shuffle_ps(vec_g, vec_g, 0);
    vec_b = _mm_shuffle_ps(vec_b, vec_b, 0);

    vec_r = _mm_mul_ps(vec_r, mat0);
    vec_g = _mm_mul_ps(vec_g, mat1);
    vec_b = _mm_mul_ps(vec_b, mat2);

    vec_r  = _mm_add_ps(vec_r, _mm_add_ps(vec_g, vec_b));
    vec_r  = _mm_max_ps(min, vec_r);
    vec_r  = _mm_min_ps(max, vec_r);
    result = _mm_mul_ps(vec_r, scale);

    _mm_store_si128((__m128i*)output, _mm_cvtps_epi32(result));

    dest[0] = otdata_r[output[0]];
    dest[1] = otdata_g[output[1]];
    dest[2] = otdata_b[output[2]];
}

void qcms_transform_data_rgba_out_lut_sse2(qcms_transform *transform,
                                           unsigned char *src,
                                           unsigned char *dest,
                                           size_t length)
{
    unsigned int i;
    float (*mat)[4] = transform->matrix;
    char input_back[32];
    /* Ensure we have a buffer that's 16 byte aligned regardless of the original
     * stack alignment. We can't use __attribute__((aligned(16))) or __declspec(align(32))
     * because they don't work on stack variables. gcc 4.4 does do the right thing
     * on x86 but that's too new for us right now. For more info: gcc bug #16660 */
    float const * input = (float*)(((uintptr_t)&input_back[16]) & ~0xf);
    /* share input and output locations to save having to keep the
     * locations in separate registers */
    uint32_t const * output = (uint32_t*)input;

    /* deref *transform now to avoid it in loop */
    const float *igtbl_r = transform->input_gamma_table_r;
    const float *igtbl_g = transform->input_gamma_table_g;
    const float *igtbl_b = transform->input_gamma_table_b;

    /* deref *transform now to avoid it in loop */
    const uint8_t *otdata_r = &transform->output_table_r->data[0];
    const uint8_t *otdata_g = &transform->output_table_g->data[0];
    const uint8_t *otdata_b = &transform->output_table_b->data[0];

    /* input matrix values never change */
    const __m128 mat0  = _mm_load_ps(mat[0]);
    const __m128 mat1  = _mm_load_ps(mat[1]);
    const __m128 mat2  = _mm_load_ps(mat[2]);

    /* these values don't change, either */
    const __m128 max   = _mm_load_ps(clampMaxValueX4);
    const __m128 min   = _mm_setzero_ps();
    const __m128 scale = _mm_load_ps(floatScaleX4);

    /* working variables */
    __m128 vec_r, vec_g, vec_b, result;
    unsigned char alpha;

    /* CYA */
    if (!length)
        return;

    /* one pixel is handled outside of the loop */
    length--;

    /* setup for transforming 1st pixel */
    vec_r = _mm_load_ss(&igtbl_r[src[0]]);
    vec_g = _mm_load_ss(&igtbl_g[src[1]]);
    vec_b = _mm_load_ss(&igtbl_b[src[2]]);
    alpha = src[3];
    src += 4;

    /* transform all but final pixel */

    for (i=0; i<length; i++)
    {
        /* position values from gamma tables */
        vec_r = _mm_shuffle_ps(vec_r, vec_r, 0);
        vec_g = _mm_shuffle_ps(vec_g, vec_g, 0);
        vec_b = _mm_shuffle_ps(vec_b, vec_b, 0);

        /* gamma * matrix */
        vec_r = _mm_mul_ps(vec_r, mat0);
        vec_g = _mm_mul_ps(vec_g, mat1);
        vec_b = _mm_mul_ps(vec_b, mat2);

        /* store alpha for this pixel; load alpha for next */
        dest[3] = alpha;
        alpha   = src[3];

        /* crunch, crunch, crunch */
        vec_r  = _mm_add_ps(vec_r, _mm_add_ps(vec_g, vec_b));
        vec_r  = _mm_max_ps(min, vec_r);
        vec_r  = _mm_min_ps(max, vec_r);
        result = _mm_mul_ps(vec_r, scale);

        /* store calc'd output tables indices */
        _mm_store_si128((__m128i*)output, _mm_cvtps_epi32(result));

        /* load gamma values for next loop while store completes */
        vec_r = _mm_load_ss(&igtbl_r[src[0]]);
        vec_g = _mm_load_ss(&igtbl_g[src[1]]);
        vec_b = _mm_load_ss(&igtbl_b[src[2]]);
        src += 4;

        /* use calc'd indices to output RGB values */
        dest[0] = otdata_r[output[0]];
        dest[1] = otdata_g[output[1]];
        dest[2] = otdata_b[output[2]];
        dest += 4;
    }

    /* handle final (maybe only) pixel */

    vec_r = _mm_shuffle_ps(vec_r, vec_r, 0);
    vec_g = _mm_shuffle_ps(vec_g, vec_g, 0);
    vec_b = _mm_shuffle_ps(vec_b, vec_b, 0);

    vec_r = _mm_mul_ps(vec_r, mat0);
    vec_g = _mm_mul_ps(vec_g, mat1);
    vec_b = _mm_mul_ps(vec_b, mat2);

    dest[3] = alpha;

    vec_r  = _mm_add_ps(vec_r, _mm_add_ps(vec_g, vec_b));
    vec_r  = _mm_max_ps(min, vec_r);
    vec_r  = _mm_min_ps(max, vec_r);
    result = _mm_mul_ps(vec_r, scale);

    _mm_store_si128((__m128i*)output, _mm_cvtps_epi32(result));

    dest[0] = otdata_r[output[0]];
    dest[1] = otdata_g[output[1]];
    dest[2] = otdata_b[output[2]];
}


text:
#pragma once

#include <utility.reader.h>

namespace nspace {

  class Color;
  class Material;

/**
 * \brief Material reader (MTL format).
 *       specification of mtl:  http://web.archive.org/web/20080813073052/http://local.wasp.uwa.edu.au/~pbourke/dataformats/mtl/
 */
  class MtlReader : public Reader {
    REFLECTABLE_OBJECT(MtlReader);
    SUBCLASSOF(Reader);

    /**
     * \brief resulting vector of materials
     *
     */
    std::vector<std::shared_ptr<Material> > _materials;

    /**
     * \brief map of parsers for line beginnings.
     */
    std::map<std::string, std::function<void (std::istream & stream)> > parsers;

    /**
     * \brief The current material being read.
     */
    std::shared_ptr<Material> currentMaterial;
private:
    void parseNewMaterial(std::istream &stream);
    Color parseColor(std::istream & stream);
    void parseSpecular(std::istream & stream);
    void parseDiffuse(std::istream & stream);
    void parseAmbient(std::istream & stream);
    void parseIlluminationModel(std::istream & stream);
    void parseShininess(std::istream & stream);
    void parseSharpness(std::istream  &stream);
    void parseRefractionIndex(std::istream & stream);
    void parseDissolve(std::istream & stream);
    void parseTransmissionFilter(std::istream & stream);

public:

    /**
     * \brief Default constructor.
     */
    MtlReader();

    /**
     * \brief Gets the materials that were read.
     *
     * \return  the reference to the material pointer vector.
     */
    const std::vector<std::shared_ptr<Material> > & Materials();
protected:

    /**
     * \brief Executes the read operation.
     *
     * \return  true if it succeeds, false if it fails.
     */
    bool doRead();
  };
}


text:
<?php

namespace WebSockets\Common;

/**
 * Dispatches events.
 *
 * @package WebSockets\Server
 */
trait EventDispatcherTrait
{
    /** @var EventListenerInterface[]|callable[] */
    private $eventListeners = [];

    /**
     * Adds a event listener to the subscribed list.
     *
     * @param EventListenerInterface|callable $listener
     */
    public function addEventListener($listener)
    {
        $this->eventListeners[] = $listener;
    }

    /**
     * Un-subscribe a event listener.
     *
     * @param EventListenerInterface|callable $listener
     */
    public function removeEventListener($listener)
    {
        $key = array_search($listener, $this->eventListeners, false);
        if ($key !== false) {
            unset($this->eventListeners[$key]);
        }
    }

    /**
     * Notify the event listeners that there's a event, or connection is opened or closed.
     *
     * @param Event $event The event object.
     */
    public function notifyEventListeners(Event $event)
    {
        $event->setSent();
        foreach ($this->eventListeners as $listener) {
            if ($listener instanceof EventListenerInterface) {
                $listener->gotEvent($event);
            } else {
                if (is_callable($listener)) {
                    $listener($event);
                }
            }
        }
    }

    /**
     * Creates an event object.
     *
     * @param null $eventId
     * @return Event A new event.
     */
    protected function createEvent($eventId = null)
    {
        $event = new Event($this, $eventId);

        return $event;
    }
}


text:
<?php

namespace PMS\Machine;
use PMS\Object\Interfaces\ServerInterface;
use Exception;
use SimpleXMLElement;
use PMS\Object\SimplePMSObject;

class Server implements ServerInterface{

    protected $silent = false;
    protected $metadata = [
        'name'      =>      null,
        'address'   =>      null,
        'port'      =>      null,
        'timeout'   =>      5
    ];

    protected $ch = null;

    public function __construct(array $params, $silent = false) {
        $this->silent = (bool)$silent;
        $this->import($params);
    }

    //======================= Item Part =======================
    public function __get($name) {
        if(isset($this->$name)) return $this->metadata[$name];
        return null;
    }

    public function __isset($name) {
        return array_key_exists($name, $this->metadata);
    }

    public function __set($name, $value) {
        if(!isset($this->$name)) return;
        $message = sprintf('%s : Property "%s" is invalid.',  get_called_class(), $name);
        switch ($name){
            case 'name';
                if(!is_string($value)) return $this->throwException($message);
                break;
            case 'address':
                if(!filter_var($value,FILTER_VALIDATE_IP)) return $this->throwException($message);
                break;
            case 'port':
            case 'timeout':
                if(!is_int($value) or $value < 1 or $value > 65535) return $this->throwException($message);
                break;
        }
        $this->metadata[$name] = $value;

    }

    public function __unset($name) {}

    public function export() {
        $r = [];
        foreach ($this->metadata as $name => $value){
            $r[$name]=$value;
        }
        return $r;
    }

    public function import($data) {
        if(!is_array($data)) return false;
        foreach ($data as $name => $value){
            $this->$name = $value;
        }
        $this->connect();
    }

    public function serialize() {
        return serialize($this->export());
    }

    public function unserialize($serialized) {
        $this->import(unserialize($serialized));
    }

    //======================= Exception =======================
    protected function throwException($message){
        if($this->silent) return null;
        throw new Exception($message);
    }

    //======================= Request Handling =======================

    protected function connect(){
        $ch = &$this->ch;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT , $this->timeout);
        curl_setopt($ch, CURLOPT_URL, $this->getBaseUrl());
        $response = curl_exec($ch);
        if ($response === false){
            $this->throwException(sprintf('%s : Cannot connect to PMS Server "%s" : %s.',  get_called_class(),  $this->name, curl_error($ch)));
            $ch = null;
        }

    }

    public function getData($url) {
        if($xml = $this->getRawData($url)) return new SimplePMSObject($this->parseXML($xml));
        return null;
    }

    public function getaData($url) {
        if($xml = $this->getRawData($url)) return $this->parseXML($xml);
        return null;
    }

    public function getRawData($url) {
        if(!$this->isConnected()) return null;
        $url = $this->getBaseUrl().$url;
        $ch = &$this->ch;
        curl_setopt($ch, CURLOPT_URL, $url);
        $response = curl_exec($ch);
        if ($response === FALSE) {
            $exception = sprintf('%s : Curl Error : error connecting to url "%s" : %s.',  get_class($this), $url, curl_error($ch));
            $this->throw_exception($exception);
        }
        return $response;
    }

    public function isConnected() {
        return !is_null($this->ch);
    }

    public function parseXML($xml) {
        if($xmlobj = simplexml_load_string($xml)) return $this->mergeAttributes ($xmlobj);
        return null;
    }

    protected function mergeAttributes(SimpleXMLElement $xmlobj, $pass = 0) {
        $r = [];
        if($pass > 0){
            foreach ($xmlobj->attributes() as $k => $v){
                $r[$k] = (string) $v[0];
            }
        }
        foreach ($xmlobj->children() as $el => $child){
            if($pass > 0){
                $r[$el][] = $this->mergeattributes($child,($pass + 1));
            }
            else{
                $r[] = $this->mergeattributes($child,($pass + 1));
            }
        }
        return $r;
    }

    public function getBaseUrl() {
        return sprintf('http://%s:%d',  $this->address,  $this->port);
    }

}


text:
Function Get-PerformanceCounterLocalName
{
  param
  (
    [UInt32]
    $ID,

    $ComputerName = $env:COMPUTERNAME
  )

  $code = '[DllImport("pdh.dll", SetLastError=true, CharSet=CharSet.Unicode)] public static extern UInt32 PdhLookupPerfNameByIndex(string szMachineName, uint dwNameIndex, System.Text.StringBuilder szNameBuffer, ref uint pcchNameBufferSize);'

  $Buffer = New-Object System.Text.StringBuilder(1024)
  [UInt32]$BufferSize = $Buffer.Capacity

  $t = Add-Type -MemberDefinition $code -PassThru -Name PerfCounter -Namespace Utility
  $rv = $t::PdhLookupPerfNameByIndex($ComputerName, $id, $Buffer, [Ref]$BufferSize)

  if ($rv -eq 0)
  {
    $Buffer.ToString().Substring(0, $BufferSize-1)
  }
  else
  {
    Throw 'Get-PerformanceCounterLocalName : Unable to retrieve localized name. Check computer name and performance counter ID.'
  }
}

$processor = Get-PerformanceCounterLocalName 238
$percentProcessorTime = Get-PerformanceCounterLocalName 6

(Get-Counter "\$processor(_total)\$percentProcessorTime" -SampleInterval 1).CounterSamples.CookedValue


text:
Changes the sign of a number.

## Usage:

**negate number**

## Arguments:

**number** - The number argument. (must be: number pair money time bitset)

## Description:

Returns the negative of the value provided.

```
print negate 123
-123
```

```
print negate -123
123
```

```
print negate 123.45
-123.45
```

```
print negate -123.45
123.45
```

```
print negate 10:30
-10:30
```

```
print negate 100x20
-100x-20
```

```
print negate 100x-20
-100x20
```

## Related:

[**+**](http://www.rebol.com/docs/words/w+.html) - Returns the result of adding two values.
[**-**](http://www.rebol.com/docs/words/w-.html) - Returns the second value subtracted from the first.
[**negative?**](http://www.rebol.com/docs/words/wnegativeq.html) - Returns TRUE if the number is negative.
[**positive?**](http://www.rebol.com/docs/words/wpositiveq.html) - Returns TRUE if the value is positive.


text:
namespace gameplay
{

extern void luaGlobal_Register_Conversion_Function(const char* className, void*(*func)(void*, const char*));

static Theme::ThemeImage* getInstance(lua_State* state)
{
    void* userdata = luaL_checkudata(state, 1, "ThemeThemeImage");
    luaL_argcheck(state, userdata != NULL, 1, "'ThemeThemeImage' expected.");
    return (Theme::ThemeImage*)((gameplay::ScriptUtil::LuaObject*)userdata)->instance;
}

static int lua_ThemeThemeImage__gc(lua_State* state)
{
    // Get the number of parameters.
    int paramCount = lua_gettop(state);

    // Attempt to match the parameters to a valid binding.
    switch (paramCount)
    {
        case 1:
        {
            if ((lua_type(state, 1) == LUA_TUSERDATA))
            {
                void* userdata = luaL_checkudata(state, 1, "ThemeThemeImage");
                luaL_argcheck(state, userdata != NULL, 1, "'ThemeThemeImage' expected.");
                gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)userdata;
                if (object->owns)
                {
                    Theme::ThemeImage* instance = (Theme::ThemeImage*)object->instance;
                    SAFE_RELEASE(instance);
                }

                return 0;
            }

            lua_pushstring(state, "lua_ThemeThemeImage__gc - Failed to match the given parameters to a valid function signature.");
            lua_error(state);
            break;
        }
        default:
        {
            lua_pushstring(state, "Invalid number of parameters (expected 1).");
            lua_error(state);
            break;
        }
    }
    return 0;
}

static int lua_ThemeThemeImage_addRef(lua_State* state)
{
    // Get the number of parameters.
    int paramCount = lua_gettop(state);

    // Attempt to match the parameters to a valid binding.
    switch (paramCount)
    {
        case 1:
        {
            if ((lua_type(state, 1) == LUA_TUSERDATA))
            {
                Theme::ThemeImage* instance = getInstance(state);
                instance->addRef();

                return 0;
            }

            lua_pushstring(state, "lua_ThemeThemeImage_addRef - Failed to match the given parameters to a valid function signature.");
            lua_error(state);
            break;
        }
        default:
        {
            lua_pushstring(state, "Invalid number of parameters (expected 1).");
            lua_error(state);
            break;
        }
    }
    return 0;
}

static int lua_ThemeThemeImage_getColor(lua_State* state)
{
    // Get the number of parameters.
    int paramCount = lua_gettop(state);

    // Attempt to match the parameters to a valid binding.
    switch (paramCount)
    {
        case 1:
        {
            if ((lua_type(state, 1) == LUA_TUSERDATA))
            {
                Theme::ThemeImage* instance = getInstance(state);
                void* returnPtr = (void*)&(instance->getColor());
                if (returnPtr)
                {
                    gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
                    object->instance = returnPtr;
                    object->owns = false;
                    luaL_getmetatable(state, "Vector4");
                    lua_setmetatable(state, -2);
                }
                else
                {
                    lua_pushnil(state);
                }

                return 1;
            }

            lua_pushstring(state, "lua_ThemeThemeImage_getColor - Failed to match the given parameters to a valid function signature.");
            lua_error(state);
            break;
        }
        default:
        {
            lua_pushstring(state, "Invalid number of parameters (expected 1).");
            lua_error(state);
            break;
        }
    }
    return 0;
}

static int lua_ThemeThemeImage_getId(lua_State* state)
{
    // Get the number of parameters.
    int paramCount = lua_gettop(state);

    // Attempt to match the parameters to a valid binding.
    switch (paramCount)
    {
        case 1:
        {
            if ((lua_type(state, 1) == LUA_TUSERDATA))
            {
                Theme::ThemeImage* instance = getInstance(state);
                const char* result = instance->getId();

                // Push the return value onto the stack.
                lua_pushstring(state, result);

                return 1;
            }

            lua_pushstring(state, "lua_ThemeThemeImage_getId - Failed to match the given parameters to a valid function signature.");
            lua_error(state);
            break;
        }
        default:
        {
            lua_pushstring(state, "Invalid number of parameters (expected 1).");
            lua_error(state);
            break;
        }
    }
    return 0;
}

static int lua_ThemeThemeImage_getRefCount(lua_State* state)
{
    // Get the number of parameters.
    int paramCount = lua_gettop(state);

    // Attempt to match the parameters to a valid binding.
    switch (paramCount)
    {
        case 1:
        {
            if ((lua_type(state, 1) == LUA_TUSERDATA))
            {
                Theme::ThemeImage* instance = getInstance(state);
                unsigned int result = instance->getRefCount();

                // Push the return value onto the stack.
                lua_pushunsigned(state, result);

                return 1;
            }

            lua_pushstring(state, "lua_ThemeThemeImage_getRefCount - Failed to match the given parameters to a valid function signature.");
            lua_error(state);
            break;
        }
        default:
        {
            lua_pushstring(state, "Invalid number of parameters (expected 1).");
            lua_error(state);
            break;
        }
    }
    return 0;
}

static int lua_ThemeThemeImage_getRegion(lua_State* state)
{
    // Get the number of parameters.
    int paramCount = lua_gettop(state);

    // Attempt to match the parameters to a valid binding.
    switch (paramCount)
    {
        case 1:
        {
            if ((lua_type(state, 1) == LUA_TUSERDATA))
            {
                Theme::ThemeImage* instance = getInstance(state);
                void* returnPtr = (void*)&(instance->getRegion());
                if (returnPtr)
                {
                    gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
                    object->instance = returnPtr;
                    object->owns = false;
                    luaL_getmetatable(state, "Rectangle");
                    lua_setmetatable(state, -2);
                }
                else
                {
                    lua_pushnil(state);
                }

                return 1;
            }

            lua_pushstring(state, "lua_ThemeThemeImage_getRegion - Failed to match the given parameters to a valid function signature.");
            lua_error(state);
            break;
        }
        default:
        {
            lua_pushstring(state, "Invalid number of parameters (expected 1).");
            lua_error(state);
            break;
        }
    }
    return 0;
}

static int lua_ThemeThemeImage_getUVs(lua_State* state)
{
    // Get the number of parameters.
    int paramCount = lua_gettop(state);

    // Attempt to match the parameters to a valid binding.
    switch (paramCount)
    {
        case 1:
        {
            if ((lua_type(state, 1) == LUA_TUSERDATA))
            {
                Theme::ThemeImage* instance = getInstance(state);
                void* returnPtr = (void*)&(instance->getUVs());
                if (returnPtr)
                {
                    gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
                    object->instance = returnPtr;
                    object->owns = false;
                    luaL_getmetatable(state, "ThemeUVs");
                    lua_setmetatable(state, -2);
                }
                else
                {
                    lua_pushnil(state);
                }

                return 1;
            }

            lua_pushstring(state, "lua_ThemeThemeImage_getUVs - Failed to match the given parameters to a valid function signature.");
            lua_error(state);
            break;
        }
        default:
        {
            lua_pushstring(state, "Invalid number of parameters (expected 1).");
            lua_error(state);
            break;
        }
    }
    return 0;
}

static int lua_ThemeThemeImage_release(lua_State* state)
{
    // Get the number of parameters.
    int paramCount = lua_gettop(state);

    // Attempt to match the parameters to a valid binding.
    switch (paramCount)
    {
        case 1:
        {
            if ((lua_type(state, 1) == LUA_TUSERDATA))
            {
                Theme::ThemeImage* instance = getInstance(state);
                instance->release();

                return 0;
            }

            lua_pushstring(state, "lua_ThemeThemeImage_release - Failed to match the given parameters to a valid function signature.");
            lua_error(state);
            break;
        }
        default:
        {
            lua_pushstring(state, "Invalid number of parameters (expected 1).");
            lua_error(state);
            break;
        }
    }
    return 0;
}

// Provides support for conversion to all known relative types of Theme::ThemeImage
static void* __convertTo(void* ptr, const char* typeName)
{
    Theme::ThemeImage* ptrObject = reinterpret_cast<Theme::ThemeImage*>(ptr);

    if (strcmp(typeName, "Ref") == 0)
    {
        return reinterpret_cast<void*>(static_cast<Ref*>(ptrObject));
    }

    // No conversion available for 'typeName'
    return NULL;
}

static int lua_ThemeThemeImage_to(lua_State* state)
{
    // There should be only a single parameter (this instance)
    if (lua_gettop(state) != 2 || lua_type(state, 1) != LUA_TUSERDATA || lua_type(state, 2) != LUA_TSTRING)
    {
        lua_pushstring(state, "lua_ThemeThemeImage_to - Invalid number of parameters (expected 2).");
        lua_error(state);
        return 0;
    }

    Theme::ThemeImage* instance = getInstance(state);
    const char* typeName = gameplay::ScriptUtil::getString(2, false);
    void* result = __convertTo((void*)instance, typeName);

    if (result)
    {
        gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
        object->instance = (void*)result;
        object->owns = false;
        luaL_getmetatable(state, typeName);
        lua_setmetatable(state, -2);
    }
    else
    {
        lua_pushnil(state);
    }

    return 1;
}

void luaRegister_ThemeThemeImage()
{
    const luaL_Reg lua_members[] =
    {
        {"addRef", lua_ThemeThemeImage_addRef},
        {"getColor", lua_ThemeThemeImage_getColor},
        {"getId", lua_ThemeThemeImage_getId},
        {"getRefCount", lua_ThemeThemeImage_getRefCount},
        {"getRegion", lua_ThemeThemeImage_getRegion},
        {"getUVs", lua_ThemeThemeImage_getUVs},
        {"release", lua_ThemeThemeImage_release},
        {"to", lua_ThemeThemeImage_to},
        {NULL, NULL}
    };
    const luaL_Reg* lua_statics = NULL;
    std::vector<std::string> scopePath;
    scopePath.push_back("Theme");

    gameplay::ScriptUtil::registerClass("ThemeThemeImage", lua_members, NULL, lua_ThemeThemeImage__gc, lua_statics, scopePath);

    luaGlobal_Register_Conversion_Function("ThemeThemeImage", __convertTo);
}

}


text:
package com.microsoft.azure.management.network.v2018_04_01;

import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * Application Gateway autoscale bounds on number of Application Gateway
 * instance.
 */
public class ApplicationGatewayAutoscaleBounds {
    /**
     * Lower bound on number of Application Gateway instances.
     */
    @JsonProperty(value = "min", required = true)
    private int min;

    /**
     * Upper bound on number of Application Gateway instances.
     */
    @JsonProperty(value = "max", required = true)
    private int max;

    /**
     * Get lower bound on number of Application Gateway instances.
     *
     * @return the min value
     */
    public int min() {
        return this.min;
    }

    /**
     * Set lower bound on number of Application Gateway instances.
     *
     * @param min the min value to set
     * @return the ApplicationGatewayAutoscaleBounds object itself.
     */
    public ApplicationGatewayAutoscaleBounds withMin(int min) {
        this.min = min;
        return this;
    }

    /**
     * Get upper bound on number of Application Gateway instances.
     *
     * @return the max value
     */
    public int max() {
        return this.max;
    }

    /**
     * Set upper bound on number of Application Gateway instances.
     *
     * @param max the max value to set
     * @return the ApplicationGatewayAutoscaleBounds object itself.
     */
    public ApplicationGatewayAutoscaleBounds withMax(int max) {
        this.max = max;
        return this;
    }

}


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

package com.googlecode.bumblebee.dto;

import java.lang.reflect.Method;

/**
 * A ValueDescriptor is used to describe a value of a data object. It contains information
 * about the target property of the data object and the expression used to extract the data from the
 * source object.
 *
 * @author Andreas Nilsson
 */
public interface ValueDescriptor {

    /**
     * Returns the accessor of the value in the data object class.
     *
     * @return The value accessor.
     */
    public Method getAccessor();

    /**
     * Returns the type of the property in the data object interface. This corresponds to the
     * return type of the corresponding accessor.
     *
     * @return The type of the property in the DTO.
     */
    public Class<?> getPropertyType();

    /**
     * Returns the property in the data object that the expression should be mapped to.
     *
     * @return The target property of the data object.
     */
    public String getProperty();

    /**
     * Returns the expression used to dig out the original value from the source object.
     *
     * @return An expression that defines what data should be fetched from the source object.
     */
    public String getExpression();

}


text:
"""
@file
@brief Keeps an encrypted of personal data
"""
import re
import os
import datetime
import zlib
from io import BytesIO as StreamIO
from .files_status import FilesStatus
from ..loghelper.flog import noLOG
from .transfer_api import TransferAPI_FileInfo
from .encryption import encrypt_stream, decrypt_stream

class EncryptedBackupError(Exception):
    """
    raised by @see cl EncryptedBackup
    """
    pass

class EncryptedBackup:

    """
    This class aims at keeping an encrypted and compressed backup of files.
    Every file is compressed and then encrypted before being uploaded to the
    remote location. Its name still contains the container but the
    file name is a hash. A

    .. exref::
        :title: Encrypted and compressed backup

        Here is an example which stores everything on hard drive.
        A second run only modifies files updated between the two processes.
        A modified file does not remove the previous version,
        it creates a new file.
        Example::

            from pyquickhelper.loghelper import fLOG
            from pyquickhelper.filehelper import FileTreeNode, EncryptedBackup
            from pyensae.remote import TransferAPIFile

            key_crypt = "crypt"

            local = os.path.normpath(os.path.join(os.path.dirname(__file__), ".."))
            this = os.path.normpath(os.path.dirname(__file__))
            file_status=os.path.join(this, "backup_status.txt")
            file_map=os.path.join(this, "backup_mapping.txt")

            backup = True
            if backup:
                # code to backup
                root = os.path.normpath(os.path.join(os.path.dirname(__file__)))
                api = TransferAPIFile("f:\\\\mycryptedbackup")
                ft = FileTreeNode(root, repository=True)
                enc = EncryptedBackup(
                    key=key_crypt,
                    file_tree_node=ft,
                    transfer_api=api,
                    root_local=local,
                    file_status=file_status,
                    file_map=file_map,
                    fLOG=print)

                enc.start_transfering()

            restore = not backup
            if restore:
                # code to restore
                root = os.path.normpath(os.path.join(os.path.dirname(__file__)))
                api = TransferAPIFile("f:\\\\mycryptedbackup")
                enc = EncryptedBackup(
                    key=key_crypt,
                    file_tree_node=None,
                    transfer_api=api,
                    root_local=local,
                    file_status=file_status,
                    file_map=file_map,
                    fLOG=print)

                dest=os.path.join(this, "_temp")
                enc.retrieve_all(dest)
    """

    def __init__(self, key, file_tree_node, transfer_api,
                 file_status, file_map, root_local=None,
                 root_remote=None, filter_out=None,
                 threshold_size=2 ** 24, algo="AES",
                 compression="lzma", fLOG=noLOG):
        """
        constructor

        @param      key                 key for encryption
        @param      file_tree_node      @see cl FileTreeNode
        @param      transfer_api        @see cl TransferFTP
        @param      file_status         file keeping the status for each file (date, hash of the content for the last upload)
        @param      file_map            keep track of local filename and remote location
        @param      root_local          local root
        @param      root_remote         remote root
        @param      filter_out          regular expression to exclude some files, it can also be a function.
        @param      threshold_size      above that size, big files are split
        @param      algo                encrypting algorithm
        @param      compression         kind of compression ``'lzma'`` or ``'zip'``
        @param      fLOG                logging function
        """
        self._key = key
        self.fLOG = fLOG
        self._ftn = file_tree_node
        self._api = transfer_api
        self._map = file_map
        self._algo = algo
        self._mapping = None
        self._compress = compression
        self._threshold_size = threshold_size
        self._root_local = root_local if root_local is not None else (
            file_tree_node.root if file_tree_node else None)
        self._root_remote = root_remote if root_remote is not None else ""
        if filter_out is not None and not isinstance(filter_out, str):
            self._filter_out = filter_out
        else:
            self._filter_out_reg = None if filter_out is None else re.compile(
                filter_out)
            self._filter_out = (lambda f: False) if filter_out is None else (
                lambda f: self._filter_out_reg.search(f) is not None)

        self._ft = FilesStatus(file_status) if file_status else None

    def iter_eligible_files(self):
        """
        iterates on eligible file for transfering (if they have been modified)

        @return         iterator on file name
        """
        for f in self._ftn:
            if f.isfile():
                if self._filter_out(f.fullname):
                    continue
                n = self._ft.has_been_modified_and_reason(f.fullname)[0]
                if n:
                    yield f

    def update_status(self, file):
        """
        update the status of a file

        @param      file        filename
        @return                 @see cl FileInfo
        """
        r = self._ft.update_copied_file(file)
        self._ft.save_dates()
        return r

    def update_mapping(self, key, maps):
        """
        update the status of a file

        @param      key         key
        @param      maps        update the mapping
        """
        self.Mapping[key] = maps
        self.transfer_mapping()

    def load_mapping(self):
        """
        retrieves existing mapping

        @return         dictionary
        """
        self._mapping = self._api.retrieve_mapping(lambda data: decrypt_stream(
            self._key, data, chunksize=None, algo=self._algo))
        return self._mapping

    def transfer_mapping(self):
        """
        transfer the mapping
        """
        self._api.transfer_mapping(self.Mapping,
                                   lambda data: encrypt_stream(
                                       self._key, data, chunksize=None, algo=self._algo),
                                   self._map)

    @property
    def Mapping(self):
        """
        returns the mapping
        """
        return self._mapping

    def enumerate_read_encrypt(self, fullname):
        """
        enumerate pieces of files as bytes

        @param      fullname        fullname
        @return                     iterator on chunk of data
        """
        with open(fullname, "rb") as f:
            try:
                data = f.read(self._threshold_size)
                cont = True
            except PermissionError as e:  # pragma: no cover
                yield e
                cont = False
            if cont:
                while data and cont:
                    data = self.compress(data)
                    enc = encrypt_stream(
                        self._key, data, chunksize=None, algo=self._algo)
                    yield enc
                    try:
                        data = f.read(self._threshold_size)
                    except PermissionError as e:  # pragma: no cover
                        yield e
                        cont = False

    def compress(self, data):
        """
        compress data

        @param      data        binary data
        @return                 binary data
        """
        if self._compress == "zip":
            return zlib.compress(data)
        elif self._compress == "lzma":
            # delay import
            try:
                import lzma
            except ImportError:  # pragma: no cover
                import pylzma as lzma
            return lzma.compress(data)
        elif self._compress is None:
            return data
        else:
            raise ValueError(  # pragma: no cover
                f"Unexpected compression algorithm '{self._compress}'.")

    def decompress(self, data):
        """
        decompress data

        @param      data        binary data
        @return                 binary data
        """
        if self._compress == "zip":
            return zlib.decompress(data)
        elif self._compress == "lzma":
            # delay import
            try:
                import lzma
            except ImportError:  # pragma: no cover
                import pylzma as lzma
            return lzma.decompress(data)
        elif self._compress is None:
            return data
        else:
            raise ValueError(  # pragma: no cover
                f"Unexpected compression algorithm '{self._compress}'.")

    def start_transfering(self):
        """
        starts transfering files to the remote website

        :return: list of transferred @see cl FileInfo
        :raises FolderTransferFTPException: The class raises an
            exception (@see cl FolderTransferFTPException)
            if more than 5 issues happened.
        """
        self.load_mapping()

        issues = []
        total = list(self.iter_eligible_files())
        sum_bytes = 0
        done = []
        for i, file in enumerate(total):
            if i % 20 == 0:
                self.fLOG("#### transfering %d/%d (so far %d bytes)" %
                          (i, len(total), sum_bytes))
            relp = os.path.relpath(file.fullname, self._root_local)
            if ".." in relp:
                raise ValueError(  # pragma: no cover
                    "The local root is not accurate:\n{0}\nFILE:\n{1}\nRELPATH:\n{2}".format(
                        self, file.fullname, relp))

            path = self._root_remote + "/" + os.path.split(relp)[0]
            path = path.replace("\\", "/")

            size = os.stat(file.fullname).st_size
            self.fLOG("[upload % 8d bytes name=%s -- fullname=%s -- to=%s]" % (
                size,
                os.path.split(file.fullname)[-1],
                file.fullname,
                path))

            maps = TransferAPI_FileInfo(relp, [], datetime.datetime.now())
            r = True
            for ii, data in enumerate(self.enumerate_read_encrypt(file.fullname)):
                if data is None or isinstance(data, Exception):
                    # it means something went wrong
                    r = False
                    err = data
                    break
                to = self._api.get_remote_path(data, relp, ii)
                to = path + "/" + to
                to = to.lstrip("/")
                r &= self.transfer(to, data)
                maps.add_piece(to)
                sum_bytes += len(data)
                if not r:
                    break

            if r:
                self.update_status(file.fullname)
                self.update_mapping(relp, maps)
                done.append(relp)
            else:
                self.fLOG("   issue", err)
                issues.append((relp, err))

            if len(issues) >= 5:
                raise EncryptedBackupError(  # pragma: no cover
                    "Too many issues:\n{0}".format(
                        "\n".join("{0} -- {1}".format(a, b) for a, b in issues)))

        self.transfer_mapping()
        return done, issues

    def transfer(self, to, data):
        """
        transfer data

        @param      to      remote path
        @param      data    binary data
        @return             boolean
        """
        return self._api.transfer(to, data)

    def retrieve(self, path, filename=None, root=None):
        """
        retrieve a backuped file

        @param      path        path of the file to retrieve
        @param      filename    if not None, store the file into this file
        @param      root        if not None, store the file into root + path
        @return                 filename or data
        """
        if self.Mapping is None:
            raise EncryptedBackupError(  # pragma: no cover
                "Load first the mapping with method load_mapping.")
        if path not in self.Mapping:
            raise EncryptedBackupError(  # pragma: no cover
                f"The mapping is not up to date or file '{path}' cannot be found.")
        info = self.Mapping[path]
        if len(info.pieces) == 0:
            # the file is empty
            if root is not None:
                filename = os.path.join(root, path)
            if filename is not None:
                dirname = os.path.dirname(filename)
                if not os.path.exists(dirname):
                    os.makedirs(dirname)
                with open(filename, "w") as f:
                    pass
            return filename
        else:
            if root is not None:
                filename = os.path.join(root, path)
            if filename is not None:
                dirname = os.path.dirname(filename)
                if not os.path.exists(dirname):
                    os.makedirs(dirname)
                with open(filename, "wb") as f:
                    for p in info.pieces:
                        data = self._api.retrieve(p)
                        data = decrypt_stream(
                            self._key, data, chunksize=None, algo=self._algo)
                        data = self.decompress(data)
                        f.write(data)
                return filename
            else:
                if len(info.pieces) == 1:
                    return self._api.retrieve(info.pieces[0])
                else:
                    byt = StreamIO()
                    for p in info.pieces:
                        data = self._api.retrieve(p)
                        data = decrypt_stream(
                            self._key, data, chunksize=None, algo=self._algo)
                        data = self.decompress(data)
                        byt.write(data)
                    return byt.getvalue()

    def retrieve_all(self, dest, regex=None):
        """
        retrieve all backuped files

        @param      dest        destination
        @param      regex       retrieve a subset matching the regular expression
        @return                 list of restored files
        """
        rema = re.compile(regex) if regex else None

        def match(na):
            "local function"
            if rema:
                return rema.search(na)
            else:
                return True

        self.fLOG("load mapping")
        self.load_mapping()
        self.fLOG("number of files", len(self.Mapping))
        done = []
        for k in sorted(self.Mapping.keys()):
            name = self.retrieve(k, root=dest)
            if match(name):
                size = os.stat(name).st_size
                self.fLOG("[download % 8d bytes name=%s -- fullname=%s -- to=%s]" % (
                    size,
                    os.path.split(name)[-1],
                    dest,
                    os.path.dirname(name)))
                done.append(name)
        return done


text:
"use strict";
/**
 * Directive for site header which contains navigation,
 * project list and filter.
 * @author SOON_
 * @module thisissoon.header.header
 * @class  header
 */
angular.module("thisissoon.header.header", [
    "thisissoon.header.HeaderCtrl"
])

.directive("header",[
    /**
     * @constructor
     */
    function (){
        return {
            restrict: "C",
            scope: {},
            controller: "HeaderCtrl",
            templateUrl: "partials/header.html"
        };
    }
]);


text:
#include "microbe/Neuron.hpp"

namespace microbe {
    void Neuron::setFunction(Function& function)
    {
        this->function = &function;
    }

    Function &Neuron::getFunction(void)
    {
        return *function;
    }

    double Neuron::getOutput(void)
    {
        return output;
    }

    double Neuron::getSum(void)
    {
        return sum;
    }

    std::vector<Connection*> Neuron::getInputConnections(void)
    {
        return inputConnections;
    }

    std::vector<Connection*> Neuron::getOutputConnections(void)
    {
        return outputConnections;
    }

    void Neuron::addInputConnection(Connection& connection)
    {
        inputConnections.push_back(&connection);
    }

    void Neuron::addOutputConnection(Connection& connection)
    {
        outputConnections.push_back(&connection);
    }

    void Neuron::setLearningData(LearningData& data)
    {
        learningData = &data;
    }

    LearningData &Neuron::getLearningData(void)
    {
        return *learningData;
    }

    double Neuron::activate()
    {
        sum = 0;

        std::vector<Connection*>::iterator it;
        for (it = inputConnections.begin(); it != inputConnections.end(); ++it) {
            Connection &conn = **it;
            sum += conn.getWeightedInput();
        }

        output = function->function(sum);

        return output;
    }

    Neuron::NeuronType Neuron::getType(void)
    {
        return NeuronType::Plain;
    }
}


text: """Advanced operations examples."""


text:
/**
 Problem 4. Has property

 Write a function that checks if a given object contains a given property.

 var obj  = …;
 var hasProp = hasProperty(obj, 'length');
 */
function hasProperty(obj,property)
{
    for(var key in obj)
    {
     if(key===property)
     {
         return true;
     }

    }
    return false;
}
var objTrue={count:3, length:50};
var length="length";
console.log("The objTrue has lenght-->"+hasProperty(objTrue,length));
var objFalse={count:2, len:3};
console.log("The objFalse has lenght-->"+hasProperty(objFalse,length));


text:
fprintf('\n');
disp('Figure 6.10')
disp('This edge detection figure can be reproduced')
disp('with the LastWave software, which is available on the Internet at')
disp('http://www.cmap.polytechnique.fr/users/www.bacry')

%
%  Part of Wavelab Version 850
%  Built Tue Jan  3 13:20:39 EST 2006
%  This is Copyrighted Material
%  For Copying permissions see COPYING.m
%  Comments? e-mail wavelab@stat.stanford.edu


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>io.ifar.skid-road</groupId>
        <artifactId>skid-road-parent</artifactId>
        <version>10-SNAPSHOT</version>
    </parent>

    <artifactId>skid-road</artifactId>

    <name>Skid Road Core</name>
    <description>Multi-host encrypted log rolling.</description>

    <dependencies>
        <dependency>
            <groupId>org.jdbi</groupId>
            <artifactId>jdbi</artifactId>
        </dependency>
        <dependency>
            <groupId>io.ifar.dw-goodies</groupId>
            <artifactId>dw-goodies</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
        </dependency>
        <dependency>
            <groupId>org.joda</groupId>
            <artifactId>joda-convert</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jul-to-slf4j</artifactId>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-core</artifactId>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>log4j-over-slf4j</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-java-sdk</artifactId>
        </dependency>
        <dependency>
            <groupId>org.bouncycastle</groupId>
            <artifactId>bcprov-jdk15on</artifactId>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
        </dependency>
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
        </dependency>
        <dependency>
            <groupId>io.dropwizard.metrics</groupId>
            <artifactId>metrics-core</artifactId>
        </dependency>
        <dependency>
            <groupId>io.dropwizard.metrics</groupId>
            <artifactId>metrics-healthchecks</artifactId>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-csv</artifactId>
        </dependency>

        <dependency>
            <groupId>com.google.code.findbugs</groupId>
            <artifactId>jsr305</artifactId>
        </dependency>

        <dependency>
            <groupId>org.hsqldb</groupId>
            <artifactId>hsqldb</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-all</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

</project>


text:
package com.alachisoft.tayzgrid.common.util;

import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReaderWriterLock
{
    //setting ReentrantReadWRiteLock to fair usage(true) so it may behave like .NET ReaderWriterLock
    //This will allow to operate the locks in the followin manner
    //A thread that tries to acquire a fair read lock (non-reentrantly) will block if either the write lock is held, or there is a waiting writer
    //thread. The thread will not acquire the read lock until after the oldest currently waiting writer thread has acquired and released the write lock. Of course, if a waiting writer abandons its wait, leaving one or more reader threads as the longest waiters in the queue with the write lock free, then those readers will be assigned the read lock.
    //A thread that tries to acquire a fair write lock (non-reentrantly) will block unless both the read lock and write lock are free
    //Internally it initiates a ReadLock and WriteLock

    ReentrantReadWriteLock _syncObj = new ReentrantReadWriteLock(true);

    /**
     * If the current thread holds the writer lock
     * @return true if the current thread holds the writer lock; otherwise, false.
     */
    public boolean IsWriterLockHeld()
    {
        return _syncObj.isWriteLockedByCurrentThread();
    }

    /**
     * AcquireReaderLock supports recursive reader-lock requests. That is, a thread can call AcquireReaderLock multiple times, which increments the lock count each time.
     * You must call ReleaseReaderLock once for each time you call AcquireReaderLock. Alternatively, you can call ReleaseLock to reduce the lock count to zero immediately.
     * Recursive lock requests are always granted immediately, without placing the requesting thread in the reader queue. Use recursive locks with caution, to avoid blocking
     * writer-lock requests for long periods.
     *
     * Takes non-interruptible Lock
     *
     * @param timeOut timeOut to acquiring lock
     */
    public void AcquireReaderLock()
    {
        _syncObj.readLock().lock();
    }

    /**
     * Decrements the lock count.
     */
    public void ReleaseReaderLock()
    {
        _syncObj.readLock().unlock();
    }

    /**
     *  AcquireWriterLock supports recursive writer-lock requests. That is, a thread can call AcquireWriterLock multiple times, which increments the lock count each time.
     * You must call ReleaseWriterLock once for each time you call AcquireWriterLock. Alternatively, you can call ReleaseLock to reduce the lock count to zero immediately.
     */
    public void AcquireWriterLock()
    {
        _syncObj.writeLock().lock();
    }

    /**
     * Decrements the lock count.
     */
    public void ReleaseWriterLock()
    {
        _syncObj.writeLock().unlock();
    }

}