text:
#ifndef BADVPN_PREDICATE_BPREDICATE_H
#define BADVPN_PREDICATE_BPREDICATE_H

#include <misc/debug.h>
#include <structure/BAVL.h>
#include <base/DebugObject.h>

#define PREDICATE_TYPE_BOOL 1
#define PREDICATE_TYPE_STRING 2

#define PREDICATE_MAX_NAME 16
#define PREDICATE_MAX_ARGS 16

/**
 * Handler function called when evaluating a custom function in the predicate.
 *
 * @param user value passed to {@link BPredicateFunction_Init}
 * @param args arguments to the function. Points to an array of pointers (as many as the
 *             function has arguments), where each pointer points to either to an int or
 *             a zero-terminated string (depending on the type of the argument).
 * @return 1 for true, 0 for false, -1 for error
 */
typedef int (*BPredicate_callback) (void *user, void **args);

/**
 * Object that parses and evaluates a logical expression.
 * Allows the user to define custom functions than can be
 * used in the expression.
 */
typedef struct {
    DebugObject d_obj;
    void *root;
    BAVL functions_tree;
    #ifndef NDEBUG
    int in_function;
    #endif
} BPredicate;

/**
 * Object that represents a custom function in {@link BPredicate}.
 */
typedef struct {
    DebugObject d_obj;
    BPredicate *p;
    char name[PREDICATE_MAX_NAME + 1];
    int args[PREDICATE_MAX_ARGS];
    int num_args;
    BPredicate_callback callback;
    void *user;
    BAVLNode tree_node;
} BPredicateFunction;

/**
 * Initializes the object.
 *
 * @param p the object
 * @param str logical expression
 * @return 1 on success, 0 on failure
 */
int BPredicate_Init (BPredicate *p, char *str) WARN_UNUSED;

/**
 * Frees the object.
 * Must have no custom functions.
 * Must not be called from function handlers.
 *
 * @param p the object
 */
void BPredicate_Free (BPredicate *p);

/**
 * Evaluates the logical expression.
 * Must not be called from function handlers.
 *
 * @param p the object
 * @return 1 for true, 0 for false, -1 for error
 */
int BPredicate_Eval (BPredicate *p);

/**
 * Registers a custom function for {@link BPredicate}.
 * Must not be called from function handlers.
 *
 * @param o the object
 * @param p predicate to register the function for
 * @param args array of argument types. Each type is either PREDICATE_TYPE_BOOL or PREDICATE_TYPE_STRING.
 * @param num_args number of arguments for the function. Must be >=0 and <=PREDICATE_MAX_ARGS.
 * @param callback handler to call to evaluate the function
 * @param user value to pass to handler
 */
void BPredicateFunction_Init (BPredicateFunction *o, BPredicate *p, char *name, int *args, int num_args, BPredicate_callback callback, void *user);

/**
 * Removes a custom function for {@link BPredicate}.
 * Must not be called from function handlers.
 *
 * @param o the object
 */
void BPredicateFunction_Free (BPredicateFunction *o);

#endif


text:
/**
 * Created by neulion-qa on 15/5/17.
 */
var StockModel = function(line){
	var firstQuoteIndex = line.indexOf('"');
	var lastQuoteIndex = line.lastIndexOf('"');
	if(firstQuoteIndex==-1 || firstQuoteIndex==lastQuoteIndex){
		console.log('return null, because (firstQuoteIndex==-1 || firstQuoteIndex==lastQuoteIndex)');
		return null;
	}

	function getFormattedNumber (number){
		number = parseFloat(number);
		return Math.abs(number)>1 ? number.toFixed(2) : number.toFixed(3);
	}

	var dataString = line.substring(firstQuoteIndex+1, lastQuoteIndex);
	var dataParts = dataString.split(",");
	if(dataParts.length>31){
		var model = {
			stockCode: "",
			stockName: dataParts[0],
			openingPriceToday: getFormattedNumber(dataParts[1]),
			closingPriceYesterday: getFormattedNumber(dataParts[2]),
			currentPrice: getFormattedNumber(dataParts[3]),
			highestPriceToday: getFormattedNumber(dataParts[4])+'元',
			lowestPriceToday: getFormattedNumber(dataParts[5])+'元',
			buyPrice: getFormattedNumber(dataParts[6])+'元',
			sellPrice: getFormattedNumber(dataParts[7])+'元',
			tradedAmountOfStock: getFormattedNumber(dataParts[8]/1000000)+'万手',
			tradedAmountOfMoney: getFormattedNumber(dataParts[9]/100000000)+'亿元',
			buyers:[
				{stock:dataParts[10]/100+'手', price:getFormattedNumber(dataParts[11])+'元'},
				{stock:dataParts[12]/100+'手', price:getFormattedNumber(dataParts[13])+'元'},
				{stock:dataParts[14]/100+'手', price:getFormattedNumber(dataParts[15])+'元'},
				{stock:dataParts[16]/100+'手', price:getFormattedNumber(dataParts[17])+'元'},
				{stock:dataParts[18]/100+'手', price:getFormattedNumber(dataParts[19])+'元'}
			],
			sellers:[
				{stock:dataParts[20]/100+'手', price:getFormattedNumber(dataParts[21])+'元'},
				{stock:dataParts[22]/100+'手', price:getFormattedNumber(dataParts[23])+'元'},
				{stock:dataParts[24]/100+'手', price:getFormattedNumber(dataParts[25])+'元'},
				{stock:dataParts[26]/100+'手', price:getFormattedNumber(dataParts[27])+'元'},
				{stock:dataParts[28]/100+'手', price:getFormattedNumber(dataParts[29])+'元'}
			],
			date: dataParts[30],
			time: dataParts[31]
		};
		var delta = model.currentPrice-model.closingPriceYesterday;
		var deltaPercent = delta/model.closingPriceYesterday*100;
		var symbol = deltaPercent>=0?'+':'';
		delta = Math.abs(model.currentPrice)>1 ? delta.toFixed(2) : delta.toFixed(3);
		model.deltaPrice = symbol+delta;
		model.deltaPercent = symbol+deltaPercent.toFixed(2)+'%';
		return model;
	}else{
		console.log('return null, because (dataParts.length>31)');
		return null;
	}
};

module.exports = StockModel;

redpajama_set_name: RedPajamaGithub


text:
import creole

from .utils import binders_map, object_slug

class PinaxWikiHtmlEmitter(creole.HtmlEmitter):

    def __init__(self, wiki, root, link_rules=None):
        self.wiki = wiki
        super().__init__(root, link_rules)

    def link_emit(self, node):
        target = node.content
        if node.children:
            inside = self.emit_children(node)
        else:
            inside = self.html_escape(target)
        m = self.link_rules.addr_re.match(target)
        if m:
            if m.group("extern_addr"):
                return '{}'.format(self.attr_escape(target), inside)
            elif m.group("inter_wiki"):
                raise NotImplementedError
        slug = object_slug(self.wiki)
        page_url = binders_map()[slug].page_url(self.wiki, target)
        return '{}'.format(self.attr_escape(page_url), inside)

def creole_parse(wiki, text):
    document = creole.CreoleParser(text, blog_line_breaks=True).parse()
    return PinaxWikiHtmlEmitter(wiki, document).emit()


text:
package com.bluemaestro.utility.sdk.views.generic;

import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.Button;

/**
 * Created by Garrett on 05/08/2016.
 */
public class BMButton extends Button {

    public BMButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        Typeface font = Typeface.createFromAsset(context.getAssets(), "fonts/Montserrat-Regular.ttf");
        super.setTypeface(font);
    }
}


text:
@interface GHUnitIPhoneViewController : UIViewController <UITableViewDelegate, GHTestRunnerDelegate, UISearchBarDelegate> {

  GHUnitIPhoneView *view_;

  //! Data source for table view
  GHUnitIPhoneTableViewDataSource *dataSource_;
  GHTestSuite *suite_;

  UIBarButtonItem *runButton_;

  //! If set then we will no longer auto scroll as tests are run
  BOOL userDidDrag_;

}

@property (retain, nonatomic) GHTestSuite *suite;

- (void)reloadTest:(id<GHTest>)test;

- (void)scrollToTest:(id<GHTest>)test;
- (void)scrollToBottom;

- (void)setStatusText:(NSString *)message;

- (void)runTests;

- (void)cancel;

- (void)reload;

- (void)loadDefaults;
- (void)saveDefaults;

- (GHUnitIPhoneTableViewDataSource *)dataSource;

@end


text:
package com.vk.api.sdk.queries.messages;

import com.vk.api.sdk.client.AbstractQueryBuilder;
import com.vk.api.sdk.client.Utils;
import com.vk.api.sdk.client.VkApiClient;
import com.vk.api.sdk.client.actors.UserActor;

import java.util.Arrays;
import java.util.List;

/**
 * Query for Messages.markAsImportant method
 */
public class MessagesMarkAsImportantQuery extends AbstractQueryBuilder<MessagesMarkAsImportantQuery, List<Integer>> {
    /**
     * Creates a AbstractQueryBuilder instance that can be used to build api request with various parameters
     *
     * @param client VK API client
     * @param actor  actor with access token
     */
    public MessagesMarkAsImportantQuery(VkApiClient client, UserActor actor) {
        super(client, "messages.markAsImportant", Utils.buildParametrizedType(List.class, Integer.class));
        accessToken(actor.getAccessToken());
    }

    /**
     * IDs of messages to mark as important.
     *
     * @param value value of "message ids" parameter.
     * @return a reference to this {@code AbstractQueryBuilder} object to fulfill the "Builder" pattern.
     */
    public MessagesMarkAsImportantQuery messageIds(Integer... value) {
        return unsafeParam("message_ids", value);
    }

    /**
     * IDs of messages to mark as important.
     *
     * @param value value of "message ids" parameter.
     * @return a reference to this {@code AbstractQueryBuilder} object to fulfill the "Builder" pattern.
     */
    public MessagesMarkAsImportantQuery messageIds(List<Integer> value) {
        return unsafeParam("message_ids", value);
    }

    /**
     * "true" - to add a star (mark as important)
     * "false" - to remove the star
     *
     * @param value value of "important" parameter. Minimum is 0.
     * @return a reference to this {@code AbstractQueryBuilder} object to fulfill the "Builder" pattern.
     */
    public MessagesMarkAsImportantQuery important(Boolean value) {
        return unsafeParam("important", value);
    }

    @Override
    protected MessagesMarkAsImportantQuery getThis() {
        return this;
    }

    @Override
    protected List<String> essentialKeys() {
        return Arrays.asList("access_token");
    }
}


text:
let Instruction = require('./Instruction');

let hitRegion = (id, points) => new Instruction('hitRegion', { id, points });

module.exports = hitRegion;


text:
package com.facebook.internal;

import android.app.Activity;
import android.content.*;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import com.facebook.*;
import com.facebook.widget.FacebookDialog;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

/**
 * com.facebook.internal is solely for the use of other packages within the Facebook SDK for Android. Use of
 * any of the classes in this package is unsupported, and they may be modified or removed without warning at
 * any time.
 */
public class LikeActionController {

