text:
{                                   \
  if (myproc==0) {                  \
    std::cout.width(30);            \
    std::cout << msg;               \
    std::cout.flush();              \
  }                                 \
  timer_type rtf_t0 = mytimer();    \
  fn;                               \
  time_inc = mytimer() - rtf_t0;    \
  time_total += time_inc;           \
  if (myproc==0) {                  \
    std::cout << time_inc << "s, total time: " << time_total << std::endl; \
  }                                 \
}

//This program assembles finite-element matrices into a global matrix and
//vector, then solves the linear-system using Conjugate Gradients.
//Each finite-element is a hexahedron with 8 vertex-nodes.
//
//Notes:
//- In finite-element terms, the box dimensions are in elements, not nodes.
//  In other words, a 2x2x2 box describes 8 elements, each of which has 8 nodes,
//  so it is a 3x3x3 node domain (27 nodes).
//  The assembled linear system will have 1 equation for each finite element node.
//
//- The coordinate origin is at the corner of the global box where x=0,
//  y=0, z=0, and the box extends along the positive x-axis, positive y-axis,
//  and the *negative* z-axis.
//
//- Some aspects of matrix-structure generation and finite-element assembly
//  are convenient to do using global node identifiers.
//  A global identifier for each node is obtained from coordinates plus
//  global box dimensions. See the function 'get_id' in box_utils.hpp.
//
//- Each node corresponds to a row in the matrix. The RCB partitioning method
//  we use to split the global box among processors results in some
//  processors owning non-contiguous blocks of global node identifiers.
//  Since it is convenient for matrices and vectors to store contiguously-
//  numbered blocks of rows, we map global node identifiers to a separate
//  space of row numbers such that each processor's nodes correspond to a
//  contiguous block of row numbers.
//

namespace miniFE {

template<typename Scalar,
         typename LocalOrdinal,
         typename GlobalOrdinal,
         typename ComputeNodeType>
__attribute__((annotate("kernel")))
void driver(const int global_box[][2], int my_box[][2], ComputeNodeType& compute_node, Parameters& params, YAML_Doc& ydoc) {
  int global_nx = global_box[0][1];
  int global_ny = global_box[1][1];
  int global_nz = global_box[2][1];

  int numprocs = 1, myproc = 0;
#ifdef HAVE_MPI
  MPI_Comm_size(MPI_COMM_WORLD, &numprocs);
  MPI_Comm_rank(MPI_COMM_WORLD, &myproc);
#endif

  if (params.load_imbalance > 0) {
    add_imbalance<GlobalOrdinal>(global_box, my_box, params.load_imbalance, ydoc);
  }

  float largest_imbalance = 0, std_dev = 0;
  compute_imbalance<GlobalOrdinal>(global_box, my_box, largest_imbalance,
                                   std_dev, ydoc, true);

  //Create a representation of the mesh:
  //Note that 'stk_mesh_description' contains a fully populated stk::mesh
  //database, while 'simple_mesh_description' is a virtual or conceptual
  //mesh that doesn't actually store mesh data.

  if (myproc==0) {
    std::cout.width(30);
    std::cout << "creating/filling mesh...";
    std::cout.flush();
  }

  timer_type t_start = mytimer();
  timer_type t0 = mytimer();

#ifdef MINIFE_HAVE_STK
  stk::ParallelMachine comm = stk::parallel_machine_null();
#ifdef HAVE_MPI
  comm = MPI_COMM_WORLD;
#endif
  bool create_elem_mat_fields = params.use_elem_mat_fields==1;
  stk_mesh_description<Scalar,GlobalOrdinal> mesh(comm, create_elem_mat_fields);
  populate_mesh( mesh , global_box , my_box );
#else
  simple_mesh_description<GlobalOrdinal> mesh(global_box, my_box);
#endif

  timer_type mesh_fill = mytimer() - t0;
  timer_type t_total = mytimer() - t_start;

  if (myproc==0) {
    std::cout << mesh_fill << "s, total time: " << t_total << std::endl;
  }

  //next we will generate the matrix structure.

 //Declare matrix object:

  SparseMatrix<Scalar,LocalOrdinal,GlobalOrdinal,ComputeNodeType> A(compute_node);

  timer_type gen_structure;
  RUN_TIMED_FUNCTION("generating matrix structure...",
                     generate_matrix_structure(mesh, A),
                     gen_structure, t_total);

  GlobalOrdinal local_nrows = A.rows.size();
  GlobalOrdinal my_first_row = local_nrows > 0 ? A.rows[0] : -1;

  Vector<Scalar,LocalOrdinal,GlobalOrdinal,ComputeNodeType> b(my_first_row, local_nrows,compute_node);
  Vector<Scalar,LocalOrdinal,GlobalOrdinal,ComputeNodeType> x(my_first_row, local_nrows,compute_node);

  //Assemble finite-element sub-matrices and sub-vectors into the global
  //linear system:

  timer_type fe_assembly;
  RUN_TIMED_FUNCTION("assembling FE data...",
                     assemble_FE_data(mesh, A, b, params),
                     fe_assembly, t_total);

  if (myproc == 0) {
    ydoc.add("Matrix structure generation","");
    ydoc.get("Matrix structure generation")->add("Mat-struc-gen Time",gen_structure);
    ydoc.add("FE assembly","");
    ydoc.get("FE assembly")->add("FE assembly Time",fe_assembly);
  }

//  //For large systems it seems to be necessary to add a value to the diagonal
//  //in order to get the CG solve to converge. Should this be necessary?
//  //Does it indicate a problem with the dirichlet boundary-condition that is
//  //applied below?
//  Scalar value = 1.e-8*global_nx;
//  value *= global_ny*global_nz;
//  value += 0.5;
//
//#ifdef MINIFE_DEBUG
//  outstream() << "add to diag: " << value << std::endl;
//#endif
//
//  add_to_diagonal(value, A);

  //Now apply a dirichlet boundary-condition to the x=0 face of the global box.
  //(This is needed to make the matrix non-singular.)

#ifdef MINIFE_DEBUG
  write_matrix("A_prebc.mtx", A);
  write_vector("b_prebc.vec", b);
#endif

  timer_type dirbc_time;
  RUN_TIMED_FUNCTION("imposing Dirichlet BC...",
            impose_dirichlet_x0(1.0, A, b, global_nx+1, global_ny+1, global_nz+1, mesh),
                     dirbc_time, t_total);

#ifdef MINIFE_DEBUG
  write_matrix("A.mtx", A);
  write_vector("b.vec", b);
#endif

  //Transform global indices to local, set up communication information:

  timer_type make_local_time;
  RUN_TIMED_FUNCTION("making matrix indices local...",
                     make_local_matrix(A),
                     make_local_time, t_total);

  size_t global_nnz = compute_matrix_stats(A, myproc, numprocs, ydoc);

  //Prepare to perform conjugate gradient solve:

  LocalOrdinal max_iters = 50;
  LocalOrdinal num_iters = 0;
  typedef typename TypeTraits<Scalar>::magnitude_type magnitude;
  magnitude rnorm = 0;
  magnitude tol = std::numeric_limits<magnitude>::epsilon();

  timer_type cg_times[NUM_TIMERS];

  typedef Vector<Scalar,LocalOrdinal,GlobalOrdinal,ComputeNodeType> VectorType;
  typedef SparseMatrix<Scalar,LocalOrdinal,GlobalOrdinal,ComputeNodeType> MatrixType;

  t_total = mytimer() - t_start;

//  MatrixType A2(compute_node);
//  copy_matrix(A, A2);

  bool matvec_with_comm_overlap = params.mv_overlap_comm_comp==1;

#if MINIFE_KERNELS != 0
  if (myproc==0) {
    std::cout.width(30);
    std::cout << "Starting kernel timing loops ..." << std::endl;
  }

  max_iters = 500;
  x.coefs[0] = 0.9;
  if (matvec_with_comm_overlap) {
    time_kernels(A, b, x, matvec_overlap<MatrixType,VectorType>(), max_iters, rnorm, cg_times);
  }
  else {
    time_kernels(A, b, x, matvec_std<MatrixType,VectorType>(), max_iters, rnorm, cg_times);
  }
  num_iters = max_iters;
  std::string title("Kernel timings");
#else
  if (myproc==0) {
    std::cout << "Starting CG solver ... " << std::endl;
  }

  if (matvec_with_comm_overlap) {
    rearrange_matrix_local_external(A);
    cg_solve(A, b, x, matvec_overlap<MatrixType,VectorType>(), max_iters, tol,
           num_iters, rnorm, cg_times);
  }
  else {
    cg_solve(A, b, x, matvec_std<MatrixType,VectorType>(), max_iters, tol,
           num_iters, rnorm, cg_times);
  }

#ifdef MINIFE_DEBUG
  write_vector("x.vec", x);
#endif
  std::string title("CG solve");
#endif

  if (myproc == 0) {
    ydoc.get("Global Run Parameters")->add("ScalarType",TypeTraits<Scalar>::name());
    ydoc.get("Global Run Parameters")->add("GlobalOrdinalType",TypeTraits<GlobalOrdinal>::name());
    ydoc.get("Global Run Parameters")->add("LocalOrdinalType",TypeTraits<LocalOrdinal>::name());
    ydoc.add(title,"");
    ydoc.get(title)->add("Iterations",num_iters);
    ydoc.get(title)->add("Final Resid Norm",rnorm);
    std::cout << "Final Resid Norm: " << rnorm << std::endl;

    GlobalOrdinal global_nrows = global_nx;
    global_nrows *= global_ny*global_nz;

    //flops-per-mv, flops-per-dot, flops-per-waxpy:
    double mv_flops = global_nnz*2.0;
    double dot_flops = global_nrows*2.0;
    double waxpy_flops = global_nrows*3.0;

#if MINIFE_KERNELS == 0
//if MINIFE_KERNELS == 0 then we did a CG solve, and in that case
//there were num_iters+1 matvecs, num_iters*2 dots, and num_iters*3+2 waxpys.
    mv_flops *= (num_iters+1);
    dot_flops *= (2*num_iters);
    waxpy_flops *= (3*num_iters+2);
#else
//if MINIFE_KERNELS then we did one of each operation per iteration.
    mv_flops *= num_iters;
    dot_flops *= num_iters;
    waxpy_flops *= num_iters;
#endif

    double total_flops = mv_flops + dot_flops + waxpy_flops;

    double mv_mflops = -1;
    if (cg_times[MATVEC] > 1.e-4)
      mv_mflops = 1.e-6 * (mv_flops/cg_times[MATVEC]);

    double dot_mflops = -1;
    if (cg_times[DOT] > 1.e-4)
      dot_mflops = 1.e-6 * (dot_flops/cg_times[DOT]);

    double waxpy_mflops = -1;
    if (cg_times[WAXPY] > 1.e-4)
      waxpy_mflops = 1.e-6 *  (waxpy_flops/cg_times[WAXPY]);

    double total_mflops = -1;
    if (cg_times[TOTAL] > 1.e-4)
      total_mflops = 1.e-6 * (total_flops/cg_times[TOTAL]);

    ydoc.get(title)->add("WAXPY Time",cg_times[WAXPY]);
    ydoc.get(title)->add("WAXPY Flops",waxpy_flops);
    if (waxpy_mflops >= 0)
      ydoc.get(title)->add("WAXPY Mflops",waxpy_mflops);
    else
      ydoc.get(title)->add("WAXPY Mflops","inf");

    ydoc.get(title)->add("DOT Time",cg_times[DOT]);
    ydoc.get(title)->add("DOT Flops",dot_flops);
    if (dot_mflops >= 0)
      ydoc.get(title)->add("DOT Mflops",dot_mflops);
    else
      ydoc.get(title)->add("DOT Mflops","inf");

    ydoc.get(title)->add("MATVEC Time",cg_times[MATVEC]);
    ydoc.get(title)->add("MATVEC Flops",mv_flops);
    if (mv_mflops >= 0)
      ydoc.get(title)->add("MATVEC Mflops",mv_mflops);
    else
      ydoc.get(title)->add("MATVEC Mflops","inf");

#ifdef MINIFE_FUSED
    ydoc.get(title)->add("MATVECDOT Time",cg_times[MATVECDOT]);
    ydoc.get(title)->add("MATVECDOT Flops",mv_flops);
    if (mv_mflops >= 0)
      ydoc.get(title)->add("MATVECDOT Mflops",mv_mflops);
    else
      ydoc.get(title)->add("MATVECDOT Mflops","inf");
#endif

#if MINIFE_KERNELS == 0
    ydoc.get(title)->add("Total","");
    ydoc.get(title)->get("Total")->add("Total CG Time",cg_times[TOTAL]);
    ydoc.get(title)->get("Total")->add("Total CG Flops",total_flops);
    if (total_mflops >= 0)
      ydoc.get(title)->get("Total")->add("Total CG Mflops",total_mflops);
    else
      ydoc.get(title)->get("Total")->add("Total CG Mflops","inf");
    ydoc.get(title)->add("Time per iteration",cg_times[TOTAL]/num_iters);
#endif
  }
}

}//namespace miniFE

