text:
var settings_bots = (function () {

var exports = {};

exports.hide_errors = function () {
    $('#bot_table_error').hide();
    $('.bot_error').hide();
};

var focus_tab = {
    add_a_new_bot_tab: function () {
        $("#bots_lists_navbar .active").removeClass("active");
        $("#bots_lists_navbar .add-a-new-bot-tab").addClass("active");
        $("#add-a-new-bot-form").show();
        $("#active_bots_list").hide();
        $("#inactive_bots_list").hide();
        exports.hide_errors();
    },
    active_bots_tab: function () {
        $("#bots_lists_navbar .active").removeClass("active");
        $("#bots_lists_navbar .active-bots-tab").addClass("active");
        $("#add-a-new-bot-form").hide();
        $("#active_bots_list").show();
        $("#inactive_bots_list").hide();
        exports.hide_errors();
    },
    inactive_bots_tab: function () {
        $("#bots_lists_navbar .active").removeClass("active");
        $("#bots_lists_navbar .inactive-bots-tab").addClass("active");
        $("#add-a-new-bot-form").hide();
        $("#active_bots_list").hide();
        $("#inactive_bots_list").show();
        exports.hide_errors();
    },
};

exports.get_bot_info_div = function (bot_id) {
    var sel = '.bot_info[data-user-id="' + bot_id + '"]';
    return $(sel).expectOne();
};

exports.bot_error = function (bot_id, xhr) {
    var bot_info = exports.get_bot_info_div(bot_id);
    var bot_error_div = bot_info.find('.bot_error');
    bot_error_div.text(JSON.parse(xhr.responseText).msg);
    bot_error_div.show();
    var bot_box = bot_info.closest('.bot-information-box');
    bot_box.scrollTop(bot_box[0].scrollHeight - bot_box[0].clientHeight);
};

function add_bot_row(info) {
    var row = $(templates.render('bot_avatar_row', info));
    if (info.is_active) {
        $('#active_bots_list').append(row);
    } else {
        $('#inactive_bots_list').append(row);
    }
}

function is_local_part(value, element) {
    // Adapted from Django's EmailValidator
    return this.optional(element) || /^[\-!#$%&'*+\/=?\^_`{}|~0-9A-Z]+(\.[\-!#$%&'*+\/=?\^_`{}|~0-9A-Z]+)*$/i.test(value);
}

exports.type_id_to_string = function (type_id) {
    var name = _.find(page_params.bot_types, function (bot_type) {
        return bot_type.type_id === type_id;
    }).name;
    return i18n.t(name);
};

exports.render_bots = function () {
    $('#active_bots_list').empty();
    $('#inactive_bots_list').empty();

    var all_bots_for_current_user = bot_data.get_all_bots_for_current_user();
    var user_owns_an_active_bot = false;

    _.each(all_bots_for_current_user, function (elem) {
        add_bot_row({
            name: elem.full_name,
            email: elem.email,
            user_id: elem.user_id,
            type: exports.type_id_to_string(elem.bot_type),
            avatar_url: elem.avatar_url,
            api_key: elem.api_key,
            is_active: elem.is_active,
            zuliprc: 'zuliprc', // Most browsers do not allow filename starting with `.`
        });
        user_owns_an_active_bot = user_owns_an_active_bot || elem.is_active;
    });

    if (settings_bots.can_create_new_bots()) {
        if (!user_owns_an_active_bot) {
            focus_tab.add_a_new_bot_tab();
            return;
        }
    }

    if ($("#bots_lists_navbar .add-a-new-bot-tab").hasClass("active")) {
        $("#add-a-new-bot-form").show();
        $("#active_bots_list").hide();
        $("#inactive_bots_list").hide();
    } else if ($("#bots_lists_navbar .active-bots-tab").hasClass("active")) {
        $("#add-a-new-bot-form").hide();
        $("#active_bots_list").show();
        $("#inactive_bots_list").hide();
    } else {
        $("#add-a-new-bot-form").hide();
        $("#active_bots_list").hide();
        $("#inactive_bots_list").show();
    }
};

exports.generate_zuliprc_uri = function (bot_id) {
    var bot = bot_data.get(bot_id);
    var data;
    var token;
    // For outgoing webhooks, include the token in the zuliprc.
    // It's needed for authenticating to the Botserver.
    if (bot.bot_type === 3) {
        token = bot_data.get_services(bot_id)[0].token;
    }
    data = exports.generate_zuliprc_content(bot.email, bot.api_key, token);
    return exports.encode_zuliprc_as_uri(data);
};

exports.encode_zuliprc_as_uri = function (zuliprc) {
    return "data:application/octet-stream;charset=utf-8," + encodeURIComponent(zuliprc);
};

exports.generate_zuliprc_content = function (email, api_key, token) {
    return "[api]" +
           "\nemail=" + email +
           "\nkey=" + api_key +
           "\nsite=" + page_params.realm_uri +
           (token === undefined ? "" : "\ntoken=" + token) +
           // Some tools would not work in files without a trailing new line.
           "\n";
};

exports.generate_botserverrc_content = function (email, api_key, token) {
    return "[]" +
           "\nemail=" + email +
           "\nkey=" + api_key +
           "\nsite=" + page_params.realm_uri +
           "\ntoken=" + token +
           "\n";
};

exports.bot_creation_policy_values = {
    everyone: {
        code: 1,
        description: i18n.t("Members and admins"),
    },
    admins_only: {
        code: 3,
        description: i18n.t("Admins only"),
    },
    restricted: {
        code: 2,
        description: i18n.t("Members and admins, but only admins can add generic bots"),
    },
};

exports.can_create_new_bots = function () {
    if (page_params.is_admin) {
        return true;
    }

    if (page_params.is_guest) {
        return false;
    }

    return page_params.realm_bot_creation_policy !==
        exports.bot_creation_policy_values.admins_only.code;
};

exports.update_bot_settings_tip = function () {
    var permission_type = exports.bot_creation_policy_values;
    var current_permission = page_params.realm_bot_creation_policy;
    var tip_text;
    if (current_permission === permission_type.admins_only.code) {
        tip_text = i18n.t("Only organization administrators can add bots to this organization");
    } else if (current_permission === permission_type.restricted.code) {
        tip_text = i18n.t("Only organization administrators can add generic bots");
    } else {
        tip_text = i18n.t("Anyone in this organization can add bots");
    }
    $(".bot-settings-tip").text(tip_text);
};

exports.update_bot_permissions_ui = function () {
    exports.update_bot_settings_tip();
    exports.hide_errors();
    $("#id_realm_bot_creation_policy").val(page_params.realm_bot_creation_policy);
    if (!exports.can_create_new_bots()) {
        $('#create_bot_form').hide();
        $('.add-a-new-bot-tab').hide();
        focus_tab.active_bots_tab();
    } else {
        $('#create_bot_form').show();
        $('.add-a-new-bot-tab').show();
    }
};

exports.set_up = function () {
    $('#payload_url_inputbox').hide();
    $('#create_payload_url').val('');
    $('#service_name_list').hide();
    $('#config_inputbox').hide();
    var selected_embedded_bot = 'converter';
    $('#select_service_name').val(selected_embedded_bot); // TODO: Use 'select a bot'.
    $('#config_inputbox').children().hide();
    $("[name*='" + selected_embedded_bot + "']").show();

    $('#download_botserverrc').click(function () {
        var OUTGOING_WEBHOOK_BOT_TYPE_INT = 3;
        var content = "";
        _.each(bot_data.get_all_bots_for_current_user(), function (bot) {
            if (bot.is_active && bot.bot_type === OUTGOING_WEBHOOK_BOT_TYPE_INT) {
                var bot_token = bot_data.get_services(bot.user_id)[0].token;
                content += exports.generate_botserverrc_content(bot.email, bot.api_key, bot_token);
            }
        });
        $(this).attr("href", "data:application/octet-stream;charset=utf-8," + encodeURIComponent(content));
    });

    exports.render_bots();

    $.validator.addMethod("bot_local_part",
                          function (value, element) {
                              return is_local_part.call(this, value + "-bot", element);
                          },
                          "Please only use characters that are valid in an email address");

    var create_avatar_widget = avatar.build_bot_create_widget();
    var OUTGOING_WEBHOOK_BOT_TYPE = '3';
    var GENERIC_BOT_TYPE = '1';
    var EMBEDDED_BOT_TYPE = '4';

    var GENERIC_INTERFACE = '1';

    $('#create_bot_form').validate({
        errorClass: 'text-error',
        success: function () {
            exports.hide_errors();
        },
        submitHandler: function () {
            var bot_type = $('#create_bot_type :selected').val();
            var full_name = $('#create_bot_name').val();
            var short_name = $('#create_bot_short_name').val() || $('#create_bot_short_name').text();
            var payload_url = $('#create_payload_url').val();
            var interface_type = $('#create_interface_type').val();
            var service_name = $('#select_service_name :selected').val();
            var formData = new FormData();
            var spinner = $('.create_bot_spinner');

            formData.append('csrfmiddlewaretoken', csrf_token);
            formData.append('bot_type', bot_type);
            formData.append('full_name', full_name);
            formData.append('short_name', short_name);

            // If the selected bot_type is Outgoing webhook
            if (bot_type === OUTGOING_WEBHOOK_BOT_TYPE) {
                formData.append('payload_url', JSON.stringify(payload_url));
                formData.append('interface_type', interface_type);
            } else if (bot_type === EMBEDDED_BOT_TYPE) {
                formData.append('service_name', service_name);
                var config_data = {};
                $("#config_inputbox [name*='" + service_name + "'] input").each(function () {
                    config_data[$(this).attr('name')] = $(this).val();
                });
                formData.append('config_data', JSON.stringify(config_data));
            }
            jQuery.each($('#bot_avatar_file_input')[0].files, function (i, file) {
                formData.append('file-' + i, file);
            });
            loading.make_indicator(spinner, {text: i18n.t('Creating bot')});
            channel.post({
                url: '/json/bots',
                data: formData,
                cache: false,
                processData: false,
                contentType: false,
                success: function () {
                    exports.hide_errors();
                    $('#create_bot_name').val('');
                    $('#create_bot_short_name').val('');
                    $('#create_payload_url').val('');
                    $('#payload_url_inputbox').hide();
                    $('#config_inputbox').hide();
                    $("[name*='" + service_name + "'] input").each(function () {
                        $(this).val('');
                    });
                    $('#create_bot_type').val(GENERIC_BOT_TYPE);
                    $('#select_service_name').val('converter'); // TODO: Later we can change this to hello bot or similar
                    $('#service_name_list').hide();
                    $('#create_bot_button').show();
                    $('#create_interface_type').val(GENERIC_INTERFACE);
                    create_avatar_widget.clear();
                    $("#bots_lists_navbar .add-a-new-bot-tab").removeClass("active");
                    $("#bots_lists_navbar .active-bots-tab").addClass("active");
                },
                error: function (xhr) {
                    $('#bot_table_error').text(JSON.parse(xhr.responseText).msg).show();
                },
                complete: function () {
                    loading.destroy_indicator(spinner);
                },
            });
        },
    });

    $("#create_bot_type").on("change", function () {
        var bot_type = $('#create_bot_type :selected').val();
        // For "generic bot" or "incoming webhook" both these fields need not be displayed.
        $('#service_name_list').hide();
        $('#select_service_name').removeClass('required');
        $('#config_inputbox').hide();

        $('#payload_url_inputbox').hide();
        $('#create_payload_url').removeClass('required');
        if (bot_type === OUTGOING_WEBHOOK_BOT_TYPE) {
            $('#payload_url_inputbox').show();
            $('#create_payload_url').addClass('required');

        } else if (bot_type === EMBEDDED_BOT_TYPE) {
            $('#service_name_list').show();
            $('#select_service_name').addClass('required');
            $("#select_service_name").trigger('change');
            $('#config_inputbox').show();
        }
    });

    $("#select_service_name").on("change", function () {
        $('#config_inputbox').children().hide();
        var selected_bot = $('#select_service_name :selected').val();
        $("[name*='" + selected_bot + "']").show();
    });

    $("#active_bots_list").on("click", "button.delete_bot", function (e) {
        var bot_id = $(e.currentTarget).attr('data-user-id');

        channel.del({
            url: '/json/bots/' + encodeURIComponent(bot_id),
            success: function () {
                var row = $(e.currentTarget).closest("li");
                row.hide('slow', function () { row.remove(); });
            },
            error: function (xhr) {
                exports.bot_error(bot_id, xhr);
            },
        });
    });

    $("#inactive_bots_list").on("click", "button.reactivate_bot", function (e) {
        var user_id = $(e.currentTarget).attr('data-user-id');

        channel.post({
            url: '/json/users/' + encodeURIComponent(user_id) + "/reactivate",
            error: function (xhr) {
                exports.bot_error(user_id, xhr);
            },
        });
    });

    $("#active_bots_list").on("click", "button.regenerate_bot_api_key", function (e) {
        var bot_id = $(e.currentTarget).attr('data-user-id');
        channel.post({
            url: '/json/bots/' + encodeURIComponent(bot_id) + '/api_key/regenerate',
            idempotent: true,
            success: function (data) {
                var row = $(e.currentTarget).closest("li");
                row.find(".api_key").find(".value").text(data.api_key);
                row.find("api_key_error").hide();
            },
            error: function (xhr) {
                var row = $(e.currentTarget).closest("li");
                row.find(".api_key_error").text(JSON.parse(xhr.responseText).msg).show();
            },
        });
    });

    var image_version = 0;

    $("#active_bots_list").on("click", "button.open_edit_bot_form", function (e) {
        var li = $(e.currentTarget).closest('li');
        var bot_id = li.find('.bot_info').attr('data-user-id').valueOf();
        var bot = bot_data.get(bot_id);
        var users_list = people.get_active_human_persons();
        $("#edit_bot").empty();
        $("#edit_bot").append(templates.render('edit_bot', {bot: bot,
                                                            users_list: users_list}));
        var avatar_widget = avatar.build_bot_edit_widget($("#settings_page"));
        var form = $('#settings_page .edit_bot_form');
        var image = li.find(".image");
        var errors = form.find('.bot_edit_errors');

        $("#settings_page .edit_bot .edit-bot-owner select").val(bot.owner);
        var service = bot_data.get_services(bot_id)[0];
        if (bot.bot_type.toString() === OUTGOING_WEBHOOK_BOT_TYPE) {
            $("#service_data").append(templates.render("edit-outgoing-webhook-service",
                                                       {service: service}));
            $("#edit_service_interface").val(service.interface);
        }
        if (bot.bot_type.toString() === EMBEDDED_BOT_TYPE) {
            $("#service_data").append(templates.render("edit-embedded-bot-service",
                                                       {service: service}));
        }

        avatar_widget.clear();

        form.validate({
            errorClass: 'text-error',
            success: function () {
                errors.hide();
            },
            submitHandler: function () {
                var bot_id = form.attr('data-user-id');
                var type = form.attr('data-type');

                var full_name = form.find('.edit_bot_name').val();
                var bot_owner = form.find('.edit-bot-owner select').val();
                var file_input = $(".edit_bot").find('.edit_bot_avatar_file_input');
                var spinner = form.find('.edit_bot_spinner');
                var edit_button = form.find('.edit_bot_button');

                var formData = new FormData();
                formData.append('csrfmiddlewaretoken', csrf_token);
                formData.append('full_name', full_name);
                formData.append('bot_owner_id', people.get_by_email(bot_owner).user_id);

                if (type === OUTGOING_WEBHOOK_BOT_TYPE) {
                    var service_payload_url = $("#edit_service_base_url").val();
                    var service_interface = $("#edit_service_interface :selected").val();
                    formData.append('service_payload_url', JSON.stringify(service_payload_url));
                    formData.append('service_interface', service_interface);
                } else if (type === EMBEDDED_BOT_TYPE) {
                    var config_data = {};
                    $("#config_edit_inputbox input").each(function () {
                        config_data[$(this).attr('name')] = $(this).val();
                    });
                    formData.append('config_data', JSON.stringify(config_data));
                }
                jQuery.each(file_input[0].files, function (i, file) {
                    formData.append('file-' + i, file);
                });
                loading.make_indicator(spinner, {text: 'Editing bot'});
                edit_button.hide();
                channel.patch({
                    url: '/json/bots/' + encodeURIComponent(bot_id),
                    data: formData,
                    cache: false,
                    processData: false,
                    contentType: false,
                    success: function (data) {
                        loading.destroy_indicator(spinner);
                        errors.hide();
                        edit_button.show();
                        avatar_widget.clear();
                        typeahead_helper.clear_rendered_person(bot_id);
                        if (data.avatar_url) {
                            // Note that the avatar_url won't actually change on the back end
                            // when the user had a previous uploaded avatar.  Only the content
                            // changes, so we version it to get an uncached copy.
                            image_version += 1;
                            image.find('img').attr('src', data.avatar_url + '&v=' + image_version.toString());
                        }
                    },
                    error: function (xhr) {
                        loading.destroy_indicator(spinner);
                        edit_button.show();
                        errors.text(JSON.parse(xhr.responseText).msg).show();
                    },
                });
            },
        });
    });

    $("#active_bots_list").on("click", "a.download_bot_zuliprc", function () {
        var bot_info = $(this).closest(".bot-information-box").find(".bot_info");
        var bot_id = bot_info.attr("data-user-id");
        $(this).attr("href", exports.generate_zuliprc_uri(bot_id));
    });

    new ClipboardJS('#copy_zuliprc', {
        text: function (trigger) {
            var bot_info = trigger.closest(".bot-information-box");
            var email = $(bot_info).find(".email .value").text();
            var api_key = $(bot_info).find(".api_key .api-key-value-and-button .value").text();
            var data = exports.generate_zuliprc_content(email.trim(), api_key.trim());
            return data;
        },
    });

    $("#bots_lists_navbar .add-a-new-bot-tab").click(function (e) {
        e.preventDefault();
        e.stopPropagation();
        focus_tab.add_a_new_bot_tab();
    });

    $("#bots_lists_navbar .active-bots-tab").click(function (e) {
        e.preventDefault();
        e.stopPropagation();
        focus_tab.active_bots_tab();
    });

    $("#bots_lists_navbar .inactive-bots-tab").click(function (e) {
        e.preventDefault();
        e.stopPropagation();
        focus_tab.inactive_bots_tab();
    });

};

return exports;
}());

if (typeof module !== 'undefined') {
    module.exports = settings_bots;
}
window.settings_bots = settings_bots;


text:
using base::android::ConvertJavaStringToUTF8;
using base::android::ConvertUTF8ToJavaString;
using base::android::JavaParamRef;
using base::android::ScopedJavaGlobalRef;
using base::android::ScopedJavaLocalRef;

namespace offline_pages {
namespace android {

namespace {

void ToJavaOfflinePageList(JNIEnv* env,
                           jobject j_result_obj,
                           const std::vector<OfflinePageItem>& offline_pages) {
  for (const OfflinePageItem& offline_page : offline_pages) {
    Java_OfflinePageEvaluationBridge_createOfflinePageAndAddToList(
        env, j_result_obj,
        ConvertUTF8ToJavaString(env, offline_page.url.spec()),
        offline_page.offline_id,
        ConvertUTF8ToJavaString(env, offline_page.client_id.name_space),
        ConvertUTF8ToJavaString(env, offline_page.client_id.id),
        ConvertUTF8ToJavaString(env, offline_page.file_path.value()),
        offline_page.file_size, offline_page.creation_time.ToJavaTime(),
        offline_page.access_count, offline_page.last_access_time.ToJavaTime());
  }
}

ScopedJavaLocalRef<jobject> ToJavaSavePageRequest(
    JNIEnv* env,
    const SavePageRequest& request) {
  return Java_SavePageRequest_create(
      env, static_cast<int>(request.request_state()), request.request_id(),
      ConvertUTF8ToJavaString(env, request.url().spec()),
      ConvertUTF8ToJavaString(env, request.client_id().name_space),
      ConvertUTF8ToJavaString(env, request.client_id().id));
}

ScopedJavaLocalRef<jobjectArray> CreateJavaSavePageRequests(
    JNIEnv* env,
    std::vector<std::unique_ptr<SavePageRequest>> requests) {
  ScopedJavaLocalRef<jclass> save_page_request_clazz = base::android::GetClass(
      env, "org/chromium/chrome/browser/offlinepages/SavePageRequest");
  jobjectArray joa = env->NewObjectArray(
      requests.size(), save_page_request_clazz.obj(), nullptr);
  base::android::CheckException(env);

  for (size_t i = 0; i < requests.size(); i++) {
    SavePageRequest request = *(requests[i]);
    ScopedJavaLocalRef<jobject> j_save_page_request =
        ToJavaSavePageRequest(env, request);
    env->SetObjectArrayElement(joa, i, j_save_page_request.obj());
  }

  return ScopedJavaLocalRef<jobjectArray>(env, joa);
}

void GetAllPagesCallback(
    const ScopedJavaGlobalRef<jobject>& j_result_obj,
    const ScopedJavaGlobalRef<jobject>& j_callback_obj,
    const OfflinePageModel::MultipleOfflinePageItemResult& result) {
  JNIEnv* env = base::android::AttachCurrentThread();
  ToJavaOfflinePageList(env, j_result_obj.obj(), result);
  base::android::RunCallbackAndroid(j_callback_obj, j_result_obj);
}

void OnPushRequestsDone(const ScopedJavaGlobalRef<jobject>& j_callback_obj,
                        bool result) {
  base::android::RunCallbackAndroid(j_callback_obj, result);
}

void OnGetAllRequestsDone(
    const ScopedJavaGlobalRef<jobject>& j_callback_obj,
    std::vector<std::unique_ptr<SavePageRequest>> all_requests) {
  JNIEnv* env = base::android::AttachCurrentThread();

  ScopedJavaLocalRef<jobjectArray> j_result_obj =
      CreateJavaSavePageRequests(env, std::move(all_requests));
  base::android::RunCallbackAndroid(j_callback_obj, j_result_obj);
}

void OnRemoveRequestsDone(const ScopedJavaGlobalRef<jobject>& j_callback_obj,
                          const MultipleItemStatuses& removed_request_results) {
  base::android::RunCallbackAndroid(j_callback_obj,
                                    int(removed_request_results.size()));
}
}  // namespace

static ScopedJavaLocalRef<jobject> GetBridgeForProfile(
    JNIEnv* env,
    const JavaParamRef<jclass>& jcaller,
    const JavaParamRef<jobject>& j_profile,
    const jboolean j_use_evaluation_scheduler) {
  Profile* profile = ProfileAndroid::FromProfileAndroid(j_profile);

  OfflinePageModel* offline_page_model =
      OfflinePageModelFactory::GetForBrowserContext(profile);

  RequestCoordinator* request_coordinator = nullptr;

  if (j_use_evaluation_scheduler) {
    request_coordinator = static_cast<RequestCoordinator*>(
        RequestCoordinatorFactory::GetInstance()->SetTestingFactoryAndUse(
            profile,
            &OfflinePageEvaluationBridge::GetTestingRequestCoordinator));
  } else {
    request_coordinator =
        RequestCoordinatorFactory::GetForBrowserContext(profile);
  }

  if (offline_page_model == nullptr || request_coordinator == nullptr)
    return ScopedJavaLocalRef<jobject>();

  OfflinePageEvaluationBridge* bridge = new OfflinePageEvaluationBridge(
      env, profile, offline_page_model, request_coordinator);

  return ScopedJavaLocalRef<jobject>(bridge->java_ref());
}

// static
bool OfflinePageEvaluationBridge::Register(JNIEnv* env) {
  return RegisterNativesImpl(env);
}

// static
std::unique_ptr<KeyedService>
OfflinePageEvaluationBridge::GetTestingRequestCoordinator(
    content::BrowserContext* context) {
  std::unique_ptr<OfflinerPolicy> policy(new OfflinerPolicy());
  std::unique_ptr<OfflinerFactory> prerenderer_offliner(
      new PrerenderingOfflinerFactory(context));

  scoped_refptr<base::SequencedTaskRunner> background_task_runner =
      content::BrowserThread::GetBlockingPool()->GetSequencedTaskRunner(
          content::BrowserThread::GetBlockingPool()->GetSequenceToken());
  Profile* profile = Profile::FromBrowserContext(context);
  base::FilePath queue_store_path =
      profile->GetPath().Append(chrome::kOfflinePageRequestQueueDirname);

  std::unique_ptr<RequestQueueStoreSQL> queue_store(
      new RequestQueueStoreSQL(background_task_runner, queue_store_path));
  std::unique_ptr<RequestQueue> queue(new RequestQueue(std::move(queue_store)));
  std::unique_ptr<android::EvaluationTestScheduler> scheduler(
      new android::EvaluationTestScheduler());
  net::NetworkQualityEstimator::NetworkQualityProvider*
      network_quality_estimator =
          UINetworkQualityEstimatorServiceFactory::GetForProfile(profile);
  // TODO(fgorski): Something needs to keep the handle to the Notification
  // dispatcher.
  std::unique_ptr<RequestCoordinator> request_coordinator =
      base::MakeUnique<RequestCoordinator>(
          std::move(policy), std::move(prerenderer_offliner), std::move(queue),
          std::move(scheduler), network_quality_estimator);
  request_coordinator->SetImmediateScheduleCallbackForTest(
      base::Bind(&android::EvaluationTestScheduler::ImmediateScheduleCallback,
                 base::Unretained(scheduler.get())));

  DownloadNotifyingObserver::CreateAndStartObserving(
      request_coordinator.get(),
      base::MakeUnique<android::OfflinePageNotificationBridge>());

  return std::move(request_coordinator);
}

OfflinePageEvaluationBridge::OfflinePageEvaluationBridge(
    JNIEnv* env,
    content::BrowserContext* browser_context,
    OfflinePageModel* offline_page_model,
    RequestCoordinator* request_coordinator)
    : browser_context_(browser_context),
      offline_page_model_(offline_page_model),
      request_coordinator_(request_coordinator) {
  java_ref_.Reset(Java_OfflinePageEvaluationBridge_create(
      env, reinterpret_cast<jlong>(this)));

  NotifyIfDoneLoading();
  offline_page_model_->AddObserver(this);
  request_coordinator_->AddObserver(this);
}

OfflinePageEvaluationBridge::~OfflinePageEvaluationBridge() {
  JNIEnv* env = base::android::AttachCurrentThread();
  Java_OfflinePageEvaluationBridge_offlinePageEvaluationBridgeDestroyed(
      env, java_ref_);
}

// Implement OfflinePageModel::Observer
void OfflinePageEvaluationBridge::OfflinePageModelLoaded(
    OfflinePageModel* model) {
  DCHECK_EQ(offline_page_model_, model);
  NotifyIfDoneLoading();
}

void OfflinePageEvaluationBridge::OfflinePageModelChanged(
    OfflinePageModel* model) {}

void OfflinePageEvaluationBridge::OfflinePageDeleted(
    int64_t offline_id,
    const ClientId& client_id) {}

// Implement RequestCoordinator::Observer
void OfflinePageEvaluationBridge::OnAdded(const SavePageRequest& request) {
  JNIEnv* env = base::android::AttachCurrentThread();
  Java_OfflinePageEvaluationBridge_savePageRequestAdded(
      env, java_ref_, ToJavaSavePageRequest(env, request));
}

void OfflinePageEvaluationBridge::OnCompleted(
    const SavePageRequest& request,
    RequestNotifier::BackgroundSavePageResult status) {
  JNIEnv* env = base::android::AttachCurrentThread();
  Java_OfflinePageEvaluationBridge_savePageRequestCompleted(
      env, java_ref_, ToJavaSavePageRequest(env, request),
      static_cast<int>(status));
}

void OfflinePageEvaluationBridge::OnChanged(const SavePageRequest& request) {
  JNIEnv* env = base::android::AttachCurrentThread();
  Java_OfflinePageEvaluationBridge_savePageRequestChanged(
      env, java_ref_, ToJavaSavePageRequest(env, request));
}

void OfflinePageEvaluationBridge::GetAllPages(
    JNIEnv* env,
    const JavaParamRef<jobject>& obj,
    const JavaParamRef<jobject>& j_result_obj,
    const JavaParamRef<jobject>& j_callback_obj) {
  DCHECK(j_result_obj);
  DCHECK(j_callback_obj);

  ScopedJavaGlobalRef<jobject> j_result_ref(j_result_obj);
  ScopedJavaGlobalRef<jobject> j_callback_ref(j_callback_obj);

  offline_page_model_->GetAllPages(
      base::Bind(&GetAllPagesCallback, j_result_ref, j_callback_ref));
}

bool OfflinePageEvaluationBridge::PushRequestProcessing(
    JNIEnv* env,
    const JavaParamRef<jobject>& obj,
    const JavaParamRef<jobject>& j_callback_obj) {
  ScopedJavaGlobalRef<jobject> j_callback_ref(j_callback_obj);
  DCHECK(request_coordinator_);
  base::android::RunCallbackAndroid(j_callback_obj, false);

  net::NetworkChangeNotifier::ConnectionType connection =
      net::NetworkChangeNotifier::GetConnectionType();
  DeviceConditions device_conditions(false, 0, connection);
  return request_coordinator_->StartProcessing(
      device_conditions, base::Bind(&OnPushRequestsDone, j_callback_ref));
}

void OfflinePageEvaluationBridge::SavePageLater(
    JNIEnv* env,
    const JavaParamRef<jobject>& obj,
    const JavaParamRef<jstring>& j_url,
    const JavaParamRef<jstring>& j_namespace,
    const JavaParamRef<jstring>& j_client_id,
    jboolean user_requested) {
  offline_pages::ClientId client_id;
  client_id.name_space = ConvertJavaStringToUTF8(env, j_namespace);
  client_id.id = ConvertJavaStringToUTF8(env, j_client_id);

  request_coordinator_->SavePageLater(
      GURL(ConvertJavaStringToUTF8(env, j_url)), client_id,
      static_cast<bool>(user_requested),
      RequestCoordinator::RequestAvailability::ENABLED_FOR_OFFLINER);
}

void OfflinePageEvaluationBridge::GetRequestsInQueue(
    JNIEnv* env,
    const JavaParamRef<jobject>& obj,
    const JavaParamRef<jobject>& j_callback_obj) {
  ScopedJavaGlobalRef<jobject> j_callback_ref(j_callback_obj);
  request_coordinator_->GetAllRequests(
      base::Bind(&OnGetAllRequestsDone, j_callback_ref));
}

void OfflinePageEvaluationBridge::RemoveRequestsFromQueue(
    JNIEnv* env,
    const JavaParamRef<jobject>& obj,
    const JavaParamRef<jlongArray>& j_request_ids,
    const JavaParamRef<jobject>& j_callback_obj) {
  std::vector<int64_t> request_ids;
  base::android::JavaLongArrayToInt64Vector(env, j_request_ids, &request_ids);
  ScopedJavaGlobalRef<jobject> j_callback_ref(j_callback_obj);
  request_coordinator_->RemoveRequests(
      request_ids, base::Bind(&OnRemoveRequestsDone, j_callback_ref));
}

void OfflinePageEvaluationBridge::NotifyIfDoneLoading() const {
  if (!offline_page_model_->is_loaded())
    return;
  JNIEnv* env = base::android::AttachCurrentThread();
  Java_OfflinePageEvaluationBridge_offlinePageModelLoaded(env, java_ref_);
}

}  // namespace android
}  // namespace offline_pages

redpajama_set_name: RedPajamaGithub


text:
import React from "react";

import SvgIcon from "../components/svg/SvgIcon";

import {ProjectContext} from "../project/constants";
import {findObject, getNextInSequence} from "../utils/sequence";

export default class AnswerDesigner extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            selectedColor: this.props.color || "#1527f6",
            newAnswerText: this.props.answer || "",
            required: this.props.required || false
        };
    }

    removeAnswer = () => {
        const {surveyQuestionId, answerId} = this.props;
        const {surveyQuestions, setProjectDetails} = this.context;
        const matchingQuestion = findObject(
            surveyQuestions,
            ([_id, sq]) => sq.parentQuestionId === surveyQuestionId && sq.parentAnswerIds.includes(answerId)
        );
        if (matchingQuestion) {
            alert(
                "You cannot remove this answer because a sub question ("
                + matchingQuestion[1].question
                + ") is referencing it."
            );
        } else {
            const surveyQuestion = surveyQuestions[surveyQuestionId];
            // eslint-disable-next-line no-unused-vars
            const {[answerId]: _id, ...remainingAnswers} = surveyQuestion.answers;
            setProjectDetails({
                surveyQuestions: {
                    ...surveyQuestions,
                    [surveyQuestionId]: {...surveyQuestion, answers: remainingAnswers}
                }
            });
        }
    };

    saveSurveyAnswer = () => {
        const {surveyQuestionId, surveyQuestion, answerId} = this.props;
        const {surveyQuestions, setProjectDetails} = this.context;
        if (this.state.newAnswerText.length > 0) {
            const newId = answerId || getNextInSequence(Object.keys(surveyQuestion.answers));
            const newAnswer = {
                answer: this.state.newAnswerText,
                color: this.state.selectedColor,
                ...surveyQuestion.componentType === "input" && {required: this.state.required}
            };
            setProjectDetails({
                surveyQuestions: {
                    ...surveyQuestions,
                    [surveyQuestionId]: {
                        ...surveyQuestion,
                        answers: {
                            ...surveyQuestion.answers,
                            [newId]: newAnswer
                        }
                    }
                }
            });
            if (answerId == null) this.setState({selectedColor: "#1527f6", newAnswerText: ""});
        } else {
            alert("Please enter a value for the answer.");
        }
    };

    renderExisting = () => {
        const {answer, color, required, surveyQuestion} = this.props;
        return (

                        {answer}

                {surveyQuestion.componentType === "input" && required && (

Required

                )}

        );
    };

    renderNew = () => {
        const {surveyQuestion, answerId, editMode} = this.props;
        const {newAnswerText, selectedColor} = this.state;
        return (

                    {answerId != null
                        ? (
                            <>
                                {editMode === "full" && (
                                    <button
                                        className="btn btn-outline-red py-0 px-2 mr-1"
                                        onClick={this.removeAnswer}
                                        type="button"
                                    >
                                        <SvgIcon icon="trash" size="0.9rem"/>
                                    </button>
                                )}
                                <button
                                    className="btn btn-lightgreen py-0 px-2 mr-1"
                                    onClick={this.saveSurveyAnswer}
                                    type="button"
                                >
                                    <SvgIcon icon="save" size="0.9rem"/>
                                </button>
                            </>
                        ) : (
                            <button
                                className="btn btn-lightgreen py-0 px-2 mr-1"
                                onClick={this.saveSurveyAnswer}
                                type="button"
                            >
                                <SvgIcon icon="plus" size="0.9rem"/>
                            </button>
                        )}
                    <input
                        className="mr-1"
                        onChange={e => this.setState({selectedColor: e.target.value})}
                        type="color"
                        value={selectedColor}
                    />
                    <input
                        autoComplete="off"
                        maxLength="120"
                        onChange={e => this.setState({newAnswerText: e.target.value})}
                        onKeyDown={e => {
                            if (e.key === "e" && surveyQuestion.dataType === "number") e.preventDefault();
                        }}
                        type={surveyQuestion.dataType === "number" ? "number" : "text"}
                        value={newAnswerText}
                    />

                {surveyQuestion.componentType === "input" && (

                        <input
                            checked={this.state.required}
                            id="required"
                            onChange={() => this.setState({required: !this.state.required})}
                            type="checkbox"
                        />
                        Text Required?

                )}

        );
    };

    render() {
        const {editMode} = this.props;
        return (

                {editMode === "review"
                    ? this.renderExisting()
                    : this.renderNew()}

        );
    }
}
AnswerDesigner.contextType = ProjectContext;


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

                «

    <p class="styleSans62.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Existing Wells Within Spacing Unit
