text:
StackArchive::Application.routes.draw do

  root 'home#root'

  match 'search', to: 'home#home', via: :get
  match 'post', to: 'home#home', via: :get

  match 'dbs', to: "home#grabDBs", via: :get

  match 'post_data', to: 'home#postData', via: :get
  match 'search_data', to: 'home#searchData', via: :get

  match '*path' => redirect('/'), via: :get

end


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">KeepWalking</string>
    <string name="action_settings">Settings</string>
    <string name="title_activity_bounce_scroll_view">BounceScrollViewActivity</string>

    <string name="phone_login">手机登录</string>
    <string name="phone_reg">注册帐号</string>
    <string name="title_activity_pull_to_refresh_list_view">PullToRefreshListViewActivity</string>

    <string name="hello_world">Hello world!</string>
    <string name="select_mode">选择模式</string>
    <string name="mode_single">单选</string>
    <string name="mode_multi">多选</string>
    <string name="max_select_amount">最大选择数量</string>
    <string name="hint_default_amount">默认数量为9</string>
    <string name="enable_camera">是否启用照相机</string>
    <string name="enable">是</string>
    <string name="disable">否</string>
    <string name="go_select">图片选择</string>

    <!-- Strings for WeiXinMainActivity -->
    <string name="weixin">微信</string>
    <string name="action_search">搜索</string>
    <string name="action_add">添加</string>
    <string name="action_scan">扫一扫</string>
    <string name="action_message">信息</string>
    <string name="bar_conversation">微信</string>
    <string name="bar_friend_list">通讯录</string>
    <string name="bar_search">发现</string>
    <string name="bar_me">我</string>

    <string name="share_sdk">Share SDK</string>
    <string name="login_with_wechat">用微信登录</string>
    <string name="login_with_qzone">用QQ空间登录</string>
    <string name="login_with_other_plat">其他帐号登录</string>
    <string name="share_other">分享到</string>
    <string name="share_wechat">微信好友</string>
    <string name="share_wechat_moments">微信朋友圈</string>
    <string name="share_tencent">腾讯好友</string>
    <string name="share_tencent_weibo">腾讯微博</string>
    <string name="share_qzone">QQ空间</string>
    <string name="share_sina_weibo">新浪微博</string>
    <string name="share_completed">分享成功!</string>
    <string name="share_canceled">分享取消!</string>
    <string name="share_failed">分享失败!</string>
    <string name="userid_found">用户信息已存在,正在跳转登录操作…</string>
    <string name="logining">使用%s帐号登录中…</string>
    <string name="auth_cancel">授权操作已取消</string>
    <string name="auth_error">授权操作遇到错误,请阅读Logcat输出</string>
    <string name="auth_complete">授权成功,正在跳转登录操作…</string>
    <string name="if_register_needed">如果您需要注册功能…</string>
    <string name="after_auth">一般来说第三方登录时,第三方平台已经为您完成用户身份校验,您可以放心让用户登录。\n\n但如果您需要判断用户是否为新用户,可以在授权操作完成后,将用户的信息通过字段"HashMap userInfo"携带给login方法。客户端通过"String userId"执行登录请求,如果服务端判定此userId为未注册用户,可以将userInfo发送给注册接口,获取用户在此平台上的昵称、头像等数据,然后执行注册</string>
    <string name="ok">确定</string>
    <string name="pay_tip">提示</string>
    <string name="pay_result_callback_msg" formatted="false">微信支付结果:%s</string>
</resources>

redpajama_set_name: RedPajamaGithub


text:
include(FindPackageHandleStandardArgs)

FIND_PATH( Wt_INCLUDE_DIR NAMES Wt/WObject PATHS ENV PATH PATH_SUFFIXES include wt )

SET( Wt_FIND_COMPONENTS Release Debug )

IF( Wt_INCLUDE_DIR )
        FIND_LIBRARY( Wt_LIBRARY NAMES wt PATHS PATH PATH_SUFFIXES lib lib-release lib_release )
        FIND_LIBRARY( Wt_EXT_LIBRARY NAMES wtext PATHS PATH PATH_SUFFIXES lib lib-release lib_release )
        FIND_LIBRARY( Wt_HTTP_LIBRARY NAMES wthttp PATHS PATH PATH_SUFFIXES lib lib-release lib_release )
        FIND_LIBRARY( Wt_FCGI_LIBRARY NAMES wtfcgi PATHS PATH PATH_SUFFIXES lib lib-release lib_release )
        FIND_LIBRARY( Wt_DBO_LIBRARY NAMES wtdbo PATHS PATH PATH_SUFFIXES lib lib-release lib_release )
        FIND_LIBRARY( Wt_DBOSQLITE3_LIBRARY NAMES wtdbosqlite3 PATHS PATH PATH_SUFFIXES lib lib-release lib_release )
        FIND_LIBRARY( Wt_DBOPOSTGRES_LIBRARY NAMES wtdbopostgres PATHS PATH PATH_SUFFIXES lib lib-release lib_release )

        FIND_LIBRARY( Wt_DEBUG_LIBRARY NAMES wtd wt PATHS PATH PATH_SUFFIXES lib libd lib-debug lib_debug HINTS /usr/lib/debug/usr/lib)
        FIND_LIBRARY( Wt_EXT_DEBUG_LIBRARY NAMES wtextd wtext PATHS PATH PATH_SUFFIXES lib libd lib-debug lib_debug HINTS /usr/lib/debug/usr/lib)
        FIND_LIBRARY( Wt_HTTP_DEBUG_LIBRARY NAMES wthttpd wthttp PATHS PATH PATH_SUFFIXES lib libd lib-debug lib_debug HINTS /usr/lib/debug/usr/lib)
        FIND_LIBRARY( Wt_FCGI_DEBUG_LIBRARY NAMES wtfcgid wtfcgi PATHS PATH PATH_SUFFIXES lib libd lib-debug lib_debug HINTS /usr/lib/debug/usr/lib)
        FIND_LIBRARY( Wt_DBO_DEBUG_LIBRARY NAMES wtdbod wtdbo PATHS PATH PATH_SUFFIXES lib lib-debug lib_debug HINTS /usr/lib/debug/usr/lib)
        FIND_LIBRARY( Wt_DBOSQLITE3_DEBUG_LIBRARY NAMES wtdbosqlite3d wtdbosqlite3 PATHS PATH PATH_SUFFIXES lib lib-debug lib_debug HINTS /usr/lib/debug/usr/lib)
        FIND_LIBRARY( Wt_DBOPOSTGRES_DEBUG_LIBRARY NAMES wtdbopostgresd wtdbopostgres PATHS PATH PATH_SUFFIXES lib lib-debug lib_debug HINTS /usr/lib/debug/usr/lib)

        IF( Wt_LIBRARY )
            IF( Wt_HTTP_LIBRARY )
                SET( Wt_FOUND TRUE )
        SET( Wt_FIND_REQUIRED_Release TRUE )
                SET( Wt_LIBRARIES ${Wt_HTTP_LIBRARY} ${Wt_LIBRARY} )

        IF( Wt_FCGI_LIBRARY )
                    SET( Wt_LIBRARIES ${Wt_LIBRARIES} ${Wt_FCGI_LIBRARY} )
        ENDIF( Wt_FCGI_LIBRARY )
        ELSE( Wt_HTTP_LIBRARY )
           IF( Wt_FCGI_LIBRARY )
                    SET( Wt_FOUND TRUE )
            SET( Wt_FIND_REQUIRED_Release TRUE )
                    SET( Wt_LIBRARIES ${Wt_FCGI_LIBRARY} ${Wt_LIBRARY} )
           ENDIF( Wt_FCGI_LIBRARY )
            ENDIF( Wt_HTTP_LIBRARY )
        ENDIF( Wt_LIBRARY )

        IF( Wt_EXT_LIBRARY )
        SET( Wt_LIBRARIES ${Wt_LIBRARIES} ${Wt_EXT_LIBRARY} )
        ENDIF( Wt_EXT_LIBRARY )

        IF( Wt_DBO_LIBRARY )
        SET( Wt_LIBRARIES ${Wt_LIBRARIES} ${Wt_DBO_LIBRARY} )
        IF( Wt_DBOSQLITE3_LIBRARY )
        SET( Wt_LIBRARIES ${Wt_LIBRARIES} ${Wt_DBOSQLITE3_LIBRARY} )
        ENDIF( Wt_DBOSQLITE3_LIBRARY )
        IF( Wt_DBOPOSTGRES_LIBRARY )
        SET( Wt_LIBRARIES ${Wt_LIBRARIES} ${Wt_DBOPOSTGRES_LIBRARY} )
        ENDIF( Wt_DBOPOSTGRES_LIBRARY )
        ENDIF( Wt_DBO_LIBRARY )

        IF( Wt_DEBUG_LIBRARY )
        IF ( Wt_HTTP_DEBUG_LIBRARY)
                SET( Wt_DEBUG_FOUND TRUE )
        SET( Wt_FIND_REQUIRED_Debug TRUE )
                SET( Wt_DEBUG_LIBRARIES ${Wt_HTTP_DEBUG_LIBRARY} ${Wt_DEBUG_LIBRARY} )

        IF( Wt_FCGI_DEBUG_LIBRARY )
                    SET( Wt_DEBUG_LIBRARIES ${Wt_DEBUG_LIBRARIES} ${Wt_FCGI_DEBUG_LIBRARY} )
        ENDIF( Wt_FCGI_DEBUG_LIBRARY )
        ELSE( Wt_HTTP_DEBUG_LIBRARY )
            IF( Wt_FCGI_DEBUG_LIBRARY )
                    SET( Wt_DEBUG_FOUND TRUE )
            SET( Wt_FIND_REQUIRED_Debug TRUE )
                    SET( Wt_DEBUG_LIBRARIES ${Wt_FCGI_DEBUG_LIBRARY} ${Wt_DEBUG_LIBRARY} )
        ENDIF( Wt_FCGI_DEBUG_LIBRARY )
        ENDIF( Wt_HTTP_DEBUG_LIBRARY)
        ENDIF( Wt_DEBUG_LIBRARY )

         IF( Wt_DBO_DEBUG_LIBRARY )
        SET( Wt_DEBUG_LIBRARIES ${Wt_DEBUG_LIBRARIES} ${Wt_DBO_DEBUG_LIBRARY} )
        IF( Wt_DBOSQLITE3_DEBUG_LIBRARY )
            SET( Wt_DEBUG_LIBRARIES ${Wt_DEBUG_LIBRARIES} ${Wt_DBOSQLITE3_DEBUG_LIBRARY} )
        ENDIF( Wt_DBOSQLITE3_DEBUG_LIBRARY )
        IF( Wt_DBOPOSTGRES_DEBUG_LIBRARY )
            SET( Wt_DEBUG_LIBRARIES ${Wt_DEBUG_LIBRARIES} ${Wt_DBOPOSTGRES_DEBUG_LIBRARY} )
        ENDIF( Wt_DBOPOSTGRES_DEBUG_LIBRARY )
        ENDIF( Wt_DBO_DEBUG_LIBRARY )

        IF(Wt_FOUND)
                IF (NOT Wt_FIND_QUIETLY)
                        MESSAGE(STATUS "Found the Wt libraries at ${Wt_LIBRARIES}")
                        MESSAGE(STATUS "Found the Wt headers at ${Wt_INCLUDE_DIR}")
                ENDIF (NOT Wt_FIND_QUIETLY)
        ELSE(Wt_FOUND)
                IF(Wt_FIND_REQUIRED)
                        MESSAGE(FATAL_ERROR "Could NOT find Wt")
                ENDIF(Wt_FIND_REQUIRED)
        ENDIF(Wt_FOUND)

        IF(Wt_DEBUG_FOUND)
                IF (NOT Wt_FIND_QUIETLY)
                        MESSAGE(STATUS "Found the Wt debug libraries at ${Wt_DEBUG_LIBRARIES}")
                        MESSAGE(STATUS "Found the Wt debug headers at ${Wt_INCLUDE_DIR}")
                ENDIF (NOT Wt_FIND_QUIETLY)
        ELSE(Wt_DEBUG_FOUND)
                IF(Wt_FIND_REQUIRED_Debug)
                        MESSAGE(FATAL_ERROR "Could NOT find Wt debug libraries")
                ENDIF(Wt_FIND_REQUIRED_Debug)
        ENDIF(Wt_DEBUG_FOUND)

