text:
"""
Hooks for Cloud Memorystore service
"""
from typing import Dict, Optional, Sequence, Tuple, Union

from google.api_core.exceptions import NotFound
from google.api_core.retry import Retry
from google.cloud.redis_v1 import CloudRedisClient
from google.cloud.redis_v1.gapic.enums import FailoverInstanceRequest
from google.cloud.redis_v1.types import FieldMask, InputConfig, Instance, OutputConfig
from google.protobuf.json_format import ParseDict

from airflow import AirflowException, version
from airflow.gcp.hooks.base import CloudBaseHook

class CloudMemorystoreHook(CloudBaseHook):
    """
    Hook for Google Cloud Memorystore APIs.

    All the methods in the hook where project_id is used must be called with
    keyword arguments rather than positional.

    :param gcp_conn_id: The connection ID to use when fetching connection info.
    :type gcp_conn_id: str
    :param delegate_to: The account to impersonate, if any.
        For this to work, the service account making the request must have
        domain-wide delegation enabled.
    :type delegate_to: str
    """

    def __init__(self, gcp_conn_id: str = "google_cloud_default", delegate_to: Optional[str] = None):
        super().__init__(gcp_conn_id, delegate_to)
        self._client = None  # type: Optional[CloudRedisClient]

    def get_conn(self,):
        """
        Retrieves client library object that allow access to Cloud Memorystore service.

        """
        if not self._client:
            self._client = CloudRedisClient(credentials=self._get_credentials())
        return self._client

    @staticmethod
    def _append_label(instance: Instance, key: str, val: str) -> Instance:
        """
        Append labels to provided Instance type

        Labels must fit the regex ``[a-z]([-a-z0-9]*[a-z0-9])?`` (current
         airflow version string follows semantic versioning spec: x.y.z).

        :param instance: The proto to append resource_label airflow
            version to
        :type instance: google.cloud.container_v1.types.Cluster
        :param key: The key label
        :type key: str
        :param val:
        :type val: str
        :return: The cluster proto updated with new label
        """
        val = val.replace(".", "-").replace("+", "-")
        instance.labels.update({key: val})
        return instance

    @CloudBaseHook.fallback_to_default_project_id
    def create_instance(
        self,
        location: str,
        instance_id: str,
        instance: Union[Dict, Instance],
        project_id: Optional[str] = None,
        retry: Optional[Retry] = None,
        timeout: Optional[float] = None,
        metadata: Optional[Sequence[Tuple[str, str]]] = None,
    ):
        """
        Creates a Redis instance based on the specified tier and memory size.

        By default, the instance is accessible from the project's `default network
        <https://cloud.google.com/compute/docs/networks-and-firewalls#networks>`__.

        :param location: The location of the Cloud Memorystore instance (for example europe-west1)
        :type location: str
        :param instance_id: Required. The logical name of the Redis instance in the customer project with the
            following restrictions:

            -  Must contain only lowercase letters, numbers, and hyphens.
            -  Must start with a letter.
            -  Must be between 1-40 characters.
            -  Must end with a number or a letter.
            -  Must be unique within the customer project / location
        :type instance_id: str
        :param instance: Required. A Redis [Instance] resource

            If a dict is provided, it must be of the same form as the protobuf message
            :class:`~google.cloud.redis_v1.types.Instance`
        :type instance: Union[Dict, google.cloud.redis_v1.types.Instance]
        :param project_id: Project ID of the project that contains the instance. If set
            to None or missing, the default project_id from the GCP connection is used.
        :type project_id: str
        :param retry: A retry object used to retry requests. If ``None`` is specified, requests will not be
            retried.
        :type retry: google.api_core.retry.Retry
        :param timeout: The amount of time, in seconds, to wait for the request to complete. Note that if
            ``retry`` is specified, the timeout applies to each individual attempt.
        :type timeout: float
        :param metadata: Additional metadata that is provided to the method.
        :type metadata: Sequence[Tuple[str, str]]
        """
        client = self.get_conn()
        parent = CloudRedisClient.location_path(project_id, location)
        instance_name = CloudRedisClient.instance_path(project_id, location, instance_id)
        try:
            instance = client.get_instance(
                name=instance_name, retry=retry, timeout=timeout, metadata=metadata
            )
            self.log.info("Instance exists. Skipping creation.")
            return instance
        except NotFound:
            self.log.info("Instance not exists.")

        if isinstance(instance, dict):
            instance = ParseDict(instance, Instance())
        elif not isinstance(instance, Instance):
            raise AirflowException("instance is not instance of Instance type or python dict")

        self._append_label(instance, "airflow-version", "v" + version.version)

        result = client.create_instance(
            parent=parent,
            instance_id=instance_id,
            instance=instance,
            retry=retry,
            timeout=timeout,
            metadata=metadata,
        )
        result.result()
        self.log.info("Instance created.")
        return client.get_instance(name=instance_name, retry=retry, timeout=timeout, metadata=metadata)

    @CloudBaseHook.fallback_to_default_project_id
    def delete_instance(
        self,
        location: str,
        instance: str,
        project_id: Optional[str] = None,
        retry: Optional[Retry] = None,
        timeout: Optional[float] = None,
        metadata: Optional[Sequence[Tuple[str, str]]] = None,
    ):
        """
        Deletes a specific Redis instance.  Instance stops serving and data is deleted.

        :param location: The location of the Cloud Memorystore instance (for example europe-west1)
        :type location: str
        :param instance: The logical name of the Redis instance in the customer project.
        :type instance: str
        :param project_id:  Project ID of the project that contains the instance. If set
            to None or missing, the default project_id from the GCP connection is used.
        :type project_id: str
        :param retry: A retry object used to retry requests. If ``None`` is specified, requests will not be
            retried.
        :type retry: google.api_core.retry.Retry
        :param timeout: The amount of time, in seconds, to wait for the request to complete. Note that if
            ``retry`` is specified, the timeout applies to each individual attempt.
        :type timeout: float
        :param metadata: Additional metadata that is provided to the method.
        :type metadata: Sequence[Tuple[str, str]]
        """
        client = self.get_conn()
        name = CloudRedisClient.instance_path(project_id, location, instance)
        self.log.info("Fetching Instance: %s", name)
        instance = client.get_instance(name=name, retry=retry, timeout=timeout, metadata=metadata)

        if not instance:
            return

        self.log.info("Deleting Instance: %s", name)
        result = client.delete_instance(name=name, retry=retry, timeout=timeout, metadata=metadata)
        result.result()
        self.log.info("Instance deleted: %s", name)

    @CloudBaseHook.fallback_to_default_project_id
    def export_instance(
        self,
        location: str,
        instance: str,
        output_config: Union[Dict, OutputConfig],
        project_id: Optional[str] = None,
        retry: Optional[Retry] = None,
        timeout: Optional[float] = None,
        metadata: Optional[Sequence[Tuple[str, str]]] = None,
    ):
        """
        Export Redis instance data into a Redis RDB format file in Cloud Storage.

        Redis will continue serving during this operation.

        :param location: The location of the Cloud Memorystore instance (for example europe-west1)
        :type location: str
        :param instance: The logical name of the Redis instance in the customer project.
        :type instance: str
        :param output_config: Required. Specify data to be exported.

            If a dict is provided, it must be of the same form as the protobuf message
            :class:`~google.cloud.redis_v1.types.OutputConfig`
        :type output_config: Union[Dict, google.cloud.redis_v1.types.OutputConfig]
        :param project_id: Project ID of the project that contains the instance. If set
            to None or missing, the default project_id from the GCP connection is used.
        :type project_id: str
        :param retry: A retry object used to retry requests. If ``None`` is specified, requests will not be
            retried.
        :type retry: google.api_core.retry.Retry
        :param timeout: The amount of time, in seconds, to wait for the request to complete. Note that if
            ``retry`` is specified, the timeout applies to each individual attempt.
        :type timeout: float
        :param metadata: Additional metadata that is provided to the method.
        :type metadata: Sequence[Tuple[str, str]]
        """
        client = self.get_conn()
        name = CloudRedisClient.instance_path(project_id, location, instance)
        self.log.info("Exporting Instance: %s", name)
        result = client.export_instance(
            name=name, output_config=output_config, retry=retry, timeout=timeout, metadata=metadata
        )
        result.result()
        self.log.info("Instance exported: %s", name)

    @CloudBaseHook.fallback_to_default_project_id
    def failover_instance(
        self,
        location: str,
        instance: str,
        data_protection_mode: FailoverInstanceRequest.DataProtectionMode,
        project_id: Optional[str] = None,
        retry: Optional[Retry] = None,
        timeout: Optional[float] = None,
        metadata: Optional[Sequence[Tuple[str, str]]] = None,
    ):
        """
        Initiates a failover of the master node to current replica node for a specific STANDARD tier Cloud
        Memorystore for Redis instance.

        :param location: The location of the Cloud Memorystore instance (for example europe-west1)
        :type location: str
        :param instance: The logical name of the Redis instance in the customer project.
        :type instance: str
        :param data_protection_mode: Optional. Available data protection modes that the user can choose. If
            it's unspecified, data protection mode will be LIMITED_DATA_LOSS by default.
        :type data_protection_mode: google.cloud.redis_v1.gapic.enums.FailoverInstanceRequest
            .DataProtectionMode
        :param project_id: Project ID of the project that contains the instance. If set
            to None or missing, the default project_id from the GCP connection is used.
        :type project_id: str
        :param retry: A retry object used to retry requests. If ``None`` is specified, requests will not be
            retried.
        :type retry: google.api_core.retry.Retry
        :param timeout: The amount of time, in seconds, to wait for the request to complete. Note that if
            ``retry`` is specified, the timeout applies to each individual attempt.
        :type timeout: float
        :param metadata: Additional metadata that is provided to the method.
        :type metadata: Sequence[Tuple[str, str]]
        """
        client = self.get_conn()
        name = CloudRedisClient.instance_path(project_id, location, instance)
        self.log.info("Failovering Instance: %s", name)

        result = client.failover_instance(
            name=name,
            data_protection_mode=data_protection_mode,
            retry=retry,
            timeout=timeout,
            metadata=metadata,
        )
        result.result()
        self.log.info("Instance failovered: %s", name)

    @CloudBaseHook.fallback_to_default_project_id
    def get_instance(
        self,
        location: str,
        instance: str,
        project_id: Optional[str] = None,
        retry: Optional[Retry] = None,
        timeout: Optional[float] = None,
        metadata: Optional[Sequence[Tuple[str, str]]] = None,
    ):
        """
        Gets the details of a specific Redis instance.

        :param location: The location of the Cloud Memorystore instance (for example europe-west1)
        :type location: str
        :param instance: The logical name of the Redis instance in the customer project.
        :type instance: str
        :param project_id:  Project ID of the project that contains the instance. If set
            to None or missing, the default project_id from the GCP connection is used.
        :type project_id: str
        :param retry: A retry object used to retry requests. If ``None`` is specified, requests will not be
            retried.
        :type retry: google.api_core.retry.Retry
        :param timeout: The amount of time, in seconds, to wait for the request to complete. Note that if
            ``retry`` is specified, the timeout applies to each individual attempt.
        :type timeout: float
        :param metadata: Additional metadata that is provided to the method.
        :type metadata: Sequence[Tuple[str, str]]
        """
        client = self.get_conn()
        name = CloudRedisClient.instance_path(project_id, location, instance)
        result = client.get_instance(name=name, retry=retry, timeout=timeout, metadata=metadata)
        self.log.info("Fetched Instance: %s", name)
        return result

    @CloudBaseHook.fallback_to_default_project_id
    def import_instance(
        self,
        location: str,
        instance: str,
        input_config: Union[Dict, InputConfig],
        project_id: Optional[str] = None,
        retry: Optional[Retry] = None,
        timeout: Optional[float] = None,
        metadata: Optional[Sequence[Tuple[str, str]]] = None,
    ):
        """
        Import a Redis RDB snapshot file from Cloud Storage into a Redis instance.

        Redis may stop serving during this operation. Instance state will be IMPORTING for entire operation.
        When complete, the instance will contain only data from the imported file.

        :param location: The location of the Cloud Memorystore instance (for example europe-west1)
        :type location: str
        :param instance: The logical name of the Redis instance in the customer project.
        :type instance: str
        :param input_config: Required. Specify data to be imported.

            If a dict is provided, it must be of the same form as the protobuf message
            :class:`~google.cloud.redis_v1.types.InputConfig`
        :type input_config: Union[Dict, google.cloud.redis_v1.types.InputConfig]
        :param project_id: Project ID of the project that contains the instance. If set
            to None or missing, the default project_id from the GCP connection is used.
        :type project_id: str
        :param retry: A retry object used to retry requests. If ``None`` is specified, requests will not be
            retried.
        :type retry: google.api_core.retry.Retry
        :param timeout: The amount of time, in seconds, to wait for the request to complete. Note that if
            ``retry`` is specified, the timeout applies to each individual attempt.
        :type timeout: float
        :param metadata: Additional metadata that is provided to the method.
        :type metadata: Sequence[Tuple[str, str]]
        """
        client = self.get_conn()
        name = CloudRedisClient.instance_path(project_id, location, instance)
        self.log.info("Importing Instance: %s", name)
        result = client.import_instance(
            name=name, input_config=input_config, retry=retry, timeout=timeout, metadata=metadata
        )
        result.result()
        self.log.info("Instance imported: %s", name)

    @CloudBaseHook.fallback_to_default_project_id
    def list_instances(
        self,
        location: str,
        page_size: int,
        project_id: Optional[str] = None,
        retry: Optional[Retry] = None,
        timeout: Optional[float] = None,
        metadata: Optional[Sequence[Tuple[str, str]]] = None,
    ):
        """
        Lists all Redis instances owned by a project in either the specified location (region) or all
        locations.

        :param location: The location of the Cloud Memorystore instance (for example europe-west1)

                If it is specified as ``-`` (wildcard), then all regions available to the project are
                queried, and the results are aggregated.
        :type location: str
        :param page_size: The maximum number of resources contained in the underlying API response. If page
            streaming is performed per- resource, this parameter does not affect the return value. If page
            streaming is performed per-page, this determines the maximum number of resources in a page.
        :type page_size: int
        :param project_id: Project ID of the project that contains the instance. If set
            to None or missing, the default project_id from the GCP connection is used.
        :type project_id: str
        :param retry: A retry object used to retry requests. If ``None`` is specified, requests will not be
            retried.
        :type retry: google.api_core.retry.Retry
        :param timeout: The amount of time, in seconds, to wait for the request to complete. Note that if
            ``retry`` is specified, the timeout applies to each individual attempt.
        :type timeout: float
        :param metadata: Additional metadata that is provided to the method.
        :type metadata: Sequence[Tuple[str, str]]
        """
        client = self.get_conn()
        parent = CloudRedisClient.location_path(project_id, location)
        result = client.list_instances(
            parent=parent, page_size=page_size, retry=retry, timeout=timeout, metadata=metadata
        )
        self.log.info("Fetched instances")
        return result

    @CloudBaseHook.fallback_to_default_project_id
    def update_instance(
        self,
        update_mask: Union[Dict, FieldMask],
        instance: Union[Dict, Instance],
        location: Optional[str] = None,
        instance_id: Optional[str] = None,
        project_id: Optional[str] = None,
        retry: Optional[Retry] = None,
        timeout: Optional[float] = None,
        metadata: Optional[Sequence[Tuple[str, str]]] = None,
    ):
        """
        Updates the metadata and configuration of a specific Redis instance.

        :param update_mask: Required. Mask of fields to update. At least one path must be supplied in this
            field. The elements of the repeated paths field may only include these fields from ``Instance``:

            -  ``displayName``
            -  ``labels``
            -  ``memorySizeGb``
            -  ``redisConfig``

            If a dict is provided, it must be of the same form as the protobuf message
            :class:`~google.cloud.redis_v1.types.FieldMask`
        :type update_mask: Union[Dict, google.cloud.redis_v1.types.FieldMask]
        :param instance: Required. Update description. Only fields specified in ``update_mask`` are updated.

            If a dict is provided, it must be of the same form as the protobuf message
            :class:`~google.cloud.redis_v1.types.Instance`
        :type instance: Union[Dict, google.cloud.redis_v1.types.Instance]
        :param location: The location of the Cloud Memorystore instance (for example europe-west1)
        :type location: str
        :param instance_id: The logical name of the Redis instance in the customer project.
        :type instance_id: str
        :param project_id:  Project ID of the project that contains the instance. If set
            to None or missing, the default project_id from the GCP connection is used.
        :type project_id: str
        :param retry: A retry object used to retry requests. If ``None`` is specified, requests will not be
            retried.
        :type retry: google.api_core.retry.Retry
        :param timeout: The amount of time, in seconds, to wait for the request to complete. Note that if
            ``retry`` is specified, the timeout applies to each individual attempt.
        :type timeout: float
        :param metadata: Additional metadata that is provided to the method.
        :type metadata: Sequence[Tuple[str, str]]
        """
        client = self.get_conn()

        if isinstance(instance, dict):
            instance = ParseDict(instance, Instance())
        elif not isinstance(instance, Instance):
            raise AirflowException("instance is not instance of Instance type or python dict")

        if location and instance_id:
            name = CloudRedisClient.instance_path(project_id, location, instance_id)
            instance.name = name

        self.log.info("Updating instances: %s", instance.name)
        result = client.update_instance(
            update_mask=update_mask, instance=instance, retry=retry, timeout=timeout, metadata=metadata
        )
        result.result()
        self.log.info("Instance updated: %s", instance.name)