Continental Resources, Inc. has identified the following wells which currently exist in the spacing unit consisting of: Sec6,718, 146 N,96W&Sec31,147N,96W
Dunn County, ND
File Number API Number We" Name Welibore 17560 3302500317 NENW Sec 7, 146M, 96W Cuskelly 1-7H 230 FNL 1320 FWL

3302500798 Lot 7 Sec 6, 146N, 96W Thorvald 1-6H 200 FSL 570 FWL 21283 3302501437 Lot 7 Sec 6, 146N, 96w Thorvald 2-6H 510 FSL 165 FWL 22203 3302501530 LOT 1 Sec 7, 146N 96W Cuskelly 2—7H 200 FNL 660 FWL
CRI has determined that the identified existing wells in the spacing unit specified above are not within 500' ofthe proposed Thorvald 5-6H2 welibore and do not pose any collision threats during driiling or completion operations.


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.example.android.bluetoothchat"
      android:versionCode="1"
      android:versionName="1.0"
      split="lib_slice_8_apk">
</manifest>


text:
JabBot
======

A little AI helper on a server that is always being updated with new commands!


text:
#include <linux/module.h>
#include <linux/init.h>
#include <linux/netdevice.h>
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/skbuff.h>
#include <linux/if_arp.h>

#include <net/mac80211.h>
#include "ieee80211_i.h"
#include "ieee80211_rate.h"
#include "sta_info.h"
#include "debugfs_key.h"
#include "debugfs_sta.h"