ENDIF( Wt_INCLUDE_DIR )

find_package_handle_standard_args(Wt DEFAULT_MSG Wt_INCLUDE_DIR Wt_LIBRARY)
set(Wt_FOUND ${WT_FOUND})


text:
Describe "Add-Numbers" {

    It "can execute script" {
            Remotely { 1 + 1 } | Should Be 2
        }

    It "can return an array" {
        $returnObjs = Remotely { 1..10 }
        $returnObjs.count | Should Be 10
    }

    It "can return a hashtable" {
        $returnObjs = Remotely { @{Value = 2} }
        $returnObjs["Value"] | Should Be 2
    }

    It "can get verbose message" {
        $output = Remotely { Write-Verbose -Verbose "Verbose Message" }
        $output.GetVerbose() | Should Be "Verbose Message"
    }

    It "can get error message" {
        $output = Remotely { Write-Error "Error Message" }
        $output.GetError() | Should Be "Error Message"
    }

    It "can get warning message" {
        $output = Remotely { Write-Warning "Warning Message" }
        $output.GetWarning() | Should Be "Warning Message"
    }

    It "can get debug message" {
        $output = Remotely {
                $originalPreference = $DebugPreference
                $DebugPreference = "continue"
                Write-Debug "Debug Message"
                $DebugPreference = $originalPreference
            }
        $output.GetDebugOutput() | Should Be "Debug Message"
    }

    It "can get progress message" {
        $output = Remotely { Write-Progress -Activity "Test" -Status "Testing" -Id 1 -PercentComplete 100 -SecondsRemaining 0 }
        $output.GetProgressOutput().Activity | Should Be "Test"
        $output.GetProgressOutput().StatusDescription | Should Be "Testing"
        $output.GetProgressOutput().ActivityId | Should Be 1
    }

    It 'can return $false as a value' {
        $output = Remotely { $false }
        $output | Should Be $false
    }

    It 'can return throw messages' {
        $output = Remotely { throw 'bad' }
        $output.GetError().FullyQualifiedErrorId | Should Be 'bad'
    }

    It "can get remote sessions" {
        Remotely { 1 + 1 } | Should Be 2
        $remoteSessions = Get-RemoteSession

        $remoteSessions | % { $remoteSessions.Name -match "Remotely"  | Should Be $true}
    }

    It "can pass parameters to remote block" {
        $num = 10
        $process = Remotely { param($number) $number + 1 } -ArgumentList $num
        $process | Should Be 11
    }

    It "can get target of the remotely block" {
        $output = Remotely { 1 }
        $output.RemotelyTarget | Should Be "localhost"
    }

    It "can handle delete sessions" {
        Remotely { 1 + 1 } | Should Be 2
        $previousSession = Get-RemoteSession
        $previousSession | Remove-PSSession

        ##New session should be created
        Remotely { 1 + 1 } | Should Be 2
        $newSession = Get-RemoteSession
        $previousSession.Name | Should Not Be $newSession.Name
    }

    It "can execute against more than 1 remote machines" {
        $configFile = (join-path $PSScriptRoot 'machineConfig.csv')
        $configContent = @([pscustomobject] @{ComputerName = "localhost" }, [pscustomobject] @{ComputerName = "." }) | ConvertTo-Csv -NoTypeInformation
        $configContent | Out-File -FilePath $configFile -Force

        try
        {
            $results = Remotely { 1 + 1 }
            $results.Count | Should Be 2

            foreach($result in $results)
            {
                $result | Should Be 2
            }
        }
        catch
        {
            $_.FullyQualifiedErrorId | Should Be $null
        }
        finally
        {
            Remove-Item $configFile -ErrorAction SilentlyContinue -Force
        }
    }

    It "can clear remote sessions" {
        Clear-RemoteSession
        Get-PSSession -Name Remotely* | Should Be $null
    }
}


text:
import re

from .base import BaseAnalyser

class SqliteAnalyser(BaseAnalyser):
    migration_tests = [
        {
            "code": "RENAME_TABLE",
            "fn": lambda sql, **kw: re.search("ALTER TABLE .* RENAME TO", sql)
            and "__old" not in sql
            and "new__" not in sql,
            "type": "error",
        },
        {
            "code": "DROP_TABLE",
            # TODO: improve to detect that the table names overlap
            "fn": lambda sql_statements, **kw: any(
                sql.startswith("DROP TABLE") for sql in sql_statements
            )
            and not any(sql.startswith("CREATE TABLE") for sql in sql_statements),
            "msg": "DROPPING table",
            "mode": "transaction",
            "type": "error",
        },
        {
            "code": "NOT_NULL",
            "fn": lambda sql_statements, **kw: any(
                re.search("NOT NULL(?! PRIMARY)(?! DEFAULT)", sql)
                for sql in sql_statements
            )
            and any(
                re.search("ALTER TABLE .* RENAME TO", sql)
                and ("__old" in sql or "new__" in sql)
                for sql in sql_statements
            ),
            "mode": "transaction",
            "type": "error",
        },
    ]

    @staticmethod
    def detect_table(sql):
        if isinstance(sql, str):
            regex_result = re.search("TABLE [`\"'](.*?)[`\"']", sql, re.IGNORECASE)
            if regex_result:
                return regex_result.group(1)
            regex_result = re.search("ON [`\"'](.*?)[`\"']", sql, re.IGNORECASE)
            if regex_result:
                return regex_result.group(1)


text:
package ananas.waymq.droid.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.InflaterInputStream;

import ananas.waymq.droid.api.DefaultMember;
import ananas.waymq.droid.api.IMember;
import ananas.waymq.droid.api.IMemberManager;

public class MemberManagerImpl implements IMemberManager {

	private final Map<String, IdSet> _keyword_map;
	private final Map<String, IMember> _member_map;
	private final Set<String> _modified;

	public MemberManagerImpl() {
		this._keyword_map = new Hashtable<String, IdSet>();
		this._member_map = new Hashtable<String, IMember>();
		this._modified = new HashSet<String>();
	}

	class IdSet {

		final Set<String> _set;

		public IdSet() {
			this._set = new HashSet<String>();
		}
	}

	@Override
	public List<IMember> findMembers(String keyword) {
		List<IMember> rlt = new ArrayList<IMember>();
		if (keyword == null) {
			keyword = "";
		}
		IdSet set = this._keyword_map.get(keyword);
		if (set == null) {
			return rlt;
		}
		List<String> ids = new ArrayList<String>(set._set);
		for (String id : ids) {
			IMember mem = this._member_map.get(id);
			if (mem != null)
				rlt.add(mem);
		}
		return rlt;
	}

	@Override
	public IMember addMember(IMember member) {
		final String id = member.getId().toString().trim();
		IMember ret = this._member_map.get(id);
		if (ret == null) {
			ret = member;
			this._modified.add(id);
			this.__do_add(id, member);
		}
		return ret;
	}

	private void __do_add(String id, IMember member) {
		this._member_map.put(id, member);
		String[] kws = member.getKeyWords();
		for (String kw : kws) {
			this.__add_key_word(id, member, kw);
		}
		this.__add_key_word(id, member, "");
		this.__add_key_word(id, member, id);
		this.__add_key_word(id, member, member.getName());
		this.__add_key_word(id, member, member.getPhone());
	}

	private void __add_key_word(String id, IMember member, String keyword) {
		final int len = keyword.length();
		for (int i = Math.min(len, 4); i >= 0; i--) {
			String key = keyword.substring(0, i);
			IdSet set = this._keyword_map.get(key);
			if (set == null) {
				set = new IdSet();
				this._keyword_map.put(key, set);
			}
			set._set.add(id);
		}
	}

	@Override
	public void setModifiedMember(IMember member) {
		String id = member.getId().toString().trim();
		this._modified.add(id);
	}

