text:
<?xml version="1.0" encoding="UTF-8"?>
<catalog>
  <Weapon id="StdWeapon">
    <UIName value="Arme standard qui pue"/>
    <EffectLink value="StdDoubleShot"/>
    <Range value="5"/>
    <ScanRange value="7"/>
    <Period value="5"/>
  </Weapon>
  <Weapon id="MeleeWeapon">
    <UIName value="attaque au corps a corps"/>
    <EffectLink value="StdDamage"/>
    <Range value="0.1"/>
    <ScanRange value="5"/>
    <Period value="4"/>
  </Weapon>
  <Weapon id="Rifle">
    <UIName value="fusil standard"/>
    <EffectLink value="StdDamage"/>
    <Range value="5"/>
    <ScanRange value="5"/>
    <Period value="4"/>
  </Weapon>
  <Weapon id="Battery">
    <UIName value="battery de missile"/>
    <EffectLink value="StdLauncher"/>
    <Range value="6"/>
    <ScanRange value="8"/>
    <Period value="0.5"/>
  </Weapon>
</catalog>


text:
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
    <meta name="description" content="" />
    <meta name="keywords" content="" />
    <title class="lift:Menu.title">App: </title>

    <link rel="stylesheet" type="text/css" href="static/js/markitup-1.x/markitup/skins/markitup/style.css" />

    <link rel="stylesheet" type="text/css" href="static/js/markitup-1.x/markitup/sets/html/style.css" />

Scala Blog

The main content will get bound here

            Lift
            is Copyright 2007-2011 WorldWide Conferencing, LLC.
            Distributed under an Apache 2.0 License.

            SB
            is distributed under an Apache 2.0 License.

redpajama_set_name: RedPajamaGithub


text:
import baseKeys from './_baseKeys.js';
import getTag from './_getTag.js';
import isArrayLike from './isArrayLike.js';
import isString from './isString.js';
import stringSize from './_stringSize.js';

/** `Object#toString` result references. */
var mapTag = '[object Map]',
    setTag = '[object Set]';

/**
 * Gets the size of `collection` by returning its length for array-like
 * values or the number of own enumerable string keyed properties for objects.
 *
 * @static
 * @memberOf _
 * @since 0.1.0
 * @category Collection
 * @param {Array|Object|string} collection The collection to inspect.
 * @returns {number} Returns the collection size.
 * @example
 *
 * _.size([1, 2, 3]);
 * // => 3
 *
 * _.size({ 'a': 1, 'b': 2 });
 * // => 2
 *
 * _.size('pebbles');
 * // => 7
 */
function size(collection) {
  if (collection == null) {
    return 0;
  }
  if (isArrayLike(collection)) {
    return isString(collection) ? stringSize(collection) : collection.length;
  }
  var tag = getTag(collection);
  if (tag == mapTag || tag == setTag) {
    return collection.size;
  }
  return baseKeys(collection).length;
}

export default size;


text:
package io.hackitaly.jmusixmatch;

import io.hackitaly.jmusixmatch.config.Constants;
import io.hackitaly.jmusixmatch.config.Methods;
import io.hackitaly.jmusixmatch.config.StatusCode;
import io.hackitaly.jmusixmatch.entity.error.ErrorMessage;
import io.hackitaly.jmusixmatch.entity.lyrics.Lyrics;
import io.hackitaly.jmusixmatch.entity.lyrics.get.LyricsGetMessage;
import io.hackitaly.jmusixmatch.entity.track.Track;
import io.hackitaly.jmusixmatch.entity.track.TrackData;
import io.hackitaly.jmusixmatch.entity.track.get.TrackGetMessage;
import io.hackitaly.jmusixmatch.entity.track.search.TrackSeachMessage;
import io.hackitaly.jmusixmatch.http.MusixMatchRequest;

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

import com.google.gson.Gson;
import com.google.gson.JsonParseException;

public class MusixMatch {

	/**
	 * A musiXmatch API Key.
	 */
	private final String apiKey;

	/**
	 * MusixMatch Constructor with API-Key.
	 *
	 * @param apiKey
	 *            A musiXmatch API Key.
	 */
	public MusixMatch(String apiKey) {
		this.apiKey = apiKey;
	}

	/**
	 * Get Lyrics for the specific trackID.
	 *
	 * @param trackID
	 * @return
	 * @throws MusixMatchException
	 */
	public Lyrics getLyrics(int trackID) throws MusixMatchException {
		Lyrics lyrics = null;
		LyricsGetMessage message = null;
		Map<String, Object> params = new HashMap<String, Object>();

		params.put(Constants.API_KEY, apiKey);
		params.put(Constants.TRACK_ID, new String("" + trackID));

		String response = null;

		response = MusixMatchRequest.sendRequest(Helper.getURLString(
				Methods.TRACK_LYRICS_GET, params));

		Gson gson = new Gson();

		try {
			message = gson.fromJson(response, LyricsGetMessage.class);
		} catch (JsonParseException jpe) {
			handleErrorResponse(response);
		}

		lyrics = message.getContainer().getBody().getLyrics();

		return lyrics;
	}

	/**
	 * Search tracks using the given criteria.
	 *
	 * @param q
	 *            search into every available field
	 *            (track_name,artist_name,lyrics)
	 * @param q_artist
	 *            search for text string among artist names
	 * @param q_track
	 *            search for text string among track names
	 * @param page
	 *            request specific result page
	 * @param pageSize
	 *            specify number of items per result page
	 * @param f_has_lyrics
	 *            specify number of items per result page
	 * @return a list of tracks.
	 * @throws MusixMatchException
	 *             if any error occur
	 */
	public List<Track> searchTracks(String q, String q_artist, String q_track,
			int page, int pageSize, boolean f_has_lyrics)
			throws MusixMatchException {
		List<Track> trackList = null;
		TrackSeachMessage message = null;
		Map<String, Object> params = new HashMap<String, Object>();

		params.put(Constants.API_KEY, apiKey);
		params.put(Constants.QUERY, q);
		params.put(Constants.QUERY_ARTIST, q_artist);
		params.put(Constants.QUERY_TRACK, q_track);
		params.put(Constants.PAGE, page);
		params.put(Constants.PAGE_SIZE, pageSize);

		if (f_has_lyrics) {
			params.put(Constants.F_HAS_LYRICS, "1");
		} else {
			params.put(Constants.F_HAS_LYRICS, "0");
		}

		String response = null;

		response = MusixMatchRequest.sendRequest(Helper.getURLString(
				Methods.TRACK_SEARCH, params));

		Gson gson = new Gson();

		try {
			message = gson.fromJson(response, TrackSeachMessage.class);
		} catch (JsonParseException jpe) {
			handleErrorResponse(response);
		}

		int statusCode = message.getTrackMessage().getHeader().getStatus_code();

		if (statusCode > 200) {
			throw new MusixMatchException("Status Code is not 200");
		}

		trackList = message.getTrackMessage().getBody().getTrack_list();

		return trackList;
	}

	/**
	 * Get the track details using the specified trackId.
	 *
	 * @param trackID
	 *            track identifier in musiXmatch catalog
	 * @return the track
	 * @throws MusixMatchException
	 */
	public Track getTrack(int trackID) throws MusixMatchException {
		Track track = new Track();
		Map<String, Object> params = new HashMap<String, Object>();

		params.put(Constants.API_KEY, apiKey);
		params.put(Constants.TRACK_ID, new String("" + trackID));

		track = getTrackResponse(Methods.TRACK_GET, params);

		return track;
	}

	/**
	 * Get the most matching track which was retrieved using the search.
	 *
	 * @param q_track
	 *            search for text string among track names
	 * @param q_artist
	 *            search for text string among artist names
	 * @return the track
	 * @throws MusixMatchException
	 */
	public Track getMatchingTrack(String q_track, String q_artist)
			throws MusixMatchException {
		Track track = new Track();
		Map<String, Object> params = new HashMap<String, Object>();

		params.put(Constants.API_KEY, apiKey);
		params.put(Constants.QUERY_TRACK, q_track);
		params.put(Constants.QUERY_ARTIST, q_artist);

		track = getTrackResponse(Methods.MATCHER_TRACK_GET, params);

		return track;
	}

	/**
	 * Returns the track response which was returned through the query.
	 *
	 * @param methodName
	 *            the name of the API method.
	 * @param params
	 *            a map which contains the key-value pair
	 * @return the track details.
	 * @throws MusixMatchException
	 *             if any error occurs.
	 */
	private Track getTrackResponse(String methodName, Map<String, Object> params)
			throws MusixMatchException {
		Track track = new Track();
		String response = null;
		TrackGetMessage message = null;

		response = MusixMatchRequest.sendRequest(Helper.getURLString(
				methodName, params));

		Gson gson = new Gson();

		try {
			message = gson.fromJson(response, TrackGetMessage.class);
		} catch (JsonParseException jpe) {
			handleErrorResponse(response);
		}

		TrackData data = message.getTrackMessage().getBody().getTrack();

		track.setTrack(data);

		return track;
	}

	/**
	 * Handle the error response.
	 *
	 * @param jsonResponse
	 *            the jsonContent.
	 * @throws MusixMatchException
	 *             if any error occurs
	 */
	private void handleErrorResponse(String jsonResponse)
			throws MusixMatchException {
		StatusCode statusCode;
		Gson gson = new Gson();
		ErrorMessage errMessage = gson.fromJson(jsonResponse,
				ErrorMessage.class);
		int responseCode = errMessage.getMessageContainer().getHeader()
				.getStatus_code();

		switch (responseCode) {
		case 400:
			statusCode = StatusCode.BAD_SYNTAX;
			break;
		case 401:
			statusCode = StatusCode.AUTH_FAILED;
			break;
		case 402:
			statusCode = StatusCode.LIMIT_REACHED;
			break;
		case 403:
			statusCode = StatusCode.NOT_AUTHORIZED;
			break;
		case 404:
			statusCode = StatusCode.RESOURCE_NOT_FOUND;
			break;
		case 405:
			statusCode = StatusCode.METHOD_NOT_FOUND;
			break;
		default:
			statusCode = StatusCode.ERROR;
			break;
		}

		throw new MusixMatchException(statusCode.getStatusMessage());
	}
}


text:
package com.amarin.mywaiter.activity;

import android.app.Activity;
import android.app.FragmentManager;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

import com.amarin.mywaiter.R;
import com.amarin.mywaiter.facade.OnDishSelectedListener;
import com.amarin.mywaiter.fragment.MenuFragment;
import com.amarin.mywaiter.model.Dish;
import com.amarin.mywaiter.model.OrderItem;
import com.amarin.mywaiter.model.Restaurant;
import com.amarin.mywaiter.utils.MyWaiterConstants;

public class MenuActivity extends AppCompatActivity implements OnDishSelectedListener {

    protected int mTablePosition;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_menu);

        mTablePosition = getIntent().getIntExtra(MyWaiterConstants.ARG_TABLE_POSITION, 0);

        setTitle(getString(R.string.app_name) + getString(R.string.toolbar_title_separator) + getString(R.string.toolbar_title_menu));

        FragmentManager fm = getFragmentManager();
        if (findViewById(R.id.fragment_menu) != null) {
            if (fm.findFragmentById(R.id.fragment_menu) == null) {
                fm.beginTransaction()
                        .add(R.id.fragment_menu, MenuFragment.newInstance(mTablePosition))
                        .commit();
            }
        }
    }

    @Override
    public void onDishClick(Dish dish, View view) {
        Intent intent = new Intent(this, OrderItemActivity.class);
        OrderItem orderItem = new OrderItem(dish, null);
        intent.putExtra(MyWaiterConstants.ARG_ORDER_ITEM, orderItem);
        startActivityForResult(intent, MyWaiterConstants.REQUEST_ORDER_ITEM);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == MyWaiterConstants.REQUEST_ORDER_ITEM) {
            if (resultCode == Activity.RESULT_OK) {
                OrderItem orderItem = (OrderItem) data.getSerializableExtra(MyWaiterConstants.ARG_ORDER_ITEM);
                Restaurant.getInstance().getTableByPosition(mTablePosition).addOrderItem(orderItem);
                finish();
            }
        }
    }
}


text:
import devsim

devsim.load_devices( file="mesh2.msh")

for x in devsim.get_device_list():
    for y in devsim.get_region_list(device=x):
        print("%s %s" % (x, y))

device="MyDevice"
interface="MySiOx"
regions=("MyOxRegion", "MySiRegion")