/* Caller must hold local->sta_lock */
static void sta_info_hash_add(struct ieee80211_local *local,
			      struct sta_info *sta)
{
	sta->hnext = local->sta_hash[STA_HASH(sta->addr)];
	local->sta_hash[STA_HASH(sta->addr)] = sta;
}

/* Caller must hold local->sta_lock */
static void sta_info_hash_del(struct ieee80211_local *local,
			      struct sta_info *sta)
{
	struct sta_info *s;

	s = local->sta_hash[STA_HASH(sta->addr)];
	if (!s)
		return;
	if (memcmp(s->addr, sta->addr, ETH_ALEN) == 0) {
		local->sta_hash[STA_HASH(sta->addr)] = s->hnext;
		return;
	}

	while (s->hnext && memcmp(s->hnext->addr, sta->addr, ETH_ALEN) != 0)
		s = s->hnext;
	if (s->hnext)
		s->hnext = s->hnext->hnext;
	else
		printk(KERN_ERR "%s: could not remove STA " MAC_FMT " from "
		       "hash table\n", local->mdev->name, MAC_ARG(sta->addr));
}

static inline void __sta_info_get(struct sta_info *sta)
{
	kref_get(&sta->kref);
}

struct sta_info *sta_info_get(struct ieee80211_local *local, u8 *addr)
{
	struct sta_info *sta;

