text:
package com.xinyiglass.xygdev.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;

import org.apache.commons.net.PrintCommandListener;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

public class IterateFtpDir {
    //private static Logger logger = Logger.getLogger(FTPListAllFiles.class);
    private FTPClient ftp;
    //public ArrayList<String> arFiles;

	public FTPClient getFtp() {
		return ftp;
	}

	public void log(String logMessage){
		System.out.println(logMessage);
	}

    /**
     * 重载构造函数
     * @param isPrintCommmand 是否打印与FTPServer的交互命令
     */
    public IterateFtpDir(boolean isPrintCommmand){
        ftp = new FTPClient();
        log("host:"+Constant.FTP_HOST);
        log("port:"+Constant.FTP_PORT);
        log("user:"+Constant.FTP_USER);
        log("pwd:"+Constant.FTP_PASS);
        //String FTP_HOST="192.168.139.9";
    	//int FTP_PORT=21;
    	//String FTP_USER="applvis";
    	//String FTP_PASS="applvis";
        try {
        	//this.login(FTP_HOST,FTP_PORT, FTP_USER, FTP_PASS);
			this.login(Constant.FTP_HOST, Constant.FTP_PORT, Constant.FTP_USER, Constant.FTP_PASS);
		} catch (IOException e) {
			e.printStackTrace();
		}
        if(isPrintCommmand){
            ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
        }
    }

    /**
     * 登陆FTP服务器
     * @param host FTPServer IP地址
     * @param port FTPServer 端口
     * @param username FTPServer 登陆用户名
     * @param password FTPServer 登陆密码
     * @return 是否登录成功
     * @throws IOException
     */
    public boolean login(String host,int port,String username,String password) throws IOException{
        this.ftp.connect(host,port);
        if(FTPReply.isPositiveCompletion(this.ftp.getReplyCode())){
            if(this.ftp.login(username, password)){
                //设置编码格式,解决中文乱码问题
                if (FTPReply.isPositiveCompletion(ftp.sendCommand("OPTS UTF8", "ON"))) {
                	Constant.LOCAL_CHARSET = "UTF-8";  // 开启服务器对UTF-8的支持,如果服务器支持就用UTF-8编码,否则就使用本地编码(GBK).
                }
                ftp.setControlEncoding(Constant.LOCAL_CHARSET);
                return true;
            }
        }
        if(this.ftp.isConnected()){
            this.ftp.disconnect();
        }
        return false;
    }

    /**
     * 关闭数据链接
     * @throws IOException
     */
    public void disConnection() throws IOException{
        if(this.ftp.isConnected()){
        	this.ftp.logout();
            this.ftp.disconnect();
        }
    }

	//获取文件类型
	@SuppressWarnings("unused")
	private static String getFileType(String fileName) {
		return fileName.substring(fileName.lastIndexOf(".")+1).toUpperCase();
	}

	//获取文件名称
	public static String getFileName(String filePath) {
		if(filePath==null||filePath.length()==0){
			return "";
		}else{
			String [] fileItems=filePath.split(Constant.DIR_SEP);
			return fileItems[fileItems.length-1];
		}
	}
	//取得文件大小
	public long getFileSizes(FTPFile f) throws IOException{
        long s=0;
        if(f!=null) s=f.getSize();
        return s;
    }
	//转换文件大小
	public static String FormetFileSize(long fileS) {
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        if (fileS==0){
        	fileSizeString = "文件无法读取!";
        } else if (fileS < 1024){
            fileSizeString = df.format((double) fileS) + "B";
        } else if (fileS < 1048576) {
            fileSizeString = df.format((double) fileS / 1024) + "KB";
        } else if (fileS < 1073741824) {
            fileSizeString = df.format((double) fileS / 1048576) + "M";
        } else {
            fileSizeString = df.format((double) fileS / 1073741824) + "G";
        }
        return fileSizeString;
    }

	//解决中文乱码的问题。因为服务器的字符集永远是默认的"ISO-8859-1",不会变更。
	//http://blog.csdn.net/hehuang139/article/details/9072243
	public static String str2FtpCharset(String x){
		String ret=null;
		try {
			ret= new String(x.getBytes(Constant.LOCAL_CHARSET), Constant.SERVER_CHARSET);
		} catch (UnsupportedEncodingException e) {
			ret=x;
			e.printStackTrace();
		}
		return ret;
	}

	//文件上传
	public boolean uploadFile(String pathname,String fileName,InputStream input) throws IOException{
		boolean ret=true;
        if(!this.ftp.changeWorkingDirectory(str2FtpCharset(pathname))){
        	LogUtil.log("upload无法切换到FTP对应的工作目录pathname!");
        	return false;
        };
		this.ftp.setBufferSize(1024);
        ftp.setFileType(FTPClient.BINARY_FILE_TYPE);   // 设置文件类型(二进制)
        ftp.storeFile(str2FtpCharset(fileName), input);  // 将上传文件存储到指定目录
		return ret;
	}

	 //检查ftp目录 是否存在
    public boolean checkDirectory(String dirName) throws IOException {
        boolean _flag = false;
        FTPFile[] files = ftp.listFiles();
        for (int i = 0; i < files.length; i++) {
            FTPFile file = files[i];
            if (file.isDirectory()) {
            	//System.out.print("确认:"+file.getName());
                if (dirName.equalsIgnoreCase(file.getName())) {
                    _flag = true;
                    break;
                }
            }
        }
        return _flag;
    }
}


text:
<script>
    <?php
        foreach (array_reverse($this->validationErrors) as $fieldName => $errorMsg) {
            $fieldJson = json_encode($fieldName);
            $errorMsgJson = json_encode($errorMsg);
            echo "showValidationError($fieldJson, $errorMsgJson);\n";
        }
    ?>
</script>

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
MimeConstants (Apache FOP 1.0 API)
</TITLE>

<META NAME="keywords" CONTENT="org.apache.fop.apps.MimeConstants interface">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

fop 1.0

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.apache.fop.apps

Interface MimeConstants

All Superinterfaces:
org.apache.xmlgraphics.util.MimeConstants

public interface MimeConstants
extends org.apache.xmlgraphics.util.MimeConstants

Frequently used MIME types for various file formats used when working with Apache FOP.

Field Summary

static java.lang.String
MIME_FOP_AREA_TREE

          Apache FOP's area tree XML

static java.lang.String
MIME_FOP_AWT_PREVIEW

          Apache FOP's AWT preview (non-standard MIME type)

static java.lang.String
MIME_FOP_IF

          Apache FOP's intermediate format XML

static java.lang.String
MIME_FOP_PRINT

          Apache FOP's Direct Printing (non-standard MIME type)

Fields inherited from interface org.apache.xmlgraphics.util.MimeConstants

MIME_AFP, MIME_AFP_ALT, MIME_AFP_GOCA, MIME_AFP_IOCA_FS10, MIME_AFP_IOCA_FS11, MIME_AFP_IOCA_FS45, MIME_EMF, MIME_EPS, MIME_GIF, MIME_JPEG, MIME_MIF, MIME_PCL, MIME_PCL_ALT, MIME_PDF, MIME_PLAIN_TEXT, MIME_PNG, MIME_POSTSCRIPT, MIME_RTF, MIME_RTF_ALT1, MIME_RTF_ALT2, MIME_SVG, MIME_TIFF, MIME_XSL_FO

Field Detail

MIME_FOP_AWT_PREVIEW

public static final java.lang.String MIME_FOP_AWT_PREVIEW

Apache FOP's AWT preview (non-standard MIME type)

See Also:
Constant Field Values

MIME_FOP_PRINT

public static final java.lang.String MIME_FOP_PRINT

Apache FOP's Direct Printing (non-standard MIME type)

See Also:
Constant Field Values

MIME_FOP_AREA_TREE

public static final java.lang.String MIME_FOP_AREA_TREE

Apache FOP's area tree XML

See Also:
Constant Field Values

MIME_FOP_IF

public static final java.lang.String MIME_FOP_IF

Apache FOP's intermediate format XML

See Also:
Constant Field Values

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

fop 1.0

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Copyright 1999-2010 The Apache Software Foundation. All Rights Reserved.


text:
Clazz.declarePackage ("JSV.common");
Clazz.load (null, "JSV.common.Parameters", ["java.lang.Boolean", "java.util.Hashtable", "JSV.common.ScriptToken"], function () {
c$ = Clazz.decorateAsClass (function () {
this.name = null;
this.integralMinY = 0.1;
this.integralRange = 50.0;
this.integralOffset = 30.0;
this.integralDrawAll = false;
this.peakListThreshold = NaN;
this.peakListInterpolation = "parabolic";
this.precision = 2;
this.htBooleans = null;
Clazz.instantialize (this, arguments);
}, JSV.common, "Parameters");
Clazz.makeConstructor (c$,
function () {
this.htBooleans =  new java.util.Hashtable ();
this.setBoolean (JSV.common.ScriptToken.TITLEON, true);
this.setBoolean (JSV.common.ScriptToken.ENABLEZOOM, true);
this.setBoolean (JSV.common.ScriptToken.DISPLAY2D, true);
this.setBoolean (JSV.common.ScriptToken.COORDINATESON, true);
this.setBoolean (JSV.common.ScriptToken.GRIDON, true);
this.setBoolean (JSV.common.ScriptToken.XSCALEON, true);
this.setBoolean (JSV.common.ScriptToken.YSCALEON, true);
this.setBoolean (JSV.common.ScriptToken.XUNITSON, true);
this.setBoolean (JSV.common.ScriptToken.YUNITSON, true);
});
$_M(c$, "setName",
function (name) {
this.name = name;
return this;
}, "~S");
$_M(c$, "getBooleans",
function () {
return this.htBooleans;
});
$_M(c$, "setBoolean",
function (st, val) {
this.htBooleans.put (st, Boolean.$valueOf (val));
return val;
}, "JSV.common.ScriptToken,~B");
$_M(c$, "getBoolean",
function (t) {
return Boolean.TRUE === this.htBooleans.get (t);
}, "JSV.common.ScriptToken");
c$.isTrue = $_M(c$, "isTrue",
function (value) {
return (value.length == 0 || Boolean.parseBoolean (value));
}, "~S");
c$.getTFToggle = $_M(c$, "getTFToggle",
function (value) {
return (value.equalsIgnoreCase ("TOGGLE") ? null : JSV.common.Parameters.isTrue (value) ? Boolean.TRUE : Boolean.FALSE);
}, "~S");
$_M(c$, "setP",
function (pd, st, value) {
switch (st) {
default:
return;
case JSV.common.ScriptToken.COORDINATESON:
case JSV.common.ScriptToken.DISPLAY1D:
case JSV.common.ScriptToken.DISPLAY2D:
case JSV.common.ScriptToken.ENABLEZOOM:
case JSV.common.ScriptToken.GRIDON:
case JSV.common.ScriptToken.REVERSEPLOT:
case JSV.common.ScriptToken.TITLEON:
case JSV.common.ScriptToken.TITLEBOLDON:
case JSV.common.ScriptToken.XSCALEON:
case JSV.common.ScriptToken.XUNITSON:
case JSV.common.ScriptToken.YSCALEON:
case JSV.common.ScriptToken.YUNITSON:
var tfToggle = JSV.common.Parameters.getTFToggle (value);
if (tfToggle != null) {
this.setBoolean (st, tfToggle.booleanValue ());
break;
}if (pd == null) return;
var b = !pd.getBoolean (st);
switch (st) {
default:
break;
case JSV.common.ScriptToken.XSCALEON:
this.setBoolean (JSV.common.ScriptToken.XUNITSON, b);
pd.setBoolean (JSV.common.ScriptToken.XUNITSON, b);
break;
case JSV.common.ScriptToken.YSCALEON:
this.setBoolean (JSV.common.ScriptToken.YUNITSON, b);
pd.setBoolean (JSV.common.ScriptToken.YUNITSON, b);
break;
}
this.setBoolean (st, b);
break;
}
if (pd == null) return;
pd.setBooleans (this, st);
}, "JSV.common.PanelData,JSV.common.ScriptToken,~S");
c$.isMatch = $_M(c$, "isMatch",
function (match, key) {
return match == null || key.equalsIgnoreCase (match);
}, "~S,~S");
c$.putInfo = $_M(c$, "putInfo",
function (match, info, key, value) {
if (value != null && JSV.common.Parameters.isMatch (match, key)) info.put (match == null ? key : match, value);
}, "~S,java.util.Map,~S,~O");
});