devsim.set_parameter( device=device, region="MySiRegion", name="Permittivity", value=11.1*8.85e-14)
devsim.set_parameter( device=device, region="MySiRegion", name="ElectricCharge", value=1.6e-19)

devsim.set_parameter( device=device, region="MyOxRegion", name="Permittivity", value=3.9*8.85e-14)
devsim.set_parameter( device=device, region="MyOxRegion", name="ElectricCharge", value=1.6e-19)

for region in regions:
    devsim.node_solution( device=device, region=region, name="Potential")
    devsim.edge_from_node_model( device=device, region=region, node_model="Potential")

    devsim.edge_model( device=device, region=region, name="ElectricField", equation="(Potential@n0 - Potential@n1)*EdgeInverseLength")
    devsim.edge_model( device=device, region=region, name="ElectricField:Potential@n0", equation="EdgeInverseLength")
    devsim.edge_model( device=device, region=region, name="ElectricField:Potential@n1", equation="-EdgeInverseLength")

    devsim.edge_model( device=device, region=region, name="PotentialEdgeFlux", equation="Permittivity*ElectricField")
    devsim.edge_model( device=device, region=region, name="PotentialEdgeFlux:Potential@n0", equation="diff(Permittivity*ElectricField, Potential@n0)")
    devsim.edge_model( device=device, region=region, name="PotentialEdgeFlux:Potential@n1", equation="-PotentialEdgeFlux:Potential@n0")

    devsim.equation( device=device, region=region, name="PotentialEquation", variable_name="Potential", edge_model="PotentialEdgeFlux", variable_update="default")

devsim.set_parameter( device=device, name="topbias",    value=1.0)
devsim.set_parameter( device=device, name="botbias", value=0.0)

devsim.node_model( device=device, region="MySiRegion", name="topnode_model"          , equation="Potential - topbias")
devsim.node_model( device=device, region="MySiRegion", name="topnode_model:Potential", equation="1")

devsim.node_model( device=device, region="MyOxRegion", name="botnode_model"          , equation="Potential - botbias")
devsim.node_model( device=device, region="MyOxRegion", name="botnode_model:Potential", equation="1")

devsim.contact_equation( device=device, contact="top", name="PotentialEquation",
                         node_model="topnode_model", edge_charge_model="PotentialEdgeFlux")

devsim.contact_equation( device=device, contact="top", name="PotentialEquation",
                         node_model="topnode_model", edge_charge_model="PotentialEdgeFlux")

devsim.contact_equation( device=device, contact="bot", name="PotentialEquation",
                         node_model="botnode_model", edge_charge_model="PotentialEdgeFlux")

# type continuous means that regular equations in both regions are swapped into the primary region
devsim.interface_model( device=device, interface=interface, name="continuousPotential", equation="Potential@r0-Potential@r1")
devsim.interface_model( device=device, interface=interface, name="continuousPotential:Potential@r0", equation= "1")
devsim.interface_model( device=device, interface=interface, name="continuousPotential:Potential@r1", equation="-1")
devsim.interface_equation( device=device, interface=interface, name="PotentialEquation", interface_model="continuousPotential", type="continuous")

def print_charge():
    print(devsim.get_contact_charge( device=device, contact="top", equation="PotentialEquation"))
    print(devsim.get_contact_charge( device=device, contact="bot", equation="PotentialEquation"))
def print_flux():
    devsim.print_edge_values(device=device, region="MySiRegion", name="PotentialEdgeFlux")
    devsim.print_edge_values(device=device, region="MyOxRegion", name="PotentialEdgeFlux")
def set_permittivities(ox, si):
    devsim.set_parameter( device=device, region="MySiRegion", name="Permittivity", value=si*8.85e-14)
    devsim.set_parameter( device=device, region="MyOxRegion", name="Permittivity", value=ox*8.85e-14)

devsim.solve(type="dc", absolute_error=1.0, relative_error=1e-10, maximum_iterations=30)
print_charge()
print_flux()

set_permittivities(si=1.0, ox=1.0)
devsim.solve(type="dc", absolute_error=1.0, relative_error=1e-10, maximum_iterations=30)
print_charge()
print_flux()

# makes sure this global scope does not interfere
devsim.set_parameter( device=device, name="Permittivity", value=11.1*8.85e-14)

set_permittivities(si=11.1, ox=3.9)
devsim.solve(type="dc", absolute_error=1.0, relative_error=1e-10, maximum_iterations=30)
print_charge()
print_flux()

devsim.print_edge_values(device=device, region="MySiRegion", name="ElectricField")
devsim.print_edge_values(device=device, region="MyOxRegion", name="ElectricField")

devsim.print_node_values(device=device, region="MySiRegion", name="Potential")
devsim.print_node_values(device=device, region="MyOxRegion", name="Potential")


text:
package me.roryclaasen.rorysmod.block;

import java.util.Random;

import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import me.roryclaasen.rorysmod.block.base.BlockBaseContainer;
import me.roryclaasen.rorysmod.block.tile.TileEntityRifleTable;
import me.roryclaasen.rorysmod.core.RorysMod;
import cpw.mods.fml.common.network.internal.FMLNetworkHandler;

public class BlockRifleTable extends BlockBaseContainer {

	public BlockRifleTable(Material material, String unlocalizedName) {
		super(material, unlocalizedName);
        this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.875F, 1.0F);
        this.setHardness(10F);
        this.setResistance(5.0F);
	}

	@Override
	public int getRenderType() {
		return -1;
	}

	@Override
	public boolean isOpaqueCube() {
		return false;
	}

	@Override
	public boolean renderAsNormalBlock() {
		return false;
	}

	@Override
	public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int metadata, float hitX, float hitY, float hitZ) {
		if (!world.isRemote) {
			FMLNetworkHandler.openGui(player, RorysMod.instance, RorysMod.GUIS.RILE_TABLE.ordinal(), world, x, y, z);
		}
		return true;
	}

	@Override
	public void breakBlock(World world, int x, int y, int z, Block block, int par6) {
		dropItems(world, x, y, z);
		super.breakBlock(world, x, y, z, block, par6);
	}

	private void dropItems(World world, int x, int y, int z) {
		Random rand = new Random();
		TileEntity tileEntity = world.getTileEntity(x, y, z);
		if (!(tileEntity instanceof IInventory)) return;

		IInventory inventory = (IInventory) tileEntity;
		for (int i = 0; i < inventory.getSizeInventory(); i++) {
			ItemStack item = inventory.getStackInSlot(i);
			if (item != null && item.stackSize > 0) {
				float rx = rand.nextFloat() * 0.8F + 0.1F;
				float ry = rand.nextFloat() * 0.8F + 0.1F;
				float rz = rand.nextFloat() * 0.8F + 0.1F;
				EntityItem entityItem = new EntityItem(world, x + rx, y + ry, z + rz, new ItemStack(item.getItem(), item.stackSize, item.getItemDamage()));
				if (item.hasTagCompound()) entityItem.getEntityItem().setTagCompound((NBTTagCompound) item.getTagCompound().copy());
				float factor = 0.05F;
				entityItem.motionX = rand.nextGaussian() * factor;
				entityItem.motionY = rand.nextGaussian() * factor + 0.2F;
				entityItem.motionZ = rand.nextGaussian() * factor;
				world.spawnEntityInWorld(entityItem);
				item.stackSize = 0;
			}
		}
	}

	@Override
	public TileEntity createNewTileEntity(World worldIn, int meta) {
		return new TileEntityRifleTable();
	}
}


text:
<?php
namespace Decibels\UserBundle\Security\EntryPoint;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Http\HttpUtils;
use Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface;
use Symfony\Component\HttpFoundation\Session\Session;

class CasEntryPoint implements AuthenticationEntryPointInterface
{
	protected $loginPath;
	protected $checkPath;
	protected $httpUtils;

	public function __construct(HttpUtils $httpUtils, $loginPath, $checkPath)
	{
		$this->httpUtils = $httpUtils;
		$this->loginPath = $loginPath;
		$this->checkPath = $checkPath;
	}

	public function start(Request $request, AuthenticationException $authException = null)
	{
		$loginUrl = "https://cas.utc.fr/cas/login?service=".urlencode($request->getUriForPath($this->checkPath));

		$session = new Session;
		$session->set('url', $loginUrl);
		$session->set('compteur', 0);

		return $this->httpUtils->createRedirectResponse($request, $loginUrl);
	}
}


text:
<?php

namespace Itsup\Api\EndPoint;

use Cache\Taggable\TaggablePoolInterface;
use Doctrine\Common\Annotations\AnnotationReader;
use GuzzleHttp\Psr7\Response;
use Itsup\Api\Annotation\Cache;
use Itsup\Api\Client;
use League\Fractal\Manager;
use League\Fractal\Resource\Item;
use Psr\Http\Message\ResponseInterface;
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;

/**
 * @author Cyril LEGRAND <cyril@sctr.net>
 */
abstract class AbstractEndPoint
{
    /**
     * @var Client
     */
    protected $client;

    /**
     * @var Manager
     */
    protected $manager;

    /**
     * @var array
     */
    protected $cacheSettings;

    /**
     * AbstractEndpoint constructor.
     *
     * @param Client $client
     */
    public function __construct(Client $client)
    {
        $this->client        = $client;
        $this->manager       = new Manager();
        $this->cacheSettings = $this->setCacheSettings();
    }

    /**
     * @return Client
     */
    public function getClient(): Client
    {
        return $this->client;
    }

    /**
     * @return array
     */
    protected function setCacheSettings(): array
    {
        return [];
    }

    /**
     * Execute the API request call.
     *
     * @param       $type
     * @param       $path
     * @param array $parameters
     *
     * @return ResponseInterface
     */
    protected function request($type, $path, array $parameters = []): ResponseInterface
    {
        $parameters['headers']['Authorization']  =
            $this->client->getType().' '.$this->client->getApiKey();
        $parameters['headers']['Accept-Charset'] = 'utf-8';

        return $this->client->request($type, $path, $parameters);
    }

    /**
     * Try to find the request response in cache, if not make the API request call then return it.
     *
     * @param string $method
     * @param string $route
     * @param array  $parameters
     *
     * @return Response|null|ResponseInterface
     */
    protected function cacheRequest(string $method, string $route, array $parameters = [])
    {
        $param            = ($method === 'POST') ? 'form_params' : 'query';
        $expr             = new ExpressionLanguage();
        $cache            = $this->client->getCache();
        $cacheAnnotations = $this->getCacheAnnotations();
        if (empty($cacheAnnotations) || $cache === null) {
            return $this->request($method, $route, [$param => $parameters]);
        }

        foreach ($cacheAnnotations as $annKey => $annotation) {
            if (!empty($annotation->parameters)) {
                foreach ($annotation->parameters as $key => $value) {
                    try {
                        $annotation->parameters[$key] = $expr->evaluate(
                            $value,
                            ['method' => $method, 'route' => $route, 'parameters' => $parameters]
                        );
                    } catch (\Exception $e) {
                        unset($cacheAnnotations[$annKey]);
                        break;
                    }

                    if ($annotation->parameters[$key] === null) {
                        unset($cacheAnnotations[$annKey]);
                        break;
                    }
                }

                $annotation->key = sprintf('api-client.%s|%s', $annotation->name, sha1(json_encode($parameters)));
            } else {
                $annotation->key = 'api-client.'.$annotation->name;
            }

            $annotation->ttl = $expr->evaluate($annotation->ttl);
        }

        if ($method !== 'GET') {
            $response = $this->request($method, $route, [$param => $parameters]);
            foreach ($cacheAnnotations as $annotation) {
                $cache->deleteItem($annotation->key);
                $cache->clearTags($annotation->tags);
            }

            return $response;
        }

        // Try to fetch from all cache first
        // If that fails, run the response, and save it to all the cache entries
        try {
            $response = $this->fetchFromCache($cache, $cacheAnnotations);
        } catch (\Exception $e) {
            error_log($e->getMessage().' in file '.__FILE__.' on line '.__LINE__);
            // Leave response empty
        }
        if (empty($response)) {
            $response = $this->request($method, $route, [$param => $parameters]);

            $this->cacheResponse($cache, $cacheAnnotations, $response);
        }

        return $response;
    }

    /**
     * Get the Cache Annotations from the EndPoint.
     *
     * @return array|Cache[]
     */
    private function getCacheAnnotations(): array
    {
        $reader  = new AnnotationReader();
        $callers = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 5);

