text:
package gphoto

// #cgo LDFLAGS: -L/usr/lib/x86_64-linux-gnu -lgphoto2 -lgphoto2_port
// #cgo CFLAGS: -I/usr/include
// #include <gphoto2/gphoto2.h>
// #include <stdlib.h>
import "C"
import (
	"fmt"
	"io"
	"reflect"
	"unsafe"
)

type cameraFilePathInternal struct {
	Name   [128]uint8
	Folder [1024]uint8
}

//DownloadImage saves image pointed by path to the provided buffer. If leave on camera is set to false,the file will be deleted from the camera internal storage
func (file *CameraFilePath) DownloadImage(buffer io.Writer, leaveOnCamera bool) error {
	gpFile, err := newGpFile()
	if err != nil {
		return err
	}
	defer C.gp_file_free(gpFile)

	fileDir := C.CString(file.Folder)
	defer C.free(unsafe.Pointer(fileDir))

	fileName := C.CString(file.Name)
	defer C.free(unsafe.Pointer(fileName))

	if retval := C.gp_camera_file_get(file.camera.gpCamera, fileDir, fileName, FileTypeNormal, gpFile, file.camera.gpContext); retval != gpOk {
		return fmt.Errorf("Cannot download photo file, error code :%v", retval)
	}

	err = getFileBytes(gpFile, buffer)
	if err != nil && leaveOnCamera == false {
		C.gp_camera_file_delete(file.camera.gpCamera, fileDir, fileName, file.camera.gpContext)
	}
	return err
}

//CaptureImage captures image with current setings into camera's internal storage
func (camera *Camera) CaptureImage() (*CameraFilePath, error) {
	photoPath := cameraFilePathInternal{}

	if retval := C.gp_camera_capture(camera.gpCamera, 0, (*C.CameraFilePath)(unsafe.Pointer(&photoPath)), camera.gpContext); retval != gpOk {
		return nil, fmt.Errorf("Cannot capture photo, error code :%v", retval)
	}
	return newCameraFilePathFromInternalImpl(&photoPath, camera), nil
}

//CapturePreview  captures image preview and saves it in provided buffer
func (camera *Camera) CapturePreview(buffer io.Writer) error {
	gpFile, err := newGpFile()
	if err != nil {
		return err
	}

	if retval := C.gp_camera_capture_preview(camera.gpCamera, gpFile, camera.gpContext); retval != gpOk {
		return fmt.Errorf("Cannot capture preview, error code : %d", retval)
	}

	return getFileBytes(gpFile, buffer)
}

//DeleteFile tries to delete file from the camera, and returns error if it fails
func (camera *Camera) DeleteFile(path *CameraFilePath) error {
	fileDir := C.CString(path.Folder)
	defer C.free(unsafe.Pointer(fileDir))

	fileName := C.CString(path.Name)
	defer C.free(unsafe.Pointer(fileName))

	retval := C.gp_camera_file_delete(camera.gpCamera, fileDir, fileName, camera.gpContext)
	if retval != gpOk {
		return fmt.Errorf("Cannot delete fine on camera, error code :%v", retval)
	}
	return nil
}

//ListFiles returns a lits of files and folders on the camera
func (camera *Camera) ListFiles() ([]CameraStorageInfo, error) {
	var gpCameraStorageInformation *C.CameraStorageInformation
	var storageCount C.int
	storageCount = 0
	returnedStorageInfo := []CameraStorageInfo{}

	retval := C.gp_camera_get_storageinfo(camera.gpCamera, (**C.CameraStorageInformation)(unsafe.Pointer(&gpCameraStorageInformation)), &storageCount, camera.gpContext)
	if retval != gpOk {
		return nil, fmt.Errorf("Cannot get camera storage info, error code %d", retval)
	}
	defer C.free(unsafe.Pointer(gpCameraStorageInformation))

	hdr := reflect.SliceHeader{
		Data: uintptr(unsafe.Pointer(gpCameraStorageInformation)),
		Len:  int(storageCount),
		Cap:  int(storageCount),
	}
	nativeCameraFileSystemInfo := *(*[]C.CameraStorageInformation)(unsafe.Pointer(&hdr))
	for i := 0; i < int(storageCount); i++ {
		cameraStorage := CameraStorageInfo{
			Description: C.GoString((*C.char)(&nativeCameraFileSystemInfo[i].description[0])),
			Capacity:    uint64(nativeCameraFileSystemInfo[i].capacitykbytes),
			Free:        uint64(nativeCameraFileSystemInfo[i].freekbytes),
			FreeImages:  uint64(nativeCameraFileSystemInfo[i].freeimages),
			Children:    []CameraFilePath{},

			basedir: C.GoString((*C.char)(&nativeCameraFileSystemInfo[i].basedir[0])),
			camera:  camera,
		}

		if err := camera.recursiveListAllFiles(&cameraStorage.basedir, &cameraStorage.Children); err != nil {
			return nil, err
		}
		returnedStorageInfo = append(returnedStorageInfo, cameraStorage)
	}
	return returnedStorageInfo, nil
}

func (camera *Camera) recursiveListAllFiles(basedir *string, children *[]CameraFilePath) error {
	items, err := camera.findAllChildDirectories(basedir)
	if err != nil {
		return err
	}
	for _, dirName := range items {
		dirItem := CameraFilePath{
			Name:     dirName,
			Folder:   *basedir,
			Isdir:    true,
			Children: []CameraFilePath{},
			camera:   camera,
		}
		childPath := *basedir + "/" + dirName
		if err := camera.recursiveListAllFiles(&childPath, &dirItem.Children); err != nil {
			return err
		}
		*children = append(*children, dirItem)

	}
	items, err = camera.findAllFilesInDir(basedir)
	if err != nil {
		return err
	}
	for _, fileName := range items {
		fileItem := CameraFilePath{
			Name:     fileName,
			Folder:   *basedir,
			Isdir:    false,
			Children: nil,
			camera:   camera,
		}
		*children = append(*children, fileItem)
	}
	fmt.Println("Dir ", *basedir, " has ", len(*children), " children")
	return nil
}

//Hmm, this could be reduced to one func, and a lambda passed as an arg
func (camera *Camera) findAllChildDirectories(basedirPath *string) ([]string, error) {
	var gpFileList *C.CameraList
	var err error
	returnedSlice := []string{}

	gpDirPath := C.CString(*basedirPath)
	defer C.free(unsafe.Pointer(gpDirPath))

	if gpFileList, err = newGphotoList(); err != nil {
		return nil, err
	}
	defer C.gp_list_free(gpFileList)

	if retval := C.gp_camera_folder_list_folders(camera.gpCamera, gpDirPath, gpFileList, camera.gpContext); retval != gpOk {
		return nil, fmt.Errorf("Cannot get folder list from dir %s, error code %v", *basedirPath, retval)
	}

	listSize := int(C.gp_list_count(gpFileList))
	for i := 0; i < listSize; i++ {
		var gpListElementName *C.char
		C.gp_list_get_name(gpFileList, (C.int)(i), (**C.char)(&gpListElementName))
		returnedSlice = append(returnedSlice, C.GoString(gpListElementName))
	}
	return returnedSlice, nil
}

func (camera *Camera) findAllFilesInDir(basedirPath *string) ([]string, error) {
	var err error
	returnedSlice := []string{}

	gpDirPath := C.CString(*basedirPath)
	defer C.free(unsafe.Pointer(gpDirPath))

	gpFileList, err := newGphotoList()
	if err != nil {
		return nil, err
	}
	defer C.gp_list_free(gpFileList)

	if retval := C.gp_camera_folder_list_files(camera.gpCamera, gpDirPath, gpFileList, camera.gpContext); retval != gpOk {
		return nil, fmt.Errorf("Cannot get file list from dir %s, error code %v", *basedirPath, retval)
	}

	listSize := int(C.gp_list_count(gpFileList))
	for i := 0; i < listSize; i++ {
		var gpListElementName *C.char
		C.gp_list_get_name(gpFileList, (C.int)(i), (**C.char)(&gpListElementName))
		returnedSlice = append(returnedSlice, C.GoString(gpListElementName))
	}
	return returnedSlice, nil
}


text:
public static class StringExtensions
{
    public static string Replace(this String str, char[] chars, string replacement)
    {
        StringBuilder output = new StringBuilder(str.Length);

        for (int i = 0; i < str.Length; i++)
        {
            char c = str[i];

            bool replace = false;
            for (int j = 0; j < chars.Length; j++)
            {
                if (chars[j] == c)
                {
                    replace = true;
                    break;
                }
            }

            if (replace)
                output.Append(replacement);
            else
                output.Append(c);
        }

        return output.ToString();
    }
}

redpajama_set_name: RedPajamaGithub


text:
#ifndef __AUTONETWORK__
#define __AUTONETWORK__

//-------- ----------
// DPA implementation
//-------- ----------
#define NO_WAITING              0
#define CONFIRMATION_WAITING	1
#define RESPONSE_WAITING        2
#define DPA_OK                  4
#define DPA_ERROR               8
#define DPA_TIMEOUT             128
#define DPA_ADDRESS_MAX         239
#define DPA_ADDRESS_TEMP        254
#define DPA_ADDRESS_BROADCAST   255
#define DPA_ADDRESS_COORD       0

//----------------------
// Autonetwork constants
//----------------------
#define AN_MIN_PREBONDING_TIME 15

//------------------------
// Autonetwork event codes
//------------------------
#define EVT_AN_PROCESS_STARTED              0x00
#define EVT_AN_PROCESS_STOPPED              0x01
#define EVT_GET_NETWORK_INFO                0x02
#define EVT_ROUND_START                     0x03
#define EVT_COOR_ENABLE_PREBONDING          0x04
#define EVT_COOR_DISABLE_PREBONDING         0x05
#define EVT_COOR_READ_MID                   0x06
#define EVT_COOR_REMOVING_BOND              0x07
#define EVT_NODE_ENABLE_PREBONDING          0x08
#define EVT_NODE_DISABLE_PREBONDING         0x09
#define EVT_NODE_READ_MID                   0x0a
#define EVT_AUTHORIZE_BOND                  0x0b
#define EVT_AUTHORIZE_BOND_OK               0x0c
#define EVT_DISCOVERY                       0x0d
#define EVT_DISCOVERY_WAIT                  0x0e
#define EVT_DISCOVERY_OK                    0x0f
#define EVT_WAIT_PREBONDING                 0x10
#define EVT_FRC_DISABLE_PREBONDING          0x11
#define EVT_FRC_DISABLE_PREBONDING_BIT0_ERR 0x12
#define EVT_FRC_DISABLE_PREBONDING_BIT1_ERR 0x13
#define EVT_FRC_CHECK_NEW_NODES             0x14
#define EVT_NO_FREE_ADDRESS                 0x15
#define EVT_NO_NEW_NODE_PREBONDED           0x16
#define EVT_DPA_CONFIRMATION_TIMEOUT        0x17
#define EVT_DPA_RESPONSE_TIMEOUT            0x18
#define EVT_REMOVE_ALL_BONDS                0x19
#define EVT_MAX_NODES_PREBONDED             0x1a
#define EVT_NODE_REMOTE_UNBOND              0x1b
#define EVT_WITH_PARAM                      0x01
#define EVT_WITHOUT_PARAM                   0x00

//-------------------------
// Autonetwork return codes
//-------------------------
#define ERR_PROCESS_TERMINATED              0xff
#define ERR_NO_FREE_ADDRESS                 0xfe
#define ERR_MAX_NODES_PREBONDED             0xfd
#define AN_OK                               0x00
#define AN_ERROR                            0xff

//--------------------
// Buffer size, offset
//--------------------
#define NODE_BITMAP_SIZE                    32        // Bitmap for 256 nodes
#define MID_BUFFER_SIZE                     128       // Buffer for 128 MIDs
#define FRC_BUFFER_SIZE                     64
#define FRC_DATA_OFFSET                     0
#define FRC_DATA_SIZE                       55
#define FRC_EXTRA_DATA_OFFSET               55
#define FRC_EXTRA_DATA_SIZE                 9

//-----------------------
// Autonetwork parameters
//-----------------------
typedef struct
{
    unsigned short prebondingInterval;
    unsigned short discoveryTxPower;
    unsigned short authorizeRetries;
    unsigned short discoveryRetries;
    unsigned short temporaryAddressTimeout;
}T_AN_PARAMS;

//-------------------------
// Enable bonding structure
//-------------------------
typedef struct
{
    unsigned char BondingMask;
    unsigned char Control;
    unsigned short UserData;
} TPerCoordinatorNodeEnableRemoteBonding_Request;

//-------------
// Network info
//-------------
typedef struct
{
    unsigned char bondedNodesMap[NODE_BITMAP_SIZE];
    unsigned char bondedNodesCount;
    unsigned char discoveredNodesMap[NODE_BITMAP_SIZE];
    unsigned char discoveredNodesCount;
    unsigned char DID;
}T_NETWORK_INFO;

//----------------
// Prebonding info
//----------------
typedef struct
{
    unsigned long MIDlist[MID_BUFFER_SIZE];
    unsigned char MIDcount;
    unsigned long MID;
    unsigned short userData;
    unsigned char newNodesMap[NODE_BITMAP_SIZE];
    unsigned char frcData[FRC_BUFFER_SIZE];
    unsigned char round;
    unsigned char param;
    unsigned char origNodesCount;
    unsigned char bondingMask;
    unsigned char nextAddr;
    unsigned char newNode;
    unsigned char discoveredNodesCount;
    unsigned short wTimeout;
    unsigned short waitBonding;
    unsigned short waitBonding10ms;
    unsigned short delay;
}T_PREBONDING_INFO;