text:
<?php

namespace Chamilo\Application\Weblcms\Tool\Service;

use Chamilo\Application\Weblcms\Service\PublicationService;
use Chamilo\Application\Weblcms\Storage\DataClass\ContentObjectPublication;
use Chamilo\Application\Weblcms\Storage\DataClass\ContentObjectPublicationCategory;
use Chamilo\Libraries\Architecture\Application\Application;
use Chamilo\Libraries\Format\Structure\Breadcrumb;
use Chamilo\Libraries\Format\Structure\BreadcrumbTrail;

/**
 * Service to generate breadcrumbs for the categories (of a publication) or a selected category
 *
 * @package Chamilo\Application\Weblcms\Tool\Service
 *
 * @author Sven Vanpoucke - Hogeschool Gent
 */
class CategoryBreadcrumbsGenerator
{
    /**
     * @var \Chamilo\Application\Weblcms\Service\PublicationService
     */
    protected $publicationService;

    /**
     * CategoryBreadcrumbsGenerator constructor.
     *
     * @param \Chamilo\Application\Weblcms\Service\PublicationService $publicationService
     */
    public function __construct(PublicationService $publicationService)
    {
        $this->publicationService = $publicationService;
    }

    /**
     * Generates breadcrumbs recursively for a given ContentObjectPublicationCategory
     *
     * @param \Chamilo\Libraries\Format\Structure\BreadcrumbTrail $breadcrumbTrail
     * @param Application $urlGenerator
     * @param \Chamilo\Application\Weblcms\Storage\DataClass\ContentObjectPublicationCategory $contentObjectPublicationCategory
     */
    public function generateBreadcrumbsForCategory(
        BreadcrumbTrail $breadcrumbTrail, Application $urlGenerator,
        ContentObjectPublicationCategory $contentObjectPublicationCategory = null
    )
    {
        if (!$contentObjectPublicationCategory instanceof ContentObjectPublicationCategory)
        {
            return;
        }

        $parentId = $contentObjectPublicationCategory->get_parent();

        if (!empty($parentId))
        {
            $parent = $this->publicationService->getPublicationCategoryById($parentId);
            $this->generateBreadcrumbsForCategory($breadcrumbTrail, $urlGenerator, $parent);
        }

        $this->generateBreadcrumbForCategory($breadcrumbTrail, $urlGenerator, $contentObjectPublicationCategory);
    }

    /**
     * Generates category breadcrumbs recursively for a given ContentObjectPublication
     *
     * @param \Chamilo\Libraries\Format\Structure\BreadcrumbTrail $breadcrumbTrail
     * @param \Chamilo\Libraries\Architecture\Application\Application $urlGenerator
     * @param \Chamilo\Application\Weblcms\Storage\DataClass\ContentObjectPublication $contentObjectPublication
     */
    public function generateBreadcrumbsForContentObjectPublication(
        BreadcrumbTrail $breadcrumbTrail, Application $urlGenerator, ContentObjectPublication $contentObjectPublication
    )
    {
        $parentId = $contentObjectPublication->get_category_id();
        if(!empty($parentId))
        {
            $parent = $this->publicationService->getPublicationCategoryById($parentId);
            $this->generateBreadcrumbsForCategory($breadcrumbTrail, $urlGenerator, $parent);
        }
    }

    /**
     * Generates a single breadcrumb for a ContentObjectPublicationCategory
     *
     * @param $breadcrumbTrail
     * @param Application $urlGenerator
     * @param \Chamilo\Application\Weblcms\Storage\DataClass\ContentObjectPublicationCategory $contentObjectPublicationCategory
     */
    protected function generateBreadcrumbForCategory(
        BreadcrumbTrail $breadcrumbTrail, Application $urlGenerator,
        ContentObjectPublicationCategory $contentObjectPublicationCategory
    )
    {
        $breadcrumbTrail->add(
            new Breadcrumb(
                $urlGenerator->get_url(
                    [
                        \Chamilo\Application\Weblcms\Manager::PARAM_CATEGORY => $contentObjectPublicationCategory->getId(),
                        \Chamilo\Application\Weblcms\Tool\Manager::PARAM_ACTION => \Chamilo\Application\Weblcms\Tool\Manager::ACTION_BROWSE
                    ],
                    [
                        \Chamilo\Application\Weblcms\Manager::PARAM_PUBLICATION
                    ]
                ), $contentObjectPublicationCategory->get_name()
            )
        );
    }
}


text:
{{ heroContext.source }}

{{ heroContext.headline }}

{{ heroContext.snippet }}


text:
namespace {

// This enum is used in UMA histograms and should never be re-ordered.
enum FileVerificationResult {
  FILE_VERIFICATION_SUCCESS,
  FILE_VERIFICATION_FILE_NOT_FOUND,
  FILE_VERIFICATION_INTERNAL_ERROR,
  FILE_VERIFICATION_FAILED_UNKNOWN,
  FILE_VERIFICATION_FAILED_SAMEBASE,
  FILE_VERIFICATION_FAILED_SAMEDIR,
  FILE_VERIFICATION_SUCCESS_REDIRECT,
  FILE_VERIFICATION_FAILED_SAMEBASE_REDIRECT,
  FILE_VERIFICATION_FAILED_SAMEDIR_REDIRECT,
  NUM_FILE_VERIFICATION_RESULTS
};

// Returns a FileVerificationResult based on the state of |file| on disk.
FileVerificationResult VerifyFileAtPath(const base::FilePath& file) {
  FileVerificationResult file_verification_result =
      FILE_VERIFICATION_FAILED_UNKNOWN;
  base::FilePath normalized_path;
  int redirect_count_before = ::GetRedirectCount();
  if (!base::NormalizeFilePath(file, &normalized_path)) {
    if (::GetLastError() == ERROR_FILE_NOT_FOUND)
      file_verification_result = FILE_VERIFICATION_FILE_NOT_FOUND;
    else
      file_verification_result = FILE_VERIFICATION_INTERNAL_ERROR;
  } else {
    internal::PathComparisonReason path_comparison_reason =
        internal::ComparePathsIgnoreCase(file, normalized_path);
    // GetRedirectCount() tracks the number of CreateFile() calls that were
    // redirected. If it has increased then the CreateFile() call made by
    // base::NormalizeFilePath() was redirected.
    bool was_redirected = ::GetRedirectCount() > redirect_count_before;
    switch (path_comparison_reason) {
      case internal::PATH_COMPARISON_EQUAL:
        file_verification_result = was_redirected ?
            FILE_VERIFICATION_SUCCESS_REDIRECT : FILE_VERIFICATION_SUCCESS;
        break;
      case internal::PATH_COMPARISON_FAILED_SAMEBASE:
        file_verification_result = was_redirected ?
            FILE_VERIFICATION_FAILED_SAMEBASE_REDIRECT :
            FILE_VERIFICATION_FAILED_SAMEBASE;
        break;
      case internal::PATH_COMPARISON_FAILED_SAMEDIR:
        file_verification_result = was_redirected ?
            FILE_VERIFICATION_FAILED_SAMEDIR_REDIRECT :
            FILE_VERIFICATION_FAILED_SAMEDIR;
        break;
    }
  }
  return file_verification_result;
}

}  // namespace

namespace internal {

PathComparisonReason ComparePathsIgnoreCase(const base::FilePath& path1,
                                            const base::FilePath& path2) {
  PathComparisonReason reason = PATH_COMPARISON_FAILED_UNKNOWN;

  if (base::FilePath::CompareEqualIgnoreCase(path1.value(), path2.value())) {
    reason = PATH_COMPARISON_EQUAL;
  } else if (base::FilePath::CompareEqualIgnoreCase(path1.BaseName().value(),
                                                    path2.BaseName().value())) {
    reason = PATH_COMPARISON_FAILED_SAMEBASE;
  } else if (base::FilePath::CompareEqualIgnoreCase(path1.DirName().value(),
                                                    path2.DirName().value())) {
    reason = PATH_COMPARISON_FAILED_SAMEDIR;
  }

  return reason;
}

}  // namespace internal

void VerifyPreferencesFile(const base::FilePath& pref_file_path) {
  FileVerificationResult file_verification_result =
      VerifyFileAtPath(pref_file_path);
  UMA_HISTOGRAM_ENUMERATION("Stability.FileAtPath.Preferences",
                            file_verification_result,
                            NUM_FILE_VERIFICATION_RESULTS);
}