        $caches = [];
        foreach ($callers as $caller) {
            $refl        = new \ReflectionObject($caller['object']);
            $annotations = $reader->getMethodAnnotations($refl->getMethod($caller['function']));
            foreach ($annotations as $annotation) {
                if ($annotation instanceof Cache) {
                    $caches[] = $annotation;
                }
            }
        }

        return $caches;
    }

    /**
     * Fetch an item from the cache.
     *
     * @param TaggablePoolInterface $cache
     * @param array|Cache[]         $cacheAnnotations
     *
     * @return Response|null
     */
    private function fetchFromCache(TaggablePoolInterface $cache, array $cacheAnnotations)
    {
        foreach ($cacheAnnotations as $annotation) {
            $item = $cache->getItem($annotation->key);
            if ($item->isHit()) {
                list($status, $headers, $body) = $item->get();

                return new Response($status, $headers, $body);
            }
        }
    }

    /**
     * Put the API request call response into cache.
     *
     * @param TaggablePoolInterface $cache
     * @param array|Cache[]         $cacheAnnotations
     * @param Response              $response
     */
    private function cacheResponse(TaggablePoolInterface $cache, array $cacheAnnotations, Response $response)
    {
        foreach ($cacheAnnotations as $annotation) {
            $item = $cache->getItem($annotation->key);
            foreach ($annotation->tags as $tag) {
                $item->addTag($tag);
            }

            $item->set([$response->getStatusCode(), $response->getHeaders(), $response->getBody()->__toString()]);
            $item->expiresAfter($annotation->ttl);

            $cache->saveDeferred($item);
        }

        $cache->commit();
    }
}


text:
EZSTREAM_NEEDED_PACKAGES="build-essential libpcre3 libpcre3-dev libssl-dev wget git golang-go"
#Root paths for building files
EZSTREAM_ROOT="$HOME"
EZSTREAM_BUILD_PATH="$EZSTREAM_ROOT/EZstreambuild"
EZSTREAM_SOURCE_PATH="$HOME/EZ-StreamServer-master"
#Download locations
NGINX_TAR_PATH="https://nginx.org/download/nginx-1.11.10.tar.gz"
NGINX_RTMP_TAR_PATH="https://github.com/arut/nginx-rtmp-module/archive/v1.1.11.tar.gz"

#Begin installation
echo "Installing required packages"
apt-get -q update >> "$EZSTREAM_ROOT/package_install.log" 2>&1 \
    && apt-get -q install $EZSTREAM_NEEDED_PACKAGES -y >> "$EZSTREAM_ROOT/package_install.log" 2>&1

mkdir $EZSTREAM_BUILD_PATH
cd $EZSTREAM_BUILD_PATH

echo "Downloading and extracting $NGINX_TAR_PATH"
mkdir "nginx" && wget -qO- $NGINX_TAR_PATH | tar xz -C "nginx" --strip-components=1

echo "Downloading and extracting $NGINX_RTMP_TAR_PATH"
mkdir "nginx-rtmp-module" && wget -qO- $NGINX_RTMP_TAR_PATH | tar xz -C "nginx-rtmp-module" --strip-components=1

#Setup Go and build auth package
echo "Building Go-Auth Files"
mkdir "$EZSTREAM_ROOT/go"
export GOPATH="$EZSTREAM_ROOT/go"
export GOBIN="$GOPATH/bin"

cd $GOPATH
go get github.com/Scaless/EZ-StreamServer-Auth
go install github.com/Scaless/EZ-StreamServer-Auth

#build nginx
cd "$EZSTREAM_BUILD_PATH/nginx"

echo "Configuring NGINX - see nginx_configure.log for details"
./configure --with-http_ssl_module --add-module="../nginx-rtmp-module" >>"$EZSTREAM_ROOT/nginx_configure.log" 2>&1

echo "Building NGINX - see nginx_make.log for details"
make >>"$EZSTREAM_ROOT/nginx_make.log" 2>&1

echo "Installing NGINX - see nginx_install.log for details"
make install >>"$EZSTREAM_ROOT/nginx_install.log" 2>&1

#Copy Default Files
cp "$EZSTREAM_SOURCE_PATH/defaultfiles/index.html" "/usr/local/nginx/html/"
cp "$EZSTREAM_SOURCE_PATH/defaultfiles/nginx.conf" "/usr/local/nginx/conf/"

#start stream-auth
echo "Starting Go-Auth"
"$GOPATH/bin/EZ-StreamServer-Auth" &

#start nginx
echo "Starting NGINX"
/usr/local/nginx/sbin/nginx &


text:
namespace domain_reliability {

DomainReliabilityContextManager::DomainReliabilityContextManager(
    const MockableTime* time,
    const std::string& upload_reporter_string,
    DomainReliabilityContext::UploadAllowedCallback upload_allowed_callback,
    DomainReliabilityDispatcher* dispatcher)
    : time_(time),
      upload_reporter_string_(upload_reporter_string),
      upload_allowed_callback_(upload_allowed_callback),
      dispatcher_(dispatcher) {
  DCHECK(time_);
  DCHECK(dispatcher_);
}

DomainReliabilityContextManager::~DomainReliabilityContextManager() = default;

void DomainReliabilityContextManager::RouteBeacon(
    std::unique_ptr<DomainReliabilityBeacon> beacon) {
  const std::string& beacon_host = beacon->url.host();

  // An exact match for the host always takes priority.
  DomainReliabilityContext* context_to_use = GetContext(beacon_host);
  if (context_to_use) {
    context_to_use->OnBeacon(std::move(beacon));
    return;
  }

  DomainReliabilityContext* superdomain_context =
      GetSuperdomainContext(beacon_host);

  // Try to get a Google config which may match the host itself, or the host's
  // parent domain.
  std::unique_ptr<const DomainReliabilityConfig> google_config =
      MaybeGetGoogleConfig(beacon_host);

  if (!google_config) {
    if (superdomain_context)
      superdomain_context->OnBeacon(std::move(beacon));
    return;
  }

  context_to_use = superdomain_context;
  bool google_config_is_exact = (google_config->origin.host() == beacon_host);

  // An exact match takes priority over an existing superdomain context, if any
  // exists.
  if (google_config_is_exact || !context_to_use)
    context_to_use = AddContextForConfig(std::move(google_config));

  context_to_use->OnBeacon(std::move(beacon));
}

void DomainReliabilityContextManager::ClearBeacons(
    const base::RepeatingCallback<bool(const GURL&)>& origin_filter) {
  for (auto& context_entry : contexts_) {
    if (origin_filter.is_null() ||
        origin_filter.Run(context_entry.second->config().origin)) {
      context_entry.second->ClearBeacons();
    }
  }
}

DomainReliabilityContext* DomainReliabilityContextManager::AddContextForConfig(
    std::unique_ptr<const DomainReliabilityConfig> config) {
  const std::string& key = config->origin.host();
  auto pair = contexts_.insert(
      std::make_pair(key, CreateContextForConfig(std::move(config))));

  // Insertion should have succeeded (the key should not have already existed).
  DCHECK(pair.second);
  return pair.first->second.get();
}

void DomainReliabilityContextManager::RemoveContexts(
    const base::RepeatingCallback<bool(const GURL&)>& origin_filter) {
  if (origin_filter.is_null()) {
    contexts_.clear();
    return;
  }

  for (auto it = contexts_.begin(); it != contexts_.end();) {
    if (origin_filter.Run(it->second->config().origin)) {
      it = contexts_.erase(it);
      continue;
    }
    ++it;
  }
}

std::unique_ptr<base::Value> DomainReliabilityContextManager::GetWebUIData()
    const {
  std::unique_ptr<base::ListValue> contexts_value(new base::ListValue());
  for (const auto& context_entry : contexts_)
    contexts_value->Append(context_entry.second->GetWebUIData());
  return std::move(contexts_value);
}

DomainReliabilityContext* DomainReliabilityContextManager::GetContext(
    const std::string& host) const {
  ContextMap::const_iterator context_it = contexts_.find(host);
  if (context_it == contexts_.end())
    return nullptr;
  return context_it->second.get();
}

DomainReliabilityContext*
DomainReliabilityContextManager::GetSuperdomainContext(
    const std::string& host) const {
  // TODO(juliatuttle): Make sure parent is not in PSL before using.
  std::string parent_host = net::GetSuperdomain(host);
  if (parent_host.empty())
    return nullptr;

  DomainReliabilityContext* context = GetContext(parent_host);
  if (context && context->config().include_subdomains)
    return context;

  return nullptr;
}

void DomainReliabilityContextManager::OnNetworkChanged(base::TimeTicks now) {
  last_network_change_time_ = now;
}

void DomainReliabilityContextManager::SetUploader(
    DomainReliabilityUploader* uploader) {
  DCHECK(!uploader_);
  DCHECK(uploader);
  uploader_ = uploader;
}

std::unique_ptr<DomainReliabilityContext>
DomainReliabilityContextManager::CreateContextForConfig(
    std::unique_ptr<const DomainReliabilityConfig> config) const {
  DCHECK(config);
  DCHECK(config->IsValid());
  DCHECK(uploader_);

  return std::make_unique<DomainReliabilityContext>(
      time_, DomainReliabilityScheduler::Params::GetFromFieldTrialsOrDefaults(),
      upload_reporter_string_, &last_network_change_time_,
      upload_allowed_callback_, dispatcher_, uploader_, std::move(config));
}

}  // namespace domain_reliability


text:
using namespace swift;

void VisibleDeclConsumer::anchor() {}
void VectorDeclConsumer::anchor() {}
void NamedDeclConsumer::anchor() {}

namespace {
struct LookupState {
private:
  /// If \c false, an unqualified lookup of all visible decls in a
  /// DeclContext.
  ///
  /// If \c true, lookup of all visible members of a given object (possibly of
  /// metatype type).
  unsigned IsQualified : 1;

  /// Is this a qualified lookup on a metatype?
  unsigned IsOnMetatype : 1;

  /// Did we recurse into a superclass?
  unsigned IsOnSuperclass : 1;

  unsigned InheritsSuperclassInitializers : 1;

  /// Should instance members be included even if lookup is performed on a type?
  unsigned IncludeInstanceMembers : 1;

  LookupState()
      : IsQualified(0), IsOnMetatype(0), IsOnSuperclass(0),
        InheritsSuperclassInitializers(0), IncludeInstanceMembers(0) {}

public:
  LookupState(const LookupState &) = default;

  static LookupState makeQualified() {
    LookupState Result;
    Result.IsQualified = 1;
    return Result;
  }

  static LookupState makeUnqualified() {
    LookupState Result;
    Result.IsQualified = 0;
    return Result;
  }

  bool isQualified() const { return IsQualified; }
  bool isOnMetatype() const { return IsOnMetatype; }
  bool isOnSuperclass() const { return IsOnSuperclass; }
  bool isInheritsSuperclassInitializers() const {
    return InheritsSuperclassInitializers;
  }
  bool isIncludingInstanceMembers() const { return IncludeInstanceMembers; }

  LookupState withOnMetatype() const {
    auto Result = *this;
    Result.IsOnMetatype = 1;
    return Result;
  }

  LookupState withOnSuperclass() const {
    auto Result = *this;
    Result.IsOnSuperclass = 1;
    return Result;
  }

  LookupState withInheritsSuperclassInitializers() const {
    auto Result = *this;
    Result.InheritsSuperclassInitializers = 1;
    return Result;
  }

  LookupState withoutInheritsSuperclassInitializers() const {
    auto Result = *this;
    Result.InheritsSuperclassInitializers = 0;
    return Result;
  }

  LookupState withIncludedInstanceMembers() const {
    auto Result = *this;
    Result.IncludeInstanceMembers = 1;
    return Result;
  }
};
} // unnamed namespace

static bool areTypeDeclsVisibleInLookupMode(LookupState LS) {
  // Nested type declarations can be accessed only with unqualified lookup or
  // on metatypes.
  return !LS.isQualified() || LS.isOnMetatype();
}