    public static final String ACTION_LIKE_ACTION_CONTROLLER_UPDATED = "com.facebook.sdk.LikeActionController.UPDATED";
    public static final String ACTION_LIKE_ACTION_CONTROLLER_DID_ERROR = "com.facebook.sdk.LikeActionController.DID_ERROR";
    public static final String ACTION_LIKE_ACTION_CONTROLLER_DID_RESET = "com.facebook.sdk.LikeActionController.DID_RESET";

    public static final String ACTION_OBJECT_ID_KEY = "com.facebook.sdk.LikeActionController.OBJECT_ID";

    public static final String ERROR_INVALID_OBJECT_ID = "Invalid Object Id";

    private static final String TAG = LikeActionController.class.getSimpleName();

    private static final int LIKE_ACTION_CONTROLLER_VERSION = 2;
    private static final int MAX_CACHE_SIZE = 128;
    // MAX_OBJECT_SUFFIX basically accommodates for 1000 session-state changes before the async disk-cache-clear
    // finishes. The value is reasonably arbitrary.
    private static final int MAX_OBJECT_SUFFIX = 1000;

    private static final String LIKE_ACTION_CONTROLLER_STORE = "com.facebook.LikeActionController.CONTROLLER_STORE_KEY";
    private static final String LIKE_ACTION_CONTROLLER_STORE_PENDING_OBJECT_ID_KEY = "PENDING_CONTROLLER_KEY";
    private static final String LIKE_ACTION_CONTROLLER_STORE_OBJECT_SUFFIX_KEY = "OBJECT_SUFFIX";

    private static final String JSON_INT_VERSION_KEY = "com.facebook.internal.LikeActionController.version";
    private static final String JSON_STRING_OBJECT_ID_KEY = "object_id";
    private static final String JSON_STRING_LIKE_COUNT_WITH_LIKE_KEY = "like_count_string_with_like";
    private static final String JSON_STRING_LIKE_COUNT_WITHOUT_LIKE_KEY = "like_count_string_without_like";
    private static final String JSON_STRING_SOCIAL_SENTENCE_WITH_LIKE_KEY = "social_sentence_with_like";
    private static final String JSON_STRING_SOCIAL_SENTENCE_WITHOUT_LIKE_KEY = "social_sentence_without_like";
    private static final String JSON_BOOL_IS_OBJECT_LIKED_KEY = "is_object_liked";
    private static final String JSON_STRING_UNLIKE_TOKEN_KEY = "unlike_token";
    private static final String JSON_STRING_PENDING_CALL_ID_KEY = "pending_call_id";
    private static final String JSON_BUNDLE_PENDING_CALL_ANALYTICS_BUNDLE = "pending_call_analytics_bundle";

    private static final String LIKE_DIALOG_RESPONSE_OBJECT_IS_LIKED_KEY = "object_is_liked";
    private static final String LIKE_DIALOG_RESPONSE_LIKE_COUNT_STRING_KEY = "like_count_string";
    private static final String LIKE_DIALOG_RESPONSE_SOCIAL_SENTENCE_KEY = "social_sentence";
    private static final String LIKE_DIALOG_RESPONSE_UNLIKE_TOKEN_KEY = "unlike_token";

    private static final int ERROR_CODE_OBJECT_ALREADY_LIKED = 3501;

    private static FileLruCache controllerDiskCache;
    private static final ConcurrentHashMap<String, LikeActionController> cache =
            new ConcurrentHashMap<String, LikeActionController>();
    private static WorkQueue mruCacheWorkQueue = new WorkQueue(1); // This MUST be 1 for proper synchronization
    private static WorkQueue diskIOWorkQueue = new WorkQueue(1); // This MUST be 1 for proper synchronization
    private static Handler handler;
    private static String objectIdForPendingController;
    private static boolean isPendingBroadcastReset;
    private static boolean isInitialized;
    private static volatile int objectSuffix;

    private Session session;
    private Context context;
    private String objectId;
    private boolean isObjectLiked;
    private String likeCountStringWithLike;
    private String likeCountStringWithoutLike;
    private String socialSentenceWithLike;
    private String socialSentenceWithoutLike;
    private String unlikeToken;

    private String verifiedObjectId;
    private boolean objectIsPage;
    private boolean isObjectLikedOnServer;

    private boolean isPendingLikeOrUnlike;

    private UUID pendingCallId;

    private Bundle pendingCallAnalyticsBundle;

    private AppEventsLogger appEventsLogger;

    /**
     * Called from UiLifecycleHelper to process any pending likes that had resulted in the Like dialog
     * being displayed
     *
     * @param context Hosting context
     * @param requestCode From the originating call to onActivityResult
     * @param resultCode From the originating call to onActivityResult
     * @param data From the originating call to onActivityResult
     * @return Indication of whether the Intent was handled
     */
    public static boolean handleOnActivityResult(Context context,
                                                 final int requestCode,
                                                 final int resultCode,
                                                 final Intent data) {
        final UUID callId = NativeProtocol.getCallIdFromIntent(data);
        if (callId == null) {
            return false;
        }

        // See if we were waiting on a Like dialog completion.
        if (Utility.isNullOrEmpty(objectIdForPendingController)) {
            SharedPreferences sharedPreferences = context.getSharedPreferences(
                    LIKE_ACTION_CONTROLLER_STORE,
                    Context.MODE_PRIVATE);

            objectIdForPendingController = sharedPreferences.getString(
                    LIKE_ACTION_CONTROLLER_STORE_PENDING_OBJECT_ID_KEY,
                    null);
        }

        if (Utility.isNullOrEmpty(objectIdForPendingController)) {
            // Doesn't look like we were waiting on a Like dialog completion
            return false;
        }

        getControllerForObjectId(
                context,
                objectIdForPendingController,
                new CreationCallback() {
                    @Override
                    public void onComplete(LikeActionController likeActionController) {
                        likeActionController.onActivityResult(requestCode, resultCode, data, callId);
                    }
                });

        return true;
    }

    /**
     * Called by the LikeView when an object-id is set on it.
     * @param context context
     * @param objectId Object Id
     * @return A LikeActionController for the specified object id
     */
    public static void getControllerForObjectId(
            Context context,
            String objectId,
            CreationCallback callback) {
        if (!isInitialized) {
            performFirstInitialize(context);
        }

        LikeActionController controllerForObject = getControllerFromInMemoryCache(objectId);
        if (controllerForObject != null) {
            // Direct object-cache hit
            invokeCallbackWithController(callback, controllerForObject);
        } else {
            diskIOWorkQueue.addActiveWorkItem(new CreateLikeActionControllerWorkItem(context, objectId, callback));
        }
    }

    /**
     * NOTE: This MUST be called ONLY via the CreateLikeActionControllerWorkItem class to ensure that it happens on the
     * right thread, at the right time.
     */
    private static void createControllerForObjectId(
            Context context,
            String objectId,
            CreationCallback callback) {
        // Check again to see if the controller was created before attempting to deserialize/create one.
        // Need to check this in the case where multiple LikeViews are looking for a controller for the same object
        // and all got queued up to create one. We only want the first one to go through with the creation, and the
        // rest should get the same instance from the object-cache.
        LikeActionController controllerForObject = getControllerFromInMemoryCache(objectId);
        if (controllerForObject != null) {
            // Direct object-cache hit
            invokeCallbackWithController(callback, controllerForObject);
            return;
        }

        // Try deserialize from disk
        controllerForObject = deserializeFromDiskSynchronously(context, objectId);

        if (controllerForObject == null) {
            controllerForObject = new LikeActionController(context, Session.getActiveSession(), objectId);
            serializeToDiskAsync(controllerForObject);
        }

        // Update object-cache.
        putControllerInMemoryCache(objectId, controllerForObject);

        // Refresh the controller on the Main thread.
        final LikeActionController controllerToRefresh = controllerForObject;
        handler.post(new Runnable() {
            @Override
            public void run() {
                controllerToRefresh.refreshStatusAsync();
            }
        });

        invokeCallbackWithController(callback, controllerToRefresh);
    }

    private synchronized static void performFirstInitialize(Context context) {
        if (isInitialized) {
            return;
        }

        handler = new Handler(Looper.getMainLooper());

        SharedPreferences sharedPreferences = context.getSharedPreferences(
                LIKE_ACTION_CONTROLLER_STORE,
                Context.MODE_PRIVATE);

        objectSuffix = sharedPreferences.getInt(LIKE_ACTION_CONTROLLER_STORE_OBJECT_SUFFIX_KEY, 1);
        controllerDiskCache = new FileLruCache(context, TAG, new FileLruCache.Limits());

        registerSessionBroadcastReceivers(context);

        isInitialized = true;
    }

    private static void invokeCallbackWithController(final CreationCallback callback, final LikeActionController controller) {
        if (callback == null) {
            return;
        }

        handler.post(new Runnable() {
            @Override
            public void run() {
                callback.onComplete(controller);
            }
        });
    }

    //
    // In-memory mru-caching code
    //