text:
''' unit test for Ansible module: na_elementsw_initiators.py '''

from __future__ import print_function
import json
import pytest

from units.compat import unittest
from units.compat.mock import patch
from ansible.module_utils import basic
from ansible.module_utils._text import to_bytes
import ansible.module_utils.netapp as netapp_utils

if not netapp_utils.has_sf_sdk():
    pytestmark = pytest.mark.skip('skipping as missing required SolidFire Python SDK')

from ansible.modules.storage.netapp.na_elementsw_initiators \
    import ElementSWInitiators as my_module  # module under test

def set_module_args(args):
    """prepare arguments so that they will be picked up during module creation"""
    args = json.dumps({'ANSIBLE_MODULE_ARGS': args})
    basic._ANSIBLE_ARGS = to_bytes(args)  # pylint: disable=protected-access

class AnsibleExitJson(Exception):
    """Exception class to be raised by module.exit_json and caught by the test case"""
    pass

class AnsibleFailJson(Exception):
    """Exception class to be raised by module.fail_json and caught by the test case"""
    pass

def exit_json(*args, **kwargs):  # pylint: disable=unused-argument
    """function to patch over exit_json; package return data into an exception"""
    if 'changed' not in kwargs:
        kwargs['changed'] = False
    raise AnsibleExitJson(kwargs)

def fail_json(*args, **kwargs):  # pylint: disable=unused-argument
    """function to patch over fail_json; package return data into an exception"""
    kwargs['failed'] = True
    raise AnsibleFailJson(kwargs)

class MockSFConnection(object):
    ''' mock connection to ElementSW host '''

    class Bunch(object):  # pylint: disable=too-few-public-methods
        ''' create object with arbitrary attributes '''
        def __init__(self, **kw):
            ''' called with (k1=v1, k2=v2), creates obj.k1, obj.k2 with values v1, v2 '''
            setattr(self, '__dict__', kw)

    class Initiator(object):
        def __init__(self, entries):
            self.__dict__.update(entries)

    def list_initiators(self):
        ''' build initiator Obj '''
        all_initiators = {
            "initiators": [{
                "initiator_name": "a",
                "initiator_id": 13,
                "alias": "a2",
                "attributes": {"key": "value"}
            }]
        }
        return json.loads(json.dumps(all_initiators), object_hook=self.Initiator)

    def create_initiators(self, *args, **kwargs):  # pylint: disable=unused-argument
        ''' mock method '''
        pass

    def delete_initiators(self, *args, **kwargs):  # pylint: disable=unused-argument
        ''' mock method '''
        pass

    def modify_initiators(self, *args, **kwargs):  # pylint: disable=unused-argument
        ''' mock method '''
        pass

class TestMyModule(unittest.TestCase):
    ''' a group of related Unit Tests '''

    def setUp(self):
        self.mock_module_helper = patch.multiple(basic.AnsibleModule,
                                                 exit_json=exit_json,
                                                 fail_json=fail_json)
        self.mock_module_helper.start()
        self.addCleanup(self.mock_module_helper.stop)

    def set_default_args(self):
        return dict({
            'hostname': '10.253.168.129',
            'username': 'namburu',
            'password': 'SFlab1234',
        })

    @patch('ansible.module_utils.netapp.create_sf_connection')
    def test_module_fail_when_required_args_missing(self, mock_create_sf_connection):
        ''' required arguments are reported as errors '''
        with pytest.raises(AnsibleFailJson) as exc:
            set_module_args({})
            my_module()
        print('Info: %s' % exc.value.args[0]['msg'])

    @patch('ansible.module_utils.netapp.create_sf_connection')
    def test_create_initiators(self, mock_create_sf_connection):
        ''' test if create initiator is called '''
        module_args = {}
        module_args.update(self.set_default_args())
        initiator_dict = {
            "state": "present",
            "initiators": [{
                "name": "newinitiator1",
                "alias": "newinitiator1alias",
                "attributes": {"key1": "value1"}
            }]
        }
        module_args.update(initiator_dict)
        set_module_args(module_args)
        mock_create_sf_connection.return_value = MockSFConnection()
        my_obj = my_module()
        with pytest.raises(AnsibleExitJson) as exc:
            my_obj.apply()
        print('Info: test_create_initiators: %s' % repr(exc.value))
        assert exc.value.args[0]['changed']

    @patch('ansible.module_utils.netapp.create_sf_connection')
    def test_delete_initiators(self, mock_create_sf_connection):
        ''' test if delete initiator is called '''
        module_args = {}
        module_args.update(self.set_default_args())
        initiator_dict = {
            "state": "absent",
            "initiators": [{
                "name": "a"
            }]
        }
        module_args.update(initiator_dict)
        set_module_args(module_args)
        mock_create_sf_connection.return_value = MockSFConnection()
        my_obj = my_module()
        with pytest.raises(AnsibleExitJson) as exc:
            my_obj.apply()
        print('Info: test_delete_initiators: %s' % repr(exc.value))
        assert exc.value.args[0]['changed']

    @patch('ansible.module_utils.netapp.create_sf_connection')
    def test_modify_initiators(self, mock_create_sf_connection):
        ''' test if modify initiator is called '''
        module_args = {}
        module_args.update(self.set_default_args())
        initiator_dict = {
            "state": "present",
            "initiators": [{
                "initiator_name": "a",
                "alias": "a3",
                "attributes": {"key": "value"}
            }]
        }
        module_args.update(initiator_dict)
        set_module_args(module_args)
        mock_create_sf_connection.return_value = MockSFConnection()
        my_obj = my_module()
        with pytest.raises(AnsibleExitJson) as exc:
            my_obj.apply()
        print('Info: test_modify_initiators: %s' % repr(exc.value))
        assert exc.value.args[0]['changed']


text:
<bill session="115" type="sr" number="119" updated="2017-06-19T21:45:25Z">
  <state datetime="2017-04-06">REFERRED</state>
  <status>
    <introduced datetime="2017-04-06"/>
  </status>
  <introduced datetime="2017-04-06"/>
  <titles>
    <title type="short" as="introduced">Congressional Oversight to Start Taxpayer Savings Resolution</title>
    <title type="short" as="introduced">Congressional Oversight to Start Taxpayer Savings Resolution</title>
    <title type="short" as="introduced">COST Savings Resolution</title>
    <title type="short" as="introduced">COST Savings Resolution</title>
    <title type="official" as="introduced">A resolution requiring authorizing committees to hold annual hearings on Government Accountability Office investigative reports on the identification, consolidation, and elimination of duplicative Government programs.</title>
    <title type="display">COST Savings Resolution</title>
  </titles>
  <sponsor bioguide_id="G000562"/>
  <cosponsors>
    <cosponsor bioguide_id="P000595" joined="2017-04-06"/>
  </cosponsors>
  <actions>
    <action datetime="2017-04-06">
      <text>Introduced in Senate</text>
    </action>
    <action datetime="2017-04-06" state="REFERRED">
      <text>Referred to the Committee on Homeland Security and Governmental Affairs.</text>
      <reference ref="CR S2430" label="text of measure as introduced"/>
    </action>
  </actions>
  <committees>
    <committee subcommittee="" code="SSGA" name="Senate Homeland Security and Governmental Affairs" activity="Referral"/>
  </committees>
  <relatedbills/>
  <subjects>
    <term name="Congress"/>
    <term name="Congressional committees"/>
    <term name="Congressional oversight"/>
    <term name="Executive agency funding and structure"/>
    <term name="Government studies and investigations"/>
    <term name="Legislative rules and procedure"/>
    <term name="Senate"/>
  </subjects>
  <amendments/>
  <summary date="2017-04-06T04:00:00Z" status="Introduced in Senate">Congressional Oversight to Start Taxpayer Savings Resolution or the COST Savings Resolution

 Requires each standing committee of the Senate (except the Committee on Appropriations) with jurisdiction, after the Government Accountability Office (GAO) reports annually to Congress on federal programs, agencies, offices, and initiatives with duplicative goals and activities, to conduct hearings on the report's recommendations for consolidation and elimination of the program, agency, office, or initiative.

Requires each standing committee of the Senate (except the Committee on Appropriations) with jurisdiction over any agency or program area on a High Risk List published by the GAO to conduct hearings on the vulnerabilities to fraud, waste, abuse, and mismanagement, or need for transformation, of the agency or program area.

Authorizes committees to hold joint hearings for any program, agency, office, initiative, or program area over which more than one standing committee has jurisdiction.</summary>
  <committee-reports/>
</bill>


text:
package com.digits.sdk.android;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;

import io.fabric.sdk.android.services.concurrency.internal.RetryThreadPoolExecutor;

import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;

import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;

public class ContactsUploadServiceTests extends DigitsAndroidTestCase {
    private Cursor cursor;
    private ContactsHelper helper;
    private RetryThreadPoolExecutor executor;
    private ContactsClient contactsClient;
    private ContactsPreferenceManager perfManager;
    private ArrayList<String> cradList;
    private StubContractsService service;

    @Override
    public void setUp() throws Exception {
        super.setUp();

        executor = mock(RetryThreadPoolExecutor.class);
        perfManager = mock(MockContactsPreferenceManager.class);
        contactsClient = mock(StubContactsClient.class);
        cursor = ContactsHelperTests.createCursor();
        cradList = ContactsHelperTests.createCardList();

        helper = mock(StubContactsHelper.class);
        when(helper.getContactsCursor()).thenReturn(cursor);
        when(helper.createContactList(cursor)).thenReturn(cradList);

        service = new StubContractsService(contactsClient, helper, perfManager, executor);
    }

    public void testOnHandleIntent() throws Exception {
        when(executor.awaitTermination(anyLong(), any(TimeUnit.class))).thenReturn(true);
        doAnswer(new Answer() {
            @Override
            public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
                ((Runnable) invocationOnMock.getArguments()[0]).run();
                return null;
            }
        }).when(executor).scheduleWithRetry(any(Runnable.class));

        service.onHandleIntent(null);

        verify(helper).getContactsCursor();
        verify(helper).createContactList(cursor);
        verify(executor).scheduleWithRetry(any(Runnable.class));
        verify(executor).shutdown();
        verify(executor).awaitTermination(anyLong(), any(TimeUnit.class));

        assertTrue(service.sendBroadcastCalled);
        assertEquals(ContactsUploadService.UPLOAD_COMPLETE, service.broadcastIntent.getAction());

