text:
/*
 * Changes for GemFireXD distributed data platform (some marked by "GemStone changes")
 *
 * Portions Copyright (c) 2010-2015 Pivotal Software, Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you
 * may not use this file except in compliance with the License. You
 * may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
 * implied. See the License for the specific language governing
 * permissions and limitations under the License. See accompanying
 * LICENSE file.
 */

/*
 This file was based on the MemStore patch written by Knut Magne, published
 under the Derby issue DERBY-2798 and released under the same license,
 ASF, as described above. The MemStore patch was in turn based on Derby source
 files.
*/

package com.pivotal.gemfirexd.internal.engine.access.index;

import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Properties;

import com.gemstone.gemfire.cache.AttributesFactory;
import com.gemstone.gemfire.cache.CustomEvictionAttributes;
import com.gemstone.gemfire.cache.DataPolicy;
import com.gemstone.gemfire.cache.EntryEvent;
import com.gemstone.gemfire.cache.EvictionAttributes;
import com.gemstone.gemfire.cache.EvictionCriteria;
import com.gemstone.gemfire.cache.PartitionAttributes;
import com.gemstone.gemfire.cache.PartitionAttributesFactory;
import com.gemstone.gemfire.cache.Region;
import com.gemstone.gemfire.cache.RegionAttributes;
import com.gemstone.gemfire.distributed.internal.InternalDistributedSystem;
import com.gemstone.gemfire.i18n.LogWriterI18n;
import com.gemstone.gemfire.internal.cache.BucketRegion;
import com.gemstone.gemfire.internal.cache.EntryEventImpl;
import com.gemstone.gemfire.internal.cache.GemFireCacheImpl;
import com.gemstone.gemfire.internal.cache.LocalRegion;
import com.gemstone.gemfire.internal.cache.PartitionedRegion;
import com.gemstone.gemfire.internal.cache.RegionEntry;
import com.gemstone.gemfire.internal.cache.execute.InternalRegionFunctionContext;
import com.gemstone.gemfire.internal.cache.partitioned.PREntriesIterator;
import com.gemstone.gemfire.internal.offheap.OffHeapHelper;
import com.gemstone.gemfire.internal.offheap.annotations.Released;
import com.gemstone.gemfire.internal.shared.Version;
import com.gemstone.gemfire.internal.util.ArrayUtils;
import com.pivotal.gemfirexd.internal.engine.GfxdConstants;
import com.pivotal.gemfirexd.internal.engine.Misc;
import com.pivotal.gemfirexd.internal.engine.distributed.utils.GemFireXDUtils;
import com.pivotal.gemfirexd.internal.iapi.error.StandardException;
import com.pivotal.gemfirexd.internal.iapi.services.sanity.SanityManager;
import com.pivotal.gemfirexd.internal.iapi.types.RowLocation;
import com.pivotal.gemfirexd.internal.shared.common.reference.SQLState;

/**
 * A heap object corresponds to an instance of a heap conglomerate. It caches
 * information which makes it fast to open heap controllers from it.
 */
public final class GlobalHashIndex extends MemIndex {

  /* Constructors for This class: */
  /**
   * Zero arg constructor for Monitor to create empty object.
   */
  public GlobalHashIndex() {
  }

  @Override
  protected void allocateMemory(Properties properties, int tmpFlag)
      throws StandardException {
    // Get base table region.
    final PartitionAttributesFactory<?, ?> pafact =
      new PartitionAttributesFactory<Object, Object>();
    RegionAttributes<?, ?> ra = this.baseContainer.getRegionAttributes();
    final PartitionAttributes<?, ?> pa = ra.getPartitionAttributes();
    // check if parent region is partitioned
    if (pa == null) {
      throw StandardException.newException(SQLState.TABLE_NOT_PARTITIONED,
          this.baseContainer.getQualifiedTableName(),
          "creating global index (region attributes: " + ra + ')');
    }
    // global index does not support case-sensitivity setting
    if (properties.containsKey(GfxdConstants.INDEX_CASE_SENSITIVE_PROP)) {
      throw StandardException.newException(
          SQLState.INDEX_CASE_INSENSITIVITY_NOT_SUPPORTED,
          "primary/unique key constraint");
    }
    AttributesFactory<?, ?> afact = new AttributesFactory<Object, Object>();
    if (ra.getDataPolicy().withHDFS()) {
      LogWriterI18n log = InternalDistributedSystem.getLoggerI18n();

      CustomEvictionAttributes cea = ra.getCustomEvictionAttributes();
      if (cea == null
          && ra.getDataPolicy().withPersistence()
          && Version.GFXD_13.compareTo(GemFireXDUtils.getCurrentDDLVersion()) < 0) {
        if (log.fineEnabled()) {
          log.fine("Creating global index without HDFS storage for table " + baseContainer.getTableName());
        }

        // #51382, we skip writing the index to HDFS
        afact.setDataPolicy(DataPolicy.PERSISTENT_PARTITION);

        // Even if we don't plan on using hdfs, make sure that the proper
        // eviction attributes are set on the region.
        GemFireCacheImpl gfi = Misc.getMemStore().getGemFireCache();
        ra = gfi.setEvictionAttributesForLargeRegion(ra);
      } else {
        afact.setDataPolicy(ra.getDataPolicy());
        afact.setHDFSStoreName(ra.getHDFSStoreName());
        afact.setHDFSWriteOnly(ra.getHDFSWriteOnly());

        EvictionCriteria ec = new GlobalIndexCustomEvictionCriteria();
        afact.setCustomEvictionAttributes(ec, 0L, 0L);
      }

      if (ra.getDataPolicy().withPersistence()) {
        afact.setDiskStoreName(ra.getDiskStoreName());
        afact.setDiskSynchronous(ra.isDiskSynchronous());
        // also copy overflow to disk eviction policy
        EvictionAttributes evictAttrs = ra.getEvictionAttributes();
        if (evictAttrs != null && evictAttrs.getAction().isOverflowToDisk()) {
          afact.setEvictionAttributes(evictAttrs);
        }
      }
    }
    else if (ra.getDataPolicy().withPersistence()) {
      afact.setDataPolicy(DataPolicy.PERSISTENT_PARTITION);
      afact.setDiskStoreName(ra.getDiskStoreName());
      afact.setDiskSynchronous(ra.isDiskSynchronous());
      // also copy overflow to disk eviction policy
      EvictionAttributes evictAttrs = ra.getEvictionAttributes();
      if (evictAttrs != null && evictAttrs.getAction().isOverflowToDisk()) {
        afact.setEvictionAttributes(evictAttrs);
      }
    }
    else {
      afact.setDataPolicy(DataPolicy.PARTITION);
    }
    pafact.setLocalMaxMemory(pa.getLocalMaxMemory());
    pafact.setTotalNumBuckets(pa.getTotalNumBuckets());
    pafact.setRedundantCopies(pa.getRedundantCopies());
    pafact.setRecoveryDelay(pa.getRecoveryDelay());
    afact.setPartitionAttributes(pafact.create());
    afact.setConcurrencyLevel(ra.getConcurrencyLevel());
    afact.setInitialCapacity(ra.getInitialCapacity());
    afact.setConcurrencyChecksEnabled(ra.getConcurrencyChecksEnabled());
    properties.put(GfxdConstants.REGION_ATTRIBUTES_KEY, afact.create());
    properties.put(MemIndex.PROPERTY_BASECONGLOMID, this.baseContainer.getId());
  }

  public int getType() {
    return GLOBALHASHINDEX;
  }

  @Override
  public String getIndexTypeName() {
    return GLOBAL_HASH_INDEX;
  }

  @Override
  protected MemIndexCostController newMemIndexCostController() {
    Hash1IndexCostController retval = new Hash1IndexCostController();
    return retval;
  }

  @Override
  protected MemIndexScanController newMemIndexScanController() {
    GlobalHashIndexScanController retval = new GlobalHashIndexScanController();
    return retval;
  }

  @Override
  protected MemIndexController newMemIndexController() {
    GlobalHashIndexController retval = new GlobalHashIndexController();
    return retval;
  }

  /**
   * Return my format identifier.
   *
   * @see com.pivotal.gemfirexd.internal.iapi.services.io.TypedFormat#getTypeFormatId
   */
  @Override
  public int getTypeFormatId() {
    throw new UnsupportedOperationException("not storable");
  }

  @Override
  public void dumpIndex(String marker) {
    if (marker == null) {
      marker = "Global hash index iteration";
    }
    PartitionedRegion region = (PartitionedRegion)this.container.getRegion();
    String idMark = " [ID: " + this.baseContainer.getId() + ']';
    SanityManager.DEBUG_PRINT(GfxdConstants.TRACE_INDEX,
        "##### For GlobalHashIndex " + this.container + idMark + " Region "
            + region + marker + " begin #####");

    PREntriesIterator<?> irl = (PREntriesIterator<?>)region.getSharedDataView()
        .getLocalEntriesIterator((InternalRegionFunctionContext)null, false,
            false, true, region);
    final String lineSep = SanityManager.lineSeparator;
    StringBuilder sb = new StringBuilder().append(lineSep);
    while (irl.hasNext()) {
      RowLocation rl = (RowLocation)irl.next();
      sb.append("\tkey=");
      ArrayUtils.objectString(rl.getKey(), sb);
      sb.append(", value=");
      BucketRegion br = irl.getHostedBucketRegion();
      {
        @Released Object v = ((RegionEntry)rl).getValueOffHeapOrDiskWithoutFaultIn(br);
        try {
          ArrayUtils.objectStringNonRecursive(v, sb);
        } finally {
          OffHeapHelper.release(v);
        }
      }
      sb.append(", bucketId=");
      sb.append(br.getId());
      sb.append(", isPrimary=");
      sb.append(br.getBucketAdvisor().isPrimary());
      sb.append(lineSep);
      if (sb.length() > (4 * 1024 * 1024)) {
        SanityManager.DEBUG_PRINT(GfxdConstants.TRACE_INDEX, sb.toString());
        sb.setLength(0);
      }
    }
    SanityManager.DEBUG_PRINT(GfxdConstants.TRACE_INDEX, sb.toString());

    SanityManager.DEBUG_PRINT(GfxdConstants.TRACE_INDEX,
        "##### For GlobalHashIndex " + this.container + idMark + " Region "
            + region + marker + " end #####");
  }
}

class GlobalIndexCustomEvictionCriteria implements EvictionCriteria<Object, Object> {

  @Override
  public Iterator<Entry<Object, Object>> getKeysToBeEvicted(long currentMillis,
      Region<Object, Object> region) {
    return null;
  }

  @Override
  public boolean doEvict(EntryEvent<Object, Object> event) {
    final EntryEventImpl ev = (EntryEventImpl)event;
    final RegionEntry re = ev.getRegionEntry();
    LocalRegion region = ev.getRegion();
    if (region.getLogWriterI18n().fineEnabled()) {
      region.getLogWriterI18n().fine(
          " The entry is " + re + " and the event is " + event
              + " re marked for eviction " + re.isMarkedForEviction());
    }

    if (re != null) {
      if (re.hasAnyLock()) {
        return false;
      }
      if (re.isMarkedForEviction()) {
        return true;
      }
    }
    return false;
  }

  @Override
  public boolean isEquivalent(EvictionCriteria<Object, Object> other) {
    return false;
  }

}


text:
.. _menpo-model-InstanceLinearModel:

.. currentmodule:: menpo.model

InstanceLinearModel
===================
.. autoclass:: InstanceLinearModel
  :members:
  :inherited-members:
  :show-inheritance:

redpajama_set_name: RedPajamaGithub


text:
//
//
// (C) Copyright 2002-2003 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE.  AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
// layerDialog.cpp : implementation file

#include "stdafx.h"
#include "layerDialog.h"
#include <string.h>
#include "util.h"
#include "accmd.h"

// layerDialog dialog

IMPLEMENT_DYNAMIC(layerDialog, CDialog)

