text:
package com.android.email;

import com.android.emailcommon.Logging;
import com.android.emailcommon.mail.MessagingException;
import com.android.emailcommon.utility.Utility;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.util.Log;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;

/**
 * Class that handles "refresh" (and "send pending messages" for outboxes) related functionalities.
 *
 *
This class is responsible for two things:
 *

 *
Taking refresh requests of mailbox-lists and message-lists and the "send outgoing
 *       messages" requests from UI, and calls appropriate methods of {@link Controller}.
 *       Note at this point the timer-based refresh
 *       (by {@link com.android.email.service.MailService}) uses {@link Controller} directly.
 *
Keeping track of which mailbox list/message list is actually being refreshed.
 *

 * Refresh requests will be ignored if a request to the same target is already requested, or is
 * already being refreshed.
 *
 *
Conceptually it can be a part of {@link Controller}, but extracted for easy testing.
 *
 * (All public methods must be called on the UI thread.  All callbacks will be called on the UI
 * thread.)
 */
public class RefreshManager {
    private static final boolean LOG_ENABLED = false; // DONT SUBMIT WITH TRUE
    private static final long MAILBOX_AUTO_REFRESH_INTERVAL = 5 * 60 * 1000; // in milliseconds
    private static final long MAILBOX_LIST_AUTO_REFRESH_INTERVAL = 5 * 60 * 1000; // in milliseconds

    private static RefreshManager sInstance;

    private final Clock mClock;
    private final Context mContext;
    private final Controller mController;
    private final Controller.Result mControllerResult;

    /** Last error message */
    private String mErrorMessage;

    public interface Listener {
        /**
         * Refresh status of a mailbox list or a message list has changed.
         *
         * @param accountId ID of the account.
         * @param mailboxId -1 if it's about the mailbox list, or the ID of the mailbox list in
         * question.
         */
        public void onRefreshStatusChanged(long accountId, long mailboxId);

        /**
         * Error callback.
         *
         * @param accountId ID of the account, or -1 if unknown.
         * @param mailboxId ID of the mailbox, or -1 if unknown.
         * @param message error message which can be shown to the user.
         */
        public void onMessagingError(long accountId, long mailboxId, String message);
    }

    private final ArrayList<Listener> mListeners = new ArrayList<Listener>();

    /**
     * Status of a mailbox list/message list.
     */
    /* package */ static class Status {
        /**
         * True if a refresh of the mailbox is requested, and not finished yet.
         */
        private boolean mIsRefreshRequested;

        /**
         * True if the mailbox is being refreshed.
         *
         * Set true when {@link #onRefreshRequested} is called, i.e. refresh is requested by UI.
         * Note refresh can occur without a request from UI as well (e.g. timer based refresh).
         * In which case, {@link #mIsRefreshing} will be true with {@link #mIsRefreshRequested}
         * being false.
         */
        private boolean mIsRefreshing;

        private long mLastRefreshTime;

        public boolean isRefreshing() {
            return mIsRefreshRequested || mIsRefreshing;
        }

        public boolean canRefresh() {
            return !isRefreshing();
        }

        public void onRefreshRequested() {
            mIsRefreshRequested = true;
        }

        public long getLastRefreshTime() {
            return mLastRefreshTime;
        }

        public void onCallback(MessagingException exception, int progress, Clock clock) {
            if (exception == null && progress == 0) {
                // Refresh started
                mIsRefreshing = true;
            } else if (exception != null || progress == 100) {
                // Refresh finished
                mIsRefreshing = false;
                mIsRefreshRequested = false;
                mLastRefreshTime = clock.getTime();
            }
        }
    }

    /**
     * Map of accounts/mailboxes to {@link Status}.
     */
    private static class RefreshStatusMap {
        private final HashMap<Long, Status> mMap = new HashMap<Long, Status>();

        public Status get(long id) {
            Status s = mMap.get(id);
            if (s == null) {
                s = new Status();
                mMap.put(id, s);
            }
            return s;
        }

        public boolean isRefreshingAny() {
            for (Status s : mMap.values()) {
                if (s.isRefreshing()) {
                    return true;
                }
            }
            return false;
        }
    }

    private final RefreshStatusMap mMailboxListStatus = new RefreshStatusMap();
    private final RefreshStatusMap mMessageListStatus = new RefreshStatusMap();

    /**
     * @return the singleton instance.
     */
    public static synchronized RefreshManager getInstance(Context context) {
        if (sInstance == null) {
            sInstance = new RefreshManager(context, Controller.getInstance(context),
                    Clock.INSTANCE, new Handler());
        }
        return sInstance;
    }

    protected RefreshManager(Context context, Controller controller, Clock clock,
            Handler handler) {
        mClock = clock;
        mContext = context.getApplicationContext();
        mController = controller;
        mControllerResult = new ControllerResultUiThreadWrapper<ControllerResult>(
                handler, new ControllerResult());
        mController.addResultCallback(mControllerResult);
    }

    /**
     * MUST be called for mock instances.  (The actual instance is a singleton, so no cleanup
     * is necessary.)
     */
    public void cleanUpForTest() {
        mController.removeResultCallback(mControllerResult);
    }

    public void registerListener(Listener listener) {
        if (listener == null) {
            throw new IllegalArgumentException();
        }
        mListeners.add(listener);
    }

    public void unregisterListener(Listener listener) {
        if (listener == null) {
            throw new IllegalArgumentException();
        }
        mListeners.remove(listener);
    }

    /**
     * Refresh the mailbox list of an account.
     */
    public boolean refreshMailboxList(long accountId) {
        final Status status = mMailboxListStatus.get(accountId);
        if (!status.canRefresh()) return false;

        if (LOG_ENABLED) {
            Log.d(Logging.LOG_TAG, "refreshMailboxList " + accountId);
        }
        status.onRefreshRequested();
        notifyRefreshStatusChanged(accountId, -1);
        mController.updateMailboxList(accountId);
        return true;
    }

    public boolean isMailboxStale(long mailboxId) {
        return mClock.getTime() >= (mMessageListStatus.get(mailboxId).getLastRefreshTime()
                + MAILBOX_AUTO_REFRESH_INTERVAL);
    }

    public boolean isMailboxListStale(long accountId) {
        return mClock.getTime() >= (mMailboxListStatus.get(accountId).getLastRefreshTime()
                + MAILBOX_LIST_AUTO_REFRESH_INTERVAL);
    }

    /**
     * Refresh messages in a mailbox.
     */
    public boolean refreshMessageList(long accountId, long mailboxId, boolean userRequest) {
        return refreshMessageList(accountId, mailboxId, false, userRequest);
    }

    /**
     * "load more messages" in a mailbox.
     */
    public boolean loadMoreMessages(long accountId, long mailboxId) {
        return refreshMessageList(accountId, mailboxId, true, true);
    }

    private boolean refreshMessageList(long accountId, long mailboxId, boolean loadMoreMessages,
            boolean userRequest) {
        final Status status = mMessageListStatus.get(mailboxId);
        if (!status.canRefresh()) return false;

        if (LOG_ENABLED) {
            Log.d(Logging.LOG_TAG, "refreshMessageList " + accountId + ", " + mailboxId + ", "
                    + loadMoreMessages);
        }
        status.onRefreshRequested();
        notifyRefreshStatusChanged(accountId, mailboxId);
        if (loadMoreMessages) {
            mController.loadMoreMessages(mailboxId);
        } else {
            mController.updateMailbox(accountId, mailboxId, userRequest);
        }
        return true;
    }

    /**
     * Send pending messages.
     */
    public boolean sendPendingMessages(long accountId) {
        if (LOG_ENABLED) {
            Log.d(Logging.LOG_TAG, "sendPendingMessages " + accountId);
        }
        notifyRefreshStatusChanged(accountId, -1);
        mController.sendPendingMessages(accountId);
        return true;
    }

    /**
     * Call {@link #sendPendingMessages} for all accounts.
     */
    public void sendPendingMessagesForAllAccounts() {
        if (LOG_ENABLED) {
            Log.d(Logging.LOG_TAG, "sendPendingMessagesForAllAccounts");
        }
        new SendPendingMessagesForAllAccountsImpl()
                .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }

    private class SendPendingMessagesForAllAccountsImpl extends Utility.ForEachAccount {
        public SendPendingMessagesForAllAccountsImpl() {
            super(mContext);
        }

        @Override
        protected void performAction(long accountId) {
            sendPendingMessages(accountId);
        }
    }

    public long getLastMailboxListRefreshTime(long accountId) {
        return mMailboxListStatus.get(accountId).getLastRefreshTime();
    }

    public long getLastMessageListRefreshTime(long mailboxId) {
        return mMessageListStatus.get(mailboxId).getLastRefreshTime();
    }

    public boolean isMailboxListRefreshing(long accountId) {
        return mMailboxListStatus.get(accountId).isRefreshing();
    }

    public boolean isMessageListRefreshing(long mailboxId) {
        return mMessageListStatus.get(mailboxId).isRefreshing();
    }

    public boolean isRefreshingAnyMailboxListForTest() {
        return mMailboxListStatus.isRefreshingAny();
    }

    public boolean isRefreshingAnyMessageListForTest() {
        return mMessageListStatus.isRefreshingAny();
    }

    public String getErrorMessage() {
        return mErrorMessage;
    }

    private void notifyRefreshStatusChanged(long accountId, long mailboxId) {
        for (Listener l : mListeners) {
            l.onRefreshStatusChanged(accountId, mailboxId);
        }
    }

    private void reportError(long accountId, long mailboxId, String errorMessage) {
        mErrorMessage = errorMessage;
        for (Listener l : mListeners) {
            l.onMessagingError(accountId, mailboxId, mErrorMessage);
        }
    }

    /* package */ Collection<Listener> getListenersForTest() {
        return mListeners;
    }

    /* package */ Status getMailboxListStatusForTest(long accountId) {
        return mMailboxListStatus.get(accountId);
    }

    /* package */ Status getMessageListStatusForTest(long mailboxId) {
        return mMessageListStatus.get(mailboxId);
    }

    private class ControllerResult extends Controller.Result {
        private boolean mSendMailExceptionReported = false;

        private String exceptionToString(MessagingException exception) {
            if (exception == null) {
                return "(no exception)";
            } else {
                return MessagingExceptionStrings.getErrorString(mContext, exception);
            }
        }