    private static void registerSessionBroadcastReceivers(Context context) {
        LocalBroadcastManager broadcastManager = LocalBroadcastManager.getInstance(context);

        IntentFilter filter = new IntentFilter();
        filter.addAction(Session.ACTION_ACTIVE_SESSION_UNSET);
        filter.addAction(Session.ACTION_ACTIVE_SESSION_CLOSED);
        filter.addAction(Session.ACTION_ACTIVE_SESSION_OPENED);

        broadcastManager.registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context receiverContext, Intent intent) {
                if (isPendingBroadcastReset) {
                    return;
                }

                String action = intent.getAction();
                final boolean shouldClearDisk =
                        Utility.areObjectsEqual(Session.ACTION_ACTIVE_SESSION_UNSET, action) ||
                                Utility.areObjectsEqual(Session.ACTION_ACTIVE_SESSION_CLOSED, action);

                isPendingBroadcastReset = true;
                // Delaying sending the broadcast to reset, because we might get many successive calls from Session
                // (to UNSET, SET & OPEN) and a delay would prevent excessive chatter.
                final Context broadcastContext = receiverContext;
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        // Bump up the objectSuffix so that we don't have a filename collision between a cache-clear and
                        // and a cache-read/write.
                        //
                        // NOTE: We know that onReceive() was called on the main thread. This means that even this code
                        // is running on the main thread, and therefore, there aren't synchronization issues with
                        // incrementing the objectSuffix and clearing the caches here.
                        if (shouldClearDisk) {
                            objectSuffix = (objectSuffix + 1) % MAX_OBJECT_SUFFIX;
                            broadcastContext.getSharedPreferences(LIKE_ACTION_CONTROLLER_STORE, Context.MODE_PRIVATE)
                                    .edit()
                                    .putInt(LIKE_ACTION_CONTROLLER_STORE_OBJECT_SUFFIX_KEY, objectSuffix)
                                    .apply();

                            // Only clearing the actual caches. The MRU index will self-clean with usage.
                            // Clearing the caches is necessary to prevent leaking like-state across sessions.
                            cache.clear();
                            controllerDiskCache.clearCache();
                        }

                        broadcastAction(broadcastContext, null, ACTION_LIKE_ACTION_CONTROLLER_DID_RESET);
                        isPendingBroadcastReset = false;
                    }
                }, 100);
            }
        }, filter);
    }

    private static void putControllerInMemoryCache(String objectId, LikeActionController controllerForObject) {
        String cacheKey = getCacheKeyForObjectId(objectId);
        // Move this object to the front. Also trim cache if necessary
        mruCacheWorkQueue.addActiveWorkItem(new MRUCacheWorkItem(cacheKey, true));

        cache.put(cacheKey, controllerForObject);
    }

    private static LikeActionController getControllerFromInMemoryCache(String objectId) {
        String cacheKey = getCacheKeyForObjectId(objectId);

        LikeActionController controller = cache.get(cacheKey);
        if (controller != null) {
            // Move this object to the front
            mruCacheWorkQueue.addActiveWorkItem(new MRUCacheWorkItem(cacheKey, false));
        }

        return controller;
    }

    //
    // Disk caching code
    //

    private static void serializeToDiskAsync(LikeActionController controller) {
        String controllerJson = serializeToJson(controller);
        String cacheKey = getCacheKeyForObjectId(controller.objectId);

        if (!Utility.isNullOrEmpty(controllerJson) && !Utility.isNullOrEmpty(cacheKey)) {
            diskIOWorkQueue.addActiveWorkItem(new SerializeToDiskWorkItem(cacheKey, controllerJson));
        }
    }

    /**
     * NOTE: This MUST be called ONLY via the SerializeToDiskWorkItem class to ensure that it happens on the
     * right thread, at the right time.
     */
    private static void serializeToDiskSynchronously(String cacheKey, String controllerJson) {
        OutputStream outputStream = null;
        try {
            outputStream = controllerDiskCache.openPutStream(cacheKey);
            outputStream.write(controllerJson.getBytes());
        } catch (IOException e) {
            Log.e(TAG, "Unable to serialize controller to disk", e);
        } finally {
            if (outputStream != null) {
                Utility.closeQuietly(outputStream);
            }
        }
    }

    /**
     * NOTE: This MUST be called ONLY via the CreateLikeActionControllerWorkItem class to ensure that it happens on the
     * right thread, at the right time.
     */
    private static LikeActionController deserializeFromDiskSynchronously(
            Context context,
            String objectId) {
        LikeActionController controller = null;

        InputStream inputStream = null;
        try {
            String cacheKey = getCacheKeyForObjectId(objectId);
            inputStream = controllerDiskCache.get(cacheKey);
            if (inputStream != null) {
                String controllerJsonString = Utility.readStreamToString(inputStream);
                if (!Utility.isNullOrEmpty(controllerJsonString)) {
                    controller = deserializeFromJson(context, controllerJsonString);
                }
            }
        } catch (IOException e) {
            Log.e(TAG, "Unable to deserialize controller from disk", e);
            controller = null;
        } finally {
            if (inputStream != null) {
                Utility.closeQuietly(inputStream);
            }
        }

        return controller;
    }

    private static LikeActionController deserializeFromJson(Context context, String controllerJsonString) {
        LikeActionController controller;

        try {
            JSONObject controllerJson = new JSONObject(controllerJsonString);
            int version = controllerJson.optInt(JSON_INT_VERSION_KEY, -1);
            if (version != LIKE_ACTION_CONTROLLER_VERSION) {
                // Don't attempt to deserialize a controller that might be serialized differently than expected.
                return null;
            }

            controller = new LikeActionController(
                    context,
                    Session.getActiveSession(),
                    controllerJson.getString(JSON_STRING_OBJECT_ID_KEY));

            // Make sure to default to null and not empty string, to keep the logic elsewhere functioning properly.
            controller.likeCountStringWithLike = controllerJson.optString(JSON_STRING_LIKE_COUNT_WITH_LIKE_KEY, null) ;
            controller.likeCountStringWithoutLike = controllerJson.optString(JSON_STRING_LIKE_COUNT_WITHOUT_LIKE_KEY, null) ;
            controller.socialSentenceWithLike = controllerJson.optString(JSON_STRING_SOCIAL_SENTENCE_WITH_LIKE_KEY, null);
            controller.socialSentenceWithoutLike = controllerJson.optString(JSON_STRING_SOCIAL_SENTENCE_WITHOUT_LIKE_KEY, null);
            controller.isObjectLiked = controllerJson.optBoolean(JSON_BOOL_IS_OBJECT_LIKED_KEY);
            controller.unlikeToken = controllerJson.optString(JSON_STRING_UNLIKE_TOKEN_KEY, null);
            String pendingCallIdString = controllerJson.optString(JSON_STRING_PENDING_CALL_ID_KEY, null);
            if (!Utility.isNullOrEmpty(pendingCallIdString)) {
                controller.pendingCallId = UUID.fromString(pendingCallIdString);
            }

            JSONObject analyticsJSON = controllerJson.optJSONObject(JSON_BUNDLE_PENDING_CALL_ANALYTICS_BUNDLE);
            if (analyticsJSON != null) {
                controller.pendingCallAnalyticsBundle = BundleJSONConverter.convertToBundle(analyticsJSON);
            }
        } catch (JSONException e) {
            Log.e(TAG, "Unable to deserialize controller from JSON", e);
            controller = null;
        }

        return controller;
    }

    private static String serializeToJson(LikeActionController controller) {
        JSONObject controllerJson = new JSONObject();
        try {
            controllerJson.put(JSON_INT_VERSION_KEY, LIKE_ACTION_CONTROLLER_VERSION);
            controllerJson.put(JSON_STRING_OBJECT_ID_KEY, controller.objectId);
            controllerJson.put(JSON_STRING_LIKE_COUNT_WITH_LIKE_KEY, controller.likeCountStringWithLike);
            controllerJson.put(JSON_STRING_LIKE_COUNT_WITHOUT_LIKE_KEY, controller.likeCountStringWithoutLike);
            controllerJson.put(JSON_STRING_SOCIAL_SENTENCE_WITH_LIKE_KEY, controller.socialSentenceWithLike);
            controllerJson.put(JSON_STRING_SOCIAL_SENTENCE_WITHOUT_LIKE_KEY, controller.socialSentenceWithoutLike);
            controllerJson.put(JSON_BOOL_IS_OBJECT_LIKED_KEY, controller.isObjectLiked);
            controllerJson.put(JSON_STRING_UNLIKE_TOKEN_KEY, controller.unlikeToken);
            if (controller.pendingCallId != null) {
                controllerJson.put(JSON_STRING_PENDING_CALL_ID_KEY, controller.pendingCallId.toString());
            }
            if (controller.pendingCallAnalyticsBundle != null) {
                JSONObject analyticsJSON = BundleJSONConverter.convertToJSON(controller.pendingCallAnalyticsBundle);
                if (analyticsJSON != null) {
                    controllerJson.put(JSON_BUNDLE_PENDING_CALL_ANALYTICS_BUNDLE, analyticsJSON);
                }
            }
        } catch (JSONException e) {
            Log.e(TAG, "Unable to serialize controller to JSON", e);
            return null;
        }

        return controllerJson.toString();
    }

    private static String getCacheKeyForObjectId(String objectId) {
        String accessTokenPortion = null;
        Session activeSession = Session.getActiveSession();
        if (activeSession != null && activeSession.isOpened()) {
            accessTokenPortion = activeSession.getAccessToken();
        }
        if (accessTokenPortion != null) {
            // Cache-key collisions are not something to worry about here, since we only store state for
            // one session. Even in the case where the previous session's serialized files have not been deleted yet,
            // the objectSuffix will be different due to the session-change, thus making the key different.
            accessTokenPortion = Utility.md5hash(accessTokenPortion);
        }
        return String.format(
                "%s|%s|com.fb.sdk.like|%d",
                objectId,
                Utility.coerceValueIfNullOrEmpty(accessTokenPortion, ""),
                objectSuffix);
    }

    //
    // Broadcast handling code
    //

    private static void broadcastAction(Context context, LikeActionController controller, String action) {
        broadcastAction(context, controller, action, null);
    }

    private static void broadcastAction(Context context, LikeActionController controller, String action, Bundle data) {
        Intent broadcastIntent = new Intent(action);
        if (controller != null) {
            if (data == null) {
                data = new Bundle();
            }

            data.putString(ACTION_OBJECT_ID_KEY, controller.getObjectId());
        }

        if (data != null) {
            broadcastIntent.putExtras(data);
        }
        LocalBroadcastManager.getInstance(context.getApplicationContext()).sendBroadcast(broadcastIntent);
    }

    /**
     * Constructor
     */
    private LikeActionController(Context context, Session session, String objectId) {
        this.context = context;
        this.session = session;
        this.objectId = objectId;

        appEventsLogger = AppEventsLogger.newLogger(context, session);
    }

    /**
     * Gets the the associated object id
     * @return object id
     */
    public String getObjectId() {
        return objectId;
    }

    /**
     * Gets the String representation of the like-count for the associated object
     * @return String representation of the like-count for the associated object
     */
    public String getLikeCountString() {
        return isObjectLiked ? likeCountStringWithLike : likeCountStringWithoutLike;
    }

    /**
     * Gets the String representation of the like-count for the associated object
     * @return String representation of the like-count for the associated object
     */
    public String getSocialSentence() {
        return isObjectLiked ? socialSentenceWithLike : socialSentenceWithoutLike;
    }

    /**
     * Indicates whether the associated object is liked
     * @return Indication of whether the associated object is liked
     */
    public boolean isObjectLiked() {
        return isObjectLiked;
    }

    /**
     * Entry-point to the code that performs the like/unlike action.
     */
    public void toggleLike(Activity activity, Bundle analyticsParameters) {
        appEventsLogger.logSdkEvent(AnalyticsEvents.EVENT_LIKE_VIEW_DID_TAP, null, analyticsParameters);

        boolean shouldLikeObject = !this.isObjectLiked;
        if (canUseOGPublish(shouldLikeObject)) {
            // Update UI state optimistically
            updateState(shouldLikeObject,
                    this.likeCountStringWithLike,
                    this.likeCountStringWithoutLike,
                    this.socialSentenceWithLike,
                    this.socialSentenceWithoutLike,
                    this.unlikeToken);
            if (isPendingLikeOrUnlike) {
                // If the user toggled the button quickly, and there is still a publish underway, don't fire off
                // another request. Also log this behavior.

                appEventsLogger.logSdkEvent(AnalyticsEvents.EVENT_LIKE_VIEW_DID_UNDO_QUICKLY, null, analyticsParameters);
                return;
            }
        }

        performLikeOrUnlike(activity, shouldLikeObject, analyticsParameters);
    }

    private void performLikeOrUnlike(Activity activity, boolean shouldLikeObject, Bundle analyticsParameters) {
        if (canUseOGPublish(shouldLikeObject)) {
            if (shouldLikeObject) {
                publishLikeAsync(activity, analyticsParameters);
            } else {
                publishUnlikeAsync(activity, analyticsParameters);
            }
        } else {
            presentLikeDialog(activity, analyticsParameters);
        }
    }

    private void updateState(boolean isObjectLiked,
                             String likeCountStringWithLike,
                             String likeCountStringWithoutLike,
                             String socialSentenceWithLike,
                             String socialSentenceWithoutLike,
                             String unlikeToken) {
        // Normalize all empty strings to null, so that we don't have any problems with comparison.
        likeCountStringWithLike = Utility.coerceValueIfNullOrEmpty(likeCountStringWithLike, null);
        likeCountStringWithoutLike = Utility.coerceValueIfNullOrEmpty(likeCountStringWithoutLike, null);
        socialSentenceWithLike = Utility.coerceValueIfNullOrEmpty(socialSentenceWithLike, null);
        socialSentenceWithoutLike = Utility.coerceValueIfNullOrEmpty(socialSentenceWithoutLike, null);
        unlikeToken = Utility.coerceValueIfNullOrEmpty(unlikeToken, null);

        boolean stateChanged = isObjectLiked != this.isObjectLiked ||
                !Utility.areObjectsEqual(likeCountStringWithLike, this.likeCountStringWithLike) ||
                !Utility.areObjectsEqual(likeCountStringWithoutLike, this.likeCountStringWithoutLike) ||
                !Utility.areObjectsEqual(socialSentenceWithLike, this.socialSentenceWithLike) ||
                !Utility.areObjectsEqual(socialSentenceWithoutLike, this.socialSentenceWithoutLike) ||
                !Utility.areObjectsEqual(unlikeToken, this.unlikeToken);

        if (!stateChanged) {
            return;
        }

        this.isObjectLiked = isObjectLiked;
        this.likeCountStringWithLike = likeCountStringWithLike;
        this.likeCountStringWithoutLike = likeCountStringWithoutLike;
        this.socialSentenceWithLike = socialSentenceWithLike;
        this.socialSentenceWithoutLike = socialSentenceWithoutLike;
        this.unlikeToken = unlikeToken;

        serializeToDiskAsync(this);

        broadcastAction(context, this, ACTION_LIKE_ACTION_CONTROLLER_UPDATED);
    }

    private void presentLikeDialog(Activity activity, Bundle analyticsParameters) {
        LikeDialogBuilder likeDialogBuilder = new LikeDialogBuilder(activity, objectId);

        if (likeDialogBuilder.canPresent()) {
            trackPendingCall(likeDialogBuilder.build().present(), analyticsParameters);
            appEventsLogger.logSdkEvent(AnalyticsEvents.EVENT_LIKE_VIEW_DID_PRESENT_DIALOG, null, analyticsParameters);
        } else {
            String webFallbackUrl = likeDialogBuilder.getWebFallbackUrl();
            if (!Utility.isNullOrEmpty(webFallbackUrl)) {
                boolean webFallbackShown = FacebookWebFallbackDialog.presentWebFallback(
                        activity,
                        webFallbackUrl,
                        likeDialogBuilder.getApplicationId(),
                        likeDialogBuilder.getAppCall(),
                        getFacebookDialogCallback(analyticsParameters));
                if (webFallbackShown) {
                    appEventsLogger.logSdkEvent(
                            AnalyticsEvents.EVENT_LIKE_VIEW_DID_PRESENT_FALLBACK, null, analyticsParameters);
                }
            }
        }
    }

    private boolean onActivityResult(int requestCode, int resultCode, Intent data, UUID callId) {
        if (pendingCallId == null || !pendingCallId.equals(callId)) {
            return false;
        }

        // See if we were waiting for a dialog completion
        FacebookDialog.PendingCall pendingCall = PendingCallStore.getInstance().getPendingCallById(pendingCallId);
        if (pendingCall == null) {
            return false;
        }

        // Look for results
        FacebookDialog.handleActivityResult(
                context,
                pendingCall,
                requestCode,
                data,
                getFacebookDialogCallback(pendingCallAnalyticsBundle));

        // The handlers from above will run synchronously. So by the time we get here, it should be safe to
        // stop tracking this call and also serialize the controller to disk
        stopTrackingPendingCall();

        return true;
    }

    private FacebookDialog.Callback getFacebookDialogCallback(final Bundle analyticsParameters) {
        return new FacebookDialog.Callback() {
            @Override
            public void onComplete(FacebookDialog.PendingCall pendingCall, Bundle data) {
                if (!data.containsKey(LIKE_DIALOG_RESPONSE_OBJECT_IS_LIKED_KEY)) {
                    // This is an empty result that we can't handle. Don't lose like state.
                    return;
                }

                boolean isObjectLiked = data.getBoolean(LIKE_DIALOG_RESPONSE_OBJECT_IS_LIKED_KEY);
                String likeCountString = data.getString(LIKE_DIALOG_RESPONSE_LIKE_COUNT_STRING_KEY);
                String socialSentence = data.getString(LIKE_DIALOG_RESPONSE_SOCIAL_SENTENCE_KEY);
                String unlikeToken = data.getString(LIKE_DIALOG_RESPONSE_UNLIKE_TOKEN_KEY);

                Bundle logParams = (analyticsParameters == null) ? new Bundle() : analyticsParameters;
                logParams.putString(AnalyticsEvents.PARAMETER_CALL_ID, pendingCall.getCallId().toString());
                appEventsLogger.logSdkEvent(AnalyticsEvents.EVENT_LIKE_VIEW_DIALOG_DID_SUCCEED, null, logParams);

                updateState(
                        isObjectLiked,
                        likeCountString,
                        likeCountString,
                        socialSentence,
                        socialSentence,
                        unlikeToken);
            }

            @Override
            public void onError(FacebookDialog.PendingCall pendingCall, Exception error, Bundle data) {
                Logger.log(LoggingBehavior.REQUESTS, TAG, "Like Dialog failed with error : %s", error);

                Bundle logParams = analyticsParameters == null ? new Bundle() : analyticsParameters;
                logParams.putString(AnalyticsEvents.PARAMETER_CALL_ID, pendingCall.getCallId().toString());

                // Log the error and AppEvent
                logAppEventForError("present_dialog", logParams);

                broadcastAction(context, LikeActionController.this, ACTION_LIKE_ACTION_CONTROLLER_DID_ERROR, data);
            }
        };
    }

    private void trackPendingCall(FacebookDialog.PendingCall pendingCall, Bundle analyticsParameters) {
        PendingCallStore.getInstance().trackPendingCall(pendingCall);

        // Save off the call id for processing the response
        pendingCallId = pendingCall.getCallId();
        storeObjectIdForPendingController(objectId);

        // Store off the analytics parameters as well, for completion-logging
        pendingCallAnalyticsBundle = analyticsParameters;

        // Serialize to disk, in case we get terminated while waiting for the dialog to complete
        serializeToDiskAsync(this);
    }

    private void stopTrackingPendingCall() {
        PendingCallStore.getInstance().stopTrackingPendingCall(pendingCallId);

        pendingCallId = null;
        pendingCallAnalyticsBundle = null;

        storeObjectIdForPendingController(null);
    }

    private void storeObjectIdForPendingController(String objectId) {
        objectIdForPendingController = objectId;
        context.getSharedPreferences(LIKE_ACTION_CONTROLLER_STORE, Context.MODE_PRIVATE)
                .edit()
                .putString(LIKE_ACTION_CONTROLLER_STORE_PENDING_OBJECT_ID_KEY, objectIdForPendingController)
                .apply();
    }

    private boolean canUseOGPublish(boolean willPerformLike) {
        // Verify that the object isn't a Page, that we have permissions and that, if we're unliking, then
        // we have an unlike token.
        return !objectIsPage &&
                verifiedObjectId != null &&
                session != null &&
                session.getPermissions() != null &&
                session.getPermissions().contains("publish_actions") &&
                (willPerformLike || !Utility.isNullOrEmpty(unlikeToken));
    }

    private void publishLikeAsync(final Activity activity, final Bundle analyticsParameters) {
        isPendingLikeOrUnlike = true;

        fetchVerifiedObjectId(new RequestCompletionCallback() {
            @Override
            public void onComplete() {
                if (Utility.isNullOrEmpty(verifiedObjectId)) {
                    // Could not get a verified id
                    Bundle errorBundle = new Bundle();
                    errorBundle.putString(NativeProtocol.STATUS_ERROR_DESCRIPTION, ERROR_INVALID_OBJECT_ID);

                    broadcastAction(context, LikeActionController.this, ACTION_LIKE_ACTION_CONTROLLER_DID_ERROR, errorBundle);
                    return;
                }

                // Perform the Like.
                RequestBatch requestBatch = new RequestBatch();
                final PublishLikeRequestWrapper likeRequest = new PublishLikeRequestWrapper(verifiedObjectId);
                likeRequest.addToBatch(requestBatch);
                requestBatch.addCallback(new RequestBatch.Callback() {
                    @Override
                    public void onBatchCompleted(RequestBatch batch) {
                        isPendingLikeOrUnlike = false;

                        if (likeRequest.error != null) {
                            // We already updated the UI to show button in the Liked state. Since this failed, let's
                            // revert back to the Unliked state and show the dialog. We need to do this because the
                            // dialog-flow expects the button to only be updated once the dialog returns

                            updateState(
                                    false,
                                    likeCountStringWithLike,
                                    likeCountStringWithoutLike,
                                    socialSentenceWithLike,
                                    socialSentenceWithoutLike,
                                    unlikeToken);

                            presentLikeDialog(activity, analyticsParameters);
                        } else {
                            unlikeToken = Utility.coerceValueIfNullOrEmpty(likeRequest.unlikeToken, null);
                            isObjectLikedOnServer = true;

                            appEventsLogger.logSdkEvent(AnalyticsEvents.EVENT_LIKE_VIEW_DID_LIKE, null, analyticsParameters);

                            toggleAgainIfNeeded(activity, analyticsParameters);
                        }
                    }
                });

                requestBatch.executeAsync();
            }
        });
    }

    private void publishUnlikeAsync(final Activity activity, final Bundle analyticsParameters) {
        isPendingLikeOrUnlike = true;

        // Perform the Unlike.
        RequestBatch requestBatch = new RequestBatch();
        final PublishUnlikeRequestWrapper unlikeRequest = new PublishUnlikeRequestWrapper(unlikeToken);
        unlikeRequest.addToBatch(requestBatch);
        requestBatch.addCallback(new RequestBatch.Callback() {
            @Override
            public void onBatchCompleted(RequestBatch batch) {
                isPendingLikeOrUnlike = false;

                if (unlikeRequest.error != null) {
                    // We already updated the UI to show button in the Unliked state. Since this failed, let's
                    // revert back to the Liked state and show the dialog. We need to do this because the
                    // dialog-flow expects the button to only be updated once the dialog returns

                    updateState(
                            true,
                            likeCountStringWithLike,
                            likeCountStringWithoutLike,
                            socialSentenceWithLike,
                            socialSentenceWithoutLike,
                            unlikeToken);

                    presentLikeDialog(activity, analyticsParameters);
                } else {
                    unlikeToken = null;
                    isObjectLikedOnServer = false;

                    appEventsLogger.logSdkEvent(AnalyticsEvents.EVENT_LIKE_VIEW_DID_UNLIKE, null, analyticsParameters);

                    toggleAgainIfNeeded(activity, analyticsParameters);
                }
            }
        });

        requestBatch.executeAsync();
    }

    private void refreshStatusAsync() {
        if (session == null || session.isClosed() || SessionState.CREATED.equals(session.getState())) {
            // Only when we know that there is no active session, or if there is, it is not open OR being opened,
            // should we attempt getting like state from the service. Otherwise, use the access token of the session
            // to make sure we get the correct like state.
            refreshStatusViaService();
            return;
        }

        fetchVerifiedObjectId(new RequestCompletionCallback() {
            @Override
            public void onComplete() {
                final GetOGObjectLikesRequestWrapper objectLikesRequest =
                        new GetOGObjectLikesRequestWrapper(verifiedObjectId);
                final GetEngagementRequestWrapper engagementRequest =
                        new GetEngagementRequestWrapper(verifiedObjectId);

                RequestBatch requestBatch = new RequestBatch();
                objectLikesRequest.addToBatch(requestBatch);
                engagementRequest.addToBatch(requestBatch);

                requestBatch.addCallback(new RequestBatch.Callback() {
                    @Override
                    public void onBatchCompleted(RequestBatch batch) {
                        if (objectLikesRequest.error != null ||
                                engagementRequest.error != null) {
                            // Refreshing is best-effort. If the refresh fails, don't lose old state.
                            Logger.log(
                                    LoggingBehavior.REQUESTS,
                                    TAG,
                                    "Unable to refresh like state for id: '%s'", objectId);
                            return;
                        }

                        updateState(
                                objectLikesRequest.objectIsLiked,
                                engagementRequest.likeCountStringWithLike,
                                engagementRequest.likeCountStringWithoutLike,
                                engagementRequest.socialSentenceStringWithLike,
                                engagementRequest.socialSentenceStringWithoutLike,
                                objectLikesRequest.unlikeToken);
                    }
                });

                requestBatch.executeAsync();
            }
        });
    }

    private void refreshStatusViaService() {
        LikeStatusClient likeStatusClient = new LikeStatusClient(
                context,
                Settings.getApplicationId(),
                objectId);
        if (!likeStatusClient.start()) {
            return;
        }

        LikeStatusClient.CompletedListener callback = new LikeStatusClient.CompletedListener() {
            @Override
            public void completed(Bundle result) {
                if (result == null || !result.containsKey(NativeProtocol.EXTRA_OBJECT_IS_LIKED)) {
                    // Don't lose old state if the service response is incomplete.
                    return;
                }

                boolean objectIsLiked = result.getBoolean(NativeProtocol.EXTRA_OBJECT_IS_LIKED);
                String likeCountWithLike = result.getString(NativeProtocol.EXTRA_LIKE_COUNT_STRING_WITH_LIKE);
                String likeCountWithoutLike = result.getString(NativeProtocol.EXTRA_LIKE_COUNT_STRING_WITHOUT_LIKE);
                String socialSentenceWithLike = result.getString(NativeProtocol.EXTRA_SOCIAL_SENTENCE_WITH_LIKE);
                String socialSentenceWithoutLike = result.getString(NativeProtocol.EXTRA_SOCIAL_SENTENCE_WITHOUT_LIKE);
                String unlikeToken = result.getString(NativeProtocol.EXTRA_UNLIKE_TOKEN);

                updateState(
                        objectIsLiked,
                        likeCountWithLike,
                        likeCountWithoutLike,
                        socialSentenceWithLike,
                        socialSentenceWithoutLike,
                        unlikeToken);
            }
        };

        likeStatusClient.setCompletedListener(callback);
    }

    private void toggleAgainIfNeeded(Activity activity, Bundle analyticsParameters) {
        if (isObjectLiked != isObjectLikedOnServer) {
            performLikeOrUnlike(activity, isObjectLiked, analyticsParameters);
        }
    }

    private void fetchVerifiedObjectId(final RequestCompletionCallback completionHandler) {
        if (!Utility.isNullOrEmpty(verifiedObjectId)) {
            if (completionHandler != null) {
                completionHandler.onComplete();
            }

            return;
        }

        final GetOGObjectIdRequestWrapper objectIdRequest = new GetOGObjectIdRequestWrapper(objectId);
        final GetPageIdRequestWrapper pageIdRequest = new GetPageIdRequestWrapper(objectId);

        RequestBatch requestBatch = new RequestBatch();
        objectIdRequest.addToBatch(requestBatch);
        pageIdRequest.addToBatch(requestBatch);

        requestBatch.addCallback(new RequestBatch.Callback() {
            @Override
            public void onBatchCompleted(RequestBatch batch) {
                verifiedObjectId = objectIdRequest.verifiedObjectId;
                if (Utility.isNullOrEmpty(verifiedObjectId)) {
                    verifiedObjectId = pageIdRequest.verifiedObjectId;
                    objectIsPage = pageIdRequest.objectIsPage;
                }

                if (Utility.isNullOrEmpty(verifiedObjectId)) {
                    Logger.log(LoggingBehavior.DEVELOPER_ERRORS,
                            TAG,
                            "Unable to verify the FB id for '%s'. Verify that it is a valid FB object or page", objectId);
                    logAppEventForError("get_verified_id",
                            pageIdRequest.error != null ? pageIdRequest.error : objectIdRequest.error);
                }

                if (completionHandler != null) {
                    completionHandler.onComplete();
                }
            }
        });

        requestBatch.executeAsync();
    }

    private void logAppEventForError(String action, Bundle parameters) {
        Bundle logParams = new Bundle(parameters);
        logParams.putString(AnalyticsEvents.PARAMETER_LIKE_VIEW_OBJECT_ID, objectId);
        logParams.putString(AnalyticsEvents.PARAMETER_LIKE_VIEW_CURRENT_ACTION, action);

        appEventsLogger.logSdkEvent(AnalyticsEvents.EVENT_LIKE_VIEW_ERROR, null, logParams);
    }

    private void logAppEventForError(String action, FacebookRequestError error) {
        Bundle logParams = new Bundle();
        if (error != null) {
            JSONObject requestResult = error.getRequestResult();
            if (requestResult != null) {
                logParams.putString(AnalyticsEvents.PARAMETER_LIKE_VIEW_ERROR_JSON, requestResult.toString());
            }
        }
        logAppEventForError(action, logParams);
    }

    //
    // Interfaces
    //

    /**
     * Used by the call to getControllerForObjectId()
     */
    public interface CreationCallback {
        public void onComplete(LikeActionController likeActionController);
    }

    /**
     * Used by all the request wrappers
     */
    private interface RequestCompletionCallback {
        void onComplete();
    }

    //
    // Inner classes
    //

    private class GetOGObjectIdRequestWrapper extends AbstractRequestWrapper {
        String verifiedObjectId;

        GetOGObjectIdRequestWrapper(String objectId) {
            super(objectId);

            Bundle objectIdRequestParams = new Bundle();
            objectIdRequestParams.putString("fields", "og_object.fields(id)");
            objectIdRequestParams.putString("ids", objectId);

            setRequest(new Request(session, "", objectIdRequestParams, HttpMethod.GET));
        }

        @Override
        protected void processError(FacebookRequestError error) {
            // If this object Id is for a Page, an error will be received for this request
            // We will then rely on the other request to come through.
            if (error.getErrorMessage().contains("og_object")) {
                this.error = null;
            } else {
                Logger.log(LoggingBehavior.REQUESTS,
                        TAG,
                        "Error getting the FB id for object '%s' : %s", objectId, error);
            }
        }

        @Override
        protected void processSuccess(Response response) {
            JSONObject results = Utility.tryGetJSONObjectFromResponse(response.getGraphObject(), objectId);
            if (results != null) {
                // See if we can get the OG object Id out
                JSONObject ogObject = results.optJSONObject("og_object");
                if (ogObject != null) {
                    verifiedObjectId = ogObject.optString("id");
                }
            }
        }
    }

    private class GetPageIdRequestWrapper extends AbstractRequestWrapper {
        String verifiedObjectId;
        boolean objectIsPage;

        GetPageIdRequestWrapper(String objectId) {
            super(objectId);

            Bundle pageIdRequestParams = new Bundle();
            pageIdRequestParams.putString("fields", "id");
            pageIdRequestParams.putString("ids", objectId);

            setRequest(new Request(session, "", pageIdRequestParams, HttpMethod.GET));
        }

        @Override
        protected void processSuccess(Response response) {
            JSONObject results = Utility.tryGetJSONObjectFromResponse(response.getGraphObject(), objectId);
            if (results != null) {
                verifiedObjectId = results.optString("id");
                objectIsPage = !Utility.isNullOrEmpty(verifiedObjectId);
            }
        }

        @Override
        protected void processError(FacebookRequestError error) {
            Logger.log(LoggingBehavior.REQUESTS,
                    TAG,
                    "Error getting the FB id for object '%s' : %s", objectId, error);
        }
    }

    private class PublishLikeRequestWrapper extends AbstractRequestWrapper {
        String unlikeToken;

        PublishLikeRequestWrapper(String objectId) {
            super(objectId);

            Bundle likeRequestParams = new Bundle();
            likeRequestParams.putString("object", objectId);

            setRequest(new Request(session, "me/og.likes", likeRequestParams, HttpMethod.POST));
        }

        @Override
        protected void processSuccess(Response response) {
            unlikeToken = Utility.safeGetStringFromResponse(response.getGraphObject(), "id");
        }

        @Override
        protected void processError(FacebookRequestError error) {
            int errorCode = error.getErrorCode();
            if (errorCode == ERROR_CODE_OBJECT_ALREADY_LIKED) {
                // This isn't an error for us. Client was just out of sync with server
                // This will prevent us from showing the dialog for this.

                // However, there is no unliketoken. So a subsequent unlike WILL show the dialog
                this.error = null;
            } else {
                Logger.log(LoggingBehavior.REQUESTS,
                        TAG,
                        "Error liking object '%s' : %s", objectId, error);
                logAppEventForError("publish_like", error);
            }
        }
    }

    private class PublishUnlikeRequestWrapper extends AbstractRequestWrapper {
        private String unlikeToken;

        PublishUnlikeRequestWrapper(String unlikeToken) {
            super(null);

            this.unlikeToken = unlikeToken;

            setRequest(new Request(session, unlikeToken, null, HttpMethod.DELETE));
        }

        @Override
        protected void processSuccess(Response response) {
        }

        @Override
        protected void processError(FacebookRequestError error) {
            Logger.log(LoggingBehavior.REQUESTS,
                    TAG,
                    "Error unliking object with unlike token '%s' : %s", unlikeToken, error);
            logAppEventForError("publish_unlike", error);
        }
    }

    private class GetOGObjectLikesRequestWrapper extends AbstractRequestWrapper {
        boolean objectIsLiked;
        String unlikeToken;

        GetOGObjectLikesRequestWrapper(String objectId) {
            super(objectId);

            Bundle requestParams = new Bundle();
            requestParams.putString("fields", "id,application");
            requestParams.putString("object", objectId);

            setRequest(new Request(session, "me/og.likes", requestParams, HttpMethod.GET));
        }

        @Override
        protected void processSuccess(Response response) {
            JSONArray dataSet = Utility.tryGetJSONArrayFromResponse(response.getGraphObject(), "data");
            if (dataSet != null) {
                for (int i = 0; i < dataSet.length(); i++) {
                    JSONObject data = dataSet.optJSONObject(i);
                    if (data != null) {
                        objectIsLiked = true;
                        JSONObject appData = data.optJSONObject("application");
                        if (appData != null) {
                            if (Utility.areObjectsEqual(session.getApplicationId(), appData.optString("id"))) {
                                unlikeToken = data.optString("id");
                            }
                        }
                    }
                }
            }
        }

        @Override
        protected void processError(FacebookRequestError error) {
            Logger.log(LoggingBehavior.REQUESTS,
                    TAG,
                    "Error fetching like status for object '%s' : %s", objectId, error);
            logAppEventForError("get_og_object_like", error);
        }
    }

    private class GetEngagementRequestWrapper extends AbstractRequestWrapper {
        String likeCountStringWithLike;
        String likeCountStringWithoutLike;
        String socialSentenceStringWithLike;
        String socialSentenceStringWithoutLike;

        GetEngagementRequestWrapper(String objectId) {
            super(objectId);

            Bundle requestParams = new Bundle();
            requestParams.putString(
                    "fields",
                    "engagement.fields(" +
                            "count_string_with_like," +
                            "count_string_without_like," +
                            "social_sentence_with_like," +
                            "social_sentence_without_like)");

            setRequest(new Request(session, objectId, requestParams, HttpMethod.GET));
        }

        @Override
        protected void processSuccess(Response response) {
            JSONObject engagementResults = Utility.tryGetJSONObjectFromResponse(response.getGraphObject(), "engagement");
            if (engagementResults != null) {
                likeCountStringWithLike = engagementResults.optString("count_string_with_like");
                likeCountStringWithoutLike = engagementResults.optString("count_string_without_like");
                socialSentenceStringWithLike = engagementResults.optString("social_sentence_with_like");
                socialSentenceStringWithoutLike = engagementResults.optString("social_sentence_without_like");
            }
        }

        @Override
        protected void processError(FacebookRequestError error) {
            Logger.log(LoggingBehavior.REQUESTS,
                    TAG,
                    "Error fetching engagement for object '%s' : %s", objectId, error);
            logAppEventForError("get_engagement", error);
        }
    }

    private abstract class AbstractRequestWrapper {
        private Request request;
        protected String objectId;

        FacebookRequestError error;

        protected AbstractRequestWrapper(String objectId) {
            this.objectId = objectId;
        }

        void addToBatch(RequestBatch batch) {
            batch.add(request);
        }

        protected void setRequest(Request request) {
            this.request = request;
            // Make sure that our requests are hitting the latest version of the API known to this sdk.
            request.setVersion(ServerProtocol.GRAPH_API_VERSION);
            request.setCallback(new Request.Callback() {
                @Override
                public void onCompleted(Response response) {
                    error = response.getError();
                    if (error != null) {
                        processError(error);
                    } else {
                        processSuccess(response);
                    }
                }
            });
        }

        protected void processError(FacebookRequestError error) {
            Logger.log(LoggingBehavior.REQUESTS,
                    TAG,
                    "Error running request for object '%s' : %s", objectId, error);
        }

        protected abstract void processSuccess(Response response);
    }

    private enum LikeDialogFeature implements FacebookDialog.DialogFeature {

        LIKE_DIALOG(NativeProtocol.PROTOCOL_VERSION_20140701);

        private int minVersion;

        private LikeDialogFeature(int minVersion) {
            this.minVersion = minVersion;
        }

        public String getAction() {
            return NativeProtocol.ACTION_LIKE_DIALOG;
        }

        public int getMinVersion() {
            return minVersion;
        }
    }

    private static class LikeDialogBuilder extends FacebookDialog.Builder<LikeDialogBuilder> {
        private String objectId;

        public LikeDialogBuilder(Activity activity, String objectId) {
            super(activity);

            this.objectId = objectId;
        }

        @Override
        protected EnumSet<? extends FacebookDialog.DialogFeature> getDialogFeatures() {
            return EnumSet.of(LikeDialogFeature.LIKE_DIALOG);
        }

        @Override
        protected Bundle getMethodArguments() {
            Bundle methodArgs = new Bundle();

            methodArgs.putString(NativeProtocol.METHOD_ARGS_OBJECT_ID, objectId);

            return methodArgs;
        }

        public FacebookDialog.PendingCall getAppCall() {
            return appCall;
        }

        public String getApplicationId() {
            return applicationId;
        }

        public String getWebFallbackUrl() {
            return getWebFallbackUrlInternal();
        }
    }

    // Performs cache re-ordering/trimming to keep most-recently-used items up front
    // ** NOTE ** It is expected that only _ONE_ MRUCacheWorkItem is ever running. This is enforced by
    // setting the concurrency of the WorkQueue to 1. Changing the concurrency will most likely lead to errors.
    private static class MRUCacheWorkItem implements Runnable {
        private static ArrayList<String> mruCachedItems = new ArrayList<String>();
        private String cacheItem;
        private boolean shouldTrim;

        MRUCacheWorkItem(String cacheItem, boolean shouldTrim) {
            this.cacheItem = cacheItem;
            this.shouldTrim = shouldTrim;
        }

        @Override
        public void run() {
            if (cacheItem != null) {
                mruCachedItems.remove(cacheItem);
                mruCachedItems.add(0, cacheItem);
            }
            if (shouldTrim && mruCachedItems.size() >= MAX_CACHE_SIZE) {
                int targetSize = MAX_CACHE_SIZE / 2; // Optimize for fewer trim-passes.
                while (targetSize < mruCachedItems.size()) {
                    String cacheKey = mruCachedItems.remove(mruCachedItems.size() - 1);

                    // Here is where we actually remove from the cache of LikeActionControllers.
                    cache.remove(cacheKey);
                }
            }
        }
    }

    private static class SerializeToDiskWorkItem implements Runnable {
        private String cacheKey;
        private String controllerJson;

        SerializeToDiskWorkItem(String cacheKey, String controllerJson) {
            this.cacheKey = cacheKey;
            this.controllerJson = controllerJson;
        }

        @Override
        public void run() {
            serializeToDiskSynchronously(cacheKey, controllerJson);
        }
    }

    private static class CreateLikeActionControllerWorkItem implements Runnable {
        private Context context;
        private String objectId;
        private CreationCallback callback;

        CreateLikeActionControllerWorkItem(Context context, String objectId, CreationCallback callback) {
            this.context = context;
            this.objectId = objectId;
            this.callback = callback;
        }

        @Override
        public void run() {
            createControllerForObjectId(context, objectId, callback);
        }
    }
}


