text:
package org.apache.hadoop.hdfs;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileAlreadyExistsException;
import org.apache.hadoop.fs.FileSystem;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.ZooDefs.Perms;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Id;
import org.apache.zookeeper.data.Stat;

public class AvatarZooKeeperClient {
  private String connection;
  private int timeout;
  private int connectTimeout;
  private boolean watch;
  // Prefix under which the data for this client will be stored
  private String prefix;
  private Watcher watcher;
  private ZooKeeper zk;

  // Making it large enough to be sure that the cluster is down
  // these retries go one after another so they do not take long
  public static final int ZK_CONNECTION_RETRIES = 10;
  public static final int ZK_CONNECT_TIMEOUT_DEFAULT = 10000; // 10 seconds

  public AvatarZooKeeperClient(Configuration conf, Watcher watcher) {
    this.connection = conf.get("fs.ha.zookeeper.quorum");
    this.timeout = conf.getInt("fs.ha.zookeeper.timeout", 3000);
    this.connectTimeout = conf.getInt("fs.ha.zookeeper.connect.timeout",
        ZK_CONNECT_TIMEOUT_DEFAULT);
    this.watch = conf.getBoolean("fs.ha.zookeeper.watch", false);
    this.prefix = conf.get("fs.ha.zookeeper.prefix", "/hdfs");
    this.watcher = new ProxyWatcher(watcher);
    if (watcher == null) {
      // If there was no watcher regardless of the watch policy in the conf
      // set it to false. Since there is no watcher being set
      watch = false;
    }
  }

  private static class ProxyWatcher implements Watcher {
    private Watcher impl;
    ProxyWatcher(Watcher impl) {
      this.impl = impl;
    }

    public void process(WatchedEvent event) {
      if (event.getType() == Event.EventType.None
              && event.getState() == Event.KeeperState.SyncConnected) {
        // The ZooKeeper client is connected
        synchronized (this) {
          this.notifyAll();
        }
      }
    }
  }

  public synchronized void clearPrimary(String address) throws IOException {
    String node = getRegistrationNode(address);
    zkCreateRecursively(node, null, true);
  }

  public synchronized void registerPrimary(String address, String realAddress,
      boolean overwrite)
    throws UnsupportedEncodingException, IOException {
    String node = getRegistrationNode(address);
    zkCreateRecursively(node, realAddress.getBytes("UTF-8"), overwrite);
  }

  public synchronized void registerPrimary(String address, String realAddress)
      throws UnsupportedEncodingException, IOException {
    registerPrimary(address, realAddress, true);
  }

  private void zkCreateRecursively(String zNode, byte[] data,
      boolean overwrite) throws IOException {
    initZK();
    System.out.println("create " + zNode);
    String[] parts = zNode.split("/");
    String path = "";
    byte[] payLoad = new byte[0];
    List<ACL> acls = new ArrayList<ACL>(1);
    acls.add(new ACL(Perms.ALL, new Id("world", "anyone")));

    try {
      for (int i = 0; i < parts.length; i++) {
        if (parts[i].isEmpty())
          continue;
        path += "/" + parts[i];
        if (i == parts.length - 1) {
          payLoad = data;
        }
        Stat stat;
        boolean created = false;
        while (!created) {
          // While loop to keep trying through the ConnectionLoss exceptions
          try {
            if ((stat = zk.exists(path, false)) != null) {
              // -1 indicates that we should update zNode regardless of its
              // version
              // since we are not utilizing versions in zNode - this is the best
              if (i == parts.length - 1 && !overwrite) {
                throw new FileAlreadyExistsException("ZNode " + path + " already exists.");
              }
              zk.setData(path, payLoad, -1);
            } else {
              zk.create(path, payLoad, acls, CreateMode.PERSISTENT);
            }
            created = true;
          } catch (KeeperException ex) {
            ex.printStackTrace();
            if (KeeperException.Code.CONNECTIONLOSS != ex.code()) {
              throw ex;
            }
          }
        }
      }
      FileSystem.LOG.info("Wrote zNode " + zNode);
    } catch (KeeperException e) {
      e.printStackTrace();
    } catch (InterruptedException e) {
      e.printStackTrace();
      Thread.currentThread().interrupt();
    } finally {
      try {
        stopZK();
      } catch (InterruptedException ex) {
        Thread.currentThread().interrupt();
      }
    }
  }

  /**
   * Tries to connect to ZooKeeper. To be used when we need to test if the
   * ZooKeeper cluster is available and the config is correct
   *
   * @throws IOException
   * @throws InterruptedException
   */
  public synchronized void primeConnection() throws IOException,
      InterruptedException {
    initZK();
    if (!watch) {
      stopZK();
    }
  }

  private void initZK() throws IOException {
    synchronized (watcher) {
      if (zk == null || zk.getState() == ZooKeeper.States.CLOSED) {
        zk = new ZooKeeper(connection, timeout, watcher);
      }
      if (zk.getState() != ZooKeeper.States.CONNECTED) {
        try {
          watcher.wait(this.connectTimeout);
        } catch (InterruptedException iex) {
        }
      }
      if (zk.getState() != ZooKeeper.States.CONNECTED) {
        throw new IOException("Timed out trying to connect to ZooKeeper");
      }
    }
  }

  private void stopZK() throws InterruptedException {
    if (zk == null)
      return;
    zk.close();
    zk = null;
  }

  /**
   * Get the information stored in the node of zookeeper. If retry is set
   * to true it will keep retrying until the data in that node is available
   * (failover case). If the retry is set to false it will return the first
   * value that it gets from the zookeeper.
   *
   * @param node the path of zNode in zookeeper
   * @param stat {@link Stat} object that will contain stats of the node
   * @param retry if true will retry until the data in znode is not null
   * @return byte[] the data in the znode
   * @throws IOException
   * @throws KeeperException
   * @throws InterruptedException
   */
  private synchronized byte[] getNodeData(String node, Stat stat, boolean retry)
      throws IOException, KeeperException, InterruptedException {
    int failures = 0;

    byte[] data = null;
    while (data == null) {
      initZK();
      try {
        data = zk.getData(node, watch, stat);
        if (data == null && retry) {
          // Failover is in progress
          // reset the failures
          failures = 0;
          DistributedAvatarFileSystem.LOG.info("Failover is in progress. Waiting");
          try {
            Thread.sleep(DistributedAvatarFileSystem.FAILOVER_CHECK_PERIOD);
          } catch (InterruptedException iex) {
            Thread.currentThread().interrupt();
          }
        } else {
          return data;
        }
      } catch (KeeperException kex) {
        if (KeeperException.Code.CONNECTIONLOSS == kex.code()
            && failures < ZK_CONNECTION_RETRIES) {
          failures++;
          // This means there was a failure connecting to zookeeper
          // we should retry since some nodes might be down.
          continue;
        }
        throw kex;
      } finally {
      }
    }
    return data;
  }

  public String getPrimaryAvatarAddress(String address, Stat stat, boolean retry)
    throws IOException, KeeperException, InterruptedException {
    String node = getRegistrationNode(address);
    byte[] data = getNodeData(node, stat, retry);
    if (data == null) {
      return null;
    }
    return new String(data, "UTF-8");
  }

  public String getPrimaryAvatarAddress(URI address, Stat stat, boolean retry)
    throws IOException, KeeperException, InterruptedException {
    return getPrimaryAvatarAddress(address.getAuthority(), stat, retry);
  }

  /**
   * Gets the {@link Stat} of the node. Will create and destroy connection if
   * the AvatarZooKeeperClient is not configured to set watchers
   *
   * @param node
   *          the path of zNode to get {@link Stat} for
   * @return {@link Stat} of the node
   * @throws IOException
   * @throws KeeperException
   * @throws InterruptedException
   */
  private synchronized Stat getNodeStats(String node) throws IOException,
      KeeperException, InterruptedException {
    int failures = 0;
    boolean gotStats = false;
    Stat res = null;
    while (!gotStats) {
      initZK();
      try {
        res = zk.exists(node, watch);
        // Since stats can be null we have to control the execution with a flag
        gotStats = true;
      } catch (KeeperException kex) {
        if (KeeperException.Code.CONNECTIONLOSS == kex.code()
            && failures < ZK_CONNECTION_RETRIES) {
          failures++;
          continue;
        }
        throw kex;
      } finally {
      }
    }
    return res;
  }

  public long getPrimaryRegistrationTime(URI address) throws IOException,
      KeeperException, InterruptedException {
    String node = getRegistrationNode(address.getAuthority());
    return getNodeStats(node).getMtime();
  }
  /*
   * ZNode address is formed by the logical name of the filesystem:
   * dfs.data.xxx.com:9000 will be represented by zNode
   * /prefix/dfs.data.xxx.com/9000 in ZooKeeper
   */
  private String getRegistrationNode(String clusterAddress) {
    return prefix + "/" + clusterAddress.replaceAll("[:]", "/").toLowerCase();
  }