        /**
         * Callback for mailbox list refresh.
         */
        @Override
        public void updateMailboxListCallback(MessagingException exception, long accountId,
                int progress) {
            if (LOG_ENABLED) {
                Log.d(Logging.LOG_TAG, "updateMailboxListCallback " + accountId + ", " + progress
                        + ", " + exceptionToString(exception));
            }
            mMailboxListStatus.get(accountId).onCallback(exception, progress, mClock);
            if (exception != null) {
                reportError(accountId, -1,
                        MessagingExceptionStrings.getErrorString(mContext, exception));
            }
            notifyRefreshStatusChanged(accountId, -1);
        }

        /**
         * Callback for explicit (user-driven) mailbox refresh.
         */
        @Override
        public void updateMailboxCallback(MessagingException exception, long accountId,
                long mailboxId, int progress, int dontUseNumNewMessages,
                ArrayList<Long> addedMessages) {
            if (LOG_ENABLED) {
                Log.d(Logging.LOG_TAG, "updateMailboxCallback " + accountId + ", "
                        + mailboxId + ", " + progress + ", " + exceptionToString(exception));
            }
            updateMailboxCallbackInternal(exception, accountId, mailboxId, progress, 0);
        }

        /**
         * Callback for implicit (timer-based) mailbox refresh.
         *
         * Do the same as {@link #updateMailboxCallback}.
         * TODO: Figure out if it's really okay to do the same as updateMailboxCallback.
         * If both the explicit refresh and the implicit refresh can run at the same time,
         * we need to keep track of their status separately.
         */
        @Override
        public void serviceCheckMailCallback(
                MessagingException exception, long accountId, long mailboxId, int progress,
                long tag) {
            if (LOG_ENABLED) {
                Log.d(Logging.LOG_TAG, "serviceCheckMailCallback " + accountId + ", "
                        + mailboxId + ", " + progress + ", " + exceptionToString(exception));
            }
            updateMailboxCallbackInternal(exception, accountId, mailboxId, progress, 0);
        }

        private void updateMailboxCallbackInternal(MessagingException exception, long accountId,
                long mailboxId, int progress, int dontUseNumNewMessages) {
            // Don't use dontUseNumNewMessages.  serviceCheckMailCallback() don't set it.
            mMessageListStatus.get(mailboxId).onCallback(exception, progress, mClock);
            if (exception != null) {
                reportError(accountId, mailboxId,
                        MessagingExceptionStrings.getErrorString(mContext, exception));
            }
            notifyRefreshStatusChanged(accountId, mailboxId);
        }

        /**
         * Send message progress callback.
         *
         * We don't keep track of the status of outboxes, but we monitor this to catch
         * errors.
         */
        @Override
        public void sendMailCallback(MessagingException exception, long accountId, long messageId,
                int progress) {
            if (LOG_ENABLED) {
                Log.d(Logging.LOG_TAG, "sendMailCallback " + accountId + ", "
                        + messageId + ", " + progress + ", " + exceptionToString(exception));
            }
            if (progress == 0 && messageId == -1) {
                mSendMailExceptionReported = false;
            }
            if (exception != null && !mSendMailExceptionReported) {
                // Only the first error in a batch will be reported.
                mSendMailExceptionReported = true;
                reportError(accountId, messageId,
                        MessagingExceptionStrings.getErrorString(mContext, exception));
            }
            if (progress == 100) {
                mSendMailExceptionReported = false;
            }
        }
    }
}