text:
package com.ptrprograms.navigationdrawer.utils;

import com.squareup.otto.Bus;

/**
 * Created by PaulTR on 5/12/14.
 */
public class NavigationBus extends Bus {
	private static final NavigationBus navigationBus = new NavigationBus();

	public static NavigationBus getInstance() {
		return navigationBus;
	}

	private NavigationBus() {

	}

}


text:
<?php

namespace Anthem\Forms\Input;

use Silex\Application;
use Anthem\Forms\Input\VirtualInputInterface;
use Anthem\Forms\Input\BaseInput;

/**
 * An input which allows associating an object to any object of another model.
 * Options are:
 * - ref_model (string, required): Ref model class.
 * - query_target_objects (function, required): A function which retrieves possible target models.
 * - query_ref_objects (function(object), required): A function which retrieves existing ref objects.
 * - set_ref_master_method (string, required): Method of ref model class to set master object.
 * - get_ref_target_id_method (string, required): Method of ref model class to get target object id.
 * - set_ref_target_id_method (string, required): Method of ref model class to set target object id.
 * - empty_message (string): Message to show if no target objects exist.
 */
class PropelManyToManyInput extends BaseInput
                            implements VirtualInputInterface
{
  /**
   * @var \BaseObject $master Master object.
   */
  protected $master;

  /**
   * @var \BaseObject[] $refs Ref objects.
   */
  protected $refs = array();

  /**
   * The constructor.  Checks that options are set, and initializes sub-forms.
   *
   * @param \Silex\Application $app
   * @param array $options
   * @throws \LogicException
   */
  public function __construct(Application $app, array $options = array())
  {
    foreach (array('ref_model', 'query_target_objects', 'query_ref_objects',
                   'set_ref_master_method', 'get_ref_target_id_method', 'set_ref_target_id_method') as $option)
      if (empty($options[$option]))
        throw new \LogicException($option . ' option must be set.');

    $options['target_objects'] = $options['query_target_objects']();
    $options['show_own_help'] = true;

    parent::__construct($app, $options);
  }

  /**
   * Loads a value from object.
   *
   * @param  $object
   * @return void
   */
  public function load($object)
  {
    $refs = $this->options['query_ref_objects']($object);
    foreach ($refs as $ref) $this->refs[call_user_func(array($ref, $this->options['get_ref_target_id_method']))] = $ref;

    $this->value = array();
    foreach ($this->refs as $target_id => $ref)
      $this->value[$target_id] = true;
  }

  /**
   * Saves a value into object.
   *
   * @param  $object
   * @return void
   */
  public function save($object)
  {
    if (is_array($this->value))
    {
      foreach ($this->value as $target_id => $enable)
      {
        if ($enable)
        {
          // Ref object already exists
          if (isset($this->refs[$target_id]))
          {
            unset($this->refs[$target_id]);
            continue;
          }

          // Create ref object
          $ref = new $this->options['ref_model']();
          call_user_func(array($ref, $this->options['set_ref_master_method']), $object);
          call_user_func(array($ref, $this->options['set_ref_target_id_method']), $target_id);
        }
      }
    }

    // Delete all leftover refs
    foreach ($this->refs as $ref) $ref->delete();
  }

  /**
   * Returns default template.
   *
   * @param  none
   * @return string
   */
  protected function getDefaultTemplate()
  {
    return 'Anthem/Forms:many_to_many.php';
  }
}