static bool isDeclVisibleInLookupMode(ValueDecl *Member, LookupState LS,
                                      const DeclContext *FromContext,
                                      LazyResolver *TypeResolver) {
  if (TypeResolver) {
    TypeResolver->resolveDeclSignature(Member);
    TypeResolver->resolveAccessibility(Member);
  }

  // Check accessibility when relevant.
  if (!Member->getDeclContext()->isLocalContext() &&
      !isa<GenericTypeParamDecl>(Member) && !isa<ParamDecl>(Member) &&
      FromContext->getASTContext().LangOpts.EnableAccessControl) {
    if (Member->isInvalid() && !Member->hasAccessibility())
      return false;
    if (!Member->isAccessibleFrom(FromContext))
      return false;
  }

  if (auto *FD = dyn_cast<FuncDecl>(Member)) {
    // Cannot call static functions on non-metatypes.
    if (!LS.isOnMetatype() && FD->isStatic())
      return false;

    // Otherwise, either call a function or curry it.
    return true;
  }
  if (auto *VD = dyn_cast<VarDecl>(Member)) {
    // Cannot use static properties on non-metatypes.
    if (!(LS.isQualified() && LS.isOnMetatype()) && VD->isStatic())
      return false;

    // Cannot use instance properties on metatypes.
    if (LS.isOnMetatype() && !VD->isStatic() && !LS.isIncludingInstanceMembers())
      return false;

    return true;
  }
  if (isa<EnumElementDecl>(Member)) {
    // Cannot reference enum elements on non-metatypes.
    if (!(LS.isQualified() && LS.isOnMetatype()))
      return false;
  }
  if (auto CD = dyn_cast<ConstructorDecl>(Member)) {
    // Constructors with stub implementations cannot be called in Swift.
    if (CD->hasStubImplementation())
      return false;
    if (LS.isQualified() && LS.isOnSuperclass()) {
      // Cannot call initializers from a superclass, except for inherited
      // convenience initializers.
      return LS.isInheritsSuperclassInitializers() && CD->isInheritable();
    }
  }
  if (isa<TypeDecl>(Member))
    return areTypeDeclsVisibleInLookupMode(LS);

  return true;
}

/// Lookup members in extensions of \p LookupType, using \p BaseType as the
/// underlying type when checking any constraints on the extensions.
static void doGlobalExtensionLookup(Type BaseType,
                                    Type LookupType,
                                    SmallVectorImpl<ValueDecl *> &FoundDecls,
                                    const DeclContext *CurrDC,
                                    LookupState LS,
                                    DeclVisibilityKind Reason,
                                    LazyResolver *TypeResolver) {
  auto nominal = LookupType->getAnyNominal();

  // Look in each extension of this type.
  for (auto extension : nominal->getExtensions()) {
    if (!isExtensionApplied(*const_cast<DeclContext*>(CurrDC), BaseType,
                            extension))
      continue;
    bool validatedExtension = false;
    if (TypeResolver && extension->getAsProtocolExtensionContext()) {
      if (!TypeResolver->isProtocolExtensionUsable(
              const_cast<DeclContext *>(CurrDC), BaseType, extension)) {
        continue;
      }
      validatedExtension = true;
    }

    for (auto Member : extension->getMembers()) {
      if (auto VD = dyn_cast<ValueDecl>(Member))
        if (isDeclVisibleInLookupMode(VD, LS, CurrDC, TypeResolver)) {
          // Resolve the extension, if we haven't done so already.
          if (!validatedExtension && TypeResolver) {
            TypeResolver->resolveExtension(extension);
            validatedExtension = true;
          }

          FoundDecls.push_back(VD);
        }
    }
  }

  // Handle shadowing.
  removeShadowedDecls(FoundDecls, CurrDC->getParentModule(), TypeResolver);
}

/// \brief Enumerate immediate members of the type \c LookupType and its
/// extensions, as seen from the context \c CurrDC.
///
/// Don't do lookup into superclasses or implemented protocols.  Uses
/// \p BaseType as the underlying type when checking any constraints on the
/// extensions.
static void lookupTypeMembers(Type BaseType, Type LookupType,
                              VisibleDeclConsumer &Consumer,
                              const DeclContext *CurrDC, LookupState LS,
                              DeclVisibilityKind Reason,
                              LazyResolver *TypeResolver) {
  NominalTypeDecl *D = LookupType->getAnyNominal();
  assert(D && "should have a nominal type");

  bool LookupFromChildDeclContext = false;
  const DeclContext *TempDC = CurrDC;
  while (!TempDC->isModuleContext()) {
    if (TempDC == D) {
      LookupFromChildDeclContext = true;
      break;
    }
    TempDC = TempDC->getParent();
  }

  SmallVector<ValueDecl*, 2> FoundDecls;

  if (LookupFromChildDeclContext) {
    // Current decl context is contained inside 'D', so generic parameters
    // are visible.
    if (D->getGenericParams())
      for (auto Param : *D->getGenericParams())
        if (isDeclVisibleInLookupMode(Param, LS, CurrDC, TypeResolver))
          FoundDecls.push_back(Param);
  }

  for (Decl *Member : D->getMembers()) {
    if (auto *VD = dyn_cast<ValueDecl>(Member))
      if (isDeclVisibleInLookupMode(VD, LS, CurrDC, TypeResolver))
        FoundDecls.push_back(VD);
  }
  doGlobalExtensionLookup(BaseType, LookupType, FoundDecls, CurrDC, LS, Reason,
                          TypeResolver);

  // Report the declarations we found to the consumer.
  for (auto *VD : FoundDecls)
    Consumer.foundDecl(VD, Reason);
}

/// Enumerate AnyObject declarations as seen from context \c CurrDC.
static void doDynamicLookup(VisibleDeclConsumer &Consumer,
                            const DeclContext *CurrDC,
                            LookupState LS,
                            LazyResolver *TypeResolver) {
  class DynamicLookupConsumer : public VisibleDeclConsumer {
    VisibleDeclConsumer &ChainedConsumer;
    LookupState LS;
    const DeclContext *CurrDC;
    LazyResolver *TypeResolver;
    llvm::DenseSet<std::pair<Identifier, CanType>> FunctionsReported;
    llvm::DenseSet<CanType> SubscriptsReported;
    llvm::DenseSet<std::pair<Identifier, CanType>> PropertiesReported;

  public:
    explicit DynamicLookupConsumer(VisibleDeclConsumer &ChainedConsumer,
                                   LookupState LS, const DeclContext *CurrDC,
                                   LazyResolver *TypeResolver)
        : ChainedConsumer(ChainedConsumer), LS(LS), CurrDC(CurrDC),
          TypeResolver(TypeResolver) {}

    void foundDecl(ValueDecl *D, DeclVisibilityKind Reason) override {
      // If the declaration has an override, name lookup will also have found
      // the overridden method.  Skip this declaration, because we prefer the
      // overridden method.
      if (D->getOverriddenDecl())
        return;

      // Ensure that the declaration has a type.
      if (!D->hasInterfaceType()) {
        if (!TypeResolver) return;
        TypeResolver->resolveDeclSignature(D);
        if (!D->hasInterfaceType()) return;
      }

      switch (D->getKind()) {
#define DECL(ID, SUPER) \
      case DeclKind::ID:
#define VALUE_DECL(ID, SUPER)
#include "swift/AST/DeclNodes.def"
        llvm_unreachable("not a ValueDecl!");

      // Types cannot be found by dynamic lookup.
      case DeclKind::GenericTypeParam:
      case DeclKind::AssociatedType:
      case DeclKind::TypeAlias:
      case DeclKind::Enum:
      case DeclKind::Class:
      case DeclKind::Struct:
      case DeclKind::Protocol:
        return;

      // Initializers cannot be found by dynamic lookup.
      case DeclKind::Constructor:
      case DeclKind::Destructor:
        return;

      // These cases are probably impossible here but can also just
      // be safely ignored.
      case DeclKind::EnumElement:
      case DeclKind::Param:
      case DeclKind::Module:
        return;

      // For other kinds of values, check if we already reported a decl
      // with the same signature.

      case DeclKind::Func: {
        auto FD = cast<FuncDecl>(D);
        assert(FD->getImplicitSelfDecl() && "should not find free functions");
        (void)FD;

        if (FD->isInvalid())
          break;

        // Get the type without the first uncurry level with 'self'.
        CanType T = D->getInterfaceType()
                        ->castTo<AnyFunctionType>()
                        ->getResult()
                        ->getCanonicalType();

        auto Signature = std::make_pair(D->getName(), T);
        if (!FunctionsReported.insert(Signature).second)
          return;
        break;
      }

      case DeclKind::Subscript: {
        auto Signature = D->getInterfaceType()->getCanonicalType();
        if (!SubscriptsReported.insert(Signature).second)
          return;
        break;
      }

      case DeclKind::Var: {
        auto *VD = cast<VarDecl>(D);
        auto Signature =
            std::make_pair(VD->getName(),
                           VD->getInterfaceType()->getCanonicalType());
        if (!PropertiesReported.insert(Signature).second)
          return;
        break;
      }
      }

      if (isDeclVisibleInLookupMode(D, LS, CurrDC, TypeResolver))
        ChainedConsumer.foundDecl(D, DeclVisibilityKind::DynamicLookup);
    }
  };

  DynamicLookupConsumer ConsumerWrapper(Consumer, LS, CurrDC, TypeResolver);

  CurrDC->getParentSourceFile()->forAllVisibleModules(
      [&](ModuleDecl::ImportedModule Import) {
        Import.second->lookupClassMembers(Import.first, ConsumerWrapper);
      });
}

namespace {
  typedef llvm::SmallPtrSet<TypeDecl *, 8> VisitedSet;
} // end anonymous namespace

static DeclVisibilityKind getReasonForSuper(DeclVisibilityKind Reason) {
  switch (Reason) {
  case DeclVisibilityKind::MemberOfCurrentNominal:
  case DeclVisibilityKind::MemberOfProtocolImplementedByCurrentNominal:
  case DeclVisibilityKind::MemberOfSuper:
    return DeclVisibilityKind::MemberOfSuper;

  case DeclVisibilityKind::MemberOfOutsideNominal:
    return DeclVisibilityKind::MemberOfOutsideNominal;

  default:
    llvm_unreachable("should not see this kind");
  }
}

static void lookupDeclsFromProtocolsBeingConformedTo(
    Type BaseTy, VisibleDeclConsumer &Consumer, LookupState LS,
    const DeclContext *FromContext, DeclVisibilityKind Reason,
    LazyResolver *TypeResolver, VisitedSet &Visited) {
  NominalTypeDecl *CurrNominal = BaseTy->getAnyNominal();
  if (!CurrNominal)
    return;

  for (auto Conformance : CurrNominal->getAllConformances()) {
    auto Proto = Conformance->getProtocol();
    if (!Proto->isAccessibleFrom(FromContext))
      continue;

    DeclVisibilityKind ReasonForThisProtocol;
    if (Reason == DeclVisibilityKind::MemberOfCurrentNominal)
      ReasonForThisProtocol =
          DeclVisibilityKind::MemberOfProtocolImplementedByCurrentNominal;
    else
      ReasonForThisProtocol = getReasonForSuper(Reason);

    auto NormalConformance = Conformance->getRootNormalConformance();
    for (auto Member : Proto->getMembers()) {
      if (auto *ATD = dyn_cast<AssociatedTypeDecl>(Member)) {
        // Skip type decls if they aren't visible, or any type that has a
        // witness. This cuts down on duplicates.
        if (areTypeDeclsVisibleInLookupMode(LS) &&
            !NormalConformance->hasTypeWitness(ATD)) {
          Consumer.foundDecl(ATD, ReasonForThisProtocol);
        }
        continue;
      }
      if (auto *VD = dyn_cast<ValueDecl>(Member)) {
        if (TypeResolver)
          TypeResolver->resolveDeclSignature(VD);

        // Skip value requirements that have corresponding witnesses. This cuts
        // down on duplicates.
        if (!NormalConformance->hasWitness(VD) ||
            !NormalConformance->getWitness(VD, nullptr) ||
            NormalConformance->getWitness(VD, nullptr).getDecl()->getFullName()
              != VD->getFullName()) {
          Consumer.foundDecl(VD, ReasonForThisProtocol);
        }
      }
    }

    // Add members from any extensions.
    SmallVector<ValueDecl *, 2> FoundDecls;
    doGlobalExtensionLookup(BaseTy, Proto->getDeclaredType(), FoundDecls,
                            FromContext, LS, ReasonForThisProtocol,
                            TypeResolver);
    for (auto *VD : FoundDecls)
      Consumer.foundDecl(VD, ReasonForThisProtocol);
  }
}