text:
This is a very simple, synchronous Minecraft and Minecraft Pocket Edition (Minecraft PE, Pocketmine) RCON client, implemented to [these specs](http://wiki.vg/Rcon).

[cli/main.go](cli/main.go) implements a REPL CLI as an example of how to use the client.

# Shortcomings
- Synchronous.
- Long (split) responses from server aren't handled correctly.
- Probably a lot more.

# License
See the [LICENSE](LICENSE) file.

redpajama_set_name: RedPajamaGithub


text:
import json
from datetime import datetime

from dojo.models import Finding

class JFrogXrayUnifiedParser(object):
    """JFrog Xray JSON reports"""

    def get_scan_types(self):
        return ["JFrog Xray Unified Scan"]

    def get_label_for_scan_types(self, scan_type):
        return scan_type

    def get_description_for_scan_types(self, scan_type):
        return "Import Xray Unified (i.e. Xray version 3+) findings in JSON format."

    def get_findings(self, json_output, test):
        tree = json.load(json_output)
        return self.get_items(tree, test)

    def get_items(self, tree, test):
        items = []
        if 'rows' in tree:
            vulnerabilityTree = tree['rows']

            for node in vulnerabilityTree:
                item = get_item(node, test)

                items.append(item)

        return items

def get_item(vulnerability, test):
    # Some items have multiple CVEs for some reason, so get the CVE with the highest CVSSv3 score.
    # Note: the xray v2 importer just took the first CVE in the list, that doesn't seem ideal though
    highestCvssV3Index = 0
    highestCvssV3Score = 0

    for thisCveIndex in range(0, len(vulnerability['cves']) - 1):
        # not all cves have cvssv3 scores, so skip these. If no v3 scores, we'll default to index 0
        if 'cvss_v3_score' in vulnerability['cves'][thisCveIndex]:
            thisCvssV3Score = vulnerability['cves'][thisCveIndex]['cvss_v3_score']
            if thisCvssV3Score > highestCvssV3Score:
                highestCvssV3Index = thisCveIndex
                highestCvssV3Score = thisCvssV3Score

    # Following the CVSS Scoring per https://nvd.nist.gov/vuln-metrics/cvss
    if 'severity' in vulnerability:
        if vulnerability['severity'] == 'Unknown':
            severity = "Info"
        else:
            severity = vulnerability['severity'].title()
    # TODO: Needs UNKNOWN new status in the model.
    else:
        severity = "Info"

    cveIndex = highestCvssV3Index

    vulnerability_id = None
    cvss_v3 = "No CVSS v3 score."  # for justification field
    cvssv3 = None  # for actual cvssv3 field
    cvss_v2 = "No CVSS v2 score."
    mitigation = None
    extra_desc = ""

    cves = vulnerability.get('cves', [])
    if len(cves) > 0:
        worstCve = cves[cveIndex]
        if 'cve' in cves[cveIndex]:
            vulnerability_id = worstCve['cve']
        if 'cvss_v3_vector' in worstCve:
            cvss_v3 = worstCve['cvss_v3_vector']
            cvssv3 = cvss_v3
        if 'cvss_v2_vector' in worstCve:
            cvss_v2 = worstCve['cvss_v2_vector']

    if 'fixed_versions' in vulnerability and len(vulnerability['fixed_versions']) > 0:
        mitigation = "Versions containing a fix:\n"
        mitigation = mitigation + "\n".join(vulnerability['fixed_versions'])

    if 'external_advisory_source' in vulnerability and 'external_advisory_severity' in vulnerability:
        extra_desc = vulnerability['external_advisory_source'] + ": " + vulnerability['external_advisory_severity']

    if vulnerability['issue_id']:
        title = vulnerability['issue_id'] + " - " + vulnerability['summary']
    else:
        title = vulnerability['summary']

    references = "\n".join(vulnerability['references'])

    scan_time = datetime.strptime(vulnerability['artifact_scan_time'], "%Y-%m-%dT%H:%M:%S%z")

    # component has several parts separated by colons. Last part is the version, everything else is the name
    splitComponent = vulnerability['vulnerable_component'].split(':')
    component_name = ":".join(splitComponent[:-1])
    component_version = splitComponent[-1:][0]
    # remove package type from component name
    component_name = component_name.split("://", 1)[1]

    tags = ["packagetype_" + vulnerability['package_type']]

    # create the finding object
    finding = Finding(
        title=title,
        test=test,
        severity=severity,
        description=(vulnerability['description'] + "\n\n" + extra_desc).strip(),
        mitigation=mitigation,
        component_name=component_name,
        component_version=component_version,
        file_path=vulnerability['path'],
        severity_justification="CVSS v3 base score: {}\nCVSS v2 base score: {}".format(cvss_v3, cvss_v2),
        static_finding=True,
        dynamic_finding=False,
        references=references,
        impact=severity,
        cvssv3=cvssv3,
        date=scan_time,
        unique_id_from_tool=vulnerability['issue_id'],
        tags=tags)

    if vulnerability_id:
        finding.unsaved_vulnerability_ids = [vulnerability_id]

    return finding


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using UnityEngine;

namespace SR_PluginLoader
{
    [Flags]
    public enum TextureOpFlags
    {
        None = (1 << 0),
        /// <summary>
        /// Doesnt disable mipmap generation, but rather sets the mipmap bias to a negative value such that nothing but the highest mipmap level is used (the texture originally uploaded)
        /// </summary>
        NO_MIPMAPPING = (1 << 1),
        /// <summary>
        /// Sets the texture wrap mode to CLAMP so it does not repeat.
        /// </summary>
        NO_WRAPPING = (1 << 2),
    }
    /// <summary>
    /// Assists with common tasks for loading textures into unity.
    /// </summary>
    public static class TextureHelper
    {
        private static int randIdx = 0;
        #region Common Textures
        private static Texture2D _transparent = null;
        public static Texture TRANSPARENT { get { if (_transparent == null) { _transparent = new Texture2D(1, 1); _transparent.SetPixel(0, 0, new Color(1f, 1f, 1f, 0f)); _transparent.Apply(); } return _transparent; } }

        public static Texture2D icon_unknown = null;
        public static Texture2D icon_alert = null;
        public static Texture2D icon_close = null;
        public static Texture2D icon_close_dark = null;
        public static Texture2D icon_logo = null;
        public static Texture2D icon_logo_sad = null;
        public static Texture2D icon_checkbox = null;
        public static Texture2D icon_checkmark = null;
        public static Texture2D icon_arrow_left = null;
        public static Texture2D icon_arrow_right = null;
        public static Texture2D icon_node_arrow_right = null;
        public static Texture2D icon_node_arrow_down = null;
        #endregion

        #region Public Functions

        /// <summary>
        /// Assists in loading a texture from a file that is an embedded resource.
        /// </summary>
        /// <param name="name">The embedded resource name.</param>
        /// <param name="namespace_str">The main namespace of the calling Assembly.</param>
        /// <returns></returns>
        public static Texture Load_From_Resource(string name, string namespace_str)
        {
            string asset_name = String.Format("{0}.Resources.{1}", namespace_str, name);
            using (Stream stream = Assembly.GetCallingAssembly().GetManifestResourceStream(asset_name))
            {
                byte[] data = Util.Read_Stream(stream);
                if (data == null) SLog.Info("UNABLE TO LOAD SPECIFIED RESOURCE: {0}", name);
                return Load(data, name);
            }
        }

        /// <summary>
        /// Assists in loading a texture from a file that is an embedded resource.
        /// </summary>
        /// <param name="name">The embedded resource name.</param>
        /// <param name="namespace_str">The main namespace of the calling Assembly.</param>
        /// <param name="flags">A set of flags from the <c>TextureOpFlags</c> enum.</param>
        /// <returns></returns>
        public static Texture Load_From_Resource(string name, string namespace_str, TextureOpFlags flags)
        {
            string asset_name = String.Format("{0}.Resources.{1}", namespace_str, name);
            using (Stream stream = Assembly.GetCallingAssembly().GetManifestResourceStream(asset_name))
            {
                byte[] data = Util.Read_Stream(stream);
                if (data == null) SLog.Info("UNABLE TO LOAD SPECIFIED RESOURCE: {0}", name);
                return Load(data, flags, name);
            }
        }

        /// <summary>
        /// Assists in loading a texture from a byte array.
        /// </summary>
        public static Texture Load(byte[] data, string name = null)
        {
            if (data == null || data.Length <= 0) return null;

            Texture2D tex = null;
            //Determine our file type
            TextureType type = Identify_Texture_Type(data);
            switch (type)
            {
                case TextureType.DXT:
                    Load_Texture_DXT(out tex, data);
                    break;
                case TextureType.PNG:
                    Load_Texture_Non_DXT(out tex, data);
                    break;
                case TextureType.JPEG:
                    Load_Texture_Non_DXT(out tex, data);
                    break;
                default:
                    throw new NotImplementedException("Unable to determine that the given file was of a supported format!");
            }

            if (tex != null)// Suspected that at some point the 'tex' var would become a bad pointer to another texture and setting filterMode or ansioLevel was causing GUIStyle text character maps to render reallyyyy blurry, distorted, and misaligned. odd.
            {// Likely would indicate a deeper problem elsewhere in the code, we shall see.
                // Just some default's that are nice to have in most cases.
                tex.wrapMode = TextureWrapMode.Repeat;
                //tex.filterMode = FilterMode.Trilinear;
                //tex.anisoLevel = 1;
            }

            if (tex != null && name!=null) tex.name = name;
            return tex;
        }

        /// <summary>
        /// Assists in loading a texture from a stream.
        /// </summary>
        public static Texture Load(Stream stream, string name = null)
        {
            if (stream == null) return null;

            byte[] data = Util.Read_Stream(stream);
            return Load(data, name);
        }

        /// <summary>
        /// Assists in loading a texture from a byte array.
        /// </summary>
        /// <param name="data">The texture file data.</param>
        /// <param name="name">A name to assign the texture instance.</param>
        /// <param name="flags">A set of flags from the <c>TextureOpFlags</c> enum.</param>
        /// <returns></returns>
        public static Texture Load(byte[] data, TextureOpFlags flags, string name = null)
        {
            if (data == null || data.Length <= 0) return null;
            Texture2D tex = (Texture2D)TextureHelper.Load(data, name);
            Enforce_Flags(ref tex, flags);
            return tex;
        }

        internal static void Enforce_Flags(ref Texture2D tex, TextureOpFlags flags)
        {
            if ((flags & TextureOpFlags.NO_MIPMAPPING) == TextureOpFlags.NO_MIPMAPPING) tex.mipMapBias = -(tex.mipmapCount);
            if ((flags & TextureOpFlags.NO_WRAPPING) == TextureOpFlags.NO_WRAPPING) tex.wrapMode = TextureWrapMode.Clamp;
        }

        /// <summary>
        /// Creates a copy of a texture pixel-by-pixel, it's slow but reliable for DEBUG purposes.
        /// </summary>
        public static Texture2D Clone(Texture2D tex)
        {
            Texture2D clone = new Texture2D(tex.width, tex.height, TextureFormat.ARGB32, true);
            for(int x=0; x<tex.width; x++)
            {
                for(int y=0; y<tex.height; y++)
                {
                    clone.SetPixel(x, y, tex.GetPixel(x,y));
                }
            }

            return clone;
        }

        #endregion

        #region Debug
        /// <summary>
        /// A Debugging function, Cycles through all Textures loaded into unity.
        /// </summary>
        public static Texture Get_Next_From_All()
        {
            Texture2D[] all = Resources.FindObjectsOfTypeAll<Texture2D>();
            if ((randIdx + 1) >= all.Length) randIdx = 0;

            return all[randIdx++];
        }
        #endregion

        #region Internal Functions

        internal enum TextureType
        {
            UNKNOWN = 0,
            PNG,
            JPEG,
            DXT,
        }

        internal static readonly byte[] DDS_HEADER = new byte[] { 0x44, 0x44, 0x53, 0x20 };// The series of bytes that indicate a particular file contains DXT encoded image data.
        internal static readonly byte[] PNG_HEADER = new byte[] { 137, 80, 78, 71, 13, 10, 26, 10 };// The series of bytes that would indicate a particular file contians PNG image data.
        internal static readonly byte[] JPEG_MAGIC = new byte[] { 0xFF, 0xD8, 0xFF, 0xE0 };// The magic number that identifies the start of a JPEG header.
        internal static readonly byte[] JPEG_HEADER = new byte[] { 0x4A, 0x46, 0x49, 0x46, 0x00, };// The series of bytes for a JPEG header that would indicate it contains image data and not another type of file.

        internal static TextureType Identify_Texture_Type(byte[] data)
        {
            //Determine our file type
            if (Check_Header(data, DDS_HEADER))// Is it A DDS?
                return TextureType.DXT;
            else if (Check_Header(data, PNG_HEADER))// Is it PNG?
                return TextureType.PNG;
            else if (Check_Header(data, JPEG_MAGIC) && Check_Header(data, JPEG_HEADER, 6))// Is it JPEG?
                return TextureType.JPEG;

            return TextureType.UNKNOWN;
        }

        private static void Load_Texture_Non_DXT(out Texture2D tex, byte[] data)
        {
            tex = new Texture2D(1, 1);
            tex.LoadImage(data);
        }

        private static void Load_Texture_DXT(out Texture2D tex, byte[] ddsBytes)
        {
            byte ddsSizeCheck = ddsBytes[4];
            if (ddsSizeCheck != 124)
                throw new Exception("Invalid DDS DXTn texture. Unable to read");  //this header byte should be 124 for DDS image files

            DDS_HEADER header = Util.BytesToStructure<DDS_HEADER>(ddsBytes);
            uint fourCC = header.pixelFormat.dwFourCC;
            //PLog.Info("DDPF_FOURCC: {0}", fourCC);

            TextureFormat textureFormat = TextureFormat.DXT1;
            if (fourCC == DXT.MAKEFOURCC('D', 'X', 'T', '1')) textureFormat = TextureFormat.DXT1;
            else if (fourCC == DXT.MAKEFOURCC('D', 'X', 'T', '5')) textureFormat = TextureFormat.DXT5;

            if (textureFormat != TextureFormat.DXT1 && textureFormat != TextureFormat.DXT5)
                throw new Exception("Invalid TextureFormat. Only DXT1 and DXT5 formats are supported by this method.");

            int height = ddsBytes[13] * 256 + ddsBytes[12];
            int width = ddsBytes[17] * 256 + ddsBytes[16];

            int DDS_HEADER_SIZE = 128;
            byte[] dxtBytes = new byte[ddsBytes.Length - DDS_HEADER_SIZE];
            Buffer.BlockCopy(ddsBytes, DDS_HEADER_SIZE, dxtBytes, 0, ddsBytes.Length - DDS_HEADER_SIZE);

            tex = new Texture2D(width, height, textureFormat, false);
            tex.filterMode = FilterMode.Trilinear;
            tex.LoadRawTextureData(dxtBytes);
            tex.Apply();
            tex.Compress(true);
        }

        #endregion

        #region Internal Helpers
        private static bool Check_Header(byte[] data, byte[] magic, int offset = 0)
        {
            if (magic == null || data == null || magic.Length <= 0 || (data.Length - offset) <= 0 || magic.Length > (data.Length - offset))
            {
                SLog.Info("Bad arguments.");
                return false;
            }

            for (int i = 0; i < magic.Length; i++)
                if (data[i + offset] != magic[i])
                    return false;

            return true;
        }
        #endregion

        #region Extensions
        public static Texture getTexture(this Sprite sprite)
        {
            return ResourceExt.FindTexture(sprite.name);
        }
        #endregion

        internal static void Setup()
        {
            Load_Common();
        }

        /// <summary>
        /// Loads all of the predefined common texture resources.
        /// </summary>
        internal static void Load_Common()
        {
            const string myNamespace = "SR_PluginLoader";
            TextureOpFlags FLAGS = (TextureOpFlags.NO_MIPMAPPING & TextureOpFlags.NO_WRAPPING);

            TextureHelper.icon_logo = (Texture2D)TextureHelper.Load_From_Resource("logo.png", myNamespace, FLAGS);
            TextureHelper.icon_logo_sad = (Texture2D)TextureHelper.Load_From_Resource("logo_sad.png", myNamespace, FLAGS);
            TextureHelper.icon_unknown = (Texture2D)TextureHelper.Load_From_Resource("mystery.png", myNamespace, FLAGS);
            TextureHelper.icon_alert = (Texture2D)TextureHelper.Load_From_Resource("alert.png", myNamespace, FLAGS);
            TextureHelper.icon_close = (Texture2D)TextureHelper.Load_From_Resource("close.png", myNamespace, FLAGS);
            TextureHelper.icon_close_dark = (Texture2D)TextureHelper.Load_From_Resource("close.png", myNamespace, FLAGS);
            TextureHelper.icon_checkbox = (Texture2D)TextureHelper.Load_From_Resource("checkbox.png", myNamespace, FLAGS);
            TextureHelper.icon_checkmark = (Texture2D)TextureHelper.Load_From_Resource("checkmark.png", myNamespace, FLAGS);

            TextureHelper.icon_arrow_left = (Texture2D)TextureHelper.Load_From_Resource("arrow_left.png", myNamespace, FLAGS);
            TextureHelper.icon_arrow_right = (Texture2D)TextureHelper.Load_From_Resource("arrow_right.png", myNamespace, FLAGS);

            TextureHelper.icon_node_arrow_right = (Texture2D)TextureHelper.Load_From_Resource("node_arrow.png", myNamespace, FLAGS);
            TextureHelper.icon_node_arrow_down = Rotate_90(icon_node_arrow_right, FLAGS);

            Util.Tint_Texture(TextureHelper.icon_close_dark, new Color(1f, 1f, 1f, 0.5f));
        }

        #region Texture Manipulation

        /// <summary>
        /// Creates a copy of a given texture rotated 90 degrees Clockwise.
        /// </summary>
        public static Texture2D Rotate_90(Texture2D tex, TextureOpFlags flags)
        {
            Texture2D cpy = new Texture2D(tex.width, tex.height);
            for (int x = 0; x < tex.width; x++)
            {
                for (int y = 0; y < tex.height; y++)
                {
                    Color p = tex.GetPixel(x, y);
                    cpy.SetPixel(y, (tex.width - (x + 1)), p);
                }
            }

            cpy.Apply();
            Enforce_Flags(ref cpy, flags);
            return cpy;
        }

        public static Texture2D Flip_Horizontal(Texture2D tex, TextureOpFlags flags)
        {
            Texture2D cpy = new Texture2D(tex.width, tex.height);
            for (int x = 0; x < tex.width; x++)
            {
                for (int y = 0; y < tex.height; y++)
                {
                    Color p = tex.GetPixel(x, y);
                    cpy.SetPixel((tex.width - (x + 1)), y, p);
                }
            }

            cpy.Apply();
            Enforce_Flags(ref cpy, flags);
            return cpy;
        }

        public static Texture2D Flip_Vertical(Texture2D tex, TextureOpFlags flags)
        {
            Texture2D cpy = new Texture2D(tex.width, tex.height);
            for (int x = 0; x < tex.width; x++)
            {
                for (int y = 0; y < tex.height; y++)
                {
                    Color p = tex.GetPixel(x, y);
                    cpy.SetPixel(x, (tex.height-(y + 1)), p);
                }
            }

            cpy.Apply();
            Enforce_Flags(ref cpy, flags);
            return cpy;
        }
        #endregion
    }
}


text:
package sofia.util;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

// -------------------------------------------------------------------------
/**
 *

 * An implementation of the {@link List} interface that is {@link Observable}
 * and notifies its observers whenever the collection is changed.
 *

 * Users of this class can add themselves as observers to an instance of this
 * class and they will be notified when the structure of the list changes; that
 * is, when items are added, removed, or replaced.
 *

 *
 * @param <E> the type of element stored in the list
 *
 * @author Tony Allevato
 */
public class ObservableList<E>
	extends Observable
    implements List<E>
{
    //~ Fields ................................................................

    private List<E> contents;

    //~ Constructors ..........................................................

    // ----------------------------------------------------------
    /**
     * Creates a new {@code ObservableList} that is backed by an
     * {@link ArrayList} with default capacity.
     */
    public ObservableList()
    {
        contents = new ArrayList<E>();
    }

    // ----------------------------------------------------------
    /**
     * Creates a new {@code ObservableList} that is backed by an
     * {@link ArrayList} with the specified capacity.
     *
     * @param capacity the capacity of the array list
     */
    public ObservableList(int capacity)
    {
        contents = new ArrayList<E>(capacity);
    }

    // ----------------------------------------------------------
    /**
     * Creates a new {@code ObservableList} that provides an observable view of
     * an existing list. The list passed to this constructor is not
     * copied; changes made to the observable list will also be reflected in
     * the list being wrapped, and vice versa.
     *
     * @param listToWrap the list to wrap with an observable front-end
     */
    public ObservableList(List<E> listToWrap)
    {
    	contents = listToWrap;
    }

    // ----------------------------------------------------------
    /**
     * Creates a new {@code ObservableList} that is initialized with a copy of
     * the data in the specified collection. Since this constructor creates a
     * copy, changes to the observable list will not be reflected in
     * the source collection, and vice versa.
     *
     * @param collection the collection to be copied into the new list
     */
    public ObservableList(Collection<? extends E> collection)
    {
        contents = new ArrayList<E>(collection);
    }

    //~ Methods ...............................................................

    // ----------------------------------------------------------
    public void add(int index, E item)
    {
        contents.add(index, item);

        notifyObservers();
    }

    // ----------------------------------------------------------
    public boolean add(E item)
    {
        boolean result = contents.add(item);

        notifyObservers();

        return result;
    }

    // ----------------------------------------------------------
    public boolean addAll(int index, Collection<? extends E> collection)
    {
        boolean result = contents.addAll(index, collection);

        notifyObservers();

        return result;
    }

    // ----------------------------------------------------------
    public boolean addAll(Collection<? extends E> collection)
    {
        boolean result = contents.addAll(collection);

        notifyObservers();

        return result;
    }

    // ----------------------------------------------------------
    public void clear()
    {
        contents.clear();

        notifyObservers();
    }

    // ----------------------------------------------------------
    public boolean contains(Object object)
    {
        return contents.contains(object);
    }

    // ----------------------------------------------------------
    public boolean containsAll(Collection<?> collection)
    {
        return contents.containsAll(collection);
    }

    // ----------------------------------------------------------
    public E get(int index)
    {
        return contents.get(index);
    }

    // ----------------------------------------------------------
    public int indexOf(Object object)
    {
        return contents.indexOf(object);
    }

    // ----------------------------------------------------------
    public boolean isEmpty()
    {
        return contents.isEmpty();
    }

    // ----------------------------------------------------------
    public Iterator<E> iterator()
    {
        return new NotifyingIterator(contents.iterator());
    }

    // ----------------------------------------------------------
    public int lastIndexOf(Object object)
    {
        return contents.lastIndexOf(object);
    }

    // ----------------------------------------------------------
    public ListIterator<E> listIterator()
    {
        return new NotifyingListIterator(contents.listIterator());
    }

    // ----------------------------------------------------------
    public ListIterator<E> listIterator(int index)
    {
        return new NotifyingListIterator(contents.listIterator(index));
    }

    // ----------------------------------------------------------
    public E remove(int index)
    {
        E result = contents.remove(index);

        notifyObservers();

        return result;
    }

    // ----------------------------------------------------------
    public boolean remove(Object object)
    {
        boolean result = contents.remove(object);

        notifyObservers();

        return result;
    }

    // ----------------------------------------------------------
    public boolean removeAll(Collection<?> collection)
    {
        boolean result = contents.removeAll(collection);

        notifyObservers();

        return result;
    }

    // ----------------------------------------------------------
    public boolean retainAll(Collection<?> collection)
    {
        boolean result = contents.retainAll(collection);

        notifyObservers();

        return result;
    }

    // ----------------------------------------------------------
    public E set(int index, E item)
    {
        E result = contents.set(index, item);

        notifyObservers();

        return result;
    }

    // ----------------------------------------------------------
    public int size()
    {
        return contents.size();
    }

    // ----------------------------------------------------------
    public List<E> subList(int start, int end)
    {
        return contents.subList(start, end);
    }

    // ----------------------------------------------------------
    public Object[] toArray()
    {
        return contents.toArray();
    }

    // ----------------------------------------------------------
    public <T> T[] toArray(T[] array)
    {
        return contents.toArray(array);
    }

    //~ Nested classes ........................................................

    // ----------------------------------------------------------
    private class NotifyingIterator implements Iterator<E>
    {
        private Iterator<E> iterator;

        // ----------------------------------------------------------
        public NotifyingIterator(Iterator<E> iterator)
        {
            this.iterator = iterator;
        }

        // ----------------------------------------------------------
        public boolean hasNext()
        {
            return iterator.hasNext();
        }

        // ----------------------------------------------------------
        public E next()
        {
            return iterator.next();
        }

        // ----------------------------------------------------------
        public void remove()
        {
            iterator.remove();

            notifyObservers();
        }
    }

    // ----------------------------------------------------------
    private class NotifyingListIterator implements ListIterator<E>
    {
        private ListIterator<E> iterator;

        // ----------------------------------------------------------
        public NotifyingListIterator(ListIterator<E> iterator)
        {
            this.iterator = iterator;
        }

        // ----------------------------------------------------------
        public void add(E item)
        {
            iterator.add(item);

            notifyObservers();
        }

        // ----------------------------------------------------------
        public boolean hasNext()
        {
            return iterator.hasNext();
        }

        // ----------------------------------------------------------
        public boolean hasPrevious()
        {
            return iterator.hasPrevious();
        }

        // ----------------------------------------------------------
        public E next()
        {
            return iterator.next();
        }

        // ----------------------------------------------------------
        public int nextIndex()
        {
            return iterator.nextIndex();
        }

        // ----------------------------------------------------------
        public E previous()
        {
            return iterator.previous();
        }

        // ----------------------------------------------------------
        public int previousIndex()
        {
            return iterator.previousIndex();
        }

        // ----------------------------------------------------------
        public void remove()
        {
            iterator.remove();

            notifyObservers();
        }

        // ----------------------------------------------------------
        public void set(E item)
        {
            iterator.set(item);

            notifyObservers();
        }
    }
}


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=../../../../libc/constant.PR_GET_SECUREBITS.html">

Redirecting to ../../../../libc/constant.PR_GET_SECUREBITS.html...


text:
package com.example.administrator.ggcode.Fragment;

import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.example.administrator.ggcode.Activity.TodayDetailActivity;
import com.example.administrator.ggcode.Adapter.TodayAdapter;
import com.example.administrator.ggcode.Bean.TodayOfHistoryBean;
import com.example.administrator.ggcode.Commons.Constants;
import com.example.administrator.ggcode.R;
import com.example.administrator.ggcode.net.QClitent;
import com.example.administrator.ggcode.net.QNewsService;

import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class TodayFragment extends Fragment {
    @BindView(R.id.tb_today)
    Toolbar tbToday;
    @BindView (R.id.rv_today)
    RecyclerView rvToday;
    @BindView (R.id.fab)
    FloatingActionButton fab;

    //历史上今天的适配器
    private TodayAdapter adapter;

    @TargetApi(Build.VERSION_CODES.N)
    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view=inflater.inflate(R.layout.fragment_today, container, false);
        ButterKnife.bind(this,view);
        adapter=new TodayAdapter();
        adapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_BOTTOM);
        if (Build.VERSION.SDK_INT<= Build.VERSION_CODES.LOLLIPOP){
            fab.setVisibility(View.GONE);
        }
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (fab!=null){
                    rvToday.scrollToPosition(0);
                }
            }
        });
        StaggeredGridLayoutManager ll=new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL);
        rvToday.setLayoutManager(ll);
        rvToday.setAdapter(adapter);
        rvToday.addOnItemTouchListener(new OnItemChildClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
            @Override
            public void onSimpleItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent=new Intent(getActivity(),TodayDetailActivity.class);
                intent.putExtra("e_id",((TodayOfHistoryBean.ResultBean)adapter.getItem(position)).getE_id());
                getActivity().overridePendingTransition(R.anim.design_snackbar_in,R.anim.design_snackbar_out);
                getActivity().startActivity(intent);
            }
        });

        //获得当前的日期
        Calendar calendar=Calendar.getInstance();
        int month=calendar.get(Calendar.MONTH)+1;
        int day=calendar.get(Calendar.DAY_OF_MONTH);
        String params = month + "/" + day;

        //初次加载数据
        QClitent.getInstance().create(QNewsService.class, Constants.BASE_JUHE_URL)
                .getTodayOfHistoryData(params)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<TodayOfHistoryBean>() {
                    @Override
                    public void accept(TodayOfHistoryBean todayOfHistoryBean) throws Exception {
                        List<TodayOfHistoryBean.ResultBean> result = todayOfHistoryBean.getResult();
                        adapter.setNewData(result);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        Toast.makeText(getContext(), "获取数据失败", Toast.LENGTH_SHORT).show();
                    }
                });
        return view;
    }

}