        verify(perfManager).setContactImportPermissionGranted();
        verify(perfManager).setContactsUploaded(cradList.size());
        verify(perfManager).setContactsReadTimestamp(anyLong());

        final ContactsUploadResult result = service.broadcastIntent
                .getParcelableExtra(ContactsUploadService.UPLOAD_COMPLETE_EXTRA);
        assertEquals(cradList.size(), result.successCount);
        assertEquals(cradList.size(), result.totalCount);
    }

    public void testOnHandleIntent_uploadTimeout() throws Exception {
        when(executor.awaitTermination(anyLong(), any(TimeUnit.class))).thenReturn(false);

        service.onHandleIntent(null);

        verify(helper).getContactsCursor();
        verify(helper).createContactList(cursor);
        verify(executor).scheduleWithRetry(any(Runnable.class));
        verify(executor).shutdown();
        verify(executor).awaitTermination(anyLong(), any(TimeUnit.class));
        verify(executor).shutdownNow();

        assertTrue(service.sendBroadcastCalled);
        assertEquals(ContactsUploadService.UPLOAD_FAILED, service.broadcastIntent.getAction());

        verify(perfManager).setContactImportPermissionGranted();
        verifyNoMoreInteractions(perfManager);
    }

    public void testGetNumberOfPages() {
        assertEquals(1, service.getNumberOfPages(100));
        assertEquals(1, service.getNumberOfPages(50));
        assertEquals(2, service.getNumberOfPages(101));
        assertEquals(2, service.getNumberOfPages(199));
    }

    public void testSendFailureBroadcast() {
        service.sendFailureBroadcast();

        assertTrue(service.sendBroadcastCalled);
        assertEquals(ContactsUploadService.UPLOAD_FAILED, service.broadcastIntent.getAction());
    }

    public void testSendSuccessBroadcast() {
        service.sendSuccessBroadcast(new ContactsUploadResult(1, 1));

        assertTrue(service.sendBroadcastCalled);
        assertEquals(ContactsUploadService.UPLOAD_COMPLETE, service.broadcastIntent.getAction());
        final ContactsUploadResult result = service.broadcastIntent
                .getParcelableExtra(ContactsUploadService.UPLOAD_COMPLETE_EXTRA);
        assertEquals(1, result.successCount);
        assertEquals(1, result.totalCount);
    }

    public class StubContactsHelper extends ContactsHelper {

        public StubContactsHelper(Context context) {
            super(context);
        }
    }

    public class StubContractsService extends ContactsUploadService {
        boolean sendBroadcastCalled = false;
        Intent broadcastIntent;

        StubContractsService(ContactsClient contactsClient, ContactsHelper helper,
                ContactsPreferenceManager perfManager, RetryThreadPoolExecutor executor) {
            super(contactsClient, helper, perfManager, executor);
        }

        @Override
        public void sendBroadcast(Intent intent) {
            sendBroadcastCalled = true;
            broadcastIntent = intent;
        }
    }

    public class StubContactsClient extends ContactsClient {
        public UploadResponse uploadContacts(Vcards vcards) {
            return null;
        }
    }
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.trellisldp.rosid.file;

import static java.util.Arrays.asList;
import static java.util.Collections.unmodifiableSet;
import static java.util.Optional.of;
import static org.slf4j.LoggerFactory.getLogger;
import static org.trellisldp.api.RDFUtils.toDataset;
import static org.trellisldp.rosid.common.ResourceData.from;
import static org.trellisldp.rosid.file.Constants.RESOURCE_JOURNAL;
import static org.trellisldp.rosid.file.RDFPatch.asStream;
import static org.trellisldp.rosid.file.RDFPatch.asTimeMap;

import java.io.File;
import java.time.Instant;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Stream;

import org.apache.commons.rdf.api.Dataset;
import org.apache.commons.rdf.api.IRI;
import org.apache.commons.rdf.api.Quad;
import org.slf4j.Logger;

import org.trellisldp.api.Resource;
import org.trellisldp.api.RuntimeRepositoryException;
import org.trellisldp.api.VersionRange;
import org.trellisldp.rosid.common.ResourceData;
import org.trellisldp.vocabulary.LDP;
import org.trellisldp.vocabulary.OA;
import org.trellisldp.vocabulary.RDF;
import org.trellisldp.vocabulary.Trellis;

/**
 * An object that mediates access to the resource version files.
 *
 * @author acoburn
 */
public class VersionedResource extends AbstractFileResource {

    private static final Logger LOGGER = getLogger(VersionedResource.class);

    private static final Set<IRI> nonContainers = unmodifiableSet(
            new HashSet<>(asList(LDP.NonRDFSource, LDP.RDFSource)));
    private static final Set<IRI> containerGraphs = unmodifiableSet(
            new HashSet<>(asList(LDP.PreferContainment, LDP.PreferMembership)));

    private static Predicate<Quad> filterContainmentMembership(final IRI interactionModel) {
        return quad -> !nonContainers.contains(interactionModel) || !quad.getGraphName()
            .filter(containerGraphs::contains).isPresent();
    }

    /* User-controllable properties that become part of the core resource data */
    private static final Set<IRI> specialUserProperties = unmodifiableSet(new HashSet<>(
                asList(LDP.inbox, LDP.membershipResource, LDP.hasMemberRelation, LDP.isMemberOfRelation,
                    LDP.insertedContentRelation, OA.annotationService, RDF.type)));

    private static final Predicate<Quad> isAclTriple = quad ->
        quad.getGraphName().filter(Trellis.PreferAccessControl::equals).isPresent() &&
        RDF.type.equals(quad.getPredicate());

    private static final Predicate<Quad> isServerManagedTriple = quad ->
        quad.getGraphName().filter(Trellis.PreferServerManaged::equals).isPresent();

    private static final Predicate<Quad> isResourceTriple = isServerManagedTriple.or(isAclTriple).or(quad ->
        quad.getGraphName().filter(Trellis.PreferUserManaged::equals).isPresent() &&
        specialUserProperties.contains(quad.getPredicate()));

    private final Instant time;

    /**
     * Write a stream of added/deleted quads to a resource
     * @param directory the directory
     * @param delete the quads to delete
     * @param add the quads to add
     * @param time the time
     * @return true if the operation succeeded; false otherwise
     */
    public static Boolean write(final File directory, final Stream<? extends Quad> delete,
            final Stream<? extends Quad> add, final Instant time) {
        return RDFPatch.write(new File(directory, RESOURCE_JOURNAL), delete, add, time);
    }

    /**
     * Find the resource at a particular point in time
     * @param directory the directory
     * @param identifier the identifier
     * @param time the time
     * @return the resource, if it exists at the given time
     */
    public static Optional<Resource> find(final File directory, final String identifier, final Instant time) {
        return find(directory, rdf.createIRI(identifier), time);
    }

    /**
     * Find the resource at a particular point in time
     * @param directory the directory
     * @param identifier the identifier
     * @param time the time
     * @return the resource, if it exists at the given time
     */
    public static Optional<Resource> find(final File directory, final IRI identifier, final Instant time) {
        return read(directory, identifier, time).map(data -> new VersionedResource(directory, identifier, data, time));
    }

    /**
     * Read the state of the resource data at a particular point in time
     * @param directory the directory
     * @param identifier the identifier
     * @param time the time
     * @return the resource data, if it exists
     */
    public static Optional<ResourceData> read(final File directory, final String identifier, final Instant time) {
        return read(directory, rdf.createIRI(identifier), time);
    }

    /**
     * Read the state of the resource data at a particular point in time
     * @param directory the directory
     * @param identifier the identifier
     * @param time the time
     * @return the resource data, if it exists
     */
    public static Optional<ResourceData> read(final File directory, final IRI identifier, final Instant time) {
        LOGGER.debug("Reading journal to generate the resource data");
        return of(new File(directory, RESOURCE_JOURNAL)).filter(File::exists).flatMap(file -> {
            final List<Instant> mementos = new ArrayList<>();
            final List<VersionRange> ranges = asTimeMap(file);
            ranges.stream().map(VersionRange::getFrom).findFirst().ifPresent(mementos::add);
            ranges.stream().map(VersionRange::getUntil).forEachOrdered(mementos::add);

            try (final Stream<Quad> stream = asStream(rdf, file, identifier, time)) {
                try (final Dataset dataset = stream.filter(isResourceTriple).collect(toDataset())) {
                    LOGGER.debug("Creating resource: {} at {}", identifier, time);
                    return from(identifier, dataset, mementos);
                } catch (final Exception ex) {
                    throw new RuntimeRepositoryException("Error processing dataset", ex);
                }
            }
        });
    }

    /**
     * Create a File-based versioned resource
     * @param directory the directory
     * @param identifier the resource identifier
     * @param data the resource data
     * @param time the time
     */
    protected VersionedResource(final File directory, final IRI identifier, final ResourceData data,
            final Instant time) {
        super(directory, identifier, data);
        this.time = time;
        LOGGER.debug("Fetching a Versioned Resource for {}", identifier.getIRIString());
    }

    @Override
    public Boolean isMemento() {
        return true;
    }

    @Override
    public Stream<Quad> stream() {
        LOGGER.debug("Streaming versioned resource data");
        return of(new File(directory, RESOURCE_JOURNAL)).filter(File::exists)
            .map(file -> asStream(rdf, file, identifier, time)).orElseGet(Stream::empty)
            .filter(filterContainmentMembership(getInteractionModel()));
    }
}


text:
import unittest

loader = unittest.TestLoader()
tests  = loader.discover('.')

with open('./log/make.log', 'wb') as log:
    testRunner = unittest.TextTestRunner(stream = log, verbosity = 2)
    testRunner.run(tests)

with open('./log/make.log', 'rU') as log:
    print '\n=== Test results ' + '='*53
    print log.read()


text:
<!doctype html>

		<meta charset="utf-8">

		<title>reveal.js - template for presentations</title>

		<meta name="description" content="Talk title">
		<meta name="author" content="Alina Mackenzie">

		<meta name="apple-mobile-web-app-capable" content="yes" />
		<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />

		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, minimal-ui">

		<link rel="stylesheet" href="css/reveal.css">
    <link rel="stylesheet" href="css/theme/black.css" id="theme">
		<link rel="stylesheet" href="custom/style.css" id="theme">

    <link rel="stylesheet" href="custom/font-awesome-4.4.0/css/font-awesome.min.css">

		<link rel="stylesheet" href="lib/css/zenburn.css">

