text:
package com.hector.luis.spaceapp2016.earthlivelh.Activities;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.hector.luis.spaceapp2016.earthlivelh.Generic.AppConstant;
import com.hector.luis.spaceapp2016.earthlivelh.Models.Layer;
import com.hector.luis.spaceapp2016.earthlivelh.R;

import java.util.ArrayList;

import io.realm.Realm;
import io.realm.RealmConfiguration;
import io.realm.RealmResults;

public class MainActivity extends AppCompatActivity {

    private Realm realm;

    private ListView list;

    private ArrayList<Layer> layersList = new ArrayList<>();
    private LayerAdaper adaper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        RealmConfiguration realmConfig = new RealmConfiguration.Builder(this).build();
        // Get a Realm instance for this thread
        realm = Realm.getInstance(realmConfig);

        RealmResults<Layer> results = realm.where(Layer.class).findAll();

        layersList.addAll(results);

        list = (ListView) findViewById(R.id.list);
        adaper = new LayerAdaper(this, android.R.layout.simple_list_item_1, layersList);

        list.setAdapter(adaper);
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //Intent intent = new Intent(MainActivity.this, MapTestZoom0Activity.class);
                Intent intent = new Intent(MainActivity.this, MapActivity.class);
                intent.putExtra(AppConstant.KEY_INTENT_MAP, layersList.get(position).getTitle());

                startActivity(intent);
            }
        });
    }

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

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

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

        return super.onOptionsItemSelected(item);
    }
}

class LayerAdaper extends ArrayAdapter<Layer> {

    private Context context;
    private LayoutInflater inflater;
    private int resource;
    private ArrayList<Layer> layers;

    public LayerAdaper(Context context, int resource, ArrayList<Layer> layers) {
        super(context, resource);

        this.context = context;
        this.resource = resource;
        this.layers = layers;
        inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

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

    @Override
    public Layer getItem(int position) {
        return layers.get(position);
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = convertView;

        if (view == null)
            view = inflater.inflate(resource, null);

        TextView text1 = (TextView) view.findViewById(android.R.id.text1);
        String title = layers.get(position).getTitle().replace('_', ' ');
        title = title.replace("Day", "(Day)");
        title = title.replace(" Night", " (Night)");

        text1.setText(title);
        return view;
    }
}


text:
<?php
/**
 * This file is the main application controller for pasteshare
 * @license MIT
 */
namespace pasteshare;

/**
 * Main application controller for pasteshare
 *
 * @author Anthony Vitacco <anthony@littlegno.me>
 */
class PasteShare
{
    /** @var object An instance of pasteshare\Application */
    private $app;

    /**
     * This function stores the application instance globally
     *
     * @param object $app An instance of pasteshare\Application
     */
    public function __construct(Application $app)
    {
        $this->app = $app;
    }

    /**
     * Main index page for pasteshare
     *
     * @return object An instance of Symfony's response class
     */
    public function newPastePage()
    {
        $options = $this->app["options"];
        $options["languages"] = $this->getLanguagesFromCodeMirror();
        return $this->app->render("pages/main.twig", $options);
    }

    /**
     * Save function for pastes
     *
     * @param object $request An instance of Symfony's request class
     * @return object An instance of Symfony's response class
     */
    public function savePaste(\Symfony\Component\HttpFoundation\Request $request)
    {
        try {
            $dm = $this->app["deps"]["mongoDm"];
            $timezone = new \DateTimeZone($this->app["deps"]["siteConfig"]->application->timezone);
            $paste = new \pasteshare\Paste();

            if ($request->get("encrypted")) {
                $paste->encrypted = true;
                $paste->iv = $request->get("iv");
            }

            $paste->language = $request->get("language");
            $paste->contents = $request->get("contents");
            $paste->created = new \DateTime("now", $timezone);

            if ($request->get("expires") != "Never") {
                $paste->expires = true;
                $paste->expiration = new \DateTime($request->get("expires"), $timezone);
            }

            $dm->persist($paste);
            $dm->flush();

            $pasteUrl = $this->app->path("view", ["uniqid" => $paste->uniqid]);

            return $this->app->json(["status" => 200, "redirect" => $pasteUrl]);
        } catch (\RuntimeException $e) {
            return $this->app->json(["status" => 403, "error" => "Database unavailable"]);
        }
    }

    /**
     * View function for pastes
     *
     * @param object $request An instance of Symfony's request class
     * @return object An instance of Symfony's response class
     */
    public function viewPaste(\Symfony\Component\HttpFoundation\Request $request)
    {
        try {
            $dm = $this->app["deps"]["mongoDm"];
            $paste = $dm->getRepository("\pasteshare\Paste")->findOneBy(["uniqid" => $request->get("uniqid")]);
        } catch (\RuntimeException $e) {
        }

        $options = $this->app["options"];
        $options["paste"] = $paste->toArray();
        $options["language"] = $this->getLanguagesFromCodeMirror()[$paste->language];
        return $this->app->render("pages/main.twig", $options);
    }