	spin_lock_bh(&local->sta_lock);
	sta = local->sta_hash[STA_HASH(addr)];
	while (sta) {
		if (memcmp(sta->addr, addr, ETH_ALEN) == 0) {
			__sta_info_get(sta);
			break;
		}
		sta = sta->hnext;
	}
	spin_unlock_bh(&local->sta_lock);

	return sta;
}
EXPORT_SYMBOL(sta_info_get);

int sta_info_min_txrate_get(struct ieee80211_local *local)
{
	struct sta_info *sta;
	struct ieee80211_hw_mode *mode;
	int min_txrate = 9999999;
	int i;

	spin_lock_bh(&local->sta_lock);
	mode = local->oper_hw_mode;
	for (i = 0; i < STA_HASH_SIZE; i++) {
		sta = local->sta_hash[i];
		while (sta) {
			if (sta->txrate < min_txrate)
				min_txrate = sta->txrate;
			sta = sta->hnext;
		}
	}
	spin_unlock_bh(&local->sta_lock);
	if (min_txrate == 9999999)
		min_txrate = 0;

	return mode->rates[min_txrate].rate;
}

static void sta_info_release(struct kref *kref)
{
	struct sta_info *sta = container_of(kref, struct sta_info, kref);
	struct ieee80211_local *local = sta->local;
	struct sk_buff *skb;

	/* free sta structure; it has already been removed from
	 * hash table etc. external structures. Make sure that all
	 * buffered frames are release (one might have been added
	 * after sta_info_free() was called). */
	while ((skb = skb_dequeue(&sta->ps_tx_buf)) != NULL) {
		local->total_ps_buffered--;
		dev_kfree_skb_any(skb);
	}
	while ((skb = skb_dequeue(&sta->tx_filtered)) != NULL) {
		dev_kfree_skb_any(skb);
	}
	rate_control_free_sta(sta->rate_ctrl, sta->rate_ctrl_priv);
	rate_control_put(sta->rate_ctrl);
	if (sta->key)
		ieee80211_debugfs_key_sta_del(sta->key, sta);
	kfree(sta);
}

void sta_info_put(struct sta_info *sta)
{
	kref_put(&sta->kref, sta_info_release);
}
EXPORT_SYMBOL(sta_info_put);

struct sta_info * sta_info_add(struct ieee80211_local *local,
			       struct net_device *dev, u8 *addr, gfp_t gfp)
{
	struct sta_info *sta;

	sta = kzalloc(sizeof(*sta), gfp);
	if (!sta)
		return NULL;

	kref_init(&sta->kref);

	sta->rate_ctrl = rate_control_get(local->rate_ctrl);
	sta->rate_ctrl_priv = rate_control_alloc_sta(sta->rate_ctrl, gfp);
	if (!sta->rate_ctrl_priv) {
		rate_control_put(sta->rate_ctrl);
		kref_put(&sta->kref, sta_info_release);
		kfree(sta);
		return NULL;
	}

	memcpy(sta->addr, addr, ETH_ALEN);
	sta->local = local;
	sta->dev = dev;
	skb_queue_head_init(&sta->ps_tx_buf);
	skb_queue_head_init(&sta->tx_filtered);
	__sta_info_get(sta);	/* sta used by caller, decremented by
				 * sta_info_put() */
	spin_lock_bh(&local->sta_lock);
	list_add(&sta->list, &local->sta_list);
	local->num_sta++;
	sta_info_hash_add(local, sta);
	spin_unlock_bh(&local->sta_lock);
	if (local->ops->sta_table_notification)
		local->ops->sta_table_notification(local_to_hw(local),
						  local->num_sta);
	sta->key_idx_compression = HW_KEY_IDX_INVALID;

#ifdef CONFIG_MAC80211_VERBOSE_DEBUG
	printk(KERN_DEBUG "%s: Added STA " MAC_FMT "\n",
	       local->mdev->name, MAC_ARG(addr));
#endif /* CONFIG_MAC80211_VERBOSE_DEBUG */

#ifdef CONFIG_MAC80211_DEBUGFS
	if (!in_interrupt()) {
		sta->debugfs_registered = 1;
		ieee80211_sta_debugfs_add(sta);
		rate_control_add_sta_debugfs(sta);
	} else {
		/* debugfs entry adding might sleep, so schedule process
		 * context task for adding entry for STAs that do not yet
		 * have one. */
		queue_work(local->hw.workqueue, &local->sta_debugfs_add);
	}
#endif

	return sta;
}

static void finish_sta_info_free(struct ieee80211_local *local,
				 struct sta_info *sta)
{
#ifdef CONFIG_MAC80211_VERBOSE_DEBUG
	printk(KERN_DEBUG "%s: Removed STA " MAC_FMT "\n",
	       local->mdev->name, MAC_ARG(sta->addr));
#endif /* CONFIG_MAC80211_VERBOSE_DEBUG */

	if (sta->key) {
		ieee80211_debugfs_key_remove(sta->key);
		ieee80211_key_free(sta->key);
		sta->key = NULL;
	}

	rate_control_remove_sta_debugfs(sta);
	ieee80211_sta_debugfs_remove(sta);

	sta_info_put(sta);
}

static void sta_info_remove(struct sta_info *sta)
{
	struct ieee80211_local *local = sta->local;
	struct ieee80211_sub_if_data *sdata;

	sta_info_hash_del(local, sta);
	list_del(&sta->list);
	sdata = IEEE80211_DEV_TO_SUB_IF(sta->dev);
	if (sta->flags & WLAN_STA_PS) {
		sta->flags &= ~WLAN_STA_PS;
		if (sdata->bss)
			atomic_dec(&sdata->bss->num_sta_ps);
	}
	local->num_sta--;
	sta_info_remove_aid_ptr(sta);
}

void sta_info_free(struct sta_info *sta, int locked)
{
	struct sk_buff *skb;
	struct ieee80211_local *local = sta->local;

	if (!locked) {
		spin_lock_bh(&local->sta_lock);
		sta_info_remove(sta);
		spin_unlock_bh(&local->sta_lock);
	} else {
		sta_info_remove(sta);
	}
	if (local->ops->sta_table_notification)
		local->ops->sta_table_notification(local_to_hw(local),
						  local->num_sta);

	while ((skb = skb_dequeue(&sta->ps_tx_buf)) != NULL) {
		local->total_ps_buffered--;
		dev_kfree_skb_any(skb);
	}
	while ((skb = skb_dequeue(&sta->tx_filtered)) != NULL) {
		dev_kfree_skb_any(skb);
	}

	if (sta->key) {
		if (local->ops->set_key) {
			struct ieee80211_key_conf *key;
			key = ieee80211_key_data2conf(local, sta->key);
			if (key) {
				local->ops->set_key(local_to_hw(local),
						   DISABLE_KEY,
						   sta->addr, key, sta->aid);
				kfree(key);
			}
		}
	} else if (sta->key_idx_compression != HW_KEY_IDX_INVALID) {
		struct ieee80211_key_conf conf;
		memset(&conf, 0, sizeof(conf));
		conf.hw_key_idx = sta->key_idx_compression;
		conf.alg = ALG_NULL;
		conf.flags |= IEEE80211_KEY_FORCE_SW_ENCRYPT;
		local->ops->set_key(local_to_hw(local), DISABLE_KEY,
				   sta->addr, &conf, sta->aid);
		sta->key_idx_compression = HW_KEY_IDX_INVALID;
	}

#ifdef CONFIG_MAC80211_DEBUGFS
	if (in_atomic()) {
		list_add(&sta->list, &local->deleted_sta_list);
		queue_work(local->hw.workqueue, &local->sta_debugfs_add);
	} else
#endif
		finish_sta_info_free(local, sta);
}

static inline int sta_info_buffer_expired(struct ieee80211_local *local,
					  struct sta_info *sta,
					  struct sk_buff *skb)
{
	struct ieee80211_tx_packet_data *pkt_data;
	int timeout;

	if (!skb)
		return 0;

	pkt_data = (struct ieee80211_tx_packet_data *) skb->cb;

	/* Timeout: (2 * listen_interval * beacon_int * 1024 / 1000000) sec */
	timeout = (sta->listen_interval * local->hw.conf.beacon_int * 32 /
		   15625) * HZ;
	if (timeout < STA_TX_BUFFER_EXPIRE)
		timeout = STA_TX_BUFFER_EXPIRE;
	return time_after(jiffies, pkt_data->jiffies + timeout);
}

static void sta_info_cleanup_expire_buffered(struct ieee80211_local *local,
					     struct sta_info *sta)
{
	unsigned long flags;
	struct sk_buff *skb;

	if (skb_queue_empty(&sta->ps_tx_buf))
		return;