text:
Examples explaining crontab lines

## Fields and Allowed Values

```0-59``` minute

```0-23``` hour

```1-31``` day of month

```1-12``` or ```first 3 letters``` month

```0-7``` or ```first 3 letters (0 or 7 is Sun)``` day of week

## Special Characters

```Asterisk (*)``` The Asterisk is used as a wild card, used to specify any occurrence of the field

```Comma (,)``` The Comma is used when creating a list, to specify 2 or more times of execution

```Hyphen (-)```  The Hyphen is used to specify a range

```Forward Slash (/)```	The Slash is used as an interval, it can be used with a range or wild card to run at a specified interval

```@reboot```  Run once, at startup.

```@yearly or @annually```  Run once a year, equivalent to ```0 0 1 1 *```

```@monthly```  Run once a month, equivalent to ```0 0 1 * * ```

```@weekly```  Run once a week, equivalent to ```0 0 * * 0 ```

```@daily or @midnight```  Run once a day, equivalent to ```0 0 * * * ```

```@hourly```  Run once an hour, equivalent to ```0 * * * * ```

## Examples

Run every Tuesday at 2:30:

```30 2 * * tue /path/to/command``` or ```30 2 * * 2 /path/to/command```

Run every 10 minutes:

```*/10 * * * * /path/to/command```

