# Deploying services onto EKS with Spinnaker

## Install Halyard

Halyard is the command line interface for managing and deploying Spinnaker. Although a Helm chart is available for Spinnaker, Halyard is still considered the best way to install Spinnaker.

### Install on OSX

**Prerequisites**

Be sure you have Java 1.8 installed before continuing.  To determine whether you have Java 1.8 installed, from the command line, type:

```
java -version
```

If you don't have it installed, Java 1.8 can be download for OSX from [http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html](http://download.oracle.com/otn-pub/java/jdk/8u171-b11/512cd62ec5174c3487ac17c61aaa89e8/jdk-8u171-macosx-x64.dmg).

Once installed, run java_home to verify the Java 1.8 home:

```
/usr/libexec/java_home -v 1.8
```

**Download the Installer**

```
curl -O https://raw.githubusercontent.com/spinnaker/halyard/master/install/macos/InstallHalyard.sh
```

Install Halyard:

```
sudo bash InstallHalyard.sh
```

If you get an error about not finding Java 1.8, manually set the environment:

```
export JAVA_HOME=/usr/libexec/java_home -v 1.8
export PATH=$PATH:$JAVA_HOME/bin
```

and pass the same environment to launch the installer:

```
sudo JAVA_HOME=`/usr/libexec/java_home -v 1.8` PATH=$PATH:$JAVA_HOME/bin bash InstallHalyard.sh
```

**Verify Installation**

```
hal -v
```

Move `hal` into your `$PATH`

## Create a Github repository

Later in this exercise you will be creating a Spinnaker pipeline that runs when code is pushed to a Github repository called spin-kub-repo.