#drupal

            Business Applications of Mentoring Lessions
             /

            YesCT


text:
<!DOCTYPE html>

	<meta charset="utf-8">

	<title>Class Att\M2X\MQTT\ResourceCollection</title>

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

		Overview

Namespaces

						Att

						M2X

						MQTT

						Error

						Net

						Packet

						Test

Classes

Command

CommandCollection

Device

Distribution

MQTTClient

MQTTResponse

Resource

ResourceCollection

Stream

	<form id="search">
		<input type="hidden" name="cx" value="">
		<input type="hidden" name="ie" value="UTF-8">
		<input type="text" name="q" class="text" placeholder="Search">
	</form>

				Overview

				Namespace

Class

Class ResourceCollection

Att\M2X\MQTT\ResourceCollection
			 implements
Iterator,

Countable

Direct known subclasses

			Att\M2X\MQTT\CommandCollection

		Abstract

		Namespace: Att\M2X\MQTT

			Located at ResourceCollection.php

Methods summary

			 public

		#
		__construct( Att\M2X\MQTT\MQTTClient <var>$client</var>,  <var>$params</var> = array() )

Resource collection constructor

Resource collection constructor

Parameters

<var>$client</var>

<var>$params</var>

			 public

		#
		fetch(  <var>$page</var> = 1 )

			 protected

		#
		setResource( integer <var>$i</var>, array <var>$data</var> )

Initialize and add a resource to the collection

Initialize and add a resource to the collection

Parameters

<var>$i</var>

<var>$data</var>

			 protected

		#
		path( )

Return the API path for the query

Return the API path for the query

			 public

			integer

		#
		count( )

Number of resources in the dataset

Number of resources in the dataset

Returns

					integer

Implementation of

Countable::count()

			 public

		#
		rewind( )

this method takes the pointer back to the beginning
of the dataset to restart the iteration

this method takes the pointer back to the beginning
of the dataset to restart the iteration

Implementation of

Iterator::rewind()

			 public

		#
		current( )

This method returns the resource at the current
position in the dataset.

This method returns the resource at the current
position in the dataset.

Implementation of

Iterator::current()

			 public

			integer

		#
		key( )

Returns the current value of the pointer

Returns the current value of the pointer

Returns

					integer

Implementation of

Iterator::key()

			 public

		#
		next( )

Moves the pointer to the next resource in the dataset

Moves the pointer to the next resource in the dataset

Implementation of

Iterator::next()

			 public

			integer

		#
		page( )

Returns the current page number

Returns the current page number

Returns

					integer

			 public

			boolean

		#
		valid( )

Returns a boolean indicating if there is a resource
at the current position in the dataset

Returns a boolean indicating if there is a resource
at the current position in the dataset

Returns

					boolean

Implementation of

Iterator::valid()

			 protected

		#
		preloadPage( )

Properties summary

			protected
			array

				<var>$resources</var>

Holds the instances of the resources

Holds the instances of the resources

				#
				array()

			protected
			M2X

				<var>$client</var>

Holds the client instance

Holds the client instance

				#
				null

			protected
			array

				<var>$params</var>

Parameters used in the query

Parameters used in the query

				#
				array()

			protected
			integer

				<var>$total</var>

Total amount of resources

Total amount of resources

				#
				null

			protected
			integer

				<var>$pages</var>

Total amount of pages

Total amount of pages

				#
				null

			protected
			integer

				<var>$currentPage</var>

The current page in the result set

The current page in the result set

				#
				1

			protected
			integer

				<var>$limit</var>

Number of resources to fetch per page

Number of resources to fetch per page

				#
				null

			protected
			integer

				<var>$position</var>

Current position in the iterator

Current position in the iterator

				#
				0

			protected
			boolean

				<var>$paginate</var>

Boolean flag to define if the resource collection
is paginated or not.

Boolean flag to define if the resource collection
is paginated or not.

				#
				true

		 API documentation generated by ApiGen


text:
<!DOCTYPE html>

<TITLE>Manpage of GStreamer</TITLE>
<meta charset="utf-8">
<link rel="stylesheet" href="/css/main.css" type="text/css">

linux manpages

{"type":"documentation"}

GStreamer

Section: User Commands  (1)
Updated: May 2003
Index
Return to Main Contents

NAME

gst-typefind - print MIME type of file

SYNOPSIS

gst-typefind <file>

DESCRIPTION

gst-typefind uses the GStreamer type finding system to
determine the relevant GStreamer plugin to parse or decode file,
and the corresponding MIME type.

OPTIONS

gst-typefind accepts the following options:

--help

Print help synopsis and available FLAGS

--gst-info-mask=FLAGS

GStreamer info flags to set (list with --help)

--gst-debug-mask=FLAGS

GStreamer debugging flags to set (list with --help)

--gst-mask=FLAGS

GStreamer info and debugging flags to set (list with --help)

--gst-plugin-spew

GStreamer info flags to set
Enable printout of errors while loading GStreamer plugins

--gst-plugin-path=PATH

Add directories separated with ':' to the plugin search path

SEE ALSO

gst-feedback(1),

gst-inspect(1),

gst-launch(1)

AUTHOR

The GStreamer team at http://gstreamer.freedesktop.org/

Index

NAME

SYNOPSIS

DESCRIPTION

OPTIONS

SEE ALSO

AUTHOR

This document was created by
man2html,
using the manual pages.

Time: 05:29:04 GMT, December 24, 2015


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Doubly-Linked Lists</title>
<meta name="generator" content="DocBook XSL Stylesheets V1.72.0">
<link rel="start" href="index.html" title="GLib Reference Manual">
<link rel="up" href="glib-data-types.html" title="GLib Data Types">
<link rel="prev" href="glib-Memory-Chunks.html" title="Memory Chunks">
<link rel="next" href="glib-Singly-Linked-Lists.html" title="Singly-Linked Lists">
<meta name="generator" content="GTK-Doc V1.7 (XML mode)">
<link rel="stylesheet" href="style.css" type="text/css">
<link rel="chapter" href="glib.html" title="GLib Overview">
<link rel="chapter" href="glib-fundamentals.html" title="GLib Fundamentals">
<link rel="chapter" href="glib-core.html" title="GLib Core Application Support">
<link rel="chapter" href="glib-utilities.html" title="GLib Utilities">
<link rel="chapter" href="glib-data-types.html" title="GLib Data Types">
<link rel="chapter" href="tools.html" title="GLib Tools">
<link rel="index" href="ix01.html" title="Index">
<link rel="index" href="ix02.html" title="Index of deprecated symbols">
<link rel="index" href="ix03.html" title="Index of new symbols in 2.2">
<link rel="index" href="ix04.html" title="Index of new symbols in 2.4">
<link rel="index" href="ix05.html" title="Index of new symbols in 2.6">
<link rel="index" href="ix06.html" title="Index of new symbols in 2.8">
<link rel="index" href="ix07.html" title="Index of new symbols in 2.10">
<link rel="index" href="ix08.html" title="Index of new symbols in 2.12">

GLib Reference Manual

<nobr>Top
                   |
                  Description</nobr>

Doubly-Linked Lists

Doubly-Linked Lists — linked lists containing integer values or pointers to data, with the ability
to iterate over the list in both directions.

Synopsis

#include <glib.h>

                    GList;

GList*              g_list_append                       (GList *list,
                                                         gpointer data);
GList*              g_list_prepend                      (GList *list,
                                                         gpointer data);
GList*              g_list_insert                       (GList *list,
                                                         gpointer data,
                                                         gint position);
GList*              g_list_insert_before                (GList *list,
                                                         GList *sibling,
                                                         gpointer data);
GList*              g_list_insert_sorted                (GList *list,
                                                         gpointer data,
                                                         GCompareFunc func);
GList*              g_list_remove                       (GList *list,
                                                         gconstpointer data);
GList*              g_list_remove_link                  (GList *list,
                                                         GList *llink);
GList*              g_list_delete_link                  (GList *list,
                                                         GList *link_);
GList*              g_list_remove_all                   (GList *list,
                                                         gconstpointer data);
void                g_list_free                         (GList *list);

GList*              g_list_alloc                        (void);
void                g_list_free_1                       (GList *list);
#define             g_list_free1

guint               g_list_length                       (GList *list);
GList*              g_list_copy                         (GList *list);
GList*              g_list_reverse                      (GList *list);
GList*              g_list_sort                         (GList *list,
                                                         GCompareFunc compare_func);
gint                (*GCompareFunc)                     (gconstpointer a,
                                                         gconstpointer b);
GList*              g_list_insert_sorted_with_data      (GList *list,
                                                         gpointer data,
                                                         GCompareDataFunc func,
                                                         gpointer user_data);
GList*              g_list_sort_with_data               (GList *list,
                                                         GCompareDataFunc compare_func,
                                                         gpointer user_data);
gint                (*GCompareDataFunc)                 (gconstpointer a,
                                                         gconstpointer b,
                                                         gpointer user_data);
GList*              g_list_concat                       (GList *list1,
                                                         GList *list2);
void                g_list_foreach                      (GList *list,
                                                         GFunc func,
                                                         gpointer user_data);
void                (*GFunc)                            (gpointer data,
                                                         gpointer user_data);

GList*              g_list_first                        (GList *list);
GList*              g_list_last                         (GList *list);
#define             g_list_previous                     (list)
#define             g_list_next                         (list)
GList*              g_list_nth                          (GList *list,
                                                         guint n);
gpointer            g_list_nth_data                     (GList *list,
                                                         guint n);
GList*              g_list_nth_prev                     (GList *list,
                                                         guint n);

GList*              g_list_find                         (GList *list,
                                                         gconstpointer data);
GList*              g_list_find_custom                  (GList *list,
                                                         gconstpointer data,
                                                         GCompareFunc func);
gint                g_list_position                     (GList *list,
                                                         GList *llink);
gint                g_list_index                        (GList *list,
                                                         gconstpointer data);

void                g_list_push_allocator               (gpointer allocator);
void                g_list_pop_allocator                (void);

Description

The GList structure and its associated functions provide a standard
doubly-linked list data structure.

Each element in the list contains a piece of data, together with pointers
which link to the previous and next elements in the list.
Using these pointers it is possible to move through the list in both
directions (unlike the
Singly-Linked Lists
which only allows movement through the list in the forward direction).

The data contained in each element can be either integer values, by using one
of the
Type Conversion Macros,
or simply pointers to any type of data.