Run every 2 hours, on the half-hour:

```30 */2 * * * /path/to/command```

Run every 2 hours on the half-hour, but only on weekdays:

```30 */2 * * 1-5 /path/to/command```

Run at 12:05, 13:05, ..., and 18:05 :

```5 12-18/2 * * * /path/to/command```

Run on the first day of every month, at 12:00am :

```0 0 1 * * /path/to/command```

Run on the first day of every third month, at 12:00am :

```0 0 1 */3 * /path/to/command```

Execute /path/to/command when the system starts:

```@reboot /path/to/command```


text:
<Alloy>
	<Window class="container">
		<ImageView class="logo"></ImageView>
		<ImageView id="logoEmpresa" class="logoEmpresa"></ImageView>
		AGRADECEMOS OS SEUS PEDIDOS ABAIXO RELACIONADOS
		<View id="corpo" class="corpo"></View>
		<View class="rodapeTotal">
			SOMA DOS PEDIDOS

		</View>
		<View class="rodape">
			<Button class="pedidos_voltar" onClick="voltar">Voltar Home</Button>
		</View>
		ESTES PEDIDOS FORAM ENVIADOS PARA OS E-MAILS CADASTRADOS ANTERIORMENTE:

	</Window>
</Alloy>


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/.idea/Archimede School Project.iml" filepath="$PROJECT_DIR$/.idea/Archimede School Project.iml" />
      <module fileurl="file://$PROJECT_DIR$/.idea/startbootstrap-creative-gh-pages.iml" filepath="$PROJECT_DIR$/.idea/startbootstrap-creative-gh-pages.iml" />
    </modules>
  </component>
</project>


text:
package com.amazonaws.services.ec2.model;

import java.io.Serializable;
import javax.annotation.Generated;

import com.amazonaws.AmazonWebServiceRequest;
import com.amazonaws.Request;
import com.amazonaws.services.ec2.model.transform.AllocateAddressRequestMarshaller;

/**
 *
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class AllocateAddressRequest extends AmazonWebServiceRequest implements Serializable, Cloneable, DryRunSupportedRequest<AllocateAddressRequest> {

    /**
     *

     * Set to vpc to allocate the address for use with instances in a VPC.
     *

     *

     * Default: The address is for use with instances in EC2-Classic.
     *

     */
    private String domain;
    /**
     *

     * [EC2-VPC] The Elastic IP address to recover or an IPv4 address from an address pool.
     *

     */
    private String address;
    /**
     *

     * The ID of an address pool that you own. Use this parameter to let Amazon EC2 select an address from the address
     * pool. To specify a specific address from the address pool, use the Address parameter instead.
     *

     */
    private String publicIpv4Pool;

    /**
     *

     * Set to vpc to allocate the address for use with instances in a VPC.
     *

     *

     * Default: The address is for use with instances in EC2-Classic.
     *

     *
     * @param domain
     *        Set to vpc to allocate the address for use with instances in a VPC.

     *

     *        Default: The address is for use with instances in EC2-Classic.
     * @see DomainType
     */

    public void setDomain(String domain) {
        this.domain = domain;
    }

    /**
     *

     * Set to vpc to allocate the address for use with instances in a VPC.
     *

     *

     * Default: The address is for use with instances in EC2-Classic.
     *

     *
     * @return Set to vpc to allocate the address for use with instances in a VPC.

     *

     *         Default: The address is for use with instances in EC2-Classic.
     * @see DomainType
     */

    public String getDomain() {
        return this.domain;
    }

    /**
     *

     * Set to vpc to allocate the address for use with instances in a VPC.
     *

     *

     * Default: The address is for use with instances in EC2-Classic.
     *

     *
     * @param domain
     *        Set to vpc to allocate the address for use with instances in a VPC.

     *

     *        Default: The address is for use with instances in EC2-Classic.
     * @return Returns a reference to this object so that method calls can be chained together.
     * @see DomainType
     */

    public AllocateAddressRequest withDomain(String domain) {
        setDomain(domain);
        return this;
    }

    /**
     *

     * Set to vpc to allocate the address for use with instances in a VPC.
     *

     *

     * Default: The address is for use with instances in EC2-Classic.
     *

     *
     * @param domain
     *        Set to vpc to allocate the address for use with instances in a VPC.

     *

     *        Default: The address is for use with instances in EC2-Classic.
     * @see DomainType
     */

    public void setDomain(DomainType domain) {
        withDomain(domain);
    }

    /**
     *

     * Set to vpc to allocate the address for use with instances in a VPC.
     *

     *

     * Default: The address is for use with instances in EC2-Classic.
     *

     *
     * @param domain
     *        Set to vpc to allocate the address for use with instances in a VPC.

     *

     *        Default: The address is for use with instances in EC2-Classic.
     * @return Returns a reference to this object so that method calls can be chained together.
     * @see DomainType
     */

    public AllocateAddressRequest withDomain(DomainType domain) {
        this.domain = domain.toString();
        return this;
    }

    /**
     *

     * [EC2-VPC] The Elastic IP address to recover or an IPv4 address from an address pool.
     *

     *
     * @param address
     *        [EC2-VPC] The Elastic IP address to recover or an IPv4 address from an address pool.
     */

    public void setAddress(String address) {
        this.address = address;
    }

    /**
     *

     * [EC2-VPC] The Elastic IP address to recover or an IPv4 address from an address pool.
     *

     *
     * @return [EC2-VPC] The Elastic IP address to recover or an IPv4 address from an address pool.
     */

    public String getAddress() {
        return this.address;
    }

    /**
     *

     * [EC2-VPC] The Elastic IP address to recover or an IPv4 address from an address pool.
     *

     *
     * @param address
     *        [EC2-VPC] The Elastic IP address to recover or an IPv4 address from an address pool.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public AllocateAddressRequest withAddress(String address) {
        setAddress(address);
        return this;
    }

    /**
     *

     * The ID of an address pool that you own. Use this parameter to let Amazon EC2 select an address from the address
     * pool. To specify a specific address from the address pool, use the Address parameter instead.
     *

     *
     * @param publicIpv4Pool
     *        The ID of an address pool that you own. Use this parameter to let Amazon EC2 select an address from the
     *        address pool. To specify a specific address from the address pool, use the Address parameter
     *        instead.
     */

    public void setPublicIpv4Pool(String publicIpv4Pool) {
        this.publicIpv4Pool = publicIpv4Pool;
    }

    /**
     *

     * The ID of an address pool that you own. Use this parameter to let Amazon EC2 select an address from the address
     * pool. To specify a specific address from the address pool, use the Address parameter instead.
     *

     *
     * @return The ID of an address pool that you own. Use this parameter to let Amazon EC2 select an address from the
     *         address pool. To specify a specific address from the address pool, use the Address parameter
     *         instead.
     */

    public String getPublicIpv4Pool() {
        return this.publicIpv4Pool;
    }

    /**
     *

     * The ID of an address pool that you own. Use this parameter to let Amazon EC2 select an address from the address
     * pool. To specify a specific address from the address pool, use the Address parameter instead.
     *

     *
     * @param publicIpv4Pool
     *        The ID of an address pool that you own. Use this parameter to let Amazon EC2 select an address from the
     *        address pool. To specify a specific address from the address pool, use the Address parameter
     *        instead.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public AllocateAddressRequest withPublicIpv4Pool(String publicIpv4Pool) {
        setPublicIpv4Pool(publicIpv4Pool);
        return this;
    }

    /**
     * This method is intended for internal use only. Returns the marshaled request configured with additional
     * parameters to enable operation dry-run.
     */
    @Override
    public Request<AllocateAddressRequest> getDryRunRequest() {
        Request<AllocateAddressRequest> request = new AllocateAddressRequestMarshaller().marshall(this);
        request.addParameter("DryRun", Boolean.toString(true));
        return request;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getDomain() != null)
            sb.append("Domain: ").append(getDomain()).append(",");
        if (getAddress() != null)
            sb.append("Address: ").append(getAddress()).append(",");
        if (getPublicIpv4Pool() != null)
            sb.append("PublicIpv4Pool: ").append(getPublicIpv4Pool());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof AllocateAddressRequest == false)
            return false;
        AllocateAddressRequest other = (AllocateAddressRequest) obj;
        if (other.getDomain() == null ^ this.getDomain() == null)
            return false;
        if (other.getDomain() != null && other.getDomain().equals(this.getDomain()) == false)
            return false;
        if (other.getAddress() == null ^ this.getAddress() == null)
            return false;
        if (other.getAddress() != null && other.getAddress().equals(this.getAddress()) == false)
            return false;
        if (other.getPublicIpv4Pool() == null ^ this.getPublicIpv4Pool() == null)
            return false;
        if (other.getPublicIpv4Pool() != null && other.getPublicIpv4Pool().equals(this.getPublicIpv4Pool()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getDomain() == null) ? 0 : getDomain().hashCode());
        hashCode = prime * hashCode + ((getAddress() == null) ? 0 : getAddress().hashCode());
        hashCode = prime * hashCode + ((getPublicIpv4Pool() == null) ? 0 : getPublicIpv4Pool().hashCode());
        return hashCode;
    }

    @Override
    public AllocateAddressRequest clone() {
        return (AllocateAddressRequest) super.clone();
    }
}