Login to Github and fork the [lwander/spin-kub-demo](https://github.com/lwander/spin-kub-demo) repository to your Github account.

> For directions on how to fork a repository, see https://help.github.com/articles/fork-a-repo/

## Create a link to your Github repository from Docker Hub

In this exercise you'll be using Docker's automated build service to create Docker images when code is pushed to your Github repository.  The first step is to link your Github repository from Docker Hub.

1. Log into Docker Hub.
2. Navigate to **Your Login Name > Settings > Linked Accounts & Services**.
3. Click **Link Github**.
    The system prompts you to choose between Public and Private and Limited Access. Choose the **Public and Private** connection type since its required if you want to use the Automated Builds.
4. Press **Select** under Public and Private connection type.
    The system will prompt you to enter your Github credentials.

![linked-account](https://github.com/jicowan/aws-microservices-deploy-options/blob/master/images/linked-acct.png)

After you grant access to you code repository, the system returns you to Docker Hub and the link is complete.

## Create an automated build repository

Automated build repositories build an image when changes are pushed to your source code repository.  To create an automated build repository follow these instructions:

1. Select **Create** > **Create Automated Build** (from the drop down, upper right) on [Docker Hub](https://hub.docker.com/).
2. Select **Github.**
    The system prompts you with a list of User/Organizations and code repositories.
3. Select your username from the User/Organizations list.
4. Select `spin-kub-demo` repository from the list.
5. Customize the automated build by pressing the **Click here to customize** this behavior link.
    1. Enter “Spin Kub Build Demo” for **Short Description**.
    2. Set the **Docker Tag value** for **Push Type: Branch** to latest
    3. Add a **Push Type: Tag** with the Docker Tag Name of 1.0
6. Click **Create**.
7. Click **Build Settings**.
8. Click **Trigger** to trigger the build manually.

## Add docker registry provider

Enable the `docker-registry` provider:

```
hal config provider docker-registry enable
```

Add Docker Hub as the registry provider:

```
hal config provider docker-registry account add dockerhub \
--address index.docker.io \
--repositories <your_dockerhub_username>/spin-kub-demo \
--username <your_dockerhub_username> \
--password
```

## Add a Kubernetes account

Enable the Kubernetes (legacy) provider, enter the following commands in a terminal:

```
hal config provider kubernetes enable
```

Add the Kubernetes provider to your account:

```
hal config provider kubernetes account add eks-cluster \
--docker-registries dockerhub
```

### Configure kubernetes roles (rbac)

The following YAML creates the correct `ClusterRoleBinding` and `ServiceAccount`.

```
cat > spinnaker.yaml <<EOF
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
 name: spinnaker-robot
roleRef:
 apiGroup: rbac.authorization.k8s.io
 kind: ClusterRole
 name: cluster-admin
subjects:
- kind: ServiceAccount
  name: spinnaker-robot
  namespace: default
---
apiVersion: v1
kind: ServiceAccount
metadata:
 name: spinnaker-robot
 namespace: default
EOF
```

Apply the manifest:

```
kubectl apply -f spinnaker.yaml
```

### Extract  token from the secret associated with the Spinnaker service account:

List the secrets with:

```
kubectl get secrets
```

The output should include a secret named similarly to **spinnaker-robot-token-xxxx**.  Copy that token name for use below.

Retrieve the token from the **spinnaker-robot-token-xxxx** using the following command:

```
kubectl get secret <secret name> -o jsonpath="{['data']['token']}" | base64 -D
```

Update `kubeconfig`:

> Create a backup of your kubeconfig, e.g. cp ~/.kube/config ~/.kube/config.old, before making the following modifications.

```
users:
- name: aws
  user:
    token: <token_string>
    exec:
      apiVersion: client.authentication.k8s.io/v1alpha1
      command: heptio-authenticator-aws
      args:
        - "token"
        - "-i"
        - "<eks_cluster_name>"
```

## Choose an environment

This tells Halyard what type of environment to install Spinnaker into.  For this exercise we'll be using the distributed installation on Kubernetes method.  This method deploys each of Spinnaker's microservices separately.

Run the following command to add the environment:

```
hal config deploy edit --type distributed --account-name eks-cluster
```

## Choose a storage service

Spinnaker can be configured to use S3 to store all its persistent data in a S3 bucket.

To configure the S3 settings, run the following (notice, do not supply the value of `--secret-access-key` on the command line, you will be prompted to enter the value on STDIN once the command has started running):

```
hal config storage s3 edit \
--access-key-id <aws_access_key_id> \
--secret-access-key \
--region <aws_region>
```

> This assumes that you are logged in as a IAM user with administrator/root privileges

Set the storage source to S3:

```
hal config storage edit --type s3
```

> If you get an S3 error such as “Access Denied”, insure that you have proper S3 bucket create and write access.

## Deploy

Now that we've finished setting the configuration parameters for Spinnaker, we're ready to deploy it and connect to it.

### Pick a version

List the available versions:

```
hal version list
```

Set the version you want to use:

```
hal config version edit --version 1.8.0
```

## Deploy Spinnaker

```
hal deploy apply
```

## Connect to the Spinnaker UI

Spinnaker will not be publicly reachable by default so you will need to run the following command to reach the UI on [localhost:9000](http://localhost:9000/):

```
hal deploy connect
```

## Create a Spinnaker pipline

For the rest of the exercise we will be following the steps in this tutorial, https://www.spinnaker.io/guides/tutorials/codelabs/kubernetes-source-to-prod/#1-create-a-spinnaker-application

{'repo_name': 'aws-samples/aws-microservices-deploy-options', 'stars': '347', 'repo_language': 'Jsonnet', 'file_name': 'Dockerfile', 'mime_type': 'text/plain', 'hash': -2099776436531465251, 'source_dataset': 'data'}


## This file must *NOT* be checked into Version Control Systems,
# as it contains information specific to your local configuration.
#
# Location of the SDK. This is only used by Gradle.
# For customization when using a Version Control System, please read the
# header note.
#Mon Oct 15 23:54:00 IST 2018
ndk.dir=/Users/anupamchugh/Library/Android/sdk/ndk-bundle
sdk.dir=/Users/anupamchugh/Library/Android/sdk

{'repo_name': 'journaldev/journaldev', 'stars': '717', 'repo_language': 'Java', 'file_name': 'org.springframework.ide.eclipse.core.prefs', 'mime_type': 'text/plain', 'hash': 8360478594429698758, 'source_dataset': 'data'}


package com.leyou.item.api;

import com.leyou.item.pojo.Brand;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

/**
 * @Author: 98050
 * Time: 2018-10-11 20:04
 * Feature:品牌服务接口
 */
@RequestMapping("brand")
public interface BrandApi {
    /**
     * 根据品牌id集合，查询品牌信息
     * @param ids
     * @return
     */
    @GetMapping("list")
    List<Brand> queryBrandByIds(@RequestParam("ids") List<Long> ids);
}

{'repo_name': 'lyj8330328/leyou', 'stars': '472', 'repo_language': 'TSQL', 'file_name': 'JwtTest.java', 'mime_type': 'text/x-java', 'hash': 5618487350408813387, 'source_dataset': 'data'}


// RUN: %clang_cc1 %s -emit-llvm-only -verify
// expected-no-diagnostics

struct A {};
struct B : A {};
void a(const A& x = B());
void b() { a(); }

{'repo_name': 'leaningtech/cheerp-clang', 'stars': '201', 'repo_language': 'C++', 'file_name': '__init__.py', 'mime_type': 'text/plain', 'hash': -7158658546888963553, 'source_dataset': 'data'}


/**
* This file is part of DSO.
*
* Copyright 2016 Technical University of Munich and Intel.
* Developed by Jakob Engel <engelj at in dot tum dot de>,
* for more information see <http://vision.in.tum.de/dso>.
* If you use this code, please cite the respective publications as
* listed on the above website.
*
* DSO is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* DSO is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with DSO. If not, see <http://www.gnu.org/licenses/>.
*/

#include <stdio.h>
#include "util/settings.h"

//#include <GL/glx.h>
//#include <GL/gl.h>
//#include <GL/glu.h>

#include <pangolin/pangolin.h>
#include "KeyFrameDisplay.h"
#include "FullSystem/HessianBlocks.h"
#include "FullSystem/ImmaturePoint.h"
#include "util/FrameShell.h"

namespace dso
{
namespace IOWrap
{

KeyFrameDisplay::KeyFrameDisplay()
{
	originalInputSparse = 0;
	numSparseBufferSize=0;
	numSparsePoints=0;

	id = 0;
	active= true;
	camToWorld = SE3();

	needRefresh=true;

	my_scaledTH =1e10;
	my_absTH = 1e10;
	my_displayMode = 1;
	my_minRelBS = 0;
	my_sparsifyFactor = 1;

	numGLBufferPoints=0;
	bufferValid = false;
}
void KeyFrameDisplay::setFromF(FrameShell* frame, CalibHessian* HCalib)
{
	id = frame->id;
	fx = HCalib->fxl();
	fy = HCalib->fyl();
	cx = HCalib->cxl();
	cy = HCalib->cyl();
	width = wG[0];
	height = hG[0];
	fxi = 1/fx;
	fyi = 1/fy;
	cxi = -cx / fx;
	cyi = -cy / fy;
	camToWorld = frame->camToWorld;
	needRefresh=true;
}

void KeyFrameDisplay::setFromKF(FrameHessian* fh, CalibHessian* HCalib)
{
	setFromF(fh->shell, HCalib);

	// add all traces, inlier and outlier points.
	int npoints = 	fh->immaturePoints.size() +
					fh->pointHessians.size() +
					fh->pointHessiansMarginalized.size() +
					fh->pointHessiansOut.size();

	if(numSparseBufferSize < npoints)
	{
		if(originalInputSparse != 0) delete originalInputSparse;
		numSparseBufferSize = npoints+100;
        originalInputSparse = new InputPointSparse<MAX_RES_PER_POINT>[numSparseBufferSize];
	}

    InputPointSparse<MAX_RES_PER_POINT>* pc = originalInputSparse;
	numSparsePoints=0;
	for(ImmaturePoint* p : fh->immaturePoints)
	{
		for(int i=0;i<patternNum;i++)
			pc[numSparsePoints].color[i] = p->color[i];

		pc[numSparsePoints].u = p->u;
		pc[numSparsePoints].v = p->v;
		pc[numSparsePoints].idpeth = (p->idepth_max+p->idepth_min)*0.5f;
		pc[numSparsePoints].idepth_hessian = 1000;
		pc[numSparsePoints].relObsBaseline = 0;
		pc[numSparsePoints].numGoodRes = 1;
		pc[numSparsePoints].status = 0;
		numSparsePoints++;
	}

	for(PointHessian* p : fh->pointHessians)
	{
		for(int i=0;i<patternNum;i++)
			pc[numSparsePoints].color[i] = p->color[i];
		pc[numSparsePoints].u = p->u;
		pc[numSparsePoints].v = p->v;
		pc[numSparsePoints].idpeth = p->idepth_scaled;
		pc[numSparsePoints].relObsBaseline = p->maxRelBaseline;
		pc[numSparsePoints].idepth_hessian = p->idepth_hessian;
		pc[numSparsePoints].numGoodRes =  0;
		pc[numSparsePoints].status=1;

		numSparsePoints++;
	}

	for(PointHessian* p : fh->pointHessiansMarginalized)
	{
		for(int i=0;i<patternNum;i++)
			pc[numSparsePoints].color[i] = p->color[i];
		pc[numSparsePoints].u = p->u;
		pc[numSparsePoints].v = p->v;
		pc[numSparsePoints].idpeth = p->idepth_scaled;
		pc[numSparsePoints].relObsBaseline = p->maxRelBaseline;
		pc[numSparsePoints].idepth_hessian = p->idepth_hessian;
		pc[numSparsePoints].numGoodRes =  0;
		pc[numSparsePoints].status=2;
		numSparsePoints++;
	}

	for(PointHessian* p : fh->pointHessiansOut)
	{
		for(int i=0;i<patternNum;i++)
			pc[numSparsePoints].color[i] = p->color[i];
		pc[numSparsePoints].u = p->u;
		pc[numSparsePoints].v = p->v;
		pc[numSparsePoints].idpeth = p->idepth_scaled;
		pc[numSparsePoints].relObsBaseline = p->maxRelBaseline;
		pc[numSparsePoints].idepth_hessian = p->idepth_hessian;
		pc[numSparsePoints].numGoodRes =  0;
		pc[numSparsePoints].status=3;
		numSparsePoints++;
	}
	assert(numSparsePoints <= npoints);

	camToWorld = fh->PRE_camToWorld;
	needRefresh=true;
}

KeyFrameDisplay::~KeyFrameDisplay()
{
	if(originalInputSparse != 0)
		delete[] originalInputSparse;
}

bool KeyFrameDisplay::refreshPC(bool canRefresh, float scaledTH, float absTH, int mode, float minBS, int sparsity)
{
	if(canRefresh)
	{
		needRefresh = needRefresh ||
				my_scaledTH != scaledTH ||
				my_absTH != absTH ||
				my_displayMode != mode ||
				my_minRelBS != minBS ||
				my_sparsifyFactor != sparsity;
	}

	if(!needRefresh) return false;
	needRefresh=false;

	my_scaledTH = scaledTH;
	my_absTH = absTH;
	my_displayMode = mode;
	my_minRelBS = minBS;
	my_sparsifyFactor = sparsity;

	// if there are no vertices, done!
	if(numSparsePoints == 0)
		return false;

	// make data
	Vec3f* tmpVertexBuffer = new Vec3f[numSparsePoints*patternNum];
	Vec3b* tmpColorBuffer = new Vec3b[numSparsePoints*patternNum];
	int vertexBufferNumPoints=0;

	for(int i=0;i<numSparsePoints;i++)
	{
		/* display modes:
		 * my_displayMode==0 - all pts, color-coded
		 * my_displayMode==1 - normal points
		 * my_displayMode==2 - active only
		 * my_displayMode==3 - nothing
		 */

		if(my_displayMode==1 && originalInputSparse[i].status != 1 && originalInputSparse[i].status!= 2) continue;
		if(my_displayMode==2 && originalInputSparse[i].status != 1) continue;
		if(my_displayMode>2) continue;

		if(originalInputSparse[i].idpeth < 0) continue;

		float depth = 1.0f / originalInputSparse[i].idpeth;
		float depth4 = depth*depth; depth4*= depth4;
		float var = (1.0f / (originalInputSparse[i].idepth_hessian+0.01));

		if(var * depth4 > my_scaledTH)
			continue;

		if(var > my_absTH)
			continue;

		if(originalInputSparse[i].relObsBaseline < my_minRelBS)
			continue;

		for(int pnt=0;pnt<patternNum;pnt++)
		{

			if(my_sparsifyFactor > 1 && rand()%my_sparsifyFactor != 0) continue;
			int dx = patternP[pnt][0];
			int dy = patternP[pnt][1];

			tmpVertexBuffer[vertexBufferNumPoints][0] = ((originalInputSparse[i].u+dx)*fxi + cxi) * depth;
			tmpVertexBuffer[vertexBufferNumPoints][1] = ((originalInputSparse[i].v+dy)*fyi + cyi) * depth;
			tmpVertexBuffer[vertexBufferNumPoints][2] = depth*(1 + 2*fxi * (rand()/(float)RAND_MAX-0.5f));

			if(my_displayMode==0)
			{
				if(originalInputSparse[i].status==0)
				{
					tmpColorBuffer[vertexBufferNumPoints][0] = 0;
					tmpColorBuffer[vertexBufferNumPoints][1] = 255;
					tmpColorBuffer[vertexBufferNumPoints][2] = 255;
				}
				else if(originalInputSparse[i].status==1)
				{
					tmpColorBuffer[vertexBufferNumPoints][0] = 0;
					tmpColorBuffer[vertexBufferNumPoints][1] = 255;
					tmpColorBuffer[vertexBufferNumPoints][2] = 0;
				}
				else if(originalInputSparse[i].status==2)
				{
					tmpColorBuffer[vertexBufferNumPoints][0] = 0;
					tmpColorBuffer[vertexBufferNumPoints][1] = 0;
					tmpColorBuffer[vertexBufferNumPoints][2] = 255;
				}
				else if(originalInputSparse[i].status==3)
				{
					tmpColorBuffer[vertexBufferNumPoints][0] = 255;
					tmpColorBuffer[vertexBufferNumPoints][1] = 0;
					tmpColorBuffer[vertexBufferNumPoints][2] = 0;
				}
				else
				{
					tmpColorBuffer[vertexBufferNumPoints][0] = 255;
					tmpColorBuffer[vertexBufferNumPoints][1] = 255;
					tmpColorBuffer[vertexBufferNumPoints][2] = 255;
				}

			}
			else
			{
				tmpColorBuffer[vertexBufferNumPoints][0] = originalInputSparse[i].color[pnt];
				tmpColorBuffer[vertexBufferNumPoints][1] = originalInputSparse[i].color[pnt];
				tmpColorBuffer[vertexBufferNumPoints][2] = originalInputSparse[i].color[pnt];
			}
			vertexBufferNumPoints++;

			assert(vertexBufferNumPoints <= numSparsePoints*patternNum);
		}
	}

	if(vertexBufferNumPoints==0)
	{
		delete[] tmpColorBuffer;
		delete[] tmpVertexBuffer;
		return true;
	}

	numGLBufferGoodPoints = vertexBufferNumPoints;
	if(numGLBufferGoodPoints > numGLBufferPoints)
	{
		numGLBufferPoints = vertexBufferNumPoints*1.3;
		vertexBuffer.Reinitialise(pangolin::GlArrayBuffer, numGLBufferPoints, GL_FLOAT, 3, GL_DYNAMIC_DRAW );
		colorBuffer.Reinitialise(pangolin::GlArrayBuffer, numGLBufferPoints, GL_UNSIGNED_BYTE, 3, GL_DYNAMIC_DRAW );
	}
	vertexBuffer.Upload(tmpVertexBuffer, sizeof(float)*3*numGLBufferGoodPoints, 0);
	colorBuffer.Upload(tmpColorBuffer, sizeof(unsigned char)*3*numGLBufferGoodPoints, 0);
	bufferValid=true;
	delete[] tmpColorBuffer;
	delete[] tmpVertexBuffer;

	return true;
}

void KeyFrameDisplay::drawCam(float lineWidth, float* color, float sizeFactor)
{
	if(width == 0)
		return;

	float sz=sizeFactor;

	glPushMatrix();

		Sophus::Matrix4f m = camToWorld.matrix().cast<float>();
		glMultMatrixf((GLfloat*)m.data());

		if(color == 0)
		{
			glColor3f(1,0,0);
		}
		else
			glColor3f(color[0],color[1],color[2]);

		glLineWidth(lineWidth);
		glBegin(GL_LINES);
		glVertex3f(0,0,0);
		glVertex3f(sz*(0-cx)/fx,sz*(0-cy)/fy,sz);
		glVertex3f(0,0,0);
		glVertex3f(sz*(0-cx)/fx,sz*(height-1-cy)/fy,sz);
		glVertex3f(0,0,0);
		glVertex3f(sz*(width-1-cx)/fx,sz*(height-1-cy)/fy,sz);
		glVertex3f(0,0,0);
		glVertex3f(sz*(width-1-cx)/fx,sz*(0-cy)/fy,sz);

		glVertex3f(sz*(width-1-cx)/fx,sz*(0-cy)/fy,sz);
		glVertex3f(sz*(width-1-cx)/fx,sz*(height-1-cy)/fy,sz);

		glVertex3f(sz*(width-1-cx)/fx,sz*(height-1-cy)/fy,sz);
		glVertex3f(sz*(0-cx)/fx,sz*(height-1-cy)/fy,sz);

		glVertex3f(sz*(0-cx)/fx,sz*(height-1-cy)/fy,sz);
		glVertex3f(sz*(0-cx)/fx,sz*(0-cy)/fy,sz);

		glVertex3f(sz*(0-cx)/fx,sz*(0-cy)/fy,sz);
		glVertex3f(sz*(width-1-cx)/fx,sz*(0-cy)/fy,sz);

		glEnd();
	glPopMatrix();
}

void KeyFrameDisplay::drawPC(float pointSize)
{

	if(!bufferValid || numGLBufferGoodPoints==0)
		return;

	glDisable(GL_LIGHTING);

	glPushMatrix();

		Sophus::Matrix4f m = camToWorld.matrix().cast<float>();
		glMultMatrixf((GLfloat*)m.data());

		glPointSize(pointSize);

		colorBuffer.Bind();
		glColorPointer(colorBuffer.count_per_element, colorBuffer.datatype, 0, 0);
		glEnableClientState(GL_COLOR_ARRAY);

		vertexBuffer.Bind();
		glVertexPointer(vertexBuffer.count_per_element, vertexBuffer.datatype, 0, 0);
		glEnableClientState(GL_VERTEX_ARRAY);
		glDrawArrays(GL_POINTS, 0, numGLBufferGoodPoints);
		glDisableClientState(GL_VERTEX_ARRAY);
		vertexBuffer.Unbind();

		glDisableClientState(GL_COLOR_ARRAY);
		colorBuffer.Unbind();

	glPopMatrix();
}

}
}

{'repo_name': 'muskie82/CNN-DSO', 'stars': '111', 'repo_language': 'C++', 'file_name': 'FindSuiteParse.cmake', 'mime_type': 'text/plain', 'hash': 3777750468263753794, 'source_dataset': 'data'}


/*
 * btnode.c - NILFS B-tree node cache
 *
 * Copyright (C) 2005-2008 Nippon Telegraph and Telephone Corporation.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * Originally written by Seiji Kihara.
 * Fully revised by Ryusuke Konishi for stabilization and simplification.
 *
 */

#include <linux/types.h>
#include <linux/buffer_head.h>
#include <linux/mm.h>
#include <linux/backing-dev.h>
#include <linux/gfp.h>
#include "nilfs.h"
#include "mdt.h"
#include "dat.h"
#include "page.h"
#include "btnode.h"

void nilfs_btnode_cache_clear(struct address_space *btnc)
{
	invalidate_mapping_pages(btnc, 0, -1);
	truncate_inode_pages(btnc, 0);
}

struct buffer_head *
nilfs_btnode_create_block(struct address_space *btnc, __u64 blocknr)
{
	struct inode *inode = NILFS_BTNC_I(btnc);
	struct buffer_head *bh;

	bh = nilfs_grab_buffer(inode, btnc, blocknr, BIT(BH_NILFS_Node));
	if (unlikely(!bh))
		return NULL;

	if (unlikely(buffer_mapped(bh) || buffer_uptodate(bh) ||
		     buffer_dirty(bh))) {
		brelse(bh);
		BUG();
	}
	memset(bh->b_data, 0, 1 << inode->i_blkbits);
	bh->b_bdev = inode->i_sb->s_bdev;
	bh->b_blocknr = blocknr;
	set_buffer_mapped(bh);
	set_buffer_uptodate(bh);

	unlock_page(bh->b_page);
	put_page(bh->b_page);
	return bh;
}

int nilfs_btnode_submit_block(struct address_space *btnc, __u64 blocknr,
			      sector_t pblocknr, int mode, int mode_flags,
			      struct buffer_head **pbh, sector_t *submit_ptr)
{
	struct buffer_head *bh;
	struct inode *inode = NILFS_BTNC_I(btnc);
	struct page *page;
	int err;

	bh = nilfs_grab_buffer(inode, btnc, blocknr, BIT(BH_NILFS_Node));
	if (unlikely(!bh))
		return -ENOMEM;

	err = -EEXIST; /* internal code */
	page = bh->b_page;

	if (buffer_uptodate(bh) || buffer_dirty(bh))
		goto found;

	if (pblocknr == 0) {
		pblocknr = blocknr;
		if (inode->i_ino != NILFS_DAT_INO) {
			struct the_nilfs *nilfs = inode->i_sb->s_fs_info;

			/* blocknr is a virtual block number */
			err = nilfs_dat_translate(nilfs->ns_dat, blocknr,
						  &pblocknr);
			if (unlikely(err)) {
				brelse(bh);
				goto out_locked;
			}
		}
	}

	if (mode_flags & REQ_RAHEAD) {
		if (pblocknr != *submit_ptr + 1 || !trylock_buffer(bh)) {
			err = -EBUSY; /* internal code */
			brelse(bh);
			goto out_locked;
		}
	} else { /* mode == READ */
		lock_buffer(bh);
	}
	if (buffer_uptodate(bh)) {
		unlock_buffer(bh);
		err = -EEXIST; /* internal code */
		goto found;
	}
	set_buffer_mapped(bh);
	bh->b_bdev = inode->i_sb->s_bdev;
	bh->b_blocknr = pblocknr; /* set block address for read */
	bh->b_end_io = end_buffer_read_sync;
	get_bh(bh);
	submit_bh(mode, mode_flags, bh);
	bh->b_blocknr = blocknr; /* set back to the given block address */
	*submit_ptr = pblocknr;
	err = 0;
found:
	*pbh = bh;

out_locked:
	unlock_page(page);
	put_page(page);
	return err;
}

/**
 * nilfs_btnode_delete - delete B-tree node buffer
 * @bh: buffer to be deleted
 *
 * nilfs_btnode_delete() invalidates the specified buffer and delete the page
 * including the buffer if the page gets unbusy.
 */
void nilfs_btnode_delete(struct buffer_head *bh)
{
	struct address_space *mapping;
	struct page *page = bh->b_page;
	pgoff_t index = page_index(page);
	int still_dirty;

	get_page(page);
	lock_page(page);
	wait_on_page_writeback(page);

	nilfs_forget_buffer(bh);
	still_dirty = PageDirty(page);
	mapping = page->mapping;
	unlock_page(page);
	put_page(page);

	if (!still_dirty && mapping)
		invalidate_inode_pages2_range(mapping, index, index);
}

/**
 * nilfs_btnode_prepare_change_key
 *  prepare to move contents of the block for old key to one of new key.
 *  the old buffer will not be removed, but might be reused for new buffer.
 *  it might return -ENOMEM because of memory allocation errors,
 *  and might return -EIO because of disk read errors.
 */
int nilfs_btnode_prepare_change_key(struct address_space *btnc,
				    struct nilfs_btnode_chkey_ctxt *ctxt)
{
	struct buffer_head *obh, *nbh;
	struct inode *inode = NILFS_BTNC_I(btnc);
	__u64 oldkey = ctxt->oldkey, newkey = ctxt->newkey;
	int err;

	if (oldkey == newkey)
		return 0;

	obh = ctxt->bh;
	ctxt->newbh = NULL;

	if (inode->i_blkbits == PAGE_SHIFT) {
		lock_page(obh->b_page);
		/*
		 * We cannot call radix_tree_preload for the kernels older
		 * than 2.6.23, because it is not exported for modules.
		 */
retry:
		err = radix_tree_preload(GFP_NOFS & ~__GFP_HIGHMEM);
		if (err)
			goto failed_unlock;
		/* BUG_ON(oldkey != obh->b_page->index); */
		if (unlikely(oldkey != obh->b_page->index))
			NILFS_PAGE_BUG(obh->b_page,
				       "invalid oldkey %lld (newkey=%lld)",
				       (unsigned long long)oldkey,
				       (unsigned long long)newkey);

		spin_lock_irq(&btnc->tree_lock);
		err = radix_tree_insert(&btnc->page_tree, newkey, obh->b_page);
		spin_unlock_irq(&btnc->tree_lock);
		/*
		 * Note: page->index will not change to newkey until
		 * nilfs_btnode_commit_change_key() will be called.
		 * To protect the page in intermediate state, the page lock
		 * is held.
		 */
		radix_tree_preload_end();
		if (!err)
			return 0;
		else if (err != -EEXIST)
			goto failed_unlock;

		err = invalidate_inode_pages2_range(btnc, newkey, newkey);
		if (!err)
			goto retry;
		/* fallback to copy mode */
		unlock_page(obh->b_page);
	}

	nbh = nilfs_btnode_create_block(btnc, newkey);
	if (!nbh)
		return -ENOMEM;

	BUG_ON(nbh == obh);
	ctxt->newbh = nbh;
	return 0;

 failed_unlock:
	unlock_page(obh->b_page);
	return err;
}

/**
 * nilfs_btnode_commit_change_key
 *  commit the change_key operation prepared by prepare_change_key().
 */
void nilfs_btnode_commit_change_key(struct address_space *btnc,
				    struct nilfs_btnode_chkey_ctxt *ctxt)
{
	struct buffer_head *obh = ctxt->bh, *nbh = ctxt->newbh;
	__u64 oldkey = ctxt->oldkey, newkey = ctxt->newkey;
	struct page *opage;

	if (oldkey == newkey)
		return;

	if (nbh == NULL) {	/* blocksize == pagesize */
		opage = obh->b_page;
		if (unlikely(oldkey != opage->index))
			NILFS_PAGE_BUG(opage,
				       "invalid oldkey %lld (newkey=%lld)",
				       (unsigned long long)oldkey,
				       (unsigned long long)newkey);
		mark_buffer_dirty(obh);

		spin_lock_irq(&btnc->tree_lock);
		radix_tree_delete(&btnc->page_tree, oldkey);
		radix_tree_tag_set(&btnc->page_tree, newkey,
				   PAGECACHE_TAG_DIRTY);
		spin_unlock_irq(&btnc->tree_lock);

		opage->index = obh->b_blocknr = newkey;
		unlock_page(opage);
	} else {
		nilfs_copy_buffer(nbh, obh);
		mark_buffer_dirty(nbh);

		nbh->b_blocknr = newkey;
		ctxt->bh = nbh;
		nilfs_btnode_delete(obh); /* will decrement bh->b_count */
	}
}

/**
 * nilfs_btnode_abort_change_key
 *  abort the change_key operation prepared by prepare_change_key().
 */
void nilfs_btnode_abort_change_key(struct address_space *btnc,
				   struct nilfs_btnode_chkey_ctxt *ctxt)
{
	struct buffer_head *nbh = ctxt->newbh;
	__u64 oldkey = ctxt->oldkey, newkey = ctxt->newkey;

	if (oldkey == newkey)
		return;

	if (nbh == NULL) {	/* blocksize == pagesize */
		spin_lock_irq(&btnc->tree_lock);
		radix_tree_delete(&btnc->page_tree, newkey);
		spin_unlock_irq(&btnc->tree_lock);
		unlock_page(ctxt->bh->b_page);
	} else
		brelse(nbh);
}

{'repo_name': 'PhoenixOS/kernel', 'stars': '202', 'repo_language': 'C', 'file_name': 'img-ir-hw.c', 'mime_type': 'text/x-c', 'hash': 5318843345033087096, 'source_dataset': 'data'}


%%
%% %CopyrightBegin%
%%
%% Copyright Ericsson AB 2006-2016. 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.
%%
%% %CopyrightEnd%
%%
-module(snmpa_target_cache).

-behaviour(gen_server).

%% External exports
-export([start_link/2, stop/0, verbosity/1]).

-export([
	 invalidate/0, % invalidate/1, invalidate/2,
	 targets/1, targets/2
	]).

%% gen_server callbacks
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2,
         code_change/3]).

-ifdef(snmp_qc).
-export([
	 lock/1,
	 unlock/0,
	 upgrade_lock/0,
	 downgrade_lock/0
	]).
-endif.

-include("snmpa_internal.hrl").
-include("snmp_debug.hrl").
-include("snmp_verbosity.hrl").

-record(state,
        {
          active_count = 0,
          writer       = false, % Active or waiting write-lock
          waiting      = []     % Waiting lockers
	 }
       ).
-record(locker, {pid, from, mon_ref, type, state}).

-define(SERVER,     ?MODULE).
-define(CACHE,      ?MODULE).
-define(LOCKER_TAB, snmpa_target_cache_locker).

-ifndef(default_verbosity).
-define(default_verbosity,silence).
-endif.

-ifdef(snmp_debug).
-define(GS_START_LINK(Prio, Opts),
        gen_server:start_link({local, ?SERVER}, ?MODULE,
                              [Prio, Opts], [{debug,[trace]}])).
-else.
-define(GS_START_LINK(Prio, Opts),
        gen_server:start_link({local, ?SERVER}, ?MODULE,
                              [Prio, Opts], [])).
-endif.

%%%-------------------------------------------------------------------
%%% API
%%%-------------------------------------------------------------------
start_link(Prio, Opts) ->
    ?d("start_link -> entry with"
       "~n   Prio: ~p"
       "~n   Opts: ~p", [Prio, Opts]),
    ?GS_START_LINK(Prio, Opts).

stop() ->
    call(stop).

verbosity(V) ->
    call({verbosity, V}).

%% Targets   -> notify_targets()
%% notify_targets() -> [notify_target()]
%% notify_target()  -> {NotifyName, target()}
%% target() -> {DestAddr, TargetName, TargetParams, NotifyType}

targets(TargetsFun) when is_function(TargetsFun) ->
    Pat = {{'_', '$1'}, '$2'},
    get_targets(Pat, TargetsFun).

targets(TargetsFun, NotifyName) when is_function(TargetsFun) ->
    Pat = {{NotifyName, '$1'}, '$2'},
    get_targets(Pat, TargetsFun).

get_targets(Pat, TargetsFun) ->
    lock(read), % Get a read lock
    Targets =
	case ets:lookup(?CACHE, state) of
	    [{state, invalid}] ->
		upgrade_lock(), % Upgrade to write lock
		%% Make sure it's still invalid
		case ets:lookup(?CACHE, state) of
		    [{state, invalid}] ->
			insert_all( TargetsFun() ),
			ets:insert(?CACHE, {state, valid});
		    _ ->
			ok % This means that someone got there before us
		end,
		downgrade_lock(), % Downgrade to read lock
		get_targets(Pat);
	    [{state, valid}] ->
		get_targets(Pat)
	end,
    unlock(), % Release the read lock
    Targets.

get_targets(Pat) ->
    NotifyTargets = ets:match(?CACHE, Pat),
    [{DestAddr, TargetName, TargetParams, NotifyType} ||
	[TargetName, {DestAddr, TargetParams, NotifyType}] <-
	    NotifyTargets].

invalidate() ->
    lock(write),
    case ets:lookup(?CACHE, state) of
	[{state, invalid}] ->
	    ok;
	[{state, valid}] ->
	    delete_all(),
	    ets:insert(?CACHE, {state, invalid})
    end,
    unlock(),
    ok.

%%%-------------------------------------------------------------------
%%% Callback functions from gen_server
%%%-------------------------------------------------------------------

%%--------------------------------------------------------------------
%% Func: init/1
%% Returns: {ok, State}          |
%%          {ok, State, Timeout} |
%%          ignore               |
%%          {stop, Reason}
%%--------------------------------------------------------------------
init([Prio, Opts]) ->
    case (catch do_init(Prio, Opts)) of
        {ok, State} ->
            ?vdebug("started",[]),
            {ok, State};
        {error, Reason} ->
            config_err("failed starting target-cache server: ~n~p", [Reason]),
            {stop, {error, Reason}};
        Error ->
            config_err("failed starting target-cache server: ~n~p", [Error]),
            {stop, {error, Error}}
    end.

do_init(Prio, Opts) ->
    process_flag(priority, Prio),
    process_flag(trap_exit, true),
    put(sname, tcs),
    put(verbosity, get_opt(verbosity, Opts, ?default_verbosity)),
    ?vlog("starting",[]),
    ets:new(?CACHE,      [set, named_table, public]),
    ets:insert(?CACHE,   {state, invalid}),
    ets:new(?LOCKER_TAB, [set, named_table, {keypos, #locker.pid}]),
    {ok, #state{}}.

%%--------------------------------------------------------------------
%% Func: handle_call/3
%% Returns: {reply, Reply, State}          |
%%          {reply, Reply, State, Timeout} |
%%          {noreply, State}               |
%%          {noreply, State, Timeout}      |
%%          {stop, Reason, Reply, State}   | (terminate/2 is called)
%%          {stop, Reason, State}            (terminate/2 is called)
%%--------------------------------------------------------------------

%%%-----------------------------------------------------------------

%%
%% (1) As long as there are no _waiting_ or active write locks,
%%     read-locks will allways be granted
%% (2) When there are no active readers, write-locks will be
%%     granted.
%% (3) When there are active readers (clients with read-locks),
%%     a write-lock will have to wait for _all_ the read-locks
%%     to be released.
%% (4) If there is a waiting write-lock, all subsequent lock-
%%     requests will have to wait.
%% (5) If there is an active write-lock, all subsequent lock-
%%     requests will have to wait.
%%

%% (1) No write_lock active or waiting
handle_call({lock, read = Type, infinity}, {Pid, _} = From,
	    #state{active_count = Cnt, writer = false} = State) ->
    ?vlog("lock(read, infinity) -> "
	  "entry when no waiting or active writer with"
	  "~n   Pid: ~p"
	  "~n   Cnt: ~p", [Pid, Cnt]),
    MonRef = erlang:monitor(process, Pid),
    Locker = #locker{pid     = Pid,
                     from    = From,
		     mon_ref = MonRef,
		     type    = Type,
		     state   = active},
    ets:insert(?LOCKER_TAB, Locker),
%%     ?vtrace("lock(read, infinity) -> done when"
%% 	    "~n   Lockers: ~p", [ets:tab2list(?LOCKER_TAB)]),
    {reply, ok, State#state{active_count = inc(Cnt)}};

%% (4,5) There is waiting or active write locks
handle_call({lock, read = Type, infinity}, {Pid, _} = From, State) ->
    ?vlog("lock(read, infinity) -> "
	  "entry when active or waiting write locks with"
	  "~n   Pid: ~p", [Pid]),
    MonRef = erlang:monitor(process, Pid),
    Locker = #locker{pid     = Pid,
		     from    = From,
		     mon_ref = MonRef,
		     type    = Type,
		     state   = waiting},
    ets:insert(?LOCKER_TAB, Locker),
    Waiting = lists:append(State#state.waiting, [Pid]),
%%     ?vtrace("lock(read, infinity) -> done when"
%% 	    "~n   Waiting: ~p"
%% 	    "~n   Lockers: ~p", [Waiting, ets:tab2list(?LOCKER_TAB)]),
    {noreply, State#state{waiting = Waiting}};

%% (2) No active locks
%% Since there are no active lockers, that also means that
%% there is no lockers waiting.
handle_call({lock, write = Type, infinity}, {Pid, _} = From,
	    #state{active_count = 0, writer = false} = State) ->
    ?vlog("lock(write, infinity) -> "
	  "entry when no active lockers with"
	  "~n   Pid: ~p", [Pid]),
    MonRef = erlang:monitor(process, Pid),
    Locker = #locker{pid     = Pid,
                     from    = From,
		     mon_ref = MonRef,
		     type    = Type,
		     state   = active},
    ets:insert(?LOCKER_TAB, Locker),
%%     ?vtrace("lock(write, infinity) -> done when"
%% 	    "~n   Lockers: ~p", [ets:tab2list(?LOCKER_TAB)]),
    {reply, ok, State#state{active_count = 1, writer = true}};

%% (3) No waiting or active writers, but at least one active reader
handle_call({lock, write = Type, infinity}, {Pid, _} = From,
	    #state{writer = false} = State) ->
    ?vlog("lock(write, infinity) -> "
	  "entry when active lockers with"
	  "~n   Pid: ~p", [Pid]),
    MonRef = erlang:monitor(process, Pid),
    Locker = #locker{pid     = Pid,
		     from    = From,
		     mon_ref = MonRef,
		     type    = Type,
		     state   = waiting},
    ets:insert(?LOCKER_TAB, Locker),
    Waiting = lists:append(State#state.waiting, [Pid]),
%%     ?vtrace("lock(write, infinity) -> done when"
%% 	    "~n   Waiting: ~p"
%% 	    "~n   Lockers: ~p", [Waiting, ets:tab2list(?LOCKER_TAB)]),
    {noreply, State#state{waiting = Waiting, writer = true}};

handle_call({lock, write = Type, infinity}, {Pid, _} = From,
	    #state{writer = true} = State) ->
    ?vlog("lock(write, infinity) -> entry with"
	  "~n   Pid: ~p", [Pid]),
    MonRef = erlang:monitor(process, Pid),
    Locker = #locker{pid     = Pid,
		     from    = From,
		     mon_ref = MonRef,
		     type    = Type,
		     state   = waiting},
    ets:insert(?LOCKER_TAB, Locker),
    Waiting = lists:append(State#state.waiting, [Pid]),
%%     ?vtrace("lock(write, infinity) -> done when"
%% 	    "~n   Waiting: ~p"
%% 	    "~n   Lockers: ~p", [Waiting, ets:tab2list(?LOCKER_TAB)]),
    {noreply, State#state{waiting = Waiting}};

handle_call({verbosity, Verbosity}, _From, State) ->
    ?vlog("verbosity: ~p -> ~p", [get(verbosity), Verbosity]),
    Old = put(verbosity, ?vvalidate(Verbosity)),
    {reply, Old, State};

%% If there are no more active read'ers, and no waiting,
%% then set to writer and reply now
handle_call({upgrade_lock, Pid}, _From,
	    #state{active_count = 1, waiting = []} = State) ->
    ?vlog("upgrade_lock -> "
	  "entry when one active locker and no waiting with"
	  "~n   Pid: ~p", [Pid]),
    case ets:lookup(?LOCKER_TAB, Pid) of
	[#locker{type = read} = Locker] ->
	    ets:insert(?LOCKER_TAB, Locker#locker{type = write}),
%% 	    ?vtrace("upgrade_lock -> done when"
%% 		    "~n   Lockers: ~p", [ets:tab2list(?LOCKER_TAB)]),
	    {reply, ok, State#state{writer = true}};

	[#locker{type = write}] ->
	    {reply, ok, State}
    end;

%% If there are no more active read'ers, and no waiting,
%% then set to writer and reply now
handle_call({upgrade_lock, Pid}, {Pid, _} = From,
	    #state{active_count = 1, waiting = Waiting} = State) ->
    ?vlog("upgrade_lock -> "
	  "entry when one active locker with"
	  "~n   Pid:     ~p"
	  "~n   Waiting: ~p", [Pid, Waiting]),
    case ets:lookup(?LOCKER_TAB, Pid) of
	[#locker{type = read} = Locker] ->
	    case active_waiting_writer(Waiting) of
		{true, StillWaiting} ->
		    ?vtrace("upgrade_lock -> activated when"
			    "~n   StillWaiting: ~p", [StillWaiting]),
		    ets:insert(?LOCKER_TAB, Locker#locker{from  = From,
							  type  = write,
							  state = waiting}),
%% 		    ?vtrace("upgrade_lock -> done when"
%% 			    "~n   Lockers: ~p", [ets:tab2list(?LOCKER_TAB)]),
		    {noreply, State#state{waiting = StillWaiting ++ [Pid]}};
		{false, []} ->
		    ?vtrace("upgrade_lock -> none activated, "
			    "so we can let the upgrader in", []),
		    ets:insert(?LOCKER_TAB, Locker#locker{type = write}),
%% 		    ?vtrace("upgrade_lock -> done when"
%% 			    "~n   Lockers: ~p", [ets:tab2list(?LOCKER_TAB)]),
		    {reply, ok, State#state{writer  = true,
					    waiting = []}}
	    end;

	[#locker{type = write}] ->
	    {reply, ok, State};

	_ ->
	    {reply, {error, not_found}, State}
    end;

%% There are active and waiting locker's
handle_call({upgrade_lock, Pid}, {Pid, _} = From,
	    #state{active_count = Cnt, waiting = Waiting} = State) ->
    ?vlog("upgrade_lock -> entry with"
	  "~n   Pid:     ~p"
	  "~n   Waiting: ~p", [Pid, Waiting]),
    case ets:lookup(?LOCKER_TAB, Pid) of
	[#locker{type = read} = Locker] ->
	    ets:insert(?LOCKER_TAB, Locker#locker{from  = From,
						  type  = write,
						  state = waiting}),
%% 	    ?vtrace("upgrade_lock -> done when"
%% 		    "~n   Lockers: ~p", [ets:tab2list(?LOCKER_TAB)]),
	    {noreply, State#state{active_count = dec(Cnt),
				  waiting      = Waiting ++ [Pid]}};

	[#locker{type = write}] ->
	    {reply, ok, State};

	_ ->
	    {reply, {error, not_found}, State}
    end;

handle_call(stop, _From, State) ->
    ?vlog("stop",[]),
    {stop, normal, stopped, State};

handle_call(Req, _From, State) ->
    warning_msg("received unknown request: ~n~p", [Req]),
    Reply = {error, {unknown, Req}},
    {reply, Reply, State}.

%%--------------------------------------------------------------------
%% Func: handle_cast/2
%% Returns: {noreply, State}          |
%%          {noreply, State, Timeout} |
%%          {stop, Reason, State}            (terminate/2 is called)
%%--------------------------------------------------------------------
handle_cast({unlock, Pid},
	    #state{active_count = Cnt, waiting = []} = State) ->
    ?vlog("unlock -> entry when no waiting with"
	  "~n   Pid: ~p"
	  "~n   Cnt: ~p", [Pid, Cnt]),
    case ets:lookup(?LOCKER_TAB, Pid) of
	[#locker{mon_ref = MonRef, type = read}] ->
	    ?vdebug("unlock -> found read locker"
		    "~n   MonRef: ~p", [MonRef]),
	    erlang:demonitor(MonRef, [flush]),
	    ets:delete(?LOCKER_TAB, Pid),
%% 	    ?vtrace("unlock -> done when"
%% 		    "~n   Lockers: ~p", [ets:tab2list(?LOCKER_TAB)]),
	    {noreply, State#state{active_count = dec(Cnt)}};
	[#locker{mon_ref = MonRef, type = write}] ->
	    ?vdebug("unlock -> found write locker"
		    "~n   MonRef: ~p", [MonRef]),
	    erlang:demonitor(MonRef, [flush]),
	    ets:delete(?LOCKER_TAB, Pid),
%% 	    ?vtrace("unlock -> done when"
%% 		    "~n   Lockers: ~p", [ets:tab2list(?LOCKER_TAB)]),
	    {noreply, State#state{active_count = dec(Cnt), writer = false}};
	_ ->
	    {noreply, State}
    end;

handle_cast({unlock, Pid},
	    #state{active_count = Cnt, waiting = Waiting} = State) ->
    ?vlog("unlock -> entry when waiting with"
	  "~n   Pid: ~p"
	  "~n   Cnt: ~p", [Pid, Cnt]),
    case ets:lookup(?LOCKER_TAB, Pid) of
	%% Last active reader: Time to let the waiting in
	%% The first of the waiting _has_ to be a write-lock
	%% (read-locks will only be set waiting if there is
	%% a waiting or active write).
	[#locker{mon_ref = MonRef, type = read}] when (Cnt == 1) ->
	    ?vdebug("unlock -> found read locker"
		    "~n   MonRef: ~p", [MonRef]),
	    erlang:demonitor(MonRef, [flush]),
	    ets:delete(?LOCKER_TAB, Pid),
	    case active_waiting_writer(Waiting) of
		{true, StillWaiting} ->
		    ?vtrace("unlock -> activated when"
			    "~n   StillWaiting: ~p", [StillWaiting]),
%% 		    ?vtrace("unlock -> done when"
%% 			    "~n   Lockers: ~p", [ets:tab2list(?LOCKER_TAB)]),
		    {noreply, State#state{active_count = 1,
					  writer       = true,
					  waiting      = StillWaiting}};
		{false, []} ->
		    ?vtrace("unlock -> none activated", []),
%% 		    ?vtrace("unlock -> done when"
%% 			    "~n   Lockers: ~p", [ets:tab2list(?LOCKER_TAB)]),
		    {noreply, State#state{active_count = 0,
					  writer       = false,
					  waiting      = []}}
	    end;

	[#locker{mon_ref = MonRef, type = read}] ->
	    ?vdebug("unlock -> found read locker"
		    "~n   MonRef: ~p", [MonRef]),
	    erlang:demonitor(MonRef, [flush]),
	    ets:delete(?LOCKER_TAB, Pid),
%% 	    ?vtrace("unlock -> done when"
%% 		    "~n   Lockers: ~p", [ets:tab2list(?LOCKER_TAB)]),
	    {noreply, State#state{active_count = dec(Cnt)}};

	[#locker{mon_ref = MonRef, type = write}] ->
	    %% Release the hord (maybe)
	    ?vdebug("unlock -> found write locker"
		    "~n   MonRef: ~p", [MonRef]),
	    erlang:demonitor(MonRef, [flush]),
	    ets:delete(?LOCKER_TAB, Pid),
	    {Active, StillWaiting, Writer} =
		activate_waiting_readers_or_maybe_writer(Waiting),
	    ?vtrace("unlock -> new reader(s) or maybe writer activated:"
		    "~n   Active:       ~p"
		    "~n   StillWaiting: ~p"
		    "~n   Writer:       ~p", [Active, StillWaiting, Writer]),
%% 	    ?vtrace("unlock -> done when"
%% 		    "~n   Lockers: ~p", [ets:tab2list(?LOCKER_TAB)]),
	    {noreply, State#state{active_count = Active,
				  writer       = Writer,
				  waiting      = StillWaiting}};

	%% If we have no active lockers, this may be a bug and therefor
	%% see if we can activate some of the waiting
	_ when (State#state.active_count == 0) ->
	    ?vdebug("unlock -> could not find locker", []),
	    {Active, StillWaiting, Writer} =
		activate_waiting_readers_or_maybe_writer(Waiting),
	    ?vtrace("unlock -> new reader(s) or maybe writer activated:"
		    "~n   Active:       ~p"
		    "~n   StillWaiting: ~p"
		    "~n   Writer:       ~p", [Active, StillWaiting, Writer]),
%% 	    ?vtrace("unlock -> done when"
%% 		    "~n   Lockers: ~p", [ets:tab2list(?LOCKER_TAB)]),
	    {noreply,
	     State#state{active_count = Active,
			 writer       = Writer,
			 waiting      = StillWaiting}};

	_ ->
	    {noreply, State}
    end;

handle_cast({downgrade_lock, Pid}, #state{waiting = Waiting} = State) ->
    ?vlog("downgrade_lock -> entry when waiting with"
	  "~n   Pid: ~p", [Pid]),
    case ets:lookup(?LOCKER_TAB, Pid) of
	[#locker{type = read}] ->
	    {noreply, State};

	[#locker{type = write} = Locker] ->
	    %% We need to check if this is the only write(r),
	    %% in that case we must update the writer field
	    ets:insert(?LOCKER_TAB, Locker#locker{type = read}),
	    {Cnt, NewWaiting} = activate_waiting_readers(Waiting),
	    ?vtrace("downgrade_lock -> entry when waiting with"
		    "~n   Cnt:        ~p"
		    "~n   NewWaiting: ~p", [Cnt, NewWaiting]),
%% 	    ?vtrace("downgrade_lock -> done when"
%% 		    "~n   Lockers: ~p", [ets:tab2list(?LOCKER_TAB)]),
	    {noreply, State#state{active_count = Cnt,
				  waiting      = NewWaiting,
				  writer       = is_writer(NewWaiting)}}
    end;

handle_cast(Msg, State) ->
    warning_msg("received unknown message: ~n~p", [Msg]),
    {noreply, State}.

%%--------------------------------------------------------------------
%% Func: handle_info/2
%% Returns: {noreply, State}          |
%%          {noreply, State, Timeout} |
%%          {stop, Reason, State}            (terminate/2 is called)
%%--------------------------------------------------------------------

%% This must be a glitch
handle_info({'DOWN', _MonRef, process, Pid, Reason},
	    #state{active_count = 0, waiting = []} = State) ->
    ?vlog("received DOWN message from ~p when no active and no waiting"
	  "~n   exited for reason: ~n~p", [Pid, Reason]),
    {noreply, State};

handle_info({'DOWN', _MonRef, process, Pid, Reason},
	    #state{active_count = Cnt, waiting = []} = State) ->
    ?vlog("received DOWN message from ~p when active but no waiting"
	  "~n   exited for reason: ~n~p", [Pid, Reason]),
    case handle_maybe_active_down(Cnt, Pid) of
	{NewCnt, write} ->
%% 	    ?vtrace("DOWN -> done when"
%% 		    "~n   Lockers: ~p", [ets:tab2list(?LOCKER_TAB)]),
	    {noreply, State#state{active_count = NewCnt, writer = false}};
	{NewCnt, read} ->
%% 	    ?vtrace("DOWN -> done when"
%% 		    "~n   Lockers: ~p", [ets:tab2list(?LOCKER_TAB)]),
	    {noreply, State#state{active_count = NewCnt}}
    end;

handle_info({'DOWN', _MonRef, process, Pid, Reason}, State) ->
    ?vlog("received DOWN message from ~p"
	  "~n   exited for reason: ~n~p", [Pid, Reason]),
    NewState = handle_maybe_active_or_waiting_down(Pid, State),
%%     ?vtrace("DOWN -> done when"
%% 	    "~n   Lockers: ~p", [ets:tab2list(?LOCKER_TAB)]),
    {noreply, NewState};

handle_info({'EXIT', Pid, Reason}, S) ->
    %% The only other process we should be linked to is
    %% our supervisor, so die...
    {stop, {received_exit, Pid, Reason}, S};

handle_info(Info, State) ->
    warning_msg("received unknown info: ~n~p", [Info]),
    {noreply, State}.

%%--------------------------------------------------------------------
%% Func: terminate/2
%% Purpose: Shutdown the server
%% Returns: any (ignored by gen_server)
%%--------------------------------------------------------------------
terminate(Reason, State) ->
    ?vlog("terminate ->"
	  "~n   Reason: ~p"
	  "~n   State:  ~p", [Reason, State]),
    ets:delete(?CACHE),
    ets:delete(?LOCKER_TAB),
    ok.

%%%-------------------------------------------------------------------
%%% Internal functions
%%%-------------------------------------------------------------------

%% Locks are initially exclusive which means that it is possible
%% to both read _and_ write. After a downgrade, it is only possible
%% to read. But since, by then, the process already has a lock, it
%% can just go ahead and read.

lock(Type) ->
    call({lock, Type, infinity}).

%% Upgrade from read to lock write
upgrade_lock() ->
    call({upgrade_lock, self()}).

%% Downgrade from write to read lock
downgrade_lock() ->
    cast({downgrade_lock, self()}).

unlock() ->
    cast({unlock, self()}).

insert_all(Targets) ->
    Fun = fun({NotifyName, Data}) -> insert(NotifyName, Data) end,
    lists:foreach(Fun, Targets).

insert(NotifyName, {DestAddr, TargetName, TargetParams, NotifyType}) ->
    Key  = {NotifyName, TargetName},
    Data = {DestAddr, TargetParams, NotifyType},
    ets:insert(?CACHE, {Key, Data}).

delete_all() ->
    ets:delete_all_objects(?CACHE).

%%----------------------------------------------------------

%% This function is called when we have active but no waiting
%% lockers. So, if we have it stored, it's an active locker.
handle_maybe_active_down(Cnt, Pid) ->
    case ets:lookup(?LOCKER_TAB, Pid) of
	[#locker{type = Type}] ->
	    ets:delete(?LOCKER_TAB, Pid),
	    {dec(Cnt), Type};
	_ ->
	    {Cnt, read}
    end.

handle_maybe_active_or_waiting_down(Pid,
				    #state{active_count = Cnt,
					   waiting      = Waiting} = State) ->
    case ets:lookup(?LOCKER_TAB, Pid) of
	[#locker{state = active, type = read}] when (Cnt == 1) ->
	    %% 1) This means that the writer must be waiting
	    %% 2) The last reader terminated,
	    %%    time to activate the wating writer
	    %%    If this was the last one, then we must
	    %%    activate the waiting writer.
	    ets:delete(?LOCKER_TAB, Pid),
	    case active_waiting_writer(Waiting) of
		{true, StillWaiting} ->
		    %% active count is still 1, so no need to update that
		    State#state{writer  = true,
                                waiting = StillWaiting};
		{false, []} ->
		    State#state{active_count = 0,
				writer       = false,
				waiting      = []}
	    end;

	[#locker{state = active, type = read}] ->
	    %% 1) This means that the writer must be waiting
	    %% 2) More then one (read-) locker active, just
	    %%    clean up.
	    ets:delete(?LOCKER_TAB, Pid),
	    State#state{active_count = dec(Cnt)};

	[#locker{state = active, type = write}] ->
	    ets:delete(?LOCKER_TAB, Pid),
	    {Active, StillWaiting, Writer} =
		activate_waiting_readers_or_maybe_writer(Waiting),
	    State#state{active_count = Active,
			writer       = Writer,
			waiting      = StillWaiting};

	[#locker{state = waiting, type = read}] ->
	    ets:delete(?LOCKER_TAB, Pid),
	    State#state{waiting = lists:delete(Pid, Waiting)};

	[#locker{state = waiting, type = write}] ->
	    %% We need to check if this is the only waiting writer.
	    %% If it is we shall set the writer field to false
	    ets:delete(?LOCKER_TAB, Pid),
	    NewWaiting = lists:delete(Pid, Waiting),
	    Writer =
		case ets:match_object(?LOCKER_TAB,
				      #locker{state = active,
					      type  = write,
					      _     = '_'}) of
		    [] ->
			is_writer(NewWaiting);
		    _ ->
			true
		end,
	    State#state{writer  = Writer,
			waiting = NewWaiting};

	_Other ->
	    State

    end.

is_writer([]) ->
    false;
is_writer([Pid|Pids]) ->
    case ets:lookup(?LOCKER_TAB, Pid) of
	[#locker{type = write}] ->
	    true;
	_Other ->
	    is_writer(Pids)
    end.

%%----------------------------------------------------------

%% This is just a utility function to make sure we don't
%% end up in a lockout situation.
active_waiting_writer([]) ->
    {false, []};
active_waiting_writer([H|T]) ->
    case ets:lookup(?LOCKER_TAB, H) of
        [#locker{from = From} = L] ->
            ets:insert(?LOCKER_TAB, L#locker{state = active}),
            gen_server:reply(From, ok),
            {true, T};
        [] ->
            %% Oups
            error_msg("Could not find locker record for ~p", [H]),
            active_waiting_writer(T)
    end.

%% Activate waiting read(ers)
activate_waiting_readers(Waiting) ->
    activate_waiting_readers(Waiting, 1).

activate_waiting_readers([], Cnt) ->
    {Cnt, []};
activate_waiting_readers([H|T] = Waiting, Cnt) ->
    case ets:lookup(?LOCKER_TAB, H) of
        [#locker{from = From, type = read} = L] ->
            ets:insert(?LOCKER_TAB, L#locker{state = active}),
            gen_server:reply(From, ok),
            activate_waiting_readers(T, inc(Cnt));

        %% Found a writer, time to stop starting readers
        [#locker{type = write}] ->
            {Cnt, Waiting};

        [] ->
            %% Oups
            error_msg("Could not find locker record for ~p", [H]),
            activate_waiting_readers(T, Cnt)

    end.

activate_waiting_readers_or_maybe_writer(Waiting) ->
    activate_waiting_readers_or_maybe_writer(Waiting, 0).

activate_waiting_readers_or_maybe_writer([], Cnt) ->
    {Cnt, [], false};
activate_waiting_readers_or_maybe_writer([H|T] = Waiting, Cnt) ->
    case ets:lookup(?LOCKER_TAB, H) of
        [#locker{from = From, type = read} = L] ->
            ets:insert(?LOCKER_TAB, L#locker{state = active}),
            gen_server:reply(From, ok),
            activate_waiting_readers_or_maybe_writer(T, inc(Cnt));

        %% Only active writer only if it's the first
        [#locker{from = From, type = write} = L] when (Cnt == 0) ->
            ets:insert(?LOCKER_TAB, L#locker{state = active}),
            gen_server:reply(From, ok),
            {1, T, true};

        %% Found a writer, time to stop starting readers
        [#locker{type = write}] ->
            {Cnt, Waiting, false};

        [] ->
            %% Oups
            error_msg("Could not find locker record for ~p", [H]),
            activate_waiting_readers_or_maybe_writer(T, Cnt)

    end.

%%----------------------------------------------------------
%% Code change
%%----------------------------------------------------------

%% downgrade
%%
%% code_change({down, _Vsn}, S1, downgrade_to_pre_4_7) ->
%%     #state{dets = D, ets = E, notify_clients = NC, backup = B} = S1,
%%     stop_backup_server(B),
%%     S2 = {state, D, E, NC},
%%     {ok, S2};

%% upgrade
%%
%% code_change(_Vsn, S1, upgrade_from_pre_4_7) ->
%%     {state, D, E, NC} = S1,
%%     S2 = #state{dets = D, ets = E, notify_clients = NC},
%%     {ok, S2};

code_change(_Vsn, State, _Extra) ->
    {ok, State}.

%%------------------------------------------------------------------

inc(Cnt) ->
    Cnt + 1.

dec(Cnt) when (Cnt =< 0) ->
    0;
dec(Cnt) ->
    Cnt - 1.

%%------------------------------------------------------------------
%% This functions retrieves option values from the Options list.
%%------------------------------------------------------------------

get_opt(Key, Opts, Def) ->
    snmp_misc:get_option(Key, Opts, Def).

%%------------------------------------------------------------------

%% info_msg(F, A) ->
%%     ?snmpa_info("Target cache server: " ++ F, A).

warning_msg(F, A) ->
    ?snmpa_warning("Target cache server: " ++ F, A).

error_msg(F, A) ->
    ?snmpa_error("Target cache server: " ++ F, A).

%% ---

%% user_err(F, A) ->
%%     snmpa_error:user_err(F, A).

config_err(F, A) ->
    snmpa_error:config_err(F, A).

%% error(Reason) ->
%%     throw({error, Reason}).

%% ----------------------------------------------------------------

call(Req) ->
    gen_server:call(?SERVER, Req, infinity).

cast(Msg) ->
    gen_server:cast(?SERVER, Msg).

{'repo_name': 'erlang/otp', 'stars': '8441', 'repo_language': 'Erlang', 'file_name': 'vxworks_resolv.c', 'mime_type': 'text/x-c', 'hash': -2776511125482189445, 'source_dataset': 'data'}


using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Threading.Tasks;

namespace Dapper
{
    /// <summary>
    /// xml命令映射器
    /// </summary>
    public interface IXmlQuery
    {
        /// <summary>
        ///执行多结果集查询，返回IMultiResult
        /// </summary>
        /// <param name="commandTimeout">超时时间</param>
        /// <param name="commandType">命令类型</param>
        /// <returns></returns>
        IDbMultipleResult MultipleQuery(int? commandTimeout = null, CommandType? commandType = null);
        /// <summary>
        /// 执行单结果集查询，并返回dynamic类型的结果集
        /// </summary>
        /// <param name="commandTimeout">超时时间</param>
        /// <param name="commandType">命令类型</param>
        /// <returns></returns>
        IEnumerable<dynamic> Query(int? commandTimeout = null, CommandType? commandType = null);
        /// <summary>
        /// 异步执行单结果集查询，并返回dynamic类型的结果集
        /// </summary>
        /// <param name="commandTimeout">超时时间</param>
        /// <param name="commandType">命令类型</param>
        /// <returns></returns>
        Task<IEnumerable<dynamic>> QueryAsync(int? commandTimeout = null, CommandType? commandType = null);
        /// <summary>
        /// 执行单结果集查询，并返回T类型的结果集
        /// </summary>
        /// <typeparam name="T">返回类型</typeparam>
        /// <param name="commandTimeout">超时时间</param>
        /// <param name="commandType">命令类型</param>
        /// <returns></returns>
        IEnumerable<T> Query<T>(int? commandTimeout = null, CommandType? commandType = null);
        /// <summary>
        /// 异步执行单结果集查询，并返回T类型的结果集
        /// </summary>
        /// <typeparam name="T">返回类型</typeparam>
        /// <param name="commandTimeout">超时时间</param>
        /// <param name="commandType">命令类型</param>
        /// <returns></returns>
        Task<IEnumerable<T>> QueryAsync<T>(int? commandTimeout = null, CommandType? commandType = null);
        /// <summary>
        /// 执行无结果集查询，并返回受影响的行数
        /// </summary>
        /// <param name="commandTimeout">超时时间</param>
        /// <param name="commandType">命令类型</param>
        /// <returns></returns>
        int Execute(int? commandTimeout = null, CommandType? commandType = null);
        /// <summary>
        /// 异步执行无结果集查询，并返回受影响的行数
        /// </summary>
        /// <param name="commandTimeout">超时时间</param>
        /// <param name="commandType">命令类型</param>
        /// <returns></returns>
        Task<int> ExecuteAsync(int? commandTimeout = null, CommandType? commandType = null);
        /// <summary>
        /// 执行无结果集查询，并返回指定类型的数据
        /// </summary>
        /// <typeparam name="T">返回类型</typeparam>
        /// <param name="commandTimeout">超时时间</param>
        /// <param name="commandType">命令类型</param>
        /// <returns></returns>
        T ExecuteScalar<T>(int? commandTimeout = null, CommandType? commandType = null);
        /// <summary>
        /// 异步执行无结果集查询，并返回指定类型的数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="commandTimeout">超时时间</param>
        /// <param name="commandType">命令类型</param>
        /// <returns></returns>
        Task<T> ExecuteScalarAsync<T>(int? commandTimeout = null, CommandType? commandType = null);
        /// <summary>
        /// 添加数据库参数
        /// </summary>
        /// <param name="name"></param>
        /// <param name="value"></param>
        void AddDbParameter(string name, object value);
    }

    /// <summary>
    /// 实现xml命令映射器
    /// </summary>
    internal class XmlQuery : IXmlQuery
    {
        private readonly string _sql = null;

        private Dictionary<string, object> _parameters = null;

        private readonly IDbContext _mapper = null;

        public XmlQuery(IDbContext mapper, string sql, Dictionary<string,object> parameters=null)
        {
            _mapper = mapper;
            _sql = sql;
            _parameters = parameters;
        }

        public IDbMultipleResult MultipleQuery(int? commandTimeout = null, CommandType? commandType = null)
        {
            return _mapper.QueryMultiple(_sql, _parameters, commandTimeout,commandType);
        }

        public int Execute(int? commandTimeout = null, CommandType? commandType = null)
        {
            return _mapper.Execute(_sql, _parameters, commandTimeout, commandType);
        }

        public Task<int> ExecuteAsync(int? commandTimeout = null, CommandType? commandType = null)
        {
            return _mapper.ExecuteAsync(_sql, _parameters, commandTimeout, commandType);
        }

        public IEnumerable<T> Query<T>(int? commandTimeout = null, CommandType? commandType = null)
        {
            return _mapper.Query<T>(_sql, _parameters, commandTimeout, commandType);
        }

        public IEnumerable<dynamic> Query(int? commandTimeout = null, CommandType? commandType = null)
        {
            return _mapper.Query(_sql, _parameters, commandTimeout, commandType);
        }

        public Task<IEnumerable<T>> QueryAsync<T>(int? commandTimeout = null, CommandType? commandType = null)
        {
            return _mapper.QueryAsync<T>(_sql, _parameters, commandTimeout, commandType);
        }

        public Task<IEnumerable<dynamic>> QueryAsync(int? commandTimeout = null, CommandType? commandType = null)
        {
            return _mapper.QueryAsync(_sql, _parameters, commandTimeout, commandType);
        }

        public T ExecuteScalar<T>(int? commandTimeout = null, CommandType? commandType = null)
        {
            return _mapper.ExecuteScalar<T>(_sql, _parameters, commandTimeout, commandType);
        }

        public Task<T> ExecuteScalarAsync<T>(int? commandTimeout = null, CommandType? commandType = null)
        {
            return _mapper.ExecuteScalarAsync<T>(_sql, _parameters, commandTimeout, commandType);
        }

        public void AddDbParameter(string name,object value)
        {
            if (_parameters == null)
            {
                _parameters = new Dictionary<string, object>();
            }
            if (_parameters.ContainsKey(name))
            {
                _parameters[name] = value;
            }
            else
            {
                _parameters.Add(name,value);
            }
        }
    }
}

{'repo_name': '1448376744/Dapper.Linq', 'stars': '134', 'repo_language': 'C#', 'file_name': 'DbQuery.cs', 'mime_type': 'text/x-c++', 'hash': 5963074023892380290, 'source_dataset': 'data'}


<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:media="http://search.yahoo.com/mrss/">
<channel>
  <title>Chris Penner</title>
  <link>{{domain}}</link>
  <atom:link href="{{domain}}{{url}}" rel="self" type="application/rss+xml" />
  <description>The Personal blog and musings of Chris Penner; designer, developer and future opsimath.</description>
  <category>Technology</category>
  <copyright>2014 Chris Penner</copyright>
  <language>en-us</language>
  <image>
      <url>{{domain}}/images/favicon.png</url>
    <title>Chris Penner</title>
    <link>{{domain}}</link>
  </image>
  {{#posts}}
  <item>
      <title>{{title}}</title>
      <author>chris@chrispenner.ca (Chris Penner)</author>
      <link>{{domain}}{{url}}</link>
      <guid>{{domain}}{{url}}</guid>
      <pubDate>{{date}}</pubDate>
      <description>{{description}}...</description>
        {{#image}}
            <media:thumbnail url='{{domain}}/images/{{{image}}}' height='75' width='75' />
        {{/image}}
      <content:encoded><![CDATA[
        {{#image}}
            <img src="{{domain}}/images/{{{image}}}" alt="{{title}}">
        {{/image}}
        {{{content}}}
      ]]></content:encoded>
  </item>
  {{/posts}}
</channel>
</rss>

{'repo_name': 'ChrisPenner/SitePipe', 'stars': '114', 'repo_language': 'Haskell', 'file_name': 'Makefile', 'mime_type': 'text/x-makefile', 'hash': 8304102555048750138, 'source_dataset': 'data'}


import { route } from 'preact-router';

import { Livechat } from '../api';
import { upsert, createToken, asyncForEach } from '../components/helpers';
import store from '../store';
import { normalizeAgent } from './api';
import { processUnread } from './main';
import { parentCall } from './parentCall';

const agentCacheExpiry = 3600000;
let agentPromise;
const getAgent = (triggerAction) => {
	if (agentPromise) {
		return agentPromise;
	}

	agentPromise = new Promise(async (resolve, reject) => {
		const { params } = triggerAction;

		if (params.sender === 'queue') {
			const { state } = store;
			const { defaultAgent, iframe: { guest: { department } } } = state;
			if (defaultAgent && defaultAgent.ts && Date.now() - defaultAgent.ts < agentCacheExpiry) {
				return resolve(defaultAgent); // cache valid for 1
			}

			let agent;
			try {
				agent = await Livechat.nextAgent(department);
			} catch (error) {
				return reject(error);
			}

			store.setState({ defaultAgent: { ...agent, ts: Date.now() } });
			resolve(agent);
		} else if (params.sender === 'custom') {
			resolve({
				username: params.name,
			});
		} else {
			reject('Unknown sender');
		}
	});

	// expire the promise cache as well
	setTimeout(() => {
		agentPromise = null;
	}, agentCacheExpiry);

	return agentPromise;
};

class Triggers {
	constructor() {
		if (!Triggers.instance) {
			this._started = false;
			this._requests = [];
			this._triggers = [];
			this._enabled = true;
			Triggers.instance = this;
		}

		return Triggers.instance;
	}

	init() {
		if (this._started) {
			return;
		}

		const { token, firedTriggers = [], config: { triggers } } = store.state;
		Livechat.credentials.token = token;

		if (!(triggers && triggers.length > 0)) {
			return;
		}

		this._started = true;
		this._triggers = [...triggers];

		firedTriggers.forEach((triggerId) => {
			this._triggers.forEach((trigger) => {
				if (trigger._id === triggerId) {
					trigger.skip = true;
				}
			});
		});

		this.processTriggers();
	}

	async fire(trigger) {
		const { token, user, firedTriggers = [] } = store.state;
		if (!this._enabled || user) {
			return;
		}
		const { actions } = trigger;

		await asyncForEach(actions, (action) => {
			if (action.name === 'send-message') {
				trigger.skip = true;

				getAgent(action).then(async (agent) => {
					const ts = new Date();

					const message = {
						msg: action.params.msg,
						token,
						u: agent,
						ts: ts.toISOString(),
						_id: createToken(),
						trigger: true,
					};

					await store.setState({
						triggered: true,
						messages: upsert(store.state.messages, message, ({ _id }) => _id === message._id, ({ ts }) => ts),
					});
					await processUnread();

					if (agent && agent._id) {
						await store.setState({ agent });
						parentCall('callback', ['assign-agent', normalizeAgent(agent)]);
					}

					route('/');
					parentCall('openWidget');
					store.setState({ minimized: false });
				});
			}
		});

		if (trigger.runOnce) {
			trigger.skip = true;
			firedTriggers.push(trigger._id);
			store.setState({ firedTriggers });
		}
	}

	processRequest(request) {
		this._requests.push(request);
		if (!this._started) {
			return;
		}

		this.processTriggers();
	}

	processTriggers() {
		this._triggers.forEach((trigger) => {
			if (trigger.skip) {
				return;
			}

			const self = this;
			trigger.conditions.forEach((condition) => {
				switch (condition.name) {
					case 'page-url':
						this._requests.forEach((request) => {
							const hrefRegExp = new RegExp(condition.value, 'g');
							if (request.location.href.match(hrefRegExp)) {
								self.fire(trigger);
							}
						});
						this._requests = [];
						break;
					case 'time-on-site':
						if (trigger.timeout) {
							clearTimeout(trigger.timeout);
						}
						trigger.timeout = setTimeout(() => {
							this.fire(trigger);
						}, parseInt(condition.value, 10) * 1000);
						break;
				}
			});
		});
	}

	set triggers(newTriggers) {
		this._triggers = [...newTriggers];
	}

	set enabled(value) {
		this._enabled = value;
	}
}

const instance = new Triggers();
export default instance;

{'repo_name': 'RocketChat/Rocket.Chat.Livechat', 'stars': '122', 'repo_language': 'JavaScript', 'file_name': 'config.yml', 'mime_type': 'text/plain', 'hash': -8842698483304926050, 'source_dataset': 'data'}


<testcase>
<info>
<keywords>
HTTP
HTTP FORMPOST
HTTP replaced headers
</keywords>
</info>
# Server-side
<reply>
<data>
HTTP/1.0 200 OK swsclose
Date: Thu, 09 Nov 2010 14:49:00 GMT
Server: test-server/fake

blablabla

</data>
</reply>

# Client-side
<client>
<server>
http
</server>
 <name>
HTTP RFC1867-type formposting without Expect: header
 </name>
 <command>
http://%HOSTIP:%HTTPPORT/we/want/44 -F name=daniel -F tool=curl -F file=@log/test44.txt -H "Expect:"
</command>
# We create this file before the command is invoked!
<file name="log/test44.txt">
foo-
This is a moo-
bar
</file>
</client>

# Verify data after the test has been "shot"
<verify>
<strip>
^(User-Agent:|Content-Type: multipart/form-data;|------).*
</strip>
<protocol>
POST /we/want/44 HTTP/1.1
User-Agent: curl/7.10.4 (i686-pc-linux-gnu) libcurl/7.10.4 OpenSSL/0.9.7a ipv6 zlib/1.1.3
Host: %HOSTIP:%HTTPPORT
Accept: */*
Content-Length: 408
Content-Type: multipart/form-data; boundary=----------------------------7c633d5c27ce

------------------------------7c633d5c27ce
Content-Disposition: form-data; name="name"

daniel
------------------------------7c633d5c27ce
Content-Disposition: form-data; name="tool"

curl
------------------------------7c633d5c27ce
Content-Disposition: form-data; name="file"; filename="test44.txt"
Content-Type: text/plain

foo-
This is a moo-
bar

------------------------------7c633d5c27ce--
</protocol>
</verify>
</testcase>

{'repo_name': 'ecere/ecere-sdk', 'stars': '228', 'repo_language': 'eC', 'file_name': 'dpl.c', 'mime_type': 'text/x-c', 'hash': -4929280846423619723, 'source_dataset': 'data'}


T12957.hs:4:16: warning: [-Woverlapping-patterns (in -Wdefault)]
    Pattern match is redundant
    In a case alternative: (_ : _) -> ...

{'repo_name': 'ghc/ghc', 'stars': '2376', 'repo_language': 'Haskell', 'file_name': 'Env.hs', 'mime_type': 'text/plain', 'hash': 6217693393380365414, 'source_dataset': 'data'}


/*
Copyright The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

// Code generated by client-gen. DO NOT EDIT.

package v1beta1

import (
	"time"

	v1beta1 "k8s.io/api/events/v1beta1"
	v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	types "k8s.io/apimachinery/pkg/types"
	watch "k8s.io/apimachinery/pkg/watch"
	scheme "k8s.io/client-go/kubernetes/scheme"
	rest "k8s.io/client-go/rest"
)

// EventsGetter has a method to return a EventInterface.
// A group's client should implement this interface.
type EventsGetter interface {
	Events(namespace string) EventInterface
}

// EventInterface has methods to work with Event resources.
type EventInterface interface {
	Create(*v1beta1.Event) (*v1beta1.Event, error)
	Update(*v1beta1.Event) (*v1beta1.Event, error)
	Delete(name string, options *v1.DeleteOptions) error
	DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error
	Get(name string, options v1.GetOptions) (*v1beta1.Event, error)
	List(opts v1.ListOptions) (*v1beta1.EventList, error)
	Watch(opts v1.ListOptions) (watch.Interface, error)
	Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1beta1.Event, err error)
	EventExpansion
}

// events implements EventInterface
type events struct {
	client rest.Interface
	ns     string
}

// newEvents returns a Events
func newEvents(c *EventsV1beta1Client, namespace string) *events {
	return &events{
		client: c.RESTClient(),
		ns:     namespace,
	}
}

// Get takes name of the event, and returns the corresponding event object, and an error if there is any.
func (c *events) Get(name string, options v1.GetOptions) (result *v1beta1.Event, err error) {
	result = &v1beta1.Event{}
	err = c.client.Get().
		Namespace(c.ns).
		Resource("events").
		Name(name).
		VersionedParams(&options, scheme.ParameterCodec).
		Do().
		Into(result)
	return
}

// List takes label and field selectors, and returns the list of Events that match those selectors.
func (c *events) List(opts v1.ListOptions) (result *v1beta1.EventList, err error) {
	var timeout time.Duration
	if opts.TimeoutSeconds != nil {
		timeout = time.Duration(*opts.TimeoutSeconds) * time.Second
	}
	result = &v1beta1.EventList{}
	err = c.client.Get().
		Namespace(c.ns).
		Resource("events").
		VersionedParams(&opts, scheme.ParameterCodec).
		Timeout(timeout).
		Do().
		Into(result)
	return
}

// Watch returns a watch.Interface that watches the requested events.
func (c *events) Watch(opts v1.ListOptions) (watch.Interface, error) {
	var timeout time.Duration
	if opts.TimeoutSeconds != nil {
		timeout = time.Duration(*opts.TimeoutSeconds) * time.Second
	}
	opts.Watch = true
	return c.client.Get().
		Namespace(c.ns).
		Resource("events").
		VersionedParams(&opts, scheme.ParameterCodec).
		Timeout(timeout).
		Watch()
}

// Create takes the representation of a event and creates it.  Returns the server's representation of the event, and an error, if there is any.
func (c *events) Create(event *v1beta1.Event) (result *v1beta1.Event, err error) {
	result = &v1beta1.Event{}
	err = c.client.Post().
		Namespace(c.ns).
		Resource("events").
		Body(event).
		Do().
		Into(result)
	return
}

// Update takes the representation of a event and updates it. Returns the server's representation of the event, and an error, if there is any.
func (c *events) Update(event *v1beta1.Event) (result *v1beta1.Event, err error) {
	result = &v1beta1.Event{}
	err = c.client.Put().
		Namespace(c.ns).
		Resource("events").
		Name(event.Name).
		Body(event).
		Do().
		Into(result)
	return
}

// Delete takes name of the event and deletes it. Returns an error if one occurs.
func (c *events) Delete(name string, options *v1.DeleteOptions) error {
	return c.client.Delete().
		Namespace(c.ns).
		Resource("events").
		Name(name).
		Body(options).
		Do().
		Error()
}

// DeleteCollection deletes a collection of objects.
func (c *events) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error {
	var timeout time.Duration
	if listOptions.TimeoutSeconds != nil {
		timeout = time.Duration(*listOptions.TimeoutSeconds) * time.Second
	}
	return c.client.Delete().
		Namespace(c.ns).
		Resource("events").
		VersionedParams(&listOptions, scheme.ParameterCodec).
		Timeout(timeout).
		Body(options).
		Do().
		Error()
}

// Patch applies the patch and returns the patched event.
func (c *events) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1beta1.Event, err error) {
	result = &v1beta1.Event{}
	err = c.client.Patch(pt).
		Namespace(c.ns).
		Resource("events").
		SubResource(subresources...).
		Name(name).
		Body(data).
		Do().
		Into(result)
	return
}

{'repo_name': 'cni-genie/CNI-Genie', 'stars': '356', 'repo_language': 'Go', 'file_name': 'bridge.go', 'mime_type': 'text/plain', 'hash': 8303897429857357707, 'source_dataset': 'data'}


namespace Effekseer.GUI.Component
{
	partial class PathForSound
	{
		/// <summary>
		/// 必要なデザイナー変数です。
		/// </summary>
		private System.ComponentModel.IContainer components = null;

		/// <summary>
		/// 使用中のリソースをすべてクリーンアップします。
		/// </summary>
		/// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param>
		protected override void Dispose(bool disposing)
		{
			if (disposing && (components != null))
			{
				components.Dispose();
			}
			base.Dispose(disposing);
		}

		#region コンポーネント デザイナーで生成されたコード

		/// <summary>
		/// デザイナー サポートに必要なメソッドです。このメソッドの内容を
		/// コード エディターで変更しないでください。
		/// </summary>
		private void InitializeComponent()
		{
			this.btn_load = new System.Windows.Forms.Button();
			this.lbl_file = new System.Windows.Forms.Label();
			this.lbl_info1 = new System.Windows.Forms.Label();
			this.btn_delete = new System.Windows.Forms.Button();
			this.btn_play = new System.Windows.Forms.Button();
			this.lbl_info2 = new System.Windows.Forms.Label();
			this.SuspendLayout();
			//
			// btn_load
			//
			this.btn_load.Font = new System.Drawing.Font("MS UI Gothic", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(128)));
			this.btn_load.Location = new System.Drawing.Point(0, 0);
			this.btn_load.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
			this.btn_load.Name = "btn_load";
			this.btn_load.Size = new System.Drawing.Size(53, 25);
			this.btn_load.TabIndex = 0;
			this.btn_load.Text = global::Effekseer.Properties.Resources.Load;
			this.btn_load.UseVisualStyleBackColor = true;
			this.btn_load.Click += new System.EventHandler(this.btn_load_Click);
			//
			// lbl_file
			//
			this.lbl_file.AutoSize = true;
			this.lbl_file.Font = new System.Drawing.Font("MS UI Gothic", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(128)));
			this.lbl_file.Location = new System.Drawing.Point(56, 6);
			this.lbl_file.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
			this.lbl_file.Name = "lbl_file";
			this.lbl_file.Size = new System.Drawing.Size(28, 14);
			this.lbl_file.TabIndex = 1;
			this.lbl_file.Text = "aaa";
			//
			// lbl_info1
			//
			this.lbl_info1.AutoSize = true;
			this.lbl_info1.Font = new System.Drawing.Font("MS UI Gothic", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(128)));
			this.lbl_info1.Location = new System.Drawing.Point(56, 30);
			this.lbl_info1.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
			this.lbl_info1.Name = "lbl_info1";
			this.lbl_info1.Size = new System.Drawing.Size(45, 14);
			this.lbl_info1.TabIndex = 3;
			this.lbl_info1.Text = "format";
			//
			// btn_delete
			//
			this.btn_delete.Font = new System.Drawing.Font("MS UI Gothic", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(128)));
			this.btn_delete.Location = new System.Drawing.Point(0, 24);
			this.btn_delete.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
			this.btn_delete.Name = "btn_delete";
			this.btn_delete.Size = new System.Drawing.Size(53, 25);
			this.btn_delete.TabIndex = 4;
			this.btn_delete.Text = global::Effekseer.Properties.Resources.Delete;
			this.btn_delete.UseVisualStyleBackColor = true;
			this.btn_delete.Click += new System.EventHandler(this.btn_delete_Click);
			//
			// btn_play
			//
			this.btn_play.Font = new System.Drawing.Font("MS UI Gothic", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(128)));
			this.btn_play.Location = new System.Drawing.Point(0, 48);
			this.btn_play.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
			this.btn_play.Name = "btn_play";
			this.btn_play.Size = new System.Drawing.Size(53, 25);
			this.btn_play.TabIndex = 5;
			this.btn_play.Text = global::Effekseer.Properties.Resources.PlayString;
			this.btn_play.UseVisualStyleBackColor = true;
			this.btn_play.Click += new System.EventHandler(this.btn_play_Click);
			//
			// lbl_info2
			//
			this.lbl_info2.AutoSize = true;
			this.lbl_info2.Font = new System.Drawing.Font("MS UI Gothic", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(128)));
			this.lbl_info2.Location = new System.Drawing.Point(56, 54);
			this.lbl_info2.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
			this.lbl_info2.Name = "lbl_info2";
			this.lbl_info2.Size = new System.Drawing.Size(45, 14);
			this.lbl_info2.TabIndex = 6;
			this.lbl_info2.Text = "format";
			//
			// PathForSound
			//
			this.AllowDrop = true;
			this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 15F);
			this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
			this.Controls.Add(this.lbl_info2);
			this.Controls.Add(this.btn_play);
			this.Controls.Add(this.btn_delete);
			this.Controls.Add(this.lbl_info1);
			this.Controls.Add(this.lbl_file);
			this.Controls.Add(this.btn_load);
			this.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
			this.Name = "PathForSound";
			this.Size = new System.Drawing.Size(209, 74);
			this.DragDrop += new System.Windows.Forms.DragEventHandler(this.PathForSound_DragDrop);
			this.DragEnter += new System.Windows.Forms.DragEventHandler(this.PathForSound_DragEnter);
			this.DragLeave += new System.EventHandler(this.PathForSound_DragLeave);
			this.ResumeLayout(false);
			this.PerformLayout();

		}

		#endregion

		private System.Windows.Forms.Button btn_load;
		private System.Windows.Forms.Label lbl_file;
		private System.Windows.Forms.Label lbl_info1;
		private System.Windows.Forms.Button btn_delete;
		private System.Windows.Forms.Button btn_play;
		private System.Windows.Forms.Label lbl_info2;
	}
}

{'repo_name': 'effekseer/Effekseer', 'stars': '512', 'repo_language': 'C++', 'file_name': 'test_screenshot.py', 'mime_type': 'text/x-python', 'hash': -6377628588305135351, 'source_dataset': 'data'}


<?php

namespace Google\AdsApi\AdManager\v202008;

/**
 * This file was generated from WSDL. DO NOT EDIT.
 */
class ActivateAudienceSegments extends \Google\AdsApi\AdManager\v202008\AudienceSegmentAction
{

    public function __construct()
    {

    }

}

{'repo_name': 'googleads/googleads-php-lib', 'stars': '541', 'repo_language': 'PHP', 'file_name': 'ReportDownloaderTest.php', 'mime_type': 'text/x-php', 'hash': 1056060670965463069, 'source_dataset': 'data'}


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

	<title>{#advanced_dlg.colorpicker_title}</title>

	{#advanced_dlg.colorpicker_title}
<form onsubmit="insertAction();return false" action="#">

{#advanced_dlg.colorpicker_picker_tab}

{#advanced_dlg.colorpicker_palette_tab}

{#advanced_dlg.colorpicker_named_tab}

			<fieldset>
				<legend>{#advanced_dlg.colorpicker_picker_title}</legend>

			</fieldset>

			<fieldset>
				<legend id="webcolors_title">{#advanced_dlg.colorpicker_palette_title}</legend>

			</fieldset>

			<fieldset id="named_picker_label">
				<legend id="named_title">{#advanced_dlg.colorpicker_named_title}</legend>

					{#advanced_dlg.colorpicker_name}

			</fieldset>

		<input type="submit" id="insert" name="insert" value="{#apply}" />
		<input type="button" id="cancel" name="cancel" value="{#cancel}" onclick="tinyMCEPopup.close();"/>

{#advanced_dlg.colorpicker_color} <input id="color" type="text" size="8" class="text mceFocus" aria-required="true" />

</form>

{'repo_name': 'diefenbach/django-lfs', 'stars': '521', 'repo_language': 'Python', 'file_name': 'config', 'mime_type': 'text/plain', 'hash': 6545245285496607044, 'source_dataset': 'data'}


/* grcfulib.c - Contains all remaining calls not contained in the
   comp calls dcomp calls or common calls and a function to load
   all of them into a fully loaded library

   	   Generic display driver for hi-res animator.
   Useful to fill in parts of a driver that are not implemented.
   Requires you to fill in _get_dot and _put_dot.  The rest of
   the system will funnel through these.  Over-ride other
   functions for increased performance.  Does reasonably well
   speedwise if _get_hseg(), _put_hseg(), and pj__set_hline() are
   implemented as higher level functions such as the blits go through
   these. */

#define GRCLIB_C
#include "errcodes.h"
#include "ptrmacro.h"
#include "memory.h"
#include "rastcall.h"
#include "rastlib.h"
#include "libdummy.h"

static void _grc_put_vseg(const Raster *v,Pixel *pixbuf,
	Ucoor x,Ucoor y,Ucoor height)
/* Move pixels from memory to a vertical line of destination raster. */
/* (Unclipped) */
{
while (height-- > 0)
	PUT_DOT(v, *pixbuf++, x, y++);
}

static void _grc_get_vseg(const Raster *v,Pixel *pixbuf,
	Ucoor x,Ucoor y,Ucoor height)
/* Move pixels from a vertical line of source raster to memory buffer. */
/* (Unclipped) */
{
while (height-- > 0)
	*pixbuf++ = GET_DOT(v, x, y++);
}

static void _grc_set_vline(const Raster *v, Pixel color,
	Ucoor x, Ucoor y, Ucoor height)
/* Draw a solid vertical line. */
/* (Unclipped) */
{
while (height-- > 0)
	PUT_DOT(v, color, x, y++);
}

static void _grc_xor_rect(const Raster *v, Pixel color,
	Ucoor x, Ucoor y, Ucoor width, Ucoor height)
/* Xor a rectangular piece of the raster with color. */
/* (Unclipped) */
{
Ucoor x1, w1;
Pixel sbuf[SBUF_SIZE/sizeof(Pixel)];
Pixel *lbuf;

lbuf = sbuf;
if(width > Array_els(sbuf))
	{
	if ((lbuf = pj_malloc(width*sizeof(Pixel))) == NULL)
		goto SLOW;
	}
while (height-- > 0)
	{
	GET_HSEG(v,lbuf,x,y,width);
	pj_xor_bytes(color,lbuf,width);
	PUT_HSEG(v,lbuf,x,y++,width);
	}
if (lbuf != sbuf)
	pj_free(lbuf);
return;
SLOW:
while (height-- > 0)
	{
	x1 = x;
	w1 = width;
	while (w1-- > 0)
		{
		PUT_DOT(v, color^GET_DOT(v,x1,y), x1, y);
		x1++;
		}
	y++;
	}
}

#ifdef UNTESTED
static void mask1line(UBYTE *mbytes, UBYTE bit1, Pixel *lbuf, Coor width,
					 const Pixel oncolor)

/* Expand an array of bits in memory into pixel buffer.  Where there are
   1's in the source bit-array set to oncolor. */
/* (Private to grc_driver.) */
{
UBYTE byte;

	byte = *mbytes++;
	while(--width >= 0)
	{
		if(bit1 & byte)
			*lbuf++ = oncolor;

		if((bit1>>=1) == 0)
		{
			bit1 = 0x80;
			byte = *mbytes++;
		}
	}
}
static void _grc_mask1blit(UBYTE *mbytes, const unsigned mbpr,
 	Coor src_x, Coor src_y,
	const Raster *dest,
	Coor dest_x, Coor dest_y,
	Coor width, Coor height,
	const Pixel oncolor)
/* Expand a memory buffer arranged as a bit-plane into a rectangular
   area of dest raster.  Used to implement graphics text and icons.
   1's in bit-plane are set to oncolor in dest.
   0's in bit-plane leave dest unchanged. */
/* (Unclipped.) */
{
Pixel *lbuf;
Pixel sbuf[SBUF_SIZE/sizeof(Pixel)];
UBYTE bit1;

	lbuf = sbuf;
	if(width > Array_els(sbuf))
	{
		if((lbuf = pj_malloc(width*sizeof(Pixel))) == NULL)
			return;
	}

	bit1 = (0x80>>(src_x&7));
	mbytes += (src_x>>3) + src_y*mbpr;

	while(--height >= 0)
	{
		GET_HSEG(dest,lbuf,dest_x,dest_y,width);
		mask1line(mbytes,bit1,lbuf,width,oncolor);
		PUT_HSEG(dest,lbuf,dest_x,dest_y++,width);
		mbytes += mbpr;
	}
	if(lbuf != sbuf)
		pj_free(lbuf);
}
#endif /* UNTESTED */

static mask1line(UBYTE *mbytes, UBYTE bit1, Coor width,
	const Raster *dest, Coor dest_x, const Coor dest_y,
	const Pixel oncolor)
/* Expand an array of bits in memory into dest raster.  Where there are
   0's in the source bit-array leave the raster as is.
   1's in the source bit-array set raster to oncolor. */
/* (Private to grc_driver.) */
{
UBYTE byte;

byte = *mbytes++;
while (--width >= 0)
	{
	if (bit1 & byte)
		PUT_DOT(dest, oncolor, dest_x, dest_y);
	dest_x++;
	if ((bit1>>=1) == 0)
		{
		bit1 = 0x80;
		byte = *mbytes++;
		}
	}
}

static void _grc_mask1blit(UBYTE *mbytes, const unsigned mbpr,
 	Coor src_x, Coor src_y,
	const Raster *dest,
	Coor dest_x, Coor dest_y,
	Coor width, Coor height,
	const Pixel oncolor)
/* Expand a memory buffer arranged as a bit-plane into a rectangular
   area of dest raster.  Used to implement graphics text and icons.
   1's in bit-plane are set to oncolor in dest.
   0's in bit-plane leave dest unchanged. */
/* (Unclipped.) */
{
UBYTE bit1;

bit1 = (0x80>>(src_x&7));
mbytes += (src_x>>3) + src_y*mbpr;
while (--height >= 0)
	{
	mask1line(mbytes, bit1, width, dest, dest_x, dest_y, oncolor);
	mbytes += mbpr;
	++src_y;
	++dest_y;
	}
}

static void mask2line(UBYTE *mbytes, UBYTE bit1, Pixel *lbuf, Coor width,
					 const Pixel oncolor, const Pixel offcolor)

/* Expand an array of bits in memory into pixel buffer.  Where there are
   0's in the source bit-array set to offcolor.
   1's in the source bit-array set to oncolor. */
/* (Private to grc_driver.) */
{
UBYTE byte;

	byte = *mbytes++;
	while(--width >= 0)
	{
		if(bit1 & byte)
			*lbuf++ = oncolor;
		else
			*lbuf++ = offcolor;

		if((bit1>>=1) == 0)
		{
			bit1 = 0x80;
			byte = *mbytes++;
		}
	}
}

static void _grc_mask2blit(UBYTE *mbytes, const unsigned mbpr,
	Coor src_x, Coor src_y,
	const Raster *dest,
	Coor dest_x, Coor dest_y,
	Coor width, Coor height,
	const Pixel oncolor, const Pixel offcolor)

/* Expand a memory buffer arranged as a bit-plane into a rectangular
   area of dest raster.  Used to implement graphics text and icons.
   1's in bit-plane are set to oncolor in dest.
   0's in bit-plane are set to offcolor in dest. */
/* (Unclipped.) */

{
Pixel *lbuf;
Pixel sbuf[SBUF_SIZE/sizeof(Pixel)];
UBYTE bit1;

	lbuf = sbuf;
	if(width > Array_els(sbuf))
	{
		if((lbuf = pj_malloc(width*sizeof(Pixel))) == NULL)
			return;
	}

	bit1 = (0x80>>(src_x&7));
	mbytes += (src_x>>3) + src_y*mbpr;

	while(--height >= 0)
	{
		mask2line(mbytes,bit1,lbuf,width,oncolor,offcolor);
		mbytes += mbpr;
		PUT_HSEG(dest,lbuf,dest_x,dest_y++,width);
	}
	if(lbuf != sbuf)
		pj_free(lbuf);
}

static void grc_swaprect(Raster *ra,			 	 /* raster a */
			  LONG ax, LONG ay,  		 /* ra Minx and Miny */
			  Raster *rb,   		     /* raster b */
			  LONG bx, LONG by, 		 /* rb minx and miny */
			  LONG width, LONG height) /* blit size */

/* unclipped swap rectangles in a and b this is NOT clipped */
{
UBYTE la[150], lb[150];
LONG wbx, wax;
LONG width_left;
LONG get_width;

	if(width <= sizeof(la))
	{
		while(height--)
		{
			GET_HSEG(ra,la,ax,ay,width);
			GET_HSEG(rb,lb,bx,by,width);
			PUT_HSEG(ra,lb,ax,ay++,width);
			PUT_HSEG(rb,la,bx,by++,width);
		}
		return;
	}

	while(height--)
	{
		wax = ax;
		wbx = bx;
		width_left = width;
		get_width = sizeof(la);
		for(;;)
		{
			GET_HSEG(ra,la,wax,ay,get_width);
			GET_HSEG(rb,lb,wbx,by,get_width);
			PUT_HSEG(ra,lb,wax,ay,get_width);
			PUT_HSEG(rb,la,wbx,by,get_width);

			if((width_left -= sizeof(la)) <= 0)
				break;
			wax += get_width;
			wbx += get_width;
			if(width_left < get_width)
				get_width = width_left;
		}
		++ay;
		++by;
	}
	return;
}

static Errcode grc_tblitrect(const Raster *src,	/* source raster */
				  Coor src_x, Coor src_y,	/* source Minx and Miny */
				  const Raster *dest,		/* destination raster */
				  Coor dest_x, Coor dest_y, /* destination minx and miny */
				  Coor width, Coor height,  /* blit size */
				  const Pixel tcolor)		/* transparent color */
/* Copys rectangle from src to dest except for transparent color in
   source. */
{
Pixel *source_buf, *dest_buf;
Pixel sbuf[SBUF_SIZE/sizeof(Pixel)];
Pixel ptcolor;

	ptcolor = tcolor;
	source_buf = sbuf;
	if(width > (Array_els(sbuf)/2))
	{
		if ((source_buf = pj_malloc((width+width)*sizeof(Pixel))) == NULL)
			return(Err_no_memory);
	}
	dest_buf = source_buf + width;
	while(height--)
	{
		GET_HSEG(src,source_buf,src_x,src_y++,width);
		GET_HSEG(dest,dest_buf,dest_x,dest_y,width);
		pj_tbli_line(source_buf, dest_buf, width, (void *)&ptcolor);
		PUT_HSEG(dest,dest_buf,dest_x,dest_y++,width);
	}
	if(source_buf != sbuf)
		pj_free(source_buf);
	return(Success);
}

static void xor_line(Pixel *source, Pixel *dest, Coor count)
/* (Private to grc_driver.) */
{
Pixel *maxdest;

	maxdest = dest + count;
	while(dest < maxdest)
		*dest++ ^= *source++;
}

static Errcode grc_xor_rast(Raster *source, Raster *dest)
/* Xor source raster into dest.  Assumes source and dest are same size */
{
Pixel *source_buf, *dest_buf;
Coor width, height;
Pixel sbuf[SBUF_SIZE/sizeof(Pixel)];
int y;

	width = dest->width;
	height = dest->height;
	y = 0;

	source_buf = sbuf;
	if(width > (Array_els(sbuf)/2))
	{
		if ((source_buf = pj_malloc((width+width)*sizeof(Pixel))) == NULL)
			return(Err_no_memory);
	}

	dest_buf = source_buf + width;
	while (--height >= 0)
	{
		GET_HSEG(source,source_buf,0,y,width);
		GET_HSEG(dest,dest_buf,0,y,width);
		xor_line(source_buf, dest_buf, width);
		PUT_HSEG(dest,dest_buf,0,y++,width);
	}
	if(source_buf != sbuf)
		pj_free(source_buf);
	return(Success);
}

/* this isn't static because bytemap lib uses it */

Errcode pj_grc_zoomblit( Raster *source,		/* source raster */
	           Coor src_x, Coor src_y,  /* source Minx and Miny */
	           Raster *dest,   		/* destination raster */
	           Coor dest_x, Coor dest_y,   /* destination minx and miny */
	           Ucoor width, Ucoor height,  /* destination blit size */
	           LONG zoom_x, LONG zoom_y )  /* zoom scalers */
/* Move rectangular area of raster expanding pixels as you go. */
{
Pixel *hline; /* note not too big here will have to be re-done */
Coor swidth;
Coor maxy;
Coor nexty;
Pixel *testzx;
Pixel *zend;
Pixel *lend;
int rightpix;
Pixel sbuf[SBUF_SIZE/sizeof(Pixel)];

	if(!height)
		return(0);

	hline = sbuf;
	if(width > Array_els(sbuf))
	{
		if ((hline = pj_malloc(width*sizeof(Pixel))) == NULL)
			return(Err_no_memory);
	}
	swidth = width/zoom_x;

	if((rightpix = width%zoom_x) != 0)
		++swidth;
	else
		rightpix = zoom_x;

	maxy = dest_y + height;
	nexty = dest_y;

	for(;;)
	{
		GET_HSEG(source,hline,src_x,src_y,swidth);
		++src_y;

		zend = &hline[width] - 1;
		lend = &hline[swidth] - 1;

		testzx = zend - rightpix;
		for(;;)
		{
			if(testzx < hline)
			{
				while(zend >= hline)
					*zend-- = *lend;
				break;
			}
			while(zend > testzx)
				*zend-- = *lend;
			--lend;
			testzx -= zoom_x;
		}
		if((nexty += zoom_y) >= maxy)
		{
			while(dest_y < maxy)
				PUT_HSEG(dest,hline,dest_x,dest_y++,width);
			goto OUT;
		}
		while(dest_y < nexty)
			PUT_HSEG(dest,hline,dest_x,dest_y++,width);
	}
OUT:
	if(hline != sbuf)
		pj_free(hline);
	return(Success);
}
#ifndef FLILIB_CODE
static void grc_diag_to_ptable( Raster *src, Pixel *dseg, Ucoor dsize,
			   			        Coor x0, Coor y0, Coor x1, Coor y1)

/* copy from an arbitrary line in src to a pixel array dsize long starting
   at dseg. This scales the pixels read from the source to the size of the
   destination buffer */
{
int incx, incy;
int dx, dy;
int dots;
int xerr, yerr;
Boolean didx;
Pixel spixel;

	if((dx = x1 - x0) < 0)
	{
		incx = -1;
	}
	else
	{
		incx = 1;
		dx = -dx;
	}
	if((dy = y1 - y0) < 0)
	{
		incy = -1;
	}
	else
	{
		incy = +1;
		dy = -dy;
	}
	dots = dsize;
	xerr = dots + (dx>>1);
	yerr = dots + (dy>>1);
	dx -= 1;
	dy -= 1;

	spixel = pj__get_dot(src,x0,y0);
	didx = FALSE;

	while (--dots >= 0)
	{
		*dseg++ = spixel; 	/* output one pixel */
		if((xerr += dx) <= 0)
		{
			didx = TRUE;
NEXTX:
			x0 += incx;
			if ((xerr += dsize) <= 0)
				goto NEXTX;
		}
		if((yerr += dy) > 0)
		{
			if(!didx)
				continue;
		}
		else
		{
NEXTY:
			y0 += incy;
			if ((yerr += dsize) <= 0)
				goto NEXTY;
		}
		spixel = pj__get_dot(src,x0,y0);
		didx = FALSE;
	}
}
#endif /* FLILIB_CODE */

#ifdef SLUFFED
void grc_wseg(const Raster *v, const SHORT pix2, Coor x, Coor y, Coor count)
{
#define WPSZ 100
SHORT pbuf[WPSZ];
short lc;

while (count > 0)
	{
	lc = count;
	if (lc > WPSZ)
		lc = WPSZ;
	pj_stuff_words(pix2, pbuf, lc);
	PUT_HSEG(v, pbuf, x, y, lc+lc);
	count -= lc;
	}
#undef WPSZ
}
#endif /* SLUFFED */

void pj_grc_load_fullcalls(struct rastlib *lib)
/* Return pointer to generic display function jump-table */
{
#ifdef NEVER
	lib->put_dot = _xxx_put_dot;
	lib->get_dot = _xxx_get_dot;
#endif /* NEVER */

	pj_grc_load_dcompcalls(lib);

#ifdef IN_DCOMPCALLS

	lib->put_hseg = _grc_put_hseg;
	lib->put_rectpix = grc_put_rectpix;
	lib->set_hline = _grc_set_hline;
	lib->set_rect = _grc_set_rect;
	lib->set_rast = grc_set_rast;

	lib->unbrun_rect = grc_unbrun_rect;
	lib->unlccomp_rect = grc_unlccomp_rect;
	lib->unss2_rect = grc_unss2_rect;

	lib->uncc64 = grc_uncc64;
	lib->uncc256 = grc_uncc256;

#endif /* IN_DCOMPCALLS */

	pj_grc_load_compcalls(lib);

#ifdef IN_COMPCALLS
	lib->get_hseg = _grc_get_hseg;
	lib->get_rectpix = grc_get_rectpix;
#endif /* IN_COMPCALLS */

	pj_grc_load_commcalls(lib);

#ifdef IN_COMMONCALLS

	lib->cput_dot = _grc_cput_dot;
	lib->cget_dot = _grc_cget_dot;

	/* binary calls */

	lib->blitrect[RL_TO_SAME] = grc_blitrect;
	lib->blitrect[RL_TO_BYTEMAP] = grc_t_blitrect;
	lib->blitrect[RL_FROM_BYTEMAP] = grc_f_blitrect;
	lib->blitrect[RL_TO_OTHER] = grc_blitrect;
#endif /* IN_COMMONCALLS */

	lib->put_vseg = _grc_put_vseg;
	lib->get_vseg = _grc_get_vseg;

	lib->set_vline = _grc_set_vline;

	lib->xor_rect = _grc_xor_rect;
	lib->mask1blit = (rl_type_mask1blit)_grc_mask1blit;
	lib->mask2blit = (rl_type_mask2blit)_grc_mask2blit;

	lib->swaprect[RL_TO_SAME] = grc_swaprect;
	lib->swaprect[RL_TO_BYTEMAP] = grc_swaprect;
	lib->swaprect[RL_FROM_BYTEMAP] = grc_swaprect;
	lib->swaprect[RL_TO_OTHER] = grc_swaprect;

	lib->tblitrect[RL_TO_SAME] = grc_tblitrect;
	lib->tblitrect[RL_TO_BYTEMAP] = grc_tblitrect;
	lib->tblitrect[RL_FROM_BYTEMAP] = grc_tblitrect;
	lib->tblitrect[RL_TO_OTHER] = grc_tblitrect;

	lib->xor_rast[RL_TO_SAME] = grc_xor_rast;
	lib->xor_rast[RL_TO_BYTEMAP] = grc_xor_rast;
	lib->xor_rast[RL_FROM_BYTEMAP] = grc_xor_rast;
	lib->xor_rast[RL_TO_OTHER] = grc_xor_rast;

	lib->zoomblit[RL_TO_SAME] = pj_grc_zoomblit;
	lib->zoomblit[RL_TO_BYTEMAP] = pj_grc_zoomblit;
	lib->zoomblit[RL_FROM_BYTEMAP] = pj_grc_zoomblit;
	lib->zoomblit[RL_TO_OTHER] = pj_grc_zoomblit;

#ifndef FLILIB_CODE
	lib->diag_to_ptable = grc_diag_to_ptable;
#endif /* FLILIB_CODE */
}

{'repo_name': 'AnimatorPro/Animator-Pro', 'stars': '152', 'repo_language': 'C', 'file_name': 'ABLITS.C', 'mime_type': 'text/x-c', 'hash': 1585825621971231262, 'source_dataset': 'data'}


require 'package'

class Iptables < Package
  description 'iptables is the userspace command line program used to configure the Linux 2.4.x and later packet filtering ruleset.'
  homepage 'https://www.netfilter.org/projects/iptables/'
  version '1.8.3'
  compatibility 'all'
  source_url 'https://www.netfilter.org/projects/iptables/files/iptables-1.8.3.tar.bz2'
  source_sha256 'a23cac034181206b4545f4e7e730e76e08b5f3dd78771ba9645a6756de9cdd80'

  binary_url ({
    aarch64: 'https://dl.bintray.com/chromebrew/chromebrew/iptables-1.8.3-chromeos-armv7l.tar.xz',
     armv7l: 'https://dl.bintray.com/chromebrew/chromebrew/iptables-1.8.3-chromeos-armv7l.tar.xz',
       i686: 'https://dl.bintray.com/chromebrew/chromebrew/iptables-1.8.3-chromeos-i686.tar.xz',
     x86_64: 'https://dl.bintray.com/chromebrew/chromebrew/iptables-1.8.3-chromeos-x86_64.tar.xz',
  })
  binary_sha256 ({
    aarch64: '18c2cdd028a017bd6e7fa02ebc1f41158fa3793873bcd33a3054d746a7655be1',
     armv7l: '18c2cdd028a017bd6e7fa02ebc1f41158fa3793873bcd33a3054d746a7655be1',
       i686: '7d19db312bd7d3ebad6e90049f03b656add0abf7f55f299a2243316136a2e130',
     x86_64: 'fbef75acb3252c55f30712ac902662a1c2968932e167df82173ba64cd333e45e',
  })

  def self.build
    system "./configure --prefix=#{CREW_PREFIX} --libdir=#{CREW_LIB_PREFIX} --disable-nftables"
    system 'make'
  end

  def self.install
    system "make", "DESTDIR=#{CREW_DEST_DIR}", "install"
  end
end

{'repo_name': 'skycocker/chromebrew', 'stars': '1588', 'repo_language': 'Ruby', 'file_name': 'test_all', 'mime_type': 'text/x-ruby', 'hash': 8958848289083963996, 'source_dataset': 'data'}