  public synchronized void shutdown() throws InterruptedException {
    stopZK();
  }
}


text:
package com.qc4w.ilocker.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.qc4w.ilocker.R;
import com.qc4w.ilocker.config.ConfigManager;
import com.qc4w.ilocker.constant.Constants;
import com.qc4w.ilocker.db.WallpaperDAO;
import com.qc4w.ilocker.ui.CreatePasswordActivity;
import com.qc4w.ilocker.ui.view.EnterDigitalIndicator;
import com.qc4w.ilocker.ui.view.HeartPasswordView;
import com.qc4w.ilocker.util.MD5Utils;
import com.qc4w.ilocker.util.WallpaperUtils;

public class LPictureConfirmPasswordFragment extends FragmentBase  implements OnClickListener {

	private View mRootLayout;

	private ConfigManager mConfig;
	private WallpaperDAO mDao;

	private HeartPasswordView mPasswordView;
	private EnterDigitalIndicator indicator;

	private String password;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mConfig = ConfigManager.getInstance(getActivity());
		mDao = WallpaperDAO.getInstance(getActivity());
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if(mRootLayout != null) {
			((ViewGroup)mRootLayout.getParent()).removeAllViews();
			return mRootLayout;
		}

		mRootLayout = inflater.inflate(R.layout.fragment_lpicture_confirm_password, container, false);
		initUI();
		return mRootLayout;
	}

	private void initUI() {
		ImageView ivBackground = (ImageView) mRootLayout.findViewById(R.id.iv_background);
		WallpaperUtils.showWallpaper(getActivity(), ivBackground, mDao.getCurrent());

		mPasswordView = (HeartPasswordView) mRootLayout.findViewById(R.id.hpv_password_view);
		mPasswordView.setOnClickListener(this);

		int width = getResources().getDisplayMetrics().widthPixels / 6;
		RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(width * 5, width * 5);
		params.addRule(RelativeLayout.CENTER_IN_PARENT);
		params.addRule(RelativeLayout.BELOW, R.id.edi_indicator);
		mPasswordView.setLayoutParams(params);

		indicator = (EnterDigitalIndicator) mRootLayout.findViewById(R.id.edi_indicator);
	}

	@Override
	public void onClick(View v) {
		if(password == null) {
			password = "";
		}
		switch (v.getId()) {
			case R.id.hfibv_0:
				password += 0;
				break;
			case R.id.hfibv_1:
				password += 1;
				break;
			case R.id.hfibv_2:
				password += 2;
				break;
			case R.id.hfibv_3:
				password += 3;
				break;
			case R.id.hfibv_4:
				password += 4;
				break;
			case R.id.hfibv_5:
				password += 5;
				break;
			case R.id.hfibv_6:
				password += 6;
				break;
			case R.id.hfibv_7:
				password += 7;
				break;
			case R.id.hfibv_8:
				password += 8;
				break;
			case R.id.hfibv_9:
				password += 9;
				break;
			case R.id.btn_del:
				if(password.length() > 0) {
					password = password.substring(0, password.length() - 1);
				}
				break;
			default:
				break;
		}

		indicator.passwordChanged(password);
		mHandler.postDelayed(r, 200);
	}

	public void clearPassword() {
		password = "";
		indicator.passwordChanged(password);
	}

	private Runnable r = new Runnable() {
		@Override
		public void run() {
			if(password.length() > 4) {
				password = password.substring(0, 4);
			}
			if(password.length() == 4) {
				if(mConfig.getDigitalPassword().equals(MD5Utils.MD5(password))) {
					if(!getActivity().isFinishing()) {
						getActivity().finish();
						Intent intent = new Intent(getActivity(), CreatePasswordActivity.class);
						intent.putExtra(Constants.StringConstant.PARAMS_DATA, Constants.LockerMode.LOCK_MODE_LPICTURE);
						startActivity(intent);
					}
				} else {
					indicator.passwordWrong();
					password = "";
				}
			}
		}
	};

	private Handler mHandler = new Handler();

}

redpajama_set_name: RedPajamaGithub


text:
layout: post
title: 无题
categories: [life]
tags: [misc]
fullview: false
---
Talk not of wasted affection! affection never was wasted;

If it enrich not the heart of another, its waters, returning

Back to the springs, like the rain, shall fill them full of refershment:

That which the fountain sends forth returns again to the fountain.

Henry Wadsworth Longfellow,

Evangeline, 1847


text:
<?php

/**
 * Sitemap data helper
 *
 * @category   Mage
 * @package    Mage_Sitemap
 */
class Mage_Sitemap_Helper_Data extends Mage_Core_Helper_Abstract
{

}


text:
namespace BigIntegerLibrary
{

    /// <summary>
    /// The number's sign, where Positive also stands for the number zero.
    /// </summary>
    enum Sign { Positive, Negative };

}


text:
class Mailer < ActionMailer::Base
  default from: proc { Sugar.config.mail_sender || "no-reply@example.com" }

  def invite(invite, login_url)
    @invite    = invite
    @login_url = login_url
    mail(
      to:      @invite.email,
      subject: "#{@invite.user.realname_or_username} has invited you to " \
        "#{Sugar.config.forum_name}!"
    )
  end

  def new_user(user, login_url)
    @user      = user
    @login_url = login_url
    mail(
      to:      @user.email,
      subject: "Welcome to #{Sugar.config.forum_name}!"
    )
  end

  def password_reset(email, url)
    @url = url
    mail(
      to: email,
      subject: "Password reset for #{Sugar.config.forum_name}"
    )
  end

  def new_post(username, email, url, conversation)
    @username = username
    @url = url
    @conversation = conversation
    mail(
      to: email,
      subject: "New post in conversation at #{Sugar.config.forum_name}!"
    )
  end
end


text:
author: slowe
comments: true
date: 2016-08-09
layout: post
title: Open vSwitch Now a Linux Foundation Project
categories: News
tags:
- Linux
- OVS
- Networking
- OSS
---

News emerged today that [Open vSwitch (OVS)][link-1] has formally moved over to the [Linux Foundation][link-2]. This is something that has been discussed within the OVS community for a while, and I for one am glad to see it happen.

Why am I glad to see it happen? The project can finally shed itself of the (unfair) claims that the governance under Nicira (and later VMware) wasn't "open enough." These accusations persisted despite numerous indications otherwise. Thomas Graf, an OVS committer---who does not work for VMware, for the record---came to this conclusion in [his OVSCon 2015 presentation][link-3]:

>OVS is one of the most effective and well governed open source projects I've worked on.

Moving to the Linux Foundation allows OVS to continue to grow and flourish without continued accusations of unfair governance. The project intends to continue to use its existing governance model, in which technical leadership of the project is determined by the committers, and committer status is determined by your involvement in the project via code contributions and code reviews.

For more information, refer to [the official Linux Foundation press release][link-4].

[link-1]: http://openvswitch.org/
[link-2]: https://www.linuxfoundation.org/
[link-3]: http://openvswitch.org/support/ovscon2015/17/1255-graf.pdf
[link-4]: https://www.linuxfoundation.org/announcements/open-vswitch-joins-linux-foundation-open-networking-ecosystem


text:
// .NAME vtkXMLPRectilinearGridWriter - Write PVTK XML RectilinearGrid files.
// .SECTION Description
// vtkXMLPRectilinearGridWriter writes the PVTK XML RectilinearGrid
// file format.  One rectilinear grid input can be written into a
// parallel file format with any number of pieces spread across files.
// The standard extension for this writer's file format is "pvtr".
// This writer uses vtkXMLRectilinearGridWriter to write the
// individual piece files.

// .SECTION See Also
// vtkXMLRectilinearGridWriter

#ifndef vtkXMLPRectilinearGridWriter_h
#define vtkXMLPRectilinearGridWriter_h

#include "vtkIOParallelXMLModule.h" // For export macro
#include "vtkXMLPStructuredDataWriter.h"

class vtkRectilinearGrid;

class VTKIOPARALLELXML_EXPORT vtkXMLPRectilinearGridWriter : public vtkXMLPStructuredDataWriter
{
public:
  static vtkXMLPRectilinearGridWriter* New();
  vtkTypeMacro(vtkXMLPRectilinearGridWriter,vtkXMLPStructuredDataWriter);
  void PrintSelf(ostream& os, vtkIndent indent);

  //BTX
  // Description:
  // Get/Set the writer's input.
  vtkRectilinearGrid* GetInput();
  //ETX

  // Description:
  // Get the default file extension for files written by this writer.
  const char* GetDefaultFileExtension();

protected:
  vtkXMLPRectilinearGridWriter();
  ~vtkXMLPRectilinearGridWriter();

  // see algorithm for more info
  virtual int FillInputPortInformation(int port, vtkInformation* info);

