text:
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.browser.device_dialog;

import android.app.Dialog;
import android.support.test.filters.LargeTest;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

import org.chromium.base.test.util.CommandLineFlags;
import org.chromium.base.test.util.JniMocker;
import org.chromium.base.test.util.RetryOnFailure;
import org.chromium.chrome.R;
import org.chromium.chrome.browser.ChromeActivity;
import org.chromium.chrome.browser.flags.ChromeSwitches;
import org.chromium.chrome.test.ChromeActivityTestRule;
import org.chromium.chrome.test.ChromeJUnit4ClassRunner;
import org.chromium.components.security_state.ConnectionSecurityLevel;
import org.chromium.content_public.browser.test.util.Criteria;
import org.chromium.content_public.browser.test.util.CriteriaHelper;
import org.chromium.content_public.browser.test.util.TestThreadUtils;
import org.chromium.content_public.browser.test.util.TouchCommon;
import org.chromium.ui.widget.TextViewWithClickableSpans;

/**
 * Tests for the UsbChooserDialog class.
 */
@RunWith(ChromeJUnit4ClassRunner.class)
@RetryOnFailure
@CommandLineFlags.Add({ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE})
public class UsbChooserDialogTest {
    @Rule
    public ChromeActivityTestRule<ChromeActivity> mActivityTestRule =
            new ChromeActivityTestRule<>(ChromeActivity.class);

    @Rule
    public JniMocker mocker = new JniMocker();

    private String mSelectedDeviceId = "";

    private UsbChooserDialog mChooserDialog;

    private class TestUsbChooserDialogJni implements UsbChooserDialog.Natives {
        @Override
        public void onItemSelected(long nativeUsbChooserDialogAndroid, String deviceId) {
            mSelectedDeviceId = deviceId;
        }

        @Override
        public void onDialogCancelled(long nativeUsbChooserDialogAndroid) {}

        @Override
        public void loadUsbHelpPage(long nativeUsbChooserDialogAndroid) {}
    }

    @Before
    public void setUp() throws Exception {
        mocker.mock(UsbChooserDialogJni.TEST_HOOKS, new TestUsbChooserDialogJni());
        mActivityTestRule.startMainActivityOnBlankPage();
        mChooserDialog = createDialog();
    }

    private UsbChooserDialog createDialog() {
        return TestThreadUtils.runOnUiThreadBlockingNoException(() -> {
            UsbChooserDialog dialog = new UsbChooserDialog(/*nativeUsbChooserDialogPtr=*/42);
            dialog.show(mActivityTestRule.getActivity(), "https://origin.example.com/",
                    ConnectionSecurityLevel.SECURE);
            return dialog;
        });
    }

    private void selectItem(int position) {
        final Dialog dialog = mChooserDialog.mItemChooserDialog.getDialogForTesting();
        final ListView items = (ListView) dialog.findViewById(R.id.items);
        final Button button = (Button) dialog.findViewById(R.id.positive);

        CriteriaHelper.pollUiThread(new Criteria() {
            @Override
            public boolean isSatisfied() {
                return items.getChildAt(0) != null;
            }
        });

        // The actual index for the first item displayed on screen.
        int firstVisiblePosition = items.getFirstVisiblePosition();
        TouchCommon.singleClickView(items.getChildAt(position - firstVisiblePosition));

        CriteriaHelper.pollUiThread(new Criteria() {
            @Override
            public boolean isSatisfied() {
                return button.isEnabled();
            }
        });

        TouchCommon.singleClickView(button);

        CriteriaHelper.pollUiThread(new Criteria() {
            @Override
            public boolean isSatisfied() {
                return !mSelectedDeviceId.equals("");
            }
        });
    }

    /**
     * The messages include <link> ... </link> or <link1> ... </link1>, <link2> ... </link2>
     * sections that are used to create clickable spans. For testing the messages, this function
     * returns the raw string without the tags.
     */
    private static String removeLinkTags(String message) {
        return message.replaceAll("</?link1>", "").replaceAll(
                "</?link2>", "").replaceAll("</?link>", "");
    }

    @Test
    @LargeTest
    public void testCancel() {
        Dialog dialog = mChooserDialog.mItemChooserDialog.getDialogForTesting();
        Assert.assertTrue(dialog.isShowing());

        final ListView items = (ListView) dialog.findViewById(R.id.items);
        final Button button = (Button) dialog.findViewById(R.id.positive);

        // The 'Connect' button should be disabled and the list view should be hidden.
        Assert.assertFalse(button.isEnabled());
        Assert.assertEquals(View.GONE, items.getVisibility());

        dialog.cancel();

        CriteriaHelper.pollUiThread(new Criteria() {
            @Override
            public boolean isSatisfied() {
                return mSelectedDeviceId.equals("");
            }
        });
    }

    @Test
    @LargeTest
    public void testSelectItem() {
        Dialog dialog = mChooserDialog.mItemChooserDialog.getDialogForTesting();

        TextViewWithClickableSpans statusView =
                (TextViewWithClickableSpans) dialog.findViewById(R.id.status);
        final ListView items = (ListView) dialog.findViewById(R.id.items);
        final Button button = (Button) dialog.findViewById(R.id.positive);
        final int position = 1;

        TestThreadUtils.runOnUiThreadBlocking(() -> {
            mChooserDialog.addDevice("device_id_0", "device_name_0");
            mChooserDialog.addDevice("device_id_1", "device_name_1");
            mChooserDialog.addDevice("device_id_2", "device_name_2");
            // Show the desired position at the top of the ListView (in case
            // not all the items can fit on small devices' screens).
            items.setSelection(position);
        });

        // After adding items to the dialog, the help message should be showing,
        // the 'Connect' button should still be disabled (since nothing's selected),
        // and the list view should show.
        Assert.assertEquals(removeLinkTags(mActivityTestRule.getActivity().getString(
                                    R.string.usb_chooser_dialog_footnote_text)),
                statusView.getText().toString());
        Assert.assertFalse(button.isEnabled());
        Assert.assertEquals(View.VISIBLE, items.getVisibility());

        selectItem(position);

        Assert.assertEquals("device_id_1", mSelectedDeviceId);
    }
}


text:
.class final Lcom/android/internal/policy/impl/keyguard/SlidingChallengeLayout$1;
.super Landroid/util/FloatProperty;
.source "SlidingChallengeLayout.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/internal/policy/impl/keyguard/SlidingChallengeLayout;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x8
    name = null
.end annotation

.annotation system Ldalvik/annotation/Signature;
    value = {
        "Landroid/util/FloatProperty",
        "<",
        "Lcom/android/internal/policy/impl/keyguard/SlidingChallengeLayout;",
        ">;"
    }
.end annotation

# direct methods
.method constructor <init>(Ljava/lang/String;)V
    .locals 0
    .parameter "x0"

    .prologue
    .line 136
    invoke-direct {p0, p1}, Landroid/util/FloatProperty;-><init>(Ljava/lang/String;)V

    return-void
.end method

# virtual methods
.method public get(Lcom/android/internal/policy/impl/keyguard/SlidingChallengeLayout;)Ljava/lang/Float;
    .locals 1
    .parameter "view"

    .prologue
    .line 145
    iget v0, p1, Lcom/android/internal/policy/impl/keyguard/SlidingChallengeLayout;->mHandleAlpha:F

    invoke-static {v0}, Ljava/lang/Float;->valueOf(F)Ljava/lang/Float;

    move-result-object v0

    return-object v0
.end method

.method public bridge synthetic get(Ljava/lang/Object;)Ljava/lang/Object;
    .locals 1
    .parameter "x0"

    .prologue
    .line 136
    check-cast p1, Lcom/android/internal/policy/impl/keyguard/SlidingChallengeLayout;

    .end local p1
    invoke-virtual {p0, p1}, Lcom/android/internal/policy/impl/keyguard/SlidingChallengeLayout$1;->get(Lcom/android/internal/policy/impl/keyguard/SlidingChallengeLayout;)Ljava/lang/Float;

    move-result-object v0

    return-object v0
.end method

.method public setValue(Lcom/android/internal/policy/impl/keyguard/SlidingChallengeLayout;F)V
    .locals 0
    .parameter "view"
    .parameter "value"

    .prologue
    .line 139
    iput p2, p1, Lcom/android/internal/policy/impl/keyguard/SlidingChallengeLayout;->mHandleAlpha:F

    .line 140
    invoke-virtual {p1}, Lcom/android/internal/policy/impl/keyguard/SlidingChallengeLayout;->invalidate()V

    .line 141
    return-void
.end method

.method public bridge synthetic setValue(Ljava/lang/Object;F)V
    .locals 0
    .parameter "x0"
    .parameter "x1"

    .prologue
    .line 136
    check-cast p1, Lcom/android/internal/policy/impl/keyguard/SlidingChallengeLayout;

    .end local p1
    invoke-virtual {p0, p1, p2}, Lcom/android/internal/policy/impl/keyguard/SlidingChallengeLayout$1;->setValue(Lcom/android/internal/policy/impl/keyguard/SlidingChallengeLayout;F)V

    return-void
.end method

redpajama_set_name: RedPajamaGithub


text:
const x: outer.debugger.Foo|null = null;

export {};


text:
package org.hisp.dhis.android.core.common;

public enum AssignedUserMode {
    CURRENT,
    PROVIDED,
    NONE,
    ANY
}


text:
package com.taobao.api.response;

import com.taobao.api.internal.mapping.ApiField;
import com.taobao.api.domain.CancelOrderResult;

import com.taobao.api.TaobaoResponse;

/**
 * TOP API: alibaba.logistics.order.cancel response.
 *
 * @author auto create
 * @since 1.0, null
 */
public class AlibabaLogisticsOrderCancelResponse extends TaobaoResponse {

	private static final long serialVersionUID = 2735344515219577161L;

	/**
	 * 撤销物流订单结果
	 */
	@ApiField("cancel_order_result")
	private CancelOrderResult cancelOrderResult;

	public void setCancelOrderResult(CancelOrderResult cancelOrderResult) {
		this.cancelOrderResult = cancelOrderResult;
	}
	public CancelOrderResult getCancelOrderResult( ) {
		return this.cancelOrderResult;
	}

}


text:
package fr.vidal.oss.jax_rs_linker;

import java.lang.String;

public final class ApplicationName {
	public static String get() {
		return "fr.vidal.oss.jax_rs_linker.it.Configuration";
	}
}


text:
#include "lua_cocos2dx_gui_manual.hpp"

#ifdef __cplusplus
extern "C" {
#endif
#include  "tolua_fix.h"
#ifdef __cplusplus
}
#endif

#include "cocos2d.h"
#include "LuaBasicConversions.h"
#include "LuaScriptHandlerMgr.h"
#include "CCLuaValue.h"
#include "CocosGUI.h"
#include "CCLuaEngine.h"

using namespace gui;

class LuaCocoStudioEventListener:public Ref
{
public:
    LuaCocoStudioEventListener();
    virtual ~LuaCocoStudioEventListener();

    static LuaCocoStudioEventListener* create();

    virtual void eventCallbackFunc(Ref* sender,int eventType);
};

LuaCocoStudioEventListener::LuaCocoStudioEventListener()
{

}

LuaCocoStudioEventListener::~LuaCocoStudioEventListener()
{

}

LuaCocoStudioEventListener* LuaCocoStudioEventListener::create()
{
    LuaCocoStudioEventListener* listener = new LuaCocoStudioEventListener();
    if (nullptr == listener)
        return nullptr;

    listener->autorelease();

    return listener;
}

void LuaCocoStudioEventListener::eventCallbackFunc(Ref* sender,int eventType)
{
    int handler = ScriptHandlerMgr::getInstance()->getObjectHandler((void*)this, ScriptHandlerMgr::HandlerType::STUDIO_EVENT_LISTENER);

    if (0 != handler)
    {
        LuaStudioEventListenerData eventData(sender,eventType);
        BasicScriptData data(this,(void*)&eventData);
        LuaEngine::getInstance()->handleEvent(ScriptHandlerMgr::HandlerType::STUDIO_EVENT_LISTENER, (void*)&data);
    }
}