List elements are allocated from the slice
allocator, which is more efficient than allocating elements
individually.

Note that most of the GList functions expect to be passed a pointer to
the first element in the list. The functions which insert elements return
the new start of the list, which may have changed.

There is no function to create a GList. NULL is considered to be the empty
list so you simply set a GList* to NULL.

To add elements, use g_list_append(), g_list_prepend(), g_list_insert()
and g_list_insert_sorted().

To remove elements, use g_list_remove().

To find elements in the list use g_list_first(), g_list_last(), g_list_next(),
g_list_previous(), g_list_nth(), g_list_nth_data(), g_list_find() and
g_list_find_custom().

To find the index of an element use g_list_position() and g_list_index().

To call a function for each element in the list use g_list_foreach().

To free the entire list, use g_list_free().

Details

GList

typedef struct {
  gpointer data;
  GList *next;
  GList *prev;
} GList;

The GList struct is used for each element in a doubly-linked list.

<col align="left" valign="top">

gpointer data;
holds the element's data, which can be a pointer to any kind of data,
  or any integer value using the
  Type Conversion Macros.

GList *next;
contains the link to the next element in the list.

GList *prev;
contains the link to the previous element in the list.

g_list_append ()

GList*              g_list_append                       (GList *list,
                                                         gpointer data);

Adds a new element on to the end of the list.

Note

The return value is the new start of the list, which may have changed, so
make sure you store the new value.

Note

Note that g_list_append() has to traverse the entire list to find the end,
which is inefficient when adding multiple elements. A common idiom to
avoid the inefficiency is to prepend the elements and reverse the list
when all elements have been added.

  /* Notice that these are initialized to the empty list. */
  GList *list = NULL, *number_list = NULL;

  /* This is a list of strings. */
  list = g_list_append (list, "first");
  list = g_list_append (list, "second");

  /* This is a list of integers. */
  number_list = g_list_append (number_list, GINT_TO_POINTER (27));
  number_list = g_list_append (number_list, GINT_TO_POINTER (14));

<col align="left" valign="top">

list :
a pointer to a GList.

data :
the data for the new element.

Returns :
the new start of the GList.

g_list_prepend ()

GList*              g_list_prepend                      (GList *list,
                                                         gpointer data);

Adds a new element on to the start of the list.

Note

The return value is the new start of the list, which may have changed, so
make sure you store the new value.

  /* Notice that it is initialized to the empty list. */
  GList *list = NULL;
  list = g_list_prepend (list, "last");
  list = g_list_prepend (list, "first");

<col align="left" valign="top">

list :
a pointer to a GList.

data :
the data for the new element.

Returns :
the new start of the GList.

g_list_insert ()

GList*              g_list_insert                       (GList *list,
                                                         gpointer data,
                                                         gint position);

Inserts a new element into the list at the given position.

<col align="left" valign="top">

list :
a pointer to a GList.

data :
the data for the new element.

position :
the position to insert the element. If this is negative, or is
larger than the number of elements in the list, the new element is added on
to the end of the list.

Returns :
the new start of the GList.

g_list_insert_before ()

GList*              g_list_insert_before                (GList *list,
                                                         GList *sibling,
                                                         gpointer data);

Inserts a new element into the list before the given position.

<col align="left" valign="top">

list :
a pointer to a GList.

sibling :
the list element before which the new element is inserted
  or NULL to insert at the end of the list.

data :
the data for the new element.

Returns :
the new start of the GList.

g_list_insert_sorted ()

GList*              g_list_insert_sorted                (GList *list,
                                                         gpointer data,
                                                         GCompareFunc func);

Inserts a new element into the list, using the given comparison function
to determine its position.

<col align="left" valign="top">

list :
a pointer to a GList.

data :
the data for the new element.

func :
the function to compare elements in the list. It should return a
number > 0 if the first parameter comes after the second parameter in
the sort order.

Returns :
the new start of the GList.

g_list_remove ()

GList*              g_list_remove                       (GList *list,
                                                         gconstpointer data);

Removes an element from a GList.
If two elements contain the same data, only the first is removed.
If none of the elements contain the data, the GList is unchanged.

<col align="left" valign="top">

list :
a GList.

data :
the data of the element to remove.

Returns :
the new start of the GList.

g_list_remove_link ()

GList*              g_list_remove_link                  (GList *list,
                                                         GList *llink);

Removes an element from a GList, without freeing the element.
The removed element's prev and next links are set to NULL, so that it becomes a
self-contained list with one element.

<col align="left" valign="top">

list :
a GList.

llink :
an element in the GList.

Returns :
the new start of the GList, without the element.

g_list_delete_link ()

GList*              g_list_delete_link                  (GList *list,
                                                         GList *link_);

Deletes the node link_ from list.

<col align="left" valign="top">

list :
a GList.

link_ :
node to delete from list.

Returns :
the new head of list.

g_list_remove_all ()

GList*              g_list_remove_all                   (GList *list,
                                                         gconstpointer data);

Removes all list nodes with data equal to data. Returns the new
head of the list. Contrast with g_list_remove() which removes only
the first node matching the given data.

<col align="left" valign="top">

list :
a GList.

data :
data to remove.

Returns :
new head of list.

g_list_free ()

void                g_list_free                         (GList *list);

Frees all of the memory used by a GList.
The freed elements are returned to the slice allocator.

Note

If list elements contain dynamically-allocated memory, they should be freed
first.

<col align="left" valign="top">

list :
a GList.

g_list_alloc ()

GList*              g_list_alloc                        (void);

Allocates space for one GList element.
It is called by g_list_append(), g_list_prepend(), g_list_insert() and
g_list_insert_sorted() and so is rarely used on its own.

<col align="left" valign="top">

Returns :
a pointer to the newly-allocated GList element.

g_list_free_1 ()

void                g_list_free_1                       (GList *list);

Frees one GList element.
It is usually used after g_list_remove_link().

<col align="left" valign="top">

list :
a GList element.

g_list_free1

#define             g_list_free1

Another name for g_list_free_1().

g_list_length ()

guint               g_list_length                       (GList *list);

Gets the number of elements in a GList.

<col align="left" valign="top">

list :
a GList.

Returns :
the number of elements in the GList.

g_list_copy ()

GList*              g_list_copy                         (GList *list);

Copies a GList.

Note that this is a "shallow" copy. If the list elements consist of pointers
to data, the pointers are copied but the actual data isn't.

<col align="left" valign="top">

list :
a GList.

Returns :
a copy of list.

g_list_reverse ()

GList*              g_list_reverse                      (GList *list);

Reverses a GList.
It simply switches the next and prev pointers of each element.

<col align="left" valign="top">

list :
a GList.

Returns :
the start of the reversed GList.

g_list_sort ()

GList*              g_list_sort                         (GList *list,
                                                         GCompareFunc compare_func);

Sorts a GList using the given comparison function.

<col align="left" valign="top">

list :
a GList.

compare_func :
the comparison function used to sort the GList.
This function is passed the data from 2 elements of the GList and should
return 0 if they are equal, a negative value if the first element
comes before the second, or a positive value if the first element
comes after the second.

Returns :
the start of the sorted GList.

GCompareFunc ()

gint                (*GCompareFunc)                     (gconstpointer a,
                                                         gconstpointer b);

Specifies the type of a comparison function used to compare two
values.  The function should return a negative integer if the first
value comes before the second, 0 if they are equal, or a positive
integer if the first value comes after the second.

<col align="left" valign="top">

a :
a value.

b :
a value to compare with.

Returns :
negative value if a < b; zero if a = b; positive value
if a > b.

g_list_insert_sorted_with_data ()

GList*              g_list_insert_sorted_with_data      (GList *list,
                                                         gpointer data,
                                                         GCompareDataFunc func,
                                                         gpointer user_data);

Inserts a new element into the list, using the given comparison function
to determine its position.

<col align="left" valign="top">

list :
a pointer to a GList.

data :
the data for the new element.

func :
the function to compare elements in the list. It should return a
number > 0 if the first parameter comes after the second parameter in
the sort order.

user_data :
user data to pass to comparison function.

Returns :
the new start of the GList.
Since 2.10

g_list_sort_with_data ()

GList*              g_list_sort_with_data               (GList *list,
                                                         GCompareDataFunc compare_func,
                                                         gpointer user_data);

Like g_list_sort(), but the comparison function accepts a user data argument.

<col align="left" valign="top">

list :
a GList.

compare_func :
comparison function.

user_data :
user data to pass to comparison function.

Returns :
the new head of list.

GCompareDataFunc ()

gint                (*GCompareDataFunc)                 (gconstpointer a,
                                                         gconstpointer b,
                                                         gpointer user_data);

Specifies the type of a comparison function used to compare two
values.  The function should return a negative integer if the first
value comes before the second, 0 if they are equal, or a positive
integer if the first value comes after the second.

<col align="left" valign="top">

a :
a value.

b :
a value to compare with.

user_data :
user data to pass to comparison function.

Returns :
negative value if a < b; zero if a = b; positive value
if a > b.

g_list_concat ()

GList*              g_list_concat                       (GList *list1,
                                                         GList *list2);

Adds the second GList onto the end of the first GList.
Note that the elements of the second GList are not copied.
They are used directly.

<col align="left" valign="top">

list1 :
a GList.

list2 :
the GList to add to the end of the first GList.

Returns :
the start of the new GList.

g_list_foreach ()

void                g_list_foreach                      (GList *list,
                                                         GFunc func,
                                                         gpointer user_data);

Calls a function for each element of a GList.

<col align="left" valign="top">

list :
a GList.

func :
the function to call with each element's data.

user_data :
user data to pass to the function.

GFunc ()

void                (*GFunc)                            (gpointer data,
                                                         gpointer user_data);

Specifies the type of functions passed to g_list_foreach() and
g_slist_foreach().

<col align="left" valign="top">

data :
the element's data.

user_data :
user data passed to g_list_foreach() or g_slist_foreach().

g_list_first ()

GList*              g_list_first                        (GList *list);

Gets the first element in a GList.

<col align="left" valign="top">

list :
a GList.

Returns :
the first element in a GList, or NULL if the GList has no elements.

g_list_last ()

GList*              g_list_last                         (GList *list);

Gets the last element in a GList.

<col align="left" valign="top">

list :
a GList.

Returns :
the last element in the GList, or NULL if the GList has no
elements.

g_list_previous()

#define             g_list_previous(list)

A convenience macro to gets the previous element in a GList.

