text:
package com.example.balinator.androidprojekt;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.TextView;

import com.example.balinator.androidprojekt.database.Database;
import com.example.balinator.androidprojekt.services.screenonservice.MyScreenOnOffReciver;
import com.example.balinator.androidprojekt.services.screenonservice.MyScreenOnService;
import com.example.balinator.androidprojekt.services.struct.MyService;

import java.util.ArrayList;

/**
 * Created by Balinator on 2016. 12. 12..
 */
public class MyAdapter extends BaseAdapter {
    private static final String tag = "BaseAdapter";

    private ArrayList<MyService> mData = new ArrayList<>();
    private LayoutInflater mInflater;
    private Database db;
    private Context context;

    public MyAdapter(Context context) {
        this.context = context;
        mInflater = LayoutInflater.from(context);
        db = new Database(context);
        refreshItems();
    }

    public void refreshItems() {
        mData = new ArrayList<>();
        db.open();
        for(MyService s: db.getAllService()){
            mData.add(s);
        }
        db.close();
        notifyDataSetChanged();
    }

    @Override
    public int getItemViewType(int position) {
        return 0;
    }

    @Override
    public int getViewTypeCount() {
        return 1;
    }

    @Override
    public int getCount() {
        return mData.size();
    }

    @Override
    public MyService getItem(int position) {
        return mData.get(position);
    }

    @Override
    public long getItemId(int position) {
        return mData.get(position).getId();
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        final MyService service = mData.get(position);
        if (convertView == null) {
            holder = new ViewHolder();

            convertView = mInflater.inflate(R.layout.main_list_adapter, null);
            holder.title = (TextView)convertView.findViewById(R.id.main_list_view_item_title);
            holder.description = (TextView)convertView.findViewById(R.id.main_list_view_item_description);
            holder.aSwitch = (Switch)convertView.findViewById(R.id.main_list_view_item_switch);

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder)convertView.getTag();
        }
        holder.title.setText(service.getName());
        holder.description.setText(service.getDescription());
        holder.aSwitch.setChecked(service.isFavorite());
        holder.aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                db.open();
                db.updateService(service.getId(),service.getName(),service.getDescription(),toInt(isChecked));
                db.close();
                notifyDataset();
                MainActivity.updateMyWidgets(context);
            }

            private int toInt(boolean isChecked) {
                if (!isChecked) {
                    return 0;
                }
                return 1;
            }
        });

        holder.description.setTextColor(Color.BLACK);
        holder.title.setTextColor(Color.BLACK);
        return convertView;
    }

    private void notifyDataset() {
        Intent intent = new Intent("UPDATE_DATASET");

        context.sendBroadcast(intent);
    }

    private static class ViewHolder {
        private TextView title;
        private TextView description;
        private Switch aSwitch;
    }
}


text:
permalink: /
title: ""
excerpt: "About me"
author_profile: true
redirect_from:
  - /about/
  - /about.html
---
{% comment %} {% endcomment %}

My research is focused on genomics and computing, with emphasis on variant and copy number analysis, gene expression, microbiome and proteomics studies. I am also interested in Big data analytics in medicine and healthcare with real-time data processing, messaging and streaming techniques. Ongoing projects in this area include disease modeling using Induced pluripotent stem cells (iPSCs) of Lesch-Nyhan disease and DYT1 dystonia (Hess-Jinnah Research Group).

NEWS

2022

Abnormalities of Neural Stem Cells in Lesch-Nyhan Disease published in Journal of Neurogenetics.

Uric Acid in Parkinsons Disease: What Is the Connection? published in Movement Disorders.

2021

Induced Pluripotent Stem Cells from Subjects with Lesch-Nyhan Disease published in Scientific Reports.

Differential expression of striatal proteins in a mouse model of DOPA-responsive dystonia reveals shared mechanisms among dystonic disorders published in Molecular Genetics and Metabolism.