  const char* GetDataSetName();
  vtkXMLStructuredDataWriter* CreateStructuredPieceWriter();
  void WritePData(vtkIndent indent);

private:
  vtkXMLPRectilinearGridWriter(const vtkXMLPRectilinearGridWriter&);  // Not implemented.
  void operator=(const vtkXMLPRectilinearGridWriter&);  // Not implemented.
};

#endif


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Hjerpbakk.DIPSBot.Configuration;
using SlackConnector;
using SlackConnector.Models;

namespace Hjerpbakk.DIPSBot
{
    public class SlackConnection
    {
        readonly string slackKey;
        readonly ISlackConnector connector;

        ISlackConnection connection;
        Func<SlackMessage, Task> messageReceived;

        public SlackConnection(ISlackConnector connector, IReadOnlyAppConfiguration configuration)
        {
            this.connector = connector ?? throw new ArgumentNullException(nameof(connector));
            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }

            if (string.IsNullOrEmpty(configuration.SlackAPIToken))
            {
                throw new ArgumentException(nameof(configuration.SlackAPIToken));
            }

            slackKey = configuration.SlackAPIToken;
        }

        /// <summary>
        ///     Connects the bot to Slack.
        /// </summary>
        /// <returns>No object or value is returned by this method when it completes.</returns>
        public async Task Connect(Func<SlackMessage, Task> messageReceived)
        {
            connection = await connector.Connect(slackKey);
            if (connection == null)
            {
                throw new ArgumentException("Could not connect to Slack.");
            }

            this.messageReceived = messageReceived;
            connection.OnMessageReceived += Connection_OnMessageReceived;
        }

        public async Task<ISlackConnection> GetConnection() {
            if (connection.IsConnected) {
                return connection;
            }

            await Close();
            await Connect(messageReceived);
            return connection;
        }

        // TODO: Abonner på flere events og track feil bedre?

        public async Task Close()
        {
            connection.OnMessageReceived -= Connection_OnMessageReceived;
            await connection.Close();
        }

        public async Task<SlackChatHub> GetDirectMessageChannel(string userId) =>
            await (await GetConnection()).JoinDirectMessageChannel(userId);

        public async Task SendMessage(BotMessage message) {
            await (await GetConnection()).Say(message);
        }

        public async Task<IEnumerable<SlackUser>> GetAllUsers()
            => await (await GetConnection()).GetUsers();

        public async Task<SlackUser> GetUser(string userId) =>
            (await GetConnection()).UserCache.ContainsKey(userId)
                ? (await GetConnection()).UserCache[userId]
                : (await GetAllUsers()).SingleOrDefault(u => u.Id == userId);

        async Task Connection_OnMessageReceived(SlackMessage message)
        {
            await messageReceived(message);
        }
    }
}


text:
<?php declare(strict_types=1);

namespace Malios\Ast2Zephir\Generator\Expr;

use Malios\Ast2Zephir\Enum\Expr;
use Malios\Ast2Zephir\Generator\Common\NodeToCode;
use Malios\Ast2Zephir\Generator\Generator;
use PhpParser\Node;

final class UnaryPlus extends Generator
{
    use NodeToCode;

    /**
     * {@inheritdoc}
     * @see Generator::canGenerateCode()
     */
    protected function canGenerateCode(Node $node): bool
    {
        return $node->getType() === Expr::UNARY_PLUS;
    }

    /**
     * {@inheritdoc}
     * @see Generator::doGenerateCode()
     * @param Node\Expr\UnaryPlus $node
     */
    protected function doGenerateCode($node): string
    {
        $code = '+' . $this->nodeToCode($node->expr, $this->finder);
        return $code;
    }
}


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

import static com.google.devtools.build.lib.skyframe.SkyFunctions.DIRECTORY_LISTING_STATE;
import static com.google.devtools.build.lib.vfs.FileStateKey.FILE_STATE;

import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.devtools.build.lib.actions.FileStateValue;
import com.google.devtools.build.lib.skyframe.ExternalFilesHelper.FileType;
import com.google.devtools.build.lib.util.io.TimestampGranularityMonitor;
import com.google.devtools.build.lib.vfs.Root;
import com.google.devtools.build.lib.vfs.RootedPath;
import com.google.devtools.build.lib.vfs.SyscallCache;
import com.google.devtools.build.skyframe.SkyKey;
import com.google.devtools.build.skyframe.SkyValue;
import java.io.IOException;
import java.util.EnumSet;
import java.util.Set;
import javax.annotation.Nullable;

/** Utilities for checking dirtiness of keys (mainly filesystem keys) in the graph. */
public class DirtinessCheckerUtils {
  private DirtinessCheckerUtils() {}

  private static class FileDirtinessChecker extends SkyValueDirtinessChecker {
    @Override
    public boolean applies(SkyKey skyKey) {
      return skyKey.functionName().equals(FILE_STATE);
    }

    @Override
    @Nullable
    public SkyValue createNewValue(
        SkyKey key, SyscallCache syscallCache, @Nullable TimestampGranularityMonitor tsgm) {
      try {
        return FileStateValue.create((RootedPath) key.argument(), syscallCache, tsgm);
      } catch (IOException e) {
        // TODO(bazel-team): An IOException indicates a failure to get a file digest or a symlink
        // target, not a missing file. Such a failure really shouldn't happen, so failing early
        // may be better here.
        return null;
      }
    }
  }

  private static class DirectoryDirtinessChecker extends SkyValueDirtinessChecker {
    @Override
    public boolean applies(SkyKey skyKey) {
      return skyKey.functionName().equals(DIRECTORY_LISTING_STATE);
    }

    @Override
    @Nullable
    public SkyValue createNewValue(
        SkyKey key, SyscallCache syscallCache, @Nullable TimestampGranularityMonitor tsgm) {
      RootedPath rootedPath = (RootedPath) key.argument();
      try {
        return DirectoryListingStateValue.create(syscallCache.readdir(rootedPath.asPath()));
      } catch (IOException e) {
        return null;
      }
    }
  }

  // Visible for testing, referenced only from tests and
  // SequencedSkyframeExecutor#invalidateFilesUnderPathForTestingImpl.
  static class BasicFilesystemDirtinessChecker extends SkyValueDirtinessChecker {
    private final FileDirtinessChecker fdc = new FileDirtinessChecker();
    private final DirectoryDirtinessChecker ddc = new DirectoryDirtinessChecker();
    private final UnionDirtinessChecker checker =
        new UnionDirtinessChecker(ImmutableList.of(fdc, ddc));

    @Override
    public boolean applies(SkyKey skyKey) {
      return fdc.applies(skyKey) || ddc.applies(skyKey);
    }

    @Override
    @Nullable
    public SkyValue createNewValue(
        SkyKey key, SyscallCache syscallCache, @Nullable TimestampGranularityMonitor tsgm) {
      return checker.createNewValue(key, syscallCache, tsgm);
    }
  }

  static final class MissingDiffDirtinessChecker extends BasicFilesystemDirtinessChecker {
    private final Set<Root> missingDiffPackageRoots;

    MissingDiffDirtinessChecker(Set<Root> missingDiffPackageRoots) {
      this.missingDiffPackageRoots = missingDiffPackageRoots;
    }

    @Override
    public boolean applies(SkyKey key) {
      return super.applies(key)
          && missingDiffPackageRoots.contains(((RootedPath) key.argument()).getRoot());
    }
  }

  /**
   * Serves for tracking whether there are external and output files {@see ExternalFilesKnowledge}.
   * Filtering of files, for which the new values should not be injected into evaluator, is done in
   * SequencedSkyframeExecutor.handleChangedFiles().
   */
  static final class ExternalDirtinessChecker extends BasicFilesystemDirtinessChecker {
    private final ExternalFilesHelper externalFilesHelper;
    private final EnumSet<FileType> fileTypesToCheck;

    ExternalDirtinessChecker(ExternalFilesHelper externalFilesHelper,
        EnumSet<FileType> fileTypesToCheck) {
      this.externalFilesHelper = externalFilesHelper;
      this.fileTypesToCheck = fileTypesToCheck;
    }

    @Override
    public boolean applies(SkyKey key) {
      if (!super.applies(key)) {
        return false;
      }
      FileType fileType = externalFilesHelper.getAndNoteFileType((RootedPath) key.argument());
      return fileTypesToCheck.contains(fileType);
    }

    @Nullable
    @Override
    public SkyValue createNewValue(
        SkyKey key, SyscallCache syscallCache, @Nullable TimestampGranularityMonitor tsgm) {
      throw new UnsupportedOperationException();
    }