//constructor
layerDialog::layerDialog(CWnd* pParent /*=NULL*/)
	: CDialog(layerDialog::IDD, pParent)
{
	/*void*/
}

//destructor
layerDialog::~layerDialog()
{
	/*void*/
}

//data exchange
void layerDialog::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_LAYERLIST, m_layerList);
	DDX_Control(pDX, IDC_BUTTON_ENTORDER, m_entOrderBtn);
	DDX_Control(pDX, IDC_BUTTON_LAYERORDER, m_layerOrderBtn);
}

BEGIN_MESSAGE_MAP(layerDialog, CDialog)
	ON_BN_CLICKED(IDCLOSE, OnBnClickedClose)
	ON_BN_CLICKED(IDC_BUTTON_ENTORDER, OnBnClickedButtonEntorder)
	ON_BN_CLICKED(IDC_BUTTON_LAYERORDER, OnBnClickedButtonLayerorder)
	ON_BN_CLICKED(IDC_BUTTON_APPLY, OnBnClickedButtonApply)
	ON_BN_CLICKED(IDC_BUTTONOK, OnBnClickedButtonok)
	ON_LBN_SELCHANGE(IDC_LAYERLIST, OnLbnSelchangeLayerlist)
END_MESSAGE_MAP()

//This function display the layer order in CDraglistbox.
//"layers" is an array of layerIds. iRepeats is an interger array which indicate
//if the draworders of entities on a certain layer are continuous. For example, if
//iRepeat.at(0) is 0, the draworders of  entities on layers.at(0) are continous. If iRepeat.at(0)
//is greater than 0, draworders of entities on layers.at(0) are not continuous and the layer name
//of layers.at(0) displayed in the list box will have a "*" prefix and postfix.
bool layerDialog::displayLayerOrder(AcDbObjectIdArray &layers, CUIntArray* iRepeats)
{
	//Clear the current display
	m_layerList.ResetContent();

	//if iRepeat is NULL, just list the layers' names in the array, "layers".
	if (iRepeats == NULL)
	{

		for (int i = 0; i < layers.length(); i++)
		{
			AcDbObject* pLayer;
			if (Acad::eOk == acdbOpenObject(pLayer, layers.at(i), AcDb::kForRead))
			{
				const char* name;
				AcDbLayerTableRecord::cast(pLayer)->getName(name);
				char newName[260];
				strcpy(newName, " ");
				strcat(newName, name);
				strcat(newName, " ");
				m_layerList.AddString(newName);
			}
			pLayer->close();
		}

		// You can't drag any item beyond the last item in CDragListbox by default.
		//This sample workaroud this problem by appending an empty string to the end of layer list.
		m_layerList.AddString("");

		return true;
	}
	else //if iRepeats != NULL
	{

		for (int i = 0; i < layers.length(); i++)
		{
			AcDbObject* pLayer;
			if (Acad::eOk == acdbOpenObject(pLayer, layers.at(i), AcDb::kForRead))
			{
				const char* name;
				AcDbLayerTableRecord::cast(pLayer)->getName(name);

				//iRepeats->GetAt(i) > 0 indicates the draworders of entities on layers.at(i) are not continuous
				if (iRepeats->GetAt(i) > 0)
				{
					char newName[kNameLength];
					//prefix "*"
					strcpy(newName, "*");
					strcat(newName, name);
					//postfix "*"
					strcat(newName, "*");
					m_layerList.AddString(newName);
				}else //if iRepeat->GetAt(i)==0, the draworders of entities on layers.at(i) are continous
				{
					char newName[kNameLength];
					//prefix " "
					strcpy(newName, " ");
					strcat(newName, name);
					//postfix " "
					strcat(newName, " ");
					m_layerList.AddString(newName);
				}

			}
			pLayer->close();
		}

		m_layerList.AddString("");

		return true;
	}
}

//This function is to let tooltip control to handle messages first. This is used to display tooltips on buttons
BOOL layerDialog::PreTranslateMessage(MSG* pMsg)
{
	m_tooltipCtrl.RelayEvent(pMsg);
	return CDialog::PreTranslateMessage(pMsg);
}

// onInitDialog event handling
BOOL layerDialog::OnInitDialog( )
{
	CDialog::OnInitDialog();

	//Create tooltips
	m_tooltipCtrl.Create(this);
	m_tooltipCtrl.SetMaxTipWidth(300);
	m_tooltipCtrl.Activate(true);
	m_tooltipCtrl.AddTool(&m_entOrderBtn, _T("\r\n Sort the layer list by the order \r\n  entities appear in the drawing \r\n"));
	m_tooltipCtrl.AddTool(&m_layerOrderBtn, _T("\r\n Sort the layer list by the \r\n order in the layer table. \r\n"));

	//Displayer all the layers in the order in the layer table
	m_layerList.SubclassDlgItem(IDC_LAYERLIST, this);
	AcDbObjectIdArray arrAllLayers;
	if(getAllLayers(arrAllLayers))
		if(displayLayerOrder(arrAllLayers, NULL))
			return true;

	return false;
}

//Button,"cancel",is clicked
void layerDialog::OnBnClickedClose()
{
	OnCancel();
}

//Button,"Sort By Entity Order", is clicked
void layerDialog::OnBnClickedButtonEntorder()
{
	Acad::ErrorStatus es ;
	AcDbObjectIdArray ents;
	AcDbObjectIdArray layers;
	CUIntArray iRepeat;
	AcDbSortentsTable *pSortTab = NULL;

	//Get the AcDbSortEntsTable object
	if(getOrCreateSortEntsDictionary(pSortTab))
	{

		//Get the draw order of all the entities
		es = pSortTab->getFullDrawOrder(ents);
		pSortTab->close();
		pSortTab = NULL;
		if(es == Acad::eOk)
		{
			if(ents.isEmpty() == Adesk::kFalse)
			{
				//Iterate through all the entities
				for(int i = 0; i < ents.length(); i++)
				{
					AcDbEntity* pEnt;
					acdbOpenObject(pEnt,ents.at(i),AcDb::kForRead);
					//If the array "layers" is empty, append the entity's layerId to array "layers"
					//and append 0 to array "iRepeats"

					if(layers.isEmpty() == true)
					{
						layers.append(pEnt->layerId());
						iRepeat.Add(0);
					}
					else //if layers.isEmpty() == false
					{
						//If the entity's layerId is the same as the layerId of last entity, go to the next entity.
						if( pEnt->layerId() == layers.last())
							continue;

						int index;
						//If the entity's layerId is not the same as the last entity, but it's appeared before, change the
						//corresponding item in array "iRepeat" to 1 to indicate the draworders of entities on that layer are
						//not continuous
						if(Adesk::kTrue == layers.find( pEnt->layerId(), index))
						{
							iRepeat.SetAt(index, 1);
						}else //If the entity's layerId hasn't appear before, append it to the array ,"layers"
						{
							layers.append(pEnt->layerId());
							iRepeat.Add(0);
						}
					}

					pEnt->close();
				}

			}
		}
		//Display the layer order in the dragListBox.
		displayLayerOrder(layers, &iRepeat);
	}
}

//Button, "Sort By Layer Table" is clicked
void layerDialog::OnBnClickedButtonLayerorder()
{
	AcDbObjectIdArray arrAllLayers;

	//Get all the layerIds in the layer table
	getAllLayers(arrAllLayers);

	//Display all the layers in the order in layer table.
	displayLayerOrder(arrAllLayers,NULL);
}

//Button, "Apply", is clicked
void layerDialog::OnBnClickedButtonApply()
{
	//redraw entities based on the layer order in the dragListBox
	ApplyLayerOrder();

	//Refresh the layer list in the dragListBox.
	refreshList();

	return;

}

//Button,"OK" , is clicked
void layerDialog::OnBnClickedButtonok()
{
	//redraw entities based on the layer order in the dragListBox
	ApplyLayerOrder();

	OnOK();
}

//If the last item in the dragListBox(the empty string) is selected,
//deselect it and select the last layer name in stead.
void layerDialog::OnLbnSelchangeLayerlist()
{
	if(m_layerList.GetCurSel()==m_layerList.GetCount()-1)
	{
		m_layerList.SetCurSel(m_layerList.GetCount()-2);
	}
}

//Refresh the layer list in the dragBox after reordering the entities based on
//layer order. This is to change the prefix and postfix from "*" to " " since
//the draworders of entities on all the layers should be continuous by now.
bool layerDialog::refreshList(void)
{
	CStringArray arrItems;

	for(int i=0;i<m_layerList.GetCount();i++)
	{
		CString sItem;
		m_layerList.GetText(i,sItem);
		if(sItem[0]=='*')
			sItem.Replace('*',' ');
		arrItems.Add(sItem);
	}

	//Clear current display and display the updated names.
	m_layerList.ResetContent();

	for(int i=0;i<arrItems.GetCount();i++)
	{
		m_layerList.AddString(arrItems.GetAt(i));
	}

	return true;
}

//redraw all entities based on the order of the layers in the dragListBox
void layerDialog::ApplyLayerOrder(void)
{
	AcDbDatabase *pDb = acdbHostApplicationServices()->workingDatabase();
	Acad::ErrorStatus es ;

	if(pDb)
	{
		AcDbObjectIdArray AllEnts;

		//Iterate through the layer names in the dragListBox
		for (int i = 0; i < m_layerList.GetCount()-1; i++)
		{
			AcDbObjectIdArray entsOnLayer;
			CString str;
			char* layerName;
			m_layerList.GetText(i, str);
			//Remove prefix and postfix if there is any
			if(str[0] == ' ' || str[0] == '*')
				str = str.Mid(1, str.GetLength() - 2);
			layerName = str.GetBuffer(str.GetLength());
			//Get all the entities on the layer
			if(getAllEntitiesOnLayer(layerName, entsOnLayer))
				//Append all the entities on the layer to array, "AllEnts"
				AllEnts.append(entsOnLayer);
			str.ReleaseBuffer();
		}

		//Get the AcDbSortEntsTable
		AcDbSortentsTable *pSortTab = NULL;
		if(getOrCreateSortEntsDictionary(pSortTab))
		{
			//Use setRelativeDrawOrder method to set the entities' draworders based on the layer they reside
			es = pSortTab->setRelativeDrawOrder(AllEnts);
		}
		pSortTab->close();
		pSortTab = NULL;

		//Regen to update the screen.
		ads_regen();

		return;
	}
}


text:
#include <procinfo/process.h>

#include <fcntl.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>

#include <set>
#include <thread>
#include <vector>

#include <gtest/gtest.h>

#include <android-base/stringprintf.h>

#if !defined(__BIONIC__)
#include <syscall.h>
static pid_t gettid() {
  return syscall(__NR_gettid);
}
#endif

TEST(process_info, process_info_smoke) {
  android::procinfo::ProcessInfo self;
  ASSERT_TRUE(android::procinfo::GetProcessInfo(gettid(), &self));
  ASSERT_EQ(gettid(), self.tid);
  ASSERT_EQ(getpid(), self.pid);
  ASSERT_EQ(getppid(), self.ppid);
  ASSERT_EQ(getuid(), self.uid);
  ASSERT_EQ(getgid(), self.gid);
}

TEST(process_info, process_info_proc_pid_fd_smoke) {
  android::procinfo::ProcessInfo self;
  int fd = open(android::base::StringPrintf("/proc/%d", gettid()).c_str(), O_DIRECTORY | O_RDONLY);
  ASSERT_NE(-1, fd);
  ASSERT_TRUE(android::procinfo::GetProcessInfoFromProcPidFd(fd, &self));

  // Process name is capped at 15 bytes.
  ASSERT_EQ("libprocinfo_tes", self.name);
  ASSERT_EQ(gettid(), self.tid);
  ASSERT_EQ(getpid(), self.pid);
  ASSERT_EQ(getppid(), self.ppid);
  ASSERT_EQ(getuid(), self.uid);
  ASSERT_EQ(getgid(), self.gid);
  close(fd);
}