//------------------
// Autonetwork state
//------------------
typedef struct
{
    T_NETWORK_INFO *newtorkInfo;
    T_PREBONDING_INFO *prebondingInfo;
    T_AN_PARAMS *params;
}T_AN_STATE;

//-------------------------------
// Autonetwork callback functions
//-------------------------------
typedef void (*autonetworkNotify_CB)(unsigned char eventCode, T_AN_STATE *state);
typedef unsigned char (*autonetworkCheckInput_CB)(T_AN_PARAMS *AN_Params);

//-----------
// Prototypes
//-----------
void autonetworkTick(void);
void autonetworkInit(autonetworkNotify_CB notify_CB, autonetworkCheckInput_CB checkInput_CB);
unsigned char autonetwork(T_AN_PARAMS *par);
void removeAllBonds(void);
unsigned char ledR(unsigned short addr, unsigned char cmd);

#endif


text:
package org.araqne.logstorage;

import java.util.List;

public class LogFlushCallbackArgs {
	private String tableName;
	private List<Log> logs;

	public LogFlushCallbackArgs(String tableName) {
		this.tableName = tableName;
	}

	// only for shallowCopy
	private LogFlushCallbackArgs(String tableName, List<Log> logs) {
		this.tableName = tableName;
		this.logs = logs;
	}

	public String getTableName() {
		return this.tableName;
	}

	public void setLogs(List<Log> logs) {
		this.logs = logs;
	}

	public List<Log> getLogs() {
		return this.logs;
	}

	public LogFlushCallbackArgs shallowCopy() {
		return new LogFlushCallbackArgs(tableName, logs);
	}
}


text:
package com.alumnigroup.app.acty;

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

import org.apache.http.Header;
import org.json.JSONObject;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.alumnigroup.adapter.BaseViewPagerAdapter;
import com.alumnigroup.adapter.FootOnPageChangelistener;
import com.alumnigroup.adapter.IssueAdapter;
import com.alumnigroup.adapter.MemberAdapter;
import com.alumnigroup.adapter.MyOnPageChangeListener;
import com.alumnigroup.api.ActivityAPI;
import com.alumnigroup.api.ActivityShareAPI;
import com.alumnigroup.api.RestClient;
import com.alumnigroup.api.StarAPI;
import com.alumnigroup.app.AppInfo;
import com.alumnigroup.app.BaseActivity;
import com.alumnigroup.app.R;
import com.alumnigroup.app.SyncData;
import com.alumnigroup.entity.ErrorCode;
import com.alumnigroup.entity.Issue;
import com.alumnigroup.entity.MActivity;
import com.alumnigroup.entity.MPicture;
import com.alumnigroup.entity.User;
import com.alumnigroup.entity.Userships;
import com.alumnigroup.imple.JsonResponseHandler;
import com.alumnigroup.utils.CalendarUtils;
import com.alumnigroup.utils.Constants;
import com.alumnigroup.widget.XListView;
import com.alumnigroup.widget.XListView.IXListViewListener;
import com.astuetz.PagerSlidingTabStrip;
import com.nostra13.universalimageloader.core.ImageLoader;

/**
 * 活动详情页面
 *
 * @author Jayin Ton
 *
 */
public class ActivitiesInfo extends BaseActivity {
	PagerSlidingTabStrip tabs;
	private String[] titles ;
 	private View btn_more;
	private TextView tv_starttime, tv_applyDeadline, tv_money, tv_applyNum,
			tv_site, tv_description, tv_name, tv_duration;
	private ImageView iv_avatar;
	private MActivity acty;
	private ActivityAPI api;
	private XListView lv_member, lv_share;
	private List<User> data_member;
	private MemberAdapter adapter_member;
	private ViewPager viewpager;
	private PopupWindow mPopupWindow;
	private User user;
	private ActivityShareAPI shareAPI;
	private List<Issue> data_share;
	private IssueAdapter adapter_share;
	private int page_share = 0, page_member = 0;
	private ImageView iv_pic1, iv_pic2, iv_pic3;
	private BroadcastReceiver mReceiver = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.acty_activitiesinfo);
		initData();
		initPopupWindow();
		initLayout();
		initController();
		openReceiver();
	}

	private void openReceiver() {
		mReceiver = new BroadcastReceiver() {

			@Override
			public void onReceive(Context context, Intent intent) {
				if (intent.getAction().equals(
						Constants.Action_ActivityInfo_Edit)) {
					acty = (MActivity) intent.getSerializableExtra("activity");
					fillInData();
				} else if (intent.getAction().equals(
						Constants.Action_ActivityShare_Edit)) {
					Issue issue = (Issue) intent.getSerializableExtra("issue");
					SyncData.updateEditIssue(data_share, adapter_share, issue);
 				}else if(intent.getAction().equals(Constants.Action_Issue_delete)){
					Issue deleteItem = (Issue)intent.getSerializableExtra("issue");
					SyncData.updateDeleteIssue(data_share, adapter_share, deleteItem);
				}

			}
		};
		IntentFilter filter = new IntentFilter();
		filter.addAction(Constants.Action_ActivityInfo_Edit);
		filter.addAction(Constants.Action_ActivityShare_Edit);
		filter.addAction(Constants.Action_Issue_delete);
		registerReceiver(mReceiver, filter);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (mReceiver != null) {
			unregisterReceiver(mReceiver);
		}
	}

	private void initPopupWindow() {
		View view = getLayoutInflater().inflate(
				R.layout.popup_acty_activitiesinfo, null);

		(view.findViewById(R.id.btn_manage)).setOnClickListener(this);
		(view.findViewById(R.id.btn_join)).setOnClickListener(this);
		(view.findViewById(R.id.btn_exit)).setOnClickListener(this);
		(view.findViewById(R.id.btn_favourite)).setOnClickListener(this);
		(view.findViewById(R.id.btn_activity_share)).setOnClickListener(this);

		mPopupWindow = new PopupWindow(view);
		mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
		mPopupWindow.setOutsideTouchable(true);

		// 控制popupwindow的宽度和高度自适应
		view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
		mPopupWindow.setWidth(view.getMeasuredWidth());
		mPopupWindow.setHeight(view.getMeasuredHeight());
	}

	private void initController() {
		lv_member.setPullRefreshEnable(true);
		lv_member.setPullLoadEnable(false);// 一次性加载全部用户

		lv_share.setPullRefreshEnable(true);
		lv_share.setPullLoadEnable(true);

		lv_member.setAdapter(adapter_member);
		lv_share.setAdapter(adapter_share);
		lv_member.setXListViewListener(new IXListViewListener() {

			@Override
			public void onRefresh() {
				// 一次性加载全部用户
				api.getUserListAll(acty.getNumUsership(), acty.getId(),
						new JsonResponseHandler() {
							@Override
							public void onOK(Header[] headers, JSONObject obj) {
								List<Userships> us = Userships
										.create_by_jsonarray(obj.toString());
								List<User> newData_member = new ArrayList<User>();
								for (Userships _us : us) {
									newData_member.add(_us.getUser());
								}
								if (newData_member.size() == 0) {
									toast("还没人参加这活动");
								} else {
									data_member.clear();
									data_member.addAll(newData_member);
									adapter_member.notifyDataSetChanged();
									page_member = 1;
								}
								lv_member.stopRefresh();
							}

							@Override
							public void onFaild(int errorType, int errorCode) {
								toast(ErrorCode.errorList.get(errorCode));
								lv_member.stopRefresh();

							}
						});

			}

			@Override
			public void onLoadMore() {

			}
		});

		lv_share.setXListViewListener(new IXListViewListener() {

			@Override
			public void onRefresh() {
				shareAPI.getShareList(1, acty.getId(),
						new JsonResponseHandler() {

							@Override
							public void onOK(Header[] headers, JSONObject obj) {
								List<Issue> newData_share = Issue
										.create_by_jsonarray(obj.toString());
								if (newData_share == null) {
									toast("网络异常 解析错误");
								} else if (newData_share.size() == 0) {
									toast("还没有分享");
									lv_share.setPullLoadEnable(false);
								} else {
									page_share = 1;
									data_share.clear();
									data_share.addAll(newData_share);
									adapter_share.notifyDataSetChanged();
									if(newData_share.size()<10){
										lv_share.setPullLoadEnable(false);
									}else{
										lv_share.setPullLoadEnable(true);
									}
								}
								lv_share.stopRefresh();
							}

							@Override
							public void onFaild(int errorType, int errorCode) {
								toast(ErrorCode.errorList.get(errorCode));
								lv_share.stopRefresh();
							}
						});

			}

			@Override
			public void onLoadMore() {
				if (page_share == 0) {
					lv_share.stopLoadMore();
					lv_share.startRefresh();
					return;
				}
				shareAPI.getShareList(page_share + 1, acty.getId(),
						new JsonResponseHandler() {

							@Override
							public void onOK(Header[] headers, JSONObject obj) {
								List<Issue> newData_share = Issue
										.create_by_jsonarray(obj.toString());
								if (newData_share == null) {
									toast("网络异常,解析错误");
								} else if (newData_share.size() == 0) {
									toast("没有更多");
									lv_share.setPullLoadEnable(false);
								} else {
									page_share++;
									data_share.addAll(newData_share);
									adapter_share.notifyDataSetChanged();
									if(newData_share.size()<10){
										lv_share.setPullLoadEnable(false);
									}else{
										lv_share.setPullLoadEnable(true);
									}
								}
								lv_share.stopLoadMore();
							}

							@Override
							public void onFaild(int errorType, int errorCode) {
								toast(ErrorCode.errorList.get(errorCode));
								lv_share.stopLoadMore();

							}
						});

			}
		});
		lv_share.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				if (position - 1 == -1)
					return;
				Intent intent = new Intent(getContext(),
						ActivitiesShareDetail.class);
				intent.putExtra("issue", data_share.get(position - 1));
				intent.putExtra("activity", acty);
				openActivity(intent);
			}
		});
	}

	@Override
	protected void initData() {
		titles = getResources().getStringArray(R.array.title_activity_info);
		acty = (MActivity) getSerializableExtra("activity");
		user = AppInfo.getUser(getContext());
		if (user == null) {
			toast("无用户信息,请重新登录");
			closeActivity();
		}
		api = new ActivityAPI();
		shareAPI = new ActivityShareAPI();
		data_member = new ArrayList<User>();
		data_share = new ArrayList<Issue>();
		adapter_member = new MemberAdapter(data_member, getContext());
		adapter_share = new IssueAdapter(getContext(), data_share);
	}

	private void initViewPager() {
		tabs = (PagerSlidingTabStrip)_getView(R.id.tabs);
		viewpager = (ViewPager) _getView(R.id.acty_activitiesinfo_content);
		View info = getLayoutInflater().inflate(
				R.layout.frame_acty_activitiesinfo_introduce, null);
		View member = getLayoutInflater().inflate(
				R.layout.frame_acty_activitiesinfo_userlist, null);
		View share = getLayoutInflater().inflate(
				R.layout.frame_acty_activitiesinfo_share, null);

		lv_member = (XListView) member
				.findViewById(R.id.frame_acty_activitiesinfo_userlist_listview);
		lv_share = (XListView) share
				.findViewById(R.id.frame_acty_activitiesinfo_share_listview);

		tv_starttime = (TextView) info.findViewById(R.id.tv_starttime);
		tv_applyDeadline = (TextView) info.findViewById(R.id.tv_deadline);// 结束日期
		tv_money = (TextView) info.findViewById(R.id.tv_money);
		tv_applyNum = (TextView) info.findViewById(R.id.tv_applyNum);
		tv_site = (TextView) info.findViewById(R.id.tv_address);
		tv_description = (TextView) info.findViewById(R.id.tv_description);
		tv_duration = (TextView) info.findViewById(R.id.tv_duration);
		tv_name = (TextView) info
				.findViewById(R.id.frame_acty_activityinfo_introduce_name);

		iv_avatar = (ImageView) info.findViewById(R.id.iv_avatar);

		fillInData();

		List<View> views = new ArrayList<View>();
		views.add(info);
		views.add(member);
		views.add(share);

		List<XListView> listviews = new ArrayList<XListView>();
		listviews.add(null);
		listviews.add(lv_member);
		listviews.add(lv_share);

		List<BaseAdapter> adapters = new ArrayList<BaseAdapter>();
		adapters.add(null);
		adapters.add(adapter_member);
		adapters.add(adapter_share);

		viewpager.setAdapter(new BaseViewPagerAdapter(views,titles));
		tabs.setViewPager(viewpager);
		tabs.setOnPageChangeListener(new MyOnPageChangeListener(listviews));

		iv_pic1 = (ImageView) info.findViewById(R.id.iv_pic1);
		iv_pic2 = (ImageView) info.findViewById(R.id.iv_pic2);
		iv_pic3 = (ImageView) info.findViewById(R.id.iv_pic3);

		for (int i = 0; i < acty.getPictures().size(); i++) {
			switch (i) {
			case 0:
				iv_pic1.setVisibility(View.VISIBLE);
				ImageLoader.getInstance().displayImage(
						RestClient.BASE_URL
								+ acty.getPictures().get(i).getPath(), iv_pic1);
				iv_pic1.setOnClickListener(this);

				break;
			case 1:
				iv_pic2.setVisibility(View.VISIBLE);
				ImageLoader.getInstance().displayImage(
						RestClient.BASE_URL
								+ acty.getPictures().get(i).getPath(), iv_pic2);
				iv_pic2.setOnClickListener(this);
				break;
			case 2:
				iv_pic3.setVisibility(View.VISIBLE);
				ImageLoader.getInstance().displayImage(
						RestClient.BASE_URL
								+ acty.getPictures().get(i).getPath(), iv_pic3);
				iv_pic3.setOnClickListener(this);
				break;
			default:
				break;
			}
		}
	}

	// 填充数据
	private void fillInData() {
		if (acty.getAvatar() != null) {
			ImageLoader.getInstance().displayImage(
					RestClient.BASE_URL + acty.getAvatar(), iv_avatar);
		} else {
			ImageLoader.getInstance().displayImage(
					"drawable://" + R.drawable.ic_img_activity_default, iv_avatar);
		}

		tv_name.setText(acty.getName());
		tv_applyDeadline.setText(CalendarUtils.getTimeFromat(
				acty.getRegdeadline(), CalendarUtils.TYPE_TWO));
		tv_starttime.setText(CalendarUtils.getTimeFromat(acty.getStarttime(),
				CalendarUtils.TYPE_TWO));
		tv_site.setText(acty.getSite());
		tv_description.setText(acty.getContent());
		tv_applyNum.setText(acty.getNumUsership() + "/" + acty.getMaxnum());
		tv_duration.setText(acty.getDuration() + "天");
		tv_money.setText(acty.getMoney() + "RMB");
	}

	@Override
	protected void initLayout() {
	 btn_more =  _getView(R.id.acty_head_btn_more);
	 btn_more.setOnClickListener(this);
		_getView(R.id.acty_head_btn_back).setOnClickListener(this);
		initViewPager();
	}

	@Override
	public void onClick(View v) {
		Intent intent = null;
		switch (v.getId()) {
		case R.id.acty_head_btn_back:
			closeActivity();
			break;
		case R.id.acty_head_btn_more:
			if (!mPopupWindow.isShowing())
				mPopupWindow.showAsDropDown(btn_more);
			break;
		case R.id.btn_manage:
			mPopupWindow.dismiss();
			if (acty.getOwnerid() == user.getId()) {
				intent = new Intent(getContext(), ActivitiesManage.class);
				intent.putExtra("activity", acty);
				openActivity(intent);
			} else {
				toast("无权管理该活动");
			}
			break;
		case R.id.btn_join:
			mPopupWindow.dismiss();
			joinActivity();
			break;
		case R.id.btn_exit:
			mPopupWindow.dismiss();
			cancelActivity();
			break;
		case R.id.btn_favourite:
			mPopupWindow.dismiss();
			favourite();
			break;
		case R.id.btn_activity_share:
			mPopupWindow.dismiss();
			intent = new Intent(this, ActivitiesSharePublish.class);
			intent.putExtra("activity", acty);
			openActivity(intent);
			break;
		case R.id.iv_pic1:
			intent = new Intent(getContext(), ImageDisplay.class);
			intent.putExtra("url", RestClient.BASE_URL
					+ acty.getPictures().get(0).getPath());
			openActivity(intent);
			break;
		case R.id.iv_pic2:
			intent = new Intent(getContext(), ImageDisplay.class);
			intent.putExtra("url", RestClient.BASE_URL
					+ acty.getPictures().get(1).getPath());
			openActivity(intent);
			break;
		case R.id.iv_pic3:
			intent = new Intent(getContext(), ImageDisplay.class);
			intent.putExtra("url", RestClient.BASE_URL
					+ acty.getPictures().get(2).getPath());
			openActivity(intent);
			break;
		default:
			break;
		}
	}

	private void cancelActivity() {
		api.cancelActivity(acty.getId(), new JsonResponseHandler() {

			@Override
			public void onOK(Header[] headers, JSONObject obj) {
				toast("已退出活动");
			}

			@Override
			public void onFaild(int errorType, int errorCode) {
				toast("退出活动失败 " + ErrorCode.errorList.get(errorCode));
			}
		});

	}

	private void joinActivity() {
		api.joinActivity(acty.getId(), new JsonResponseHandler() {

			@Override
			public void onOK(Header[] headers, JSONObject obj) {
				toast("已报名参加");
			}

			@Override
			public void onFaild(int errorType, int errorCode) {
				if (errorCode == 20506) {
					toast("已报名,请等待审核");
				} else {
					toast("报名失败 " + ErrorCode.errorList.get(errorCode));
				}
			}
		});

	}

	// 收藏的remark默认为期类型名
	private void favourite() {
		StarAPI starapi = new StarAPI();
		starapi.star(StarAPI.Item_type_activity, acty.getId(), "activity",
				new JsonResponseHandler() {

					@Override
					public void onOK(Header[] headers, JSONObject obj) {
						toast("收藏成功");

					}

					@Override
					public void onFaild(int errorType, int errorCode) {
						if (errorCode == 20506) {
							toast("已收藏");
						} else {
							toast("收藏失败 " + ErrorCode.errorList.get(errorCode));
						}

					}
				});

	}

}