    @Override
    public SkyValueDirtinessChecker.DirtyResult check(
        SkyKey skyKey,
        SkyValue oldValue,
        SyscallCache syscallCache,
        @Nullable TimestampGranularityMonitor tsgm) {
      FileType fileType = externalFilesHelper.getAndNoteFileType((RootedPath) skyKey.argument());
      boolean cacheable = isCacheableType(fileType);
      SkyValue newValue =
          super.createNewValue(skyKey, cacheable ? syscallCache : SyscallCache.NO_CACHE, tsgm);
      if (Objects.equal(newValue, oldValue)) {
        return SkyValueDirtinessChecker.DirtyResult.notDirty();
      }
      if (cacheable) {
        return SkyValueDirtinessChecker.DirtyResult.dirtyWithNewValue(newValue);
      }
      // Files under output_base/external have a dependency on the WORKSPACE file, so we don't add
      // a new SkyValue to the graph yet because it might change once the WORKSPACE file has been
      // parsed. Similarly, output files might change during execution.
      return SkyValueDirtinessChecker.DirtyResult.dirty();
    }

    private static boolean isCacheableType(FileType fileType) {
      switch (fileType) {
        case INTERNAL:
        case EXTERNAL:
        case BUNDLED:
          return true;
        case EXTERNAL_REPO:
        case OUTPUT:
          return false;
      }
      throw new AssertionError("Unknown type " + fileType);
    }
  }

  /** {@link SkyValueDirtinessChecker} that encompasses a union of other dirtiness checkers. */
  static final class UnionDirtinessChecker extends SkyValueDirtinessChecker {
    private final Iterable<SkyValueDirtinessChecker> dirtinessCheckers;

    UnionDirtinessChecker(Iterable<SkyValueDirtinessChecker> dirtinessCheckers) {
      this.dirtinessCheckers = dirtinessCheckers;
    }

    @Nullable
    private SkyValueDirtinessChecker getChecker(SkyKey key) {
      for (SkyValueDirtinessChecker dirtinessChecker : dirtinessCheckers) {
        if (dirtinessChecker.applies(key)) {
          return dirtinessChecker;
        }
      }
      return null;
    }

    @Override
    public boolean applies(SkyKey key) {
      return getChecker(key) != null;
    }

    @Override
    @Nullable
    public SkyValue createNewValue(
        SkyKey key, SyscallCache syscallCache, @Nullable TimestampGranularityMonitor tsgm) {
      return Preconditions.checkNotNull(getChecker(key), key)
          .createNewValue(key, syscallCache, tsgm);
    }

    @Override
    public DirtyResult check(
        SkyKey key,
        @Nullable SkyValue oldValue,
        SyscallCache syscallCache,
        @Nullable TimestampGranularityMonitor tsgm) {
      return Preconditions.checkNotNull(getChecker(key), key)
          .check(key, oldValue, syscallCache, tsgm);
    }
  }
}


text:
require 'forwardable'
require 'webmock'

WebMock.disable! # デフォルトでブロックしてしまうので排除

module SphyGmo::Stub
  class << self
    extend Forwardable

    def modes
      @modes ||= [:disable]
    end

    def mode
      modes[-1]
    end

    def mode=(mode)
      update_stubbing(modes.last, mode)

      modes[-1] = mode
    end

    def stub(mode, &block)
      push(mode)
      ret = yield
      pop
      ret
    end

    def push(mode)
      update_stubbing(modes.last, mode)
      modes.push(mode)
    end

    def pop
      ret = modes.pop
      update_stubbing(ret, modes.last)
      ret
    end

    def update_stubbing(prev, mode)
      if prev != mode
        case mode
        when :enable
          enable_stubbing
        when :disable
          disable_stubbing
        else
          raise "stub mode must be :enable or :disable"
        end
      end
    end

    def enable_stubbing
      WebMock.enable!

      WebMock.stub_request(:any, SphyGmo.configuration.host)

      WebMock.stub_request(
        :post, "https://#{SphyGmo.configuration.host}/payment/SearchMember.idPass")
        .to_return(status: 200, body: '', headers: {})
      WebMock.stub_request(
        :post, "https://#{SphyGmo.configuration.host}/payment/SaveCard.idPass")
        .to_return(status: 200, body: '', headers: {})
    end

    def disable_stubbing
      WebMock.reset!
      WebMock.disable!
    end

    def stub_entry_tran(success: )
      target_url = "https://#{SphyGmo.configuration.host}/payment/EntryTran.idPass"
      if success
        body = Rack::Utils.build_nested_query(AccessID: rand(0..10000), AccessPass: rand(0..10000))
      else
        err = SphyGmo::ErrorInfo.all.values.sample
        body = Rack::Utils.build_nested_query(ErrCode: err.code ,ErrInfo: err.info)
      end
      WebMock.stub_request(:post, target_url).to_return(status: 200, body: body)
    end

    def stub_exec_tran(success: )
      target_url = "https://#{SphyGmo.configuration.host}/payment/ExecTran.idPass"
      if success
        body = Rack::Utils.build_nested_query({})
      else
        err = SphyGmo::ErrorInfo.all.values.sample
        body = Rack::Utils.build_nested_query(ErrCode: err.code ,ErrInfo: err.info)
      end
      WebMock.stub_request(:post, target_url).to_return(status: 200, body: body)
    end
  end
end


text:
package java.nio;

import libcore.io.SizeOf;
import libcore.io.Memory;

/**
 * ByteArrayBuffer implements byte[]-backed ByteBuffers.
 */
final class ByteArrayBuffer extends ByteBuffer {

  /**
   * These fields are non-private for NioUtils.unsafeArray.
   */
  final byte[] backingArray;
  final int arrayOffset;

  private final boolean isReadOnly;

  ByteArrayBuffer(byte[] backingArray) {
    this(backingArray.length, backingArray, 0, false);
  }

  private ByteArrayBuffer(int capacity, byte[] backingArray, int arrayOffset, boolean isReadOnly) {
    super(capacity, 0);
    this.backingArray = backingArray;
    this.arrayOffset = arrayOffset;
    this.isReadOnly = isReadOnly;
    if (arrayOffset + capacity > backingArray.length) {
      throw new IndexOutOfBoundsException("backingArray.length=" + backingArray.length +
                                              ", capacity=" + capacity + ", arrayOffset=" + arrayOffset);
    }
  }

  private static ByteArrayBuffer copy(ByteArrayBuffer other, int markOfOther, boolean isReadOnly) {
    ByteArrayBuffer buf = new ByteArrayBuffer(other.capacity(), other.backingArray, other.arrayOffset, isReadOnly);
    buf.limit = other.limit;
    buf.position = other.position();
    buf.mark = markOfOther;
    return buf;
  }

  @Override public ByteBuffer asReadOnlyBuffer() {
    return copy(this, mark, true);
  }

  @Override public ByteBuffer compact() {
    if (isReadOnly) {
      throw new ReadOnlyBufferException();
    }
    System.arraycopy(backingArray, position + arrayOffset, backingArray, arrayOffset, remaining());
    position = limit - position;
    limit = capacity;
    mark = UNSET_MARK;
    return this;
  }

  @Override public ByteBuffer duplicate() {
    return copy(this, mark, isReadOnly);
  }

  @Override public ByteBuffer slice() {
    return new ByteArrayBuffer(remaining(), backingArray, arrayOffset + position, isReadOnly);
  }

  @Override public boolean isReadOnly() {
    return isReadOnly;
  }

  @Override byte[] protectedArray() {
    if (isReadOnly) {
      throw new ReadOnlyBufferException();
    }
    return backingArray;
  }

  @Override int protectedArrayOffset() {
    if (isReadOnly) {
      throw new ReadOnlyBufferException();
    }
    return arrayOffset;
  }

  @Override boolean protectedHasArray() {
    if (isReadOnly) {
      return false;
    }
    return true;
  }

  @Override public final ByteBuffer get(byte[] dst, int dstOffset, int byteCount) {
    checkGetBounds(1, dst.length, dstOffset, byteCount);
    System.arraycopy(backingArray, arrayOffset + position, dst, dstOffset, byteCount);
    position += byteCount;
    return this;
  }

  final void get(char[] dst, int dstOffset, int charCount) {
    int byteCount = checkGetBounds(SizeOf.CHAR, dst.length, dstOffset, charCount);
    Memory.unsafeBulkGet(dst, dstOffset, byteCount, backingArray, arrayOffset + position, SizeOf.CHAR, order.needsSwap);
    position += byteCount;
  }

  final void get(double[] dst, int dstOffset, int doubleCount) {
    int byteCount = checkGetBounds(SizeOf.DOUBLE, dst.length, dstOffset, doubleCount);
    Memory.unsafeBulkGet(dst, dstOffset, byteCount, backingArray, arrayOffset + position, SizeOf.DOUBLE, order.needsSwap);
    position += byteCount;
  }

  final void get(float[] dst, int dstOffset, int floatCount) {
    int byteCount = checkGetBounds(SizeOf.FLOAT, dst.length, dstOffset, floatCount);
    Memory.unsafeBulkGet(dst, dstOffset, byteCount, backingArray, arrayOffset + position, SizeOf.FLOAT, order.needsSwap);
    position += byteCount;
  }