	@Override
	public void save(File path) {
		try {
			Set<String> set = new HashSet<String>(this._modified);
			for (String id : set) {
				IMember member = this._member_map.get(id);
				if (member != null) {
					File file = Helper.getFileById(path, id);
					Properties prop = member.toProperties();
					Helper.savePropertiesAsZip(file, prop);
				}
			}
			this._modified.clear();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void load(File path) {
		try {
			if (!path.exists())
				return;
			if (!path.isDirectory())
				return;
			File[] list = path.listFiles();
			for (File file : list) {
				if (!file.isDirectory()) {
					Properties prop = Helper.loadPropertiesAsZip(file);
					if (prop != null) {
						IMember member = new DefaultMember(prop);
						this.__do_add(member.getId().toString(), member);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	static class Helper {

		public static File getFileById(File path, String id) {
			return new File(path, "member_" + id);
		}

		public static Properties loadPropertiesAsZip(File file)
				throws IOException {

			if (!file.exists())
				return null;
			if (file.isDirectory())
				return null;
			InputStream in = new FileInputStream(file);
			in = new InflaterInputStream(in);
			Properties prop = new Properties();
			prop.load(in);
			in.close();
			return prop;
		}

		public static void savePropertiesAsZip(File file, Properties prop)
				throws IOException {

			File parent = file.getParentFile();
			if (!parent.exists()) {
				parent.mkdirs();
			}
			OutputStream out = new FileOutputStream(file);
			out = new DeflaterOutputStream(out);
			prop.store(out, file.getName());
			out.close();
		}
	}
}


text:
using System;
using System.Collections.Generic;
using NakedFramework.Architecture.Facet;
using NakedFramework.Architecture.Spec;
using NakedFramework.Architecture.SpecImmutable;

namespace NakedFramework.Core.Util;

/// <summary>
///     Compares by <see cref="IMemberOrderFacet" /> obtained from each <see cref="IMemberSpecImmutable" />
/// </summary>
/// <para>
///     If there is no attribute on either member, then will compare the members by name instead.
/// </para>
public class MemberOrderComparator<T> : IComparer<T> where T : ISpecification {
    private readonly MemberIdentifierComparator<T> fallbackComparator = new();

    #region IComparer<T> Members

    public int Compare(T o1, T o2) {
        var m1 = GetMemberOrder(o1);
        var m2 = GetMemberOrder(o2);

        if (m1 is null && m2 is null) {
            return fallbackComparator.Compare(o1, o2);
        }

        if (m1 is null) {
            return +1; // annotated before non-annotated
        }

        if (m2 is null) {
            return -1; // annotated before non-annotated
        }

        var components1 = m1.Sequence.Split('.');
        var components2 = m2.Sequence.Split('.');

        var length1 = components1.Length;
        var length2 = components2.Length;

        // shouldn't happen but just in case.
        if (length1 == 0 && length2 == 0) {
            return fallbackComparator.Compare(o1, o2);
        }

        // continue to loop until we run out of components.
        var n = 0;
        while (true) {
            var length = n + 1;
            // check if run out of components in either side
            if (length1 < length && length2 >= length) {
                return -1; // o1 before o2
            }

            if (length2 < length && length1 >= length) {
                return +1; // o2 before o1
            }

            if (length1 < length && length2 < length) {
                // run out of components
                return fallbackComparator.Compare(o1, o2);
            }

            // we have this component on each side
            int componentCompare;
            if (int.TryParse(components1[n], out var c1) && int.TryParse(components2[n], out var c2)) {
                componentCompare = c1.CompareTo(c2);
            }
            else {
                componentCompare = string.Compare(components1[n], components2[n], StringComparison.InvariantCulture);
            }

            if (componentCompare != 0) {
                return componentCompare;
            }

            // this component is the same; lets look at the next
            n++;
        }
    }

    #endregion

    private static IMemberOrderFacet GetMemberOrder(ISpecification specification) => specification.GetFacet<IMemberOrderFacet>();
}


text:
require 'active_support'

module ActiveRecord
  class Base
    # Use this method to find or create records that have uniqueness constraints enforced by the database.
    # After calling the AR find_or_create_by method it queries the preexisting or created record by the attributes
    # provided, thereby ensuring that a concurrently created record is returned when a AR RecordNotUnique error is
    # raised. When no record can be found, because for instance validations fail on create, the created object
    # containing the validation errors is returned instead.
    def self.uniq_find_or_create_by(attributes, &block)
      find_or_create_by(attributes, &block)
    rescue ActiveRecord::RecordNotUnique => exception
      find_by(attributes) || raise(exception)
    end

    # Use this method if you want an exception to be raised when creating a new record fails due to some validation
    # error other than uniqueness.
    def self.uniq_find_or_create_by!(attributes, &block)
      find_or_create_by!(attributes, &block)
    rescue ActiveRecord::RecordNotUnique => exception
      find_by(attributes) || raise(exception)
    rescue ActiveRecord::RecordInvalid => exception
      find_by(attributes) || raise(exception)
    end
  end
end


text:
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/*                                                                       */
/*    This file is part of the HiGHS linear optimization suite           */
/*                                                                       */
/*    Written and engineered 2008-2020 at the University of Edinburgh    */
/*                                                                       */
/*    Available as open-source under the MIT License                     */
/*                                                                       */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/**@file io/HighsIO.cpp
 * @brief IO methods for HiGHS - currently just print/log messages
 * @author Julian Hall, Ivet Galabova, Qi Huangfu and Michael Feldmeier
 */
#include "HighsIO.h"

#include <cstdarg>
#include <cstdio>
#include <ctime>

#include "lp_data/HighsLp.h"
#include "lp_data/HighsOptions.h"

void (*printmsgcb)(int, const char*, void*) = NULL;
void (*logmsgcb)(HighsMessageType, const char*, void*) = NULL;
void* msgcb_data = NULL;

char msgbuffer[65536];

void HighsPrintMessage(FILE* pass_output, const int pass_message_level,
                       const int level, const char* format, ...) {
  if (pass_output == NULL) {
    return;
  }
  if (pass_message_level & level) {
    va_list argptr;
    va_start(argptr, format);
    if (printmsgcb == NULL)
      vfprintf(pass_output, format, argptr);
    else {
      int len;
      len = vsnprintf(msgbuffer, sizeof(msgbuffer), format, argptr);
      if (len >= (int)sizeof(msgbuffer)) {
        // Output was truncated: for now just ensure string is null-terminated
        msgbuffer[sizeof(msgbuffer) - 1] = '\0';
      }
      printmsgcb(level, msgbuffer, msgcb_data);
    }
    va_end(argptr);
  }
}

void HighsLogMessage(FILE* pass_logfile, HighsMessageType type,
                     const char* format, ...) {
  if (pass_logfile == NULL) {
    return;
  }

  time_t rawtime;
  struct tm* timeinfo;

  time(&rawtime);
  timeinfo = localtime(&rawtime);
  va_list argptr;
  va_start(argptr, format);

  if (logmsgcb == NULL) {
    fprintf(pass_logfile, "%-7s: ", HighsMessageTypeTag[(int)type]);
    vfprintf(pass_logfile, format, argptr);
    fprintf(pass_logfile, "\n");
  } else {
    int len;
    len = snprintf(msgbuffer, sizeof(msgbuffer), "%02d:%02d:%02d [%-7s] ",
                   timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec,
                   HighsMessageTypeTag[(int)type]);
    if (len < (int)sizeof(msgbuffer))
      len +=
          vsnprintf(msgbuffer + len, sizeof(msgbuffer) - len, format, argptr);
    if (len < (int)sizeof(msgbuffer) - 1) {
      msgbuffer[len] = '\n';
      ++len;
      msgbuffer[len] = '\0';
    } else
      msgbuffer[sizeof(msgbuffer) - 1] = '\0';
    logmsgcb(type, msgbuffer, msgcb_data);
  }

  va_end(argptr);
}

void HighsSetMessageCallback(
    void (*printmsgcb_)(int level, const char* msg, void* msgcb_data),
    void (*logmsgcb_)(HighsMessageType type, const char* msg, void* msgcb_data),
    void* msgcb_data_) {
  printmsgcb = printmsgcb_;
  logmsgcb = logmsgcb_;
  msgcb_data = msgcb_data_;
}

void HighsSetIO(HighsOptions& options) {
  printmsgcb = options.printmsgcb;
  logmsgcb = options.logmsgcb;
  msgcb_data = options.msgcb_data;
}


text:
module.exports = function ({ $lookup }) {
    return {
        object: function () {
            const assert = require('assert')

            return function ($buffer, $start, {
                counter = (() => [ 0 ])()
            } = {}) {
                let $accumulator = {}

                let object = {
                    value: {
                        first: 0,
                        second: 0
                    },
                    sentry: 0
                }

                $accumulator['counter'] = counter

                object.value.first = $buffer[$start++]

                object.value.second = $buffer[$start++]

                object.sentry = $buffer[$start++]

                object = (function ({ $_, counter }) {
                    console.log('>>>', counter)
                    assert.deepEqual(counter, [ 0 ])
                    return $_
                })({
                    $_: object,
                    counter: $accumulator['counter']
                })

                return object
            }
        } ()
    }
}


text:
import ko from 'knockout';
import './app';
import rootScope from './root-scope';

export function run() {
  'use strict';

  ko.applyBindings(rootScope, window.document.documentElement);
}


text:
package org.wso2.carbon.identity.configuration.mgt.core.search;

import org.wso2.carbon.identity.configuration.mgt.core.model.ResourceSearchBean;
import org.wso2.carbon.identity.configuration.mgt.core.search.constant.ConditionType;
import org.wso2.carbon.identity.configuration.mgt.core.search.exception.PrimitiveConditionValidationException;

import java.lang.reflect.Field;

public class PrimitiveConditionValidator {

    private SearchBean searchBean;

    public PrimitiveConditionValidator(SearchBean searchBean) {

        this.searchBean = searchBean;
    }

    /**
     * Validate parameters in a {@link PrimitiveCondition} with the given Search bean
     *
     * @param primitiveCondition
     * @return A db qualified {@link PrimitiveCondition}.
     * @throws PrimitiveConditionValidationException
     */
    public PrimitiveCondition validate(PrimitiveCondition primitiveCondition) throws PrimitiveConditionValidationException {

        if (searchBean == null) {
            throw new NullPointerException("Invalid search bean: null in the PrimitiveCondition validate.");
        }
        String property = primitiveCondition.getProperty();
        ConditionType.PrimitiveOperator operator = primitiveCondition.getOperator();
        Object value = primitiveCondition.getValue();

        if (property == null || operator == null || value == null) {
            throw new PrimitiveConditionValidationException(
                    "Invalid primitive condition parameters found in: property = " + property
                            + (operator == null ? ", condition = null" : "")
                            + (value == null ? ", value = null" : "")
                            + "."
            );
        }
        try {
            Field field = this.searchBean.getClass().getDeclaredField(property);
            if (!field.getType().getName().equals(value.getClass().getName())) {
                throw new PrimitiveConditionValidationException(
                        "Value for the property: " + property + " is expected to be: " + field.getType().getName() +
                                " but found: " + value.getClass().getName()
                );
            }
        } catch (NoSuchFieldException e) {
            throw new PrimitiveConditionValidationException(
                    "Property: " + property + " is not found in the allowed search properties present in the bean " +
                            "class: " + ResourceSearchBean.class.getName()
            );
        }

        // If parameter validation are a success then build a database qualified primitive condition.
        PrimitiveCondition dbQualifiedPrimitiveCondition;
        dbQualifiedPrimitiveCondition = this.searchBean.mapPrimitiveCondition(primitiveCondition);
        dbQualifiedPrimitiveCondition.setProperty(this.searchBean.getDBQualifiedFieldName(
                dbQualifiedPrimitiveCondition.getProperty()
        ));
        return dbQualifiedPrimitiveCondition;
    }
}


text:
import CryptoHelpers from '../../../utils/CryptoHelpers';
import Network from '../../../utils/Network';
import helpers from '../../../utils/helpers';
import KeyPair from '../../../utils/KeyPair';
import Address from '../../../utils/Address';

class citizenRegisterCtrl {
	// Set services as constructor parameter

    constructor($q, $location, $timeout, $localStorage, Alert, WalletBuilder, AppConstants, NetworkRequests, Wallet, Transactions, DataBridge ) {
        'ngInject';

        // Location service <- check
        this._location = $location;
        this._q = $q;

        // $timeout to digest asynchronously
        this._$timeout = $timeout;

        //Local storage
        this._storage = $localStorage;

        // Alert service
        this._Alert = Alert;

        // WalletBuilder service
        this._WalletBuilder = WalletBuilder;

        // $state for redirect
        //this._$state = $state;

        // App constants
        this._AppConstants = AppConstants;

        // Get wallets from local storage or create empty array
        this._storage.wallets = this._storage.wallets || [];

        // NetworkRequests service
        this._NetworkRequests = NetworkRequests;

        // Wallet service
        this._Wallet = Wallet;

        // Transactions service
        this._Transactions = Transactions;

        // DataBridge service
        this._DataBridge = DataBridge;

        // To store our password and decrypted/generated private key
        this.common = {
        "password": "",
        "privateKey": ""
        }

        //If no wallet show alert and redirect to home
        if (!this._Wallet.current) {
            this._Alert.noWalletLoaded();
            this._location.path('/');
            return;
        }

        // current network
        this.network = this._Wallet.network;

        /**
        * Default simple transfer properties
        */
        this.transferData = {}
        this.transferData.recipient = '';
        this.transferData.amount = 0;
        this.transferData.message = '';
        this.transferData.encryptMessage = false;
        this.transferData.fee = 0;
        this.transferData.innerFee = 0;
        // TODO: What if multisig?
        this.transferData.isMultisig = false;
        this.transferData.multisigAccount = '';

        // Mosaics data
        // Counter for mosaic gid
        this.counter = 1;
        this.transferData.mosaics = null;
        this.mosaicsMetaData = this._DataBridge.mosaicDefinitionMetaDataPair;
        this.transferData.isMosaicTransfer = false;
        this.currentAccountMosaicNames = [];
        this.selectedMosaic = "nem:xem";
        // Mosaics data for current account
        this.currentAccountMosaicData = "";

        /****** USECASE Variables ******/

        this.step = {}
        this.country = "atlantis";

        this.namespaces = {};
        this.namespaces.country = "country."+this.country;
        this.namespaces.register = this.namespaces.country+".register";
        this.namespaces.revoke = this.namespaces.country+".revoke";

        this.buttonDisabled = false;

        // 1. Officer inputs ID:dateOfBirth,NIS,...:country
        //Randomize sample
        var randomnumber = Math.floor(Math.random() * (999999999999 - 111111111111 + 1)) + 111111111111;
        this.citizenID = randomnumber;
        this.citizenInfo = "Alice Brown, 1970-01-01";
        this.citizenAccount = "TDTSZ6TYSPR7PBH3SQJJ4F3Q3URQJGQMODY7PYME"; //"this is a test wallet2"

        // 2. [CP] BW gets created
        this.step.bwCreated = false;
        this.cpAccount = "";
        // 3. [G] sends message (ID=C) to [CP]
        this.step.cpLinked = false;
        // 4. [CP] is set to be a MultiSignature acct from [G]
        this.step.cpOwned = false;
        // 5. [G] creates and sends atlantis.register:citizen to [CP]
        this.step.tokensToCP = false;
        // 6. [G] creates and sends atlantis:citizen to [C]
        this.step.tokensToC = false;
        // 7. End of Use case
        this.step.success = false;

        // Init account mosaics
        this._updateCurrentAccountMosaics();
    }

    /**
     * _updateCurrentAccountMosaics() Get current account mosaics names
     */
    _updateCurrentAccountMosaics() {
        //Fix this.transferData.multisigAccount error on logout
        if (null === this.transferData.multisigAccount) {
            return;
        }
            // Get current account
            let acct = this._Wallet.currentAccount.address;
            if (this.transferData.isMultisig) {
                // Use selected multisig
                acct = this.transferData.multisigAccount.address;
            }
            // Set current account mosaics names if mosaicOwned is not undefined
            if (undefined !== this._DataBridge.mosaicOwned[acct]) {
                this.currentAccountMosaicData = this._DataBridge.mosaicOwned[acct];
                this.currentAccountMosaicNames = Object.keys(this._DataBridge.mosaicOwned[acct]).sort();
            } else {
                this.currentAccountMosaicNames = ["nem:xem"];
                this.currentAccountMosaicData = "";
            }
            // Default selected is nem:xem
            this.selectedMosaic = "nem:xem";
    }

    /**
     * _checkAccess() Ensure that the user is authentic by checking his password and setting the private key to this.common
     */
    _checkAccess(){
        // Decrypt/generate private key and check it. Returned private key is contained into this.common
        if (!CryptoHelpers.passwordToPrivatekeyClear(this.common, this._Wallet.currentAccount, this._Wallet.algo, true)) {
            this._Alert.invalidPassword();
            // Enable send button
            this.buttonDisabled = false;
            return false;
        } else if (!CryptoHelpers.checkAddress(this.common.privateKey, this._Wallet.network, this._Wallet.currentAccount.address)) {
            this._Alert.invalidPassword();
            // Enable send button
            this.buttonDisabled = false;
            return false;
        }
        return true;
    }

    /**
     * _processRecipient() Process recipient input and get data from network
     */
    _processRecipient(transferData) {
        // return if no value or address length < to min address length
        if (!transferData || !transferData.recipient || transferData.recipient.length < 40) {
            return;
        }

        // Clean address
        let recipientAddress = transferData.recipient.toUpperCase().replace(/-/g, '');
        // Check if address is from the same network
        if (Address.isFromNetwork(recipientAddress, this.network)) {
            // Get recipient account data from network
            return this._NetworkRequests.getAccountData(helpers.getHostname(this._Wallet.node), recipientAddress).then((data) => {
                    // Store recipient public key (needed to encrypt messages)
                    transferData.recipientPubKey = data.account.publicKey;
                    console.log(transferData.recipientPubKey)
                    // Set the address to send to
                    transferData.recipient = recipientAddress;
                },
                (err) => {
                    this._Alert.getAccountDataError(err.data.message);
                    // Reset recipient data
                    // this.resetRecipientData();
                    return;
                });
        } else {
            // Error
            this._Alert.invalidAddressForNetwork(recipientAddress, this._Wallet.network);
            // Reset recipient data
            return;
        }

    }

    /**
     * _createBrainWallet() creates a new brain wallet using the seed as name and passphrase and sets it for further operations
     */
    _createBrainWallet(seed) {
        var deferred = this._q.defer();
        var promise = deferred.promise;

        if (!seed) {
            this._Alert.missingtransferData();
            this.buttonDisabled = false;
            return;
        }

        // Create the brain wallet from the seed on the form.
        // We want the official to create the brainwallet
        this._WalletBuilder.createBrainWallet(seed, seed, this.network).then((wallet) => {
            this._$timeout(() => {
                if (wallet) {

                    var mainAccount = {};
                    mainAccount.address = wallet.accounts[0].address;
                    mainAccount.password = seed;
                    mainAccount.privateKey = "";

                    // Decrypt/generate private key and check it. Returned private key is contained into this.common
                    if (!CryptoHelpers.passwordToPrivatekeyClear(mainAccount, wallet.accounts[0], wallet.accounts[0].algo, false)) {
                        this._Alert.invalidPassword();
                        return;
                    }

                    mainAccount.publicKey = KeyPair.create(mainAccount.privateKey).publicKey.toString();

                    // On success concat new wallet to local storage wallets
                    this._storage.wallets = this._storage.wallets.concat(wallet);
                    this._Alert.createWalletSuccess();

                    this.cpAccount = wallet['accounts']['0']['address'];

                    this.step.bwCreated = true;
                    deferred.resolve(mainAccount);
                }
            }, 10);
        },
        (err) => {
            this._Alert.createWalletFailed(err);
            this.buttonDisabled = false;
            deferred.reject(false);
        });

        return deferred.promise;
    }

    /**
     * _send(entity) Sends a transaction to the network based on an entity
     */
    _send(entity, common){
        // Construct transaction byte array, sign and broadcast it to the network
        return this._Transactions.serializeAndAnnounceTransaction(entity, common).then((result) => {
            // Check status
            if (result.status === 200) {
                // If code >= 2, it's an error
                if (result.data.code >= 2) {
                    this._Alert.transactionError(result.data.message);
                } else {
                    this._Alert.transactionSuccess();
                }
            }
        },
        (err) => {
            // Enable send button
            this.buttonDisabled = false;
            this._Alert.transactionError('Failed ' + err.data.error + " " + err.data.message);
        });
    }

    /**
     * _sendMessage(recipient, message) Sends a minimal transaction containing a message to poin
     */
    _sendMessage(recipient, message, common) {

        var transferData = {}

        // Check that the recipient is a valid account and process it's public key
        transferData.recipient = recipient;
        this._processRecipient(transferData);
        // transferData.recipientPubKey is set now

        transferData.amount = 0;
        transferData.message = message;
        transferData.encryptMessage = false; // Maybe better to encrypt?
        transferData.isMultisig = false;
        transferData.isMosaicTransfer = false;

        // Build the entity to send
        let entity = this._Transactions.prepareTransfer(common, transferData, this.mosaicsMetaData);
        return this._send(entity, common);
    }

    /**
     * _sendMosaic(recipient, namespaceId, mosaics, amount) Sends a minimal transaction containing one or more mosaics
     */
    _sendMosaic(recipient, namespaceId, mosaics, amount, common, options) {

        var xem = ""
        var message = ""
        if(options.xem) xem = options.xem;
        if(options.message) message = options.message;

        var transferData = {}

        // Check that the recipient is a valid account and process it's public key
        transferData.recipient = recipient;
        this._processRecipient(transferData);
        // transferData.recipientPubKey is set now

        // In case of mosaic transfer amount is used as multiplier, set to 1 as default
        transferData.amount = 1;

        // Other necessary
        transferData.message = message;
        transferData.encryptMessage = false;

        // Setup mosaics information
        transferData.mosaics = [{
            'mosaicId': {
                'namespaceId': namespaceId,
                'name': mosaics
            },
            'quantity': amount,
        }];

        if(xem > 0){
            transferData.mosaics[1] = {
                'mosaicId': {
                    'namespaceId': "nem",
                    'name': 'xem'
                },
                'quantity': xem,
            }
        }

        // Build the entity to send
        let entity = this._Transactions.prepareTransfer(common, transferData, this.mosaicsMetaData);
        return this._send(entity, common);
    }

    /**
     * _sendOwnedBySelf(subjectAccount)
     *    > subjectFullAccount.publicKey
     *    > subjectFullAccount.privateKey
     *    > subjectFullAccount.account
     *    > ownersArray[0].publicKey
     */
    _sendOwnedBySelf(subjectFullAccount) {

        // Obtain own public key and address
        let owner = {};
        owner.address = this._Wallet.currentAccount.address;
        owner.publicKey = KeyPair.create(this.common.privateKey).publicKey.toString();

        // Set current account as owner
        let ownersArray = [{}];
        ownersArray[0].pubKey = owner.publicKey;

        // Set transferData
        let transferData = {};
        transferData.minCosigs = 1;
        transferData.accountToConvert = subjectFullAccount.publicKey; // OJO!!!!
        transferData.cosignatoryAddress = owner.address;
        transferData.multisigPubKey = subjectFullAccount.publicKey;

        // Build the entity to send
        console.log("subjectFullAccount", subjectFullAccount);
        let entity = this._Transactions._constructAggregate(transferData, ownersArray);
        return this._send(entity, subjectFullAccount);
    }

    /**
     * This usecase showcases how to create and validate a citizen account on the blockchain with the following steps:
     *    - 0. A Government officer is logged into this account and a Citizen already owns an account (citizenAccount)
     *    - 1. A form with 2 password fields appears.
     *    -     1.1  Officer inputs ID:country
     *    -     1.2 [CP] BW gets created
     *    -     1.3 [CP] is set to be a MS acct from [G]
     *    -     1.4 [G] sends message (ID=C) to [CP]
     *    -     1.5 [G] creates and sends atlantis.register:citizen to [CP]
     *    -     1.6 [G] creates and sends atlantis:citizen to [C]
     */
    submit(){

        // Verify password and generate/get the PK into this.common
        if(!this._checkAccess()){
            this.buttonDisabled = false;
            return;
        }

        // User is authorized, starting...
        this.buttonDisabled = true;

        // 1. Create a brain wallet using a seed based on the citizen's ID and a pattern so that there are few collisions. On a real use cases this should be stronger.
        // Sample: "citizenID:country"
        let seed = this.citizenID+"-"+this.citizenInfo+"@"+this.country+":citizen";
        var cpBwMainAccount = {};
        this._createBrainWallet(seed).then((cpBwMainAccount)=>{
            // cpBwMainAccount.address is set
            // cpBwMainAccount.privateKey is set
            // cpBwMainAccount.publicKey is set

            // 2.5 [G] creates and sends atlantis.register:citizen to [CP]
            // together with  a message to the poiner account to link it to the citizen's
            console.log("Sending token to CP: " + this.cpAccount);
            let options = {'xem':22000000, 'message':this.citizenID+"="+this.citizenAccount};
            this._sendMosaic(cpBwMainAccount.address, this.namespaces.register, "citizen", 1, this.common, options).then((data)=>{
                this.step.tokensToCP = true;
                this.step.cpLinked = true;

                //2. [CP] is set to be a MS acct from [G]
                console.log("Taking control of CP");
                this._sendOwnedBySelf(cpBwMainAccount).then((data)=>{
                    this.step.cpOwned = true;

                    //2.6 [G] creates and sends atlantis:citizen to [C]
                    console.log("Sending token to C: " + this.citizenAccount);
                    this._sendMosaic(this.citizenAccount, this.namespaces.country, "citizen", 1, this.common, {}).then((data)=>{
                        this.step.tokensToC = true;
                        this.step.success = true;

                    });
                });
            });

        },
        (err) => {
            // Delete private key in common
            this.common.privateKey = '';
            // Enable send button
            this.buttonDisabled = false;
            this._Alert.transactionError('Failed ' + err.data.error + " " + err.data.message);
        });
    }
}

export default citizenRegisterCtrl;


text:
package it.infn.ct.futuregateway.apiserver.utils;

import it.infn.ct.futuregateway.apiserver.resources.Application;
import it.infn.ct.futuregateway.apiserver.resources.Infrastructure;
import it.infn.ct.futuregateway.apiserver.resources.Params;
import it.infn.ct.futuregateway.apiserver.resources.Task;
import it.infn.ct.futuregateway.apiserver.resources.TaskFileInput;
import it.infn.ct.futuregateway.apiserver.resources.TaskFileOutput;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import org.apache.commons.lang3.RandomStringUtils;

/**
 * The TestDataIT class contains all the data registered in the DB during the
 integration tests.
 * The provided methods allow to generate all the resources to store in the DB
 * and use for the the tests.
 *
 * @author Marco Fargetta <marco.fargetta@ct.infn.it>
 */
public final class TestDataIT {

    /**
     * Max number of entities to add in a random list for test.
     */
    public static final int MAX_ENTITIES_IN_LIST = 10;

    /**
     * Max number of entities to add in a random list for test.
     */
    public static final int MAX_STRING_LENGTH = 10;

    /**
     * Max number of entities to add in a random list for test.
     */
    public static final int MAX_DESC_LENGTH = 60;

    /**
     * Random generator for the boolean.
     */
    private static Random rnd = new Random();

    /**
     * Create a random infrastructure.
     * Data are randomly generated.
     *
     * @return The infrastructure
     */
    public static Infrastructure createInfrastructure() {
        Infrastructure infra = new Infrastructure();
        infra.setName(RandomStringUtils.randomAlphanumeric(
                (int) (1 + (Math.random() * MAX_STRING_LENGTH))));
        infra.setDescription(RandomStringUtils.randomAlphanumeric(
                (int) (1 + (Math.random() * MAX_DESC_LENGTH))));
        infra.setEnabled(rnd.nextBoolean());
        List<Params> params = (List<Params>) new LinkedList<Params>();
        for (int i = 0; i < (int) (Math.random() * MAX_ENTITIES_IN_LIST); i++) {
            Params p = new Params();
            p.setDescription(RandomStringUtils.randomAlphanumeric(
                    (int) (1 + (Math.random() * MAX_DESC_LENGTH))));
            p.setName(RandomStringUtils.randomAlphanumeric(
                    (int) (1 + (Math.random() * MAX_STRING_LENGTH))));
            p.setValue(RandomStringUtils.randomAlphanumeric(
                    (int) (1 + (Math.random() * MAX_STRING_LENGTH))));
            params.add(p);
        }
        if (!params.isEmpty()) {
            infra.setParameters(params);
        }
        return infra;
    }

    /**
     * Create a random infrastructure.
     * All data are randomly generated but the infrastructure which is not
     * included.
     *
     * @return The infrastructure
     */
    public static Application createApplication() {
        Application app = new Application();
        app.setName(RandomStringUtils.randomAlphanumeric(
                (int) (1 + (Math.random() * MAX_STRING_LENGTH))));
        app.setDescription(RandomStringUtils.randomAlphanumeric(
                (int) (1 + (Math.random() * MAX_DESC_LENGTH))));
        app.setEnabled(rnd.nextBoolean());
        List<Params> params = (List<Params>) new LinkedList<Params>();
        for (int i = 0; i < (int) (Math.random() * MAX_ENTITIES_IN_LIST); i++) {
            Params p = new Params();
            p.setDescription(RandomStringUtils.randomAlphanumeric(
                    (int) (1 + (Math.random() * MAX_DESC_LENGTH))));
            p.setName(RandomStringUtils.randomAlphanumeric(
                    (int) (1 + (Math.random() * MAX_STRING_LENGTH))));
            p.setValue(RandomStringUtils.randomAlphanumeric(
                    (int) (1 + (Math.random() * MAX_STRING_LENGTH))));
            params.add(p);
        }
        if (!params.isEmpty()) {
            app.setParameters(params);
        }
        return app;
    }

    /**
     * Create a random task.
     * All data are randomly generated but the application.
     *
     * @return The task
     */
    public static Task createTask() {
        Task task = new Task();
        List<String> someArgs = new LinkedList<>();
        for (int i = 0; i < (int) (Math.random() * MAX_ENTITIES_IN_LIST); i++) {
            someArgs.add(RandomStringUtils.randomAlphanumeric(
                    (int) (1 + (Math.random() * MAX_STRING_LENGTH))));
        }
        task.setArguments(someArgs);
        task.setDescription(RandomStringUtils.randomAlphanumeric(
                    (int) (1 + (Math.random() * MAX_DESC_LENGTH))));
        List<TaskFileInput> inputs = new LinkedList<>();
        for (int i = 0; i < (int) (Math.random() * MAX_ENTITIES_IN_LIST); i++) {
            TaskFileInput in = new TaskFileInput();
            in.setName(RandomStringUtils.randomAlphanumeric(
                    (int) (1 + (Math.random() * MAX_STRING_LENGTH))));
            inputs.add(in);
        }
        if (!inputs.isEmpty()) {
            task.setInputFiles(inputs);
        }
        List<TaskFileOutput> outputs = new LinkedList<>();
        for (int i = 0; i < (int) (Math.random() * MAX_ENTITIES_IN_LIST); i++) {
            TaskFileOutput out = new TaskFileOutput();
            out.setName(RandomStringUtils.randomAlphanumeric(
                    (int) (1 + (Math.random() * MAX_STRING_LENGTH))));
            outputs.add(out);
        }
        if (!outputs.isEmpty()) {
            task.setOutputFiles(outputs);
        }
        return task;
    }

    /**
     * Utility class cannot be allocated.
     */
    private TestDataIT() { }
}


text:
/*
 * This program is free software; you can redistribute it and/or modify it
 * under the terms and conditions of the GNU General Public License,
 * version 2, as published by the Free Software Foundation.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include <linux/fs.h>
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/cdev.h>
#include <linux/poll.h>
#include <linux/device.h>
#include <linux/major.h>
#include <linux/hid.h>
#include <linux/mutex.h>
#include <linux/sched.h>
#include <linux/smp_lock.h>

#include <linux/hidraw.h>

static int hidraw_major;
static struct cdev hidraw_cdev;
static struct class *hidraw_class;
static struct hidraw *hidraw_table[HIDRAW_MAX_DEVICES];
static DEFINE_MUTEX(minors_lock);

static ssize_t hidraw_read(struct file *file, char __user *buffer, size_t count, loff_t *ppos)
{
	struct hidraw_list *list = file->private_data;
	int ret = 0, len;
	char *report;
	DECLARE_WAITQUEUE(wait, current);

	mutex_lock(&list->read_mutex);

	while (ret == 0) {
		if (list->head == list->tail) {
			add_wait_queue(&list->hidraw->wait, &wait);
			set_current_state(TASK_INTERRUPTIBLE);

			while (list->head == list->tail) {
				if (file->f_flags & O_NONBLOCK) {
					ret = -EAGAIN;
					break;
				}
				if (signal_pending(current)) {
					ret = -ERESTARTSYS;
					break;
				}
				if (!list->hidraw->exist) {
					ret = -EIO;
					break;
				}

				/* allow O_NONBLOCK to work well from other threads */
				mutex_unlock(&list->read_mutex);
				schedule();
				mutex_lock(&list->read_mutex);
				set_current_state(TASK_INTERRUPTIBLE);
			}

			set_current_state(TASK_RUNNING);
			remove_wait_queue(&list->hidraw->wait, &wait);
		}

		if (ret)
			goto out;

		report = list->buffer[list->tail].value;
		len = list->buffer[list->tail].len > count ?
			count : list->buffer[list->tail].len;

		if (copy_to_user(buffer, list->buffer[list->tail].value, len)) {
			ret = -EFAULT;
			goto out;
		}
		ret += len;

		kfree(list->buffer[list->tail].value);
		list->tail = (list->tail + 1) & (HIDRAW_BUFFER_SIZE - 1);
	}
out:
	mutex_unlock(&list->read_mutex);
	return ret;
}

/* the first byte is expected to be a report number */
static ssize_t hidraw_write(struct file *file, const char __user *buffer, size_t count, loff_t *ppos)
{
	unsigned int minor = iminor(file->f_path.dentry->d_inode);
	/* FIXME: What stops hidraw_table going NULL */
	struct hid_device *dev = hidraw_table[minor]->hid;
	__u8 *buf;
	int ret = 0;

	if (!dev->hid_output_raw_report)
		return -ENODEV;

	if (count > HID_MAX_BUFFER_SIZE) {
		printk(KERN_WARNING "hidraw: pid %d passed too large report\n",
				task_pid_nr(current));
		return -EINVAL;
	}

	if (count < 2) {
		printk(KERN_WARNING "hidraw: pid %d passed too short report\n",
				task_pid_nr(current));
		return -EINVAL;
	}

	buf = kmalloc(count * sizeof(__u8), GFP_KERNEL);
	if (!buf)
		return -ENOMEM;

	if (copy_from_user(buf, buffer, count)) {
		ret = -EFAULT;
		goto out;
	}

	ret = dev->hid_output_raw_report(dev, buf, count);
out:
	kfree(buf);
	return ret;
}

static unsigned int hidraw_poll(struct file *file, poll_table *wait)
{
	struct hidraw_list *list = file->private_data;

	poll_wait(file, &list->hidraw->wait, wait);
	if (list->head != list->tail)
		return POLLIN | POLLRDNORM;
	if (!list->hidraw->exist)
		return POLLERR | POLLHUP;
	return 0;
}

static int hidraw_open(struct inode *inode, struct file *file)
{
	unsigned int minor = iminor(inode);
	struct hidraw *dev;
	struct hidraw_list *list;
	int err = 0;

	if (!(list = kzalloc(sizeof(struct hidraw_list), GFP_KERNEL))) {
		err = -ENOMEM;
		goto out;
	}

	lock_kernel();
	mutex_lock(&minors_lock);
	if (!hidraw_table[minor]) {
		printk(KERN_EMERG "hidraw device with minor %d doesn't exist\n",
				minor);
		kfree(list);
		err = -ENODEV;
		goto out_unlock;
	}

	list->hidraw = hidraw_table[minor];
	mutex_init(&list->read_mutex);
	list_add_tail(&list->node, &hidraw_table[minor]->list);
	file->private_data = list;

	dev = hidraw_table[minor];
	if (!dev->open++) {
		if (dev->hid->ll_driver->power) {
			err = dev->hid->ll_driver->power(dev->hid, PM_HINT_FULLON);
			if (err < 0)
				goto out_unlock;
		}
		err = dev->hid->ll_driver->open(dev->hid);
		if (err < 0) {
			if (dev->hid->ll_driver->power)
				dev->hid->ll_driver->power(dev->hid, PM_HINT_NORMAL);
			dev->open--;
		}
	}

out_unlock:
	mutex_unlock(&minors_lock);
	unlock_kernel();
out:
	return err;

}

static int hidraw_release(struct inode * inode, struct file * file)
{
	unsigned int minor = iminor(inode);
	struct hidraw *dev;
	struct hidraw_list *list = file->private_data;

	if (!hidraw_table[minor]) {
		printk(KERN_EMERG "hidraw device with minor %d doesn't exist\n",
				minor);
		return -ENODEV;
	}

	list_del(&list->node);
	dev = hidraw_table[minor];
	if (!--dev->open) {
		if (list->hidraw->exist) {
			if (dev->hid->ll_driver->power)
				dev->hid->ll_driver->power(dev->hid, PM_HINT_NORMAL);
			dev->hid->ll_driver->close(dev->hid);
		} else {
			kfree(list->hidraw);
		}
	}

	kfree(list);

	return 0;
}

static long hidraw_ioctl(struct file *file, unsigned int cmd,
							unsigned long arg)
{
	struct inode *inode = file->f_path.dentry->d_inode;
	unsigned int minor = iminor(inode);
	long ret = 0;
	/* FIXME: What stops hidraw_table going NULL */
	struct hidraw *dev = hidraw_table[minor];
	void __user *user_arg = (void __user*) arg;

	lock_kernel();
	switch (cmd) {
		case HIDIOCGRDESCSIZE:
			if (put_user(dev->hid->rsize, (int __user *)arg))
				ret = -EFAULT;
			break;

		case HIDIOCGRDESC:
			{
				__u32 len;

				if (get_user(len, (int __user *)arg))
					ret = -EFAULT;
				else if (len > HID_MAX_DESCRIPTOR_SIZE - 1)
					ret = -EINVAL;
				else if (copy_to_user(user_arg + offsetof(
					struct hidraw_report_descriptor,
					value[0]),
					dev->hid->rdesc,
					min(dev->hid->rsize, len)))
					ret = -EFAULT;
				break;
			}
		case HIDIOCGRAWINFO:
			{
				struct hidraw_devinfo dinfo;

				dinfo.bustype = dev->hid->bus;
				dinfo.vendor = dev->hid->vendor;
				dinfo.product = dev->hid->product;
				if (copy_to_user(user_arg, &dinfo, sizeof(dinfo)))
					ret = -EFAULT;
				break;
			}
		default:
			{
				struct hid_device *hid = dev->hid;
				if (_IOC_TYPE(cmd) != 'H' || _IOC_DIR(cmd) != _IOC_READ) {
					ret = -EINVAL;
					break;
				}

				if (_IOC_NR(cmd) == _IOC_NR(HIDIOCGRAWNAME(0))) {
					int len;
					if (!hid->name) {
						ret = 0;
						break;
					}
					len = strlen(hid->name) + 1;
					if (len > _IOC_SIZE(cmd))
						len = _IOC_SIZE(cmd);
					ret = copy_to_user(user_arg, hid->name, len) ?
						-EFAULT : len;
					break;
				}

				if (_IOC_NR(cmd) == _IOC_NR(HIDIOCGRAWPHYS(0))) {
					int len;
					if (!hid->phys) {
						ret = 0;
						break;
					}
					len = strlen(hid->phys) + 1;
					if (len > _IOC_SIZE(cmd))
						len = _IOC_SIZE(cmd);
					ret = copy_to_user(user_arg, hid->phys, len) ?
						-EFAULT : len;
					break;
				}
                }

		ret = -ENOTTY;
	}
	unlock_kernel();
	return ret;
}

static const struct file_operations hidraw_ops = {
	.owner =        THIS_MODULE,
	.read =         hidraw_read,
	.write =        hidraw_write,
	.poll =         hidraw_poll,
	.open =         hidraw_open,
	.release =      hidraw_release,
	.unlocked_ioctl = hidraw_ioctl,
};

void hidraw_report_event(struct hid_device *hid, u8 *data, int len)
{
	struct hidraw *dev = hid->hidraw;
	struct hidraw_list *list;

	list_for_each_entry(list, &dev->list, node) {
		list->buffer[list->head].value = kmemdup(data, len, GFP_ATOMIC);
		list->buffer[list->head].len = len;
		list->head = (list->head + 1) & (HIDRAW_BUFFER_SIZE - 1);
		kill_fasync(&list->fasync, SIGIO, POLL_IN);
	}

	wake_up_interruptible(&dev->wait);
}
EXPORT_SYMBOL_GPL(hidraw_report_event);

int hidraw_connect(struct hid_device *hid)
{
	int minor, result;
	struct hidraw *dev;

	/* we accept any HID device, no matter the applications */

	dev = kzalloc(sizeof(struct hidraw), GFP_KERNEL);
	if (!dev)
		return -ENOMEM;

	result = -EINVAL;

	mutex_lock(&minors_lock);

	for (minor = 0; minor < HIDRAW_MAX_DEVICES; minor++) {
		if (hidraw_table[minor])
			continue;
		hidraw_table[minor] = dev;
		result = 0;
		break;
	}

	if (result) {
		mutex_unlock(&minors_lock);
		kfree(dev);
		goto out;
	}

	dev->dev = device_create(hidraw_class, &hid->dev, MKDEV(hidraw_major, minor),
				 NULL, "%s%d", "hidraw", minor);

	if (IS_ERR(dev->dev)) {
		hidraw_table[minor] = NULL;
		mutex_unlock(&minors_lock);
		result = PTR_ERR(dev->dev);
		kfree(dev);
		goto out;
	}

	mutex_unlock(&minors_lock);
	init_waitqueue_head(&dev->wait);
	INIT_LIST_HEAD(&dev->list);

	dev->hid = hid;
	dev->minor = minor;

	dev->exist = 1;
	hid->hidraw = dev;

out:
	return result;

}
EXPORT_SYMBOL_GPL(hidraw_connect);

void hidraw_disconnect(struct hid_device *hid)
{
	struct hidraw *hidraw = hid->hidraw;

	hidraw->exist = 0;

	mutex_lock(&minors_lock);
	hidraw_table[hidraw->minor] = NULL;
	mutex_unlock(&minors_lock);

	device_destroy(hidraw_class, MKDEV(hidraw_major, hidraw->minor));

	if (hidraw->open) {
		hid->ll_driver->close(hid);
		wake_up_interruptible(&hidraw->wait);
	} else {
		kfree(hidraw);
	}
}
EXPORT_SYMBOL_GPL(hidraw_disconnect);

int __init hidraw_init(void)
{
	int result;
	dev_t dev_id;

	result = alloc_chrdev_region(&dev_id, HIDRAW_FIRST_MINOR,
			HIDRAW_MAX_DEVICES, "hidraw");

	hidraw_major = MAJOR(dev_id);

	if (result < 0) {
		printk(KERN_WARNING "hidraw: can't get major number\n");
		result = 0;
		goto out;
	}

	hidraw_class = class_create(THIS_MODULE, "hidraw");
	if (IS_ERR(hidraw_class)) {
		result = PTR_ERR(hidraw_class);
		unregister_chrdev(hidraw_major, "hidraw");
		goto out;
	}

        cdev_init(&hidraw_cdev, &hidraw_ops);
        cdev_add(&hidraw_cdev, dev_id, HIDRAW_MAX_DEVICES);
out:
	return result;
}

void hidraw_exit(void)
{
	dev_t dev_id = MKDEV(hidraw_major, 0);

	cdev_del(&hidraw_cdev);
	class_destroy(hidraw_class);
	unregister_chrdev_region(dev_id, HIDRAW_MAX_DEVICES);

}


text:
// Copyright 2015 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.

/**
 * @fileoverview Polymer element for displaying a bluetooth device in a list.
 */

import '//resources/cr_elements/cr_action_menu/cr_action_menu.js';
import '//resources/cr_elements/cr_icon_button/cr_icon_button.m.js';
import '//resources/cr_elements/icons.m.js';
import '//resources/polymer/v3_0/iron-icon/iron-icon.js';
import '../os_icons.m.js';
import '../../settings_shared_css.js';

import {CrActionMenuElement} from '//resources/cr_elements/cr_action_menu/cr_action_menu.js';
import {FocusRowBehavior} from '//resources/js/cr/ui/focus_row_behavior.m.js';
import {I18nBehavior} from '//resources/js/i18n_behavior.m.js';
import {html, Polymer} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js';

import {BluetoothPageBrowserProxy, BluetoothPageBrowserProxyImpl} from './bluetooth_page_browser_proxy.js';

Polymer({
  _template: html`{__html_template__}`,
  is: 'bluetooth-device-list-item',

  behaviors: [I18nBehavior, FocusRowBehavior],

  properties: {
    /**
     * The bluetooth device.
     * @type {!chrome.bluetooth.Device}
     */
    device: {
      type: Object,
      observer: 'onDeviceChanged_',
    },

    /**
     * The aria-label attribute for the top-level bluetooth-device-list-item
     * element.
     */
    ariaLabel: {
      type: String,
      notify: true,
      computed: 'getAriaLabel_(device)',
    },

    // TODO(crbug.com/1208155) Add managed policy icon that is shown when this
    // flag is true.
    /** @private */
    shouldShowManagedIcon_: {
      type: Boolean,
      value: false,
    },
  },

  hostAttributes: {role: 'button'},

  /** @private {?BluetoothPageBrowserProxy} */
  browserProxy_: null,

  /** @override */
  ready() {
    this.browserProxy_ = BluetoothPageBrowserProxyImpl.getInstance();
  },

  /** @override */
  detached() {
    // Fire an event in case the tooltip was previously showing for the managed
    // icon in this item and this item is being removed.
    this.fireTooltipStateChangeEvent_(/*showTooltip=*/ false);
  },

  /**
   * @param {!Event} event
   * @private
   */
  ignoreEnterKey_(event) {
    if (event.key === 'Enter') {
      event.stopPropagation();
    }
  },

  /** @private */
  tryConnect_() {
    if (!this.isDisconnected_(this.device)) {
      return;
    }

    this.fire('device-event', {
      action: 'connect',
      device: this.device,
    });
  },

  /** @private */
  onClick_() {
    this.tryConnect_();
  },

  /**
   * @param {!KeyboardEvent} e
   * @private
   */
  onKeyDown_(e) {
    if (e.key === 'Enter' || e.key === ' ') {
      this.tryConnect_();
      e.preventDefault();
    }
  },

  /**
   * @param {!Event} event
   * @private
   */
  onMenuButtonTap_(event) {
    const button = /** @type {!HTMLElement} */ (event.target);
    const menu = /** @type {!CrActionMenuElement} */ (this.$.dotsMenu);
    menu.showAt(button);
    event.stopPropagation();
  },

  /** @private */
  onConnectActionTap_() {
    const action = this.isDisconnected_(this.device) ? 'connect' : 'disconnect';
    this.fire('device-event', {
      action: action,
      device: this.device,
    });
    /** @type {!CrActionMenuElement} */ (this.$.dotsMenu).close();
  },

  /** @private */
  onRemoveTap_() {
    this.fire('device-event', {
      action: 'remove',
      device: this.device,
    });
    /** @type {!CrActionMenuElement} */ (this.$.dotsMenu).close();
  },

  /**
   * @param {boolean} connected
   * @return {string} The text to display for the connect/disconnect menu item.
   * @private
   */
  getConnectActionText_(connected) {
    return this.i18n(connected ? 'bluetoothDisconnect' : 'bluetoothConnect');
  },

  /**
   * @param {!chrome.bluetooth.Device} device
   * @return {string} The text to display for |device| in the device list.
   * @private
   */
  getDeviceName_(device) {
    return device.name || device.address;
  },

  /**
   * @param {!chrome.bluetooth.Device} device
   * @return {string} The aria label to use for a |device| that will include the
   * device name and device type if known.
   * @private
   */
  getAriaLabel_(device) {
    // We need to turn the device name, connection status and type into a single
    // localized string.
    // The possible device type enum values can be seen here:
    // https://developer.chrome.com/apps/bluetooth#type-Device.
    // The localization id is computed dynamically to avoid maintaining a
    // mapping from the enum string value to the localization id.
    // if device.type is not defined, we fall back to an unknown device string.
    const deviceName = this.getDeviceName_(device);
    const deviceStatus = this.getConnectionStatusText_(device);

    const a11ydeviceNameAndType = (device.type) ?
        this.i18n('bluetoothDeviceType_' + device.type, deviceName) :
        this.i18n('bluetoothDeviceType_unknown', deviceName);
    return this.i18n(
        'bluetoothDeviceWithConnectionStatus', a11ydeviceNameAndType,
        deviceStatus);
  },

  /**
   * @param {!chrome.bluetooth.Device} device
   * @return {string} The text to display the connection status of |device|.
   * @private
   */
  getConnectionStatusText_(device) {
    if (!this.hasConnectionStatusText_(device)) {
      return '';
    }
    if (device.connecting) {
      return this.i18n('bluetoothConnecting');
    }
    if (!device.connected) {
      return this.i18n('bluetoothNotConnected');
    }
    return device.batteryPercentage !== undefined ?
        this.i18n('bluetoothConnectedWithBattery', device.batteryPercentage) :
        this.i18n('bluetoothConnected');
  },

  /**
   * @param {!chrome.bluetooth.Device} device
   * @return {boolean} True if connection status should be shown as the
   *     secondary text of the |device| in device list.
   * @private
   */
  hasConnectionStatusText_(device) {
    return !!(device.paired || device.connecting);
  },

  /**
   * @param {!chrome.bluetooth.Device} device
   * @return {boolean}
   * @private
   */
  isDisconnected_(device) {
    return !device.connected && !device.connecting;
  },

  /**
   * Returns device type icon's ID corresponding to the given device.
   * To be consistent with the Bluetooth device list in system menu, this
   * mapping needs to be synced with ash::tray::GetBluetoothDeviceIcon().
   *
   * @param {!chrome.bluetooth.Device} device
   * @return {string}
   * @private
   */
  getDeviceIcon_(device) {
    switch (device.type) {
      case 'computer':
        return 'cr:computer';
      case 'phone':
        return 'os-settings:smartphone';
      case 'audio':
      case 'carAudio':
        return 'os-settings:headset';
      case 'video':
        return 'cr:videocam';
      case 'joystick':
      case 'gamepad':
        return 'os-settings:gamepad';
      case 'keyboard':
      case 'keyboardMouseCombo':
        return 'os-settings:keyboard';
      case 'tablet':
        return 'os-settings:tablet';
      case 'mouse':
        return 'os-settings:mouse';
      default:
        return device.connected ? 'os-settings:bluetooth-connected' :
                                  'cr:bluetooth';
    }
  },

  /**
   * @param {?chrome.bluetooth.Device} newValue
   * @param {?chrome.bluetooth.Device} oldValue
   * @private
   */
  onDeviceChanged_(newValue, oldValue) {
    if (!newValue) {
      this.shouldShowManagedIcon_ = false;
      return;
    }

    this.browserProxy_.isDeviceBlockedByPolicy(newValue.address)
        .then((isBlocked) => {
          this.shouldShowManagedIcon_ = isBlocked;
          if (!this.shouldShowManagedIcon_) {
            // Fire an event in case the tooltip was previously showing for this
            // icon and this icon now is hidden.
            this.fireTooltipStateChangeEvent_(/*showTooltip=*/ false);
          }
        });
  },

  /** @private */
  onShowTooltip_: function() {
    this.fireTooltipStateChangeEvent_(/*showTooltip=*/ true);
  },

  /**
   * @param {boolean} showTooltip
   */
  fireTooltipStateChangeEvent_(showTooltip) {
    this.fire('blocked-tooltip-state-change', {
      address: this.device.address,
      show: showTooltip,
      element: showTooltip ? this.$$('#managedIcon') : undefined,
    });
  },
});


text:
const Utils = require('../../../../utils');
const BaseAssertion = require('../_baseAssertion.js');

class ExpectElement extends BaseAssertion {
  /**
   * @override
   */
  onResultSuccess() {}

  /**
   * @override
   */
  onResultFailed() {}

  onPromiseResolved(value) {
    if (value) {
      if (Utils.isObject(value) && value.elementId) {
        this.elementId = value.elementId;
      } else {
        this.elementId = this.transport.getElementId(value);
      }
    }

    super.onPromiseResolved();
  }

  formatMessage() {
    let {selector} = this.element;
    if (!selector) {
      selector = this.element.toString();
    }

    this.message = Utils.format(this.message, selector, this.elapsedTime);

    super.formatMessage();
  }

  /**
   *
   * @param {String} protocolAction
   * @param {Array} [args]
   * @return {Promise}
   */
  executeProtocolAction(protocolAction, args = []) {
    if (!Array.isArray(args)) {
      args = [args];
    }

    const {sessionId} = this.emitter;
    args.unshift(this.elementId);

    if (sessionId) {
      return this.transportActions[protocolAction](args, sessionId);
    }

    return this.transportActions[protocolAction](...args);
  }

  retryCommand() {
    if (this.shouldRetryLocateElement()) {
      this.promise = this.emitter.createRetryPromise();
      this.promise.then(this.onPromiseResolved.bind(this), this.onPromiseRejected.bind(this));
      this.emitter.retryCommand();
    } else {
      this.onPromiseResolved();
    }
  }

  shouldRetryLocateElement() {
    return (!this.elementId || this.stateElementReference(this.resultStatus) || this.stateElementReference(this.resultErrorStatus));
  }

  stateElementReference(errorStatus) {
    return this.transport.staleElementReference({
      errorStatus
    });
  }
}

module.exports = ExpectElement;


text:
"""QuizStatistics API Version 1.0.

This API client was generated using a template. Make sure this code is valid before using it.
"""
import logging
from datetime import date, datetime
from base import BaseCanvasAPI
from base import BaseModel

class QuizStatisticsAPI(BaseCanvasAPI):
    """QuizStatistics API Version 1.0."""

    def __init__(self, *args, **kwargs):
        """Init method for QuizStatisticsAPI."""
        super(QuizStatisticsAPI, self).__init__(*args, **kwargs)
        self.logger = logging.getLogger("pycanvas.QuizStatisticsAPI")

    def fetching_latest_quiz_statistics(self, quiz_id, course_id, all_versions=None):
        """
        Fetching the latest quiz statistics.

        This endpoint provides statistics for all quiz versions, or for a specific
        quiz version, in which case the output is guaranteed to represent the
        _latest_ and most current version of the quiz.

        <b>200 OK</b> response code is returned if the request was successful.
        """
        path = {}
        data = {}
        params = {}

        # REQUIRED - PATH - course_id
        """ID"""
        path["course_id"] = course_id

        # REQUIRED - PATH - quiz_id
        """ID"""
        path["quiz_id"] = quiz_id

        # OPTIONAL - all_versions
        """Whether the statistics report should include all submissions attempts."""
        if all_versions is not None:
            params["all_versions"] = all_versions

        self.logger.debug("GET /api/v1/courses/{course_id}/quizzes/{quiz_id}/statistics with query params: {params} and form data: {data}".format(params=params, data=data, **path))
        return self.generic_request("GET", "/api/v1/courses/{course_id}/quizzes/{quiz_id}/statistics".format(**path), data=data, params=params, no_data=True)

class Quizstatisticsquestionstatistics(BaseModel):
    """Quizstatisticsquestionstatistics Model.
    Statistics for submissions made to a specific quiz question."""

    def __init__(self, responses=None, answers=None):
        """Init method for Quizstatisticsquestionstatistics class."""
        self._responses = responses
        self._answers = answers

        self.logger = logging.getLogger('pycanvas.Quizstatisticsquestionstatistics')

    @property
    def responses(self):
        """Number of students who have provided an answer to this question. Blank or empty responses are not counted."""
        return self._responses

    @responses.setter
    def responses(self, value):
        """Setter for responses property."""
        self.logger.warn("Setting values on responses will NOT update the remote Canvas instance.")
        self._responses = value

    @property
    def answers(self):
        """Statistics related to each individual pre-defined answer."""
        return self._answers

    @answers.setter
    def answers(self, value):
        """Setter for answers property."""
        self.logger.warn("Setting values on answers will NOT update the remote Canvas instance.")
        self._answers = value

class Quizstatistics(BaseModel):
    """Quizstatistics Model."""

    def __init__(self, id, quiz_id, question_statistics=None, links=None, multiple_attempts_exist=None, url=None, html_url=None, submission_statistics=None, generated_at=None, includes_all_versions=None):
        """Init method for Quizstatistics class."""
        self._question_statistics = question_statistics
        self._links = links
        self._multiple_attempts_exist = multiple_attempts_exist
        self._url = url
        self._html_url = html_url
        self._submission_statistics = submission_statistics
        self._generated_at = generated_at
        self._quiz_id = quiz_id
        self._includes_all_versions = includes_all_versions
        self._id = id

        self.logger = logging.getLogger('pycanvas.Quizstatistics')

    @property
    def question_statistics(self):
        """Question-specific statistics for each question and its answers."""
        return self._question_statistics

    @question_statistics.setter
    def question_statistics(self, value):
        """Setter for question_statistics property."""
        self.logger.warn("Setting values on question_statistics will NOT update the remote Canvas instance.")
        self._question_statistics = value

    @property
    def links(self):
        """JSON-API construct that contains links to media related to this quiz statistics object.
NOTE: AVAILABLE ONLY IN JSON-API REQUESTS."""
        return self._links

    @links.setter
    def links(self, value):
        """Setter for links property."""
        self.logger.warn("Setting values on links will NOT update the remote Canvas instance.")
        self._links = value

    @property
    def multiple_attempts_exist(self):
        """Whether there are any students that have made mutliple submissions for this quiz."""
        return self._multiple_attempts_exist

    @multiple_attempts_exist.setter
    def multiple_attempts_exist(self, value):
        """Setter for multiple_attempts_exist property."""
        self.logger.warn("Setting values on multiple_attempts_exist will NOT update the remote Canvas instance.")
        self._multiple_attempts_exist = value

    @property
    def url(self):
        """The API HTTP/HTTPS URL to this quiz statistics."""
        return self._url

    @url.setter
    def url(self, value):
        """Setter for url property."""
        self.logger.warn("Setting values on url will NOT update the remote Canvas instance.")
        self._url = value

    @property
    def html_url(self):
        """The HTTP/HTTPS URL to the page where the statistics can be seen visually."""
        return self._html_url

    @html_url.setter
    def html_url(self, value):
        """Setter for html_url property."""
        self.logger.warn("Setting values on html_url will NOT update the remote Canvas instance.")
        self._html_url = value

    @property
    def submission_statistics(self):
        """Question-specific statistics for each question and its answers."""
        return self._submission_statistics

    @submission_statistics.setter
    def submission_statistics(self, value):
        """Setter for submission_statistics property."""
        self.logger.warn("Setting values on submission_statistics will NOT update the remote Canvas instance.")
        self._submission_statistics = value

    @property
    def generated_at(self):
        """The time at which the statistics were generated, which is usually after the occurrence of a quiz event, like a student submitting it."""
        return self._generated_at

    @generated_at.setter
    def generated_at(self, value):
        """Setter for generated_at property."""
        self.logger.warn("Setting values on generated_at will NOT update the remote Canvas instance.")
        self._generated_at = value

    @property
    def quiz_id(self):
        """The ID of the Quiz the statistics report is for.
NOTE: AVAILABLE ONLY IN NON-JSON-API REQUESTS."""
        return self._quiz_id

    @quiz_id.setter
    def quiz_id(self, value):
        """Setter for quiz_id property."""
        self.logger.warn("Setting values on quiz_id will NOT update the remote Canvas instance.")
        self._quiz_id = value

    @property
    def includes_all_versions(self):
        """In the presence of multiple attempts, this field describes whether the statistics describe all the submission attempts and not only the latest ones."""
        return self._includes_all_versions

    @includes_all_versions.setter
    def includes_all_versions(self, value):
        """Setter for includes_all_versions property."""
        self.logger.warn("Setting values on includes_all_versions will NOT update the remote Canvas instance.")
        self._includes_all_versions = value

    @property
    def id(self):
        """The ID of the quiz statistics report."""
        return self._id

    @id.setter
    def id(self, value):
        """Setter for id property."""
        self.logger.warn("Setting values on id will NOT update the remote Canvas instance.")
        self._id = value

class Quizstatisticsanswerpointbiserial(BaseModel):
    """Quizstatisticsanswerpointbiserial Model.
    A point-biserial construct for a single pre-defined answer in a Multiple-Choice or True/False question."""

    def __init__(self, point_biserial=None, distractor=None, correct=None, answer_id=None):
        """Init method for Quizstatisticsanswerpointbiserial class."""
        self._point_biserial = point_biserial
        self._distractor = distractor
        self._correct = correct
        self._answer_id = answer_id

        self.logger = logging.getLogger('pycanvas.Quizstatisticsanswerpointbiserial')

    @property
    def point_biserial(self):
        """The point biserial value for this answer. Value ranges between -1 and 1."""
        return self._point_biserial

    @point_biserial.setter
    def point_biserial(self, value):
        """Setter for point_biserial property."""
        self.logger.warn("Setting values on point_biserial will NOT update the remote Canvas instance.")
        self._point_biserial = value

    @property
    def distractor(self):
        """Convenience attribute that denotes whether this is a distractor answer and not the correct one. This is mutually exclusive with the `correct` value."""
        return self._distractor

    @distractor.setter
    def distractor(self, value):
        """Setter for distractor property."""
        self.logger.warn("Setting values on distractor will NOT update the remote Canvas instance.")
        self._distractor = value

    @property
    def correct(self):
        """Convenience attribute that denotes whether this is the correct answer as opposed to being a distractor. This is mutually exclusive with the `distractor` value."""
        return self._correct

    @correct.setter
    def correct(self, value):
        """Setter for correct property."""
        self.logger.warn("Setting values on correct will NOT update the remote Canvas instance.")
        self._correct = value

    @property
    def answer_id(self):
        """ID of the answer the point biserial is for."""
        return self._answer_id

    @answer_id.setter
    def answer_id(self, value):
        """Setter for answer_id property."""
        self.logger.warn("Setting values on answer_id will NOT update the remote Canvas instance.")
        self._answer_id = value

class Quizstatisticsanswerstatistics(BaseModel):
    """Quizstatisticsanswerstatistics Model.
    Statistics for a specific pre-defined answer in a Multiple-Choice or True/False quiz question."""

    def __init__(self, text=None, id=None, weight=None, responses=None):
        """Init method for Quizstatisticsanswerstatistics class."""
        self._text = text
        self._id = id
        self._weight = weight
        self._responses = responses

        self.logger = logging.getLogger('pycanvas.Quizstatisticsanswerstatistics')

    @property
    def text(self):
        """The text attached to the answer."""
        return self._text

    @text.setter
    def text(self, value):
        """Setter for text property."""
        self.logger.warn("Setting values on text will NOT update the remote Canvas instance.")
        self._text = value

    @property
    def id(self):
        """ID of the answer."""
        return self._id

    @id.setter
    def id(self, value):
        """Setter for id property."""
        self.logger.warn("Setting values on id will NOT update the remote Canvas instance.")
        self._id = value

    @property
    def weight(self):
        """An integer to determine correctness of the answer. Incorrect answers should be 0, correct answers should be non-negative."""
        return self._weight

    @weight.setter
    def weight(self, value):
        """Setter for weight property."""
        self.logger.warn("Setting values on weight will NOT update the remote Canvas instance.")
        self._weight = value

    @property
    def responses(self):
        """Number of students who have chosen this answer."""
        return self._responses

    @responses.setter
    def responses(self, value):
        """Setter for responses property."""
        self.logger.warn("Setting values on responses will NOT update the remote Canvas instance.")
        self._responses = value

class Quizstatisticslinks(BaseModel):
    """Quizstatisticslinks Model.
    Links to media related to QuizStatistics."""

    def __init__(self, quiz=None):
        """Init method for Quizstatisticslinks class."""
        self._quiz = quiz

        self.logger = logging.getLogger('pycanvas.Quizstatisticslinks')

    @property
    def quiz(self):
        """HTTP/HTTPS API URL to the quiz this statistics describe."""
        return self._quiz

    @quiz.setter
    def quiz(self, value):
        """Setter for quiz property."""
        self.logger.warn("Setting values on quiz will NOT update the remote Canvas instance.")
        self._quiz = value

class Quizstatisticssubmissionstatistics(BaseModel):
    """Quizstatisticssubmissionstatistics Model.
    Generic statistics for all submissions for a quiz."""

    def __init__(self, duration_average=None, score_average=None, score_low=None, incorrect_count_average=None, unique_count=None, score_high=None, scores=None, correct_count_average=None, score_stdev=None):
        """Init method for Quizstatisticssubmissionstatistics class."""
        self._duration_average = duration_average
        self._score_average = score_average
        self._score_low = score_low
        self._incorrect_count_average = incorrect_count_average
        self._unique_count = unique_count
        self._score_high = score_high
        self._scores = scores
        self._correct_count_average = correct_count_average
        self._score_stdev = score_stdev

        self.logger = logging.getLogger('pycanvas.Quizstatisticssubmissionstatistics')

    @property
    def duration_average(self):
        """The average time spent by students while taking the quiz."""
        return self._duration_average

    @duration_average.setter
    def duration_average(self, value):
        """Setter for duration_average property."""
        self.logger.warn("Setting values on duration_average will NOT update the remote Canvas instance.")
        self._duration_average = value

    @property
    def score_average(self):
        """The mean of the student submission scores."""
        return self._score_average

    @score_average.setter
    def score_average(self, value):
        """Setter for score_average property."""
        self.logger.warn("Setting values on score_average will NOT update the remote Canvas instance.")
        self._score_average = value

    @property
    def score_low(self):
        """The lowest submission score."""
        return self._score_low

    @score_low.setter
    def score_low(self, value):
        """Setter for score_low property."""
        self.logger.warn("Setting values on score_low will NOT update the remote Canvas instance.")
        self._score_low = value

    @property
    def incorrect_count_average(self):
        """The mean of the number of questions answered incorrectly by each student."""
        return self._incorrect_count_average

    @incorrect_count_average.setter
    def incorrect_count_average(self, value):
        """Setter for incorrect_count_average property."""
        self.logger.warn("Setting values on incorrect_count_average will NOT update the remote Canvas instance.")
        self._incorrect_count_average = value

    @property
    def unique_count(self):
        """The number of students who have taken the quiz."""
        return self._unique_count

    @unique_count.setter
    def unique_count(self, value):
        """Setter for unique_count property."""
        self.logger.warn("Setting values on unique_count will NOT update the remote Canvas instance.")
        self._unique_count = value

    @property
    def score_high(self):
        """The highest submission score."""
        return self._score_high

    @score_high.setter
    def score_high(self, value):
        """Setter for score_high property."""
        self.logger.warn("Setting values on score_high will NOT update the remote Canvas instance.")
        self._score_high = value

    @property
    def scores(self):
        """A percentile distribution of the student scores, each key is the percentile (ranges between 0 and 100%) while the value is the number of students who received that score."""
        return self._scores

    @scores.setter
    def scores(self, value):
        """Setter for scores property."""
        self.logger.warn("Setting values on scores will NOT update the remote Canvas instance.")
        self._scores = value

    @property
    def correct_count_average(self):
        """The mean of the number of questions answered correctly by each student."""
        return self._correct_count_average

    @correct_count_average.setter
    def correct_count_average(self, value):
        """Setter for correct_count_average property."""
        self.logger.warn("Setting values on correct_count_average will NOT update the remote Canvas instance.")
        self._correct_count_average = value

    @property
    def score_stdev(self):
        """Standard deviation of the submission scores."""
        return self._score_stdev

    @score_stdev.setter
    def score_stdev(self, value):
        """Setter for score_stdev property."""
        self.logger.warn("Setting values on score_stdev will NOT update the remote Canvas instance.")
        self._score_stdev = value


text:
package org.springframework.jdbc.core;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.dao.DataAccessException;

/**
 * Callback interface used by {@link JdbcTemplate}'s query methods.
 * Implementations of this interface perform the actual work of extracting
 * results from a {@link java.sql.ResultSet}, but don't need to worry
 * about exception handling. {@link java.sql.SQLException SQLExceptions}
 * will be caught and handled by the calling JdbcTemplate.
 *
 *
This interface is mainly used within the JDBC framework itself.
 * A {@link RowMapper} is usually a simpler choice for ResultSet processing,
 * mapping one result object per row instead of one result object for
 * the entire ResultSet.
 *
 *
Note: In contrast to a {@link RowCallbackHandler}, a ResultSetExtractor
 * object is typically stateless and thus reusable, as long as it doesn't
 * access stateful resources (such as output streams when streaming LOB
 * contents) or keep result state within the object.
 *
 * @author Rod Johnson
 * @author Juergen Hoeller
 * @since April 24, 2003
 * @see JdbcTemplate
 * @see RowCallbackHandler
 * @see RowMapper
 * @see org.springframework.jdbc.core.support.AbstractLobStreamingResultSetExtractor
 */
public interface ResultSetExtractor {

	/**
	 * Implementations must implement this method to process the entire ResultSet.
	 * @param rs ResultSet to extract data from. Implementations should
	 * not close this: it will be closed by the calling JdbcTemplate.
	 * @return an arbitrary result object, or null if none
	 * (the extractor will typically be stateful in the latter case).
	 * @throws SQLException if a SQLException is encountered getting column
	 * values or navigating (that is, there's no need to catch SQLException)
	 * @throws DataAccessException in case of custom exceptions
	 */
	Object extractData(ResultSet rs) throws SQLException, DataAccessException;

}


text:
package gce

// MigLister is a mig listing interface
type MigLister interface {
	// GetMigs returns the list of migs
	GetMigs() []Mig
	// HandleMigIssue handles an issue with a given mig
	HandleMigIssue(migRef GceRef, err error)
}

type migLister struct {
	cache *GceCache
}

// NewMigLister returns an instance of migLister
func NewMigLister(cache *GceCache) *migLister {
	return &migLister{
		cache: cache,
	}
}

// GetMigs returns the list of migs
func (l *migLister) GetMigs() []Mig {
	return l.cache.GetMigs()
}

// HandleMigIssue handles an issue with a given mig
func (l *migLister) HandleMigIssue(_ GceRef, _ error) {
}


text:
{{'Position' | localize}}:

            1.d4
            d5(e6!)
            2.h3

        <button ng-click="back()" ng-show="moveNumber!=0"> « </button>
        <button ng-click="switchOrientation()"> ↕ </button>
        <button ng-click="reload()" ng-show="moveNumber!=0"> ↻ </button>


text:
			<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
				Toggle navigation

			</button>
			iPot

Stoner Diary

				<button type="button" class="btn btn-danger navbar-btn">logout</button>

				<input class="form-control" type="text" placeholder="Search diary" />

									Collapsible Group Item #1

									Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.


text:
package com.gson8.floatingballwindow;

/*
 * FloatingBallWindow making by Syusuke/琴声悠扬 on 2016/6/1
 * E-Mail: Zyj7810@126.com
 * Package: com.gson8.floatingballwindow.PopupService
 * Description: null
 */

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class PopupService extends Service implements View.OnClickListener {

    /**
     * 控件window
     */
    private FloatingView mFloatingWindow;

    /**
     * 两个状态的View
     */
    private View mFloatView;
    private View mPopupView;

    /**
     * 相关控件
     */
    private TextView mTvShowShotTime;

    private ImageView mIvShotGif;
    private ImageView mIvShotVideo;
    private ImageView mIvShotFolder;
    private ImageView mIvShotSettings;

    @Override
    public IBinder onBind(Intent intent) {
        return new PopupBinder();
    }

    public class PopupBinder extends Binder {
        public PopupService getService() {
            return PopupService.this;
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();

        initFloatingWindow();

    }

    private void initFloatingWindow() {
        mFloatView = LayoutInflater.from(this).inflate(R.layout.folating_view, null);
        mPopupView = LayoutInflater.from(this).inflate(R.layout.popup_view, null);

        mTvShowShotTime = (TextView) mFloatView.findViewById(R.id.id_show_shot_time);

        mIvShotGif = (ImageView) mPopupView.findViewById(R.id.id_pop_shot_gif);
        mIvShotVideo = (ImageView) mPopupView.findViewById(R.id.id_pop_shot_video);
        mIvShotFolder = (ImageView) mPopupView.findViewById(R.id.id_pop_shot_folder);
        mIvShotSettings = (ImageView) mPopupView.findViewById(R.id.id_pop_shot_settings);

        mIvShotGif.setOnClickListener(this);
        mIvShotVideo.setOnClickListener(this);
        mIvShotFolder.setOnClickListener(this);
        mIvShotSettings.setOnClickListener(this);

        mFloatingWindow = new FloatingView(this);
        mFloatingWindow.setFloatingView(mFloatView);
        mFloatingWindow.setPopupView(mPopupView);
    }

    public void show() {
        if(null != mFloatingWindow)
            mFloatingWindow.show();
    }

    public void dimiss() {
        if(null != mFloatingWindow)
            mFloatingWindow.dismiss();
    }

    @Override
    public void onClick(View v) {
        switch(v.getId()) {
            case R.id.id_pop_shot_gif:
                Toast.makeText(this, "gif", Toast.LENGTH_SHORT).show();
                break;
            case R.id.id_pop_shot_video:
                Toast.makeText(this, "video", Toast.LENGTH_SHORT).show();
                break;
            case R.id.id_pop_shot_folder:
                Toast.makeText(this, "folder", Toast.LENGTH_SHORT).show();
                break;
            case R.id.id_pop_shot_settings:
                Toast.makeText(this, "settings", Toast.LENGTH_SHORT).show();
                break;
            default:
                break;
        }
        mFloatingWindow.turnMini();
    }

}


text:
export class ProfileModel {
    displayName: string;
    firstName: string;
    lastName: string;
    email: string;
    profileImageURL: string;
    provider: string;
    title: string;
}


text:
const TradingAnalysis = () =>
  (typeof window.TradingAnalysis !== 'undefined' ? window.TradingAnalysis : {
    request: () => {},
    digit_info: () => {},
    set_digit_info: () => {},
    japan_info: () => {},
    getActiveTab: () => {},
    bindAnalysisTabEvent: () => {},
  });

export default TradingAnalysis;