text:
/*
Scoring probabilities
Problem 286
Barbara
 is a mathematician and a basketball player. She has found that the probability of scoring a point when shooting from a distance x is exactly (1 - x/q), where q is a real constant greater than 50.
During each practice run, she takes shots from distances x = 1, x = 2, ..., x = 50 and, according to her records, she has precisely a 2 % chance to score a total of exactly 20 points.
Find q and give your answer rounded to 10 decimal places.
*/


text:
require 'pione/test-helper'

class TestLogger < Log::PioneSystemLogger
  forward :@out, :puts, :fatal
  forward :@out, :puts, :error
  forward :@out, :puts, :warn
  forward :@out, :puts, :info
  forward :@out, :puts, :debug
  forward Proc.new{ @out.string }, :include?

  def initialize
    @out = StringIO.new
  end
end

describe "Pione::Log::SystemLogger" do
  it "should log the fatal message" do
    TestLogger.new.tap{|x| x.fatal "XYZ"}.should.include("XYZ")
  end

  it "should log the error message" do
    TestLogger.new.tap{|x| x.error "XYZ"}.should.include("XYZ")
  end

  it "should log the warn message" do
    TestLogger.new.tap{|x| x.warn "XYZ"}.should.include("XYZ")
  end

  it "should log the info message" do
    TestLogger.new.tap{|x| x.info "XYZ"}.should.include("XYZ")
  end

  it "should log the debug message" do
    TestLogger.new.tap{|x| x.debug "XYZ"}.should.include("XYZ")
  end
end

shared "system logger" do
  it "should log the fatal message" do
    @logger.fatal "fatal message"
    sleep 0.1 while @logger.queued?
    @out.string.should.include("fatal message")
  end

  it "should log the error message" do
    @logger.error "error message"
    sleep 0.1 while @logger.queued?
    @out.string.should.include("error message")
  end

  it "should log the warn message" do
    @logger.warn "warn message"
    sleep 0.1 while @logger.queued?
    @out.string.should.include("warn message")
  end

  it "should log the info message" do
    @logger.info "info message"
    sleep 0.1 while @logger.queued?
    @out.string.should.include("info message")
  end

  it "should log the debug message" do
    @logger.debug "debug message"
    sleep 0.1 while @logger.queued?
    @out.string.should.include("debug message")
  end
end

describe "Pione::Log::PioneSystemLogger" do
  before do
    @out = StringIO.new
    @logger = Log::PioneSystemLogger.new(@out)
    @logger.level = :debug
  end

  after do
    @logger.terminate
  end

  behaves_like "system logger"
end

describe "Pione::Log::RubyStandardSystemLogger" do
  before do
    @out = StringIO.new
    @logger = Rootage::RubyStandardLogger.new(@out)
    @logger.level = :debug
  end

  behaves_like "system logger"
end

module MockSyslog
  @out = StringIO.new

  class << self
    attr_reader :out

    Logger::Syslog::LOGGER_MAP.values.uniq.each do |level|
      define_method(level) do |message|
        @out.puts "%s - %s" % [level.to_s, message]
      end
    end

    def reset
      @out = StringIO.new
    end
  end
end

Logger::Syslog.const_set :SYSLOG, MockSyslog

describe "Pione::Log::SyslogSystemLogger" do
  before do
    @out = MockSyslog.out
    @logger = Rootage::SyslogLogger.new
  end

  after do
    MockSyslog.reset
  end

  behaves_like "system logger"
end

describe "Pione::Log::SystemLog" do
  before do
    @orig = Global.system_logger
    @logger = TestLogger.new
    Global.system_logger = @logger
  end

  after do
    Global.system_logger = @orig
  end

  it "should log the fatal message" do
    Log::SystemLog.fatal("This is a fatal message.")
    @logger.should.include("This is a fatal message.")
  end

  it "should log the error message" do
    Log::SystemLog.fatal("This is an error message.")
    @logger.should.include("This is an error message.")
  end

  it "should log the warn message" do
    Log::SystemLog.fatal("This is a warn message.")
    @logger.should.include("This is a warn message.")
  end

  it "should log the info message" do
    Log::SystemLog.fatal("This is an info message.")
    @logger.should.include("This is an info message.")
  end

  it "should log the debug message" do
    Log::SystemLog.fatal("This is a debug message.")
    @logger.should.include("This is a debug message.")
  end
end


text:
namespace CIK.News.Web.Infras.ViewModels.Admin.DashBoard
{
    using System.ComponentModel.DataAnnotations;
    using System.Web;

    public class ItemEditingViewModel : ItemViewModel
    {
        public int ItemId { get; set; }

        [FileExtensions(Extensions = "jpg", ErrorMessage = "Specify a jpg file. (Comma-separated values)")]
        public HttpPostedFileBase SmallImage { get; set; }

        [FileExtensions(Extensions = "jpg", ErrorMessage = "Specify a jpg file. (Comma-separated values)")]
        public HttpPostedFileBase MediumImage { get; set; }

        [FileExtensions(Extensions = "jpg", ErrorMessage = "Specify a jpg file. (Comma-separated values)")]
        public HttpPostedFileBase BigImage { get; set; }

        public string SmallImagePath { get; set; }

        public string MediumImagePath { get; set; }

        public string BigImagePath { get; set; }
    }
}


text:
"""
gmm.py:  Estimation methods for a Gaussian mixture model
"""
from __future__ import division
from __future__ import print_function

import numpy as np
from vampyre.estim.base import BaseEst
from vampyre.estim.gaussian import GaussEst
from vampyre.estim.mixture import MixEst
from vampyre.common.utils import VpException, repeat_const

from sklearn import mixture

class GMMEst(BaseEst):
    """ Gaussian mixture estimator class with auto-tuning.

    There are two initialization methods.
    If :code:`probc` is supplied (i.e. is not None),
    then the GMM parameters are initialized by :code:`probc,meanc,varc`.
    Otherwise, they are initialized auto-matically.  With auto-init,
    the user must supply :code:`nc`, :code:`zmean_init` and :code:`zvar_init`.

    :param shape:  shape of the data
    :param probc:  probability for each cluster  (used as the initial value
        when EM tuning is enabled.)
    :param meanc:  mean for each cluster
    :param varc: variance for each cluster
    :param is_complex: flag indicating if data is complex
    :param map_est:  flag indicating if the estimator uses MAP estimation.
    :param zvarmin:  minimum variance in each cluster
    :param tune_gmm:  Enables EM tuning of the GMM parameters.
       In this case, `probc`, `meanc` and `varc` are used as initial estimates

    :note:  Currently the class only supports scalar (real or complex)
    Gaussian mixtures
    """
    def __init__(self, shape, probc, meanc, varc,name=None,\
        var_axes=(0,),mean_fix=None,var_fix=None,\
        is_complex=False,map_est=False,zvarmin=1e-3, tune_gmm=False):

        # Save properties
        self.map_est = map_est
        self.is_complex = is_complex
        self.zvarmin = zvarmin
        self.tune_gmm = tune_gmm
        self.mean_fix = mean_fix
        self.var_fix = var_fix

        dtype = meanc.dtype
        BaseEst.__init__(self,shape=shape,var_axes=var_axes,dtype=dtype,\
            name=name, type_name='GMM', nvars=1, cost_avail=True)

        # If the GMM parameters are given, set them now
        self.mix = None
        self.set_gmm_param(probc,meanc,varc)
        self.it = 0

        # Set the indicators on which the variance and means are fixed
        if self.mean_fix is None:
            self.mean_fix = np.zeros(len(probc))
        if self.var_fix is None:
            self.var_fix = np.zeros(len(probc))

    def set_gmm_param(self,probc,meanc,varc):
        """
        Sets the GMM parameters for the mixture estimator
        """
        nc = len(probc)

        if self.mix is None:
            # If the mixture estimator does not exist, create it
            # First, create the component Gaussian estimators
            est_list = []
            for i in range(nc):
                esti = GaussEst(meanc[i], varc[i], self.shape,
                     var_axes = self.var_axes, zmean_axes='all',
                     is_complex=self.is_complex, map_est=self.map_est)
                est_list.append(esti)

            # Create the mixture
            self.mix = MixEst(est_list,w=probc)

        else:
            # If the mixture distribution is already created,
            # set the parameters of the mixture estimator
            self.probc = probc
            self.mix.w = np.copy(probc)
            for i in range(nc):
                esti = self.mix.est_list[i]
                if not self.mean_fix[i]:
                    esti.zmean = meanc[i]
                if not self.var_fix[i]:
                    esti.zvar = np.copy(varc[i])

    def est_init(self, return_cost=False,ind_out=None,\
        avg_var_cost=True):
        """
        Initial estimator.

        See the base class :class:`vampyre.estim.base.Estim` for
        a complete description.

        :param Boolean return_cost:  Flag indicating if :code:`cost` is
            to be returned
        :returns: :code:`zmean, zvar, [cost]` which are the
            prior mean and variance
        """

        # otherwise, use the mixture estimator
        return self.mix.est_init(return_cost,ind_out,avg_var_cost)

    def est(self,r,rvar,return_cost=False,ind_out=None,\
        avg_var_cost=True):
        """
        Estimation function

        The proximal estimation function as
        described in the base class :class:`vampyre.estim.base.Estim`

        :param r: Proximal mean
        :param rvar: Proximal variance
        :param boolean return_cost:  Flag indicating if :code:`cost` is to be returned

        :returns: :code:`zhat, zhatvar, [cost]` which are the posterior
        mean, variance and optional cost.
        """

        # Run the estimator with the current parameter settings
        if return_cost:
            zhat,zhatvar,cost = self.mix.est(r,rvar,return_cost,ind_out,avg_var_cost)
        else:
            zhat,zhatvar = self.mix.est(r,rvar,return_cost,ind_out,avg_var_cost)

        # Update the parameters if tuning is enabled
        if (self.tune_gmm):
            self.update_gmm_em()

        # Increment the iteation counter
        self.it += 1

        # Return the values
        if return_cost:
            return zhat,zhatvar,cost
        else:
            return zhat,zhatvar

    def update_gmm_em(self):
        """
        Updates the GMM parameters using EM estimation
        """

        # Get the posterior probabilities, means and variances from the mixture
        # estimator.  The lists have one element for each component in the mixture
        prob_list = self.mix.prob
        zmean_list = self.mix.zmean_list
        zvar_list = self.mix.zvar_list

        # Compute new cluster probabilities mean and variances
        nc = len(prob_list)
        probc = np.zeros(nc)
        meanc = np.zeros(nc)
        varc = []
        for i in range(nc):
            probc[i] = np.mean(prob_list[i])
            meanc[i] = np.mean(prob_list[i]*zmean_list[i])/probc[i]
            dsq = zvar_list[i] + np.abs((zmean_list[i]-meanc[i]))**2
            varci = np.mean((prob_list[i]*dsq)/probc[i],axis=self.var_axes)
            varci = np.maximum(varci, self.zvarmin)
            varc.append(varci)

        # Set the parameters
        self.set_gmm_param(probc,meanc,varc)