text: from .db import MockDB


text:
package com.ddling.client.usermanage;

/**
 * Created by lingdongdong on 15/1/4.
 * 管理用户的一个服务
 */
public class UserService {

    // 保存当前登录的用户信息
    public static User loginUser = null;

    // 判断当前是否有用户登录
    public static boolean isLogin = false;

    public static User getLoginUser() {
        return loginUser;
    }

    public static void setLoginUser(User user) {
        loginUser = user;
    }

    public static boolean isIsLogin() {
        return isLogin;
    }

    public static void setIsLogin(boolean isLogin) {
        UserService.isLogin = isLogin;
    }

    /**
     * 判断数据库中是否有此用户
     * @param username 需要判断的用户名
     * @return 如果存在当前用户,则返回true, 否则返回false
     */
    public static boolean hasUser(String username) {
        UserManageClient userManage = new UserManageClient();
        userManage.sendData("Exist " + username);
        String response = userManage.response().split(" ")[0];
        userManage.closeTheConnection();

        if (response.equalsIgnoreCase("+TRUE")) {
            return true;
        }

        return false;
    }

    /**
     * 对用户进行身份的验证,判断用户名和密码是否合法
     * @param username 需要验证的用户
     * @param password 需要验证的用户密码
     * @return 验证成功返回true,验证失败返回false
     */
    public static boolean authUser(String username, String password) {
        UserManageClient userManage = new UserManageClient();
        userManage.sendData("Auth " + username + ":" + password);
        String response = userManage.response().split(" ")[0];
        userManage.closeTheConnection();

        if (response.equalsIgnoreCase("+TRUE")) {
            isLogin = true;
            loginUser = new User(username, password);
            return true;
        }

        return false;
    }

    /**
     * 注册新用户
     * @param username 需要注册的新用户名
     * @param password 需要注册的新用户密码
     * @return 注册成功返回true, 注册失败返回false
     */
    public static boolean regUser(String username, String password) {
        UserManageClient userManage = new UserManageClient();
        userManage.sendData("Reg " + username + ":" + password);
        String response = userManage.response().split(" ")[0];
        userManage.closeTheConnection();

        if (response.equalsIgnoreCase("+TRUE")) {
            return true;
        }

        return false;
    }

    /**
     * 退出登录
     */
    public static void logout() {
        loginUser = null;
        isLogin = false;
    }

    public static void main(String[] args) {
        UserService.regUser("xxx", "123456");
    }
}


text:
===============================================================
Tutorial for building tools using LibTooling and LibASTMatchers
===============================================================

This document is intended to show how to build a useful source-to-source
translation tool based on Clang's `LibTooling <LibTooling.html>`_. It is
explicitly aimed at people who are new to Clang, so all you should need
is a working knowledge of C++ and the command line.

In order to work on the compiler, you need some basic knowledge of the
abstract syntax tree (AST). To this end, the reader is incouraged to
skim the :doc:`Introduction to the Clang
AST <IntroductionToTheClangAST>`

Step 0: Obtaining Clang
=======================

As Clang is part of the LLVM project, you'll need to download LLVM's
source code first. Both Clang and LLVM are maintained as Subversion
repositories, but we'll be accessing them through the git mirror. For
further information, see the `getting started
guide <http://llvm.org/docs/GettingStarted.html>`_.

.. code-block:: console

      mkdir ~/clang-llvm && cd ~/clang-llvm
      git clone http://llvm.org/git/llvm.git
      cd llvm/tools
      git clone http://llvm.org/git/clang.git
      cd clang/tools
      git clone http://llvm.org/git/clang-tools-extra.git extra

Next you need to obtain the CMake build system and Ninja build tool. You
may already have CMake installed, but current binary versions of CMake
aren't built with Ninja support.

.. code-block:: console

      cd ~/clang-llvm
      git clone https://github.com/martine/ninja.git
      cd ninja
      git checkout release
      ./bootstrap.py
      sudo cp ninja /usr/bin/

      cd ~/clang-llvm
      git clone git://cmake.org/stage/cmake.git
      cd cmake
      git checkout next
      ./bootstrap
      make
      sudo make install

Okay. Now we'll build Clang!

.. code-block:: console

      cd ~/clang-llvm
      mkdir build && cd build
      cmake -G Ninja ../llvm -DLLVM_BUILD_TESTS=ON  # Enable tests; default is off.
      ninja
      ninja check       # Test LLVM only.
      ninja clang-test  # Test Clang only.
      ninja install

And we're live.

All of the tests should pass, though there is a (very) small chance that
you can catch LLVM and Clang out of sync. Running ``'git svn rebase'``
in both the llvm and clang directories should fix any problems.

Finally, we want to set Clang as its own compiler.

.. code-block:: console

      cd ~/clang-llvm/build
      ccmake ../llvm

The second command will bring up a GUI for configuring Clang. You need
to set the entry for ``CMAKE_CXX_COMPILER``. Press ``'t'`` to turn on
advanced mode. Scroll down to ``CMAKE_CXX_COMPILER``, and set it to
``/usr/bin/clang++``, or wherever you installed it. Press ``'c'`` to
configure, then ``'g'`` to generate CMake's files.

Finally, run ninja one last time, and you're done.

Step 1: Create a ClangTool
==========================

Now that we have enough background knowledge, it's time to create the
simplest productive ClangTool in existence: a syntax checker. While this
already exists as ``clang-check``, it's important to understand what's
going on.

First, we'll need to create a new directory for our tool and tell CMake
that it exists. As this is not going to be a core clang tool, it will
live in the ``tools/extra`` repository.

.. code-block:: console

      cd ~/clang-llvm/llvm/tools/clang
      mkdir tools/extra/loop-convert
      echo 'add_subdirectory(loop-convert)' >> tools/extra/CMakeLists.txt
      vim tools/extra/loop-convert/CMakeLists.txt

CMakeLists.txt should have the following contents:

::

      set(LLVM_LINK_COMPONENTS support)

      add_clang_executable(loop-convert
        LoopConvert.cpp
        )
      target_link_libraries(loop-convert
        clangTooling
        clangBasic
        clangASTMatchers
        )

With that done, Ninja will be able to compile our tool. Let's give it
something to compile! Put the following into
``tools/extra/loop-convert/LoopConvert.cpp``. A detailed explanation of
why the different parts are needed can be found in the `LibTooling
documentation <LibTooling.html>`_.

.. code-block:: c++

      // Declares clang::SyntaxOnlyAction.
      #include "clang/Frontend/FrontendActions.h"
      #include "clang/Tooling/CommonOptionsParser.h"
      #include "clang/Tooling/Tooling.h"
      // Declares llvm::cl::extrahelp.
      #include "llvm/Support/CommandLine.h"

      using namespace clang::tooling;
      using namespace llvm;

      // Apply a custom category to all command-line options so that they are the
      // only ones displayed.
      static llvm::cl::OptionCategory MyToolCategory("my-tool options");

      // CommonOptionsParser declares HelpMessage with a description of the common
      // command-line options related to the compilation database and input files.
      // It's nice to have this help message in all tools.
      static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage);

      // A help message for this specific tool can be added afterwards.
      static cl::extrahelp MoreHelp("\nMore help text...");

      int main(int argc, const char **argv) {
        CommonOptionsParser OptionsParser(argc, argv, MyToolCategory);
        ClangTool Tool(OptionsParser.getCompilations(),
                       OptionsParser.getSourcePathList());
        return Tool.run(newFrontendActionFactory<clang::SyntaxOnlyAction>().get());
      }

And that's it! You can compile our new tool by running ninja from the
``build`` directory.

.. code-block:: console

      cd ~/clang-llvm/build
      ninja

You should now be able to run the syntax checker, which is located in
``~/clang-llvm/build/bin``, on any source file. Try it!

.. code-block:: console

      echo "int main() { return 0; }" > test.cpp
      bin/loop-convert test.cpp --

Note the two dashes after we specify the source file. The additional
options for the compiler are passed after the dashes rather than loading
them from a compilation database - there just aren't any options needed
right now.