{% comment%}
I have migrated most of my content to my new website: [https://sys4seq.com](https://sys4seq.com).

Previously, at Emory Vaccine Center, I worked in [Human Immunology Project Consortium](https://www.immuneprofiling.org/) projects with emphasis in understanding the effects of adjuvanted seasonal flu vaccination in healthy as well as in HIV-infected individuals. At University of Florida, I applied systems biology approaches to study the effects of recreational marijuana and/or tobacco use in HIV-infected young adults. At University of California San Diego, I worked for [LIPID MAPS](http://www.lipidmaps.org) and UCSD [Signaling Gateway consortium](http://www.signalinggateway.org/molecule/) projects.
{% endcomment %}

{% comment %}
![Lesch-Nyhan-Disease](/images/illustration1.png)

* _Signatures of somatic mutations from HPV-positive head and neck squamous cell carcinomas (HNSCC)_
Human papilloma virus (HPV) causes a subset of HNSCC of the oropharynx. We combined DNA-Seq and RNA-Seq data to identify genetic variants and gene expression signatures respectively from patients with HNSCC including oropharyngeal squamous cell carcinomas (OPSCC).
![/cancer_mutations](/images/illustration2.png)
* _Rectal microbiome composition correlates with humoral immunity to HIV-1 in vaccinated rhesus macaques_
We assessed the longitudinal changes in vaginal and rectal microbiome profiles following intradermal immunization with an HIV-1 DNA vaccine in adult rhesus macaques that received two prior DNA primes. The rectal and vaginal (CVL) microbiota showed compositional differences at lower taxonomic levels. As demonstrated by the linear discriminant analysis effect size (LEfSe) plot, microbiome in vaginal and rectal compartments demonstrated characteristic phylotype abundances.
![/cladogram](/images/illustration3.png)
{% endcomment %}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <title>Line Charts</title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="css/styles.css">

First, choose a financial institution

              <input class="sans" id="bank-name" name="bank-name" type="text" />

Now, choose a type of application

            <select class="sans" id="loan-type" name="loan-type">
              <option>
                Choose a type
              </option>
              <option value="all">
                All
              </option>
              <option value="single-family">
                Single Family Originations
              </option>
              <option value="single-family-black">
                Single Family Originations - Black
              </option>
              <option value="single-family-white">
                Single Family Originations - White
              </option>
              <option value="home-improvement">
                Home Improvement
              </option>
              <option value="refi">
                Refinance
              </option>
              <option value="purchased-loan">
                Purchased Loans
              </option>
              <option value="denials">
                Denials
              </option>
              <option value="denials-black">
                Denials - Black
              </option>
              <option value="denials-white">
                Denials - White
              </option>
            </select>

Finally, choose a location

            <select class="sans" id="bank-location"></select>

            <hgroup class="col-x-large-11" id="container-heading">

Financial Institution

Application Type

Location

            </hgroup>

              Toggle between: Count and Application Amount


text:
package org.aikodi.jlo.model.expression;

import java.util.ArrayList;
import java.util.List;

import org.aikodi.chameleon.core.declaration.Declaration;
import org.aikodi.chameleon.core.declaration.DeclarationContainer;
import org.aikodi.chameleon.core.declaration.Signature;
import org.aikodi.chameleon.core.lookup.DeclarationSelector;
import org.aikodi.chameleon.core.lookup.LookupException;
import org.aikodi.chameleon.core.lookup.SelectionResult;
import org.aikodi.chameleon.core.reference.NameReference;
import org.aikodi.chameleon.core.relation.WeakPartialOrder;
import org.aikodi.chameleon.oo.expression.Expression;
import org.aikodi.chameleon.oo.expression.MethodInvocation;
import org.aikodi.chameleon.oo.language.ObjectOrientedLanguage;
import org.aikodi.chameleon.oo.language.ObjectOrientedLanguageImpl;
import org.aikodi.chameleon.oo.member.MoreSpecificTypesOrder;
import org.aikodi.chameleon.oo.member.SignatureWithParameters;
import org.aikodi.chameleon.oo.method.Method;
import org.aikodi.chameleon.oo.type.Type;
import org.aikodi.chameleon.support.member.simplename.method.NormalMethod;
import org.aikodi.jlo.model.subobject.Subobject;
import org.aikodi.rejuse.logic.ternary.Ternary;

public class SubobjectConstructorCall extends MethodInvocation<NormalMethod> {

  public SubobjectConstructorCall(NameReference<Subobject> subobjectTarget) {
  	super(subobjectTarget);
  }

  public SubobjectConstructorCall(NameReference<Subobject> subobjectTarget, List<Expression> arguments) {
  	super(subobjectTarget);
  	addAllArguments(arguments);
  }

  public SubobjectConstructorCall(String subobjectName) {
  	super(new NameReference<Subobject>(subobjectName, Subobject.class));
  }

  public SubobjectConstructorCall(String subobjectName, List<Expression> arguments) {
  	super(new NameReference<Subobject>(subobjectName, Subobject.class));
  	addAllArguments(arguments);
  }

  /**
   * @{inheritDoc}
   */
  @Override
  public Class<NormalMethod> referencedType() {
    return NormalMethod.class;
  }

  @Override
  public NameReference<Subobject> getTarget() {
  	return (NameReference<Subobject>) super.getTarget();
  }

	@Override
	protected SubobjectConstructorCall cloneSelf() {
		SubobjectConstructorCall result = new SubobjectConstructorCall((NameReference)null);
		//FIXME This is a hack iirc. Remove it!
		result.setOrigin(this);
		return result;
	}

	@Override
	public DeclarationSelector<NormalMethod> createSelector() {
		return new ConstructorSelector();
	}

	@Override
	protected Type actualType() throws LookupException {
		return language(ObjectOrientedLanguage.class).voidType(view().namespace());
	}

  public class ConstructorSelector implements DeclarationSelector<NormalMethod> {

  	//must create method selection result.

    protected class SubobjectConstructorSelectionResult implements SelectionResult {
			private final Declaration _declaration;

			protected SubobjectConstructorSelectionResult(Declaration declaration) {
				this._declaration = declaration;
			}

			@Override
			public Declaration finalDeclaration() {
				return _declaration;
			}

			@Override
			public SelectionResult updatedTo(Declaration declaration) {
				return new SubobjectConstructorSelectionResult(declaration);
			}

			@Override
			public Declaration template() {
				return finalDeclaration();
			}
		}

		public boolean selectedRegardlessOfName(NormalMethod declaration) throws LookupException {
    	return declaration.isTrue(language(ObjectOrientedLanguage.class).CONSTRUCTOR());
    }

    public List<? extends SelectionResult<NormalMethod>> selection(List<? extends Declaration> declarators) throws LookupException {
    	List<SelectionResult<NormalMethod>> tmp = new ArrayList<SelectionResult<NormalMethod>>();
    	for(Declaration decl: declarators) {
    		SelectionResult<NormalMethod> e = selection(decl);
    		if(e != null) {
    			tmp.add(e);
    		}
    	}
    	applyOrder(tmp);
      return tmp;
    }

    protected SelectionResult selection(Declaration declarator) throws LookupException {
    	// We first perform the checks on the selectionDeclaration, since a signature check may be
    	// very expensive.
    	SelectionResult result = null;
    	if(selectedBasedOnName(declarator.signature())) {
    		Declaration selectionDeclaration = declarator.selectionDeclaration();
    		if(canSelect(selectionDeclaration.getClass())) {
    			if(selectedRegardlessOfName((NormalMethod)selectionDeclaration)) {
    				result = createSelectionResult(selectionDeclaration.actualDeclaration());
    			}
    		}
    	}
    	return result;
    }

    protected SelectionResult createSelectionResult(final Declaration declaration) {
    	return new SubobjectConstructorSelectionResult(declaration);
    }

		private boolean selectedBasedOnName(Signature signature) throws LookupException {
    	boolean result = false;
			if(signature instanceof SignatureWithParameters) {
				List<Type> actuals = getActualParameterTypes();
				List<Type> formals = ((SignatureWithParameters)signature).parameterTypes();
				if (MoreSpecificTypesOrder.create().contains(actuals, formals)) {
						result = true;
				}
			}
      return result;
		}

    public WeakPartialOrder<SelectionResult> order() {
      return new WeakPartialOrder<SelectionResult>() {
        @Override
        public boolean contains(SelectionResult first, SelectionResult second)
            throws LookupException {
          return MoreSpecificTypesOrder.create().contains(((Method)first.finalDeclaration()).header().formalParameterTypes(), ((Method)second.finalDeclaration()).header().formalParameterTypes());
        }
      };
    }

		@Override
		public String selectionName(DeclarationContainer container) throws LookupException {
			// FIXME: this is horribly inefficient, but otherwise we must add more redundancy
			//        in the source code.
			return getTarget().getElement().componentType().signature().name();
		}

		protected void applyOrder(List<SelectionResult<NormalMethod>> tmp) throws LookupException {
			order().removeBiggerElements((List)tmp);
		}

		@Override
		public boolean canSelect(Class<? extends Declaration> type) {
			return NormalMethod.class.isAssignableFrom(type);
		}

  }
}


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

import com.facebook.presto.spi.ConnectorSession;
import com.facebook.presto.spi.type.Type;
import com.facebook.presto.sql.planner.PlanNodeIdAllocator;
import com.facebook.presto.sql.planner.Symbol;
import com.facebook.presto.sql.planner.SymbolAllocator;
import com.facebook.presto.sql.planner.plan.AggregationNode;
import com.facebook.presto.sql.planner.plan.DistinctLimitNode;
import com.facebook.presto.sql.planner.plan.LimitNode;
import com.facebook.presto.sql.planner.plan.MarkDistinctNode;
import com.facebook.presto.sql.planner.plan.PlanNode;
import com.facebook.presto.sql.planner.plan.PlanNodeRewriter;
import com.facebook.presto.sql.planner.plan.PlanRewriter;
import com.facebook.presto.sql.planner.plan.ProjectNode;
import com.facebook.presto.sql.planner.plan.SemiJoinNode;
import com.facebook.presto.sql.planner.plan.SortNode;
import com.facebook.presto.sql.planner.plan.TopNNode;
import com.facebook.presto.sql.planner.plan.UnionNode;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

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

public class LimitPushDown
        extends PlanOptimizer
{
    @Override
    public PlanNode optimize(PlanNode plan, ConnectorSession session, Map<Symbol, Type> types, SymbolAllocator symbolAllocator, PlanNodeIdAllocator idAllocator)
    {
        checkNotNull(plan, "plan is null");
        checkNotNull(session, "session is null");
        checkNotNull(types, "types is null");
        checkNotNull(symbolAllocator, "symbolAllocator is null");
        checkNotNull(idAllocator, "idAllocator is null");

        return PlanRewriter.rewriteWith(new Rewriter(idAllocator), plan, null);
    }

    private static class LimitContext
    {
        private final long count;

        public LimitContext(long count)
        {
            this.count = count;
        }

        public long getCount()
        {
            return count;
        }
    }

    private static class Rewriter
            extends PlanNodeRewriter<LimitContext>
    {
        private final PlanNodeIdAllocator idAllocator;

        private Rewriter(PlanNodeIdAllocator idAllocator)
        {
            this.idAllocator = checkNotNull(idAllocator, "idAllocator is null");
        }

        @Override
        public PlanNode rewriteNode(PlanNode node, LimitContext context, PlanRewriter<LimitContext> planRewriter)
        {
            PlanNode rewrittenNode = planRewriter.defaultRewrite(node, null);
            if (context != null) {
                // Drop in a LimitNode b/c we cannot push our limit down any further
                rewrittenNode = new LimitNode(idAllocator.getNextId(), rewrittenNode, context.getCount());
            }
            return rewrittenNode;
        }

        @Override
        public PlanNode rewriteLimit(LimitNode node, LimitContext context, PlanRewriter<LimitContext> planRewriter)
        {
            if (context != null && context.getCount() < node.getCount()) {
                return planRewriter.rewrite(node.getSource(), context);
            }
            else {
                return planRewriter.rewrite(node.getSource(), new LimitContext(node.getCount()));
            }
        }

        @Override
        public PlanNode rewriteAggregation(AggregationNode node, LimitContext context, PlanRewriter<LimitContext> planRewriter)
        {
            if (context != null &&
                    node.getAggregations().isEmpty() &&
                    node.getOutputSymbols().size() == node.getGroupBy().size() &&
                    node.getOutputSymbols().containsAll(node.getGroupBy())) {
                checkArgument(!node.getSampleWeight().isPresent(), "DISTINCT aggregation has sample weight symbol");
                PlanNode rewrittenSource = planRewriter.rewrite(node.getSource(), null);
                return new DistinctLimitNode(idAllocator.getNextId(), rewrittenSource, context.getCount());
            }
            PlanNode rewrittenNode = planRewriter.defaultRewrite(node, null);
            if (context != null) {
                // Drop in a LimitNode b/c limits cannot be pushed through aggregations
                rewrittenNode = new LimitNode(idAllocator.getNextId(), rewrittenNode, context.getCount());
            }
            return rewrittenNode;
        }

        @Override
        public PlanNode rewriteMarkDistinct(MarkDistinctNode node, LimitContext context, PlanRewriter<LimitContext> planRewriter)
        {
            return planRewriter.defaultRewrite(node, context);
        }

        @Override
        public PlanNode rewriteProject(ProjectNode node, LimitContext context, PlanRewriter<LimitContext> planRewriter)
        {
            return planRewriter.defaultRewrite(node, context);
        }

        @Override
        public PlanNode rewriteTopN(TopNNode node, LimitContext context, PlanRewriter<LimitContext> planRewriter)
        {
            PlanNode rewrittenSource = planRewriter.rewrite(node.getSource(), null);
            if (rewrittenSource == node.getSource() && context == null) {
                return node;
            }

            long count = node.getCount();
            if (context != null) {
                count = Math.min(count, context.getCount());
            }
            return new TopNNode(node.getId(), rewrittenSource, count, node.getOrderBy(), node.getOrderings(), node.isPartial());
        }

        @Override
        public PlanNode rewriteSort(SortNode node, LimitContext context, PlanRewriter<LimitContext> planRewriter)
        {
            PlanNode rewrittenSource = planRewriter.rewrite(node.getSource(), null);
            if (context != null) {
                return new TopNNode(node.getId(), rewrittenSource, context.getCount(), node.getOrderBy(), node.getOrderings(), false);
            }
            else if (rewrittenSource != node.getSource()) {
                return new SortNode(node.getId(), rewrittenSource, node.getOrderBy(), node.getOrderings());
            }
            return node;
        }

        @Override
        public PlanNode rewriteUnion(UnionNode node, LimitContext context, PlanRewriter<LimitContext> planRewriter)
        {
            List<PlanNode> sources = new ArrayList<>();
            for (int i = 0; i < node.getSources().size(); i++) {
                sources.add(planRewriter.rewrite(node.getSources().get(i), context));
            }

            PlanNode output = new UnionNode(node.getId(), sources, node.getSymbolMapping());
            if (context != null) {
                output = new LimitNode(idAllocator.getNextId(), output, context.getCount());
            }
            return output;
        }

        @Override
        public PlanNode rewriteSemiJoin(SemiJoinNode node, LimitContext context, PlanRewriter<LimitContext> planRewriter)
        {
            PlanNode source = planRewriter.rewrite(node.getSource(), context);
            if (source != node.getSource()) {
                return new SemiJoinNode(node.getId(), source, node.getFilteringSource(), node.getSourceJoinSymbol(), node.getFilteringSourceJoinSymbol(), node.getSemiJoinOutput());
            }
            return node;
        }
    }
}


text:
package ph.com.gerocode.asplan.controllers;

/**
 * Created by kenta on 03/10/2017.
 */

public class ChatsController {
}


text:
namespace ash {
namespace internal {
namespace {

const int kRootHeight = 600;
const int kRootWidth = 800;

}  // namespace

class MagnificationControllerTest: public test::AshTestBase {
 public:
  MagnificationControllerTest() {}
  virtual ~MagnificationControllerTest() {}

  virtual void SetUp() OVERRIDE {
    AshTestBase::SetUp();
    UpdateDisplay(base::StringPrintf("%dx%d", kRootWidth, kRootHeight));

    aura::Window* root = GetRootWindow();
    gfx::Rect root_bounds(root->bounds());

#if defined(OS_WIN)
    // RootWindow and Display can't resize on Windows Ash.
    // http://crbug.com/165962
    EXPECT_EQ(kRootHeight, root_bounds.height());
    EXPECT_EQ(kRootWidth, root_bounds.width());
#endif
  }

  virtual void TearDown() OVERRIDE {
    AshTestBase::TearDown();
  }

 protected:
  aura::Window* GetRootWindow() const {
    return Shell::GetPrimaryRootWindow();
  }

  std::string GetHostMouseLocation() {
    gfx::Point point;
    GetRootWindow()->GetHost()->QueryMouseLocation(&point);
    return point.ToString();
  }

  ash::MagnificationController* GetMagnificationController() const {
    return ash::Shell::GetInstance()->magnification_controller();
  }

  gfx::Rect GetViewport() const {
    gfx::RectF bounds(0, 0, kRootWidth, kRootHeight);
    GetRootWindow()->layer()->transform().TransformRectReverse(&bounds);
    return gfx::ToEnclosingRect(bounds);
  }

  std::string CurrentPointOfInterest() const {
    return GetMagnificationController()->
        GetPointOfInterestForTesting().ToString();
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(MagnificationControllerTest);
};

TEST_F(MagnificationControllerTest, EnableAndDisable) {
  // Confirms the magnifier is disabled.
  EXPECT_TRUE(GetRootWindow()->layer()->transform().IsIdentity());
  EXPECT_EQ(1.0f, GetMagnificationController()->GetScale());
  EXPECT_EQ("0,0 800x600", GetViewport().ToString());

  // Enables magnifier.
  GetMagnificationController()->SetEnabled(true);
  EXPECT_FALSE(GetRootWindow()->layer()->transform().IsIdentity());
  EXPECT_EQ(2.0f, GetMagnificationController()->GetScale());
  EXPECT_EQ("200,150 400x300", GetViewport().ToString());

  // Disables magnifier.
  GetMagnificationController()->SetEnabled(false);
  EXPECT_TRUE(GetRootWindow()->layer()->transform().IsIdentity());
  EXPECT_EQ(1.0f, GetMagnificationController()->GetScale());
  EXPECT_EQ("0,0 800x600", GetViewport().ToString());

  // Confirms the the scale can't be changed.
  GetMagnificationController()->SetScale(4.0f, false);
  EXPECT_TRUE(GetRootWindow()->layer()->transform().IsIdentity());
  EXPECT_EQ(1.0f, GetMagnificationController()->GetScale());
  EXPECT_EQ("0,0 800x600", GetViewport().ToString());
}

TEST_F(MagnificationControllerTest, MagnifyAndUnmagnify) {
  // Enables magnifier and confirms the default scale is 2.0x.
  GetMagnificationController()->SetEnabled(true);
  EXPECT_FALSE(GetRootWindow()->layer()->transform().IsIdentity());
  EXPECT_EQ(2.0f, GetMagnificationController()->GetScale());
  EXPECT_EQ("200,150 400x300", GetViewport().ToString());
  EXPECT_EQ("400,300", CurrentPointOfInterest());

  // Changes the scale.
  GetMagnificationController()->SetScale(4.0f, false);
  EXPECT_EQ(4.0f, GetMagnificationController()->GetScale());
  EXPECT_EQ("300,225 200x150", GetViewport().ToString());
  EXPECT_EQ("400,300", CurrentPointOfInterest());

  GetMagnificationController()->SetScale(1.0f, false);
  EXPECT_EQ(1.0f, GetMagnificationController()->GetScale());
  EXPECT_EQ("0,0 800x600", GetViewport().ToString());
  EXPECT_EQ("400,300", CurrentPointOfInterest());

  GetMagnificationController()->SetScale(3.0f, false);
  EXPECT_EQ(3.0f, GetMagnificationController()->GetScale());
  EXPECT_EQ("266,200 267x200", GetViewport().ToString());
  EXPECT_EQ("400,300", CurrentPointOfInterest());
}

TEST_F(MagnificationControllerTest, MoveWindow) {
  // Enables magnifier and confirm the viewport is at center.
  GetMagnificationController()->SetEnabled(true);
  EXPECT_EQ(2.0f, GetMagnificationController()->GetScale());
  EXPECT_EQ("200,150 400x300", GetViewport().ToString());

  // Move the viewport.
  GetMagnificationController()->MoveWindow(0, 0, false);
  EXPECT_EQ("0,0 400x300", GetViewport().ToString());

  GetMagnificationController()->MoveWindow(200, 300, false);
  EXPECT_EQ("200,300 400x300", GetViewport().ToString());

  GetMagnificationController()->MoveWindow(400, 0, false);
  EXPECT_EQ("400,0 400x300", GetViewport().ToString());

  GetMagnificationController()->MoveWindow(400, 300, false);
  EXPECT_EQ("400,300 400x300", GetViewport().ToString());

  // Confirms that the viewport can't across the top-left border.
  GetMagnificationController()->MoveWindow(-100, 0, false);
  EXPECT_EQ("0,0 400x300", GetViewport().ToString());

  GetMagnificationController()->MoveWindow(0, -100, false);
  EXPECT_EQ("0,0 400x300", GetViewport().ToString());

  GetMagnificationController()->MoveWindow(-100, -100, false);
  EXPECT_EQ("0,0 400x300", GetViewport().ToString());

  // Confirms that the viewport can't across the bittom-right border.
  GetMagnificationController()->MoveWindow(800, 0, false);
  EXPECT_EQ("400,0 400x300", GetViewport().ToString());

  GetMagnificationController()->MoveWindow(0, 400, false);
  EXPECT_EQ("0,300 400x300", GetViewport().ToString());

  GetMagnificationController()->MoveWindow(200, 400, false);
  EXPECT_EQ("200,300 400x300", GetViewport().ToString());

  GetMagnificationController()->MoveWindow(1000, 1000, false);
  EXPECT_EQ("400,300 400x300", GetViewport().ToString());
}

TEST_F(MagnificationControllerTest, PointOfInterest) {
  aura::test::EventGenerator generator(Shell::GetPrimaryRootWindow());

  generator.MoveMouseToInHost(gfx::Point(0, 0));
  EXPECT_EQ("0,0", CurrentPointOfInterest());

  generator.MoveMouseToInHost(gfx::Point(799, 599));
  EXPECT_EQ("799,599", CurrentPointOfInterest());

  generator.MoveMouseToInHost(gfx::Point(400, 300));
  EXPECT_EQ("400,300", CurrentPointOfInterest());

  GetMagnificationController()->SetEnabled(true);
  EXPECT_EQ("400,300", CurrentPointOfInterest());

  generator.MoveMouseToInHost(gfx::Point(500, 400));
  EXPECT_EQ("450,350", CurrentPointOfInterest());
}

TEST_F(MagnificationControllerTest, PanWindow2xLeftToRight) {
  const aura::Env* env = aura::Env::GetInstance();
  aura::test::EventGenerator generator(Shell::GetPrimaryRootWindow());

  generator.MoveMouseToInHost(gfx::Point(0, 0));
  EXPECT_EQ(1.f, GetMagnificationController()->GetScale());
  EXPECT_EQ("0,0 800x600", GetViewport().ToString());
  EXPECT_EQ("0,0", env->last_mouse_location().ToString());

  // Enables magnifier and confirm the viewport is at center.
  GetMagnificationController()->SetEnabled(true);
  EXPECT_EQ(2.0f, GetMagnificationController()->GetScale());

  GetMagnificationController()->MoveWindow(0, 0, false);
  generator.MoveMouseToInHost(gfx::Point(0, 0));
  EXPECT_EQ("0,0", env->last_mouse_location().ToString());
  EXPECT_EQ("0,0 400x300", GetViewport().ToString());

  generator.MoveMouseToInHost(gfx::Point(300, 150));
  EXPECT_EQ("150,75", env->last_mouse_location().ToString());
  EXPECT_EQ("0,0 400x300", GetViewport().ToString());

  generator.MoveMouseToInHost(gfx::Point(700, 150));
  EXPECT_EQ("350,75", env->last_mouse_location().ToString());
  EXPECT_EQ("0,0 400x300", GetViewport().ToString());

  generator.MoveMouseToInHost(gfx::Point(701, 150));
  EXPECT_EQ("350,75", env->last_mouse_location().ToString());
  EXPECT_EQ("0,0 400x300", GetViewport().ToString());

  generator.MoveMouseToInHost(gfx::Point(702, 150));
  EXPECT_EQ("351,75", env->last_mouse_location().ToString());
  EXPECT_EQ("1,0 400x300", GetViewport().ToString());

  generator.MoveMouseToInHost(gfx::Point(703, 150));
  EXPECT_EQ("352,75", env->last_mouse_location().ToString());
  EXPECT_EQ("2,0 400x300", GetViewport().ToString());

  generator.MoveMouseToInHost(gfx::Point(704, 150));
  EXPECT_EQ("354,75", env->last_mouse_location().ToString());
  EXPECT_EQ("4,0 400x300", GetViewport().ToString());

  generator.MoveMouseToInHost(gfx::Point(712, 150));
  EXPECT_EQ("360,75", env->last_mouse_location().ToString());
  EXPECT_EQ("10,0 400x300", GetViewport().ToString());

  generator.MoveMouseToInHost(gfx::Point(600, 150));
  EXPECT_EQ("310,75", env->last_mouse_location().ToString());
  EXPECT_EQ("10,0 400x300", GetViewport().ToString());

  generator.MoveMouseToInHost(gfx::Point(720, 150));
  EXPECT_EQ("370,75", env->last_mouse_location().ToString());
  EXPECT_EQ("20,0 400x300", GetViewport().ToString());

  generator.MoveMouseToInHost(gfx::Point(780, 150));
  EXPECT_EQ("410,75", env->last_mouse_location().ToString());
  EXPECT_EQ("410,75", CurrentPointOfInterest());
  EXPECT_EQ("60,0 400x300", GetViewport().ToString());

  generator.MoveMouseToInHost(gfx::Point(799, 150));
  EXPECT_EQ("459,75", env->last_mouse_location().ToString());
  EXPECT_EQ("109,0 400x300", GetViewport().ToString());

  generator.MoveMouseToInHost(gfx::Point(702, 150));
  EXPECT_EQ("460,75", env->last_mouse_location().ToString());
  EXPECT_EQ("110,0 400x300", GetViewport().ToString());

  generator.MoveMouseToInHost(gfx::Point(780, 150));
  EXPECT_EQ("500,75", env->last_mouse_location().ToString());
  EXPECT_EQ("150,0 400x300", GetViewport().ToString());

  generator.MoveMouseToInHost(gfx::Point(780, 150));
  EXPECT_EQ("540,75", env->last_mouse_location().ToString());
  EXPECT_EQ("190,0 400x300", GetViewport().ToString());

  generator.MoveMouseToInHost(gfx::Point(780, 150));
  EXPECT_EQ("580,75", env->last_mouse_location().ToString());
  EXPECT_EQ("230,0 400x300", GetViewport().ToString());

  generator.MoveMouseToInHost(gfx::Point(780, 150));
  EXPECT_EQ("620,75", env->last_mouse_location().ToString());
  EXPECT_EQ("270,0 400x300", GetViewport().ToString());

  generator.MoveMouseToInHost(gfx::Point(780, 150));
  EXPECT_EQ("660,75", env->last_mouse_location().ToString());
  EXPECT_EQ("310,0 400x300", GetViewport().ToString());

  generator.MoveMouseToInHost(gfx::Point(780, 150));
  EXPECT_EQ("700,75", env->last_mouse_location().ToString());
  EXPECT_EQ("350,0 400x300", GetViewport().ToString());

  generator.MoveMouseToInHost(gfx::Point(780, 150));
  EXPECT_EQ("740,75", env->last_mouse_location().ToString());
  EXPECT_EQ("390,0 400x300", GetViewport().ToString());

  generator.MoveMouseToInHost(gfx::Point(780, 150));
  EXPECT_EQ("780,75", env->last_mouse_location().ToString());
  EXPECT_EQ("400,0 400x300", GetViewport().ToString());

  generator.MoveMouseToInHost(gfx::Point(799, 150));
  EXPECT_EQ("799,75", env->last_mouse_location().ToString());
  EXPECT_EQ("400,0 400x300", GetViewport().ToString());
}

TEST_F(MagnificationControllerTest, PanWindow2xRightToLeft) {
  const aura::Env* env = aura::Env::GetInstance();
  aura::test::EventGenerator generator(Shell::GetPrimaryRootWindow());

  generator.MoveMouseToInHost(gfx::Point(799, 300));
  EXPECT_EQ(1.f, GetMagnificationController()->GetScale());
  EXPECT_EQ("0,0 800x600", GetViewport().ToString());
  EXPECT_EQ("799,300", env->last_mouse_location().ToString());

  // Enables magnifier and confirm the viewport is at center.
  GetMagnificationController()->SetEnabled(true);

  generator.MoveMouseToInHost(gfx::Point(799, 300));
  EXPECT_EQ("798,300", env->last_mouse_location().ToString());
  EXPECT_EQ("400,150 400x300", GetViewport().ToString());

  generator.MoveMouseToInHost(gfx::Point(0, 300));
  EXPECT_EQ("400,300", env->last_mouse_location().ToString());
  EXPECT_EQ("350,150 400x300", GetViewport().ToString());

  generator.MoveMouseToInHost(gfx::Point(0, 300));
  EXPECT_EQ("350,300", env->last_mouse_location().ToString());
  EXPECT_EQ("300,150 400x300", GetViewport().ToString());

  generator.MoveMouseToInHost(gfx::Point(0, 300));
  EXPECT_EQ("300,300", env->last_mouse_location().ToString());
  EXPECT_EQ("250,150 400x300", GetViewport().ToString());

  generator.MoveMouseToInHost(gfx::Point(0, 300));
  EXPECT_EQ("250,300", env->last_mouse_location().ToString());
  EXPECT_EQ("200,150 400x300", GetViewport().ToString());

  generator.MoveMouseToInHost(gfx::Point(0, 300));
  EXPECT_EQ("200,300", env->last_mouse_location().ToString());
  EXPECT_EQ("150,150 400x300", GetViewport().ToString());

  generator.MoveMouseToInHost(gfx::Point(0, 300));
  EXPECT_EQ("150,300", env->last_mouse_location().ToString());
  EXPECT_EQ("100,150 400x300", GetViewport().ToString());

  generator.MoveMouseToInHost(gfx::Point(0, 300));
  EXPECT_EQ("100,300", env->last_mouse_location().ToString());
  EXPECT_EQ("50,150 400x300", GetViewport().ToString());

  generator.MoveMouseToInHost(gfx::Point(0, 300));
  EXPECT_EQ("50,300", env->last_mouse_location().ToString());
  EXPECT_EQ("0,150 400x300", GetViewport().ToString());

  generator.MoveMouseToInHost(gfx::Point(0, 300));
  EXPECT_EQ("0,300", env->last_mouse_location().ToString());
  EXPECT_EQ("0,150 400x300", GetViewport().ToString());
}

TEST_F(MagnificationControllerTest, PanWindowToRight) {
  const aura::Env* env = aura::Env::GetInstance();
  aura::test::EventGenerator generator(Shell::GetPrimaryRootWindow());

  generator.MoveMouseToInHost(gfx::Point(400, 300));
  EXPECT_EQ(1.f, GetMagnificationController()->GetScale());
  EXPECT_EQ("0,0 800x600", GetViewport().ToString());
  EXPECT_EQ("400,300", env->last_mouse_location().ToString());

  float scale = 2.f;

  // Enables magnifier and confirm the viewport is at center.
  GetMagnificationController()->SetEnabled(true);
  EXPECT_FLOAT_EQ(2.f, GetMagnificationController()->GetScale());

  scale *= kMagnificationScaleFactor;
  GetMagnificationController()->SetScale(scale, false);
  EXPECT_FLOAT_EQ(2.3784142, GetMagnificationController()->GetScale());
  generator.MoveMouseToInHost(gfx::Point(400, 300));
  EXPECT_EQ("400,300", env->last_mouse_location().ToString());
  generator.MoveMouseToInHost(gfx::Point(799, 300));
  EXPECT_EQ("566,299", env->last_mouse_location().ToString());
  EXPECT_EQ("705,300", GetHostMouseLocation());

  scale *= kMagnificationScaleFactor;
  GetMagnificationController()->SetScale(scale, false);
  EXPECT_FLOAT_EQ(2.8284268, GetMagnificationController()->GetScale());
  generator.MoveMouseToInHost(gfx::Point(799, 300));
  EXPECT_EQ("599,299", env->last_mouse_location().ToString());
  EXPECT_EQ("702,300", GetHostMouseLocation());

  scale *= kMagnificationScaleFactor;
  GetMagnificationController()->SetScale(scale, false);
  EXPECT_FLOAT_EQ(3.3635852, GetMagnificationController()->GetScale());
  generator.MoveMouseToInHost(gfx::Point(799, 300));
  EXPECT_EQ("627,298", env->last_mouse_location().ToString());
  EXPECT_EQ("707,300", GetHostMouseLocation());

  scale *= kMagnificationScaleFactor;
  GetMagnificationController()->SetScale(scale, false);
  EXPECT_FLOAT_EQ(4.f, GetMagnificationController()->GetScale());
  generator.MoveMouseToInHost(gfx::Point(799, 300));
  EXPECT_EQ("649,298", env->last_mouse_location().ToString());
  EXPECT_EQ("704,300", GetHostMouseLocation());
}

TEST_F(MagnificationControllerTest, PanWindowToLeft) {
  const aura::Env* env = aura::Env::GetInstance();
  aura::test::EventGenerator generator(Shell::GetPrimaryRootWindow());

  generator.MoveMouseToInHost(gfx::Point(400, 300));
  EXPECT_EQ(1.f, GetMagnificationController()->GetScale());
  EXPECT_EQ("0,0 800x600", GetViewport().ToString());
  EXPECT_EQ("400,300", env->last_mouse_location().ToString());

  float scale = 2.f;

  // Enables magnifier and confirm the viewport is at center.
  GetMagnificationController()->SetEnabled(true);
  EXPECT_FLOAT_EQ(2.f, GetMagnificationController()->GetScale());

  scale *= kMagnificationScaleFactor;
  GetMagnificationController()->SetScale(scale, false);
  EXPECT_FLOAT_EQ(2.3784142, GetMagnificationController()->GetScale());
  generator.MoveMouseToInHost(gfx::Point(400, 300));
  EXPECT_EQ("400,300", env->last_mouse_location().ToString());
  generator.MoveMouseToInHost(gfx::Point(0, 300));
  EXPECT_EQ("231,299", env->last_mouse_location().ToString());
  EXPECT_EQ("100,300", GetHostMouseLocation());

  scale *= kMagnificationScaleFactor;
  GetMagnificationController()->SetScale(scale, false);
  EXPECT_FLOAT_EQ(2.8284268, GetMagnificationController()->GetScale());
  generator.MoveMouseToInHost(gfx::Point(0, 300));
  EXPECT_EQ("194,299", env->last_mouse_location().ToString());
  EXPECT_EQ("99,300", GetHostMouseLocation());

  scale *= kMagnificationScaleFactor;
  GetMagnificationController()->SetScale(scale, false);
  EXPECT_FLOAT_EQ(3.3635852, GetMagnificationController()->GetScale());
  generator.MoveMouseToInHost(gfx::Point(0, 300));
  EXPECT_EQ("164,298", env->last_mouse_location().ToString());
  EXPECT_EQ("98,300", GetHostMouseLocation());

  scale *= kMagnificationScaleFactor;
  GetMagnificationController()->SetScale(scale, false);
  EXPECT_FLOAT_EQ(4.f, GetMagnificationController()->GetScale());
  generator.MoveMouseToInHost(gfx::Point(0, 300));
  EXPECT_EQ("139,298", env->last_mouse_location().ToString());
  EXPECT_EQ("100,300", GetHostMouseLocation());
}

}  // namespace internal
}  // namespace ash


text:
using System;
using System.Diagnostics.CodeAnalysis;

namespace DasMulli.Win32.ServiceUtils
{
    [Flags]
    [SuppressMessage("ReSharper", "UnusedMember.Global", Justification = "External API")]
    internal enum Win32AccessMask : uint
    {
        Delete = 0x00010000,
        ReadControl = 0x00020000,
        WriteDac = 0x00040000,
        WriteOwner = 0x00080000,
        Synchronize = 0x00100000,

        StandardRightsRequired = 0x000F0000,

        StandardRightsRead = 0x00020000,
        StandardRightsWrite = 0x00020000,
        StandardRightsExecute = 0x00020000,

        StandardRightsAll = 0x001F0000,

        SpecificRightsAll = 0x0000FFFF,

        AccessSystemSecurity = 0x01000000,

        MaximumAllowed = 0x02000000,

        GenericRead = 0x80000000,
        GenericWrite = 0x40000000,
        GenericExecute = 0x20000000,
        GenericAll = 0x10000000,

        DesktopReadobjects = 0x00000001,
        DesktopCreatewindow = 0x00000002,
        DesktopCreatemenu = 0x00000004,
        DesktopHookcontrol = 0x00000008,
        DesktopJournalrecord = 0x00000010,
        DesktopJournalplayback = 0x00000020,
        DesktopEnumerate = 0x00000040,
        DesktopWriteobjects = 0x00000080,
        DesktopSwitchdesktop = 0x00000100,

        WinstaEnumdesktops = 0x00000001,
        WinstaReadattributes = 0x00000002,
        WinstaAccessclipboard = 0x00000004,
        WinstaCreatedesktop = 0x00000008,
        WinstaWriteattributes = 0x00000010,
        WinstaAccessglobalatoms = 0x00000020,
        WinstaExitwindows = 0x00000040,
        WinstaEnumerate = 0x00000100,
        WinstaReadscreen = 0x00000200,

        WinstaAllAccess = 0x0000037F
    }
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.mycompany.rboss.service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;

/**
 *
 * @author ib
 */
public class AuthenticationHandler extends SavedRequestAwareAuthenticationSuccessHandler{
     @Override
    protected String determineTargetUrl(HttpServletRequest request, HttpServletResponse response) {
        // Get the role of logged in user
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        String role = auth.getAuthorities().toString();

        String targetUrl = "";
        if(role.contains("user")) {
            targetUrl = "/index";
        } else if(role.contains("admin")) {
            targetUrl = "/admin/index";
        }
        return targetUrl;
    }
}


text:
module Socialinvestigator
  VERSION = "0.0.6"
end


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

<rootTag>
  <Award>
    <AwardTitle>Workshop to Identify Significant Uncertainties Concerning the Effects of Climate Change and the Antarctic Toothfish Fishery on the Ross Sea Marine Ecosystem</AwardTitle>
    <AwardEffectiveDate>05/01/2012</AwardEffectiveDate>
    <AwardExpirationDate>01/31/2013</AwardExpirationDate>
    <AwardAmount>36791</AwardAmount>
    <AwardInstrument>
      <Value>Standard Grant</Value>
    </AwardInstrument>
    <Organization>
      06090400
      <Directorate>
        <LongName>Directorate For Geosciences</LongName>
      </Directorate>
      <Division>
        <LongName>Division Of Polar Programs</LongName>
      </Division>
    </Organization>
    <ProgramOfficer>
      <SignBlockName>Adrian Dahood</SignBlockName>
    </ProgramOfficer>
    <AbstractNarration>We propose to hold a workshop among experts in Ross Sea, Antarctica, ecology in order to identify<br/>important factors that are likely to be affecting the Ross Sea in the near future, including<br/>both climate and more direct factors such as industrial fishing. On the basis of this information,<br/>a report will be generated concerning how uncertainties in this knowledge can best be addressed,<br/>including the use of technological advances in marine ecology. This information, in turn,<br/>will be used, in part, to adivse the US Department of State on a management plan required<br/>in the designation of the Ross Sea as a marine protected area under the jurisdiction of the<br/>Commission for the Conservation of Antartic Marine Living Resources.</AbstractNarration>
    <MinAmdLetterDate>05/08/2012</MinAmdLetterDate>
    <MaxAmdLetterDate>05/08/2012</MaxAmdLetterDate>
    <ARRAAmount/>
    <AwardID>1237403</AwardID>
    <Investigator>
      <FirstName>David</FirstName>
      <LastName>Ainley</LastName>
      <EmailAddress>dainley@penguinscience.com</EmailAddress>
      <StartDate>05/08/2012</StartDate>
      <EndDate/>
      <RoleCode>Principal Investigator</RoleCode>
    </Investigator>
    <Institution>
      <Name>H.T. Harvey & Associates</Name>
      <CityName>Los Gatos</CityName>
      <ZipCode>950327637</ZipCode>
      <PhoneNumber>4084583223</PhoneNumber>
      <StreetAddress>983 University Avenue</StreetAddress>
      <CountryName>United States</CountryName>
      <StateName>California</StateName>
      <StateCode>CA</StateCode>
    </Institution>
  </Award>
</rootTag>


text:
using System;
using Nest;
using Tests.Framework;
using static Tests.Framework.RoundTripper;
using Tests.Framework.MockData;
using Tests.Framework.Integration;
using System.Collections.Generic;
using Elasticsearch.Net;
using static Nest.Infer;
using Xunit;

namespace Tests.Mapping.Metafields
{
	[Collection(TypeOfCluster.ReadOnly)]
	public abstract class MetafieldsMappingApiTestsBase : ApiTestBase<IPutMappingResponse, IPutMappingRequest, PutMappingDescriptor<Project>, PutMappingRequest<Project>>
	{
		public MetafieldsMappingApiTestsBase(ReadOnlyCluster cluster, EndpointUsage usage) : base(cluster, usage) { }

		protected override LazyResponses ClientUsage() => Calls(
			fluent: (client, f) => client.Map(f),
			fluentAsync: (client, f) => client.MapAsync(f),
			request: (client, r) => client.Map(r),
			requestAsync: (client, r) => client.MapAsync(r)
		);

		protected override HttpMethod HttpMethod => HttpMethod.PUT;
		protected override string UrlPath => $"/{CallIsolatedValue}/project/_mapping";

	}
}


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

#include <gtest/gtest.h>

#include <openssl/crypto.h>
#include <openssl/err.h>
#include <openssl/mem.h>

#include "./internal.h"

#if defined(OPENSSL_WINDOWS)
OPENSSL_MSVC_PRAGMA(warning(push, 3))
#include <windows.h>
OPENSSL_MSVC_PRAGMA(warning(pop))
#else
#include <errno.h>
#endif

TEST(ErrTest, Overflow) {
  for (unsigned i = 0; i < ERR_NUM_ERRORS*2; i++) {
    ERR_put_error(1, 0 /* unused */, i+1, "test", 1);
  }

  for (unsigned i = 0; i < ERR_NUM_ERRORS - 1; i++) {
    SCOPED_TRACE(i);
    uint32_t err = ERR_get_error();
    // Errors are returned in order they were pushed, with the least recent ones
    // removed, up to |ERR_NUM_ERRORS - 1| errors. So the errors returned are
    // |ERR_NUM_ERRORS + 2| through |ERR_NUM_ERRORS * 2|, inclusive.
    EXPECT_NE(0u, err);
    EXPECT_EQ(static_cast<int>(i + ERR_NUM_ERRORS + 2), ERR_GET_REASON(err));
  }

  EXPECT_EQ(0u, ERR_get_error());
}

TEST(ErrTest, PutError) {
  ASSERT_EQ(0u, ERR_get_error())
      << "ERR_get_error returned value before an error was added.";

  ERR_put_error(1, 0 /* unused */, 2, "test", 4);
  ERR_add_error_data(1, "testing");

  int peeked_line, line, peeked_flags, flags;
  const char *peeked_file, *file, *peeked_data, *data;
  uint32_t peeked_packed_error =
      ERR_peek_error_line_data(&peeked_file, &peeked_line, &peeked_data,
                               &peeked_flags);
  uint32_t packed_error = ERR_get_error_line_data(&file, &line, &data, &flags);

  EXPECT_EQ(peeked_packed_error, packed_error);
  EXPECT_EQ(peeked_file, file);
  EXPECT_EQ(peeked_data, data);
  EXPECT_EQ(peeked_flags, flags);

  EXPECT_STREQ("test", file);
  EXPECT_EQ(4, line);
  EXPECT_TRUE(flags & ERR_FLAG_STRING);
  EXPECT_EQ(1, ERR_GET_LIB(packed_error));
  EXPECT_EQ(2, ERR_GET_REASON(packed_error));
  EXPECT_STREQ("testing", data);
}

TEST(ErrTest, ClearError) {
  ASSERT_EQ(0u, ERR_get_error())
      << "ERR_get_error returned value before an error was added.";

  ERR_put_error(1, 0 /* unused */, 2, "test", 4);
  ERR_clear_error();

  // The error queue should be cleared.
  EXPECT_EQ(0u, ERR_get_error());
}

TEST(ErrTest, Print) {
  ERR_put_error(1, 0 /* unused */, 2, "test", 4);
  ERR_add_error_data(1, "testing");
  uint32_t packed_error = ERR_get_error();

  char buf[256];
  for (size_t i = 0; i <= sizeof(buf); i++) {
    ERR_error_string_n(packed_error, buf, i);
  }
}

TEST(ErrTest, Release) {
  ERR_put_error(1, 0 /* unused */, 2, "test", 4);
  ERR_remove_thread_state(NULL);

  // The error queue should be cleared.
  EXPECT_EQ(0u, ERR_get_error());
}

static bool HasSuffix(const char *str, const char *suffix) {
  size_t suffix_len = strlen(suffix);
  size_t str_len = strlen(str);
  if (str_len < suffix_len) {
    return false;
  }
  return strcmp(str + str_len - suffix_len, suffix) == 0;
}

TEST(ErrTest, PutMacro) {
  int expected_line = __LINE__ + 1;
  OPENSSL_PUT_ERROR(USER, ERR_R_INTERNAL_ERROR);

  int line;
  const char *file;
  uint32_t error = ERR_get_error_line(&file, &line);

  EXPECT_PRED2(HasSuffix, file, "err_test.cc");
  EXPECT_EQ(expected_line, line);
  EXPECT_EQ(ERR_LIB_USER, ERR_GET_LIB(error));
  EXPECT_EQ(ERR_R_INTERNAL_ERROR, ERR_GET_REASON(error));
}

TEST(ErrTest, SaveAndRestore) {
  // Restoring no state clears the error queue, including error data.
  ERR_put_error(1, 0 /* unused */, 1, "test1.c", 1);
  ERR_put_error(2, 0 /* unused */, 2, "test2.c", 2);
  ERR_add_error_data(1, "data1");
  ERR_restore_state(nullptr);
  EXPECT_EQ(0u, ERR_get_error());

  // Add some entries to the error queue and save it.
  ERR_put_error(1, 0 /* unused */, 1, "test1.c", 1);
  ERR_add_error_data(1, "data1");
  ERR_put_error(2, 0 /* unused */, 2, "test2.c", 2);
  ERR_put_error(3, 0 /* unused */, 3, "test3.c", 3);
  ERR_add_error_data(1, "data3");
  bssl::UniquePtr<ERR_SAVE_STATE> saved(ERR_save_state());
  ASSERT_TRUE(saved);

  // The existing error queue entries still exist.
  int line, flags;
  const char *file, *data;
  uint32_t packed_error = ERR_get_error_line_data(&file, &line, &data, &flags);
  EXPECT_EQ(ERR_GET_LIB(packed_error), 1);
  EXPECT_EQ(ERR_GET_REASON(packed_error), 1);
  EXPECT_STREQ("test1.c", file);
  EXPECT_EQ(line, 1);
  EXPECT_STREQ(data, "data1");
  EXPECT_EQ(flags, ERR_FLAG_STRING);

  // The state may be restored, both over an empty and non-empty state.
  for (unsigned i = 0; i < 2; i++) {
    SCOPED_TRACE(i);
    ERR_restore_state(saved.get());

    packed_error = ERR_get_error_line_data(&file, &line, &data, &flags);
    EXPECT_EQ(ERR_GET_LIB(packed_error), 1);
    EXPECT_EQ(ERR_GET_REASON(packed_error), 1);
    EXPECT_STREQ("test1.c", file);
    EXPECT_EQ(line, 1);
    EXPECT_STREQ(data, "data1");
    EXPECT_EQ(flags, ERR_FLAG_STRING);

    packed_error = ERR_get_error_line_data(&file, &line, &data, &flags);
    EXPECT_EQ(ERR_GET_LIB(packed_error), 2);
    EXPECT_EQ(ERR_GET_REASON(packed_error), 2);
    EXPECT_STREQ("test2.c", file);
    EXPECT_EQ(line, 2);
    EXPECT_STREQ(data, "");  // No error data is reported as the empty string.
    EXPECT_EQ(flags, 0);

    packed_error = ERR_get_error_line_data(&file, &line, &data, &flags);
    EXPECT_EQ(ERR_GET_LIB(packed_error), 3);
    EXPECT_EQ(ERR_GET_REASON(packed_error), 3);
    EXPECT_STREQ("test3.c", file);
    EXPECT_EQ(line, 3);
    EXPECT_STREQ(data, "data3");
    EXPECT_EQ(flags, ERR_FLAG_STRING);

    // The error queue is now empty for the next iteration.
    EXPECT_EQ(0u, ERR_get_error());
  }

  // Test a case where the error queue wraps around. The first set of errors
  // will all be discarded, but result in wrapping the list around.
  ERR_clear_error();
  for (unsigned i = 0; i < ERR_NUM_ERRORS / 2; i++) {
    ERR_put_error(0, 0 /* unused */, 0, "invalid", 0);
  }
  for (unsigned i = 1; i < ERR_NUM_ERRORS; i++) {
    ERR_put_error(i, 0 /* unused */, i, "test", i);
  }
  saved.reset(ERR_save_state());

  // The state may be restored, both over an empty and non-empty state. Pop one
  // error off so the first iteration is tested to not be a no-op.
  ERR_get_error();
  for (int i = 0; i < 2; i++) {
    SCOPED_TRACE(i);
    ERR_restore_state(saved.get());
    for (int j = 1; j < ERR_NUM_ERRORS; j++) {
      SCOPED_TRACE(j);
      packed_error = ERR_get_error_line_data(&file, &line, &data, &flags);
      EXPECT_EQ(ERR_GET_LIB(packed_error), j);
      EXPECT_EQ(ERR_GET_REASON(packed_error), j);
      EXPECT_STREQ("test", file);
      EXPECT_EQ(line, j);
    }
    // The error queue is now empty for the next iteration.
    EXPECT_EQ(0u, ERR_get_error());
  }
}

// Querying the error queue should not affect the OS error.
#if defined(OPENSSL_WINDOWS)
TEST(ErrTest, PreservesLastError) {
  SetLastError(ERROR_INVALID_FUNCTION);
  ERR_get_error();
  EXPECT_EQ(static_cast<DWORD>(ERROR_INVALID_FUNCTION), GetLastError());
}
#else
TEST(ErrTest, PreservesErrno) {
  errno = EINVAL;
  ERR_get_error();
  EXPECT_EQ(EINVAL, errno);
}
#endif


text:
package com.amazonaws.services.connect.model;

import javax.annotation.Generated;

/**
 * <p>
 * Outbound calls to the destination number are not allowed.
 * </p>
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DestinationNotAllowedException extends com.amazonaws.services.connect.model.AmazonConnectException {
    private static final long serialVersionUID = 1L;

    /**
     * Constructs a new DestinationNotAllowedException with the specified error message.
     *
     * @param message
     *        Describes the error encountered.
     */
    public DestinationNotAllowedException(String message) {
        super(message);
    }

}


text:
@implementation NSString (TTString)

+(NSString *)documentPath {
    static NSString * path = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)
                 objectAtIndex:0] copy];
        [NSString addSkipBackupAttributeToItemAtURL:[NSURL fileURLWithPath:path]];
    });
    return path;
}
+(BOOL)addSkipBackupAttributeToItemAtURL:(NSURL *)URL
{
    if (URL==nil) {
        return NO;
    }
    NSString *systemVersion=[[UIDevice currentDevice] systemVersion];
    float version=[systemVersion floatValue];
    if (version<5.0) {
        return YES;
    }
    if ( version>=5.1) {
        assert([[NSFileManager defaultManager] fileExistsAtPath: [URL path]]);

        NSError *error = nil;
        BOOL success = [URL setResourceValue: [NSNumber numberWithBool: YES]
                                      forKey: NSURLIsExcludedFromBackupKey error: &error];
        if(!success){
        }
        return success;
    }

    if ([systemVersion isEqual:@"5.0"]) {
        return NO;
    }else{
        assert([[NSFileManager defaultManager] fileExistsAtPath: [URL path]]);

        const char* filePath = [[URL path] fileSystemRepresentation];

        const char* attrName = "com.apple.MobileBackup";
        u_int8_t attrValue = 1;

        int result = setxattr(filePath, attrName, &attrValue, sizeof(attrValue), 0, 0);
        return result == 0;
    }
    return YES;
}
+(NSString *)cachePath {
    static NSString * path = nil;
    if (!path) {
        path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)
                 objectAtIndex:0] copy];
    }
    return path;
}

