text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Branch Demo Page</title>
    <meta name="viewport" content="width=device-width">
    <meta name="description" content="Branch Demo Page">
    <meta name="author" content="Mike Kwon">
    <link rel="alternate" type="application/rss+xml" title="RSS" href="/feed.xml">
    <link rel="stylesheet" href="/style.css">
    <link rel="stylesheet" href="/css/font-awesome/css/font-awesome.min.css">
    <link href="//fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
    <link href="//fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic" rel="stylesheet" type="text/css">

    <meta name="branch:deeplink:branchtestpage" content="true" />
    <meta name="branch:deeplink:text" content="value from Branch metatag" />

    <meta name="random" content="value from non-Branch metatag" />

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>
                Branch Demo

                        Top Section

                        Middle Section

                        Bottom Section

                        Chewy Demo

                        Testpage displaying a Journeys Banner

                        <button onclick="launchBranchJourney()" onmouseover="" style="cursor: pointer; border-radius: 12px; background-color: #008CBA; border: none; color: white; padding: 12px 32px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2), 0 6px 20px 0 rgba(0,0,0,0.19); width:100%; margin: 5px 0px 5px 0px;">Launch Banner</button>
                        <button onclick="closeBranchJourney()" onmouseover="" style="cursor: pointer; border-radius: 12px; background-color: #008CBA; border: none; color: white; padding: 12px 32px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2), 0 6px 20px 0 rgba(0,0,0,0.19); width:100%; margin: 5px 0px 5px 0px;">Close Banner</button>

Filler Text

Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem

Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem

Filler Text

Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem

Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem

Branch Demo Page

                        Contact mkwon@branch.io for questions


text:
from typing import Callable
from unittest.mock import Mock, patch

import pytest

from azure.ai.ml import load_workspace_connection
from azure.ai.ml._restclient.v2022_01_01_preview.models import ConnectionCategory
from azure.ai.ml._scope_dependent_operations import OperationConfig, OperationScope
from azure.ai.ml._utils.utils import camel_to_snake
from azure.ai.ml.entities import WorkspaceConnection, PatTokenConfiguration
from azure.ai.ml.operations import WorkspaceConnectionsOperations

@pytest.fixture
def mock_credential() -> Mock:
    yield Mock()

@pytest.fixture
def mock_workspace_connection_operation(
    mock_workspace_scope: OperationScope,
    mock_operation_config: OperationConfig,
    mock_aml_services_2022_01_01_preview: Mock,
    mock_machinelearning_client: Mock,
    mock_credential: Mock,
) -> WorkspaceConnectionsOperations:
    yield WorkspaceConnectionsOperations(
        operation_scope=mock_workspace_scope,
        operation_config=mock_operation_config,
        service_client=mock_aml_services_2022_01_01_preview,
        all_operations=mock_machinelearning_client._operation_container,
        credentials=mock_credential,
    )

@pytest.mark.unittest
@pytest.mark.core_sdk_test
class TestWorkspaceConnectionsOperation:
    @pytest.mark.parametrize(
        "arg", [ConnectionCategory.GIT, ConnectionCategory.PYTHON_FEED, ConnectionCategory.CONTAINER_REGISTRY]
    )
    def test_list(self, arg: str, mock_workspace_connection_operation: WorkspaceConnectionsOperations) -> None:
        mock_workspace_connection_operation.list(connection_type=arg)
        mock_workspace_connection_operation._operation.list.assert_called_once()

    @patch.object(WorkspaceConnection, "_from_rest_object")
    def test_get(
        self,
        mock_from_rest,
        mock_workspace_connection_operation: WorkspaceConnectionsOperations,
    ) -> None:
        mock_from_rest.return_value = WorkspaceConnection(
            target="dummy_target",
            type=ConnectionCategory.PYTHON_FEED,
            credentials=PatTokenConfiguration(pat="dummy_pat"),
            name="dummy_connection",
        )
        mock_workspace_connection_operation.get("random_name")
        mock_workspace_connection_operation._operation.get.assert_called_once()

    @patch.object(WorkspaceConnection, "_from_rest_object")
    def test_create_or_update(
        self,
        mock_from_rest,
        mock_workspace_connection_operation: WorkspaceConnectionsOperations,
    ):
        mock_from_rest.return_value = WorkspaceConnection(
            target="dummy_target",
            type=camel_to_snake(ConnectionCategory.PYTHON_FEED),
            credentials=PatTokenConfiguration(pat="dummy_pat"),
            name="dummy_connection",
            metadata=None,
        )
        workspace_connection = load_workspace_connection(
            source="./tests/test_configs/workspace_connection/python_feed_pat.yaml"
        )

        mock_workspace_connection_operation.create_or_update(workspace_connection=workspace_connection)
        mock_workspace_connection_operation._operation.create.assert_called_once()

    def test_delete(
        self,
        mock_workspace_connection_operation: WorkspaceConnectionsOperations,
    ) -> None:
        mock_workspace_connection_operation.delete("randstr")
        mock_workspace_connection_operation._operation.delete.assert_called_once()

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <base href="http://www.domaine.com">
  <title>Titre de la page</title>
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" >
  <meta name="viewport" content="initial-scale=1">

  <meta name="description" content="Description de la page en 160 caractères maximum">
  <meta name="robots" content="index,follow">
  <link rel="sitemap" href="sitemap.xml">
  <link rel="canonical" href="http://www.domaine.com/url-canonique">
  <link rel="alternate" hreflang="en" href="http://www.domaine.com/url-autre-langue.html">

  <link rel="schema.dc" href="http://purl.org/dc/elements/1.1/">
  <meta name="dc.title" content="Titre de la page">
  <meta name="dc.description" content="Description de la page">
  <meta name="dc.date" scheme="DCTERMS.W3CDTF" content="AAAA-MM-JJ">
  <meta name="dc.language" scheme="DCTERMS.RFC4646" content="fr-FR">

  <meta property="og:type" content="website">
  <meta property="og:title" content="Titre de la page">
  <meta property="og:url" content="http://www.domaine.com/url-canonique">
  <meta property="og:description" content="Description de la page">
  <meta property="og:image" content="Miniature de la page">
  <meta property="og:site_name" content="Nom du site">
  <meta property="og:locale" content="fr-FR">
  <meta property="og:locale:alternate" content="en-EN">

  <meta name="twitter:card" content="summary">
  <meta name="twitter:site" content="@Compte Twitter du site">
  <meta name="twitter:creator" content="@Compte Twitter de l'auteur du contenu">
  <meta name="twitter:url" content="http://www.domaine.com/url-canonique">
  <meta name="twitter:title" content="Titre de la page">
  <meta name="twitter:description" content="Description de la page">
  <meta name="twitter:image" content="Miniature de la page">

  <link rel="apple-touch-icon" href="apple-touch-icon-144x144.png" sizes="144x144">
  <link rel="apple-touch-icon" href="apple-touch-icon-114x114.png" sizes="114x114">
  <link rel="apple-touch-icon" href="apple-touch-icon-72x72.png" sizes="72x72">
  <link rel="apple-touch-icon" href="apple-touch-icon.png">
  <link rel="icon" href="speed-dial-icon.png" type="image/png">
  <link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
  <link rel="icon" href="favicon.png">
  <link rel="icon" href="favicon-128.png" sizes="128x128">

  <meta name="application-name" content="Nom du site">
  <meta name="msapplication-TileColor" content="#FFFFFF">
  <meta name="msapplication-TileImage" content="tileicon.png">

  <link rel="stylesheet" media="all" href="styles.css">

  <link rel="alternate" title="Titre du flux" href="rss.xml">

Aller au contenu

Aller au menu

Aller à la recherche

Titre du site

Menu 1

Menu 2

Menu 3

    <form id="search" action="" method=""></form>

{Titre de la page}

        Réseaux sociaux

Copyright

Licence

Mentions légales

Plan du site

Crédits

Contact


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string msgid="4600421777120114993" name="abc_action_bar_home_description">"Перейти на головний"</string>
    <string msgid="1397052879051804371" name="abc_action_bar_home_description_format">"%1$s, %2$s"</string>
    <string msgid="6623331958280229229" name="abc_action_bar_home_subtitle_description_format">"%1$s, %2$s, %3$s"</string>
    <string msgid="1594238315039666878" name="abc_action_bar_up_description">"Перейти вгору"</string>
    <string msgid="3588849162933574182" name="abc_action_menu_overflow_description">"Інші опції"</string>
    <string msgid="4076576682505996667" name="abc_action_mode_done">"Готово"</string>
    <string msgid="7468859129482906941" name="abc_activity_chooser_view_see_all">"Переглянути всі"</string>
    <string msgid="2031811694353399454" name="abc_activitychooserview_choose_application">"Вибрати програму"</string>
    <string msgid="121134116657445385" name="abc_capital_off">"ВИМК."</string>
    <string msgid="3405795526292276155" name="abc_capital_on">"УВІМК."</string>
    <string msgid="7723749260725869598" name="abc_search_hint">"Пошук…"</string>
    <string msgid="3691816814315814921" name="abc_searchview_description_clear">"Очистити запит"</string>
    <string msgid="2550479030709304392" name="abc_searchview_description_query">"Пошуковий запит"</string>
    <string msgid="8264924765203268293" name="abc_searchview_description_search">"Пошук"</string>
    <string msgid="8928215447528550784" name="abc_searchview_description_submit">"Надіслати запит"</string>
    <string msgid="893419373245838918" name="abc_searchview_description_voice">"Голосовий пошук"</string>
    <string msgid="3421042268587513524" name="abc_shareactionprovider_share_with">"Надіслати через"</string>
    <string msgid="7165123711973476752" name="abc_shareactionprovider_share_with_application">"Надіслати через %s"</string>
    <string msgid="1603543279005712093" name="abc_toolbar_collapse_description">"Згорнути"</string>
    <string msgid="2869576371154716097" name="status_bar_notification_info_overflow">"999+"</string>
    <string name="zxing_app_name">Сканер штрих-кодів</string>
    <string name="zxing_button_ok">OK</string>
    <string name="zxing_msg_camera_framework_bug">Нажаль, виникла помилка камери. Можливо, вам знадобиться перезавантажити пристрій.</string>
    <string name="zxing_msg_default_status">Щоб відсканувати штрих-код, помістіть його в прямокутник видошукача.</string>
</resources>


text:
package com.dtodorov.androlib.services;

import android.app.Activity;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;

import java.util.HashMap;
import java.util.Map;

public class PermissionRequester implements IPermissionRequester {
    private Map<String, Integer> _permissionCodes;
    private Map<String, Boolean> _explained;

    private int _lastCode;

    private Activity _context;
    private IPermissionListener _listener;

    public PermissionRequester(Activity context) {
        Init(context, null);
    }

    public PermissionRequester(Activity context, IPermissionListener listener) {
        Init(context, listener);
    }

    private void Init(Activity context, IPermissionListener listener) {
        _explained = new HashMap<String, Boolean>();
        _context = context;
        _permissionCodes = new HashMap<String, Integer>();
        _listener = listener;
    }

    public void setListener(IPermissionListener listener) {
        _listener = listener;
    }

    private int getCode(String permission) {
        if(_permissionCodes.containsKey(permission)) {
            return _permissionCodes.get(permission);
        } else {
            Integer code = _lastCode;
            _permissionCodes.put(permission, code);
            _lastCode += 1;
            return code;
        }
    }

    private String getPermission(Integer code) {
        for(String permission : _permissionCodes.keySet()) {
            if(_permissionCodes.get(permission).equals(code))
                return permission;
        }

        return "";
    }

    @Override
    public int checkPermission(String permission) {
        return ContextCompat.checkSelfPermission(_context, permission);
    }

    @Override
    public void obtainPermission(String permission) {
        if(checkPermission(permission) != PackageManager.PERMISSION_GRANTED) {
            if(_explained.containsKey(permission) == false && ActivityCompat.shouldShowRequestPermissionRationale(_context, permission)) {
                _listener.explainPermission(permission);
                _explained.put(permission, true);
            } else {
                ActivityCompat.requestPermissions(_context, new String[] { permission }, getCode(permission));
            }
        }
    }