	for (;;) {
		spin_lock_irqsave(&sta->ps_tx_buf.lock, flags);
		skb = skb_peek(&sta->ps_tx_buf);
		if (sta_info_buffer_expired(local, sta, skb)) {
			skb = __skb_dequeue(&sta->ps_tx_buf);
			if (skb_queue_empty(&sta->ps_tx_buf))
				sta->flags &= ~WLAN_STA_TIM;
		} else
			skb = NULL;
		spin_unlock_irqrestore(&sta->ps_tx_buf.lock, flags);

		if (skb) {
			local->total_ps_buffered--;
			printk(KERN_DEBUG "Buffered frame expired (STA "
			       MAC_FMT ")\n", MAC_ARG(sta->addr));
			dev_kfree_skb(skb);
		} else
			break;
	}
}

static void sta_info_cleanup(unsigned long data)
{
	struct ieee80211_local *local = (struct ieee80211_local *) data;
	struct sta_info *sta;

	spin_lock_bh(&local->sta_lock);
	list_for_each_entry(sta, &local->sta_list, list) {
		__sta_info_get(sta);
		sta_info_cleanup_expire_buffered(local, sta);
		sta_info_put(sta);
	}
	spin_unlock_bh(&local->sta_lock);

	local->sta_cleanup.expires = jiffies + STA_INFO_CLEANUP_INTERVAL;
	add_timer(&local->sta_cleanup);
}

#ifdef CONFIG_MAC80211_DEBUGFS
static void sta_info_debugfs_add_task(struct work_struct *work)
{
	struct ieee80211_local *local =
		container_of(work, struct ieee80211_local, sta_debugfs_add);
	struct sta_info *sta, *tmp;

	while (1) {
		spin_lock_bh(&local->sta_lock);
		if (!list_empty(&local->deleted_sta_list)) {
			sta = list_entry(local->deleted_sta_list.next,
					 struct sta_info, list);
			list_del(local->deleted_sta_list.next);
		} else
			sta = NULL;
		spin_unlock_bh(&local->sta_lock);
		if (!sta)
			break;
		finish_sta_info_free(local, sta);
	}

	while (1) {
		sta = NULL;
		spin_lock_bh(&local->sta_lock);
		list_for_each_entry(tmp, &local->sta_list, list) {
			if (!tmp->debugfs_registered) {
				sta = tmp;
				__sta_info_get(sta);
				break;
			}
		}
		spin_unlock_bh(&local->sta_lock);

		if (!sta)
			break;

		sta->debugfs_registered = 1;
		ieee80211_sta_debugfs_add(sta);
		rate_control_add_sta_debugfs(sta);
		sta_info_put(sta);
	}
}
#endif

void sta_info_init(struct ieee80211_local *local)
{
	spin_lock_init(&local->sta_lock);
	INIT_LIST_HEAD(&local->sta_list);
	INIT_LIST_HEAD(&local->deleted_sta_list);

	init_timer(&local->sta_cleanup);
	local->sta_cleanup.expires = jiffies + STA_INFO_CLEANUP_INTERVAL;
	local->sta_cleanup.data = (unsigned long) local;
	local->sta_cleanup.function = sta_info_cleanup;

#ifdef CONFIG_MAC80211_DEBUGFS
	INIT_WORK(&local->sta_debugfs_add, sta_info_debugfs_add_task);
#endif
}

int sta_info_start(struct ieee80211_local *local)
{
	add_timer(&local->sta_cleanup);
	return 0;
}

void sta_info_stop(struct ieee80211_local *local)
{
	struct sta_info *sta, *tmp;

	del_timer(&local->sta_cleanup);

	list_for_each_entry_safe(sta, tmp, &local->sta_list, list) {
		/* sta_info_free must be called with 0 as the last
		 * parameter to ensure all debugfs sta entries are
		 * unregistered. We don't need locking at this
		 * point. */
		sta_info_free(sta, 0);
	}
}

void sta_info_remove_aid_ptr(struct sta_info *sta)
{
	struct ieee80211_sub_if_data *sdata;

	if (sta->aid <= 0)
		return;

	sdata = IEEE80211_DEV_TO_SUB_IF(sta->dev);

	if (sdata->local->ops->set_tim)
		sdata->local->ops->set_tim(local_to_hw(sdata->local),
					  sta->aid, 0);
	if (sdata->bss)
		__bss_tim_clear(sdata->bss, sta->aid);
}

/**
 * sta_info_flush - flush matching STA entries from the STA table
 * @local: local interface data
 * @dev: matching rule for the net device (sta->dev) or %NULL to match all STAs
 */
void sta_info_flush(struct ieee80211_local *local, struct net_device *dev)
{
	struct sta_info *sta, *tmp;

	spin_lock_bh(&local->sta_lock);
	list_for_each_entry_safe(sta, tmp, &local->sta_list, list)
		if (!dev || dev == sta->dev)
			sta_info_free(sta, 1);
	spin_unlock_bh(&local->sta_lock);
}


text:
package com.vaadin.server.react;

import java.util.function.Supplier;

import com.vaadin.server.react.harnesses.FlowTestHarness;

public abstract class FlowTestBase {

    protected abstract FlowTestHarness getHarness();

    @SuppressWarnings("unchecked")
    protected <T> T[] values(T... values) {
        return values;
    }

    @SuppressWarnings("unchecked")
    protected <T> Flow<T> flow(T... actual) {
        return getHarness().flow(actual);
    }

    protected <T> void verifyFlow(Flow<T> flow,
            Supplier<Subscriber<? super T>> supp) {
        getHarness().verifyFlow(flow, supp);

    }

    protected <T> void verifyFlow(Flow<T> flow, Subscriber<? super T> sub) {
        getHarness().verifyFlow(flow, sub);
    }

    @SuppressWarnings("unchecked")
    protected <T> Supplier<Subscriber<? super T>> expect(T... values) {
        return getHarness().expect(values);
    }

    @SuppressWarnings("unchecked")
    protected <T> Supplier<Subscriber<? super T>> expectAndUnsubscribe(
            T... values) {
        return getHarness().expectAndUnsubscribe(values);
    }

    protected <T> Supplier<Subscriber<? super T>> expectError(Exception e) {
        return getHarness().expectError(e);
    }

    @SuppressWarnings("unchecked")
    protected <T> Subscriber<? super T> expectMerged(
            T[]... values) {
        return getHarness().expectMerged(values);
    }
}


text:
//
//  UIImageView+CBCache.h
//
//  Created by Thiago Alencar on 2/12/15.
//  Copyright (c) 2015 Thiago Alencar. All rights reserved.
//

#import <UIKit/UIKit.h>
#import <CouchbaseLite/CouchbaseLite.h>

/*
 A very simple image loading category to demonstrate
 caching with Couchbase Mobile and NSURLSession+CBCache.h

 Performance Note:
 I compared the performance of this class versus other libraries such as
 SDWebImage and AFNetwork+UIImageCache (few and small-sized image) and the
 differences were so minimal that I believe integrating one of those in conjunction
 with the caching described here is not worth it (I believe the performance was similar
 because in the end we're just loading data from the flash memory anyway).
 If you really need faster framerates I'd suggest then to use a memory mapped
 library such as Path's Fast Image Cache (instead of AFNetwork+UIImageCache or SDWebImage).
 The reason is that NSURLCache caches responses, not the result of parsing them.
 For intensive decoding tasks it might be best to cache the parsed objects in a custom cache
 instead of relying on e.g. NSURLCache to simply store the raw response.
 Like always, it all always depends on your application's needs.

 This class is much simpler than AFNetworking because we don't need for example
 NSOperationQueues since the images should be loaded fast enough from local cached
 data. The point of NSOperationQueue in AFNetworking is to be able to prioritize
 one request versus another (by pausing or canceling requests which went ouf of scope) in order
 to avoid e.g. too many connections being fired, and to avoid irrelevant ones to block the most recent

 Since loading -local- data is fast, using GCD and leaving all networking with NSURLSession
 is enough when using the techniques presented here. We want to avoid the 'loading' altogether!
 */

@interface UIImageView (CBCache)

@property (nonatomic, weak) CBLDatabase * databaseObject;
@property (atomic, weak) NSString * currentURL;

/*methods with cbcache_ initial stores and retrieve data using
 Couchbase Lite; May be used to generate the cache documents*/
-(void)cbcache_setImageWithURL: (NSURL *)url
              placeHolderImage: (UIImage *)placeHolderImage;

//context is translated to CBL doc's channel (to be used for filtered pull)
-(void)cbcache_setImageWithURL: (NSURL *)url
              placeHolderImage: (UIImage *)placeHolderImage
                   withContext: (NSString*)context;

/*implement custom completion blocks*/
-(void)cbcache_setImageWithURL:(NSURL *)url
              placeHolderImage: (UIImage *)placeHolderImage
                       success:(void (^) (UIImage * image))success
                       failure:(void (^) (NSError * error))failure;

-(void)cbcache_setImageWithURL: (NSURL *)url
              placeHolderImage: (UIImage *)placeHolderImage
                   withContext: (NSString*)context
                       success: (void (^) (UIImage * image))success
                       failure: (void (^) (NSError * error))failure;

/*methods below provides basic image lazy loading enforcing use
 of stored [NSURLCache sharedURLCache] data. It does NOT directly
 use the CBL cache documents. We inject cache data from the CBL documents
 into NSURLCache first. This is to levarege the caching memory management from
 NSURLCache without reimplementing such memory management system on our own.*/
-(void)setImageWithURL:(NSURL *)url
      placeHolderImage: (UIImage *)placeHolderImage;

-(void)setImageWithURL:(NSURL *)url
       placeHolderImage: (UIImage *)placeHolderImage
                success:(void (^) (UIImage * image))success
                failure:(void (^) (NSError * error))failure;
@end


text:
namespace Brainary.Commons.Web.Annotations
{
    public class HttpGetAttribute : HttpVerbAttribute
    {
        public override string HttpVerb
        {
            get { return "GET"; }
        }
    }
}


text:
A firmware for driving Max-Sonar sensors via a PIC MCU.
The project was tested and verified for use in haptics. Each max-sonar ultrasonic sensor was use to sense obstacles within a >= 1 metre range and provide a feedback to the
user via cam-driven ERM motors (found in all vibrating cellular phones)

All you need is

A PIC16f877 MCU
3 Max-sonar ez0 ultrasonic sensors
Maxsonars should be connected in a daisy chain fashion: http://www.maxbotix.com/documents/LV_Chaining_Constantly_Looping_AN_Out.pdf
Motors need a driver circuit through the PIC.

The PIC was programmed on a breadboard via it's dedicated programming pins (please check PIC16f877 datasheet here :http://www.microchip.com/wwwproducts/en/PIC16F877)
There's a difference between a PIC16f877a and PIC16f877; Point to be noted!
Well, I eventually decided to put a PIC16F887 in the design as it was highly recommended for modern designs. It's more robust and reliable.
I have  done the PCB design in Cadsoft Eagle (v6.0 at that time).
There's an LCD routine also included in the code so  as to test/calibrate your maxsonar as per your needs. (see commented lines of code).
The code was written from scratch during which I had 2 sleepless nights- Hardwork pays off right! I was inspired by the atmega interrupts tutorial. (Just Google it!)
Any problems feel free to voice 'em out!


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class CreateModule extends CI_Controller {

 	public function __construct() {
        parent::__construct();

        $this->load->model('Model_config','m_config', True);
        $this->load->model('Model_module','m_module', True);
	}
	public function index()
	{
		$akses = $this->session->userdata('akses');
		if($akses)
		{
		$data  = array(
			'isikonten' 		=> 'main/createModule',
			'sidebar'			=> $this->m_config->getSidebar($akses,""),
			'listGroupmodule'	=> $this->m_module->getlistGroup(),
			'listModule'		=> $this->m_module->getlistModule()
			 );
		$this->load->view('wrapper',$data);
		}else
		{
			$this->session->set_flashdata('msg_error', "Expaired Login");
			redirect('login');
		}
	}

	public function GroupModule(){
		$akses = $this->session->userdata('akses');
		if($akses)
		{
		$name 		= $this->input->post('name');
		$controller = $this->input->post('controller');
		$user 		= $this->session->userdata('username');
		$date		= date('Y-m-d H:i:s');
		$data = array(
			'groupmodule_name' 			=> $name,
			'groupmodule_controller'	=> $controller,
			'groupmodule_createdate'	=> $date,
			'groupmodule_createby'		=> $user

			);
		$save = $this->m_module->simpanGroup($data);
		if($save){
			$this->session->set_flashdata('msg_success', "Simpan Groupmodule Success");
			redirect('CreateModule');
		}else{
			$this->session->set_flashdata('msg_error', "Simpan Groupmodule gagal");
			redirect('CreateModule');
		}
		}else
		{
			$this->session->set_flashdata('msg_error', "Expaired Login");
			redirect('login');
		}
	}

	public function Module(){

		$akses = $this->session->userdata('akses');
		if($akses)
		{
		$name 			= $this->input->post('name');
		$controller 	= $this->input->post('controller');
		$GroupModuleID 	= $this->input->post('groupmodule_id');
		$urutan 		= $this->input->post('urutan');
		$user 			= $this->session->userdata('username');
		$date			= date('Y-m-d H:i:s');
		$data = array(
			'module_name' 			=> $name,
			'controller'			=> $controller,
			'groupmodule_id'		=> $GroupModuleID,
			'urutan'				=> $urutan,
			'createby'				=> $user,
			'create_date'			=> $date
			);
		$save = $this->m_module->simpanModule($data);
		if($save){
			$this->session->set_flashdata('msg_success', "Simpan Groupmodule Success");
			redirect('CreateModule');
		}else{
			$this->session->set_flashdata('msg_error', "Simpan Groupmodule gagal");
			redirect('CreateModule');
		}
		}else
		{
			$this->session->set_flashdata('msg_error', "Expaired Login");
			redirect('login');
		}
	}
}