static int lua_cocos2dx_Widget_addTouchEventListener(lua_State* L)
{
    if (nullptr == L)
        return 0;

    int argc = 0;
    Widget* self = nullptr;

#if COCOS2D_DEBUG >= 1
    tolua_Error tolua_err;
	if (!tolua_isusertype(L,1,"ccui.Widget",0,&tolua_err)) goto tolua_lerror;
#endif

    self = static_cast<Widget*>(tolua_tousertype(L,1,0));

#if COCOS2D_DEBUG >= 1
	if (nullptr == self) {
		tolua_error(L,"invalid 'self' in function 'lua_cocos2dx_Widget_addTouchEventListener'\n", NULL);
		return 0;
	}
#endif

    argc = lua_gettop(L) - 1;

    if (1 == argc)
    {
#if COCOS2D_DEBUG >= 1
        if (!toluafix_isfunction(L,2,"LUA_FUNCTION",0,&tolua_err))
        {
            goto tolua_lerror;
        }
#endif
        LuaCocoStudioEventListener* listener = LuaCocoStudioEventListener::create();
        if (nullptr == listener)
        {
            tolua_error(L,"LuaCocoStudioEventListener create fail\n", NULL);
            return 0;
        }

        LUA_FUNCTION handler = (  toluafix_ref_function(L,2,0));

        ScriptHandlerMgr::getInstance()->addObjectHandler((void*)listener, handler, ScriptHandlerMgr::HandlerType::STUDIO_EVENT_LISTENER);

        self->setUserObject(listener);
        self->addTouchEventListener(listener, toucheventselector(LuaCocoStudioEventListener::eventCallbackFunc));

        return 0;
    }

    CCLOG("'addTouchEventListener' function of Widget has wrong number of arguments: %d, was expecting %d\n", argc, 1);
    return 0;

#if COCOS2D_DEBUG >= 1
tolua_lerror:
    tolua_error(L,"#ferror in function 'addTouchEventListener'.",&tolua_err);
    return 0;
#endif
}

static void extendWidget(lua_State* L)
{
    lua_pushstring(L, "ccui.Widget");
    lua_rawget(L, LUA_REGISTRYINDEX);
    if (lua_istable(L,-1))
    {
        tolua_function(L, "addTouchEventListener", lua_cocos2dx_Widget_addTouchEventListener);
    }
    lua_pop(L, 1);
}

static int lua_cocos2dx_CheckBox_addEventListenerCheckBox(lua_State* L)
{
    if (nullptr == L)
        return 0;

    int argc = 0;
    CheckBox* self = nullptr;

#if COCOS2D_DEBUG >= 1
    tolua_Error tolua_err;
	if (!tolua_isusertype(L,1,"ccui.CheckBox",0,&tolua_err)) goto tolua_lerror;
#endif

    self = static_cast<CheckBox*>(tolua_tousertype(L,1,0));

#if COCOS2D_DEBUG >= 1
	if (nullptr == self) {
		tolua_error(L,"invalid 'self' in function 'lua_cocos2dx_CheckBox_addEventListenerCheckBox'\n", NULL);
		return 0;
	}
#endif
    argc = lua_gettop(L) - 1;
    if (1 == argc)
    {
#if COCOS2D_DEBUG >= 1
        if (!toluafix_isfunction(L,2,"LUA_FUNCTION",0,&tolua_err))
        {
            goto tolua_lerror;
        }
#endif
        LuaCocoStudioEventListener* listener = LuaCocoStudioEventListener::create();
        if (nullptr == listener)
        {
            tolua_error(L,"LuaCocoStudioEventListener create fail\n", NULL);
            return 0;
        }

        LUA_FUNCTION handler = (  toluafix_ref_function(L,2,0));

        ScriptHandlerMgr::getInstance()->addObjectHandler((void*)listener, handler, ScriptHandlerMgr::HandlerType::STUDIO_EVENT_LISTENER);

        self->setUserObject(listener);
        self->addEventListenerCheckBox(listener, checkboxselectedeventselector(LuaCocoStudioEventListener::eventCallbackFunc));

        return 0;
    }

    CCLOG("'addEventListenerCheckBox' function of CheckBox has wrong number of arguments: %d, was expecting %d\n", argc, 1);
    return 0;

#if COCOS2D_DEBUG >= 1
tolua_lerror:
    tolua_error(L,"#ferror in function 'addEventListenerCheckBox'.",&tolua_err);
    return 0;
#endif
}

static void extendCheckBox(lua_State* L)
{
    lua_pushstring(L, "ccui.CheckBox");
    lua_rawget(L, LUA_REGISTRYINDEX);
    if (lua_istable(L,-1))
    {
        tolua_function(L, "addEventListenerCheckBox", lua_cocos2dx_CheckBox_addEventListenerCheckBox);
    }
    lua_pop(L, 1);
}

static int lua_cocos2dx_Slider_addEventListenerSlider(lua_State* L)
{
    if (nullptr == L)
        return 0;

    int argc = 0;
    Slider* self = nullptr;

#if COCOS2D_DEBUG >= 1
    tolua_Error tolua_err;
	if (!tolua_isusertype(L,1,"ccui.Slider",0,&tolua_err)) goto tolua_lerror;
#endif

    self = static_cast<Slider*>(tolua_tousertype(L,1,0));

#if COCOS2D_DEBUG >= 1
	if (nullptr == self) {
		tolua_error(L,"invalid 'self' in function 'lua_cocos2dx_Slider_addEventListenerSlider'\n", NULL);
		return 0;
	}
#endif
    argc = lua_gettop(L) - 1;
    if (1 == argc)
    {
#if COCOS2D_DEBUG >= 1
        if (!toluafix_isfunction(L,2,"LUA_FUNCTION",0,&tolua_err) )
        {
            goto tolua_lerror;
        }
#endif
        LuaCocoStudioEventListener* listener = LuaCocoStudioEventListener::create();
        if (nullptr == listener)
        {
            tolua_error(L,"LuaCocoStudioEventListener create fail\n", NULL);
            return 0;
        }

        LUA_FUNCTION handler = (  toluafix_ref_function(L,2,0));

        ScriptHandlerMgr::getInstance()->addObjectHandler((void*)listener, handler, ScriptHandlerMgr::HandlerType::STUDIO_EVENT_LISTENER);

        self->setUserObject(listener);
        self->addEventListenerSlider(listener, sliderpercentchangedselector(LuaCocoStudioEventListener::eventCallbackFunc));

        return 0;
    }

    CCLOG("'addEventListenerSlider' function of Slider has wrong number of arguments: %d, was expecting %d\n", argc, 1);

    return 0;

#if COCOS2D_DEBUG >= 1
tolua_lerror:
    tolua_error(L,"#ferror in function 'addEventListenerSlider'.",&tolua_err);
    return 0;
#endif
}

static void extendSlider(lua_State* L)
{
    lua_pushstring(L, "ccui.Slider");
    lua_rawget(L, LUA_REGISTRYINDEX);
    if (lua_istable(L,-1))
    {
        tolua_function(L, "addEventListenerSlider", lua_cocos2dx_Slider_addEventListenerSlider);
    }
    lua_pop(L, 1);
}

static int lua_cocos2dx_TextField_addEventListenerTextField(lua_State* L)
{
    if (nullptr == L)
        return 0;

    int argc = 0;
    TextField* self = nullptr;

#if COCOS2D_DEBUG >= 1
    tolua_Error tolua_err;
	if (!tolua_isusertype(L,1,"ccui.TextField",0,&tolua_err)) goto tolua_lerror;
#endif

    self = static_cast<TextField*>(tolua_tousertype(L,1,0));

#if COCOS2D_DEBUG >= 1
	if (nullptr == self) {
		tolua_error(L,"invalid 'self' in function 'lua_cocos2dx_TextField_addEventListenerTextField'\n", NULL);
		return 0;
	}
#endif
    argc = lua_gettop(L) - 1;
    if (1 == argc)
    {
#if COCOS2D_DEBUG >= 1
        if (!toluafix_isfunction(L,2,"LUA_FUNCTION",0,&tolua_err))
        {
            goto tolua_lerror;
        }
#endif
        LuaCocoStudioEventListener* listener = LuaCocoStudioEventListener::create();
        if (nullptr == listener)
        {
            tolua_error(L,"LuaCocoStudioEventListener create fail\n", NULL);
            return 0;
        }

        LUA_FUNCTION handler = (  toluafix_ref_function(L,2,0));

        ScriptHandlerMgr::getInstance()->addObjectHandler((void*)listener, handler, ScriptHandlerMgr::HandlerType::STUDIO_EVENT_LISTENER);

        self->setUserObject(listener);
        self->addEventListenerTextField(listener, textfieldeventselector(LuaCocoStudioEventListener::eventCallbackFunc));

        return 0;
    }

    CCLOG("'addEventListenerTextField' function of TextField has wrong number of arguments: %d, was expecting %d\n", argc, 1);

    return 0;

#if COCOS2D_DEBUG >= 1
tolua_lerror:
    tolua_error(L,"#ferror in function 'addEventListenerTextField'.",&tolua_err);
    return 0;
#endif
}

static void extendTextField(lua_State* L)
{
    lua_pushstring(L, "ccui.TextField");
    lua_rawget(L, LUA_REGISTRYINDEX);
    if (lua_istable(L,-1))
    {
        tolua_function(L, "addEventListenerTextField", lua_cocos2dx_TextField_addEventListenerTextField);
    }
    lua_pop(L, 1);
}

static int lua_cocos2dx_PageView_addEventListenerPageView(lua_State* L)
{
    if (nullptr == L)
        return 0;

    int argc = 0;
    PageView* self = nullptr;

#if COCOS2D_DEBUG >= 1
    tolua_Error tolua_err;
	if (!tolua_isusertype(L,1,"ccui.PageView",0,&tolua_err)) goto tolua_lerror;
#endif

    self = static_cast<PageView*>(tolua_tousertype(L,1,0));

#if COCOS2D_DEBUG >= 1
	if (nullptr == self) {
		tolua_error(L,"invalid 'self' in function 'lua_cocos2dx_PageView_addEventListenerPageView'\n", NULL);
		return 0;
	}
#endif
    argc = lua_gettop(L) - 1;
    if (1 == argc)
    {
#if COCOS2D_DEBUG >= 1
        if (!toluafix_isfunction(L,2,"LUA_FUNCTION",0,&tolua_err) )
        {
            goto tolua_lerror;
        }
#endif
        LuaCocoStudioEventListener* listener = LuaCocoStudioEventListener::create();
        if (nullptr == listener)
        {
            tolua_error(L,"LuaCocoStudioEventListener create fail\n", NULL);
            return 0;
        }

        LUA_FUNCTION handler = (  toluafix_ref_function(L,2,0));

        ScriptHandlerMgr::getInstance()->addObjectHandler((void*)listener, handler, ScriptHandlerMgr::HandlerType::STUDIO_EVENT_LISTENER);

        self->setUserObject(listener);
        self->addEventListenerPageView(listener, pagevieweventselector(LuaCocoStudioEventListener::eventCallbackFunc));

        return 0;
    }

    CCLOG("'addEventListenerPageView' function of PageView has wrong number of arguments: %d, was expecting %d\n", argc, 1);

    return 0;

#if COCOS2D_DEBUG >= 1
tolua_lerror:
    tolua_error(L,"#ferror in function 'addEventListenerPageView'.",&tolua_err);
    return 0;
#endif
}

static void extendPageView(lua_State* L)
{
    lua_pushstring(L, "ccui.PageView");
    lua_rawget(L, LUA_REGISTRYINDEX);
    if (lua_istable(L,-1))
    {
        tolua_function(L, "addEventListenerPageView", lua_cocos2dx_PageView_addEventListenerPageView);
    }
    lua_pop(L, 1);
}