text:
const KIND_USER = 'user'; const KIND_CATALOG = 'catalog';
const KIND_SYSTEM = 'system';
const KIND_SYSTEM_CATALOG = 'system-catalog';
const KIND_LEGACY_KUBERNETES = 'kubernetes';
const KIND_KUBERNETES = 'k8s';
const KIND_INFRA = 'infra';
const KIND_NOT_ORCHESTRATION = 'cattle';

var C = {
  CATALOG: {
    LIBRARY_KEY:           'library',
    LIBRARY_VALUE:         'https://git.rancher.io/charts',
    SYSTEM_LIBRARY_KEY:    'system-library',
    SYSTEM_LIBRARY_VALUE:  'https://git.rancher.io/system-charts',
    HELM_STABLE_KEY:       'helm',
    HELM_STABLE_VALUE:     'https://kubernetes-charts.storage.googleapis.com/',
    HELM_INCUBATOR_KEY:    'helm-incubator',
    HELM_INCUBATOR_VALUE:  'https://kubernetes-charts-incubator.storage.googleapis.com/',
    HELM_3_LIBRARY_KEY:    'helm3-library',
    HELM_3_LIBRARY_VALUE:  'https://git.rancher.io/helm3-charts',
    HELM_VERSION_2:        'rancher-helm',
    HELM_VERSION_3:        'helm_v3',
    HELM_VERSION_3_SHORT:  'v3',
    ALIBABA_APP_HUB_KEY:   'alibaba-app-hub',
    ALIBABA_APP_HUB_VALUE: 'https://apphub.aliyuncs.com',
    DEFAULT_BRANCH:        'master',
    LIBRARY_BRANCH:        'v2.0-development', // @TODO-2.0 '${RELEASE}',
    COMMUNITY_BRANCH:      'v2.0-development', // @TODO-2.0 '${RELEASE}',
  },

  COOKIE: {
    TOKEN:                    'token',
    CSRF:                     'CSRF',
    LANG:                     'LANG',
    USERNAME:                 'R_USERNAME',
    ACTIVEDIRECTORY_USERNAME: 'ACTIVEDIRECTORY_USERNAME'
  },

  EXTERNAL_ID: {
    KIND_SEPARATOR:         '://',
    GROUP_SEPARATOR:        ':',
    BASE_SEPARATOR:         '*',
    ID_SEPARATOR:           ':',
    KIND_ALL:               'containers',
    KIND_USER,
    KIND_CATALOG,
    KIND_SYSTEM,
    KIND_SYSTEM_CATALOG,
    KIND_LEGACY_KUBERNETES,
    KIND_KUBERNETES,
    KIND_INFRA,
    KIND_NOT_ORCHESTRATION,
    KIND_ORCHESTRATION:     [
      KIND_KUBERNETES,
    ],
    UPGRADEABLE: [
      KIND_CATALOG,
      KIND_SYSTEM_CATALOG
    ],
    SYSTEM_KINDS: [
      KIND_SYSTEM,
      KIND_SYSTEM_CATALOG,
    ],
    SHOW_AS_SYSTEM: [
      KIND_SYSTEM,
      KIND_INFRA,
      KIND_NOT_ORCHESTRATION,
    ],
    SYSTEM_CATEGORIES: [
      'Rancher services'
    ],
    CATALOG_DEFAULT_GROUP: 'library',
  },

  EXT_REFERENCES: {
    CN_FORUM: 'https://forums.cnrancher.com/',
    FORUM:    'https://forums.rancher.com',
    COMPANY:  'https://rancher.com',
    GITHUB:   'https://github.com/rancher/rancher',
    DOCS:     'https://rancher.com/docs/rancher',
    SLACK:    'https://slack.rancher.io',
    EULA:     'https://rancher.com/eula',
  },

  HEADER: {
    ACCOUNT_ID:         'X-Api-Account-Id',
    ACTIONS:            'X-Api-Action-Links',
    ACTIONS_VALUE:      'actionLinks',
    CSRF:               'X-Api-Csrf',
    NO_CHALLENGE:       'X-Api-No-Challenge',
    NO_CHALLENGE_VALUE: 'true',
    PROJECT_ID:         'X-Api-Project-Id',
    RANCHER_VERSION:    'X-Rancher-Version',
  },

  KEY: {
    LEFT:      37,
    UP:        38,
    RIGHT:     39,
    DOWN:      40,
    ESCAPE:    27,
    CR:        13,
    LF:        10,
    TAB:       9,
    SPACE:     32,
    PAGE_UP:   33,
    PAGE_DOWN: 34,
    HOME:      35,
    END:       36,
  },

  LABEL: {
    SYSTEM_PREFIX: 'io.rancher.',

    // Container
    DNS:                     'io.rancher.container.dns',
    HOSTNAME_OVERRIDE:       'io.rancher.container.hostname_override',
    HOSTNAME_OVERRIDE_VALUE: 'container_name',
    PULL_IMAGE:              'io.rancher.container.pull_image',
    PULL_IMAGE_VALUE:        'always',
    REQUESTED_IP:            'io.rancher.container.requested_ip',
    SERVICE_NAME:            'io.rancher.stack_service.name',
    START_ONCE:              'io.rancher.container.start_once',
    STACK_NAME:              'io.rancher.stack.name',
    STACK_UUID:              'io.rancher.stack.uuid',
    SYSTEM_TYPE:             'io.rancher.container.system',
    PER_HOST_SUBNET:         'io.rancher.network.per_host_subnet.subnet',

    // Catalog
    CERTIFIED:                      'io.rancher.certified',
    CERTIFIED_PARTNER:              'partner',
    CERTIFIED_RANCHER:              'rancher',
    CERTIFIED_RANCHER_EXPERIMENTAL: 'experimental',

    // Host
    DOCKER_VERSION: 'io.rancher.host.docker_version',
    KERNEL_VERSION: 'io.rancher.host.linux_kernel_version',
    KVM:            'io.rancher.host.kvm',
    SCHED_IPS:      'io.rancher.scheduler.ips',
    REQUIRE_ANY:    'io.rancher.scheduler.require_any',

    // Kubernetes
    K8S_DASHBOARD:     'io.rancher.k8s.kubernetes-dashboard',
    K8S_KUBECTL:       'io.rancher.k8s.kubectld',
    K8S_TOKEN:         'io.rancher.k8s.token',
    K8S_POD_NAME:      'io.kubernetes.pod.name',
    K8S_POD_NAMESPACE: 'io.kubernetes.pod.namespace',

    // Scheduling
    AFFINITY_PREFIX:       'io.rancher.scheduler.affinity:',
    SCHED_CONTAINER:       'io.rancher.scheduler.affinity:container',
    SCHED_CONTAINER_LABEL: 'io.rancher.scheduler.affinity:container_label',
    SCHED_GLOBAL:          'io.rancher.scheduler.global',
    SCHED_HOST_LABEL:      'io.rancher.scheduler.affinity:host_label',

    // Service
    DEPLOYMENT_UNIT:       'io.rancher.service.deployment.unit',
    HASH:                  'io.rancher.service.hash',
    LAUNCH_CONFIG:         'io.rancher.service.launch.config',
    LAUNCH_CONFIG_PRIMARY: 'io.rancher.service.primary.launch.config',
    BALANCER_TARGET:       'io.rancher.lb_service.target',

    DEPLOYMENT_REVISION: 'deployment.kubernetes.io/revision',

    CREATOR_ID: 'field.cattle.io/creatorId',
    TIMESTAMP:  'cattle.io/timestamp',

    // EKS Cluster session token
    EKS_SESSION_TOKEN: 'clusterstatus.management.cattle.io/temporary-security-credentials',

    // node driver special fields
    UI_HINTS: 'io.cattle.nodedriver/ui-field-hints',

    K3S_NODE_ARGS:        'k3s.io/node-args',
    K3S_NODE_CONFIG_HASH: 'k3s.io/node-config-hash',
    K3S_NODE_ENV:         'k3s.io/node-env',
    NODE_INSTANCE_TYPE:   'node.kubernetes.io/instance-type',
  },

  LANGUAGE: {
    DEFAULT:                 'en-us',
    FORMAT_RELATIVE_TIMEOUT: 1000,
    DOCS:                    ['en'],
  },

  WEBSOCKET: { SUBSCRIBE_DISCONNECTED_TIMEOUT: 30000 },

  PREFS: {
    ACCESS_WARNING:         'access-warning',
    BODY_BACKGROUND:        'body-background',
    CLUSTER_DEFAULT:        'default-cluster-id',
    CONTAINER_VIEW:         'container-view',
    COLLAPSED_CATALOGS:     'collapsed-catalogs',
    FEEDBACK:               'feedback',
    HOST_VIEW:              'host-view',
    I_HATE_SPINNERS:        'ihatespinners',
    LANGUAGE:               'language',
    LAST_IMAGE_PULL_POLICY: 'last-image-pull-policy',
    TARGET_OS:              'target-os',
    LAST_NAMESPACE:         'last-namespace',
    LAST_SCALE_MODE:        'last-scale-mode',
    PERIOD:                 'period',
    PROJECT_DEFAULT:        'default-project-id',
    PUSH_TO_REPO:           'push-to-repo',
    RECENT_CLUSTERS:        'recent-clusters',
    SORT_STACKS_BY:         'sort-stacks-by',
    TABLE_COUNT:            'table-count',
    THEME:                  'theme',
    WRAP_LINES:             'wrap-lines',
    LANDING:                'landing',
    SEEN_WHATS_NEW:         'seen-whats-new',
    CLOSED_BANNER:          'closed-banner',
  },

  PROJECT: {
    TYPE_RANCHER:                'local',
    TYPE_ACTIVE_DIRECTORY_USER:  'activedirectory_user',
    TYPE_ACTIVE_DIRECTORY_GROUP: 'activedirectory_group',
    TYPE_AZURE_USER:             'azuread_user',
    TYPE_AZURE_GROUP:            'azuread_group',
    TYPE_GITHUB_USER:            'github_user',
    TYPE_GITHUB_TEAM:            'github_team',
    TYPE_GITHUB_ORG:             'github_org',
    TYPE_KEYCLOAK_USER:          'keycloak_user',
    TYPE_KEYCLOAK_GROUP:         'keycloak_group',
    TYPE_LDAP_USER:              'ldap_user',
    TYPE_LDAP_GROUP:             'ldap_group',
    TYPE_OPENLDAP_USER:          'openldap_user',
    TYPE_OPENLDAP_GROUP:         'openldap_group',
    TYPE_SHIBBOLETH_USER:        'shibboleth_user',
    TYPE_SHIBBOLETH_GROUP:       'shibboleth_group',
    TYPE_PING_USER:              'ping_user',
    TYPE_PING_GROUP:             'ping_group',
    TYPE_ADFS_USER:              'adfs_user',
    TYPE_ADFS_GROUP:             'adfs_group',
    TYPE_OKTA_USER:              'okta_user',
    TYPE_OKTA_GROUP:             'okta_group',
    TYPE_FREEIPA_USER:           'freeipa_user',
    TYPE_FREEIPA_GROUP:          'freeipa_group',
    TYPE_GOOGLE_USER:            'googleoauth_user',
    TYPE_GOOGLE_GROUP:           'googleoauth_group',
    TYPE_GOOGLE_ORG:             'googleoauth_org',

    PERSON: 'person',
    TEAM:   'team',
    ORG:    'org',

    ROLE_MEMBER:  'member',
    ROLE_OWNER:   'owner',

    SUPPORTS_NETWORK_POLICY: [
      'ipsec',
      'vxlan',
    ]
  },

  SCHED_TOLERATION_OPERATOR: [
    {
      value: 'Equal',
      label: 'Equals'
    },
    {
      value: 'Exists',
      label: 'Exists'
    }
  ],

  SCHED_TOLERATION_EFFECT: [
    {
      value: 'NoSchedule',
      label: 'NoSchedule'
    },
    {
      value: 'NoExecute',
      label: 'NoExecute'
    },
    {
      value: 'PreferNoSchedule',
      label: 'PreferNoSchedule'
    },
  ],

  VOLUME_NODE_SELECTOR_OPERATOR: [
    {
      value: 'Exists',
      label: 'formScheduling.nodeSelector.operator.exists',
    },
    {
      value: 'DoesNotExist',
      label: 'formScheduling.nodeSelector.operator.notExists',
    },
    {
      value: 'In',
      label: 'formScheduling.nodeSelector.operator.in',
    },
    {
      value: 'NotIn',
      label: 'formScheduling.nodeSelector.operator.notIn',
    },
  ],

  SCHED_NODE_SELECTOR_OPERATOR: [
    {
      value: '=',
      label: 'formScheduling.nodeSelector.operator.eq',
    },
    {
      value: '!=',
      label: 'formScheduling.nodeSelector.operator.ne',
    },
    {
      value: 'Exists',
      label: 'formScheduling.nodeSelector.operator.exists',
    },
    {
      value: 'DoesNotExist',
      label: 'formScheduling.nodeSelector.operator.notExists',
    },
    {
      value: 'In',
      label: 'formScheduling.nodeSelector.operator.in',
    },
    {
      value: 'NotIn',
      label: 'formScheduling.nodeSelector.operator.notIn',
    },
    {
      value: '<',
      label: 'formScheduling.nodeSelector.operator.lt',
    },
    {
      value: '>',
      label: 'formScheduling.nodeSelector.operator.gt',
    },
  ],

  PROJECT_TEMPLATE: { DEFAULT: 'cattle', },

  RULE_VERBS: [
    'create',
    'delete',
    // 'deletecollection',
    'get',
    'list',
    'patch',
    'update',
    'watch',
  ],

  BASIC_POD_SECURITY_POLICIES: [
    'allowPrivilegeEscalation',
    'defaultAllowPrivilegeEscalation',
    'hostIPC',
    'hostNetwork',
    'hostPID',
    'privileged',
    'readOnlyRootFilesystem'
  ],

  VOLUME_POLICIES: [
    'azureFile',
    'azureDisk',
    'flocker',
    'flexVolume',
    'hostPath',
    'emptyDir',
    'gcePersistentDisk',
    'awsElasticBlockStore',
    'gitRepo',
    'secret',
    'nfs',
    'iscsi',
    'glusterfs',
    'persistentVolumeClaim',
    'rbd',
    'cinder',
    'cephFS',
    'downwardAPI',
    'fc',
    'configMap',
    'vsphereVolume',
    'quobyte',
    'photonPersistentDisk',
    'projected',
    'portworxVolume',
    'scaleIO',
    'storageos',
    '*',
  ],

  BASIC_ROLE_TEMPLATE_ROLES: [
    'cluster-owner',
    'cluster-member',
    'project-owner',
    'project-member'
  ],

  ROLE_RULES: [
    'Apps',
    'AuthConfigs',
    'Catalogs',
    'ClusterAlerts',
    'ClusterComposeConfigs',
    'ClusterEvents',
    'ClusterLoggings',
    'ClusterPipelines',
    'ClusterRegistrationTokens',
    'ClusterRoleTemplateBindings',
    'CertificateSigningRequests',
    'ClusterRoleBindings',
    'ClusterRoles',
    'Clusters',
    'ComponentStatuses',
    'ConfigMaps',
    'ControllerRevisions',
    'CronJobs',
    'DaemonSets',
    'Deployments',
    'Endpoints',
    'Events',
    'GlobalComposeConfigs',
    'GlobalRoleBindings',
    'GlobalRoles',
    'GroupMembers',
    'Groups',
    'HorizontalPodAutoscalers',
    'Ingresses',
    'Jobs',
    'LimitRanges',
    'ListenConfigs',
    'Namespaces',
    'NetworkPolicies',
    'NodeDrivers',
    'NodePools',
    'NodeTemplates',
    'Nodes',
    'Notifiers',
    'PersistentVolumeClaims',
    'PersistentVolumes',
    'PodDisruptionBudgets',
    'PodPreset',
    'PodSecurityPolicies',
    'PodTemplates',
    'Pods',
    'PipelineExecutionLogs',
    'PipelineExecutions',
    'Pipelines',
    'PodSecurityPolicyTemplateProjectBindings',
    'PodSecurityPolicyTemplates',
    'Preferences',
    'Principals',
    'ProjectAlerts',
    'ProjectLoggings',
    'ProjectNetworkPolicies',
    'ProjectRoleTemplateBindings',
    'Projects',
    'ReplicaSets',
    'ReplicationControllers',
    'ResourceQuotas',
    'RoleBindings',
    'Roles',
    'RoleTemplates',
    'Secrets',
    'ServiceAccounts',
    'Services',
    'StatefulSets',
    'StorageClasses',
    'Settings',
    'SourceCodeCredentials',
    'SourceCodeRepositories',
    'TemplateVersions',
    'Templates',
    'Tokens',
    'Users',
  ],

  // Ephemeral but same but across all browser tabs
  SESSION: {
    // @TODO-2.0 remove most of these
    BACK_TO:         'backTo',
    CONTAINER_ROUTE: 'containerSubRoute',
    ISTIO_ROUTE:     'istioSubRoute',
    PROJECT_ROUTE:   'projectRoute',
    CLUSTER_ROUTE:   'clusterRoute',
    GITHUB_CACHE:    'githubCache',
    GITHUB_ORGS:     'orgs',
    GITHUB_TEAMS:    'teams',
    IDENTITY:        'userIdentity',
    IDENTITY_TYPE:   'userType',
    LANGUAGE:        'language',
    LOGIN_LANGUAGE:  'loginLanguage',
    USER_ID:         'user',
    USER_TYPE:       'userType',

    DESCRIPTION: 'UI Session',
    TTL:         16 * 60 * 60 * 1000,
  },

  SETTING: {
    IMAGE_RANCHER:                    'server-image',
    VERSION_RANCHER:                  'server-version',
    VERSION_COMPOSE:                  'compose-version',
    VERSION_CLI:                      'cli-version',
    VERSION_MACHINE:                  'machine-version',
    VERSION_HELM:                     'helm-version',
    VERSIONS_K8S:                     'k8s-version-to-images',
    VERSION_RKE_K8S_DEFAULT:          'k8s-version',
    VERSION_K8S_SUPPORTED_RANGE:      'ui-k8s-supported-versions-range',
    VERSION_SYSTEM_K8S_DEFAULT_RANGE: 'ui-k8s-default-version-range',

    CLI_URL:                          {
      DARWIN:                         'cli-url-darwin',
      WINDOWS:                        'cli-url-windows',
      LINUX:                          'cli-url-linux',
    },

    API_HOST:                         'api-host',
    CA_CERTS:                         'cacerts',

    HIDE_LOCAL_CLUSTER:               'hide-local-cluster',
    // CLUSTER_DEFAULTS:              'cluster-defaults',
    AUTH_TOKEN_MAX_TTL_MINUTES:       'auth-token-max-ttl-minutes',
    ENGINE_URL:                       'engine-install-url',
    ENGINE_ISO_URL:                   'engine-iso-url',
    FIRST_LOGIN:                      'first-login',
    INGRESS_IP_DOMAIN:                'ingress-ip-domain',
    PL:                               'ui-pl',
    PL_RANCHER_VALUE:                 'rancher',
    UI_BANNERS:                       'ui-banners',
    UI_ISSUES:                        'ui-issues',
    SUPPORTED_DOCKER:                 'engine-supported-range',
    NEWEST_DOCKER:                    'engine-newest-version',
    SERVER_URL:                       'server-url',
    RKE_METADATA_CONFIG:              'rke-metadata-config',
    TELEMETRY:                        'telemetry-opt',
    EULA_AGREED:                      'eula-agreed',
    AUTH_USER_INFO_MAX_AGE_SECONDS:   'auth-user-info-max-age-seconds',
    AUTH_USER_SESSION_TTL_MINUTES:    'auth-user-session-ttl-minutes',
    AUTH_USER_INFO_RESYNC_CRON:       'auth-user-info-resync-cron',
    AUTH_LOCAL_VALIDATE_DESC:         'auth-password-requirements-description',
    FEEDBACK_FORM:                    'ui-feedback-form',
    CLUSTER_TEMPLATE_ENFORCEMENT:     'cluster-template-enforcement',
    UI_DEFAULT_LANDING:               'ui-default-landing',
  },

  TABLES: { DEFAULT_COUNT: 50 },

  THEME: {
    AUTO_UPDATE_TIMER: 30 * 60 * 1000,
    START_HOUR:        7,
    END_HOUR:          18,
    DEFAULT:           'ui-light',
  },

  USER: {
    TYPE_NORMAL:  'user',
    TYPE_ADMIN:   'admin',
    BASIC_BEARER: 'x-api-bearer',
  },

  WHATS_NEW_VERSION: '2.5.0',
};