text:
package com.salton123.mengmei.view.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.salton123.base.AdapterBase;
import com.salton123.mengmei.R;
import com.salton123.mengmei.model.Province;

/**
 * User: 巫金生(newSalton@outlook.com)
 * Date: 2015-10-27
 * Time: 17:53
 * Description:
 */
public class ProvinceAdapter extends AdapterBase {
    public ProvinceAdapter(Context pContext) {
        super(pContext);
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = LayoutInflater.from(GetContext()).inflate(
                    R.layout.adapter_item_province_list, null);
            holder.province = (TextView) convertView.findViewById(R.id.name);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        Province _province = (Province) GetList().get(position);
        holder.province.setText(_province.getName());
        return convertView;
    }
    private class ViewHolder {
        private TextView province;
    }
}


text:
{namespace v=FluidTYPO3\Vhs\ViewHelpers}

<f:layout name="Pi1" />

<f:section name="main">

		<f:if condition="{successMessage}!=''">

				{successMessage}

		</f:if>
		<f:if condition="{errorMessage}!=''">

				{errorMessage}

		</f:if>

</f:section>


text:
<?php

namespace Symfony\Component\Mime\Part\Multipart;

use Symfony\Component\Mime\Exception\InvalidArgumentException;
use Symfony\Component\Mime\Part\AbstractMultipartPart;
use Symfony\Component\Mime\Part\DataPart;
use Symfony\Component\Mime\Part\TextPart;