Intermezzo: Learn AST matcher basics
====================================

Clang recently introduced the :doc:`ASTMatcher
library <LibASTMatchers>` to provide a simple, powerful, and
concise way to describe specific patterns in the AST. Implemented as a
DSL powered by macros and templates (see
`ASTMatchers.h <../doxygen/ASTMatchers_8h_source.html>`_ if you're
curious), matchers offer the feel of algebraic data types common to
functional programming languages.

For example, suppose you wanted to examine only binary operators. There
is a matcher to do exactly that, conveniently named ``binaryOperator``.
I'll give you one guess what this matcher does:

.. code-block:: c++

      binaryOperator(hasOperatorName("+"), hasLHS(integerLiteral(equals(0))))

Shockingly, it will match against addition expressions whose left hand
side is exactly the literal 0. It will not match against other forms of
0, such as ``'\0'`` or ``NULL``, but it will match against macros that
expand to 0. The matcher will also not match against calls to the
overloaded operator ``'+'``, as there is a separate ``operatorCallExpr``
matcher to handle overloaded operators.

There are AST matchers to match all the different nodes of the AST,
narrowing matchers to only match AST nodes fulfilling specific criteria,
and traversal matchers to get from one kind of AST node to another. For
a complete list of AST matchers, take a look at the `AST Matcher
References <LibASTMatchersReference.html>`_

All matcher that are nouns describe entities in the AST and can be
bound, so that they can be referred to whenever a match is found. To do
so, simply call the method ``bind`` on these matchers, e.g.:

.. code-block:: c++

      variable(hasType(isInteger())).bind("intvar")

Step 2: Using AST matchers
==========================

Okay, on to using matchers for real. Let's start by defining a matcher
which will capture all ``for`` statements that define a new variable
initialized to zero. Let's start with matching all ``for`` loops:

.. code-block:: c++

      forStmt()

Next, we want to specify that a single variable is declared in the first
portion of the loop, so we can extend the matcher to

.. code-block:: c++

      forStmt(hasLoopInit(declStmt(hasSingleDecl(varDecl()))))

Finally, we can add the condition that the variable is initialized to
zero.

.. code-block:: c++

      forStmt(hasLoopInit(declStmt(hasSingleDecl(varDecl(
        hasInitializer(integerLiteral(equals(0))))))))