C.SETTING.ALLOWED = {
  [C.SETTING.CA_CERTS]:                       { kind: 'multiline' },
  // [C.SETTING.CLUSTER_DEFAULTS]:            { kind: 'json' },
  [C.SETTING.ENGINE_URL]:                     {},
  [C.SETTING.ENGINE_ISO_URL]:                 {},
  [C.SETTING.PL]:                             {},
  [C.SETTING.UI_ISSUES]:                      {},
  [C.SETTING.INGRESS_IP_DOMAIN]:              {},
  [C.SETTING.AUTH_USER_INFO_MAX_AGE_SECONDS]: {},
  [C.SETTING.AUTH_USER_SESSION_TTL_MINUTES]:  {},
  [C.SETTING.AUTH_TOKEN_MAX_TTL_MINUTES]:     {},
  [C.SETTING.AUTH_USER_INFO_RESYNC_CRON]:     {},
  [C.SETTING.SERVER_URL]:                     { kind: 'url' },
  [C.SETTING.RKE_METADATA_CONFIG]:            { kind: 'json' },
  [C.SETTING.UI_BANNERS]:                     { kind: 'json' },
  'system-default-registry':                  {},
  'ui-index':                                 {},
  'ui-dashboard-index':                       {},
  'ui-offline-preferred':                     {},
  [C.SETTING.CLUSTER_TEMPLATE_ENFORCEMENT]:   { kind: 'boolean' },

  [C.SETTING.UI_DEFAULT_LANDING]: {
    kind:    'enum-map',
    options: {
      ember: 'Cluster Manager',
      vue:   'Cluster Explorer'
    },
  },
  [C.SETTING.TELEMETRY]: {
    kind:    'enum',
    options: ['prompt', 'in', 'out']
  },
};

C.LABELS_TO_IGNORE = [
  C.LABEL.HASH,
];

C.LABEL_ISTIO_RULE = 'io.rancher.istio';

// Excluded explicitly in form-labels-annotations so the label can be edited on a node resource
C.LABEL_CATTLE_CLUSTER_AGENT = 'cattle.io/cluster-agent';

C.READONLY_TAINT_PREFIX = [
  'node-role.kubernetes.io/',
  'node.kubernetes.io/',
  'node.cloudprovider.kubernetes.io/'
];

C.LABEL_PREFIX_TO_IGNORE = [
  'io.cattle.lifecycle.',
  'beta.kubernetes.io/',
  'failure-domain.beta.kubernetes.io/',
  'node-role.kubernetes.io/',
  'kubernetes.io/',
  'cattle.io/',
  'authz.management.cattle.io',
  'rke.cattle.io',
  'field.cattle.io',
  'workload.user.cattle.io/',
  'k3s.io',
  'node.kubernetes.io',
];

C.ANNOTATIONS_TO_IGNORE_CONTAINS = [
  'coreos.com/',
  'cattle.io/',
  'k3s.io',
]

C.ANNOTATIONS_TO_IGNORE_PREFIX = [
  'kubernetes.io/',
  'beta.kubernetes.io/',
  'node.alpha.kubernetes.io/',
  'volumes.kubernetes.io/',
  'k3s.io',
]

C.GRAY_OUT_ETCD_STATUS_PROVIDERS = [
  'k3s'
];

C.GRAY_OUT_SCHEDULER_STATUS_PROVIDERS = [
  'azureaks',
  'tencenttke',
  'linodelke'
];

C.SYSTEM_LABELS_WITH_CONTROL = [
  C.LABEL.SCHED_GLOBAL,
  C.LABEL.HOSTNAME_OVERRIDE,
  C.LABEL.DNS,
  C.LABEL.START_ONCE,
  C.LABEL.REQUESTED_IP,
  C.LABEL.PULL_IMAGE,
  C.LABEL.REQUIRE_ANY,
  C.LABEL.SCHED_IPS,
  C.LABEL.DOCKER_VERSION,
  C.LABEL.KERNEL_VERSION,
  C.LABEL.KVM,
];