static void
lookupVisibleMemberDeclsImpl(Type BaseTy, VisibleDeclConsumer &Consumer,
                             const DeclContext *CurrDC, LookupState LS,
                             DeclVisibilityKind Reason,
                             LazyResolver *TypeResolver, VisitedSet &Visited);

static void lookupVisibleProtocolMemberDecls(
    Type BaseTy, ProtocolType *PT, VisibleDeclConsumer &Consumer,
    const DeclContext *CurrDC, LookupState LS, DeclVisibilityKind Reason,
    LazyResolver *TypeResolver, VisitedSet &Visited) {
  if (PT->getDecl()->isSpecificProtocol(KnownProtocolKind::AnyObject)) {
    // Handle AnyObject in a special way.
    doDynamicLookup(Consumer, CurrDC, LS, TypeResolver);
    return;
  }
  if (!Visited.insert(PT->getDecl()).second)
    return;

  for (auto Proto : PT->getDecl()->getInheritedProtocols(nullptr))
    lookupVisibleProtocolMemberDecls(BaseTy, Proto->getDeclaredType(), Consumer, CurrDC,
                                 LS, getReasonForSuper(Reason), TypeResolver,
                                 Visited);

  lookupTypeMembers(BaseTy, PT, Consumer, CurrDC, LS, Reason, TypeResolver);
}

static void lookupVisibleMemberDeclsImpl(
    Type BaseTy, VisibleDeclConsumer &Consumer, const DeclContext *CurrDC,
    LookupState LS, DeclVisibilityKind Reason, LazyResolver *TypeResolver,
    VisitedSet &Visited) {
  // Just look through l-valueness.  It doesn't affect name lookup.
  assert(BaseTy && "lookup into null type");
  BaseTy = BaseTy->getRValueType();

  // Handle metatype references, as in "some_type.some_member".  These are
  // special and can't have extensions.
  if (auto MTT = BaseTy->getAs<AnyMetatypeType>()) {
    // The metatype represents an arbitrary named type: dig through to the
    // declared type to see what we're dealing with.
    Type Ty = MTT->getInstanceType();

    LookupState subLS = LookupState::makeQualified().withOnMetatype();
    if (LS.isIncludingInstanceMembers()) {
      subLS = subLS.withIncludedInstanceMembers();
    }

    // Just perform normal dot lookup on the type see if we find extensions or
    // anything else.  For example, type SomeTy.SomeMember can look up static
    // functions, and can even look up non-static functions as well (thus
    // getting the address of the member).
    lookupVisibleMemberDeclsImpl(Ty, Consumer, CurrDC, subLS, Reason,
                                 TypeResolver, Visited);
    return;
  }

  // Lookup module references, as on some_module.some_member.  These are
  // special and can't have extensions.
  if (ModuleType *MT = BaseTy->getAs<ModuleType>()) {
    AccessFilteringDeclConsumer FilteringConsumer(CurrDC, Consumer,
                                                  TypeResolver);
    MT->getModule()->lookupVisibleDecls(ModuleDecl::AccessPathTy(),
                                        FilteringConsumer,
                                        NLKind::QualifiedLookup);
    return;
  }

  // If the base is a protocol, enumerate its members.
  if (ProtocolType *PT = BaseTy->getAs<ProtocolType>()) {
    lookupVisibleProtocolMemberDecls(BaseTy, PT, Consumer, CurrDC, LS, Reason,
                                     TypeResolver, Visited);
    return;
  }

  // If the base is a protocol composition, enumerate members of the protocols.
  if (auto PC = BaseTy->getAs<ProtocolCompositionType>()) {
    for (auto Proto : PC->getProtocols())
      lookupVisibleMemberDeclsImpl(Proto, Consumer, CurrDC, LS, Reason,
                                   TypeResolver, Visited);
    return;
  }

  // Enumerate members of archetype's requirements.
  if (ArchetypeType *Archetype = BaseTy->getAs<ArchetypeType>()) {
    for (auto Proto : Archetype->getConformsTo())
      lookupVisibleProtocolMemberDecls(
          BaseTy, Proto->getDeclaredType(), Consumer, CurrDC, LS,
          getReasonForSuper(Reason), TypeResolver, Visited);

    if (auto superclass = Archetype->getSuperclass())
      lookupVisibleMemberDeclsImpl(superclass, Consumer, CurrDC, LS,
                                   getReasonForSuper(Reason), TypeResolver,
                                   Visited);
    return;
  }

  do {
    NominalTypeDecl *CurNominal = BaseTy->getAnyNominal();
    if (!CurNominal)
      break;

    // Look in for members of a nominal type.
    lookupTypeMembers(BaseTy, BaseTy, Consumer, CurrDC, LS, Reason,
                      TypeResolver);
    lookupDeclsFromProtocolsBeingConformedTo(BaseTy, Consumer, LS, CurrDC,
                                             Reason, TypeResolver, Visited);
    // If we have a class type, look into its superclass.
    ClassDecl *CurClass = dyn_cast<ClassDecl>(CurNominal);

    if (CurClass && CurClass->hasSuperclass()) {
      assert(BaseTy.getPointer() != CurClass->getSuperclass().getPointer() &&
             "type is its own superclass");
      BaseTy = CurClass->getSuperclass();
      Reason = getReasonForSuper(Reason);

      bool InheritsSuperclassInitializers =
          CurClass->inheritsSuperclassInitializers(TypeResolver);
      if (LS.isOnSuperclass() && !InheritsSuperclassInitializers)
        LS = LS.withoutInheritsSuperclassInitializers();
      else if (!LS.isOnSuperclass()) {
        LS = LS.withOnSuperclass();
        if (InheritsSuperclassInitializers)
          LS = LS.withInheritsSuperclassInitializers();
      }
    } else {
      break;
    }
  } while (1);
}

namespace {

struct FoundDeclTy {
  ValueDecl *D;
  DeclVisibilityKind Reason;

  FoundDeclTy(ValueDecl *D, DeclVisibilityKind Reason)
      : D(D), Reason(Reason) {}

  friend bool operator==(const FoundDeclTy &LHS, const FoundDeclTy &RHS) {
    // If this ever changes - e.g. to include Reason - be sure to also update
    // DenseMapInfo<FoundDeclTy>::getHashValue().
    return LHS.D == RHS.D;
  }
};

} // end anonymous namespace

namespace llvm {

template <> struct DenseMapInfo<FoundDeclTy> {
  static inline FoundDeclTy getEmptyKey() {
    return FoundDeclTy{nullptr, DeclVisibilityKind::LocalVariable};
  }

  static inline FoundDeclTy getTombstoneKey() {
    return FoundDeclTy{reinterpret_cast<ValueDecl *>(0x1),
                       DeclVisibilityKind::LocalVariable};
  }

  static unsigned getHashValue(const FoundDeclTy &Val) {
    // Note: FoundDeclTy::operator== only considers D, so don't hash Reason here.
    return llvm::hash_value(Val.D);
  }

  static bool isEqual(const FoundDeclTy &LHS, const FoundDeclTy &RHS) {
    return LHS == RHS;
  }
};

} // namespace llvm

namespace {

/// Similar to swift::conflicting, but lenient about protocol extensions which
/// don't affect code completion's concept of overloading.
static bool relaxedConflicting(const OverloadSignature &sig1,
                               const OverloadSignature &sig2) {

  // If the base names are different, they can't conflict.
  if (sig1.Name.getBaseName() != sig2.Name.getBaseName())
    return false;

  // If one is a compound name and the other is not, they do not conflict
  // if one is a property and the other is a non-nullary function.
  if (sig1.Name.isCompoundName() != sig2.Name.isCompoundName()) {
    return !((sig1.IsProperty && sig2.Name.getArgumentNames().size() > 0) ||
             (sig2.IsProperty && sig1.Name.getArgumentNames().size() > 0));
  }

  // Allow null property types to match non-null ones, which only happens when
  // one property is from a generic extension and the other is not.
  if (sig1.InterfaceType != sig2.InterfaceType) {
    if (!sig1.IsProperty || !sig2.IsProperty)
      return false;
    if (sig1.InterfaceType && sig2.InterfaceType)
      return false;
  }

  return sig1.Name == sig2.Name && sig1.UnaryOperator == sig2.UnaryOperator &&
         sig1.IsInstanceMember == sig2.IsInstanceMember;
}

class OverrideFilteringConsumer : public VisibleDeclConsumer {
public:
  std::set<ValueDecl *> AllFoundDecls;
  std::map<Identifier, std::set<ValueDecl *>> FoundDecls;
  llvm::SetVector<FoundDeclTy> DeclsToReport;
  Type BaseTy;
  const DeclContext *DC;
  LazyResolver *TypeResolver;

  OverrideFilteringConsumer(Type BaseTy, const DeclContext *DC,
                            LazyResolver *resolver)
      : BaseTy(BaseTy->getRValueType()), DC(DC), TypeResolver(resolver) {
    assert(DC && BaseTy);
  }

  void foundDecl(ValueDecl *VD, DeclVisibilityKind Reason) override {
    if (!AllFoundDecls.insert(VD).second)
      return;

    // If this kind of declaration doesn't participate in overriding, there's
    // no filtering to do here.
    if (!isa<AbstractFunctionDecl>(VD) && !isa<AbstractStorageDecl>(VD)) {
      DeclsToReport.insert(FoundDeclTy(VD, Reason));
      return;
    }

    if (TypeResolver) {
      TypeResolver->resolveDeclSignature(VD);
      TypeResolver->resolveAccessibility(VD);
    }

    if (VD->isInvalid()) {
      FoundDecls[VD->getName()].insert(VD);
      DeclsToReport.insert(FoundDeclTy(VD, Reason));
      return;
    }
    auto &PossiblyConflicting = FoundDecls[VD->getName()];

    // Check all overridden decls.
    {
      auto *CurrentVD = VD->getOverriddenDecl();
      while (CurrentVD) {
        if (!AllFoundDecls.insert(CurrentVD).second)
          break;
        if (PossiblyConflicting.count(CurrentVD)) {
          PossiblyConflicting.erase(CurrentVD);
          PossiblyConflicting.insert(VD);

          bool Erased = DeclsToReport.remove(
              FoundDeclTy(CurrentVD, DeclVisibilityKind::LocalVariable));
          assert(Erased);
          (void)Erased;

          DeclsToReport.insert(FoundDeclTy(VD, Reason));
          return;
        }
        CurrentVD = CurrentVD->getOverriddenDecl();
      }
    }

    // Does it make sense to substitute types?
    bool shouldSubst = !BaseTy->hasUnboundGenericType() &&
                       !isa<AnyMetatypeType>(BaseTy.getPointer()) &&
                       !BaseTy->isAnyExistentialType() &&
                       !BaseTy->hasTypeVariable() &&
                       VD->getDeclContext()->isTypeContext();
    ModuleDecl *M = DC->getParentModule();

    auto FoundSignature = VD->getOverloadSignature();
    if (FoundSignature.InterfaceType && shouldSubst) {
      auto subs = BaseTy->getMemberSubstitutions(VD);
      if (auto CT = FoundSignature.InterfaceType.subst(M, subs, None))
        FoundSignature.InterfaceType = CT->getCanonicalType();
    }

    for (auto I = PossiblyConflicting.begin(), E = PossiblyConflicting.end();
         I != E; ++I) {
      auto *OtherVD = *I;
      if (OtherVD->isInvalid()) {
        // For some invalid decls it might be impossible to compute the
        // signature, for example, if the types could not be resolved.
        continue;
      }

      auto OtherSignature = OtherVD->getOverloadSignature();
      if (OtherSignature.InterfaceType && shouldSubst) {
        auto subs = BaseTy->getMemberSubstitutions(OtherVD);
        if (auto CT = OtherSignature.InterfaceType.subst(M, subs, None))
          OtherSignature.InterfaceType = CT->getCanonicalType();
      }

      if (relaxedConflicting(FoundSignature, OtherSignature)) {
        if (VD->getFormalAccess() > OtherVD->getFormalAccess()) {
          PossiblyConflicting.erase(I);
          PossiblyConflicting.insert(VD);

          bool Erased = DeclsToReport.remove(
              FoundDeclTy(OtherVD, DeclVisibilityKind::LocalVariable));
          assert(Erased);
          (void)Erased;

          DeclsToReport.insert(FoundDeclTy(VD, Reason));
        }
        return;
      }
    }

    PossiblyConflicting.insert(VD);
    DeclsToReport.insert(FoundDeclTy(VD, Reason));
  }
};
} // unnamed namespace