  final void get(int[] dst, int dstOffset, int intCount) {
    int byteCount = checkGetBounds(SizeOf.INT, dst.length, dstOffset, intCount);
    Memory.unsafeBulkGet(dst, dstOffset, byteCount, backingArray, arrayOffset + position, SizeOf.INT, order.needsSwap);
    position += byteCount;
  }

  final void get(long[] dst, int dstOffset, int longCount) {
    int byteCount = checkGetBounds(SizeOf.LONG, dst.length, dstOffset, longCount);
    Memory.unsafeBulkGet(dst, dstOffset, byteCount, backingArray, arrayOffset + position, SizeOf.LONG, order.needsSwap);
    position += byteCount;
  }

  final void get(short[] dst, int dstOffset, int shortCount) {
    int byteCount = checkGetBounds(SizeOf.SHORT, dst.length, dstOffset, shortCount);
    Memory.unsafeBulkGet(dst, dstOffset, byteCount, backingArray, arrayOffset + position, SizeOf.SHORT, order.needsSwap);
    position += byteCount;
  }

  @Override public final byte get() {
    if (position == limit) {
      throw new BufferUnderflowException();
    }
    return backingArray[arrayOffset + position++];
  }

  @Override public final byte get(int index) {
    checkIndex(index);
    return backingArray[arrayOffset + index];
  }

  @Override public final char getChar() {
    int newPosition = position + SizeOf.CHAR;
    if (newPosition > limit) {
      throw new BufferUnderflowException();
    }
    char result = (char) Memory.peekShort(backingArray, arrayOffset + position, order);
    position = newPosition;
    return result;
  }

  @Override public final char getChar(int index) {
    checkIndex(index, SizeOf.CHAR);
    return (char) Memory.peekShort(backingArray, arrayOffset + index, order);
  }

  @Override public final double getDouble() {
    return Double.longBitsToDouble(getLong());
  }

  @Override public final double getDouble(int index) {
    return Double.longBitsToDouble(getLong(index));
  }

  @Override public final float getFloat() {
    return Float.intBitsToFloat(getInt());
  }

  @Override public final float getFloat(int index) {
    return Float.intBitsToFloat(getInt(index));
  }

  @Override public final int getInt() {
    int newPosition = position + SizeOf.INT;
    if (newPosition > limit) {
      throw new BufferUnderflowException();
    }
    int result = Memory.peekInt(backingArray, arrayOffset + position, order);
    position = newPosition;
    return result;
  }

  @Override public final int getInt(int index) {
    checkIndex(index, SizeOf.INT);
    return Memory.peekInt(backingArray, arrayOffset + index, order);
  }

  @Override public final long getLong() {
    int newPosition = position + SizeOf.LONG;
    if (newPosition > limit) {
      throw new BufferUnderflowException();
    }
    long result = Memory.peekLong(backingArray, arrayOffset + position, order);
    position = newPosition;
    return result;
  }

  @Override public final long getLong(int index) {
    checkIndex(index, SizeOf.LONG);
    return Memory.peekLong(backingArray, arrayOffset + index, order);
  }

  @Override public final short getShort() {
    int newPosition = position + SizeOf.SHORT;
    if (newPosition > limit) {
      throw new BufferUnderflowException();
    }
    short result = Memory.peekShort(backingArray, arrayOffset + position, order);
    position = newPosition;
    return result;
  }

  @Override public final short getShort(int index) {
    checkIndex(index, SizeOf.SHORT);
    return Memory.peekShort(backingArray, arrayOffset + index, order);
  }

  @Override public final boolean isDirect() {
    return false;
  }

  @Override public ByteBuffer put(byte b) {
    if (isReadOnly) {
      throw new ReadOnlyBufferException();
    }
    if (position == limit) {
      throw new BufferOverflowException();
    }
    backingArray[arrayOffset + position++] = b;
    return this;
  }

  @Override public ByteBuffer put(int index, byte b) {
    if (isReadOnly) {
      throw new ReadOnlyBufferException();
    }
    checkIndex(index);
    backingArray[arrayOffset + index] = b;
    return this;
  }

  @Override public ByteBuffer put(byte[] src, int srcOffset, int byteCount) {
    if (isReadOnly) {
      throw new ReadOnlyBufferException();
    }
    checkPutBounds(1, src.length, srcOffset, byteCount);
    System.arraycopy(src, srcOffset, backingArray, arrayOffset + position, byteCount);
    position += byteCount;
    return this;
  }

  final void put(char[] src, int srcOffset, int charCount) {
    int byteCount = checkPutBounds(SizeOf.CHAR, src.length, srcOffset, charCount);
    Memory.unsafeBulkPut(backingArray, arrayOffset + position, byteCount, src, srcOffset, SizeOf.CHAR, order.needsSwap);
    position += byteCount;
  }

  final void put(double[] src, int srcOffset, int doubleCount) {
    int byteCount = checkPutBounds(SizeOf.DOUBLE, src.length, srcOffset, doubleCount);
    Memory.unsafeBulkPut(backingArray, arrayOffset + position, byteCount, src, srcOffset, SizeOf.DOUBLE, order.needsSwap);
    position += byteCount;
  }

  final void put(float[] src, int srcOffset, int floatCount) {
    int byteCount = checkPutBounds(SizeOf.FLOAT, src.length, srcOffset, floatCount);
    Memory.unsafeBulkPut(backingArray, arrayOffset + position, byteCount, src, srcOffset, SizeOf.FLOAT, order.needsSwap);
    position += byteCount;
  }

  final void put(int[] src, int srcOffset, int intCount) {
    int byteCount = checkPutBounds(SizeOf.INT, src.length, srcOffset, intCount);
    Memory.unsafeBulkPut(backingArray, arrayOffset + position, byteCount, src, srcOffset, SizeOf.INT, order.needsSwap);
    position += byteCount;
  }

  final void put(long[] src, int srcOffset, int longCount) {
    int byteCount = checkPutBounds(SizeOf.LONG, src.length, srcOffset, longCount);
    Memory.unsafeBulkPut(backingArray, arrayOffset + position, byteCount, src, srcOffset, SizeOf.LONG, order.needsSwap);
    position += byteCount;
  }

  final void put(short[] src, int srcOffset, int shortCount) {
    int byteCount = checkPutBounds(SizeOf.SHORT, src.length, srcOffset, shortCount);
    Memory.unsafeBulkPut(backingArray, arrayOffset + position, byteCount, src, srcOffset, SizeOf.SHORT, order.needsSwap);
    position += byteCount;
  }

  @Override public ByteBuffer putChar(int index, char value) {
    if (isReadOnly) {
      throw new ReadOnlyBufferException();
    }
    checkIndex(index, SizeOf.CHAR);
    Memory.pokeShort(backingArray, arrayOffset + index, (short) value, order);
    return this;
  }

  @Override public ByteBuffer putChar(char value) {
    if (isReadOnly) {
      throw new ReadOnlyBufferException();
    }
    int newPosition = position + SizeOf.CHAR;
    if (newPosition > limit) {
      throw new BufferOverflowException();
    }
    Memory.pokeShort(backingArray, arrayOffset + position, (short) value, order);
    position = newPosition;
    return this;
  }

  @Override public ByteBuffer putDouble(double value) {
    return putLong(Double.doubleToRawLongBits(value));
  }

  @Override public ByteBuffer putDouble(int index, double value) {
    return putLong(index, Double.doubleToRawLongBits(value));
  }

  @Override public ByteBuffer putFloat(float value) {
    return putInt(Float.floatToRawIntBits(value));
  }

  @Override public ByteBuffer putFloat(int index, float value) {
    return putInt(index, Float.floatToRawIntBits(value));
  }

  @Override public ByteBuffer putInt(int value) {
    if (isReadOnly) {
      throw new ReadOnlyBufferException();
    }
    int newPosition = position + SizeOf.INT;
    if (newPosition > limit) {
      throw new BufferOverflowException();
    }
    Memory.pokeInt(backingArray, arrayOffset + position, value, order);
    position = newPosition;
    return this;
  }

  @Override public ByteBuffer putInt(int index, int value) {
    if (isReadOnly) {
      throw new ReadOnlyBufferException();
    }
    checkIndex(index, SizeOf.INT);
    Memory.pokeInt(backingArray, arrayOffset + index, value, order);
    return this;
  }

  @Override public ByteBuffer putLong(int index, long value) {
    if (isReadOnly) {
      throw new ReadOnlyBufferException();
    }
    checkIndex(index, SizeOf.LONG);
    Memory.pokeLong(backingArray, arrayOffset + index, value, order);
    return this;
  }

  @Override public ByteBuffer putLong(long value) {
    if (isReadOnly) {
      throw new ReadOnlyBufferException();
    }
    int newPosition = position + SizeOf.LONG;
    if (newPosition > limit) {
      throw new BufferOverflowException();
    }
    Memory.pokeLong(backingArray, arrayOffset + position, value, order);
    position = newPosition;
    return this;
  }