#endif


text:
{% extends "base.html" %}

{% block content %}
    {% include "siteuser/change_password.html" %}
{% endblock %}

redpajama_set_name: RedPajamaGithub


text:
package org.spongycastle.cert.ocsp;

import java.util.Date;

import org.spongycastle.asn1.ASN1Sequence;
import org.spongycastle.asn1.ocsp.ResponseData;
import org.spongycastle.asn1.ocsp.SingleResponse;
import org.spongycastle.asn1.x509.Extensions;

public class RespData
{
    private ResponseData    data;

    public RespData(
        ResponseData    data)
    {
        this.data = data;
    }

    public int getVersion()
    {
        return data.getVersion().getValue().intValue() + 1;
    }

    public RespID getResponderId()
    {
        return new RespID(data.getResponderID());
    }

    public Date getProducedAt()
    {
        return OCSPUtils.extractDate(data.getProducedAt());
    }

    public SingleResp[] getResponses()
    {
        ASN1Sequence    s = data.getResponses();
        SingleResp[]    rs = new SingleResp[s.size()];

        for (int i = 0; i != rs.length; i++)
        {
            rs[i] = new SingleResp(SingleResponse.getInstance(s.getObjectAt(i)));
        }

        return rs;
    }

    public Extensions getResponseExtensions()
    {
        return data.getResponseExtensions();
    }
}


text:
<?php

namespace Webiny\Component\Rest\Parser;

use Webiny\Component\StdLib\StdLibTrait;

/**
 * This class builds paths from strings based on different rules.
 *
 * @package         Webiny\Component\Rest\Parser
 */
class PathTransformations
{
    use StdLibTrait;

    /**
     * Transforms method name to a url path.
     *
     * @param string $methodName Method name.
     *
     * @return string
     */
    public static function methodNameToUrl($methodName)
    {
        $url = preg_replace('/([A-Z])/', ' $1', $methodName);
        $url = self::str($url)->trim()->replace(' ', '-')->caseLower()->val();

        return $url;
    }

    /**
     * Transforms the class name to url path.
     *
     * @param string $className Class name.
     * @param bool $normalize Should the name be normalized or not
     *
     * @return string
     */
    public static function classNameToUrl($className, $normalize)
    {
        $className = self::str($className)->explode('\\')->last()->val();
        if(!$normalize){
            return $className;
        }
        $url = preg_replace('/([A-Z])/', ' $1', $className);
        $url = self::str($url)->trim()->replace(' ', '-')->caseLower()->val();

        return $url;
    }
}


text:
int main(int argc, const char *argv[]) {

  clang::tooling::CommonOptionsParser OptParser(argc, argv,
                                                llvm::cl::GeneralCategory);

  ohmu::lsa::DefaultCallGraphBuilder Builder;
  clang::ast_matchers::MatchFinder Finder;
  ohmu::lsa::CallGraphBuilderTool BuilderTool;
  BuilderTool.RegisterMatchers(Builder, &Finder);

  clang::tooling::ClangTool Tool(OptParser.getCompilations(),
                                 OptParser.getSourcePathList());

  int res = Tool.run(clang::tooling::newFrontendActionFactory(&Finder).get());
  if (res != 0)
    return res;

  std::cout << "Graph created.\n";

  Builder.Print(std::cout);

  return 0;
}


text:
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="40dp"
    android:height="40dp"
    android:viewportWidth="40"
    android:viewportHeight="40"
    android:tint="?attr/colorControlNormal">
  <path
      android:fillColor="@android:color/white"
      android:pathData="M8.292,35.083V4.833H31.75V35.083L20,30.083Z"/>
</vector>


text:
<!DOCTYPE HTML>

<meta name="viewport" content="initial-scale=1">
<title>A div with its reflection below which results in multiple render passes</title>


text:
<?php echo $pagetitle;?>

				<?php echo $bredcrumbs;?>

<?php
	    	$attributes = array('class' => 'horizontal-form', 'id' => 'myform');
			echo form_open_multipart('products/add_stock/'.$product_details[0]['pid'],$attributes);

			$on_date = set_value('on_date');
			$data_on_date = array(
						  		 'name'         => 'on_date',
								  'id'          => 'on_date',
								  'value'       => $on_date,
								  'class'		=> 'form-control',
								  'required' 	=> 'required',
								  'readonly' 	=> 'readonly',
								  'maxlength' => '12',
								  'placeholder' => 'Date'
								 );

			$arr_submit = array(
								'name' => 'submit',
								'value' => $pagetitle,
								'class' => 'btn green'
			);

	   ?>

 Add Stock Of <?php echo $product_details[0]['product_name']; ?>

            <?php if(validation_errors()){?>

				<button class="close" data-close="alert"></button>
				You have some form errors. Please check below.

		<?php } ?>
		<?php if(isset($_SESSION['suc_msg'])){ ?>
		 <div class="alert alert-<?php echo $_SESSION['msg-type']; ?>">
		  <?php echo $_SESSION['suc_msg'];
				 unset($_SESSION['suc_msg']); unset($_SESSION['msg-type']);
		  ?>

		<?php } ?>

                  Date Of Inward *

					  <?php echo form_input($data_on_date); ?>

					  <button class="btn default" type="button"></button>

                   <?php echo form_error('on_date'); ?>

                  Supplier Name *
                  <?php
				  $su_id = set_value('su_id');
				  echo form_dropdown('su_id',$suppliers_details,$su_id,'class="form-control select2me" tabindex="0" placeholder= "Select Supplier" required="required"');?>
                   <?php echo form_error('su_id'); ?>

                  Firm Name *
					<?php
				  $invoice_firm = set_value('invoice_firm');
				  $invoice_firm_array  = array('0'=>'Select Firm','1'=>'Horizon Agrotech', '2'=> 'Alligo Agrovet PVt. Ltd','7'=>'Animal Health','8'=>'Alligo Animal Health Bulk', '10'=>'Alligo Agro Bulk');
				  // echo form_dropdown('invoice_firm',$invoice_firm_array,$invoice_firm,'class="form-control" tabindex="0" required="required"');
				  echo form_dropdown('invoice_firm',$firmList,$invoice_firm,'class="form-control select2me" tabindex="0" placeholder= "Select Firm" required="required"');
				  ?>

                   <?php echo form_error('invoice_firm'); ?>

                  Product Name *
                  <?php

				  echo form_dropdown('pid',$products_data,$product_details[0]['pid'],'class="form-control select2me" tabindex="0" placeholder= "Select Product" required="required"');?>
                   <?php echo form_error('pid'); ?>

                  Invoice Number *
					<?php
						$invoice_no = set_value('invoice_no');
						$data_invoice_no = array(
							 'name'         => 'invoice_no',
							  'id'          => 'invoice_no',
							  'value'       => $invoice_no,
							  'class'		=> 'form-control',
							  'required' 	=> 'required',
							  'maxlength' => '20',
							  'placeholder' => 'Invoice Number'
							 );
				  		echo form_input($data_invoice_no);
				  ?>

                   <?php echo form_error('invoice_no'); ?>

                  Sample Number
                  <?php
						$sample_no = set_value('sample_no');
						$data_sample_no = array(
							 'name'         => 'sample_no',
							  'id'          => 'sample_no',
							  'value'       => $sample_no,
							  'class'		=> 'form-control',
							  'maxlength' => '15',
							  'placeholder' => 'Sample Number'
							 );
				  		echo form_input($data_sample_no);
				  ?>
                   <?php echo form_error('sample_no'); ?>

                  Packing *
					<?php
						$packing = set_value('packing');
						$data_packing = array(
							 'name'         => 'packing',

							  'id'          => 'packing',
							  'value'       => $packing,
							  'class'		=> 'form-control',
							  'required' 	=> 'required',
							  'maxlength' => '5',
							  'min' => '0',
							  'type'         => 'number',
							  'step' => 'any',
							  'placeholder' => 'Packing'
							 );
				  		echo form_input($data_packing);
				  ?>

                   <?php echo form_error('packing'); ?>

                  Bags / Drums Numbers *
                  <?php
						$bag_no = set_value('bag_no');
						$data_bag_no = array(
							 'name'         => 'bag_no',
							  'id'          => 'bag_no',
							  'value'       => $bag_no,
							  'class'		=> 'form-control',
							  'required' 	=> 'required',
							  'maxlength' => '5',
							  'min' => '0',
							  'step' => 'any',
							  'type'         => 'number',
							  'placeholder' => 'Total Bags/Drums'
							 );
				  		echo form_input($data_bag_no);
				  ?>
                   <?php echo form_error('bag_no'); ?>

                  Purchase Rate *
					<?php
						$rate = set_value('rate');
						$data_rate = array(
							 'name'         => 'rate',
							  'id'          => 'rate',
							  'value'       => $rate,
							  'class'		=> 'form-control',
							  'required' 	=> 'required',
							  'maxlength' => '10',
							  'min' => '0',
							  'step' => 'any',
							  'type'         => 'number',
							  'placeholder' => 'Purchase Rate'
							 );
				  		echo form_input($data_rate);
				  ?>

                   <?php echo form_error('rate'); ?>

                  Product Weight *
                  <?php
						$inw_qty  = set_value('inw_qty');
						$data_inw_qty  = array(
							 'name'         => 'inw_qty',
							  'id'          => 'inw_qty',
							  'value'       => $inw_qty ,
							  'class'		=> 'form-control',
							  'maxlength' => '15',
							  'required' 	=> 'required',
							  'min' => '0',
							  'step' => 'any',
							  'type'         => 'number',
							  'placeholder' => 'Product Weight'
							 );
				  		echo form_input($data_inw_qty);
				  ?>
                   <?php echo form_error('inw_qty'); ?>

                  Manufacturing Date
					<?php
						$manufacturing_date = set_value('manufacturing_date');
						$data_manufacturing_date = array(
											 'name'         => 'manufacturing_date',
											  'id'          => 'manufacturing_date',
											  'value'       => $manufacturing_date,
											  'class'		=> 'form-control',
											  'readonly' 	=> 'readonly',
											  'maxlength' => '12',
											  'placeholder' => 'Manufacturing Date'
											 );
				  ?>

					  <?php echo form_input($data_manufacturing_date); ?>

					  <button class="btn default" type="button"></button>

                   <?php echo form_error('manufacturing_date'); ?>

                  Expiry Date
					<?php
						$expiry_date = set_value('expiry_date');
						$data_expiry_date = array(
											 'name'         => 'expiry_date',
											  'id'          => 'expiry_date',
											  'value'       => $expiry_date,
											  'class'		=> 'form-control',
											  'readonly' 	=> 'readonly',
											  'maxlength' => '12',
											  'placeholder' => 'Expiry Date'
											 );
				  ?>

					  <?php echo form_input($data_expiry_date); ?>

					  <button class="btn default" type="button"></button>

                   <?php echo form_error('expiry_date'); ?>

				  	 GST Applied  *
				  <?php
						$tax_id = set_value('tax_id');
						echo form_dropdown('tax_id',$taxList,$tax_id,'class="form-control select2me" tabindex="0" placeholder= "Select Tax" required="required"');?>
				  <?php echo form_error('tax_id'); ?>

                  CGST Applied
				  <?php
						$excise = set_value('excise');
						echo form_dropdown('excise',$exciseTaxList,$excise,'class="form-control select2me" tabindex="0" placeholder= "Select Excise" required="required"');?>
				  <?php echo form_error('excise'); ?>

 <?php echo form_submit($arr_submit)?> <a href="<?php echo base_url();?>client">
            <button type="button" class="btn default">Cancel</button>

      <?php
			echo form_fieldset_close();
			echo form_close();
		  ?>