/**
 * Implements RFC 7578.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 */
final class FormDataPart extends AbstractMultipartPart
{
    private $fields = [];

    /**
     * @param array<string|array|DataPart> $fields
     */
    public function __construct(array $fields = [])
    {
        parent::__construct();

        foreach ($fields as $name => $value) {
            if (!\is_string($value) && !\is_array($value) && !$value instanceof TextPart) {
                throw new InvalidArgumentException(sprintf('A form field value can only be a string, an array, or an instance of TextPart ("%s" given).', get_debug_type($value)));
            }

            $this->fields[$name] = $value;
        }
        // HTTP does not support \r\n in header values
        $this->getHeaders()->setMaxLineLength(\PHP_INT_MAX);
    }

    public function getMediaSubtype(): string
    {
        return 'form-data';
    }

    public function getParts(): array
    {
        return $this->prepareFields($this->fields);
    }

    private function prepareFields(array $fields): array
    {
        $values = [];

        $prepare = function ($item, $key, $root = null) use (&$values, &$prepare) {
            if (\is_int($key) && \is_array($item)) {
                if (1 !== \count($item)) {
                    throw new InvalidArgumentException(sprintf('Form field values with integer keys can only have one array element, the key being the field name and the value being the field value, %d provided.', \count($item)));
                }

                $key = key($item);
                $item = $item[$key];
            }

            $fieldName = null !== $root ? sprintf('%s[%s]', $root, $key) : $key;

            if (\is_array($item)) {
                array_walk($item, $prepare, $fieldName);

                return;
            }

            $values[] = $this->preparePart($fieldName, $item);
        };

        array_walk($fields, $prepare);

        return $values;
    }