text:
class DeploymentTargetMetadataSerializer < ActiveModel::Serializer
  attributes :id, :agent_version, :adapter_version, :adapter_type, :created_at
end


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="ru.zzzzzzerg.linden" >

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
//These permissions are only required for showing the ad when pressing the Home button:
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
<uses-permission android:name="android.permission.GET_TASKS"/>

</manifest>


text:
namespace ContosoUniversity.DependencyResolution {
    using StructureMap;

    public static class IoC {
        public static IContainer Initialize() {
            return new Container(c => c.AddRegistry<DefaultRegistry>());
        }
    }
}


text:
package org.marat.workflow.samples.one;

import org.marat.workflow.Workflow;
import org.marat.workflow.builder.WorkflowBuilders;
import org.marat.workflow.samples.common.AbstractSample;
import org.marat.workflow.samples.common.DefaultContext;

public class SampleOne extends AbstractSample {

	public static void main(final String[] args) {
		new SampleOne().run(true);
	}

	@Override
	protected void prepare() {
	}

	@Override
	protected DefaultContext createContext() {
		return new DefaultContext();
	}

	@Override
	protected Workflow<DefaultContext> createWorkflow() {
		final SampleOneNode node = new SampleOneNode();

		return WorkflowBuilders.DEFAULT.newInstance()
			.addNode(node, node)
			.addDefaultStartTransition(node)
			.addDefaultEndTransition(node)
			.build();
	}

}


text:
import * as React from 'react';
import { UseListboxRootSlotProps } from '../ListboxUnstyled';

export interface MenuItemMetadata {
  id: string;
  disabled: boolean;
  label?: string;
  ref: React.RefObject<HTMLElement>;
}

export interface MenuItemState {
  disabled: boolean;
  highlighted: boolean;
}

export interface UseMenuParameters {
  open?: boolean;
  onClose?: () => void;
  listboxId?: string;
  listboxRef?: React.Ref<any>;
}

interface UseMenuListboxSlotEventHandlers {
  onBlur: React.FocusEventHandler;
  onKeyDown: React.KeyboardEventHandler;
}

export type UseMenuListboxSlotProps<TOther = {}> = UseListboxRootSlotProps<
  Omit<TOther, keyof UseMenuListboxSlotEventHandlers> & UseMenuListboxSlotEventHandlers
> & {
  ref: React.Ref<any>;
  role: React.AriaRole;
};


text:
//
//  QMBaseViewController.m
//  QQMusic
//
//  Created by xwmedia01 on 17/3/2.
//  Copyright © 2017年 xwmedia01. All rights reserved.
//

#import "QMBaseViewController.h"

@interface QMBaseViewController ()

@end

@implementation QMBaseViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    self.view.backgroundColor = [UIColor whiteColor];

    self.extendedLayoutIncludesOpaqueBars = NO;

    self.edgesForExtendedLayout = UIRectEdgeNone;

    self.automaticallyAdjustsScrollViewInsets = NO;

    self.view.backgroundColor = [UIColor whiteColor];

}

- (void)setShowNav:(BOOL)showNav
{
    _showNav = showNav;
    if (showNav && !self.navView.superview) {
        self.navView = [[BETouchView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, STATUS_AND_NAV_BAR_HEIGHT)];
        self.navView.backgroundColor = MAIN_TONE_COLOR;
        [self.view addSubview:self.navView];
    }
}
- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


text:
"""Performs face detection in realtime.

Based on code from https://github.com/shanren7/real_time_face_recognition
"""
# MIT License
#
# Copyright (c) 2017 François Gervais
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import argparse
import sys
import time

import cv2

import face

def add_overlays(frame, faces, frame_rate):
    if faces is not None:
        for face in faces:
            face_bb = face.bounding_box.astype(int)
            cv2.rectangle(frame,
                          (face_bb[0], face_bb[1]), (face_bb[2], face_bb[3]),
                          (0, 255, 0), 2)
            if face.name is not None:
                cv2.putText(frame, face.name, (face_bb[0], face_bb[3]),
                            cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0),
                            thickness=2, lineType=2)

    cv2.putText(frame, str(frame_rate) + " fps", (10, 30),
                cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0),
                thickness=2, lineType=2)

def main(args):
    frame_interval = 3  # Number of frames after which to run face detection
    fps_display_interval = 5  # seconds
    frame_rate = 0
    frame_count = 0

    video_capture = cv2.VideoCapture(0)
    face_recognition = face.Recognition()
    start_time = time.time()

    if args.debug:
        print("Debug enabled")
        face.debug = True

    while True:
        # Capture frame-by-frame
        ret, frame = video_capture.read()

        if (frame_count % frame_interval) == 0:
            faces = face_recognition.identify(frame)

            # Check our current fps
            end_time = time.time()
            if (end_time - start_time) > fps_display_interval:
                frame_rate = int(frame_count / (end_time - start_time))
                start_time = time.time()
                frame_count = 0

        add_overlays(frame, faces, frame_rate)

        frame_count += 1
        cv2.imshow('Video', frame)

        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

    # When everything is done, release the capture
    video_capture.release()
    cv2.destroyAllWindows()

def parse_arguments(argv):
    parser = argparse.ArgumentParser()

    parser.add_argument('--debug', action='store_true',
                        help='Enable some debug outputs.')
    return parser.parse_args(argv)

if __name__ == '__main__':
    main(parse_arguments(sys.argv[1:]))


text:
{% if audio %}
{{ audio.title }}
{% endif %}


text:
import Phaser2NavMesh from "./phaser2-navmesh";

/**
 * This class can create navigation meshes for use in Phaser 2 / Phaser CE. (For Phaser 3, see
 * {@link PhaserNavMeshPlugin}.) The navmeshes can be constructed from convex polygons embedded in a
 * Tiled map. The class that conforms to Phaser 2's plugin structure.
 *
 * @export
 * @class Phaser2NavMeshPlugin
 */
export default class Phaser2NavMeshPlugin extends Phaser.Plugin {
  constructor(game, pluginManager) {
    super(game, pluginManager);

    this.phaserNavMeshes = {};
  }

  /**
   * Destroy all navmeshes created and the plugin itself
   *
   * @memberof Phaser2NavMeshPlugin
   */
  destroy() {
    const meshes = Object.values(this.phaserNavMeshes);
    this.phaserNavMeshes = {};
    meshes.forEach(m => m.destroy());
    this.game = undefined;
  }

  /**
   * Remove the navmesh stored under the given key from the plugin. This does not destroy the
   * navmesh.
   *
   * @param {string} key
   * @memberof Phaser2NavMeshPlugin
   */
  removeMesh(key) {
    if (this.phaserNavMeshes[key]) this.phaserNavMeshes[key] = undefined;
  }

  /**
   * Load a navmesh from Tiled. Currently assumes that the polygons are squares! Does not support
   * tilemap layer scaling, rotation or position.
   *
   * @param {string} key Key to use when storign this navmesh within the plugin.
   * @param {Phaser.Tilemaps.ObjectLayer} objectLayer The ObjectLayer from a tilemap that contains
   * the polygons that make up the navmesh.
   * @param {number} [meshShrinkAmount=0] The amount (in pixels) that the navmesh has been shrunk
   * around obstacles (a.k.a the amount obstacles have been expanded)
   * @returns {Phaser2NavMesh}
   * @memberof Phaser2NavMeshPlugin
   */
  buildMeshFromTiled(key, objectLayer, meshShrinkAmount = 0) {
    if (this.phaserNavMeshes[key]) {
      console.warn(`NavMeshPlugin: a navmesh already exists with the given key: ${key}`);
      return this.phaserNavMeshes[key];
    }

    if (!objectLayer || objectLayer.length === 0) {
      console.warn(
        `NavMeshPlugin: The given tilemap object layer is empty or undefined: ${objectLayer}`
      );
    }

    // Load up the object layer
    const objects = objectLayer || [];

    // Loop over the objects and construct a polygon - assumes a rectangle for now!
    // TODO: support layer position, scale, rotation
    const polygons = objects.map(obj => {
      const top = obj.y;
      const bottom = obj.y + obj.height;
      const left = obj.x;
      const right = obj.x + obj.width;
      return [
        { x: left, y: top },
        { x: left, y: bottom },
        { x: right, y: bottom },
        { x: right, y: top }
      ];
    });

    const mesh = new Phaser2NavMesh(this, key, polygons, meshShrinkAmount);

    this.phaserNavMeshes[key] = mesh;

    return mesh;
  }
}


text:
class Message
  attr_reader :command, :channel, :body

  def initialize(sanitized_input_str)
    @command, @channel, @body = sanitized_input_str.split(' ', 3)
  end

  def to_s
    [command, channel, body].join(' ')
  end
end


text:
namespace {
constexpr folly::StringPiece FIRST_SENT_POSITION = "FirstSentPosition";
constexpr folly::StringPiece LAST_SENT_POSITION = "LastSentPosition";
constexpr folly::StringPiece IMPLIED_POSITION = "ImpliedPosition";
constexpr folly::StringPiece LARGEST_USED_STREAMID = "LargestUsedStreamId";
constexpr folly::StringPiece STREAM_RESUME_INFOS = "StreamResumeInfos";
constexpr folly::StringPiece FRAMES = "Frames";
constexpr folly::StringPiece STREAM_TYPE = "StreamType";
constexpr folly::StringPiece REQUESTER = "Requester";
constexpr folly::StringPiece STREAM_TOKEN = "StreamToken";
constexpr folly::StringPiece PROD_ALLOWANCE = "ProducerAllowance";
constexpr folly::StringPiece CONS_ALLOWANCE = "ConsumerAllowance";
} // namespace