static int lua_cocos2dx_ListView_addEventListenerListView(lua_State* L)
{
    if (nullptr == L)
        return 0;

    int argc = 0;
    ListView* self = nullptr;

#if COCOS2D_DEBUG >= 1
    tolua_Error tolua_err;
	if (!tolua_isusertype(L,1,"ccui.ListView",0,&tolua_err)) goto tolua_lerror;
#endif

    self = static_cast<ListView*>(tolua_tousertype(L,1,0));

#if COCOS2D_DEBUG >= 1
	if (nullptr == self) {
		tolua_error(L,"invalid 'self' in function 'lua_cocos2dx_ListView_addEventListenerListView'\n", NULL);
		return 0;
	}
#endif
    argc = lua_gettop(L) - 1;
    if (1 == argc)
    {
#if COCOS2D_DEBUG >= 1
        if (!toluafix_isfunction(L,2,"LUA_FUNCTION",0,&tolua_err))
        {
            goto tolua_lerror;
        }
#endif
        LuaCocoStudioEventListener* listern = LuaCocoStudioEventListener::create();
        if (nullptr == listern)
        {
            tolua_error(L,"LuaCocoStudioEventListener create fail\n", NULL);
            return 0;
        }

        LUA_FUNCTION handler = (  toluafix_ref_function(L,2,0));

        ScriptHandlerMgr::getInstance()->addObjectHandler((void*)listern, handler, ScriptHandlerMgr::HandlerType::STUDIO_EVENT_LISTENER);

        self->setUserObject(listern);
        self->addEventListenerListView(listern, listvieweventselector(LuaCocoStudioEventListener::eventCallbackFunc));

        return 0;
    }

    CCLOG("'addEventListenerListView' function of ListView has wrong number of arguments: %d, was expecting %d\n", argc, 1);

    return 0;

#if COCOS2D_DEBUG >= 1
tolua_lerror:
    tolua_error(L,"#ferror in function 'addEventListenerListView'.",&tolua_err);
    return 0;
#endif
}

static void extendListView(lua_State* L)
{
    lua_pushstring(L, "ccui.ListView");
    lua_rawget(L, LUA_REGISTRYINDEX);
    if (lua_istable(L,-1))
    {
        tolua_function(L, "addEventListenerListView", lua_cocos2dx_ListView_addEventListenerListView);
    }
    lua_pop(L, 1);
}

static int lua_cocos2dx_LayoutParameter_setMargin(lua_State* L)
{
    if (nullptr == L)
        return 0;

    int argc = 0;
    LayoutParameter* self = nullptr;

#if COCOS2D_DEBUG >= 1
    tolua_Error tolua_err;
	if (!tolua_isusertype(L,1,"ccui.LayoutParameter",0,&tolua_err)) goto tolua_lerror;
#endif

    self = static_cast<LayoutParameter*>(tolua_tousertype(L,1,0));

#if COCOS2D_DEBUG >= 1
	if (nullptr == self) {
		tolua_error(L,"invalid 'self' in function 'lua_cocos2dx_LayoutParameter_setMargin'\n", NULL);
		return 0;
	}
#endif
    argc = lua_gettop(L) - 1;

    if (1 == argc)
    {
#if COCOS2D_DEBUG >= 1
        if (!tolua_istable(L, 2, 0, &tolua_err))
        {
            goto tolua_lerror;
        }
#endif

        Margin margin;
        lua_pushstring(L, "left");
        lua_gettable(L,2);
        margin.left = lua_isnil(L,-1) ? 0 : lua_tonumber(L,-1);
        lua_pop(L,1);

        lua_pushstring(L, "top");
        lua_gettable(L,2);
        margin.top = lua_isnil(L,-1) ? 0 : lua_tonumber(L,-1);
        lua_pop(L,1);

        lua_pushstring(L, "right");
        lua_gettable(L,2);
        margin.right = lua_isnil(L,-1) ? 0 : lua_tonumber(L,-1);
        lua_pop(L,1);

        lua_pushstring(L, "bottom");
        lua_gettable(L,2);
        margin.bottom = lua_isnil(L,-1) ? 0 : lua_tonumber(L,-1);
        lua_pop(L,1);

        self->setMargin(margin);
        return 0;
    }

    CCLOG("'setMargin' function of LayoutParameter has wrong number of arguments: %d, was expecting %d\n", argc, 1);

    return 0;

#if COCOS2D_DEBUG >= 1
tolua_lerror:
    tolua_error(L,"#ferror in function 'setMargin'.",&tolua_err);
    return 0;
#endif
}

static int lua_cocos2dx_LayoutParameter_getMargin(lua_State* L)
{
    if (nullptr == L)
        return 0;

    int argc = 0;
    LayoutParameter* self = nullptr;

#if COCOS2D_DEBUG >= 1
    tolua_Error tolua_err;
	if (!tolua_isusertype(L,1,"ccui.LayoutParameter",0,&tolua_err)) goto tolua_lerror;
#endif

    self = static_cast<LayoutParameter*>(tolua_tousertype(L,1,0));

#if COCOS2D_DEBUG >= 1
	if (nullptr == self) {
		tolua_error(L,"invalid 'self' in function 'lua_cocos2dx_LayoutParameter_getMargin'\n", NULL);
		return 0;
	}
#endif
    argc = lua_gettop(L) - 1;

    if (0 == argc)
    {
        Margin margin = self->getMargin();

        lua_newtable(L);

        lua_pushstring(L, "left");
        lua_pushnumber(L, (lua_Number) margin.left);
        lua_rawset(L, -3);

        lua_pushstring(L, "top");
        lua_pushnumber(L, (lua_Number) margin.top);
        lua_rawset(L, -3);

        lua_pushstring(L, "right");
        lua_pushnumber(L, (lua_Number) margin.right);
        lua_rawset(L, -3);

        lua_pushstring(L, "bottom");
        lua_pushnumber(L, (lua_Number) margin.bottom);
        lua_rawset(L, -3);

        return 1;
    }

    CCLOG("'getMargin' function of LayoutParameter has wrong number of arguments: %d, was expecting %d\n", argc, 0);

    return 0;

#if COCOS2D_DEBUG >= 1
tolua_lerror:
    tolua_error(L,"#ferror in function 'getMargin'.",&tolua_err);
    return 0;
#endif
}

static void extendLayoutParameter(lua_State* L)
{
    lua_pushstring(L, "ccui.LayoutParameter");
    lua_rawget(L, LUA_REGISTRYINDEX);
    if (lua_istable(L,-1))
    {
        tolua_function(L, "setMargin", lua_cocos2dx_LayoutParameter_setMargin);
        tolua_function(L, "getMargin", lua_cocos2dx_LayoutParameter_getMargin);
    }
    lua_pop(L, 1);
}

int register_all_cocos2dx_gui_manual(lua_State* L)
{
    if (nullptr == L)
        return 0;
    extendWidget(L);
    extendCheckBox(L);
    extendSlider(L);
    extendTextField(L);
    extendPageView(L);
    extendListView(L);
    extendLayoutParameter(L);

    return 0;
}


text:
using System;
using Sip.Simple;
using Base.Message;
using Http.Message;

namespace Server.Xcap
{
	class PidfManipulationHandler
		: BasePidfManipulationHandler
	{
		private readonly SimpleModule simpleModule;

		public PidfManipulationHandler(SimpleModule simpleModule)
		{
			this.simpleModule = simpleModule;
		}

		public override HttpMessageWriter ProcessGetItem(ByteArrayPart username, ByteArrayPart domain)
		{
			var document = simpleModule.GetDocument(username.ToString() + "@" + domain.ToString());

			if (document == null)
			{
				return base.CreateResponse(StatusCodes.NotFound);
			}
			else
			{
				var response = base.CreateNotFinishedResponse(StatusCodes.OK, ContentType.ApplicationPidfXml);

				document.WriteLenghtAndContent(response);

				return response;
			}
		}

		public override HttpMessageWriter ProcessPutItem(ByteArrayPart username, ByteArrayPart domain, HttpMessageReader reader, ArraySegment<byte> content)
		{
			var statusCode = StatusCodes.OK;

			int sipIfMatch = simpleModule.InvalidEtag;
			if (reader.Count.IfMatches > 0)
			{
				if (HexEncoding.TryParseHex8(reader.IfMatches[0].Bytes, reader.IfMatches[0].Begin, out sipIfMatch) == false)
					statusCode = StatusCodes.PreconditionFailed;
			}

			if (statusCode == StatusCodes.OK)
			{
				if (simpleModule.Publish(username.ToString() + "@" + domain.ToString(), ref sipIfMatch, 60, content) == false)
					statusCode = StatusCodes.BadRequest;
			}

			HttpMessageWriter response;
			if (statusCode != StatusCodes.OK)
			{
				response = CreateResponse(statusCode);
			}
			else
			{
				response = CreateNotFinishedResponse(statusCode, ContentType.None);

				response.WriteEtag(sipIfMatch);
				response.WriteCRLF();
			}

			return response;
		}
	}
}


text:
<title>Ogre::GLXUtils Class Reference - OGRE Documentation</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link type="text/css" rel="stylesheet" href="doxygen.css">
<link type="text/css" rel="stylesheet" href="tabs.css">

Main Page

Related Pages

Modules

Namespaces

Classes

Files

Directories

Class List

Class Index

Class Hierarchy

Class Members

Ogre

GLXUtils

Static Public Member Functions |
Static Public Attributes

Ogre::GLXUtils Class Reference

#include <OgreGLXUtils.h>

List of all members.

Static Public Member Functions

static GLXFBConfig 	getFBConfigFromContext (Display *display,::GLXContext context)

 	Get the GLXFBConfig used to create a ::GLXContext.

static GLXFBConfig 	getFBConfigFromDrawable (Display *display, GLXDrawable drawable, unsigned int *width, unsigned int *height)

 	Get the GLXFBConfig used to create a GLXDrawable.

static void 	initialiseGLXEW (Display *display)

 	Initialise the parts of GLXEW needed to create a GL Context.

static GLXFBConfig 	selectFBConfig (Display *display, const int *minAttribs, const int *maxAttribs)

 	Select an FBConfig given a list of required and a list of desired properties.

static bool 	loadIcon (Display *display, const std::string &name, Pixmap *pix, Pixmap *mask)

 	Loads an icon from an Ogre resource into the X Server.

Static Public Attributes

static PFNGLXCHOOSEFBCONFIGPROC 	chooseFBConfig

static PFNGLXCREATENEWCONTEXTPROC 	createNewContext

static PFNGLXGETFBCONFIGATTRIBPROC 	getFBConfigAttrib

static

PFNGLXGETVISUALFROMFBCONFIGPROC 	getVisualFromFBConfig

Detailed Description

Definition at line 37 of file OgreGLXUtils.h.

Member Function Documentation

          static GLXFBConfig Ogre::GLXUtils::getFBConfigFromContext
          (
          Display *
          display,

          ::GLXContext
          context

          )
          	 [static]

Get the GLXFBConfig used to create a ::GLXContext.

Parameters:

display	X Display

drawable	GLXContext

Returns:

GLXFBConfig used to create the context

          static GLXFBConfig Ogre::GLXUtils::getFBConfigFromDrawable
          (
          Display *
          display,

          GLXDrawable
          drawable,

          unsigned int *
          width,

          unsigned int *
          height

          )
          	 [static]

Get the GLXFBConfig used to create a GLXDrawable.

Caveat: GLX version 1.3 is needed when the drawable is a GLXPixmap

Parameters:

display	X Display

drawable	GLXDrawable

width	Receiver for the drawable width

height	Receiver for the drawable height

Returns:

GLXFBConfig used to create the drawable

          static void Ogre::GLXUtils::initialiseGLXEW
          (
          Display *
          display	)
           [static]

Initialise the parts of GLXEW needed to create a GL Context.

Parameters:

display	X Display

          static bool Ogre::GLXUtils::loadIcon
          (
          Display *
          display,

          const std::string &
          name,

          Pixmap *
          pix,

          Pixmap *
          mask

          )
          	 [static]

Loads an icon from an Ogre resource into the X Server.

This currently only works for 24 and 32 bit displays. The image must be findable by the Ogre resource system, and of format PF_A8R8G8B8.

Parameters:

display	X display

name	Name of image to load

pix	Receiver for the output pixmap

mask	Receiver for the output mask (alpha bitmap)

Returns:

true on success

          static GLXFBConfig Ogre::GLXUtils::selectFBConfig
          (
          Display *
          display,

          const int *
          minAttribs,

          const int *
          maxAttribs

          )
          	 [static]

Select an FBConfig given a list of required and a list of desired properties.

Parameters:

display	X Display

minAttribs	FBConfig attributes that must be provided with minimum values

maxAttribs	FBConfig attributes that are preferred with maximum values

Returns:

GLXFBConfig with attributes or 0 when unsupported.

Member Data Documentation

          PFNGLXCHOOSEFBCONFIGPROC Ogre::GLXUtils::chooseFBConfig [static]