    private function preparePart(string $name, string|TextPart $value): TextPart
    {
        if (\is_string($value)) {
            return $this->configurePart($name, new TextPart($value, 'utf-8', 'plain', '8bit'));
        }

        return $this->configurePart($name, $value);
    }

    private function configurePart(string $name, TextPart $part): TextPart
    {
        static $r;

        if (null === $r) {
            $r = new \ReflectionProperty(TextPart::class, 'encoding');
            $r->setAccessible(true);
        }

        $part->setDisposition('form-data');
        $part->setName($name);
        // HTTP does not support \r\n in header values
        $part->getHeaders()->setMaxLineLength(\PHP_INT_MAX);
        $r->setValue($part, '8bit');

        return $part;
    }
}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE401_Memory_Leak__int64_t_realloc_84_bad.cpp
Label Definition File: CWE401_Memory_Leak.c.label.xml
Template File: sources-sinks-84_bad.tmpl.cpp
*/
/*
 * @description
 * CWE: 401 Memory Leak
 * BadSource: realloc Allocate data using realloc()
 * GoodSource: Allocate data on the stack
 * Sinks:
 *    GoodSink: call free() on data
 *    BadSink : no deallocation of data
 * Flow Variant: 84 Data flow: data passed to class constructor and destructor by declaring the class object on the heap and deleting it after use
 *
 * */
#ifndef OMITBAD

#include "std_testcase.h"
#include "CWE401_Memory_Leak__int64_t_realloc_84.h"

namespace CWE401_Memory_Leak__int64_t_realloc_84
{
CWE401_Memory_Leak__int64_t_realloc_84_bad::CWE401_Memory_Leak__int64_t_realloc_84_bad(int64_t * dataCopy)
{
    data = dataCopy;
    /* POTENTIAL FLAW: Allocate memory on the heap */
    data = (int64_t *)realloc(data, 100*sizeof(int64_t));
    if (data == NULL) {exit(-1);}
    /* Initialize and make use of data */
    data[0] = 5LL;
    printLongLongLine(data[0]);
}

CWE401_Memory_Leak__int64_t_realloc_84_bad::~CWE401_Memory_Leak__int64_t_realloc_84_bad()
{
    /* POTENTIAL FLAW: No deallocation */
    ; /* empty statement needed for some flow variants */
}
}
#endif /* OMITBAD */


text:
package amery.spring.aop.program;

public class StudentImpl implements IStudent {

    public void addStudent(String name) {
        System.out.println(" 欢迎  " + name + "  你加入Spring家庭! ");

    }

}


text:
namespace ListBox_
{
    partial class Form1
    {
        /// <summary>
        /// 必要なデザイナ変数です。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 使用中のリソースをすべてクリーンアップします。
        /// </summary>
        /// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows フォーム デザイナで生成されたコード

        /// <summary>
        /// デザイナ サポートに必要なメソッドです。このメソッドの内容を
        /// コード エディタで変更しないでください。
        /// </summary>
        private void InitializeComponent()
        {
            this.listBox1 = new System.Windows.Forms.ListBox();
            this.button1 = new System.Windows.Forms.Button();
            this.SuspendLayout();
            //
            // listBox1
            //
            this.listBox1.FormattingEnabled = true;
            this.listBox1.ItemHeight = 12;
            this.listBox1.Location = new System.Drawing.Point(70, 28);
            this.listBox1.Name = "listBox1";
            this.listBox1.Size = new System.Drawing.Size(154, 136);
            this.listBox1.TabIndex = 0;
            //
            // button1
            //
            this.button1.Location = new System.Drawing.Point(70, 187);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(154, 37);
            this.button1.TabIndex = 1;
            this.button1.Text = "button1";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            //
            // Form1
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(284, 262);
            this.Controls.Add(this.button1);
            this.Controls.Add(this.listBox1);
            this.Name = "Form1";
            this.Text = "Form1";
            this.Load += new System.EventHandler(this.Form1_Load);
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.ListBox listBox1;
        private System.Windows.Forms.Button button1;
    }
}


text:
var app = app || {};

(function($) {
	// hook into the existing rendered form
	app.ConfigurationView = Backbone.View.extend({
		el: "#configuration",
		events: {
			'submit': 'submit'
		},
		initialize: function() {
			// initialize the model
			this.model = new app.Configuration();
			this.model.set('topic',$("#topic").val());
			this.model.set('paragraphs',$("#paragraphs").val());
		},
		submit: function() {
			// catch the form submission and process it here instead
			var topic = $("#topic").val();
			var paragraphs = parseInt($("#paragraphs").val());
			// perform some validation
			if (topic == "" || paragraphs == "NaN" || paragraphs < 1 || paragraphs > 6) {
				// error! but we'll let foundation's error handling deal with it
				return false;
			}

			// start the spinner
			var opts = {
			  lines: 13,
			  length: 5,
			  width: 2,
			  radius: 5,
			  corners: 1,
			  rotate: 0,
			  direction: 1,
			  color: '#000',
			  speed: 1,
			  trail: 60,
			  shadow: false,
			  hwaccel: false,
			  className: 'spinner',
			  zIndex: 1,
			  top: 'auto',
			  left: '30'
			};
			var spinner = new Spinner(opts).spin($(".loading-spinner")[0]);

			// disable search button
			$("#searchButton").addClass("disabled");
			$("#searchButton").attr("disabled","disabled");

			// okay now let's update the model
			this.model.set('topic',topic);
			this.model.set('paragraphs',paragraphs);

			// now we can do something with the model, namely send a server request
			var self = this;
			this.model.save({},{
				success: function(model, response) {
					// clear spinner
					$(".loading-spinner").html("");

					// re-enable search button
					$("#searchButton").removeClass("disabled");
					$("#searchButton").removeAttr("disabled");

					// check search results
					if (model.get("results").length == 0) {
						// no results
						$("#noSearchResultsModal").foundation('reveal','open');
						return false;
					}

					// okay we actually got something back, let's display the results
					self.displaySearchResults(model.get("results"));

				},
				error: function(model, response) {
					// clear spinner
					$(".loading-spinner").html("");

					// re-enable search button
					$("#searchButton").removeClass("disabled");
					$("#searchButton").removeAttr("disabled");

					// show error message
					$("#genericErrorModal").foundation('reveal','open');
				}
			});

			// don't let the page reload
			return false;
		},
		displaySearchResults: function(results) {
			var resultCollection = new app.ResultCollection();
			for (var i = 0; i < results.length; i++) {
				var thisResult = results[i];
				var newResult = new app.ResultItem({title: thisResult['title'], ns: thisResult['ns']});

				// add it to the collection
				resultCollection.add(newResult);
			}

			// okay display the view
			if (typeof app.resultsView != "undefined") {
				// this view already exists in memory so let's purge it and recreate it
				app.resultsModalView.reset();
			}
			app.resultsModalView = new app.ResultsView({collection: resultCollection});

			// cool we don't need the search results any more in this model
			this.model.unset('results');
		}
	});
})(jQuery);


text:
<?php

namespace Symfony\Component\HttpKernel\Debug;

use Symfony\Component\EventDispatcher\EventInterface;
use Symfony\Component\HttpKernel\Log\LoggerInterface;
use Symfony\Component\HttpKernel\Log\DebugLoggerInterface;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\Exception\FlattenException;
use Symfony\Component\HttpFoundation\Request;

/**
 * ExceptionListener.
 *
 * The handle method must be connected to the core.exception event.
 *
 * @author Fabien Potencier <fabien.potencier@symfony-project.com>
 */
class ExceptionListener
{
    protected $controller;
    protected $logger;

    public function __construct($controller, LoggerInterface $logger = null)
    {
        $this->controller = $controller;
        $this->logger = $logger;
    }

    public function handle(EventInterface $event)
    {
        static $handling;

        if (true === $handling) {
            return false;
        }

        $handling = true;

        $exception = $event->get('exception');
        $request = $event->get('request');

        if (null !== $this->logger) {
            $this->logger->err(sprintf('%s: %s (uncaught exception)', get_class($exception), $exception->getMessage()));
        } else {
            error_log(sprintf('Uncaught PHP Exception %s: "%s" at %s line %s', get_class($exception), $exception->getMessage(), $exception->getFile(), $exception->getLine()));
        }

        $logger = null !== $this->logger ? $this->logger->getDebugLogger() : null;

        $attributes = array(
            '_controller' => $this->controller,
            'exception'   => FlattenException::create($exception),
            'logger'      => $logger,
            // when using CLI, we force the format to be TXT
            'format'      => 0 === strncasecmp(PHP_SAPI, 'cli', 3) ? 'txt' : $request->getRequestFormat(),
        );

        $request = $request->duplicate(null, null, $attributes);

        try {
            $response = $event->getSubject()->handle($request, HttpKernelInterface::SUB_REQUEST, true);
        } catch (\Exception $e) {
            $message = sprintf('Exception thrown when handling an exception (%s: %s)', get_class($e), $e->getMessage());
            if (null !== $this->logger) {
                $this->logger->err($message);
            } else {
                error_log($message);
            }

            // re-throw the exception as this is a catch-all
            throw $exception;
        }

        $event->setProcessed();

        $handling = false;

        return $response;
    }
}


text:
"use strict";

var hasOwn = require("mout/object/hasOwn");
var create = require("mout/lang/createObject");
var merge  = require("mout/object/merge");
var kindOf = require("mout/lang/kindOf");
var mixIn  = require("mout/object/mixIn");

var implement = require('./implement');
var verbs = /^Implements|Extends|Binds$/

var uClass = function(proto){

  if(kindOf(proto) === "Function") proto = {initialize: proto};

  var superprime = proto.Extends;

  var constructor = (hasOwn(proto, "initialize")) ? proto.initialize : superprime ? superprime : function(){};

  var out = function() {
    var self = this;
      //autobinding takes place here
    if(proto.Binds) proto.Binds.forEach(function(f){
      var original = self[f];
      if(original)
        self[f] = mixIn(self[f].bind(self), original);
    });

      //clone non function/static properties to current instance
    for(var key in out.prototype) {
      var v = out.prototype[key], t = kindOf(v);

      if(key.match(verbs) || t === "Function" || t == "GeneratorFunction")
        continue;

      if(t == "Object")
        self[key] = merge({}, self[key]); //create(null, self[key]);
      else if(t == "Array")
        self[key] = v.slice(); //clone ??
      else
        self[key] = v;
    }

    if(proto.Implements)
      proto.Implements.forEach(function(Mixin){
        Mixin.call(self);
      });

    constructor.apply(this, arguments);
  }

  if (superprime) {
    // inherit from superprime
      var superproto = superprime.prototype;
      if(superproto.Binds)
        proto.Binds = (proto.Binds || []).concat(superproto.Binds);

      if(superproto.Implements)
        proto.Implements = (proto.Implements || []).concat(superproto.Implements);

      var cproto = out.prototype = create(superproto);
      // setting constructor.parent to superprime.prototype
      // because it's the shortest possible absolute reference
      out.parent = superproto;
      cproto.constructor = out

  }

 if(proto.Implements) {
    if (kindOf(proto.Implements) !== "Array")
      proto.Implements = [proto.Implements];
    proto.Implements.forEach(function(Mixin){
      implement(out, Mixin.prototype);
    });
  }

  implement(out, proto);
  if(proto.Binds)
     out.prototype.Binds = proto.Binds;
  if(proto.Implements)
     out.prototype.Implements = proto.Implements;

  return out;
};

module.exports = uClass;


text:
import { Thread } from './thread';

export class Threads {
  [threadId: string]: Thread
}


text:
import ProgressPromise, { ProgressPromiseDeferred } from "../../lib/ProgressPromise";

export type ProgressPromiseable<T, P> = T | PromiseLike<T> | ProgressPromise<T, P>;
export type ProgressContextDeferred<T, P> = Omit<ProgressPromiseDeferred<T, P>, "progress"> & { progress?: (val: P) => void | undefined };

import defer from "../../lib/defer";

export default class ProgressContext {
    private deferreds: ProgressContextDeferred<number, number>[] = [];