+(NSString *)formatCurrentDate {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *result = [dateFormatter stringFromDate:[NSDate date]];

    return result;
}
+(NSString *)formatCurrentDay {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *result = [dateFormatter stringFromDate:[NSDate date]];

    return result;
}

- (NSURL *) toURL {
    return [NSURL URLWithString:[self stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
}

- (BOOL) isEmpty {
    return nil == self
    || 0 == [[self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length];
}

- (NSString *) MD5 {
    // Create pointer to the string as UTF8
	const char* ptr = [self UTF8String];
	unsigned char md5Buffer[CC_MD5_DIGEST_LENGTH];

	// Create 16 byte MD5 hash value, store in buffer
	CC_MD5(ptr, strlen(ptr), md5Buffer);

	// Convert MD5 value in the buffer to NSString of hex values
	NSMutableString* output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
	for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
		[output appendFormat:@"%02x",md5Buffer[i]];
	}

	return output;
}
-(NSString *)trim{
    return  [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}

- (NSString*)removeAllSpace
{
    NSString* result = [self stringByReplacingOccurrencesOfString:@" " withString:@""];
    result = [result stringByReplacingOccurrencesOfString:@"    " withString:@""];
    return result;
}
@end


text:
<?php

namespace backend\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\Entity;

/**
 * EntitySearch represents the model behind the search form about `app\models\Entity`.
 */
class EntitySearch extends Entity
{
    public function rules()
    {
        return [
            [['id'], 'integer'],
            [['name', 'created', 'modified'], 'safe'],
        ];
    }

    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    public function search($params)
    {
        $query = Entity::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        if (!($this->load($params) && $this->validate())) {
            return $dataProvider;
        }

        $query->andFilterWhere([
            'id' => $this->id,
            'created' => $this->created,
            'modified' => $this->modified,
        ]);

        $query->andFilterWhere(['like', 'name', $this->name]);

        return $dataProvider;
    }
}


text:
#include "grassroots_config.h"
#include "servers_pool.h"
#include "streams.h"
#include "json_util.h"
#include "service_config.h"
#include "string_utils.h"
#include "filesystem_utils.h"
#include "json_tools.h"

static json_t *s_config_p = NULL;
static bool s_load_config_tried_flag = false;

static const json_t *GetConfig (void);
static const char *GetProviderElement (const char * const element_s);
static void InitSchemaVersionDetails (void);

bool InitConfig (void)
{
	InitSchemaVersionDetails ();

	return (GetConfig () != NULL);
}

bool DestroyConfig (void)
{
	bool success_flag = true;

	if (s_config_p)
		{
			WipeJSON (s_config_p);
		}

	return success_flag;
}

json_t *GetGlobalConfigValue (const char *key_s)
{
	json_t *value_p = NULL;
	const json_t *config_p = GetConfig ();

	if (config_p)
		{
			value_p = json_object_get (config_p, key_s);
		}

	return value_p;
}

json_t *GetGlobalServiceConfig (const char * const service_name_s, bool *alloc_flag_p)
{
	json_t *res_p = NULL;
	char *conf_s = NULL;
	char sep_s [2];

	*sep_s = GetFileSeparatorChar ();
	* (sep_s + 1) = '\0';

	*alloc_flag_p = false;

	conf_s = ConcatenateVarargsStrings ("config", sep_s, service_name_s, NULL);

	if (conf_s)
		{
			const char *root_path_s = GetServerRootDirectory ();
			char *full_config_path_s = MakeFilename (root_path_s, conf_s);

			if (full_config_path_s)
				{
					if (IsPathValid (full_config_path_s))
						{
							res_p = LoadJSONFile (full_config_path_s);

							if (res_p)
								{
									*alloc_flag_p = true;
								}
							else
								{
									PrintErrors (STM_LEVEL_SEVERE, __FILE__, __LINE__, "Failed to load config filename for %s", full_config_path_s);
								}
						}
					else
						{
							PrintErrors (STM_LEVEL_FINEST, __FILE__, __LINE__, "Separate config file %s does not exist", full_config_path_s);
						}

					FreeCopiedString (full_config_path_s);
				}		/* if (full_config_path_s) */
			else
				{
					PrintErrors (STM_LEVEL_WARNING, __FILE__, __LINE__, "Failed to create full config filename for %s", conf_s);
				}

			FreeCopiedString (conf_s);
		}		/* if (conf_s) */
	else
		{
			PrintErrors (STM_LEVEL_WARNING, __FILE__, __LINE__, "Failed to create local config filename for %s", service_name_s);
		}

	if (!res_p)
		{
			const json_t *config_p = GetConfig ();

			if (config_p)
				{
					json_t *json_p = json_object_get (config_p, SERVICES_NAME_S);

					if (json_p)
						{
							if (json_is_object (json_p))
								{
									res_p = json_object_get (json_p, service_name_s);
								}		/* if (json_is_object (json_p)) */

						}		/* if (json_p) */

				}		/* if (config_p) */
			else
				{

				}

		}		/* if (!res_p) */

	return res_p;
}

void DisconnectFromExternalServers (void)
{

}

void ConnectToExternalServers (void)
{
	const json_t *config_p = GetConfig ();

	if (config_p)
		{
			json_t *servers_p = json_object_get (config_p, SERVERS_S);

			if (servers_p)
				{
					if (json_is_object (servers_p))
						{
							AddExternalServerFromJSON (servers_p);
						}		/* if (json_is_object (json_p)) */
					else if (json_is_array (servers_p))
						{
							size_t index;
							json_t *element_p;

							json_array_foreach (servers_p, index, element_p)
								{
									AddExternalServerFromJSON (element_p);
								}
						}

				}		/* if (servers_p) */

		}		/* if (s_config_p) */
}

const char *GetServerProviderName (void)
{
	return GetProviderElement (PROVIDER_NAME_S);
}

const char *GetServerProviderDescription (void)
{
	return GetProviderElement (PROVIDER_DESCRIPTION_S);
}

const char *GetServerProviderURI (void)
{
	return GetProviderElement (PROVIDER_URI_S);
}

const json_t *GetProviderAsJSON (void)
{
	const json_t *provider_p = NULL;
	const json_t *config_p = GetConfig ();

	if (config_p)
		{
			provider_p = json_object_get (config_p, SERVER_PROVIDER_S);
		}

	return provider_p;
}

const char *GetJobLoggingURI (void)
{
	const char *uri_s = NULL;
	const json_t *config_p = GetConfig ();

	if (config_p)
		{
			const json_t *jobs_p = GetCompoundJSONObject (config_p, "admin.jobs");

			if (jobs_p)
				{
					uri_s = GetJSONString (jobs_p, "uri");
				}
		}

	return uri_s;
}

bool IsServiceEnabled (const char *service_name_s)
{
	bool enabled_flag = true;
	const json_t *services_config_p = GetGlobalConfigValue (SERVICES_NAME_S);

	if (services_config_p)
		{
			const json_t *service_statuses_p = json_object_get (services_config_p, SERVICES_STATUS_S);

			if (service_statuses_p)
				{
					const json_t *service_p = json_object_get (service_statuses_p, service_name_s);

					GetJSONBoolean (service_statuses_p, SERVICES_STATUS_DEFAULT_S, &enabled_flag);

					if (service_p)
						{
							if (json_is_true (service_p))
								{
									enabled_flag = true;
								}
							else if (json_is_false (service_p))
								{
									enabled_flag = false;
								}

						}		/* if (service_p) */

				}		/* if (service_statuses_p) */

		}		/* if (services_config_p) */

	return enabled_flag;
}

static const json_t *GetConfig (void)
{
	if (!s_config_p)
		{
			if (!s_load_config_tried_flag)
				{
					const char *root_path_s = GetServerRootDirectory ();
					char *full_config_path_s = MakeFilename (root_path_s, "grassroots.config");

					if (full_config_path_s)
						{
							json_error_t error;
							s_config_p = json_load_file (full_config_path_s, 0, &error);

							if (!s_config_p)
								{
									PrintErrors (STM_LEVEL_SEVERE, __FILE__, __LINE__, "Failed to load config from %s", full_config_path_s);
								}

							s_load_config_tried_flag = true;

							FreeCopiedString (full_config_path_s);
						}
				}
		}

	return s_config_p;
}

static const char *GetProviderElement (const char * const element_s)
{
	const char *result_s = NULL;
	const json_t *provider_p = GetProviderAsJSON ();

	if (provider_p)
		{
			result_s = GetJSONString (provider_p, element_s);
		}

	return result_s;
}

static void InitSchemaVersionDetails (void)
{
	uint32 major = CURRENT_SCHEMA_VERSION_MAJOR;
	uint32 minor = CURRENT_SCHEMA_VERSION_MINOR;
	const json_t *schema_p = GetGlobalConfigValue (SCHEMA_S);

	if (schema_p)
		{
			GetJSONInteger (schema_p, VERSION_MAJOR_S, (int *) &major);
			GetJSONInteger (schema_p, VERSION_MINOR_S, (int *) &minor);
		}

	SetSchemaVersionDetails (major, minor);
}


text:
package org.jvnet.hudson.plugins.backup;

/**
 * Common exception for backup plugin
 *
 * @author vsellier
 */
public class BackupException extends Exception {

	private static final long serialVersionUID = 8930285419536357470L;

	public BackupException() {
	}

	public BackupException(String message) {
		super(message);
	}

	public BackupException(Throwable cause) {
		super(cause);
	}

	public BackupException(String message, Throwable cause) {
		super(message, cause);
	}

}


text:
const int MAX_SIDES = 2;
const int MAX_TRACKS = 128;         // Internal format maximum, needed for 1MB TRD
const int MAX_SECTORS = 144;

const int MIN_SECTOR_SIZE = 128;

struct ScanContext
{
    CylHead last_cylhead{};
    Sector sector{ DataRate::Unknown, Encoding::Unknown, Header(0, 0, 1, 2) };
    int sectors = 0;
    int gap3 = 0;
    bool custom_cyl = false;
    bool custom_head = false;
    bool warned = false;
};

const int DUMP_OFFSETS = 1;
const int DUMP_DIFF = 2;

void DumpTrack(const CylHead& cylhead, const Track& track, const ScanContext& context, int flags = 0);
bool NormaliseTrack(const CylHead& cylhead, Track& track);
bool NormaliseBitstream(BitBuffer& bitbuf);
bool RepairTrack(const CylHead& cylhead, Track& track, const Track& src_track);

std::vector<std::pair<char, size_t>> DiffSectorCopies(const Sector& sector);

Sector GetTypicalSector(const CylHead& cylhead, const Track& track, const Sector& last);

bool WriteRegularDisk(FILE* f_, Disk& disk, const Format& format);
bool WriteAppleDODisk(FILE* f_, Disk& disk, const Format& format);

bool test_remove_gap2(const Data& data, int offset);
bool test_remove_gap3(const Data& data, int offset, int& gap3);
bool test_remove_gap4b(const Data& data, int offset);

enum class ChecksumType
{
    None,           // No checksum, known valid
    Constant_8C15,  // 8C 15
    Sum_1800,       // Sum of 0x1800 bytes
    XOR_1800,       // XOR of 0x1800 bytes
    XOR_18A0,       // XOR of 0x18a0 bytes
    CRC_D2F6_1800,  // CRC-16 (init=D2F6) for 0x1800 bytes
    CRC_D2F6_1802,  // CRC-16 (init=D2F6) for 0x1802 bytes
};

std::set<ChecksumType> ChecksumMethods(const uint8_t* buf, int len);
std::string ChecksumName(std::set<ChecksumType> method);
std::string ChecksumNameShort(std::set<ChecksumType> methods);
int ChecksumLength(ChecksumType method);

void scale_flux(std::vector<uint32_t>& flux_rev, uint64_t numerator, uint64_t denominator);


text:
require 'satisfy'
require 'pp'
require 'rspec'

module Satisfy
  module RSpec
    class << self
      def build_and_run(test_spec)
        # The call to build() will return an instance that contains a
        # specs instance variable. That, in turn, will contain a
        # representation of the test spec that was processed. That
        # will be a Feature implementation, since a Feature is how
        # Gherkin represents a test spec.
        Satisfy::Builder.build(test_spec).specs.each do |feature|
          instance_eval <<-CONTEXT, test_spec, feature.line
            describe_feature = ::RSpec.describe(feature.name, feature.metadata_hash)
            execute_feature(describe_feature, feature, test_spec)
          CONTEXT
        end
      end

      private

      def execute_feature(describe_feature, feature, test_spec)
        describe_feature.before do
          feature.backgrounds.map(&:steps).flatten.each do |step|
            run(test_spec, step)
          end
        end

        feature.scenarios.each do |scenario|
          (puts 'SCENARIO:'; pp scenario) if ENV['SATISFY_TRACE']
          instance_eval <<-CONTEXT, test_spec, scenario.line
            describe_feature.describe(scenario.name, scenario.metadata_hash) do
              it(scenario.steps.map(&:to_s).join(' -> ')) do
                scenario.steps.each do |step|
                  run(test_spec, step)
                end
              end
            end
          CONTEXT
        end
      end
    end

    module SpecLoader
      def load(*files, &block)
        puts "Loading: #{files}" if ENV['SATISFY_TRACE']
        if files.first.end_with?('.feature', '.spec', '.story')
          load_helper 'satisfy_helper'
          load_helper 'spec_helper'

          Satisfy::RSpec.build_and_run(files.first)
        else
          super
        end
      end

      private

      def load_helper(file)
        require file
      rescue LoadError => e
        # This makes sure that errors raised in the spec_helper file
        # are not hidden by rescuing a load error.
        raise unless e.message.include?(file)
      end
    end

    module SpecRunner
      include Satisfy::StepRunner

      # @param test_spec [String] full path for test spec
      # @param step [Struct Satisfy::Builder::Step] the step to execute
      def run(test_spec, step)
        instance_eval <<-CONTEXT, test_spec, step.line
          step(step)
        CONTEXT
      rescue Satisfy::Pending => e
        example = ::RSpec.current_example
        example.metadata[:line_number] = step.line
        example.metadata[:location] = "#{example.metadata[:file_path]}:#{step.line}"

        if ::RSpec.configuration.raise_error_for_unimplemented_steps
          e.backtrace.push "#{test_spec}:#{step.line}:in `#{step.description}'"
          raise
        end

        skip("No matcher for step: '#{e}'")
      rescue StandardError, ::RSpec::Expectations::ExpectationNotMetError => e
        e.backtrace.push "#{test_spec}:#{step.line}:in `#{step.description}'"
        raise e
      end
    end
  end
end

::RSpec::Core::Configuration.send(:include, Satisfy::RSpec::SpecLoader)

::RSpec.configure do |config|
  config.pattern << ',**/*.feature,**/*.spec,**/*.story'
  config.include Satisfy::RSpec::SpecRunner, satisfy: true
  config.include Satisfy::Steps, satisfy: true
  config.add_setting :raise_error_for_unimplemented_steps, default: false
end


text:
function Nota(nulla) {
	this.uuid = uuid.v4();
	this.titolo = '';
	this.testo = '';
	this.etichette = [];
	//this.dataCreazione = Date.now();
	this.dataCreazione = null;
	this.dataAggiornamento = null;
	this.inizializzata = true;

	if (nulla == true) {
		this.dataCreazione = null;
		this.uuid = '';
		this.inizializzata = false;
	}
}

function Etichetta() {
	this.valore = '';
	this.note = [];
}


text:
"""Tests for utility functions."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import itertools

import numpy as np

from tensorflow.contrib.distributions.python.ops import distribution_util
from tensorflow.contrib.distributions.python.ops import mixture
from tensorflow.contrib.distributions.python.ops import mixture_same_family
from tensorflow.contrib.distributions.python.ops import mvn_diag
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import tensor_shape
from tensorflow.python.ops import array_ops
from tensorflow.python.ops.distributions import categorical
from tensorflow.python.ops.distributions import normal
from tensorflow.python.ops.linalg import linear_operator_diag
import tensorflow.python.ops.nn_grad  # pylint: disable=unused-import
from tensorflow.python.platform import test

def _powerset(x):
  s = list(x)
  return itertools.chain.from_iterable(
      itertools.combinations(s, r) for r in range(len(s) + 1))

def _matrix_diag(d):
  """Batch version of np.diag."""
  orig_shape = d.shape
  d = np.reshape(d, (int(np.prod(d.shape[:-1])), d.shape[-1]))
  diag_list = []
  for i in range(d.shape[0]):
    diag_list.append(np.diag(d[i, ...]))
  return np.reshape(diag_list, orig_shape + (d.shape[-1],))

def _make_tril_scale(
    loc=None,
    scale_tril=None,
    scale_diag=None,
    scale_identity_multiplier=None,
    shape_hint=None):
  if scale_tril is not None:
    scale_tril = np.tril(scale_tril)
    if scale_diag is not None:
      scale_tril += _matrix_diag(np.array(scale_diag, dtype=np.float32))
    if scale_identity_multiplier is not None:
      scale_tril += (
          scale_identity_multiplier * _matrix_diag(np.ones(
              [scale_tril.shape[-1]], dtype=np.float32)))
    return scale_tril
  return _make_diag_scale(
      loc, scale_diag, scale_identity_multiplier, shape_hint)

def _make_diag_scale(
    loc=None,
    scale_diag=None,
    scale_identity_multiplier=None,
    shape_hint=None):
  if scale_diag is not None:
    scale_diag = np.asarray(scale_diag)
    if scale_identity_multiplier is not None:
      scale_diag += scale_identity_multiplier
    return _matrix_diag(scale_diag)

  if loc is None and shape_hint is None:
    return None

  if shape_hint is None:
    shape_hint = loc.shape[-1]
  if scale_identity_multiplier is None:
    scale_identity_multiplier = 1.
  return scale_identity_multiplier * np.diag(np.ones(shape_hint))

class MakeTrilScaleTest(test.TestCase):

  def _testLegalInputs(
      self, loc=None, shape_hint=None, scale_params=None):
    for args in _powerset(scale_params.items()):
      with self.test_session():
        args = dict(args)

        scale_args = dict({
            "loc": loc,
            "shape_hint": shape_hint}, **args)
        expected_scale = _make_tril_scale(**scale_args)
        if expected_scale is None:
          # Not enough shape information was specified.
          with self.assertRaisesRegexp(ValueError, ("is specified.")):
            scale = distribution_util.make_tril_scale(**scale_args)
            scale.to_dense().eval()
        else:
          scale = distribution_util.make_tril_scale(**scale_args)
          self.assertAllClose(expected_scale, scale.to_dense().eval())

  def testLegalInputs(self):
    self._testLegalInputs(
        loc=np.array([-1., -1.], dtype=np.float32),
        shape_hint=2,
        scale_params={
            "scale_identity_multiplier": 2.,
            "scale_diag": [2., 3.],
            "scale_tril": [[1., 0.],
                           [-3., 3.]],
        })

  def testLegalInputsMultidimensional(self):
    self._testLegalInputs(
        loc=np.array([[[-1., -1., 2.], [-2., -3., 4.]]], dtype=np.float32),
        shape_hint=3,
        scale_params={
            "scale_identity_multiplier": 2.,
            "scale_diag": [[[2., 3., 4.], [3., 4., 5.]]],
            "scale_tril": [[[[1., 0., 0.],
                             [-3., 3., 0.],
                             [1., -2., 1.]],
                            [[2., 1., 0.],
                             [-4., 7., 0.],
                             [1., -1., 1.]]]]
        })

  def testZeroTriU(self):
    with self.test_session():
      scale = distribution_util.make_tril_scale(scale_tril=[[1., 1], [1., 1.]])
      self.assertAllClose([[1., 0], [1., 1.]], scale.to_dense().eval())

  def testValidateArgs(self):
    with self.test_session():
      with self.assertRaisesOpError("diagonal part must be non-zero"):
        scale = distribution_util.make_tril_scale(
            scale_tril=[[0., 1], [1., 1.]], validate_args=True)
        scale.to_dense().eval()

  def testAssertPositive(self):
    with self.test_session():
      with self.assertRaisesOpError("diagonal part must be positive"):
        scale = distribution_util.make_tril_scale(
            scale_tril=[[-1., 1], [1., 1.]],
            validate_args=True,
            assert_positive=True)
        scale.to_dense().eval()

class MakeDiagScaleTest(test.TestCase):

  def _testLegalInputs(
      self, loc=None, shape_hint=None, scale_params=None):
    for args in _powerset(scale_params.items()):
      with self.test_session():
        args = dict(args)

        scale_args = dict({
            "loc": loc,
            "shape_hint": shape_hint}, **args)
        expected_scale = _make_diag_scale(**scale_args)
        if expected_scale is None:
          # Not enough shape information was specified.
          with self.assertRaisesRegexp(ValueError, ("is specified.")):
            scale = distribution_util.make_diag_scale(**scale_args)
            scale.to_dense().eval()
        else:
          scale = distribution_util.make_diag_scale(**scale_args)
          self.assertAllClose(expected_scale, scale.to_dense().eval())

  def testLegalInputs(self):
    self._testLegalInputs(
        loc=np.array([-1., -1.], dtype=np.float32),
        shape_hint=2,
        scale_params={
            "scale_identity_multiplier": 2.,
            "scale_diag": [2., 3.]
        })

  def testLegalInputsMultidimensional(self):
    self._testLegalInputs(
        loc=np.array([[[-1., -1., 2.], [-2., -3., 4.]]], dtype=np.float32),
        shape_hint=3,
        scale_params={
            "scale_identity_multiplier": 2.,
            "scale_diag": [[[2., 3., 4.], [3., 4., 5.]]]
        })

  def testValidateArgs(self):
    with self.test_session():
      with self.assertRaisesOpError("diagonal part must be non-zero"):
        scale = distribution_util.make_diag_scale(
            scale_diag=[[0., 1], [1., 1.]], validate_args=True)
        scale.to_dense().eval()

  def testAssertPositive(self):
    with self.test_session():
      with self.assertRaisesOpError("diagonal part must be positive"):
        scale = distribution_util.make_diag_scale(
            scale_diag=[[-1., 1], [1., 1.]],
            validate_args=True,
            assert_positive=True)
        scale.to_dense().eval()

class ShapesFromLocAndScaleTest(test.TestCase):

  def test_static_loc_static_scale_non_matching_event_size_raises(self):
    loc = constant_op.constant(np.zeros((2, 4)))
    scale = linear_operator_diag.LinearOperatorDiag(np.ones((5, 1, 3)))
    with self.assertRaisesRegexp(ValueError, "could not be broadcast"):
      distribution_util.shapes_from_loc_and_scale(loc, scale)

  def test_static_loc_static_scale(self):
    loc = constant_op.constant(np.zeros((2, 3)))
    scale = linear_operator_diag.LinearOperatorDiag(np.ones((5, 1, 3)))
    batch_shape, event_shape = distribution_util.shapes_from_loc_and_scale(
        loc, scale)

    self.assertEqual(tensor_shape.TensorShape([5, 2]), batch_shape)
    self.assertEqual(tensor_shape.TensorShape([3]), event_shape)

  def test_static_loc_dynamic_scale(self):
    loc = constant_op.constant(np.zeros((2, 3)))
    diag = array_ops.placeholder(dtypes.float64)
    scale = linear_operator_diag.LinearOperatorDiag(diag)
    with self.test_session() as sess:
      batch_shape, event_shape = sess.run(
          distribution_util.shapes_from_loc_and_scale(loc, scale),
          feed_dict={diag: np.ones((5, 1, 3))})
      self.assertAllEqual([5, 2], batch_shape)
      self.assertAllEqual([3], event_shape)

  def test_dynamic_loc_static_scale(self):
    loc = array_ops.placeholder(dtypes.float64)
    diag = constant_op.constant(np.ones((5, 2, 3)))
    scale = linear_operator_diag.LinearOperatorDiag(diag)
    with self.test_session():
      batch_shape, event_shape = distribution_util.shapes_from_loc_and_scale(
          loc, scale)
      # batch_shape depends on both args, and so is dynamic.  Since loc did not
      # have static shape, we inferred event shape entirely from scale, and this
      # is available statically.
      self.assertAllEqual(
          [5, 2], batch_shape.eval(feed_dict={loc: np.zeros((2, 3))}))
      self.assertAllEqual([3], event_shape)

  def test_dynamic_loc_dynamic_scale(self):
    loc = array_ops.placeholder(dtypes.float64)
    diag = array_ops.placeholder(dtypes.float64)
    scale = linear_operator_diag.LinearOperatorDiag(diag)
    with self.test_session() as sess:
      batch_shape, event_shape = sess.run(
          distribution_util.shapes_from_loc_and_scale(loc, scale),
          feed_dict={diag: np.ones((5, 2, 3)), loc: np.zeros((2, 3))})
      self.assertAllEqual([5, 2], batch_shape)
      self.assertAllEqual([3], event_shape)

  def test_none_loc_static_scale(self):
    loc = None
    scale = linear_operator_diag.LinearOperatorDiag(np.ones((5, 1, 3)))
    batch_shape, event_shape = distribution_util.shapes_from_loc_and_scale(
        loc, scale)

    self.assertEqual(tensor_shape.TensorShape([5, 1]), batch_shape)
    self.assertEqual(tensor_shape.TensorShape([3]), event_shape)

  def test_none_loc_dynamic_scale(self):
    loc = None
    diag = array_ops.placeholder(dtypes.float64)
    scale = linear_operator_diag.LinearOperatorDiag(diag)
    with self.test_session() as sess:
      batch_shape, event_shape = sess.run(
          distribution_util.shapes_from_loc_and_scale(loc, scale),
          feed_dict={diag: np.ones((5, 1, 3))})
      self.assertAllEqual([5, 1], batch_shape)
      self.assertAllEqual([3], event_shape)

class GetBroadcastShapeTest(test.TestCase):

  def test_all_static_shapes_work(self):
    x = array_ops.ones((2, 1, 3))
    y = array_ops.ones((1, 5, 3))
    z = array_ops.ones(())
    self.assertAllEqual([2, 5, 3],
                        distribution_util.get_broadcast_shape(x, y, z))

  def test_with_some_dynamic_shapes_works(self):
    x = array_ops.ones((2, 1, 3))
    y = array_ops.placeholder(x.dtype)
    z = array_ops.ones(())
    with self.test_session() as sess:
      bcast_shape = sess.run(
          distribution_util.get_broadcast_shape(x, y, z),
          feed_dict={y: np.ones((1, 5, 3)).astype(np.float32)})
      self.assertAllEqual([2, 5, 3], bcast_shape)

class TridiagTest(test.TestCase):

  def testWorksCorrectlyNoBatches(self):
    with self.test_session():
      self.assertAllEqual(
          [[4., 8., 0., 0.],
           [1., 5., 9., 0.],
           [0., 2., 6., 10.],
           [0., 0., 3, 7.]],
          distribution_util.tridiag(
              [1., 2., 3.],
              [4., 5., 6., 7.],
              [8., 9., 10.]).eval())

  def testWorksCorrectlyBatches(self):
    with self.test_session():
      self.assertAllClose(
          [[[4., 8., 0., 0.],
            [1., 5., 9., 0.],
            [0., 2., 6., 10.],
            [0., 0., 3, 7.]],
           [[0.7, 0.1, 0.0, 0.0],
            [0.8, 0.6, 0.2, 0.0],
            [0.0, 0.9, 0.5, 0.3],
            [0.0, 0.0, 1.0, 0.4]]],
          distribution_util.tridiag(
              [[1., 2., 3.],
               [0.8, 0.9, 1.]],
              [[4., 5., 6., 7.],
               [0.7, 0.6, 0.5, 0.4]],
              [[8., 9., 10.],
               [0.1, 0.2, 0.3]]).eval(),
          rtol=1e-5, atol=0.)

  def testHandlesNone(self):
    with self.test_session():
      self.assertAllClose(
          [[[4., 0., 0., 0.],
            [0., 5., 0., 0.],
            [0., 0., 6., 0.],
            [0., 0., 0, 7.]],
           [[0.7, 0.0, 0.0, 0.0],
            [0.0, 0.6, 0.0, 0.0],
            [0.0, 0.0, 0.5, 0.0],
            [0.0, 0.0, 0.0, 0.4]]],
          distribution_util.tridiag(
              diag=[[4., 5., 6., 7.],
                    [0.7, 0.6, 0.5, 0.4]]).eval(),
          rtol=1e-5, atol=0.)

class MixtureStddevTest(test.TestCase):

  def test_mixture_dev(self):
    mixture_weights = np.array([
        [1.0/3, 1.0/3, 1.0/3],
        [0.750, 0.250, 0.000]
    ])
    component_means = np.array([
        [1.0, 1.0, 1.0],
        [-5, 0, 1.25]
    ])
    component_devs = np.array([
        [1.0, 1.0, 1.0],
        [0.01, 2.0, 0.1]
    ])

    # The first case should trivially have a standard deviation of 1.0 because
    # all components are identical and have that standard deviation.
    # The second case was computed by hand.
    expected_devs = np.array([
        1.0,
        2.3848637277
    ])

    weights_tf = array_ops.constant(mixture_weights)
    means_tf = array_ops.constant(component_means)
    sigmas_tf = array_ops.constant(component_devs)
    mix_dev = distribution_util.mixture_stddev(weights_tf,
                                               means_tf,
                                               sigmas_tf)

    with self.test_session() as sess:
      actual_devs = sess.run(mix_dev)

    self.assertAllClose(actual_devs, expected_devs)

class PadMixtureDimensionsTest(test.TestCase):

  def test_pad_mixture_dimensions_mixture(self):
    with self.test_session() as sess:
      gm = mixture.Mixture(
          cat=categorical.Categorical(probs=[[0.3, 0.7]]),
          components=[
              normal.Normal(loc=[-1.0], scale=[1.0]),
              normal.Normal(loc=[1.0], scale=[0.5])
          ])

      x = array_ops.constant([[1.0, 2.0], [3.0, 4.0]])
      x_pad = distribution_util.pad_mixture_dimensions(
          x, gm, gm.cat, gm.event_shape.ndims)
      x_out, x_pad_out = sess.run([x, x_pad])

    self.assertAllEqual(x_pad_out.shape, [2, 2])
    self.assertAllEqual(x_out.reshape([-1]), x_pad_out.reshape([-1]))

  def test_pad_mixture_dimensions_mixture_same_family(self):
    with self.test_session() as sess:
      gm = mixture_same_family.MixtureSameFamily(
          mixture_distribution=categorical.Categorical(probs=[0.3, 0.7]),
          components_distribution=mvn_diag.MultivariateNormalDiag(
              loc=[[-1., 1], [1, -1]], scale_identity_multiplier=[1.0, 0.5]))

      x = array_ops.constant([[1.0, 2.0], [3.0, 4.0]])
      x_pad = distribution_util.pad_mixture_dimensions(
          x, gm, gm.mixture_distribution, gm.event_shape.ndims)
      x_out, x_pad_out = sess.run([x, x_pad])

    self.assertAllEqual(x_pad_out.shape, [2, 2, 1])
    self.assertAllEqual(x_out.reshape([-1]), x_pad_out.reshape([-1]))

class _PadTest(object):

  def testNegAxisCorrectness(self):
    x_ = np.float32([[1., 2, 3],
                     [4, 5, 6]])
    value_ = np.float32(0.25)
    count_ = np.int32(2)
    with self.test_session() as sess:
      x = array_ops.placeholder_with_default(
          x_, shape=x_.shape if self.is_static_shape else None)
      value = (constant_op.constant(value_) if self.is_static_shape
               else array_ops.placeholder_with_default(value_, shape=None))
      count = (constant_op.constant(count_) if self.is_static_shape
               else array_ops.placeholder_with_default(count_, shape=None))

      x0_front = distribution_util.pad(
          x, axis=-2, value=value, count=count, front=True)
      x0_back = distribution_util.pad(
          x, axis=-2, count=count, back=True)
      x0_both = distribution_util.pad(
          x, axis=-2, value=value, front=True, back=True)

      if self.is_static_shape:
        self.assertAllEqual([4, 3], x0_front.shape)
        self.assertAllEqual([4, 3], x0_back.shape)
        self.assertAllEqual([4, 3], x0_both.shape)

      [x0_front_, x0_back_, x0_both_] = sess.run([
          x0_front, x0_back, x0_both])

      self.assertAllClose(
          np.float32([[value_]*3,
                      [value_]*3,
                      [1, 2, 3],
                      [4, 5, 6]]),
          x0_front_, atol=0., rtol=1e-6)
      self.assertAllClose(
          np.float32([[1, 2, 3],
                      [4, 5, 6],
                      [0.]*3,
                      [0.]*3]),
          x0_back_, atol=0., rtol=1e-6)
      self.assertAllClose(
          np.float32([[value_]*3,
                      [1, 2, 3],
                      [4, 5, 6],
                      [value_]*3]),
          x0_both_, atol=0., rtol=1e-6)

  def testPosAxisCorrectness(self):
    x_ = np.float32([[1., 2, 3],
                     [4, 5, 6]])
    value_ = np.float32(0.25)
    count_ = np.int32(2)
    with self.test_session() as sess:
      x = array_ops.placeholder_with_default(
          x_, shape=x_.shape if self.is_static_shape else None)
      value = (constant_op.constant(value_) if self.is_static_shape
               else array_ops.placeholder_with_default(value_, shape=None))
      count = (constant_op.constant(count_) if self.is_static_shape
               else array_ops.placeholder_with_default(count_, shape=None))

      x1_front = distribution_util.pad(
          x, axis=1, value=value, count=count, front=True)
      x1_back = distribution_util.pad(
          x, axis=1, count=count, back=True)
      x1_both = distribution_util.pad(
          x, axis=1, value=value, front=True, back=True)

      if self.is_static_shape:
        self.assertAllEqual([2, 5], x1_front.shape)
        self.assertAllEqual([2, 5], x1_back.shape)
        self.assertAllEqual([2, 5], x1_both.shape)

      [x1_front_, x1_back_, x1_both_] = sess.run([
          x1_front, x1_back, x1_both])

      self.assertAllClose(
          np.float32([[value_]*2 + [1, 2, 3],
                      [value_]*2 + [4, 5, 6]]),
          x1_front_, atol=0., rtol=1e-6)
      self.assertAllClose(
          np.float32([[1, 2, 3] + [0.]*2,
                      [4, 5, 6] + [0.]*2]),
          x1_back_, atol=0., rtol=1e-6)
      self.assertAllClose(
          np.float32([[value_, 1, 2, 3, value_],
                      [value_, 4, 5, 6, value_]]),
          x1_both_, atol=0., rtol=1e-6)

class PadStaticTest(_PadTest, test.TestCase):

  @property
  def is_static_shape(self):
    return True

class PadDynamicTest(_PadTest, test.TestCase):

  @property
  def is_static_shape(self):
    return False

if __name__ == "__main__":
  test.main()