Definition at line 42 of file OgreGLXUtils.h.

          PFNGLXCREATENEWCONTEXTPROC Ogre::GLXUtils::createNewContext [static]

Definition at line 43 of file OgreGLXUtils.h.

          PFNGLXGETFBCONFIGATTRIBPROC Ogre::GLXUtils::getFBConfigAttrib [static]

Definition at line 44 of file OgreGLXUtils.h.

          PFNGLXGETVISUALFROMFBCONFIGPROC Ogre::GLXUtils::getVisualFromFBConfig [static]

Definition at line 45 of file OgreGLXUtils.h.

The documentation for this class was generated from the following file:

OgreGLXUtils.h

Copyright © 2012 Torus Knot Software Ltd

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.

Last modified Sun Sep 2 2012 07:27:50


text:
<?php
namespace app\modules\application;

use Yii;
use yii\base\Module;

class Application extends Module
{
	public $defaultRoute = 'application';

	/*
	public function init()
	{
		parent::init();
		$this->setLayoutPath(Yii::$app->basePath . '/views/layouts');
	}
	public function beforeAction($action)
	{
		 if (parent::beforeAction($action)) {
        	$actionName = Yii::$app->controller->action->id;
			if($actionName == 'adminlogin')
			{
				$this->layout = 'admin_login_layout';
			}
        	return true;  // or false if needed
    		}
		 else {
        	return false;
    	}
	}
	 *
	 *
	 */
}


text:
/**
 * Mark Benjamin 1st June 2017
 */

#ifndef FASTRL_BEHAVIOR_LEARNINGRATE_CONSTANT_LR_HPP
#define FASTRL_BEHAVIOR_LEARNINGRATE_CONSTANT_LR_HPP

#include "learning_rate.hpp"

class ConstantLR : public LearningRate {
public:
    double learningRate;
    explicit ConstantLR(double learning_rate = 0.1) {
        learningRate = learning_rate;
    }
    double peekAtLearningRate(State *s, Action *a) override {
        return learningRate;
    }
    double pollLearningRate(int agentTime, State *s, Action *a) override {
        return learningRate;
    }
    void resetDecay() override {}
    double peekAtLearningRate(int featureId) override {
        return learningRate;
    }
    double pollLearningRate(int agentTime, int featureId) override {
        return learningRate;
    }
};

#endif // FASTRL_BEHAVIOR_LEARNINGRATE_CONSTANT_LR_HPP


text:
// Copyright 2012-2013 Mark Dredze. All rights reserved.
// This software is released under the 2-clause BSD license.
// Mark Dredze, mdredze@cs.jhu.edu

package carmen.types;

import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import carmen.utils.CarmenProperties;
import carmen.utils.Utils;

import com.javadocmd.simplelatlng.LatLng;
import com.javadocmd.simplelatlng.LatLngTool;
import com.javadocmd.simplelatlng.util.LengthUnit;

/**
 * A helper class used by the LocationResolver to handle coordinates.
 * @author Mark Dredze mdredze@cs.jhu.edu
 *
 */
public class GeocodeLocationResolver {
	private final double maxDistance;
	private final HashMap<String,List<Location>> locationMap = new HashMap<String,List<Location>>();
	private final int cellSize = 100;

	public GeocodeLocationResolver () throws IOException {
		maxDistance = CarmenProperties.getDouble("geocode_max_distance");
	}

	public Location resolveLocation(Map<String,Object> tweet) {
		LatLng givenLatLong = Utils.getLatLngFromTweet(tweet);

		if (givenLatLong == null)
			return null;

		Set<Location> locations = this.getPossibleLocations(givenLatLong);
		Location closestLocation = null;
		double closestDistance = 0;

		for (Location location : locations) {
			// Check the distance to this location.
			LatLng latLong = location.getLatLng();

			double distanceInMiles = LatLngTool.distance(givenLatLong, latLong, LengthUnit.MILE);
			if (closestLocation == null | closestDistance > distanceInMiles) {
				closestDistance = distanceInMiles;
				closestLocation = location;
			}
		}

		if (closestLocation != null && closestDistance < this.maxDistance) {
			return closestLocation;
		}
		return null;
	}

	private Set<Location> getPossibleLocations(LatLng latLong) {
		List<String> keys = this.getKeys(latLong);

		Set<Location> locationSet = new HashSet<Location>();
		for (String key : keys) {
			if (this.locationMap.containsKey(key)) {
				List<Location> locations = this.locationMap.get(key);
				for (Location location : locations) {
					locationSet.add(location);
				}
			}
		}

		return locationSet;
	}

	public void addLocation(Location location) {
		if (location.getLatLng() == null)
			return;

		LatLng latLong = location.getLatLng();
		List<String> keys = this.getKeys(latLong);

		for (String key : keys) {
			if (!this.locationMap.containsKey(key)) {
				this.locationMap.put(key, new LinkedList<Location>());
			}

			List<Location> locations = this.locationMap.get(key);
			locations.add(location);
		}
	}

	private List<String> getKeys(LatLng latLong) {
		double latitude = latLong.getLatitude() * 100;
		double longitude = latLong.getLongitude() * 100;
		double shiftSize = this.cellSize  / (double)2;

		List<String> keys = new LinkedList<String>();

		keys.add(Integer.toString((int) (latitude/this.cellSize)) + "&&" + Integer.toString((int) (longitude/this.cellSize)));

		keys.add(Integer.toString((int) (latitude+shiftSize/this.cellSize)) + "&&" + Integer.toString((int) (longitude/this.cellSize)));
		keys.add(Integer.toString((int) (latitude-shiftSize/this.cellSize)) + "&&" + Integer.toString((int) (longitude/this.cellSize)));
		keys.add(Integer.toString((int) (latitude/this.cellSize)) + "&&" + Integer.toString((int) (longitude+shiftSize/this.cellSize)));
		keys.add(Integer.toString((int) (latitude/this.cellSize)) + "&&" + Integer.toString((int) (longitude-shiftSize/this.cellSize)));
		keys.add(Integer.toString((int) (latitude+shiftSize/this.cellSize)) + "&&" + Integer.toString((int) (longitude+shiftSize/this.cellSize)));
		keys.add(Integer.toString((int) (latitude+shiftSize/this.cellSize)) + "&&" + Integer.toString((int) (longitude-shiftSize/this.cellSize)));
		keys.add(Integer.toString((int) (latitude-shiftSize/this.cellSize)) + "&&" + Integer.toString((int) (longitude+shiftSize/this.cellSize)));
		keys.add(Integer.toString((int) (latitude-shiftSize/this.cellSize)) + "&&" + Integer.toString((int) (longitude-shiftSize/this.cellSize)));

		return keys;
	}
}


text:
<?php
/**
 * Answer Model
 *
 * @category    Answer.Model
 * @package     Recruitment.Answer.Model
 * @version     1.0
 * @author      Zak Taj <info@etechnologia.co.uk>
 * @license     http://www.opensource.org/licenses/mit-license.php The MIT License
 * @link        https://github.com/snoop-taj/Recruitment
 */
App::uses('RecruitmentAppModel', 'Recruitment.Model');

class Answer extends RecruitmentAppModel {

}


text:
var path = require('path');

var config = {
  // ### Production
  // When running Ghost in the wild, use the production environment
  // Configure your URL and mail settings here
  production: {
    url: '<%= productionUrl %>',
    mail: {},
    database: {
      client: 'sqlite3',
      connection: {
        filename: path.join(__dirname, 'content/data/ghost.db')
      },
      debug: false
    },

    server: {
      // Host to be passed to node's `net.Server#listen()`
      host: '127.0.0.1',
      // Port to be passed to node's `net.Server#listen()`, for iisnode set this to `process.env.PORT`
      port: '2368'
    }
  },

  // ### Development **(default)**
  development: {
    // The url to use when providing links to the site, E.g. in RSS and email.
    // Change this to your Ghost blogs published URL.
    url: 'http://localhost:4200',

    // Example mail config
    // Visit http://support.ghost.org/mail for instructions
    // ```
    //  mail: {
    //      transport: 'SMTP',
    //      options: {
    //          service: 'Mailgun',
    //          auth: {
    //              user: '', // mailgun username
    //              pass: ''  // mailgun password
    //          }
    //      }
    //  },
    // ```

    database: {
      client: 'sqlite3',
      connection: {
        filename: path.join(__dirname, 'content/data/ghost-dev.db')
      },
      debug: false
    },
    server: {
      // Host to be passed to node's `net.Server#listen()`
      host: '127.0.0.1',
      // Port to be passed to node's `net.Server#listen()`, for iisnode set this to `process.env.PORT`
      port: '4200'
    },
    paths: {
      contentPath: path.join(__dirname, 'content/')
    }
  }
};

// Export config
module.exports = config;


text:
package org.apache.nifi.web.security.saml.impl;

import org.apache.commons.lang3.SystemUtils;
import org.apache.nifi.util.NiFiProperties;
import org.apache.nifi.web.security.saml.SAMLConfigurationFactory;
import org.apache.nifi.web.security.saml.SAMLService;
import org.apache.nifi.web.security.saml.impl.tls.TruststoreStrategy;
import org.junit.After;
import org.junit.Assume;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

import java.io.File;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class TestStandardSAMLService {

    private NiFiProperties properties;
    private SAMLConfigurationFactory samlConfigurationFactory;
    private SAMLService samlService;

    @BeforeClass
    public static void setUpSuite() {
        Assume.assumeTrue("Test only runs on *nix", !SystemUtils.IS_OS_WINDOWS);
    }

    @Before
    public void setup() {
        properties = mock(NiFiProperties.class);
        samlConfigurationFactory = new StandardSAMLConfigurationFactory();
        samlService = new StandardSAMLService(samlConfigurationFactory, properties);
    }

    @After
    public void teardown() {
        samlService.shutdown();
    }

    @Test
    public void testSamlEnabledWithFileBasedIdpMetadata() {
        final String spEntityId = "org:apache:nifi";
        final File idpMetadataFile = new File("src/test/resources/saml/sso-circle-meta.xml");
        final String baseUrl = "https://localhost:8443/nifi-api";

        when(properties.getProperty(NiFiProperties.SECURITY_KEYSTORE)).thenReturn("src/test/resources/saml/keystore.jks");
        when(properties.getProperty(NiFiProperties.SECURITY_KEYSTORE_PASSWD)).thenReturn("passwordpassword");
        when(properties.getProperty(NiFiProperties.SECURITY_KEY_PASSWD)).thenReturn("passwordpassword");
        when(properties.getProperty(NiFiProperties.SECURITY_KEYSTORE_TYPE)).thenReturn("JKS");
        when(properties.getProperty(NiFiProperties.SECURITY_TRUSTSTORE)).thenReturn("src/test/resources/saml/truststore.jks");
        when(properties.getProperty(NiFiProperties.SECURITY_TRUSTSTORE_PASSWD)).thenReturn("passwordpassword");
        when(properties.getProperty(NiFiProperties.SECURITY_TRUSTSTORE_TYPE)).thenReturn("JKS");

        when(properties.isSamlEnabled()).thenReturn(true);
        when(properties.getSamlServiceProviderEntityId()).thenReturn(spEntityId);
        when(properties.getSamlIdentityProviderMetadataUrl()).thenReturn("file://" + idpMetadataFile.getAbsolutePath());
        when(properties.getSamlAuthenticationExpiration()).thenReturn("12 hours");
        when(properties.getSamlHttpClientTruststoreStrategy()).thenReturn(TruststoreStrategy.JDK.name());

        // initialize the saml service
        samlService.initialize();
        assertTrue(samlService.isSamlEnabled());

        // initialize the service provider
        assertFalse(samlService.isServiceProviderInitialized());
        samlService.initializeServiceProvider(baseUrl);
        assertTrue(samlService.isServiceProviderInitialized());

        // obtain the service provider metadata xml
        final String spMetadataXml = samlService.getServiceProviderMetadata();
        assertTrue(spMetadataXml.contains("entityID=\"org:apache:nifi\""));
        assertTrue(spMetadataXml.contains("<md:AssertionConsumerService Binding=\"urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST\" Location=\"https://localhost:8443/nifi-api/access/saml/login/consumer\""));
        assertTrue(spMetadataXml.contains("<md:SingleLogoutService Binding=\"urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST\" Location=\"https://localhost:8443/nifi-api/access/saml/single-logout/consumer\"/>"));
        assertTrue(spMetadataXml.contains("<md:SingleLogoutService Binding=\"urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect\" Location=\"https://localhost:8443/nifi-api/access/saml/single-logout/consumer\"/>"));
    }

    @Test
    public void testInitializeWhenSamlNotEnabled() {
        when(properties.isSamlEnabled()).thenReturn(false);

        // initialize the saml service
        samlService.initialize();
        assertFalse(samlService.isSamlEnabled());

        // methods should throw IllegalStateException...

        try {
            samlService.initializeServiceProvider("https://localhost:8443/nifi-api");
            fail("Should have thrown exception");
        } catch (IllegalStateException e) {

        }

        try {
            samlService.getServiceProviderMetadata();
            fail("Should have thrown exception");
        } catch (IllegalStateException e) {

        }
    }
}