    public constructor(public count: number) {
        this.reset();
    }

    public promises(): Array<PromiseLike<number> | ProgressPromise<number, number>> {
        return this.deferreds.map(d => d.promise);
    }

    public addFake(): this {
        const dfd = defer();
        this.deferreds.push({
            resolve: dfd.resolve,
            reject: dfd.reject,
            progress: undefined,
            promise: <any>dfd.promise
        });

        return this;
    }

    public resolve(): void;
    public resolve(index: number): void;
    public resolve(index: number, value: number): void;
    public resolve(index?: number, value?: number): void {
        if (typeof index === "undefined") {
            this.deferreds.forEach(d => d.resolve());
            return;
        }

        const defer = this.deferreds[index];
        if (defer) {
            defer.resolve(value);
        }
    }

    public reject(): void;
    public reject(index: number): void;
    public reject(index: number, value: number): void;
    public reject(index?: number, reason?: Error | any): void {
        if (typeof index === "undefined") {
            this.deferreds.forEach(d => d.reject(reason));
            return;
        }

        const defer = this.deferreds[index];
        if (defer) {
            defer.reject(reason);
        }
    }

    public progress(index: number): void;
    public progress(index: number, value: number): void;
    public progress(index: number, value?: number): void {
        if (typeof value === "undefined") {
            this.deferreds.forEach(d => d.progress && d.progress(index));
            return;
        }

        const defer = this.deferreds[index];
        if (defer && defer.progress) {
            defer.progress(value);
        }
    }

    public all(): ProgressPromise<number[], Array<number | undefined>> {
        return ProgressPromise.all(this.promises()) as ProgressPromise<number[], Array<number | undefined>>;
    }

    public race(): ProgressPromise<number, Array<number | undefined>> {
        return ProgressPromise.race(this.promises()) as ProgressPromise<number, Array<number | undefined>>;
    }

    public reset(): void {
        this.deferreds = new Array(this.count);

        for (let i = 0; i < this.count; i++) {
            this.deferreds[i] = ProgressPromise.defer<number, number>();
        }
    }
}


text:
.class final Lcom/google/android/gms/internal/fl$p;
.super Lcom/google/android/gms/internal/fl$ao;

# interfaces
.implements Lcom/google/android/gms/games/multiplayer/Invitations$LoadInvitationsResult;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/google/android/gms/internal/fl;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x10
    name = "p"
.end annotation

.annotation system Ldalvik/annotation/Signature;
    value = {
        "Lcom/google/android/gms/internal/fl$ao<Lcom/google/android/gms/common/api/a$c<Lcom/google/android/gms/games/multiplayer/Invitations$LoadInvitationsResult;>;>;Lcom/google/android/gms/games/multiplayer/Invitations$LoadInvitationsResult;"
    }
.end annotation

# instance fields
.field final synthetic tZ:Lcom/google/android/gms/internal/fl;

.field private final ug:Lcom/google/android/gms/games/multiplayer/InvitationBuffer;

# direct methods
.method constructor <init>(Lcom/google/android/gms/internal/fl;Lcom/google/android/gms/common/api/a$c;Lcom/google/android/gms/common/data/DataHolder;)V
    .locals 1
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(Lcom/google/android/gms/common/api/a$c<Lcom/google/android/gms/games/multiplayer/Invitations$LoadInvitationsResult;>;Lcom/google/android/gms/common/data/DataHolder;)V"
        }
    .end annotation

    iput-object p1, p0, Lcom/google/android/gms/internal/fl$p;->tZ:Lcom/google/android/gms/internal/fl;

    invoke-direct {p0, p1, p2, p3}, Lcom/google/android/gms/internal/fl$ao;-><init>(Lcom/google/android/gms/internal/fl;Lcom/google/android/gms/common/api/a$c;Lcom/google/android/gms/common/data/DataHolder;)V

    new-instance v0, Lcom/google/android/gms/games/multiplayer/InvitationBuffer;

    invoke-direct {v0, p3}, Lcom/google/android/gms/games/multiplayer/InvitationBuffer;-><init>(Lcom/google/android/gms/common/data/DataHolder;)V

    iput-object v0, p0, Lcom/google/android/gms/internal/fl$p;->ug:Lcom/google/android/gms/games/multiplayer/InvitationBuffer;

    return-void
.end method

# virtual methods
.method protected final a(Lcom/google/android/gms/common/api/a$c;Lcom/google/android/gms/common/data/DataHolder;)V
    .locals 0
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(Lcom/google/android/gms/common/api/a$c<Lcom/google/android/gms/games/multiplayer/Invitations$LoadInvitationsResult;>;Lcom/google/android/gms/common/data/DataHolder;)V"
        }
    .end annotation

    invoke-interface {p1, p0}, Lcom/google/android/gms/common/api/a$c;->a(Ljava/lang/Object;)V

    return-void
.end method

.method protected final bridge synthetic a(Ljava/lang/Object;Lcom/google/android/gms/common/data/DataHolder;)V
    .locals 1

    move-object v0, p1

    check-cast v0, Lcom/google/android/gms/common/api/a$c;

    invoke-virtual {p0, v0, p2}, Lcom/google/android/gms/internal/fl$p;->a(Lcom/google/android/gms/common/api/a$c;Lcom/google/android/gms/common/data/DataHolder;)V

    return-void
.end method

.method public final getInvitations()Lcom/google/android/gms/games/multiplayer/InvitationBuffer;
    .locals 1

    iget-object v0, p0, Lcom/google/android/gms/internal/fl$p;->ug:Lcom/google/android/gms/games/multiplayer/InvitationBuffer;

    return-object v0
.end method


text:
<?php

namespace Calculate;

use Mockery as m;

class AddOperationTest extends \PHPUnit_Framework_TestCase
{
    public function getAddOperation()
    {
        return new AddOperation;
    }

    public function testAdd()
    {
        $add = $this->getAddOperation();

        $this->assertEquals(4, $add(2, 2));
    }
}


text:
import React from 'react';
import { connect } from 'react-redux';

const injector = (Component) => {
  const Injector = (props) => (
    <Component
      {...props}
    />
  );

  const mapStateToProps = (state) => ({
    featureToggles: state.featureToggles
  });

  return connect(mapStateToProps)(Injector);
};

export default injector;


text:
"""
This is revision from 3058ab9d9d4875589638cc45e84b59e7e1d7c9c3 of
https://github.com/ojii/django-load.

ANY changes to this file, be it upstream fixes or changes for the cms *must* be
documented clearly within this file with comments.

For documentation on how to use the functions described in this file, please
refer to http://django-load.readthedocs.org/en/latest/index.html.
"""
import imp
import traceback # changed

from importlib import import_module
from django.utils.six.moves import filter, map

from .compat.dj import installed_apps

def get_module(app, modname, verbose, failfast):
    """
    Internal function to load a module from a single app.
    """
    module_name = '%s.%s' % (app, modname)
    # the module *should* exist - raise an error if it doesn't
    app_mod = import_module(app)
    try:
        imp.find_module(modname, app_mod.__path__ if hasattr(app_mod, '__path__') else None)
    except ImportError:
        # this ImportError will be due to the module not existing
        # so here we can silently ignore it.  But an ImportError
        # when we import_module() should not be ignored
        if failfast:
            raise
        elif verbose:
            print(u"Could not find %r from %r" % (modname, app)) # changed
            traceback.print_exc() # changed
        return None

    module = import_module(module_name)

    if verbose:
        print(u"Loaded %r from %r" % (modname, app))
    return module

def load(modname, verbose=False, failfast=False):
    """
    Loads all modules with name 'modname' from all installed apps.

    If verbose is True, debug information will be printed to stdout.

    If failfast is True, import errors will not be surpressed.
    """
    for app in installed_apps():
        get_module(app, modname, verbose, failfast)

def iterload(modname, verbose=False, failfast=False):
    """
    Loads all modules with name 'modname' from all installed apps and returns
    and iterator of those modules.

    If verbose is True, debug information will be printed to stdout.

    If failfast is True, import errors will not be surpressed.
    """
    return filter(None, (get_module(app, modname, verbose, failfast)
                         for app in installed_apps()))

def load_object(import_path):
    """
    Loads an object from an 'import_path', like in MIDDLEWARE_CLASSES and the
    likes.

    Import paths should be: "mypackage.mymodule.MyObject". It then imports the
    module up until the last dot and tries to get the attribute after that dot
    from the imported module.

    If the import path does not contain any dots, a TypeError is raised.

    If the module cannot be imported, an ImportError is raised.

    If the attribute does not exist in the module, a AttributeError is raised.
    """
    if '.' not in import_path:
        raise TypeError(
            "'import_path' argument to 'django_load.core.load_object' must "
            "contain at least one dot."
        )
    module_name, object_name = import_path.rsplit('.', 1)
    module = import_module(module_name)
    return getattr(module, object_name)

def iterload_objects(import_paths):
    """
    Load a list of objects.
    """
    return map(load_object, import_paths)

def get_subclasses(c):
    """
    Get all subclasses of a given class
    """
    return c.__subclasses__() + sum(map(get_subclasses, c.__subclasses__()), [])

def load_from_file(module_path):
    """
    Load a python module from its absolute filesystem path
    """
    from imp import load_module, PY_SOURCE

    imported = None
    if module_path:
        with open(module_path, 'r') as openfile:
            imported = load_module("mod", openfile, module_path, ('imported', 'r', PY_SOURCE))
    return imported