C.ACTIVEISH_STATES = [
  'running',
  'active',
  'healthy',
  'initializing',
  'locked',
  'reinitializing',
  'degraded',
  'unhealthy',
  'upgrading',
  'updating',
  'upgraded',
  'draining',
  'drained',
  'cordoned'
];

C.READY_STATES = [
  'healthy',
];

C.REMOVEDISH_STATES = [
  'removed',
  // 'removing',
  'purging',
  'purged'
];

C.DISCONNECTED_STATES = [
  'disconnected',
  'reconnecting',
  'unavailable',
];

C.INITIALIZING_STATES = [
  'initializing',
  'reinitializing'
];

// This is populated by each app/components/schema/*
C.SUPPORTED_SCHEMA_INPUTS = [
  'boolean',
  'certificate',
  'date',
  'enum',
  'float',
  'host',
  'hostname',
  'int',
  'multiline',
  'istiohost',
  'password',
  'pvc',
  'service',
  'storageclass',
  'string',
  'masked',
  'secret',
  'base64',
];

C.RESOURCE_QUOTAS = [
  'limitsCpu',
  'requestsCpu',
  'limitsMemory',
  'requestsMemory',
  'requestsStorage',
  'servicesLoadBalancers',
  'servicesNodePorts',
  'pods',
  'services',
  'configMaps',
  'persistentVolumeClaims',
  'replicationControllers',
  'secrets',
];

C.AZURE_AD = {
  STANDARD: {
    KEY:            'standard',
    ENDPOINT:       'https://login.microsoftonline.com/',
    GRAPH_ENDPOINT: 'https://graph.windows.net/'
  },
  CHINA: {
    KEY:            'china',
    ENDPOINT:       'https://login.chinacloudapi.cn/',
    GRAPH_ENDPOINT: 'https://graph.chinacloudapi.cn/'
  },
  CUSTOM: { KEY: 'custom' }
};

C.AZURE_DEFAULTS = [
  'aadClientCertPassword',
  'aadClientCertPath',
  'aadClientId',
  'aadClientSecret',
  'cloud',
  'cloudProviderBackoff',
  'cloudProviderBackoffDuration',
  'cloudProviderBackoffExponent',
  'cloudProviderBackoffJitter',
  'cloudProviderBackoffRetries',
  'cloudProviderRateLimit',
  'cloudProviderRateLimitBucket',
  'cloudProviderRateLimitQPS',
  'loadBalancerSku',
  'location',
  'maximumLoadBalancerRuleCount',
  'primaryAvailabilitySetName',
  'primaryScaleSetName',
  'resourceGroup',
  'routeTableName',
  'securityGroupName',
  'subnetName',
  'subscriptionId',
  'tenantId',
  'useInstanceMetadata',
  'useManagedIdentityExtension',
  'vmType',
  'vnetName',
  'vnetResourceGroup',
];

C.VOLUME_TYPES = {
  BIND_MOUNT:      'bindMount',
  TMPFS:           'tmpfs',
  SECRET:          'secret',
  CERTIFICATE:     'certificate',
  CONFIG_MAP:      'configmap',
  CUSTOM_LOG_PATH: 'customLogPath'
}

C.NOTIFIER_TABLE_LABEL = {
  SLACK:     'Default Channel',
  PAGERDUTY: 'Service Key',
  SMTP:      'Default Recipient Address',
  WEBHOOK:   'URL',
  DEFAULT:   'Notifier',
  WECHAT:    'Default Recipient',
}

C.CONDITION = {
  SUCCESS: 'Success',
  CHANGED: 'Changed',
  FAILED:  'Failed',
}

C.ALERTING_COMPARISON = {
  EQUAL:            'equal',
  NOT_EQUAL:        'not-equal',
  GREATER_THAN:     'greater-than',
  LESS_THAN:        'less-than',
  GREATER_OR_EQUAL: 'greater-or-equal',
  LESS_OR_EQUAL:    'less-or-equal',
  HAS_VALUE:        'has-value',
}

C.ALERT_DURATION = [{
  label: '1 second',
  value: '1s',
}, {
  label: '10 seconds',
  value: '10s',
}, {
  label: '30 seconds',
  value: '30s',
}, {
  label: '1 minute',
  value: '1m',
}, {
  label: '2 minutes',
  value: '2m',
}, {
  label: '3 minutes',
  value: '3m',
}, {
  label: '4 minutes',
  value: '4m',
}, {
  label: '5 minutes',
  value: '5m',
}, {
  label: '10 minutes',
  value: '10m',
}, {
  label: '15 minutes',
  value: '15m',
}, {
  label: '20 minutes',
  value: '20m',
}, {
  label: '30 minutes',
  value: '30m',
}, {
  label: '1 hour',
  value: '1h',
}, {
  label: '2 hours',
  value: '2h',
}, {
  label: '3 hours',
  value: '3h',
}, {
  label: '6 hours',
  value: '6h',
}, {
  label: '7 hours',
  value: '7h',
}, {
  label: '12 hours',
  value: '12h',
}, {
  label: '13 hours',
  value: '13h',
}, {
  label: '24 hours',
  value: '1d',
}]

C.LOGGING_TPYE_TO_CONFIG = {
  elasticsearch:  'elasticsearch',
  splunk_hec:     'splunk',
  remote_syslog:  'syslog',
  kafka_buffered: 'kafka',
  forward:        'fluentForwarder',
}

C.POSTGRESQL_SSL_MODE = [
  'disable',
  'allow',
  'prefer',
  'require',
  'verify-ca',
  'verify-full',
]

C.NETWORK_CONFIG_DEFAULTS = {
  BACKEND_PORT:         '4789',
  BACKEND_VNI:          '4096',
  CALICO:               'calico',
  CANAL:                'canal',
  DEFAULT_BACKEND_TYPE: 'vxlan',
  FLANNEL:              'flannel',
  VXLAN:                'vxlan',
  WEAVE:                'weave',
}

C.CLUSTER_TEMPLATE_ROLES = {
  OWNER:     'owner',
  READ_ONLY: 'read-only',
}

// these fields are filtered when launching a cluster with a template because they have UI components
C.CLUSTER_TEMPLATE_IGNORED_OVERRIDES = [
  'defaultPodSecurityPolicyTemplateId',
  'dockerRootDir',
  'enableNetworkPolicy',
  'windowsPreferedCluster',
  'localClusterAuthEndpoint.caCerts',
  'localClusterAuthEndpoint.enabled',
  'localClusterAuthEndpoint.fqdn',
  'rancherKubernetesEngineConfig.ignoreDockerVersion',
  'rancherKubernetesEngineConfig.ingress.provider',
  'rancherKubernetesEngineConfig.kubernetesVersion',
  'rancherKubernetesEngineConfig.monitoring.provider',
  'rancherKubernetesEngineConfig.network.options',
  'rancherKubernetesEngineConfig.network.options.flannel_backend_port',
  'rancherKubernetesEngineConfig.network.options.flannel_backend_type',
  'rancherKubernetesEngineConfig.network.options.flannel_backend_vni',
  'rancherKubernetesEngineConfig.network.plugin',
  'rancherKubernetesEngineConfig.network.weaveNetworkProvider',
  'rancherKubernetesEngineConfig.privateRegistries[0].url',
  'rancherKubernetesEngineConfig.privateRegistries[0].user',
  'rancherKubernetesEngineConfig.privateRegistries[0].password',
  'rancherKubernetesEngineConfig.services.etcd.backupConfig.enabled',
  'rancherKubernetesEngineConfig.services.etcd.backupConfig.intervalHours',
  'rancherKubernetesEngineConfig.services.etcd.backupConfig.retention',
  'rancherKubernetesEngineConfig.services.etcd.backupConfig.s3BackupConfig.accessKey',
  'rancherKubernetesEngineConfig.services.etcd.backupConfig.s3BackupConfig.bucketName',
  'rancherKubernetesEngineConfig.services.etcd.backupConfig.s3BackupConfig.endpoint',
  'rancherKubernetesEngineConfig.services.etcd.backupConfig.s3BackupConfig.region',
  'rancherKubernetesEngineConfig.services.etcd.backupConfig.s3BackupConfig.secretKey',
  'rancherKubernetesEngineConfig.services.etcd.backupConfig.s3BackupConfig.folder',
  'rancherKubernetesEngineConfig.services.kubeApi.podSecurityPolicy',
  'rancherKubernetesEngineConfig.services.kubeApi.serviceNodePortRange',
]

C.CAN_SHELL_STATES = [
  'running',
  'notready'
]

C.SYSTEM_CHART_APPS = [
  'cluster-monitoring',
  'project-monitoring',
  'cluster-alerting',
  'rancher-logging',
  'cluster-istio',
  'monitoring-operator',
]

C.RESOURCE_TYPES = {
  NAMESPACE: 'namespace',
  PROJECT:   'project',
  CLUSTER:   'cluster'
};

C.FEATURES = {
  UNSUPPORTED_STORAGE_DRIVERS: 'unsupported-storage-drivers',
  ISTIO_VIRTUAL_SERVICE_UI:    'istio-virtual-service-ui',
  DASHBOARD:                   'dashboard',
}

C.NODES = { MASTER_NODE: 'node-role.kubernetes.io/master' };

C.STORAGE = {
  LONGHORN_PROVISIONER_KEY:           'driver.longhorn.io',
  LONGHORN_CATALOG_TEMPLATE_ID:       'cattle-global-data:library-longhorn',
  LONGHORN_CATALOG_ITEM_DEFAULT_NAME: 'longhorn-system',
};

C.LOGGING_FILE_TO_FORM = {
  ELASTICSEARCH: {
    hosts:               'endpoint',
    user:                'authUsername',
    password:            'authPassword',
    logstash_prefix:     'indexPrefix',
    logstash_dateformat: 'dateFormat',
  },
  SPLUNK: {
    host:          '',
    port:          '',
    token:         'token',
    sourcetype:    'source',
    default_index: 'index',
  },
  KAFKA: {
    zookeeper:     'zookeeperEndpoint',
    default_topic: 'topic',
    brokers:       'brokers',
  },
  SYSLOG: {
    host:     '',
    port:     '',
    protocol: 'protocol',
    program:  'program',
    token:    'token',
    severity: 'severity',
  },
  FLUENTD: {
    host:       '',
    port:       '',
    shared_key: 'sharedKey',
    username:   'username',
    password:   'password',
    weight:     'weight',
    standby:    'standby',
    name:       'hostname',
  }
}
export default C;


text:
import tkinter as tk
from tkinter import filedialog
from tkinter import messagebox
from ApplePie import *
from Utils import *

from ApplePieTk.subFrame.BaseFrame import *
from ApplePieTk.subFrame.Frame31 import *
from ApplePieTk.subFrame.Frame32 import *

class Frame3(BaseFrame):
    subFrame1 = None
    subFrame2 = None

    def __init__(self, parentFrame):
        super().__init__(parentFrame)
        self.subFrame1 = Frame31(self.frame)
        self.subFrame2 = Frame32(self.frame)

    def pack(self, applePieTk, row=None, col=None, colspan=None, align=None, side=None):
        super().pack(applePieTk, row, col, colspan, align, side)

        self.subFrame1.pack(self.pieTk)
        self.subFrame2.pack(self.pieTk)

    def refresh(self):
        print('frame3 refresh')
        self.subFrame1.refresh()
        self.subFrame2.refresh()


text:
import { Injectable } from '@angular/core';
import { nvD3 } from 'ontimize-web-ngx-nvd3';

import { ChartMarginConfiguration } from '../models/options/ChartMarginConfiguration.class';

@Injectable()
export class ChartService {
  private _chart: any;
  private _chartWrapper: nvD3;

  public get chart() {
    return this._chart;
  }

  public get chartWrapper(): nvD3 {
    return this._chartWrapper;
  }

  public set chartWrapper(chart: nvD3) {
    this._chartWrapper = chart;
    if (this._chartWrapper) {
      this._chart = (this._chartWrapper as any).chart;
    }
  }

  /**
   * Returns all configured options of chart.
   * @returns Object
   */
  public getChartOptions(): Object {
    if (this._chartWrapper) {
      return this._chartWrapper.options['chart'];
    }
    return {};
  }

  public setXAxisLabel(text: string) {
    let opts = this.getChartOptions();
    if (opts && opts['xAxis']) {
      opts['xAxis']['axisLabel'] = text;
    }
  }

  public setXAxisLabelDistance(distance: number) {
    let opts = this.getChartOptions();
    if (opts && opts['xAxis']) {
      opts['xAxis']['axisLabelDistance'] = distance;
    }
  }

  public setYAxisLabel(text: string) {
    let opts = this.getChartOptions();
    if (opts && opts['yAxis']) {
      opts['yAxis']['axisLabel'] = text;
    }
  }

  public setYAxisLabelDistance(distance: number) {
    let opts = this.getChartOptions();
    if (opts && opts['yAxis']) {
      opts['yAxis']['axisLabelDistance'] = distance;
    }
  }

  setMargin(margin: ChartMarginConfiguration) {
    let opts = this.getChartOptions();
    if (opts && margin) {
      opts['margin'] = margin;
    }
  }

}


text:
package ubic.gemma.model.common.auditAndSecurity.eventType;

/**
 * Indicates that we got batch information, but there was (as far as we can tell) just one batch. For example, a single
 * HiSeq lane.
 *
 * @author paul
 */
public class SingleBatchDeterminationEvent extends BatchInformationFetchingEvent {

    /**
     *
     */
    private static final long serialVersionUID = -6544162258733474787L;