<col align="left" valign="top">

list :
an element in a GList.

Returns :
the previous element, or NULL if there are no previous elements.

g_list_next()

#define             g_list_next(list)

A convenience macro to gets the next element in a GList.

<col align="left" valign="top">

list :
an element in a GList.

Returns :
the next element, or NULL if there are no more elements.

g_list_nth ()

GList*              g_list_nth                          (GList *list,
                                                         guint n);

Gets the element at the given position in a GList.

<col align="left" valign="top">

list :
a GList.

n :
the position of the element, counting from 0.

Returns :
the element, or NULL if the position is off the end of the GList.

g_list_nth_data ()

gpointer            g_list_nth_data                     (GList *list,
                                                         guint n);

Gets the data of the element at the given position.

<col align="left" valign="top">

list :
a GList.

n :
the position of the element.

Returns :
the element's data, or NULL if the position is off the end of the
GList.

g_list_nth_prev ()

GList*              g_list_nth_prev                     (GList *list,
                                                         guint n);

Gets the element n places before list.

<col align="left" valign="top">

list :
a GList.

n :
the position of the element, counting from 0.

Returns :
the element, or NULL if the position is off the end of the GList.

g_list_find ()

GList*              g_list_find                         (GList *list,
                                                         gconstpointer data);

Finds the element in a GList which contains the given data.

<col align="left" valign="top">

list :
a GList.

data :
the element data to find.

Returns :
the found GList element, or NULL if it is not found.

g_list_find_custom ()

GList*              g_list_find_custom                  (GList *list,
                                                         gconstpointer data,
                                                         GCompareFunc func);

Finds an element in a GList, using a supplied function to find the desired
element.
It iterates over the list, calling the given function which should return 0
when the desired element is found.
The function takes two gconstpointer arguments, the GList element's data as
the first argument and the given user data.

<col align="left" valign="top">

list :
a GList.

data :
user data passed to the function.

func :
the function to call for each element. It should return 0 when the
desired element is found.

Returns :
the found GList element, or NULL if it is not found.

g_list_position ()

gint                g_list_position                     (GList *list,
                                                         GList *llink);

Gets the position of the given element in the GList (starting from 0).

<col align="left" valign="top">

list :
a GList.

llink :
an element in the GList.

Returns :
the position of the element in the GList, or -1 if the element is
not found.

g_list_index ()

gint                g_list_index                        (GList *list,
                                                         gconstpointer data);

Gets the position of the element containing the given data (starting from 0).

<col align="left" valign="top">

list :
a GList.

data :
the data to find.

Returns :
the index of the element containing the data, or -1 if the data
is not found.

g_list_push_allocator ()

void                g_list_push_allocator               (gpointer allocator);

Warning

g_list_push_allocator has been deprecated since version 2.10 and should not be used in newly-written code. It does nothing, since GList has been
converted to the slice allocator

Sets the allocator to use to allocate GList elements.
Use g_list_pop_allocator() to restore the previous allocator.

Note that this function is not available if GLib has been compiled
with --disable-mem-pools

<col align="left" valign="top">

allocator :
the GAllocator to use when allocating GList elements.

g_list_pop_allocator ()

void                g_list_pop_allocator                (void);

Warning

g_list_pop_allocator has been deprecated since version 2.10 and should not be used in newly-written code. It does nothing, since GList has been
converted to the slice allocator

Restores the previous GAllocator, used when allocating GList elements.

Note that this function is not available if GLib has been compiled
with --disable-mem-pools


text:
package cloudformation

import (
	"encoding/json"
	"errors"
	"fmt"
)

// AWSOpsWorksElasticLoadBalancerAttachment AWS CloudFormation Resource (AWS::OpsWorks::ElasticLoadBalancerAttachment)
// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-elbattachment.html
type AWSOpsWorksElasticLoadBalancerAttachment struct {

	// ElasticLoadBalancerName AWS CloudFormation Property
	// Required: true
	// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-elbattachment.html#cfn-opsworks-elbattachment-elbname
	ElasticLoadBalancerName string `json:"ElasticLoadBalancerName,omitempty"`

	// LayerId AWS CloudFormation Property
	// Required: true
	// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-elbattachment.html#cfn-opsworks-elbattachment-layerid
	LayerId string `json:"LayerId,omitempty"`
}

// AWSCloudFormationType returns the AWS CloudFormation resource type
func (r *AWSOpsWorksElasticLoadBalancerAttachment) AWSCloudFormationType() string {
	return "AWS::OpsWorks::ElasticLoadBalancerAttachment"
}

// MarshalJSON is a custom JSON marshalling hook that embeds this object into
// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'.
func (r *AWSOpsWorksElasticLoadBalancerAttachment) MarshalJSON() ([]byte, error) {
	type Properties AWSOpsWorksElasticLoadBalancerAttachment
	return json.Marshal(&struct {
		Type       string
		Properties Properties
	}{
		Type:       r.AWSCloudFormationType(),
		Properties: (Properties)(*r),
	})
}

// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer
// AWS CloudFormation resource object, and just keeps the 'Properties' field.
func (r *AWSOpsWorksElasticLoadBalancerAttachment) UnmarshalJSON(b []byte) error {
	type Properties AWSOpsWorksElasticLoadBalancerAttachment
	res := &struct {
		Type       string
		Properties *Properties
	}{}
	if err := json.Unmarshal(b, &res); err != nil {
		fmt.Printf("ERROR: %s\n", err)
		return err
	}

	// If the resource has no Properties set, it could be nil
	if res.Properties != nil {
		*r = AWSOpsWorksElasticLoadBalancerAttachment(*res.Properties)
	}

	return nil
}

// GetAllAWSOpsWorksElasticLoadBalancerAttachmentResources retrieves all AWSOpsWorksElasticLoadBalancerAttachment items from an AWS CloudFormation template
func (t *Template) GetAllAWSOpsWorksElasticLoadBalancerAttachmentResources() map[string]AWSOpsWorksElasticLoadBalancerAttachment {
	results := map[string]AWSOpsWorksElasticLoadBalancerAttachment{}
	for name, untyped := range t.Resources {
		switch resource := untyped.(type) {
		case AWSOpsWorksElasticLoadBalancerAttachment:
			// We found a strongly typed resource of the correct type; use it
			results[name] = resource
		case map[string]interface{}:
			// We found an untyped resource (likely from JSON) which *might* be
			// the correct type, but we need to check it's 'Type' field
			if resType, ok := resource["Type"]; ok {
				if resType == "AWS::OpsWorks::ElasticLoadBalancerAttachment" {
					// The resource is correct, unmarshal it into the results
					if b, err := json.Marshal(resource); err == nil {
						var result AWSOpsWorksElasticLoadBalancerAttachment
						if err := json.Unmarshal(b, &result); err == nil {
							results[name] = result
						}
					}
				}
			}
		}
	}
	return results
}

// GetAWSOpsWorksElasticLoadBalancerAttachmentWithName retrieves all AWSOpsWorksElasticLoadBalancerAttachment items from an AWS CloudFormation template
// whose logical ID matches the provided name. Returns an error if not found.
func (t *Template) GetAWSOpsWorksElasticLoadBalancerAttachmentWithName(name string) (AWSOpsWorksElasticLoadBalancerAttachment, error) {
	if untyped, ok := t.Resources[name]; ok {
		switch resource := untyped.(type) {
		case AWSOpsWorksElasticLoadBalancerAttachment:
			// We found a strongly typed resource of the correct type; use it
			return resource, nil
		case map[string]interface{}:
			// We found an untyped resource (likely from JSON) which *might* be
			// the correct type, but we need to check it's 'Type' field
			if resType, ok := resource["Type"]; ok {
				if resType == "AWS::OpsWorks::ElasticLoadBalancerAttachment" {
					// The resource is correct, unmarshal it into the results
					if b, err := json.Marshal(resource); err == nil {
						var result AWSOpsWorksElasticLoadBalancerAttachment
						if err := json.Unmarshal(b, &result); err == nil {
							return result, nil
						}
					}
				}
			}
		}
	}
	return AWSOpsWorksElasticLoadBalancerAttachment{}, errors.New("resource not found")
}


text:
'use strict';
import { NumberComponent } from './Number';
import { components as comps } from './fixtures/index';
import { Harness } from '../../../test/harness';
describe('Number Component', function() {
  it('Should build an number component', function(done) {
    Harness.testCreate(NumberComponent, comps.comp1).then((component) => {
      Harness.testElements(component, 'input[type="number"]', 1);
      done();
    });
  });
});


text:
package com.example.dialogflow;

import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertEquals;

import com.google.cloud.dialogflow.v2beta1.DocumentName;
import com.google.cloud.dialogflow.v2beta1.KnowledgeAnswers;
import com.google.cloud.dialogflow.v2beta1.KnowledgeAnswers.Answer;
import com.google.cloud.dialogflow.v2beta1.KnowledgeBaseName;
import com.google.common.collect.ImmutableList;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

@RunWith(JUnit4.class)
@SuppressWarnings("checkstyle:abbreviationaswordinname")
public class DetectIntentKnowledgeTest {

  private static String PROJECT_ID = System.getenv().get("GOOGLE_CLOUD_PROJECT");
  private static String TEST_KNOWLEDGE_BASE_ID = "MTA4MzE0ODY5NTczMTQzNzU2ODA";
  private static String TEST_DOCUMENT_ID = "MTUwNjk0ODg1NTU4NzkzMDExMg";
  private static String SESSION_ID = UUID.randomUUID().toString();
  private static String LANGUAGE_CODE = "en-US";

  private static List<String> TEXTS =
      ImmutableList.of(
          "How do I sign up?",
          "Is my data redundant?",
          "Where can I find pricing information?",
          "Where is my data stored?",
          "What are my support options?",
          "How can I maximize the availability of my data?");

  @Before
  public void setUp() {
    System.setOut(new PrintStream(new ByteArrayOutputStream()));
  }

  @After
  public void tearDown() {
    System.setOut(null);
  }

