text:
package com.shipdream.lib.android.mvc.samples.note.view.internal;

import android.content.Context;
import android.content.SharedPreferences;

import com.shipdream.lib.android.mvc.samples.note.service.android.PreferenceService;

public class PreferenceServiceImpl implements PreferenceService {
    private SharedPreferences sharedPreferences;

    public PreferenceServiceImpl(Context context, String preferenceName, int mode){
        sharedPreferences = context.getSharedPreferences(preferenceName, mode);
    }

    @Override
    public boolean contains(String key) {
        return sharedPreferences.contains(key);
    }

    @Override
    public int getInt(String key, int defaultValue) {
        return sharedPreferences.getInt(key, defaultValue);
    }

    @Override
    public long getLong(String key, long defaultValue) {
        return sharedPreferences.getLong(key, defaultValue);
    }

    @Override
    public float getFloat(String key, float defaultValue) {
        return sharedPreferences.getFloat(key, defaultValue);
    }

    @Override
    public boolean getBoolean(String key, boolean defaultValue) {
        return sharedPreferences.getBoolean(key, defaultValue);
    }

    @Override
    public String getString(String key, String defaultValue) {
        return sharedPreferences.getString(key, defaultValue);
    }

    @Override
    public Editor edit() {
        return new AndroidPreferenceEditor(sharedPreferences.edit());
    }

    private static class AndroidPreferenceEditor implements Editor{
        private SharedPreferences.Editor editor;
        AndroidPreferenceEditor(SharedPreferences.Editor andEditor){
            editor = andEditor;
        }

        @Override
        public Editor putInt(String key, int value) {
            return new AndroidPreferenceEditor(editor.putInt(key, value));
        }

        @Override
        public Editor putLong(String key, long value) {
            return new AndroidPreferenceEditor(editor.putLong(key, value));
        }

        @Override
        public Editor putFloat(String key, float value) {
            return new AndroidPreferenceEditor(editor.putFloat(key, value));
        }

        @Override
        public Editor putBoolean(String key, boolean value) {
            return new AndroidPreferenceEditor(editor.putBoolean(key, value));
        }

        @Override
        public Editor putString(String key, String value) {
            return new AndroidPreferenceEditor(editor.putString(key, value));
        }

        @Override
        public Editor clear() {
            return new AndroidPreferenceEditor(editor.clear());
        }

        @Override
        public boolean commit() {
            return editor.commit();
        }

        @Override
        public void apply() {
            editor.apply();
        }
    }
}


text:
#include <linux/fs.h>
#include <linux/list.h>
#include <linux/gfp.h>
#include <linux/wait.h>
#include <linux/net.h>
#include <linux/delay.h>
#include <linux/freezer.h>
#include <asm/uaccess.h>
#include <asm/processor.h>
#include <linux/mempool.h>
#include "cifspdu.h"
#include "cifsglob.h"
#include "cifsproto.h"
#include "cifs_debug.h"

extern mempool_t *cifs_mid_poolp;

static void
wake_up_task(struct mid_q_entry *mid)
{
	wake_up_process(mid->callback_data);
}

struct mid_q_entry *
AllocMidQEntry(const struct smb_hdr *smb_buffer, struct TCP_Server_Info *server)
{
	struct mid_q_entry *temp;

	if (server == NULL) {
		cERROR(1, "Null TCP session in AllocMidQEntry");
		return NULL;
	}

	temp = mempool_alloc(cifs_mid_poolp, GFP_NOFS);
	if (temp == NULL)
		return temp;
	else {
		memset(temp, 0, sizeof(struct mid_q_entry));
		temp->mid = smb_buffer->Mid;	/* always LE */
		temp->pid = current->pid;
		temp->command = cpu_to_le16(smb_buffer->Command);
		cFYI(1, "For smb_command %d", smb_buffer->Command);
	/*	do_gettimeofday(&temp->when_sent);*/ /* easier to use jiffies */
		/* when mid allocated can be before when sent */
		temp->when_alloc = jiffies;

		/*
		 * The default is for the mid to be synchronous, so the
		 * default callback just wakes up the current task.
		 */
		temp->callback = wake_up_task;
		temp->callback_data = current;
	}

	atomic_inc(&midCount);
	temp->mid_state = MID_REQUEST_ALLOCATED;
	return temp;
}

void
DeleteMidQEntry(struct mid_q_entry *midEntry)
{
#ifdef CONFIG_CIFS_STATS2
	unsigned long now;
#endif
	midEntry->mid_state = MID_FREE;
	atomic_dec(&midCount);
	if (midEntry->large_buf)
		cifs_buf_release(midEntry->resp_buf);
	else
		cifs_small_buf_release(midEntry->resp_buf);
#ifdef CONFIG_CIFS_STATS2
	now = jiffies;
	/* commands taking longer than one second are indications that
	   something is wrong, unless it is quite a slow link or server */
	if ((now - midEntry->when_alloc) > HZ) {
		if ((cifsFYI & CIFS_TIMER) &&
		    (midEntry->command != cpu_to_le16(SMB_COM_LOCKING_ANDX))) {
			printk(KERN_DEBUG " CIFS slow rsp: cmd %d mid %llu",
			       midEntry->command, midEntry->mid);
			printk(" A: 0x%lx S: 0x%lx R: 0x%lx\n",
			       now - midEntry->when_alloc,
			       now - midEntry->when_sent,
			       now - midEntry->when_received);
		}
	}
#endif
	mempool_free(midEntry, cifs_mid_poolp);
}

static void
delete_mid(struct mid_q_entry *mid)
{
	spin_lock(&GlobalMid_Lock);
	list_del(&mid->qhead);
	spin_unlock(&GlobalMid_Lock);

	DeleteMidQEntry(mid);
}

static int
smb_sendv(struct TCP_Server_Info *server, struct kvec *iov, int n_vec)
{
	int rc = 0;
	int i = 0;
	struct msghdr smb_msg;
	__be32 *buf_len = (__be32 *)(iov[0].iov_base);
	unsigned int len = iov[0].iov_len;
	unsigned int total_len;
	int first_vec = 0;
	unsigned int smb_buf_length = get_rfc1002_length(iov[0].iov_base);
	struct socket *ssocket = server->ssocket;

	if (ssocket == NULL)
		return -ENOTSOCK; /* BB eventually add reconnect code here */

	smb_msg.msg_name = (struct sockaddr *) &server->dstaddr;
	smb_msg.msg_namelen = sizeof(struct sockaddr);
	smb_msg.msg_control = NULL;
	smb_msg.msg_controllen = 0;
	if (server->noblocksnd)
		smb_msg.msg_flags = MSG_DONTWAIT + MSG_NOSIGNAL;
	else
		smb_msg.msg_flags = MSG_NOSIGNAL;

	total_len = 0;
	for (i = 0; i < n_vec; i++)
		total_len += iov[i].iov_len;

	cFYI(1, "Sending smb:  total_len %d", total_len);
	dump_smb(iov[0].iov_base, len);

	i = 0;
	while (total_len) {
		rc = kernel_sendmsg(ssocket, &smb_msg, &iov[first_vec],
				    n_vec - first_vec, total_len);
		if ((rc == -ENOSPC) || (rc == -EAGAIN)) {
			i++;
			/*
			 * If blocking send we try 3 times, since each can block
			 * for 5 seconds. For nonblocking  we have to try more
			 * but wait increasing amounts of time allowing time for
			 * socket to clear.  The overall time we wait in either
			 * case to send on the socket is about 15 seconds.
			 * Similarly we wait for 15 seconds for a response from
			 * the server in SendReceive[2] for the server to send
			 * a response back for most types of requests (except
			 * SMB Write past end of file which can be slow, and
			 * blocking lock operations). NFS waits slightly longer
			 * than CIFS, but this can make it take longer for
			 * nonresponsive servers to be detected and 15 seconds
			 * is more than enough time for modern networks to
			 * send a packet.  In most cases if we fail to send
			 * after the retries we will kill the socket and
			 * reconnect which may clear the network problem.
			 */
			if ((i >= 14) || (!server->noblocksnd && (i > 2))) {
				cERROR(1, "sends on sock %p stuck for 15 seconds",
				    ssocket);
				rc = -EAGAIN;
				break;
			}
			msleep(1 << i);
			continue;
		}
		if (rc < 0)
			break;

		if (rc == total_len) {
			total_len = 0;
			break;
		} else if (rc > total_len) {
			cERROR(1, "sent %d requested %d", rc, total_len);
			break;
		}
		if (rc == 0) {
			/* should never happen, letting socket clear before
			   retrying is our only obvious option here */
			cERROR(1, "tcp sent no data");
			msleep(500);
			continue;
		}
		total_len -= rc;
		/* the line below resets i */
		for (i = first_vec; i < n_vec; i++) {
			if (iov[i].iov_len) {
				if (rc > iov[i].iov_len) {
					rc -= iov[i].iov_len;
					iov[i].iov_len = 0;
				} else {
					iov[i].iov_base += rc;
					iov[i].iov_len -= rc;
					first_vec = i;
					break;
				}
			}
		}
		i = 0; /* in case we get ENOSPC on the next send */
	}

	if ((total_len > 0) && (total_len != smb_buf_length + 4)) {
		cFYI(1, "partial send (%d remaining), terminating session",
			total_len);
		/* If we have only sent part of an SMB then the next SMB
		   could be taken as the remainder of this one.  We need
		   to kill the socket so the server throws away the partial
		   SMB */
		server->tcpStatus = CifsNeedReconnect;
	}

	if (rc < 0 && rc != -EINTR)
		cERROR(1, "Error %d sending data on socket to server", rc);
	else
		rc = 0;

	/* Don't want to modify the buffer as a side effect of this call. */
	*buf_len = cpu_to_be32(smb_buf_length);

	return rc;
}

int
smb_send(struct TCP_Server_Info *server, struct smb_hdr *smb_buffer,
	 unsigned int smb_buf_length)
{
	struct kvec iov;

	iov.iov_base = smb_buffer;
	iov.iov_len = smb_buf_length + 4;

	return smb_sendv(server, &iov, 1);
}

static int
wait_for_free_credits(struct TCP_Server_Info *server, const int optype,
		      int *credits)
{
	int rc;

	spin_lock(&server->req_lock);
	if (optype == CIFS_ASYNC_OP) {
		/* oplock breaks must not be held up */
		server->in_flight++;
		*credits -= 1;
		spin_unlock(&server->req_lock);
		return 0;
	}

	while (1) {
		if (*credits <= 0) {
			spin_unlock(&server->req_lock);
			cifs_num_waiters_inc(server);
			rc = wait_event_killable(server->request_q,
						 has_credits(server, credits));
			cifs_num_waiters_dec(server);
			if (rc)
				return rc;
			spin_lock(&server->req_lock);
		} else {
			if (server->tcpStatus == CifsExiting) {
				spin_unlock(&server->req_lock);
				return -ENOENT;
			}

			/*
			 * Can not count locking commands against total
			 * as they are allowed to block on server.
			 */

			/* update # of requests on the wire to server */
			if (optype != CIFS_BLOCKING_OP) {
				*credits -= 1;
				server->in_flight++;
			}
			spin_unlock(&server->req_lock);
			break;
		}
	}
	return 0;
}

static int
wait_for_free_request(struct TCP_Server_Info *server, const int optype)
{
	return wait_for_free_credits(server, optype, get_credits_field(server));
}

static int allocate_mid(struct cifs_ses *ses, struct smb_hdr *in_buf,
			struct mid_q_entry **ppmidQ)
{
	if (ses->server->tcpStatus == CifsExiting) {
		return -ENOENT;
	}

	if (ses->server->tcpStatus == CifsNeedReconnect) {
		cFYI(1, "tcp session dead - return to caller to retry");
		return -EAGAIN;
	}

	if (ses->status != CifsGood) {
		/* check if SMB session is bad because we are setting it up */
		if ((in_buf->Command != SMB_COM_SESSION_SETUP_ANDX) &&
			(in_buf->Command != SMB_COM_NEGOTIATE))
			return -EAGAIN;
		/* else ok - we are setting up session */
	}
	*ppmidQ = AllocMidQEntry(in_buf, ses->server);
	if (*ppmidQ == NULL)
		return -ENOMEM;
	spin_lock(&GlobalMid_Lock);
	list_add_tail(&(*ppmidQ)->qhead, &ses->server->pending_mid_q);
	spin_unlock(&GlobalMid_Lock);
	return 0;
}

static int
wait_for_response(struct TCP_Server_Info *server, struct mid_q_entry *midQ)
{
	int error;

	error = wait_event_freezekillable_unsafe(server->response_q,
				    midQ->mid_state != MID_REQUEST_SUBMITTED);
	if (error < 0)
		return -ERESTARTSYS;

	return 0;
}