TEST(process_info, process_tids_smoke) {
  pid_t main_tid = gettid();
  std::thread([main_tid]() {
    pid_t thread_tid = gettid();

    {
      std::vector<pid_t> vec;
      ASSERT_TRUE(android::procinfo::GetProcessTids(getpid(), &vec));
      ASSERT_EQ(1, std::count(vec.begin(), vec.end(), main_tid));
      ASSERT_EQ(1, std::count(vec.begin(), vec.end(), thread_tid));
    }

    {
      std::set<pid_t> set;
      ASSERT_TRUE(android::procinfo::GetProcessTids(getpid(), &set));
      ASSERT_EQ(1, std::count(set.begin(), set.end(), main_tid));
      ASSERT_EQ(1, std::count(set.begin(), set.end(), thread_tid));
    }
  }).join();
}


text:
package org.jfree.data.xy;

import org.jfree.data.general.DatasetChangeEvent;
import org.jfree.data.general.DatasetChangeListener;
import org.jfree.util.PublicCloneable;

/**
 * A dataset wrapper class that converts a standard {@link XYDataset} into an
 * {@link IntervalXYDataset} suitable for use in creating XY bar charts.
 */
public class XYBarDataset extends AbstractIntervalXYDataset
                          implements IntervalXYDataset, DatasetChangeListener {

    /** The underlying dataset. */
    private XYDataset underlying;

    /** The bar width. */
    private double barWidth;

    /**
     * Creates a new dataset.
     *
     * @param underlying  the underlying dataset (null not
     *     permitted).
     * @param barWidth  the width of the bars.
     */
    public XYBarDataset(XYDataset underlying, double barWidth) {
        this.underlying = underlying;
        this.underlying.addChangeListener(this);
        this.barWidth = barWidth;
    }

    /**
     * Returns the underlying dataset that was specified via the constructor.
     *
     * @return The underlying dataset (never null).
     *
     * @since 1.0.4
     */
    public XYDataset getUnderlyingDataset() {
        return this.underlying;
    }

    /**
     * Returns the bar width.
     *
     * @return The bar width.
     *
     * @see #setBarWidth(double)
     * @since 1.0.4
     */
    public double getBarWidth() {
        return this.barWidth;
    }

    /**
     * Sets the bar width and sends a {@link DatasetChangeEvent} to all
     * registered listeners.
     *
     * @param barWidth  the bar width.
     *
     * @see #getBarWidth()
     * @since 1.0.4
     */
    public void setBarWidth(double barWidth) {
        this.barWidth = barWidth;
        notifyListeners(new DatasetChangeEvent(this, this));
    }

    /**
     * Returns the number of series in the dataset.
     *
     * @return The series count.
     */
    public int getSeriesCount() {
        return this.underlying.getSeriesCount();
    }

    /**
     * Returns the key for a series.
     *
     * @param series  the series index (in the range 0 to
     *     getSeriesCount() - 1).
     *
     * @return The series key.
     */
    public Comparable getSeriesKey(int series) {
        return this.underlying.getSeriesKey(series);
    }

    /**
     * Returns the number of items in a series.
     *
     * @param series  the series index (zero-based).
     *
     * @return The item count.
     */
    public int getItemCount(int series) {
        return this.underlying.getItemCount(series);
    }

    /**
     * Returns the x-value for an item within a series.
     *
     * @param series  the series index (zero-based).
     * @param item  the item index (zero-based).
     *
     * @return The x-value.
     *
     * @see #getXValue(int, int)
     */
    public Number getX(int series, int item) {
        return this.underlying.getX(series, item);
    }

    /**
     * Returns the x-value (as a double primitive) for an item within a series.
     *
     * @param series  the series index (zero-based).
     * @param item  the item index (zero-based).
     *
     * @return The value.
     *
     * @see #getX(int, int)
     */
    public double getXValue(int series, int item) {
        return this.underlying.getXValue(series, item);
    }

    /**
     * Returns the y-value for an item within a series.
     *
     * @param series  the series index (zero-based).
     * @param item  the item index (zero-based).
     *
     * @return The y-value (possibly null).
     *
     * @see #getYValue(int, int)
     */
    public Number getY(int series, int item) {
        return this.underlying.getY(series, item);
    }

    /**
     * Returns the y-value (as a double primitive) for an item within a series.
     *
     * @param series  the series index (zero-based).
     * @param item  the item index (zero-based).
     *
     * @return The value.
     *
     * @see #getY(int, int)
     */
    public double getYValue(int series, int item) {
        return this.underlying.getYValue(series, item);
    }

    /**
     * Returns the starting X value for the specified series and item.
     *
     * @param series  the series index (zero-based).
     * @param item  the item index (zero-based).
     *
     * @return The value.
     */
    public Number getStartX(int series, int item) {
        Number result = null;
        Number xnum = this.underlying.getX(series, item);
        if (xnum != null) {
             result = new Double(xnum.doubleValue() - this.barWidth / 2.0);
        }
        return result;
    }

    /**
     * Returns the starting x-value (as a double primitive) for an item within
     * a series.
     *
     * @param series  the series index (zero-based).
     * @param item  the item index (zero-based).
     *
     * @return The value.
     *
     * @see #getXValue(int, int)
     */
    public double getStartXValue(int series, int item) {
        return getXValue(series, item) - this.barWidth / 2.0;
    }

    /**
     * Returns the ending X value for the specified series and item.
     *
     * @param series  the series index (zero-based).
     * @param item  the item index (zero-based).
     *
     * @return The value.
     */
    public Number getEndX(int series, int item) {
        Number result = null;
        Number xnum = this.underlying.getX(series, item);
        if (xnum != null) {
             result = new Double(xnum.doubleValue() + this.barWidth / 2.0);
        }
        return result;
    }

    /**
     * Returns the ending x-value (as a double primitive) for an item within
     * a series.
     *
     * @param series  the series index (zero-based).
     * @param item  the item index (zero-based).
     *
     * @return The value.
     *
     * @see #getXValue(int, int)
     */
    public double getEndXValue(int series, int item) {
        return getXValue(series, item) + this.barWidth / 2.0;
    }

    /**
     * Returns the starting Y value for the specified series and item.
     *
     * @param series  the series index (zero-based).
     * @param item  the item index (zero-based).
     *
     * @return The value.
     */
    public Number getStartY(int series, int item) {
        return this.underlying.getY(series, item);
    }

    /**
     * Returns the starting y-value (as a double primitive) for an item within
     * a series.
     *
     * @param series  the series index (zero-based).
     * @param item  the item index (zero-based).
     *
     * @return The value.
     *
     * @see #getYValue(int, int)
     */
    public double getStartYValue(int series, int item) {
        return getYValue(series, item);
    }

    /**
     * Returns the ending Y value for the specified series and item.
     *
     * @param series  the series index (zero-based).
     * @param item  the item index (zero-based).
     *
     * @return The value.
     */
    public Number getEndY(int series, int item) {
        return this.underlying.getY(series, item);
    }

    /**
     * Returns the ending y-value (as a double primitive) for an item within
     * a series.
     *
     * @param series  the series index (zero-based).
     * @param item  the item index (zero-based).
     *
     * @return The value.
     *
     * @see #getYValue(int, int)
     */
    public double getEndYValue(int series, int item) {
        return getYValue(series, item);
    }

    /**
     * Receives notification of an dataset change event.
     *
     * @param event  information about the event.
     */
    public void datasetChanged(DatasetChangeEvent event) {
        this.notifyListeners(event);
    }

    /**
     * Tests this dataset for equality with an arbitrary object.
     *
     * @param obj  the object (null permitted).
     *
     * @return A boolean.
     */
    public boolean equals(Object obj) {
        if (obj == this) {
            return true;
        }
        if (!(obj instanceof XYBarDataset)) {
            return false;
        }
        XYBarDataset that = (XYBarDataset) obj;
        if (!this.underlying.equals(that.underlying)) {
            return false;
        }
        if (this.barWidth != that.barWidth) {
            return false;
        }
        return true;
    }

    /**
     * Returns an independent copy of the dataset.  Note that:
     *

     *
the underlying dataset is only cloned if it implements the
     * {@link PublicCloneable} interface;

     *
the listeners registered with this dataset are not carried over to
     * the cloned dataset.

     *

     *
     * @return An independent copy of the dataset.
     *
     * @throws CloneNotSupportedException if the dataset cannot be cloned for
     *         any reason.
     */
    public Object clone() throws CloneNotSupportedException {
        XYBarDataset clone = (XYBarDataset) super.clone();
        if (this.underlying instanceof PublicCloneable) {
            clone.underlying
                    = (XYDataset) ((PublicCloneable) this.underlying).clone();
        }
        return clone;
    }

}


text:
import generateCodeMap from 'ember-keyboard/utils/generate-code-map';

let platform, product = '';

if (typeof FastBoot === 'undefined') {
  platform = navigator.platform;
  product = navigator.product;
}

export default generateCodeMap(platform, product);


text:
using System;
using MqttLib;

/// <summary>
/// Delegate represents end-point for receipt of messages
/// </summary>
/// <param name="sender">Object responsible for invoking the delegate</param>
/// <param name="e">Arguments containing Message body and other detains</param>
/// <returns>return true to signify receipt of the message</returns>
public delegate bool PublishArrivedDelegate(object sender, PublishArrivedArgs e);

/// <summary>
/// Delegate represents completion of some task, such as message delivery.
/// </summary>
/// <param name="sender">Object responsible for invoking the delegate</param>
/// <param name="e">Arguments contain a unique ID for the completed task. This
/// ID will have been provided on initiating the task</param>
public delegate void CompleteDelegate(object sender, CompleteArgs e);

/// <summary>
/// Delegate represents a change in connection status.
/// </summary>
/// <param name="sender">Object responsible for invoking the delegate</param>
/// <param name="e"></param>
public delegate void ConnectionDelegate(object sender, EventArgs e);


text:
import sys

from setuptools import setup, find_packages

import versioneer
versioneer.versionfile_source = 'obfsproxy/_version.py'
versioneer.versionfile_build = 'obfsproxy/_version.py'
versioneer.tag_prefix = 'obfsproxy-' # tags are like 1.2.0
versioneer.parentdir_prefix = 'obfsproxy-' # dirname like 'myproject-1.2.0'

setup(
    name = "obfsproxy",
    author = "asn",
    author_email = "asn@torproject.org",
    description = ("A pluggable transport proxy written in Python"),
    license = "BSD",
    keywords = ['tor', 'obfuscation', 'twisted'],

    version=versioneer.get_version(),
    cmdclass=versioneer.get_cmdclass(),

    packages = find_packages(),
    entry_points = {
        'console_scripts': [
            'obfsproxy = obfsproxy.pyobfsproxy:run'
            ]
        },

    install_requires = [
        'setuptools',
        'PyCrypto',
        'Twisted',
        'argparse',
        'pyptlib >= 0.0.6',
        'pyyaml'
        ],

    extras_require = {
        'SOCKS': ["txsocksx"]
        }
)


text:
#ifndef TENSORFLOW_CONTRIB_S3_S3_FILE_SYSTEM_H_
#define TENSORFLOW_CONTRIB_S3_S3_FILE_SYSTEM_H_

#include <aws/s3/S3Client.h>
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/mutex.h"

namespace tensorflow {

class S3FileSystem : public FileSystem {
 public:
  S3FileSystem();
  ~S3FileSystem();

  Status NewRandomAccessFile(
      const string& fname, std::unique_ptr<RandomAccessFile>* result) override;

  Status NewWritableFile(const string& fname,
                         std::unique_ptr<WritableFile>* result) override;

  Status NewAppendableFile(const string& fname,
                           std::unique_ptr<WritableFile>* result) override;

  Status NewReadOnlyMemoryRegionFromFile(
      const string& fname,
      std::unique_ptr<ReadOnlyMemoryRegion>* result) override;

  Status FileExists(const string& fname) override;

  Status GetChildren(const string& dir, std::vector<string>* result) override;

  Status Stat(const string& fname, FileStatistics* stat) override;

  Status DeleteFile(const string& fname) override;