    /**
     * No-arg constructor added to satisfy javabean contract
     *
     * @author Paul
     */
    public SingleBatchDeterminationEvent() {
    }

    @SuppressWarnings({ "unused", "WeakerAccess" }) // Possible external use
    public static final class Factory {
        public static SingleBatchDeterminationEvent newInstance() {
            return new SingleBatchDeterminationEvent();
        }

    }

}


text:
set -e -x
source ../../kube/config.sh

# New service account we will create.
SA_NAME="skcq-fe"
SA_EMAIL="${SA_NAME}@${PROJECT_SUBDOMAIN}.iam.gserviceaccount.com"

../../kube/secrets/add-service-account.sh \
  skia-public \
  skia-public \
  ${SA_NAME} \
  "Service account for SkCQ Frontend."
gcloud projects add-iam-policy-binding skia-firestore --member serviceAccount:${SA_EMAIL} --role roles/datastore.user


text:
#include "objMesh.h"
#include "massSpringSystemFromObjMesh.h"

int MassSpringSystemFromObjMesh::GenerateMassSpringSystem(ObjMesh * quadMesh, MassSpringSystem ** massSpringSystem, double surfaceDensity, double tensileStiffness, double shearStiffness, double bendStiffness, double damping, int addGravity)
{
  if (!quadMesh->isQuadrilateralMesh())
  {
    printf("Error: mesh is not quadrilateral.\n");
    return 1;
  }

  int numParticles;
  double * restPositions;
  int numQuads;
  int * faceCardinalities;
  int * quads;

  quadMesh->exportFaceGeometry(&numParticles, &restPositions, &numQuads, &faceCardinalities, &quads);

  *massSpringSystem = new MassSpringSystem(numParticles, restPositions, numQuads, quads, surfaceDensity, tensileStiffness, shearStiffness, bendStiffness, damping, addGravity);

  free(quads);
  free(faceCardinalities);
  free(restPositions);

  return 0;
}


text:
steal('can/util', 'can/view', 'can/util/string', 'can/observe/compute', 'can/view/scanner.js', 'can/view/render.js', function( can ) {
	// ## ejs.js
	// `can.EJS`
	// _Embedded JavaScript Templates._

	// Helper methods.
	var extend = can.extend,
		EJS = function( options ) {
			// Supports calling EJS without the constructor
			// This returns a function that renders the template.
			if ( this.constructor != EJS ) {
				var ejs = new EJS(options);
				return function( data, helpers ) {
					return ejs.render(data, helpers);
				};
			}
			// If we get a `function` directly, it probably is coming from
			// a `steal`-packaged view.
			if ( typeof options == "function" ) {
				this.template = {
					fn: options
				};
				return;
			}
			// Set options on self.
			extend(this, options);
			this.template = this.scanner.scan(this.text, this.name);
		};

	can.EJS = EJS;

	/**
	 * @add can.EJS
	 * @prototype
	 */
	EJS.prototype.
	/**
	 * @function can.EJS.prototype.render render
	 * @parent can.EJS.prototype
	 * @description Render a view object with data and helpers.
	 * @signature `render(data[, helpers])`
	 * @param {Object} [data] The data to populate the template with.
	 * @param {Object.<String, function>} [helpers] Helper methods referenced in the template.
	 * @return {String} The template with interpolated data.
	 *
	 * @body
	 * Renders an object with view helpers attached to the view.
	 *
	 *     new can.EJS({text: "<%= message %>"}).render({
	 *       message: "foo"
	 *     },{helper: function(){ ... }})
	 */
	render = function( object, extraHelpers ) {
		object = object || {};
		return this.template.fn.call(object, object, new EJS.Helpers(object, extraHelpers || {}));
	};

	extend(EJS.prototype, {
		/**
		 * @hide
		 * Singleton scanner instance for parsing templates.
		 */
		scanner: new can.view.Scanner({
			/**
			 * @hide
			 * An ordered token registry for the scanner.
			 * This needs to be ordered by priority to prevent token parsing errors.
			 * Each token is defined as: ["token-name", "string representation", "optional regexp override"]
			 */
			tokens: [
				["templateLeft", "<%%"], // Template
				["templateRight", "%>"], // Right Template
				["returnLeft", "<%=="], // Return Unescaped
				["escapeLeft", "<%="], // Return Escaped
				["commentLeft", "<%#"], // Comment
				["left", "<%"], // Run --- this is hack for now
				["right", "%>"], // Right -> All have same FOR Mustache ...
				["returnRight", "%>"]
			],

			/**
			 * @hide
			 * Transforms the EJS template to add support for shared blocks.
			 * Essentially, this breaks up EJS tags into multiple EJS tags
			 * if they contained unmatched brackets.
			 *
			 * For example, this doesn't work:
			 * 	<% if (1) { %><% if (1) { %> hi <% } } %>
			 * ...without isolated EJS blocks:
			 * 	<% if (1) { %><% if (1) { %> hi <% } %><% } %>
			 * The result of transforming:
			 * 	<% if (1) { %><% %><% if (1) { %><% %> hi <% } %><% } %>
			 */
			transform: function(source) {
				return source.replace(/<%([\s\S]+?)%>/gm, function(whole, part) {
					var brackets = [],
						foundBracketPair,
						i;

					// Look for brackets (for removing self-contained blocks)
					part.replace(/[{}]/gm, function(bracket, offset) {
						brackets.push([ bracket, offset ]);
					});

					// Remove bracket pairs from the list of replacements
					do {
						foundBracketPair = false;
						for (i = brackets.length - 2; i >= 0; i--) {
							if (brackets[i][0] == '{' && brackets[i+1][0] == '}') {
								brackets.splice(i, 2);
								foundBracketPair = true;
								break;
							}
						}
					} while (foundBracketPair);

					// Unmatched brackets found, inject EJS tags
					if (brackets.length >= 2) {
						var result = ['<%'],
							bracket,
							last = 0;
						for (i = 0; bracket = brackets[i]; i++) {
							result.push(part.substring(last, last = bracket[1]));
							if ((bracket[0] == '{' && i < brackets.length - 1) || (bracket[0] == '}' && i > 0)) {
								result.push(bracket[0] == '{' ? '{ %><% ' : ' %><% }');
							}
							else {
								result.push(bracket[0]);
							}
							++last;
						}
						result.push(part.substring(last), '%>');
						return result.join('');
					}
					// Otherwise return the original
					else {
						return '<%' + part + '%>';
					}
				});
			}
		})
	});

	EJS.Helpers = function( data, extras ) {
		this._data = data;
		this._extras = extras;
		extend(this, extras);
	};

	/**
	 * @page can.EJS.Helpers Helpers
	 * @parent can.EJS
	 *
	 * @body
	 * By adding functions to can.EJS.Helpers.prototype, those functions will be available in the
	 * views.
	 *
	 * The following helper converts a given string to upper case:
	 *
	 * 	can.EJS.Helpers.prototype.toUpper = function(params)
	 * 	{
	 * 		return params.toUpperCase();
	 * 	}
	 *
	 * Use it like this in any EJS template:
	 *
	 * 	<%= toUpper('javascriptmvc') %>
	 *
	 * To access the current DOM element return a function that takes the element as a parameter:
	 *
	 * 	can.EJS.Helpers.prototype.upperHtml = function(params)
	 * 	{
	 * 		return function(el) {
	 * 			$(el).html(params.toUpperCase());
	 * 		}
	 * 	}
	 *
	 * In your EJS view you can then call the helper on an element tag:
	 *
	 * 	<div <%= upperHtml('javascriptmvc') %>></div>
	 */
	EJS.Helpers.prototype = {
		// TODO Deprecated!!
		list : function(list, cb){

			can.each(list, function(item, i){
				cb(item, i, list)
			})
		},
		each: function(list, cb){
			// Normal arrays don't get live updated
			if (can.isArray(list)) {
				this.list(list, cb);
			}
			else {
				can.view.lists(list, cb);
			}
		}
	};

	// Options for `steal`'s build.
	can.view.register({
		suffix: "ejs",
		// returns a `function` that renders the view.
		script: function( id, src ) {
			return "can.EJS(function(_CONTEXT,_VIEW) { " + new EJS({
				text: src,
				name: id
			}).template.out + " })";
		},
		renderer: function( id, text ) {
			return EJS({
				text: text,
				name: id
			});
		}
	});

	return can;
});


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/pubsub/v1/pubsub.proto

package com.google.pubsub.v1;

public interface GetTopicRequestOrBuilder
    extends
    // @@protoc_insertion_point(interface_extends:google.pubsub.v1.GetTopicRequest)
    com.google.protobuf.MessageOrBuilder {

  /**
   *
   *
   *

   * Required. The name of the topic to get.
   * Format is `projects/{project}/topics/{topic}`.
   *

   *
   *
   * string topic = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
   *
   *
   * @return The topic.
   */
  java.lang.String getTopic();
  /**
   *
   *
   *

   * Required. The name of the topic to get.
   * Format is `projects/{project}/topics/{topic}`.
   *

   *
   *
   * string topic = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
   *
   *
   * @return The bytes for topic.
   */
  com.google.protobuf.ByteString getTopicBytes();
}


text:
		<div
			class     ="fixed tl whole-width whole-height scroll-overflow slow transitions container"
			ng-repeat ="content in DialogShelfController.$contents"
			ng-if     ="DialogShelfController.indexReady( $index )"
			ng-class  ="{
				'opaque way-way-above': $index == shownIndex,
				'mostly-opaque'       : $index != shownIndex && DialogShelfController.indexVisible( $index ),
				'transparent'         : ! DialogShelfController.indexVisible( $index ),
				'to-left'             : $index < shownIndex,
				'to-right'            : $index > shownIndex
			}"
		>

												{{ dialogTitle }}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">Jupiter Broadcasting</string>
    <string name="rss">Flux RSS</string>
    <string name="donate">Faire un don</string>
    <string-array name="OpenEpisode">
        <item >Page web</item>
        <item >Flux</item>
    </string-array>
    <string name="openepisodetitle">Voudriez-vous</string>
    <string name="plaiyinglivestream">Lecture en direct</string>
    <string name="opening">Ouverture </string>
    <string name="whichstream">Quel flux</string>
    <string name="audio">Audio</string>
    <string name="video">Vidéo</string>
    <string name="pause">Pause</string>
    <string name="loading">Chargement </string>
    <string name="allshows">Toutes les émissions</string>
    <string name="youtubefeed">Flux Youtube</string>
    <string name="play">Jouer</string>
</resources>


text:
require "commander"
require "fastlane_core"
require "supply"

HighLine.track_eof = false

module Supply
  class CommandsGenerator
    include Commander::Methods

    def self.start
      new.run
    end

    def run
      program :name, 'supply'
      program :version, Fastlane::VERSION
      program :description, Supply::DESCRIPTION
      program :help, 'Author', 'Felix Krause <supply@krausefx.com>'
      program :help, 'Website', 'https://fastlane.tools'
      program :help, 'GitHub', 'https://github.com/fastlane/fastlane/tree/master/supply'
      program :help_formatter, :compact

      always_trace!

      global_option('--verbose') { FastlaneCore::Globals.verbose = true }

      command :run do |c|
        c.syntax = 'fastlane supply'
        c.description = 'Run a deploy process'

        FastlaneCore::CommanderGenerator.new.generate(Supply::Options.available_options)

        c.action do |args, options|
          Supply.config = FastlaneCore::Configuration.create(Supply::Options.available_options, options.__hash__)
          load_supplyfile

          Supply::Uploader.new.perform_upload
        end
      end

      command :init do |c|
        c.syntax = 'fastlane supply init'
        c.description = 'Sets up supply for you'

        FastlaneCore::CommanderGenerator.new.generate(Supply::Options.available_options)

        c.action do |args, options|
          require 'supply/setup'
          Supply.config = FastlaneCore::Configuration.create(Supply::Options.available_options, options.__hash__)
          load_supplyfile

          Supply::Setup.new.perform_download
        end
      end

      default_command :run

      run!
    end

    def load_supplyfile
      Supply.config.load_configuration_file('Supplyfile')
    end
  end
end


text:
/**
 * Example controller
 * @author Simon Tannai <tannai.simon@gmail.com>
 * @license MIT
 * @todo: Nothing
 */

/**
 * Some function
 * @param  {Mixed} someParameter Some parameter
 * @return {Mixed}               Return parameter
 */
const someFunction = (someParameter) => {
  const result = someParameter + 10
  return result
}

/**
 * Export module with functions
 * @type {Object}
 */
module.exports = {
  someFunction: someFunction,
}


text:
namespace Cocos2D
{
    public class CCJumpTo : CCJumpBy
    {
        public CCJumpTo(float duration, CCPoint position, float height, uint jumps) :
            base(duration, position, height, jumps)
        {
            InitWithDuration(duration, position, height, jumps);
        }

        protected CCJumpTo(CCJumpTo jumpTo) : base(jumpTo)
        {
            InitWithDuration(jumpTo.m_fDuration, jumpTo.m_delta, jumpTo.m_height, jumpTo.m_nJumps);
        }

        protected internal override void StartWithTarget(CCNode target)
        {
            base.StartWithTarget(target);
            m_delta = new CCPoint(m_delta.X - m_startPosition.X, m_delta.Y - m_startPosition.Y);
        }

        public override object Copy(ICCCopyable zone)
        {
            if (zone != null)
            {
                var ret = zone as CCJumpTo;
                if (ret == null)
                {
                    return null;
                }
                base.Copy(zone);

                ret.InitWithDuration(m_fDuration, m_delta, m_height, m_nJumps);

                return ret;
            }
            else
            {
                return new CCJumpTo(this);
            }
        }
    }
}