/// \brief Enumerate all members in \c BaseTy (including members of extensions,
/// superclasses and implemented protocols), as seen from the context \c CurrDC.
///
/// This operation corresponds to a standard "dot" lookup operation like "a.b"
/// where 'self' is the type of 'a'.  This operation is only valid after name
/// binding.
static void lookupVisibleMemberDecls(
    Type BaseTy, VisibleDeclConsumer &Consumer, const DeclContext *CurrDC,
    LookupState LS, DeclVisibilityKind Reason, LazyResolver *TypeResolver) {
  OverrideFilteringConsumer ConsumerWrapper(BaseTy, CurrDC, TypeResolver);
  VisitedSet Visited;
  lookupVisibleMemberDeclsImpl(BaseTy, ConsumerWrapper, CurrDC, LS, Reason,
                               TypeResolver, Visited);

  // Report the declarations we found to the real consumer.
  for (const auto &DeclAndReason : ConsumerWrapper.DeclsToReport)
    Consumer.foundDecl(DeclAndReason.D, DeclAndReason.Reason);
}

void swift::lookupVisibleDecls(VisibleDeclConsumer &Consumer,
                               const DeclContext *DC,
                               LazyResolver *TypeResolver,
                               bool IncludeTopLevel,
                               SourceLoc Loc) {
  const ModuleDecl &M = *DC->getParentModule();
  const SourceManager &SM = DC->getASTContext().SourceMgr;
  auto Reason = DeclVisibilityKind::MemberOfCurrentNominal;

  // If we are inside of a method, check to see if there are any ivars in scope,
  // and if so, whether this is a reference to one of them.
  while (!DC->isModuleScopeContext()) {
    const ValueDecl *BaseDecl = nullptr;
    GenericParamList *GenericParams = nullptr;
    Type ExtendedType;
    auto LS = LookupState::makeUnqualified();

    // Skip initializer contexts, we will not find any declarations there.
    if (isa<Initializer>(DC)) {
      DC = DC->getParent();
      LS = LS.withOnMetatype();
    }

    if (auto *AFD = dyn_cast<AbstractFunctionDecl>(DC)) {
      // Look for local variables; normally, the parser resolves these
      // for us, but it can't do the right thing inside local types.
      // FIXME: when we can parse and typecheck the function body partially for
      // code completion, AFD->getBody() check can be removed.
      if (Loc.isValid() && AFD->getBody()) {
        namelookup::FindLocalVal(SM, Loc, Consumer).visit(AFD->getBody());
      }

      for (auto *P : AFD->getParameterLists())
        namelookup::FindLocalVal(SM, Loc, Consumer).checkParameterList(P);

      // Constructors and destructors don't have 'self' in parameter patterns.
      if (isa<ConstructorDecl>(AFD) || isa<DestructorDecl>(AFD))
        if (auto *selfParam = AFD->getImplicitSelfDecl())
          Consumer.foundDecl(const_cast<ParamDecl*>(selfParam),
                             DeclVisibilityKind::FunctionParameter);

      if (AFD->getDeclContext()->isTypeContext()) {
        ExtendedType = AFD->getDeclContext()->getSelfTypeInContext();
        BaseDecl = AFD->getImplicitSelfDecl();
        DC = DC->getParent();

        if (auto *FD = dyn_cast<FuncDecl>(AFD))
          if (FD->isStatic())
            ExtendedType = MetatypeType::get(ExtendedType);
      }

      // Look in the generic parameters after checking our local declaration.
      GenericParams = AFD->getGenericParams();
    } else if (auto CE = dyn_cast<ClosureExpr>(DC)) {
      if (Loc.isValid()) {
        namelookup::FindLocalVal(SM, Loc, Consumer).visit(CE->getBody());
        if (auto P = CE->getParameters()) {
          namelookup::FindLocalVal(SM, Loc, Consumer).checkParameterList(P);
        }
      }
    } else if (auto ED = dyn_cast<ExtensionDecl>(DC)) {
      ExtendedType = ED->getExtendedType();
      if (ExtendedType)
        BaseDecl = ExtendedType->getNominalOrBoundGenericNominal();
    } else if (auto ND = dyn_cast<NominalTypeDecl>(DC)) {
      ExtendedType = ND->getDeclaredType();
      BaseDecl = ND;
    }

    if (BaseDecl && ExtendedType) {
      ::lookupVisibleMemberDecls(ExtendedType, Consumer, DC, LS, Reason,
                                 TypeResolver);
    }

    // Check any generic parameters for something with the given name.
    namelookup::FindLocalVal(SM, Loc, Consumer)
          .checkGenericParams(GenericParams);

    DC = DC->getParent();
    Reason = DeclVisibilityKind::MemberOfOutsideNominal;
  }

  SmallVector<ModuleDecl::ImportedModule, 8> extraImports;
  if (auto SF = dyn_cast<SourceFile>(DC)) {
    if (Loc.isValid()) {
      // Look for local variables in top-level code; normally, the parser
      // resolves these for us, but it can't do the right thing for
      // local types.
      namelookup::FindLocalVal(SM, Loc, Consumer).checkSourceFile(*SF);
    }

    if (IncludeTopLevel) {
      auto &cached = SF->getCachedVisibleDecls();
      if (!cached.empty()) {
        for (auto result : cached)
          Consumer.foundDecl(result, DeclVisibilityKind::VisibleAtTopLevel);
        return;
      }

      SF->getImportedModules(extraImports, ModuleDecl::ImportFilter::Private);
    }
  }

  if (IncludeTopLevel) {
    using namespace namelookup;
    SmallVector<ValueDecl *, 0> moduleResults;
    auto &mutableM = const_cast<ModuleDecl&>(M);
    lookupVisibleDeclsInModule(&mutableM, {}, moduleResults,
                               NLKind::UnqualifiedLookup,
                               ResolutionKind::Overloadable,
                               TypeResolver, DC, extraImports);
    for (auto result : moduleResults)
      Consumer.foundDecl(result, DeclVisibilityKind::VisibleAtTopLevel);

    if (auto SF = dyn_cast<SourceFile>(DC))
      SF->cacheVisibleDecls(std::move(moduleResults));
  }
}

void swift::lookupVisibleMemberDecls(VisibleDeclConsumer &Consumer, Type BaseTy,
                                     const DeclContext *CurrDC,
                                     LazyResolver *TypeResolver,
                                     bool includeInstanceMembers) {
  assert(CurrDC);
  LookupState ls = LookupState::makeQualified();
  if (includeInstanceMembers) {
    ls = ls.withIncludedInstanceMembers();
  }

  ::lookupVisibleMemberDecls(BaseTy, Consumer, CurrDC, ls,
                             DeclVisibilityKind::MemberOfCurrentNominal,
                             TypeResolver);
}


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

import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.fail;

import com.google.common.collect.Maps;
import com.google.devtools.build.lib.actions.ActionInput;
import com.google.devtools.build.lib.actions.ActionInputHelper;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.actions.EmptyRunfilesSupplier;
import com.google.devtools.build.lib.actions.Root;
import com.google.devtools.build.lib.actions.RunfilesSupplier;
import com.google.devtools.build.lib.analysis.Runfiles;
import com.google.devtools.build.lib.analysis.RunfilesSupplierImpl;
import com.google.devtools.build.lib.exec.util.FakeActionInputFileCache;
import com.google.devtools.build.lib.skyframe.FileArtifactValue;
import com.google.devtools.build.lib.vfs.FileSystem;
import com.google.devtools.build.lib.vfs.FileSystemUtils;
import com.google.devtools.build.lib.vfs.Path;
import com.google.devtools.build.lib.vfs.PathFragment;
import com.google.devtools.build.lib.vfs.inmemoryfs.InMemoryFileSystem;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/**
 * Tests for {@link SpawnInputExpander}.
 */
@RunWith(JUnit4.class)
public class SpawnInputExpanderTest {
  private static final byte[] FAKE_DIGEST = new byte[] {1, 2, 3, 4};

  private FileSystem fs;
  private SpawnInputExpander expander;
  private Map<PathFragment, ActionInput> inputMappings;

  @Before
  public final void createSpawnInputExpander() throws Exception  {
    fs = new InMemoryFileSystem();
    expander = new SpawnInputExpander(/*strict=*/true);
    inputMappings = Maps.newHashMap();
  }

  private void scratchFile(String file, String... lines) throws Exception {
    Path path = fs.getPath(file);
    FileSystemUtils.createDirectoryAndParents(path.getParentDirectory());
    FileSystemUtils.writeLinesAs(path, StandardCharsets.UTF_8, lines);
  }

  @Test
  public void testEmptyRunfiles() throws Exception {
    RunfilesSupplier supplier = EmptyRunfilesSupplier.INSTANCE;
    expander.addRunfilesToInputs(inputMappings, supplier, null);
    assertThat(inputMappings).isEmpty();
  }

  @Test
  public void testRunfilesSingleFile() throws Exception {
    Artifact artifact =
        new Artifact(fs.getPath("/root/dir/file"), Root.asSourceRoot(fs.getPath("/root")));
    Runfiles runfiles = new Runfiles.Builder("workspace").addArtifact(artifact).build();
    RunfilesSupplier supplier = new RunfilesSupplierImpl(PathFragment.create("runfiles"), runfiles);
    FakeActionInputFileCache mockCache = new FakeActionInputFileCache();
    mockCache.put(artifact, FileArtifactValue.createNormalFile(FAKE_DIGEST, 0));

    expander.addRunfilesToInputs(inputMappings, supplier, mockCache);
    assertThat(inputMappings).hasSize(1);
    assertThat(inputMappings)
        .containsEntry(PathFragment.create("runfiles/workspace/dir/file"), artifact);
  }

  @Test
  public void testRunfilesDirectoryStrict() throws Exception {
    Artifact artifact =
        new Artifact(fs.getPath("/root/dir/file"), Root.asSourceRoot(fs.getPath("/root")));
    Runfiles runfiles = new Runfiles.Builder("workspace").addArtifact(artifact).build();
    RunfilesSupplier supplier = new RunfilesSupplierImpl(PathFragment.create("runfiles"), runfiles);
    FakeActionInputFileCache mockCache = new FakeActionInputFileCache();
    mockCache.put(artifact, FileArtifactValue.createDirectory(-1));

    try {
      expander.addRunfilesToInputs(inputMappings, supplier, mockCache);
      fail();
    } catch (IOException expected) {
      assertThat(expected.getMessage().contains("Not a file: /root/dir/file")).isTrue();
    }
  }

  @Test
  public void testRunfilesDirectoryNonStrict() throws Exception {
    Artifact artifact =
        new Artifact(fs.getPath("/root/dir/file"), Root.asSourceRoot(fs.getPath("/root")));
    Runfiles runfiles = new Runfiles.Builder("workspace").addArtifact(artifact).build();
    RunfilesSupplier supplier = new RunfilesSupplierImpl(PathFragment.create("runfiles"), runfiles);
    FakeActionInputFileCache mockCache = new FakeActionInputFileCache();
    mockCache.put(artifact, FileArtifactValue.createDirectory(-1));

    expander = new SpawnInputExpander(/*strict=*/false);
    expander.addRunfilesToInputs(inputMappings, supplier, mockCache);
    assertThat(inputMappings).hasSize(1);
    assertThat(inputMappings)
        .containsEntry(PathFragment.create("runfiles/workspace/dir/file"), artifact);
  }

  @Test
  public void testRunfilesTwoFiles() throws Exception {
    Artifact artifact1 =
        new Artifact(fs.getPath("/root/dir/file"), Root.asSourceRoot(fs.getPath("/root")));
    Artifact artifact2 =
        new Artifact(fs.getPath("/root/dir/baz"), Root.asSourceRoot(fs.getPath("/root")));
    Runfiles runfiles = new Runfiles.Builder("workspace")
        .addArtifact(artifact1)
        .addArtifact(artifact2)
        .build();
    RunfilesSupplier supplier = new RunfilesSupplierImpl(PathFragment.create("runfiles"), runfiles);
    FakeActionInputFileCache mockCache = new FakeActionInputFileCache();
    mockCache.put(artifact1, FileArtifactValue.createNormalFile(FAKE_DIGEST, 1));
    mockCache.put(artifact2, FileArtifactValue.createNormalFile(FAKE_DIGEST, 2));

    expander.addRunfilesToInputs(inputMappings, supplier, mockCache);
    assertThat(inputMappings).hasSize(2);
    assertThat(inputMappings)
        .containsEntry(PathFragment.create("runfiles/workspace/dir/file"), artifact1);
    assertThat(inputMappings)
        .containsEntry(PathFragment.create("runfiles/workspace/dir/baz"), artifact2);
  }