static int
cifs_setup_async_request(struct TCP_Server_Info *server, struct kvec *iov,
			 unsigned int nvec, struct mid_q_entry **ret_mid)
{
	int rc;
	struct smb_hdr *hdr = (struct smb_hdr *)iov[0].iov_base;
	struct mid_q_entry *mid;

	/* enable signing if server requires it */
	if (server->sec_mode & (SECMODE_SIGN_REQUIRED | SECMODE_SIGN_ENABLED))
		hdr->Flags2 |= SMBFLG2_SECURITY_SIGNATURE;

	mid = AllocMidQEntry(hdr, server);
	if (mid == NULL)
		return -ENOMEM;

	/* put it on the pending_mid_q */
	spin_lock(&GlobalMid_Lock);
	list_add_tail(&mid->qhead, &server->pending_mid_q);
	spin_unlock(&GlobalMid_Lock);

	rc = cifs_sign_smb2(iov, nvec, server, &mid->sequence_number);
	if (rc)
		delete_mid(mid);
	*ret_mid = mid;
	return rc;
}

/*
 * Send a SMB request and set the callback function in the mid to handle
 * the result. Caller is responsible for dealing with timeouts.
 */
int
cifs_call_async(struct TCP_Server_Info *server, struct kvec *iov,
		unsigned int nvec, mid_receive_t *receive,
		mid_callback_t *callback, void *cbdata, bool ignore_pend)
{
	int rc;
	struct mid_q_entry *mid;

	rc = wait_for_free_request(server, ignore_pend ? CIFS_ASYNC_OP : 0);
	if (rc)
		return rc;

	mutex_lock(&server->srv_mutex);
	rc = cifs_setup_async_request(server, iov, nvec, &mid);
	if (rc) {
		mutex_unlock(&server->srv_mutex);
		cifs_add_credits(server, 1);
		wake_up(&server->request_q);
		return rc;
	}

	mid->receive = receive;
	mid->callback = callback;
	mid->callback_data = cbdata;
	mid->mid_state = MID_REQUEST_SUBMITTED;

	cifs_in_send_inc(server);
	rc = smb_sendv(server, iov, nvec);
	cifs_in_send_dec(server);
	cifs_save_when_sent(mid);
	mutex_unlock(&server->srv_mutex);

	if (rc)
		goto out_err;

	return rc;
out_err:
	delete_mid(mid);
	cifs_add_credits(server, 1);
	wake_up(&server->request_q);
	return rc;
}

/*
 *
 * Send an SMB Request.  No response info (other than return code)
 * needs to be parsed.
 *
 * flags indicate the type of request buffer and how long to wait
 * and whether to log NT STATUS code (error) before mapping it to POSIX error
 *
 */
int
SendReceiveNoRsp(const unsigned int xid, struct cifs_ses *ses,
		 char *in_buf, int flags)
{
	int rc;
	struct kvec iov[1];
	int resp_buf_type;

	iov[0].iov_base = in_buf;
	iov[0].iov_len = get_rfc1002_length(in_buf) + 4;
	flags |= CIFS_NO_RESP;
	rc = SendReceive2(xid, ses, iov, 1, &resp_buf_type, flags);
	cFYI(DBG2, "SendRcvNoRsp flags %d rc %d", flags, rc);

	return rc;
}

static int
cifs_sync_mid_result(struct mid_q_entry *mid, struct TCP_Server_Info *server)
{
	int rc = 0;

	cFYI(1, "%s: cmd=%d mid=%llu state=%d", __func__,
	     le16_to_cpu(mid->command), mid->mid, mid->mid_state);

	spin_lock(&GlobalMid_Lock);
	switch (mid->mid_state) {
	case MID_RESPONSE_RECEIVED:
		spin_unlock(&GlobalMid_Lock);
		return rc;
	case MID_RETRY_NEEDED:
		rc = -EAGAIN;
		break;
	case MID_RESPONSE_MALFORMED:
		rc = -EIO;
		break;
	case MID_SHUTDOWN:
		rc = -EHOSTDOWN;
		break;
	default:
		list_del_init(&mid->qhead);
		cERROR(1, "%s: invalid mid state mid=%llu state=%d", __func__,
		       mid->mid, mid->mid_state);
		rc = -EIO;
	}
	spin_unlock(&GlobalMid_Lock);

	DeleteMidQEntry(mid);
	return rc;
}

/*
 * An NT cancel request header looks just like the original request except:
 *
 * The Command is SMB_COM_NT_CANCEL
 * The WordCount is zeroed out
 * The ByteCount is zeroed out
 *
 * This function mangles an existing request buffer into a
 * SMB_COM_NT_CANCEL request and then sends it.
 */
static int
send_nt_cancel(struct TCP_Server_Info *server, struct smb_hdr *in_buf,
		struct mid_q_entry *mid)
{
	int rc = 0;

	/* -4 for RFC1001 length and +2 for BCC field */
	in_buf->smb_buf_length = cpu_to_be32(sizeof(struct smb_hdr) - 4  + 2);
	in_buf->Command = SMB_COM_NT_CANCEL;
	in_buf->WordCount = 0;
	put_bcc(0, in_buf);

	mutex_lock(&server->srv_mutex);
	rc = cifs_sign_smb(in_buf, server, &mid->sequence_number);
	if (rc) {
		mutex_unlock(&server->srv_mutex);
		return rc;
	}
	rc = smb_send(server, in_buf, be32_to_cpu(in_buf->smb_buf_length));
	mutex_unlock(&server->srv_mutex);

	cFYI(1, "issued NT_CANCEL for mid %u, rc = %d",
		in_buf->Mid, rc);

	return rc;
}

int
cifs_check_receive(struct mid_q_entry *mid, struct TCP_Server_Info *server,
		   bool log_error)
{
	unsigned int len = get_rfc1002_length(mid->resp_buf) + 4;

	dump_smb(mid->resp_buf, min_t(u32, 92, len));

	/* convert the length into a more usable form */
	if (server->sec_mode & (SECMODE_SIGN_REQUIRED | SECMODE_SIGN_ENABLED)) {
		struct kvec iov;

		iov.iov_base = mid->resp_buf;
		iov.iov_len = len;
		/* FIXME: add code to kill session */
		if (cifs_verify_signature(&iov, 1, server,
					  mid->sequence_number + 1) != 0)
			cERROR(1, "Unexpected SMB signature");
	}

	/* BB special case reconnect tid and uid here? */
	return map_smb_to_linux_error(mid->resp_buf, log_error);
}

static int
cifs_setup_request(struct cifs_ses *ses, struct kvec *iov,
		   unsigned int nvec, struct mid_q_entry **ret_mid)
{
	int rc;
	struct smb_hdr *hdr = (struct smb_hdr *)iov[0].iov_base;
	struct mid_q_entry *mid;

	rc = allocate_mid(ses, hdr, &mid);
	if (rc)
		return rc;
	rc = cifs_sign_smb2(iov, nvec, ses->server, &mid->sequence_number);
	if (rc)
		delete_mid(mid);
	*ret_mid = mid;
	return rc;
}

int
SendReceive2(const unsigned int xid, struct cifs_ses *ses,
	     struct kvec *iov, int n_vec, int *pRespBufType /* ret */,
	     const int flags)
{
	int rc = 0;
	int long_op;
	struct mid_q_entry *midQ;
	char *buf = iov[0].iov_base;

	long_op = flags & CIFS_TIMEOUT_MASK;

	*pRespBufType = CIFS_NO_BUFFER;  /* no response buf yet */

	if ((ses == NULL) || (ses->server == NULL)) {
		cifs_small_buf_release(buf);
		cERROR(1, "Null session");
		return -EIO;
	}

	if (ses->server->tcpStatus == CifsExiting) {
		cifs_small_buf_release(buf);
		return -ENOENT;
	}

	/*
	 * Ensure that we do not send more than 50 overlapping requests
	 * to the same server. We may make this configurable later or
	 * use ses->maxReq.
	 */

	rc = wait_for_free_request(ses->server, long_op);
	if (rc) {
		cifs_small_buf_release(buf);
		return rc;
	}

	/*
	 * Make sure that we sign in the same order that we send on this socket
	 * and avoid races inside tcp sendmsg code that could cause corruption
	 * of smb data.
	 */

	mutex_lock(&ses->server->srv_mutex);

	rc = cifs_setup_request(ses, iov, n_vec, &midQ);
	if (rc) {
		mutex_unlock(&ses->server->srv_mutex);
		cifs_small_buf_release(buf);
		/* Update # of requests on wire to server */
		cifs_add_credits(ses->server, 1);
		return rc;
	}

	midQ->mid_state = MID_REQUEST_SUBMITTED;
	cifs_in_send_inc(ses->server);
	rc = smb_sendv(ses->server, iov, n_vec);
	cifs_in_send_dec(ses->server);
	cifs_save_when_sent(midQ);

	mutex_unlock(&ses->server->srv_mutex);

	if (rc < 0) {
		cifs_small_buf_release(buf);
		goto out;
	}

	if (long_op == CIFS_ASYNC_OP) {
		cifs_small_buf_release(buf);
		goto out;
	}

	rc = wait_for_response(ses->server, midQ);
	if (rc != 0) {
		send_nt_cancel(ses->server, (struct smb_hdr *)buf, midQ);
		spin_lock(&GlobalMid_Lock);
		if (midQ->mid_state == MID_REQUEST_SUBMITTED) {
			midQ->callback = DeleteMidQEntry;
			spin_unlock(&GlobalMid_Lock);
			cifs_small_buf_release(buf);
			cifs_add_credits(ses->server, 1);
			return rc;
		}
		spin_unlock(&GlobalMid_Lock);
	}

	cifs_small_buf_release(buf);

	rc = cifs_sync_mid_result(midQ, ses->server);
	if (rc != 0) {
		cifs_add_credits(ses->server, 1);
		return rc;
	}

	if (!midQ->resp_buf || midQ->mid_state != MID_RESPONSE_RECEIVED) {
		rc = -EIO;
		cFYI(1, "Bad MID state?");
		goto out;
	}

	buf = (char *)midQ->resp_buf;
	iov[0].iov_base = buf;
	iov[0].iov_len = get_rfc1002_length(buf) + 4;
	if (midQ->large_buf)
		*pRespBufType = CIFS_LARGE_BUFFER;
	else
		*pRespBufType = CIFS_SMALL_BUFFER;

	rc = cifs_check_receive(midQ, ses->server, flags & CIFS_LOG_ERROR);

	/* mark it so buf will not be freed by delete_mid */
	if ((flags & CIFS_NO_RESP) == 0)
		midQ->resp_buf = NULL;
out:
	delete_mid(midQ);
	cifs_add_credits(ses->server, 1);

	return rc;
}

int
SendReceive(const unsigned int xid, struct cifs_ses *ses,
	    struct smb_hdr *in_buf, struct smb_hdr *out_buf,
	    int *pbytes_returned, const int long_op)
{
	int rc = 0;
	struct mid_q_entry *midQ;

	if (ses == NULL) {
		cERROR(1, "Null smb session");
		return -EIO;
	}
	if (ses->server == NULL) {
		cERROR(1, "Null tcp session");
		return -EIO;
	}

	if (ses->server->tcpStatus == CifsExiting)
		return -ENOENT;

	/* Ensure that we do not send more than 50 overlapping requests
	   to the same server. We may make this configurable later or
	   use ses->maxReq */

	if (be32_to_cpu(in_buf->smb_buf_length) > CIFSMaxBufSize +
			MAX_CIFS_HDR_SIZE - 4) {
		cERROR(1, "Illegal length, greater than maximum frame, %d",
			   be32_to_cpu(in_buf->smb_buf_length));
		return -EIO;
	}

	rc = wait_for_free_request(ses->server, long_op);
	if (rc)
		return rc;

	/* make sure that we sign in the same order that we send on this socket
	   and avoid races inside tcp sendmsg code that could cause corruption
	   of smb data */

	mutex_lock(&ses->server->srv_mutex);

	rc = allocate_mid(ses, in_buf, &midQ);
	if (rc) {
		mutex_unlock(&ses->server->srv_mutex);
		/* Update # of requests on wire to server */
		cifs_add_credits(ses->server, 1);
		return rc;
	}

	rc = cifs_sign_smb(in_buf, ses->server, &midQ->sequence_number);
	if (rc) {
		mutex_unlock(&ses->server->srv_mutex);
		goto out;
	}

	midQ->mid_state = MID_REQUEST_SUBMITTED;

	cifs_in_send_inc(ses->server);
	rc = smb_send(ses->server, in_buf, be32_to_cpu(in_buf->smb_buf_length));
	cifs_in_send_dec(ses->server);
	cifs_save_when_sent(midQ);
	mutex_unlock(&ses->server->srv_mutex);

	if (rc < 0)
		goto out;

	if (long_op == CIFS_ASYNC_OP)
		goto out;

	rc = wait_for_response(ses->server, midQ);
	if (rc != 0) {
		send_nt_cancel(ses->server, in_buf, midQ);
		spin_lock(&GlobalMid_Lock);
		if (midQ->mid_state == MID_REQUEST_SUBMITTED) {
			/* no longer considered to be "in-flight" */
			midQ->callback = DeleteMidQEntry;
			spin_unlock(&GlobalMid_Lock);
			cifs_add_credits(ses->server, 1);
			return rc;
		}
		spin_unlock(&GlobalMid_Lock);
	}

	rc = cifs_sync_mid_result(midQ, ses->server);
	if (rc != 0) {
		cifs_add_credits(ses->server, 1);
		return rc;
	}

	if (!midQ->resp_buf || !out_buf ||
	    midQ->mid_state != MID_RESPONSE_RECEIVED) {
		rc = -EIO;
		cERROR(1, "Bad MID state?");
		goto out;
	}

	*pbytes_returned = get_rfc1002_length(midQ->resp_buf);
	memcpy(out_buf, midQ->resp_buf, *pbytes_returned + 4);
	rc = cifs_check_receive(midQ, ses->server, 0);
out:
	delete_mid(midQ);
	cifs_add_credits(ses->server, 1);

	return rc;
}