text:
package org.apache.samza.checkpoint;

import java.util.Objects;
import org.apache.commons.lang3.StringUtils;
import org.apache.samza.annotation.InterfaceStability;

/**
 * Checkpoint ID has the format: [currentTimeMillis, last 6 digits of nanotime], separated by a dash.
 * This is to avoid conflicts, e.g when requesting frequent manual commits.
 *
 * It is expected that persistent stores use the {@link #toString()} representation of the checkpoint id
 * as the store checkpoint directory name.
 */
@InterfaceStability.Unstable
public class CheckpointId {
  public static final String SEPARATOR = "-";

  private final long millis;
  private final long nanos;

  public CheckpointId(long millis, long nanos) {
    this.millis = millis;
    this.nanos = nanos;
  }

  public static CheckpointId create() {
    return new CheckpointId(System.currentTimeMillis(), System.nanoTime() % 1000000);
  }

  public static CheckpointId fromString(String checkpointId) {
    if (StringUtils.isBlank(checkpointId)) {
      throw new IllegalArgumentException("Invalid checkpoint id: " + checkpointId);
    }
    String[] parts = checkpointId.split(SEPARATOR);
    return new CheckpointId(Long.parseLong(parts[0]), Long.parseLong(parts[1]));
  }

  public long getMillis() {
    return millis;
  }

  public long getNanos() {
    return nanos;
  }

  @Override
  public String toString() {
    return String.format("%s%s%s", millis, SEPARATOR, nanos);
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    CheckpointId that = (CheckpointId) o;
    return millis == that.millis &&
        nanos == that.nanos;
  }

  @Override
  public int hashCode() {
    return Objects.hash(millis, nanos);
  }
}


text:
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using System;
using System.Linq;
using System.Threading.Tasks;
using Grpc.Core;
using Microsoft.Azure.WebJobs.Script.Abstractions;
using Microsoft.Azure.WebJobs.Script.Grpc.Messages;

namespace Microsoft.Azure.WebJobs.Script.Grpc
{
    public class GrpcServer : IRpcServer, IDisposable
    {
        private Server _server;
        private bool _disposed = false;
        public const int MaxMessageLengthBytes = 128 * 1024 * 1024;

        public GrpcServer(FunctionRpc.FunctionRpcBase serviceImpl)
        {
            ChannelOption maxReceiveMessageLength = new ChannelOption(ChannelOptions.MaxReceiveMessageLength, MaxMessageLengthBytes);
            ChannelOption maxSendMessageLength = new ChannelOption(ChannelOptions.MaxSendMessageLength, MaxMessageLengthBytes);
            ChannelOption[] grpcChannelOptions = { maxReceiveMessageLength, maxSendMessageLength };
            _server = new Server(grpcChannelOptions)
            {
                Services = { FunctionRpc.BindService(serviceImpl) },
                Ports = { new ServerPort("127.0.0.1", ServerPort.PickUnused, ServerCredentials.Insecure) }
            };
        }

        public Uri Uri => new Uri($"http://127.0.0.1:{_server.Ports.First().BoundPort}");

        public Task StartAsync()
        {
            _server.Start();
            return Task.CompletedTask;
        }

        public Task ShutdownAsync() => _server.ShutdownAsync();

        public Task KillAsync() => _server.KillAsync();

        protected virtual void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing)
                {
                    _server.ShutdownAsync();
                }
                _disposed = true;
            }
        }

        public void Dispose()
        {
            Dispose(true);
        }
    }
}


text:
<resources>
    <string name="app_name">CoachMark</string>
</resources>


text:
<?xml version="1.0"?>
<package>
  <name>lg_common</name>
  <version>3.6.0</version>
  <description>Common software for Liquid Galaxy ROS nodes.</description>

  <maintainer email="lg@endpoint.com">End Point Liquid Galaxy Team</maintainer>

  <license>TODO</license>

  <url type="website">https://github.com/EndPointCorp/lg_ros_nodes</url>

  <author email="matt@endpoint.com">Matt Vollrath</author>

  <buildtool_depend>catkin</buildtool_depend>
  <build_depend>rospy</build_depend>
  <run_depend>message_runtime</run_depend>
  <run_depend>appctl</run_depend>
  <run_depend>std_msgs</run_depend>
  <run_depend>std_srvs</run_depend>
  <run_depend>interactivespaces_msgs</run_depend>
  <run_depend>rospy</run_depend>
  <run_depend>rosbridge_suite</run_depend>
  <run_depend>lg_msg_defs</run_depend>
  <run_depend>socat</run_depend>
  <test_depend>rostest</test_depend>
  <test_depend>python-pytest</test_depend>
</package>


text:
Network Model
-------------

Crowbar orchestrations the creation of networks and connects them to
other roles using conduits

Conduits
~~~~~~~~

A logical description of the networks to help Crowbar bind generically
across hardware platforms.

| On physical infrastructure, NIC enumeration is unpredictable and not
helpful for functional
| topologies. For example, a storage application wants to bind it's
primary service interface
| to the fasted teamed network available; however, there is no default
teamed network because
| they have to be constructed.

| Crowbar uses the network and conduit information to build abstract
networks for use by other
| roles.

| Conduits are defined using a Speed + Order syntax. Speed are given as
1g, 10g, 100m, etc
| and then order is ordinal from 0. The first 10g network would be noted
as 10g0.

    The on board management (aka IPMI or BMC) interface is a special
    conduit named 'bmc'

Please import more reference more material! There is a lot written about
conduits for CB1.

Ranges (networks\_ranges)
~~~~~~~~~~~~~~~~~~~~~~~~~

| A network has at least 1 range. Ranges are use to allocate v4 and v6
IP addresses to nodes
| using the network.

Ranges can have distinct conduits but will share the network conduit by
default.

Router (networks\_router)
~~~~~~~~~~~~~~~~~~~~~~~~~

Optional.

Describes the router used by the network and is required if the operator
wishes to have Crowbar configure a router when the network is setup on a
node.

Allocations (networks\_allcation)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Tracks the IP addresses that have been assigned to the network.

IPs are allocated as CIDRs.


text:
{% if site.disqus %}

	Please enable JavaScript to view the comments powered by Disqus.

{% endif %}


text:
package cn.nec.nlc.example.jamesli.activitytest52fragment;

import android.app.Fragment;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ScrollView;
import android.widget.TextView;

public class DetailsFragment extends Fragment {
    /**
     * Create a new instance of DetailsFragment, initialized to
     * show the text at 'index'.
     */
    public static DetailsFragment newInstance(int index) {
        DetailsFragment f = new DetailsFragment();

        // Supply index input as an argument.
        Bundle args = new Bundle();     // args is in terms of Bundle
        args.putInt("index", index);    // the bundle has only one parameter - index
        f.setArguments(args);

        return f;
    }

    // to check the corresponding detail is aligned with ListView selected index
    public int getShownIndex() {
        // access the index by ..
        return getArguments().getInt("index", 0);
    }

    // there is no other view, so we don't need onActivityCreated()
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (container == null) {
            // We have different layouts, and in one of them this
            // fragment's containing frame doesn't exist.  The fragment
            // may still be created from its saved state, but there is
            // no reason to try to create its view hierarchy because it
            // won't be displayed.  Note this is not needed -- we could
            // just run the code below, where we would create and return
            // the view hierarchy; it would just never be used.
            return null;
        }

        ScrollView scroller = new ScrollView(getActivity());
        TextView text = new TextView(getActivity());    // create TextView within Activity
        int padding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
                4, getActivity().getResources().getDisplayMetrics());
        text.setPadding(padding, padding, padding, padding);
        scroller.addView(text);     // embed TextView to ScrollView
        text.setText(Shakespeare.DIALOGUE[getShownIndex()]);
        return scroller;
    }
}


text:
*Common Data Model ETL Mapping Specification for Optum Extended SES & Extended DOD*

*CDM Version = 5.0.1, Clinformatics Version = v7.0*

*Authors: Qianli Ma; Erica Voss, Chris Knoll, Ajit Londhe, Clair Blacketer (Janssen)*

[Back to README](README.md)

---

# CDM Table: COST

The COST table captures cost information associated with any medical entity recorded in the [DRUG], [PROCEDURE], [VISIT], and [DEVICE] domains.

**Key conventions:**

- Use [*DRUG_EXPOSURE*](drug_exposure.md), [*PROCEDURE_OCCURRENCE*](procedure_occurrence.md), [*VISIT_OCCURRENCE*](visit_occurrence.md), and [*DEVICE_EXPOSURE*](device_exposure.md) to reference the COST_EVENT_ID
- Use *PAYER_PLAN_PERIOD* to obtain the PAYER_PLAN_PERIOD_ID.
- Use **RX_CLAIMS** and **TEMP_MEDICAL** to obtain the actual costs.

- Since the amount of observation time in *OBSERVATION_PERIOD* may be greater than that in *PAYER_PLAN_PERIOD* table, use left join to avoid excluding records when pulling PAYER_PLAN_PERIOD_ID. For those records fall out of PAYER_PLAN_PERIOD_START_DATE AND PAYER_PLAN_PERIOD_END_DATE, set PAYER_PLAN_PERIOD_ID as NULL.

**Destination Field**|**Source Field**|**Applied Rule**|**Comment**
:-----:|:-----:|:-----:|:-----:
COST_ID|-|-|A unique identifier for each COST record.
COST_EVENT_ID|*DRUG_EXPOSURE*
drug_exposure_id

*PROCEDURE_OCCURRENCE*
procedure_occurrence_id