  @Override public ByteBuffer putShort(int index, short value) {
    if (isReadOnly) {
      throw new ReadOnlyBufferException();
    }
    checkIndex(index, SizeOf.SHORT);
    Memory.pokeShort(backingArray, arrayOffset + index, value, order);
    return this;
  }

  @Override public ByteBuffer putShort(short value) {
    if (isReadOnly) {
      throw new ReadOnlyBufferException();
    }
    int newPosition = position + SizeOf.SHORT;
    if (newPosition > limit) {
      throw new BufferOverflowException();
    }
    Memory.pokeShort(backingArray, arrayOffset + position, value, order);
    position = newPosition;
    return this;
  }

  @Override public final CharBuffer asCharBuffer() {
    return ByteBufferAsCharBuffer.asCharBuffer(this);
  }

  @Override public final DoubleBuffer asDoubleBuffer() {
    return ByteBufferAsDoubleBuffer.asDoubleBuffer(this);
  }

  @Override public final FloatBuffer asFloatBuffer() {
    return ByteBufferAsFloatBuffer.asFloatBuffer(this);
  }

  @Override public final IntBuffer asIntBuffer() {
    return ByteBufferAsIntBuffer.asIntBuffer(this);
  }

  @Override public final LongBuffer asLongBuffer() {
    return ByteBufferAsLongBuffer.asLongBuffer(this);
  }

  @Override public final ShortBuffer asShortBuffer() {
    return ByteBufferAsShortBuffer.asShortBuffer(this);
  }
}


text:
<!DOCTYPE HTML>

<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,minimum-scale=1,user-scalable=no" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<title>Slider Tests</title>
<link href="css/test.css" rel="stylesheet"/>

View1

				0
				<input id="view1-Slider1" data-dojo-type="dojox.mobile.Slider" name="sh1" value="31.4" min="0" max="100" step="0.1" type="range" style="width:150px;">
				100

				0

				100

				0
				<input id="view1-Slider3" name="sh3" value="31.4" min="0" max="100" step="0.1" type="range" style="width:150px;">
				100

View2

				0
				<input id="view2-Slider1" data-dojo-type="dojox.mobile.Slider" name="sh1" value="31.4" min="0" max="100" step="0.1" type="range" style="width:150px;">
				100

				0

				100

				0
				<input id="view2-Slider3" name="sh3" value="31.4" min="0" max="100" step="0.1" type="range" style="width:150px;">
				100


text:
local Modifier = _G.Freya:GetComponent "Crystal/Modifier"

local function ReadOnly(t, k, v)
  return error(string.format(
    "Readonly method: Unable to set %s to %s for [%s]",
    tostring(k),
    tostring(v),
    tostring(t)
  ), 2)
end

local function Construct(data, obj, sym, mt)
  local nom = data.Name;
  local f = data.Properties[1];
  if not f then return end;
  sym[nom] = function(o, ...)
    if o == obj then
      o = sym
    end
    return f(o, ...);
  end
  mt.__members[nom] = false;
  mt.__set[nom] = ReadOnly;
end

return Modifier.CreateBase(Construct)


text:
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace Elasticsearch.Net
{
	public class ElasticsearchDefaultSerializer : IElasticsearchSerializer
	{
		public static readonly ElasticsearchDefaultSerializer Instance = new ElasticsearchDefaultSerializer();
		private static readonly ElasticsearchNetJsonStrategy Strategy = new ElasticsearchNetJsonStrategy();

		public T Deserialize<T>(Stream stream)
		{
			if (stream == null) return default(T);

			using (var ms = new MemoryStream())
			using(stream)
			{
				stream.CopyTo(ms);
				byte[] buffer = ms.ToArray();
				if (buffer.Length <= 1)
					return default(T);
				return SimpleJson.DeserializeObject<T>(buffer.Utf8String(), ElasticsearchDefaultSerializer.Strategy);
			}
		}

		public async Task<T> DeserializeAsync<T>(Stream stream, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (stream == null)
				return default(T);

			using (var ms = new MemoryStream())
			using (stream)
			{
				await stream.CopyToAsync(ms, 8096, cancellationToken);
				var buffer = ms.ToArray();
				if (buffer.Length <= 1)
					return default(T);
				var r = SimpleJson.DeserializeObject<T>(buffer.Utf8String(), ElasticsearchDefaultSerializer.Strategy);
				return r;
			}
		}

		public void Serialize(object data, Stream writableStream, SerializationFormatting formatting = SerializationFormatting.Indented)
		{
			var serialized = SimpleJson.SerializeObject(data);
			if (formatting == SerializationFormatting.None)
				serialized = RemoveNewLinesAndTabs(serialized);
			using (var ms = new MemoryStream(serialized.Utf8Bytes()))
			{
				ms.CopyTo(writableStream);
			}
		}

		public static string RemoveNewLinesAndTabs(string input)
		{
			return new string(input
				.Where(c => c != '\r' && c != '\n')
				.ToArray());
		}
	}
}


text:
<?php

namespace Oro\Bundle\EntityBundle\Tests\Unit\ORM;

use Doctrine\ORM\Internal\Hydration\IterableResult;
use Oro\Bundle\EntityBundle\ORM\SingleObjectIterableResultDecorator;

class SingleObjectIterableResultDecoratorTest extends \PHPUnit_Framework_TestCase
{
    /** @var IterableResult|\PHPUnit_Framework_MockObject_MockObject */
    protected $iterableResult;

    /** @var SingleObjectIterableResultDecorator */
    protected $iterableResultDecorator;

    public function setUp()
    {
        $this->iterableResult = $this->getMockBuilder('Doctrine\ORM\Internal\Hydration\IterableResult')
            ->disableOriginalConstructor()
            ->getMock();

        $this->iterableResultDecorator = new SingleObjectIterableResultDecorator($this->iterableResult);
    }

    public function testRewind()
    {
        $this->iterableResult
            ->expects($this->once())
            ->method('rewind');

        $this->iterableResultDecorator->rewind();
    }

    public function testNextWhenArrayIsReturned()
    {
        $sampleObject = new \stdClass();

        $this->iterableResult
            ->expects($this->once())
            ->method('next')
            ->willReturn([$sampleObject]);

        $this->assertEquals($sampleObject, $this->iterableResultDecorator->next());
    }

    public function testNextWhenNotArrayIsReturned()
    {
        $this->iterableResult
            ->expects($this->once())
            ->method('next')
            ->willReturn(false);

        $this->assertEquals(false, $this->iterableResultDecorator->next());
    }

    public function testCurrent()
    {
        $sampleObject = new \stdClass();

        $this->iterableResult
            ->expects($this->once())
            ->method('current')
            ->willReturn([$sampleObject]);

        $this->assertEquals($sampleObject, $this->iterableResultDecorator->current());
    }

    public function testKey()
    {
        $this->iterableResult
            ->expects($this->once())
            ->method('key')
            ->willReturn('sample_key');

        $this->assertEquals('sample_key', $this->iterableResultDecorator->key());
    }

    public function testValid()
    {
        $this->iterableResult
            ->expects($this->once())
            ->method('valid')
            ->willReturn(true);

        $this->assertEquals(true, $this->iterableResultDecorator->valid());
    }
}


text:
/*
Two positive integers N and M are given. Integer N represents the number of chocolates arranged in a circle, numbered from 0 to N   1.
You start to eat the chocolates. After eating a chocolate you leave only a wrapper.
You begin with eating chocolate number 0. Then you omit the next M   1 chocolates or wrappers on the circle, and eat the following one.
More precisely, if you ate chocolate number X, then you will next eat the chocolate with number (X + M) modulo N (remainder of division).
You stop eating when you encounter an empty wrapper.
For example, given integers N = 10 and M = 4. You will eat the following chocolates: 0, 4, 8, 2, 6.
The goal is to count the number of chocolates that you will eat, following the above rules.
Write a function:
int solution(int N, int M);
that, given two positive integers N and M, returns the number of chocolates that you will eat.
For example, given integers N = 10 and M = 4. the function should return 5, as explained above.
Assume that:
N and M are integers within the range [1..1,000,000,000].
Complexity:
expected worst-case time complexity is O(log(N+M));
expected worst-case space complexity is O(1).

*/

#include <fstream>
#include <iostream>
#include <sstream>
//-----------------------------------------------------------------------------------
#include <vector>
#include <algorithm>
#include <stdlib.h>
using namespace std;

int gcd(int a, int b) {
  if(a < b) return gcd(b, a);
  if(a % b == 0) return b;
  return gcd(b, a % b );
}

int solution(int N, int M) {
  if (M == 1) return N;
  return (int) N/gcd(M,N);
}

//-----------------------------------------------------------------------------------

void print_v(vector<int> &A){
  int N = A.size();
  cout << "Size: " << N << endl;
  for(int i=0;i<N;i++){
    cout << A[i] << " ";
  }
  cout << endl;
}