  Status CreateDir(const string& name) override;

  Status DeleteDir(const string& name) override;

  Status GetFileSize(const string& fname, uint64* size) override;

  Status RenameFile(const string& src, const string& target) override;
 private:
  // Returns the member S3 client, initializing as-needed.
  // When the client tries to access the object in S3, e.g.,
  //   s3://bucket-name/path/to/object
  // the behavior could be controlled by various environmental
  // variables.
  // By default S3 access regional endpoint, with region
  // controlled by `AWS_REGION`. The endpoint could be overridden
  // explicitly with `S3_ENDPOINT`. S3 uses HTTPS by default.
  // If S3_USE_HTTPS=0 is specified, HTTP is used. Also,
  // S3_VERIFY_SSL=0 could disable SSL verification in case
  // HTTPS is used.
  // This S3 Client does not support Virtual Hosted–Style Method
  // for a bucket.
  std::shared_ptr<Aws::S3::S3Client> GetS3Client();

  std::shared_ptr<Aws::S3::S3Client> s3_client_;
  // Lock held when checking for s3_client_ initialization.
  mutex client_lock_;
};

}  // namespace tensorflow

#endif  // TENSORFLOW_CONTRIB_S3_S3_FILE_SYSTEM_H_


text:
extern crate rustc_serialize;

#[derive(RustcDecodable, RustcEncodable)]
pub struct GetRequest {
    pub key: String
}

#[derive(RustcDecodable, RustcEncodable)]
pub struct GetResponse {
    pub value: String
}

#[derive(RustcDecodable, RustcEncodable)]
pub struct SetRequest {
    pub key: String,
    pub value: String
}

#[derive(RustcDecodable, RustcEncodable)]
pub struct SetResponse {
    pub status: String
}


text:
from django.db import models
from django.urls import reverse

from osm_field.fields import LatitudeField, LongitudeField, OSMField

class ExampleModel(models.Model):
    location = OSMField()
    location_lat = LatitudeField()
    location_lon = LongitudeField()
    another = OSMField(lat_field="some_lat_field", lon_field="other_lon_field")
    some_lat_field = LatitudeField()
    other_lon_field = LongitudeField()

    def __str__(self):
        return str(self.get_location_info())

    def get_absolute_url(self):
        return reverse("detail", kwargs={"pk": self.pk})


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Nova Hedwigia, Beih. 111: 66 (1996)

#### Original name
Marasmius micraster var. brevipes Corner

### Remarks
null


text:
  display: none;
}

#container, #main {
  width: auto;
  height: auto;
  float: none;
}

#header {
  display: none;
}

h4.blueblk {
  background: white;
  border: none;
}

.post {
  margin-bottom: 5px;
}

.admintools {
  display: none;
}

.comment-list li, input, textarea, select, body, #header, #content {
  background: white;
}


text:
class RemoveBoardIdFromActivity < ActiveRecord::Migration[5.0]
  def change
    remove_column :activities, :board_id, :integer
  end
end


text:
'use strict';

const Fs = require('fs');
const ChildProcess = require('child_process');
const Path = require('path');

const internals = {
    tempFolder: Path.join(__dirname,'_temp')
};

// These should only run once
process.on('exit', () => {

    ChildProcess.exec('rm -rf ' + internals.tempFolder, (err1) => {});
});

if (!Fs.existsSync(internals.tempFolder)) {
    Fs.mkdirSync(internals.tempFolder);
}


text:
These files switch an Xubuntu PC between Laptop-only display and dual monitor setup via external HDMI.
The scripts include setting the xfce4-panel to the primary monitor on HDMI.


text:
import * as React from 'react';
import { IconBaseProps } from 'react-icon-base';
export default class TiGroupOutline extends React.Component<IconBaseProps, any> { }


text:
/*
Gradebook from Names and Scores
I worked on this challenge [Caroline Kenworthy & Nicolette Chambers]
This challenge took me [#] hours.
You will work with the following two variables.  The first, students, holds the names of four students.
The second, scores, holds groups of test scores.  The relative positions of elements within the two
variables match (i.e., 'Joseph' is the first element in students; his scores are the first value in scores.).
Do not alter the students and scores code.
*/

var students = ["Joseph", "Susan", "William", "Elizabeth"]

var scores = [ [80, 70, 70, 100],
               [85, 80, 90, 90],
               [75, 70, 80, 75],
               [100, 90, 95, 85] ]

// __________________________________________
// Write your code below.
// var gradebook = {
//   Joseph: {testScores: scores[0]},
//   Susan: {testScores: scores[1]},
//   William: {testScores: scores[2]},
//   Elizabeth: {testScores: scores[3]},
//   addScore : function(name, score){
//                  gradebook[name].testScores.push(score);
//              },
//   getAverage : function(name) {
//                 return average(gradebook[name].testScores);
//                },
// };

// function average(arr) {
//       var sum = arr.reduce(
//           function(total, num){
//             return total + num;
//           } , 0);

//       return (sum / arr.length);
// };

// __________________________________________
// Refactored Solution

var gradebook = {
  Joseph: {testScores: scores[0]},
  Susan: {testScores: scores[1]},
  William: {testScores: scores[2]},
  Elizabeth: {testScores: scores[3]},
  addScore : function(name, score){
                 this[name].testScores.push(score);
  },
  getAverage : function(name) {
                return average(this[name].testScores);
  },
};

function average(arr) {
      var sum = arr.reduce(function(total, num){
            return total + num;
      });

      return (sum / arr.length);
};

// __________________________________________
// Reflect
// What did you learn about adding functions to objects?
// I learned about the usage of the keyword this.
// We used the this keyword before in one of the challenges last week.
// However, I didn't really understand why we had to use it.
// However, when refactoring it became clear that I could substitute the object name for the this keyword.

// How did you iterate over nested arrays in JavaScript?
// We used the reduce function.

// Were there any new methods you were able to incorporate? If so, what were they and how did they work?
// My pair introduced me to reduce. I wasn't familiar with it before this challenge.

// __________________________________________
// Test Code:  Do not alter code below this line.

function assert(test, message, test_number) {
  if (!test) {
    console.log(test_number + "false");
    throw "ERROR: " + message;
  }
  console.log(test_number + "true");
  return true;
}

assert(
  (gradebook instanceof Object),
  "The value of gradebook should be an Object.\n",
  "1. "
)

assert(
  (gradebook["Elizabeth"] instanceof Object),
  "gradebook's Elizabeth property should be an object.",
  "2. "
)

assert(
  (gradebook.William.testScores === scores[2]),
  "William's testScores should equal the third element in scores.",
  "3. "
)

assert(
  (gradebook.addScore instanceof Function),
  "The value of gradebook's addScore property should be a Function.",
  "4. "
)

gradebook.addScore("Susan", 80)

assert(
  (gradebook.Susan.testScores.length === 5
   && gradebook.Susan.testScores[4] === 80),
  "Susan's testScores should have a new score of 80 added to the end.",
  "5. "
)

assert(
  (gradebook.getAverage instanceof Function),
  "The value of gradebook's getAverage property should be a Function.",
  "6. "
)

assert(
  (average instanceof Function),
  "The value of average should be a Function.\n",
  "7. "
)
assert(
  average([1, 2, 3]) === 2,
  "average should return the average of the elements in the array argument.\n",
  "8. "
)

assert(
  (gradebook.getAverage("Joseph") === 80),
  "gradebook's getAverage should return 80 if passed 'Joseph'.",
  "9. "
)


text: function hello() {'use strict'; eval = 10; }


text:
package net.hydromatic.linq4j;

import java.util.Arrays;
import java.util.List;

/**
 * Enumerator over the cartesian product of enumerators.
 *
 * @param <T> Element type
 */
class CartesianProductEnumerator<T> implements Enumerator<List<T>> {
  private final List<Enumerator<T>> enumerators;
  private final T[] elements;
  private boolean first = true;

  public CartesianProductEnumerator(List<Enumerator<T>> enumerators) {
    this.enumerators = enumerators;
    //noinspection unchecked
    this.elements = (T[]) new Object[enumerators.size()];
  }

  public List<T> current() {
    return Arrays.asList(elements.clone());
  }

  public boolean moveNext() {
    if (first) {
      if (enumerators.isEmpty()) {
        return false;
      }
      int i = 0;
      for (Enumerator<T> enumerator : enumerators) {
        if (!enumerator.moveNext()) {
          return false;
        }
        elements[i++] = enumerator.current();
      }
      first = false;
      return true;
    }
    int ordinal = enumerators.size() - 1;
    for (;;) {
      final Enumerator<T> enumerator = enumerators.get(ordinal);
      if (enumerator.moveNext()) {
        elements[ordinal] = enumerator.current();
        return true;
      }

      // Move back to first element.
      enumerator.reset();
      if (!enumerator.moveNext()) {
        // Very strange... this was empty all along.
        return false;
      }
      elements[ordinal] = enumerator.current();

      // Advance higher rank enumerator.
      if (ordinal == 0) {
        return false;
      }
      --ordinal;
    }
  }

  public void reset() {
    first = true;
  }

  public void close() {
    // If there is one or more exceptions, carry on and close all enumerators,
    // then throw the first.
    Throwable rte = null;
    for (Enumerator<T> enumerator : enumerators) {
      try {
        enumerator.close();
      } catch (Throwable e) {
        rte = e;
      }
    }
    if (rte != null) {
      if (rte instanceof Error) {
        throw (Error) rte;
      } else {
        throw (RuntimeException) rte;
      }
    }
  }
}

// End CartesianProductEnumerator.java


text:
'use strict';

const fs = require('fs');
if (process.argv.length < 3) {
  console.log('File not provided');
  process.exit(1);
}

try {
  const path = process.argv[2];
  const data = fs.readFileSync(path);
  const reportCategories = JSON.parse(data).reportCategories;
  const pwa = reportCategories.find(a => a.name === 'Progressive Web App');
  const pwaAvg = pwa.audits.reduce((last, s) => {
    return last + s.score;
  }, 0) / pwa.audits.filter((s) => {return !s.result.manual}).length;

  const performance = reportCategories.find(a => a.name === 'Performance');
  const performanceAvg = performance.audits.reduce((last, s) => {
    return last + s.score;
  }, 0) / performance.audits.filter((s) => {return !s.result.manual}).length;

  const accessibility = reportCategories.find(a => a.name === 'Accessibility');
  const accessibilityAvg = accessibility.audits.reduce((last, s) => {
    return last + s.score;
  }, 0) / accessibility.audits.filter((s) => {return !s.result.manual}).length;

  const bestPractices = reportCategories.find(a => a.name === 'Best Practices');
  const bestPracticesAvg = bestPractices.audits.reduce((last, s) => {
    return last + s.score;
  }, 0) / bestPractices.audits.filter((s) => {return !s.result.manual}).length;

  // Failed to get more than 80% in the PWA section, so bail.
  // This is currently super lenient because I'm not testing over HTTPS, which
  // means those tests will fail.
  console.log(`PWA Score: ${pwaAvg}. Performance Score: ${performanceAvg}. Accessibility Score: ${accessibilityAvg}. Best Practices Score: ${bestPracticesAvg}.`);

  if (pwaAvg < 0.8) {
    console.log(JSON.stringify(pwa, null, 2));
    process.exit(1);
  }

  // All good.
  process.exit(0);
} catch (e) {
  console.log(e);
  process.exit(1);
}


text:
import {SubmissionError} from 'redux-form';
import create from './create';
export {SUFFIX} from './common';

export const {onSubmitActions, formSubmitSaga, addFormSubmitSagaTo} = create(SubmissionError);


text:
<?php

declare(strict_types=1);

namespace PentagonalProject\App\Rest\Exceptions;

/**
 * Class UnauthorizedException
 * @package PentagonalProject\App\Rest\Exceptions
 */
class UnauthorizedException extends \ErrorException
{
}


text:
module TestData (

  AprioriTestData(..)
, AprioriDebugData(..)

, AssocRulesTestData(..)

) where