    /**
     * This helper function parses the mode info from CodeMirror's mode/meta.js
     *
     * @return array The language information from mode/meta.js
     */
    private function getLanguagesFromCodeMirror()
    {
        $meta = file_get_contents(
            $this->app["deps"]["siteConfig"]->paths->app_root . "/bower_components/codemirror/mode/meta.js"
        );

        preg_match("/CodeMirror.modeInfo = (\[.*?\]);/s", $meta, $json);
        $json = $json[1];

        preg_match_all("/{.*}/", $json, $languages);

        $return = [];
        foreach ($languages[0] as $language) {
            preg_match("/name:\s\"(.+?)\"/", $language, $name);
            preg_match("/mode:\s\"(.+?)\"/", $language, $mode);
            $return[$mode[1]] = [
                "name" => $name[1],
                "mode" => $mode[1]
            ];
        }
        return $return;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package common

import (
    "encoding"
    "time"

    "github.com/swiftkick-io/xbinary"
)

// Snapshot captures a specific state of the log. It consists of the time the snapshot was taken, the number of items in the log, and a XXH64 hash of all the log entries.
type Snapshot interface {
    Time() time.Time
    Size() int64
    Hash() uint64
    encoding.BinaryMarshaler
}

func NewSnapshot(nanos, size int64, hash uint64) Snapshot {
    return BasicSnapshot{nanos, size, hash}
}

// BasicSnapshot represents the simplest snapshot which fulfills the Snapshot interface. The timestamp is stored as nanoseconds since epoch. Both size and hash are stored as 64-bit integers.
type BasicSnapshot struct {
    nanos int64
    size  int64
    hash  uint64
}

// Time converts the nanoseconds since epoch into a `time.Time` instance.
func (b BasicSnapshot) Time() time.Time {
    return time.Unix(0, b.nanos)
}

// Size returns the number of records in the log at the time the snapshot was taken.
func (b BasicSnapshot) Size() int64 {
    return b.size
}

// Hash returns the XXH64 hash of the log file.
func (b BasicSnapshot) Hash() uint64 {
    return b.hash
}

// MarshalBinary converts the snapshot into a byte array.
// The byte array is formatted like so:
//
// ```
// 8-byte int64  time
// 8-byte uint64 size
// 8-byte uint64 hash
//
// 0        8        16       24
// +--------+--------+--------+
// |  time  |  size  |  hash  |
// +--------+--------+--------+
// ```
func (b BasicSnapshot) MarshalBinary() ([]byte, error) {
    buffer := make([]byte, 24)
    xbinary.LittleEndian.PutInt64(buffer, 0, b.nanos)
    xbinary.LittleEndian.PutInt64(buffer, 8, b.size)
    xbinary.LittleEndian.PutUint64(buffer, 16, b.hash)
    return buffer, nil
}

// #### **UnmarshalShapshot**

// UnmarshalSnapshot is a utility function which converts a byte array into a snapshot. If the byte array is too small, a `ErrInvalidSnapshot` is returned.
func UnmarshalShapshot(data []byte) (Snapshot, error) {
    if len(data) != 24 {
        return nil, ErrInvalidSnapshot
    }

    var snapshot BasicSnapshot
    nanos, _ := xbinary.LittleEndian.Int64(data, 0)
    snapshot.nanos = nanos

    size, _ := xbinary.LittleEndian.Int64(data, 8)
    snapshot.size = size

    hash, _ := xbinary.LittleEndian.Uint64(data, 16)
    snapshot.hash = hash

    return snapshot, nil
}


text:
An Nodejs express boilerplate

To have your express template running just:

 1. `git clone git@github.com:rasensio/nodejs-express-template.git`
 2. `cd nodejs-express-template`
 3. `npm install`
 4. `node index.js`
 5. `curl localhost:3000`

Rodrigo Asensio [@rasensio](http://twitter.com/rasensio).


text:
package ec2

import (
	"net"

	"github.com/tmrts/flamingo/pkg/datasrc/metadata"
	"github.com/tmrts/flamingo/pkg/sys/ssh"
)

type Metadata struct {
	instanceAction     string      `json:"instance-action"`
	instanceID         string      `json:"instance-id"`
	instanceType       string      `json:"instance-type"`
	kernelID           string      `json:"kernel-id"`
	localHostname      string      `json:"local-hostname"`
	publicHostname     string      `json:"public-hostname"`
	aMIID              string      `json:"ami-id"`
	aMILaunchIndex     string      `json:"ami-launch-index"`
	aMIManifestPath    string      `json:"ami-manifest-path"`
	blockDeviceMapping string      `json:"block-device-mapping"`
	ramDiskID          string      `json:"ramdisk-id"`
	reservationID      string      `json:"reservation-id"`
	securityGroups     []string    `json:"security-groups"`
	placement          interface{} `json:"placement"`

	Hostname   string            `json:"hostname"`
	LocalIPv4  net.IP            `json:"local-ipv4"`
	PublicIPv4 net.IP            `json:"public-ipv4"`
	PublicKeys map[string]string `json:"public-keys"`
}

// Digest extracts the important parts of meta-data and returns it.
func (m *Metadata) Digest() metadata.Digest {
	sshKeys := make(map[string][]ssh.Key)

	for _, publicKey := range m.PublicKeys {
		sshKeys["root"] = append(sshKeys["root"], ssh.Key(publicKey))
	}

	primaryNetworkInterface := metadata.NetworkInterface{
		PrivateIP: m.LocalIPv4,
		PublicIPs: []net.IP{m.PublicIPv4},
	}

	return metadata.Digest{
		Hostname: m.Hostname,
		SSHKeys:  sshKeys,

		NetworkInterfaces: []metadata.NetworkInterface{
			primaryNetworkInterface,
		},
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<selector
	xmlns:android="http://schemas.android.com/apk/res/android">
	<item
		android:state_checked="true"
		android:state_enabled="false"
		android:drawable="@drawable/btn_check_on_disable" />
	<item
		android:state_checked="false"
		android:state_enabled="false"
		android:drawable="@drawable/btn_check_off_disable" />
	<item
		android:state_checked="true"
		android:state_enabled="true"
		android:drawable="@drawable/btn_check_on_normal" />
	<item
		android:state_checked="false"
		android:state_enabled="true"
		android:drawable="@drawable/btn_check_off_normal" />
</selector>


text:
<?php

namespace RoyallTheFourth\HtmlDocument\Element;

use RoyallTheFourth\HtmlDocument\Attribute\BooleanAttribute;
use RoyallTheFourth\HtmlDocument\Attribute\StandardAttribute;
use RoyallTheFourth\HtmlDocument\Set\AttributeSet;
use RoyallTheFourth\HtmlDocument\Set\ElementSet;
use RoyallTheFourth\HtmlDocument\Tag\Standard;

/**
 * Class Head
 * @see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/head
 */
final class Head extends AbstractElement implements ParentElementInterface
{
    public function __construct(AttributeSet $attributes = null, ElementSet $children = null)
    {
        $this->attributes = $attributes ?? new AttributeSet();
        $this->children = $children ?? new ElementSet();
        $this->tag = new Standard('head', $attributes, $children);
    }

    public function withAttribute(string $name, string $value = null): Head
    {
        if ($value) {
            $attribute = new StandardAttribute($name, $value);
        } else {
            $attribute = new BooleanAttribute($name);
        }

        return new Head($this->attributes->add($attribute), $this->children);
    }

    public function withChild(ElementInterface $element): Head
    {
        return new Head($this->attributes, $this->children->add($element));
    }
}


text:
import type { Dispatch } from 'react'
import type { FetchProxyDataResponse } from '@looker/extension-sdk'
import { extractMessageFromError } from '../../../utils'
import { updateErrorMessage } from '../data/DataReducer'

/**
 * Utility method to handle responses from the data server. Will log the user out
 * if a 401 response is returned.
 * @param response
 * @param dataDispatch
 * @param errorMessage
 */
export const handleResponse = (
  response: FetchProxyDataResponse,
  dataDispatch: Dispatch<any>,
  errorMessage = 'Unexpected error. Has the data server been started? yarn start start-data-server',
  firstTime = false
): boolean => {
  const { ok, status } = response
  if (ok) {
    if (!firstTime) {
      updateErrorMessage(dataDispatch, undefined)
    }
    return true
  } else {
    if (status === 401) {
      updateErrorMessage(dataDispatch, 'Token expired!')
    } else {
      updateErrorMessage(dataDispatch, errorMessage)
    }
    return false
  }
}

/**
 * Standard error handling for data server response. Parses out the error messages and
 * provides feed to user if environment has not been setup correctly (for example
 * data server not running).
 * @param error
 * @param dataDispatch
 * @param firstTime
 */
export const handleError = (
  error: any,
  dataDispatch: Dispatch<any>,
  firstTime = false
) => {
  console.error(error)
  const errorMessage = extractMessageFromError(error)
  if (errorMessage.startsWith('Extension not entitled to access external ')) {
    updateErrorMessage(dataDispatch, errorMessage)
  } else if (errorMessage.startsWith('Required Looker version ')) {
    updateErrorMessage(
      dataDispatch,
      'This version of Looker does not support external API functions'
    )
  } else if (errorMessage.startsWith('Entitlements must be defined')) {
    updateErrorMessage(
      dataDispatch,
      'Entitlements must be defined to use external API functionality'
    )
  } else if (firstTime) {
    updateErrorMessage(
      dataDispatch,
      'Has the data server been started? yarn start start-data-server'
    )
  } else {
    updateErrorMessage(
      dataDispatch,
      `An unexpected error occured: ${errorMessage}`
    )
  }
}


text:
package com.github.milenkovicm.kafka.protocol;

import java.util.List;

public class ProduceResponse extends Response {

    public final List<TopicProduceResponse> topics;

    public ProduceResponse(int correlationId, List<TopicProduceResponse> topics) {
        super(correlationId);
        this.topics = topics;
    }

    @Override
    public String toString() {
        return "ProduceResponse{" + "topics=" + topics + '}';
    }

    public static class TopicProduceResponse {

        public final String topicName;
        public final List<PartitionProduceResponse> partitions;

        public TopicProduceResponse(String topicName, List<PartitionProduceResponse> partitions) {
            this.topicName = topicName;
            this.partitions = partitions;
        }

        @Override
        public String toString() {
            return "TopicProduceResponse{" + "topicName='" + topicName + '\'' + ", partitions=" + partitions + '}';
        }
    }

    public static class PartitionProduceResponse {

        public final int partition;
        public final short errorCode;
        public final long offset;

        public PartitionProduceResponse(int partition, short errorCode, long offset) {
            this.partition = partition;
            this.errorCode = errorCode;
            this.offset = offset;
        }

        @Override
        public String toString() {
            return "PartitionProduceResponse{" + "partition=" + partition + ", errorCode=" + Error.valueOf(errorCode) + ", offset=" + offset + '}';
        }
    }
}


text:
/**
 * This class was created by <Vazkii>. It's distributed as
 * part of the Botania Mod. Get the Source Code in github:
 * https://github.com/Vazkii/Botania
 *
 * Botania is Open Source and distributed under a
 * Creative Commons Attribution-NonCommercial-ShareAlike 3.0 License
 * (http://creativecommons.org/licenses/by-nc-sa/3.0/deed.en_GB)
 *
 * File Created @ [Oct 29, 2014, 6:31:35 PM (GMT)]
 */
package vazkii.botania.api.internal;

/**
 * A Callback for when a shader is called. Used to define shader uniforms.
 */
public abstract class ShaderCallback {

	public abstract void call(int shader);

}


text:
@extends('layouts.app')

@section('style')

@endsection
@section('content')

Create Grade System here

            <form    id="form" accept-charset="utf-8" method="POST" name="applicationForm"  v-form>
                <input type="hidden" name="_token" value="{!! csrf_token() !!}">

                        Programme Categories*

                                             {!!  Form::select('type', array('HND'=>'HND','BTECH'=>'BTECH','DBS' => 'DBS','NON-T'=>'NON-TERTIARY' ), null, ['placeholder' => 'Select category','id'=>'parent','class'=>'md-input','required'=>'required','v-model'=>'type','v-form-ctrl'=>'','v-select'=>'','style'=>'width:200px'],old("type","")); !!}

              Lower Boundary  <input type="text"  v-model='lower[]' v-form-ctrl=''   class="md-input md-input"  name="lower[]" style="width:auto;">

              Upper Boundary  <input type="text"   class="md-input md-input" required=""   v-model='upper[]' v-form-ctrl='' name="upper[]" style="width:auto;">

          Grade
             {!! Form::select('grade[]',
                                (['' => 'select grade'] +$grade ),
                                  old("grade",""),
                                    ['class' => 'md-input gad','style'=>'width:200px','required'=>'','v-model'=>'grade','v-form-ctrl'=>'','v-select'=>''] )  !!}

          Value  <input type="text"    class="md-input md-input" required="" v-model='value[]' v-form-ctrl=''  name="value[]" style="width:auto;">

	  <button  type="button" id="insertPaymentRow" class="md-btn md-btn-primary md-btn-small " >add</button>

<input type="submit" value="Save" id='save'  class="md-btn   md-btn-success uk-margin-small-top">
      <input type="reset" value="Cancel" class="md-btn   md-btn-default uk-margin-small-top">

            </form>

@endsection

@section('js')


text: Configure Vim as a better python IDE using Puppet.


text:
package serviceaccount

import (
	"context"
	"errors"
	"fmt"

	authorizationv1beta1 "k8s.io/api/authorization/v1beta1"
	corev1 "k8s.io/api/core/v1"
	rbacv1 "k8s.io/api/rbac/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/client-go/kubernetes"
	clientcmdapi "k8s.io/client-go/tools/clientcmd/api/v1"
	"k8s.io/test-infra/gencred/pkg/kubeconfig"
)

const (
	// clusterRole is the ClusterRole role reference for created ClusterRoleBinding.
	clusterRole = "cluster-admin"
	// clusterRoleBindingName is the name for the created ClusterRoleBinding.
	clusterRoleBindingName = "serviceaccount-cluster-admin-crb"
	// serviceAccountName is the name for the created ServiceAccount.
	serviceAccountName = "serviceaccount-cluster-admin"
)

// checkSAAuth checks authorization for required cluster service account (SA) resources.
func checkSAAuth(clientset kubernetes.Interface) error {
	client := clientset.AuthorizationV1beta1().SelfSubjectAccessReviews()

	// https://kubernetes.io/docs/reference/access-authn-authz/rbac/#privilege-escalation-prevention-and-bootstrapping
	if sar, err := client.Create(
		context.TODO(),
		&authorizationv1beta1.SelfSubjectAccessReview{
			Spec: authorizationv1beta1.SelfSubjectAccessReviewSpec{
				ResourceAttributes: &authorizationv1beta1.ResourceAttributes{
					Group:    "rbac.authorization.k8s.io",
					Verb:     "bind",
					Resource: "clusterroles",
					Name:     clusterRole,
				},
			},
		},
		metav1.CreateOptions{}); err != nil {
		return fmt.Errorf("bind %s: %v", clusterRole, err)
	} else if !sar.Status.Allowed {
		return fmt.Errorf("not authorized to bind %s: %s", clusterRole, sar.Status.Reason)
	}

	return nil
}

// getOrCreateSA gets existing or creates new service account (SA).
func getOrCreateSA(clientset kubernetes.Interface) ([]byte, []byte, error) {
	client := clientset.CoreV1().ServiceAccounts(corev1.NamespaceDefault)

	// Check SelfSubjectAccessReviews are allowed.
	if err := checkSAAuth(clientset); err != nil {
		return nil, nil, err
	}

	// Create ServiceAccount if not exists.
	if _, err := client.Get(context.TODO(), serviceAccountName, metav1.GetOptions{}); err != nil {
		// Generate a Kubernetes ServiceAccount object.
		saObj := &corev1.ServiceAccount{
			ObjectMeta: metav1.ObjectMeta{
				Name: serviceAccountName,
			},
		}

		// Create ServiceAccount.
		_, err := client.Create(context.TODO(), saObj, metav1.CreateOptions{})
		if err != nil {
			return nil, nil, fmt.Errorf("create SA: %v", err)
		}
	}

	// Get/Create ClusterRoleBinding.
	err := getOrCreateCRB(clientset)
	if err != nil {
		return nil, nil, fmt.Errorf("get or create CRB: %v", err)
	}

	// Get ServiceAccount.
	saObj, err := client.Get(context.TODO(), serviceAccountName, metav1.GetOptions{})
	if err != nil {
		return nil, nil, fmt.Errorf("get SA: %v", err)
	}

	return getSASecrets(clientset, saObj)
}

// getOrCreateCRB gets existing or creates new cluster role binding (CRB).
func getOrCreateCRB(clientset kubernetes.Interface) error {
	client := clientset.RbacV1().ClusterRoleBindings()

	// Get ClusterRoleBinding if exists.
	if _, err := client.Get(context.TODO(), clusterRoleBindingName, metav1.GetOptions{}); err == nil {
		return nil
	}

	// Generate a Kubernetes ClusterRoleBinding object.
	crbObj := &rbacv1.ClusterRoleBinding{
		ObjectMeta: metav1.ObjectMeta{Name: clusterRoleBindingName},
		Subjects:   []rbacv1.Subject{{Kind: "ServiceAccount", Name: serviceAccountName, Namespace: corev1.NamespaceDefault}},
		RoleRef:    rbacv1.RoleRef{Kind: "ClusterRole", Name: clusterRole},
	}

	// Create ClusterRoleBinding.
	_, err := client.Create(context.TODO(), crbObj, metav1.CreateOptions{})
	if err != nil {
		return fmt.Errorf("create CRB: %v", err)
	}

	return nil
}

// getSASecrets gets service account token and root CA secrets.
func getSASecrets(clientset kubernetes.Interface, saObj *corev1.ServiceAccount) ([]byte, []byte, error) {
	client := clientset.CoreV1().Secrets(corev1.NamespaceDefault)

	if len(saObj.Secrets) == 0 {
		return nil, nil, errors.New("locate secrets")
	}

	// Get Secret.
	secretObj, err := client.Get(context.TODO(), saObj.Secrets[0].Name, metav1.GetOptions{})
	if err != nil {
		return nil, nil, fmt.Errorf("get secret: %v", err)
	}

	token, ok := secretObj.Data[corev1.ServiceAccountTokenKey]
	if !ok {
		return nil, nil, errors.New("locate token")
	}

	caPEM, ok := secretObj.Data[corev1.ServiceAccountRootCAKey]
	if !ok {
		return nil, nil, errors.New("locate root CA")
	}

	return token, caPEM, nil
}

// CreateClusterServiceAccountCredentials creates a service account to authenticate to a cluster API server.
func CreateClusterServiceAccountCredentials(clientset kubernetes.Interface) (token []byte, caPEM []byte, err error) {
	token, caPEM, err = getOrCreateSA(clientset)
	if err != nil {
		return nil, nil, fmt.Errorf("get or create SA: %v", err)
	}

	return token, caPEM, nil
}

// CreateKubeConfigWithServiceAccountCredentials creates a kube config containing a service account token to authenticate to a Kubernetes cluster API server.
func CreateKubeConfigWithServiceAccountCredentials(clientset kubernetes.Interface, name string) ([]byte, error) {
	token, caPEM, err := CreateClusterServiceAccountCredentials(clientset)
	if err != nil {
		return nil, err
	}

	authInfo := clientcmdapi.AuthInfo{
		Token: string(token),
	}

	return kubeconfig.CreateKubeConfig(clientset, name, caPEM, authInfo)
}


text:
package wolf.interfaces;

/**
 * An interface for each type of function in WOLF
 * @author Kevin Dittmar
 * @author William Ezekiel
 * @author Joseph Alacqua
 * @version Apr 3, 2016
 */
public interface WolfFunction extends Arg, ListArgument {
    @Override
    public Object accept(Visitor v);
}


text:
package org.apache.activemq.artemis.core.protocol.openwire.amq;

import org.apache.activemq.command.MessageAck;
import org.apache.activemq.command.MessagePull;

public class AMQSingleConsumerBrokerExchange extends AMQConsumerBrokerExchange {

   private AMQConsumer consumer;

   public AMQSingleConsumerBrokerExchange(AMQSession amqSession, AMQConsumer consumer) {
      super(amqSession);
      this.consumer = consumer;
   }

   @Override
   public void processMessagePull(MessagePull messagePull) throws Exception {
      consumer.processMessagePull(messagePull);
   }

   @Override
   public void removeConsumer() throws Exception {
      consumer.removeConsumer();
   }

   @Override
   public void acknowledge(MessageAck ack) throws Exception {
      consumer.acknowledge(ack);
   }

   @Override
   public void updateConsumerPrefetchSize(int prefetch) {
      consumer.setPrefetchSize(prefetch);
   }

}


text:
published: true
title: Variable length struct in C++
tags: c++ array
---
> since it's a POD, everything works just like it did in C. - [SO](https://stackoverflow.com/a/19970507/51386)

- [Multiple return values (structured bindings) with unmovable types and guaranteed RVO in C++17](https://stackoverflow.com/questions/38385451/multiple-return-values-structured-bindings-with-unmovable-types-and-guaranteed)
- [Array-to-pointer decay](https://stackoverflow.com/a/4810668/51386) - The only "connection" between T[n] and T[m] is that both types can implicitly be converted to T*, and the result of this conversion is a pointer to the first element of the array.

{% highlight cpp %}
struct var
{
    int a;
    int b[1];

    static std::shared_ptr<var> make_var(int num_b) {
        const extra_bytes = (num_b ? num_b-1 : 0)*sizeof(int);
        return std::shared_ptr<var>(
                new char[sizeof(var)+extra_bytes ],
                [](var* p){delete[]((char*)(p));});
}
{% endhighlight %}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=11"/>
<meta name="generator" content="Doxygen 1.9.3"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Tweakr: Member List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Tweakr

Android Library for Remote Debugging,  Autogenerating Settings/Preference UIs, and Wizard-of-Ozing

com.google.tweakr.types.EnumValueType< T > Member List

This is the complete list of members for com.google.tweakr.types.EnumValueType< T >, including all inherited members.

convert(Object newValue)	com.google.tweakr.types.EnumValueType< T >

EnumValueType(Class< T > clazz) (defined in com.google.tweakr.types.EnumValueType< T >)	com.google.tweakr.types.EnumValueType< T >

equals(Object o) (defined in com.google.tweakr.types.EnumValueType< T >)	com.google.tweakr.types.EnumValueType< T >

getDefault()	com.google.tweakr.types.EnumValueType< T >

getName()	com.google.tweakr.types.EnumValueType< T >

getPossibleValues()	com.google.tweakr.types.EnumValueType< T >

hashCode() (defined in com.google.tweakr.types.EnumValueType< T >)	com.google.tweakr.types.EnumValueType< T >

TYPE_ENUM (defined in com.google.tweakr.types.EnumValueType< T >)	com.google.tweakr.types.EnumValueType< T >	static

Generated by  1.9.3


text:
package com.android.settings;

import android.accessibilityservice.AccessibilityServiceInfo;
import android.app.ActionBar;
import android.app.Activity;
import android.app.ActivityManagerNative;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ResolveInfo;
import android.content.pm.ServiceInfo;
import android.content.res.Configuration;
import android.database.ContentObserver;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.os.SystemProperties;
import android.preference.CheckBoxPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceCategory;
import android.preference.PreferenceScreen;
import android.provider.Settings;
import android.text.TextUtils;
import android.text.TextUtils.SimpleStringSplitter;
import android.view.Gravity;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;

import com.android.internal.content.PackageMonitor;
import com.android.internal.view.RotationPolicy;
import com.android.settings.AccessibilitySettings.ToggleSwitch.OnBeforeCheckedChangeListener;

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

/**
 * Activity with the accessibility settings.
 */
public class AccessibilitySettings extends SettingsPreferenceFragment implements DialogCreatable,
        Preference.OnPreferenceChangeListener {
    private static final String DEFAULT_SCREENREADER_MARKET_LINK =
            "market://search?q=pname:com.google.android.marvin.talkback";

    private static final float LARGE_FONT_SCALE = 1.3f;

    private static final String SYSTEM_PROPERTY_MARKET_URL = "ro.screenreader.market";

    // Timeout before we update the services if packages are added/removed since
    // the AccessibilityManagerService has to do that processing first to
    // generate
    // the AccessibilityServiceInfo we need for proper presentation.
    private static final long DELAY_UPDATE_SERVICES_MILLIS = 1000;

    private static final char ENABLED_ACCESSIBILITY_SERVICES_SEPARATOR = ':';

    private static final String KEY_INSTALL_ACCESSIBILITY_SERVICE_OFFERED_ONCE =
            "key_install_accessibility_service_offered_once";

    // Preference categories
    private static final String SERVICES_CATEGORY = "services_category";
    private static final String SYSTEM_CATEGORY = "system_category";

    // Preferences
    private static final String TOGGLE_LARGE_TEXT_PREFERENCE =
            "toggle_large_text_preference";
    private static final String TOGGLE_POWER_BUTTON_ENDS_CALL_PREFERENCE =
            "toggle_power_button_ends_call_preference";
    private static final String TOGGLE_LOCK_SCREEN_ROTATION_PREFERENCE =
            "toggle_lock_screen_rotation_preference";
    private static final String TOGGLE_SPEAK_PASSWORD_PREFERENCE =
            "toggle_speak_password_preference";
    private static final String SELECT_LONG_PRESS_TIMEOUT_PREFERENCE =
            "select_long_press_timeout_preference";
    private static final String ENABLE_ACCESSIBILITY_GESTURE_PREFERENCE_SCREEN =
            "enable_global_gesture_preference_screen";
    private static final String DISPLAY_MAGNIFICATION_PREFERENCE_SCREEN =
            "screen_magnification_preference_screen";

    // Extras passed to sub-fragments.
    private static final String EXTRA_PREFERENCE_KEY = "preference_key";
    private static final String EXTRA_CHECKED = "checked";
    private static final String EXTRA_TITLE = "title";
    private static final String EXTRA_SUMMARY = "summary";
    private static final String EXTRA_SETTINGS_TITLE = "settings_title";
    private static final String EXTRA_COMPONENT_NAME = "component_name";
    private static final String EXTRA_SETTINGS_COMPONENT_NAME = "settings_component_name";

    // Dialog IDs.
    private static final int DIALOG_ID_NO_ACCESSIBILITY_SERVICES = 1;

    // Auxiliary members.
    private final static SimpleStringSplitter sStringColonSplitter =
            new SimpleStringSplitter(ENABLED_ACCESSIBILITY_SERVICES_SEPARATOR);

    private static final Set<ComponentName> sInstalledServices = new HashSet<ComponentName>();

    private final Map<String, String> mLongPressTimeoutValuetoTitleMap =
            new HashMap<String, String>();

    private final Configuration mCurConfig = new Configuration();

    private final PackageMonitor mSettingsPackageMonitor = new SettingsPackageMonitor();

    private final Handler mHandler = new Handler() {
        @Override
        public void dispatchMessage(Message msg) {
            super.dispatchMessage(msg);
            loadInstalledServices();
            updateServicesPreferences();
        }
    };

    private final SettingsContentObserver mSettingsContentObserver =
            new SettingsContentObserver(mHandler) {
        @Override
        public void onChange(boolean selfChange, Uri uri) {
            loadInstalledServices();
            updateServicesPreferences();
        }
    };

    private final RotationPolicy.RotationPolicyListener mRotationPolicyListener =
            new RotationPolicy.RotationPolicyListener() {
                @Override
                public void onChange() {
                    updateLockScreenRotationCheckbox();
                }
            };

    // Preference controls.
    private PreferenceCategory mServicesCategory;
    private PreferenceCategory mSystemsCategory;

    private CheckBoxPreference mToggleLargeTextPreference;
    private CheckBoxPreference mTogglePowerButtonEndsCallPreference;
    private CheckBoxPreference mToggleLockScreenRotationPreference;
    private CheckBoxPreference mToggleSpeakPasswordPreference;
    private ListPreference mSelectLongPressTimeoutPreference;
    private Preference mNoServicesMessagePreference;
    private PreferenceScreen mDisplayMagnificationPreferenceScreen;
    private PreferenceScreen mGlobalGesturePreferenceScreen;

    private int mLongPressTimeoutDefault;

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        addPreferencesFromResource(R.xml.accessibility_settings);
        initializeAllPreferences();
    }

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

        offerInstallAccessibilitySerivceOnce();

        mSettingsPackageMonitor.register(getActivity(), getActivity().getMainLooper(), false);
        mSettingsContentObserver.register(getContentResolver());
        RotationPolicy.registerRotationPolicyListener(getActivity(),
                mRotationPolicyListener);
    }

    @Override
    public void onPause() {
        mSettingsPackageMonitor.unregister();
        RotationPolicy.unregisterRotationPolicyListener(getActivity(),
                mRotationPolicyListener);
        mSettingsContentObserver.unregister(getContentResolver());
        super.onPause();
    }

    public boolean onPreferenceChange(Preference preference, Object newValue) {
        if (preference == mSelectLongPressTimeoutPreference) {
            String stringValue = (String) newValue;
            Settings.Secure.putInt(getContentResolver(),
                    Settings.Secure.LONG_PRESS_TIMEOUT, Integer.parseInt(stringValue));
            mSelectLongPressTimeoutPreference.setSummary(
                    mLongPressTimeoutValuetoTitleMap.get(stringValue));
            return true;
        }
        return false;
    }

    @Override
    public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
        if (mToggleLargeTextPreference == preference) {
            handleToggleLargeTextPreferenceClick();
            return true;
        } else if (mTogglePowerButtonEndsCallPreference == preference) {
            handleTogglePowerButtonEndsCallPreferenceClick();
            return true;
        } else if (mToggleLockScreenRotationPreference == preference) {
            handleLockScreenRotationPreferenceClick();
            return true;
        } else if (mToggleSpeakPasswordPreference == preference) {
            handleToggleSpeakPasswordPreferenceClick();
            return true;
        } else if (mGlobalGesturePreferenceScreen == preference) {
            handleTogglEnableAccessibilityGesturePreferenceClick();
            return true;
        } else if (mDisplayMagnificationPreferenceScreen == preference) {
            handleDisplayMagnificationPreferenceScreenClick();
            return true;
        }
        return super.onPreferenceTreeClick(preferenceScreen, preference);
    }

    private void handleToggleLargeTextPreferenceClick() {
        try {
            mCurConfig.fontScale = mToggleLargeTextPreference.isChecked() ? LARGE_FONT_SCALE : 1;
            ActivityManagerNative.getDefault().updatePersistentConfiguration(mCurConfig);
        } catch (RemoteException re) {
            /* ignore */
        }
    }

    private void handleTogglePowerButtonEndsCallPreferenceClick() {
        Settings.Secure.putInt(getContentResolver(),
                Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR,
                (mTogglePowerButtonEndsCallPreference.isChecked()
                        ? Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR_HANGUP
                        : Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR_SCREEN_OFF));
    }

    private void handleLockScreenRotationPreferenceClick() {
        RotationPolicy.setRotationLockForAccessibility(getActivity(),
                !mToggleLockScreenRotationPreference.isChecked());
    }

    private void handleToggleSpeakPasswordPreferenceClick() {
        Settings.Secure.putInt(getContentResolver(),
                Settings.Secure.ACCESSIBILITY_SPEAK_PASSWORD,
                mToggleSpeakPasswordPreference.isChecked() ? 1 : 0);
    }

    private void handleTogglEnableAccessibilityGesturePreferenceClick() {
        Bundle extras = mGlobalGesturePreferenceScreen.getExtras();
        extras.putString(EXTRA_TITLE, getString(
                R.string.accessibility_global_gesture_preference_title));
        extras.putString(EXTRA_SUMMARY, getString(
                R.string.accessibility_global_gesture_preference_description));
        extras.putBoolean(EXTRA_CHECKED, Settings.Global.getInt(getContentResolver(),
                Settings.Global.ENABLE_ACCESSIBILITY_GLOBAL_GESTURE_ENABLED, 0) == 1);
        super.onPreferenceTreeClick(mGlobalGesturePreferenceScreen,
                mGlobalGesturePreferenceScreen);
    }

    private void handleDisplayMagnificationPreferenceScreenClick() {
        Bundle extras = mDisplayMagnificationPreferenceScreen.getExtras();
        extras.putString(EXTRA_TITLE, getString(
                R.string.accessibility_screen_magnification_title));
        extras.putCharSequence(EXTRA_SUMMARY, getActivity().getResources().getText(
                R.string.accessibility_screen_magnification_summary));
        extras.putBoolean(EXTRA_CHECKED, Settings.Secure.getInt(getContentResolver(),
                Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_ENABLED, 0) == 1);
        super.onPreferenceTreeClick(mDisplayMagnificationPreferenceScreen,
                mDisplayMagnificationPreferenceScreen);
    }

    private void initializeAllPreferences() {
        mServicesCategory = (PreferenceCategory) findPreference(SERVICES_CATEGORY);
        mSystemsCategory = (PreferenceCategory) findPreference(SYSTEM_CATEGORY);

        // Large text.
        mToggleLargeTextPreference =
                (CheckBoxPreference) findPreference(TOGGLE_LARGE_TEXT_PREFERENCE);

        // Power button ends calls.
        mTogglePowerButtonEndsCallPreference =
                (CheckBoxPreference) findPreference(TOGGLE_POWER_BUTTON_ENDS_CALL_PREFERENCE);
        if (!KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_POWER)
                || !Utils.isVoiceCapable(getActivity())) {
            mSystemsCategory.removePreference(mTogglePowerButtonEndsCallPreference);
        }

        // Lock screen rotation.
        mToggleLockScreenRotationPreference =
                (CheckBoxPreference) findPreference(TOGGLE_LOCK_SCREEN_ROTATION_PREFERENCE);

        // Speak passwords.
        mToggleSpeakPasswordPreference =
                (CheckBoxPreference) findPreference(TOGGLE_SPEAK_PASSWORD_PREFERENCE);

        // Long press timeout.
        mSelectLongPressTimeoutPreference =
                (ListPreference) findPreference(SELECT_LONG_PRESS_TIMEOUT_PREFERENCE);
        mSelectLongPressTimeoutPreference.setOnPreferenceChangeListener(this);
        if (mLongPressTimeoutValuetoTitleMap.size() == 0) {
            String[] timeoutValues = getResources().getStringArray(
                    R.array.long_press_timeout_selector_values);
            mLongPressTimeoutDefault = Integer.parseInt(timeoutValues[0]);
            String[] timeoutTitles = getResources().getStringArray(
                    R.array.long_press_timeout_selector_titles);
            final int timeoutValueCount = timeoutValues.length;
            for (int i = 0; i < timeoutValueCount; i++) {
                mLongPressTimeoutValuetoTitleMap.put(timeoutValues[i], timeoutTitles[i]);
            }
        }

        // Display magnification.
        mDisplayMagnificationPreferenceScreen = (PreferenceScreen) findPreference(
                DISPLAY_MAGNIFICATION_PREFERENCE_SCREEN);

        // Global gesture.
        mGlobalGesturePreferenceScreen =
                (PreferenceScreen) findPreference(ENABLE_ACCESSIBILITY_GESTURE_PREFERENCE_SCREEN);
    }

    private void updateAllPreferences() {
        updateServicesPreferences();
        updateSystemPreferences();
    }

    private void updateServicesPreferences() {
        // Since services category is auto generated we have to do a pass
        // to generate it since services can come and go and then based on
        // the global accessibility state to decided whether it is enabled.

        // Generate.
        mServicesCategory.removeAll();

        AccessibilityManager accessibilityManager = AccessibilityManager.getInstance(getActivity());

        List<AccessibilityServiceInfo> installedServices =
                accessibilityManager.getInstalledAccessibilityServiceList();
        Set<ComponentName> enabledServices = getEnabledServicesFromSettings(getActivity());

        final boolean accessibilityEnabled = Settings.Secure.getInt(getContentResolver(),
                Settings.Secure.ACCESSIBILITY_ENABLED, 0) == 1;

        for (int i = 0, count = installedServices.size(); i < count; ++i) {
            AccessibilityServiceInfo info = installedServices.get(i);

            PreferenceScreen preference = getPreferenceManager().createPreferenceScreen(
                    getActivity());
            String title = info.getResolveInfo().loadLabel(getPackageManager()).toString();

            ServiceInfo serviceInfo = info.getResolveInfo().serviceInfo;
            ComponentName componentName = new ComponentName(serviceInfo.packageName,
                    serviceInfo.name);

            preference.setKey(componentName.flattenToString());

            preference.setTitle(title);
            final boolean serviceEnabled = accessibilityEnabled
                    && enabledServices.contains(componentName);
            if (serviceEnabled) {
                preference.setSummary(getString(R.string.accessibility_feature_state_on));
            } else {
                preference.setSummary(getString(R.string.accessibility_feature_state_off));
            }

            preference.setOrder(i);
            preference.setFragment(ToggleAccessibilityServicePreferenceFragment.class.getName());
            preference.setPersistent(true);

            Bundle extras = preference.getExtras();
            extras.putString(EXTRA_PREFERENCE_KEY, preference.getKey());
            extras.putBoolean(EXTRA_CHECKED, serviceEnabled);
            extras.putString(EXTRA_TITLE, title);

            String description = info.loadDescription(getPackageManager());
            if (TextUtils.isEmpty(description)) {
                description = getString(R.string.accessibility_service_default_description);
            }
            extras.putString(EXTRA_SUMMARY, description);

            String settingsClassName = info.getSettingsActivityName();
            if (!TextUtils.isEmpty(settingsClassName)) {
                extras.putString(EXTRA_SETTINGS_TITLE,
                        getString(R.string.accessibility_menu_item_settings));
                extras.putString(EXTRA_SETTINGS_COMPONENT_NAME,
                        new ComponentName(info.getResolveInfo().serviceInfo.packageName,
                                settingsClassName).flattenToString());
            }

            extras.putParcelable(EXTRA_COMPONENT_NAME, componentName);

            mServicesCategory.addPreference(preference);
        }

        if (mServicesCategory.getPreferenceCount() == 0) {
            if (mNoServicesMessagePreference == null) {
                mNoServicesMessagePreference = new Preference(getActivity()) {
                    @Override
                    protected void onBindView(View view) {
                        super.onBindView(view);
                        TextView summaryView = (TextView) view.findViewById(R.id.summary);
                        String title = getString(R.string.accessibility_no_services_installed);
                        summaryView.setText(title);
                    }
                };
                mNoServicesMessagePreference.setPersistent(false);
                mNoServicesMessagePreference.setLayoutResource(
                        R.layout.text_description_preference);
                mNoServicesMessagePreference.setSelectable(false);
            }
            mServicesCategory.addPreference(mNoServicesMessagePreference);
        }
    }

    private void updateSystemPreferences() {
        // Large text.
        try {
            mCurConfig.updateFrom(ActivityManagerNative.getDefault().getConfiguration());
        } catch (RemoteException re) {
            /* ignore */
        }
        mToggleLargeTextPreference.setChecked(mCurConfig.fontScale == LARGE_FONT_SCALE);

        // Power button ends calls.
        if (KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_POWER)
                && Utils.isVoiceCapable(getActivity())) {
            final int incallPowerBehavior = Settings.Secure.getInt(getContentResolver(),
                    Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR,
                    Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR_DEFAULT);
            final boolean powerButtonEndsCall =
                    (incallPowerBehavior == Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR_HANGUP);
            mTogglePowerButtonEndsCallPreference.setChecked(powerButtonEndsCall);
        }

        // Auto-rotate screen
        updateLockScreenRotationCheckbox();

        // Speak passwords.
        final boolean speakPasswordEnabled = Settings.Secure.getInt(getContentResolver(),
                Settings.Secure.ACCESSIBILITY_SPEAK_PASSWORD, 0) != 0;
        mToggleSpeakPasswordPreference.setChecked(speakPasswordEnabled);

        // Long press timeout.
        final int longPressTimeout = Settings.Secure.getInt(getContentResolver(),
                Settings.Secure.LONG_PRESS_TIMEOUT, mLongPressTimeoutDefault);
        String value = String.valueOf(longPressTimeout);
        mSelectLongPressTimeoutPreference.setValue(value);
        mSelectLongPressTimeoutPreference.setSummary(mLongPressTimeoutValuetoTitleMap.get(value));

        // Screen magnification.
        final boolean magnificationEnabled = Settings.Secure.getInt(getContentResolver(),
                Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_ENABLED, 0) == 1;
        if (magnificationEnabled) {
            mDisplayMagnificationPreferenceScreen.setSummary(
                    R.string.accessibility_feature_state_on);
        } else {
            mDisplayMagnificationPreferenceScreen.setSummary(
                    R.string.accessibility_feature_state_off);
        }

        // Global gesture
        final boolean globalGestureEnabled = Settings.Global.getInt(getContentResolver(),
                Settings.Global.ENABLE_ACCESSIBILITY_GLOBAL_GESTURE_ENABLED, 0) == 1;
        if (globalGestureEnabled) {
            mGlobalGesturePreferenceScreen.setSummary(
                    R.string.accessibility_global_gesture_preference_summary_on);
        } else {
            mGlobalGesturePreferenceScreen.setSummary(
                    R.string.accessibility_global_gesture_preference_summary_off);
        }
    }

    private void updateLockScreenRotationCheckbox() {
        Context context = getActivity();
        if (context != null) {
            mToggleLockScreenRotationPreference.setChecked(
                    !RotationPolicy.isRotationLocked(context));
        }
    }

    private void offerInstallAccessibilitySerivceOnce() {
        // There is always one preference - if no services it is just a message.
        if (mServicesCategory.getPreference(0) != mNoServicesMessagePreference) {
            return;
        }
        SharedPreferences preferences = getActivity().getPreferences(Context.MODE_PRIVATE);
        final boolean offerInstallService = !preferences.getBoolean(
                KEY_INSTALL_ACCESSIBILITY_SERVICE_OFFERED_ONCE, false);
        if (offerInstallService) {
            String screenreaderMarketLink = SystemProperties.get(
                    SYSTEM_PROPERTY_MARKET_URL,
                    DEFAULT_SCREENREADER_MARKET_LINK);
            Uri marketUri = Uri.parse(screenreaderMarketLink);
            Intent marketIntent = new Intent(Intent.ACTION_VIEW, marketUri);

            if (getPackageManager().resolveActivity(marketIntent, 0) == null) {
                // Don't show the dialog if no market app is found/installed.
                return;
            }

            preferences.edit().putBoolean(KEY_INSTALL_ACCESSIBILITY_SERVICE_OFFERED_ONCE,
                    true).commit();
            // Notify user that they do not have any accessibility
            // services installed and direct them to Market to get TalkBack.
            showDialog(DIALOG_ID_NO_ACCESSIBILITY_SERVICES);
        }
    }

    @Override
    public Dialog onCreateDialog(int dialogId) {
        switch (dialogId) {
            case DIALOG_ID_NO_ACCESSIBILITY_SERVICES:
                return new AlertDialog.Builder(getActivity())
                        .setTitle(R.string.accessibility_service_no_apps_title)
                        .setMessage(R.string.accessibility_service_no_apps_message)
                        .setPositiveButton(android.R.string.ok,
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        // dismiss the dialog before launching
                                        // the activity otherwise
                                        // the dialog removal occurs after
                                        // onSaveInstanceState which
                                        // triggers an exception
                                        removeDialog(DIALOG_ID_NO_ACCESSIBILITY_SERVICES);
                                        String screenreaderMarketLink = SystemProperties.get(
                                                SYSTEM_PROPERTY_MARKET_URL,
                                                DEFAULT_SCREENREADER_MARKET_LINK);
                                        Uri marketUri = Uri.parse(screenreaderMarketLink);
                                        Intent marketIntent = new Intent(Intent.ACTION_VIEW,
                                                marketUri);
                                        startActivity(marketIntent);
                                    }
                                })
                        .setNegativeButton(android.R.string.cancel, null)
                        .create();
            default:
                return null;
        }
    }

    private void loadInstalledServices() {
        Set<ComponentName> installedServices = sInstalledServices;
        installedServices.clear();

        List<AccessibilityServiceInfo> installedServiceInfos =
                AccessibilityManager.getInstance(getActivity())
                        .getInstalledAccessibilityServiceList();
        if (installedServiceInfos == null) {
            return;
        }

        final int installedServiceInfoCount = installedServiceInfos.size();
        for (int i = 0; i < installedServiceInfoCount; i++) {
            ResolveInfo resolveInfo = installedServiceInfos.get(i).getResolveInfo();
            ComponentName installedService = new ComponentName(
                    resolveInfo.serviceInfo.packageName,
                    resolveInfo.serviceInfo.name);
            installedServices.add(installedService);
        }
    }

    private static Set<ComponentName> getEnabledServicesFromSettings(Context context) {
        String enabledServicesSetting = Settings.Secure.getString(context.getContentResolver(),
                Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
        if (enabledServicesSetting == null) {
            enabledServicesSetting = "";
        }
        Set<ComponentName> enabledServices = new HashSet<ComponentName>();
        SimpleStringSplitter colonSplitter = sStringColonSplitter;
        colonSplitter.setString(enabledServicesSetting);
        while (colonSplitter.hasNext()) {
            String componentNameString = colonSplitter.next();
            ComponentName enabledService = ComponentName.unflattenFromString(
                    componentNameString);
            if (enabledService != null) {
                enabledServices.add(enabledService);
            }
        }
        return enabledServices;
    }

    private class SettingsPackageMonitor extends PackageMonitor {

        @Override
        public void onPackageAdded(String packageName, int uid) {
            Message message = mHandler.obtainMessage();
            mHandler.sendMessageDelayed(message, DELAY_UPDATE_SERVICES_MILLIS);
        }

        @Override
        public void onPackageAppeared(String packageName, int reason) {
            Message message = mHandler.obtainMessage();
            mHandler.sendMessageDelayed(message, DELAY_UPDATE_SERVICES_MILLIS);
        }

        @Override
        public void onPackageDisappeared(String packageName, int reason) {
            Message message = mHandler.obtainMessage();
            mHandler.sendMessageDelayed(message, DELAY_UPDATE_SERVICES_MILLIS);
        }

        @Override
        public void onPackageRemoved(String packageName, int uid) {
            Message message = mHandler.obtainMessage();
            mHandler.sendMessageDelayed(message, DELAY_UPDATE_SERVICES_MILLIS);
        }
    }

    public static class ToggleSwitch extends Switch {

        private OnBeforeCheckedChangeListener mOnBeforeListener;

        public static interface OnBeforeCheckedChangeListener {
            public boolean onBeforeCheckedChanged(ToggleSwitch toggleSwitch, boolean checked);
        }

        public ToggleSwitch(Context context) {
            super(context);
        }

        public void setOnBeforeCheckedChangeListener(OnBeforeCheckedChangeListener listener) {
            mOnBeforeListener = listener;
        }

        @Override
        public void setChecked(boolean checked) {
            if (mOnBeforeListener != null
                    && mOnBeforeListener.onBeforeCheckedChanged(this, checked)) {
                return;
            }
            super.setChecked(checked);
        }

        public void setCheckedInternal(boolean checked) {
            super.setChecked(checked);
        }
    }

    public static class ToggleAccessibilityServicePreferenceFragment
            extends ToggleFeaturePreferenceFragment implements DialogInterface.OnClickListener {

        private static final int DIALOG_ID_ENABLE_WARNING = 1;
        private static final int DIALOG_ID_DISABLE_WARNING = 2;

        private final SettingsContentObserver mSettingsContentObserver =
                new SettingsContentObserver(new Handler()) {
            @Override
            public void onChange(boolean selfChange, Uri uri) {
                String settingValue = Settings.Secure.getString(getContentResolver(),
                        Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
                final boolean enabled = settingValue.contains(mComponentName.flattenToString());
                mToggleSwitch.setCheckedInternal(enabled);
            }
        };

        private ComponentName mComponentName;

        private int mShownDialogId;

        @Override
        public void onResume() {
            mSettingsContentObserver.register(getContentResolver());
            super.onResume();
        }

        @Override
        public void onPause() {
            mSettingsContentObserver.unregister(getContentResolver());
            super.onPause();
        }

        @Override
        public void onPreferenceToggled(String preferenceKey, boolean enabled) {
            // Parse the enabled services.
            Set<ComponentName> enabledServices = getEnabledServicesFromSettings(getActivity());

            // Determine enabled services and accessibility state.
            ComponentName toggledService = ComponentName.unflattenFromString(preferenceKey);
            boolean accessibilityEnabled = false;
            if (enabled) {
                enabledServices.add(toggledService);
                // Enabling at least one service enables accessibility.
                accessibilityEnabled = true;
            } else {
                enabledServices.remove(toggledService);
                // Check how many enabled and installed services are present.
                Set<ComponentName> installedServices = sInstalledServices;
                for (ComponentName enabledService : enabledServices) {
                    if (installedServices.contains(enabledService)) {
                        // Disabling the last service disables accessibility.
                        accessibilityEnabled = true;
                        break;
                    }
                }
            }

            // Update the enabled services setting.
            StringBuilder enabledServicesBuilder = new StringBuilder();
            // Keep the enabled services even if they are not installed since we
            // have no way to know whether the application restore process has
            // completed. In general the system should be responsible for the
            // clean up not settings.
            for (ComponentName enabledService : enabledServices) {
                enabledServicesBuilder.append(enabledService.flattenToString());
                enabledServicesBuilder.append(ENABLED_ACCESSIBILITY_SERVICES_SEPARATOR);
            }
            final int enabledServicesBuilderLength = enabledServicesBuilder.length();
            if (enabledServicesBuilderLength > 0) {
                enabledServicesBuilder.deleteCharAt(enabledServicesBuilderLength - 1);
            }
            Settings.Secure.putString(getContentResolver(),
                    Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES,
                    enabledServicesBuilder.toString());

            // Update accessibility enabled.
            Settings.Secure.putInt(getContentResolver(),
                    Settings.Secure.ACCESSIBILITY_ENABLED, accessibilityEnabled ? 1 : 0);
        }

        // IMPORTANT: Refresh the info since there are dynamically changing capabilities. For
        // example, before JellyBean MR2 the user was granting the explore by touch one.
        private AccessibilityServiceInfo getAccessibilityServiceInfo() {
            List<AccessibilityServiceInfo> serviceInfos = AccessibilityManager.getInstance(
                    getActivity()).getInstalledAccessibilityServiceList();
            final int serviceInfoCount = serviceInfos.size();
            for (int i = 0; i < serviceInfoCount; i++) {
                AccessibilityServiceInfo serviceInfo = serviceInfos.get(i);
                ResolveInfo resolveInfo = serviceInfo.getResolveInfo();
                if (mComponentName.getPackageName().equals(resolveInfo.serviceInfo.packageName)
                        && mComponentName.getClassName().equals(resolveInfo.serviceInfo.name)) {
                    return serviceInfo;
                }
            }
            return null;
        }

        @Override
        public Dialog onCreateDialog(int dialogId) {
            switch (dialogId) {
                case DIALOG_ID_ENABLE_WARNING: {
                    mShownDialogId = DIALOG_ID_ENABLE_WARNING;
                    AccessibilityServiceInfo info = getAccessibilityServiceInfo();
                    if (info == null) {
                        return null;
                    }
                    return new AlertDialog.Builder(getActivity())
                        .setTitle(getString(R.string.enable_service_title,
                                info.getResolveInfo().loadLabel(getPackageManager())))
                        .setIconAttribute(android.R.attr.alertDialogIcon)
                        .setView(createEnableDialogContentView(info))
                        .setCancelable(true)
                        .setPositiveButton(android.R.string.ok, this)
                        .setNegativeButton(android.R.string.cancel, this)
                        .create();
                }
                case DIALOG_ID_DISABLE_WARNING: {
                    mShownDialogId = DIALOG_ID_DISABLE_WARNING;
                    AccessibilityServiceInfo info = getAccessibilityServiceInfo();
                    if (info == null) {
                        return null;
                    }
                    return new AlertDialog.Builder(getActivity())
                        .setTitle(getString(R.string.disable_service_title,
                                info.getResolveInfo().loadLabel(getPackageManager())))
                        .setIconAttribute(android.R.attr.alertDialogIcon)
                        .setMessage(getString(R.string.disable_service_message,
                                info.getResolveInfo().loadLabel(getPackageManager())))
                        .setCancelable(true)
                        .setPositiveButton(android.R.string.ok, this)
                        .setNegativeButton(android.R.string.cancel, this)
                        .create();
                }
                default: {
                    throw new IllegalArgumentException();
                }
            }
        }

        private View createEnableDialogContentView(AccessibilityServiceInfo info) {
            LayoutInflater inflater = (LayoutInflater) getSystemService(
                    Context.LAYOUT_INFLATER_SERVICE);

            View content = inflater.inflate(R.layout.enable_accessibility_service_dialog_content,
                    null);

            TextView capabilitiesHeaderView = (TextView) content.findViewById(
                    R.id.capabilities_header);
            capabilitiesHeaderView.setText(getString(R.string.capabilities_list_title,
                    info.getResolveInfo().loadLabel(getPackageManager())));

            LinearLayout capabilitiesView = (LinearLayout) content.findViewById(R.id.capabilities);

            // This capability is implicit for all services.
            View capabilityView = inflater.inflate(
                    com.android.internal.R.layout.app_permission_item_old, null);

            ImageView imageView = (ImageView) capabilityView.findViewById(
                    com.android.internal.R.id.perm_icon);
            imageView.setImageDrawable(getResources().getDrawable(
                    com.android.internal.R.drawable.ic_text_dot));

            TextView labelView = (TextView) capabilityView.findViewById(
                    com.android.internal.R.id.permission_group);
            labelView.setText(getString(R.string.capability_title_receiveAccessibilityEvents));

            TextView descriptionView = (TextView) capabilityView.findViewById(
                    com.android.internal.R.id.permission_list);
            descriptionView.setText(getString(R.string.capability_desc_receiveAccessibilityEvents));

            List<AccessibilityServiceInfo.CapabilityInfo> capabilities =
                    info.getCapabilityInfos();

            capabilitiesView.addView(capabilityView);

            // Service specific capabilities.
            final int capabilityCount = capabilities.size();
            for (int i = 0; i < capabilityCount; i++) {
                AccessibilityServiceInfo.CapabilityInfo capability = capabilities.get(i);

                capabilityView = inflater.inflate(
                        com.android.internal.R.layout.app_permission_item_old, null);

                imageView = (ImageView) capabilityView.findViewById(
                        com.android.internal.R.id.perm_icon);
                imageView.setImageDrawable(getResources().getDrawable(
                        com.android.internal.R.drawable.ic_text_dot));

                labelView = (TextView) capabilityView.findViewById(
                        com.android.internal.R.id.permission_group);
                labelView.setText(getString(capability.titleResId));

                descriptionView = (TextView) capabilityView.findViewById(
                        com.android.internal.R.id.permission_list);
                descriptionView.setText(getString(capability.descResId));

                capabilitiesView.addView(capabilityView);
            }

            return content;
        }

        @Override
        public void onClick(DialogInterface dialog, int which) {
            final boolean checked;
            switch (which) {
                case DialogInterface.BUTTON_POSITIVE:
                    checked = (mShownDialogId == DIALOG_ID_ENABLE_WARNING);
                    mToggleSwitch.setCheckedInternal(checked);
                    getArguments().putBoolean(EXTRA_CHECKED, checked);
                    onPreferenceToggled(mPreferenceKey, checked);
                    break;
                case DialogInterface.BUTTON_NEGATIVE:
                    checked = (mShownDialogId == DIALOG_ID_DISABLE_WARNING);
                    mToggleSwitch.setCheckedInternal(checked);
                    getArguments().putBoolean(EXTRA_CHECKED, checked);
                    onPreferenceToggled(mPreferenceKey, checked);
                    break;
                default:
                    throw new IllegalArgumentException();
            }
        }

        @Override
        protected void onInstallActionBarToggleSwitch() {
            super.onInstallActionBarToggleSwitch();
            mToggleSwitch.setOnBeforeCheckedChangeListener(new OnBeforeCheckedChangeListener() {
                @Override
                public boolean onBeforeCheckedChanged(ToggleSwitch toggleSwitch, boolean checked) {
                    if (checked) {
                        toggleSwitch.setCheckedInternal(false);
                        getArguments().putBoolean(EXTRA_CHECKED, false);
                        showDialog(DIALOG_ID_ENABLE_WARNING);
                    } else {
                        toggleSwitch.setCheckedInternal(true);
                        getArguments().putBoolean(EXTRA_CHECKED, true);
                        showDialog(DIALOG_ID_DISABLE_WARNING);
                    }
                    return true;
                }
            });
        }

        @Override
        protected void onProcessArguments(Bundle arguments) {
            super.onProcessArguments(arguments);
            // Settings title and intent.
            String settingsTitle = arguments.getString(EXTRA_SETTINGS_TITLE);
            String settingsComponentName = arguments.getString(EXTRA_SETTINGS_COMPONENT_NAME);
            if (!TextUtils.isEmpty(settingsTitle) && !TextUtils.isEmpty(settingsComponentName)) {
                Intent settingsIntent = new Intent(Intent.ACTION_MAIN).setComponent(
                        ComponentName.unflattenFromString(settingsComponentName.toString()));
                if (!getPackageManager().queryIntentActivities(settingsIntent, 0).isEmpty()) {
                    mSettingsTitle = settingsTitle;
                    mSettingsIntent = settingsIntent;
                    setHasOptionsMenu(true);
                }
            }

            mComponentName = arguments.getParcelable(EXTRA_COMPONENT_NAME);
        }
    }

    public static class ToggleScreenMagnificationPreferenceFragment
            extends ToggleFeaturePreferenceFragment {
        @Override
        protected void onPreferenceToggled(String preferenceKey, boolean enabled) {
            Settings.Secure.putInt(getContentResolver(),
                    Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_ENABLED, enabled? 1 : 0);
        }

        @Override
        protected void onInstallActionBarToggleSwitch() {
            super.onInstallActionBarToggleSwitch();
            mToggleSwitch.setOnBeforeCheckedChangeListener(new OnBeforeCheckedChangeListener() {
                @Override
                public boolean onBeforeCheckedChanged(ToggleSwitch toggleSwitch, boolean checked) {
                    toggleSwitch.setCheckedInternal(checked);
                    getArguments().putBoolean(EXTRA_CHECKED, checked);
                    onPreferenceToggled(mPreferenceKey, checked);
                    return false;
                }
            });
        }
    }

    public static class ToggleGlobalGesturePreferenceFragment
            extends ToggleFeaturePreferenceFragment {
        @Override
        protected void onPreferenceToggled(String preferenceKey, boolean enabled) {
            Settings.Global.putInt(getContentResolver(),
                    Settings.Global.ENABLE_ACCESSIBILITY_GLOBAL_GESTURE_ENABLED, enabled ? 1 : 0);
        }

        @Override
        protected void onInstallActionBarToggleSwitch() {
            super.onInstallActionBarToggleSwitch();
            mToggleSwitch.setOnBeforeCheckedChangeListener(new OnBeforeCheckedChangeListener() {
                @Override
                public boolean onBeforeCheckedChanged(ToggleSwitch toggleSwitch, boolean checked) {
                    toggleSwitch.setCheckedInternal(checked);
                    getArguments().putBoolean(EXTRA_CHECKED, checked);
                    onPreferenceToggled(mPreferenceKey, checked);
                    return false;
                }
            });
        }
    }

    public static abstract class ToggleFeaturePreferenceFragment
            extends SettingsPreferenceFragment {

        protected ToggleSwitch mToggleSwitch;

        protected String mPreferenceKey;
        protected Preference mSummaryPreference;

        protected CharSequence mSettingsTitle;
        protected Intent mSettingsIntent;

        // TODO: Showing sub-sub fragment does not handle the activity title
        // so we do it but this is wrong. Do a real fix when there is time.
        private CharSequence mOldActivityTitle;

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            PreferenceScreen preferenceScreen = getPreferenceManager().createPreferenceScreen(
                    getActivity());
            setPreferenceScreen(preferenceScreen);
            mSummaryPreference = new Preference(getActivity()) {
                @Override
                protected void onBindView(View view) {
                    super.onBindView(view);
                    TextView summaryView = (TextView) view.findViewById(R.id.summary);
                    summaryView.setText(getSummary());
                    sendAccessibilityEvent(summaryView);
                }

                private void sendAccessibilityEvent(View view) {
                    // Since the view is still not attached we create, populate,
                    // and send the event directly since we do not know when it
                    // will be attached and posting commands is not as clean.
                    AccessibilityManager accessibilityManager =
                            AccessibilityManager.getInstance(getActivity());
                    if (accessibilityManager.isEnabled()) {
                        AccessibilityEvent event = AccessibilityEvent.obtain();
                        event.setEventType(AccessibilityEvent.TYPE_VIEW_FOCUSED);
                        view.onInitializeAccessibilityEvent(event);
                        view.dispatchPopulateAccessibilityEvent(event);
                        accessibilityManager.sendAccessibilityEvent(event);
                    }
                }
            };
            mSummaryPreference.setPersistent(false);
            mSummaryPreference.setLayoutResource(R.layout.text_description_preference);
            preferenceScreen.addPreference(mSummaryPreference);
        }

        @Override
        public void onViewCreated(View view, Bundle savedInstanceState) {
            super.onViewCreated(view, savedInstanceState);
            onInstallActionBarToggleSwitch();
            onProcessArguments(getArguments());
            // Set a transparent drawable to prevent use of the default one.
            getListView().setSelector(new ColorDrawable(Color.TRANSPARENT));
            getListView().setDivider(null);
        }

        @Override
        public void onDestroyView() {
            getActivity().getActionBar().setCustomView(null);
            if (mOldActivityTitle != null) {
                getActivity().getActionBar().setTitle(mOldActivityTitle);
            }
            mToggleSwitch.setOnBeforeCheckedChangeListener(null);
            super.onDestroyView();
        }

        protected abstract void onPreferenceToggled(String preferenceKey, boolean enabled);

        @Override
        public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
            super.onCreateOptionsMenu(menu, inflater);
            MenuItem menuItem = menu.add(mSettingsTitle);
            menuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
            menuItem.setIntent(mSettingsIntent);
        }

        protected void onInstallActionBarToggleSwitch() {
            mToggleSwitch = createAndAddActionBarToggleSwitch(getActivity());
        }

        private ToggleSwitch createAndAddActionBarToggleSwitch(Activity activity) {
            ToggleSwitch toggleSwitch = new ToggleSwitch(activity);
            final int padding = activity.getResources().getDimensionPixelSize(
                    R.dimen.action_bar_switch_padding);
            toggleSwitch.setPaddingRelative(0, 0, padding, 0);
            activity.getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM,
                    ActionBar.DISPLAY_SHOW_CUSTOM);
            activity.getActionBar().setCustomView(toggleSwitch,
                    new ActionBar.LayoutParams(ActionBar.LayoutParams.WRAP_CONTENT,
                            ActionBar.LayoutParams.WRAP_CONTENT,
                            Gravity.CENTER_VERTICAL | Gravity.END));
            return toggleSwitch;
        }

        protected void onProcessArguments(Bundle arguments) {
            // Key.
            mPreferenceKey = arguments.getString(EXTRA_PREFERENCE_KEY);
            // Enabled.
            final boolean enabled = arguments.getBoolean(EXTRA_CHECKED);
            mToggleSwitch.setCheckedInternal(enabled);
            // Title.
            PreferenceActivity activity = (PreferenceActivity) getActivity();
            if (!activity.onIsMultiPane() || activity.onIsHidingHeaders()) {
                mOldActivityTitle = getActivity().getTitle();
                String title = arguments.getString(EXTRA_TITLE);
                getActivity().getActionBar().setTitle(title);
            }
            // Summary.
            CharSequence summary = arguments.getCharSequence(EXTRA_SUMMARY);
            mSummaryPreference.setSummary(summary);
        }
    }