text:
/***

BLIH (c) Giovambattista Vieri 2015,2016

All rights reserved

https://github.com/gvieri/BLIH/

configuration.js

This file contains configuration data.

License: see github pages

*/

	$(document).ready(function() {
		var poi;
		var boxBounds;
		var initLat;
		var initLng;
		var initZoom;
		var marker;
		var myMarkers=[];
		var myControl;
		var splahDialog;
		var circle=null;

		initLat= localStorage.getItem("initLat");
		initLng= localStorage.getItem("initLng");
		initZoom=localStorage.getItem("initZoom");
		if((initLat==null) && (initLng==null)) {
			initLat=initLatConfVal;
			initLng=initLngConfVal;
		}

		L.Control.myControl = L.Control.extend({
                                options: {
                                        position: 'bottomleft',
                                        saveText: 'SA',
                                        saveTitle: 'save all marker',
                                        resetText: 'RST',
                                        resetTitle: 'reset, delete marker',
                                        centerOnGPSText: 'CG',
                                        centerOnGPSTitle: 'center on gps position',
                                        helpText: 'H',
                                        helpTitle: 'Help'
                                },
                                onAdd: function (map) {
                                        this._map= map;
                                        var controlName = 'gin-control-zoom',
                                        container = L.DomUtil.create('div', controlName + ' leaflet-bar'),
                                        options = this.options;

                                        this._centerOnGPSButton = this._createButton(options.centerOnGPSText, options.centerOnGPSTitle,
                                                controlName + '-home', container, this._centerOnGPS);
//                                        this._saveButton = this._createButton(options.saveText, options.saveTitle, controlName + '-home', container, this._save);
//                                        this._resetButton = this._createButton(options.resetText, options.resetTitle, controlName + '-home', container, this._resetAll);
                                        this._helpButton = this._createButton(options.helpText, options.helpTitle, controlName + '-home', container, this._help);

                                        this._updateDisabled();
                                        map.on('zoomend zoomlevelschange', this._updateDisabled, this);

                                        return container;
                                    },
				   onRemove: function (map) {
                                        map.off('zoomend zoomlevelschange', this._updateDisabled, this);
                                    },

                                _centerOnGPS: function (e) {
                                        this._map.locate({setView: true, maxZoom: 16, enableHighAccuracy: true});

                                    },

                                _save: function (e) {

                                    },
                                _resetAll: function (e) {

                                    },
                                _help: function (e) {

                                    },

                                _createButton: function (html, title, className, container, fn) {
                                        var link = L.DomUtil.create('a', className, container);
                                        link.innerHTML = html;
                                        link.href = '#';
                                        link.title = title;

                                        L.DomEvent.on(link, 'mousedown dblclick', L.DomEvent.stopPropagation)
                                            .on(link, 'click', L.DomEvent.stop)
                                            .on(link, 'click', fn, this)
                                            .on(link, 'click', this._refocusOnMap, this);

                                        return link;
                                    },

                                _updateDisabled: function () {
                                        var map = this._map,
                                        className = 'leaflet-disabled';

                                }
                        });

		if (initZoom==null) { initZoom = 13 }
		var mappa= L.map('mappetta').setView([initLat,initLng],13);
		L.tileLayer(tileLayerConfVal, {
			attribution: attributionCopyConfVal  +
                                                attributionLicenseConfVal +
                                                attributionThirdVal,
			maxZoom: maxZoomConfVal
		}).addTo(mappa);

		var poppup = L.popup();
		boxBounds=mappa.getBounds().toBBoxString()
		caricaMappa();
		function caricaMappa() {

                        var myurl="dump_table_box.php?boxBounds="+boxBounds;
			if (consoleLoggingFlag )  { console.log(myurl); }
                        $.getJSON(myurl, function(data) {
                              poi = data;
                              if (consoleLoggingFlag )  { console.log("==============================="); }
                                        var iiii=0;
                                data.forEach(function(entry) {
					if (consoleLoggingFlag )  { console.log(entry) ; }
                                        L.marker([entry.lat,entry.lng]).addTo(mappa).bindPopup("message: "+entry.message);
                                        iiii++;
                                });
                            });

		}
		function prendiPosECarica() {
			boxBounds=mappa.getBounds().toBBoxString();
			caricaMappa();
		}

		function onClickMarker(e) {
			var IdToRemove;
			mappa.removeLayer(e.target);
			if (consoleLoggingFlag )  { console.log("marker: called onClickMarker"); }
			IdToRemove = e.target.mymarker.Id;
			if (consoleLoggingFlag )  {
				console.log("markerid="+IdToRemove);
				console.log(JSON.stringify(myMarkers));
			}
			/// scan marker's array to find id...
			for(var i = myMarkers.length - 1; i >= 0; i--) {
			    if(myMarkers[i].Id == IdToRemove) {
			       if (consoleLoggingFlag )  { console.log("bingo"); }
			       myMarkers.splice(i, 1);
			    }
			}
			if (consoleLoggingFlag )  { console.log(JSON.stringify(myMarkers)); }
			localStorage.setItem("myMarkers", JSON.stringify(myMarkers));
			delete(e.target.mymarker);

		}
		function onMouseOverMarker(e) {
			if (consoleLoggingFlag )  {
				console.log("marker: called onMouseOverMarker");
				console.log("marker",this.messaggio);
				console.log("e = ",e) ;
			}
			e.target.openPopup();
		}
		function onMouseOutMarker(e) {
			if (consoleLoggingFlag )  {
				console.log("marker: called onMouseOutMarker");
				console.log("marker",this.messaggio);
			}
			e.target.closePopup();
		}

		function saveOnServer(e) {
//			var data= JSON.stringify(myMarkers);
			if (consoleLoggingFlag )  {
				console.log("marker: called saveOnServer");
				console.log("e = ",e) ;
			}
			$.ajax
			    ({
				type: "GET",
				dataType : 'json',
				async: false,
				url: './save_json.php',
				data: "data="+JSON.stringify(myMarkers),
				success: function () {alert("Thanks!"); },
				failure: function() {alert("Error!");}
			    });

		}

		function help (e) {
			var dia= bootbox.dialog({
			title: "BLIH - &copy 2015 Giovambattista Vieri",
			message: "

List of available commands

CG center map on GPS and, draw a circle related with the position on the map
"
			+"
H help

"
			+"
Please feel free to brose the map freely
",
			buttons: {
				main: {
				label: "Close",
				size: 'large',
				className: "btn-primary",
				callback: function() {
					}
				}
			}
			});
			return(dia);
		}

		function resetAll(e) {
			if(marker!=null) {
				mappa.removeLayer(marker);
			}
			if(circle!=null) {
				mappa.removeLayer(circle);
			}
			delete marker;
			margerMsg="deleted";
			markerPos="deleted";
			saveMap();
		}
		function onLocationFound(e) {
			var radius = Math.floor(e.accuracy / 2);
			if (circle!=null) {
				mappa.removeLayer(circle);
			}
			circle=L.circle(e.latlng, radius).addTo(mappa);
			poppup
				.setLatLng(e.latlng)
				.setContent("You are here
in about" + radius + " meters from this point")
				.openOn(mappa);
			lastCenterPosition= e.latlng;

			setTimeout(function(){ popupDown(); }, 6000);

		}
		function onLocationError(e) {
			alert(e.message);
		}

		mappa.on('locationfound', onLocationFound);
		mappa.on('locationerror', onLocationError);

		mappa.on('moveend', prendiPosECarica);
		mappa.on('zoomend', prendiPosECarica);
		mappa.on('zoomlevelchange', prendiPosECarica);
		mappa.on('resize', prendiPosECarica);

		myControl= new L.Control.myControl();
		myControl._save= function (e) { saveOnServer(e) ; } ;
		myControl._centerOnMarker= function (e) { centerOnMarker(e) ; } ;
		myControl._resetAll= function (e) { resetAll(e) ; } ;
		myControl._help= function (e) { help(e) ; } ;
		myControl.addTo(mappa);

		splashDialog=help();
		setTimeout(function(){ splashDialog.modal('hide') }, splashScreenTimeOutConfVal);
	  });


text:
/// Copyright (c) 2012 Ecma International.  All rights reserved.
/// Ecma International makes this code available under the terms and conditions set
/// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
/// "Use Terms").   Any redistribution of this code must retain the above
/// copyright and this notice and otherwise comply with the Use Terms.
/**
 * @path ch15/15.2/15.2.3/15.2.3.7/15.2.3.7-5-b-234.js
 * @description Object.defineProperties - 'set' property of 'descObj' is own accessor property that overrides an inherited data property (8.10.5 step 8.a)
 */

function testcase() {
        var data1 = "data";
        var data2 = "data";

        var proto = {};
        proto.set = function (value) {
            data1 = value;
        };

        var Con = function () { };
        Con.prototype = proto;

        var child = new Con();
        Object.defineProperty(child, "set", {
            get: function () {
                return function (value) {
                    data2 = value;
                };
            }
        });

        var obj = {};

        Object.defineProperties(obj, {
            prop: child
        });
        obj.prop = "overrideData";

        return obj.hasOwnProperty("prop") && data2 === "overrideData" && data1 === "data";

    }
runTestCase(testcase);


text:
package untappd

import (
	"net/http"
	"net/url"
	"strconv"
	"strings"
	"testing"
)

// TestClientBeerInfoBadBeer verifies that Client.Beer.Info returns an error when
// an invalid beer is queried.
func TestClientBeerInfoBadBeer(t *testing.T) {
	beerID := -1
	sBeerID := strconv.Itoa(beerID)

	c, done := beerInfoTestClient(t, func(t *testing.T, w http.ResponseWriter, r *http.Request) {
		path := "/v4/beer/info/" + sBeerID + "/"
		if p := r.URL.Path; p != path {
			t.Fatalf("unexpected URL path: %q != %q", p, path)
		}

		w.WriteHeader(http.StatusInternalServerError)
		w.Write(invalidBeerErrJSON)
	})
	defer done()

	_, _, err := c.Beer.Info(beerID, false)
	assertInvalidBeerErr(t, err)
}

// TestClientBeerInfoCompactOK verifies that Client.Beer.Info properly requests compact
// beer output.
func TestClientBeerInfoCompactOK(t *testing.T) {
	c, done := beerInfoTestClient(t, func(t *testing.T, w http.ResponseWriter, r *http.Request) {
		assertParameters(t, r, url.Values{
			"compact": []string{"true"},
		})

		// In the future, we may return compact canned beer data here.
		// For now, write a mostly empty JSON object is enough to get
		// test coverage.
		w.Write([]byte(`{"response":{"beer":{"id":1}}}`))
	})
	defer done()

	if _, _, err := c.Beer.Info(1, true); err != nil {
		t.Fatal(err)
	}
}

// TestClientBeerInfoOK verifies that Client.Beer.Info returns a valid beer when
// provided with correct input parameters.
func TestClientBeerInfoOK(t *testing.T) {
	beerID := 1
	sBeerID := strconv.Itoa(beerID)

	c, done := beerInfoTestClient(t, func(t *testing.T, w http.ResponseWriter, r *http.Request) {
		path := "/v4/beer/info/" + sBeerID + "/"
		if p := r.URL.Path; p != path {
			t.Fatalf("unexpected URL path: %q != %q", p, path)
		}

		w.Write(blackNoteBeerJSON)
	})
	defer done()

	b, _, err := c.Beer.Info(beerID, false)
	if err != nil {
		t.Fatal(err)
	}

	if id := b.ID; id != beerID {
		t.Fatalf("unexpected ID: %d != %d", id, 1)
	}
	beerName := "Black Note Stout"
	if n := b.Name; n != beerName {
		t.Fatalf("unexpected Name: %q != %q", n, beerName)
	}
	breweryName := "Bell's Brewery, Inc."
	if n := b.Brewery.Name; n != breweryName {
		t.Fatalf("unexpected Brewery.Name: %q != %q", n, breweryName)
	}
	overallCount := 123
	if c := b.OverallCount; c != overallCount {
		t.Fatalf("unexpected OverallCount: %q != %q", c, overallCount)
	}
}

// beerInfoTestClient builds upon testClient, and adds additional sanity checks
// for tests which target the beer info API.
func beerInfoTestClient(t *testing.T, fn func(t *testing.T, w http.ResponseWriter, r *http.Request)) (*Client, func()) {
	return testClient(t, func(t *testing.T, w http.ResponseWriter, r *http.Request) {
		// Always GET request
		method := "GET"
		if m := r.Method; m != method {
			t.Fatalf("unexpected HTTP method: %q != %q", m, method)
		}

		// Always uses specific path prefix
		prefix := "/v4/beer/info/"
		if p := r.URL.Path; !strings.HasPrefix(p, prefix) {
			t.Fatalf("unexpected HTTP path prefix: %q != %q", p, prefix)
		}

		// Guard against panics
		if fn != nil {
			fn(t, w, r)
		}
	})
}

// Canned JSON used in tests
var blackNoteBeerJSON = []byte(`
{
  "meta": {
    "code": 200,
    "response_time": {
      "time": 0,
      "measure": "seconds"
    }
  },
  "notifications": {},
  "response": {
  "beer": {
    "bid": 1,
    "beer_name": "Black Note Stout",
    "rating_count": 123,
    "brewery": {
      "brewery_name": "Bell's Brewery, Inc."
    }
  }
  }
}`)


text:
"""
This is a dictionary based implementation of the challenge.
It accepts any number of santas delivering presents via command line options.
Each santa has it's own position, but the `houses` are shared. Each house
is accessed by its position (represented by a tuple). Only houses that have
been visited exist, so the length of the `houses` dict is the number of houses
that got at least one present.

For a single santa:
    $ ./day3.py

For 2 santas:
    $ ./day3.py -n 2
"""

from collections import defaultdict
import argparse
import itertools

# Accept any number of santas via command line args
parser = argparse.ArgumentParser()
parser.add_argument(
    "-n", "--numsantas", type=int, default=1,
    help="number of Santas that deliver presents")
args = parser.parse_args()

# direction: (axis index, increment)
# "<": (0, -1) means "subtract 1 from the 0-index axis (x)"
direction_map = {"<": (0, -1), ">": (0, 1), "^": (1, -1), "v": (1, 1)}
# List of positions for each santa
positions = [[0, 0] for n in range(args.numsantas)]
# Dict of houses, the key is a tuple with the house position
# The defaultdict is initialized with 1 present in the house at (0, 0)
houses = defaultdict(int, {(0, 0): 1})
# Iterable versions of the positions dict
# With next() we can get each element of the list in a loop
ipositions = itertools.cycle(positions)

# Read directions from file
with open("inputs/day3.txt", "r") as f:
    directions = f.read()

# Each type we get a new direction, we move to the position and the
# houses of the next santa, repeating as needed
for d in directions:
    axis, value = direction_map[d]
    position = next(ipositions)
    position[axis] += value
    houses[tuple(position)] += 1

# In the end, the length of each house_dict is the number of houses
# that got at least one present
msg = "{} houses got at least one present in {} visits."
print(msg.format(len(houses), len(directions)))


text:
from django.test import TestCase
from mock import Mock, patch

from paymentexpress.facade import Facade
from paymentexpress.gateway import AUTH, PURCHASE
from paymentexpress.models import OrderTransaction
from tests import (XmlTestingMixin, CARD_VISA, SAMPLE_SUCCESSFUL_RESPONSE,
                   SAMPLE_DECLINED_RESPONSE, SAMPLE_ERROR_RESPONSE)

from oscar.apps.payment.utils import Bankcard
from oscar.apps.payment.exceptions import (UnableToTakePayment,
    InvalidGatewayRequestError)

class MockedResponseTestCase(TestCase):

    def create_mock_response(self, body, status_code=200):
        response = Mock()
        response.content = body
        response.text = body
        response.status_code = status_code
        return response

class FacadeTests(TestCase, XmlTestingMixin):

    def setUp(self):
        self.facade = Facade()

    def test_zero_amount_raises_exception(self):
        card = Bankcard(card_number=CARD_VISA,
                        expiry_date='1015',
                        name="Frankie", cvv="123",
                        start_date="1010")
        with self.assertRaises(UnableToTakePayment):
            self.facade.authorise('1000', 0, card)

    def test_zero_amount_for_complete_raises_exception(self):
        with self.assertRaises(UnableToTakePayment):
            self.facade.complete('1000', 0, '1234')

    def test_zero_amount_for_purchase_raises_exception(self):
        with self.assertRaises(UnableToTakePayment):
            self.facade.purchase('1000', 0)

    def test_purchase_without_billing_id_or_card_raises_exception(self):
        with self.assertRaises(ValueError):
            self.facade.purchase('1000', 1.23)

    def test_zero_amount_for_refund_raises_exception(self):
        with self.assertRaises(UnableToTakePayment):
            self.facade.refund('1000', 0, '1234')

    def test_merchant_reference_format(self):
        merchant_ref = self.facade._get_merchant_reference('1000', AUTH)
        self.assertRegexpMatches(merchant_ref, r'^\d+_[A-Z]+_\d+_\d{4}$')

class FacadeSuccessfulResponseTests(MockedResponseTestCase):

    dps_txn_ref = '000000030884cdc6'
    dps_billing_id = '0000080023225598'

    def setUp(self):
        self.facade = Facade()
        self.card = Bankcard(card_number=CARD_VISA,
                             expiry_date='1015',
                             name="Frankie", cvv="123",
                             start_date="1010")

    def test_successful_call_returns_valid_dict(self):
        with patch('requests.post') as post:
            post.return_value = self.create_mock_response(
                SAMPLE_SUCCESSFUL_RESPONSE)

            auth_dict = self.facade.authorise('1000', 1, self.card)
            complete_dict = self.facade.complete('1000', 1.23,
                                                 self.dps_txn_ref)
            refund_dict = self.facade.refund('1000', 1.23, '000000030884cdc6')
            validate_dict = self.facade.validate(self.card)
            response_dicts = (auth_dict, complete_dict, refund_dict,
                validate_dict)

            for response_dict in response_dicts:
                self.assertEquals(self.dps_txn_ref,
                    response_dict['txn_reference'])
                self.assertEquals(self.dps_billing_id,
                    response_dict['partner_reference'])

    def test_purchase_with_billing_id_returns_valid_dict(self):
        with patch('requests.post') as post:
            post.return_value = self.create_mock_response(
                SAMPLE_SUCCESSFUL_RESPONSE)

            txn_ref = self.facade.purchase('1000', 1.23, 'abc123')
            self.assertEquals(self.dps_txn_ref, txn_ref['txn_reference'])

    def test_purchase_with_bankcard_returns_valid_dict(self):
        with patch('requests.post') as post:
            post.return_value = self.create_mock_response(
                SAMPLE_SUCCESSFUL_RESPONSE)
            txn_ref = self.facade.purchase('1000', 1.23, None, self.card)
            self.assertEquals(self.dps_txn_ref, txn_ref['txn_reference'])

    def test_successful_call_is_recorded(self):
        with patch('requests.post') as post:
            post.return_value = self.create_mock_response(
                SAMPLE_SUCCESSFUL_RESPONSE)
            self.facade.authorise('10001', 10.25, self.card)
            txn = OrderTransaction.objects.filter(order_number='10001')[0]
            self.assertEquals(AUTH, txn.txn_type)

    def test_empty_issue_date_is_allowed(self):
        with patch('requests.post') as post:
            post.return_value = self.create_mock_response(
                SAMPLE_SUCCESSFUL_RESPONSE)
            card = Bankcard(card_number=CARD_VISA,
                            expiry_date='1015',
                            name="Frankie", cvv="123")
            txn_ref = self.facade.authorise('1000', 1.23, card)
            self.assertEquals(self.dps_txn_ref, txn_ref['txn_reference'])

class FacadeDeclinedResponseTests(MockedResponseTestCase):

    def setUp(self):
        self.facade = Facade()
        self.card = Bankcard(card_number=CARD_VISA,
                            expiry_date='1015',
                            name="Frankie", cvv="123",
                            start_date="1010")

    def test_declined_call_raises_an_exception(self):
        with patch('requests.post') as post:
            post.return_value = self.create_mock_response(
                SAMPLE_DECLINED_RESPONSE)

            with self.assertRaises(UnableToTakePayment):
                self.facade.authorise('1000', 1, self.card)

            with self.assertRaises(UnableToTakePayment):
                self.facade.complete('1000', 1.23, '000000030884cdc6')

            with self.assertRaises(UnableToTakePayment):
                self.facade.purchase('1000', 1.23, 'abc123')

            with self.assertRaises(UnableToTakePayment):
                self.facade.purchase('1000', 1.23, None, self.card)

            with self.assertRaises(UnableToTakePayment):
                self.facade.refund('1000', 1.23, '000000030884cdc6')

            with self.assertRaises(UnableToTakePayment):
                self.facade.validate(self.card)

    def test_declined_call_is_recorded(self):
        with patch('requests.post') as post:
            post.return_value = self.create_mock_response(
                SAMPLE_DECLINED_RESPONSE)
            try:
                self.facade.purchase('1001', 10.24, None, self.card)
            except Exception:
                pass
            txn = OrderTransaction.objects.filter(order_number='1001')[0]
            self.assertIsNotNone(txn)
            self.assertEquals(PURCHASE, txn.txn_type)

class FacadeErrorResponseTests(MockedResponseTestCase):

    def setUp(self):
        self.facade = Facade()
        self.card = Bankcard(card_number=CARD_VISA,
                            expiry_date='1015',
                            name="Frankie", cvv="123",
                            start_date="1010")

    def test_error_response_raises_invalid_gateway_request_exception(self):
        with patch('requests.post') as post:
            post.return_value = self.create_mock_response(
                SAMPLE_ERROR_RESPONSE)
            with self.assertRaises(InvalidGatewayRequestError):
                self.facade.purchase('1000', 10.24, None, self.card)


text:
var LicenceEdit = {};
LicenceEdit.get_json_preview = function(){
    $.ajax({
      url: $('#form-wrapper form').attr('action') + '?preview=true',
      type: $('#form-wrapper form').attr('method'),
        data: $('.licences form').serialize(),
      success: function(data, textStatus, jqXHR){
          $.JSONView(data, $('#json-preview').empty());
      },
      dataType: 'json'
    });
}

// toggle attribution fields
LicenceEdit.attribution_toggle = function(){
    if($(this).prop('checked')){
        $('.attribution, .attribution textarea, .attribution input').prop('disabled', false);
    }
    else{
        $('.attribution input').prop('checked',false);
        $('.attribution textarea').val('');
        $('.attribution, .attribution textarea, .attribution input').prop('disabled', true);
    }
}

// toggle copyleft fields
LicenceEdit.copyleft_toggle = function(){
    if($(this).prop('checked')){
        $('.copyleft, .copyleft input').prop('disabled', false);
    }
    else{
        $('.copyleft input').prop('checked',false);
        $('.copyleft, .copyleft input').prop('disabled', true);
    }
}

// toggle patent licence fields
LicenceEdit.patent_licence_toggle = function(){
    if($(this).prop('checked')){
        $('.patents .patent-licence-extends-to input').prop('disabled', false);
    }
    else{
        $('.patents .patent-licence-extends-to input').prop('disabled', true).prop('checked', false);
    }
}

// toggle patent retaliation fields
LicenceEdit.patent_retaliation_toggle = function(){
    if($(this).prop('checked')){
        $('.patents .patent-retaliation input, .patents .patent-retaliation-engages-upon input').prop('disabled', false);
    }
    else{
        $('.patents .patent-retaliation input, .patents .patent-retaliation-engages-upon input')
            .prop('disabled', true).prop('checked',false);
    }
}

// register on-change events
$(document).ready(function(){
    // conditional fields in licence editing
    $('.licences #form-wrapper').each(function(){
        $('#licence_obligation_attributes_obligation_attribution').change(LicenceEdit.attribution_toggle).change();
        $('#licence_obligation_attributes_obligation_copyleft').change(LicenceEdit.copyleft_toggle).change();
        $('#licence_right_attributes_covers_patents_explicitly').change(LicenceEdit.patent_licence_toggle).change();
        $('#licence_right_attributes_prohibits_patent_actions').change(LicenceEdit.patent_retaliation_toggle).change();
    });

    // update licence editor json preview
    $('.licences #json-preview').each(function(){
        $('.licences input, .licences textarea').change(LicenceEdit.get_json_preview);
        LicenceEdit.get_json_preview();

        // load the json on the licence metadata tab
        $('#json-data').each(function(){
            var url = $(this).attr('data-url');
            var content_wrapper = $(this);
            $.getJSON(url, function(data){
                $.JSONView(data, content_wrapper);
            });
        });
    });
});


text:
/**
 * @ngdoc directive
 * @name monthlyReports
 * @description
 * This directive contains all the required functions displaying monthly reports
 * @example
 *   <div monthly-reports></div>
 */
 angular.module('BitGo.Enterprise.MonthlyReportsDirective', [])

.directive('monthlyReports', ['$rootScope', 'NotifyService', 'ReportsAPI', 'UtilityService',
  function($rootScope, Notify, ReportsAPI, Utils) {
    return {
      restrict: 'A',
      controller: ['$scope', function($scope) {

        // The date range for all wallets reports on this enterprise
        $scope.dateVisibleRange = null;
        // The current wallet for reports (if a user selects one)
        $scope.selectedWallet = null;
        // The selected month to see reports for all wallets in an enterprise for a given month
        $scope.selectedDate = null;
        // Flag to see if there are any reports for the current period
        $scope.hasReportsForCurrentPeriod = false;

        // Filtering function to show only wallets in the view that have a report
        // to show for the current month selected
        // TODO(gavin): clean this up? can we do better than double loop?
        $scope.showWalletForCurrentPeriod = function(wallet) {
          var hasMonth;
          _.forEach(wallet.data.reportDates, function(reportDate) {
            _.forEach(reportDate.data, function(monthlyData) {
              if (monthlyData.dateVisible === $scope.selectedDate) {
                $scope.hasReportsForCurrentPeriod = true;
                hasMonth = true;
                return;
              }
            });
          });
          return hasMonth;
        };

        // Function to fetch the monthly report data for a wallet from the server
        $scope.getReport = function(wallet, dateInfo) {
          var reportInfoObj;
          // If there is dateInfo passed (to specify getting a report for that)
          // specific period, use dateInfo to construct the fetch params
          if (dateInfo) {
            reportInfoObj = wallet.getReportDateInfoForPeriod(dateInfo.dateVisible);
          } else {
            reportInfoObj = wallet.getReportDateInfoForPeriod($scope.selectedDate);
          }

          var reportTime = moment.utc(reportInfoObj.startTime);
          var reportStart = reportInfoObj.startTime;
          var reportParams = {
            walletAddress: wallet.data.id,
            start: reportStart,
            period: 'month',
            format: 'pdf'
          };

          ReportsAPI.getReport(reportParams)
          .then(function(data) {
            if (data.format === 'pdf') {
              // Safari does not support Blob downloads, and opening a Blob URL with
              // an unsupported data-type causes Safari to complain.
              // Github Issue: https://github.com/eligrey/FileSaver.js/issues/12
              if (bowser.name === "Safari") {
                document.location.href = "data:application/pdf;base64, " + data.data;
              } else {
                var buffer = Utils.Converters.base64ToArrayBuffer(data.data);
                var file = new Blob([buffer], { type: 'application/octet-stream'});
                var name = 'BitGo-Monthly-' + wallet.data.id.slice(0,8) + '-' + reportTime.format('YYYY-MM') + '.pdf';
                saveAs(file, name);
              }
            }
          })
          .catch(Notify.errorHandler);
        };

        // Build a UI-consumable array of dates for the reports based on all wallets
        // in the enterprise
        function buildUIReportRange(allWalletRanges) {
          var yearlyReports = [];
          var monthlyReports = [];
          var year = "";
          var oldYear = "";

          // reset dateVisibleRange on the scope
          $scope.dateVisibleRange = [];
          // ranges will be an object of date objects for each wallet in the enterprise
          _.forIn(allWalletRanges, function(singleWalletRanges, walletId) {
            _.forEach(singleWalletRanges, function(rangeItem) {
              if (!rangeItem.dateVisible) {
                throw new Error('Missing `dateVisible` property when using report range');
              }
              $scope.dateVisibleRange.push(rangeItem.dateVisible);
            });
            yearlyReports = [];
            monthlyReports = [];
            year = "";
            oldYear = "";
            //orders the reports in chunks based on year
            if (singleWalletRanges) {
              _.forEach(singleWalletRanges, function(month){
                //fetches the year of the report from the date visible
                year = month.dateVisible.substr(month.dateVisible.length -4);
                if (year !== oldYear && oldYear !== "") {
                  yearlyReports.push({
                    year: oldYear,
                    data: monthlyReports
                  });
                  monthlyReports=[];
                }
                monthlyReports.push(month);
                oldYear = year;
              });
              yearlyReports.push({
                year: year,
                data: monthlyReports
              });
              // incase $rootScope.wallets.all is emptied out due to navigation
              if ($rootScope.wallets.all[walletId]){
                // Add the report data to each wallet instance
                $rootScope.wallets.all[walletId].setReportDates(yearlyReports);
              }
            }
          });
          // Filter out any duplicates from the all array and sort by time
          $scope.dateVisibleRange = _.uniq($scope.dateVisibleRange).sort(function(a, b) {
            var aTime = new moment(a);
            var bTime = new moment(b);
            return aTime - bTime;
          });
        }

        // Get report date ranges for all wallets in the current enterprise
        function getEnterpriseReportRange(wallets) {
          if (!wallets) {
            throw new Error('Expect wallets object when fetching an enterprise report range');
          }
          var params = {
            wallets: wallets,
            stepType: 'month'
          };
          ReportsAPI.getAllWalletsReportRange(params)
          .then(function(ranges) {
            buildUIReportRange(ranges);
          })
          .catch(Notify.errorHandler);
        }

        // Event handlers
        // Set up the report data once the FilteredWallets have been set up (based on the
        // current enterprise and list of all possible wallets)
        var killWalletsSetListener = $rootScope.$on('WalletsAPI.UserWalletsSet', function(evt, data) {
          getEnterpriseReportRange(data.enterpriseWallets.all);
        });

        // Clean out the scope listeners to reduce run loop and multiple registrations
        $scope.$on('$destroy', function() {
          killWalletsSetListener();
        });

        function init() {
          $scope.dateVisibleRange = [];
          // TODO(gavin): clean up
          if (!_.isEmpty($rootScope.wallets.all)) {
            getEnterpriseReportRange($rootScope.wallets.all);
          }
        }
        init();

      }]
    };
  }
]);


text:
            <?php if ($this->uri->segment(2) == 'success'): ?>

                            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>

                                 Exitoso

                            El registro ingresado se ha almacenado correctamente.

            <?php endif ?>
            <?php if ($this->uri->segment(2) == 'success-delete'): ?>

                            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>

                                 Exitoso

                            El registro seleccionado ha sido eliminado correctamente.

            <?php endif ?>
            <?php if ($this->uri->segment(2) == 'success-edit'): ?>

                            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>

                                 Exitoso

                            El registro seleccionado ha sido actualizado correctamente.

            <?php endif ?>

                Listado de Unidades de Medida

                    <a href="<?php echo base_url('unitsmeasure/add') ?>" class="btn btn-primary" title="Agregar Unidad Medida">

                    Código
                    Unidad Medida
                    Abreviatura
                    Opciones

                    Código
                    Unidad Medida
                    Abreviatura
                    Opciones

                    <?php foreach ($full_listing as $key => $value): ?>

                            <?php echo $value['id_unit_measure'] ?>
                            <?php echo $value['unit_measure'] ?>
                            <?php echo $value['abbreviation'] ?>

                                    <a href="<?php echo base_url('unitsmeasure/edit/').$value['id_unit_measure'] ?>" class="btn btn-warning btn-sm">

                                        <button type="button" class="btn btn-danger btn-delete btn-sm" id="<?php echo $value['id_unit_measure'] ?>">

                                        </button>

                    <?php endforeach ?>

                    Estas seguro de seguir y ejecutar está acción, recuerda que no tienes ninguna opción para recuperar este registro


text:
package com.alibaba.otter.manager.web.home.module.screen;

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

import javax.annotation.Resource;

import com.alibaba.citrus.turbine.Context;
import com.alibaba.citrus.turbine.dataresolver.Param;
import com.alibaba.otter.manager.biz.config.datamatrix.DataMatrixService;
import com.alibaba.otter.manager.biz.config.datamediasource.DataMediaSourceService;
import com.alibaba.otter.shared.common.model.config.data.DataMatrix;
import com.alibaba.otter.shared.common.model.config.data.DataMediaSource;

public class DataMatrixInfo {

    @Resource(name = "dataMatrixService")
    private DataMatrixService      dataMatrixService;

    @Resource(name = "dataMediaSourceService")
    private DataMediaSourceService dataMediaSourceService;

    public void execute(@Param("matrixId") Long matrixId, Context context) throws Exception {
        DataMatrix matrix = dataMatrixService.findById(matrixId);

        Map condition = new HashMap();
        condition.put("searchKey", "jdbc:mysql://groupKey=" + matrix.getGroupKey());
        List<DataMediaSource> dataSources = dataMediaSourceService.listByCondition(condition);

        context.put("dataMatrix", matrix);
        context.put("dataSources", dataSources);
    }
}


text:
module Gerrit
  # Provides interface for collecting input from the user.
  class Input
    # Creates an {Gerrit::Input} wrapping the given IO stream.
    #
    # @param [IO] input the input stream
    def initialize(input)
      @input = input
    end

    # Blocks until a line of input is returned from the input source.
    #
    # @return [String, nil]
    def get
      @input.gets
    end
  end
end


text:
module Customly
  class Configuration

    attr_accessor :validations
    attr_reader :field_types
    attr_accessor :flags

    def initialize
      @validations = {}
      @field_types = {}
      @flags = []
    end

    def define_field_type (key, &block)
      ft = Customly::FieldType.new
      yield ft
      @field_types[key] = ft
    end

  end

  class << self
    attr_writer :configuration

    def configuration
      @configuration ||= Configuration.new
    end

    def configure
      yield configuration
    end
  end

end


text:
package uk.ac.ebi.pride.jmztab.utils.errors;

import java.util.Map;
import java.util.TreeMap;

/**
 * This list class used to storage all types of MZTabError, and provide query service based on
 * the error/warn code. This class used to generate mzTab help document.
 *
 * @author qingwei
 * @since 27/02/13
 */
public class MZTabErrorTypeMap {
    private Map<Integer, MZTabErrorType> typeMap = new TreeMap<Integer, MZTabErrorType>();

    private void add(MZTabErrorType type) {
        typeMap.put(type.getCode(), type);
    }

    public MZTabErrorTypeMap() {
        add(FormatErrorType.LinePrefix);
        add(FormatErrorType.CountMatch);
        add(FormatErrorType.IndexedElement);
        add(FormatErrorType.AbundanceColumn);
        add(FormatErrorType.MsRunOptionalColumn);
        add(FormatErrorType.OptionalCVParamColumn);
        add(FormatErrorType.StableColumn);
        add(FormatErrorType.MTDLine);
        add(FormatErrorType.MTDDefineLabel);
        add(FormatErrorType.MZTabMode);
        add(FormatErrorType.MZTabType);
        add(FormatErrorType.Param);
        add(FormatErrorType.ParamList);
        add(FormatErrorType.Publication);
        add(FormatErrorType.URI);
        add(FormatErrorType.URL);
        add(FormatErrorType.Email);
        add(FormatErrorType.Integer);
        add(FormatErrorType.Double);
        add(FormatErrorType.Reliability);
        add(FormatErrorType.StringList);
        add(FormatErrorType.DoubleList);
        add(FormatErrorType.ModificationList);
        add(FormatErrorType.GOTermList);
        add(FormatErrorType.MZBoolean);
        add(FormatErrorType.SpectraRef);
        add(FormatErrorType.CHEMMODSAccession);
        add(FormatErrorType.SearchEngineScore);
        add(FormatErrorType.Sequence);
        add(FormatErrorType.ColUnit);

        add(LogicalErrorType.NULL);
        add(LogicalErrorType.NotNULL);
        add(LogicalErrorType.LineOrder);
        add(LogicalErrorType.HeaderLine);
        add(LogicalErrorType.NoHeaderLine);
        add(LogicalErrorType.MsRunNotDefined);
        add(LogicalErrorType.AssayNotDefined);
        add(LogicalErrorType.StudyVariableNotDefined);
        add(LogicalErrorType.NotDefineInHeader);
        add(LogicalErrorType.NotDefineInMetadata);
        add(LogicalErrorType.DuplicationDefine);
        add(LogicalErrorType.DuplicationAccession);
        add(LogicalErrorType.AssayRefs);
        add(LogicalErrorType.ProteinCoverage);
        add(LogicalErrorType.IdNumber);
        add(LogicalErrorType.ModificationPosition);
        add(LogicalErrorType.CHEMMODS);
        add(LogicalErrorType.SubstituteIdentifier);
        add(LogicalErrorType.SoftwareVersion);
        add(LogicalErrorType.AbundanceColumnTogether);
        add(LogicalErrorType.AbundanceColumnSameId);

        add(LogicalErrorType.SpectraRef);
        add(LogicalErrorType.AmbiguityMod);
        add(LogicalErrorType.MsRunLocation);
        add(LogicalErrorType.FixedMod);
        add(LogicalErrorType.VariableMod);
        add(LogicalErrorType.PeptideSection);
        add(LogicalErrorType.QuantificationAbundance);
        add(LogicalErrorType.DuplicationID);
    }

    public MZTabErrorType getType(int code) {
        return typeMap.get(code);
    }

    public Map<Integer, MZTabErrorType> getTypeMap() {
        return typeMap;
    }
}


text:
package com.groupon.seleniumgridextras.config;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.File;
import java.util.LinkedList;
import java.util.List;

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

public class RuntimeConfigTest {

    @Before
    public void setUp() throws Exception {
        RuntimeConfig.clearConfig();
        RuntimeConfig.setConfigFile("merge_configs_test.json");

    }

    @After
    public void tearDown() throws Exception {
        File config = new File(RuntimeConfig.getConfigFile());
        config.delete();
        new File(RuntimeConfig.getConfigFile() + ".example").delete();
    }

    @Test
    public void testLoadDefaultsOnly() throws Exception {
        assertNull(RuntimeConfig.getConfig());

        writeEmptyConfig();
        RuntimeConfig.load();

        assertNotNull(RuntimeConfig.getConfig());
        assertNotNull(RuntimeConfig.getConfig().getWebdriver().getVersion());
        assertEquals(File.separator + "tmp" + File.separator + "webdriver", RuntimeConfig.getConfig().getWebdriver().getDirectory());

        List<String> expectedSetup = new LinkedList<String>();
        expectedSetup.add("com.groupon.seleniumgridextras.tasks.MoveMouse");

        assertEquals(expectedSetup, RuntimeConfig.getConfig().getSetup());

        assertEquals(true, RuntimeConfig.getConfig().getAutoStartNode());
        assertEquals(false, RuntimeConfig.getConfig().getAutoStartHub());

    }

    @Test
    public void testLoadWithOverwrites() throws Exception {
        assertNull(RuntimeConfig.getConfig());

        loadOverwriteConfigs();
        RuntimeConfig.load();

        assertNotNull(RuntimeConfig.getConfig());
        assertEquals("1.1.1.1.1", RuntimeConfig.getConfig().getWebdriver().getVersion());
        assertEquals("some_dir", RuntimeConfig.getConfig().getWebdriver().getDirectory());

        assertEquals("64", RuntimeConfig.getConfig().getChromeDriver().getBit());
        assertEquals("40.0.1.0", RuntimeConfig.getConfig().getChromeDriver().getVersion());

        List<String> expectedSetup = new LinkedList<String>();
        assertEquals(expectedSetup, RuntimeConfig.getConfig().getSetup());

        assertEquals(false, RuntimeConfig.getConfig().getAutoStartNode());
        assertEquals(true, RuntimeConfig.getConfig().getAutoStartHub());

    }

    private void writeEmptyConfig() throws Exception {
        File f = new File(RuntimeConfig.getConfigFile());
        FileUtils.writeStringToFile(f, "{}");
    }

    private void loadOverwriteConfigs() throws Exception {
        JsonObject fullConfig = new JsonObject();
        JsonObject theConfigMap = new JsonObject();
        JsonObject chromedriver = new JsonObject();

        JsonObject webdriver = new JsonObject();
        webdriver.addProperty("directory", "some_dir");
        webdriver.addProperty("version", "1.1.1.1.1");

        chromedriver.addProperty("bit", "64");
        chromedriver.addProperty("version", "40.0.1.0");

        theConfigMap.add("webdriver", webdriver);
        theConfigMap.add("chromedriver", chromedriver);
        theConfigMap.add("setup", new JsonArray());
        theConfigMap.addProperty("auto_start_hub", "1");
        theConfigMap.addProperty("auto_start_node", "0");
        theConfigMap.addProperty("days_until_log_deletion", "7");

        File f = new File(RuntimeConfig.getConfigFile());

        fullConfig.add("theConfigMap", theConfigMap);

        FileUtils.writeStringToFile(f, fullConfig.toString());

    }

}


text:
package main

import (
	"errors"
	"gobox/common"
	"os"
	"path/filepath"
)

func init() {
	// "gobox" has to be added here for two reasons
	// 1.) So it can't be removed, it's core functionalty
	// 2.) It causes cyclic dependencies otherwise
	Applets["gobox"] = GoboxMain
}

func run() {
	callname := filepath.Base(os.Args[0])
	applet, ok := Applets[callname]
	if !ok {
		panic(errors.New("Could not find applet \"" + callname + "\""))
	}

	// If the Gobox applet is called (i.e. the executable itself)
	// check, if the second parameter is an applet name.
	// If so, call that applet instead
	args := os.Args
	if callname == "gobox" && len(args) >= 2 {
		subapplet, ok := Applets[args[1]]
		if ok {
			applet = subapplet
			args = args[1:]
		}
	}

	applet(args)
}

func main() {
	defer func() {
		if p := recover(); p != nil {
			e, ok := p.(error)
			if !ok {
				e = errors.New("Some error occured")
			}
			common.DumpError(e)
		}
	}()
	run()
}


text:
var Beacon = require('./beacon');
var secret = 'very_secret_token';

exports.authorizeSocketClient = function(socket, next) {
  var handshakeData = socket.request;

  if (handshakeData._query.foo !== 'bar') {
    console.log('Unauthorized');
    console.log('Invalid secret: ' + handshakeData._query.foo);
    return next(new Error('not authorized'));
  }
  next();
};

exports.authenticateRequest = function(req, res, next) {
  if (secret !== req.headers['x-access-token']) {
    return res.status(401).json({ error: 'Invalid x-access-token' });
  }
  next();
}

// Create beacons
exports.seedData = function() {
  var beacon_uuid = '123456789'

  Beacon.find({ uuid: beacon_uuid }, function(err, beacons) {
    if (err) {
      console.log(err);
    }

    if (beacons.length == 0) {
      var beacon = Beacon({
        uuid: beacon_uuid,
        major: '123',
        minor: '456',
        messages: [{type: '1', message: 'Immediate proximity'},
                   {type: '2', message: 'Near proximity'},
                   {type: '3', message: 'Far proximity'}]
      });

      beacon.save(function(err) {
        if (err) throw err;
        console.log('beacon created');
      });
    }
  });
}


text:
// Note: comments done with
// http://patorjk.com/software/taag/#p=display&f=Doom&t=Logger

//                  _
//                 (_)
//  _ __ ___   __ _ _ _ __
// | '_ ` _ \ / _` | | '_ \
// | | | | | | (_| | | | | |
// |_| |_| |_|\__,_|_|_| |_|

// Find canvas
var canvas = document.querySelector('#renderCanvas');

// Load Babylon
var engine = new BABYLON.Engine(canvas, true);

// Main master object
var main = {};

// Main create scene
main.createScene = function () {

  // Create scene object
  this.scene = new BABYLON.Scene(engine);
  var scene = this.scene;

  // Set main serverInfo
  this.serverInfo = {};

  // Make environment
  this.makeEnvironment();

  // Make player
  this.makePlayer();

  // Initialize foreign players
  this.foreignData = {};
  // The foreign player player data
  this.foreignData.players = {};
  // The current animation time of foreign player movement
  this.foreignData.gradientTime = 0;
  // Make camera
  this.makeCamera();

  // // Return the scene
  return scene;
};

// Main start scene rendering
main.renderScene_start = function () {
  // Set main old time
  main.newTime = Date.now()/1000;
  // Render
  engine.runRenderLoop(function () {
    // Update time
    main.updateTime();
    // Move player
    main.movePlayer();
    // Move foreign players
    main.moveForeignPlayers();
    // Render scene
    main.scene.render();
  });
};

// Main update time
main.updateTime = function () {
  main.oldTime = main.newTime;
  main.newTime = Date.now()/1000;
  main.deltaTime = main.newTime - main.oldTime;
};

// Main make environment
main.makeEnvironment = function () {
  // Get scene reference
  var scene = main.scene;

  // Add light pointing directly up
  var light = new BABYLON.HemisphericLight('light0',
    new BABYLON.Vector3(0, 1, 0), scene);
  // Dim light
  light.intensity = .5;

  // Create floor
  main.floor = BABYLON.Mesh.CreateBox('floor0',
    1, scene);
  var floor = main.floor;
  // Scale
  floor.scaling.y = 2;
  floor.scaling.x = 100;
  floor.scaling.z = 100;
  floor.position.y -= floor.scaling.y/2;
  // Create floor material
  var floorMaterial = new BABYLON.StandardMaterial('floorMat',
    scene);
  // Set wireframe
  floorMaterial.wireframe = true;
  // Set material of floor
  floor.material = floorMaterial;
  // Check collisions on floor
  floor.checkCollisions = true;

  // Set gravity
  main.gravity = -10;
};

// Make camera
main.makeCamera = function () {
  // Create camera
  var camera = new BABYLON.FreeCamera('camera0',
    new BABYLON.Vector3(0, 3, -7), main.scene);
  // Set camera target
  camera.setTarget(BABYLON.Vector3.Zero());
  // Add camera to canvas
  camera.attachControl(canvas, false);
  // Set camera
  main.camera = camera;
  // Dont move camera
  camera.speed = 0;
  // Set camera's parent to be player's parent
  camera.parent = main.player.gameObject_parent;
};

//  _                 _        _ _            _
// | |               | |      | (_)          | |
// | | ___   ___ __ _| |   ___| |_  ___ _ __ | |_
// | |/ _ \ / __/ _` | |  / __| | |/ _ \ '_ \| __|
// | | (_) | (_| (_| | | | (__| | |  __/ | | | |_
// |_|\___/ \___\__,_|_|  \___|_|_|\___|_| |_|\__|

// Main make player
main.makePlayer = function () {
  // Make player object
  main.player = {};
  var player = main.player;
  // Set player speed
  player.speed = 10;
  // Set player jumpTime
  player.jumpTime = -1;
  // Set player jumpVelocity_Start
  player.jumpVelocity_Start = 6;
  // Set player jumpHeight_Start
  player.jumpHeight_Start = -1;
  // Set player jump count
  player.jumpCount = 2;
  player.jumpCount_Start = 2;
  // Player completed flip bool
  player.flipComplete = false;
  // Set player gravity multiplier
  player.gravMult = 1.0;
  // Get player max jump height time
  player.maxJumpHeightTime
    = -player.jumpVelocity_Start/(main.gravity
      * main.player.gravMult);

  // Set player LR rotation speed
  player.rotationSpeed = 2;

  // Set player velocites
  player.currentVelocities = {};

  // Get scene reference
  var scene = main.scene;

  // Set player game object's parent
  var boxParent = BABYLON.Mesh.CreateBox('playerParent',
    1.0, scene);
  boxParent.position.y = .5;
  main.player.gameObject_parent = boxParent;
  main.player.gameObject_parent.isVisible = false;
  // Set player game object
  var boxChild = BABYLON.Mesh.CreateBox('playerChild',
    1.0, scene);
  boxChild.position.y = .5;
  main.player.gameObject_child = boxChild;
  // Check collisions on child
  boxChild.checkCollisions = true;
  // Parent boxChild to boxParent
  boxChild.parent = boxParent;

  // Set player ground
  main.player.groundedHeight
    = boxChild.scaling.y * .5;
};

// Main move player
main.movePlayer = function () {
  // Reset player velocities
  this.resetPlayerVelocities();

  // Left and right input
  var x = 0;
  // If left key
  if (inputs[37]) {
    x -= 1;
  }
  // If right key
  if (inputs[39]) {
    x += 1;
  }

  // Back and forward input
  var z = 0;
  // If down arrow key
  if (inputs[38]) {
    z +=1;
  }
  // If up arrow key
  if (inputs[40]) {
    z -= 1;
  }

  // Player
  var player = main.player;
  // Player game object
  var playerParent = player.gameObject_parent;
  var playerChild = player.gameObject_child;
  // Player speed
  var playerSpeed = player.speed;

  // Move player left, right, forward, and back
  var netAddedXZ = {
    x: 0,
    z: 0
  };

  // If player net-left/right motion isn't 0
  if (x !== 0) {
    // Add relative to rotation
    var relativeLR
      = main.relativeRight(playerParent.rotation.y);
    netAddedXZ.x += x * relativeLR.x;
    netAddedXZ.z += x * relativeLR.z;
  }
  // If player net-forward/back motion isn't 0
  if (z !== 0) {
    // Add relative to rotation
    var relativeFB
      = main.relativeForward(playerParent.rotation.y);
    netAddedXZ.x += z * relativeFB.x;
    netAddedXZ.z += z * relativeFB.z;
  }
  // Update player positions
  playerParent.position.x
    += netAddedXZ.x * main.deltaTime * playerSpeed;
  playerParent.position.z
    += netAddedXZ.z * main.deltaTime * playerSpeed;

  // Set current player x and z velocites for server update
  player.currentVelocities.x = netAddedXZ.x * playerSpeed;
  player.currentVelocities.z = netAddedXZ.z * playerSpeed;

  // Jump input
  // If player has reached top of jump
  // and has jumps left
  if (inputs[32]
    && (player.jumpTime === -1
      || player.maxJumpHeightTime < player.jumpTime)
    && 0 < player.jumpCount) {
    // Set time in jump to now
    player.jumpTime = 0;
    // Set jump initial height
    player.jumpHeight_Start
      = playerParent.position.y;
    // Decrement jump count
    --player.jumpCount;
  }
  // If player has jumped
  if (player.jumpTime !== -1) {
    // Increase time in jump
    player.jumpTime += main.deltaTime;
    // Get reference to old player position
    var oldPlayerHeight = playerParent.position.y;
    // Get current jump position
    var y = main.jumpInterpretter();
    // If player has finished first half of jump
    // AND y is too low
    if (player.maxJumpHeightTime < player.jumpTime
      && y < player.groundedHeight) {
      // Place player on ground
      y = player.groundedHeight;
      // Reset jump parameters
      player.jumpTime = -1;
      player.jumpHeight_Start = -1;
      player.jumpCount = player.jumpCount_Start;
      player.flipComplete = false;
    }
    // Move player vertically
    playerParent.position.y = y;

    // Set y velocity
    player.currentVelocities.y
      = (y - oldPlayerHeight) / main.deltaTime;
  }

  // Left right rotation
  var y_r = 0;
  // If Q
  if (inputs[69]) {
    y_r += 1;
  }
  // If E
  if (inputs[81]) {
    y_r -= 1;
  }

  // Rotate player
  if (y_r !== 0) {
    playerParent.rotation.y
      += (y_r * main.deltaTime * player.rotationSpeed);
  }

  // Set player y rotation
  player.currentVelocities.y_r = y_r * player.rotationSpeed;

  // Flip player
  var x_r = 0;
  // If used both jumps
  if (!player.flipComplete && player.jumpCount === 0) {
    // Get current x rotation
    var oldPlayerXRotation = playerChild.rotation.x;
    // Get flip ratio
    var flipRatio = main.flipInterpretter();
    // If ratio exceeds 1
    if (1 < flipRatio) {
      // Set flip ratio to 0
      flipRatio = 0
      // Complete flip
      player.flipComplete = true;
    }
    // Set new rotation
    playerChild.rotation.x = flipRatio * 2 * Math.PI;

    // Set x rotational velocity
    player.currentVelocities.x_r
      = (playerChild.rotation.x -
          oldPlayerXRotation) / main.deltaTime;
  }
};

// Main clear local player velocity
main.resetPlayerVelocities = function () {
  // Get reference to local player
  var player = main.player;
  // Reset all velocities to 0

  // Positional velocity
  player.currentVelocities.x = 0;
  player.currentVelocities.y = 0;
  player.currentVelocities.z = 0;
  // Rotational velocity
  player.currentVelocities.x_r = 0;
  player.currentVelocities.y_r = 0;
};

//   __               _                    _ _            _
//  / _|             (_)                  | (_)          | |
// | |_ ___  _ __ ___ _  __ _ _ __     ___| |_  ___ _ __ | |_
// |  _/ _ \| '__/ _ \ |/ _` | '_ \   / __| | |/ _ \ '_ \| __|
// | || (_) | | |  __/ | (_| | | | | | (__| | |  __/ | | | |_
// |_| \___/|_|  \___|_|\__, |_| |_|  \___|_|_|\___|_| |_|\__|
//                       __/ |
//                      |___/

// Main make foreign players
main.makeForeignPlayers = function (data) {
  // Delete data about us
  delete data[main.player.username];
  // Get foreign players
  var foreignPlayers = this.foreignData.players;
  // Get animation gradient
  var gradient = 1;
  // Iterate over all players
  for (var username in data) {
    // If the username isn't a current foreign player
    if (foreignPlayers[username] === undefined) {
      // Make empty object
      foreignPlayers[username] = {};
      // Make the player gameObject
      foreignPlayers[username].gameObject
        = BABYLON.Mesh.CreateBox(username, 1.0, main.scene);
    }
    // Reference to player data
    var playerData = data[username];
    // Add object and attributes
    foreignPlayers[username].onUpdate = {
      position: main.makeVector3(playerData.position),
      rotation: main.makeVector3(playerData.rotation),
      scaling: main.makeVector3(playerData.scaling),
      velocities: playerData.velocities
    };

    // Reference to onUpdate (current transform)
    var onUpdate = foreignPlayers[username].onUpdate;
    // Set the players predicted position
    foreignPlayers[username].predictions = {
      // Position
      position: main.makeVector3({
        // Current position plus expected position added
        x: onUpdate.position.x
          + (onUpdate.velocities.x
              * main.serverInfo.updateRate/1000),
        // Current position plus expected position
        y: onUpdate.position.y
          + (onUpdate.velocities.y
              * main.serverInfo.updateRate/1000),
        // Current position plus expected position
        z: onUpdate.position.z
          + (onUpdate.velocities.z
              * main.serverInfo.updateRate/1000)
      }),

      // Rotation
      rotation: main.makeVector3({
        // Current rotation plus expected rotation added
        x: onUpdate.rotation.x
          + (onUpdate.velocities.x_r
              * main.serverInfo.updateRate/1000),
        // Current rotation plus expected rotation added
        y: onUpdate.rotation.y
          + (onUpdate.velocities.y_r
              * main.serverInfo.updateRate/1000),
        // Current rotation plus expected rotation added
        z: onUpdate.rotation.z
      })

      // Scaling
    };
  }
  // Reset the current foreignPlayers animation percentage
  this.foreignData.gradientTime = 0;
};

// Main move foreign players
main.moveForeignPlayers = function () {
  // Get animation gradient
  var gradient = this.getAnimationGradient();

  // Iterate over all players
  var foreignPlayers = this.foreignData.players;
  for (var username in foreignPlayers) {
    // Get reference to player and predictions
    var player = foreignPlayers[username];
    var onUpdate = player.onUpdate;
    var predictions = player.predictions;
    // Get velocities
    var velocities = player.velocities;

    // Interpolate position
    var newPosition
      = BABYLON.Animation.prototype.vector3InterpolateFunction(
          onUpdate.position,
          predictions.position,
          gradient
        );
    player.gameObject.position = newPosition;
    // Set rotation
    var newRotation
      = BABYLON.Animation.prototype.vector3InterpolateFunction(
          onUpdate.rotation,
          predictions.rotation,
          gradient
        );
    player.gameObject.rotation = newRotation;
    console.log(newPosition);
    // Set scaling
    /*var newScaling
      = BABYLON.Animation.prototype.vector3InterpolateFunction(
          onUpdate.scaling,
          predictions.scaling,
          gradient
        );
    player.gameObject.scaling = newScaling;*/
  }

  // Update gradient by delta time
  main.incrementAnimationGradient();

};

// Main calculate gradient time
main.getAnimationGradient  = function () {
  // Get animation gradient
  var gradientTime = this.foreignData.gradientTime;
  var updateRate = this.serverInfo.updateRate;
  return gradientTime / updateRate;
};

// Main increment animation gradient time
main.incrementAnimationGradient = function () {
  // Increment animation gradient
  this.foreignData.gradientTime += (main.deltaTime * 1000);
};

// Main make BABYLON.Vector3
main.makeVector3 = function (data) {
  return new BABYLON.Vector3(data.x, data.y, data.z);
};

// Main relative forward
main.relativeForward = function (rad) {
  return {
    x: Math.sin(rad),
    z: Math.cos(rad)
  };
}

// Main relative right
main.relativeRight = function (rad) {
  return {
    x: Math.cos(rad),
    z: -Math.sin(rad)
  };
}

// Main jump interpreter
main.jumpInterpretter = function () {
  // Local player
  var player = main.player;
  // Height of jump start
  var jumpHeight_Start = player.jumpHeight_Start;
  // Time in jump
  var jumpTime = player.jumpTime;
  // Jump velocity
  var jumpVelocity_Start = player.jumpVelocity_Start;
  // Gravity
  var gravity = player.gravMult * main.gravity;

  // Return kinematics
  return jumpHeight_Start + jumpVelocity_Start * jumpTime
    + .5 * gravity * jumpTime * jumpTime;
};

// Main flip interpreter
main.flipInterpretter = function () {
  // Local player
  var player = main.player;
  // Time in jump
  var jumpTime = player.jumpTime;
  // Flip ratio
  var flipRatio = .75 * jumpTime / player.maxJumpHeightTime;
  // Return rotation
  return flipRatio;
};

// Main get local update
main.getLocalUpdate = function () {
  // Get reference to player game objects
  var playerParent = main.player.gameObject_parent;
  var playerChild = main.player.gameObject_child;
  // Get required attributes
  return {
    // Username
    username: main.player.username,
    // Game object attributes
    playerData: {
      position: {
        x: playerParent.position.x,
        y: playerParent.position.y,
        z: playerParent.position.z
      },
      rotation: {
        x: playerChild.rotation.x,
        y: playerParent.rotation.y,
        z: playerParent.rotation.z
      },
      scaling: {
        x: playerParent.scaling.x,
        y: playerParent.scaling.y,
        z: playerParent.scaling.z
      },
      velocities: main.player.currentVelocities
    }
  };
};

// On window resize
window.addEventListener('resize', function () {
  engine.resize();
});


text:
Portus targets [version 2](https://github.com/docker/distribution/blob/master/docs/spec/api.md)
of the Docker registry API. It aims to act both as
an authoritzation server and as a user interface for the next generation of the
Docker registry.

![preview](https://raw.githubusercontent.com/SUSE/Portus/master/doc/portus.png)

## Features

### Fine-grained control of permissions

Portus supports the concept of users and teams. Each user has its personal Docker namespace where she has read (aka `docker pull`) and write (aka `docker push`) access.

A team is a group of users that have read and write access to a certain namespace.

Portus implements the [token based authentication system](https://github.com/docker/distribution/blob/master/docs/spec/auth/token.md)
described by the new version of the Docker registry. This can be used to have full control over the images served by an instance of the Docker registry.

### Web interface for Docker registry

Portus provides quick access to all the images available on your private instance of Docker registry. User's privileges are taken into account to make sure private images (the ones requiring special rights also for `docker pull`) are not shown to unauthorized personnel.

## Current limitations

Portus' knowledge of the images available on the private instance of a Docker registry is built using the [notifications](https://github.com/docker/distribution/blob/master/docs/notifications.md) sent by the Docker registry itself.

If Portus is unreachable when a new image is being pushed to the Docker registry, Portus won't be aware of it. This issue is going to be solved by next versions of Portus.

## Contributing

First of all, make sure that you have a working development environment. You
can easily do this with either Docker or Vagrant, as it's explained on the
[wiki](https://github.com/SUSE/Portus/wiki/The-development-environment).

Also, make sure to understand our contribution guidelines, as explained in
[this](https://github.com/SUSE/Portus/blob/master/CONTRIBUTING.md) document.

Happy hacking!

## Licensing

Portus is licensed under the Apache License, Version 2.0. See
[LICENSE](https://github.com/SUSE/Portus/blob/master/LICENSE) for the full
license text.


text:
#include <linux/completion.h>
#include <linux/ip.h>
#include <linux/module.h>
#include <linux/sunrpc/svc.h>
#include <linux/sunrpc/svcsock.h>
#include <linux/nfs_fs.h>
#include <linux/errno.h>
#include <linux/mutex.h>
#include <linux/freezer.h>
#include <linux/kthread.h>
#include <linux/sunrpc/svcauth_gss.h>
#include <linux/sunrpc/bc_xprt.h>

#include <net/inet_sock.h>

#include "nfs4_fs.h"
#include "callback.h"
#include "internal.h"
#include "netns.h"

#define NFSDBG_FACILITY NFSDBG_CALLBACK

struct nfs_callback_data {
	unsigned int users;
	struct svc_serv *serv;
	struct svc_rqst *rqst;
	struct task_struct *task;
};

static struct nfs_callback_data nfs_callback_info[NFS4_MAX_MINOR_VERSION + 1];
static DEFINE_MUTEX(nfs_callback_mutex);
static struct svc_program nfs4_callback_program;

static int nfs4_callback_up_net(struct svc_serv *serv, struct net *net)
{
	int ret;
	struct nfs_net *nn = net_generic(net, nfs_net_id);

	ret = svc_create_xprt(serv, "tcp", net, PF_INET,
				nfs_callback_set_tcpport, SVC_SOCK_ANONYMOUS);
	if (ret <= 0)
		goto out_err;
	nn->nfs_callback_tcpport = ret;
	dprintk("NFS: Callback listener port = %u (af %u, net %p)\n",
			nn->nfs_callback_tcpport, PF_INET, net);

	ret = svc_create_xprt(serv, "tcp", net, PF_INET6,
				nfs_callback_set_tcpport, SVC_SOCK_ANONYMOUS);
	if (ret > 0) {
		nn->nfs_callback_tcpport6 = ret;
		dprintk("NFS: Callback listener port = %u (af %u, net %p)\n",
				nn->nfs_callback_tcpport6, PF_INET6, net);
	} else if (ret != -EAFNOSUPPORT)
		goto out_err;
	return 0;

out_err:
	return (ret) ? ret : -ENOMEM;
}

/*
 * This is the NFSv4 callback kernel thread.
 */
static int
nfs4_callback_svc(void *vrqstp)
{
	int err;
	struct svc_rqst *rqstp = vrqstp;

	set_freezable();

	while (!kthread_should_stop()) {
		/*
		 * Listen for a request on the socket
		 */
		err = svc_recv(rqstp, MAX_SCHEDULE_TIMEOUT);
		if (err == -EAGAIN || err == -EINTR)
			continue;
		svc_process(rqstp);
	}
	return 0;
}

/*
 * Prepare to bring up the NFSv4 callback service
 */
static struct svc_rqst *
nfs4_callback_up(struct svc_serv *serv)
{
	return svc_prepare_thread(serv, &serv->sv_pools[0], NUMA_NO_NODE);
}

#if defined(CONFIG_NFS_V4_1)
static int nfs41_callback_up_net(struct svc_serv *serv, struct net *net)
{
	/*
	 * Create an svc_sock for the back channel service that shares the
	 * fore channel connection.
	 * Returns the input port (0) and sets the svc_serv bc_xprt on success
	 */
	return svc_create_xprt(serv, "tcp-bc", net, PF_INET, 0,
			      SVC_SOCK_ANONYMOUS);
}

/*
 * The callback service for NFSv4.1 callbacks
 */
static int
nfs41_callback_svc(void *vrqstp)
{
	struct svc_rqst *rqstp = vrqstp;
	struct svc_serv *serv = rqstp->rq_server;
	struct rpc_rqst *req;
	int error;
	DEFINE_WAIT(wq);

	set_freezable();

	while (!kthread_should_stop()) {
		if (try_to_freeze())
			continue;

		prepare_to_wait(&serv->sv_cb_waitq, &wq, TASK_INTERRUPTIBLE);
		spin_lock_bh(&serv->sv_cb_lock);
		if (!list_empty(&serv->sv_cb_list)) {
			req = list_first_entry(&serv->sv_cb_list,
					struct rpc_rqst, rq_bc_list);
			list_del(&req->rq_bc_list);
			spin_unlock_bh(&serv->sv_cb_lock);
			dprintk("Invoking bc_svc_process()\n");
			error = bc_svc_process(serv, req, rqstp);
			dprintk("bc_svc_process() returned w/ error code= %d\n",
				error);
		} else {
			spin_unlock_bh(&serv->sv_cb_lock);
			schedule();
		}
		finish_wait(&serv->sv_cb_waitq, &wq);
	}
	return 0;
}

/*
 * Bring up the NFSv4.1 callback service
 */
static struct svc_rqst *
nfs41_callback_up(struct svc_serv *serv)
{
	struct svc_rqst *rqstp;

	INIT_LIST_HEAD(&serv->sv_cb_list);
	spin_lock_init(&serv->sv_cb_lock);
	init_waitqueue_head(&serv->sv_cb_waitq);
	rqstp = svc_prepare_thread(serv, &serv->sv_pools[0], NUMA_NO_NODE);
	if (IS_ERR(rqstp)) {
		svc_xprt_put(serv->sv_bc_xprt);
		serv->sv_bc_xprt = NULL;
	}
	dprintk("--> %s return %ld\n", __func__,
		IS_ERR(rqstp) ? PTR_ERR(rqstp) : 0);
	return rqstp;
}

static void nfs_minorversion_callback_svc_setup(struct svc_serv *serv,
		struct svc_rqst **rqstpp, int (**callback_svc)(void *vrqstp))
{
	*rqstpp = nfs41_callback_up(serv);
	*callback_svc = nfs41_callback_svc;
}

static inline void nfs_callback_bc_serv(u32 minorversion, struct rpc_xprt *xprt,
		struct svc_serv *serv)
{
	if (minorversion)
		/*
		 * Save the svc_serv in the transport so that it can
		 * be referenced when the session backchannel is initialized
		 */
		xprt->bc_serv = serv;
}
#else
static int nfs41_callback_up_net(struct svc_serv *serv, struct net *net)
{
	return 0;
}

static void nfs_minorversion_callback_svc_setup(struct svc_serv *serv,
		struct svc_rqst **rqstpp, int (**callback_svc)(void *vrqstp))
{
	*rqstpp = ERR_PTR(-ENOTSUPP);
	*callback_svc = ERR_PTR(-ENOTSUPP);
}

static inline void nfs_callback_bc_serv(u32 minorversion, struct rpc_xprt *xprt,
		struct svc_serv *serv)
{
}
#endif /* CONFIG_NFS_V4_1 */

static int nfs_callback_start_svc(int minorversion, struct rpc_xprt *xprt,
				  struct svc_serv *serv)
{
	struct svc_rqst *rqstp;
	int (*callback_svc)(void *vrqstp);
	struct nfs_callback_data *cb_info = &nfs_callback_info[minorversion];
	char svc_name[12];
	int ret;

	nfs_callback_bc_serv(minorversion, xprt, serv);

	if (cb_info->task)
		return 0;

	switch (minorversion) {
	case 0:
		/* v4.0 callback setup */
		rqstp = nfs4_callback_up(serv);
		callback_svc = nfs4_callback_svc;
		break;
	default:
		nfs_minorversion_callback_svc_setup(serv,
				&rqstp, &callback_svc);
	}

	if (IS_ERR(rqstp))
		return PTR_ERR(rqstp);

	svc_sock_update_bufs(serv);

	sprintf(svc_name, "nfsv4.%u-svc", minorversion);
	cb_info->serv = serv;
	cb_info->rqst = rqstp;
	cb_info->task = kthread_run(callback_svc, cb_info->rqst, svc_name);
	if (IS_ERR(cb_info->task)) {
		ret = PTR_ERR(cb_info->task);
		svc_exit_thread(cb_info->rqst);
		cb_info->rqst = NULL;
		cb_info->task = NULL;
		return ret;
	}
	dprintk("nfs_callback_up: service started\n");
	return 0;
}

static void nfs_callback_down_net(u32 minorversion, struct svc_serv *serv, struct net *net)
{
	struct nfs_net *nn = net_generic(net, nfs_net_id);

	if (--nn->cb_users[minorversion])
		return;

	dprintk("NFS: destroy per-net callback data; net=%p\n", net);
	svc_shutdown_net(serv, net);
}

static int nfs_callback_up_net(int minorversion, struct svc_serv *serv, struct net *net)
{
	struct nfs_net *nn = net_generic(net, nfs_net_id);
	int ret;

	if (nn->cb_users[minorversion]++)
		return 0;

	dprintk("NFS: create per-net callback data; net=%p\n", net);

	ret = svc_bind(serv, net);
	if (ret < 0) {
		printk(KERN_WARNING "NFS: bind callback service failed\n");
		goto err_bind;
	}

	switch (minorversion) {
		case 0:
			ret = nfs4_callback_up_net(serv, net);
			break;
		case 1:
			ret = nfs41_callback_up_net(serv, net);
			break;
		default:
			printk(KERN_ERR "NFS: unknown callback version: %d\n",
					minorversion);
			ret = -EINVAL;
			break;
	}

	if (ret < 0) {
		printk(KERN_ERR "NFS: callback service start failed\n");
		goto err_socks;
	}
	return 0;

err_socks:
	svc_rpcb_cleanup(serv, net);
err_bind:
	dprintk("NFS: Couldn't create callback socket: err = %d; "
			"net = %p\n", ret, net);
	return ret;
}

static struct svc_serv *nfs_callback_create_svc(int minorversion)
{
	struct nfs_callback_data *cb_info = &nfs_callback_info[minorversion];
	struct svc_serv *serv;

	/*
	 * Check whether we're already up and running.
	 */
	if (cb_info->task) {
		/*
		 * Note: increase service usage, because later in case of error
		 * svc_destroy() will be called.
		 */
		svc_get(cb_info->serv);
		return cb_info->serv;
	}

	/*
	 * Sanity check: if there's no task,
	 * we should be the first user ...
	 */
	if (cb_info->users)
		printk(KERN_WARNING "nfs_callback_create_svc: no kthread, %d users??\n",
			cb_info->users);

	serv = svc_create(&nfs4_callback_program, NFS4_CALLBACK_BUFSIZE, NULL);
	if (!serv) {
		printk(KERN_ERR "nfs_callback_create_svc: create service failed\n");
		return ERR_PTR(-ENOMEM);
	}
	/* As there is only one thread we need to over-ride the
	 * default maximum of 80 connections
	 */
	serv->sv_maxconn = 1024;
	dprintk("nfs_callback_create_svc: service created\n");
	return serv;
}

/*
 * Bring up the callback thread if it is not already up.
 */
int nfs_callback_up(u32 minorversion, struct rpc_xprt *xprt)
{
	struct svc_serv *serv;
	struct nfs_callback_data *cb_info = &nfs_callback_info[minorversion];
	int ret;
	struct net *net = xprt->xprt_net;

	mutex_lock(&nfs_callback_mutex);

	serv = nfs_callback_create_svc(minorversion);
	if (IS_ERR(serv)) {
		ret = PTR_ERR(serv);
		goto err_create;
	}

	ret = nfs_callback_up_net(minorversion, serv, net);
	if (ret < 0)
		goto err_net;

	ret = nfs_callback_start_svc(minorversion, xprt, serv);
	if (ret < 0)
		goto err_start;

	cb_info->users++;
	/*
	 * svc_create creates the svc_serv with sv_nrthreads == 1, and then
	 * svc_prepare_thread increments that. So we need to call svc_destroy
	 * on both success and failure so that the refcount is 1 when the
	 * thread exits.
	 */
err_net:
	svc_destroy(serv);
err_create:
	mutex_unlock(&nfs_callback_mutex);
	return ret;

err_start:
	nfs_callback_down_net(minorversion, serv, net);
	dprintk("NFS: Couldn't create server thread; err = %d\n", ret);
	goto err_net;
}

/*
 * Kill the callback thread if it's no longer being used.
 */
void nfs_callback_down(int minorversion, struct net *net)
{
	struct nfs_callback_data *cb_info = &nfs_callback_info[minorversion];

	mutex_lock(&nfs_callback_mutex);
	nfs_callback_down_net(minorversion, cb_info->serv, net);
	cb_info->users--;
	if (cb_info->users == 0 && cb_info->task != NULL) {
		kthread_stop(cb_info->task);
		dprintk("nfs_callback_down: service stopped\n");
		svc_exit_thread(cb_info->rqst);
		dprintk("nfs_callback_down: service destroyed\n");
		cb_info->serv = NULL;
		cb_info->rqst = NULL;
		cb_info->task = NULL;
	}
	mutex_unlock(&nfs_callback_mutex);
}

/* Boolean check of RPC_AUTH_GSS principal */
int
check_gss_callback_principal(struct nfs_client *clp, struct svc_rqst *rqstp)
{
	char *p = rqstp->rq_cred.cr_principal;

	if (rqstp->rq_authop->flavour != RPC_AUTH_GSS)
		return 1;

	/* No RPC_AUTH_GSS on NFSv4.1 back channel yet */
	if (clp->cl_minorversion != 0)
		return 0;
	/*
	 * It might just be a normal user principal, in which case
	 * userspace won't bother to tell us the name at all.
	 */
	if (p == NULL)
		return 0;

	/* Expect a GSS_C_NT_HOSTBASED_NAME like "nfs@serverhostname" */

	if (memcmp(p, "nfs@", 4) != 0)
		return 0;
	p += 4;
	if (strcmp(p, clp->cl_hostname) != 0)
		return 0;
	return 1;
}

/*
 * pg_authenticate method for nfsv4 callback threads.
 *
 * The authflavor has been negotiated, so an incorrect flavor is a server
 * bug. Drop packets with incorrect authflavor.
 *
 * All other checking done after NFS decoding where the nfs_client can be
 * found in nfs4_callback_compound
 */
static int nfs_callback_authenticate(struct svc_rqst *rqstp)
{
	switch (rqstp->rq_authop->flavour) {
	case RPC_AUTH_NULL:
		if (rqstp->rq_proc != CB_NULL)
			return SVC_DROP;
		break;
	case RPC_AUTH_GSS:
		/* No RPC_AUTH_GSS support yet in NFSv4.1 */
		 if (svc_is_backchannel(rqstp))
			return SVC_DROP;
	}
	return SVC_OK;
}

/*
 * Define NFS4 callback program
 */
static struct svc_version *nfs4_callback_version[] = {
	[1] = &nfs4_callback_version1,
	[4] = &nfs4_callback_version4,
};

static struct svc_stat nfs4_callback_stats;

static struct svc_program nfs4_callback_program = {
	.pg_prog = NFS4_CALLBACK,			/* RPC service number */
	.pg_nvers = ARRAY_SIZE(nfs4_callback_version),	/* Number of entries */
	.pg_vers = nfs4_callback_version,		/* version table */
	.pg_name = "NFSv4 callback",			/* service name */
	.pg_class = "nfs",				/* authentication class */
	.pg_stats = &nfs4_callback_stats,
	.pg_authenticate = nfs_callback_authenticate,
};