    public void onRequestPermissionResult(int code, String received[], int[] results) {
        if(_listener == null)
            return;

        String requested = getPermission(code);
        if(requested != "") {
            if(received.length == 0) {
                _listener.onCancelled(requested);
            } else if( received[0].equals(requested)
                    && results[0] == PackageManager.PERMISSION_GRANTED) {
                _listener.onGranted(requested);
            } else {
                _listener.onDenied(requested);
            }
        }
    }
}


text:
classdef KinematicDirtran < KinematicTrajectoryOptimization ...
                            & DirtranTrajectoryOptimization
  % Trajectory planning problem in which the acceleration of the joints is
  % taken to be directly controllable. The decision variables are the joint
  % postitions (q), velocities (v), and accelerations (u) at each knot point.
  % Linear interpolation is used to enforce the relationships between those
  % quantities as described in DirtranTrajectoryOptimization.
  properties
    v_inds % nv x N array of indices into the decision variable vector
           % corresponding to the velocities at each knot point.
  end
  methods
    function obj = KinematicDirtran(robot,N,duration,options)
      plant = KinematicDummyPlant(robot);
      parent_args = {plant,N,duration};
      if nargin > 3, parent_args{end+1} = options; end
      obj = obj@DirtranTrajectoryOptimization(parent_args{:});
      obj = obj@KinematicTrajectoryOptimization(robot);
      %obj.v_inds = obj.u_inds;
      obj.v_inds = obj.x_inds(robot.getNumPositions()+(1:robot.getNumVelocities()),:);
    end

    function obj = addConstraint(obj, constraint, varargin)
      if isa(constraint, 'RigidBodyConstraint')
        obj = addRigidBodyConstraint(obj,constraint, varargin{:});
      else
        obj = addConstraint@DirtranTrajectoryOptimization(obj,constraint,varargin{:});
      end
    end

    function [xtraj,z,F,info] = solveTraj(obj,t_init,q_traj_init)
      traj_init.x = [q_traj_init;q_traj_init.fnder()];
      traj_init.u = q_traj_init.fnder().fnder();
      [xtraj,~,z,F,info] = solveTraj@DirectTrajectoryOptimization(obj,t_init,traj_init);
    end
  end
end


text:
const path = require('path');

module.exports = function () {
    return {
        visitor: {
            CallExpression: function CallExpression(_path) {
                var callee = _path.node.callee;

                var modulePath = _path.node.arguments[0];
                var calleeIsRequire = callee.type == 'Identifier' && callee.name == 'require';

                var isCloudModulePath = modulePath && modulePath.type == 'StringLiteral' && modulePath.value.indexOf('cloud/') === 0;

                if (calleeIsRequire && isCloudModulePath) {
                    var fromPath = _path.hub.file.log.filename.split(path.win32.sep).join(path.posix.sep);
                    var targetPath = modulePath.value;
                    var relativePath = path.posix.relative(path.dirname(fromPath), targetPath);
                    if (relativePath.indexOf('.') !== 0) {
                        relativePath = './' + relativePath;
                    }
                    console.log(JSON.stringify({fromPath, targetPath, relativePath}));
                    modulePath.value = relativePath;
                }
            }
        }
    };
};


text:
// Copyright (c) 2003-2014, Jodd Team (jodd.org). All Rights Reserved.

package jodd.lagarto;

import java.io.IOException;

/**
 * Tag information.
 */
public interface Tag {

	// ---------------------------------------------------------------- read

	/**
	 * Returns tags name.
	 */
	String getName();

	/**
	 * Returns {@link TagType type of tag} (e.g. open, close, etc).
	 */
	TagType getType();

	/**
	 * Returns id attribute value of a tag.
	 * Implementations may simply call {@link #getAttributeValue(String, boolean)}
	 * or to cache this value for better performances.
	 */
	String getId();

	/**
	 * Returns 1-based deep level of a tag from the root.
	 */
	int getDeepLevel();

	/**
	 * Returns number of tag attributes.
	 */
	int getAttributeCount();

	/**
	 * Returns attribute name.
	 */
	String getAttributeName(int index);

	/**
	 * Returns attribute value or null for an empty attribute,
	 */
	String getAttributeValue(int index);

	/**
	 * Returns attribute value or null for an empty attribute,
	 * Returns null also if attribute name does not exist.
	 */
	String getAttributeValue(String name, boolean caseSensitive);

	/**
	 * Returns attribute index or -1 if not found.
	 */
	int getAttributeIndex(String name, boolean caseSensitive);

	/**
	 * Detects if an attribute is present.
	 */
	boolean hasAttribute(String name, boolean caseSensitive);

	// ---------------------------------------------------------------- advanced

	/**
	 * Returns tag position in the input source.
	 */
	int getTagPosition();

	/**
	 * Calculates current position of a tag .
	 */
	LagartoLexer.Position calculateTagPosition();

	/**
	 * Returns tag length in the input source.
	 */
	int getTagLength();

	// ---------------------------------------------------------------- write

	/**
	 * Sets new tag name.
	 */
	void setName(String tagName);

	/**
	 * Sets new tag type.
	 */
	void setType(TagType type);

	/**
	 * Adds new attribute without checking if it already exist
	 * thus allowing duplicate attributes.
	 */
	void addAttribute(String name, String value);

	/**
	 * Sets new attribute value. If attribute already exist, it's value is changed.
	 * If attribute does not exist, it will be added to the list.
	 */
	void setAttribute(String name, boolean caseSensitive, String value);

	/**
	 * Sets value for attribute at specific index.
	 */
	void setAttributeValue(int index, String value);

	/**
	 * Sets value for attribute at specific index.
	 */
	void setAttributeValue(String name, boolean caseSensitive, String value);

	/**
	 * Changes attribute name on specific index.
	 */
	void setAttributeName(int index, String name);

	/**
	 * Removes attribute.
	 */
	void removeAttribute(int index);

	/**
	 * Removes attribute.
	 */
	void removeAttribute(String name, boolean caseSensitive);

	/**
	 * Removes all attributes.
	 */
	void removeAttributes();

	/**
	 * Returns true if tag is modified.
	 */
	boolean isModified();

	/**
	 * Force {@link #isModified()} to be true.
	 * Used when tags needs to be regenerated.
	 */
	void setModified();

	// ---------------------------------------------------------------- output

	/**
	 * Shortcut for writeTo(out, false).
	 */
	void writeTo(Appendable out) throws IOException;

	/**
	 * Write out the complete tag. There are two modes how tag can be written.
	 *

	 *
 optimized - if tag is not modified it will be written in its original form. otherwise it will be generated.

	 *
 force build - tag will be always build from tag name and attributes. Resulting tag may be different than source.

	 *

	 */
	void writeTo(Appendable out, boolean forceBuild) throws IOException;

	/**
	 * Get the complete tag.
	 *

	 * This is a bit slower method in that it needs to construct a String and generates tag always.
	 * Use it for debugging purposes.
	 */
	String toString();
}


text:
class GoodsController < ApplicationController
  def index
    @goods = Good.all
  end
end


text:
package devchache.sj114.s2.studyjams.cn.secretme;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.MultiAutoCompleteTextView;
import android.widget.TextView;

import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import java.util.Date;
import java.util.UUID;

import devchache.sj114.s2.studyjams.cn.secretme.CommentList.CommentItem;
import devchache.sj114.s2.studyjams.cn.secretme.SecretCard.SecretCardItem;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link ComposeFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ComposeFragment extends Fragment {
    private View mView;
    private EditText mEditText;
    private int mSection;
    private String mSecretId;

    private DatabaseReference mDatabaseReference;

    public ComposeFragment() {
    }

    public static ComposeFragment newInstance(String param1, String param2) {
        ComposeFragment fragment = new ComposeFragment();

        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mSection = getArguments().getInt("section");
        try{
            mSecretId = getArguments().getString("secretId");
        }catch (Exception e){
            mSecretId = null;
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mView =  inflater.inflate(R.layout.fragment_compose, container, false);
        mEditText = (EditText)mView.findViewById(R.id.fragment_compose_content_text);

        mEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String text = mEditText.getText().toString().trim();
                if(text.length()>=182){
                    ((TextView)getView().findViewById(R.id.fragment_compose_validation_text)).setTextColor(getResources().getColor(R.color.colorError));
                    mView.findViewById(R.id.fragment_compose_confirm).setEnabled(false);
                    ((Button)mView.findViewById(R.id.fragment_compose_confirm)).setTextColor(getResources().getColor(R.color.colorSubtext));
                    ((TextView)getView().findViewById(R.id.fragment_compose_validation_text)).setText(getResources().getText(R.string.compose_validation_text_error));
                }else{
                    mView.findViewById(R.id.fragment_compose_confirm).setEnabled(true);
                    ((Button)mView.findViewById(R.id.fragment_compose_confirm)).setTextColor(getResources().getColor(R.color.colorCardOrange));
                    ((TextView)getView().findViewById(R.id.fragment_compose_validation_text)).setTextColor(getResources().getColor(R.color.colorSubtext));
                    ((TextView)getView().findViewById(R.id.fragment_compose_validation_text)).setText(getResources().getText(R.string.compose_validation_text_normal));
                }
            }
        });

        mView.findViewById(R.id.fragment_compose_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().getSupportFragmentManager().popBackStack();
            }
        });
        mView.findViewById(R.id.fragment_compose_confirm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDatabaseReference = FirebaseDatabase.getInstance().getReference();
                if(mSection==1&&mSecretId==null){
                    final SecretCardItem secretCardItem = new SecretCardItem();
                    secretCardItem.secretId = UUID.randomUUID().toString();
                    secretCardItem.secretDatetime = new Date().getTime();
                    secretCardItem.secretContent = mEditText.getText().toString().trim();
                    mDatabaseReference
                            .child("secret_cards")
                            .child(secretCardItem.secretId)
                            .setValue(secretCardItem).addOnSuccessListener(new OnSuccessListener<Void>() {
                        @Override
                        public void onSuccess(Void aVoid) {
                            mDatabaseReference
                                    .child("post_secret")
                                    .child(FirebaseAuth.getInstance().getCurrentUser().getUid())
                                    .child(secretCardItem.secretId)
                                    .setValue(true).addOnSuccessListener(new OnSuccessListener<Void>() {
                                @Override
                                public void onSuccess(Void aVoid) {
                                    getActivity().getSupportFragmentManager().popBackStack();
                                }
                            });
                        }
                    });

                }else if(mSection==1&&mSecretId.length()>0){
                    final CommentItem commentItem = new CommentItem();
                    commentItem.commentId = UUID.randomUUID().toString();
                    commentItem.commentDatetime = new Date().getTime();
                    commentItem.commentContent = mEditText.getText().toString().trim();
                    mDatabaseReference
                            .child("comments")
                            .child(commentItem.commentId)
                            .setValue(commentItem).addOnSuccessListener(new OnSuccessListener<Void>() {
                        @Override
                        public void onSuccess(Void aVoid) {
                            mDatabaseReference
                                    .child("comment_secret")
                                    .child(mSecretId)
                                    .child(commentItem.commentId)
                                    .setValue(true).addOnSuccessListener(new OnSuccessListener<Void>() {
                                @Override
                                public void onSuccess(Void aVoid) {
                                    getActivity().getSupportFragmentManager().popBackStack();
                                }
                            });
                        }
                    });
                }
            }
        });
        return mView;
    }

}


text:
import gym
import os
import sys
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from gym import wrappers
from datetime import datetime

# a version of HiddenLayer that keeps track of params
class HiddenLayer:
  def __init__(self, M1, M2, f=tf.nn.tanh, use_bias=True):
    self.W = tf.Variable(tf.random_normal(shape=(M1, M2)))
    self.params = [self.W]
    self.use_bias = use_bias
    if use_bias:
      self.b = tf.Variable(np.zeros(M2).astype(np.float32))
      self.params.append(self.b)
    self.f = f

  def forward(self, X):
    if self.use_bias:
      a = tf.matmul(X, self.W) + self.b
    else:
      a = tf.matmul(X, self.W)
    return self.f(a)