namespace rsocket {

ColdResumeManager::ColdResumeManager(
    std::shared_ptr<RSocketStats> stats,
    std::string inputFile)
    : WarmResumeManager(std::move(stats)) {
  if (inputFile.empty()) {
    return;
  }
  LOG(INFO) << "Reading state from " << inputFile;

  try {
    std::ifstream f(inputFile);
    std::stringstream buffer;
    buffer << f.rdbuf();
    auto state = folly::parseJson(buffer.str());
    f.close();

    if (!state.isObject() || state.size() != 6) {
      throw std::runtime_error(
          "Invalid file content.  Expected dynamic object of 6 elements");
    }

    if (state.count(FIRST_SENT_POSITION) != 1 ||
        state.count(LAST_SENT_POSITION) != 1 ||
        state.count(IMPLIED_POSITION) != 1 ||
        state.count(LARGEST_USED_STREAMID) != 1 ||
        state.count(STREAM_RESUME_INFOS) != 1 || state.count(FRAMES) != 1) {
      throw std::runtime_error("Invalid file content.  Keys Missing");
    }

    firstSentPosition_ = state[FIRST_SENT_POSITION].getInt();
    lastSentPosition_ = state[LAST_SENT_POSITION].getInt();
    impliedPosition_ = state[IMPLIED_POSITION].getInt();
    largestUsedStreamId_ = state[LARGEST_USED_STREAMID].getInt();

    for (const auto& item : state[STREAM_RESUME_INFOS].items()) {
      auto streamId = folly::to<int64_t>(item.first.getString());
      auto streamResumeInfoObj = item.second;
      if (streamResumeInfoObj.count(STREAM_TYPE) != 1 ||
          streamResumeInfoObj.count(STREAM_TOKEN) != 1 ||
          streamResumeInfoObj.count(PROD_ALLOWANCE) != 1 ||
          streamResumeInfoObj.count(CONS_ALLOWANCE) != 1 ||
          streamResumeInfoObj.count(CONS_ALLOWANCE) != 1) {
        throw std::runtime_error(
            "Invalid file content.  StreamResumeInfo Keys Missing");
      }
      StreamResumeInfo streamResumeInfo(
          static_cast<StreamType>(streamResumeInfoObj[STREAM_TYPE].getInt()),
          static_cast<RequestOriginator>(
              streamResumeInfoObj[REQUESTER].getInt()),
          streamResumeInfoObj[STREAM_TOKEN].getString());
      streamResumeInfo.producerAllowance =
          streamResumeInfoObj[PROD_ALLOWANCE].getInt();
      streamResumeInfo.consumerAllowance =
          streamResumeInfoObj[CONS_ALLOWANCE].getInt();
      streamResumeInfos_.emplace(streamId, std::move(streamResumeInfo));
    }

    auto framesObj = state[FRAMES];
    if (!framesObj.isArray()) {
      throw std::runtime_error(
          "Invalid file content. Frames not in right format");
    }

    for (const auto& item : framesObj) {
      if (!item.isObject() || item.size() != 1) {
        throw std::runtime_error(
            "Invalid file content.  Expected dynamic object of 1 element");
      }
      auto ioBuf = folly::IOBuf::copyBuffer(
          item.values().begin()->getString().c_str(),
          item.values().begin()->getString().size());
      frames_.emplace_back(
          folly::to<int64_t>(item.keys().begin()->getString()),
          std::move(ioBuf));
    }
  } catch (const std::exception& ex) {
    throw std::runtime_error(
        folly::sformat("Failed parsing file {}. {}", inputFile, ex.what()));
  }
}

void ColdResumeManager::persistState(std::string outputFile) {
  VLOG(1) << "~ColdResumeManager";
  if (outputFile.empty()) {
    throw std::runtime_error("Persisting to file failed.  Empty filename");
  }
  LOG(INFO) << "Persisting state to " << outputFile;
  try {
    folly::dynamic state = folly::dynamic::object();
    state[FIRST_SENT_POSITION] = firstSentPosition_;
    state[LAST_SENT_POSITION] = lastSentPosition_;
    state[IMPLIED_POSITION] = impliedPosition_;
    state[LARGEST_USED_STREAMID] = largestUsedStreamId_;
    state[STREAM_RESUME_INFOS] = folly::dynamic::object();
    for (const auto& streamResumeInfo : streamResumeInfos_) {
      folly::dynamic val = folly::dynamic::object();
      val[STREAM_TYPE] = folly::to<int>(streamResumeInfo.second.streamType);
      val[STREAM_TOKEN] = streamResumeInfo.second.streamToken;
      val[REQUESTER] = folly::to<int>(streamResumeInfo.second.requester);
      val[CONS_ALLOWANCE] = streamResumeInfo.second.consumerAllowance;
      val[PROD_ALLOWANCE] = streamResumeInfo.second.producerAllowance;
      state[STREAM_RESUME_INFOS].insert(
          folly::to<std::string>(streamResumeInfo.first), val);
    }
    state[FRAMES] = folly::dynamic::array();
    for (const auto& frame : frames_) {
      state[FRAMES].push_back(folly::dynamic::object(
          folly::to<std::string>(frame.first),
          frame.second->moveToFbString().toStdString()));
    }
    std::string jsonState = folly::toPrettyJson(state);
    std::ofstream f(outputFile);
    f << jsonState;
    f.close();
  } catch (const std::exception& ex) {
    throw std::runtime_error(folly::sformat(
        "Persisting state to {} failed. {}", outputFile, ex.what()));
  }
  LOG(INFO) << "Done persisting state to " << outputFile;
}

void ColdResumeManager::trackReceivedFrame(
    size_t frameLength,
    FrameType frameType,
    StreamId streamId,
    size_t consumerAllowance) {
  if (!shouldTrackFrame(frameType)) {
    return;
  }
  auto it = streamResumeInfos_.find(streamId);
  // If streamId is not present in streamResumeInfo it likely means a
  // COMPLETE/CANCEL/ERROR was received in this frame and the
  // ResumeMananger::onCloseStream() was already invoked resulting in the entry
  // being deleted.
  if (it != streamResumeInfos_.end()) {
    it->second.consumerAllowance = consumerAllowance;
  }
  WarmResumeManager::trackReceivedFrame(
      frameLength, frameType, streamId, consumerAllowance);
}

void ColdResumeManager::trackSentFrame(
    const folly::IOBuf& serializedFrame,
    FrameType frameType,
    StreamId streamId,
    size_t consumerAllowance) {
  if (!shouldTrackFrame(frameType)) {
    return;
  }
  auto it = streamResumeInfos_.find(streamId);
  CHECK(it != streamResumeInfos_.end());
  it->second.consumerAllowance = consumerAllowance;
  WarmResumeManager::trackSentFrame(
      std::move(serializedFrame), frameType, streamId, consumerAllowance);
}

void ColdResumeManager::onStreamClosed(StreamId streamId) {
  streamResumeInfos_.erase(streamId);
}

void ColdResumeManager::onStreamOpen(
    StreamId streamId,
    RequestOriginator requester,
    std::string streamToken,
    StreamType streamType) {
  CHECK(streamType != StreamType::FNF);
  CHECK(streamResumeInfos_.find(streamId) == streamResumeInfos_.end());
  if (requester == RequestOriginator::LOCAL &&
      streamId > largestUsedStreamId_) {
    largestUsedStreamId_ = streamId;
  }
  streamResumeInfos_.emplace(
      streamId, StreamResumeInfo(streamType, requester, streamToken));
}

} // namespace rsocket


text:
var massahHelper = require('massah/helper')
  , helper = massahHelper.application.helper