/* We send a LOCKINGX_CANCEL_LOCK to cause the Windows
   blocking lock to return. */

static int
send_lock_cancel(const unsigned int xid, struct cifs_tcon *tcon,
			struct smb_hdr *in_buf,
			struct smb_hdr *out_buf)
{
	int bytes_returned;
	struct cifs_ses *ses = tcon->ses;
	LOCK_REQ *pSMB = (LOCK_REQ *)in_buf;

	/* We just modify the current in_buf to change
	   the type of lock from LOCKING_ANDX_SHARED_LOCK
	   or LOCKING_ANDX_EXCLUSIVE_LOCK to
	   LOCKING_ANDX_CANCEL_LOCK. */

	pSMB->LockType = LOCKING_ANDX_CANCEL_LOCK|LOCKING_ANDX_LARGE_FILES;
	pSMB->Timeout = 0;
	pSMB->hdr.Mid = GetNextMid(ses->server);

	return SendReceive(xid, ses, in_buf, out_buf,
			&bytes_returned, 0);
}

int
SendReceiveBlockingLock(const unsigned int xid, struct cifs_tcon *tcon,
	    struct smb_hdr *in_buf, struct smb_hdr *out_buf,
	    int *pbytes_returned)
{
	int rc = 0;
	int rstart = 0;
	struct mid_q_entry *midQ;
	struct cifs_ses *ses;

	if (tcon == NULL || tcon->ses == NULL) {
		cERROR(1, "Null smb session");
		return -EIO;
	}
	ses = tcon->ses;

	if (ses->server == NULL) {
		cERROR(1, "Null tcp session");
		return -EIO;
	}

	if (ses->server->tcpStatus == CifsExiting)
		return -ENOENT;

	/* Ensure that we do not send more than 50 overlapping requests
	   to the same server. We may make this configurable later or
	   use ses->maxReq */

	if (be32_to_cpu(in_buf->smb_buf_length) > CIFSMaxBufSize +
			MAX_CIFS_HDR_SIZE - 4) {
		cERROR(1, "Illegal length, greater than maximum frame, %d",
			   be32_to_cpu(in_buf->smb_buf_length));
		return -EIO;
	}

	rc = wait_for_free_request(ses->server, CIFS_BLOCKING_OP);
	if (rc)
		return rc;

	/* make sure that we sign in the same order that we send on this socket
	   and avoid races inside tcp sendmsg code that could cause corruption
	   of smb data */

	mutex_lock(&ses->server->srv_mutex);

	rc = allocate_mid(ses, in_buf, &midQ);
	if (rc) {
		mutex_unlock(&ses->server->srv_mutex);
		return rc;
	}

	rc = cifs_sign_smb(in_buf, ses->server, &midQ->sequence_number);
	if (rc) {
		delete_mid(midQ);
		mutex_unlock(&ses->server->srv_mutex);
		return rc;
	}

	midQ->mid_state = MID_REQUEST_SUBMITTED;
	cifs_in_send_inc(ses->server);
	rc = smb_send(ses->server, in_buf, be32_to_cpu(in_buf->smb_buf_length));
	cifs_in_send_dec(ses->server);
	cifs_save_when_sent(midQ);
	mutex_unlock(&ses->server->srv_mutex);

	if (rc < 0) {
		delete_mid(midQ);
		return rc;
	}

	/* Wait for a reply - allow signals to interrupt. */
	rc = wait_event_interruptible(ses->server->response_q,
		(!(midQ->mid_state == MID_REQUEST_SUBMITTED)) ||
		((ses->server->tcpStatus != CifsGood) &&
		 (ses->server->tcpStatus != CifsNew)));

	/* Were we interrupted by a signal ? */
	if ((rc == -ERESTARTSYS) &&
		(midQ->mid_state == MID_REQUEST_SUBMITTED) &&
		((ses->server->tcpStatus == CifsGood) ||
		 (ses->server->tcpStatus == CifsNew))) {

		if (in_buf->Command == SMB_COM_TRANSACTION2) {
			/* POSIX lock. We send a NT_CANCEL SMB to cause the
			   blocking lock to return. */
			rc = send_nt_cancel(ses->server, in_buf, midQ);
			if (rc) {
				delete_mid(midQ);
				return rc;
			}
		} else {
			/* Windows lock. We send a LOCKINGX_CANCEL_LOCK
			   to cause the blocking lock to return. */

			rc = send_lock_cancel(xid, tcon, in_buf, out_buf);

			/* If we get -ENOLCK back the lock may have
			   already been removed. Don't exit in this case. */
			if (rc && rc != -ENOLCK) {
				delete_mid(midQ);
				return rc;
			}
		}

		rc = wait_for_response(ses->server, midQ);
		if (rc) {
			send_nt_cancel(ses->server, in_buf, midQ);
			spin_lock(&GlobalMid_Lock);
			if (midQ->mid_state == MID_REQUEST_SUBMITTED) {
				/* no longer considered to be "in-flight" */
				midQ->callback = DeleteMidQEntry;
				spin_unlock(&GlobalMid_Lock);
				return rc;
			}
			spin_unlock(&GlobalMid_Lock);
		}

		/* We got the response - restart system call. */
		rstart = 1;
	}

	rc = cifs_sync_mid_result(midQ, ses->server);
	if (rc != 0)
		return rc;

	/* rcvd frame is ok */
	if (out_buf == NULL || midQ->mid_state != MID_RESPONSE_RECEIVED) {
		rc = -EIO;
		cERROR(1, "Bad MID state?");
		goto out;
	}

	*pbytes_returned = get_rfc1002_length(midQ->resp_buf);
	memcpy(out_buf, midQ->resp_buf, *pbytes_returned + 4);
	rc = cifs_check_receive(midQ, ses->server, 0);
out:
	delete_mid(midQ);
	if (rstart && rc == -EACCES)
		return -ERESTARTSYS;
	return rc;
}

redpajama_set_name: RedPajamaGithub


text:
using storage::BlobItemBytesRequest;
using storage::BlobItemBytesResponse;
using storage::DataElement;

namespace content {
namespace {

BlobItemBytesResponse ResponseWithData(size_t request_number,
                                       const std::string& str) {
  BlobItemBytesResponse response(request_number);
  response.inline_data.assign(str.begin(), str.end());
  return response;
}

static DataElement MakeBlobElement(const std::string& uuid,
                                   uint64_t offset,
                                   uint64_t size) {
  DataElement element;
  element.SetToBlobRange(uuid, offset, size);
  return element;
}

static DataElement MakeDataDescriptionElement(size_t size) {
  DataElement element;
  element.SetToBytesDescription(size);
  return element;
}

static DataElement MakeDataElement(const std::string& str) {
  DataElement element;
  element.SetToBytes(str.c_str(), str.size());
  return element;
}

static blink::WebThreadSafeData CreateData(const std::string& str) {
  return blink::WebThreadSafeData(str.c_str(), str.size());
}

}  // namespace

class BlobTransportControllerTest : public testing::Test {
 public:
  void SetUp() override { BlobTransportController::GetInstance()->Clear(); }

  void TearDown() override { BlobTransportController::GetInstance()->Clear(); }
};

TEST_F(BlobTransportControllerTest, Descriptions) {
  const std::string kBlobUUID = "uuid";
  const std::string KRefBlobUUID = "refuuid";
  const std::string kBadBlobUUID = "uuuidBad";
  const size_t kShortcutSize = 11;
  BlobTransportController* holder = BlobTransportController::GetInstance();

  // The first two data elements should be combined and the data shortcut.
  scoped_ptr<BlobConsolidation> consolidation(new BlobConsolidation());
  consolidation->AddBlobItem(KRefBlobUUID, 10, 10);
  consolidation->AddDataItem(CreateData("Hello"));
  consolidation->AddDataItem(CreateData("Hello2"));
  consolidation->AddBlobItem(KRefBlobUUID, 0, 10);
  consolidation->AddDataItem(CreateData("Hello3"));

  std::vector<DataElement> out;
  holder->GetDescriptions(consolidation.get(), kShortcutSize, &out);

  std::vector<DataElement> expected;
  expected.push_back(MakeBlobElement(KRefBlobUUID, 10, 10));
  expected.push_back(MakeDataElement("HelloHello2"));
  expected.push_back(MakeBlobElement(KRefBlobUUID, 0, 10));
  expected.push_back(MakeDataDescriptionElement(6));
  EXPECT_EQ(expected, out);
}

TEST_F(BlobTransportControllerTest, Responses) {
  using ResponsesStatus = BlobTransportController::ResponsesStatus;
  const std::string kBlobUUID = "uuid";
  const std::string KRefBlobUUID = "refuuid";
  const std::string kBadBlobUUID = "uuuidBad";
  BlobTransportController* holder = BlobTransportController::GetInstance();

  // The first two data elements should be combined.
  BlobConsolidation* consolidation = new BlobConsolidation();
  consolidation->AddBlobItem(KRefBlobUUID, 10, 10);
  consolidation->AddDataItem(CreateData("Hello"));
  consolidation->AddDataItem(CreateData("Hello2"));
  consolidation->AddBlobItem(KRefBlobUUID, 0, 10);
  consolidation->AddDataItem(CreateData("Hello3"));
  // See the above test for the expected descriptions layout.

  holder->blob_storage_.insert(
      std::make_pair(kBlobUUID, make_scoped_ptr(consolidation)));

  std::vector<BlobItemBytesRequest> requests;
  std::vector<base::SharedMemoryHandle> memory_handles;
  std::vector<IPC::PlatformFileForTransit> file_handles;
  std::vector<storage::BlobItemBytesResponse> output;

  // Request for all of first data
  requests.push_back(BlobItemBytesRequest::CreateIPCRequest(0, 1, 0, 11));
  EXPECT_EQ(ResponsesStatus::SUCCESS,
            holder->GetResponses(kBlobUUID, requests, &memory_handles,
                                 file_handles, &output));
  EXPECT_EQ(1u, output.size());
  std::vector<storage::BlobItemBytesResponse> expected;
  expected.push_back(ResponseWithData(0, "HelloHello2"));
  EXPECT_EQ(expected, output);

  // Part of second data
  output.clear();
  requests[0] = BlobItemBytesRequest::CreateIPCRequest(1000, 3, 1, 5);
  EXPECT_EQ(ResponsesStatus::SUCCESS,
            holder->GetResponses(kBlobUUID, requests, &memory_handles,
                                 file_handles, &output));
  EXPECT_EQ(1u, output.size());
  expected.clear();
  expected.push_back(ResponseWithData(1000, "ello3"));
  EXPECT_EQ(expected, output);

  // Both data segments
  output.clear();
  requests[0] = BlobItemBytesRequest::CreateIPCRequest(0, 1, 0, 11);
  requests.push_back(BlobItemBytesRequest::CreateIPCRequest(1, 3, 0, 6));
  EXPECT_EQ(ResponsesStatus::SUCCESS,
            holder->GetResponses(kBlobUUID, requests, &memory_handles,
                                 file_handles, &output));
  EXPECT_EQ(2u, output.size());
  expected.clear();
  expected.push_back(ResponseWithData(0, "HelloHello2"));
  expected.push_back(ResponseWithData(1, "Hello3"));
  EXPECT_EQ(expected, output);
}

TEST_F(BlobTransportControllerTest, SharedMemory) {
  using ResponsesStatus = BlobTransportController::ResponsesStatus;
  const std::string kBlobUUID = "uuid";
  const std::string KRefBlobUUID = "refuuid";
  const std::string kBadBlobUUID = "uuuidBad";
  BlobTransportController* holder = BlobTransportController::GetInstance();

  // The first two data elements should be combined.
  BlobConsolidation* consolidation = new BlobConsolidation();
  consolidation->AddBlobItem(KRefBlobUUID, 10, 10);
  consolidation->AddDataItem(CreateData("Hello"));
  consolidation->AddDataItem(CreateData("Hello2"));
  consolidation->AddBlobItem(KRefBlobUUID, 0, 10);
  consolidation->AddDataItem(CreateData("Hello3"));
  // See the above test for the expected descriptions layout.

  holder->blob_storage_.insert(
      std::make_pair(kBlobUUID, make_scoped_ptr(consolidation)));

  std::vector<BlobItemBytesRequest> requests;
  std::vector<base::SharedMemoryHandle> memory_handles;
  std::vector<IPC::PlatformFileForTransit> file_handles;
  std::vector<storage::BlobItemBytesResponse> output;

  // Request for all data in shared memory
  requests.push_back(
      BlobItemBytesRequest::CreateSharedMemoryRequest(0, 1, 0, 11, 0, 0));
  requests.push_back(
      BlobItemBytesRequest::CreateSharedMemoryRequest(1, 3, 0, 6, 0, 11));
  base::SharedMemory memory;
  memory.CreateAndMapAnonymous(11 + 6);
  base::SharedMemoryHandle handle =
      base::SharedMemory::DuplicateHandle(memory.handle());
  CHECK(base::SharedMemory::NULLHandle() != handle);
  memory_handles.push_back(handle);

  EXPECT_EQ(ResponsesStatus::SUCCESS,
            holder->GetResponses(kBlobUUID, requests, &memory_handles,
                                 file_handles, &output));
  EXPECT_EQ(2u, output.size());
  std::vector<storage::BlobItemBytesResponse> expected;
  expected.push_back(BlobItemBytesResponse(0));
  expected.push_back(BlobItemBytesResponse(1));
  EXPECT_EQ(expected, output);
  std::string expected_memory = "HelloHello2Hello3";
  const char* mem_location = static_cast<const char*>(memory.memory());
  std::vector<char> value(mem_location, mem_location + memory.requested_size());
  EXPECT_THAT(value, testing::ElementsAreArray(expected_memory.c_str(),
                                               expected_memory.size()));
}

TEST_F(BlobTransportControllerTest, TestPublicMethods) {
  const std::string kBlobUUID = "uuid";
  const std::string KRefBlobUUID = "refuuid";
  const std::string kBadBlobUUID = "uuuidBad";
  BlobTransportController* holder = BlobTransportController::GetInstance();

  BlobConsolidation* consolidation = new BlobConsolidation();
  consolidation->AddBlobItem(KRefBlobUUID, 10, 10);
  holder->InitiateBlobTransfer(kBlobUUID, "", make_scoped_ptr(consolidation),
                               nullptr);
  holder->OnCancel(kBlobUUID,
                   storage::IPCBlobCreationCancelCode::OUT_OF_MEMORY);
  EXPECT_FALSE(holder->IsTransporting(kBlobUUID));

  consolidation = new BlobConsolidation();
  consolidation->AddBlobItem(KRefBlobUUID, 10, 10);
  holder->InitiateBlobTransfer(kBlobUUID, "", make_scoped_ptr(consolidation),
                               nullptr);
  holder->OnDone(kBlobUUID);
  EXPECT_FALSE(holder->IsTransporting(kBlobUUID));
}

TEST_F(BlobTransportControllerTest, ResponsesErrors) {
  using ResponsesStatus = BlobTransportController::ResponsesStatus;
  const std::string kBlobUUID = "uuid";
  const std::string KRefBlobUUID = "refuuid";
  const std::string kBadBlobUUID = "uuuidBad";
  BlobTransportController* holder = BlobTransportController::GetInstance();

  BlobConsolidation* consolidation = new BlobConsolidation();
  consolidation->AddBlobItem(KRefBlobUUID, 10, 10);

  holder->blob_storage_.insert(
      std::make_pair(kBlobUUID, make_scoped_ptr(consolidation)));

  std::vector<BlobItemBytesRequest> requests;
  std::vector<base::SharedMemoryHandle> memory_handles;
  std::vector<IPC::PlatformFileForTransit> file_handles;
  std::vector<storage::BlobItemBytesResponse> output;

  // Error conditions
  EXPECT_EQ(ResponsesStatus::BLOB_NOT_FOUND,
            holder->GetResponses(kBadBlobUUID, requests, &memory_handles,
                                 file_handles, &output));
  EXPECT_EQ(0u, output.size());
}

}  // namespace content