class DQN:
  def __init__(self, D, K, hidden_layer_sizes, gamma, max_experiences=10000, min_experiences=100, batch_sz=32):
    self.K = K

    # create the graph
    self.layers = []
    M1 = D
    for M2 in hidden_layer_sizes:
      layer = HiddenLayer(M1, M2)
      self.layers.append(layer)
      M1 = M2

    # final layer
    layer = HiddenLayer(M1, K, lambda x: x)
    self.layers.append(layer)

    # collect params for copy
    self.params = []
    for layer in self.layers:
      self.params += layer.params

    # inputs and targets
    self.X = tf.placeholder(tf.float32, shape=(None, D), name='X')
    self.G = tf.placeholder(tf.float32, shape=(None,), name='G')
    self.actions = tf.placeholder(tf.int32, shape=(None,), name='actions')

    # calculate output and cost
    Z = self.X
    for layer in self.layers:
      Z = layer.forward(Z)
    Y_hat = Z
    self.predict_op = Y_hat

    selected_action_values = tf.reduce_sum(
      Y_hat * tf.one_hot(self.actions, K),
      reduction_indices=[1]
    )

    cost = tf.reduce_sum(tf.square(self.G - selected_action_values))
    self.train_op = tf.train.AdamOptimizer(10e-3).minimize(cost)
    # self.train_op = tf.train.AdagradOptimizer(10e-3).minimize(cost)
    # self.train_op = tf.train.MomentumOptimizer(10e-4, momentum=0.9).minimize(cost)
    # self.train_op = tf.train.GradientDescentOptimizer(10e-5).minimize(cost)

    # create replay memory
    self.experience = {'s': [], 'a': [], 'r': [], 's2': [], 'done': []}
    self.max_experiences = max_experiences
    self.min_experiences = min_experiences
    self.batch_sz = batch_sz
    self.gamma = gamma

  def set_session(self, session):
    self.session = session

  def copy_from(self, other):
    # collect all the ops
    ops = []
    my_params = self.params
    other_params = other.params
    for p, q in zip(my_params, other_params):
      actual = self.session.run(q)
      op = p.assign(actual)
      ops.append(op)
    # now run them all
    self.session.run(ops)

  def predict(self, X):
    X = np.atleast_2d(X)
    return self.session.run(self.predict_op, feed_dict={self.X: X})

  def train(self, target_network):
    # sample a random batch from buffer, do an iteration of GD
    if len(self.experience['s']) < self.min_experiences:
      # don't do anything if we don't have enough experience
      return

    # randomly select a batch
    idx = np.random.choice(len(self.experience['s']), size=self.batch_sz, replace=False)
    # print("idx:", idx)
    states = [self.experience['s'][i] for i in idx]
    actions = [self.experience['a'][i] for i in idx]
    rewards = [self.experience['r'][i] for i in idx]
    next_states = [self.experience['s2'][i] for i in idx]
    dones = [self.experience['done'][i] for i in idx]
    next_Q = np.max(target_network.predict(next_states), axis=1)
    targets = [r + self.gamma*next_q if not done else r for r, next_q, done in zip(rewards, next_Q, dones)]

    # call optimizer
    self.session.run(
      self.train_op,
      feed_dict={
        self.X: states,
        self.G: targets,
        self.actions: actions
      }
    )

  def add_experience(self, s, a, r, s2, done):
    if len(self.experience['s']) >= self.max_experiences:
      self.experience['s'].pop(0)
      self.experience['a'].pop(0)
      self.experience['r'].pop(0)
      self.experience['s2'].pop(0)
      self.experience['done'].pop(0)
    self.experience['s'].append(s)
    self.experience['a'].append(a)
    self.experience['r'].append(r)
    self.experience['s2'].append(s2)
    self.experience['done'].append(done)

  def sample_action(self, x, eps):
    if np.random.random() < eps:
      return np.random.choice(self.K)
    else:
      X = np.atleast_2d(x)
      return np.argmax(self.predict(X)[0])

def play_one(env, model, tmodel, eps, gamma, copy_period):
  observation = env.reset()
  done = False
  totalreward = 0
  iters = 0
  while not done and iters < 2000:
    # if we reach 2000, just quit, don't want this going forever
    # the 200 limit seems a bit early
    action = model.sample_action(observation, eps)
    prev_observation = observation
    observation, reward, done, info = env.step(action)

    totalreward += reward
    if done:
      reward = -200

    # update the model
    model.add_experience(prev_observation, action, reward, observation, done)
    model.train(tmodel)

    iters += 1

    if iters % copy_period == 0:
      tmodel.copy_from(model)

  return totalreward

def plot_running_avg(totalrewards):
  N = len(totalrewards)
  running_average = np.empty(N)
  for t in range(N):
    running_average[t] = totalrewards[max(0, t-100):(t)].mean()
  plt.plot(running_average)
  plt.title("Running Average")
  plt.show()

def main():
  env = gym.make('CartPole-v0')
  gamma = 0.99
  copy_period = 50

  D = len(env.observation_space.sample())
  K = env.action_space.n
  sizes = [200,200]
  model = DQN(D, K, sizes, gamma)
  tmodel = DQN(D, K, sizes, gamma)
  init = tf.global_variables_initializer()
  session = tf.InteractiveSession()
  session.run(init)
  model.set_session(session)
  tmodel.set_session(session)

  if 'monitor' in sys.argv:
    filename = os.path.basename(__file__).split('.')[0]
    monitor_dir = './' + filename + '_' + str(datetime.now())
    env = wrappers.Monitor(env, monitor_dir)

  N = 500
  totalrewards = np.empty(N)
  costs = np.empty(N)
  for n in range(N):
    eps = 1.0/np.sqrt(n+1)
    totalreward = play_one(env, model, tmodel, eps, gamma, copy_period)
    totalrewards[n] = totalreward
    if n % 100 == 0:
      print("episode:", n, "total reward:", totalreward, "eps:", eps, "avg reward (last 100):", totalrewards[max(0, n-100):(n+1)].mean())

  print("avg reward for last 100 episodes:", totalrewards[-100:].mean())
  print("total steps:", totalrewards.sum())

  plt.plot(totalrewards)
  plt.title("Rewards")
  plt.show()

  plot_running_avg(totalrewards)

if __name__ == '__main__':
  main()


text:
namespace syncer {

NormalGetUpdatesRequestEvent::NormalGetUpdatesRequestEvent(
    base::Time timestamp,
    const NudgeTracker& nudge_tracker,
    const sync_pb::ClientToServerMessage& request)
    : NormalGetUpdatesRequestEvent(timestamp,
                                   nudge_tracker.GetNudgedTypes(),
                                   nudge_tracker.GetNotifiedTypes(),
                                   nudge_tracker.GetRefreshRequestedTypes(),
                                   nudge_tracker.IsRetryRequired(),
                                   request) {}

NormalGetUpdatesRequestEvent::NormalGetUpdatesRequestEvent(
    base::Time timestamp,
    ModelTypeSet nudged_types,
    ModelTypeSet notified_types,
    ModelTypeSet refresh_requested_types,
    bool is_retry,
    sync_pb::ClientToServerMessage request)
    : timestamp_(timestamp),
      nudged_types_(nudged_types),
      notified_types_(notified_types),
      refresh_requested_types_(refresh_requested_types),
      is_retry_(is_retry),
      request_(request) {}

std::unique_ptr<ProtocolEvent> NormalGetUpdatesRequestEvent::Clone() const {
  return std::make_unique<NormalGetUpdatesRequestEvent>(
      timestamp_, nudged_types_, notified_types_, refresh_requested_types_,
      is_retry_, request_);
}

NormalGetUpdatesRequestEvent::~NormalGetUpdatesRequestEvent() = default;

base::Time NormalGetUpdatesRequestEvent::GetTimestamp() const {
  return timestamp_;
}

std::string NormalGetUpdatesRequestEvent::GetType() const {
  return "Normal GetUpdate request";
}

std::string NormalGetUpdatesRequestEvent::GetDetails() const {
  std::string details;

  if (!nudged_types_.Empty()) {
    if (!details.empty())
      details.append("\n");
    details.append(base::StringPrintf(
        "Nudged types: %s", ModelTypeSetToDebugString(nudged_types_).c_str()));
  }

  if (!notified_types_.Empty()) {
    if (!details.empty())
      details.append("\n");
    details.append(
        base::StringPrintf("Notified types: %s",
                           ModelTypeSetToDebugString(notified_types_).c_str()));
  }

  if (!refresh_requested_types_.Empty()) {
    if (!details.empty())
      details.append("\n");
    details.append(base::StringPrintf(
        "Refresh requested types: %s",
        ModelTypeSetToDebugString(refresh_requested_types_).c_str()));
  }

  if (is_retry_) {
    if (!details.empty())
      details.append("\n");
    details.append(base::StringPrintf("Is retry: True"));
  }

  return details;
}

std::unique_ptr<base::DictionaryValue>
NormalGetUpdatesRequestEvent::GetProtoMessage(bool include_specifics) const {
  return ClientToServerMessageToValue(request_, include_specifics);
}

}  // namespace syncer


text:
package mark.webserver;

import com.gargoylesoftware.htmlunit.WebClient;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import mark.server.Config;
import org.eclipse.jetty.rewrite.handler.RewriteHandler;
import org.eclipse.jetty.rewrite.handler.Rule;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.server.handler.ResourceHandler;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.ini4j.Wini;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Thibault Debatty
 */
public class WebServer {

    private static final Logger LOGGER = LoggerFactory.getLogger(
            WebServer.class);

    /**
     * Pages that should be manually fetched to avoid Quercus 500 errors
     */
    private static final String[] pages_to_test = new String[]{
        "/",
        "/status",
        "/report/123456"};

    private Server server;
    private final Config config;

    /**
     * Instantiate a web server with provided config.
     * @param config
     */
    public WebServer(final Config config) {
        this.config = config;
    }

    /**
     * Start the web server (non-blocking).
     *
     * @throws java.lang.Exception if jetty fails to start
     */
    public final void start() throws Exception {
        if (!config.start_webserver) {
            return;
        }

        LOGGER.info("Starting web interface at port 8000");

        // Write config.ini file for PHP framework...
        Wini wini = new Wini();
        wini.put("config", "server_host", config.server_host);
        wini.put("config", "server_port", config.server_port);
        wini.put("config", "update_interval", config.update_interval);
        wini.put("config", "adapter_class", config.adapter_class);
        wini.store(config.getWebserverRoot().toPath()
                        .resolve("config.ini").toFile());

        // Handle php files
        ServletContextHandler php_handler = new ServletContextHandler();
        php_handler.addServlet(
                com.caucho.quercus.servlet.QuercusServlet.class, "*.php");
        php_handler.setResourceBase(
                config.getWebserverRoot().getAbsolutePath());

        // Handle static files (if it's not php)
        ResourceHandler resource_handler = new ResourceHandler() {

            @Override
            public void handle(
                    final String target,
                    final Request base_request,
                    final HttpServletRequest request,
                    final HttpServletResponse response)
                    throws IOException, ServletException {

                if (target.endsWith(".php")) {
                    return;
                }

                super.handle(target, base_request, request, response);
            }

        };
        resource_handler.setDirectoriesListed(false);
        resource_handler.setResourceBase(
                config.getWebserverRoot().getAbsolutePath());

        HandlerList handler_list = new HandlerList();
        handler_list.setHandlers(new Handler[]{
            resource_handler,
            php_handler
        });

        // First of all, redirect to index.php if file does not exist
        RewriteHandler rewrite_handler = new RewriteHandler();
        rewrite_handler.setRewriteRequestURI(false);
        rewrite_handler.setRewritePathInfo(false);
        rewrite_handler.setOriginalPathAttribute("requestedPath");
        rewrite_handler.addRule(new RewriteIfNotExistsRule(
                config.getWebserverRoot()));
        rewrite_handler.setHandler(handler_list);

        server = new Server(config.webserver_port);
        server.setHandler(rewrite_handler);
        server.start();

        // Manually perform some http requests to the web server, to avoid
        // the 500 errors generated by Quercus at boot...
        WebClient client = new WebClient();
        String base_url = "http://127.0.0.1:8000";
        client.getCache().clear();
        client.getPage(base_url);

        client.getCache().clear();
        client.getPage(base_url);

        for (String page : pages_to_test) {
            client.getCache().clear();
            client.getPage(base_url + page);
        }
    }