*VISIT_OCCURRENCE*
visit_occurrence_id| |A foreign key identifier to the event (e.g. Measurement, Procedure, Visit, Drug Exposure, etc) record for which cost data are recorded.
COST_DOMAIN_ID|cost_event_id|WHEN cost_event_id = drug_exposure.drug_exposure_id THEN cost_domain_id = 'Drug'
WHEN cost_event_id = procedure_occurrence.procedure_occurrence_id THEN cost_domain_id = 'Procedure'
WHEN cost_event_id = visit_occurrence.visit_occurrence_id THEN cost_domain_id = 'Visit'
|
COST_TYPE_CONCEPT_ID|0| |Awaiting clarity on what codes to use here.
CURRENCY_CONCEPT_ID|-|[44818668](http://www.ohdsi.org/web/atlas/#/concept/44818668)|American dollar
TOTAL_CHARGE|[DRUG]
**RX_CLAIMS**
sum(charge)

[PROCEDURE]
**TEMP_MEDICAL**
charge

[VISIT]
**TEMP_MEDICAL**
charge| |
TOTAL_COST|-| |
TOTAL_PAID|-| |
PAID_BY_PAYER|-|-|
PAID_BY_PATIENT|[DRUG]
-

[PROCEDURE]
**TEMP_MEDICAL**
COINS+DEDUCT

[VISIT]
**TEMP_MEDICAL**
COINS+DEDUCT| |
PAID_PATIENT_COPAY|[DRUG]
**RX_CLAIMS**
sum(COPAY)

[PROCEDURE]
**TEMP_MEDICAL**
COPAY

[VISIT]
**TEMP_MEDICAL**
COPAY| |
PAID_PATIENT_COINSURANCE|[DRUG]
-

[PROCEDURE]
**TEMP_MEDICAL**
COINS

[VISIT]
**TEMP_MEDICAL**
COINS| |
PAID_PATIENT_DEDUCTIBLE|[DRUG]
**RX_CLAIMS**
sum(DEDUCT)

[PROCEDURE]
**TEMP_MEDICAL**
DEDUCT

[VISIT]
**TEMP_MEDICAL**
DEDUCT| |
PAID_BY_PRIMARY|-| |
PAID_INGREDIENT_COST|-| |
PAID_DISPENSING_COST|-| |
PAID_DISPENSING_FEE|[DRUG]
**RX_CLAIMS**
sum(DISPFEE)| |
PAYER_PLAN_PERIOD_ID|*PAYER_PLAN_PERIOD*
PAYER_PLAN_PERIOD_ID|[DRUG]
Look up associated PAYER_PLAN_PERIOD_ID by PERSON_ID and DRUG_EXPOSURE_START_DATE AND PAT_PLANID.  If there no match, put NULL.

[PROCEDURE]
Lookup associated PAYER_PLAN_PERIOD_ID.  Look up by PERSON_ID and PROCEDURE_DATE.  If there no match, put NULL.

[VISIT]
Lookup associated PAYER_PLAN_PERIOD_ID.  Look up by PERSON_ID and VISIT_START_DATE.  If there no match, put NULL.|
AMOUNT_ALLOWED|[DRUG]
**RX_CLAIMS**
sum(STD_COST)

[PROCEDURE]
**TEMP_MEDICAL**
STD_COST

[VISIT]
**TEMP_MEDICAL**
STD_COST| |
REVENUE_CODE_CONCEPT_ID|**TEMP_MEDICAL**
RVNU_CD|Use Vocabulary map  [Source to Source](code_snippets.md#source-to-source).
Filters:
```WHERE SOURCE_VOCABULARY_ID IN ('Revenue Code')<br>AND TARGET_VOCABULARY_ID IN ('Revenue Code')```|
REVENUE_CODE_SOURCE_VALUE|**TEMP_MEDICAL**
RVNU_CD|```if RVNU_CD == '0000' then NULL``` |


text:
 subdir.normalize.cnfilename.py
 curdir_all_html2txt_py.sh "py"
 cd txt_py/
 rm -fr TAGS
 find | grep -e "\.py$" | xargs etags -a
 echo "we have etags those list of files, make it searchable in emacs!"
 find | head
 echo "..."
 find |tail
 echo "^C to break, anykey to use emacs to search through py code!";read readline
 emacs &


text:
package net.evolutionaryarchitecture.jpa.samples;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;

@Entity
public class Factory {

    @Id
    @GeneratedValue
    Long factoryId;

    String name;

    @ManyToOne
    BusinessUnit unit;

    public Factory() {
        super();
    }

    public Factory(String name, BusinessUnit unit) {
        this.name = name;
        this.unit = unit;
    }
}


text:
const vec3 = require('../vec3')

/**
 * Determine the closest point on the given plane to the given line.
 *
 * The point of intersection will be invalid if parallel to the plane, e.g. NaN.
 *
 * @param {plane} plane the plane of reference
 * @param {line3} line the 3D line of reference
 * @returns {vec3} a new point
 */
const intersectToPlane = (plane, line) => {
  // plane: plane.normal * p = plane.w
  const pnormal = plane
  const pw = plane[3]

  const lpoint = line[0]
  const ldirection = line[1]

  // point: p = line.point + labda * line.direction
  const labda = (pw - vec3.dot(pnormal, lpoint)) / vec3.dot(pnormal, ldirection)

  const point = vec3.add(lpoint, vec3.scale(labda, ldirection))
  return point
}

module.exports = intersectToPlane


text:
<?php

namespace Silber\Bouncer\Conductors;

use Silber\Bouncer\Helpers;
use Silber\Bouncer\Database\Models;

use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;

class SyncsRolesAndAbilities
{
    use Concerns\FindsAndCreatesAbilities;

    /**
     * The authority for whom to sync roles/abilities.
     *
     * @var \Illuminate\Database\Eloquent\Model|string
     */
    protected $authority;

    /**
     * Constructor.
     *
     * @param \Illuminate\Database\Eloquent\Model|string  $authority
     */
    public function __construct($authority)
    {
        $this->authority = $authority;
    }

    /**
     * Sync the provided roles to the authority.
     *
     * @param  iterable  $roles
     * @return void
     */
    public function roles($roles)
    {
        $this->sync(
            Models::role()->getRoleKeys($roles),
            $this->authority->roles()
        );
    }

    /**
     * Sync the provided abilities to the authority.
     *
     * @param  iterable  $abilities
     * @return void
     */
    public function abilities($abilities)
    {
        $this->syncAbilities($abilities);
    }

    /**
     * Sync the provided forbidden abilities to the authority.
     *
     * @param  iterable  $abilities
     * @return void
     */
    public function forbiddenAbilities($abilities)
    {
        $this->syncAbilities($abilities, ['forbidden' => true]);
    }

    /**
     * Sync the given abilities for the authority.
     *
     * @param  iterable  $abilities
     * @param  array  $options
     * @return void
     */
    protected function syncAbilities($abilities, $options = ['forbidden' => false])
    {
        $abilityKeys = $this->getAbilityIds($abilities);
        $authority = $this->getAuthority();
        $relation = $authority->abilities();

        $this->newPivotQuery($relation)
             ->where('entity_type', $authority->getMorphClass())
             ->whereNotIn($relation->getRelatedPivotKeyName(), $abilityKeys)
             ->where('forbidden', $options['forbidden'])
             ->delete();

        if ($options['forbidden']) {
            (new ForbidsAbilities($this->authority))->to($abilityKeys);
        } else {
            (new GivesAbilities($this->authority))->to($abilityKeys);
        }
    }

    /**
     * Get (and cache) the authority for whom to sync roles/abilities.
     *
     * @return \Illuminate\Database\Eloquent\Model
     */
    protected function getAuthority()
    {
        if (is_string($this->authority)) {
            $this->authority = Models::role()->firstOrCreate([
                'name' => $this->authority
            ]);
        }

        return $this->authority;
    }

    /**
     * Get the fully qualified column name for the abilities table's primary key.
     *
     * @return string
     */
    protected function getAbilitiesQualifiedKeyName()
    {
        $model = Models::ability();

        return $model->getTable().'.'.$model->getKeyName();
    }

    /**
     * Sync the given IDs on the pivot relation.
     *
     * This is a heavily-modified version of Eloquent's built-in
     * BelongsToMany@sync - which we sadly cannot use because
     * our scope sets a "closure where" on the pivot table.
     *
     * @param  array  $ids
     * @param  \Illuminate\Database\Eloquent\Relations\BelongsToMany  $relation
     * @return void
     */
    protected function sync(array $ids, BelongsToMany $relation)
    {
        $current = $this->pluck(
            $this->newPivotQuery($relation),
            $relation->getRelatedPivotKeyName()
        );

        $this->detach(array_diff($current, $ids), $relation);

        $relation->attach(
            array_diff($ids, $current),
            Models::scope()->getAttachAttributes($this->authority)
        );
    }

    /**
     * Detach the records with the given IDs from the relationship.
     *
     * @param  array  $ids
     * @param  \Illuminate\Database\Eloquent\Relations\BelongsToMany  $relation
     * @return void
     */
    public function detach(array $ids, BelongsToMany $relation)
    {
        if (empty($ids)) {
            return;
        }

        $this->newPivotQuery($relation)
             ->whereIn($relation->getRelatedPivotKeyName(), $ids)
             ->delete();
    }

    /**
     * Get a scoped query for the pivot table.
     *
     * @param  \Illuminate\Database\Eloquent\Relations\BelongsToMany  $relation
     * @return \Illuminate\Database\Query\Builder
     */
    protected function newPivotQuery(BelongsToMany $relation)
    {
        $query = $relation
            ->newPivotStatement()
            ->where('entity_type', $this->getAuthority()->getMorphClass())
            ->where(
                $relation->getForeignPivotKeyName(),
                $relation->getParent()->getKey()
            );

        return Models::scope()->applyToRelationQuery(
            $query, $relation->getTable()
        );
    }

    /**
     * Pluck the values of the given column using the provided query.
     *
     * @param  mixed  $query
     * @param  string $column
     * @return string[]
     */
    protected function pluck($query, $column)
    {
        return Arr::pluck($query->get([$column]), last(explode('.', $column)));
    }
}


text:
require "spec_helper"

describe Todoist::Service::Project do

  let(:client) { Todoist::Client.new("api_token") }
  let(:project_service) { described_class.new(client) }

  describe "creating a project" do
    let(:arguments) { resource_without_id('project') }

    it "can create an project" do
      expect{
        project_service.create(arguments)
      }.to change{ client.queue.length}.by(+1)

      expect(client.queue.last.type).to eq 'project_add'
      expect(client.queue.last.arguments).to eq arguments
    end

    it "can create an project with custom tmp id" do
      expect{
        project_service.create(arguments, 'temporary id')
      }.to change{ client.queue.length}.by(+1)

      expect(client.queue.last.temp_id).to eq 'temporary id'
    end

    it "returns an project" do
      project = project_service.create(arguments, 'temporary id')
      expect(project.to_submittable_hash).to eq(arguments)
    end
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:id="@+id/interest_header"
    android:layout_width="fill_parent"
    android:layout_height="38dp"
    android:padding="5dp"
    android:background="@drawable/interest_background">

    <TextView
        android:id="@+id/interest_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
       	android:layout_centerVertical="true"
        android:textColor="@drawable/conversation_item_text_selector"
        android:textStyle="bold" />

</RelativeLayout>


text:
import unittest

from os.path import join
from unittest import mock

from tests.recipes.recipe_lib_test import RecipeCtx

class TestPandasRecipe(RecipeCtx, unittest.TestCase):
    """
    TestCase for recipe :mod:`~pythonforandroid.recipes.pandas`
    """
    recipe_name = "pandas"

    @mock.patch("pythonforandroid.recipe.Recipe.check_recipe_choices")
    @mock.patch("pythonforandroid.build.ensure_dir")
    @mock.patch("pythonforandroid.archs.glob")
    @mock.patch("pythonforandroid.archs.find_executable")
    def test_get_recipe_env(
        self,
        mock_find_executable,
        mock_glob,
        mock_ensure_dir,
        mock_check_recipe_choices,
    ):
        """
        Test that method
        :meth:`~pythonforandroid.recipes.pandas.PandasRecipe.get_recipe_env`
        returns the expected flags
        """

        mock_find_executable.return_value = (
            "/opt/android/android-ndk/toolchains/"
            "llvm/prebuilt/linux-x86_64/bin/clang"
        )
        mock_glob.return_value = ["llvm"]
        mock_check_recipe_choices.return_value = sorted(
            self.ctx.recipe_build_order
        )
        numpy_includes = join(
            self.ctx.get_python_install_dir(self.arch.arch), "numpy/core/include",
        )
        env = self.recipe.get_recipe_env(self.arch)
        self.assertIn(numpy_includes, env["NUMPY_INCLUDES"])
        self.assertIn(" -landroid", env["LDFLAGS"])

        # make sure that the mocked methods are actually called
        mock_glob.assert_called()
        mock_ensure_dir.assert_called()
        mock_find_executable.assert_called()
        mock_check_recipe_choices.assert_called()


text:
angular
   .module('Covalence')
   .controller('FilesController', FilesController);

function FilesController($scope, $stateParams, $state, $http) {
   var database = 'https://console.firebase.google.com/project/covalence-6384b/database/data/projects/pageData.json';
   $http.get(database)

   .then(function (result) {
     console.log("hello");
 })
}


text:
"""fix data access permissions for virtual datasets

Revision ID: 3fbbc6e8d654
Revises: e5ef6828ac4e
Create Date: 2020-09-24 12:04:33.827436

"""

# revision identifiers, used by Alembic.
revision = "3fbbc6e8d654"
down_revision = "e5ef6828ac4e"

import re

from alembic import op
from sqlalchemy import (
    Column,
    ForeignKey,
    Integer,
    orm,
    Sequence,
    String,
    Table,
    UniqueConstraint,
)
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import backref, relationship

Base = declarative_base()

# Partial freeze of the current metadata db schema

class Permission(Base):
    __tablename__ = "ab_permission"
    id = Column(Integer, Sequence("ab_permission_id_seq"), primary_key=True)
    name = Column(String(100), unique=True, nullable=False)

class ViewMenu(Base):
    __tablename__ = "ab_view_menu"
    id = Column(Integer, Sequence("ab_view_menu_id_seq"), primary_key=True)
    name = Column(String(250), unique=True, nullable=False)

    def __eq__(self, other):
        return (isinstance(other, self.__class__)) and (self.name == other.name)

    def __neq__(self, other):
        return self.name != other.name

assoc_permissionview_role = Table(
    "ab_permission_view_role",
    Base.metadata,
    Column("id", Integer, Sequence("ab_permission_view_role_id_seq"), primary_key=True),
    Column("permission_view_id", Integer, ForeignKey("ab_permission_view.id")),
    Column("role_id", Integer, ForeignKey("ab_role.id")),
    UniqueConstraint("permission_view_id", "role_id"),
)

class Role(Base):
    __tablename__ = "ab_role"

    id = Column(Integer, Sequence("ab_role_id_seq"), primary_key=True)
    name = Column(String(64), unique=True, nullable=False)
    permissions = relationship(
        "PermissionView", secondary=assoc_permissionview_role, backref="role"
    )

class PermissionView(Base):
    __tablename__ = "ab_permission_view"
    __table_args__ = (UniqueConstraint("permission_id", "view_menu_id"),)
    id = Column(Integer, Sequence("ab_permission_view_id_seq"), primary_key=True)
    permission_id = Column(Integer, ForeignKey("ab_permission.id"))
    permission = relationship("Permission")
    view_menu_id = Column(Integer, ForeignKey("ab_view_menu.id"))
    view_menu = relationship("ViewMenu")

sqlatable_user = Table(
    "sqlatable_user",
    Base.metadata,
    Column("id", Integer, primary_key=True),
    Column("user_id", Integer, ForeignKey("ab_user.id")),
    Column("table_id", Integer, ForeignKey("tables.id")),
)

class Database(Base):  # pylint: disable=too-many-public-methods

    """An ORM object that stores Database related information"""

    __tablename__ = "dbs"
    __table_args__ = (UniqueConstraint("database_name"),)

    id = Column(Integer, primary_key=True)
    verbose_name = Column(String(250), unique=True)
    # short unique name, used in permissions
    database_name = Column(String(250), unique=True, nullable=False)

    def __repr__(self) -> str:
        return self.name

    @property
    def name(self) -> str:
        return self.verbose_name if self.verbose_name else self.database_name

class SqlaTable(Base):
    __tablename__ = "tables"
    __table_args__ = (UniqueConstraint("database_id", "table_name"),)

    # Base columns from Basedatasource
    id = Column(Integer, primary_key=True)
    table_name = Column(String(250), nullable=False)
    database_id = Column(Integer, ForeignKey("dbs.id"), nullable=False)
    database = relationship(
        "Database",
        backref=backref("tables", cascade="all, delete-orphan"),
        foreign_keys=[database_id],
    )

    def get_perm(self) -> str:
        return f"[{self.database}].[{self.table_name}](id:{self.id})"

def upgrade():
    """
    Previous sqla_viz behaviour when creating a virtual dataset was faulty
    by creating an associated data access permission with [None] on the database name.

    This migration revision, fixes all faulty permissions that may exist on the db
    Only fixes permissions that still have an associated dataset (fetch by id)
    and replaces them with the current (correct) permission name
    """

    bind = op.get_bind()
    session = orm.Session(bind=bind)

    faulty_view_menus = (
        session.query(ViewMenu)
        .join(PermissionView)
        .join(Permission)
        .filter(ViewMenu.name.ilike("[None].[%](id:%)"))
        .filter(Permission.name == "datasource_access")
        .all()
    )
    orphaned_faulty_view_menus = []
    for faulty_view_menu in faulty_view_menus:
        # Get the dataset id from the view_menu name
        match_ds_id = re.match("\[None\]\.\[.*\]\(id:(\d+)\)", faulty_view_menu.name)
        if match_ds_id:
            dataset_id = int(match_ds_id.group(1))
            dataset = session.query(SqlaTable).get(dataset_id)
            if dataset:
                try:
                    new_view_menu = dataset.get_perm()
                except Exception:
                    # This can fail on differing SECRET_KEYS
                    return
                existing_view_menu = (
                    session.query(ViewMenu)
                    .filter(ViewMenu.name == new_view_menu)
                    .one_or_none()
                )
                # A view_menu permission with the right name already exists,
                # so delete the faulty one later
                if existing_view_menu:
                    orphaned_faulty_view_menus.append(faulty_view_menu)
                # No view_menu permission with this name exists
                # so safely change this one
                else:
                    faulty_view_menu.name = new_view_menu
    # Commit all view_menu updates
    try:
        session.commit()
    except SQLAlchemyError:
        session.rollback()

    # Delete all orphaned faulty permissions
    for orphaned_faulty_view_menu in orphaned_faulty_view_menus:
        pvm = (
            session.query(PermissionView)
            .filter(PermissionView.view_menu == orphaned_faulty_view_menu)
            .one_or_none()
        )
        if pvm:
            # Removes orphaned pvm from all roles
            roles = session.query(Role).filter(Role.permissions.contains(pvm)).all()
            for role in roles:
                if pvm in role.permissions:
                    role.permissions.remove(pvm)
            # Now it's safe to remove the pvm pair
            session.delete(pvm)
        # finally remove the orphaned view_menu permission
        session.delete(orphaned_faulty_view_menu)

    try:
        session.commit()
    except SQLAlchemyError:
        session.rollback()

def downgrade():
    pass


text:
#include <stdio.h>

#include "ms_speech/ms_speech_logging.h"
#include "ms_speech_priv.h"
#include "ms_speech_logging_priv.h"

static int ms_speech_log_levels = 0;
static ms_speech_global_log_t ms_speech_global_log_callback = NULL;

void ms_speech_set_logging(int levels, ms_speech_global_log_t callback)
{
	ms_speech_log_levels = levels;
	ms_speech_global_log_callback = callback;
	lws_set_log_level(levels, (void (*)(int, const char *))&ms_speech_log);
}

void ms_speech_log(ms_speech_log_level_t level, const char *format, ...)
{
	if (ms_speech_global_log_callback && (level & ms_speech_log_levels)) {
		va_list args;
		va_start(args, format);

		char *buffer = NULL;
		int r = vasprintf(&buffer, format, args);
		if (r != -1) {
			ms_speech_global_log_callback(level, buffer);
			free(buffer);
		}
		else {
			ms_speech_global_log_callback(MS_SPEECH_LOG_WARN, "Unable to allocate memory for logging");
		}

		va_end(args);
	}
}

void ms_speech_connection_log(ms_speech_connection_t connection, ms_speech_log_level_t level, const char *format, ...)
{
	if (level & ms_speech_log_levels) {
		va_list args;
		va_start(args, format);

		char *buffer = NULL;
		int r = vasprintf(&buffer, format, args);
		if (r == -1) {
			buffer = (char *)malloc(255);
			sprintf(buffer, "Unable to allocate memory for logging");
			level = MS_SPEECH_LOG_WARN;
		}
		if (connection->callbacks->log)
			connection->callbacks->log(connection, connection->callbacks->user_data, level, buffer);
		else if (ms_speech_global_log_callback)
			ms_speech_global_log_callback(level, buffer);

		free(buffer);

		va_end(args);
	}
}


text:
package com.graphhopper.routing.util.parsers;

import com.graphhopper.reader.ReaderWay;
import com.graphhopper.routing.ev.EnumEncodedValue;
import com.graphhopper.routing.ev.TrackType;
import com.graphhopper.routing.util.EncodingManager;
import com.graphhopper.storage.IntsRef;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class OSMTrackTypeParserTest {

    private EncodingManager em;
    private IntsRef relFlags;
    private EnumEncodedValue<TrackType> ttEnc;
    private OSMTrackTypeParser parser;

    @Before
    public void setUp() {
        parser = new OSMTrackTypeParser();
        em = new EncodingManager.Builder().add(parser).build();
        ttEnc = em.getEnumEncodedValue(TrackType.KEY, TrackType.class);
        relFlags = em.createRelationFlags();
    }

    @Test
    public void testSimpleTags() {
        ReaderWay readerWay = new ReaderWay(1);
        IntsRef intsRef = em.createEdgeFlags();
        readerWay.setTag("tracktype", "grade1");
        parser.handleWayTags(intsRef, readerWay, false, relFlags);
        assertEquals(TrackType.GRADE1, ttEnc.getEnum(false, intsRef));

        intsRef = em.createEdgeFlags();
        readerWay.setTag("tracktype", "grade2");
        parser.handleWayTags(intsRef, readerWay, false, relFlags);
        assertEquals(TrackType.GRADE2, ttEnc.getEnum(false, intsRef));

        intsRef = em.createEdgeFlags();
        readerWay.setTag("tracktype", "grade3");
        parser.handleWayTags(intsRef, readerWay, false, relFlags);
        assertEquals(TrackType.GRADE3, ttEnc.getEnum(false, intsRef));

        intsRef = em.createEdgeFlags();
        readerWay.setTag("tracktype", "grade4");
        parser.handleWayTags(intsRef, readerWay, false, relFlags);
        assertEquals(TrackType.GRADE4, ttEnc.getEnum(false, intsRef));

        intsRef = em.createEdgeFlags();
        readerWay.setTag("tracktype", "grade5");
        parser.handleWayTags(intsRef, readerWay, false, relFlags);
        assertEquals(TrackType.GRADE5, ttEnc.getEnum(false, intsRef));
    }

    @Test
    public void testUnkownValue() {
        ReaderWay readerWay = new ReaderWay(1);
        IntsRef intsRef = em.createEdgeFlags();
        readerWay.setTag("tracktype", "unknownstuff");
        parser.handleWayTags(intsRef, readerWay, false, relFlags);
        assertEquals(TrackType.MISSING, ttEnc.getEnum(false, intsRef));
    }

    @Test
    public void testNoNPE() {
        ReaderWay readerWay = new ReaderWay(1);
        IntsRef intsRef = em.createEdgeFlags();
        parser.handleWayTags(intsRef, readerWay, false, relFlags);
        assertEquals(TrackType.MISSING, ttEnc.getEnum(false, intsRef));
    }
}


text:
  <title>Hide Facebook Posts Matching a Keyword</title>
  <link rel="stylesheet" type="text/css" href="Keywords.css" />

Hide Facebook Posts

Posts containing these (comma-separated) keywords will be hidden.

  <textarea id="block_keywords" placeholder="Replace,these,words">
  </textarea>

  <button id="save">
  Save
  </button>


text:
(function (window) {
  var Muuri = window.Muuri;

  QUnit.module('Grid instance');

  QUnit.test('Muuri should be a global function', function (assert) {
    assert.expect(1);
    assert.strictEqual(typeof Muuri, 'function');
  });
})(this);


text:
module Azure::ServiceFabric::V6_2_0_9
  module Models
    #
    # Represents the health of the stateful service replica.
    # Contains the replica aggregated health state, the health events and the
    # unhealthy evaluations.
    #
    class StatefulServiceReplicaHealth < ReplicaHealth

      include MsRestAzure

      def initialize
        @ServiceKind = "Stateful"
      end

      attr_accessor :ServiceKind

      # @return [String] Id of a stateful service replica. ReplicaId is used by
      # Service Fabric to uniquely identify a replica of a partition. It is
      # unique within a partition and does not change for the lifetime of the
      # replica. If a replica gets dropped and another replica gets created on
      # the same node for the same partition, it will get a different value for
      # the id. Sometimes the id of a stateless service instance is also
      # referred as a replica id.
      attr_accessor :replica_id

      #
      # Mapper for StatefulServiceReplicaHealth class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'Stateful',
          type: {
            name: 'Composite',
            class_name: 'StatefulServiceReplicaHealth',
            model_properties: {
              aggregated_health_state: {
                client_side_validation: true,
                required: false,
                serialized_name: 'AggregatedHealthState',
                type: {
                  name: 'String'
                }
              },
              health_events: {
                client_side_validation: true,
                required: false,
                serialized_name: 'HealthEvents',
                type: {
                  name: 'Sequence',
                  element: {
                      client_side_validation: true,
                      required: false,
                      serialized_name: 'HealthEventElementType',
                      type: {
                        name: 'Composite',
                        class_name: 'HealthEvent'
                      }
                  }
                }
              },
              unhealthy_evaluations: {
                client_side_validation: true,
                required: false,
                serialized_name: 'UnhealthyEvaluations',
                type: {
                  name: 'Sequence',
                  element: {
                      client_side_validation: true,
                      required: false,
                      serialized_name: 'HealthEvaluationWrapperElementType',
                      type: {
                        name: 'Composite',
                        class_name: 'HealthEvaluationWrapper'
                      }
                  }
                }
              },
              health_statistics: {
                client_side_validation: true,
                required: false,
                serialized_name: 'HealthStatistics',
                type: {
                  name: 'Composite',
                  class_name: 'HealthStatistics'
                }
              },
              partition_id: {
                client_side_validation: true,
                required: false,
                serialized_name: 'PartitionId',
                type: {
                  name: 'String'
                }
              },
              ServiceKind: {
                client_side_validation: true,
                required: true,
                serialized_name: 'ServiceKind',
                type: {
                  name: 'String'
                }
              },
              replica_id: {
                client_side_validation: true,
                required: false,
                serialized_name: 'ReplicaId',
                type: {
                  name: 'String'
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
namespace('Sy.ServiceContainer');

/**
 * Alias to another service
 *
 * @package Sy
 * @subpackage ServiceContainer
 * @class
 */

Sy.ServiceContainer.Alias = function (id) {
    this.id = id;
};

Sy.ServiceContainer.Alias.prototype = Object.create(Object.prototype, {

    /**
     * Return the original service id
     *
     * @return {String}
     */

    toString: {
        value: function () {
            return this.id
        }
    }

});


text:
package  org.apache.struts.webapp.upload;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

/**
 * This class takes the UploadForm and retrieves the text value
 * and file attributes and puts them in the request for the display.jsp
 * page to display them
 *
 * @author Mike Schachter
 * @version $Rev: 471754 $ $Date: 2006-11-06 08:55:09 -0600 (Mon, 06 Nov 2006) $
 */

public class UploadAction extends Action
{
    public ActionForward execute(ActionMapping mapping,
                                 ActionForm form,
                                 HttpServletRequest request,
                                 HttpServletResponse response)
        throws Exception {

        if (form instanceof UploadForm) {

            //this line is here for when the input page is upload-utf8.jsp,
            //it sets the correct character encoding for the response
            String encoding = request.getCharacterEncoding();
            if ((encoding != null) && (encoding.equalsIgnoreCase("utf-8")))
            {
                response.setContentType("text/html; charset=utf-8");
            }

            UploadForm theForm = (UploadForm) form;

            //retrieve the text data
            String text = theForm.getTheText();

            //retrieve the query string value
            String queryValue = theForm.getQueryParam();

            //retrieve the file representation
            FormFile file = theForm.getTheFile();

            //retrieve the file name
            String fileName= file.getFileName();

            //retrieve the content type
            String contentType = file.getContentType();

            boolean writeFile = theForm.getWriteFile();

            //retrieve the file size
            String size = (file.getFileSize() + " bytes");

            String data = null;

            try {
                //retrieve the file data
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                InputStream stream = file.getInputStream();
                if (!writeFile) {
                    //only write files out that are less than 1MB
                    if (file.getFileSize() < (4*1024000)) {

                        byte[] buffer = new byte[8192];
                        int bytesRead = 0;
                        while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
                            baos.write(buffer, 0, bytesRead);
                        }
                        data = new String(baos.toByteArray());
                    }
                    else {
                        data = new String("The file is greater than 4MB, " +
                                " and has not been written to stream." +
                                " File Size: " + file.getFileSize() + " bytes. This is a" +
                                " limitation of this particular web application, hard-coded" +
                                " in org.apache.struts.webapp.upload.UploadAction");
                    }
                }
                else {
                    //write the file to the file specified
                    OutputStream bos = new FileOutputStream(theForm.getFilePath());
                    int bytesRead = 0;
                    byte[] buffer = new byte[8192];
                    while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
                        bos.write(buffer, 0, bytesRead);
                    }
                    bos.close();
                    data = "The file has been written to \"" + theForm.getFilePath() + "\"";
                }
                //close the stream
                stream.close();
            }
            catch (FileNotFoundException fnfe) {
                return null;
            }
            catch (IOException ioe) {
                return null;
            }

            //place the data into the request for retrieval from display.jsp
            request.setAttribute("text", text);
            request.setAttribute("queryValue", queryValue);
            request.setAttribute("fileName", fileName);
            request.setAttribute("contentType", contentType);
            request.setAttribute("size", size);
            request.setAttribute("data", data);

            //destroy the temporary file created
            file.destroy();

            //return a forward to display.jsp
            return mapping.findForward("display");
        }

        //this shouldn't happen in this example
        return null;
    }
}


text:
FAdmin.StartHooks["God"] = function()
    FAdmin.Access.AddPrivilege("God", 2)
    FAdmin.Commands.AddCommand("god", nil, "<Player>")
    FAdmin.Commands.AddCommand("ungod", nil, "<Player>")

    FAdmin.ScoreBoard.Player:AddActionButton(function(ply)
        if ply:FAdmin_GetGlobal("FAdmin_godded") then return "Ungod" end
        return "God"
    end, function(ply)
        if ply:FAdmin_GetGlobal("FAdmin_godded") then return "fadmin/icons/god", "fadmin/icons/disable" end
        return "fadmin/icons/god"
    end, Color(255, 130, 0, 255),

    function(ply) return FAdmin.Access.PlayerHasPrivilege(LocalPlayer(), "God") end, function(ply, button)
        if not ply:FAdmin_GetGlobal("FAdmin_godded") then
            RunConsoleCommand("_FAdmin", "god", ply:UserID())
        else
            RunConsoleCommand("_FAdmin", "ungod", ply:UserID())
        end

        if not ply:FAdmin_GetGlobal("FAdmin_godded") then button:SetImage2("fadmin/icons/disable") button:SetText("Ungod") button:GetParent():InvalidateLayout() return end
        button:SetImage2("null")
        button:SetText("God")
        button:GetParent():InvalidateLayout()
    end)
end


text:
[expect php]
[file]
<?php

class ErrorCodes {
	const FATAL = "Fatal error\n";
	const WARNING = "Warning\n";
	const INFO = "Informational message\n";

	static function print_fatal_error_codes() {
		echo @("FATAL = " . FATAL . "\n");
		echo "self::FATAL = " . self::FATAL;
    }
}

class ErrorCodesDerived extends ErrorCodes {
	const FATAL = "Worst error\n";
	static function print_fatal_error_codes() {
		echo "self::FATAL = " . self::FATAL;
		echo "parent::FATAL = " . parent::FATAL;
    }
}

/* Call the static function and move into the ErrorCodes scope */
ErrorCodes::print_fatal_error_codes();
ErrorCodesDerived::print_fatal_error_codes();

?>


text:
package socket.client;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;

public class SocketClientInitializer extends ChannelInitializer<SocketChannel> {
    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();

        pipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0 , 4, 0, 4));
        pipeline.addLast(new LengthFieldPrepender(4));
        pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
        pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));
        pipeline.addLast(new SocketClientHandler());
    }
}