  @Test
  public void testRunfilesSymlink() throws Exception {
    Artifact artifact =
        new Artifact(fs.getPath("/root/dir/file"), Root.asSourceRoot(fs.getPath("/root")));
    Runfiles runfiles = new Runfiles.Builder("workspace")
        .addSymlink(PathFragment.create("symlink"), artifact).build();
    RunfilesSupplier supplier = new RunfilesSupplierImpl(PathFragment.create("runfiles"), runfiles);
    FakeActionInputFileCache mockCache = new FakeActionInputFileCache();
    mockCache.put(artifact, FileArtifactValue.createNormalFile(FAKE_DIGEST, 1));

    expander.addRunfilesToInputs(inputMappings, supplier, mockCache);
    assertThat(inputMappings).hasSize(1);
    assertThat(inputMappings)
        .containsEntry(PathFragment.create("runfiles/workspace/symlink"), artifact);
  }

  @Test
  public void testRunfilesRootSymlink() throws Exception {
    Artifact artifact =
        new Artifact(fs.getPath("/root/dir/file"), Root.asSourceRoot(fs.getPath("/root")));
    Runfiles runfiles = new Runfiles.Builder("workspace")
        .addRootSymlink(PathFragment.create("symlink"), artifact).build();
    RunfilesSupplier supplier = new RunfilesSupplierImpl(PathFragment.create("runfiles"), runfiles);
    FakeActionInputFileCache mockCache = new FakeActionInputFileCache();
    mockCache.put(artifact, FileArtifactValue.createNormalFile(FAKE_DIGEST, 1));

    expander.addRunfilesToInputs(inputMappings, supplier, mockCache);
    assertThat(inputMappings).hasSize(2);
    assertThat(inputMappings).containsEntry(PathFragment.create("runfiles/symlink"), artifact);
    // If there's no other entry, Runfiles adds an empty file in the workspace to make sure the
    // directory gets created.
    assertThat(inputMappings)
        .containsEntry(
            PathFragment.create("runfiles/workspace/.runfile"), SpawnInputExpander.EMPTY_FILE);
  }

  @Test
  public void testEmptyManifest() throws Exception {
    // See AnalysisUtils for the mapping from "foo" to "_foo/MANIFEST".
    scratchFile("/root/_foo/MANIFEST");

    Artifact artifact =
        new Artifact(fs.getPath("/root/foo"), Root.asSourceRoot(fs.getPath("/root")));
    expander.parseFilesetManifest(inputMappings, artifact, "workspace");
    assertThat(inputMappings).isEmpty();
  }

  @Test
  public void testManifestWithSingleFile() throws Exception {
    // See AnalysisUtils for the mapping from "foo" to "_foo/MANIFEST".
    scratchFile(
        "/root/out/_foo/MANIFEST",
        "workspace/bar /dir/file",
        "<some digest>");

    Root outputRoot = Root.asDerivedRoot(fs.getPath("/root"), fs.getPath("/root/out"), true);
    Artifact artifact = new Artifact(fs.getPath("/root/out/foo"), outputRoot);
    expander.parseFilesetManifest(inputMappings, artifact, "workspace");
    assertThat(inputMappings).hasSize(1);
    assertThat(inputMappings)
        .containsEntry(PathFragment.create("out/foo/bar"), ActionInputHelper.fromPath("/dir/file"));
  }

  @Test
  public void testManifestWithTwoFiles() throws Exception {
    // See AnalysisUtils for the mapping from "foo" to "_foo/MANIFEST".
    scratchFile(
        "/root/out/_foo/MANIFEST",
        "workspace/bar /dir/file",
        "<some digest>",
        "workspace/baz /dir/file",
        "<some digest>");

    Root outputRoot = Root.asDerivedRoot(fs.getPath("/root"), fs.getPath("/root/out"), true);
    Artifact artifact = new Artifact(fs.getPath("/root/out/foo"), outputRoot);
    expander.parseFilesetManifest(inputMappings, artifact, "workspace");
    assertThat(inputMappings).hasSize(2);
    assertThat(inputMappings)
        .containsEntry(PathFragment.create("out/foo/bar"), ActionInputHelper.fromPath("/dir/file"));
    assertThat(inputMappings)
        .containsEntry(PathFragment.create("out/foo/baz"), ActionInputHelper.fromPath("/dir/file"));
  }

  @Test
  public void testManifestWithDirectory() throws Exception {
    // See AnalysisUtils for the mapping from "foo" to "_foo/MANIFEST".
    scratchFile(
        "/root/out/_foo/MANIFEST",
        "workspace/bar /some",
        "<some digest>");

    Root outputRoot = Root.asDerivedRoot(fs.getPath("/root"), fs.getPath("/root/out"), true);
    Artifact artifact = new Artifact(fs.getPath("/root/out/foo"), outputRoot);
    expander.parseFilesetManifest(inputMappings, artifact, "workspace");
    assertThat(inputMappings).hasSize(1);
    assertThat(inputMappings)
        .containsEntry(
            PathFragment.create("out/foo/bar"), ActionInputHelper.fromPath("/some"));
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<resources>

    <color name="just_white">#FFFFFFFF</color>
    <color name="just_black">#FF000000</color>
    <color name="background_dark">#FF000000</color>
    <color name="background_light">#FFFFFFFF</color>
    <color name="background_dark_notice">#FF191919</color>
    <color name="background_light_notice">#FFDFDFDF</color>
    <color name="background_dark_transparent">#44000000</color>
    <color name="background_light_transparent">#44FFFFFF</color>
    <color name="separator_dark">#44FFFFFF</color>
    <color name="separator_light">#44000000</color>
    <color name="text_icon">#FFFFFFFF</color>
    <color name="text_dark">#FFFFFFFF</color>
    <color name="text_light">#FF000000</color>
    <color name="text_headline_dark">#88FFFFFF</color>
    <color name="text_headline_light">#88000000</color>
    <color name="text_grey_dark">#AAFFFFFF</color>
    <color name="text_grey_light">#AA000000</color>
    <color name="text_hint_dark">#44FFFFFF</color>
    <color name="text_hint_light">#44000000</color>
    <color name="link">#FF00C0FF</color>
    <color name="button_enabled">#FF000000</color>
    <color name="button_disabled">#66000000</color>
    <color name="archived_cache_color">#FFAC0B0B</color>
    <color name="button_default">#282828</color>
    <color name="steel">#675C68</color>

</resources>


text:
package org.hisp.dhis.android.core.program.internal;

import org.hisp.dhis.android.core.arch.db.access.DatabaseAdapter;
import org.hisp.dhis.android.core.arch.db.stores.internal.IdentifiableObjectStore;
import org.hisp.dhis.android.core.arch.handlers.internal.HandlerWithTransformer;
import org.hisp.dhis.android.core.arch.repositories.children.internal.ChildrenAppender;
import org.hisp.dhis.android.core.program.ProgramStageSection;

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

import dagger.Module;
import dagger.Provides;
import dagger.Reusable;

@Module
public final class ProgramStageSectionEntityDIModule {

    @Provides
    @Reusable
    public IdentifiableObjectStore<ProgramStageSection> store(DatabaseAdapter databaseAdapter) {
        return ProgramStageSectionStore.create(databaseAdapter);
    }

    @Provides
    @Reusable
    public HandlerWithTransformer<ProgramStageSection> handler(ProgramStageSectionHandler impl) {
        return impl;
    }

    @Provides
    @Reusable
    @SuppressWarnings("PMD.NonStaticInitializer")
    Map<String, ChildrenAppender<ProgramStageSection>> childrenAppenders(DatabaseAdapter databaseAdapter) {
        return new HashMap<String, ChildrenAppender<ProgramStageSection>>() {{
            put(ProgramStageSectionFields.PROGRAM_INDICATORS,
                    ProgramStageSectionProgramIndicatorChildrenAppender.create(databaseAdapter));
            put(ProgramStageSectionFields.DATA_ELEMENTS,
                    ProgramStageSectionDataElementChildrenAppender.create(databaseAdapter));
        }};
    }
}


text:
package org.apache.ambari.server.api.services;

import org.apache.ambari.server.controller.ApiModel;
import org.apache.ambari.server.controller.SettingRequest;
import org.apache.ambari.server.controller.internal.SettingResourceProvider;

import io.swagger.annotations.ApiModelProperty;

@SuppressWarnings("unused") // for Swagger
public interface SettingRequestSwagger extends ApiModel {
  @ApiModelProperty(name = SettingResourceProvider.RESPONSE_KEY)
  SettingRequest getSettingRequest();
}


text:
package blue.lapis.pore.impl.event.player;

import static com.google.common.base.Preconditions.checkNotNull;

import org.apache.commons.lang3.NotImplementedException;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerKickEvent;
import org.spongepowered.api.event.entity.player.PlayerEvent;

public class PorePlayerKickEvent extends PlayerKickEvent {

    private final PlayerEvent handle;

    public PorePlayerKickEvent(PlayerEvent handle) {
        super(null, null, null);
        this.handle = checkNotNull(handle, "handle");
    }

    public PlayerEvent getHandle() {
        return handle;
    }

    @Override
    public Player getPlayer() {
        throw new NotImplementedException("TODO");
    }

    @Override
    public String getReason() {
        throw new NotImplementedException("TODO");
    }

    @Override
    public void setReason(String kickReason) {
        throw new NotImplementedException("TODO");
    }

    @Override
    public String getLeaveMessage() {
        throw new NotImplementedException("TODO");
    }

    @Override
    public void setLeaveMessage(String leaveMessage) {
        throw new NotImplementedException("TODO");
    }

    @Override
    public boolean isCancelled() {
        throw new NotImplementedException("TODO");
    }

    @Override
    public void setCancelled(boolean cancel) {
        throw new NotImplementedException("TODO");
    }

}


text:
package nl.nn.adapterframework.configuration.classloaders;

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

import java.net.URL;
import java.util.List;
import java.util.jar.JarFile;

import org.junit.Test;

import nl.nn.adapterframework.testutil.TestAppender;

public class JarFileClassLoaderTest extends ConfigurationClassLoaderTestBase<JarFileClassLoader> {

	@Override
	protected String getScheme() {
		return "classpath";
	}

	@Override
	public JarFileClassLoader createClassLoader(ClassLoader parent) throws Exception {
		return createClassLoader(parent, JAR_FILE);
	}

	private JarFileClassLoader createClassLoader(ClassLoader parent, String jarFile) throws Exception {
		URL file = this.getClass().getResource(jarFile);
		assertNotNull("jar url ["+jarFile+"] not found", file);

		assertNotNull("jar file not found", new JarFile(file.getFile())); // verify the jar file

		JarFileClassLoader cl = new JarFileClassLoader(parent);
		cl.setJar(file.getFile());
		appConstants.put("configurations."+getConfigurationName()+".jar", file.getFile());
		return cl;
	}

	/* test files that are only present in the JAR_FILE zip */
	@Test
	public void classloaderOnlyFile() {
		resourceExists("fileOnlyOnZipClassPath.xml");
	}

	@Test
	public void classloaderOnlyFolder() {
		resourceExists("ClassLoader/fileOnlyOnZipClassPath.xml");
	}

	@Test
	public void checkFilePathWithoutBasePath() throws Exception {
		String filename = "fileOnlyOnZipClassPath.xml";

		createAndConfigure("ClassLoader"); //Create a ClassLoader with BasePath

		URL url = getResource(filename);
		assertEquals("Path of resource invalid", filename, url.getPath());
	}

	@Test
	public void checkFilePathWithBasePath() throws Exception {
		String fileNameWithBasePath = "ClassLoader/fileOnlyOnZipClassPath.xml";

		URL url = getResource(fileNameWithBasePath); //This ClassLoader doesn't have a BasePath so we need to append it
		assertEquals("Path of resource invalid", fileNameWithBasePath, url.getPath());
	}

	@Test
	public void testMyConfig() throws Exception {
		TestAppender appender = TestAppender.newBuilder().useIbisPatternLayout("%level - %m").build();
		TestAppender.addToRootLogger(appender);

		try {
			JarFileClassLoader classLoader = createClassLoader(null, "/ClassLoader/zip/myConfig.zip");

			appConstants.put("configurations.myConfig.classLoaderType", classLoader.getClass().getSimpleName());
			classLoader.configure(ibisContext, "myConfig");

			List<String> logEvents = appender.getLogLines();
			System.out.println(logEvents);
			URL configurationURL = classLoader.getResource("Configuration.xml");
			assertNotNull("unable to locate test file [Configuration.xml]", configurationURL);

			assertEquals("Should find 8 log messages", 8, logEvents.size());
			long warnMsgs = logEvents.stream().filter(k -> k.startsWith("WARN")).count();
			assertEquals("Should find one warning message", 1, warnMsgs);
		} finally {
			TestAppender.removeAppender(appender);
		}
	}
}


text:
package sample.dialogs;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;

import sample.engine.JavaTypeItemsFilter;
import sample.history.JavaTypeSelectionHistory;
/**
 *
 * @author CuiKun cuikunbj@cn.ibm.com
 *
 */
@SuppressWarnings("unchecked")
public class JavaTypeContentProvider implements IStructuredContentProvider {

	private JavaTypeSelectionHistory javaTypeSelectionHistory;

	private OpenJavaTypeByAuthorDialog dialog;

	private List items;

	private List resultItems;

	private List sortedItems;

	public JavaTypeContentProvider(
			JavaTypeSelectionHistory pluginSelectionHistory,
			OpenJavaTypeByAuthorDialog dialog) {
		this.items = new ArrayList();
		this.resultItems = new ArrayList();
		this.sortedItems = new ArrayList();
		this.dialog = dialog;
		this.javaTypeSelectionHistory = pluginSelectionHistory;
	}

	public void add(Object item) {
		boolean contained = false;
		Iterator iterator = items.iterator();
		while (iterator.hasNext()) {
			if (iterator.next().equals(item)) {
				contained = true;
				break;
			}
		}
		if (!contained) {
			this.items.add(item);
		}
	}

	public void addHistoryItems(JavaTypeItemsFilter itemsFilter) {
		if (this.javaTypeSelectionHistory != null) {
			Object[] items = this.javaTypeSelectionHistory.getHistoryItems();
			for (int i = 0; i < items.length; i++) {
				Object item = items[i];
				if (itemsFilter != null) {
					if (itemsFilter.matchItem(item)) {
						if (itemsFilter.isConsistentItem(item)) {
							if (!this.items.contains(item)) {
								this.items.add(item);
							}
						} else {
							this.javaTypeSelectionHistory.remove(item);
						}
					}
				}
			}
		}
	}

	public void refresh() {
		setResultItems();
		Display.getDefault().asyncExec(new Runnable() {
			@Override
			public void run() {
				TableViewer viewer = dialog.getTableViewer();
				if (viewer != null && !viewer.getTable().isDisposed()) {
					viewer.setItemCount(resultItems.size());
					viewer.refresh();
					if (resultItems.size() > 0) {
						viewer.getTable().setSelection(0);
						viewer.getTable().notifyListeners(SWT.Selection,
								new Event());
					}
				}
			}
		});
	}

	public void reset() {
		this.items.clear();
		this.sortedItems.clear();
	}

	private Comparator getHistoryComparator() {
		return new JavaTypeHistoryComparator();
	}

	public void addHistoryElement(Object item) {
		if (this.javaTypeSelectionHistory != null)
			this.javaTypeSelectionHistory.accessed(item);
		if (dialog.getFilter() == null || !dialog.getFilter().matchItem(item)) {
			this.items.remove(item);
			this.sortedItems.remove(item);
		}
		synchronized (sortedItems) {
			Collections.sort(sortedItems, getHistoryComparator());
		}
		this.refresh();
	}

	public boolean isHistoryElement(Object item) {
		if (!(item instanceof JavaTypeNameMatch)) {
			return false;
		}
		if (this.javaTypeSelectionHistory != null) {
			return this.javaTypeSelectionHistory.contains(item);
		}
		return false;
	}

	public void rememberResult(JavaTypeItemsFilter itemsFilter) {
		if (sortedItems.size() != items.size()) {
			synchronized (sortedItems) {
				sortedItems.clear();
				sortedItems.addAll(items);
				Collections.sort(sortedItems, getHistoryComparator());
			}
		}
		List itemsList = new ArrayList();
		itemsList.addAll(sortedItems);
		if (itemsFilter == dialog.getFilter()) {
			dialog.setLastCompletedFilter(itemsFilter);
			dialog.setLastCompletedResult(itemsList);
		}

	}

	private void setResultItems() {
		if (sortedItems.size() != items.size()) {
			synchronized (sortedItems) {
				sortedItems.clear();
				sortedItems.addAll(items);
				Collections.sort(sortedItems, getHistoryComparator());
			}
		}
		resultItems.clear();
		boolean hasHistory = false;
		if (sortedItems.size() > 0) {
			hasHistory = isHistoryElement(sortedItems.get(0));
		}
		for (Object o : sortedItems) {
			if (hasHistory && !isHistoryElement(o)) {
				resultItems.add(new JavaTypeItemsListSeparator(
						"Workspace Matches"));
				hasHistory = false;
			}
			resultItems.add(o);
		}
	}

	public Object[] getElements(Object inputElement) {
		return resultItems.toArray();
	}

	public void dispose() {

	}

	public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
	}

	public void updateElement(int index) {

		dialog.getTableViewer().replace(
				(resultItems.size() > index) ? resultItems.get(index) : null,
				index);

	}

	private class JavaTypeHistoryComparator implements Comparator {

		public int compare(Object o1, Object o2) {
			if (!(o1 instanceof JavaTypeNameMatch)
					|| !(o2 instanceof JavaTypeNameMatch)) {
				return 0;
			}
			JavaTypeNameMatch type1 = (JavaTypeNameMatch) o1, type2 = (JavaTypeNameMatch) o2;
			boolean history1 = isHistoryElement(type1), history2 = isHistoryElement(type2);
			if (history1 ^ history2) {
				if (history1) {
					return -1;
				} else {
					return 1;
				}
			} else {
				String name1 = null, name2 = null;
				name1 = type1.getAuthorName();
				name2 = type2.getAuthorName();
				if (name1 == null || name2 == null) {
					return 0;
				}
				int nameCompare = name1.compareTo(name2);
				if (nameCompare == 0) {
					return type1.getFullyQualifiedName().compareTo(
							type2.getFullyQualifiedName());
				} else {
					return nameCompare;
				}
			}
		}
	}

}


text:
package com.reserva;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.reserva.database.usersDataSource;

public class login extends Activity implements View.OnClickListener {