    /**
     *
     * @throws Exception if an error happens while stopping the server
     */
    public final void stop() throws Exception {
        if (server == null) {
            return;
        }

        server.stop();
    }
}

/**
 * Rewrite the request if the requested file does not exist.
 * Similar to following Apache .htaccess:
 * RewriteEngine On
 * RewriteCond %{REQUEST_FILENAME} !-f
 * RewriteRule ^(.*)$ index.php [QSA,L]
 *
 * Or to following nginx:
 * server {
 *   location / {
 *     try_files $uri /index.php;
 *   }
 * }
 * @author Thibault Debatty
 */
class RewriteIfNotExistsRule extends Rule {
    private final Path root;

    RewriteIfNotExistsRule(final File root) {
        this.root = root.toPath();
        _terminating = false;
        _handling = false;
    }

    @Override
    public String matchAndApply(
            final String target,
            final HttpServletRequest request,
            final HttpServletResponse response) throws IOException {

        // Remove the leading / from the request path
        File resource = root.resolve(target.substring(1)).toFile();
        if (resource.exists() && resource.isFile()) {
            return target;
        }

        return "/index.php";
    }
}


text:
<?php

namespace Rch\SiteBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Rch\SiteBundle\Entity\Articles;
use Rch\SiteBundle\Form\ArticlesType;

class SiteController extends Controller
{
    public function indexAction()
    {
        return $this->render('SiteBundle:Site:index.html.twig');
    }

    public function adminAction()
    {
        return $this->render('SiteBundle:Site:admin.index.html.twig');
    }

    public function articlesAction()
    {

        $em = $this->getDoctrine()->getManager();
        $article =  $em->getRepository("SiteBundle:Articles")->findAll();

        return $this->render('SiteBundle:Site:admin.articles.html.twig', array(
            'Articles' => $article
        ));
    }

    public function ajouterAction()
    {

        $em = $this->getDoctrine()->getManager();

        $article = new articles();

        $form = $this->createForm (new ArticlesType(), $article);

        $request = $this->getRequest();
        if($request->ismethod('POST')) {
            $form->bind($this->getRequest($request));

            $article = $form->getData();
            $em->persist($article);
            //$em->persist($article->getImage());
            $em->flush();

            //$this->get('session')->getFlashBag()->add('notice', 'Article bien enregistré');

            return $this->redirect($this->generateUrl('site_admin_articles'));

        }

        return $this->render('SiteBundle:Site:admin.articles.ajouter.html.twig', array(
             'form' => $form->createView(),
        ));
    }

    public function editerAction(Articles $article)
    {
        $em = $this->getDoctrine()->getManager();

        $form = $this->createForm (new ArticlesType(), $article);

        $request = $this->getRequest();
        if($request->ismethod('POST')) {
            $form->bind($this->getRequest($request));

            $article = $form->getData();
            $em->persist($article);
            $em->flush();

            return $this->redirect($this->generateUrl('site_admin_articles', array(
                'id' => $article->getId(),
                ))
            );
        }

       return $this->render('SiteBundle:Site:admin.articles.editer.html.twig', array(
             'Articles' => $article,
             'form'     => $form->createView(),
            ));
    }

    public function supprimerAction(Articles $article){

        $em = $this->getDoctrine()->getManager();

        $em->remove($article);
        $em->flush();

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

    public function categoriesAction()
    {
        return $this->render('SiteBundle:Site:admin.categories.html.twig');
    }

    public function mediasAction()
    {

        /* $em = $this->getDoctrine()->getManager();
        $article =  $em->getRepository("SiteBundle:Articles")->findAll();

        return $this->render('SiteBundle:Site:admin.articles.html.twig', array(
            'Articles' => $article
        )); */

        return $this->render('SiteBundle:Site:admin.medias.html.twig');
    }
}


text:
    For authenticating user and determing the roles given to this user, Hudson performs
    multiple LDAP queries.

    Since an LDAP database is conceptually a big tree and the search is performed recursively,
    in theory if we can start a search starting at a sub-node (as opposed to root), you get
    a better performance because it narrows down the scope of a search.
    This field specifies the DN of such a subtree.

    But in practice, LDAP servers maintain an extensive index over the data, so specifying
    this field is rarely necessary — you should just let Hudson figure this out
    by talking to LDAP.

    If you do specify this value, the field normally looks something like <tt>"dc=sun,dc=com"</tt>


text:
.. _about-sponsors:

########
Sponsors
########

Dropwizard is generously supported by some companies with licenses and free accounts for their products.

JetBrains
=========

.. image:: jetbrains.png

`JetBrains <https://www.jetbrains.com/>`__ supports our open source project by sponsoring some `All Products Packs <https://www.jetbrains.com/products.html>`__ within their `Free Open Source License <https://www.jetbrains.com/buy/opensource/>`__ program.


text:
.class Lcom/quizup/core/activities/test/TestUIActivity$8;
.super Ljava/lang/Object;
.source ""

# interfaces
.implements Landroid/view/View$OnClickListener;

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Lcom/quizup/core/activities/test/TestUIActivity;->onCreate(Landroid/os/Bundle;)V
.end annotation

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

# instance fields
.field final synthetic this$0:Lcom/quizup/core/activities/test/TestUIActivity;

# direct methods
.method constructor <init>(Lcom/quizup/core/activities/test/TestUIActivity;)V
    .locals 0

    .line 186
    iput-object p1, p0, Lcom/quizup/core/activities/test/TestUIActivity$8;->this$0:Lcom/quizup/core/activities/test/TestUIActivity;

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public onClick(Landroid/view/View;)V
    .locals 1

    .line 192
    iget-object v0, p0, Lcom/quizup/core/activities/test/TestUIActivity$8;->this$0:Lcom/quizup/core/activities/test/TestUIActivity;

    #getter for: Lcom/quizup/core/activities/test/TestUIActivity;->blockDialog:Lo/ỉ;
    invoke-static {v0}, Lcom/quizup/core/activities/test/TestUIActivity;->access$600(Lcom/quizup/core/activities/test/TestUIActivity;)Lo/ỉ;

    move-result-object v0

    invoke-virtual {v0}, Lo/ỉ;->ˎ()V

    .line 193
    return-void
.end method


text:
#include <memory>
#include <vector>

#include "base_test.hpp"

#include "expression/expression_functional.hpp"
#include "hyrise.hpp"
#include "logical_query_plan/aggregate_node.hpp"
#include "logical_query_plan/alias_node.hpp"
#include "logical_query_plan/create_prepared_plan_node.hpp"
#include "logical_query_plan/create_table_node.hpp"
#include "logical_query_plan/create_view_node.hpp"
#include "logical_query_plan/delete_node.hpp"
#include "logical_query_plan/drop_table_node.hpp"
#include "logical_query_plan/drop_view_node.hpp"
#include "logical_query_plan/dummy_table_node.hpp"
#include "logical_query_plan/insert_node.hpp"
#include "logical_query_plan/join_node.hpp"
#include "logical_query_plan/limit_node.hpp"
#include "logical_query_plan/mock_node.hpp"
#include "logical_query_plan/predicate_node.hpp"
#include "logical_query_plan/projection_node.hpp"
#include "logical_query_plan/sort_node.hpp"
#include "logical_query_plan/static_table_node.hpp"
#include "logical_query_plan/stored_table_node.hpp"
#include "logical_query_plan/union_node.hpp"
#include "logical_query_plan/update_node.hpp"
#include "logical_query_plan/validate_node.hpp"
#include "statistics/attribute_statistics.hpp"
#include "statistics/cardinality_estimator.hpp"
#include "statistics/statistics_objects/equal_distinct_count_histogram.hpp"
#include "statistics/statistics_objects/generic_histogram.hpp"
#include "statistics/table_statistics.hpp"
#include "storage/table_column_definition.hpp"
#include "utils/load_table.hpp"

using namespace hyrise::expression_functional;  // NOLINT

namespace hyrise {

class CardinalityEstimatorTest : public BaseTest {
 public:
  void SetUp() override {
    /**
     * node_a
     */
    // clang-format on
    node_a = create_mock_node_with_statistics({{DataType::Int, "a"}, {DataType::Int, "b"}}, 100,
                                              {GenericHistogram<int32_t>::with_single_bin(1, 100, 100, 10),
                                               GenericHistogram<int32_t>::with_single_bin(10, 129, 70, 55)});
    // clang-format off

    a_a = node_a->get_column("a");
    a_b = node_a->get_column("b");

    /**
     * node_b
     */
    // clang-format off
    const auto histogram_b_a = std::make_shared<GenericHistogram<int32_t>>(
      std::vector<int32_t>{0, 5, 10}, std::vector<int32_t>{4, 9, 15},
      std::vector<HistogramCountType>{10, 10, 12}, std::vector<HistogramCountType>{5, 5, 6});

    const auto histogram_b_b = std::make_shared<GenericHistogram<int32_t>>(
      std::vector<int32_t>{0}, std::vector<int32_t>{9},
      std::vector<HistogramCountType>{32}, std::vector<HistogramCountType>{10});
    // clang-format on

    node_b = create_mock_node_with_statistics({{DataType::Int, "a"}, {DataType::Int, "b"}}, 32,
                                              {histogram_b_a, histogram_b_b});

    b_a = node_b->get_column("a");
    b_b = node_b->get_column("b");

    /**
     * node_c
     */
    // clang-format off
    const auto histogram_c_x = std::make_shared<EqualDistinctCountHistogram<int32_t>>(
      std::vector<int32_t>{0, 8}, std::vector<int32_t>{7, 15},
      std::vector<HistogramCountType>{32, 32}, 8, 0);

    const auto histogram_c_y = std::make_shared<GenericHistogram<int32_t>>(
      std::vector<int32_t>{0},
      std::vector<int32_t>{9},
      std::vector<HistogramCountType>{64},
      std::vector<HistogramCountType>{10});
    // clang-format on

    node_c = create_mock_node_with_statistics({{DataType::Int, "x"}, {DataType::Int, "y"}}, 64,
                                              {histogram_c_x, histogram_c_y});

    c_x = node_c->get_column("x");

    /**
     * node_d
     */
    node_d = create_mock_node_with_statistics(
        MockNode::ColumnDefinitions{{DataType::Int, "a"}, {DataType::Int, "b"}, {DataType::Int, "c"}}, 100,
        {GenericHistogram<int32_t>::with_single_bin(10, 100, 100, 20),
         GenericHistogram<int32_t>::with_single_bin(50, 60, 100, 5),
         GenericHistogram<int32_t>::with_single_bin(110, 1100, 100, 2)});

    d_a = std::make_shared<LQPColumnExpression>(node_d, ColumnID{0});
    d_b = std::make_shared<LQPColumnExpression>(node_d, ColumnID{1});
    d_c = std::make_shared<LQPColumnExpression>(node_d, ColumnID{2});

    /**
     * node_e
     * Has no statistics on column "b"
     */
    // clang-format on
    node_e = create_mock_node_with_statistics({{DataType::Int, "a"}, {DataType::Int, "b"}}, 100,
                                              {GenericHistogram<int32_t>::with_single_bin(1, 100, 10, 10), nullptr});
    // clang-format off

    e_a = node_e->get_column("a");
    e_b = node_e->get_column("b");

    /**
     * node_f
     * Has columns with different data types
     */
    // clang-format on
    node_f = create_mock_node_with_statistics({{DataType::Int, "a"}, {DataType::Float, "b"}}, 200,
                                              {GenericHistogram<int32_t>::with_single_bin(1, 200, 200, 10),
                                               GenericHistogram<float>::with_single_bin(1.0f, 100.0f, 200, 150.0f)});
    // clang-format off

    f_a = node_f->get_column("a");
    f_b = node_f->get_column("b");

    /**
     * node_g
     * Has a string column
     */
    // clang-format on
    node_g = create_mock_node_with_statistics({{DataType::String, "a"}}, 100,
                                              {GenericHistogram<pmr_string>::with_single_bin("a", "z", 100, 40)});
    // clang-format off

    g_a = node_g->get_column("a");
  }