  @Test
  public void testDetectIntentKnowledge() throws Exception {
    KnowledgeBaseName knowledgeBaseName =
        KnowledgeBaseName.newBuilder()
            .setProject(PROJECT_ID)
            .setKnowledgeBase(TEST_KNOWLEDGE_BASE_ID)
            .build();

    DocumentName documentName =
        DocumentName.newBuilder()
            .setProject(PROJECT_ID)
            .setKnowledgeBase(TEST_KNOWLEDGE_BASE_ID)
            .setDocument(TEST_DOCUMENT_ID)
            .build();

    Map<String, KnowledgeAnswers> allAnswers =
        DetectIntentKnowledge.detectIntentKnowledge(
            PROJECT_ID, knowledgeBaseName.toString(), SESSION_ID, LANGUAGE_CODE, TEXTS);
    assertEquals(TEXTS.size(), allAnswers.size());
    int answersFound = 0;
    for (String text : TEXTS) {
      KnowledgeAnswers knowledgeAnswers = allAnswers.get(text);
      if (knowledgeAnswers.getAnswersCount() > 0) {
        Answer answer = knowledgeAnswers.getAnswers(0);
        if (text.equals(answer.getFaqQuestion())
            && documentName.toString().equals(answer.getSource())) {
          answersFound++;
        }
      }
    }
    // To make the test less flaky, check that half of the texts got a result.
    assertThat(answersFound).isGreaterThan(TEXTS.size() / 2);
  }
}


text:
<?php
/* @var $this NoticeController */
/* @var $model Notice */
/* @var $form CActiveForm */
?>

<?php $form=$this->beginWidget('CActiveForm', array(
	'action'=>Yii::app()->createUrl($this->route),
	'method'=>'get',
)); ?>

		<?php echo $form->label($model,'title'); ?>

			<?php echo $form->textField($model,'title',array('size'=>60,'maxlength'=>255)); ?>

		<?php echo $form->label($model,'content'); ?>

			<?php echo $form->textField($model,'content',array('size'=>60,'maxlength'=>255)); ?>

		<?php echo CHtml::submitButton('搜索'); ?>

<?php $this->endWidget(); ?>


text:
#pragma once
#include <aws/lambda/Lambda_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace Lambda
{
namespace Model
{

  /**
   *
Specific configuration settings for an Amazon Managed Streaming for Apache
   * Kafka (Amazon MSK) event source.

See Also:
   AWS
   * API Reference

   */
  class AWS_LAMBDA_API AmazonManagedKafkaEventSourceConfig
  {
  public:
    AmazonManagedKafkaEventSourceConfig();
    AmazonManagedKafkaEventSourceConfig(Aws::Utils::Json::JsonView jsonValue);
    AmazonManagedKafkaEventSourceConfig& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
The identifier for the Kafka consumer group to join. The consumer group ID
     * must be unique among all your Kafka event sources. After creating a Kafka event
     * source mapping with the consumer group ID specified, you cannot update this
     * value. For more information, see Customizable
     * consumer group ID.

     */
    inline const Aws::String& GetConsumerGroupId() const{ return m_consumerGroupId; }

    /**
     *
The identifier for the Kafka consumer group to join. The consumer group ID
     * must be unique among all your Kafka event sources. After creating a Kafka event
     * source mapping with the consumer group ID specified, you cannot update this
     * value. For more information, see Customizable
     * consumer group ID.

     */
    inline bool ConsumerGroupIdHasBeenSet() const { return m_consumerGroupIdHasBeenSet; }

    /**
     *
The identifier for the Kafka consumer group to join. The consumer group ID
     * must be unique among all your Kafka event sources. After creating a Kafka event
     * source mapping with the consumer group ID specified, you cannot update this
     * value. For more information, see Customizable
     * consumer group ID.

     */
    inline void SetConsumerGroupId(const Aws::String& value) { m_consumerGroupIdHasBeenSet = true; m_consumerGroupId = value; }

    /**
     *
The identifier for the Kafka consumer group to join. The consumer group ID
     * must be unique among all your Kafka event sources. After creating a Kafka event
     * source mapping with the consumer group ID specified, you cannot update this
     * value. For more information, see Customizable
     * consumer group ID.

     */
    inline void SetConsumerGroupId(Aws::String&& value) { m_consumerGroupIdHasBeenSet = true; m_consumerGroupId = std::move(value); }

    /**
     *
The identifier for the Kafka consumer group to join. The consumer group ID
     * must be unique among all your Kafka event sources. After creating a Kafka event
     * source mapping with the consumer group ID specified, you cannot update this
     * value. For more information, see Customizable
     * consumer group ID.

     */
    inline void SetConsumerGroupId(const char* value) { m_consumerGroupIdHasBeenSet = true; m_consumerGroupId.assign(value); }

    /**
     *
The identifier for the Kafka consumer group to join. The consumer group ID
     * must be unique among all your Kafka event sources. After creating a Kafka event
     * source mapping with the consumer group ID specified, you cannot update this
     * value. For more information, see Customizable
     * consumer group ID.

     */
    inline AmazonManagedKafkaEventSourceConfig& WithConsumerGroupId(const Aws::String& value) { SetConsumerGroupId(value); return *this;}

    /**
     *
The identifier for the Kafka consumer group to join. The consumer group ID
     * must be unique among all your Kafka event sources. After creating a Kafka event
     * source mapping with the consumer group ID specified, you cannot update this
     * value. For more information, see Customizable
     * consumer group ID.

     */
    inline AmazonManagedKafkaEventSourceConfig& WithConsumerGroupId(Aws::String&& value) { SetConsumerGroupId(std::move(value)); return *this;}

    /**
     *
The identifier for the Kafka consumer group to join. The consumer group ID
     * must be unique among all your Kafka event sources. After creating a Kafka event
     * source mapping with the consumer group ID specified, you cannot update this
     * value. For more information, see Customizable
     * consumer group ID.

     */
    inline AmazonManagedKafkaEventSourceConfig& WithConsumerGroupId(const char* value) { SetConsumerGroupId(value); return *this;}

  private:

    Aws::String m_consumerGroupId;
    bool m_consumerGroupIdHasBeenSet = false;
  };

} // namespace Model
} // namespace Lambda
} // namespace Aws


text:
\hypertarget{include_8hh}{}\section{valmiiden\+\_\+toteutus/include/include.hh File Reference}
\label{include_8hh}\index{valmiiden\+\_\+toteutus/include/include.\+hh@{valmiiden\+\_\+toteutus/include/include.\+hh}}

pääohjelman kirjastojen liittämistiedosto

{\ttfamily \#include \char`\"{}../../koordinaatti.\+hh\char`\"{}}\\*
{\ttfamily \#include \char`\"{}../../pelirajapinta.\+hh\char`\"{}}\\*
{\ttfamily \#include \char`\"{}../../nayttorajapinta.\+hh\char`\"{}}\\*
{\ttfamily \#include \char`\"{}../../pelitehdas.\+hh\char`\"{}}\\*
{\ttfamily \#include \char`\"{}../../vaittama.\+hh\char`\"{}}\\*
{\ttfamily \#include \char`\"{}../../alustusvirhe.\+hh\char`\"{}}\\*
{\ttfamily \#include \char`\"{}../../komentovirhe.\+hh\char`\"{}}\\*
{\ttfamily \#include \char`\"{}../../logiikkavirhe.\+hh\char`\"{}}\\*
{\ttfamily \#include \char`\"{}../../toteuttamaton\+\_\+virhe.\+hh\char`\"{}}\\*
{\ttfamily \#include \char`\"{}../../virhe.\+hh\char`\"{}}\\*
{\ttfamily \#include \char`\"{}../../debug.\+hh\char`\"{}}\\*
{\ttfamily \#include \char`\"{}komentotulkki.\+hh\char`\"{}}\\*
{\ttfamily \#include \char`\"{}rakentaja.\+hh\char`\"{}}\\*
{\ttfamily \#include $<$memory$>$}\\*
{\ttfamily \#include $<$iostream$>$}\\*
{\ttfamily \#include $<$string$>$}\\*
{\ttfamily \#include $<$deque$>$}\\*
{\ttfamily \#include $<$cstdlib$>$}\\*

\subsection{Detailed Description}
pääohjelman kirjastojen liittämistiedosto

\begin{DoxyVersion}{Version}

\end{DoxyVersion}
\begin{DoxyParagraph}{Id}
\hyperlink{include_8hh}{include.\+hh} 1802 2011-\/02-\/07 09\+:17\+:58\+Z salone58
\end{DoxyParagraph}

\begin{DoxyAuthor}{Author}
©2011 Eero Salonen \href{mailto:eero.j.salonen@tut.fi}{\tt eero.\+j.\+salonen@tut.\+fi}
\end{DoxyAuthor}


text:
class HaikuApplication : public BApplication
{
public:
   HaikuApplication();
};

#endif


text:
var uuid = require('node-uuid');
// var jsdom = require('jsdom');

// module.exports.setupDom = function setupDom() {
//   global.document = jsdom.jsdom();
//   global.window = document.createWindow();
//   global.navigator = window.navigator;
// };

// module.exports.teardownDom = function teardownDom() {
//   delete global.document;
//   delete global.window;
//   delete global.navigator;
// };

module.exports.makeData = function(length) {
  var _ = require('lodash');
  var initializeState = [];
  var updateIndex = Math.floor(length/2);

  length = length || 25;
  for (var ix = 0; ix < length; ix++) {
    initializeState.push({
      id: uuid.v4(),
      key: _.uniqueId('item'),
      label: 'list item ' + ix
    });
  }
  return initializeState;
};


text:
import Scheduler from "./scheduler.js";
/**
 * @class Speed-based scheduler
 */
export default class Speed extends Scheduler {
    /**
     * @param {object} item anything with "getSpeed" method
     * @param {bool} repeat
     * @param {number} [time=1/item.getSpeed()]
     * @see ROT.Scheduler#add
     */
    add(item, repeat, time) {
        this._queue.add(item, time !== undefined ? time : 1 / item.getSpeed());
        return super.add(item, repeat);
    }
    /**
     * @see ROT.Scheduler#next
     */
    next() {
        if (this._current && this._repeat.indexOf(this._current) != -1) {
            this._queue.add(this._current, 1 / this._current.getSpeed());
        }
        return super.next();
    }
}


text:
<?php

namespace setasign\Fpdi\PdfParser\CrossReference;

use setasign\Fpdi\PdfParser\Type\PdfDictionary;

/**
 * ReaderInterface for cross-reference readers.
 */
interface ReaderInterface
{
    /**
     * Get an offset by an object number.
     *
     * @param int $objectNumber
     * @return int|bool False if the offset was not found.
     */
    public function getOffsetFor($objectNumber);

    /**
     * Get the trailer related to this cross reference.
     *
     * @return PdfDictionary
     */
    public function getTrailer();
}