text:
import sbt._
import Keys._

object SaaloopBuild extends Build {
  import Dependencies._
  import BuildSettings._

  override lazy val settings = super.settings :+ {
    shellPrompt := { s => Project.extract(s).currentProject.id + " > " }
  }

  // -------------------------------------------------------------------------------------------------------------------
  // Root Project
  // -------------------------------------------------------------------------------------------------------------------

  lazy val saaloop = Project("saaloop", file("."))
    .settings(basicSettings: _*)
    .aggregate(core, examples)

  // -------------------------------------------------------------------------------------------------------------------
  // Modules
  // -------------------------------------------------------------------------------------------------------------------

  lazy val core = Project("saaloop-core", file("saaloop-core"))
    .settings(basicSettings: _*)
    .settings(
    libraryDependencies ++= Seq(
      Compile.hadoop,
      Test.spec2
    )
  )

  // -------------------------------------------------------------------------------------------------------------------
  // Examples
  // -------------------------------------------------------------------------------------------------------------------

  lazy val examples = Project("saaloop-examples", file("saaloop-examples"))
    .settings(exampleSettings: _*)
    .settings(
    libraryDependencies ++= Seq(
      Compile.hadoop
    )
  ).dependsOn(core)

}


text:
class AddEnabledFieldToUsersMigration < Sequel::Migration

  def up
    add_column :users, :enabled, :boolean, :default => false
  end

  def down
    drop_column :users, :enabled
  end