  CardinalityEstimator estimator;
  std::shared_ptr<LQPColumnExpression> a_a, a_b, b_a, b_b, c_x, d_a, d_b, d_c, e_a, e_b, f_a, f_b, g_a;
  std::shared_ptr<MockNode> node_a, node_b, node_c, node_d, node_e, node_f, node_g;
};

TEST_F(CardinalityEstimatorTest, Aggregate) {
  // clang-format off
  const auto input_lqp =
  AggregateNode::make(expression_vector(a_b, add_(a_b, a_a)), expression_vector(sum_(a_a)),
                      node_a);
  // clang-format on

  const auto input_table_statistics = node_a->table_statistics();
  const auto result_table_statistics = estimator.estimate_statistics(input_lqp);

  EXPECT_EQ(result_table_statistics->row_count, 100u);
  ASSERT_EQ(result_table_statistics->column_statistics.size(), 3u);
  EXPECT_EQ(result_table_statistics->column_statistics.at(0), input_table_statistics->column_statistics.at(1));
  EXPECT_TRUE(result_table_statistics->column_statistics.at(1));
  EXPECT_TRUE(result_table_statistics->column_statistics.at(2));
}

TEST_F(CardinalityEstimatorTest, Alias) {
  // clang-format off
  const auto input_lqp =
  AliasNode::make(expression_vector(a_b, a_a), std::vector<std::string>{"x", "y"},
    node_a);
  // clang-format on

  const auto input_table_statistics = node_a->table_statistics();
  const auto result_table_statistics = estimator.estimate_statistics(input_lqp);

  EXPECT_EQ(result_table_statistics->row_count, 100u);
  ASSERT_EQ(result_table_statistics->column_statistics.size(), 2u);
  EXPECT_EQ(result_table_statistics->column_statistics.at(0), input_table_statistics->column_statistics.at(1));
  EXPECT_EQ(result_table_statistics->column_statistics.at(1), input_table_statistics->column_statistics.at(0));
}

TEST_F(CardinalityEstimatorTest, JoinNumericEquiInner) {
  // clang-format off
  const auto input_lqp =
  JoinNode::make(JoinMode::Inner, equals_(b_a, c_x),
     node_b,
     node_c);
  // clang-format on

  const auto result_statistics = estimator.estimate_statistics(input_lqp);

  ASSERT_EQ(result_statistics->column_statistics.size(), 4u);
  ASSERT_EQ(result_statistics->row_count, 128u);

  const auto column_statistics_b_a =
      std::dynamic_pointer_cast<AttributeStatistics<int32_t>>(result_statistics->column_statistics.at(0));
  const auto join_histogram_b_a = column_statistics_b_a->histogram;
  EXPECT_EQ(join_histogram_b_a->bin_count(), 4u);

  const auto column_statistics_b_b =
      std::dynamic_pointer_cast<AttributeStatistics<int32_t>>(result_statistics->column_statistics[1]);
  const auto scaled_histogram_b_b = column_statistics_b_b->histogram;
  EXPECT_EQ(scaled_histogram_b_b->total_count(), 32 * 4);

  const auto column_statistics_c_x =
      std::dynamic_pointer_cast<AttributeStatistics<int32_t>>(result_statistics->column_statistics[2]);
  const auto join_histogram_c_x = column_statistics_c_x->histogram;
  EXPECT_EQ(join_histogram_c_x->bin_count(), 4u);

  const auto column_statistics_c_y =
      std::dynamic_pointer_cast<AttributeStatistics<int32_t>>(result_statistics->column_statistics[3]);
  const auto scaled_histogram_c_y = column_statistics_c_y->histogram;
  EXPECT_EQ(scaled_histogram_c_y->total_count(), 64 * 2);
}

TEST_F(CardinalityEstimatorTest, JoinNumericEquiInnerMultiPredicates) {
  // For now, secondary join predicates are ignored for CardinalityEstimation

  // clang-format off
  const auto input_lqp =
  JoinNode::make(JoinMode::Inner, expression_vector(equals_(b_a, c_x), equals_(b_b, c_x)),
    node_b,
    node_c);
  // clang-format on

  const auto result_statistics = estimator.estimate_statistics(input_lqp);

  ASSERT_EQ(result_statistics->column_statistics.size(), 4u);
  ASSERT_EQ(result_statistics->row_count, 128u);
}

TEST_F(CardinalityEstimatorTest, JoinNumericNonEquiInner) {
  // Test that joins on with non-equi predicate conditions are estimated as cross joins (for now)

  // clang-format off
  const auto input_lqp_a = JoinNode::make(JoinMode::Inner, not_equals_(b_a, c_x), node_b, node_c);
  const auto input_lqp_b = JoinNode::make(JoinMode::Inner, greater_than_(b_a, c_x), node_b, node_c);
  const auto input_lqp_c = JoinNode::make(JoinMode::Inner, greater_than_equals_(b_a, c_x), node_b, node_c);
  const auto input_lqp_d = JoinNode::make(JoinMode::Inner, less_than_(b_a, c_x), node_b, node_c);
  const auto input_lqp_e = JoinNode::make(JoinMode::Inner, less_than_equals_(b_a, c_x), node_b, node_c);
  // clang-format on

  EXPECT_EQ(estimator.estimate_statistics(input_lqp_a)->row_count, 32u * 64u);
  EXPECT_EQ(estimator.estimate_statistics(input_lqp_a)->column_statistics.size(), 4u);
  EXPECT_EQ(estimator.estimate_statistics(input_lqp_b)->row_count, 32u * 64u);
  EXPECT_EQ(estimator.estimate_statistics(input_lqp_b)->column_statistics.size(), 4u);
  EXPECT_EQ(estimator.estimate_statistics(input_lqp_c)->row_count, 32u * 64u);
  EXPECT_EQ(estimator.estimate_statistics(input_lqp_c)->column_statistics.size(), 4u);
  EXPECT_EQ(estimator.estimate_statistics(input_lqp_d)->row_count, 32u * 64u);
  EXPECT_EQ(estimator.estimate_statistics(input_lqp_d)->column_statistics.size(), 4u);
  EXPECT_EQ(estimator.estimate_statistics(input_lqp_e)->row_count, 32u * 64u);
  EXPECT_EQ(estimator.estimate_statistics(input_lqp_e)->column_statistics.size(), 4u);
}

TEST_F(CardinalityEstimatorTest, JoinEquiInnerDifferentDataTypes) {
  // Test that joins on columns with non-equal data types are estimated as cross joins (for now)

  // clang-format off
  const auto input_lqp =
  JoinNode::make(JoinMode::Inner, equals_(b_a, f_b),
     node_b,
     node_f);
  // clang-format on

  const auto result_statistics = estimator.estimate_statistics(input_lqp);

  ASSERT_EQ(result_statistics->row_count, 32u * 200u);
  ASSERT_EQ(result_statistics->column_statistics.size(), 4u);
}

TEST_F(CardinalityEstimatorTest, JoinCross) {
  // clang-format off
  const auto input_lqp =
  JoinNode::make(JoinMode::Cross,
    node_b,
    node_c);
  // clang-format on

  const auto result_statistics = estimator.estimate_statistics(input_lqp);

  ASSERT_EQ(result_statistics->row_count, 32u * 64u);

  ASSERT_EQ(result_statistics->column_statistics.size(), 4u);

  const auto column_statistics_b_a =
      std::dynamic_pointer_cast<AttributeStatistics<int32_t>>(result_statistics->column_statistics.at(0));
  EXPECT_EQ(column_statistics_b_a->histogram->total_count(), 32u * 64u);

  const auto column_statistics_b_b =
      std::dynamic_pointer_cast<AttributeStatistics<int32_t>>(result_statistics->column_statistics.at(1));
  EXPECT_EQ(column_statistics_b_b->histogram->total_count(), 32u * 64u);

  const auto column_statistics_c_x =
      std::dynamic_pointer_cast<AttributeStatistics<int32_t>>(result_statistics->column_statistics.at(2));
  EXPECT_EQ(column_statistics_c_x->histogram->total_count(), 32u * 64u);

  const auto column_statistics_c_y =
      std::dynamic_pointer_cast<AttributeStatistics<int32_t>>(result_statistics->column_statistics.at(3));
  EXPECT_EQ(column_statistics_c_y->histogram->total_count(), 32u * 64u);
}

TEST_F(CardinalityEstimatorTest, JoinBinsInnerEqui) {
  EXPECT_FLOAT_EQ(CardinalityEstimator::estimate_inner_equi_join_of_bins(1.0f, 1.0f, 1.0f, 1.0f).first, 1.0f);
  EXPECT_FLOAT_EQ(CardinalityEstimator::estimate_inner_equi_join_of_bins(1.0f, 1.0f, 1.0f, 1.0f).second, 1.0f);

  EXPECT_FLOAT_EQ(CardinalityEstimator::estimate_inner_equi_join_of_bins(2.0f, 1.0f, 1.0f, 1.0f).first, 2.0f);
  EXPECT_FLOAT_EQ(CardinalityEstimator::estimate_inner_equi_join_of_bins(2.0f, 1.0f, 1.0f, 1.0f).second, 1.0f);

  EXPECT_FLOAT_EQ(CardinalityEstimator::estimate_inner_equi_join_of_bins(2.0f, 1.0f, 2.0f, 1.0f).first, 4.0f);
  EXPECT_FLOAT_EQ(CardinalityEstimator::estimate_inner_equi_join_of_bins(2.0f, 1.0f, 2.0f, 1.0f).second, 1.0f);

  EXPECT_FLOAT_EQ(CardinalityEstimator::estimate_inner_equi_join_of_bins(2.0f, 2.0f, 2.0f, 1.0f).first, 2.0f);
  EXPECT_FLOAT_EQ(CardinalityEstimator::estimate_inner_equi_join_of_bins(2.0f, 2.0f, 1.0f, 1.0f).second, 1.0f);

  EXPECT_FLOAT_EQ(CardinalityEstimator::estimate_inner_equi_join_of_bins(200.0f, 20.0f, 3000.0f, 2500.0f).first,
                  240.0f);
  EXPECT_FLOAT_EQ(CardinalityEstimator::estimate_inner_equi_join_of_bins(200.0f, 20.0f, 3000.0f, 2500.0f).second,
                  20.0f);

  // Test DistinctCount > Height
  EXPECT_FLOAT_EQ(CardinalityEstimator::estimate_inner_equi_join_of_bins(2.0f, 3.0f, 2.0f, 7.0f).first, 0.5714286f);
  EXPECT_FLOAT_EQ(CardinalityEstimator::estimate_inner_equi_join_of_bins(2.0f, 3.0f, 1.0f, 7.0f).second, 3.0f);

  // Test Heights/Distinct counts < 1
  EXPECT_FLOAT_EQ(CardinalityEstimator::estimate_inner_equi_join_of_bins(2.0f, 0.1f, 2.0f, 1.0f).first, 4.0f);
  EXPECT_FLOAT_EQ(CardinalityEstimator::estimate_inner_equi_join_of_bins(2.0f, 0.1f, 2.0f, 1.0f).second, 0.1f);

  EXPECT_FLOAT_EQ(CardinalityEstimator::estimate_inner_equi_join_of_bins(0.0f, 0.0f, 2.0f, 1.0f).first, 0.0f);
  EXPECT_FLOAT_EQ(CardinalityEstimator::estimate_inner_equi_join_of_bins(0.0f, 0.0f, 2.0f, 1.0f).second, 0.0f);

  EXPECT_FLOAT_EQ(CardinalityEstimator::estimate_inner_equi_join_of_bins(200.0f, 20.0f, 3000.0f, 0.1f).first, 30000.0f);
  EXPECT_FLOAT_EQ(CardinalityEstimator::estimate_inner_equi_join_of_bins(200.0f, 20.0f, 3000.0f, 0.1f).second, 0.1f);

  EXPECT_FLOAT_EQ(CardinalityEstimator::estimate_inner_equi_join_of_bins(200.0f, 1.0f, 0.3f, 0.3f).first, 60.0f);
  EXPECT_FLOAT_EQ(CardinalityEstimator::estimate_inner_equi_join_of_bins(200.0f, 1.0f, 0.3f, 0.3f).second, 0.3f);
}

TEST_F(CardinalityEstimatorTest, JoinInnerEquiHistograms) {
  const auto left_histogram = GenericHistogram<int32_t>(
      std::vector<int32_t>{0, 10, 20, 30, 40, 50, 60}, std::vector<int32_t>{9, 19, 29, 39, 49, 59, 69},
      std::vector<HistogramCountType>{10, 15, 10, 20, 5, 15, 5}, std::vector<HistogramCountType>{1, 1, 3, 8, 1, 5, 1});

  const auto right_histogram =
      GenericHistogram<int32_t>(std::vector<int32_t>{20, 30, 50}, std::vector<int32_t>{29, 39, 59},
                                std::vector<HistogramCountType>{10, 5, 10}, std::vector<HistogramCountType>{7, 2, 10});

  const auto join_histogram =
      CardinalityEstimator::estimate_inner_equi_join_with_histograms<int32_t>(left_histogram, right_histogram);

  ASSERT_EQ(join_histogram->bin_count(), 3u);

  EXPECT_EQ(join_histogram->bin_minimum(0), 20);
  EXPECT_EQ(join_histogram->bin_maximum(0), 29);
  EXPECT_FLOAT_EQ(join_histogram->bin_height(0), 10.f * 10.f * (1.f / 7.f));
  EXPECT_EQ(join_histogram->bin_distinct_count(0), 3u);

  EXPECT_EQ(join_histogram->bin_minimum(1), 30);
  EXPECT_EQ(join_histogram->bin_maximum(1), 39);
  EXPECT_FLOAT_EQ(join_histogram->bin_height(1), 20.f * 5.f * (1.f / 8.f));
  EXPECT_EQ(join_histogram->bin_distinct_count(1), 2u);

  EXPECT_EQ(join_histogram->bin_minimum(2), 50);
  EXPECT_EQ(join_histogram->bin_maximum(2), 59);
  EXPECT_FLOAT_EQ(join_histogram->bin_height(2), 15.f * 10.f * (1.f / 10.f));
  EXPECT_EQ(join_histogram->bin_distinct_count(2), 5u);
}

TEST_F(CardinalityEstimatorTest, JoinOuter) {
  // Test that left, right and full outer join operations are estimated the same as an inner join (for now)

  const auto inner_join_lqp = JoinNode::make(JoinMode::Inner, equals_(a_a, b_a), node_a, node_b);
  const auto inner_join_cardinality = estimator.estimate_cardinality(inner_join_lqp);

  const auto left_join_lqp = JoinNode::make(JoinMode::Left, equals_(a_a, b_a), node_a, node_b);
  EXPECT_EQ(estimator.estimate_cardinality(left_join_lqp), inner_join_cardinality);

  const auto right_join_lqp = JoinNode::make(JoinMode::Right, equals_(a_a, b_a), node_a, node_b);
  EXPECT_EQ(estimator.estimate_cardinality(right_join_lqp), inner_join_cardinality);

  const auto full_join_lqp = JoinNode::make(JoinMode::FullOuter, equals_(a_a, b_a), node_a, node_b);
  EXPECT_EQ(estimator.estimate_cardinality(left_join_lqp), inner_join_cardinality);
}

TEST_F(CardinalityEstimatorTest, JoinSemiHistograms) {
  const auto left_join_column_histogram = std::make_shared<GenericHistogram<int32_t>>(
      std::vector<int32_t>{0, 10, 20, 30, 40, 50, 60}, std::vector<int32_t>{9, 19, 29, 39, 49, 59, 69},
      std::vector<HistogramCountType>{10, 15, 10, 20, 5, 15, 5}, std::vector<HistogramCountType>{1, 1, 3, 8, 1, 6, 1});
  const auto left_join_column_statistics = std::make_shared<AttributeStatistics<int32_t>>();
  left_join_column_statistics->set_statistics_object(left_join_column_histogram);

  const auto left_non_join_column_histogram = std::make_shared<GenericHistogram<int32_t>>(
      std::vector<int32_t>{0, 5, 10}, std::vector<int32_t>{4, 9, 14}, std::vector<HistogramCountType>{20, 40, 30},
      std::vector<HistogramCountType>{1, 1, 3});
  const auto left_non_join_column_statistics = std::make_shared<AttributeStatistics<int32_t>>();
  left_non_join_column_statistics->set_statistics_object(left_non_join_column_histogram);

  const auto right_histogram = std::make_shared<GenericHistogram<int32_t>>(
      std::vector<int32_t>{20, 30, 50, 70}, std::vector<int32_t>{29, 39, 69, 79},
      std::vector<HistogramCountType>{10, 5, 10, 8}, std::vector<HistogramCountType>{7, 2, 6, 8});
  const auto right_statistics = std::make_shared<AttributeStatistics<int32_t>>();
  right_statistics->set_statistics_object(right_histogram);

  const auto left_table_statistics =
      TableStatistics{{left_join_column_statistics, left_non_join_column_statistics}, 90};
  const auto right_table_statistics = TableStatistics{{right_statistics}, 33};

  const auto join_estimation =
      CardinalityEstimator::estimate_semi_join(ColumnID{0}, ColumnID{0}, left_table_statistics, right_table_statistics);

  // Left Join Column Histogram:  |  Right Join Column Histogram:  |  Resulting Histogram
  //                              |                                |
  // Bin       Height  Distinct   |  Bin       Height  Distinct    |  Bin       Height  Distinct  Comment
  // [ 0,  9]  10      1          |                                |
  // [10, 19]  15      1          |                                |
  // [20, 29]  10      3          |  [20, 29]  (10)    7           |  [20, 29]  10      3         100% as 3 <= 7
  // [30, 39]  20      8          |  [30, 39]  (5)     2           |  [30, 39]  5       2         h: 20*(2/8)
  // [40, 49]   5      1          |                                |
  // [50, 59]  15      6          |  [50,                          |  [50, 59]  7.5     3         h: 15*((6/2)/6)
  // [60, 69]   5      1          |       69]  (10)    6           |  [69, 69]  5       1         100% as 1 <= (6/2)
  //                              |  [70, 79]  (8)     8           |
  //                              |                                |
  //                              |  (Height is ignored on right)  |      sum:  27.5

  EXPECT_EQ(join_estimation->row_count, 27.5);
  EXPECT_EQ(join_estimation->column_statistics.size(), 2);

  const auto& first_column_histogram =
      *static_cast<const AttributeStatistics<int32_t>&>(*join_estimation->column_statistics[0]).histogram;
  EXPECT_EQ(first_column_histogram.bin_count(), 4);
  EXPECT_EQ(first_column_histogram.bin(0), HistogramBin<int32_t>(20, 29, 10, 3));
  EXPECT_EQ(first_column_histogram.bin(1), HistogramBin<int32_t>(30, 39, 5, 2));
  EXPECT_EQ(first_column_histogram.bin(2), HistogramBin<int32_t>(50, 59, 7.5, 3));
  EXPECT_EQ(first_column_histogram.bin(3), HistogramBin<int32_t>(60, 69, 5, 1));

  const auto& second_column_histogram =
      *static_cast<const AttributeStatistics<int32_t>&>(*join_estimation->column_statistics[1]).histogram;
  EXPECT_EQ(second_column_histogram.bin_count(), 3);
  const auto selectivity = 27.5f / 90;
  EXPECT_EQ(second_column_histogram.bin(0), HistogramBin<int32_t>(0, 4, 20 * selectivity, 1));
  EXPECT_EQ(second_column_histogram.bin(1), HistogramBin<int32_t>(5, 9, 40 * selectivity, 1));
  EXPECT_EQ(second_column_histogram.bin(2), HistogramBin<int32_t>(10, 14, 30 * selectivity, 3));
}

TEST_F(CardinalityEstimatorTest, JoinAnti) {
  // Test that anti joins are estimated return the left input statistics (for now)

  const auto anti_null_as_false_join_lqp = JoinNode::make(JoinMode::AntiNullAsFalse, equals_(a_a, b_a), node_a, node_b);
  EXPECT_EQ(estimator.estimate_statistics(anti_null_as_false_join_lqp), node_a->table_statistics());

  const auto anti_null_as_true_join_lqp = JoinNode::make(JoinMode::AntiNullAsTrue, equals_(a_a, b_a), node_a, node_b);
  EXPECT_EQ(estimator.estimate_statistics(anti_null_as_true_join_lqp), node_a->table_statistics());
}

TEST_F(CardinalityEstimatorTest, LimitWithValueExpression) {
  const auto limit_lqp_a = LimitNode::make(value_(1), node_a);
  EXPECT_EQ(estimator.estimate_cardinality(limit_lqp_a), 1);

  const auto limit_statistics_a = estimator.estimate_statistics(limit_lqp_a);

  EXPECT_EQ(limit_statistics_a->row_count, 1);
  ASSERT_EQ(limit_statistics_a->column_statistics.size(), 2u);

  const auto column_statistics_a =
      std::dynamic_pointer_cast<AttributeStatistics<int32_t>>(limit_statistics_a->column_statistics.at(0));
  const auto column_statistics_b =
      std::dynamic_pointer_cast<AttributeStatistics<int32_t>>(limit_statistics_a->column_statistics.at(1));

  // Limit doesn't write out StatisticsObjects
  ASSERT_TRUE(column_statistics_a);
  EXPECT_FALSE(column_statistics_a->histogram);
  ASSERT_TRUE(column_statistics_b);
  EXPECT_FALSE(column_statistics_b->histogram);
}

TEST_F(CardinalityEstimatorTest, LimitWithValueExpressionExeedingInputRowCount) {
  const auto limit_lqp_a = LimitNode::make(value_(1000), node_a);
  EXPECT_EQ(estimator.estimate_cardinality(limit_lqp_a), 100);

  const auto limit_statistics_a = estimator.estimate_statistics(limit_lqp_a);

  EXPECT_EQ(limit_statistics_a->row_count, 100);
}

TEST_F(CardinalityEstimatorTest, LimitWithComplexExpression) {
  const auto limit_lqp_a = LimitNode::make(add_(1, 2), node_a);
  // The "complex" expression `1+2` is evaluated and LimitNode is estimated to have a selectivity of 1
  EXPECT_EQ(estimator.estimate_cardinality(limit_lqp_a), 100);
  EXPECT_EQ(estimator.estimate_statistics(limit_lqp_a), node_a->table_statistics());
}

TEST_F(CardinalityEstimatorTest, MockNode) {
  EXPECT_EQ(estimator.estimate_cardinality(node_a), 100);
  EXPECT_EQ(estimator.estimate_statistics(node_a), node_a->table_statistics());
}

TEST_F(CardinalityEstimatorTest, PredicateWithOneSimplePredicate) {
  // clang-format off
  const auto input_lqp =
  PredicateNode::make(greater_than_(a_a, 50),
    node_a);
  // clang-format on

  EXPECT_FLOAT_EQ(estimator.estimate_cardinality(input_lqp), 50.0f);

  const auto plan_output_statistics = estimator.estimate_statistics(input_lqp);
  EXPECT_FLOAT_EQ(plan_output_statistics->row_count, 50.0f);  // Same as above
  ASSERT_EQ(plan_output_statistics->column_statistics.size(), 2u);

  const auto plan_output_statistics_a =
      std::dynamic_pointer_cast<AttributeStatistics<int32_t>>(plan_output_statistics->column_statistics.at(0));
  const auto plan_output_statistics_b =
      std::dynamic_pointer_cast<AttributeStatistics<int32_t>>(plan_output_statistics->column_statistics.at(1));
  ASSERT_TRUE(plan_output_statistics_a);
  ASSERT_TRUE(plan_output_statistics_b);

  ASSERT_TRUE(plan_output_statistics_a->histogram);
  ASSERT_TRUE(plan_output_statistics_b->histogram);

  ASSERT_EQ(plan_output_statistics_a->histogram->bin_count(), 1u);
  EXPECT_EQ(plan_output_statistics_a->histogram->bin_minimum(BinID{0}), 51);
  EXPECT_EQ(plan_output_statistics_a->histogram->bin_maximum(BinID{0}), 100);
  EXPECT_EQ(plan_output_statistics_a->histogram->bin_height(BinID{0}), 50);

  ASSERT_EQ(plan_output_statistics_b->histogram->bin_count(), 1u);
  EXPECT_EQ(plan_output_statistics_b->histogram->bin_minimum(BinID{0}), 10);
  EXPECT_EQ(plan_output_statistics_b->histogram->bin_maximum(BinID{0}), 129);
  EXPECT_EQ(plan_output_statistics_b->histogram->bin_height(BinID{0}), 35);
}

TEST_F(CardinalityEstimatorTest, PredicateWithOneBetweenPredicate) {
  for (const auto between_predicate_condition :
       {PredicateCondition::BetweenInclusive, PredicateCondition::BetweenLowerExclusive,
        PredicateCondition::BetweenUpperExclusive, PredicateCondition::BetweenExclusive}) {
    const auto between_predicate =
        std::make_shared<BetweenExpression>(between_predicate_condition, a_a, value_(10), value_(89));

    // clang-format off
    const auto input_lqp =
      PredicateNode::make(between_predicate,
        node_a);
    // clang-format on

    EXPECT_FLOAT_EQ(estimator.estimate_cardinality(input_lqp), 80.0f);

    const auto plan_output_statistics = estimator.estimate_statistics(input_lqp);
    EXPECT_FLOAT_EQ(plan_output_statistics->row_count, 80.0f);  // Same as above
    ASSERT_EQ(plan_output_statistics->column_statistics.size(), 2u);

    const auto plan_output_statistics_a =
        std::dynamic_pointer_cast<AttributeStatistics<int32_t>>(plan_output_statistics->column_statistics.at(0));
    const auto plan_output_statistics_b =
        std::dynamic_pointer_cast<AttributeStatistics<int32_t>>(plan_output_statistics->column_statistics.at(1));
    ASSERT_TRUE(plan_output_statistics_a);
    ASSERT_TRUE(plan_output_statistics_b);

    ASSERT_TRUE(plan_output_statistics_a->histogram);
    ASSERT_TRUE(plan_output_statistics_b->histogram);

    ASSERT_EQ(plan_output_statistics_a->histogram->bin_count(), 1u);
    EXPECT_EQ(plan_output_statistics_a->histogram->bin_minimum(BinID{0}), 10);
    EXPECT_EQ(plan_output_statistics_a->histogram->bin_maximum(BinID{0}), 89);
    EXPECT_EQ(plan_output_statistics_a->histogram->bin_height(BinID{0}), 80);
  }
}

TEST_F(CardinalityEstimatorTest, PredicateTwoOnTheSameColumn) {
  // clang-format off
  const auto input_lqp =
  PredicateNode::make(greater_than_(a_a, 50),
    PredicateNode::make(less_than_equals_(a_a, 75),
      node_a));
  // clang-format on

  EXPECT_FLOAT_EQ(estimator.estimate_cardinality(input_lqp), 25);
}

TEST_F(CardinalityEstimatorTest, PredicateAnd) {
  // Same as PredicateTwoOnTheSameColumn, but the conditions are within one predicate
  // clang-format off
  const auto input_lqp =
  PredicateNode::make(and_(greater_than_(a_a, 50), less_than_equals_(a_a, 75)),
      node_a);
  // clang-format on

  EXPECT_FLOAT_EQ(estimator.estimate_cardinality(input_lqp), 25);
}

TEST_F(CardinalityEstimatorTest, PredicateOr) {
  // clang-format off
  const auto input_lqp =
  PredicateNode::make(or_(less_than_equals_(a_a, 10), greater_than_(a_a, 90)),
      node_a);
  // clang-format on

  EXPECT_FLOAT_EQ(estimator.estimate_cardinality(input_lqp), 20);
}

TEST_F(CardinalityEstimatorTest, PredicateOrDoesNotIncreaseCardinality) {
  // While we do not handle overlapping ranges yet, we at least want to make sure that tables don't become bigger.
  // clang-format off
  const auto input_lqp =
  PredicateNode::make(or_(less_than_equals_(a_a, 60), greater_than_(a_a, 20)),
      node_a);
  // clang-format on

  EXPECT_FLOAT_EQ(estimator.estimate_cardinality(input_lqp), 100);
}

TEST_F(CardinalityEstimatorTest, PredicateIn) {
  // clang-format off
  const auto input_lqp =
  PredicateNode::make(in_(a_a, list_(10, 11, 12, 13)),
      node_a);
  // clang-format on

  EXPECT_FLOAT_EQ(estimator.estimate_cardinality(input_lqp), 40);
}

TEST_F(CardinalityEstimatorTest, PredicateTwoOnDifferentColumns) {
  // clang-format off
  const auto input_lqp =
  // 50% of rows in histogram, which itself covers 100% of rows in the table, leads to a selectivity of 0.5 * 1 = 0.5
  PredicateNode::make(greater_than_(a_a, 50),
    // 55% of rows in histogram, which itself covers 70% of rows in the table,
    // leads to a selectivity of 0.55*0.7 = 0.385
    PredicateNode::make(less_than_equals_(a_b, 75),
    node_a));
  // clang-format on

  EXPECT_FLOAT_EQ(estimator.estimate_cardinality(input_lqp), 19.25f);
  EXPECT_FLOAT_EQ(estimator.estimate_cardinality(input_lqp->left_input()), 38.5f);
  EXPECT_FLOAT_EQ(estimator.estimate_cardinality(input_lqp->left_input()->left_input()), 100.0f);
}

TEST_F(CardinalityEstimatorTest, PredicateMultiple) {
  // clang-format off
  const auto input_lqp =
  PredicateNode::make(equals_(d_a, 95),
    PredicateNode::make(greater_than_(d_b, 55),
      PredicateNode::make(greater_than_(d_b, 40),
        PredicateNode::make(greater_than_equals_(d_a, 90),
          PredicateNode::make(less_than_(d_c, 500),
            node_d)))));
  // clang-format on

  EXPECT_FLOAT_EQ(estimator.estimate_cardinality(input_lqp), 1.0f);
  EXPECT_FLOAT_EQ(estimator.estimate_cardinality(input_lqp->left_input()), 2.1623178f);
  EXPECT_FLOAT_EQ(estimator.estimate_cardinality(input_lqp->left_input()->left_input()), 4.7571f);
  EXPECT_FLOAT_EQ(estimator.estimate_cardinality(input_lqp->left_input()->left_input()->left_input()), 4.7571f);
  EXPECT_FLOAT_EQ(estimator.estimate_cardinality(input_lqp->left_input()->left_input()->left_input()->left_input()),
                  39.3542f);
}

TEST_F(CardinalityEstimatorTest, PredicateWithValuePlaceholder) {
  // 20 distinct values in column d_a and 100 values total. So == is assumed to have a selectivity of 5%, != of 95%, and
  // everything else is assumed to hit 50%

  const auto lqp_a = PredicateNode::make(equals_(d_a, placeholder_(ParameterID{0})), node_d);
  EXPECT_FLOAT_EQ(estimator.estimate_cardinality(lqp_a), 5.0f);

  const auto lqp_b = PredicateNode::make(not_equals_(d_a, placeholder_(ParameterID{0})), node_d);
  EXPECT_FLOAT_EQ(estimator.estimate_cardinality(lqp_b), 95.0f);

  const auto lqp_c = PredicateNode::make(less_than_(d_a, placeholder_(ParameterID{0})), node_d);
  EXPECT_FLOAT_EQ(estimator.estimate_cardinality(lqp_c), 50.0f);

  const auto lqp_d = PredicateNode::make(greater_than_(d_a, placeholder_(ParameterID{0})), node_d);
  EXPECT_FLOAT_EQ(estimator.estimate_cardinality(lqp_d), 50.0f);

  // BETWEEN is split up into (a >= ? AND a <= ?), so it ends up with a selecitivity of 25%
  const auto lqp_e =
      PredicateNode::make(between_inclusive_(d_a, placeholder_(ParameterID{0}), placeholder_(ParameterID{1})), node_d);
  EXPECT_FLOAT_EQ(estimator.estimate_cardinality(lqp_e), 25.0f);
}

TEST_F(CardinalityEstimatorTest, PredicateMultipleWithCorrelatedParameter) {
  // clang-format off
  const auto input_lqp =
  PredicateNode::make(greater_than_(a_a, 50),  // s=0.5
    PredicateNode::make(less_than_equals_(a_b, correlated_parameter_(ParameterID{1}, a_a)),
      node_a));
  // clang-format on

  EXPECT_FLOAT_EQ(estimator.estimate_cardinality(input_lqp), 45.0f);
  EXPECT_FLOAT_EQ(estimator.estimate_cardinality(input_lqp->left_input()), 90.0f);
  EXPECT_FLOAT_EQ(estimator.estimate_cardinality(input_lqp->left_input()->left_input()), 100.0f);
}

TEST_F(CardinalityEstimatorTest, PredicateWithNull) {
  const auto lqp_a = PredicateNode::make(equals_(a_a, NullValue{}), node_a);
  EXPECT_FLOAT_EQ(estimator.estimate_cardinality(lqp_a), 0.0f);

  const auto lqp_b = PredicateNode::make(like_(g_a, NullValue{}), node_g);
  EXPECT_FLOAT_EQ(estimator.estimate_cardinality(lqp_b), 0.0f);

  const auto lqp_c = PredicateNode::make(between_inclusive_(a_a, 5, NullValue{}), node_a);
  EXPECT_FLOAT_EQ(estimator.estimate_cardinality(lqp_c), 0.0f);
}

TEST_F(CardinalityEstimatorTest, PredicateEstimateColumnVsColumnEquiScan) {
  // clang-format off
  const auto left_histogram = GenericHistogram<int32_t>(
    std::vector<int32_t>           {10, 13, 16},
    std::vector<int32_t>           {12, 14, 20},
    std::vector<HistogramCountType>{3,   9, 10},
    std::vector<HistogramCountType>{2,   3, 10});

  const auto right_histogram = GenericHistogram<int32_t>(
    std::vector<int32_t>           {0, 13, 15, 16},
    std::vector<int32_t>           {5, 14, 15, 20},
    std::vector<HistogramCountType>{7,  5, 1,  10},
    std::vector<HistogramCountType>{5,  2, 1,   2});
  // clang-format on

  const auto result_histogram =
      CardinalityEstimator::estimate_column_vs_column_equi_scan_with_histograms(left_histogram, right_histogram);

  ASSERT_EQ(result_histogram->bin_count(), 2u);
  EXPECT_EQ(result_histogram->bin(BinID{0}), HistogramBin<int32_t>(13, 14, 5, 2));
  EXPECT_EQ(result_histogram->bin(BinID{1}), HistogramBin<int32_t>(16, 20, 10, 2));
}

TEST_F(CardinalityEstimatorTest, PredicateEstimateColumnVsColumnNonEquiScan) {
  // Test that a selectivity of 1 is used for ColumnVsColumn scans with a non-equals PredicateCondition

  EXPECT_EQ(estimator.estimate_cardinality(PredicateNode::make(not_equals_(a_a, a_b), node_a)), 100);
  EXPECT_EQ(estimator.estimate_cardinality(PredicateNode::make(greater_than_(a_a, a_b), node_a)), 100);
  EXPECT_EQ(estimator.estimate_cardinality(PredicateNode::make(greater_than_equals_(a_a, a_b), node_a)), 100);
  EXPECT_EQ(estimator.estimate_cardinality(PredicateNode::make(less_than_(a_a, a_b), node_a)), 100);
  EXPECT_EQ(estimator.estimate_cardinality(PredicateNode::make(less_than_equals_(a_a, a_b), node_a)), 100);
}

TEST_F(CardinalityEstimatorTest, PredicateColumnVsColumnDifferentDataTypes) {
  // Test that a selectivity of 1 is used for ColumnVsColumn scans on columns with differing column data types

  // clang-format off
  const auto input_lqp =
  PredicateNode::make(equals_(f_a, f_b),
    node_f);
  // clang-format on

  EXPECT_FLOAT_EQ(estimator.estimate_cardinality(input_lqp), 200.0f);

  const auto estimated_statistics = estimator.estimate_statistics(input_lqp);

  const auto estimated_column_statistics_a =
      std::dynamic_pointer_cast<AttributeStatistics<int32_t>>(estimated_statistics->column_statistics.at(0));
  const auto estimated_column_statistics_b =
      std::dynamic_pointer_cast<AttributeStatistics<float>>(estimated_statistics->column_statistics.at(1));

  ASSERT_TRUE(estimated_column_statistics_a);
  ASSERT_TRUE(estimated_column_statistics_b);

  EXPECT_TRUE(estimated_column_statistics_a->histogram);
  EXPECT_TRUE(estimated_column_statistics_b->histogram);
}

TEST_F(CardinalityEstimatorTest, PredicateWithMissingStatistics) {
  // Test that a node, lacking statistical information on one column, produces an estimation when scanning on the column
  // WITH statistics and has a selectivity of 1 on columns WITHOUT statistics

  // clang-format off
  const auto input_lqp_a =
  PredicateNode::make(greater_than_(e_a, 50),
    node_e);

  const auto input_lqp_b =
  PredicateNode::make(greater_than_(e_b, 50),
    node_e);
  // clang-format on

  EXPECT_FLOAT_EQ(estimator.estimate_cardinality(input_lqp_a), 5.0f);
  EXPECT_FLOAT_EQ(estimator.estimate_cardinality(input_lqp_b), 100.0f);

  const auto estimated_statistics_a = estimator.estimate_statistics(input_lqp_a);
  const auto estimated_statistics_b = estimator.estimate_statistics(input_lqp_a);

  const auto estimated_column_statistics_a_a =
      std::dynamic_pointer_cast<AttributeStatistics<int32_t>>(estimated_statistics_a->column_statistics.at(0));
  const auto estimated_column_statistics_a_b =
      std::dynamic_pointer_cast<AttributeStatistics<int32_t>>(estimated_statistics_a->column_statistics.at(1));
  const auto estimated_column_statistics_b_a =
      std::dynamic_pointer_cast<AttributeStatistics<int32_t>>(estimated_statistics_b->column_statistics.at(0));
  const auto estimated_column_statistics_b_b =
      std::dynamic_pointer_cast<AttributeStatistics<int32_t>>(estimated_statistics_b->column_statistics.at(1));

  ASSERT_TRUE(estimated_column_statistics_a_a);
  ASSERT_TRUE(estimated_column_statistics_a_b);
  ASSERT_TRUE(estimated_column_statistics_b_a);
  ASSERT_TRUE(estimated_column_statistics_b_b);

  EXPECT_TRUE(estimated_column_statistics_a_a->histogram);
  EXPECT_FALSE(estimated_column_statistics_a_b->histogram);
  EXPECT_TRUE(estimated_column_statistics_b_a->histogram);
  EXPECT_FALSE(estimated_column_statistics_b_b->histogram);
}

TEST_F(CardinalityEstimatorTest, PredicateString) {
  const auto input_lqp_a = PredicateNode::make(equals_(g_a, "a"), node_g);
  EXPECT_FLOAT_EQ(estimator.estimate_cardinality(input_lqp_a), 2.5f);

  const auto input_lqp_b = PredicateNode::make(equals_(g_a, "z"), node_g);
  EXPECT_FLOAT_EQ(estimator.estimate_cardinality(input_lqp_b), 2.5f);

  const auto input_lqp_c = PredicateNode::make(greater_than_equals_(g_a, "a"), node_g);
  EXPECT_FLOAT_EQ(estimator.estimate_cardinality(input_lqp_c), 100.0f);

  const auto input_lqp_d = PredicateNode::make(greater_than_equals_(g_a, "m"), node_g);
  EXPECT_FLOAT_EQ(estimator.estimate_cardinality(input_lqp_d), 52.0f);

  const auto input_lqp_e = PredicateNode::make(like_(g_a, "a%"), node_g);
  EXPECT_FLOAT_EQ(estimator.estimate_cardinality(input_lqp_e), 10.0f);

  const auto input_lqp_f = PredicateNode::make(not_like_(g_a, "a%"), node_g);
  EXPECT_FLOAT_EQ(estimator.estimate_cardinality(input_lqp_f), 90.0f);
}

TEST_F(CardinalityEstimatorTest, Projection) {
  // clang-format off
  const auto input_lqp =
  ProjectionNode::make(expression_vector(a_b, add_(a_b, a_a), a_a),
    node_a);
  // clang-format on

  const auto input_table_statistics = node_a->table_statistics();
  const auto result_table_statistics = estimator.estimate_statistics(input_lqp);

  EXPECT_EQ(result_table_statistics->row_count, 100u);
  ASSERT_EQ(result_table_statistics->column_statistics.size(), 3u);
  EXPECT_EQ(result_table_statistics->column_statistics.at(0), input_table_statistics->column_statistics.at(1));
  EXPECT_TRUE(result_table_statistics->column_statistics.at(1));
  EXPECT_EQ(result_table_statistics->column_statistics.at(2), input_table_statistics->column_statistics.at(0));
}

TEST_F(CardinalityEstimatorTest, Sort) {
  // clang-format off
  const auto input_lqp =
  SortNode::make(expression_vector(a_b), std::vector<SortMode>{SortMode::Ascending},
                 node_a);
  // clang-format on

  const auto result_table_statistics = estimator.estimate_statistics(input_lqp);
  EXPECT_EQ(result_table_statistics, node_a->table_statistics());
}

TEST_F(CardinalityEstimatorTest, StoredTable) {
  Hyrise::get().storage_manager.add_table("t", load_table("resources/test_data/tbl/int.tbl"));
  EXPECT_EQ(estimator.estimate_cardinality(StoredTableNode::make("t")), 3);
}

TEST_F(CardinalityEstimatorTest, Validate) {
  // Test Validate doesn't break the TableStatistics. The CardinalityEstimator is not estimating anything for Validate
  // as there are no statistics available atm to base such an estimation on.

  // clang-format off
  const auto input_lqp =
  ValidateNode::make(
    node_a);
  // clang-format on

  const auto input_table_statistics = node_a->table_statistics();
  const auto result_table_statistics = estimator.estimate_statistics(input_lqp);

  EXPECT_EQ(result_table_statistics->row_count, 100u);
  ASSERT_EQ(result_table_statistics->column_statistics.size(), 2u);
}

TEST_F(CardinalityEstimatorTest, Union) {
  // Test that UnionNodes sum up the input row counts and return the left input statistics (for now)

  // clang-format off
  const auto input_lqp =
  UnionNode::make(SetOperationMode::Positions,
    node_a,
    node_b);
  // clang-format on

  EXPECT_FLOAT_EQ(estimator.estimate_cardinality(input_lqp), 132.0f);

  const auto result_statistics = estimator.estimate_statistics(input_lqp);

  ASSERT_EQ(result_statistics->column_statistics.size(), 2u);
  ASSERT_EQ(result_statistics->column_statistics.at(0), node_a->table_statistics()->column_statistics.at(0));
  ASSERT_EQ(result_statistics->column_statistics.at(1), node_a->table_statistics()->column_statistics.at(1));
}

TEST_F(CardinalityEstimatorTest, NonQueryNodes) {
  // Test that, basically, the CardinalityEstimator doesn't crash when processing non-query nodes. There is not much
  // more to test here

  const auto create_table_lqp = CreateTableNode::make("t", false, node_a);
  EXPECT_EQ(estimator.estimate_cardinality(create_table_lqp), 0.0f);

  const auto prepared_plan = std::make_shared<PreparedPlan>(node_a, std::vector<ParameterID>{});
  const auto create_prepared_plan_lqp = CreatePreparedPlanNode::make("t", prepared_plan);
  EXPECT_EQ(estimator.estimate_cardinality(create_prepared_plan_lqp), 0.0f);

  const auto lqp_view = std::make_shared<LQPView>(
      node_a, std::unordered_map<ColumnID, std::string>{{ColumnID{0}, "x"}, {ColumnID{1}, "y"}});
  const auto create_view_lqp = CreateViewNode::make("v", lqp_view, false);
  EXPECT_EQ(estimator.estimate_cardinality(create_view_lqp), 0.0f);

  const auto update_lqp = UpdateNode::make("t", node_a, node_b);
  EXPECT_EQ(estimator.estimate_cardinality(update_lqp), 0.0f);

  const auto insert_lqp = InsertNode::make("t", node_a);
  EXPECT_EQ(estimator.estimate_cardinality(insert_lqp), 0.0f);

  EXPECT_EQ(estimator.estimate_cardinality(DeleteNode::make(node_a)), 0.0f);
  EXPECT_EQ(estimator.estimate_cardinality(DropViewNode::make("v", false)), 0.0f);
  EXPECT_EQ(estimator.estimate_cardinality(DropTableNode::make("t", false)), 0.0f);
  EXPECT_EQ(estimator.estimate_cardinality(DummyTableNode::make()), 0.0f);
}

}  // namespace hyrise


text:
	<title>www.redips.net - Reading multiple parameters from URL</title>