int main(int argc,char *argv[]){
  if(argc < 2) {
    printf("You must provide at least one argument\n");
    exit(0);
  }
  string line;
  ifstream file;
  file.open(argv[1]);
  while(getline(file, line)){
    int i;
    vector<int> P;
    istringstream issP(line);
    while (issP >> i)
      P.push_back(i);
    print_v(P);

    cout << "solution: " << solution(P[0], P[1]) << endl;

  }
  return 0;
}


text:
namespace Microsoft.Azure.Management.Sql.Models
{
    using Microsoft.Rest;
    using Microsoft.Rest.Serialization;
    using Newtonsoft.Json;
    using System.Linq;

    /// <summary>
    /// A LongTermRetentionBackup operation result resource.
    /// </summary>
    [Rest.Serialization.JsonTransformation]
    public partial class LongTermRetentionBackupOperationResult : ProxyResource
    {
        /// <summary>
        /// Initializes a new instance of the
        /// LongTermRetentionBackupOperationResult class.
        /// </summary>
        public LongTermRetentionBackupOperationResult()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the
        /// LongTermRetentionBackupOperationResult class.
        /// </summary>
        /// <param name="id">Resource ID.</param>
        /// <param name="name">Resource name.</param>
        /// <param name="type">Resource type.</param>
        /// <param name="requestId">Request Id.</param>
        /// <param name="operationType">Operation type.</param>
        /// <param name="fromBackupResourceId">Source backup resource
        /// id</param>
        /// <param name="toBackupResourceId">Target backup resource id</param>
        /// <param name="targetBackupStorageRedundancy">The storage redundancy
        /// type of the copied backup. Possible values include: 'Geo', 'Local',
        /// 'Zone', 'GeoZone'</param>
        /// <param name="status">Operation status</param>
        /// <param name="message">Progress message</param>
        public LongTermRetentionBackupOperationResult(string id = default(string), string name = default(string), string type = default(string), System.Guid? requestId = default(System.Guid?), string operationType = default(string), string fromBackupResourceId = default(string), string toBackupResourceId = default(string), string targetBackupStorageRedundancy = default(string), string status = default(string), string message = default(string))
            : base(id, name, type)
        {
            RequestId = requestId;
            OperationType = operationType;
            FromBackupResourceId = fromBackupResourceId;
            ToBackupResourceId = toBackupResourceId;
            TargetBackupStorageRedundancy = targetBackupStorageRedundancy;
            Status = status;
            Message = message;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets request Id.
        /// </summary>
        [JsonProperty(PropertyName = "properties.requestId")]
        public System.Guid? RequestId { get; private set; }

        /// <summary>
        /// Gets operation type.
        /// </summary>
        [JsonProperty(PropertyName = "properties.operationType")]
        public string OperationType { get; private set; }

        /// <summary>
        /// Gets source backup resource id
        /// </summary>
        [JsonProperty(PropertyName = "properties.fromBackupResourceId")]
        public string FromBackupResourceId { get; private set; }

        /// <summary>
        /// Gets target backup resource id
        /// </summary>
        [JsonProperty(PropertyName = "properties.toBackupResourceId")]
        public string ToBackupResourceId { get; private set; }

        /// <summary>
        /// Gets the storage redundancy type of the copied backup. Possible
        /// values include: 'Geo', 'Local', 'Zone', 'GeoZone'
        /// </summary>
        [JsonProperty(PropertyName = "properties.targetBackupStorageRedundancy")]
        public string TargetBackupStorageRedundancy { get; private set; }

        /// <summary>
        /// Gets operation status
        /// </summary>
        [JsonProperty(PropertyName = "properties.status")]
        public string Status { get; private set; }

        /// <summary>
        /// Gets progress message
        /// </summary>
        [JsonProperty(PropertyName = "properties.message")]
        public string Message { get; private set; }

    }
}


text:
<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="description" content="Jasmine tests spec runner">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Jasmine tests spec runner</title>
        <link rel="stylesheet" href="bower_components/jasmine/lib/jasmine-core/jasmine.css">
    </head>
    <body>

        <script src="bower_components/jasmine/lib/jasmine-core/jasmine.js"></script>
        <script src="bower_components/jasmine/lib/jasmine-core/jasmine-html.js"></script>
        <script src="bower_components/jasmine/lib/jasmine-core/boot.js"></script>

        <script src="src/tightly.js"></script>

        <script src="spec/tightly-spec.js"></script>
    </body>
</html>


text:
/**
 * Created by aresn on 16/6/20.
 */
import Vue from 'vue';
import VueRouter from 'vue-router';
import App from './app.vue';
import testIndex from '../src/index';
// import locale from '../src/locale/lang/en-US';
import locale from '../src/locale/lang/zh-CN';

Vue.use(VueRouter);
Vue.use(testIndex, { locale });

// 开启debug模式
Vue.config.debug = true;

// 路由配置
const router = new VueRouter({
    routes: [
        {
            path: '/datagridtest',
            component: require('./routers/datagrid_test.vue')
        }
    ]
});

new Vue({
    el: '#app',
    router: router,
    render: h => h(App)
});


text:
// .NAME vtkGenericCell - provides thread-safe access to cells
// .SECTION Description
// vtkGenericCell is a class that provides access to concrete types of cells.
// It's main purpose is to allow thread-safe access to cells, supporting
// the vtkDataSet::GetCell(vtkGenericCell *) method. vtkGenericCell acts
// like any type of cell, it just dereferences an internal representation.
// The SetCellType() methods use \#define constants; these are defined in
// the file vtkCellType.h.

// .SECTION See Also
// vtkCell vtkDataSet

#ifndef __vtkGenericCell_h
#define __vtkGenericCell_h

#include "vtkCommonDataModelExport.h" // For export macro
#include "vtkCell.h"

class VTKCOMMONDATAMODEL_EXPORT vtkGenericCell : public vtkCell
{
public:
  // Description:
  // Create handle to any type of cell; by default a vtkEmptyCell.
  static vtkGenericCell *New();

  vtkTypeMacro(vtkGenericCell,vtkCell);
  void PrintSelf(ostream& os, vtkIndent indent);

  // Description:
  // See the vtkCell API for descriptions of these methods.
  void ShallowCopy(vtkCell *c);
  void DeepCopy(vtkCell *c);
  int GetCellType();
  int GetCellDimension();
  int IsLinear();
  int RequiresInitialization();
  void Initialize();
  int RequiresExplicitFaceRepresentation();
  void SetFaces(vtkIdType *faces);
  vtkIdType *GetFaces();
  int GetNumberOfEdges();
  int GetNumberOfFaces();
  vtkCell *GetEdge(int edgeId);
  vtkCell *GetFace(int faceId);
  int CellBoundary(int subId, double pcoords[3], vtkIdList *pts);
  int EvaluatePosition(double x[3], double* closestPoint,
                       int& subId, double pcoords[3],
                       double& dist2, double *weights);
  void EvaluateLocation(int& subId, double pcoords[3],
                        double x[3], double *weights);
  void Contour(double value, vtkDataArray *cellScalars,
               vtkIncrementalPointLocator *locator, vtkCellArray *verts,
               vtkCellArray *lines, vtkCellArray *polys,
               vtkPointData *inPd, vtkPointData *outPd,
               vtkCellData *inCd, vtkIdType cellId, vtkCellData *outCd);
  void Clip(double value, vtkDataArray *cellScalars,
            vtkIncrementalPointLocator *locator, vtkCellArray *connectivity,
            vtkPointData *inPd, vtkPointData *outPd,
            vtkCellData *inCd, vtkIdType cellId, vtkCellData *outCd,
            int insideOut);
  int IntersectWithLine(double p1[3], double p2[3], double tol, double& t,
                        double x[3], double pcoords[3], int& subId);
  int Triangulate(int index, vtkIdList *ptIds, vtkPoints *pts);
  void Derivatives(int subId, double pcoords[3], double *values,
                   int dim, double *derivs);
  int GetParametricCenter(double pcoords[3]);
  double *GetParametricCoords();
  int IsPrimaryCell();

  // Description:
  // Compute the interpolation functions/derivatives
  // (aka shape functions/derivatives)
  virtual void InterpolateFunctions(double pcoords[3], double *weights);
  virtual void InterpolateDerivs(double pcoords[3], double *derivs);