    private static abstract class SettingsContentObserver extends ContentObserver {

        public SettingsContentObserver(Handler handler) {
            super(handler);
        }

        public void register(ContentResolver contentResolver) {
            contentResolver.registerContentObserver(Settings.Secure.getUriFor(
                    Settings.Secure.ACCESSIBILITY_ENABLED), false, this);
            contentResolver.registerContentObserver(Settings.Secure.getUriFor(
                    Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES), false, this);
        }

        public void unregister(ContentResolver contentResolver) {
            contentResolver.unregisterContentObserver(this);
        }

        @Override
        public abstract void onChange(boolean selfChange, Uri uri);
    }
}


text:
package com.microsoft.reef.examples.nggroup.bgd.simplelinesearch;

import com.microsoft.reef.runtime.hdinsight.client.UnsafeHDInsightRuntimeConfiguration;
import com.microsoft.tang.Configuration;

/**
 * Runs BGD on HDInsight
 */
public class BGDHDI {
  public static void main(final String[] args) throws Exception {
    final BGDClient bgdClient = BGDClient.fromCommandLine(args);
    final Configuration runtimeConfiguration = UnsafeHDInsightRuntimeConfiguration.fromEnvironment();
    bgdClient.submit(runtimeConfiguration, System.getProperty("user.name") + "-" + "SimpleBGDHDILineSearch");
  }
}


text:
if __name__ == '__main__':
    from IPython.qt.console.qtconsoleapp import main
    main()


text:
namespace taiju {

class PodsTrie : public TrieBase
{
public:
	PodsTrie();
	~PodsTrie() { clear(); }