import DataAssociation.Definitions
import DataAssociation.APriori.Debug

data AprioriTestData set it = AprioriTestData{
  tTransactions :: [set it]
, tMinsup  :: MinSupport
, tRuns    :: [AprioriDebugData set it]
}

data AssocRulesTestData set it = AssocRulesTestData{
  trTransactions :: [set it]
, tLargeItemset  :: (set it, Float)
, tMinconf       :: MinConfidence
, tRules         :: [AssocRule set it]
}


text:
package org.semanticweb.cogExp.OWLFormulas;

/** Class represents integer values to be part of cardinality restrictions
 *
 * @author marvin
 *
 */
public class OWLInteger implements OWLAtom{
	private int value;

	public OWLInteger(int value){
		this.value = value;
	}

	public int getValue(){
		return value;
	}

	@Override
	public boolean equals(Object other){
	    if (other == null) return false;
	    if (other == this) return true;
	    if (!(other instanceof OWLInteger))return false;
	    boolean valsSame = value==(((OWLInteger) other).getValue());
	    if (!valsSame){return false;}
	    // System.out.println("class name equal? " + classname + " / " + ((OWLClassName) other).getName() + " AND " + ontologyname + " / " + ((OWLClassName) other).ontologyname);
	    return valsSame;
	}

	@Override
    public int hashCode() {
        int hash = 1;
        hash = hash * 17 + this.value;
        // for (OWLFormula form : this.tail){
        // 	hash = hash * 31 + form.hashCode();
        // }
        return hash;
    }

	@Override
	public String toString(){
		return "|" + value + "|";
	}

	@Override
	public OWLInteger clone(){
		return new OWLInteger(value);
	}

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

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

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

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

}


text:
_cset :cache_dir, 'cache'

## Tasks
namespace :deploy do
  namespace :cache do
    task :clear, :roles => :app, :only => { :primary => true } do
      run "find #{fetch(:current_path)}/public/#{fetch(:cache_dir)} -type f -delete"
    end
  end
end


text:
The Docker systemd unit can be customized by overriding the unit that ships with the default Container Linux settings. Common use-cases for doing this are covered below.

## Enable the remote API on a new socket

Create a file called `/etc/systemd/system/docker-tcp.socket` to make Docker available on a TCP socket on port 2375.

```ini
[Unit]
Description=Docker Socket for the API

[Socket]
ListenStream=2375
BindIPv6Only=both
Service=docker.service

[Install]
WantedBy=sockets.target
```

Then enable this new socket:

```sh
systemctl enable docker-tcp.socket
systemctl stop docker
systemctl start docker-tcp.socket
systemctl start docker
```

Test that it's working:

```sh
docker -H tcp://127.0.0.1:2375 ps
```

### Container Linux Config

To enable the remote API on every Container Linux machine in a cluster, use a [Container Linux Config][cl-configs]. We need to provide the new socket file and Docker's socket activation support will automatically start using the socket:

```yaml container-linux-config
systemd:
  units:
    - name: docker-tcp.socket
      enable: true
      contents: |
        [Unit]
        Description=Docker Socket for the API

        [Socket]
        ListenStream=2375
        BindIPv6Only=both
        Service=docker.service

        [Install]
        WantedBy=sockets.target
```

To keep access to the port local, replace the `ListenStream` configuration above with:

```yaml
        [Socket]
        ListenStream=127.0.0.1:2375
```

## Enable the remote API with TLS authentication

Docker TLS configuration consists of three parts: keys creation, configuring new [systemd socket][systemd-socket] unit and systemd [drop-in][drop-in] configuration.

### TLS keys creation

Please follow the [instruction][self-signed-certs] to know how to create self-signed certificates and private keys. Then copy with following files into `/etc/docker` Container Linux's directory and fix their permissions:

```sh
scp ~/cfssl/{server.pem,server-key.pem,ca.pem} coreos.example.com:
ssh core@coreos.example.com
sudo mv {server.pem,server-key.pem,ca.pem} /etc/docker/
sudo chown root:root /etc/docker/{server-key.pem,server.pem,ca.pem}
sudo chmod 0600 /etc/docker/server-key.pem
```

On your local host copy certificates into `~/.docker`:

```sh
mkdir ~/.docker
chmod 700 ~/.docker
cd ~/.docker
cp -p ~/cfssl/ca.pem ca.pem
cp -p ~/cfssl/client.pem cert.pem
cp -p ~/cfssl/client-key.pem key.pem
```

### Enable the secure remote API on a new socket

Create a file called `/etc/systemd/system/docker-tls-tcp.socket` to make Docker available on a secured TCP socket on port 2376.

```ini
[Unit]
Description=Docker Secured Socket for the API

[Socket]
ListenStream=2376
BindIPv6Only=both
Service=docker.service

[Install]
WantedBy=sockets.target
```

Then enable this new socket:

```sh
systemctl enable docker-tls-tcp.socket
systemctl stop docker
systemctl start docker-tls-tcp.socket
```

### Drop-in configuration

Create `/etc/systemd/system/docker.service.d/10-tls-verify.conf` [drop-in][drop-in] for systemd Docker service:

```ini
[Service]
Environment="DOCKER_OPTS=--tlsverify --tlscacert=/etc/docker/ca.pem --tlscert=/etc/docker/server.pem --tlskey=/etc/docker/server-key.pem"
```

Reload systemd config files and restart docker service:

```sh
sudo systemctl daemon-reload
sudo systemctl restart docker.service
```

Now you can access your Docker's API through TLS secured connection:

```sh
docker --tlsverify -H tcp://server:2376 images
# or
docker --tlsverify -H tcp://server.example.com:2376 images
```

If you've experienceed problems connection to remote Docker API using TLS connection, you can debug it with `curl`:

```sh
curl -v --cacert ~/.docker/ca.pem --cert ~/.docker/cert.pem --key ~/.docker/key.pem https://server:2376
```

Or on your Container Linux host:

```sh
journalctl -f -u docker.service
```

In addition you can export environment variables and use docker client without additional options:

```sh
export DOCKER_HOST=tcp://server.example.com:2376 DOCKER_TLS_VERIFY=1
docker images
```

### Container Linux Config

A Container Linux Config for Docker TLS authentication will look like:

```yaml container-linux-config
storage:
  files:
    - path: /etc/docker/ca.pem
      filesystem: root
      mode: 0644
      contents:
        inline: |
          -----BEGIN CERTIFICATE-----
          MIIFNDCCAx6gAwIBAgIBATALBgkqhkiG9w0BAQswLTEMMAoGA1UEBhMDVVNBMRAw
          DgYDVQQKEwdldGNkLWNhMQswCQYDVQQLEwJDQTAeFw0xNTA5MDIxMDExMDhaFw0y
          NTA5MDIxMDExMThaMC0xDDAKBgNVBAYTA1VTQTEQMA4GA1UEChMHZXRjZC1jYTEL
          ... ... ...
    - path: /etc/docker/server.pem
      filesystem: root
      mode: 0644
      contents:
        inline: |
          -----BEGIN CERTIFICATE-----
          MIIFajCCA1SgAwIBAgIBBTALBgkqhkiG9w0BAQswLTEMMAoGA1UEBhMDVVNBMRAw
          DgYDVQQKEwdldGNkLWNhMQswCQYDVQQLEwJDQTAeFw0xNTA5MDIxMDM3MDFaFw0y
          NTA5MDIxMDM3MDNaMEQxDDAKBgNVBAYTA1VTQTEQMA4GA1UEChMHZXRjZC1jYTEQ
          ... ... ...
    - path: /etc/docker/server-key.pem
      filesystem: root
      mode: 0644
      contents:
        inline: |
          -----BEGIN RSA PRIVATE KEY-----
          MIIJKAIBAAKCAgEA23Q4yELhNEywScrHl6+MUtbonCu59LIjpxDMAGxAHvWhWpEY
          P5vfas8KgxxNyR+U8VpIjEXvwnhwCx/CSCJc3/VtU9v011Ir0WtTrNDocb90fIr3
          YeRWq744UJpBeDHPV9opf8xFE7F74zWeTVMwtiMPKcQDzZ7XoNyJMxg1wmiMbdCj
          ... ... ...
systemd:
  units:
    - name: docker-tls-tcp.socket
      enable: true
      contents: |
        [Unit]
        Description=Docker Secured Socket for the API

        [Socket]
        ListenStream=2376
        BindIPv6Only=both
        Service=docker.service

        [Install]
        WantedBy=sockets.target
docker:
  flags:
    - --tlsverify
    - --tlscacert=/etc/docker/ca.pem
    - --tlscert=/etc/docker/server.pem
    - --tlskey=/etc/docker/server-key.pem
```

## Use attached storage for Docker images

Docker containers can be very large and debugging a build process makes it easy to accumulate hundreds of containers. It's advantageous to use attached storage to expand your capacity for container images. Check out the guide to [mounting storage to your Container Linux machine][mounting-storage] for an example of how to bind mount storage into `/var/lib/docker`.

## Enabling the Docker debug flag

Set the `--debug` (`-D`) flag in the `DOCKER_OPTS` environment variable by using a drop-in file. For example, the following could be written to `/etc/systemd/system/docker.service.d/10-debug.conf`:

```ini
[Service]
Environment=DOCKER_OPTS=--debug
```

Now tell systemd about the new configuration and restart Docker:

```sh
systemctl daemon-reload
systemctl restart docker
```

To test our debugging stream, run a Docker command and then read the systemd journal, which should contain the output:

```sh
docker ps
journalctl -u docker
```

### Container Linux Config

If you need to modify a flag across many machines, you can add the flag with a Container Linux Config:

```yaml container-linux-config
docker:
  flags:
    - --debug
```

## Use an HTTP proxy

If you're operating in a locked down networking environment, you can specify an HTTP proxy for Docker to use via an environment variable. First, create a directory for drop-in configuration for Docker:

```sh
mkdir /etc/systemd/system/docker.service.d
```

Now, create a file called `/etc/systemd/system/docker.service.d/http-proxy.conf` that adds the environment variable:

```ini
[Service]
Environment="HTTP_PROXY=http://proxy.example.com:8080"
```

To apply the change, reload the unit and restart Docker:

```sh
systemctl daemon-reload
systemctl restart docker
```

Proxy environment variables can also be set [system-wide][systemd-env-vars].

### Container Linux Config

The easiest way to use this proxy on all of your machines is via a Container Linux Config:

```yaml container-linux-config
systemd:
  units:
    - name: docker.service
      enable: true
      dropins:
        - name: 20-http-proxy.conf
          contents: |
            [Service]
            Environment="HTTP_PROXY=http://proxy.example.com:8080"
```

## Increase ulimits

If you need to increase certain ulimits that are too low for your application by default, like memlock, you will need to modify the Docker service to increase the limit. First, create a directory for drop-in configuration for Docker:

```sh
mkdir /etc/systemd/system/docker.service.d
```

Now, create a file called `/etc/systemd/system/docker.service.d/increase-ulimit.conf` that adds increased limit:

```ini
[Service]
LimitMEMLOCK=infinity
```

To apply the change, reload the unit and restart Docker:

```sh
systemctl daemon-reload
systemctl restart docker
```

### Container Linux Config

The easiest way to use these new ulimits on all of your machines is via a Container Linux Config:

```yaml container-linux-configs
systemd:
  units:
    - name: docker.service
      enable: true
      dropins:
        - name: 30-increase-ulimit.conf
          contents: |
            [Service]
            LimitMEMLOCK=infinity
```

## Using a dockercfg file for authentication

A json file `.dockercfg` can be created in your home directory that holds authentication information for a public or private Docker registry.

[docker-socket-systemd]: https://github.com/docker/docker/pull/17211
[drop-in]: using-systemd-drop-in-units.md
[mounting-storage]: mounting-storage.md
[self-signed-certs]: generate-self-signed-certificates.md
[systemd-socket]: https://www.freedesktop.org/software/systemd/man/systemd.socket.html
[systemd-env-vars]: https://coreos.com/os/docs/latest/using-environment-variables-in-systemd-units.html#system-wide-environment-variables
[cl-configs]: provisioning.md