text:
package org.ayo.robot.paint.shader;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Shader;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.util.AttributeSet;

import org.ayo.lang.Bitmaps;
import org.ayo.robot.BaseView;
import org.ayo.robot.R;

/**
 * Created by Administrator on 2016/12/21.
 */

public class LinearGradientView3 extends BaseView {
    public LinearGradientView3(Context context) {
        super(context);
        init();
    }

    public LinearGradientView3(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public LinearGradientView3(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public LinearGradientView3(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init();
    }

    int startX = 5;
    int startY = 5;
    int endX = 300;
    int endY = 300;
    int startColor = 0xAA000000;
    int endColor = Color.TRANSPARENT;
    Shader.TileMode tileMode = Shader.TileMode.CLAMP;

    private Bitmap mBitmap;

    private void init(){
        mBitmap = Bitmaps.getBitmapByResource(getContext(), R.drawable.test5, 500, 500);
    }

    @Override
    protected void drawShape(Canvas canvas, int w, int h, Paint paint) {
        canvas.drawColor(Color.WHITE);

        canvas.drawBitmap(mBitmap, 0, 0, null);

        paint.setShader(new LinearGradient(startX, startY, endX, endY, startColor, endColor, tileMode));
        paint.setStyle(Paint.Style.FILL);
        canvas.drawRect(0, 0, w, h, paint);

        //绘制起点终点,便于观察
        paint.setShader(null);
        paint.setStrokeWidth(3);
        paint.setStyle(Paint.Style.STROKE);
        canvas.drawCircle(startX, startY, 5, paint);
        canvas.drawCircle(endX, endY, 5, paint);
        canvas.drawLine(startX, startY, endX, endY, paint);
        canvas.drawRect(0, 0, w, h, paint);
    }

    public void moveStartPoint(int dx, int dy){
        startX += dx;
        startY += dy;
        invalidate();
    }
    public void moveEndPoint(int dx, int dy){
        endX += dx;
        endY += dy;
        invalidate();
    }

    public void setTileMode(Shader.TileMode mode){
        this.tileMode = mode;
        invalidate();
    }

    @Override
    public String getTitle() {
        return "paint.setShader(LinearGradient)";
    }

    @Override
    public String getMethod() {
        return "";
    }

    @Override
    public String getComment() {
        return "";
    }
}


text:
package tail

import (
	"bytes"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"
	"runtime"
	"testing"
	"time"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"

	"github.com/influxdata/telegraf"
	"github.com/influxdata/telegraf/config"
	"github.com/influxdata/telegraf/plugins/parsers"
	"github.com/influxdata/telegraf/plugins/parsers/csv"
	"github.com/influxdata/telegraf/plugins/parsers/influx"
	"github.com/influxdata/telegraf/plugins/parsers/json"
	"github.com/influxdata/telegraf/testutil"
)

var (
	testdataDir = getTestdataDir()
)

func NewTestTail() *Tail {
	offsetsMutex.Lock()
	offsetsCopy := make(map[string]int64, len(offsets))
	for k, v := range offsets {
		offsetsCopy[k] = v
	}
	offsetsMutex.Unlock()
	watchMethod := defaultWatchMethod

	if runtime.GOOS == "windows" {
		watchMethod = "poll"
	}

	return &Tail{
		FromBeginning:       false,
		MaxUndeliveredLines: 1000,
		offsets:             offsetsCopy,
		WatchMethod:         watchMethod,
		PathTag:             "path",
	}
}

func TestTailBadLine(t *testing.T) {
	tmpfile, err := ioutil.TempFile("", "")
	require.NoError(t, err)
	defer os.Remove(tmpfile.Name())

	_, err = tmpfile.WriteString("cpu mytag= foo usage_idle= 100\n")
	require.NoError(t, err)

	// Write good metric so we can detect when processing is complete
	_, err = tmpfile.WriteString("cpu usage_idle=100\n")
	require.NoError(t, err)

	require.NoError(t, tmpfile.Close())

	buf := &bytes.Buffer{}
	log.SetOutput(buf)

	tt := NewTestTail()
	tt.Log = testutil.Logger{}
	tt.FromBeginning = true
	tt.Files = []string{tmpfile.Name()}
	tt.SetParserFunc(parsers.NewInfluxParser)

	err = tt.Init()
	require.NoError(t, err)

	acc := testutil.Accumulator{}
	require.NoError(t, tt.Start(&acc))

	require.NoError(t, acc.GatherError(tt.Gather))

	acc.Wait(1)

	tt.Stop()
	assert.Contains(t, buf.String(), "Malformed log line")
}

func TestTailDosLineEndings(t *testing.T) {
	tmpfile, err := ioutil.TempFile("", "")
	require.NoError(t, err)
	defer os.Remove(tmpfile.Name())
	_, err = tmpfile.WriteString("cpu usage_idle=100\r\ncpu2 usage_idle=200\r\n")
	require.NoError(t, err)
	require.NoError(t, tmpfile.Close())

	tt := NewTestTail()
	tt.Log = testutil.Logger{}
	tt.FromBeginning = true
	tt.Files = []string{tmpfile.Name()}
	tt.SetParserFunc(parsers.NewInfluxParser)

	err = tt.Init()
	require.NoError(t, err)

	acc := testutil.Accumulator{}
	require.NoError(t, tt.Start(&acc))
	defer tt.Stop()
	require.NoError(t, acc.GatherError(tt.Gather))

	acc.Wait(2)
	acc.AssertContainsFields(t, "cpu",
		map[string]interface{}{
			"usage_idle": float64(100),
		})
	acc.AssertContainsFields(t, "cpu2",
		map[string]interface{}{
			"usage_idle": float64(200),
		})
}

func TestGrokParseLogFilesWithMultiline(t *testing.T) {
	//we make sure the timeout won't kick in
	d, _ := time.ParseDuration("100s")
	duration := config.Duration(d)
	tt := NewTail()
	tt.Log = testutil.Logger{}
	tt.FromBeginning = true
	tt.Files = []string{filepath.Join(testdataDir, "test_multiline.log")}
	tt.MultilineConfig = MultilineConfig{
		Pattern:        `^[^\[]`,
		MatchWhichLine: Previous,
		InvertMatch:    false,
		Timeout:        &duration,
	}
	tt.SetParserFunc(createGrokParser)

	err := tt.Init()
	require.NoError(t, err)

	acc := testutil.Accumulator{}
	assert.NoError(t, tt.Start(&acc))
	defer tt.Stop()

	acc.Wait(3)

	expectedPath := filepath.Join(testdataDir, "test_multiline.log")
	acc.AssertContainsTaggedFields(t, "tail_grok",
		map[string]interface{}{
			"message": "HelloExample: This is debug",
		},
		map[string]string{
			"path":     expectedPath,
			"loglevel": "DEBUG",
		})
	acc.AssertContainsTaggedFields(t, "tail_grok",
		map[string]interface{}{
			"message": "HelloExample: This is info",
		},
		map[string]string{
			"path":     expectedPath,
			"loglevel": "INFO",
		})
	acc.AssertContainsTaggedFields(t, "tail_grok",
		map[string]interface{}{
			"message": "HelloExample: Sorry, something wrong! java.lang.ArithmeticException: / by zero\tat com.foo.HelloExample2.divide(HelloExample2.java:24)\tat com.foo.HelloExample2.main(HelloExample2.java:14)",
		},
		map[string]string{
			"path":     expectedPath,
			"loglevel": "ERROR",
		})

	assert.Equal(t, uint64(3), acc.NMetrics())
}

func TestGrokParseLogFilesWithMultilineTimeout(t *testing.T) {
	tmpfile, err := ioutil.TempFile("", "")
	require.NoError(t, err)
	defer os.Remove(tmpfile.Name())

	// This seems necessary in order to get the test to read the following lines.
	_, err = tmpfile.WriteString("[04/Jun/2016:12:41:48 +0100] INFO HelloExample: This is fluff\r\n")
	require.NoError(t, err)
	require.NoError(t, tmpfile.Sync())

	// set tight timeout for tests
	d := 10 * time.Millisecond
	duration := config.Duration(d)
	tt := NewTail()

	tt.Log = testutil.Logger{}
	tt.FromBeginning = true
	tt.Files = []string{tmpfile.Name()}
	tt.MultilineConfig = MultilineConfig{
		Pattern:        `^[^\[]`,
		MatchWhichLine: Previous,
		InvertMatch:    false,
		Timeout:        &duration,
	}
	tt.SetParserFunc(createGrokParser)

	err = tt.Init()
	require.NoError(t, err)

	acc := testutil.Accumulator{}
	assert.NoError(t, tt.Start(&acc))
	time.Sleep(11 * time.Millisecond) // will force timeout
	_, err = tmpfile.WriteString("[04/Jun/2016:12:41:48 +0100] INFO HelloExample: This is info\r\n")
	require.NoError(t, err)
	require.NoError(t, tmpfile.Sync())
	acc.Wait(2)
	time.Sleep(11 * time.Millisecond) // will force timeout
	_, err = tmpfile.WriteString("[04/Jun/2016:12:41:48 +0100] WARN HelloExample: This is warn\r\n")
	require.NoError(t, err)
	require.NoError(t, tmpfile.Sync())
	acc.Wait(3)
	tt.Stop()
	assert.Equal(t, uint64(3), acc.NMetrics())
	expectedPath := tmpfile.Name()

	acc.AssertContainsTaggedFields(t, "tail_grok",
		map[string]interface{}{
			"message": "HelloExample: This is info",
		},
		map[string]string{
			"path":     expectedPath,
			"loglevel": "INFO",
		})
	acc.AssertContainsTaggedFields(t, "tail_grok",
		map[string]interface{}{
			"message": "HelloExample: This is warn",
		},
		map[string]string{
			"path":     expectedPath,
			"loglevel": "WARN",
		})
}

func TestGrokParseLogFilesWithMultilineTailerCloseFlushesMultilineBuffer(t *testing.T) {
	//we make sure the timeout won't kick in
	duration := config.Duration(100 * time.Second)

	tt := NewTestTail()
	tt.Log = testutil.Logger{}
	tt.FromBeginning = true
	tt.Files = []string{filepath.Join(testdataDir, "test_multiline.log")}
	tt.MultilineConfig = MultilineConfig{
		Pattern:        `^[^\[]`,
		MatchWhichLine: Previous,
		InvertMatch:    false,
		Timeout:        &duration,
	}
	tt.SetParserFunc(createGrokParser)

	err := tt.Init()
	require.NoError(t, err)

	acc := testutil.Accumulator{}
	assert.NoError(t, tt.Start(&acc))
	acc.Wait(3)
	assert.Equal(t, uint64(3), acc.NMetrics())
	// Close tailer, so multiline buffer is flushed
	tt.Stop()
	acc.Wait(4)

	expectedPath := filepath.Join(testdataDir, "test_multiline.log")
	acc.AssertContainsTaggedFields(t, "tail_grok",
		map[string]interface{}{
			"message": "HelloExample: This is warn",
		},
		map[string]string{
			"path":     expectedPath,
			"loglevel": "WARN",
		})
}

func createGrokParser() (parsers.Parser, error) {
	grokConfig := &parsers.Config{
		MetricName:             "tail_grok",
		GrokPatterns:           []string{"%{TEST_LOG_MULTILINE}"},
		GrokCustomPatternFiles: []string{filepath.Join(testdataDir, "test-patterns")},
		DataFormat:             "grok",
	}
	parser, err := parsers.NewParser(grokConfig)
	return parser, err
}

// The csv parser should only parse the header line once per file.
func TestCSVHeadersParsedOnce(t *testing.T) {
	tmpfile, err := ioutil.TempFile("", "")
	require.NoError(t, err)
	defer os.Remove(tmpfile.Name())

	_, err = tmpfile.WriteString(`
measurement,time_idle
cpu,42
cpu,42
`)
	require.NoError(t, err)
	require.NoError(t, tmpfile.Close())

	plugin := NewTestTail()
	plugin.Log = testutil.Logger{}
	plugin.FromBeginning = true
	plugin.Files = []string{tmpfile.Name()}
	plugin.SetParserFunc(func() (parsers.Parser, error) {
		return csv.NewParser(&csv.Config{
			MeasurementColumn: "measurement",
			HeaderRowCount:    1,
			TimeFunc:          func() time.Time { return time.Unix(0, 0) },
		})
	})

	err = plugin.Init()
	require.NoError(t, err)

	acc := testutil.Accumulator{}
	err = plugin.Start(&acc)
	require.NoError(t, err)
	defer plugin.Stop()
	err = plugin.Gather(&acc)
	require.NoError(t, err)
	acc.Wait(2)
	plugin.Stop()

	expected := []telegraf.Metric{
		testutil.MustMetric("cpu",
			map[string]string{
				"path": tmpfile.Name(),
			},
			map[string]interface{}{
				"time_idle": 42,
			},
			time.Unix(0, 0)),
		testutil.MustMetric("cpu",
			map[string]string{
				"path": tmpfile.Name(),
			},
			map[string]interface{}{
				"time_idle": 42,
			},
			time.Unix(0, 0)),
	}
	testutil.RequireMetricsEqual(t, expected, acc.GetTelegrafMetrics())
}

// Ensure that the first line can produce multiple metrics (#6138)
func TestMultipleMetricsOnFirstLine(t *testing.T) {
	tmpfile, err := ioutil.TempFile("", "")
	require.NoError(t, err)
	defer os.Remove(tmpfile.Name())

	_, err = tmpfile.WriteString(`
[{"time_idle": 42}, {"time_idle": 42}]
`)
	require.NoError(t, err)
	require.NoError(t, tmpfile.Close())

	plugin := NewTestTail()
	plugin.Log = testutil.Logger{}
	plugin.FromBeginning = true
	plugin.Files = []string{tmpfile.Name()}
	plugin.PathTag = "customPathTagMyFile"
	plugin.SetParserFunc(func() (parsers.Parser, error) {
		return json.New(
			&json.Config{
				MetricName: "cpu",
			})
	})

	err = plugin.Init()
	require.NoError(t, err)

	acc := testutil.Accumulator{}
	err = plugin.Start(&acc)
	require.NoError(t, err)
	defer plugin.Stop()
	err = plugin.Gather(&acc)
	require.NoError(t, err)
	acc.Wait(2)
	plugin.Stop()

	expected := []telegraf.Metric{
		testutil.MustMetric("cpu",
			map[string]string{
				"customPathTagMyFile": tmpfile.Name(),
			},
			map[string]interface{}{
				"time_idle": 42.0,
			},
			time.Unix(0, 0)),
		testutil.MustMetric("cpu",
			map[string]string{
				"customPathTagMyFile": tmpfile.Name(),
			},
			map[string]interface{}{
				"time_idle": 42.0,
			},
			time.Unix(0, 0)),
	}
	testutil.RequireMetricsEqual(t, expected, acc.GetTelegrafMetrics(),
		testutil.IgnoreTime())
}

func TestCharacterEncoding(t *testing.T) {
	full := []telegraf.Metric{
		testutil.MustMetric("cpu",
			map[string]string{
				"cpu": "cpu0",
			},
			map[string]interface{}{
				"usage_active": 11.9,
			},
			time.Unix(0, 0),
		),
		testutil.MustMetric("cpu",
			map[string]string{
				"cpu": "cpu1",
			},
			map[string]interface{}{
				"usage_active": 26.0,
			},
			time.Unix(0, 0),
		),
		testutil.MustMetric("cpu",
			map[string]string{
				"cpu": "cpu2",
			},
			map[string]interface{}{
				"usage_active": 14.0,
			},
			time.Unix(0, 0),
		),
		testutil.MustMetric("cpu",
			map[string]string{
				"cpu": "cpu3",
			},
			map[string]interface{}{
				"usage_active": 20.4,
			},
			time.Unix(0, 0),
		),
		testutil.MustMetric("cpu",
			map[string]string{
				"cpu": "cpu-total",
			},
			map[string]interface{}{
				"usage_active": 18.4,
			},
			time.Unix(0, 0),
		),
	}

	tests := []struct {
		name     string
		plugin   *Tail
		offset   int64
		expected []telegraf.Metric
	}{
		{
			name: "utf-8",
			plugin: &Tail{
				Files:               []string{filepath.Join(testdataDir, "cpu-utf-8.influx")},
				FromBeginning:       true,
				MaxUndeliveredLines: 1000,
				Log:                 testutil.Logger{},
				CharacterEncoding:   "utf-8",
			},
			expected: full,
		},
		{
			name: "utf-8 seek",
			plugin: &Tail{
				Files:               []string{filepath.Join(testdataDir, "cpu-utf-8.influx")},
				MaxUndeliveredLines: 1000,
				Log:                 testutil.Logger{},
				CharacterEncoding:   "utf-8",
			},
			offset:   0x33,
			expected: full[1:],
		},
		{
			name: "utf-16le",
			plugin: &Tail{
				Files:               []string{filepath.Join(testdataDir, "cpu-utf-16le.influx")},
				FromBeginning:       true,
				MaxUndeliveredLines: 1000,
				Log:                 testutil.Logger{},
				CharacterEncoding:   "utf-16le",
			},
			expected: full,
		},
		{
			name: "utf-16le seek",
			plugin: &Tail{
				Files:               []string{filepath.Join(testdataDir, "cpu-utf-16le.influx")},
				MaxUndeliveredLines: 1000,
				Log:                 testutil.Logger{},
				CharacterEncoding:   "utf-16le",
			},
			offset:   0x68,
			expected: full[1:],
		},
		{
			name: "utf-16be",
			plugin: &Tail{
				Files:               []string{filepath.Join(testdataDir, "cpu-utf-16be.influx")},
				FromBeginning:       true,
				MaxUndeliveredLines: 1000,
				Log:                 testutil.Logger{},
				CharacterEncoding:   "utf-16be",
			},
			expected: full,
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			tt.plugin.SetParserFunc(func() (parsers.Parser, error) {
				handler := influx.NewMetricHandler()
				return influx.NewParser(handler), nil
			})

			if tt.offset != 0 {
				tt.plugin.offsets = map[string]int64{
					tt.plugin.Files[0]: tt.offset,
				}
			}

			err := tt.plugin.Init()
			require.NoError(t, err)

			var acc testutil.Accumulator
			err = tt.plugin.Start(&acc)
			require.NoError(t, err)
			acc.Wait(len(tt.expected))
			tt.plugin.Stop()

			actual := acc.GetTelegrafMetrics()
			for _, m := range actual {
				m.RemoveTag("path")
			}

			testutil.RequireMetricsEqual(t, tt.expected, actual, testutil.IgnoreTime())
		})
	}
}

func TestTailEOF(t *testing.T) {
	tmpfile, err := ioutil.TempFile("", "")
	require.NoError(t, err)
	defer os.Remove(tmpfile.Name())
	_, err = tmpfile.WriteString("cpu usage_idle=100\r\n")
	require.NoError(t, err)
	err = tmpfile.Sync()
	require.NoError(t, err)

	tt := NewTestTail()
	tt.Log = testutil.Logger{}
	tt.FromBeginning = true
	tt.Files = []string{tmpfile.Name()}
	tt.SetParserFunc(parsers.NewInfluxParser)

	err = tt.Init()
	require.NoError(t, err)

	acc := testutil.Accumulator{}
	require.NoError(t, tt.Start(&acc))
	defer tt.Stop()
	require.NoError(t, acc.GatherError(tt.Gather))
	acc.Wait(1) // input hits eof

	_, err = tmpfile.WriteString("cpu2 usage_idle=200\r\n")
	require.NoError(t, err)
	err = tmpfile.Sync()
	require.NoError(t, err)

	acc.Wait(2)
	require.NoError(t, acc.GatherError(tt.Gather))
	acc.AssertContainsFields(t, "cpu",
		map[string]interface{}{
			"usage_idle": float64(100),
		})
	acc.AssertContainsFields(t, "cpu2",
		map[string]interface{}{
			"usage_idle": float64(200),
		})

	err = tmpfile.Close()
	require.NoError(t, err)
}

func getTestdataDir() string {
	dir, err := os.Getwd()
	if err != nil {
		// if we cannot even establish the test directory, further progress is meaningless
		panic(err)
	}

	return filepath.Join(dir, "testdata")
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/shipin_loading"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#000000"
    android:gravity="center"
    android:orientation="vertical">

    <ProgressBar
        android:layout_width="30dp"
        style="?android:attr/progressBarStyleHorizontal"
        android:progressDrawable="@drawable/ddd"
        android:layout_height="30dp" />

    <TextView
        android:id="@+id/net_loading_speed"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="加载网络....30kb/s"
        android:textColor="#ffffff"
        android:textSize="10sp" />

</LinearLayout>


text:
Semaphore SMS API Client for NodeJS. Semaphore is The Simplest Web to SMS API ever. To find out more and subscribe to their service, visit their [homepage](http://semaphore.co/).

This SMS service is only available to mobile numbers from the Philippines.

## Installation

	npm install node-semaphore-sms

You also need to change the file **config.json.sample** to **config.json**.

You also need to provide your **API KEY** from Semaphore.

## Usage

	var Semaphore = require('node-semaphore-sms');

    var apikey = "YOUR_API_KEY";
	var sms = new Semaphore(apikey);

	// To check your account status:
    sms.status(function(error, result) {
    	if (!error)
    		console.log(result);
    });

    // To send a single SMS message:
    var payload = {
    	from: 'SEMAPHORE',
    	to: '09179008888',
    	message: 'Semaphore API Rocks!'
    };
    sms.sendsms(payload, function(error, result) {
    	if (!error) {
    		console.log(result);
    	} else
    		console.log(error);
    });

    // To send SMS to bulk numbers:
	var bulk_numbers = "09179008888,09168769988";
    sms.bulksms(bulk_numbers, function(error, result) {
    	if (!error) {
    		console.log(result);
    	} else
    		console.log(error);
    });

## License

MIT

## Release History

* 1.0.0 - Initial release
* 1.0.3 - Minor refactoring


text:
This package provides [WordPress
shortcode](http://en.support.wordpress.com/shortcodes/) support for Django
templates. It is based on [django-shortcodes](http://code.google.com/p/django-shortcodes)

## Installation

Use `pip install django-shortcodes` or clone the [Git
repository](https://github.com/agoodid/django-shortcodes).

## Usage

    {% load shortcodes_filters %}
    {{ text|shortcodes|safe }}


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2010 The Android Open Source Project

     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.
-->

<cursor-adapter xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res/com.example.android.xmladapters"
  app:uri="content://com.android.contacts/contacts"
  app:selection="has_phone_number=1"
  app:layout="@layout/contact_item">

  <bind app:from="display_name" app:to="@id/name" app:as="string" />
  <bind app:from="starred" app:to="@id/star" app:as="drawable">
        <map app:fromValue="0" app:toValue="@android:drawable/star_big_off" />
        <map app:fromValue="1" app:toValue="@android:drawable/star_big_on" />
  </bind>
  <bind app:from="_id" app:to="@id/name" app:as="com.example.android.xmladapters.ContactPhotoBinder" />

</cursor-adapter>


text:
import Vue from 'vue';
import Vuex from 'vuex';
import * as actions from './actions';
import * as getters from './getters';
import mutations from './mutations';
import state from './state';

Vue.use(Vuex);

export const createStore = () =>
  new Vuex.Store({
    state,
    getters,
    actions,
    mutations,
  });


text:
@interface PodsDummy_IMSingularity_Swift : NSObject
@end
@implementation PodsDummy_IMSingularity_Swift
@end


text:
module RailsAdmin
  module Config
    module Actions
      class AlgorithmDependencies < RailsAdmin::Config::Actions::Base

        register_instance_option :collection do
          true
        end

        register_instance_option :http_methods do
          [:get, :post]
        end

        register_instance_option :link_icon do
          'fa fa-external-link'
        end

        register_instance_option :controller do
          proc do
            if request.post?
              lang = algorithm_langs.select { |l| l[:id] == params[:lang_id] }.first
              result = puch_dependencies(lang, params[:dependencies])
              render json: result
            else
              warning = "
Warning:
"
              warning << "
"
              warning << "
This configuration is used to execute all the algorithms written under this language.
"
              warning << "
Do not modify this file if you are not sure what you are doing.
"
              warning << "
Keep in mind that deleting or updating dependencies may cause some algorithms to fail.
"
              warning << "
"

              flash[:warning] = warning.html_safe
            end
          end
        end
      end
    end
  end
end


text:
package io.netty.util.internal;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Formatter;
import java.util.List;

/**
 * String utility class.
 */
public final class StringUtil {

    public static final String NEWLINE;

    private static final String[] BYTE2HEX_PAD = new String[256];
    private static final String[] BYTE2HEX_NOPAD = new String[256];
    private static final String EMPTY_STRING = "";

    static {
        // Determine the newline character of the current platform.
        String newLine;

        try {
            newLine = new Formatter().format("%n").toString();
        } catch (Exception e) {
            // Should not reach here, but just in case.
            newLine = "\n";
        }

        NEWLINE = newLine;

        // Generate the lookup table that converts a byte into a 2-digit hexadecimal integer.
        int i;
        for (i = 0; i < 10; i ++) {
            StringBuilder buf = new StringBuilder(2);
            buf.append('0');
            buf.append(i);
            BYTE2HEX_PAD[i] = buf.toString();
            BYTE2HEX_NOPAD[i] = String.valueOf(i);
        }
        for (; i < 16; i ++) {
            StringBuilder buf = new StringBuilder(2);
            char c = (char) ('a' + i - 10);
            buf.append('0');
            buf.append(c);
            BYTE2HEX_PAD[i] = buf.toString();
            BYTE2HEX_NOPAD[i] = String.valueOf(c);
        }
        for (; i < BYTE2HEX_PAD.length; i ++) {
            StringBuilder buf = new StringBuilder(2);
            buf.append(Integer.toHexString(i));
            String str = buf.toString();
            BYTE2HEX_PAD[i] = str;
            BYTE2HEX_NOPAD[i] = str;
        }
    }

    /**
     * Splits the specified {@link String} with the specified delimiter.  This operation is a simplified and optimized
     * version of {@link String#split(String)}.
     */
    public static String[] split(String value, char delim) {
        final int end = value.length();
        final List<String> res = new ArrayList<String>();

        int start = 0;
        for (int i = 0; i < end; i ++) {
            if (value.charAt(i) == delim) {
                if (start == i) {
                    res.add(EMPTY_STRING);
                } else {
                    res.add(value.substring(start, i));
                }
                start = i + 1;
            }
        }

        if (start == 0) { // If no delimiter was found in the value
            res.add(value);
        } else {
            if (start != end) {
                // Add the last element if it's not empty.
                res.add(value.substring(start, end));
            } else {
                // Truncate trailing empty elements.
                for (int i = res.size() - 1; i >= 0; i --) {
                    if (res.get(i).isEmpty()) {
                        res.remove(i);
                    } else {
                        break;
                    }
                }
            }
        }

        return res.toArray(new String[res.size()]);
    }

    /**
     * Splits the specified {@link String} with the specified delimiter in maxParts maximum parts.
     * This operation is a simplified and optimized
     * version of {@link String#split(String, int)}.
     */
    public static String[] split(String value, char delim, int maxParts) {
        final int end = value.length();
        final List<String> res = new ArrayList<String>();

        int start = 0;
        int cpt = 1;
        for (int i = 0; i < end && cpt < maxParts; i ++) {
            if (value.charAt(i) == delim) {
                if (start == i) {
                    res.add(EMPTY_STRING);
                } else {
                    res.add(value.substring(start, i));
                }
                start = i + 1;
                cpt++;
            }
        }

        if (start == 0) { // If no delimiter was found in the value
            res.add(value);
        } else {
            if (start != end) {
                // Add the last element if it's not empty.
                res.add(value.substring(start, end));
            } else {
                // Truncate trailing empty elements.
                for (int i = res.size() - 1; i >= 0; i --) {
                    if (res.get(i).isEmpty()) {
                        res.remove(i);
                    } else {
                        break;
                    }
                }
            }
        }

        return res.toArray(new String[res.size()]);
    }

    /**
     * Get the item after one char delim if the delim is found (else null).
     * This operation is a simplified and optimized
     * version of {@link String#split(String, int)}.
     */
    public static String substringAfter(String value, char delim) {
        int pos = value.indexOf(delim);
        if (pos >= 0) {
            return value.substring(pos + 1);
        }
        return null;
    }

    /**
     * Converts the specified byte value into a 2-digit hexadecimal integer.
     */
    public static String byteToHexStringPadded(int value) {
        return BYTE2HEX_PAD[value & 0xff];
    }

    /**
     * Converts the specified byte value into a 2-digit hexadecimal integer and appends it to the specified buffer.
     */
    public static <T extends Appendable> T byteToHexStringPadded(T buf, int value) {
        try {
            buf.append(byteToHexStringPadded(value));
        } catch (IOException e) {
            PlatformDependent.throwException(e);
        }
        return buf;
    }

    /**
     * Converts the specified byte array into a hexadecimal value.
     */
    public static String toHexStringPadded(byte[] src) {
        return toHexStringPadded(src, 0, src.length);
    }

    /**
     * Converts the specified byte array into a hexadecimal value.
     */
    public static String toHexStringPadded(byte[] src, int offset, int length) {
        return toHexStringPadded(new StringBuilder(length << 1), src, offset, length).toString();
    }

    /**
     * Converts the specified byte array into a hexadecimal value and appends it to the specified buffer.
     */
    public static <T extends Appendable> T toHexStringPadded(T dst, byte[] src) {
        return toHexStringPadded(dst, src, 0, src.length);
    }

    /**
     * Converts the specified byte array into a hexadecimal value and appends it to the specified buffer.
     */
    public static <T extends Appendable> T toHexStringPadded(T dst, byte[] src, int offset, int length) {
        final int end = offset + length;
        for (int i = offset; i < end; i ++) {
            byteToHexStringPadded(dst, src[i]);
        }
        return dst;
    }

    /**
     * Converts the specified byte value into a hexadecimal integer.
     */
    public static String byteToHexString(int value) {
        return BYTE2HEX_NOPAD[value & 0xff];
    }

    /**
     * Converts the specified byte value into a hexadecimal integer and appends it to the specified buffer.
     */
    public static <T extends Appendable> T byteToHexString(T buf, int value) {
        try {
            buf.append(byteToHexString(value));
        } catch (IOException e) {
            PlatformDependent.throwException(e);
        }
        return buf;
    }

    /**
     * Converts the specified byte array into a hexadecimal value.
     */
    public static String toHexString(byte[] src) {
        return toHexString(src, 0, src.length);
    }

    /**
     * Converts the specified byte array into a hexadecimal value.
     */
    public static String toHexString(byte[] src, int offset, int length) {
        return toHexString(new StringBuilder(length << 1), src, offset, length).toString();
    }

    /**
     * Converts the specified byte array into a hexadecimal value and appends it to the specified buffer.
     */
    public static <T extends Appendable> T toHexString(T dst, byte[] src) {
        return toHexString(dst, src, 0, src.length);
    }

    /**
     * Converts the specified byte array into a hexadecimal value and appends it to the specified buffer.
     */
    public static <T extends Appendable> T toHexString(T dst, byte[] src, int offset, int length) {
        assert length >= 0;
        if (length == 0) {
            return dst;
        }

        final int end = offset + length;
        final int endMinusOne = end - 1;
        int i;

        // Skip preceding zeroes.
        for (i = offset; i < endMinusOne; i ++) {
            if (src[i] != 0) {
                break;
            }
        }

        byteToHexString(dst, src[i ++]);
        int remaining = end - i;
        toHexStringPadded(dst, src, i, remaining);

        return dst;
    }

    /**
     * The shortcut to {@link #simpleClassName(Class) simpleClassName(o.getClass())}.
     */
    public static String simpleClassName(Object o) {
        if (o == null) {
            return "null_object";
        } else {
            return simpleClassName(o.getClass());
        }
    }

    /**
     * Generates a simplified name from a {@link Class}.  Similar to {@link Class#getSimpleName()}, but it works fine
     * with anonymous classes.
     */
    public static String simpleClassName(Class<?> clazz) {
        if (clazz == null) {
            return "null_class";
        }

        Package pkg = clazz.getPackage();
        if (pkg != null) {
            return clazz.getName().substring(pkg.getName().length() + 1);
        } else {
            return clazz.getName();
        }
    }

    private StringUtil() {
        // Unused.
    }
}


text:
package com.seafile.seadroid2.ui.dialog;

import android.app.Dialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;

import com.seafile.seadroid2.R;
import com.seafile.seadroid2.SeafException;
import com.seafile.seadroid2.account.Account;
import com.seafile.seadroid2.data.DataManager;
import com.seafile.seadroid2.ui.dialog.TaskDialog.Task;

class NewDirTask extends TaskDialog.Task {
    String repoID;
    String parentDir;
    String dirName;
    DataManager dataManager;

    public NewDirTask(String repoID, String parentDir,
                      String dirName, DataManager dataManager) {
        this.repoID = repoID;
        this.parentDir = parentDir;
        this.dirName = dirName;
        this.dataManager = dataManager;
    }

    @Override
    protected void runTask() {
        try {
            dataManager.createNewDir(repoID, parentDir, dirName);
        } catch (SeafException e) {
            setTaskException(e);
        }
    }
}

public class NewDirDialog extends TaskDialog {

    private static final String STATE_TASK_REPO_ID = "new_dir_task.repo_id";
    private static final String STATE_TASK_PARENT_DIR = "new_dir_task.parent_dir";
    private static final String STATE_ACCOUNT = "new_dir_task.account.account";

    private EditText dirNameText;
    private DataManager dataManager;
    private Account account;

    private String repoID;
    private String parentDir;

    public String getNewDirName() {
        return dirNameText.getText().toString().trim();
    }

    public void init(String repoID, String parentDir, Account account) {
        this.repoID = repoID;
        this.parentDir = parentDir;
        this.account = account;
    }

    private DataManager getDataManager() {
        if (dataManager == null) {
            dataManager = new DataManager(account);
        }

        return dataManager;
    }

    @Override
    protected View createDialogContentView(LayoutInflater inflater, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.dialog_new_dir, null);
        dirNameText = (EditText) view.findViewById(R.id.new_dir_name);

        if (savedInstanceState != null) {
            repoID = savedInstanceState.getString(STATE_TASK_REPO_ID);
            parentDir = savedInstanceState.getString(STATE_TASK_PARENT_DIR);
            account = (Account)savedInstanceState.getParcelable(STATE_ACCOUNT);
        }

        return view;
    }

    @Override
    protected void onDialogCreated(Dialog dialog) {
        setTitle(getResources().getString(R.string.create_new_dir));
        //dialog.setTitle(getActivity().getString(R.string.create_new_dir));
    }

    @Override
    protected void onValidateUserInput() throws Exception {
        String dirName = dirNameText.getText().toString().trim();

        if (dirName.length() == 0) {
            String err = getActivity().getResources().getString(R.string.dir_name_empty);
            throw new Exception(err);
        }
    }

    @Override
    protected void onSaveDialogContentState(Bundle outState) {
        outState.putString(STATE_TASK_PARENT_DIR, parentDir);
        outState.putString(STATE_TASK_REPO_ID, repoID);
        outState.putParcelable(STATE_ACCOUNT, account);
    }

    @Override
    protected void disableInput() {
        super.disableInput();
        dirNameText.setEnabled(false);
    }

    @Override
    protected void enableInput() {
        super.enableInput();
        dirNameText.setEnabled(true);
    }

    @Override
    protected NewDirTask prepareTask() {
        EditText dirNameText = (EditText)getContentView().findViewById(R.id.new_dir_name);
        String dirName = dirNameText.getText().toString().trim();
        NewDirTask task = new NewDirTask(repoID, parentDir, dirName, getDataManager());
        return task;
    }
}


text:
FOUNDATION_EXPORT double PanelControllerVersionNumber;
FOUNDATION_EXPORT const unsigned char PanelControllerVersionString[];


text:
title:  Uctievanie Hospodina
date:   30/11/2019
---

### Texty na tento týždeň
Neh 12,27–47; 1Kron 25,6–8; 1Ján 1,7–9; Ján 1,29.36; 1Kor 5,7; Heb 9,1–11

>
Základný text

> Striedavo chválili a velebili Hospodina spevom: Lebo je dobrý, lebo jeho milosrdenstvo trvá naveky nad Izraelom. Všetok ľud sa ozýval veľkým jasotom a chválil Hospodina, že bol položený základ Hospodinovho domu.  (Ezd 3,11)

Základný text na tento týždeň nám ukazuje hlbší pohľad na spôsob, akým prebiehala židovská bohoslužba. Vidíme v nej vďačnosť voči Bohu a srdcia naplnené radosťou a chválou.

V roku 515 pred Kr. Izraeliti slávili zasvätenie chrámu (Ezd 6,15–18). Približne o šesťdesiat rokov neskôr národ uskutočnil vysviacku Jeruzalema a dokončených hradieb (Neh 6,15–7,3; 12,27n).

Po uvedení rodokmeňov v 11. a 12. kapitole knihy Nehemiáš sa autor sústreďuje na čas, keď sa konala vysviacka mesta. Zaznamenané oslavy však nie sú v chronologickom poradí. Neuskutočnili sa teda v čase prisťahovania do Jeruzalema, ale až keď boli dokončené hradby. Pre národ bolo príznačné, že všetko zasväcoval Bohu – chrám, mestské hradby alebo dokonca domy či verejné budovy. Takéto zasvätenia boli dôkladne pripravené. Súčasťou osláv boli prejavy radosti, spev, hudba, hodovanie, obete, všeobecné veselie, ale aj očisťovanie ľudu. Dávid ustanovil počas zasvätenia prax obetovania a židovskí vodcovia nasledovali jeho príklad – počnúc Šalamúnom, keď sa podarilo priniesť do chrámu truhlu zmluvy (1Kráľ 8,5).

Tento týždeň sa budeme venovať spôsobu, akým Izraeliti uctievali Hospodina v čase návratu z exilu. Zároveň budeme hľadať možnosti, ako sa inšpirovať ich konaním v našom uctievaní toho istého Boha.


text:
package rpc

import (
	"fmt"
	"io"
	"math/rand"
	"net"
	"net/rpc"
	"os"
	"time"

	"github.com/cockroachdb/cockroach/roachpb"
	"github.com/cockroachdb/cockroach/util"
	"github.com/cockroachdb/cockroach/util/log"
	"github.com/cockroachdb/cockroach/util/retry"
	"github.com/cockroachdb/cockroach/util/tracer"
	"github.com/gogo/protobuf/proto"
)

// TODO(pmattis): This code is only used by kv.DistSender. Perhaps move it to
// the kv package. We might also want to de-generalize it so that it knows
// about the types of the request and response protos
// (Batch{Request,Response}).

// OrderingPolicy is an enum for ordering strategies when there
// are multiple endpoints available.
type OrderingPolicy int

const (
	// OrderStable uses endpoints in the order provided.
	OrderStable = iota
	// OrderRandom randomly orders available endpoints.
	OrderRandom
)

// An Options structure describes the algorithm for sending RPCs to
// one or more replicas, depending on error conditions and how many
// successful responses are required.
type Options struct {
	// Ordering indicates how the available endpoints are ordered when
	// deciding which to send to (if there are more than one).
	Ordering OrderingPolicy
	// SendNextTimeout is the duration after which RPCs are sent to
	// other replicas in a set.
	SendNextTimeout time.Duration
	// Timeout is the maximum duration of an RPC before failure.
	// 0 for no timeout.
	Timeout time.Duration
	// If not nil, information about the request is added to this trace.
	Trace *tracer.Trace
}

// An rpcError indicates a failure to send the RPC. rpcErrors are
// retryable.
type rpcError struct {
	error
}

func newRPCError(err error) rpcError {
	return rpcError{err}
}

// CanRetry implements the Retryable interface.
// TODO(tschottdorf): the way this is used by rpc/send suggests that it
// may be better if these weren't retriable - they are returned when the
// connection fails, i.e. for example when a node is down or the network
// fails. Retrying on such errors keeps the caller waiting for a long time
// and without a positive outlook.
func (r rpcError) CanRetry() bool { return true }

// NewSendError creates a SendError. canRetry should be true in most
// cases; the only non-retryable SendErrors are for things like
// malformed (and not merely unresolvable) addresses.
func NewSendError(msg string, canRetry bool) *roachpb.SendError {
	return &roachpb.SendError{Message: msg, Retryable: canRetry}
}

// Send sends one or more method RPCs to clients specified by the slice of
// endpoint addrs. Arguments for methods are obtained using the supplied
// getArgs function. Reply structs are obtained through the getReply()
// function. On success, Send returns the first successful reply. Otherwise,
// Send returns an error if and as soon as the number of failed RPCs exceeds
// the available endpoints less the number of required replies.
func Send(opts Options, method string, addrs []net.Addr, getArgs func(addr net.Addr) proto.Message,
	getReply func() proto.Message, context *Context) (proto.Message, error) {
	trace := opts.Trace // not thread safe!

	if len(addrs) < 1 {
		return nil, NewSendError(
			fmt.Sprintf("insufficient replicas (%d) to satisfy send request of %d",
				len(addrs), 1), false)
	}

	done := make(chan *rpc.Call, len(addrs))

	var clients []*Client
	for _, addr := range addrs {
		clients = append(clients, NewClient(addr, context))
	}

	var orderedClients []*Client
	switch opts.Ordering {
	case OrderStable:
		orderedClients = clients
	case OrderRandom:
		// Randomly permute order, but keep known-unhealthy clients last.
		var healthy, unhealthy []*Client
		for _, client := range clients {
			select {
			case <-client.Healthy():
				healthy = append(healthy, client)
			default:
				unhealthy = append(unhealthy, client)
			}
		}
		for _, idx := range rand.Perm(len(healthy)) {
			orderedClients = append(orderedClients, healthy[idx])
		}
		for _, idx := range rand.Perm(len(unhealthy)) {
			orderedClients = append(orderedClients, unhealthy[idx])
		}
	}
	// TODO(spencer): going to need to also sort by affinity; closest
	// ping time should win. Makes sense to have the rpc client/server
	// heartbeat measure ping times. With a bit of seasoning, each
	// node will be able to order the healthy replicas based on latency.

	// Send the first request.
	sendOneFn(orderedClients[0], opts.Timeout, method, getArgs, getReply, trace, done)
	orderedClients = orderedClients[1:]

	var errors, retryableErrors int

	// Wait for completions.
	for {
		select {
		case call := <-done:
			if call.Error == nil {
				// Verify response data integrity if this is a proto response.
				if req, reqOk := call.Args.(roachpb.Request); reqOk {
					if resp, respOk := call.Reply.(roachpb.Response); respOk {
						if err := resp.Verify(req); err != nil {
							call.Error = err
						}
					} else {
						call.Error = util.Errorf("response to proto request must be a proto")
					}
				}
			}
			err := call.Error
			if err == nil {
				if log.V(2) {
					log.Infof("%s: successful reply: %+v", method, call.Reply)
				}

				return call.Reply.(proto.Message), nil
			}

			// Error handling.
			if log.V(1) {
				log.Warningf("%s: error reply: %s", method, err)
			}

			errors++

			// Since we have a reconnecting client here, disconnect errors are retryable.
			disconnected := err == rpc.ErrShutdown || err == io.ErrUnexpectedEOF
			if retryErr, ok := err.(retry.Retryable); disconnected || (ok && retryErr.CanRetry()) {
				retryableErrors++
			}

			if remainingNonErrorRPCs := len(addrs) - errors; remainingNonErrorRPCs < 1 {
				return nil, NewSendError(
					fmt.Sprintf("too many errors encountered (%d of %d total): %v",
						errors, len(clients), err), remainingNonErrorRPCs+retryableErrors >= 1)
			}
			// Send to additional replicas if available.
			if len(orderedClients) > 0 {
				trace.Event("error, trying next peer")
				sendOneFn(orderedClients[0], opts.Timeout, method, getArgs, getReply, trace, done)
				orderedClients = orderedClients[1:]
			}

		case <-time.After(opts.SendNextTimeout):
			// On successive RPC timeouts, send to additional replicas if available.
			if len(orderedClients) > 0 {
				trace.Event("timeout, trying next peer")
				sendOneFn(orderedClients[0], opts.Timeout, method, getArgs, getReply, trace, done)
				orderedClients = orderedClients[1:]
			}
		}
	}
}

// Allow local calls to be dispatched directly to the local server without
// sending an RPC.
//
// TODO(pmattis): We should either always enable local calls or remove this
// support. Revisit once the current performance work has completed.
var enableLocalCalls = os.Getenv("ENABLE_LOCAL_CALLS") == "1"

// sendOneFn is overwritten in tests to mock sendOne.
var sendOneFn = sendOne

// sendOne invokes the specified RPC on the supplied client when the
// client is ready. On success, the reply is sent on the channel;
// otherwise an error is sent.
//
// Do not call directly, but instead use sendOneFn. Tests mock out this method
// via sendOneFn in order to test various error cases.
func sendOne(client *Client, timeout time.Duration, method string,
	getArgs func(addr net.Addr) proto.Message, getReply func() proto.Message,
	trace *tracer.Trace, done chan *rpc.Call) {

	addr := client.RemoteAddr()
	args := getArgs(addr)
	if args == nil {
		done <- &rpc.Call{Error: newRPCError(
			util.Errorf("nil arguments returned for client %s", addr))}
		return
	}

	if log.V(2) {
		log.Infof("%s: sending request to %s: %+v", method, addr, args)
	}
	trace.Event(fmt.Sprintf("sending to %s", addr))

	if enableLocalCalls && client.localServer != nil {
		if localCall(client.localServer, method, args, done) {
			return
		}
	}

	reply := getReply()

	// Don't bother firing off a goroutine in the common case where a client
	// is already healthy.
	select {
	case <-client.Healthy():
		client.Go(method, args, reply, done)
		return
	default:
	}

	go func() {
		var timeoutChan <-chan time.Time
		if timeout != 0 {
			timeoutChan = time.After(timeout)
		}
		select {
		case <-client.Healthy():
			client.Go(method, args, reply, done)
		case <-client.Closed:
			done <- &rpc.Call{Error: newRPCError(
				util.Errorf("rpc to %s failed as client connection was closed", method))}
		case <-timeoutChan:
			done <- &rpc.Call{Error: newRPCError(
				util.Errorf("rpc to %s: client not ready after %s", method, timeout))}
		}
	}()
}

// localCall invokes the specified method directly. Returns false if the method
// is public and cannot be served with a local call.
func localCall(s *Server, method string, args proto.Message, done chan *rpc.Call) bool {
	s.mu.RLock()
	m := s.methods[method]
	s.mu.RUnlock()

	if m.handler == nil {
		done <- &rpc.Call{
			Error: newRPCError(util.Errorf("rpc:couldn't find method: %s", method)),
		}
		return true
	}

	if m.public {
		return false
	}

	// TODO(pmattis): Note that we're passing the request directly through to the
	// handler. This differs from an actual RPC which would encode the request
	// and decode it on the remote side. The result is that the method handler
	// might mutate the request which in turn might surprise the caller. We
	// should add a check to guard against that.
	m.handler(args, func(reply proto.Message, err error) {
		done <- &rpc.Call{
			ServiceMethod: method,
			Error:         err,
			Reply:         reply,
			Args:          args,
		}
	})
	return true
}


text:
<!DOCTYPE html>

  <meta charset="UTF-8">

  <title>CodePen - A Pen by  Captain Anonymous</title>

    <link rel="stylesheet" href="css/style.css">

  <!DOCTYPE html>

<title>
Intro to Programming March 2015
</title>
<link rel="stylesheet" type="text/css" href="style.css">

Frederic Lamoulie's Nanodegree Notes

Introduction to Web & HTML

Basics

A web page is a text document written in a language called HTML. Web browsers read these documents, and then interpret and display them.

HTML stands for hypertext markup language. More details here.

HTML = language = syntax + rules.

A tag links to Elements that form a tree ; DOM (Document Object Model) is a standard convention for representing and interacting with elements in HTML.

An element is created from the opening tag to the closing tag and everything in between is considered content.

Content can be empty/text/ or another element.All tags have attributes & values.

Coding happens when programmers write text in a language that a computer can understand. The computer can then follow the instructions the programmer wrote.

Programmers need to write exactly the way a computer understands (also known as writing with correct "syntax").

HTML Vocabulary

Tag:

An HTML tag is always contained within angled brackets. Most tags have an opening tag and a closing tag. Some tags (called "void" tags) do not require a closing tag.

Element:

An HTML element refers to everything within a set of opening and closing tags.

Attribute:

This is a property of an HTML element. For example,  Udacity

Inline vs Block Elements:

HTML elements are either inline or block. Block elements form an "invisible box" around the content inside of them.

Introduction to CSS

Basics

What is CSS?

CSS stands for "Cascading Style Sheets". It is a language that helps you define the style of the page.

Similarly as HTML, CSS = specific syntax + rules and allows you to change how elements look on the page (font size, colour, background, position etc.). In CSS, the most specific rule applies.

CSS Boxes

We define boxes with Div tags and create as many Div tags as boxes. You need to use class names so as to know the purpose of each box just by glancing at the code.

When you read an HTML document as text, there are changes of indentations: the more indented an element is, the more deeply nested

The concept of Inheritance

Inheritance is a key feature in CSS, it relies on the ancestor-descendant relationship to operate. Inheritance is the mechanism by which properties are applied not only to a specified element, but also to its descendants.

Example of CSS Rules

Change background = background-color: (A) for attribute

Add style to certain sections (h1), use div class

How to include CSS Styling in the web page

Method 1 consists in writing CSS in the head of the HTML. A reasonable approach for small projects only.

Method 2 consists in linking your HTML to a separate CSS file. Much better for larger projetcs.

Method 3 consists in writing the style inline with the HTML. Considered not ideal because of code repetition.

Advanced

Advanced details on CSS Boxes

Center: Content & nucleus

Padding: Clears an area around the content, affected by background colour of the box. Space inside the box that protects the content directly.

Border: goes around the padding & content. Inherited from the colour property of the box.

Margin: Outer layer, clears an area around the border. No background colour, space between boxes.

Pixels VS %: You can set sizes of the box as pixels or percentages. As a percentage, its size will change based on large /small the screen is while in pixels, size won't change.

Boxing & Positioning

Each box has 4 components.There are two techniques you can use to help deal with sizing issues:

Set sizes in terms of percents rather than pixels.

Set the box-sizing attribute to border-box for every element.

Regarding Box positioning:

Divs are block elements (as opposed to inline), so by default they take up the entire width of a page.

Adding the rule display: flex; to the appropriate CSS will override this behavior and let divs appear next to each other.

REMINDER: Code, Test & Refine

Always look for natural boxes

Look for repeated styles & semantic elements

Write your HTML

Apply Style (from BIG to small)

Fix Things


text:
Tailwind
========

Tailwind is a code coverage utility for JavaScript that runs in the browser. It works by importing the target script and uses [Esprima](http://esprima.org/) with [Escodegen](https://github.com/Constellation/escodegen) to identify which statements and branching should be watched. Analytics about the code coverage can then be polled in real-time and used to generated reports.

Tailwind is most effective when combined with a testing framework like [mocha](http://mochajs.org/).

Example
-------
This code is from the `test_tailwind.html` file in the `tests` directory.
```javascript
// Instruct Tailwind to include the test_script.js file into the page and monitor its execution
Tailwind.runScript(
    'lib/test_script.js',
    function( stats ) // The stats variable provides access to real-time code coverage statistics
    {
        // Run mocha, the testing framework
        mocha.run(
            function()
            {
                // After the tests have run, generate an HTML report showing what statements were executed
                document.getElementById( 'coverage' ).innerHTML = Tailwind.Reporters.html( stats );
            }
        );
    }
);
```

Testing Tailwind
----------------
The tests included in this repository cannot be run from the filesystem because Tailwind includes specified scripts through an ajax request. A quick workaround is to navigate to the Tailwind directory in a console window and start up a python server with `python -m SimpleHTTPServer`. The test will then be accessible at `http://localhost:8000/tests/test_tailwind.html`.

Want to Contribute?
-------------------
Please read our [Code Standards & Guidelines](https://docs.google.com/a/sympoz.com/document/d/1c83xlVHpPxMd-ISZlu-4Rzpi7EbdopV_mmKjcYEQiz4/pub)


text:
using ResourceMap = std::map<std::string, int, std::less<>>;

// Loads mapping of resources identifiers from headers generated by
// grit at paths specified in `headers`.
absl::optional<ResourceMap> LoadResourcesFromGritHeaders(
    const std::vector<base::FilePath>& headers);

#endif  // IOS_CHROME_TOOLS_STRINGS_GRIT_HEADER_PARSING_H_


text:
module Types
  class EveAllianceType < Types::BaseObject
    description "Eve Alliance object"

    field :id, ID,
      description: "Eve Alliance ID",
      method: :alliance_id,
      null: false

    field :name, String,
      description: "Eve Alliance name",
      null: true

    field :ticker, String,
      description: "Eve Alliance ticker",
      null: true

    field :date_founded, GraphQL::Types::ISO8601DateTime,
      null: true

    field :creator_corporation_id, Integer,
      null: true

    field :creator_corporation, Types::EveCorporationType,
      null: true

    field :creator_id, Integer,
      null: true

    field :creator, Types::EveCharacterType,
      null: true

    field :executor_corporation_id, Integer,
      null: true

    field :executor_corporation, Types::EveCorporationType,
      null: true

    field :faction_id, Integer,
      null: true

    field :faction, Types::EveFactionType,
      null: true

    field :corporations_count, Integer,
      description: "Eve Alliance corporations count",
      null: true

    field :characters_count, Integer,
      description: "Eve Alliance characters count",
      null: true

    field :corporations, Types::EveCorporationType.connection_type,
      description: "Eve Alliance corporations collection",
      null: true

    field :characters, Types::EveCharacterType.connection_type,
      description: "Eve Alliance characters collection",
      null: true

    # TODO: corporation_alliance_histories
    # field :history, [Types::AllianceHistoryType], null: true
  end
end


text:
<title>Random-Number Seed</title>
<link rel="stylesheet" type="text/css" href="pythia.css"/>
<link rel="shortcut icon" href="pythia32.gif"/>

Random-Number Seed

The seed of the random number generator can be set as follows:

flag   Random:setSeed
 (default = off)

Indicates whether a user-set seed should be used every time the
Pythia::init routine is called. If off, the random number
generator is initialized with its default seed at the beginning
of the run, and never again. If on, each new Pythia::init
call (should several be made in the same run) results in the random
number being re-initialized, thereby possibly starting over with the
same sequence, if you do not watch out.

mode   Random:seed
 (default = -1; maximum = 900000000)

The seed to be used, if setSeed is on.

A negative value gives the default seed,

a value 0 gives a random seed based on the time, and

a value between 1 and 900,000,000 a unique different random number
sequence.

For  on random numbers see here.
This includes methods to save and restore the state of the generator,
and some preprogrammed methods to generate non-uniform random numbers.


text:
<?php

namespace Victoire\Bundle\BusinessEntityBundle\Entity;

/**
 * The business Entity.
 */
class BusinessEntity
{
    const CACHE_CLASSES = 'victoire_business_entity_classes';
    const CACHE_WIDGETS = 'victoire_business_entity_widgets';

    protected $id = null;
    protected $class = null;
    protected $name = null;
    protected $businessProperties = [];
    protected $disable = false;

    public static function __set_state($array)
    {
        $businessEntity = new self();
        $businessEntity->setId($array['id']);
        $businessEntity->setClass($array['class']);
        $businessEntity->setName($array['name']);
        $businessEntity->setBusinessProperties($array['businessProperties']);
        $businessEntity->setDisable($array['disable']);

        return $businessEntity;
    }

    /**
     * Get the id.
     *
     * @return string The id
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set the id.
     *
     * @param string $id
     */
    public function setId($id)
    {
        $this->id = $id;
    }

    /**
     * Get the name.
     *
     * @return string The name
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set the name.
     *
     * @param string $name
     */
    public function setName($name)
    {
        $this->name = $name;
    }

    /**
     * Get the class.
     *
     * @return string The class
     */
    public function getClass()
    {
        return $this->class;
    }

    /**
     * Set the class.
     *
     * @param string $class
     */
    public function setClass($class)
    {
        $this->class = $class;
    }

    /**
     * Is disable.
     *
     * @return bool
     */
    public function isDisable()
    {
        return $this->disable;
    }

    /**
     * Set disable.
     *
     * @param bool $disable
     */
    public function setDisable($disable)
    {
        $this->disable = $disable;
    }

    /**
     * Set disable if BusinessEntity dont have all receiverProperties required.
     *
     * @param array $receiverProperties
     */
    public function setDisableForReceiverProperties($receiverProperties = [])
    {
        foreach ($receiverProperties as $receiverProperty => $value) {
            if (!array_key_exists($receiverProperty, $this->businessProperties)) {
                $this->disable = true;
            }
        }
    }

    /**
     * Add a business property.
     *
     * @param BusinessProperty $businessProperty
     */
    public function addBusinessProperty(BusinessProperty $businessProperty)
    {
        //the type of business property (textable, slideable...)
        $type = $businessProperty->getType();

        if (!isset($this->businessProperties[$type])) {
            $this->businessProperties[$type] = [];
        }

        //add the business property indexed by the type
        $this->businessProperties[$type][] = $businessProperty;
    }

    /**
     * Get the business properties.
     *
     * @return array The business properties
     */
    public function getBusinessProperties()
    {
        return $this->businessProperties;
    }

    /**
     * Get the business properties.
     *
     * @return array The business properties
     */
    public function setBusinessProperties($businessProperties)
    {
        return $this->businessProperties = $businessProperties;
    }

    /**
     * Get the business properties by type.
     *
     * @param string $type
     *
     * @return array The businnes properties
     */
    public function getBusinessPropertiesByType($type)
    {
        $bp = [];

        if (isset($this->businessProperties[$type])) {
            $bp = $this->businessProperties[$type];
        }

        return $bp;
    }
}


text:
require 'rails_helper'

RSpec.describe "election/index.html.haml", :type => :view do
  pending "add some examples to (or delete) #{__FILE__}"
end


text:
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OrmTest
{
    public class DemoF_Utilities
    {
        public static void Init()
        {
            Console.WriteLine("");
            Console.WriteLine("#### Utilities Start ####");

            SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
            {
                DbType = DbType.Sqlite,
                ConnectionString = Config.ConnectionString,
                InitKeyType = InitKeyType.Attribute,
                IsAutoCloseConnection = true,
                AopEvents = new AopEvents
                {
                    OnLogExecuting = (sql, p) =>
                    {
                        Console.WriteLine(sql);
                        Console.WriteLine(string.Join(",", p?.Select(it => it.ParameterName + ":" + it.Value)));
                    }
                }
            });

            List<int> ids = Enumerable.Range(1, 100).ToList();
            db.Utilities.PageEach(ids, 10, list =>
            {
                Console.WriteLine(string.Join("," ,list));
            });

            var list2= db.Utilities.DataTableToList<Order>(db.Ado.GetDataTable("select * from `order`"));

            //more https://github.com/sunkaixuan/SqlSugar/wiki/f.Utilities
            Console.WriteLine("#### Utilities End ####");
        }
    }
}