module.exports = (function() {
    var library = massahHelper.getLibrary()
        .when('I create a card', function() {
            new massahHelper.Webdriver.ActionSequence(this.driver)
               .doubleClick(this.driver.element('div.viewport-container div'))
               .perform()
        })
        .when('I click delete', function() {
            this.driver.element('div.card textarea').click()
            this.driver.element('div.card .card-delete').click()
        })
        .when('I (double )click change colour', function(double) {
            this.driver.element('div.card textarea').click()
            var element = this.driver.element('div.card .card-colour')
            if (double) {
                new massahHelper.Webdriver
                    .ActionSequence(this.driver)
                   .doubleClick(element)
               .perform()
            } else {
                element.click()
            }
        })
        .when('I double click controls', function(double) {
            this.driver.element('div.card textarea').click()
            var element = this.driver.element('div.card .controls a.separator')
            element.click()
        })
        .given('I click zoom', function() {
            this.driver.element('div.card textarea').click()
            this.driver.element('div.card .icon-zoom-in').click()
        })
        .given('I see the zoom out link', function() {
            var driver = this.driver
            var zoomOut = 'div.card .card-zoom'

            driver.wait(function() {
                return driver.element(zoomOut).attr('class', function(cssClass) {
                    return -1 !== cssClass.indexOf('icon-zoom-out')
                })
            }, 5000, 'Waiting for zoom out button')
        })
        .when('I click to zoom out', function() {
            var driver = this.driver
            /* Transform time is 0.8 seconds */
            setTimeout(function() {
                var zoomOut = 'div.card .card-zoom'
                driver.element(zoomOut).click()
            }, 1000)
        })
        .when('I click for card link', function() {
            this.driver.element('div.card textarea').click()
            this.driver.element('div.card .card-link').click()
        })
        .then('I see a card', function() {
            this.driver.elements('div.card').count(function(cardCount) {
                cardCount.should.equal(1)
            })
        })
        .then('I see ([0-9]*) cards', function(count) {
            count = parseInt(count)
            this.driver.elements('div.card').count(function(cardCount) {
                cardCount.should.equal(count)
            })
        })
        .then('I see the card elements', function() {
            var cardId = null
            this.driver.element('div.card').attr('draggable', function(draggable) {
                draggable.should.equal('true')
            })
            this.driver.element('div.card').attr('class', function(cssClass) {
                cssClass.should.include('card')
                cssClass.should.include('draggable')
                cssClass.should.include('card-yellow')
                cssClass.should.include('ui-draggable')
                cssClass.should.include('ui-resizable')
            })
            this.driver.element('div.card').attr('id', function(id) {
                id.should.match(/^[a-f0-9]{24}$/)
                cardId = id
            })
            this.driver.element('div.card').css('height', function(height) {
                height.should.equal('150px')
            })
            this.driver.element('div.card').css('width', function(width) {
                width.should.equal('150px')
            })
            this.driver.element('div.card').css('position', function(position) {
                position.should.equal('absolute')
            })
            this.driver.element('div.card a').attr('name', function(name) {
                name.should.match(/^[a-f0-9]{24}$/)
                name.should.equal(cardId)
            })
            var cardLinkSelector = 'div.card div.controls ' +
                'a.card-link'
            this.driver.element(cardLinkSelector).attr('title', function(title) {
                title.should.include(helper.baseUrl)
                title.should.include(cardId)
            })
            var cardDeleteSelector = 'div.card div.controls ' +
                'a.card-delete.write'
            this.driver.element(cardDeleteSelector).attr('title', function(title) {
                title.should.equal('Delete card')
            })
            var cardColourSelector = 'div.card div.controls ' +
                'a.card-colour.write'
            this.driver.element(cardColourSelector).attr('title', function(title) {
                title.should.equal('Change card colour')
            })
            var cardZoomSelector = 'div.card div.controls ' +
                'a.card-zoom'
            this.driver.element(cardZoomSelector).attr('title', function(title) {
                title.should.equal('Zoom in on this card')
            })
            this.driver.element('div.card div.ui-resizable-handle').attr('class', function(cssClass) {
                cssClass.should.include('ui-resizable-handle')
                cssClass.should.include('ui-resizable-se')
                cssClass.should.include('ui-icon')
                cssClass.should.include('ui-icon-gripsmall-diagonal-se')
            })
            this.driver.element('div.card textarea').then(
                function() {},
                function() { throw new Error('Missing card element') }
            )
        })
        .then('I see a zoomed card', function() {
            this.driver.element('body').attr('style', function(style) {
                var scale = style.split('scale(')[1].split(')')[0]
                scale = parseFloat(scale)
                scale.should.be.greaterThan(1)
            })
        })
        .then('I see a reset view', function() {
            var driver = this.driver
            /* Transform time is 0.8 seconds */
            setTimeout(function() {
                driver.element('body').attr('style', function(style) {
                    var scale = style.split('scale(')[1].split(')')[0]
                    scale = parseFloat(scale)
                    scale.should.equal(1)
                })
            }, 1000)
        })
        .define('[When|Then|And] I see the link modal', function() {
            var driver = this.driver
            var selector = '#card-link-modal div[data-role="main"]'
            driver.wait(function() {
                return driver.element(selector).isDisplayed(function(visible) {
                    return true === visible
                })
            }, 5000, 'Waiting for link modal to appear')
        })
        .then('the expected link modal elements', function() {
            var params = this.params
            var headerSelector = '#card-link-modal div[data-role="header"] h1'
            this.driver.element(headerSelector).html(function(header) {
                header.should.equal('Permalink to this card')
            })
            var cardLinkSelector = '#card-link-modal div.card-link a'
            this.driver.element(cardLinkSelector).attr('href', function(link) {
                link.should.include(helper.baseUrl + '/' + params.boardId + '#')
                link.should.match(/.*#[a-f0-9]{24}$/)
            })
            var closeSelector = '#card-link-modal div[data-role="footer"] ' +
                'button#close-card-link-modal'
            this.driver.element(closeSelector).html(function(label) {
                label.should.equal('All linked up')
            })
        })
        .then('the card link modal is closed', function() {
            var driver = this.driver
            driver.wait(function() {
                return driver.element('#card-link-modal').isDisplayed(function(visible) {
                    return visible === false
                })
            }, 5000, 'Waiting for the card link modal to close')
        })

    return library
})()


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE665_Improper_Initialization__char_ncat_52b.c
Label Definition File: CWE665_Improper_Initialization.label.xml
Template File: sources-sink-52b.tmpl.c
*/
/*
 * @description
 * CWE: 665 Improper Initialization
 * BadSource:  Do not initialize data properly
 * GoodSource: Initialize data
 * Sink: ncat
 *    BadSink : Copy string to data using strncat
 * Flow Variant: 52 Data flow: data passed as an argument from one function to another to another in three different source files
 *
 * */

#include "std_testcase.h"

#include <wchar.h>

/* all the sinks are the same, we just want to know where the hit originated if a tool flags one */

#ifndef OMITBAD

/* bad function declaration */
void CWE665_Improper_Initialization__char_ncat_52c_badSink(char * data);

void CWE665_Improper_Initialization__char_ncat_52b_badSink(char * data)
{
    CWE665_Improper_Initialization__char_ncat_52c_badSink(data);
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* good function declaration */
void CWE665_Improper_Initialization__char_ncat_52c_goodG2BSink(char * data);

/* goodG2B uses the GoodSource with the BadSink */
void CWE665_Improper_Initialization__char_ncat_52b_goodG2BSink(char * data)
{
    CWE665_Improper_Initialization__char_ncat_52c_goodG2BSink(data);
}

#endif /* OMITGOOD */


text:
"""
Sponge Knowledge Base
Jython library. This file may define Jython specific code that could be used as one of knowledge base files.
"""


text:
package com.archcra.plugin.mob.thirdauth;

import org.json.JSONObject;
import android.util.Log;

public class UserInfo {
	private String userIcon;
	private String userName;
	private String userGender;
	private String userId;

	public String getUserIcon() {
		return userIcon;
	}

	public void setUserIcon(String userIcon) {
		this.userIcon = userIcon;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getUserGender() {
		return userGender;
	}

	public void setUserGender(String userGender) {
		this.userGender = userGender;
	}

	public String getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}

	public JSONObject toJson(){
        JSONObject result = null;
       try{
		 result = new JSONObject();
		result.put("userIcon",this.userIcon);
		result.put("userName",this.userName);
		result.put("userGender",this.userGender);
		result.put("userId",this.userId);
  }catch(Exception e){
            Log.i("MyPlugin",e.toString());
        }
		return result;
	}

}


text:
'use strict';

exports.VERSION = '0.6.1';
exports.Simulator = require('./lib/simulator.js');
exports.data = require('./lib/data.js');
exports.util = require('./lib/util.js');

if (global.document) global.simu = exports;


text:
"use strict";
var Node = require('./Node');

var NonDocumentTypeChildNode = {

  nextElementSibling: { get: function() {
    if (this.parentNode) {
      var sibs = this.parentNode.childNodes;
      for(var i = this.index+1, n = sibs.length; i < n; i++) {
        if (sibs[i].nodeType === Node.ELEMENT_NODE) return sibs[i];
      }
    }
    return null;
  }},

  previousElementSibling: { get: function() {
    if (this.parentNode) {
      var sibs = this.parentNode.childNodes;
      for(var i = this.index-1; i >= 0; i--) {
        if (sibs[i].nodeType === Node.ELEMENT_NODE) return sibs[i];
      }
    }
    return null;
  }}

};

module.exports = NonDocumentTypeChildNode;


text:
cQuestWindow::cQuestWindow() :
m_pUserInterface(NULL)
{
}

cQuestWindow::~cQuestWindow()
{
	SAFE_RELEASE(m_pUserInterface);
}

void cQuestWindow::Setup(){

	m_stMoveBar.left	= (float)m_pTransform->GetPosition().x + 9.0f;
	m_stMoveBar.top		= (float)m_pTransform->GetPosition().y + 5.0f;
	m_stMoveBar.right	= (float)m_pTransform->GetPosition().x + 287.0f;
	m_stMoveBar.bottom	= (float)m_pTransform->GetPosition().y + 30.0f;

	m_pUserInterface = new cUserInterface;
	m_pUserInterface->Setup("../Resource/UI/", "UI_basicBox", ".png");
	m_pUserInterface->SetPosition(D3DXVECTOR3(0.0f, 0.0f, 0.0f));
	m_pUserInterface->SetParentLeftTop(m_pTransform->getPosPointer());

	cExitButton* p = new cExitButton;
	p->Setup("../Resource/UI/", "UI_XButton", ".png");
	p->SetPosition(D3DXVECTOR3(289.0f, 8.0f, 0.0f));
	p->SetDelegate(this);
	m_pUserInterface->AddChild(p);

	m_sTextContent = "There's a Quest. \n Make an Inventory UI";

	cTextBox* tp = new cTextBox;
	tp->Setup("../Resource/UI/", "UI_TextBox", ".png");
	tp->SetPosition(D3DXVECTOR3(12.0f, 44.0f, 0.0f));
	tp->SetCaptionTarget(&m_sTextContent);
	m_pUserInterface->AddChild(tp);

	cOKButton* okp = new cOKButton;
	okp->Setup("../Resource/UI/", "UI_AcceptButton", ".png");
	okp->SetPosition(D3DXVECTOR3(21.0f, 271.0f, 0.0f));
	okp->SetDelegate(this);
	std::string content = "Challenge Accepted";
	okp->SetContent(content);
	m_pUserInterface->AddChild(okp);

	cOKButton* cp = new cOKButton;
	cp->Setup("../Resource/UI/", "UI_CancelButton", ".png");
	cp->SetPosition(D3DXVECTOR3(184.0f, 271.0f, 0.0f));
	cp->SetDelegate(this);
	content = "Challenge Denied";
	cp->SetContent(content);
	m_pUserInterface->AddChild(cp);

	//UI_MoveBar
	cMoveBar* mp = new cMoveBar;
	mp->Setup("../Resource/UI/", "UI_MoveBar", ".png");
	mp->SetPosition(D3DXVECTOR3(9.0f, 5.0f, 0.0f));
	mp->SetDelegate(this);
	m_pUserInterface->AddChild(mp);
}

void cQuestWindow::SetPosition(D3DXVECTOR3& pos){
	m_pTransform->SetPosition(pos);
}

void cQuestWindow::SetMousePosPointer(POINT* mousPos){
	if (m_pUserInterface){
		m_pUserInterface->SetMousePosPointer(mousPos);
	}
}

void cQuestWindow::SetMouseClickInfo(bool* mousclick){

	if (m_pUserInterface){
		m_pUserInterface->SetMouseClickInfo(mousclick);
	}
}

void cQuestWindow::Update(float delta){
	if (m_bShow){
		m_pUserInterface->Update(delta);
		m_pUserInterface->UpdateRectangle(m_pTransform->getPosPointer());
	}
	else {
		if (GetKeyState('Q') & 0x8000){
			m_bShow = true;
		}
	}
}

void cQuestWindow::Render(){
	if (m_pUserInterface){
		if (m_bShow){
			m_pUserInterface->Render();
		}
	}
}

void cQuestWindow::UserInterfaceActivation(cUserInterface* pSender, std::string& sContent){
	m_sTextContent = sContent;
}

void cQuestWindow::UserInterfaceFinished(cUserInterface* pSender){
	m_bShow = false;
}

void cQuestWindow::UserInterfaceMove(cUserInterface* pSender, D3DXVECTOR2& move){
	D3DXVECTOR3 newpos = { m_pTransform->GetPosition().x + move.x, m_pTransform->GetPosition().y + move.y, 0.0f };
	m_pTransform->SetPosition(newpos);
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Senparc.Weixin.MP.Entities
{
    /// <summary>
    /// 用户发送消息数据格式规范
    /// </summary>
    public interface IRequestMessageBase : IMessageBase
    {
        /// <summary>
        /// 用户发送消息类型
        /// </summary>
        RequestMsgType MsgType { get; }
        /// <summary>
        /// 消息ID
        /// </summary>
        long MsgId { get; set; }
    }

    /// <summary>
    /// 用户发送消息基类
    /// </summary>
    public class RequestMessageBase : MessageBase, IRequestMessageBase
    {
        /// <summary>
        /// 用户发送消息类型
        /// </summary>
        public virtual RequestMsgType MsgType
        {
            get { return RequestMsgType.Text; }
        }
        /// <summary>
        /// 消息ID
        /// </summary>
        public long MsgId { get; set; }
    }
}


text:
<?php
/**
 *
 * @category   Rohde
 * @package    Rohde_Onestepcheckout
 * @author     Support <j.rohde@nederland.live>
 */

class Rohde_Onestepcheckout_Block_Onestep_Form_Address extends Mage_Checkout_Block_Onepage_Abstract
{
    public function isUseBillingAsShipping()
    {
        return $this->getConfig()->isUseBillingAsShipping();
    }

    public function getConfig()
    {
        return Mage::helper('onestepcheckout/config');
    }

    public function getAddressChangedUrl()
    {
        return Mage::getUrl('onestepcheckout/ajax/saveAddress');
    }

    public function canShip()
    {
        return !$this->getQuote()->isVirtual();
    }

    public function getBlockNumber($isIncrementNeeded = true)
    {
        return Mage::helper('onestepcheckout')->getBlockNumber($isIncrementNeeded);
    }

    public function getSaveFormValuesUrl()
    {
        return Mage::getUrl('onestepcheckout/ajax/saveFormValues');
    }
}


text:
package pcap_test

import "log"

import "github.com/ghedo/go.pkt/capture/pcap"

func ExampleCapture() {
    src, err := pcap.Open("eth0")
    if err != nil {
        log.Fatal(err)
    }
    defer src.Close()

    // you may configure the source further, e.g. by activating
    // promiscuous mode.

    err = src.Activate()
    if err != nil {
        log.Fatal(err)
    }

    for {
        buf, err := src.Capture()
        if err != nil {
            log.Fatal(err)
        }

        log.Printf("PACKET!!! %v", buf)

        // do something with the packet
    }
}

func ExampleInject() {
    dst, err := pcap.Open("eth0")
    if err != nil {
        log.Fatal(err)
    }
    defer dst.Close()

    // you may configure the source further, e.g. by activating
    // promiscuous mode.

    err = dst.Activate()
    if err != nil {
        log.Fatal(err)
    }

    err = dst.Inject([]byte("random data"))
    if err != nil {
        log.Fatal(err)
    }
}


text:
package com.fedevela.dms.util;

/**
 * Created by fvelazquez on 9/04/14.
 */
import javax.accessibility.Accessible;
import javax.swing.JPanel;

public class JPanelDms extends JPanel implements Accessible {
}


text:
* **Renderer:** Rendering a space between lines with breaks: false ([1d39b8a](https://github.com/HHogg/remarkable-react/commit/1d39b8a))

## [1.4.2](https://github.com/HHogg/remarkable-react/compare/v1.4.1...v1.4.2) (2020-06-02)

### Bug Fixes

* **Footnote:** Correct output of href/id attrs ([eceabe2](https://github.com/HHogg/remarkable-react/commit/eceabe2))


text: A Mishmash of Math, Stats, and Logic With a Smattering of Parentheses