text:
package com.alibaba.dubbo.demo.provider;

import com.alibaba.dubbo.demo.Rice;
import com.alibaba.dubbo.demo.RiceService;

public class RiceServiceImpl implements RiceService{
	public Rice wash(Rice rice) {
		System.out.println("------->wash rice");
		SleepUtil.sleep(1000);
		return rice;
	}
	public Rice cook(Rice rice) {
		System.out.println("------->cook rice");
		SleepUtil.sleep(2000);
		return rice;
	}
}


text:
package org.ovirt.engine.ui.webadmin.section.main.view.popup.storage;

import org.ovirt.engine.core.common.businessentities.VDS;
import org.ovirt.engine.ui.common.idhandler.ElementIdHandler;
import org.ovirt.engine.ui.common.idhandler.WithElementId;
import org.ovirt.engine.ui.common.view.popup.AbstractModelBoundPopupView;
import org.ovirt.engine.ui.common.widget.Align;
import org.ovirt.engine.ui.common.widget.dialog.SimpleDialogPanel;
import org.ovirt.engine.ui.common.widget.editor.ListModelListBoxEditor;
import org.ovirt.engine.ui.common.widget.editor.generic.EntityModelCheckBoxEditor;
import org.ovirt.engine.ui.common.widget.renderer.NameRenderer;
import org.ovirt.engine.ui.uicommonweb.models.storage.RemoveStorageModel;
import org.ovirt.engine.ui.webadmin.ApplicationConstants;
import org.ovirt.engine.ui.webadmin.gin.AssetProvider;
import org.ovirt.engine.ui.webadmin.section.main.presenter.popup.storage.StorageRemovePopupPresenterWidget;
import com.google.gwt.core.client.GWT;
import com.google.gwt.editor.client.SimpleBeanEditorDriver;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.resources.client.CssResource;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Label;
import com.google.inject.Inject;

public class StorageRemovePopupView extends AbstractModelBoundPopupView<RemoveStorageModel>
        implements StorageRemovePopupPresenterWidget.ViewDef {

    interface Driver extends SimpleBeanEditorDriver<RemoveStorageModel, StorageRemovePopupView> {
    }

    interface ViewUiBinder extends UiBinder<SimpleDialogPanel, StorageRemovePopupView> {
        ViewUiBinder uiBinder = GWT.create(ViewUiBinder.class);
    }

    interface ViewIdHandler extends ElementIdHandler<StorageRemovePopupView> {
        ViewIdHandler idHandler = GWT.create(ViewIdHandler.class);
    }

    @UiField
    WidgetStyle style;

    @UiField(provided = true)
    @Path(value = "hostList.selectedItem")
    @WithElementId("hostList")
    ListModelListBoxEditor<VDS> hostListEditor;

    @UiField(provided = true)
    @Path(value = "format.entity")
    @WithElementId("format")
    EntityModelCheckBoxEditor formatEditor;

    @UiField
    Label message;

    private final Driver driver = GWT.create(Driver.class);

    private static final ApplicationConstants constants = AssetProvider.getConstants();

    @Inject
    public StorageRemovePopupView(EventBus eventBus) {
        super(eventBus);
        initListBoxEditors();
        initCheckBoxEditors();
        initWidget(ViewUiBinder.uiBinder.createAndBindUi(this));
        ViewIdHandler.idHandler.generateAndSetIds(this);
        localize();
        addStyles();
        driver.initialize(this);
    }

    void initListBoxEditors() {
        hostListEditor = new ListModelListBoxEditor<>(new NameRenderer<VDS>());
    }

    void initCheckBoxEditors() {
        formatEditor = new EntityModelCheckBoxEditor(Align.RIGHT);
    }

    void addStyles() {
        formatEditor.setLabelStyleName(style.formatLabel());
        formatEditor.addContentWidgetContainerStyleName(style.formatContentWidget());
    }

    void localize() {
        hostListEditor.setLabel(constants.storageRemovePopupHostLabel());
        formatEditor.setLabel(constants.storageRemovePopupFormatLabel());
    }

    @Override
    public void edit(RemoveStorageModel object) {
        driver.edit(object);
    }

    @Override
    public RemoveStorageModel flush() {
        return driver.flush();
    }

    interface WidgetStyle extends CssResource {
        String formatLabel();

        String formatContentWidget();
    }

}


text:
using System.IO;
using UnityEditor;
using UnityEngine;
using System.Collections.Generic;

namespace GetSocialSdk.Editors
{
    [InitializeOnLoad]
    public static class GetSocialEditorUtils
    {
        public static Texture2D AndroidIcon;
        public static Texture2D IOSIcon;
        public static Texture2D SettingsIcon;
        public static Texture2D InfoIcon;
        public static Texture2D GetSocialIcon;

        private static string editorPath;
        private static string editorGuiPath;

        static GetSocialEditorUtils()
        {
            Initialize();
            AndroidIcon = (Texture2D) AssetDatabase.LoadMainAssetAtPath(editorGuiPath + "/android.png");
            IOSIcon = (Texture2D) AssetDatabase.LoadMainAssetAtPath(editorGuiPath + "/ios.png");
            SettingsIcon = (Texture2D) AssetDatabase.LoadMainAssetAtPath(editorGuiPath + "/settings.png");
            InfoIcon = (Texture2D) AssetDatabase.LoadMainAssetAtPath(editorGuiPath + "/icon_info.png");
            GetSocialIcon = (Texture2D) AssetDatabase.LoadMainAssetAtPath(editorGuiPath + "/getsocial.png");
        }

        private static void Initialize()
        {
            var rootDir = new DirectoryInfo(Application.dataPath);
            var files = rootDir.GetFiles("GetSocialEditorUtils.cs", SearchOption.AllDirectories);
            editorPath = Path.GetDirectoryName(files[0].FullName.Replace("\\", "/").Replace(Application.dataPath, "Assets"));
            editorGuiPath = editorPath + "/GUI";
        }

        public static void BeginSetSmallIconSize()
        {
            EditorGUIUtility.SetIconSize(new Vector2(12, 12));
        }

        public static void EndSetSmallIconSize()
        {
            EditorGUIUtility.SetIconSize(Vector2.zero);
        }

        public static string[] GetFiles(string path, string searchPattern, SearchOption searchOption)
        {
            var searchPatterns = searchPattern.Split(';');
            var files = new List<string>();
            foreach (string sp in searchPatterns)
            {
                files.AddRange(System.IO.Directory.GetFiles(path, sp, searchOption));
            }
            files.Sort();
            return files.ToArray();
        }
    }
}


text:
<?php

defined('_JEXEC') or die;

/**
 * @package		Joomla.Administrator
 * @subpackage	com_config
 */
class ConfigViewApplication extends JViewLegacy
{
	public $state;
	public $form;
	public $data;

	/**
	 * Method to display the view.
	 */
	public function display($tpl = null)
	{
		$form	= $this->get('Form');
		$data	= $this->get('Data');

		// Check for model errors.
		if ($errors = $this->get('Errors')) {
			JError::raiseError(500, implode('<br />', $errors));
			return false;
		}

		// Bind the form to the data.
		if ($form && $data) {
			$form->bind($data);
		}

		// Get the params for com_users.
		$usersParams = JComponentHelper::getParams('com_users');

		// Get the params for com_media.
		$mediaParams = JComponentHelper::getParams('com_media');

		// Load settings for the FTP layer.
		$ftp = JClientHelper::setCredentialsFromRequest('ftp');

		$this->assignRef('form',	$form);
		$this->assignRef('data',	$data);
		$this->assignRef('ftp',		$ftp);
		$this->assignRef('usersParams', $usersParams);
		$this->assignRef('mediaParams', $mediaParams);

		$this->addToolbar();
		parent::display($tpl);
	}

	/**
	 * Add the page title and toolbar.
	 *
	 * @since	1.6
	 */
	protected function addToolbar()
	{
		JToolBarHelper::title(JText::_('COM_CONFIG_GLOBAL_CONFIGURATION'), 'config.png');
		JToolBarHelper::apply('application.apply');
		JToolBarHelper::save('application.save');
		JToolBarHelper::divider();
		JToolBarHelper::cancel('application.cancel');
		JToolBarHelper::divider();
		JToolBarHelper::help('JHELP_SITE_GLOBAL_CONFIGURATION');
	}
}