    EditText txt_username;
    EditText txt_password;
    Button btn_login;
    Button btn_register;
    Button btn_reservation;
    usersDataSource usersDataSource;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);

        txt_username = (EditText)findViewById(R.id.username_layout);
        txt_password = (EditText)findViewById(R.id.password_layout);
        btn_login = (Button)findViewById(R.id.login_button);
        btn_register = (Button)findViewById(R.id.register_button);
        btn_reservation = (Button)findViewById(R.id.reservation_button);
        btn_login.setOnClickListener(this);
        btn_register.setOnClickListener(this);
        btn_reservation.setOnClickListener(this);
        usersDataSource = new usersDataSource(this);
    }

    @Override
    public void onClick(View view) {
        if(view.getId() == R.id.login_button){
            String username = txt_username.getText().toString();
            String password = txt_password.getText().toString();
            Boolean login = isValidLogin(username, password);
            Toast.makeText(this, String.valueOf(login) + " Login", Toast.LENGTH_SHORT).show();
        } else if(view.getId() == R.id.register_button){
            Intent registerActivity = new Intent(this, register.class);
            startActivity(registerActivity);
            finish();
        } else if(view.getId() == R.id.reservation_button){
            Intent mainActivity = new Intent(this, MainActivity.class);
            startActivity(mainActivity);
            finish();
        }
    }

    public boolean isValidLogin(String username, String password){
        usersDataSource.open();
        if(usersDataSource.getUser(username, password) == null){
            return false;
        }
        return true;
    }
}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class data_customer extends CI_Model {
    public function __construct()
	{
		parent::__construct();
		$this->load->library('script_sql');
	}

	public function get_all()
	{
		 $this->db->select('*,u.user_id as user_id,u.is_permanent as is_permanent');
        $this->db->from('customer u');
        $this->db->join('data_user_customer a', 'a.user_id=u.user_id and a.is_delete=0');
        $this->db->where('u.is_delete', '0');
		$query = $this->db->get();
		return $query->result() ;
	}

	public function get_by_id($customer_id)
	{
		 $this->db->select();
        $this->db->from('customer');
        $this->db->where('is_delete', '0');
        $this->db->where('customer_id', $customer_id);
		$query = $this->db->get();
		return $query->result() ;
	}

	public function get_row_by_id($customer_id)
	{
		 $this->db->select();
        $this->db->from('customer');
        $this->db->where('is_delete', '0');
        $this->db->where('customer_id', $customer_id);
		$query = $this->db->get();
		return $query->row() ;
	}

	public function show()
	{
		 $this->db->select();
        $this->db->from('customer');
        $this->db->where('is_delete', '0');
		$query = $this->db->get();
		return $query->result() ;
	}

	public function insert($data)
	{
		$temp=$this->db->insert('customer', $data);
		$this->session->set_userdata("last_id",$this->db->insert_id());
		return $temp;

	}

	public function delete_permanent($customer_id)
	{
		$data = array('customer_id' => $customer_id);
		$this->db->delete('customer', $data);
		$temp=$this->session->set_userdata("last_id",$customer_id);
	    return $temp;

	}

	public function delete_semu($customer_id)
	{
		$data_lama=$this->db->query('select * from customer where customer_id="'.$customer_id.'"')->num_rows();

	   $data = array(
			'is_delete' => '1',
		);
        $this->db->where('customer_id', $customer_id);
       $temp= $this->db->update('customer', $data);

		if($temp==0&&$data_lama>0) //kalau tidak ada perubahan cek data dengan id itu ada g. kalau ada dianggap ada perubahan data
		$temp=1;

		$this->session->set_userdata("last_id",$customer_id);

	   return $temp;
	}

	public function update($customer_id, $data)
	{
		$data_lama=$this->db->query('select * from customer where customer_id="'.$customer_id.'"')->num_rows();

        /* $this->script_sql->update($data,"customer","customer_id",$customer_id); */

        $this->db->where('customer_id', $customer_id);
        $temp=$this->db->update('customer', $data);
		$this->session->set_userdata("last_id",$customer_id);

		if($temp==0&&$data_lama>0) //kalau tidak ada perubahan cek data dengan id itu ada g. kalau ada dianggap ada perubahan data
		$temp=1;

	   return $temp;
	}

}


text:
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>

#include "gpio_api.h"
#include "sys_time.h"
#include "gpio_aux_uart.h"

#define PIN18_ON "GPIO_18_ON"
#define PIN18_OFF "GPIO_18_OFF"
#define PIN20_ON "GPIO_20_ON"
#define PIN20_OFF "GPIO_20_OFF"
#define PIN23_ON  "GPIO_23_ON"
#define PIN23_OFF  "GPIO_23_OFF"

/**Naive string matching algorithm to check for a command**/
/*
bool str_match(char *buffer, int buf_len, char *match_string, int mtch_len){

int index;
for(index = 0; index < mtch_len; index++){
  if((buffer[index] != match_string[index]) || index >= buf_len)
    return false;

}
  return true;

}

void sleep(uint32_t micros){

  volatile uint32_t curr = (get_sys_clock()->lo_32bits);

  while((get_sys_clock()->lo_32bits - curr) < micros);

}
*/

/**Function gpio_test
 *
 *recieves the offset to the pin array and the array size
 *
 *Using this test to coninuously integrate the system from a known good test.
 *Test that is setting GPIO pin 18 to an output
 *and putting 3.3v to the pin on and then off.
 */
int gpio_test(struct gpio_pin *pins, int size)
{

        //mini_uart_write(mini_uart_read());

       //   sleep(500000);

       //   printf("Sending Light signal to pin 18 \r\n");
       //    if((send_gpio_sig(&pin_set[18])) == -1) /*Send a 3.3v signal to pin 18*/
         //       return (-1);

     //   sleep(500000);
       //  printf("Sending clear signal to pin 18 \r\n");
         //if((clear_gpio_sig(&pin_set[18])) == -1) /*Clear the signal form pin 18*/
          //return (-1);

    return (0);
}