text:
import {Chat, Greeting, GreetingType} from './simple/foo';

const chat = new Chat({
    greeting: new Greeting({
        type: GreetingType.WAVE,
        text: 123
    }),
    body: true
});

console.log(chat);


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
FormLoginSession (ATG Java API)
</TITLE>

<META NAME="date" CONTENT="2013-04-01">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

atg.servlet.security

Class FormLoginSession

java.lang.Object
  atg.servlet.security.FormLoginSession

public class FormLoginSession
extends java.lang.Object

The FormLoginSession stores information about whether an attempt
 is being made to log in to a form.

 If the desitination property of a FormLoginSession is null then there
 is no current for login taking place for the session.

Field Summary

static java.lang.String
CLASS_VERSION

Constructor Summary

FormLoginSession()

Method Summary

 java.lang.String
getDestination()

          Returns The destination URI which caused this form login session to take place

 java.lang.String
getErrorURI()

          Returns The URI of the error page to handle errors with the
 form authorization

 java.lang.String
getFormURI()

          Returns The URI of the login form

 LoginUserAuthority
getLoginUserAuthority()

          Returns The login User Authority to be used when handling this form login

 java.lang.String[]
getRoles()

          Returns The roles that the user must be in for the specified user
 authority for the form login to have been successful

 void
setDestination(java.lang.String pDestination)

          Sets The destination URI which caused this form login session to take place

 void
setErrorURI(java.lang.String pErrorURI)

          Sets The URI of the error page to handle errors with the form
 authorization

 void
setFormURI(java.lang.String pFormURI)

          Sets The URI of the login form

 void
setLoginUserAuthority(LoginUserAuthority pLoginUserAuthority)

          Sets The login User Authority to be used when handling this form login

 void
setRoles(java.lang.String[] pRoles)

          Sets The roles that the user must be in for the specified
 user authority for the form login to have been successful

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

CLASS_VERSION

public static java.lang.String CLASS_VERSION

Constructor Detail

FormLoginSession

public FormLoginSession()

Method Detail

setDestination

public void setDestination(java.lang.String pDestination)

Sets The destination URI which caused this form login session to take place

getDestination

public java.lang.String getDestination()

Returns The destination URI which caused this form login session to take place

setLoginUserAuthority

public void setLoginUserAuthority(LoginUserAuthority pLoginUserAuthority)

Sets The login User Authority to be used when handling this form login

getLoginUserAuthority

public LoginUserAuthority getLoginUserAuthority()

Returns The login User Authority to be used when handling this form login

setFormURI

public void setFormURI(java.lang.String pFormURI)

Sets The URI of the login form

getFormURI

public java.lang.String getFormURI()

Returns The URI of the login form

setErrorURI

public void setErrorURI(java.lang.String pErrorURI)

Sets The URI of the error page to handle errors with the form
 authorization

getErrorURI

public java.lang.String getErrorURI()

Returns The URI of the error page to handle errors with the
 form authorization

setRoles

public void setRoles(java.lang.String[] pRoles)

Sets The roles that the user must be in for the specified
 user authority for the form login to have been successful

getRoles

public java.lang.String[] getRoles()

Returns The roles that the user must be in for the specified user
 authority for the form login to have been successful

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
class ISGFile : public INpaFile
{
public:
    ISGFile(const string& Filename);
    ~ISGFile();

    struct SGEntry : INpaFile::Entry
    {
        uint32_t Unk;
    };

    char* ReadFile(NpaIterator iter);
    virtual char* ReadData(NpaIterator iter, uint32_t LocalOffset, uint32_t Size, void *(*Alloc)(size_t) = DefaultAlloc);
    bool IsDirectory(NpaIterator iter);

private:
    void ReadHeader();
};

#endif


text:
class BackgroundTheme : public ui::ThemeProvider {
 public:
  BackgroundTheme(ui::ThemeProvider* provider);
  virtual ~BackgroundTheme();

  // Overridden from ui::ThemeProvider:
  virtual bool UsingSystemTheme() const OVERRIDE;
  virtual gfx::ImageSkia* GetImageSkiaNamed(int id) const OVERRIDE;
  virtual SkColor GetColor(int id) const OVERRIDE;
  virtual int GetDisplayProperty(int id) const OVERRIDE;
  virtual bool ShouldUseNativeFrame() const OVERRIDE;
  virtual bool HasCustomImage(int id) const OVERRIDE;
  virtual base::RefCountedMemory* GetRawData(
      int id,
      ui::ScaleFactor scale_factor) const OVERRIDE;
  virtual NSImage* GetNSImageNamed(int id) const OVERRIDE;
  virtual NSColor* GetNSImageColorNamed(int id) const OVERRIDE;
  virtual NSColor* GetNSColor(int id) const OVERRIDE;
  virtual NSColor* GetNSColorTint(int id) const OVERRIDE;
  virtual NSGradient* GetNSGradient(int id) const OVERRIDE;

 private:
  ui::ThemeProvider* provider_;
  base::scoped_nsobject<NSGradient> buttonGradient_;
  base::scoped_nsobject<NSGradient> buttonPressedGradient_;
  base::scoped_nsobject<NSColor> borderColor_;
};

#endif  // CHROME_BROWSER_UI_COCOA_DOWNLOAD_BACKGROUND_THEME_H_


text:
package org.apache.spark.scheduler

import java.util.Properties

import org.apache.spark.TaskContext
import org.apache.spark.util.CallSite

/**
  * Tracks information about an active job in the DAGScheduler.
  *
  * 记录该 DAGScheduler中 active job的信息
指标有:

  *
 1:numPartitions 分区数
2:finished 分区完成情况
3:numFinished完成个数
  *
  */
private[spark] class ActiveJob(
                                val jobId: Int,
                                val finalStage: Stage,
                                val func: (TaskContext, Iterator[_]) => _,
                                val partitions: Array[Int],
                                val callSite: CallSite,
                                val listener: JobListener,
                                val properties: Properties) {

  val numPartitions = partitions.length
  /**
    * Array.fill[Boolean](numPartitions)(false)是初始化一个numPartitions大小的数组,其中每一个元素的值为false

    *

    */
  val finished = Array.fill[Boolean](numPartitions)(false)

  var numFinished = 0

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
    Copyright 2017 Capital One Services, LLC and Bitwise, Inc.
    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.
 -->

 <tns:Config xmlns:tns="hydrograph/ui/ComponentConfig" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="hydrograph/ui/ComponentConfig xsds/ComponentConfig.xsd ">
	<tns:component paletteIconPath="/icons/rdbms_palette.png" canvasIconPath="/icons/rdbms_canvas.png"
		name="OTeradata" nameInPalette="Teradata" defaultNamePrefix="OTeradata"
		description="Used to write data to Teradata tables"
		helpFilePath="/hydrograph.ui.help/html/Components/Output_Teradata.html"
		acronym="OTdata">
		<tns:category>OUTPUT</tns:category>
		<tns:port>
			<tns:portSpecification  numberOfPorts="1" portAlignment="left" changePortCountDynamically="false" allowMultipleLinks="false" linkMandatory="true">
				<tns:port sequenceOfPort="0" typeOfPort="in" labelOfPort="in0" portTerminal="in0" />
			</tns:portSpecification>
		</tns:port>

		<tns:property dataType="string" name="name" renderer="COMPONENT_NAME_WIDGET" type="USER"
			group="GENERAL" subGroup="DETAILS" showAsTooltip="TRUE" tooltipDataType="TEXT"
			usage="REQUIRED" propertyHelpText="Displays Name provided by the user"/>

		<tns:property dataType="string" name="schema" renderer="SCHEMA_WIDGET" type="USER"
			group="SCHEMA" subGroup="RECORD_STRUCTURE_DETAILS" showAsTooltip="TRUE" tooltipDataType="LIST"
			usage="REQUIRED">
			<tns:validator>SCHEMA_GRID_VALIDATOR</tns:validator>
		</tns:property>

		<tns:property dataType="string" name="databaseName" value="" renderer="DATABASE_NAME_WIDGET" type="USER"
			group="GENERAL" subGroup="CONFIGURATION" showAsTooltip="TRUE" tooltipDataType="LINK"
			usage="REQUIRED" propertyHelpText="Database name to connect.">
			<tns:validator>NON_BLANK_STRING_VALIDATOR</tns:validator>
		</tns:property>

		<tns:property dataType="string" name="hostName" value="" renderer="HOST_NAME_WIDGET"
			type="USER" group="GENERAL" subGroup="CONFIGURATION" showAsTooltip="TRUE" tooltipDataType="TEXT"
			usage="REQUIRED" propertyHelpText="Displays the Database Host Name provided by the user">
			<tns:validator>NON_BLANK_STRING_VALIDATOR</tns:validator>
		</tns:property>

		<tns:property dataType="string" name="jdbcDriver" value="TeraJDBC4" renderer="JDBC_DRIVER_WIDGET" type="USER"
			group="GENERAL" subGroup="CONFIGURATION" showAsTooltip="TRUE" tooltipDataType="LINK"
			usage="REQUIRED" propertyHelpText="JDBC DRIVER use to connect with Teradata database.">
			<tns:validator>NON_BLANK_STRING_VALIDATOR</tns:validator>
		</tns:property>

		<tns:property dataType="string" name="port" value="1025" renderer="PORT_WIDGET"
			type="USER" group="GENERAL" subGroup="CONFIGURATION" showAsTooltip="TRUE" tooltipDataType="TEXT"
			usage="REQUIRED" propertyHelpText="Displays the Database Port provided by the user">
			<tns:validator>PORT_VALIDATOR</tns:validator>
		</tns:property>

		<tns:property dataType="string" name="userName" value="" renderer="USER_NAME_WIDGET"
			type="USER" group="GENERAL" subGroup="CONFIGURATION" showAsTooltip="TRUE" tooltipDataType="TEXT"
			usage="REQUIRED" propertyHelpText="Displays the Database User Name provided by the user">
			<tns:validator>NON_BLANK_STRING_VALIDATOR</tns:validator>
		</tns:property>

		<tns:property dataType="string" name="password" value="" renderer="PASSWORD_WIDGET"
			type="USER" group="GENERAL" subGroup="CONFIGURATION" showAsTooltip="FALSE" tooltipDataType="TEXT"
			usage="REQUIRED" propertyHelpText="Password requires for connection with Mysql database">
			<tns:validator>NON_BLANK_STRING_VALIDATOR</tns:validator>
		</tns:property>

		<tns:property dataType="string" name="testConnection" value="" renderer="TEST_CONNECTION_WIDGET"
			type="USER" group="GENERAL" subGroup="CONFIGURATION" showAsTooltip="TRUE" tooltipDataType="TEXT"
			usage="REQUIRED" propertyHelpText="Used to test the connection for connecting Oracle DB">
		</tns:property>

		<tns:property dataType="string" name="selectInterface" renderer="SELECT_INTERFACE_WITH_LOAD_WIDGET" type="USER"
			group="GENERAL" subGroup="CONFIGURATION" showAsTooltip="TRUE" tooltipDataType="TEXT"
			usage="REQUIRED" propertyHelpText="Selects interface for export."/>

		<tns:property dataType="string" name="tableName" value="" renderer="TABLE_NAME_WIDGET"
			type="USER" group="GENERAL" subGroup="CONFIGURATION" showAsTooltip="TRUE" tooltipDataType="TEXT"
			usage="REQUIRED" propertyHelpText="Displays the Hive Table Name provided by the user">
			<tns:validator>NON_BLANK_STRING_VALIDATOR</tns:validator>
		</tns:property>

		<tns:property dataType="string" name="load_type_configuration" renderer="LOAD_TYPE_CONFIGURATION_WIDGET"
			type="USER" group="GENERAL" subGroup="CONFIGURATION" showAsTooltip="TRUE" tooltipDataType="TEXT"
			usage="OPTIONAL" propertyHelpText="Provides user to select the Load Type i.e. records are to be inserted,updated or to create a new table.">
			<tns:validator>DATABASE_KEY_VALIDATION</tns:validator>
		</tns:property>

		<tns:property dataType="string" name="outputAdditionalParameters" value="" renderer="OUTPUT_ADDITIONAL_PARAMETERS_WIDGET"
			type="USER" group="GENERAL" subGroup="CONFIGURATION" showAsTooltip="TRUE" tooltipDataType="TEXT"
			usage="REQUIRED" propertyHelpText="Used to provide additional parameters to connect Output TeraData DB">
			<tns:validator>ADDITIONAL_PARAM_VALIDATION</tns:validator>
		</tns:property>

		<tns:property dataType="string" name="runtime_properties" renderer="RUNTIME_PROPERTIES_WIDGET"
			type="USER" group="GENERAL" subGroup="CONFIGURATION" showAsTooltip="FALSE" tooltipDataType="NONE"
			usage="OPTIONAL" propertyHelpText="Used to override runtime \nHadoop configurations specific to \nthis component at run time."/>

		<tns:property dataType="string" name="batch" value="0" renderer="BATCH_WIDGET" type="USER"
			group="GENERAL" subGroup="CONFIGURATION" showAsTooltip="TRUE" tooltipDataType="TEXT"
			usage="REQUIRED" propertyHelpText="Specifies the execution sequence of \nthis component in the job flow.">
			<tns:validator>INTEGER_VALIDATOR</tns:validator>
		</tns:property>
	</tns:component>
</tns:Config>