text:
<!-- toc -->
- [Terms](#terms)
- [Summary](#summary)
- [Motivation](#motivation)
  - [Goals](#goals)
  - [Non-Goals](#non-goals)
- [Proposal](#proposal)
  - [Approach](#approach)
    - [Phase 1 - Moving Cloud Provider Code to Staging](#phase-1---moving-cloud-provider-code-to-staging)
    - [Phase 2 - Building CCM from Provider Repos](#phase-2---building-ccm-from-provider-repos)
    - [Phase 3 - Migrating Provider Code to Provider Repos](#phase-3---migrating-provider-code-to-provider-repos)
    - [Phase 4 - Disabling In-Tree Providers](#phase-4---disabling-in-tree-providers)
  - [Staging Directory](#staging-directory)
    - [Cloud Provider Instances](#cloud-provider-instances)
- [Production Readiness Review Questionnaire](#production-readiness-review-questionnaire)
  - [Feature Enablement and Rollback](#feature-enablement-and-rollback)
  - [Rollout, Upgrade and Rollback Planning](#rollout-upgrade-and-rollback-planning)
  - [Monitoring Requirements](#monitoring-requirements)
  - [Dependencies](#dependencies)
  - [Scalability](#scalability)
  - [Troubleshooting](#troubleshooting)
- [Alternatives](#alternatives)
  - [Staging Alternatives](#staging-alternatives)
    - [Git Filter-Branch](#git-filter-branch)
  - [Build Location Alternatives](#build-location-alternatives)
    - [Build K8s/K8s from within K8s/Cloud-provider](#build-k8sk8s-from-within-k8scloud-provider)
    - [Build K8s/Cloud-provider within K8s/K8s](#build-k8scloud-provider-within-k8sk8s)
  - [Config Alternatives](#config-alternatives)
    - [Use component config to determine where controllers run](#use-component-config-to-determine-where-controllers-run)
<!-- /toc -->

## Terms

- **CCM**: Cloud Controller Manager - The controller manager responsible for running cloud provider dependent logic,
such as the service and route controllers.
- **KCM**: Kubernetes Controller Manager - The controller manager responsible for running generic Kubernetes logic,
such as job and node_lifecycle controllers.
- **KAS**: Kubernetes API Server - The core api server responsible for handling all API requests for the Kubernetes
control plane. This includes things like namespace, node, pod and job resources.
- **K8s/K8s**: The core kubernetes github repository.
- **K8s/cloud-provider**: Any or all of the repos for each cloud provider. Examples include [cloud-provider-gcp](https://github.com/kubernetes/cloud-provider-gcp),
[cloud-provider-aws](https://github.com/kubernetes/cloud-provider-aws) and [cloud-provider-azure](https://github.com/kubernetes/cloud-provider-azure).
We have created these repos for each of the in-tree cloud providers. This document assumes in various places that the
cloud providers will place the relevant code in these repos. Whether this is a long-term solution to which additional
cloud providers will be added, or an incremental step toward moving out of the Kubernetes org is out of scope of this
document, and merits discussion in a broader forum and input from SIG-Architecture and Steering Committee.
- **K8s SIGs/library**: Any SIG owned repository.
- **Staging**: Staging: Separate repositories which are currently visible under the K8s/K8s repo, which contain code
considered to be safe to be vendored outside of the K8s/K8s repo and which should eventually be fully separated from
the K8s/K8s repo. Contents of Staging are prevented from depending on code in K8s/K8s which are not in Staging.
Controlled by [publishing kubernetes-rules-configmap](https://github.com/kubernetes/publishing-bot/blob/master/configs/kubernetes-rules-configmap.yaml)
- **In-tree**: code that lives in the core Kubernetes repository [k8s.io/kubernetes](https://github.com/kubernetes/kubernetes/).
- **Out-of-Tree**: code that lives in an external repository outside of [k8s.io/kubernetes](https://github.com/kubernetes/kubernetes/).

## Summary

This is a proposal outlining steps to remove "in-tree" cloud provider code from the k8s.io/kubernetes repo while being
as least disruptive to end users and other Kubernetes developers as possible.

## Motivation

Motiviation behind this effort is to allow cloud providers to develop and make releases independent from the core
Kubernetes release cycle. The de-coupling of cloud provider code allows for separation of concern between "Kubernetes core"
and the cloud providers within the ecosystem. In addition, this ensures all cloud providers in the ecosystem are integrating with
Kubernetes in a consistent and extendable way.

Having all cloud providers developed/released in their own external repos/modules will result in the following benefits:
* The core pieces of Kubernetes (kubelet, kube-apiserver, kube-controller-manager, etc) will no longer depend on cloud provider specific
APIs (and their dependencies). This results in smaller binaries and lowers the chance of security vulnerabilities via external dependencies.
* Each cloud provider is free to release features/bug fixes at their own schedule rather than relying on the core Kubernetes release cycle.

### Goals

- Remove all cloud provider specific code from the `k8s.io/kubernetes` repository with minimal disruption to end users and developers.

### Non-Goals

- Testing/validating out-of-tree provider code for all cloud providers, this should be done by each provider.

## Proposal

### Approach

In order to remove cloud provider code from `k8s.io/kubernetes`. A 3 phase approach will be taken.

1. Move all code in `k8s.io/kubernetes/pkg/cloudprovider/providers/<provider>` to `k8s.io/kubernetes/staging/src/k8s.io/legacy-cloud-providers/<provider>/`. This requires removing all internal dependencies in each cloud provider to `k8s.io/kubernetes`.
2. Begin to build/release the CCM from external repos (`k8s.io/cloud-provider-<provider>`) with the option to import the legacy providers from `k8s.io/legacy-cloud-providers/<provider>`. This allows the cloud-controller-manager to opt into legacy behavior in-tree (for compatibility reasons) or build new implementations of the provider. Development for cloud providers in-tree is still done in `k8s.io/kubernetes/staging/src/k8s.io/legacy-cloud-providers/<provider>` during this phase.
3. Delete all code in `k8s.io/kubernetes/staging/src/k8s.io/legacy-cloud-providers` and shift main development to `k8s.io/cloud-provider-<provider>`. External cloud provider repos can optionally still import `k8s.io/legacy-cloud-providers` but it will no longer be imported from core components in `k8s.io/kubernetes`.

#### Phase 1 - Moving Cloud Provider Code to Staging

In Phase 1, all cloud provider code in `k8s.io/kubernetes/pkg/cloudprovider/providers/<provider>` will be moved to `k8s.io/kubernetes/staging/src/k8s.io/legacy-cloud-providers/<provider>`. Reasons why we "stage" cloud providers as the first phase are:
* The staged legacy provider repos can be imported from the out-of-tree provider if they choose to opt into the in-tree cloud provider implementation. This allows for a smoother transition between in-tree and out-of-tree providers in cases where there are version incompatibilites between the two.
* Staging the cloud providers indicates to the community that they are slated for removal in the future.

The biggest challenge of this phase is to remove dependences to `k8s.io/kubernetes` in all the providers. This is a requirement of staging a repository and a best practice for consuming external dependencies. All other repos "staged" (`client-go`, `apimachinery`, `api`, etc) in Kubernetes follow the same pattern. The full list of internal dependencies that need to be removed can be found in issue [69585](https://github.com/kubernetes/kubernetes/issues/69585).

#### Phase 2 - Building CCM from Provider Repos

In Phase 2, cloud providers will be expected to build the cloud controller manager from their respective provider repos (`k8s.io/cloud-provider-<provider>`). Providers can choose to vendor in their legacy provider in `k8s.io/legacy-cloud-providers/<provider>`, build implementations from scratch or both. Development in-tree is still done in the staging directories under the `k8s.io/kubernetes` repo.

The kube-controller-manager will still import the cloud provider implementations in staging. The package location of the provider implementations will change because each staged directory will be "vendored" in from their respective staging directory. The only change in core components is how the cloud providers are imported and the behavior of each cloud provider should not change.

#### Phase 3 - Migrating Provider Code to Provider Repos

In Phase 3, feature development is no longer accepted in `k8s.io/kubernetes/staging/src/k8s.io/legacy-cloud-providers/<provider>` and development of each cloud provider should be done in their respective external repos. Only bug and security fixes are accepted in-tree during this phase. It's important that by this phase, both in-tree and out-of-tree cloud providers are tested and production ready. Ideally most Kubernetes clusters in production should be using the out-of-tree provider before in-tree support is removed. A plan to migrate existing clusters from using the `kube-controller-manager` to the `cloud-controller-manager` is currently being developed. More details soon.

External cloud providers can optionally still import providers from `k8s.io/legacy-cloud-providers` but no core components in `k8s.io/kubernetes` will import the legacy provider and the respective staging directory will be removed along with all its dependencies.

#### Phase 4 - Disabling In-Tree Providers

In Phase 4, two feature gates will be introduced to gradually disable and remove in-tree cloud providers:
1. `DisableCloudProviders` - this feature gate will disable any functionality in kube-apiserver, kube-controller-manager and kubelet related to the `--cloud-provider` component flag.
2. `DisableKubeletCloudCredentialProvider` - this feature gate will disable in-tree functionality in the kubelet to authenticate to the AWS, Azure and GCP container registries for image pull credentials.

Both of these features gates only impacts functionality tied to the `--cloud-provider` flag, specifically in-tree volume plugins are not covered. Users should refer to CSI migration efforts for these.

For alpha, the feature gates will be used for testing purposes. When enabled, tests will ensure that clusters with in-tree cloud providers disabled behaves as expected. This is targeted for v1.21 and will be
disabled by default.

For beta, the feature gates will be on by default, meaning core components will disallow use of in-tree cloud providers. This will act as a warning for users to migrate to external components. Users may
choose to continue using the in-tree provider by explicitly disabling the feature gates. Beta is targeted for v1.26 with the caveat that a majority of our CI signal jobs across providers should have converted to use CCM by then.

For GA, the feature gate will be enabled by default and locked. Users at this point MUST migrate to external components and use of the in-tree cloud providers will be disallowed. GA is targeted for v1.27. One release after GA, the in-tree cloud providers can be safely removed.

NOTE: the removal of the code will depend on when we can remove the in-tree storage plugins, so the actual removal may end up in a later release.

### Staging Directory

There are several sections of code which need to be shared between the K8s/K8s repo and the K8s/Cloud-provider repos.
The plan for doing that sharing is to move the relevant code into the Staging directory as that is where we share code
today. The current Staging repo has the following packages in it.
- Api
- Apiextensions-apiserver
- Apimachinery
- Apiserver
- Client-go
- Code-generator
- Kube-aggregator
- Metrics
- Sample-apiserver
- Sample-Controller

With the additions needed in the short term to make this work; the Staging area would now need to look as follows.
- Api
- Apiextensions-apiserver
- Apimachinery
- Apiserver
- Client-go
- **legacy-cloud-providers**
- Code-generator
- Kube-aggregator
- Metrics
- Sample-apiserver
- Sample-Controller

#### Cloud Provider Instances

Currently in K8s/K8s the cloud providers are actually included in the [providers.go](https://github.com/kubernetes/kubernetes/blob/master/pkg/cloudprovider/providers/providers.go)
file which then includes each of the in-tree cloud providers. In the short term, we would leave that file where it is
and adjust it to point at the new homes under Staging. For the K8s/cloud-provider repo, would have the following CCM
wrapper file. (Essentially a modified copy of cmd/cloud-controller-manager/controller-manager.go) The wrapper for each
cloud provider would import just their vendored cloud-provider implementation rather than providers.go file.

k8s/k8s: pkg/cloudprovider/providers/providers.go
```package cloudprovider

import (
  // Prior to cloud providers having been moved to Staging
  _ "k8s.io/kubernetes/pkg/cloudprovider/providers/aws"
  _ "k8s.io/kubernetes/pkg/cloudprovider/providers/azure"
  _ "k8s.io/kubernetes/pkg/cloudprovider/providers/cloudstack"
  _ "k8s.io/kubernetes/pkg/cloudprovider/providers/gce"
  _ "k8s.io/kubernetes/pkg/cloudprovider/providers/openstack"
  _ "k8s.io/kubernetes/pkg/cloudprovider/providers/ovirt"
  _ "k8s.io/kubernetes/pkg/cloudprovider/providers/photon"
  _ "k8s.io/kubernetes/pkg/cloudprovider/providers/vsphere"
)
```

k8s/cloud-provider-gcp: pkg/cloudprovider/providers/providers.go
```package cloudprovider

import (
  // Cloud providers
  _ "k8s.io/legacy-cloud-providers/aws"
  _ "k8s.io/legacy-cloud-providers/azure"
  _ "k8s.io/legacy-cloud-providers/gce"
  _ "k8s.io/legacy-cloud-providers/openstack"
  _ "k8s.io/legacy-cloud-providers/vsphere"
)
```

## Production Readiness Review Questionnaire

### Feature Enablement and Rollback

_This section must be completed when targeting alpha to a release._

* **How can this feature be enabled / disabled in a live cluster?**
  - [X] Feature gate (also fill in values in `kep.yaml`)
    - Feature gate name: DisableCloudProviders
    - Components depending on the feature gate: kubelet, kube-apiserver, kube-controller-manager
  - [X] Feature gate (also fill in values in `kep.yaml`)
    - Feature gate name: DisableKubeletCloudCredentialProvider
    - Components depending on the feature gate: kubelet

* **Does enabling the feature change any default behavior?**
  Yes, enabling this feature will disable all capabilities enabled when `--cloud-provider` is set in core components.
  Users need to ensure they have migrated to out-of-tree components prior to enabling this feature gate.
  If appropriate extensions (CCM, credential provider, apiserver-network-proxy, etc) are in use, cloud provider capabilities
  should remain the same at the very least.

* **Can the feature be disabled once it has been enabled (i.e. can we roll back
  the enablement)?**
  Yes, the feature can be disabled once it is enabled. If disabled, users must ensure
  that the CCM is no longer running in the cluster. Credential provider plugins and the
  apiserver network proxy do not have to be stopped on rollback.

* **What happens if we reenable the feature if it was previously rolled back?**

  All capabilities from in-tree cloud providers will be re-disabled.

* **Are there any tests for feature enablement/disablement?**
  Adequate unit tests, component integration test and e2e tests will be added for this feature before
  it is goes beta and on by default.

### Rollout, Upgrade and Rollback Planning

_This section must be completed when targeting beta graduation to a release._

* **How can a rollout fail? Can it impact already running workloads?**

  TBD for beta.

* **What specific metrics should inform a rollback?**

   TBD for beta.

* **Were upgrade and rollback tested? Was the upgrade->downgrade->upgrade path tested?**

  TBD for beta.

* **Is the rollout accompanied by any deprecations and/or removals of features, APIs,
fields of API types, flags, etc.?**

  TBD for beta.

### Monitoring Requirements

_This section must be completed when targeting beta graduation to a release._

* **How can an operator determine if the feature is in use by workloads?**

  TBD for beta.

* **What are the SLIs (Service Level Indicators) an operator can use to determine
the health of the service?**

  TBD for beta.

* **What are the reasonable SLOs (Service Level Objectives) for the above SLIs?**

  TBD for beta.

* **Are there any missing metrics that would be useful to have to improve observability
of this feature?**

  TBD for beta.

### Dependencies

_This section must be completed when targeting beta graduation to a release._

* **Does this feature depend on any specific services running in the cluster?**

  TBD for beta.

### Scalability

_For alpha, this section is encouraged: reviewers should consider these questions
and attempt to answer them._

_For beta, this section is required: reviewers must answer these questions._

_For GA, this section is required: approvers should be able to confirm the
previous answers based on experience in the field._

* **Will enabling / using this feature result in any new API calls?**

  No, if anything it will result in reduced API calls in core components.

* **Will enabling / using this feature result in introducing new API types?**

  No.

* **Will enabling / using this feature result in any new calls to the cloud
provider?**

  No, it will actually remove calls to the cloud provider in all core components.

* **Will enabling / using this feature result in increasing size or count of
the existing API objects?**

  No.

* **Will enabling / using this feature result in increasing time taken by any
operations covered by [existing SLIs/SLOs]?**

  No.

* **Will enabling / using this feature result in non-negligible increase of
resource usage (CPU, RAM, disk, IO, ...) in any components?**

  No. In fact, it should reduce resource usage.

### Troubleshooting

The Troubleshooting section currently serves the `Playbook` role. We may consider
splitting it into a dedicated `Playbook` document (potentially with some monitoring
details). For now, we leave it here.

_This section must be completed when targeting beta graduation to a release._

* **How does this feature react if the API server and/or etcd is unavailable?**

TBD for beta.

* **What are other known failure modes?**

TBD for beta.

* **What steps should be taken if SLOs are not being met to determine the problem?**

TBD for beta.

[supported limits]: https://git.k8s.io/community//sig-scalability/configs-and-limits/thresholds.md
[existing SLIs/SLOs]: https://git.k8s.io/community/sig-scalability/slos/slos.md#kubernetes-slisslos

## Alternatives

### Staging Alternatives

#### Git Filter-Branch

One possible alternative is to make use of a Git Filter Branch to extract a sub-directory into a virtual repo. The repo
needs to be sync'd in an ongoing basis with K8s/K8s as we want one source of truth until K8s/K8s does not pull in the
code. This has issues such as not giving K8s/K8s developers any indications of what the dependencies various
K8s/Cloud-providers have. Without that information it becomes very easy to accidentally break various cloud providers
and time you change dependencies in the K8s/K8s repo. With staging the dependency line is simple and [automatically
enforced](https://github.com/kubernetes/kubernetes/blob/master/hack/verify-no-vendor-cycles.sh). Things in Staging are
not allowed to depend on things outside of Staging. If you want to add such a dependency you need to add the dependent
code to Staging. The act of doing this means that code should get synced and solve the problem. In addition the usage
of a second different library and repo movement mechanism will make things more difficult for everyone.

"Trying to share code through the git filter will not provide this protection. In addition it means that we now have
two sharing code mechanisms which increases complexity on the community and build tooling. As such I think it is better
to continue to use the Staging mechanisms. "

### Build Location Alternatives

#### Build K8s/K8s from within K8s/Cloud-provider

The idea here is to avoid having to add a new build target to K8s/K8s. The K8s/Cloud-provider could have their own
custom targets for building things like KAS without other cloud-providers implementations linked in. It would also
allow other customizations of the standard binaries to be created. While a powerful tool, this mechanism seems to
encourage customization of these core binaries and as such to be discouraged. Providing the appropriate generic
binaries cuts down on the need to duplicate build logic for these core components and allow each optimization of build.
Download prebuilt images at a version and then just build the appropriate addons.

#### Build K8s/Cloud-provider within K8s/K8s

The idea here would be to treat the various K8s/Cloud-provider repos as libraries. You would specify a build flavor and
we would pull in the relevant code based on what you specified. This would put tight restrictions on how the
K8s/Cloud-provider repos would work as they would need to be consumed by the K8s/K8s build system. This seems less
extensible and removes the nice loose coupling which the other systems have. It also makes it difficult for the cloud
providers to control their release cadence.

### Config Alternatives

#### Use component config to determine where controllers run

Currently KCM and CCM have their configuration passed in as command line flags. If their configuration were obtained
from a configuration server (component config) then we could have a single source of truth about where each controller
should be run. This both solves the HA migration issue and other concerns about making sure that a controller only runs
in 1 controller manager. Rather than having the controllers as on or off, controllers would now be configured to state
where they should run, KCM, CCM, Nowhere, … If the KCM could handle this as a run-time change nothing would need to
change. Otherwise it becomes a slight variant of the proposed solution. This is probably the correct long term
solution. However for the timeline we are currently working with we should use the proposed solution.


text:
package com.josephalevin.gwtplug.client;

import java.util.Iterator;

/**
 *
 * @author josephalevin
 */
public interface PluginLookup{
    public <S> Iterator<S> lookup(Class<S> service);
}


text:
package com.facebook.buck.jvm.groovy;

import static org.hamcrest.CoreMatchers.allOf;
import static org.hamcrest.Matchers.containsString;
import static org.junit.Assume.assumeTrue;

import com.facebook.buck.config.BuckConfig;
import com.facebook.buck.core.cell.DefaultCellPathResolver;
import com.facebook.buck.io.file.MorePaths;
import com.facebook.buck.io.filesystem.ProjectFilesystem;
import com.facebook.buck.io.filesystem.TestProjectFilesystems;
import com.facebook.buck.testutil.TemporaryPaths;
import com.facebook.buck.util.config.Config;
import com.facebook.buck.util.config.RawConfig;
import com.facebook.buck.util.environment.Architecture;
import com.facebook.buck.util.environment.Platform;
import com.google.common.collect.ImmutableMap;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

public class GroovyBuckConfigTest {
  @Rule public ExpectedException thrown = ExpectedException.none();
  @Rule public TemporaryPaths temporaryFolder = new TemporaryPaths();

  @Test
  public void refuseToContinueWhenInsufficientInformationToFindGroovycIsProvided()
      throws InterruptedException {
    thrown.expectMessage(
        allOf(
            containsString("Unable to locate groovy compiler"),
            containsString("GROOVY_HOME is not set, and groovy.groovy_home was not provided")));

    ImmutableMap<String, String> environment = ImmutableMap.of();
    ImmutableMap<String, ImmutableMap<String, String>> rawConfig = ImmutableMap.of();
    GroovyBuckConfig groovyBuckConfig = createGroovyConfig(environment, rawConfig);

    groovyBuckConfig.getGroovyCompiler();
  }

  @Test
  public void refuseToContinueWhenInformationResultsInANonExistentGroovycPath()
      throws InterruptedException {
    String invalidPath = temporaryFolder.getRoot().toAbsolutePath() + "DoesNotExist";
    Path invalidDir = Paths.get(invalidPath);
    Path invalidGroovyc = invalidDir.resolve(MorePaths.pathWithPlatformSeparators("bin/groovyc"));
    thrown.expectMessage(containsString("Unable to locate " + invalidGroovyc + " on PATH"));

    ImmutableMap<String, String> environment = ImmutableMap.of("GROOVY_HOME", invalidPath);
    ImmutableMap<String, ImmutableMap<String, String>> rawConfig = ImmutableMap.of();
    GroovyBuckConfig groovyBuckConfig = createGroovyConfig(environment, rawConfig);

    groovyBuckConfig.getGroovyCompiler();
  }

  @Test
  public void byDefaultFindGroovycFromGroovyHome() throws InterruptedException {
    String systemGroovyHome = System.getenv("GROOVY_HOME");
    assumeTrue(systemGroovyHome != null);

    //noinspection ConstantConditions
    ImmutableMap<String, String> environment = ImmutableMap.of("GROOVY_HOME", systemGroovyHome);
    ImmutableMap<String, ImmutableMap<String, String>> rawConfig = ImmutableMap.of();
    GroovyBuckConfig groovyBuckConfig = createGroovyConfig(environment, rawConfig);

    // it's enough that this doesn't throw.
    groovyBuckConfig.getGroovyCompiler();
  }

  @Test
  public void explicitConfigurationOverridesTheEnvironment() throws InterruptedException {
    String systemGroovyHome = System.getenv("GROOVY_HOME");
    assumeTrue(systemGroovyHome != null);

    // deliberately break the env
    ImmutableMap<String, String> environment = ImmutableMap.of("GROOVY_HOME", "/oops");
    //noinspection ConstantConditions
    ImmutableMap<String, ImmutableMap<String, String>> rawConfig =
        ImmutableMap.of("groovy", ImmutableMap.of("groovy_home", systemGroovyHome));
    GroovyBuckConfig groovyBuckConfig = createGroovyConfig(environment, rawConfig);

    // it's enough that this doesn't throw.
    groovyBuckConfig.getGroovyCompiler();
  }

  private GroovyBuckConfig createGroovyConfig(
      ImmutableMap<String, String> environment,
      ImmutableMap<String, ImmutableMap<String, String>> rawConfig) {
    ProjectFilesystem projectFilesystem =
        TestProjectFilesystems.createProjectFilesystem(temporaryFolder.getRoot());
    Config config = new Config(RawConfig.of(rawConfig));
    BuckConfig buckConfig =
        new BuckConfig(
            config,
            projectFilesystem,
            Architecture.detect(),
            Platform.detect(),
            environment,
            DefaultCellPathResolver.of(projectFilesystem.getRootPath(), config));

    return new GroovyBuckConfig(buckConfig);
  }
}


text:
#pragma once

#include "ParameterType.h"

#include <list>
#include <string>

class CEnumParameterType : public CParameterType
{
public:
    CEnumParameterType(const std::string& strName);

    // From IXmlSink
    virtual bool fromXml(const CXmlElement& xmlElement, CXmlSerializingContext& serializingContext);

    // From IXmlSource
    virtual void toXml(CXmlElement& xmlElement, CXmlSerializingContext& serializingContext) const;

    /// Conversion
    // String
    virtual bool toBlackboard(const std::string& strValue, uint32_t& uiValue, CParameterAccessContext& parameterAccessContext) const;
    virtual bool fromBlackboard(std::string& strValue, const uint32_t& uiValue, CParameterAccessContext& parameterAccessContext) const;
    // Integer
    virtual bool toBlackboard(int32_t iUserValue, uint32_t& uiValue, CParameterAccessContext& parameterAccessContext) const;
    virtual bool fromBlackboard(int32_t& iUserValue, uint32_t uiValue, CParameterAccessContext& parameterAccessContext) const;

    // Default value handling (simulation only)
    virtual uint32_t getDefaultValue() const;

    // Element properties
    virtual void showProperties(std::string& strResult) const;

    // CElement
    virtual std::string getKind() const;
private:
    // Returns true if children dynamic creation is to be dealt with
    virtual bool childrenAreDynamic() const;
    // Check std::string is a number
    static bool isNumber(const std::string& strValue);

    // Literal - numerical conversions
    bool getLiteral(int32_t iNumerical, std::string& strLiteral) const;
    bool getNumerical(const std::string& strLiteral, int& iNumerical) const;

    // Numerical validity
    bool isValid(int iNumerical, CParameterAccessContext& parameterAccessContext) const;

    // Range validity
    bool checkValueAgainstRange(const std::string& strValue, int64_t value, CParameterAccessContext& parameterAccessContext, bool bHexaValue, bool bConversionSucceeded) const;
};


text:
package org.jboss.arquillian.container.spi.client.container;

import org.jboss.arquillian.container.spi.ConfigurationException;

/**
 * Container configuration that can be validated
 *
 * @author German Escobar
 * @version $Revision: $
 */
public interface ContainerConfiguration
{

   /**
    * Validates if current configuration is valid, that is if all required
    * properties are set and have correct values
    */
   void validate() throws ConfigurationException;

}


text:
class WXDLLIMPEXP_CORE wxMiniFrame : public wxFrame
{
  wxDECLARE_DYNAMIC_CLASS(wxMiniFrame);
public:
  inline wxMiniFrame()
  {
  }
  inline wxMiniFrame(wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxDEFAULT_FRAME_STYLE | wxTINY_CAPTION, const wxString& name = wxASCII_STR(wxFrameNameStr))
  {
        // Use wxFrame constructor in absence of more specific code.
    Create(parent, id, title, pos, size, style, name);
  }
  virtual ~wxMiniFrame()
  {
  }
};
#endif
// _WX_MINIFRAM_H_