text:
A current LTS or Stable version of [Node.js](https://nodejs.org).  We recommend
using [nvm](https://github.com/creationix/nvm#readme) to manage node versions.

A utility for installing [Yeoman](http://yeoman.io/) packages.  `yo` should work
but it is recommended you use the `cnn` CLI available from
[CNN Package Generator](https://github.com/cnnlabs/cnn-package-generator#readme).

## Install

No install is necessary if you are using this generator with the `cnn` cli.

`yo` can be used to install.  Refer to the `yo`
[documentation](https://github.com/yeoman/yo#readme) for details.

Can be installed manually.

```shell
$ npm install --global generator-cnn-hapi
```

## Usage

With `cnn` (**recommended**):
- See the [README](https://github.com/cnnlabs/cnn-package-generator#readme) in
  the CNN Package Generator repo for usage details on the `cnn` CLI.

With `yo`:
- `$ yo cnn-hapi`


text:
using System.Collections.Generic;
using XCLCMS.Data.Model.Custom;

namespace XCLCMS.Data.BLL.View
{
    public class v_Orders
    {
        private readonly XCLCMS.Data.DAL.View.v_Orders dal = new XCLCMS.Data.DAL.View.v_Orders();

        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public XCLCMS.Data.Model.View.v_Orders GetModel(long AdsID)
        {
            return dal.GetModel(AdsID);
        }

        /// <summary>
        /// 获得数据列表
        /// </summary>
        public List<XCLCMS.Data.Model.View.v_Orders> GetModelList(string strWhere)
        {
            return dal.GetModelList(strWhere);
        }

        /// <summary>
        /// 分页数据列表
        /// </summary>
        public List<XCLCMS.Data.Model.View.v_Orders> GetPageList(XCLNetTools.Entity.PagerInfo pageInfo, XCLNetTools.Entity.SqlPagerConditionEntity condition)
        {
            return dal.GetPageList(pageInfo, condition);
        }

        /// <summary>
        /// 根据指定用户的指定产品返回所有订单信息
        /// </summary>
        public List<XCLCMS.Data.Model.View.v_Orders> GetUserProductOrderModelList(Order_UserProductCondition condition)
        {
            return dal.GetUserProductOrderModelList(condition);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
\chapter{Non-parametric Density Estimation}

\begin{multicols*}{2}
\noindent In parametric density estimation, we try to estimate $p(x|\omega_i, D_i)$ based on machine learning estimation. This approach requires some knowledge about the form of distribution. So, only the parameters need to be estimated. However, if we do not have any knowledge about the distribution, we need to use non-parametric density estimation.

\section{Histograms}

\noindent Divide the sample space into a number of bins and approximate the density at the center of each bin by the fraction of points in the training data that fall into the corresponding bin:
$$P_H(x) = \frac{1}{N} \frac{\text{number of } x^k \text{ in the same bin as x}}{\text{width of bin containing x}}$$
\noindent where $x^k$ is one training sample and $N$ is the number of training sample. \\

\noindent Histrogram require two parameters, bin width and starting position of the first bin. \\

\noindent The summation of $P_H(x) \times 2$ is equal to 1:
$$\int P_H dx = \sum P_H(x_c) \times 2 = 1$$
\section{General Theory for Non-parametric Density Estimation}

\noindent The probability that a vector x, drawn from a distribution p(x), will fall in a given region R of the same space is:
$$P=\int_R p(u) du$$

\noindent If random variable $X$ follow binomial distribution, we say $X \sim B(n, p)$, with $n$ trials and $p$ probability of success. The probability of getting $k$ success in $n$ trials is:
$$P(X=k) = \bigg( \begin{matrix} n \\ k \end{matrix}\bigg) p^k (1-p)^{n-k}$$
$$\bigg( \begin{matrix} n \\ k \end{matrix}\bigg) = \frac{n!}{(n-k)!k!}$$

\noindent The mean of binomial distribution is $E(k)=np$ and variance is $Var(k)=np(1-p)$. It can be proved that:
$$E(k / n) = p$$
$$Var(k / n) = \frac{p(1-p)}{n}$$

\noindent When $N\rightarrow \infty$, $p(1-p)/n \approx 0$. It means that the distribution of $k/N$ becomes very sharp at $k/n=p$. Therefore, we can use $k/n$ to approximate $p$.

$$P = \int_R p(x') dx' \approx p(x) V$$
$$\frac{k}{N} \approx p(x) V$$
$$p(x) \approx \frac{k}{nV}$$

\noindent where $R$ is a very small region around $x$, $p$ is the probability density that we want to estimate, $V$ is the volume surrounding $x$, $n$ is the total number of examples, $k$ is the number of examples inside $V$.\\

\noindent There are two approaches to apply this result:
\begin{enumerate}
    \item Kernel Density Estimation (KDE): fixed value of $V$ and determine $k$ from the data
    \item kNN approach: fixed value of $k$ and determine volume $V$ from data
\end{enumerate}

\section{Parzen Windows}

\noindent Let $R$ be a hypercube with sides of length $h$ centered at the estimation point $x$. Then in $d$ dimension, the volume is:
$$V=h^d$$

\noindent To count the number of sample points that fall inside the hypercube, we define a kernel function:
$$K(u) =
\begin{cases}
1 & |u_j| < 1/2, \forall j=1,\ldots,D \\
0 & \text{otherwise}
\end{cases}
$$

\noindent The total number of points inside the hypercube is:
$$k= \sum_{i=1}^{N} K\Big( \frac{x-x^i}{h}\Big)$$

\noindent Since we know $k$, $V$ and $N$, then:
$$p_{KDE}(x) = \frac{1}{Nh^d} \sum_{i=0}^N K \Big( \frac{x-x^i}{h}\Big)$$

\noindent Disadvantages of Parzen window:
\begin{enumerate}
    \item The estimated density has discontinuities
    \item The weights of $x_i$ are equal, regardless of their distance to the estimation point x
\end{enumerate}

\section{Smooth Kernerls}

\noindent To overcome drawbacks in Parzen window, we can replace the hypercube in the original Parzen window with other smooth kernel functions $K(u)$ such that:

$$\int_R K(x) dx = 1$$

\noindent For example, multivariate Gaussian density function:
$$K(x)=\frac{1}{(2 \pi)^{d/2}} exp \Big( - \frac{1}{2} x^T x\Big)$$

\section{Bandwidth Selection}

\noindent Problem of bandwidth:
\begin{enumerate}
    \item A large bandwidth will over-smooth the density and mask the structure in the data
    \item A small bandwidth will yield a density estimate that is spiky and very hard to interpret
\end{enumerate}

\noindent We would like to find a smoothing parameter that minimizes the error between the estimated density, $p_{KDE}$ and the true density. The mean square error is:
$$MSE(p_{KDE}(x)) = E[p_{KDE}(x) - p(x)]^2 + var(p_{KDE}(x))$$

\noindent where the $E[p_{KDE}(x) - p(x)]^2$ is called the bias and $var(p_{KDE}(x))$ is called the variance. Bias shows the expected difference of the estimation, variance shows the variation of the estimation. \\

\noindent The expression shows the bias-variance tradeoff; Reducing bias would increase variance and vice versa. Applying the bias-variance dilemma to bandwidth selction means that:
\begin{itemize}
    \item A large bandwidth will reduce the differences among the estimates of $p_{KDE}$ (the variance) but it will increase the bias of $p_{KDE}(x)$ with respect to the true density $p(x)$
    \item A small bandwidth will reduce the bias of $p_{KDE}(x)$, at the expense of larger variance in the estimates $p_{KDE}(x)$.
\end{itemize}

\section{K-nearest Neighbour}

\noindent In this approach, we fix the value of $k$ and determining the minimum volume $V$ that encompasses $k$ points in the dataset.
$$p(x)\approx \frac{k}{NV} = \frac{k}{N \times c_d \times R_k^d (d)}$$
\noindent where $R_k^d(x)$ is the distance between the estimation point $x$ and its k-th closest neighbour, $d$ is dimension of data, $c_d$ is the volumne of the unit sphere in $d$ dimensions, which is equal to:
$$
c_d =
\begin{cases}
2 & d=1 \\
\pi & d=2 \\
\frac{4\pi}{3} & d=3
\end{cases}
$$

\subsection{Approximation to Bayes Classifier}

\noindent Given sample $x$, find the $P(c_1|x)$ and $P(c_2|x)$. The number of nearest neighbour $k$ is given. To solve this problem using kNN:

\begin{enumerate}
    \item Find the $k$ number of data that are closest to $x$
    \item Compute $R$, the distance from $k$-th data to $x$
    \item Find $k_1$, which is the number of data that are belong to $c_1$
    \item Find $k_2$, which is the number of data that are belong to $c_1$
    \item Compute $P(c_i|x) = \frac{k_i}{k}$
\end{enumerate}

\end{multicols*}


text:
"use strict";

var _ = require("../lodash"),
    util = require("../util"),
    positionX = require("./bk").positionX;

module.exports = position;

function position(g) {
  g = util.asNonCompoundGraph(g);

  positionY(g);
  _.each(positionX(g), function(x, v) {
    g.node(v).x = x;
  });
}

function positionY(g) {
  var layering = util.buildLayerMatrix(g),
      rankSep = g.graph().ranksep,
      prevY = 0;
  _.each(layering, function(layer) {
    var maxHeight = _.max(_.map(layer, function(v) { return g.node(v).height; }));
    _.each(layer, function(v) {
      g.node(v).y = prevY + maxHeight / 2;
    });
    prevY += maxHeight + rankSep;
  });
}


text:
var global = require('Global');
cc.Class({
    extends: require("PopWin"),

    properties: {
        input:cc.EditBox,
        chatline:cc.Prefab,
        view:cc.ScrollView,
        layout:cc.Layout,
        _linnum:0,

        _isfirst:true,

    },

    // use this for initialization
    onLoad: function () {
        this.node.on('chat',function(event){
            this.AddChatLine(event.detail.nick +':'+event.detail.msg);
        },this);
    },

    Btn_Send:function(){
        if(this.input.string=='') return;
        this.AddChatLine(global.myinfo.nickname +':'+ this.input.string);
        // var line = cc.instantiate(this.chatline);
        // line.getComponent(cc.Label).string =  global.myinfo.nickname +':'+ this.input.string;
        // // console.log( new Date() );可加上日期
        // line.parent = this.layout.node;

        //发送消息
        var that = this;
		var p = {
			version: 102,
			method: 2003,
			seqId: Math.random() * 1000,
			timestamp: new Date().getTime(),
			data: that.input.string,
		};
		var jsp= JSON.stringify(p);
		global.socket.ws.send(jsp);

       // global.ui.emit('chat',{seat:global.myseat,msg:this.input.string});
        this.input.string='';
        //
        this.Hide();
    },
    AddChatLine:function(msg){
         if(this._isfirst){
                this.layout.node.children[0].getComponent(cc.Label).string =msg;
                this._isfirst = false;
            }else{
                var line = cc.instantiate(this.chatline);
                line.getComponent(cc.Label).string =  msg;
                line.parent = this.layout.node;
                //行数超过就删除
                var num = this.layout.node.childrenCount;

                if(num > 20)
                    this.layout.node.children[0].destroy();

                if(num> 8)
                    this.view.scrollToBottom();
            }
    }

});


text:
// Copyright 2017 Google Inc. 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.

goog.provide('upvote.packagecontents.PackageContents');

goog.require('upvote.app.constants');
goog.require('upvote.packagecontents.PackageContentsController');

/** @type {!angular.Component} */
upvote.packagecontents.PackageContents = {
  'bindings': {
    'contents': '<',
    'mainCertId': '<',
    'packageId': '<',
    'packageName': '<'
  },
  'controller': upvote.packagecontents.PackageContentsController,
  'controllerAs': 'ctrl',
  'templateUrl': upvote.app.constants.STATIC_URL_PREFIX +
      'components/packagecontents/contents.html',
};


text:
'use strict';

var program = require('commander'),
    pkg = require('../package.json');

module.exports = {

    /**
     * Main entrypoint of the CLI. Parse and process arguments passed to
     * bin/hbslint.
     *
     * @param {Array} args process.argv
     */
    interpret: function(args) {
        program
            .version(pkg.version)
            .parse(args);

        console.log(program);
    }
};


text:
package com.google.firebase.components;

import com.google.firebase.platforminfo.UserAgentPublisher;

public class TestUserAgentDependentComponent {
  private final UserAgentPublisher userAgentPublisher;

  public TestUserAgentDependentComponent(UserAgentPublisher userAgentPublisher) {
    this.userAgentPublisher = userAgentPublisher;
  }

  public UserAgentPublisher getUserAgentPublisher() {
    return userAgentPublisher;
  }
}


text:
using namespace boost::python;
using namespace GafferUIBindings;
using namespace GafferUI;

void GafferUIBindings::bindImageGadget()
{
	GadgetClass<ImageGadget>()
		.def( init<const std::string &>() )
		.def( init<IECore::ConstImagePrimitivePtr>() )
	;
}


text:
require 'digest/sha1'
# Digest::SHA1.hexdigest 'foo'
# Digest::SHA1.file(myFile).hexdigest

# --------------------------------------------------------------------------------

require 'fileutils'
# FileUtils.mkpath '/a/b/c'
# FileUtils.cp(src, dst)
# FileUtils.rm(path_to_image)

# --------------------------------------------------------------------------------------

def nyx_storage_abstraction_commit_datablob_to_nyx_store(datablob)
	blobref = "sha1-#{Digest::SHA1.hexdigest(datablob)}"
	folderpath = "#{$GLOBAL_PATH_TO_XCACHE}/#{blobref[5,2]}/#{blobref[7,2]}"
	FileUtils.mkpath folderpath if !File.exists? folderpath
	filepath = "#{folderpath}/#{blobref}"
	File.open(filepath, 'w') {|f| f.write(datablob) }
	blobref
end

def nyx_storage_abstraction_get_datablob_or_null(blobref)

	filepath = "#{$GLOBAL_PATH_TO_XCACHE}/#{blobref[5,2]}/#{blobref[7,2]}/#{blobref}"
	return IO.read(filepath) if File.exists? filepath

	Find.find("#{$GLOBAL_PATH_TO_YOUR_DOCUMENTS}") do |path|
		next if File.directory? path
		filedata = IO.read(path)
		return filedata if blobref=="sha1-#{Digest::SHA1.hexdigest(filedata)}"
	end

	nil
end


text:
int main(int argc, const char* argv[])
{
  // Allocate two large contiguous chunks.
  char* p = malloc(1024 - 8);
  char* p2 = malloc(1024 - 8);
  // Set them up with easily recognizable values.
  memset(p, 'A', 1024 - 8);
  memset(p2, 'B', 1024 - 8);
  // Overflow the first chunk, off-by-one, with a NUL byte.
  p[1024 - 8] = '\0';
  // Free the second chunk.
  // Because of the overflow, the first chunk will incorrectly be seen as free.
  // The last 8 bytes of the first chunk, 0x4141414141414141, will be treated
  // as a size. This size is a back index to the first chunk's alleged chunk
  // header location. The chunk header is deferenced.
  // You'll get a crash at around 0xbebebebebebebebe, or -0x4141414141414141 :)
  free(p2);
}


text:
package com.ericliudeveloper.sharedbillhelper.ui.activity;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import com.ericliudeveloper.sharedbillhelper.R;
import com.ericliudeveloper.sharedbillhelper.adapter.PagerAdapter;
import com.ericliudeveloper.sharedbillhelper.ui.fragment.BillListFragment;
import com.ericliudeveloper.sharedbillhelper.ui.fragment.MemberListFragment;
import com.ericliudeveloper.sharedbillhelper.util.Router;

public class MainActivity extends BaseActivity implements ViewPager.OnPageChangeListener {
    FloatingActionButton mFAB;
    View.OnClickListener createMemberClickListener, createBillClickListener;

    @Override
    protected int getSelfNavDrawerItem() {
        return R.id.nav_home;
    }

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

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        setupFloatActionButton();
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
//        View decorView = getWindow().getDecorView();

      //  Sticky flag — This is the UI you see if you use the IMMERSIVE_STICKY flag,
      // and the user swipes to display the system bars. Semi-transparent bars
      // temporarily appear and then hide again. The act of swiping doesn't clear
      // any flags, nor does it trigger your system UI visibility change listeners,
      // because the transient appearance of the system bars isn't considered a UI visibility
      // change.

        // Note: Remember that the "immersive" flags only take effect if you use them in conjunction
        // with SYSTEM_UI_FLAG_HIDE_NAVIGATION, SYSTEM_UI_FLAG_FULLSCREEN, or both. You can just use
        // one or the other, but it's common to hide both the status and the navigation bar when
        // you're implementing "full immersion" mode.

//        int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
//                | View.SYSTEM_UI_FLAG_FULLSCREEN
//                | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
//        decorView.setSystemUiVisibility(uiOptions);
    }

    private void setupFloatActionButton() {
        mFAB = (FloatingActionButton) findViewById(R.id.fab);
        createBillClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Router.startActivity(MainActivity.this, EditBillActivity.class, null);
            }
        };

        createMemberClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Intent intent = new Intent(MainActivity.this, EditMemberActivity.class);
//                startActivity(intent);
                Router.startActivity(MainActivity.this, EditMemberActivity.class, null);
            }
        };

        int currentPage = mViewPager.getCurrentItem();

        setupFABAccordingToPage(currentPage);

    }

    @Override
    protected void setupViewPager(ViewPager viewPager) {
        PagerAdapter pagerAdapter = new PagerAdapter(getFragmentManager());
        pagerAdapter.addFragment(new BillListFragment(), "Bill");
        pagerAdapter.addFragment(new MemberListFragment(), "Member");
        viewPager.setAdapter(pagerAdapter);
        viewPager.addOnPageChangeListener(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        setupFABAccordingToPage(position);
    }

    private void setupFABAccordingToPage(int position) {
        if (position == 0) {

            mFAB.setImageDrawable(getResources().getDrawable(R.drawable.ic_note_add_white_24dp));
            mFAB.setOnClickListener(createBillClickListener);
        }

        if (position == 1) {
            mFAB.setImageDrawable(getResources().getDrawable(R.drawable.ic_person_add_white_24dp));
            mFAB.setOnClickListener(createMemberClickListener);
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
}


text:
package de.intarsys.tools.stream;

import java.io.OutputStream;

/**
 *
 */
public class FastByteArrayOutputStream extends OutputStream {
	/** The buffer where data is stored. */
	protected byte[] buf;

	/** The number of valid bytes in the buffer. */
	protected int count;

	/**
	 *
	 */
	public FastByteArrayOutputStream() {
		this(32);
	}

	public FastByteArrayOutputStream(int size) {
		buf = new byte[size];
	}

	public byte[] getBytes() {
		return buf;
	}

	public void reset() {
		count = 0;
	}

	public int size() {
		return count;
	}

	public byte[] toByteArray() {
		byte[] result = new byte[count];
		System.arraycopy(buf, 0, result, 0, count);
		return result;
	}

	@Override
	public void write(byte[] b, int off, int len) {
		int newcount = count + len;
		if (newcount > buf.length) {
			byte[] newbuf = new byte[Math.max(buf.length << 1, newcount)];
			System.arraycopy(buf, 0, newbuf, 0, buf.length);
			buf = newbuf;
		}
		System.arraycopy(b, off, buf, count, len);
		count = newcount;
	}

	@Override
	public void write(int b) {
		if (count >= buf.length) {
			byte[] newbuf = new byte[Math.max(buf.length << 1, 1)];
			System.arraycopy(buf, 0, newbuf, 0, buf.length);
			buf = newbuf;
		}
		buf[count++] = (byte) b;
	}
}


text:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <omp.h>

#define DEBUG 0 // Display all error messages
#define NX 100000000 // number of cells in the x-direction
#define L 1.0 // domain length
#define C 1.0 // c, material conductivity. Uniform assumption.
#define TEND 1.0 // tEnd, output time
#define DX (L/NX) // dx, cell size
#define DT (1/(2*C*(1/DX/DX))) // dt, fix time step size
#define KX (C*DT/(DX*DX)) // numerical conductivity
#define NO_STEPS 10000 //(TEND/DT) // No. of time steps
#define PI 3.1415926535897932f

/* Declare functions */
void Manage_Memory(int phase, float **h_u, float **h_un);
void Call_Laplace(float **h_u, float **h_un);
void Call_Init(float **h_u);
void Save_Results(float *h_u);


text:
layout: docs
group: docs
title: Committees
order: 30
redirect_from:
  - /docs/committees/index.html
---

Committee listings are stored as `_committees/YY_YY.md` with YY_YY being the academic year 'span'.

##  Attribute Reference

{% include def-doc.html def=site.data.defs.committee %}

##  Example Committee

{% highlight yaml %}
---
title: 2012-13

committee:
  - role: President
    name: Sam Hayward
  - role: Treasurer
    name: Nick Stevenson
  - role: Theatre Manager
    name: James Bentley

comment: "Pretty sure there were more members!"
---
{% endhighlight %}


text:
A score rendering library in Swift.

[![Circle CI](https://circleci.com/gh/ocadaruma/museswift.svg?style=shield&circle-token= 6dbdbc73b8a0b355b7356d303e98c92a92b3a145)](https://circleci.com/gh/ocadaruma/museswift)

## Features

- Parse ABC notation.
- Render score.
- Playback

**All features are WIP**


text:
package com.intellij.openapi.application.impl;

import com.intellij.concurrency.JobSchedulerImpl;
import com.intellij.diagnostic.ThreadDumper;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.*;
import com.intellij.openapi.application.ex.ApplicationEx;
import com.intellij.openapi.application.ex.ApplicationUtil;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.progress.impl.ProgressManagerImpl;
import com.intellij.openapi.progress.util.ProgressIndicatorBase;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.EmptyRunnable;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.ThrowableComputable;
import com.intellij.testFramework.*;
import com.intellij.util.*;
import com.intellij.util.concurrency.Semaphore;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NotNull;
import org.junit.Assert;

import javax.swing.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;

import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.core.IsNot.not;

@RunFirst
public class ApplicationImplTest extends LightPlatformTestCase {
  @Override
  protected void setUp() throws Exception {
    super.setUp();
    exception = null;
    timeOut = System.currentTimeMillis() + TimeUnit.MINUTES.toMillis(2);
  }

  @Override
  protected void tearDown() throws Exception {
    readThreads = null;
    exception = null;
    super.tearDown();
  }

  private volatile Throwable exception;
  public void testAcquireReadActionLockVsRunReadActionPerformance() throws Throwable {
    final int N = 100_000_000;
    final Application application = ApplicationManager.getApplication();
    String err = null;

    for (int i=0; i<4; i++) {
      Callable<String> runnable = () -> {
        try {
          assertFalse(application.isReadAccessAllowed());
          CpuUsageData dataAcq = CpuUsageData.measureCpuUsage(() -> {
            for (int i1 = 0; i1 < N; i1++) {
              AccessToken token = application.acquireReadActionLock();
              //noinspection EmptyTryBlock
              try {
                // do it
              }
              finally {
                token.finish();
              }
            }
          });
          CpuUsageData dataRun = CpuUsageData.measureCpuUsage(() -> {
            for (int i1 = 0; i1 < N; i1++) {
              application.runReadAction(() -> {
              });
            }
          });
          long l1 = dataRun.durationMs;
          long l2 = dataAcq.durationMs;

          assertFalse(application.isReadAccessAllowed());
          int ratioPercent = (int)((l1 - l2) * 100.0 / l1);
          String msg = "acquireReadActionLock(" + l2 + "ms) vs runReadAction(" + l1 + "ms). Ratio: " + ratioPercent + "% (in "+(ratioPercent<0 ? "my" : "Maxim's") +" favor)";
          LOG.debug(msg + "\nAcquire:\n" + dataAcq.getSummary(" ") + "\nRun:\n" + dataRun.getSummary(" "));
          if (Math.abs(ratioPercent) > 40) {
            return "Suspiciously different times for " + msg;
          }
        }
        catch (Throwable e) {
          exception = e;
        }
        return null;
      };

      err = application.executeOnPooledThread(runnable).get();
      if (err == null) break;
      System.err.println("Still trying, attempt "+i+": "+err);
      System.gc();
    }

    assertNull(err);
    if (exception != null) throw exception;
  }

  public void testRead50Write50LockPerformance() {
    final int readIterations = 600_000;
    final int writeIterations = 600_000;

    runReadWrites(readIterations, writeIterations, 2000);
  }

  public void testRead100Write0LockPerformance() {
    final int readIterations = 60_000_000;
    final int writeIterations = 0;

    runReadWrites(readIterations, writeIterations, 10_000);
  }

  private static void runReadWrites(final int readIterations, final int writeIterations, int expectedMs) {
    NonBlockingReadActionImpl.cancelAllTasks(); // someone might've submitted a task depending on app events which we disable now
    final ApplicationImpl application = (ApplicationImpl)ApplicationManager.getApplication();
    Disposable disposable = Disposer.newDisposable();
    application.disableEventsUntil(disposable);

    try {
      PlatformTestUtil.startPerformanceTest("lock/unlock", expectedMs, () -> {
        final int numOfThreads = JobSchedulerImpl.getJobPoolParallelism();
        List<Thread> threads = new ArrayList<>(numOfThreads);
        for (int i = 0; i < numOfThreads; i++) {
          Thread thread = new Thread(() -> {
            assertFalse(application.isReadAccessAllowed());
            for (int i1 = 0; i1 < readIterations; i1++) {
              application.runReadAction(() -> {
              });
            }
          }, "read thread " + i);
          thread.start();
          threads.add(thread);
        }

        if (writeIterations > 0) {
          for (int i = 0; i < writeIterations; i++) {
            ApplicationManager.getApplication().runWriteAction(() -> {
            });
          }
        }
        joinWithTimeout(threads);
      }).assertTiming();
    }
    finally {
      Disposer.dispose(disposable);
    }
  }

  private static void joinWithTimeout(List<Thread> threads) throws TimeoutException {
    for (Thread thread : threads) {
      try {
        thread.join(20_000);
      }
      catch (InterruptedException e) {
        throw new RuntimeException(e);
      }
      if (thread.isAlive()) {
        System.err.println(thread + " is still running. threaddump:\n" + ThreadDumper.dumpThreadsToString());
        throw new TimeoutException();
      }
    }
  }

  private long timeOut;
  private void checkTimeout() throws Throwable {
    if (exception != null) throw exception;
    if (System.currentTimeMillis() > timeOut) throw new TimeoutException("timeout");
  }

  public void testAppLockReadWritePreference() throws Throwable {
    ApplicationImpl application = (ApplicationImpl)ApplicationManager.getApplication();
    application.assertIsDispatchThread();
    assertFalse(application.isWriteAccessAllowed());
    assertFalse(application.isWriteActionPending());

    // take read lock1.
    // try to take write lock - must wait (because of taken read lock)
    // try to take read lock2 - must wait (because of write preference - write lock is pending)
    // release read lock1 - write lock must be taken first
    // release write - read lock2 must be taken
    LOG.debug("-----");
    AtomicBoolean holdRead1 = new AtomicBoolean(true);
    AtomicBoolean holdWrite = new AtomicBoolean(true);
    AtomicBoolean read1Acquired = new AtomicBoolean(false);
    AtomicBoolean read1Released = new AtomicBoolean(false);
    AtomicBoolean read2Acquired = new AtomicBoolean(false);
    AtomicBoolean read2Released = new AtomicBoolean(false);
    AtomicBoolean writeAcquired = new AtomicBoolean(false);
    AtomicBoolean writeReleased = new AtomicBoolean(false);
    Thread readAction1 = new Thread(() -> {
      try {
        assertFalse(application.isDispatchThread());
        AccessToken stamp = application.acquireReadActionLock();
        try {
          LOG.debug("read lock1 acquired");
          read1Acquired.set(true);
          while (holdRead1.get()) checkTimeout();
        }
        finally {
          read1Released.set(true);
          stamp.finish();
          LOG.debug("read lock1 released");
        }
      }
      catch (Throwable e) {
        exception = e;
        throw new RuntimeException(e);
      }
    }, "read lock1");
    readAction1.start();

    while (!read1Acquired.get()) checkTimeout();
    AtomicBoolean aboutToAcquireWrite = new AtomicBoolean();
    // readActions2 should try to acquire read action when write action is pending
    Thread readActions2 = new Thread(() -> {
      try {
        assertFalse(application.isDispatchThread());
        while (!aboutToAcquireWrite.get()) checkTimeout();
        // make sure EDT called writelock
        while (!application.myLock.writeRequested) checkTimeout();
        assertTrue(application.isWriteActionPending());
        //assertFalse(application.tryRunReadAction(EmptyRunnable.getInstance()));
        AccessToken stamp = application.acquireReadActionLock();
        assertFalse(application.isWriteActionPending());
        try {
          LOG.debug("read lock2 acquired");
          read2Acquired.set(true);
        }
        finally {
          read2Released.set(true);
          stamp.finish();
          LOG.debug("read lock2 released");
        }
      }
      catch (Throwable e) {
        exception = e;
        throw new RuntimeException(e);
      }
    }, "read lock2");
    readActions2.start();

    Thread checkThread = new Thread(()->{
      try {
        assertFalse(application.isDispatchThread());
        while (!aboutToAcquireWrite.get()) checkTimeout();
        while (!read1Acquired.get()) checkTimeout();
        // make sure EDT called writelock
        while (!application.myLock.writeRequested) checkTimeout();

        long timeout = System.currentTimeMillis() + 2_000;
        while (System.currentTimeMillis() < timeout) {
          checkTimeout();
          assertTrue(aboutToAcquireWrite.get());
          assertTrue(read1Acquired.get());
          assertFalse(read1Released.get());
          assertFalse(read2Acquired.get());
          assertFalse(read2Released.get());
          assertFalse(writeAcquired.get());
          assertFalse(writeReleased.get());

          assertFalse(application.tryRunReadAction(EmptyRunnable.getInstance())); // write pending
          assertFalse(application.isWriteActionInProgress());
          assertFalse(application.isWriteAccessAllowed());
          assertTrue(application.isWriteActionPending());
        }

        holdRead1.set(false);
        while (!writeAcquired.get()) checkTimeout();

        timeout = System.currentTimeMillis() + 2_000;
        while (System.currentTimeMillis() < timeout) {
          checkTimeout();
          assertTrue(aboutToAcquireWrite.get());
          assertTrue(read1Acquired.get());
          assertTrue(read1Released.get());
          assertFalse(read2Acquired.get());
          assertFalse(read2Released.get());
          assertTrue(writeAcquired.get());
          assertFalse(writeReleased.get());

          assertFalse(application.tryRunReadAction(EmptyRunnable.getInstance()));
          assertTrue(application.isWriteActionInProgress());
          assertFalse(application.isWriteAccessAllowed());
          assertFalse(application.isWriteActionPending());
        }

        holdWrite.set(false);

        while (!read2Released.get()) checkTimeout();

        timeout = System.currentTimeMillis() + 2_000;
        while (System.currentTimeMillis() < timeout) {
          checkTimeout();
          assertTrue(aboutToAcquireWrite.get());
          assertTrue(read1Acquired.get());
          assertTrue(read1Released.get());
          assertTrue(read2Acquired.get());
          assertTrue(read2Released.get());
          assertTrue(writeAcquired.get());
          assertTrue(writeReleased.get());

          assertFalse(application.isWriteActionInProgress());
          assertFalse(application.isWriteAccessAllowed());
          assertFalse(application.isWriteActionPending());
        }
      }
      catch (Throwable e) {
        exception = e;
        throw new RuntimeException(e);
      }
    }, "check");
    checkThread.start();

    aboutToAcquireWrite.set(true);
    AccessToken stamp = application.acquireWriteActionLock(getClass());
    try {
      LOG.debug("write lock acquired");
      writeAcquired.set(true);

      while (holdWrite.get()) {
        checkTimeout();
        assertTrue(application.isWriteActionInProgress());
        assertTrue(application.isWriteAccessAllowed());
        assertFalse(application.isWriteActionPending());
      }
    }
    finally {
      writeReleased.set(true);
      stamp.finish();
      LOG.debug("write lock released");
    }

    joinWithTimeout(Arrays.asList(readAction1, readActions2, checkThread));
    if (exception != null) throw exception;
  }

  private volatile boolean tryingToStartWriteAction;
  private volatile boolean readStarted;
  private volatile List<Thread> readThreads;
  @SuppressWarnings("StringConcatenationInsideStringBufferAppend") // to prevent tearing
  public void testReadWontStartWhenWriteIsPending() throws Throwable {
    int N = 5;
    final AtomicBoolean[] anotherThreadStarted = new AtomicBoolean[N];
    final AtomicBoolean[] anotherReadActionStarted = new AtomicBoolean[N];
    for (int i = 0; i < anotherReadActionStarted.length; i++) {
      anotherReadActionStarted[i] = new AtomicBoolean();
      anotherThreadStarted[i] = new AtomicBoolean();
    }
    final StringBuffer LOG = new StringBuffer();
    Thread main = new Thread(() -> {
      try {
        ApplicationManager.getApplication().runReadAction((ThrowableComputable<Object, Throwable>)() -> {
          LOG.append("inside read action\n");
          readStarted = true;
          while (!tryingToStartWriteAction) checkTimeout();
          TimeoutUtil.sleep(100);

          readThreads = ContainerUtil.map(anotherReadActionStarted, readActionStarted -> new Thread(() -> {
            int finalI = ArrayUtil.indexOf(anotherReadActionStarted, readActionStarted);
            LOG.append("\nanother thread started " + finalI);
            anotherThreadStarted[finalI].set(true);
            ApplicationManager.getApplication().runReadAction(() -> {
              LOG.append("\ninside another thread read action " + finalI);
              readActionStarted.set(true);
              try {
                Thread.sleep(100);
              }
              catch (InterruptedException e) {
                throw new RuntimeException(e);
              }
              readActionStarted.set(false);
              LOG.append("\nfinished another thread read action " + finalI);
            });
            LOG.append("\nanother thread finished " + finalI);
          }, "another read action"));

          readThreads.forEach(Thread::start);

          for (AtomicBoolean threadStarted : anotherThreadStarted) {
            while (!threadStarted.get()) checkTimeout();
          }
          // now the other threads try to get read lock. we should not let them
          for (int i = 0; i < 10; i++) {
            for (AtomicBoolean readStarted1 : anotherReadActionStarted) {
              assertThat(!readStarted1.get(), "must not start another read action while write is pending");
            }
            TimeoutUtil.sleep(20);
          }
          LOG.append("\nfinished read action");

          return null;
        });
      }
      catch (Throwable e) {
        exception = e;
      }
    }, "read");
    main.start();

    while (!readStarted) checkTimeout();
    tryingToStartWriteAction = true;
    LOG.append("\nwrite about to start");
    ApplicationManager.getApplication().runWriteAction(() -> {
      LOG.append("\ninside write action");
      for (AtomicBoolean readStarted1 : anotherReadActionStarted) {
        assertThat(!readStarted1.get(), "must not start another read action while write is running");
      }
      LOG.append("\nfinished write action");
    });
    joinWithTimeout(ContainerUtil.concat(Collections.singletonList(main), readThreads));

    if (exception != null) {
      System.err.println(LOG);
      throw exception;
    }
  }

  private void assertThat(boolean condition, String msg) {
    if (!condition) {
      exception = new Exception(msg);
      throw new RuntimeException(msg);
    }
  }

  public void testProgressVsReadAction() throws Throwable {
    ProgressManager.getInstance().runProcessWithProgressSynchronously((ThrowableComputable<Void, Exception>)() -> {
      try {
        assertFalse(ApplicationManager.getApplication().isReadAccessAllowed());
        assertFalse(ApplicationManager.getApplication().isDispatchThread());
        for (int i=0; i<100;i++) {
          SwingUtilities.invokeLater(() -> ApplicationManager.getApplication().runWriteAction(() -> TimeoutUtil.sleep(20)));
          ApplicationManager.getApplication().runReadAction(() -> TimeoutUtil.sleep(20));
        }
      }
      catch (Exception e) {
        exception = e;
      }
      return null;
    }, "Cc", false, getProject());
    UIUtil.dispatchAllInvocationEvents();
    if (exception != null) throw exception;
  }

  public void testAsyncProgressVsReadAction() throws Throwable {
    Future<?> future = ((ProgressManagerImpl)ProgressManager.getInstance()).runProcessWithProgressAsynchronously(
      new Task.Backgroundable(getProject(), "Xx") {
        @Override
        public void run(@NotNull ProgressIndicator indicator) {
          try {
            assertFalse(ApplicationManager.getApplication().isReadAccessAllowed());
            assertFalse(ApplicationManager.getApplication().isDispatchThread());
          }
          catch (Exception e) {
            exception = e;
          }
        }
      });
    future.get();
    if (exception != null) throw exception;
  }

  public void testWriteActionIsAllowedFromEDTOnly() throws TimeoutException {
    Thread thread = new Thread("test") {
      @Override
      public void run() {
        try {
          ApplicationManager.getApplication().runWriteAction(EmptyRunnable.getInstance());
        }
        catch (Throwable e) {
          exception = e;
        }
      }
    };
    thread.start();
    joinWithTimeout(Collections.singletonList(thread));
    assertNotNull(exception);
  }

  public void testRunProcessWithProgressSynchronouslyInReadAction() throws Throwable {
    boolean result = ((ApplicationEx)ApplicationManager.getApplication())
      .runProcessWithProgressSynchronouslyInReadAction(getProject(), "title", true, "cancel", null, () -> {
        try {
          assertFalse(SwingUtilities.isEventDispatchThread());
          assertTrue(ApplicationManager.getApplication().isReadAccessAllowed());
        }
        catch (Throwable e) {
          exception = e;
        }
      });
    assertTrue(result);
    if (exception != null) throw exception;
  }

  public void testRunProcessWithProgressSynchronouslyInReadActionWithPendingWriteAction() throws Throwable {
    SwingUtilities.invokeLater(() -> ApplicationManager.getApplication().runWriteAction(EmptyRunnable.getInstance()));
    AtomicBoolean ran = new AtomicBoolean();
    boolean result = ((ApplicationEx)ApplicationManager.getApplication())
      .runProcessWithProgressSynchronouslyInReadAction(getProject(), "title", true, "cancel", null,
                                                       () -> ran.set(true));
    assertTrue(result);
    UIUtil.dispatchAllInvocationEvents();
    assertTrue(ran.get());
    if (exception != null) throw exception;
  }

  public void testRWLockPerformance() {
    long s = System.currentTimeMillis();
    while (System.currentTimeMillis() < s + 2000) {
      UIUtil.dispatchAllInvocationEvents();
    }
    //System.out.println("warming finished");
    final int readIterations = 100_000_000;
    PlatformTestUtil.startPerformanceTest("RWLock/unlock", 13_000, ()-> {
      ReadMostlyRWLock lock = new ReadMostlyRWLock(Thread.currentThread());

      final int numOfThreads = JobSchedulerImpl.getJobPoolParallelism();
      List<Thread> threads = new ArrayList<>(numOfThreads);
      for (int i = 0; i < numOfThreads; i++) {
        @SuppressWarnings("Convert2Lambda") // runnable is more debuggable
        Thread thread = new Thread(new Runnable() {
          @Override
          public void run() {
            for (int r = 0; r < readIterations; r++) {
              try {
                lock.readLock();
              }
              finally {
                lock.readUnlock();
              }
            }
          }
        }, "read thread " + i);
        thread.start();
        threads.add(thread);
      }
      joinWithTimeout(threads);
    }).usesAllCPUCores().assertTiming();
  }

  public void testCheckCanceledReadAction() throws Exception {
    Semaphore mayStartReadAction = new Semaphore();
    mayStartReadAction.down();

    ProgressIndicatorBase progress = new ProgressIndicatorBase();
    Future<?> future = ApplicationManager.getApplication().executeOnPooledThread(() -> ProgressManager.getInstance().runProcess(() -> {
      mayStartReadAction.waitFor();
      ReadAction.run(() -> fail("should be canceled before entering read action"));
    }, progress));

    WriteAction.run(() -> {
      mayStartReadAction.up();
      progress.cancel();
      future.get(1, TimeUnit.SECONDS);
    });
  }

  private static void safeWrite(ThrowableRunnable<RuntimeException> r) throws Throwable {
    Ref<Throwable> e = new Ref<>();
    ApplicationManager.getApplication().invokeLater(() -> {
      try {
        WriteAction.run(r);
      }
      catch (Throwable e1) {
        e.set(e1);
      }
    });
    UIUtil.dispatchAllInvocationEvents();
    if (e.get() != null) throw e.get();
  }

  public void testSuspendWriteActionDelaysForeignReadActions() throws Throwable {
    Semaphore mayStartForeignRead = new Semaphore();
    mayStartForeignRead.down();

    List<Future> futures = new ArrayList<>();

    ApplicationImpl app = (ApplicationImpl)ApplicationManager.getApplication();
    List<String> log = Collections.synchronizedList(new ArrayList<>());
    futures.add(app.executeOnPooledThread(() -> {
      assertTrue(mayStartForeignRead.waitFor(1000));
      ReadAction.run(() -> log.add("foreign read"));
    }));

    safeWrite(() -> {
      log.add("write started");
      app.executeSuspendingWriteAction(ourProject, "", () -> {
        app.invokeAndWait(() ->
          futures.add(app.executeOnPooledThread(() -> ReadAction.run(() -> log.add("foreign read")))));

        mayStartForeignRead.up();
        TimeoutUtil.sleep(50);

        ReadAction.run(() -> log.add("progress read"));
        app.invokeAndWait(() -> WriteAction.run(() -> log.add("nested write")));
        waitForFuture(app.executeOnPooledThread(() -> ReadAction.run(() -> log.add("forked read"))));
      });
      log.add("write finished");
    });

    futures.forEach(ApplicationImplTest::waitForFuture);
    assertOrderedEquals(log, "write started", "progress read", "nested write", "forked read", "write finished", "foreign read", "foreign read");
  }

  private static void waitForFuture(Future<?> future) {
    try {
      future.get(10_000, TimeUnit.MILLISECONDS);
    }
    catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  public void testHasWriteActionWorksInOtherThreads() throws Throwable {
    ApplicationImpl app = (ApplicationImpl)ApplicationManager.getApplication();
    ThrowableRunnable<RuntimeException> runnable = new ThrowableRunnable<RuntimeException>() {
      @Override
      public void run() throws RuntimeException {
        Class<? extends ThrowableRunnable<RuntimeException>> actionClass = getClass();
        assertTrue(app.hasWriteAction(actionClass));
        app.executeSuspendingWriteAction(ourProject, "", () -> ReadAction.run(() -> {
          assertTrue(app.hasWriteAction(actionClass));
          waitForFuture(app.executeOnPooledThread(() -> ReadAction.run(() -> assertTrue(app.hasWriteAction(actionClass)))));
        }));
      }
    };

    assertFalse(app.hasWriteAction(runnable.getClass()));
    safeWrite(runnable);
  }

  public void testPooledThreadsThatHappenInSuspendedWriteActionStayInSuspendedWriteAction() throws Throwable {
    LoggedErrorProcessor.getInstance().disableStderrDumping(getTestRootDisposable());

    Ref<Future> future = Ref.create();
    ApplicationImpl app = (ApplicationImpl)ApplicationManager.getApplication();
    safeWrite(() -> {
      try {
        Semaphore started = new Semaphore();
        started.down();
        app.executeSuspendingWriteAction(ourProject, "", () -> {
          future.set(app.executeOnPooledThread(() -> {
            started.up();
            TimeoutUtil.sleep(1000);
          }));
          assertTrue(started.waitFor(1000));
        });
        fail("should not allow pooled thread to stay there");
      }
      catch (AssertionError e) {
        assertTrue(ExceptionUtil.getThrowableText(e), isEscapingThreadAssertion(e));
      }
    });
    waitForFuture(future.get());
  }

  public void testPooledThreadsStartedAfterQuickSuspendedWriteActionDontGetReadPrivileges() throws Throwable {
    for (int i = 0; i < 1000; i++) {
      safeWrite(ApplicationImplTest::checkPooledThreadsDontGetWrongPrivileges);
    }
  }

  private static void checkPooledThreadsDontGetWrongPrivileges() {
    ApplicationImpl app = (ApplicationImpl)ApplicationManager.getApplication();
    Ref<Future> future = Ref.create();

    Disposable disableStderrDumping = Disposer.newDisposable();
    LoggedErrorProcessor.getInstance().disableStderrDumping(disableStderrDumping);

    Semaphore mayFinish = new Semaphore();
    mayFinish.down();
    try {
      app.executeSuspendingWriteAction(ourProject, "", () ->
        future.set(app.executeOnPooledThread(
          () -> assertTrue(mayFinish.waitFor(1000)))));
    }
    catch (AssertionError e) {
      if (!isEscapingThreadAssertion(e)) {
        e.printStackTrace();
        throw e;
      }
    }
    finally {
      Disposer.dispose(disableStderrDumping);
    }

    app.executeSuspendingWriteAction(ourProject, "", () -> {});
    mayFinish.up();
    waitForFuture(future.get());
  }

  private static boolean isEscapingThreadAssertion(AssertionError e) {
    return e.getMessage().contains("should have been terminated");
  }

  public void testReadActionInImpatientModeShouldThrowWhenThereIsAPendingWrite() throws Throwable {
    AtomicBoolean stopRead = new AtomicBoolean();
    AtomicBoolean readAcquired = new AtomicBoolean();
    ApplicationImpl app = (ApplicationImpl)ApplicationManager.getApplication();
    Future<?> readAction1 = app.executeOnPooledThread(() ->
      app.runReadAction(() -> {
        readAcquired.set(true);
        try {
          while (!stopRead.get()) checkTimeout();
        }
        catch (Throwable e) {
          exception = e;
        }
        finally {
          readAcquired.set(false);
        }
      })
    );
    while (!readAcquired.get()) checkTimeout();

    AtomicBoolean writeCompleted = new AtomicBoolean();
    Future<?> readAction2 = app.executeOnPooledThread(() -> {
      try {
        // wait for write action attempt to start - i.e. app.myLock.writeLock() started to execute
        while (!app.myLock.writeRequested) checkTimeout();
        app.executeByImpatientReader(() -> {
          try {
            assertFalse(app.isReadAccessAllowed());
            app.runReadAction(EmptyRunnable.getInstance());
            assertFalse(writeCompleted.get());
            if (exception != null) throw new RuntimeException(exception);
            System.err.println(ThreadDumper.dumpThreadsToString());
            fail("Must have been failed");
          }
          catch (ApplicationUtil.CannotRunReadActionException ignored) {

          }
          catch (Throwable e) {
            exception = e;
          }
          finally {
            stopRead.set(true);
          }
        });
      }
      catch (Throwable e) {
        exception = e;
      }
    });

    app.runWriteAction(EmptyRunnable.getInstance());
    writeCompleted.set(true);

    readAction2.get();
    readAction1.get();
    if (exception != null) throw exception;
  }

  public void testReadActionInImpatientModeMustNotThrowWhenThereIsAPendingWriteAndWeAreUnderNonCancelableSection() throws Throwable {
    AtomicBoolean stopRead = new AtomicBoolean();
    AtomicBoolean readAcquired = new AtomicBoolean();
    ApplicationImpl app = (ApplicationImpl)ApplicationManager.getApplication();
    Future<?> readAction1 = app.executeOnPooledThread(() ->
       app.runReadAction(() -> {
         readAcquired.set(true);
         try {
           while (!stopRead.get()) checkTimeout();
         }
         catch (Throwable e) {
           exception = e;
         }
         finally {
           readAcquired.set(false);
         }
       })
    );
    while (!readAcquired.get()) checkTimeout();

    AtomicBoolean executingImpatientReader = new AtomicBoolean();

    Future<?> readAction2 = app.executeOnPooledThread(() -> {
      // wait for write action attempt to start
      while (!app.myLock.writeRequested) {
        try {
          checkTimeout();
        }
        catch (Throwable e) {
          throw new RuntimeException(e);
        }
      }
      ProgressManager.getInstance().executeNonCancelableSection(()-> app.executeByImpatientReader(() -> {
        executingImpatientReader.set(true);
        app.runReadAction(EmptyRunnable.getInstance());
        // must not throw
      }));
    });

    Future<?> readAction1Canceler = app.executeOnPooledThread(() -> {
      try {
        while (!executingImpatientReader.get()) checkTimeout();
        // make sure readAction2 does call runReadAction()
        TimeoutUtil.sleep(300);
        stopRead.set(true);
      }
      catch (Throwable throwable) {
        exception = throwable;
      }
    });
    app.runWriteAction(EmptyRunnable.getInstance());

    readAction1Canceler.get();
    readAction2.get();
    readAction1.get();
    if (exception != null) throw exception;
  }

  public void testPluginsHostProperty() {
    String host = "IntellijIdeaRulezzz";

    String oldHost = System.setProperty(ApplicationInfoImpl.IDEA_PLUGINS_HOST_PROPERTY, host);

    try {
      ApplicationInfoImpl applicationInfo = new ApplicationInfoImpl();

      Assert.assertThat(applicationInfo.getPluginManagerUrl(), containsString(host));
      Assert.assertThat(applicationInfo.getPluginsListUrl(), containsString(host));
      Assert.assertThat(applicationInfo.getPluginsDownloadUrl(), containsString(host));
      Assert.assertThat(applicationInfo.getChannelsListUrl(), containsString(host));

      Assert.assertThat(applicationInfo.getPluginManagerUrl(), not(containsString(ApplicationInfoImpl.DEFAULT_PLUGINS_HOST)));
      Assert.assertThat(applicationInfo.getPluginsListUrl(), not(containsString(ApplicationInfoImpl.DEFAULT_PLUGINS_HOST)));
      Assert.assertThat(applicationInfo.getPluginsDownloadUrl(), not(containsString(ApplicationInfoImpl.DEFAULT_PLUGINS_HOST)));
      Assert.assertThat(applicationInfo.getChannelsListUrl(), not(containsString(ApplicationInfoImpl.DEFAULT_PLUGINS_HOST)));
    } finally {
      if (oldHost == null) {
        System.clearProperty(ApplicationInfoImpl.IDEA_PLUGINS_HOST_PROPERTY);
      } else {
        System.setProperty(ApplicationInfoImpl.IDEA_PLUGINS_HOST_PROPERTY, oldHost);
      }
    }
  }
}


text:
using System;
using System.Net;
namespace PusherServer
{
    public interface IRequestResult
    {
        string Body { get; }
        HttpStatusCode StatusCode { get; }
    }
}


text:
extern "C" {
#endif

   extern const char *foo(void);

#ifdef __cplusplus
}
#endif


text:
import random
import time

class RandomDate(object):

    def str_time_prop(self, start, end, format, prop):
        stime = time.mktime(time.strptime(start, format))
        etime = time.mktime(time.strptime(end, format))
        ptime = stime + prop * (etime - stime)
        return time.strftime(format, time.localtime(ptime))

    def random_date(self, start, end, prop):
        return self.str_time_prop(start, end, '%d/%b/%Y:%H:%M:%S', prop)

    def get_random(self):
        return self.random_date("1/Aug/2008:1:30:00", "1/Nov/2014:4:50:00", random.random())


text:
using Naveego.Live;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Naveego.Security
{

    public class User
    {

        private string[] _modules;
        private string[] _roles;

        public string Id { get; set; }

        public string Name
        {
            get { return Id; }
        }

        public string FirstName { get; set; }

        public string LastName { get; set; }

        public string Email { get; set; }

        public string ServiceTicket { get; set; }

        public bool IsDisabled { get; set; }

        public bool ForcePasswordReset { get; set; }

        public bool ForceAcceptAgreement { get; set; }

        public DateTime? LastLogin { get; set; }

        public string AccessCode { get; set; }

        public int AccessLevel { get; set; }

        public string BusinessPhone { get; set; }

        public string Edition { get; set; }

        public string MobilePhone { get; set; }

        public Guid UserId { get; set; }

        public string DisplayName { get; set; }

        public LiveStatus Live { get; set; }

        public string[] Roles
        {
            get
            {
                if (_roles == null)
                {
                    _roles = new string[0];
                }
                return _roles;
            }
            set { _roles = value; }
        }

        public string[] Modules
        {
            get
            {
                if (_modules == null)
                {
                    _modules = new string[0];
                }
                return _modules;
            }
            set { _modules = value; }
        }

    }
}


text:
#ifndef ARIA_wrapper_ExtraClasses_h
#define ARIA_wrapper_ExtraClasses_h

/** @cond INCLUDE_SWIG_ONLY_CLASSES */

/* ArConfigArg subclasses for specific types, since for some target languages
 * (Python) Swig can't differentiate booleans, integers, short integers,
 * unsigned integers, etc.  Furthermore, ArConfig can't change program variables
 * via pointers in most languages, so you need to only use the constructors that take
 * an initial value for an internally held variable instead of pointers anyway.
 */

class ArConfigArg_Bool : public ArConfigArg
{
public:
  ArConfigArg_Bool(const char *name, bool b, const char *desc = "") :
    ArConfigArg(name, b, desc)
  { }
};

class ArConfigArg_Int : public ArConfigArg
{
public:
  ArConfigArg_Int(const char *name, int i, const char *desc = "", int min = INT_MIN, int max = INT_MAX) :
    ArConfigArg(name, i, desc, min, max)
  { }
};

class ArConfigArg_Double : public ArConfigArg
{
public:
  ArConfigArg_Double(const char *name, double d, const char *desc = "", double min = -HUGE_VAL, double max = HUGE_VAL) :
    ArConfigArg(name, d, desc, min, max)
  { }
};

class ArConfigArg_String : public ArConfigArg
{
public:
  ArConfigArg_String(const char *name, char *str, const char *desc) :
    ArConfigArg(name, str, desc, 0)
  {
  }
};

/** @endcond INCLUDE_SWIG_ONLY_CLASSES */

#endif // wrapperExtraClasses.h


text:
package com.vmware.vim25;

/**
* @author Steve Jin (http://www.doublecloud.org)
* @version 5.1
*/

@SuppressWarnings("all")
public class FloatOption extends OptionType {
  public float min;
  public float max;
  public float defaultValue;

  public float getMin() {
    return this.min;
  }

  public float getMax() {
    return this.max;
  }

  public float getDefaultValue() {
    return this.defaultValue;
  }

  public void setMin(float min) {
    this.min=min;
  }

  public void setMax(float max) {
    this.max=max;
  }

  public void setDefaultValue(float defaultValue) {
    this.defaultValue=defaultValue;
  }
}


text:
package com.pa.util;

/**
 * @author : wallace leung
 * @email  : wallaceleung@163.com
 * @date   : 2014/12/20 0020
 * @desc   :
 */
public class APPConstants {
    public static String LOADING = "Loading";
}


text:
define('test',['jquery'], function($) {
	return $;
});


text:
<?php

namespace PHPSemVerChecker\Operation;

use PHPSemVerChecker\Configuration\LevelMapping;

abstract class Operation {
	/**
	 * @var string
	 */
	protected $code;
	/**
	 * @var string
	 */
	protected $reason;
	/**
	 * @var string
	 */
	protected $target;

	/**
	 * @return string
	 */
	public function getCode()
	{
		return $this->code;
	}

	/**
	 * @param string $code
	 * @return $this
	 */
	public function setCode($code)
	{
		$this->code = $code;

		return $this;
	}

	public function getLevel()
	{
		return LevelMapping::getLevelForCode($this->getCode());
	}

	/**
	 * @return string
	 */
	public function getReason()
	{
		return $this->reason;
	}

	/**
	 * @param string $reason
	 * @return $this
	 */
	public function setReason($reason)
	{
		$this->reason = $reason;

		return $this;
	}

	/**
	 * @return string
	 */
	public abstract function getLocation();

	public abstract function getLine();

	/**
	 * @return string
	 */
	public function getTarget()
	{
		return $this->target;
	}

	/**
	 * @param string $target
	 * @return $this
	 */
	public function setTarget($target)
	{
		$this->target = $target;

		return $this;
	}
}


text:
cask :v1 => 'cloudfoundry-cli' do
  version '6.8.0'
  sha256 'ae21984e6658a094940cbc898235e2285da3f53437aa07c6607aa9c288197162'

  # amazonaws.com is the official download host per the vendor homepage
  url "http://go-cli.s3-website-us-east-1.amazonaws.com/releases/v#{version}/installer-osx-amd64.pkg"
  name 'Cloud Foundry CLI'
  homepage 'https://github.com/cloudfoundry/cli'
  license :oss

  pkg 'installer-osx-amd64.pkg'

  uninstall :pkgutil => 'com.pivotal.cloudfoundry.pkg'
  caveats do
    files_in_usr_local
  end
end


text:
const test = require('tape');
const path = require('path');
const stream = require('stream');
const proxyquire = require('proxyquire');

//const CPRemoteGithubRepo = require('../../app/article-importer/cp-remote-github-repo');

const confStub = {
  app: {
    paths: {
      // localRepoDir: path.join(__dirname, '../_sample-articles'),
      remoteRepoOwner: 'wsierakowski',
      remoteRepoName: 'demo-content'
    }
  }
}

const fsStub = {};

const CPRemoteGithubRepo = proxyquire('../../app/article-importer/cp-remote-github-repo', {
  'fs-extra': fsStub
});

// TODO: test also with err scneario and dir
if (1)
test('contentProvider.getPathsToFiles should return paths to conf files', function(t) {
  const expectedPaths = require('./cp-local-git-repo.fixture.js').confFiles;
  const cp = new CPRemoteGithubRepo(
    '',
    confStub.app.paths.remoteRepoOwner,
    confStub.app.paths.remoteRepoName
  );

  cp.getPathsToFiles(null, ['conf', 'config'], ['json', 'yaml'], (err, fpaths) => {
    // todo - error?

    //fpaths = fpaths.map(fpath => path.relative(confStub.app.paths.localRepoDir, fpath));
    // console.log('==---- results ---==');
    // console.log('err', err);
    // console.log('fpaths', fpaths);
    // console.log('');
    // console.log('expectedPaths', expectedPaths);

    t.deepEqual(fpaths, expectedPaths);
    //t.equal(true, true);
    t.end();
  });
});

if(1)
test('contentProvider.getPathsToFiles should return paths to all files', function(t) {
  const expectedPaths = require('./cp-local-git-repo.fixture.js').allFiles;
  const cp = new CPRemoteGithubRepo(
    '',
    confStub.app.paths.remoteRepoOwner,
    confStub.app.paths.remoteRepoName
  );

  cp.getPathsToFiles(null, null, null, (err, fpaths) => {
    //fpaths = fpaths.map(fpath => path.relative(confStub.app.paths.localRepoDir, fpath));
    t.deepEqual(fpaths, expectedPaths);
    t.end();
  });
});

// TODO: create a test to fetch content inside a directory
if(0)
test('contentProvider.getPathsToFiles should return paths to all files', function(t) {
  const expectedPaths = require('./cp-local-git-repo.fixture.js').allFiles;
  const cp = new CPRemoteGithubRepo(
    '',
    confStub.app.paths.remoteRepoOwner,
    confStub.app.paths.remoteRepoName
  );

  cp.getPathsToFiles(null, null, null, (err, fpaths) => {
    //fpaths = fpaths.map(fpath => path.relative(confStub.app.paths.localRepoDir, fpath));
    t.deepEqual(fpaths, expectedPaths);
    t.end();
  });
});

if(1)
test('contentProvider.readFile should return content of a file', function(t) {
  const fileToRead = require('./cp-local-git-repo.fixture.js').sampleConfigFile;
  const cp = new CPRemoteGithubRepo(
    '',
    confStub.app.paths.remoteRepoOwner,
    confStub.app.paths.remoteRepoName
  );

  cp.readFile(fileToRead.filePath, (err, data) => {
    const expectedContent = JSON.parse(fileToRead.fileContent);
    const actualContent = JSON.parse(data);

    t.deepEqual(expectedContent, actualContent);
    t.end();
  });
});

if(1)
test('contentProvider.copyFile should copy content of a file to a destination', function(t) {
  const fileToRead = require('./cp-local-git-repo.fixture.js').sampleConfigFile;
  const cp = new CPRemoteGithubRepo(
    '',
    confStub.app.paths.remoteRepoOwner,
    confStub.app.paths.remoteRepoName
  );
  const destPath = './somepath/filename.json';

  fsStub.outputFile = (path, content, cb) => {
    t.equal(path, destPath);
    t.deepEqual(JSON.parse(content), JSON.parse(fileToRead.fileContent));
    cb(null);
  };

  cp.copyFile(fileToRead.filePath, destPath, (err) => {
    t.ifError(err, 'Copy file error');
    t.end();
  });
});


text:
internal class StartRepairData : BasicResponse
{
    public RepairDockInfo[] repairDockVo;
    public UserInfo userVo;
}


text:
<?php

namespace ModuleGenerator\CLI\Console\Generate\Backend\Action;

use ModuleGenerator\CLI\Console\GenerateCommand;
use ModuleGenerator\Module\Backend\Actions\BackendActionDataTransferObject;
use ModuleGenerator\Module\Backend\Actions\BackendActionType;
use ModuleGenerator\Module\Backend\Actions\Add\Add;
use ModuleGenerator\Module\Backend\Layout\Templates\Add\Add as AddTemplate;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class AddAction extends GenerateCommand
{
    protected function configure()
    {
        parent::configure();

        $this->setName('generate:backend:action:add')
            ->setDescription('Generate the add action for an entity');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        parent::execute($input, $output);

        /** @var BackendActionDataTransferObject $crudActionsDataTransferObject */
        $crudActionsDataTransferObject = $this->getFormData(BackendActionType::class);

        $this->generateAction($crudActionsDataTransferObject);
    }

    public function generateAction(BackendActionDataTransferObject $crudActionsDataTransferObject): void
    {
        $this->generateService->generateClass(
            Add::fromDataTransferObject($crudActionsDataTransferObject),
            $this->getTargetPhpVersion()
        );
        $this->generateService->generateFile(
            AddTemplate::fromDataTransferObject($crudActionsDataTransferObject),
            $this->getTargetPhpVersion()
        );
    }
}


text:
"use strict";

var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };

var _prototypeProperties = function (child, staticProps, instanceProps) { if (staticProps) Object.defineProperties(child, staticProps); if (instanceProps) Object.defineProperties(child.prototype, instanceProps); };

var _inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; };

var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } };

var Declaration = _interopRequire(require("./declaration"));

var Container = _interopRequire(require("./container"));

var list = _interopRequire(require("./list"));

// CSS rule like "a { }"

var Rule = (function (Container) {
    function Rule(defaults) {
        _classCallCheck(this, Rule);

        this.type = "rule";
        this.nodes = [];
        Container.call(this, defaults);
    }

    _inherits(Rule, Container);

    // Stringify rule

    Rule.prototype.stringify = function stringify(builder) {
        this.stringifyBlock(builder, this.stringifyRaw("selector"));
    };

    _prototypeProperties(Rule, null, {
        selectors: {

            // Shortcut to get selectors as array

            get: function () {
                return list.comma(this.selector);
            },
            set: function (values) {
                this.selector = values.join(", ");
            },
            configurable: true
        }
    });

    return Rule;
})(Container);

module.exports = Rule;


text:
package com.example.dateasy.model;

import java.io.Serializable;
import java.util.ArrayList;

import android.graphics.Bitmap;

/**
 * 用户类
 *
 * @author Xu
 *
 */
public class User implements Serializable {

	/**
	 * 用户昵称
	 */
	private String nick_name;

	/**
	 * 用户密码
	 */
	private String password;

	/**
	 * 用户简介
	 */
	private String description;

	/**
	 * 用户性别
	 */
	private String sex;

	/**
	 * 用户真实姓名
	 */
	private String true_name;

	/**
	 * 用户手机
	 */
	private String telephone;

	/**
	 * 用户邮箱
	 */
	private String email;

	/**
	 * 用户发起的活动
	 */
	private ArrayList<Event> mReleaseEvents;

	/**
	 * 用户报名的活动
	 */
	private ArrayList<Event> mSignupEvents;

	/**
	 * 用户头像
	 */
	private String mHead;

	public User() {

	}

	public String getNick_name() {
		return nick_name;
	}

	public void setNick_name(String nick_name) {
		this.nick_name = nick_name;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	public String getTrue_name() {
		return true_name;
	}

	public void setTrue_name(String true_name) {
		this.true_name = true_name;
	}

	public String getTelephone() {
		return telephone;
	}

	public void setTelephone(String telephone) {
		this.telephone = telephone;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public ArrayList<Event> getmReleaseEvents() {
		return mReleaseEvents;
	}

	public void setmReleaseEvents(ArrayList<Event> mReleaseEvents) {
		this.mReleaseEvents = mReleaseEvents;
	}

	public ArrayList<Event> getmSignupEvents() {
		return mSignupEvents;
	}

	public void setmSignupEvents(ArrayList<Event> mSignupEvents) {
		this.mSignupEvents = mSignupEvents;
	}

	public String getmHead() {
		return mHead;
	}

	public void setmHead(String mHead) {
		this.mHead = mHead;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

}


text:
using Flame.Compiler;
using Flame.Compiler.Expressions;
using Flame.Compiler.Statements;
using Flame.Compiler.Variables;
using Flame.Compiler.Visitors;

namespace Flame.LLVM.Passes
{
    /// <summary>
    /// A pass that registers finalizers.
    /// </summary>
    public sealed class FinalizerRegistrationVisitor : NodeVisitorBase
    {
        /// <summary>
        /// Creates a finalizer registration visitor from a garbage collector description.
        /// </summary>
        /// <param name="GarbageCollector">A GC description.</param>
        public FinalizerRegistrationVisitor(GCDescription GarbageCollector)
        {
            this.GarbageCollector = GarbageCollector;
        }

        /// <summary>
        /// Gets the garbage collector description used by this visitor.
        /// </summary>
        /// <returns>The garbage collector description.</returns>
        public GCDescription GarbageCollector { get; private set; }

        /// <inheritdoc/>
        public override bool Matches(IStatement Value)
        {
            return false;
        }

        /// <inheritdoc/>
        public override bool Matches(IExpression Value)
        {
            return Value is NewObjectExpression;
        }

        /// <inheritdoc/>
        protected override IExpression Transform(IExpression Expression)
        {
            if (Expression is NewObjectExpression)
            {
                var expr = (NewObjectExpression)Expression;
                var visitedExpr = expr.Accept(this);
                var constructedType = expr.Type;
                if (!constructedType.GetIsReferenceType())
                {
                    return visitedExpr;
                }

                // TODO: a type's finalizer is looked up every time an object is constructed.
                // That's a pretty expensive operation and we could speed it up greatly
                // by introducing a cache.
                var rootAncestor = GetRootAncestor(constructedType);
                var rootFinalizer = GetFinalizer(rootAncestor);

                if (rootFinalizer == null)
                {
                    return visitedExpr;
                }

                var finalizer = rootFinalizer.GetImplementation(constructedType) ?? rootFinalizer;

                if (finalizer.HasAttribute(
                    PrimitiveAttributes.Instance.NopAttribute.AttributeType))
                {
                    return visitedExpr;
                }

                var tmp = new SSAVariable(constructedType);

                return new InitializedExpression(
                    new BlockStatement(
                        new IStatement[]
                        {
                            tmp.CreateSetStatement(visitedExpr),
                            GarbageCollector.RegisterFinalizer(
                                new ReinterpretCastExpression(
                                    tmp.CreateGetExpression(),
                                    PrimitiveTypes.Void.MakePointerType(PointerKind.TransientPointer)),
                                finalizer)
                        }),
                    tmp.CreateGetExpression());
            }
            else
            {
                return Expression.Accept(this);
            }
        }

        /// <inheritdoc/>
        protected override IStatement Transform(IStatement Statement)
        {
            return Statement.Accept(this);
        }

        private static IMethod GetFinalizer(IType Type)
        {
            return Type.GetMethod(
                new SimpleName("Finalize"),
                false,
                PrimitiveTypes.Void,
                new IType[] { });
        }

        private static IType GetRootAncestor(IType Type)
        {
            var parent = Type.GetParent();
            if (parent == null)
                return Type;
            else
                return GetRootAncestor(parent);
        }
    }

    /// <summary>
    /// A pass that registers finalizers.
    /// </summary>
    public sealed class FinalizerRegistrationPass : IPass<IStatement, IStatement>
    {
        /// <summary>
        /// Creates a finalizer registration pass from a garbage collector description.
        /// </summary>
        /// <param name="GarbageCollector">A GC description.</param>
        public FinalizerRegistrationPass(GCDescription GarbageCollector)
        {
            this.GarbageCollector = GarbageCollector;
        }

        /// <summary>
        /// Gets the garbage collector description used by this pass.
        /// </summary>
        /// <returns>The garbage collector description.</returns>
        public GCDescription GarbageCollector { get; private set; }

        /// <summary>
        /// The name for the finalizer registration pass.
        /// </summary>
        public const string FinalizerRegistrationPassName = "register-finalizers";

        /// <inheritdoc/>
        public IStatement Apply(IStatement Value)
        {
            return new FinalizerRegistrationVisitor(GarbageCollector).Visit(Value);
        }
    }
}


text:
.class public Lcom/fasterxml/jackson/databind/ser/std/StdKeySerializer;
.super Lcom/fasterxml/jackson/databind/ser/std/StdSerializer;
.source ""

# annotations
.annotation system Ldalvik/annotation/Signature;
    value = {
        "Lcom/fasterxml/jackson/databind/ser/std/StdSerializer<Ljava/lang/Object;>;"
    }
.end annotation

# static fields
.field static final instace:Lcom/fasterxml/jackson/databind/ser/std/StdKeySerializer;

# direct methods
.method static constructor <clinit>()V
    .locals 1

    .line 23
    new-instance v0, Lcom/fasterxml/jackson/databind/ser/std/StdKeySerializer;

    invoke-direct {v0}, Lcom/fasterxml/jackson/databind/ser/std/StdKeySerializer;-><init>()V

    sput-object v0, Lcom/fasterxml/jackson/databind/ser/std/StdKeySerializer;->instace:Lcom/fasterxml/jackson/databind/ser/std/StdKeySerializer;

    return-void
.end method

.method public constructor <init>()V
    .locals 1

    .line 25
    const-class v0, Ljava/lang/Object;

    invoke-direct {p0, v0}, Lcom/fasterxml/jackson/databind/ser/std/StdSerializer;-><init>(Ljava/lang/Class;)V

    return-void
.end method

# virtual methods
.method public acceptJsonFormatVisitor(Lcom/fasterxml/jackson/databind/jsonFormatVisitors/JsonFormatVisitorWrapper;Lcom/fasterxml/jackson/databind/JavaType;)V
    .locals 1

    .line 49
    invoke-interface {p1, p2}, Lcom/fasterxml/jackson/databind/jsonFormatVisitors/JsonFormatVisitorWrapper;->expectStringFormat(Lcom/fasterxml/jackson/databind/JavaType;)Lcom/fasterxml/jackson/databind/jsonFormatVisitors/JsonStringFormatVisitor;

    .line 50
    return-void
.end method

.method public getSchema(Lcom/fasterxml/jackson/databind/SerializerProvider;Ljava/lang/reflect/Type;)Lcom/fasterxml/jackson/databind/JsonNode;
    .locals 1

    .line 42
    const-string v0, "string"

    invoke-virtual {p0, v0}, Lcom/fasterxml/jackson/databind/ser/std/StdKeySerializer;->createSchemaNode(Ljava/lang/String;)Lcom/fasterxml/jackson/databind/node/ObjectNode;

    move-result-object v0

    return-object v0
.end method

.method public serialize(Ljava/lang/Object;Lcom/fasterxml/jackson/core/JsonGenerator;Lcom/fasterxml/jackson/databind/SerializerProvider;)V
    .locals 1

    .line 31
    instance-of v0, p1, Ljava/util/Date;

    if-eqz v0, :cond_0

    .line 32
    move-object v0, p1

    check-cast v0, Ljava/util/Date;

    invoke-virtual {p3, v0, p2}, Lcom/fasterxml/jackson/databind/SerializerProvider;->defaultSerializeDateKey(Ljava/util/Date;Lcom/fasterxml/jackson/core/JsonGenerator;)V

    return-void

    .line 34
    :cond_0
    invoke-virtual {p1}, Ljava/lang/Object;->toString()Ljava/lang/String;

    move-result-object v0

    invoke-virtual {p2, v0}, Lcom/fasterxml/jackson/core/JsonGenerator;->writeFieldName(Ljava/lang/String;)V

    .line 36
    return-void
.end method


text:
package ve.com.abicelis.remindy.app.dialogs;

import android.Manifest;
import android.content.pm.PackageManager;
import android.content.res.ColorStateList;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.DialogFragment;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.transitionseverywhere.TransitionManager;

import java.io.File;
import java.io.IOException;
import java.util.Locale;
import java.util.UUID;

import ve.com.abicelis.remindy.R;
import ve.com.abicelis.remindy.app.views.VisualizerView;
import ve.com.abicelis.remindy.model.attachment.AudioAttachment;
import ve.com.abicelis.remindy.util.FileUtil;
import ve.com.abicelis.remindy.util.PermissionUtil;
import ve.com.abicelis.remindy.util.SnackbarUtil;

/**
 * Created by abice on 16/3/2017.
 */

public class RecordAudioDialogFragment extends DialogFragment implements View.OnClickListener {

    //CONST
    private static final String TAG = RecordAudioDialogFragment.class.getSimpleName();
    private static final int REQUEST_RECORD_AUDIO_PERMISSION = 200;
    private static final String AUDIO_FILE_EXTENSION = ".3gp";
    private static final int REPEAT_INTERVAL_VIZ = 50;
    private static final int REPEAT_INTERVAL_TIME = 1000;
    private static final int STATE_IDLE = 0;
    private static final int STATE_RECORDING = 1;
    private static final int STATE_PLAYING = 2;
    private static String [] permissions = {Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE};

    //DATA
    private int mState = STATE_IDLE;
    private AudioAttachment mAudioAttachment;
    private String mAudioFilePath = null;
    private MediaRecorder mRecorder = null;
    private MediaPlayer mPlayer = null;
    private Handler mVizHandler = null;                // Handler for updating the visualizer
    private Handler mTextHandler = null;                // Handler for updating the elapsed text
    private long startTime = 0L;
    private RecordAudioDialogFinishListener mListener;

    //UI
    private RelativeLayout mContainer;
    private FloatingActionButton mFab;
    private TextView mTapToStartRecording;
    private TextView mRecordTime;
    private VisualizerView mVisualizer;
    private ImageView mRecIcon;
    private ImageView mPlayIcon;

    public RecordAudioDialogFragment() {
        // Empty constructor is required for DialogFragment
        // Make sure not to add arguments to the constructor
        // Use `newInstance` instead as shown below
    }

    public static RecordAudioDialogFragment newInstance(AudioAttachment audioAttachment) {
        RecordAudioDialogFragment frag = new RecordAudioDialogFragment();
        Bundle args = new Bundle();
        args.putSerializable("audioAttachment", audioAttachment);
        frag.setArguments(args);
        return frag;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
    }

    @Override
    public void onResume() {
        super.onResume();

        int height = getResources().getDimensionPixelSize(R.dimen.dialog_record_audio_height);
        int width = getResources().getDimensionPixelSize(R.dimen.dialog_record_audio_width);

        getDialog().getWindow().setLayout(width, height);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        setCancelable(false);

        mAudioAttachment = (AudioAttachment) getArguments().getSerializable("audioAttachment");

        View dialogView =  inflater.inflate(R.layout.dialog_record_audio, container);

        File audioAttachmentDir = FileUtil.getAudioAttachmentDir(getActivity());
        try {
            FileUtil.createDirIfNotExists(audioAttachmentDir);
        }catch (IOException| SecurityException e) {
            Toast.makeText(getActivity(), "Problem!", Toast.LENGTH_SHORT).show();
        }

        if (mAudioAttachment.getAudioFilename() == null || mAudioAttachment.getAudioFilename().isEmpty()) {
            mAudioAttachment.setAudioFilename(UUID.randomUUID().toString() + AUDIO_FILE_EXTENSION);
        }
        mAudioFilePath = new File(audioAttachmentDir, "/" + mAudioAttachment.getAudioFilename()).getAbsolutePath();

        mContainer = (RelativeLayout) dialogView.findViewById(R.id.dialog_record_audio_container);
        mFab = (FloatingActionButton) dialogView.findViewById(R.id.dialog_record_audio_fab);
        mFab.setOnClickListener(this);
        mTapToStartRecording = (TextView) dialogView.findViewById(R.id.dialog_record_audio_tap_to_start_recording);

        mRecordTime = (TextView) dialogView.findViewById(R.id.dialog_record_audio_time);
        mVisualizer = (VisualizerView) dialogView.findViewById(R.id.dialog_record_audio_visualizer);
        mVisualizer.setLineColor(ContextCompat.getColor(getContext(), R.color.primary));

        mRecIcon = (ImageView) dialogView.findViewById(R.id.dialog_record_audio_rec_icon);
        mPlayIcon = (ImageView) dialogView.findViewById(R.id.dialog_record_audio_play_icon);

        // create the Handlers
        mVizHandler = new Handler();
        mTextHandler = new Handler();

        return dialogView;
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch(id) {
            case R.id.dialog_record_audio_fab:
                switch (mState) {
                    case STATE_IDLE:
                        handleStartRecording();
                        break;

                    case STATE_RECORDING:
                        mState = STATE_PLAYING;
                        stopRecording();
                        startPlaying();
                        break;

                    case STATE_PLAYING:
                        stopPlaying();
                }
                break;
        }
    }

    private void handleStartRecording() {

        // Check for the recording permissions. If not granted yet, request permission.
        String[] nonGrantedPermissions = PermissionUtil.checkIfPermissionsAreGranted(getActivity(), permissions);

        if(nonGrantedPermissions == null) {
            mState = STATE_RECORDING;
            startRecording();
        } else
            requestPermissions(permissions, REQUEST_RECORD_AUDIO_PERMISSION);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode){
            case REQUEST_RECORD_AUDIO_PERMISSION:
                for (int result : grantResults) {
                    if(result != PackageManager.PERMISSION_GRANTED) {
                        SnackbarUtil.showSnackbar(mContainer, SnackbarUtil.SnackbarType.ERROR, R.string.dialog_record_audio_snackbar_error_no_permissions, SnackbarUtil.SnackbarDuration.LONG, null);
                        return;
                    }
                }

                //Permissions granted
                mState = STATE_RECORDING;
                startRecording();
                break;
        }
    }

    private void startRecording() {

        TransitionManager.beginDelayedTransition(mContainer);

        mFab.setImageDrawable(ContextCompat.getDrawable(getContext(), R.drawable.icon_stop_fab_mini));
        mFab.setSize(FloatingActionButton.SIZE_MINI);

        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) mFab.getLayoutParams();
        lp.addRule(RelativeLayout.CENTER_HORIZONTAL, 0);    //Same as lp.removeRule(...) only this call is supported from API 17 :(
        lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, 1);
        lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, 1);
        mFab.setLayoutParams(lp);

        mTapToStartRecording.setVisibility(View.GONE);
        mRecordTime.setVisibility(View.VISIBLE);
        mVisualizer.setVisibility(View.VISIBLE);
        mRecIcon.setVisibility(View.VISIBLE);

        mRecorder = new MediaRecorder();
        mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        mRecorder.setOutputFile(mAudioFilePath);
        mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

        try {
            mRecorder.prepare();
        } catch (IOException e) {
            Log.e(TAG, "prepare() failed");
        }

        mRecorder.start();
        mVizHandler.post(updateVisualizer);
        startTime = SystemClock.uptimeMillis();
        mTextHandler.postDelayed(updateTime, REPEAT_INTERVAL_TIME);
    }

    private void stopRecording() {
        mRecorder.stop();
        mRecorder.release();
        mRecorder = null;
    }

    private void startPlaying() {
        //Reset time
        startTime = SystemClock.uptimeMillis();

        TransitionManager.beginDelayedTransition(mContainer);
        mFab.setImageDrawable(ContextCompat.getDrawable(getContext(), R.drawable.icon_check_fab_mini));
        mFab.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(getContext(), R.color.fab_accept_green)));
        mRecIcon.setVisibility(View.INVISIBLE);
        mPlayIcon.setVisibility(View.VISIBLE);

        mPlayer = new MediaPlayer();
        try {

            mPlayer.setDataSource(mAudioFilePath);
            mPlayer.prepare();
            mPlayer.start();
            mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    handleDismissDialog();

                }
            });
        } catch (IOException e) {
            Log.e(TAG, "prepare() failed");
        }
    }

    private void handleDismissDialog() {
        if(mListener != null)
            mListener.onFinishedRecording(mAudioAttachment);
        dismiss();
    }

    private void stopPlaying() {
        if(mPlayer != null) {
            mPlayer.release();
            mPlayer = null;
        }
        handleDismissDialog();
    }

    // updates the visualizer every 50 milliseconds
    Runnable updateVisualizer = new Runnable() {
        @Override
        public void run() {
            if (mState == STATE_RECORDING) // if we are already recording
            {
                // get the current amplitude
                int x = mRecorder.getMaxAmplitude();
                mVisualizer.addAmplitude(x); // update the VisualizeView
                mVisualizer.invalidate(); // refresh the VisualizerView

                // update in 40 milliseconds
                mVizHandler.postDelayed(this, REPEAT_INTERVAL_VIZ);
            }
        }
    };

    // updates the visualizer every 50 milliseconds
    Runnable updateTime = new Runnable() {
        @Override
        public void run() {
            if (mState == STATE_RECORDING || mState == STATE_PLAYING) // if we are recording or playing
            {
                long elapsedMillis = SystemClock.uptimeMillis() - startTime;

                int secs = (int) (elapsedMillis / 1000);
                int mins = secs / 60;
                secs = secs % 60;
                if (mRecordTime != null)
                    mRecordTime.setText("00:" + String.format(Locale.getDefault(), "%02d", mins) + ":" + String.format(Locale.getDefault(), "%02d", secs));
                mTextHandler.postDelayed(this, REPEAT_INTERVAL_TIME);
            }
        }
    };

    @Override
    public void onStop() {
        super.onStop();
        if (mRecorder != null) {
            mRecorder.release();
            mRecorder = null;
        }

        if (mPlayer != null) {
            mPlayer.release();
            mPlayer = null;
        }
    }

    public void setListener(RecordAudioDialogFinishListener listener) {
        mListener = listener;
    }

    public interface RecordAudioDialogFinishListener {
        void onFinishedRecording(AudioAttachment audioAttachment);
    }
}