end


text:
if !defined?(Capistrano::VERSION)
  raise "Capistrano is not present."
elsif !Capistrano::VERSION.start_with?("3")
  raise "Capistrano support is limited to version 3"
end

require 'jefferies_tube/capistrano/assets'
require 'jefferies_tube/capistrano/db'
require 'jefferies_tube/capistrano/deploy'
require 'jefferies_tube/capistrano/maintenance'
require 'jefferies_tube/capistrano/rails'
require 'jefferies_tube/capistrano/s3_assets'
require 'jefferies_tube/capistrano/ssh'


text:
namespace content {

TestSynchronousCompositor::TestSynchronousCompositor() : client_(NULL) {
}

TestSynchronousCompositor::~TestSynchronousCompositor() {
  SetClient(NULL);
}

void TestSynchronousCompositor::SetClient(SynchronousCompositorClient* client) {
  if (client_)
    client_->DidDestroyCompositor(this);
  client_ = client;
  if (client_) {
    client_->DidInitializeCompositor(this);
    client_->DidBecomeCurrent(this);
  }
}

SynchronousCompositor::Frame TestSynchronousCompositor::DemandDrawHw(
    const gfx::Size& surface_size,
    const gfx::Transform& transform,
    const gfx::Rect& viewport,
    const gfx::Rect& clip,
    const gfx::Rect& viewport_rect_for_tile_priority,
    const gfx::Transform& transform_for_tile_priority) {
  return std::move(hardware_frame_);
}

void TestSynchronousCompositor::ReturnResources(
    uint32_t output_surface_id,
    const cc::CompositorFrameAck& frame_ack) {
  ReturnedResources returned_resources;
  returned_resources.output_surface_id = output_surface_id;
  returned_resources.resources = frame_ack.resources;
  frame_ack_array_.push_back(returned_resources);
}

void TestSynchronousCompositor::SwapReturnedResources(FrameAckArray* array) {
  DCHECK(array);
  frame_ack_array_.swap(*array);
}

bool TestSynchronousCompositor::DemandDrawSw(SkCanvas* canvas) {
  DCHECK(canvas);
  return true;
}

void TestSynchronousCompositor::SetHardwareFrame(
    uint32_t output_surface_id,
    std::unique_ptr<cc::CompositorFrame> frame) {
  hardware_frame_.output_surface_id = output_surface_id;
  hardware_frame_.frame = std::move(frame);
}

TestSynchronousCompositor::ReturnedResources::ReturnedResources()
    : output_surface_id(0u) {}

TestSynchronousCompositor::ReturnedResources::ReturnedResources(
    const ReturnedResources& other) = default;

TestSynchronousCompositor::ReturnedResources::~ReturnedResources() {}

}  // namespace content


text:
package cli

import (
	"github.com/posener/complete/cmd/install"
)

// autocompleteInstaller is an interface to be implemented to perform the
// autocomplete installation and uninstallation with a CLI.
//
// This interface is not exported because it only exists for unit tests
// to be able to test that the installation is called properly.
type autocompleteInstaller interface {
	Install(string) error
	Uninstall(string) error
}

// realAutocompleteInstaller uses the real install package to do the
// install/uninstall.
type realAutocompleteInstaller struct{}

func (i *realAutocompleteInstaller) Install(cmd string) error {
	return install.Install(cmd)
}

func (i *realAutocompleteInstaller) Uninstall(cmd string) error {
	return install.Uninstall(cmd)
}

// mockAutocompleteInstaller is used for tests to record the install/uninstall.
type mockAutocompleteInstaller struct {
	InstallCalled   bool
	UninstallCalled bool
}

func (i *mockAutocompleteInstaller) Install(cmd string) error {
	i.InstallCalled = true
	return nil
}

func (i *mockAutocompleteInstaller) Uninstall(cmd string) error {
	i.UninstallCalled = true
	return nil
}