	Query string

	<?php print($_SERVER['QUERY_STRING']) ?>

	Accepted parameters:

	<?php
		// accept parameters (p is array)
		$arr = $_REQUEST['p'];
		// open loop through each array element
		foreach ($arr as $p){
			// detach values from each parameter
			list($id, $row, $cell) = explode('_', $p);
			// instead of print, you can store accepted parameteres to the database
			print "Id=$id Row=$row Cell=$cell
";
		}
	?>


text:
/* receiver.c */

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

/*
	File Naming information.
	------------------------
	Files that end with:
		_B : Is a file that contains a benchmark function
		_R : Is a file that contains the receiver task
			 of a benchmark function
 */

#include "receiver.h"

char data_recv[OCTET_TO_SIZEOFUNIT(MESSAGE_SIZE)] = { 0 };

void dequtask(void);
void waittask(void);
void mailrecvtask(void);
void piperecvtask(void);

/**
 *
 * @brief Main function of the task that receives data in the test
 *
 * @return N/A
 */
void recvtask(void)
{
	/* order must be compatible with master.c ! */
#ifdef FIFO_BENCH
	task_sem_take(STARTRCV, TICKS_UNLIMITED);
	dequtask();
#endif
#ifdef SEMA_BENCH
	task_sem_take(STARTRCV, TICKS_UNLIMITED);
	waittask();
#endif
#ifdef MAILBOX_BENCH
	task_sem_take(STARTRCV, TICKS_UNLIMITED);
	mailrecvtask();
#endif
#ifdef PIPE_BENCH
	task_sem_take(STARTRCV, TICKS_UNLIMITED);
	piperecvtask();
#endif
}