It is fairly easy to read and understand the matcher definition ("match
loops whose init portion declares a single variable which is initialized
to the integer literal 0"), but deciding that every piece is necessary
is more difficult. Note that this matcher will not match loops whose
variables are initialized to ``'\0'``, ``0.0``, ``NULL``, or any form of
zero besides the integer 0.

The last step is giving the matcher a name and binding the ``ForStmt``
as we will want to do something with it:

.. code-block:: c++

      StatementMatcher LoopMatcher =
        forStmt(hasLoopInit(declStmt(hasSingleDecl(varDecl(
          hasInitializer(integerLiteral(equals(0)))))))).bind("forLoop");

Once you have defined your matchers, you will need to add a little more
scaffolding in order to run them. Matchers are paired with a
``MatchCallback`` and registered with a ``MatchFinder`` object, then run
from a ``ClangTool``. More code!

Add the following to ``LoopConvert.cpp``:

.. code-block:: c++

      #include "clang/ASTMatchers/ASTMatchers.h"
      #include "clang/ASTMatchers/ASTMatchFinder.h"

      using namespace clang;
      using namespace clang::ast_matchers;

      StatementMatcher LoopMatcher =
        forStmt(hasLoopInit(declStmt(hasSingleDecl(varDecl(
          hasInitializer(integerLiteral(equals(0)))))))).bind("forLoop");

      class LoopPrinter : public MatchFinder::MatchCallback {
      public :
        virtual void run(const MatchFinder::MatchResult &Result) {
          if (const ForStmt *FS = Result.Nodes.getNodeAs<clang::ForStmt>("forLoop"))
            FS->dump();
        }
      };

And change ``main()`` to:

.. code-block:: c++

      int main(int argc, const char **argv) {
        CommonOptionsParser OptionsParser(argc, argv, MyToolCategory);
        ClangTool Tool(OptionsParser.getCompilations(),
                       OptionsParser.getSourcePathList());

        LoopPrinter Printer;
        MatchFinder Finder;
        Finder.addMatcher(LoopMatcher, &Printer);

        return Tool.run(newFrontendActionFactory(&Finder).get());
      }

Now, you should be able to recompile and run the code to discover for
loops. Create a new file with a few examples, and test out our new
handiwork:

.. code-block:: console

      cd ~/clang-llvm/llvm/llvm_build/
      ninja loop-convert
      vim ~/test-files/simple-loops.cc
      bin/loop-convert ~/test-files/simple-loops.cc

Step 3.5: More Complicated Matchers
===================================

Our simple matcher is capable of discovering for loops, but we would
still need to filter out many more ourselves. We can do a good portion
of the remaining work with some cleverly chosen matchers, but first we
need to decide exactly which properties we want to allow.

How can we characterize for loops over arrays which would be eligible
for translation to range-based syntax? Range based loops over arrays of
size ``N`` that:

-  start at index ``0``
-  iterate consecutively
-  end at index ``N-1``

We already check for (1), so all we need to add is a check to the loop's
condition to ensure that the loop's index variable is compared against
``N`` and another check to ensure that the increment step just
increments this same variable. The matcher for (2) is straightforward:
require a pre- or post-increment of the same variable declared in the
init portion.

Unfortunately, such a matcher is impossible to write. Matchers contain
no logic for comparing two arbitrary AST nodes and determining whether
or not they are equal, so the best we can do is matching more than we
would like to allow, and punting extra comparisons to the callback.

In any case, we can start building this sub-matcher. We can require that
the increment step be a unary increment like this:

.. code-block:: c++

      hasIncrement(unaryOperator(hasOperatorName("++")))

Specifying what is incremented introduces another quirk of Clang's AST:
Usages of variables are represented as ``DeclRefExpr``'s ("declaration
reference expressions") because they are expressions which refer to
variable declarations. To find a ``unaryOperator`` that refers to a
specific declaration, we can simply add a second condition to it:

.. code-block:: c++

      hasIncrement(unaryOperator(
        hasOperatorName("++"),
        hasUnaryOperand(declRefExpr())))

Furthermore, we can restrict our matcher to only match if the
incremented variable is an integer:

.. code-block:: c++

      hasIncrement(unaryOperator(
        hasOperatorName("++"),
        hasUnaryOperand(declRefExpr(to(varDecl(hasType(isInteger())))))))

And the last step will be to attach an identifier to this variable, so
that we can retrieve it in the callback:

.. code-block:: c++

      hasIncrement(unaryOperator(
        hasOperatorName("++"),
        hasUnaryOperand(declRefExpr(to(
          varDecl(hasType(isInteger())).bind("incrementVariable"))))))

We can add this code to the definition of ``LoopMatcher`` and make sure
that our program, outfitted with the new matcher, only prints out loops
that declare a single variable initialized to zero and have an increment
step consisting of a unary increment of some variable.

Now, we just need to add a matcher to check if the condition part of the
``for`` loop compares a variable against the size of the array. There is
only one problem - we don't know which array we're iterating over
without looking at the body of the loop! We are again restricted to
approximating the result we want with matchers, filling in the details
in the callback. So we start with:

.. code-block:: c++

      hasCondition(binaryOperator(hasOperatorName("<"))

It makes sense to ensure that the left-hand side is a reference to a
variable, and that the right-hand side has integer type.

.. code-block:: c++

      hasCondition(binaryOperator(
        hasOperatorName("<"),
        hasLHS(declRefExpr(to(varDecl(hasType(isInteger()))))),
        hasRHS(expr(hasType(isInteger())))))

Why? Because it doesn't work. Of the three loops provided in
``test-files/simple.cpp``, zero of them have a matching condition. A
quick look at the AST dump of the first for loop, produced by the
previous iteration of loop-convert, shows us the answer:

::

      (ForStmt 0x173b240
        (DeclStmt 0x173afc8
          0x173af50 "int i =
            (IntegerLiteral 0x173afa8 'int' 0)")
        <<>>
        (BinaryOperator 0x173b060 '_Bool' '<'
          (ImplicitCastExpr 0x173b030 'int'
            (DeclRefExpr 0x173afe0 'int' lvalue Var 0x173af50 'i' 'int'))
          (ImplicitCastExpr 0x173b048 'int'
            (DeclRefExpr 0x173b008 'const int' lvalue Var 0x170fa80 'N' 'const int')))
        (UnaryOperator 0x173b0b0 'int' lvalue prefix '++'
          (DeclRefExpr 0x173b088 'int' lvalue Var 0x173af50 'i' 'int'))
        (CompoundStatement ...

We already know that the declaration and increments both match, or this
loop wouldn't have been dumped. The culprit lies in the implicit cast
applied to the first operand (i.e. the LHS) of the less-than operator,
an L-value to R-value conversion applied to the expression referencing
``i``. Thankfully, the matcher library offers a solution to this problem
in the form of ``ignoringParenImpCasts``, which instructs the matcher to
ignore implicit casts and parentheses before continuing to match.
Adjusting the condition operator will restore the desired match.

.. code-block:: c++

      hasCondition(binaryOperator(
        hasOperatorName("<"),
        hasLHS(ignoringParenImpCasts(declRefExpr(
          to(varDecl(hasType(isInteger())))))),
        hasRHS(expr(hasType(isInteger())))))

After adding binds to the expressions we wished to capture and
extracting the identifier strings into variables, we have array-step-2
completed.

Step 4: Retrieving Matched Nodes
================================

So far, the matcher callback isn't very interesting: it just dumps the
loop's AST. At some point, we will need to make changes to the input
source code. Next, we'll work on using the nodes we bound in the
previous step.

The ``MatchFinder::run()`` callback takes a
``MatchFinder::MatchResult&`` as its parameter. We're most interested in
its ``Context`` and ``Nodes`` members. Clang uses the ``ASTContext``
class to represent contextual information about the AST, as the name
implies, though the most functionally important detail is that several
operations require an ``ASTContext*`` parameter. More immediately useful
is the set of matched nodes, and how we retrieve them.

Since we bind three variables (identified by ConditionVarName,
InitVarName, and IncrementVarName), we can obtain the matched nodes by
using the ``getNodeAs()`` member function.

In ``LoopConvert.cpp`` add

.. code-block:: c++

      #include "clang/AST/ASTContext.h"

Change ``LoopMatcher`` to

.. code-block:: c++

      StatementMatcher LoopMatcher =
          forStmt(hasLoopInit(declStmt(
                      hasSingleDecl(varDecl(hasInitializer(integerLiteral(equals(0))))
                                        .bind("initVarName")))),
                  hasIncrement(unaryOperator(
                      hasOperatorName("++"),
                      hasUnaryOperand(declRefExpr(
                          to(varDecl(hasType(isInteger())).bind("incVarName")))))),
                  hasCondition(binaryOperator(
                      hasOperatorName("<"),
                      hasLHS(ignoringParenImpCasts(declRefExpr(
                          to(varDecl(hasType(isInteger())).bind("condVarName"))))),
                      hasRHS(expr(hasType(isInteger())))))).bind("forLoop");

And change ``LoopPrinter::run`` to

.. code-block:: c++

      void LoopPrinter::run(const MatchFinder::MatchResult &Result) {
        ASTContext *Context = Result.Context;
        const ForStmt *FS = Result.Nodes.getNodeAs<ForStmt>("forLoop");
        // We do not want to convert header files!
        if (!FS || !Context->getSourceManager().isWrittenInMainFile(FS->getForLoc()))
          return;
        const VarDecl *IncVar = Result.Nodes.getNodeAs<VarDecl>("incVarName");
        const VarDecl *CondVar = Result.Nodes.getNodeAs<VarDecl>("condVarName");
        const VarDecl *InitVar = Result.Nodes.getNodeAs<VarDecl>("initVarName");

        if (!areSameVariable(IncVar, CondVar) || !areSameVariable(IncVar, InitVar))
          return;
        llvm::outs() << "Potential array-based loop discovered.\n";
      }

Clang associates a ``VarDecl`` with each variable to represent the variable's
declaration. Since the "canonical" form of each declaration is unique by
address, all we need to do is make sure neither ``ValueDecl`` (base class of
``VarDecl``) is ``NULL`` and compare the canonical Decls.

.. code-block:: c++

      static bool areSameVariable(const ValueDecl *First, const ValueDecl *Second) {
        return First && Second &&
               First->getCanonicalDecl() == Second->getCanonicalDecl();
      }

If execution reaches the end of ``LoopPrinter::run()``, we know that the
loop shell that looks like

.. code-block:: c++

      for (int i= 0; i < expr(); ++i) { ... }

For now, we will just print a message explaining that we found a loop.
The next section will deal with recursively traversing the AST to
discover all changes needed.

As a side note, it's not as trivial to test if two expressions are the same,
though Clang has already done the hard work for us by providing a way to
canonicalize expressions:

.. code-block:: c++

      static bool areSameExpr(ASTContext *Context, const Expr *First,
                              const Expr *Second) {
        if (!First || !Second)
          return false;
        llvm::FoldingSetNodeID FirstID, SecondID;
        First->Profile(FirstID, *Context, true);
        Second->Profile(SecondID, *Context, true);
        return FirstID == SecondID;
      }

This code relies on the comparison between two
``llvm::FoldingSetNodeIDs``. As the documentation for
``Stmt::Profile()`` indicates, the ``Profile()`` member function builds
a description of a node in the AST, based on its properties, along with
those of its children. ``FoldingSetNodeID`` then serves as a hash we can
use to compare expressions. We will need ``areSameExpr`` later. Before
you run the new code on the additional loops added to
test-files/simple.cpp, try to figure out which ones will be considered
potentially convertible.


text:
package ru.stqa.pft.rest;

/**
 * Created by Ксюшенька on 23.04.2016.
 */
public class Issue {
    private int id;
    private String subject;
    private String description;

    public int getId() {
        return id;
    }

    public Issue withId( int id ) {
        this.id = id;
        return this;
    }

    public String getSubject() {
        return subject;
    }

    public Issue withSubject( String subject ) {
        this.subject = subject;
        return this;
    }

    public String getDescription() {
        return description;
    }

    public Issue withDescription( String description ) {
        this.description = description;
        return this;
    }

    @Override
    public boolean equals( Object o ) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Issue issue = (Issue) o;

        if (id != issue.id) return false;
        if (subject != null ? !subject.equals(issue.subject) : issue.subject != null) return false;
        return description != null ? description.equals(issue.description) : issue.description == null;

    }

    @Override
    public int hashCode() {
        int result = id;
        result = 31 * result + (subject != null ? subject.hashCode() : 0);
        result = 31 * result + (description != null ? description.hashCode() : 0);
        return result;
    }
}


text:
#ifndef log_accel_h
#define log_accel_h

#include <cmath>

#include <stdint.h>

#include "base/lnav_log.hh"

/**
 * Helper class for figuring out changes in the log message rate.
 */
class log_accel {
public:
    /*< The direction of the message rate: steady, accelerating, or decelerating
     */
    enum direction_t {
        A_STEADY,
        A_DECEL,
        A_ACCEL,
    };

    /**
     * Add a time point that will be used to compute velocity and then
     * acceleration.  Points should be added in reverse order, from most
     * recent to oldest.
     *
     * @param  point The point in time.
     * @return       True if more points can be added.
     */
    bool add_point(int64_t point);

    /**
     * Get the average acceleration based on the time points we've received.
     *
     * @return The average message acceleration.
     */
    double get_avg_accel() const;

    /**
     * Compute the message rate direction.  If the average acceleration is less
     * than a certain threshold, then we consider the rate to be steady.
     * Otherwise, the message rate is increasing or decreasing.
     *
     * @return The direction of the message rate.
     */
    direction_t get_direction() const;

private:
    /**
     * The amount of historical data to include in the average acceleration
     * computation.
     */
    static const int HISTORY_SIZE = 8;
    /**
     * The minimum range of velocities seen.  This value should limit false-
     * positives for small millisecond level fluctuations.
     */
    static const double MIN_RANGE;
    static const double THRESHOLD;

    int64_t la_last_point{0};
    bool la_last_point_set{false};
    int64_t la_min_velocity{INT64_MAX};
    int64_t la_max_velocity{INT64_MIN};
    int64_t la_velocity[HISTORY_SIZE];
    int la_velocity_size{0};
};

#endif


text: nunit-console /noshadow /domain:single CGbR.Tests\bin\Release\CGbR.Tests.dll


text:
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>W28669_text</title>
        <link rel="stylesheet" type="text/css" href="style.css" />

                «

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">AFFIDAVIT AFFIRMING SURFACE USE AGREEMENT

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Dolyniuk 34-23PH

    <p class="styleSans11.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Well Name: Dolyniuk 34-23PH
Location: 350' FNL & 1975' FWL Section 26-T140N-R99W County: Stark, North Dakota Permit No.: Pending
Whiting Oil and Gas Corporation has obtained a signed Surface Use Agreement for the Dolyniuk 34-23PH
well location which is off-unit. The legal description is as follows:
Township 140 NorthI Range 99 West Section 26: NE/4
Dated: 6,2014 32' l W ,
Scott M. Webb-Regulatory & Permitting Manager
Whiting Oil and Gas Corporation

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">ACKNOWLEDGEMENT

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">STATE OF COLORADO

    <p class="styleSans11.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">)ss. COUNTY OF DENVER )
On this 6th day of May, 2014, before me, a Notary Public, personally appeared Scott M. Webb, who being by me duly sworn, did say that he is Regulatory & Permitting Manager of Whiting Oil and Gas Corporation, and that the foregoing instrument was executed by him on behalf of said company as its free act and deed.
IN WITNESS WHEREOF, I have hereunto set my hand and affixed by Notarial Seal the day and year first above written.

    <p class="styleSans10.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">(SEAL)

    <p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans27.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">NOTARY PUBLIC
MyCommission Expires: \ 7 [B


text:
```
docker build -t obigroup/cozy-dataindexer .
```

# Dependencies
[Cozy CouchDb](https://registry.hub.docker.com/u/obigroup/cozy-couchdb/)

# Run:
With fig :
```
dataindexer:
    image: obigroup/cozy-dataindexer
    hostname: dataindexer
    volumes_from:
    - couchdb
```

#More about updates
```
https://forum.cozy.io/t/deployer-cozy-avec-docker-et-des-containers-autonomes/468
```


text:
@implementation NSError (TPNS)

+ (instancetype)TPNS_errorWithCode:(NSInteger)code description:(NSString *)description {
    NSParameterAssert(description.length > 0);

    NSDictionary *userInfo = @{NSLocalizedDescriptionKey: description};
    NSError *customError = [NSError errorWithDomain:DTPNSErrorDomain
                                               code:code
                                           userInfo:userInfo];
    return customError;
}

+ (instancetype)TPNS_errorWithCode:(NSInteger)code {

    NSString *description;
    switch (code) {
        case TPNSErrorCodeDeviceNotRegistered:
            description = @"Unable to unregister device - No AppID, DeviceID found. You need to register this device first.";
            break;
        case TPNSErrorCodeRegistrationIsAlreadyInProgress:
            description = @"There is already a registration in progress. Ignoring addional request.";
            break;
        case TPNSErrorCodeUnregisterBeforeYouRegisterAgain:
            description = @"Please unregister before you register again.";
            break;
        default:
            description = @"Unknown error";
            break;
    }

    return [self TPNS_errorWithCode:code description:description];
}

+ (instancetype)TPNS_httpErrorWithCode:(NSInteger)code originalErrorMessage:(NSString *)message {

    NSString *description;
    switch (code) {
        case 422:
            description = [NSString stringWithFormat:@"Appkey, DeviceId or Application Type empty / invalid (original error:%@)", message];
            break;
        case 500:
            description = [NSString stringWithFormat:@"Internal Server Error (original error:%@)", message];
            break;
        case 400:
            description = [NSString stringWithFormat:@"Bad Request (original error:%@)", message];
            break;
        case 403:
            description = [NSString stringWithFormat:@"ApiKey invalid / not authorized (original error:%@)", message];
            break;
        default:
            message = message.length > 0 ? message : @"No error description was provided";
            description = [NSString stringWithFormat:@"Request failed (original error:%@)", message];
            break;
    }

    return [self TPNS_errorWithCode:code description:description];
}

@end