	TrieType type() const { return PODS_TRIE; }
	const char *type_name() const { return "PodsTrie"; }

	UInt64 root() const { return num_nodes() - 1; }
	bool child(UInt64 id, UInt64 *id_ptr = NULL) const;
	bool sibling(UInt64 id, UInt64 *id_ptr = NULL) const;
	UInt8 label(UInt64 id) const { return labels_[id]; }
	bool is_terminal(UInt64 id) const { return is_terminals_[id]; }
	UInt64 key_id(UInt64 id) const { return is_terminals_.rank(id) - 1; }

	bool empty() const { return num_keys_ == 0; }
	UInt64 num_keys() const { return num_keys_; }
	UInt64 num_nodes() const { return labels_.num_objs(); }
	UInt64 size() const;

	bool find(const void *ptr, UInt64 size, UInt64 *key_id_ptr = NULL) const
	{ return TrieMethod::find(*this, ptr, size, key_id_ptr); }
	bool follow(UInt64 id, const void *ptr, UInt64 size,
		UInt64 *id_ptr = NULL) const
	{ return TrieMethod::follow(*this, id, ptr, size, id_ptr); }
	bool follow(UInt64 id, UInt8 label, UInt64 *id_ptr = NULL) const
	{ return TrieMethod::follow(*this, id, label, id_ptr); }