text:
// This file is automatically generated.

package adila.db;

/*
 * Multilaser M7s Dual Core
 *
 * DEVICE: NB116_NB117_NB118
 * MODEL: M7s Dual ML03
 */
final class nb1165fnb1175fnb118_m7s20dual20ml03 {
    public static final String DATA = "Multilaser|M7s Dual Core|";
}

redpajama_set_name: RedPajamaGithub


text:
layout: event
sidebar: event
title: "Activism Then: Recognition"
starts_at: "2017-09-30T14:00"
ends_at: "2017-09-30T15:30"
location: "2155 N Prospect Ave"
organization: "Milwaukee Film Festival"
external_link: "https://www.facebook.com/events/269430780220435/"
---

Join this conversation about the impact of community organizing during and after Milwaukee's 1967 fair housing marches and the 1971 migrant workers' march from Milwaukee to Madison, as well as the role organizers played in reaching Wisconsin's most underrepresented citizens.

[RSVP for this event on Facebook here.](https://www.facebook.com/events/269430780220435/)

This event is FREE & open to the public and is part of the 2017 [Milwaukee Film Festival](http://www.mkefilm.org/), taking place from Sept. 28 - Oct. 12.


text:
layout: post
title: J'en ai rêvé, Github pages l'a fait
subtitle: Ou comment mettre sur pied un site statique en trois clics
category: lesmainsdanslecambouis
tags: github blog
feature-image: 2015-04-22-Github_feature.jpeg
---

Ca me trottait dans la tête depuis quelques mois. Après avoir passé près de cinq ans la tête sous un monticule de bytecode depuis mon diplôme, l'idée a fini par germer jusqu'à atteindre le bon dosage d'engrais. Une bonne pelletée de **Devoxx**, parsemée d'une poignée de **Github pages**. Et paf, ça fait des chocapic un blog perso !

> Au fait, c'est quoi **Github pages** ?

Le meilleur moyen de raconter votre vie. Ou autre chose, d'ailleurs. Peu importe.
[**Github pages**](https://pages.github.com/) est un service proposé par [**Github**](https://github.com/). Installez git sur votre machine, créez un dépôt, et poussez-y un fichier **index.html**. Et le tour est joué, vous avez un site  perso.

> Je peux aussi le faire chez **Heroku** ou **Free**, c'est pas nouveau ton truc.

Certes, l'idée n'est pas forcément révolutionnaire. Sauf si on ajoute la fonctionnalité qui peut faire pencher la balance. Comme je l'ai expliqué, **Github pages** vous propose de monter votre propre site relié à votre compte **Github** en quelques minutes. Vous avez gratuitement le nom de domaine, l'hébergement et toutes les fonctionnalités de **Git** directement intégré à votre projet. Elle est pas belle, la vie ?

> C'est pas mal, en effet. Tu peux nous en dire plus ?

Œuf corse. **Github pages** vous propose donc un site très rapidement opérationnel. Et si vous aimez ça, chacun de vos projets hébergés sur **Github** peut bénéficier de son propre site également.
Certes, vous ne pouvez héberger que des sites statiques. Néanmoins, **Github pages** supporte nativement [**Jekyll**](http://jekyllrb.com/), un outil de génération de site statique. En quelques mots, **Jekyll** permet de gérer de la pagination automatique (pratique pour un blog), ou encore l'utilisation d'outils de markdown, comme par exemple [**Kramdown**](http://kramdown.gettalong.org/) qui vous permet de vous abstraire du code **HTML** pour vous focaliser sur une syntaxe simplifiée comme dans un wiki pour la rédaction de vos billets. **Githug pages** est capable de parser des billets de blog ainsi construits et poussés directement dans votre dépôt **Github** sans que vous ayez besoin de générer vous-même le site en exécutant **Jekyll** sur votre machine. Néanmoins, il est toujours possible de l'installer en local dans l'optique de vérifier votre travail avant de pousser sur votre dépôt à l'aide d'outils bien pratiques sur lesquels je ne vais pas m'étendre.

> Au final, tu peux te construire un blog statique en une heure ?

Exactement. Et en bonus, je peux citer deux fonctionnalités très appréciables. En premier lieu, il existe nombre de thèmes tout prêts à l'emploi, disponibles gratuitement, afin que vous n'ayez pas à personnaliser de A à Z l'ensemble de votre site. Une bonne base pour commencer vos recherches peut être [**Jekyll Themes**](http://jekyllthemes.org/). Faites un fork sur le dépôt d'un de ces thèmes, et il ne vous reste plus qu'à remplacer l'ensemble des placeholders par vos données persos. Et vous voilà avec un blog utilisable immédiatement.
L'autre fonctionnalité, vous pourrez l'expérimenter à la fin de ce billet. Il s'agit d'une intégration avec [**Disqus**](https://disqus.com/). En quelques lignes HTML, vous pouvez intégrer un système de commentaires à l'ensemble de vos billets, avec les outils d'administration qui vont bien, proposés sur le site de **Disqus**. Rien à coder, juste à apprécier.

Merci **Github pages** !

***Bibliographie*** :

[Github](https://github.com)

[Github pages](https://pages.github.com)

[Jekyll](http://jekyllrb.com)

[Jekyll Themes](http://jekyllthemes.org)

[Kramdown](http://kramdown.gettalong.org/)

[Disqus](https://disqus.com)


text:
title: Scala 2.10
link: https://www.javadoc.io/doc/org.scala-debugger/scala-debugger-tool_2.10/
render: false
weight: 0
---


text:
sap.ui.define([
	"sap/ui/core/mvc/Controller",
	"sap/ui/integration/util/ManifestResolver",
	"sap/m/MessageToast"
], function (Controller, ManifestResolver, MessageToast) {
	"use strict";

	return Controller.extend("sap.f.cardsdemo.controller.StateChangedEvent", {

		onInit: function () {
		},

		onStateChanged: function () {
			MessageToast.show("State changed", {
				at: "center center",
				duration: 1000
			});

			this.resolveManifest();
		},

		onRefresh: function () {
			this.byId("card1").refresh();
		},

		onRefreshData: function () {
			this.byId("card1").refreshData();
		},

		onPreviousPage: function () {
			var oCard = this.byId("card1");
			oCard.getCardFooter().getPaginator().previous();
		},

		onNextPage: function () {
			var oCard = this.byId("card1");
			oCard.getCardFooter().getPaginator().next();
		},

		onChangeSelectFilter: function () {
			var oCard = this.byId("card1");
			oCard.setFilterValue("shipper", "2");
		},

		onInitialSelectFilter: function () {
			var oCard = this.byId("card1");
			oCard.setFilterValue("shipper", "3");
		},

		resolveManifest: function () {
			var oCard = this.byId("card1"),
				oCodeEditor = this.byId("output");

			ManifestResolver.resolveCard(oCard).then(function (oRes) {
				oCodeEditor.setValue(JSON.stringify(oRes, null, "\t"));
			});
		}
	});
});


text:
'use strict';
import template from 'app/main/template.html!text';
import Controller from 'app/main/controller';

/**
 * Component-like directive to bootstrap the application.
 * @returns {object}
 */
function mainDirective() {
  return {
    template: template,
    controller: Controller,
    controllerAs: 'mainCtrl'
  };
}

export default mainDirective;


text:
package edu.isi.karma.cleaning.features;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;

import libsvm.svm;
import libsvm.svm_model;
import libsvm.svm_node;
import libsvm.svm_parameter;
import libsvm.svm_print_interface;
import libsvm.svm_problem;

import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import au.com.bytecode.opencsv.CSVWriter;
/*import de.bwaldvogel.liblinear.Feature;
 import de.bwaldvogel.liblinear.FeatureNode;
 import de.bwaldvogel.liblinear.Linear;
 import de.bwaldvogel.liblinear.Model;
 import de.bwaldvogel.liblinear.parameterseter;
 import de.bwaldvogel.liblinear.Problem;
 import de.bwaldvogel.liblinear.SolverType;*/
import edu.isi.karma.cleaning.PartitionClassifierType;
import edu.isi.karma.cleaning.UtilTools;

public class RecordClassifier implements PartitionClassifierType {
	Logger ulogger = LoggerFactory.getLogger(RecordClassifier.class);
	RecordFeatureSet rf;
	svm_model model;
	ArrayList<svm_node[]> trainData = new ArrayList<svm_node[]>();
	ArrayList<String> rawData = new ArrayList<String>();
	ArrayList<Double> targets = new ArrayList<Double>();
	int exampleCnt = 0;
	HashMap<String, Double> labelMapping = new HashMap<String, Double>();
	public double[] maxValues;
	public double[] minValues;

	public RecordClassifier() {
		this.rf = new RecordFeatureSet();
	}

	public RecordClassifier(RecordFeatureSet rf) {
		this.rf = rf;
	}

	public void init() {
		this.trainData = new ArrayList<svm_node[]>();
		this.targets = new ArrayList<Double>();
		labelMapping = new HashMap<String, Double>();
		exampleCnt = 0;
		model = null;
		this.minValues = null;
		this.maxValues = null;
		this.rf.init();
	}

	public void addTrainingData(String v, double[] value, String label) {
		// convert value to feature vector
		rawData.add(v);
		svm_node[] testNodes = new svm_node[value.length];
		for (int k = 0; k < testNodes.length; k++) {
			svm_node node = new svm_node();
			node.index = k;
			node.value = value[k];
			testNodes[k] = node;
		}
		this.trainData.add(testNodes);
		// convert label to a double class label
		if (labelMapping.containsKey(label)) {
			this.targets.add(labelMapping.get(label));
		} else {
			double lb = 0;
			if (!this.labelMapping.isEmpty()) {
				lb = Collections.max(labelMapping.values()) + 1;
			}
			this.labelMapping.put(label, lb);
			this.targets.add(lb);
		}
	}

	public void addTrainingData(String value, String label) {
		// convert value to feature vector
		rawData.add(value);
		Collection<Feature> cfeat = rf.computeFeatures(value, "");
		Feature[] x = cfeat.toArray(new Feature[cfeat.size()]);
		// row.add(f.getName());
		svm_node[] testNodes = new svm_node[cfeat.size()];
		for (int k = 0; k < cfeat.size(); k++) {
			svm_node node = new svm_node();
			node.index = k;
			node.value = x[k].getScore();
			testNodes[k] = node;
		}
		this.trainData.add(testNodes);
		// convert label to a double class label
		if (labelMapping.containsKey(label)) {
			this.targets.add(labelMapping.get(label));
		} else {
			double lb = 0;
			if (!this.labelMapping.isEmpty()) {
				lb = Collections.max(labelMapping.values()) + 1;
			}
			this.labelMapping.put(label, lb);
			this.targets.add(lb);
		}
	}

	public void printTraindata(svm_node[][] data) {
		String res = "";
		String line = Arrays.toString(this.rf.getFeatureNames().toArray(
				new String[this.rf.getFeatureNames().size()]));
		res += line + "\n";
		for (svm_node[] l : data) {
			String tmp = "";
			for (svm_node n : l) {
				tmp += n.index + ":" + n.value + " ";
			}
			tmp = tmp.substring(0, tmp.length() - 1);
			res += tmp + "\n";
		}
	}

	// duplicate data to avoid the situation that one instance per class (svm
	// doesn't support prob estimation for this case)
	public void duplicateData() {
		int size = trainData.size();
		for (int i = 0; i < size; i++) {
			// insert row into traindata
			svm_node[] row = trainData.get(i);
			trainData.add(row);
			// insert target into the target values
			Double val = targets.get(i);
			targets.add(val);
		}
	}

	// used to balance unbalanced data.
	public HashMap<Double, Double> adjustunbalancedData() {
		HashMap<Double, Double> class2weight = new HashMap<Double, Double>();
		for (Double b : targets) {
			if (class2weight.containsKey(b)) {
				class2weight.put(b, class2weight.get(b) + 1);
			} else {
				class2weight.put(b, 1.0);
			}
		}
		Double maxNumber = Collections.max(class2weight.values());
		for (Double key : class2weight.keySet()) {
			class2weight.put(key, maxNumber / class2weight.get(key) * 1.0);
		}
		return class2weight;
	}

	public void dignose() {
		String s = Arrays.toString(this.rf.vocabs);
		ulogger.info("Diagnose info....Vocbulary learned: " + s);
	}

	public void rescale(svm_node[] tmp) {
		double[] maxvals = this.maxValues;
		double[] minvals = this.minValues;
		for (int i = 0; i < tmp.length; i++) {
			if (maxvals[i] > minvals[i]) {
				tmp[i].value = (tmp[i].value - minvals[i]) * 1.0
						/ (maxvals[i] - minvals[i]);
			} else {
				tmp[i].value = 0;
			}
		}
	}

	public void convertToCSVfile() {
		ArrayList<String[]> xArrayList = new ArrayList<String[]>();
		String[] attrname = new String[rf.getFeatureNames().size() + 1];
		String[] names = rf.getFeatureNames().toArray(
				new String[attrname.length - 1]);
		// add attribute names
		System.arraycopy(names, 0, attrname, 0, names.length);
		attrname[attrname.length - 1] = "label";
		xArrayList.add(attrname);
		for (svm_node[] tmp : trainData) {
			String[] row = new String[tmp.length + 1];
			for (int i = 0; i < tmp.length; i++) {
				row[i] = tmp[i].value + "";
			}
			row[row.length - 1] = "c" + targets.get(trainData.indexOf(tmp));
			xArrayList.add(row);
		}
		try {
			CSVWriter cr = new CSVWriter(new FileWriter(
					"/Users/bowu/Research/testdata/tmp/data.csv"));
			for (String[] line : xArrayList) {
				cr.writeNext(line);
			}
			cr.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void NormalizeTrainingData() {
		int featuresize = rf.getFeatureNames().size();
		double[] maxvals = new double[featuresize];
		maxvals = UtilTools.initArray(maxvals, -1);
		double[] minvals = new double[featuresize];
		minvals = UtilTools.initArray(minvals, Double.MAX_VALUE);
		for (svm_node[] tmp : trainData) {
			for (int i = 0; i < tmp.length; i++) {
				if (tmp[i].value > maxvals[i]) {
					maxvals[i] = tmp[i].value;
				}
				if (tmp[i].value < minvals[i]) {
					minvals[i] = tmp[i].value;
				}
			}
		}
		minValues = minvals;
		maxValues = maxvals;

		for (svm_node[] tmp : trainData) {
			for (int i = 0; i < tmp.length; i++) {
				if (maxvals[i] > minvals[i]) {
					tmp[i].value = (tmp[i].value - minvals[i]) * 1.0
							/ (maxvals[i] - minvals[i]);
				} else {
					tmp[i].value = 0;
				}
			}
		}
	}

	public void parameterselectionandScale() {
		this.NormalizeTrainingData();
		this.gridSearch();
	}

	public double getAccuracy() {
		int totalCnt = trainData.size();
		int errorCnt = 0;
		for (int i = 0; i < trainData.size(); i++) {
			svm_node[] tdata = trainData.get(i);
			double tar = targets.get(i);
			double v = svm.svm_predict(model, tdata);
			if (v != tar) {
				errorCnt++;
			}
		}
		return (totalCnt - errorCnt) * 1.0 / totalCnt;

	}

	@Override
	public String learnClassifer() {
		//dignose();
		this.parameterselectionandScale();
		return "";
	}

	public void gridSearch() {
		double[][] gammas = { { 0.001,0.005, 0.01, 0.03, 0.05,0.1,0.5},
				{ 0.06, 0.07, 0.08, 0.09, 0.1 } };
		double[][] c = { { 0.5, 0.6, 0.7, 0.8, 0.9, 1.0 },
				{ 2.0, 3.0, 4.0, 5.0, 6.0 } };
		double maxAcc = -1;
		double optG = 0.5;
		double optC = 1;
		// coarse level search
		double[] gInd = {
				(gammas[0][0] + gammas[0][gammas[0].length - 1]) * 1.0 / 2,
				(gammas[1][0] + gammas[1][gammas[1].length - 1]) * 1.0 / 2 };
		double[] cInd = { (c[0][0] + c[0][c[0].length - 1]) * 1.0 / 2,
				(c[1][0] + c[1][c[1].length - 1]) * 1.0 / 2 };
		int gIndex = -1;
		int cIndex = -1;
		for (int i = 0; i < gInd.length; i++) {
			for (int j = 0; j < cInd.length; j++) {
				double acc = cross_verify(gInd[i], cInd[j]);
				if (acc > maxAcc) {
					maxAcc = acc;
					gIndex = i;
					cIndex = j;

				}
			}
		}
		maxAcc = -1;
		// fine level search
		for (int i = 0; i < gammas[gIndex].length; i++) {
			for (int j = 0; j < c[cIndex].length; j++) {
				double acc = cross_verify(gammas[gIndex][i], c[cIndex][j]);
				if (acc > maxAcc) {
					maxAcc = acc;
					optC = c[cIndex][j];
					optG = gammas[gIndex][i];
				}
			}
		}
		// retain on all the data
		//System.out.println(String.format("Gamma: %f, C: %f, Acc: %f", optG,optC, maxAcc));
		this.model = internallearnClassifer(optG, optC, trainData, targets);
		return;
	}

	public double cross_verify(double gamma, double c) {
		double acc = 0.0;
		int fold = 5;
		HashMap<Double, ArrayList<Integer>> labPos = new HashMap<Double, ArrayList<Integer>>();
		for (int i = 0; i < targets.size(); i++) {
			Double l = targets.get(i);
			if (labPos.containsKey(l)) {
				labPos.get(l).add(i);
			} else {
				ArrayList<Integer> pos = new ArrayList<Integer>();
				pos.add(i);
				labPos.put(l, pos);
			}
		}

		for (int i = 0; i < fold; i++) {
			ArrayList<svm_node[]> tmpTrain = new ArrayList<svm_node[]>();
			ArrayList<svm_node[]> tmpTest = new ArrayList<svm_node[]>();
			ArrayList<Double> tmpTraintar = new ArrayList<Double>();
			ArrayList<Double> tmpTesttar = new ArrayList<Double>();
			for (Double l : labPos.keySet()) {
				int datasize = labPos.get(l).size();
				if (datasize < fold) {
					// add its own data until reach the fold number
					int times = fold / datasize;
					@SuppressWarnings("unchecked")
					ArrayList<Integer> ditems = (ArrayList<Integer>) labPos
							.get(l).clone();
					for (int t = 1; t < times+1; t++) {
						labPos.get(l).addAll(ditems);
					}
					datasize = labPos.get(l).size();
				}
				for (int k = 0; k < datasize; k++) {
					int itemIndex = labPos.get(l).get(k);
					if (k % fold == i) {
						tmpTest.add(trainData.get(itemIndex));
						tmpTesttar.add(targets.get(itemIndex));
					} else {
						tmpTrain.add(trainData.get(itemIndex));
						tmpTraintar.add(targets.get(itemIndex));
					}
				}
			}
			svm_model m = internallearnClassifer(gamma, c, tmpTrain,
					tmpTraintar);
			acc += getAccuracy(m, tmpTest, tmpTesttar);
		}
		return acc * 1.0 / fold;
	}

	public double getAccuracy(svm_model m, ArrayList<svm_node[]> tData,
			ArrayList<Double> tars) {
		if (tData.size() == 0) {
			return 0;
		}
		int errorCnt = 0;
		for (int i = 0; i < tData.size(); i++) {
			double v = svm.svm_predict(m, tData.get(i));
			if (v != tars.get(i)) {
				errorCnt++;
			}
		}
		return 1 - errorCnt * 1.0 / tData.size();
	}

	public svm_model internallearnClassifer(double gamma, double c,
			ArrayList<svm_node[]> tData, ArrayList<Double> tars) {
		// duplicateData();
		this.convertToCSVfile();
		svm_problem problem = new svm_problem();
		problem.l = tData.size();
		problem.x = tData.toArray(new svm_node[tData.size()][]); // feature
																	// nodes
		problem.y = ArrayUtils
				.toPrimitive(tars.toArray(new Double[tars.size()])); // target
																		// values
		svm_parameter parameters = new svm_parameter();

		parameters.gamma = gamma;
		parameters.svm_type = svm_parameter.C_SVC;
		parameters.kernel_type = svm_parameter.RBF;
		parameters.degree = 3;
		parameters.coef0 = 0;
		parameters.nu = 0.5;
		parameters.cache_size = 100;
		parameters.C = c;
		parameters.eps = 1e-5;
		parameters.p = 0.1;
		parameters.shrinking = 1;
		parameters.probability = 1;

		HashMap<Double, Double> wtsdict = adjustunbalancedData();
		parameters.nr_weight = wtsdict.keySet().size();
		int ptr = 0;
		int[] wts_labels = new int[parameters.nr_weight];
		double[] wts = new double[parameters.nr_weight];
		for (Double key : wtsdict.keySet()) {
			wts_labels[ptr] = key.intValue();
			wts[ptr] = wtsdict.get(key);
			ptr++;
		}
		parameters.weight_label = wts_labels;
		parameters.weight = wts;

		svm.svm_set_print_string_function(new svm_print_interface() {
			public void print(String s) {
			}
		});
		svm.rand.setSeed(0);
		svm_model model = svm.svm_train(problem, parameters);
		return model;
	}

	@Override
	public String getLabel(String value) {
		Collection<Feature> cfeat = rf.computeFeatures(value, "");
		Feature[] x = cfeat.toArray(new Feature[cfeat.size()]);
		// row.add(f.getName());
		svm_node[] testNodes = new svm_node[cfeat.size()];
		for (int k = 0; k < cfeat.size(); k++) {
			svm_node node = new svm_node();
			node.index = k;
			node.value = x[k].getScore();
			testNodes[k] = node;
		}
		/* temp test */

		// double[] prob_estimates = new
		// double[this.labelMapping.keySet().size()];
		rescale(testNodes);
		double v = svm.svm_predict(model, testNodes);
		// find string lable
		return findLable(v);
	}

	public String findLable(double v) {
		String label = "";
		for (String key : labelMapping.keySet()) {
			if (labelMapping.get(key) == v) {
				label = key;
			}
		}
		if (label.compareTo("") == 0) {
			ulogger.info("Double Label doesn't exist!");
		}
		return label;
	}

	public void selfVerify2() {
		for (int i = 0; i < this.trainData.size(); i++) {
			System.out.println("Label: " + this.rawData.get(i) + ", "
					+ this.getLabel(this.rawData.get(i)));
			System.out.println("Test1:" + this.printLine(trainData.get(i)));
			System.out.println("Model: "
					+ svm.svm_predict(model, this.trainData.get(i)));
		}
	}

	public String printLine(svm_node[] line) {
		String x = "";
		for (int i = 0; i < line.length; i++) {
			x += line[i].value + ",";
		}
		x = x.substring(0, x.length() - 1);
		return x;
	}

	public boolean selfVerify() {
		boolean res = true;
		for (int i = 0; i < trainData.size(); i++) {
			svm_node[] tdata = trainData.get(i);
			double tar = targets.get(i);
			double v = svm.svm_predict(model, tdata);
			if (v != tar) {
				return false;
			}
		}
		return res;
	}

	public void testOnFile() {
		String[] vocbs = { "x","DIGITs" };
		String fpath1 = "/Users/bowu/Research/testdata/tmp/data.txt";
		String fpath2 = "/Users/bowu/Research/testdata/tmp/labels.txt";
		try {
			BufferedReader br1 = new BufferedReader(new FileReader(fpath1));
			BufferedReader br2 = new BufferedReader(new FileReader(fpath2));
			String line = "";
			ArrayList<String> data = new ArrayList<String>();
			ArrayList<String> labels = new ArrayList<String>();
			while ((line = br1.readLine()) != null) {
				if (line.trim().length() > 0) {
					data.add(line);
				}
			}
			while ((line = br2.readLine()) != null) {
				if (line.trim().length() > 0) {
					labels.add(line);
				}
			}
			RecordFeatureSet rfs = new RecordFeatureSet();
			rfs.addVocabulary(vocbs);
			this.rf = rfs;
			for (int i = 0; i < data.size(); i++) {
				addTrainingData(data.get(i), "c" + labels.get(i));
			}
			learnClassifer();
			String[] test = { "4 x 9\"",
					"H: 58 x  W: 25\"",
					"15\" x 18\"",
					"14.75\" H x 11\" W",
					"Framed at 21.75\" H x 24.25\" W",
					"49.5\" x 9\""};
			for (int i = 0; i < test.length; i++) {
				System.out.println(String.format("%s, %s ", test[i],
						getLabel(test[i])));
			}
			selfVerify();
			br1.close();
			br2.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	public static void main(String[] args) {
		// RecordFeatureSet rfs = new RecordFeatureSet();
		// String[] vocbs = { "D", "E", "G", "(", ")", "H", ".", "in", "I",
		// "DIGITs", "W", "cm", "P", "x" };
		// // String[] vocbs ={};
		// rfs.addVocabulary(vocbs);
		// RecordClassifier rcf = new RecordClassifier(rfs);
		// rcf.addTrainingData(
		// "11.75 in|15.5 in HIGH x 15.75 in|19.75 in WIDE(29.84 cm|39.37 cm HIGH x 40.00 cm|50.16 cm WIDE)",
		// "c1");
		// rcf.addTrainingData(
		// "7.25 in|11.5 in HIGH x 9.25 in|13 in WIDE(18.41 cm|29.21 cm HIGH x 23.49 cm|33.02 cm WIDE)",
		// "c1");
		// rcf.addTrainingData(
		// "9.75 in|16 in HIGH x 13.75 in|19.5 in WIDE(24.76 cm|40.64 cm HIGH x 34.92 cm|49.53 cm WIDE)",
		// "c1");
		// rcf.addTrainingData("20 in. HIGH x 24 in. WIDE", "c2");
		// rcf.addTrainingData("26 in. HIGH x 22.5 in. WIDE", "c2");
		// rcf.addTrainingData("10.25 in. HIGH x 8.5 in. WIDE", "c2");
		// rcf.addTrainingData("59.75 in WIDE(151.76 cm WIDE)", "c3");
		// rcf.addTrainingData("29.75 in HIGH(75.56 cm HIGH)", "c4");
		// rcf.learnClassifer();
		// for (String val : rcf.rawData) {
		// System.out.println("class: " + rcf.getLabel(val));
		// }
		//
		// System.out.println("self verifying....");
		// System.out.println(rcf.selfVerify());
		// // System.out.println("class: "+rcf.getLabel("."));
		// // System.out.println("class: "+rcf.getLabel("&$"));
		RecordFeatureSet rfs1 = new RecordFeatureSet();
		String[] vocbs1 = { "by", "G", "L", "M", "K", "ade", "DIGITs" };
		rfs1.addVocabulary(vocbs1);
		RecordClassifier rcf1 = new RecordClassifier(rfs1);
		rcf1.testOnFile();
	}

}


text:
<?php
require("application/views/FPDF/fpdf.php");
$pdf = new FPDF();

$pdf->AddPage();
$pdf->SetTitle("Reference Information");

$referenceNumber = $this->encryption->decrypt($application->get_referenceNum());
$businessName = utf8_decode($application->get_businessName());
$nameOfOwner = utf8_decode($application->get_firstName() . " " . $application->get_middleName() . " " . $application->get_lastName());
$datePrinted = new DateTime('now');
$dateHolder = date('M d Y');
//
$x = $pdf->GetX();
$y = $pdf->GetY();
$pdf->Image('application/views/dashboard/bplo/ref_bg.jpg',$x-10,$y-10,90,67);
// $pdf->Rect(10,10,90,67);

$x = $pdf->GetX();
$y = $pdf->GetY();
$pdf->SetFont("Arial","B","30");
$pdf->Text($x-6,$y+21.5,"$referenceNumber");

$pdf->SetFont("Arial","","14");
$pdf->Text($x+21,$y+35,"$businessName");
$pdf->Text($x+7,$y+42.6,"$nameOfOwner");
$pdf->Text($x+17,$y+50.3,"$dateHolder");
$pdf->Output();
 ?>


text:
using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using WimdioApiProxy.v2.DataTransferObjects;
using WimdioApiProxy.v2.Helpers;

namespace WimdioApiProxy.v2.Rest
{
    internal class BaseClient
    {
        protected readonly ILog log = LogManager.GetLogger(typeof(BaseClient));

        private int? RequestTimeoutInMilliseconds { get; set; }

        protected string BaseUrl { get; set; }
        protected IDictionary<HttpRequestHeader, string> Headers { get; set; }
        protected IDictionary<string, string> CustomHeaders { get; set; }
        protected string ContentType { get; set; }
        protected ISerializer Serializer { get; set; }
        protected IRequestDataWriter RequestWriter { get; set; }
        protected IResponseDataReader ResponseReader { get; set; }

        public BaseClient(string baseUrl, ISerializer dataSerializer, IRequestDataWriter requestDataWriter, IResponseDataReader responseDataReader, int? requestTimeoutInSeconds = null)
        {
            if (!RestUriBuilder.IsValidUri(baseUrl))
                throw new ArgumentException($"{nameof(baseUrl)} must be set to a valid Url");

            if (dataSerializer == null)
                throw new ArgumentException($"{nameof(dataSerializer)} can not be Null");

            if (requestDataWriter == null)
                throw new ArgumentException($"{nameof(requestDataWriter)} can not be Null");

            if (responseDataReader == null)
                throw new ArgumentException($"{nameof(responseDataReader)} can not be Null");

            BaseUrl = baseUrl;
            Serializer = dataSerializer;
            RequestWriter = requestDataWriter;
            ResponseReader = responseDataReader;

            Headers = new Dictionary<HttpRequestHeader, string>();
            CustomHeaders = new Dictionary<string, string>();

            if (requestTimeoutInSeconds.HasValue)
                RequestTimeoutInMilliseconds = (int)Math.Truncate(TimeSpan.FromSeconds(requestTimeoutInSeconds.Value).TotalMilliseconds);
        }

        public async Task<T> Get<T>(string method, IDictionary<string, string> queryStringParameters = null) where T : class
        {
            return await ExecuteCall<T>(method, HttpVerbs.Get, queryStringParameters);
        }

        public async Task<T> Post<T>(string method, object parameter, IDictionary<string, string> queryStringParameters = null) where T : class
        {
            return await ExecuteCall<T>(method, HttpVerbs.Post, parameter, queryStringParameters);
        }

        public async Task<T> Put<T>(string method, object parameter, IDictionary<string, string> queryStringParameters = null) where T : class
        {
            return await ExecuteCall<T>(method, HttpVerbs.Put, parameter, queryStringParameters);
        }

        public async Task<T> Delete<T>(string method, IDictionary<string, string> queryStringParameters = null) where T : class
        {
            return await ExecuteCall<T>(method, HttpVerbs.Delete, queryStringParameters);
        }

        public async Task<T> ExecuteCall<T>(string method, HttpVerbs verb, object bodyParameter = null, IDictionary<string, string> queryStringParameters = null) where T : class
        {
            if (string.IsNullOrEmpty(method))
                throw new ArgumentException($"{nameof(method)} must be set");

            T result = null;

            var uri = new RestUriBuilder(BaseUrl, method, queryStringParameters);
            var request = GetRequest(uri.ToString(), verb);

            string serializedObject = null;
            if (bodyParameter != null)
            {
                serializedObject = Serializer.Serialize(bodyParameter);

                await RequestWriter.WriteAsync(request, serializedObject);
            }

            string responseString = null;
            try
            {
                var response = (HttpWebResponse)await request.GetResponseAsync();

                using (response)
                {
                    responseString = await ResponseReader.ReadAsync(response);

                    if (!string.IsNullOrWhiteSpace(responseString))
                        result = Serializer.Deserialize<T>(responseString);
                }
            }
            catch (WebException we)
            {
                request?.Abort();

                var errorResponse = ((HttpWebResponse)we.Response);

                using (errorResponse)
                {
                    responseString = await ResponseReader.ReadAsync(errorResponse);

                    if (!string.IsNullOrWhiteSpace(responseString))
                    {
                        var errorResult = errorResponse.ContentType.EndsWith("json")
                                        ? Serializer.Deserialize<ErrorResponse>(responseString)
                                        : null;

                        log.Error($"RESTful '{method}' {verb.ToString().ToUpper()} failed with code: '{(int)errorResponse.StatusCode}', message: '{errorResult?.Error ?? errorResult?.Status ?? "NULL"}'", we);
                        throw;
                    }
                }
            }
            catch(Exception ex)
            {
                request?.Abort();

                log.Error(ex.Message, ex);
                throw;
            }

            return result;
        }

        protected virtual HttpWebRequest GetRequest(string uri, HttpVerbs verb)
        {
            HttpWebRequest request = null;
            try
            {
                request = (HttpWebRequest)WebRequest.Create(uri);

                if (RequestTimeoutInMilliseconds.HasValue)
                    request.Timeout = RequestTimeoutInMilliseconds.Value;

                request.Headers.Clear();
                Headers?.ToList().ForEach(h => request.Headers.Add(h.Key, h.Value));
                CustomHeaders?.ToList().ForEach(h => request.Headers.Add(h.Key, h.Value));

                request.Referer = BaseUrl;
                request.Method = verb.ToString().ToUpper();

                request.ContentType = ContentType;
                request.Accept = ContentType;

                return request;
            }
            catch (Exception ex)
            {
                request?.Abort();

                log.Error(ex.Message, ex);
                throw;
            }
        }
    }
}


text:
.class synthetic Lcom/android/server/sip/SipWakeupTimer$1;
.super Ljava/lang/Object;
.source "SipWakeupTimer.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/server/sip/SipWakeupTimer;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x1008
    name = null
.end annotation


text:
package data

import (
	"encoding/json"
	"flag"
	"os"
	"path/filepath"
	"sort"
	"testing"

	"github.com/stretchr/testify/assert"

	"github.com/mbrt/gmailctl/internal/engine/config"
	"github.com/mbrt/gmailctl/internal/engine/config/v1alpha3"
)

// update is useful to regenerate the json files, whenever necessary.
// Make sure the new version makes sense!!
var update = flag.Bool("update", false, "update .json files")

type testPaths struct {
	jsonnets []string
	jsons    []string
}

func globPaths(t *testing.T, pattern string) []string {
	fs, err := filepath.Glob(pattern)
	if err != nil {
		t.Fatal(err)
	}
	sort.Strings(fs)
	return fs
}

func allTestPaths(t *testing.T) testPaths {
	tp := testPaths{
		jsonnets: globPaths(t, "testdata/*.jsonnet"),
		jsons:    globPaths(t, "testdata/*.json"),
	}
	if len(tp.jsonnets) != len(tp.jsons) {
		t.Fatal("expected both jsonnet and json to be present")
	}
	return tp
}

func read(t *testing.T, path string) []byte {
	t.Helper()
	b, err := os.ReadFile(path)
	if err != nil {
		t.Fatal(err)
	}
	return b
}

func TestJsonnetLib(t *testing.T) {
	tps := allTestPaths(t)
	for i := 0; i < len(tps.jsonnets); i++ {
		jfile := tps.jsonnets[i]

		t.Run(jfile, func(t *testing.T) {
			jnparsed, err := config.ReadFile(jfile, "")
			assert.Nil(t, err)

			jsfile := tps.jsons[i]
			if *update {
				// Update the golden files
				buf, err := json.MarshalIndent(jnparsed, "", "  ")
				assert.Nil(t, err)
				err = os.WriteFile(jsfile, buf, 0600)
				assert.Nil(t, err)
			} else {
				// Test them
				var jsparsed v1alpha3.Config
				err := json.Unmarshal(read(t, jsfile), &jsparsed)
				assert.Nil(t, err)
				assert.Equal(t, jsparsed, jnparsed)
			}
		})
	}
}


text:
define([
	"../resource/get"
], function( resourceGet ) {

	/**
	 * setAvailableBundles( Cldr, json )
	 *
	 * @Cldr [Cldr class]
	 *
	 * @json resolved/unresolved cldr data.
	 *
	 * Set available bundles queue based on passed json CLDR data. Considers a bundle as any String at /main/{bundle}.
	 */
	return function( Cldr, json ) {
		var bundle,
			availableBundleMapQueue = Cldr._availableBundleMapQueue,
			main = resourceGet( json, [ "main" ] );

		if ( main ) {
			for ( bundle in main ) {
				if ( main.hasOwnProperty( bundle ) && bundle !== "root" &&
							availableBundleMapQueue.indexOf( bundle ) === -1 ) {
					availableBundleMapQueue.push( bundle );
				}
			}
		}
	};
});


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SnakeLadderQuiz.Data.Entities
{
    public class Soal
    {
        public int Soal_Id { get; set; }
        public string Soal_Jenis { get; set; }
        public string Soal_Tanya { get; set; }
        public string Soal_Jawab { get; set; }
        public DateTime Soal_CreateDate { get; set; }
        public DateTime Soal_LastUpdate { get; set; }
    }
}


text:
package org.fujaba.graphengine.unitTests;

import org.junit.Test;
import org.fujaba.graphengine.PatternEngine;
import org.fujaba.graphengine.graph.Graph;
import org.fujaba.graphengine.graph.Node;
import org.junit.Assert;

import net.sourceforge.jeval.EvaluationException;
import net.sourceforge.jeval.Evaluator;

public class TestUseExpressionLibrary {

	@Test
	public void testUseExpressionLibrary() {
		Evaluator evaluator = new Evaluator();
		try {
			/**
			 * Add the variables to our instance of the Evaluator class.
			 */
			evaluator.putVariable("a", "'Hello'");
			evaluator.putVariable("b", "'World'");
			evaluator.putVariable("c", "7");
			evaluator.putVariable("d", "3.5");
			evaluator.putVariable("e", "1");
			evaluator.putVariable("f", "0");
			/**
			 * This sample simply outputs the variables.
			 */
			System.out.println(evaluator.evaluate("#{a}"));
			System.out.println(evaluator.evaluate("#{b}"));
			/**
			 * This sample outputs a preloaded math varibles.
			 */
			System.out.println(evaluator.evaluate("#{PI}"));
			/**
			 * This sample adds the variables together to form a sentence.
			 */
			System.out.println(evaluator.evaluate("#{c} + #{d} == 10.5"));
			System.out.println(evaluator.evaluate("#{c} * #{d} == 24.5"));

			System.out.println(evaluator.evaluate("#{e} && #{f}"));
			System.out.println(evaluator.evaluate("#{e} || #{f}"));
		} catch (EvaluationException ee) {
			System.out.println(ee);
		}

	}

	@Test
	public void testUseExpressionLibraryOnFerrymansGraph() {
		Graph graph = getAdjustedFerrymansGraph();

		String expression = "#{type} == 'Cargo' && #{species} == 'Wolf' && (#{count} < 5 || #{count} > 1000) && #{existant} == 1.0";

		boolean matched = false;
		for (Node node: graph.getNodes()) {
			matched = PatternEngine.evaluate(node, expression);
			if (matched) {
				break;
			}
		}
		Assert.assertTrue(matched);
	}

	@Test
	public void testComplexExpression() {
		Node n = new Node();
		n.setAttribute("type", "Product");
		n.setAttribute("name", "Raspberry Pi 3");
		n.setAttribute("netPrice", 30.25);
		n.setAttribute("tax", 0.19);
		n.setAttribute("amount", 3);

		Assert.assertTrue(PatternEngine.evaluate(n, "#{type} == 'Product' && #{netPrice} * (1 + #{tax}) * #{amount} > 100"));
		Assert.assertTrue(PatternEngine.evaluate(n, "#{type} == 'Product' && indexOf(#{name}, 'Raspberry Pi', 0) != -1"));
	}

	/**
	 * Method to obtain an adjusted initial situation of the ferryman's problem as a graph.
	 * @return an adjusted initial situation of the ferryman's problem as a graph.
	 */
	private Graph getAdjustedFerrymansGraph() {
		Graph ferrymansGraph = new Graph();
		Node wolf = new Node(), goat = new Node(), cabbage = new Node(), ferry = new Node(), north = new Node(), south = new Node();
		ferrymansGraph.addNode(wolf).addNode(goat).addNode(cabbage).addNode(ferry).addNode(north).addNode(south);
		wolf.setAttribute("type", "Cargo").setAttribute("species", "Wolf").setAttribute("count", 1).setAttribute("existant", true).addEdge("eats", goat).addEdge("at", north);
		goat.setAttribute("type", "Cargo").setAttribute("species", "Goat").setAttribute("count", 1).setAttribute("existant", true).addEdge("eats", cabbage).addEdge("at", north);
		cabbage.setAttribute("type", "Cargo").setAttribute("species", "Cabbage").setAttribute("count", 5).setAttribute("existant", true).addEdge("at", north);
		ferry.setAttribute("type", "Ferry").setAttribute("count", 1).setAttribute("existant", true).addEdge("at", north);
		north.setAttribute("type", "Bank").setAttribute("count", 1).setAttribute("existant", true).setAttribute("side", "north").addEdge("opposite", south);
		south.setAttribute("type", "Bank").setAttribute("count", 1).setAttribute("existant", true).setAttribute("side", "south").addEdge("opposite", north);
		return ferrymansGraph;
	}

}


text:
define([
    'text!templates/lead/search.html'
],
    function (tmpl) {
        "use strict";

        var LeadSearchView = Backbone.View.extend({
            tagName  : 'div',
            id       : 'search',
            className: 'eight columns',

            render: function () {
                this.$el.html(tmpl);
            },

            initialize: function (options) {
            }
        });

        return LeadSearchView;
    });


text:
package ch.sama.sql.dialect.tsql.schema;

import ch.sama.sql.dbo.Field;
import ch.sama.sql.dbo.Table;
import ch.sama.sql.dialect.tsql.type.TYPE;
import org.junit.Test;

import java.io.File;
import java.io.FileNotFoundException;
import java.net.URL;
import java.util.List;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;

public class FileSchemaTest {
    private File getResource(String path) throws FileNotFoundException {
        URL url = getClass().getClassLoader().getResource(path);
        if (url == null) {
            throw new FileNotFoundException("File {" + path + "} not found");
        }

        return new File(url.getPath());
    }

    private File getSchemaFile(String name) {
        File file = null;

        try {
            file = getResource("schema/" + name + ".sql");
        } catch (FileNotFoundException e) {
            // ignore
        }

        assertNotEquals(null, file);
        return file;
    }

    private TSqlSchema getSchema(String name) {
        File file = getSchemaFile(name);

        return new TSqlSchema(file);
    }

    @Test
    public void basicTable() {
        TSqlSchema schema = getSchema("BasicTable");

        assertEquals(true, schema.hasTable("tblTable"));

        Table table = schema.getTable("tblTable");

        List<Field> primaryKey = table.getPrimaryKey();
        assertEquals(1, primaryKey.size());

        assertEquals("iId", primaryKey.get(0).getName());

        assertEquals(true, table.hasColumn("iId"));

        Field id = table.getColumn("iId");
        assertEquals(true, id.isPrimaryKey());
        assertEquals(false, id.isNullable());
        assertEquals(true, TYPE.isWeakEqualType(id.getDataType(), TYPE.INT_TYPE));

        assertEquals(true, table.hasColumn("sName"));

        Field name = table.getColumn("sName");
        assertEquals(false, name.isNullable());
        assertEquals(true, TYPE.isWeakEqualType(name.getDataType(), TYPE.VARCHAR_TYPE(50)));

        assertEquals(true, table.hasColumn("sLastName"));

        Field lastName = table.getColumn("sLastName");
        assertEquals(true, lastName.isNullable());
        assertEquals(true, TYPE.isWeakEqualType(lastName.getDataType(), TYPE.VARCHAR_TYPE(50)));
    }

    @Test
    public void withAutoIncrement() {
        TSqlSchema schema = getSchema("TableWithAutoIncrement");

        Table table = schema.getTable("tblTable");

        assertEquals(true, table.hasColumn("iId"));

        Field id = table.getColumn("iId");
        assertEquals(true, id.isAutoIncrement());
        assertEquals(false, id.isNullable());
        assertEquals(true, TYPE.isWeakEqualType(id.getDataType(), TYPE.INT_TYPE));
    }

    @Test
    public void withDefaultValue() {
        TSqlSchema schema = getSchema("TableWithDefault");

        Table table = schema.getTable("tblTable");

        assertEquals(true, table.hasColumn("uidId"));

        Field id = table.getColumn("uidId");
        assertEquals(true, id.hasDefaultValue());
        assertEquals("newsequentialid()", id.getDefaultValue().getValue());
        assertEquals(false, id.isNullable());
        assertEquals(true, TYPE.isWeakEqualType(id.getDataType(), TYPE.UNIQUEIDENTIFIER_TYPE));
    }
}


text:
describe("Restangular", function() {
  // API
  var Restangular, $httpBackend;
  var accountsModel, restangularAccounts, restangularAccount0, restangularAccount1;
  var messages, newAccount;

  // Utils
  // Apply "sanitizeRestangularOne" function to an array of items
  function sanitizeRestangularAll(items) {
    var all = _.map(items, function(item) {
      return sanitizeRestangularOne(item);
    });
    return sanitizeRestangularOne(all);
  };

  // Remove all Restangular/AngularJS added methods in order to use Jasmine toEqual between the retrieve resource and the model
  function sanitizeRestangularOne(item) {
    return _.omit(item, "route", "parentResource", "getList", "get", "post", "put", "remove", "head", "trace", "options", "patch",
      "$then", "$resolved", "restangularCollection", "customOperation", "customGET", "customPOST",
      "customPUT", "customDELETE", "customGETLIST", "$getList", "$resolved", "restangularCollection", "one", "all","doGET", "doPOST",
      "doPUT", "doDELETE", "doGETLIST", "addRestangularMethod", "getRestangularUrl");
  };

  // Load required modules
  beforeEach(angular.mock.module("ngResource"));
  beforeEach(angular.mock.module("restangular"));

  // Init HTTP mock backend and Restangular resources
  beforeEach(inject(function($injector) {
    // Model
    accountsModel = [
      {id: 0, user: "Martin ", amount: 42, transactions: []},
      {id: 1, user: "Paul", amount: 3.1416, transactions: [{from: "Martin", amount: 3, id: 0}, {from: "Anonymous", amount: 0.1416, id:1}]}
    ];

    newAccount = {id: 44, user: "First User", amount: 45, transactions: []};

    messages = [{id: 23, name: "Gonto"}, {id: 45, name: "John"}]

    $httpBackend = $injector.get("$httpBackend");

    $httpBackend.when("HEAD", "/accounts").respond();
    $httpBackend.when("TRACE", "/accounts").respond();
    $httpBackend.when("OPTIONS", "/accounts").respond();

    $httpBackend.whenGET("/accounts").respond(accountsModel);
    $httpBackend.whenGET("/accounts/messages").respond(messages);
    $httpBackend.whenGET("/accounts/1/message").respond(messages[0]);
    $httpBackend.whenGET("/accounts/1/messages").respond(messages);
    $httpBackend.whenGET("/accounts/0").respond(accountsModel[1]);
    $httpBackend.whenGET("/accounts/1").respond(accountsModel[1]);
    $httpBackend.whenGET("/accounts/1/transactions").respond(accountsModel[1].transactions);
    $httpBackend.whenGET("/accounts/1/transactions/1").respond(accountsModel[1].transactions[1]);

    $httpBackend.whenPOST("/accounts").respond(function(method, url, data, headers) {
      var newData = angular.fromJson(data);
      newData.fromServer = true;
      return [201, JSON.stringify(newData), ""];
    });

    $httpBackend.whenPOST("/accounts/1/transactions").respond(function(method, url, data, headers) {
      return [201, "", ""];
    });

    $httpBackend.whenDELETE("/accounts/1/transactions/1").respond(function(method, url, data, headers) {
      return [200, "", ""];
    });

    $httpBackend.whenDELETE("/accounts/1").respond(function(method, url, data, headers) {
      return [200, "", ""];
    });

    $httpBackend.whenPUT("/accounts/1").respond(function(method, url, data, headers) {
      accountsModel[1] = angular.fromJson(data);
      return [201, data, ""];
    });

    Restangular = $injector.get("Restangular");
    restangularAccounts = Restangular.all("accounts");
    restangularAccount0 = Restangular.one("accounts", 0);
    restangularAccount1 = Restangular.one("accounts", 1);
  }));

  afterEach(function() {
    $httpBackend.verifyNoOutstandingExpectation();
    $httpBackend.verifyNoOutstandingRequest();
  });

  describe("ALL", function() {
    it("getList() should return an array of items", function() {
      restangularAccounts.getList().then(function(accounts) {
        expect(sanitizeRestangularAll(accounts)).toEqual(sanitizeRestangularAll(accountsModel));
      });

      $httpBackend.flush();
    });

    it('uses all to get the list without parameters', function() {
      Restangular.one('accounts', 1).all('messages').getList();
      $httpBackend.expectGET('/accounts/1/messages');
      $httpBackend.flush();
    });

    it("Custom GET methods should work", function() {
      restangularAccounts.customGETLIST("messages").then(function(msgs) {
        expect(sanitizeRestangularAll(msgs)).toEqual(sanitizeRestangularAll(messages));
      });

      $httpBackend.flush();
    });

    it("post() should add a new item", function() {
     restangularAccounts.post({id: 2, user: "Someone"}).then(function() {
       expect(accountsModel.length).toEqual(2);
     });

    $httpBackend.expectPOST('/accounts').respond(201, '');
    $httpBackend.flush();
   });

    it("post() should add a new item with data and return the data from the server", function() {
     restangularAccounts.post(newAccount).then(function(added) {
       expect(added.fromServer).toEqual(true);
       expect(added.id).toEqual(newAccount.id);
     });

    $httpBackend.expectPOST('/accounts');
    $httpBackend.flush();
   });

    it("Doing a post and then other operation (delete) should call right URLs", function() {
      restangularAccounts.post(newAccount).then(function(added) {
        added.remove();
        $httpBackend.expectDELETE('/accounts/44').respond(201, '');
      });

      $httpBackend.flush();
    });

    it("Doing a post to a server that returns no element will return undefined", function() {
      restangularAccounts.getList().then(function(accounts) {
        var newTransaction = {id: 1, name: "Gonto"};
        accounts[1].post('transactions', newTransaction).then(function(transaction) {
          expect(transaction).toBeUndefined();
        });
      });

      $httpBackend.flush();
    });

    it("head() should safely return", function() {
      restangularAccounts.head().then(function() {
        expect(true).toBe(true);
      });
      $httpBackend.flush();
    });

    it("trace()  should safely return", function() {
      restangularAccounts.trace().then(function() {
        expect(true).toBe(true);
      });

      $httpBackend.flush();
    });

    it("options()  should safely return", function() {
      restangularAccounts.options().then(function() {
        expect(true).toBe(true);
      });

      $httpBackend.flush();
    });

     it("getList() should correctly handle params after customDELETE", function() {
      $httpBackend.expectGET('/accounts?foo=1').respond(accountsModel);
      restangularAccounts.getList({foo: 1}).then(function(){
        $httpBackend.expectDELETE('/accounts?id=1').respond(201, '');
        return restangularAccounts.customDELETE('', {id: 1});
      }).then(function() {
          $httpBackend.expectGET('/accounts?foo=1').respond(accountsModel);
          return restangularAccounts.getList({foo: 1});
        }).then(function(accounts) {
          expect(sanitizeRestangularAll(accounts)).toEqual(sanitizeRestangularAll(accountsModel));
        });

      $httpBackend.flush();
    });
  });

  describe("ONE", function() {
    it("get() should return a JSON item", function() {
      restangularAccount1.get().then(function(account) {
        expect(sanitizeRestangularOne(account))
          .toEqual(sanitizeRestangularOne(accountsModel[1]));
      });

      $httpBackend.flush();
    });

    it("Should make RequestLess connections with one", function() {
      restangularAccount1.one("transactions", 1).get().then(function(transaction) {
        expect(sanitizeRestangularOne(transaction))
          .toEqual(sanitizeRestangularOne(accountsModel[1].transactions[1]));
      });

      $httpBackend.flush();
    });

    it("Should make RequestLess connections with all", function() {
      restangularAccount1.all("transactions").getList().then(function(transactions) {
        expect(sanitizeRestangularAll(transactions))
          .toEqual(sanitizeRestangularAll(accountsModel[1].transactions));
      });

      $httpBackend.flush();
    });

    it("Custom GET methods should work", function() {
      restangularAccount1.customGET("message").then(function(msg) {
        expect(sanitizeRestangularOne(msg)).toEqual(sanitizeRestangularOne(messages[0]));
      });

      $httpBackend.flush();
    });

    it("put() should update the value", function() {
      restangularAccount1.get().then(function(account) {
        account.amount = 1.618;
        account.put().then(function(newAc) {
          expect(accountsModel[1].amount).toEqual(1.618);
          newAc.remove();
          $httpBackend.expectDELETE("/accounts/1");
        });
        $httpBackend.expectPUT("/accounts/1");

      });

      $httpBackend.flush();
    });

    it("should return an array when accessing a subvalue", function() {
      restangularAccount1.get().then(function(account) {
        account.getList("transactions").then(function(transactions) {
          expect(sanitizeRestangularAll(transactions))
            .toEqual(sanitizeRestangularAll(accountsModel[1].transactions));
        });
      });

      $httpBackend.flush();
    });
  });

  describe("COPY", function() {
    it("should copy an object and 'this' should reference the copied object", function() {
      var copiedAccount = Restangular.copy(accountsModel[0]);
      var that;

      copiedAccount.user = "Copied string";
      expect(copiedAccount).not.toBe(accountsModel[0]);

      // create a spy for one of the methods to capture the value of 'this'
      spyOn(copiedAccount, 'getRestangularUrl').andCallFake(function() {
        that = this;
      });

      copiedAccount.getRestangularUrl(); // invoke the method we are spying on
      expect(that).toBe(copiedAccount);
    });
  });

  describe("getRestangularUrl", function() {
    it("should return the generated URL when you chain Restangular methods together", function() {
      var restangularSpaces = Restangular.one("accounts",123).one("buildings", 456).all("spaces");
      expect(restangularSpaces.getRestangularUrl()).toEqual("/accounts/123/buildings/456/spaces");
    });
  });

  describe("addElementTransformer", function() {
    it("should allow for a custom method to be placed at the collection level", function() {
      var accountsPromise;

      Restangular.addElementTransformer('accounts', true, function(collection) {
         collection.totalAmount = function() {};
         return collection;
      });

      accountsPromise = Restangular.all('accounts').getList();

      accountsPromise.then(function(accounts) {
        expect(typeof accounts.totalAmount).toEqual("function");
      });

      $httpBackend.flush();
    });

    it("should allow for a custom method to be placed at the model level when one model is requested", function() {
      var accountPromise;

      Restangular.addElementTransformer('accounts', false, function(model) {
         model.prettifyAmount = function() {};
         return model;
      });

      accountPromise = Restangular.one('accounts', 1).get();

      accountPromise.then(function(account) {
        expect(typeof account.prettifyAmount).toEqual("function");
      });

      $httpBackend.flush();
    });

    it("should allow for a custom method to be placed at the model level when several models are requested", function() {
      var accountPromise;

      Restangular.addElementTransformer('accounts', false, function(model) {
         model.prettifyAmount = function() {};
         return model;
      });

      accountsPromise = Restangular.all('accounts', 1).getList();

      accountsPromise.then(function(accounts) {
        accounts.forEach(function(account, index) {
          expect(typeof account.prettifyAmount).toEqual("function");
        });
      });

      $httpBackend.flush();
    });
  });

  describe("extendCollection", function() {
    it("should be an alias for a specific invocation of addElementTransformer", function() {
      var spy = spyOn(Restangular, 'addElementTransformer');

      var fn = function(collection) {
        collection.totalAmount = function() {};
        return collection;
      };

      Restangular.extendCollection('accounts', fn);

      expect(spy).toHaveBeenCalledWith('accounts', true, fn);
    });
  });

  describe("extendModel", function() {
    it("should be an alias for a specific invocation of addElementTransformer", function() {
      var spy = spyOn(Restangular, 'addElementTransformer');

      var fn = function(model) {
        model.prettifyAmount = function() {};
        return model;
      };

      Restangular.extendModel('accounts', fn);

      expect(spy).toHaveBeenCalledWith('accounts', false, fn);
    });
  });
});


text:
<?php

namespace Pagekit\User\Controller;

use Pagekit\Framework\Controller\Controller;
use Pagekit\Framework\Controller\Exception;
use Pagekit\User\Entity\UserRepository;
use Pagekit\User\Model\UserInterface;

/**
 * @Route("/user/password")
 */
class ResetPasswordController extends Controller
{
    /**
     * @var UserInterface
     */
    protected $user;

    /**
     * @var UserRepository
     */
    protected $users;

    /**
     * Constructor.
     */
    public function __construct()
    {
        $this->user  = $this['user'];
        $this->users = $this['users']->getUserRepository();
    }

    /**
     * @Response("extension://system/views/user/reset/request.razr")
     */
    public function indexAction()
    {
        if ($this->user->isAuthenticated()) {
            return $this->redirect('/');
        }

        return ['head.title' => __('Reset')];
    }

    /**
     * @Request({"email"})
     * @Response("extension://system/views/user/reset/request.razr")
     */
    public function resetAction($email)
    {
        try {

            if ($this->user->isAuthenticated()) {
                return $this->redirect('/');
            }

            if (!$this['csrf']->validate($this['request']->request->get('_csrf'))) {
                throw new Exception(__('Invalid token. Please try again.'));
            }

            if (empty($email)) {
                throw new Exception(__('Enter a email address.'));
            }

            if (!$user = $this->users->findByEmail($email)) {
                throw new Exception(__('Invalid email address.'));
            }

            if ($user->isBlocked()) {
                throw new Exception(__('Your account has not been activated or is blocked.'));
            }

            $user->setActivation($this['auth.random']->generateString(32));

            $url = $this['url']->route('@system/resetpassword/confirm', ['user' => $user->getUsername(), 'key' => $user->getActivation()], true);

            try {

                $mail = $this['mailer']->create();
                $mail->setTo($user->getEmail())
                     ->setSubject(__('Reset password for %site%.', ['%site%' => $this['config']->get('app.site_title')]))
                     ->setBody($this['view']->render('extension://system/views/user/mails/reset.razr', compact('user', 'url', 'mail')), 'text/html')
                     ->send();

            } catch (\Exception $e) {
                throw new Exception(__('Unable to send confirmation link.'));
            }

            $this->users->save($user);

            $this['message']->success(__('Check your email for the confirmation link.'));

            return $this->redirect('/');

        } catch (Exception $e) {
            $this['message']->error($e->getMessage());
        }

        return $this->redirect('@system/resetpassword');
    }

    /**
     * @Request({"user", "key"})
     * @Response("extension://system/views/user/reset/confirm.razr")
     */
    public function confirmAction($username = "", $activation = "")
    {
        if (empty($username) or empty($activation) or !$user = $this->users->where(compact('username', 'activation'))->first()) {
            $this['message']->error(__('Invalid key.'));
            return $this->redirect('/');
        }

        if ($user->isBlocked()) {
            $this['message']->error(__('Your account has not been activated or is blocked.'));
            return $this->redirect('/');
        }

        if ('POST' === $this['request']->getMethod()) {

            try {

                if (!$this['csrf']->validate($this['request']->request->get('_csrf'))) {
                    throw new Exception(__('Invalid token. Please try again.'));
                }

                $password = $this['request']->request->get('password');

                if (empty($password)) {
                    throw new Exception(__('Enter password.'));
                }

                if ($password != trim($password)) {
                    throw new Exception(__('Invalid password.'));
                }

                $user->setPassword($this['auth.password']->hash($password));
                $user->setActivation(null);

                $this->users->save($user);

                $this['message']->success(__('Your password has been reset.'));
                return $this->redirect('/');

            } catch (Exception $e) {
                $this['message']->error($e->getMessage());
            }
        }

        return ['head.title' => __('Reset Confirm'), 'username' => $username, 'activation' => $activation];
    }
}


text:
using System;

class FindGreatestNumber
{
	static void Main()
	{
		int[] numbers = new int[5];
		for (byte i = 0; i < numbers.Length; i++)
		{
			Console.WriteLine("Please enter number {0}",i + 1);
			numbers[i] = GetNumber();
		}
		int greatestNumber = numbers[0];
		for(byte k = 1; k < numbers.Length; k++)
		{
			if (numbers[k] > numbers[k - 1])
			{
				greatestNumber = numbers[k];
			}
		}
		Console.WriteLine("The greatest number is {0}", greatestNumber);
	}
	static int GetNumber()
	{
		int number;
		while(!int.TryParse(Console.ReadLine(),out number))
		{
			Console.WriteLine("Please enter correct number (integer)");
		}
		return number;
	}
}


text:
package net.hexogendev.hexogen.api.world;

import net.hexogendev.hexogen.api.block.Block;
import net.hexogendev.hexogen.api.utils.NumberConversions;
import net.hexogendev.hexogen.api.world.chunk.Chunk;

public class Position {

	private double x;
	private double y;
	private double z;
	private World world;

	public Position(World world, double x, double y, double z) {
		this.world = world;
		this.x = x;
		this.y = y;
		this.z = z;
	}

	public double getX() {
		return x;
	}

	public void setX(double x) {
		this.x = x;
	}

	public double getY() {
		return y;
	}

	public void setY(double y) {
		this.y = y;
	}

	public double getZ() {
		return z;
	}

	public void setZ(double z) {
		this.z = z;
	}

	public World getWorld() {
		return world;
	}

	public int getBlockX() {
		return NumberConversions.floor(x); // TODO
	}

	public int getBlockY() {
		return NumberConversions.floor(y); // TODO
	}

	public int getBlockZ() {
		return NumberConversions.floor(z); // TODO
	}

	public Block getBlock() {
		return world.getBlock(this);// TODO
	}

	public Chunk getChunk() {
		return getWorld().getChunkManager().getChunkFromBlockCoords(getBlockX(), getBlockZ());
	}

	public double distanceTo(Position pos) {
		double var2 = pos.getX() - this.getX();
		double var4 = pos.getY() - this.getY();
		double var6 = pos.getZ() - this.getZ();
		return Math.sqrt(var2 * var2 + var4 * var4 + var6 * var6);
	}

	public double squareDistanceTo(Position pos) {
		double var2 = pos.getX() - this.getX();
		double var4 = pos.getY() - this.getY();
		double var6 = pos.getZ() - this.getZ();
		return var2 * var2 + var4 * var4 + var6 * var6;
	}

	public void add(double x, double y, double z) {
		this.x += x;
		this.y += y;
		this.z += z;
	}

	public void substract(double x, double y, double z) {
		this.x -= x;
		this.y -= y;
		this.z -= z;
	}

	public void add(Position pos) {
		this.x += pos.getX();
		this.y += pos.getY();
		this.z += pos.getZ();
	}

	public void substract(Position pos) {
		this.x -= pos.getX();
		this.y -= pos.getY();
		this.z -= pos.getZ();
	}
}


text:
namespace Xunit.AutoDisplayNameAttributes.UnitTests
{
    using Xunit;

    public static class Fact_FormatDisplayName_PascalCaseToTitleCaseTests
    {
        public sealed class Constructor
        {
            [Theory.FormatDisplayName.ReplaceUnderscoresWithSpaces]
            [ClassData(typeof(PascalCaseToTitleCase_Constructor_TestData))]
            public void Correctly_sets_value_of_DisplayName_property(ConstructorTestParameters testParams)
            {
                var sut = new Fact.FormatDisplayName.PascalCaseToTitleCaseAttribute(testParams.TestMethodName);

                Assert.Equal(testParams.ExpectedDisplayName, sut.DisplayName);
            }
        }
    }
}


text:
[Core](../modules/Core.md).IArtworkRenderFunctions

Additional functions exported by render

**`function`** pause What pause does.

**`function`** colorReset Resets the current lines screen color back to normal.

## Table of contents

### Methods

- [colorReset](Core.IArtworkRenderFunctions.md#colorreset)
- [cursor](Core.IArtworkRenderFunctions.md#cursor)
- [gotoxy](Core.IArtworkRenderFunctions.md#gotoxy)
- [pause](Core.IArtworkRenderFunctions.md#pause)
- [prompt](Core.IArtworkRenderFunctions.md#prompt)

## Methods

### colorReset

▸ **colorReset**(): `void`

Resets the screen color

#### Returns

`void`

#### Defined in

[packages/core/src/index.ts:199](https://github.com/iniquitybbs/iniquity/blob/29195b9/packages/core/src/index.ts#L199)

___

### cursor

▸ **cursor**(`x`, `y`): `void`

#### Parameters

| Name | Type |
| :------ | :------ |
| `x` | `number` |
| `y` | `number` |

#### Returns

`void`

#### Defined in

[packages/core/src/index.ts:203](https://github.com/iniquitybbs/iniquity/blob/29195b9/packages/core/src/index.ts#L203)

___

### gotoxy

▸ **gotoxy**(`x`, `y`): `void`

#### Parameters

| Name | Type |
| :------ | :------ |
| `x` | `number` |
| `y` | `number` |

#### Returns

`void`

#### Defined in

[packages/core/src/index.ts:201](https://github.com/iniquitybbs/iniquity/blob/29195b9/packages/core/src/index.ts#L201)

___

### pause

▸ **pause**(`options?`): `void`

**`see`** [IQPauseOptions](Core.IQPauseOptions.md)

#### Parameters

| Name | Type |
| :------ | :------ |
| `options?` | [`IQPauseOptions`](Core.IQPauseOptions.md) |

#### Returns

`void`

#### Defined in

[packages/core/src/index.ts:195](https://github.com/iniquitybbs/iniquity/blob/29195b9/packages/core/src/index.ts#L195)

___

### prompt

▸ **prompt**(`x`, `y`, `text?`): `void`

#### Parameters

| Name | Type |
| :------ | :------ |
| `x` | `number` |
| `y` | `number` |
| `text?` | `string` |

#### Returns

`void`

#### Defined in

[packages/core/src/index.ts:202](https://github.com/iniquitybbs/iniquity/blob/29195b9/packages/core/src/index.ts#L202)


text:
The Prioritised Objective Setting and Communication application is to facilitate individuals and teams to organise, set and prioritise objectives.

## Getting Started

Install [Meteor](https://www.meteor.com/install)
Start the app:

```sh
meteor
```


text:
/**
 * Created by Raphson on 9/24/16.
 */
let keyMirror = require('keymirror');
let _ = require('lodash');
module.exports = keyMirror({
    USER_SIGNUP : null,
    USER_LOGIN : null,
    AUTH_USER : null,
    USER_UPDATE : null,
    PROJECT_SHARE: null,
    GET_PROJECTS: null,
    GET_PROJECT: null,
    POST_JOB: null,
    GET_JOBS: null,
    GET_DEVELOPERS: null,
    GET_DEVELOPER: null,
    RESET : null,
    CHANGE : null,
    CONTACT : null
});


text:
using namespace swift;
using namespace constraints;

ConstraintFix::~ConstraintFix() {}

Expr *ConstraintFix::getAnchor() const { return getLocator()->getAnchor(); }

void ConstraintFix::print(llvm::raw_ostream &Out) const {
  Out << "[fix: ";
  Out << getName();
  Out << ']';
  Out << " @ ";
  getLocator()->dump(&CS.getASTContext().SourceMgr, Out);
}

void ConstraintFix::dump() const {print(llvm::errs()); }

std::string ForceDowncast::getName() const {
  llvm::SmallString<16> name;
  name += "force downcast (as! ";
  name += DowncastTo->getString();
  name += ")";
  return name.c_str();
}

bool ForceDowncast::diagnose(Expr *expr, bool asNote) const {
  MissingExplicitConversionFailure failure(expr, getConstraintSystem(),
                                           getLocator(), DowncastTo);
  return failure.diagnose(asNote);
}

ForceDowncast *ForceDowncast::create(ConstraintSystem &cs, Type toType,
                                     ConstraintLocator *locator) {
  return new (cs.getAllocator()) ForceDowncast(cs, toType, locator);
}

bool ForceOptional::diagnose(Expr *root, bool asNote) const {
  MissingOptionalUnwrapFailure failure(root, getConstraintSystem(),
                                       getLocator());
  return failure.diagnose(asNote);
}

ForceOptional *ForceOptional::create(ConstraintSystem &cs,
                                     ConstraintLocator *locator) {
  return new (cs.getAllocator()) ForceOptional(cs, locator);
}

bool UnwrapOptionalBase::diagnose(Expr *root, bool asNote) const {
  bool resultIsOptional =
      getKind() == FixKind::UnwrapOptionalBaseWithOptionalResult;
  MemberAccessOnOptionalBaseFailure failure(
      root, getConstraintSystem(), getLocator(), MemberName, resultIsOptional);
  return failure.diagnose(asNote);
}

UnwrapOptionalBase *UnwrapOptionalBase::create(ConstraintSystem &cs,
                                               DeclName member,
                                               ConstraintLocator *locator) {
  return new (cs.getAllocator())
      UnwrapOptionalBase(cs, FixKind::UnwrapOptionalBase, member, locator);
}

UnwrapOptionalBase *UnwrapOptionalBase::createWithOptionalResult(
    ConstraintSystem &cs, DeclName member, ConstraintLocator *locator) {
  return new (cs.getAllocator()) UnwrapOptionalBase(
      cs, FixKind::UnwrapOptionalBaseWithOptionalResult, member, locator);
}

bool AddAddressOf::diagnose(Expr *root, bool asNote) const {
  MissingAddressOfFailure failure(root, getConstraintSystem(), getLocator());
  return failure.diagnose(asNote);
}

AddAddressOf *AddAddressOf::create(ConstraintSystem &cs,
                                   ConstraintLocator *locator) {
  return new (cs.getAllocator()) AddAddressOf(cs, locator);
}

bool TreatRValueAsLValue::diagnose(Expr *root, bool asNote) const {
  RValueTreatedAsLValueFailure failure(getConstraintSystem(), getLocator());
  return failure.diagnose(asNote);
}

TreatRValueAsLValue *TreatRValueAsLValue::create(ConstraintSystem &cs,
                                   ConstraintLocator *locator) {
  return new (cs.getAllocator()) TreatRValueAsLValue(cs, locator);
}

bool CoerceToCheckedCast::diagnose(Expr *root, bool asNote) const {
  MissingForcedDowncastFailure failure(root, getConstraintSystem(),
                                       getLocator());
  return failure.diagnose(asNote);
}

CoerceToCheckedCast *CoerceToCheckedCast::create(ConstraintSystem &cs,
                                                 ConstraintLocator *locator) {
  return new (cs.getAllocator()) CoerceToCheckedCast(cs, locator);
}

bool MarkExplicitlyEscaping::diagnose(Expr *root, bool asNote) const {
  NoEscapeFuncToTypeConversionFailure failure(root, getConstraintSystem(),
                                              getLocator(), ConvertTo);
  return failure.diagnose(asNote);
}

MarkExplicitlyEscaping *
MarkExplicitlyEscaping::create(ConstraintSystem &cs, ConstraintLocator *locator,
                               Type convertingTo) {
  return new (cs.getAllocator())
      MarkExplicitlyEscaping(cs, locator, convertingTo);
}

bool RelabelArguments::diagnose(Expr *root, bool asNote) const {
  LabelingFailure failure(getConstraintSystem(), getLocator(), getLabels());
  return failure.diagnose(asNote);
}

RelabelArguments *
RelabelArguments::create(ConstraintSystem &cs,
                         llvm::ArrayRef<Identifier> correctLabels,
                         ConstraintLocator *locator) {
  unsigned size = totalSizeToAlloc<Identifier>(correctLabels.size());
  void *mem = cs.getAllocator().Allocate(size, alignof(RelabelArguments));
  return new (mem) RelabelArguments(cs, correctLabels, locator);
}

bool MissingConformance::diagnose(Expr *root, bool asNote) const {
  MissingConformanceFailure failure(root, getConstraintSystem(), getLocator(),
                                    {NonConformingType, Protocol});
  return failure.diagnose(asNote);
}

MissingConformance *MissingConformance::create(ConstraintSystem &cs, Type type,
                                               ProtocolDecl *protocol,
                                               ConstraintLocator *locator) {
  return new (cs.getAllocator())
      MissingConformance(cs, type, protocol, locator);
}

bool SkipSameTypeRequirement::diagnose(Expr *root, bool asNote) const {
  SameTypeRequirementFailure failure(root, getConstraintSystem(), LHS, RHS,
                                     getLocator());
  return failure.diagnose(asNote);
}

SkipSameTypeRequirement *
SkipSameTypeRequirement::create(ConstraintSystem &cs, Type lhs, Type rhs,
                                ConstraintLocator *locator) {
  return new (cs.getAllocator()) SkipSameTypeRequirement(cs, lhs, rhs, locator);
}

bool SkipSuperclassRequirement::diagnose(Expr *root, bool asNote) const {
  SuperclassRequirementFailure failure(root, getConstraintSystem(), LHS, RHS,
                                       getLocator());
  return failure.diagnose(asNote);
}

SkipSuperclassRequirement *
SkipSuperclassRequirement::create(ConstraintSystem &cs, Type lhs, Type rhs,
                                  ConstraintLocator *locator) {
  return new (cs.getAllocator())
      SkipSuperclassRequirement(cs, lhs, rhs, locator);
}


text:
"""This is a shard that works off a fixed set of values. The shard_field
configuration property should be set to an incoming message property that
can be used to select a shard. Each node's definition should have a property
called shard_field_value. This is used to build a mapping from vlaues of
the shard_field to nodes.
"""
import sys
import os.path
from logging import ERROR, WARN, INFO, DEBUG
import time
import random
from collections import defaultdict

try:
  import datablox_framework
except ImportError:
  sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__),
                                               "../../datablox_framework")))
  import datablox_framework

from datablox_framework.block import *
from datablox_framework.shard import *

class EnumShardError(Exception):
  pass

class ValueNotInEnum(Exception):
  def __init__(self, v):
    Exception.__init__(self, "Value '%s' not found in Enum" % v)
    self.v = v

class enum_shard(Shard):
  @classmethod
  def initial_configs(cls, config):
    if isinstance(config["node_type"]["args"], list):
      #at least have as many arguments as there are nodes
      assert(len(config["node_type"]["args"]) >= config["nodes"])
      return [config["node_type"]["args"][i] for i in range(config["nodes"])]
    else:
      return [config["node_type"]["args"] for i in range(config["nodes"])]

  def on_load(self, config):
    self.nodes = config["nodes"]
    self.config = config
    self.shard_field = config["shard_field"]
    self.add_port("input", Port.PUSH, Port.UNNAMED, [])
    self.add_port("input_query", Port.QUERY, Port.UNNAMED, [])
    self.field_to_node_mapping = {}
    self.message_counts = []
    for i in range(config["nodes"]):
      node_info = config["node_type"]["args"][i]
      if not node_info.has_key("shard_field_value"):
        raise EnumShardError("Shard %d missing shard_field_value property" % i)
      v = node_info["shard_field_value"]
      if self.field_to_node_mapping.has_key(v):
        raise EnumShardError("Shard has multiple nodes defined for field value %s" %
                             v)
      self.field_to_node_mapping[v] = i
      self.message_counts.append(0)
    self.log(INFO, "field to node mapping: %r" % self.field_to_node_mapping)
    self.log(INFO, "Enum shard loaded")

  def find_node_num(self, row):
    val = row[self.shard_field]
    if self.field_to_node_mapping.has_key(val):
      return self.field_to_node_mapping[val]
    else:
      raise ValueNotInEnum(val)

  def flush_logs(self, logs):
    for p_num, log in logs.items():
      self.push_node(p_num, log)

  def process_log(self, log):
    logs = defaultdict(Log)
    for row in log.iter_flatten():
      try:
        p = self.find_node_num(row)
        logs[p].append_row(row)
        self.message_counts[p] += 1
      except KeyError:
        #this row does not have shard field - send it to all ports
        #useful for sending tokens
        #first flush all the pending logs, because this doesn't have the same names
        self.flush_logs(logs)
        logs = defaultdict(Log)
        nl = Log()
        nl.append_row(row)
        for i in range(self.nodes):
          self.push_node(i, nl)
          self.message_counts[i] += 1
      except ValueNotInEnum, e:
        #this row's shard field value not in enum- send it to a random port
        #first flush all the pending logs, because this doesn't have the same names
        self.flush_logs(logs)
        logs = defaultdict(Log)
        dest_node = random.randint(0, self.nodes-1)
        self.log(WARN,"%s, sending to a random node (%d)" %
                 (e, dest_node))
        nl = Log()
        nl.append_row(row)
        self.push_node(dest_node, nl)
        self.message_counts[dest_node] += 1
    self.flush_logs(logs)

  def recv_push(self, port, log):
    self.process_log(log)

  #migration not implemented yet
  def can_add_node(self):
    return False

  def recv_query(self, port, log):
    self.process_log(log)
    ret = Log()
    ret.log["result"] = True
    self.return_query_res(port, ret)

  def on_shutdown(self):
    self.log(INFO, "Total messages processed: %d" % sum(self.message_counts))
    for i in range(self.config["nodes"]):
      self.log(INFO, "  Node %d: %d messages sent" %
               (i, self.message_counts[i]))


text: X


text:
import NumericPrelude hiding
    (not, (&&), (||), Monad, Functor, (*>), (++),
     (>>=), (>>), return, fail, fmap, mapM, mapM_, sequence, sequence_,
     (=<<), foldl, foldl1, foldr, foldr1, and, or, any, all, sum, product,
     concat, concatMap, maximum, minimum, elem, notElem)