  // Description:
  // This method is used to support the vtkDataSet::GetCell(vtkGenericCell *)
  // method. It allows vtkGenericCell to act like any cell type by
  // dereferencing an internal instance of a concrete cell type. When
  // you set the cell type, you are resetting a pointer to an internal
  // cell which is then used for computation.
  void SetCellType(int cellType);
  void SetCellTypeToEmptyCell() {this->SetCellType(VTK_EMPTY_CELL);}
  void SetCellTypeToVertex() {this->SetCellType(VTK_VERTEX);}
  void SetCellTypeToPolyVertex() {this->SetCellType(VTK_POLY_VERTEX);}
  void SetCellTypeToLine() {this->SetCellType(VTK_LINE);}
  void SetCellTypeToPolyLine() {this->SetCellType(VTK_POLY_LINE);}
  void SetCellTypeToTriangle() {this->SetCellType(VTK_TRIANGLE);}
  void SetCellTypeToTriangleStrip() {this->SetCellType(VTK_TRIANGLE_STRIP);}
  void SetCellTypeToPolygon() {this->SetCellType(VTK_POLYGON);}
  void SetCellTypeToPixel() {this->SetCellType(VTK_PIXEL);}
  void SetCellTypeToQuad() {this->SetCellType(VTK_QUAD);}
  void SetCellTypeToTetra() {this->SetCellType(VTK_TETRA);}
  void SetCellTypeToVoxel() {this->SetCellType(VTK_VOXEL);}
  void SetCellTypeToHexahedron() {this->SetCellType(VTK_HEXAHEDRON);}
  void SetCellTypeToWedge() {this->SetCellType(VTK_WEDGE);}
  void SetCellTypeToPyramid() {this->SetCellType(VTK_PYRAMID);}
  void SetCellTypeToPentagonalPrism() {this->SetCellType(VTK_PENTAGONAL_PRISM);}
  void SetCellTypeToHexagonalPrism() {this->SetCellType(VTK_HEXAGONAL_PRISM);}
  void SetCellTypeToPolyhedron() {this->SetCellType(VTK_POLYHEDRON);}
  void SetCellTypeToConvexPointSet() {this->SetCellType(VTK_CONVEX_POINT_SET);}
  void SetCellTypeToQuadraticEdge() {this->SetCellType(VTK_QUADRATIC_EDGE);}
  void SetCellTypeToCubicLine() {this->SetCellType(VTK_CUBIC_LINE);}
  void SetCellTypeToQuadraticTriangle() {this->SetCellType(VTK_QUADRATIC_TRIANGLE);}
  void SetCellTypeToBiQuadraticTriangle() {this->SetCellType(VTK_BIQUADRATIC_TRIANGLE);}
  void SetCellTypeToQuadraticQuad() {this->SetCellType(VTK_QUADRATIC_QUAD);}
  void SetCellTypeToQuadraticTetra() {this->SetCellType(VTK_QUADRATIC_TETRA);}
  void SetCellTypeToQuadraticHexahedron() {this->SetCellType(VTK_QUADRATIC_HEXAHEDRON);}
  void SetCellTypeToQuadraticWedge() {this->SetCellType(VTK_QUADRATIC_WEDGE);}
  void SetCellTypeToQuadraticPyramid() {this->SetCellType(VTK_QUADRATIC_PYRAMID);}
  void SetCellTypeToQuadraticLinearQuad() {this->SetCellType(VTK_QUADRATIC_LINEAR_QUAD);}
  void SetCellTypeToBiQuadraticQuad() {this->SetCellType(VTK_BIQUADRATIC_QUAD);}
  void SetCellTypeToQuadraticLinearWedge() {this->SetCellType(VTK_QUADRATIC_LINEAR_WEDGE);}
  void SetCellTypeToBiQuadraticQuadraticWedge() {
    this->SetCellType(VTK_BIQUADRATIC_QUADRATIC_WEDGE);}
  void SetCellTypeToTriQuadraticHexahedron() {
    this->SetCellType(VTK_TRIQUADRATIC_HEXAHEDRON);}
  void SetCellTypeToBiQuadraticQuadraticHexahedron() {
    this->SetCellType(VTK_BIQUADRATIC_QUADRATIC_HEXAHEDRON);}

  // Description:
  // Instantiate a new vtkCell based on it's cell type value
  static vtkCell* InstantiateCell(int cellType);

protected:
  vtkGenericCell();
  ~vtkGenericCell();

  vtkCell *Cell;

private:
  vtkGenericCell(const vtkGenericCell&);  // Not implemented.
  void operator=(const vtkGenericCell&);  // Not implemented.
};

#endif


text:
************************************
Setup Windows Toolchain from Scratch
************************************

Setting up the environment gives you some more control over the process, and also provides the information for advanced users to customize the install. The :doc:`pre-built environment <windows-setup>`, addressed to less experienced users, has been prepared by following these steps.

To quickly setup the toolchain in standard way, using prebuild environment, proceed to section :doc:`windows-setup`.

.. _configure-windows-toolchain-from-scratch:

Configure Toolchain & Environment from Scratch
==============================================

This process involves installing MSYS2_, then installing the MSYS2_ and Python packages which ESP-IDF uses, and finally downloading and installing the Xtensa toolchain.

* Navigate to the MSYS2_ installer page and download the ``msys2-i686-xxxxxxx.exe`` installer executable (we only support a 32-bit MSYS environment, it works on both 32-bit and 64-bit Windows.) At time of writing, the latest installer is ``msys2-i686-20161025.exe``.

* Run through the installer steps. **Uncheck the "Run MSYS2 32-bit now" checkbox at the end.**

* Once the installer exits, open Start Menu and find "MSYS2 MinGW 32-bit" to run the terminal.

  *(Why launch this different terminal? MSYS2 has the concept of different kinds of environments. The default "MSYS" environment is Cygwin-like and uses a translation layer for all Windows API calls. We need the "MinGW" environment in order to have a native Python which supports COM ports.)*

* The ESP-IDF repository on github contains a script in the tools directory titled ``windows_install_prerequisites.sh``. If you haven't got a local copy of the ESP-IDF yet, that's OK - you can just download that one file in Raw format from here: :idf_raw:`tools/windows/windows_install_prerequisites.sh`. Save it somewhere on your computer.

* Type the path to the shell script into the MSYS2 terminal window. You can type it as a normal Windows path, but use forward-slashes instead of back-slashes. ie: ``C:/Users/myuser/Downloads/windows_install_prerequisites.sh``. You can read the script beforehand to check what it does.

* The ``windows_install_prerequisites.sh`` script will download and install packages for ESP-IDF support, and the ESP32 toolchain.

* During the initial update step, MSYS may update itself into a state where it can no longer operate. You may see errors like the following::

     *** fatal error - cygheap base mismatch detected - 0x612E5408/0x612E4408. This problem is probably due to using incompatible versions of the cygwin DLL.

  If you see errors like this, close the terminal window entirely (terminating the processes running there) and then re-open a new terminal. Re-run ``windows_install_prerequisites.sh`` (tip: use the up arrow key to see the last run command). The update process will resume after this step.

MSYS2 Mirrors in China
~~~~~~~~~~~~~~~~~~~~~~

There are some (unofficial) MSYS2 mirrors inside China, which substantially improves download speeds inside China.

To add these mirrors, edit the following two MSYS2 mirrorlist files before running the setup script. The mirrorlist files can be found in the ``/etc/pacman.d`` directory (i.e. ``c:\msys2\etc\pacman.d``).

Add these lines at the top of ``mirrorlist.mingw32``::

  Server = http://mirrors.ustc.edu.cn/msys2/mingw/i686/
  Server = http://mirror.bit.edu.cn/msys2/REPOS/MINGW/i686

Add these lines at the top of ``mirrorlist.msys``::

  Server = http://mirrors.ustc.edu.cn/msys2/msys/$arch
  Server = http://mirror.bit.edu.cn/msys2/REPOS/MSYS2/$arch

HTTP Proxy
~~~~~~~~~~

You can enable an HTTP proxy for MSYS and PIP downloads by setting the ``http_proxy`` variable in the terminal before running the setup script::

    export http_proxy='http://http.proxy.server:PORT'

Or with credentials::

    export http_proxy='http://user:password@http.proxy.server:PORT'

Add this line to ``/etc/profile`` in the MSYS directory in order to permanently enable the proxy when using MSYS.

Alternative Setup: Just download a toolchain
============================================

If you already have an MSYS2 install or want to do things differently, you can download just the toolchain here:

https://dl.espressif.com/dl/xtensa-esp32-elf-win32-1.22.0-61-gab8375a-5.2.0.zip

.. note::

	If you followed instructions :ref:`configure-windows-toolchain-from-scratch`, you already have the toolchain and you won't need this download.

.. important::

	Just having this toolchain is *not enough* to use ESP-IDF on Windows. You will need GNU make, bash, and sed at minimum. The above environments provide all this, plus a host compiler (required for menuconfig support).

Next Steps
==========

To carry on with development environment setup, proceed to section :ref:`get-started-get-esp-idf`.

.. _MSYS2: https://msys2.github.io/


text:
    <meta http-equiv='Content-Type' content='text/html; charset=utf-8'>
    <meta name='viewport' content='width=device-width, initial-scale=1' />
    <link rel='stylesheet' type='text/css' href='/style.css'>
    <title>Constellational</title>

<%- react -%>