	void clear();
	void swap(PodsTrie *target);
	const void *map(Mapper mapper, bool checks_type = true);
	void read(Reader reader, bool checks_type = true);
	void write(Writer writer) const;

private:
	UInt64 num_keys_;
	ConstBiasedIntVector child_diffs_;
	ConstVector<bool> has_siblings_;
	ConstVector<UInt8> labels_;
	ConstBitVector is_terminals_;

	// Disallows copies.
	PodsTrie(const PodsTrie &);
	PodsTrie &operator=(const PodsTrie &);
};

inline bool PodsTrie::child(UInt64 id, UInt64 *id_ptr) const
{
	if (child_diffs_.is_zero(id))
		return false;

	if (id_ptr != NULL)
		*id_ptr = id - child_diffs_.as_non_zero(id);
	return true;
}

inline bool PodsTrie::sibling(UInt64 id, UInt64 *id_ptr) const
{
	if (!has_siblings_[id])
		return false;

	if (id_ptr != NULL)
		*id_ptr = id - 1;
	return true;
}

}  // namespace taiju

#endif  // TAIJU_PODS_TRIE_H


text:
    {{=current.menu.about}}

     {{poweredby=T("Powered by Sahana")}}
     {{=poweredby}}


text:
class ActiveSupport::TestCase

	setup do
		@server = RakeUp::ServerTask.new
		@server.custom_initialize
		@server.custom_start
	end

	teardown do
		@server.custom_end
	end

end