text:
using EnvDTE;
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;

namespace AfominDotCom.NgProjectTemplate.Wizards
{
    public static class NgWizardHelper
    {
        // private const string NgVersionSuccessFragment = "@angular/cli";
        private const string NgVersionSuccessFragment1 = "angular";
        private const string NgVersionSuccessFragment2 = "cli";
        internal const string GitignoreFileName = ".gitignore";
        internal const string GitignoreTempFileName = ".gitignore.temp";
        internal const string PackageJsonFileName = "package.json";
        internal const string PackageJsonOldFileName = "package.json.old";
        internal const string AngularCliJsonFileName = ".angular-cli.json";
        internal const string AngularJsonFileName = "angular.json";
        internal const string TsconfigJsonFileName = "tsconfig.json";
        internal const string TsconfigJsonOldFileName = "tsconfig.json.old";
        internal const string StartupCsFileName = "Startup.cs";
        internal const string NgFoundLogFileName = "ErrorNgNotFound.txt";

        private static string RunCmd(string arguments, string workingDirectory, bool createNoWindow, bool redirectStandardOutput)
        {
            string output = null;
            var startInfo = new ProcessStartInfo
            {
                FileName = "cmd.exe",
                Arguments = arguments,
                WorkingDirectory = workingDirectory,
                UseShellExecute = false,
                CreateNoWindow = createNoWindow,
                RedirectStandardOutput = redirectStandardOutput,
            };
            using (var process = System.Diagnostics.Process.Start(startInfo))
            {
                if (redirectStandardOutput)
                {
                    output = process.StandardOutput.ReadToEnd();
                }
                process.WaitForExit();
            }
            return output;
        }

        private static string RunNgVersion(string workingDirectory)
        {
            var cmdArguments = "/c ng --version";
            return RunCmd(cmdArguments, workingDirectory, true, true);
        }

        internal static string RunNgNew(string projectDirectory, string projectName, bool addRouting, bool isNgFound)
        {
            var path = projectDirectory.EndsWith("\\") ? projectDirectory : string.Concat(projectDirectory, "\\");
            var directoryInfo = Directory.GetParent(path);
            var parentDirectory = directoryInfo.Parent.FullName;
            var directory = directoryInfo.Name;

            var routingOption = addRouting ? " --routing" : "";

            // CMD writes errors to the StandardError stream. NG writes errors to StandardOutput.
            // To read both the streams is possible but needs extra effots to avoid a thread deadlock.
            // If NG was not found, we display the Command Window to the user to watch the errors.
            var cmdArguments = $"/c ng new {projectName} --directory {directory}{routingOption} --skip-git --skip-install"
                + (isNgFound ? "" : " & timeout /t 10");

            return RunCmd(cmdArguments, parentDirectory, isNgFound, isNgFound);
        }

        /// <summary>
        ///  Test if @angular/cli is installed globally.
        /// </summary>
        /// <param name="preferredDirectory">Prefererred directory</param>
        /// <returns></returns>
        internal static bool IsNgFound(string preferredDirectory)
        {
            // Be optimistic. Missing target is better than false alarm. We will check the result of "ng new" anyway.
            var isNgFound = true;
            var desktopDirectory = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
            var workingDirectory = Directory.Exists(preferredDirectory)
                ? preferredDirectory
                : (Directory.Exists(desktopDirectory) ? desktopDirectory : null);
            string ngVersionOutput = String.Empty;
            var start = DateTime.Now;
            if (!String.IsNullOrEmpty(workingDirectory))
            {
                ngVersionOutput = RunNgVersion(workingDirectory);
                // Old versions of CLI ~1.1 (actually chalk / supports-color) on Windows 7 fail when the output stream is redirected. ngVersionOutput is null/empty in that case.
                isNgFound = !String.IsNullOrEmpty(ngVersionOutput);
                if (isNgFound)
                {
                    var lowerCaseOutput = ngVersionOutput.ToLower();
                    isNgFound = lowerCaseOutput.Contains(NgVersionSuccessFragment1)
                        && lowerCaseOutput.Contains(NgVersionSuccessFragment2);
                }
            }
            return isNgFound;
        }

        //public static ProjectItem FindProjectItem(Project project, string fileName)
        //{
        //    ProjectItem projectItem = null;
        //    if (project != null)
        //    {
        //        foreach (var i in project.ProjectItems)
        //        {
        //            if (i is ProjectItem item)
        //            {
        //                var itemName = item.Name;
        //                if (itemName.Equals(fileName, StringComparison.OrdinalIgnoreCase))
        //                {
        //                    projectItem = item;
        //                    break;
        //                }
        //            }
        //        }
        //    }
        //    return projectItem;
        //}

        internal static bool FindFileInRootDir(Project project, string fileName)
        {
            return FindFileInRootDir(project, fileName, out string filePath);
        }

        internal static bool FindFileInRootDir(Project project, string fileName, out string filePath)
        {
            filePath = null;
            if (project != null)
            {
                var projectDirectory = Path.GetDirectoryName(project.FullName);
                if (Directory.Exists(projectDirectory))
                {
                    var path = Path.Combine(projectDirectory, fileName);
                    if (File.Exists(path))
                    {
                        filePath = path;
                        return true;
                    }
                }
            }
            return false;
        }

        internal static Version GetVersion()
        {
            return typeof(AfominDotCom.NgProjectTemplate.Wizards.NgWizardHelper).Assembly.GetName().Version;
        }

        internal static bool FindWindow(Project project, string filePath)
        {
            return FindWindow(project, filePath, out EnvDTE.Window window);
        }

        internal static bool FindWindow(Project project, string filePath, out EnvDTE.Window window)
        {
            window = null;
            var windows = project.DTE.Windows;
            foreach (var w in windows)
            {
                if (w is EnvDTE.Window wnd)
                {
                    var projectItem = wnd.ProjectItem;
                    if ((projectItem != null) && (projectItem.FileCount != 0) /* && window.Type == vsWindowType.vsWindowTypeDocument */)
                    {
                        var fileName = projectItem.FileNames[1]; // 1-based array
                        if (fileName == filePath)
                        {
                            window = wnd;
                            return true;
                        }
                    }
                }
            }
            return false;
        }

        //internal static bool FindAndCloseWindow(Project project, string filePath, vsSaveChanges saveChanges)
        //{
        //    if (FindWindow(project, filePath, out Window window))
        //    {
        //        window.Close(saveChanges);
        //        return true;
        //    }
        //    return false;
        //}

        internal static void RewriteFile(string filePath, string fileContents)
        {
            // Don't do: File.WriteAllText(filePath, result.ToString(), System.Text.Encoding.UTF8); // That writes a BOM. BOM causes Webpack to fail.
            var bytes = Encoding.UTF8.GetBytes(fileContents);
            using (var memoryStream = new MemoryStream(bytes))
            {
                using (var fileStream = new FileStream(filePath, FileMode.Truncate, FileAccess.Write))
                {
                    memoryStream.CopyTo(fileStream);
                }
            }
        }

        internal static bool IsAspNetCore2(Project project)
        {
            var filePath = project?.FullName;
            if (File.Exists(filePath))
            {
                var lines = File.ReadAllLines(filePath);
                var isCoreVersion2x = lines
                    .Where(i => i.Contains("<TargetFramework>") && i.Contains("netcoreapp2."))
                    .Any()
                    ;
                //var isAspNetCore20 = lines
                //    .Where(i => i.Contains("<PackageReference") && i.Contains("\"Microsoft.AspNetCore.") && i.Contains("\"2."))
                //    .Any()
                //    ;
                // ASP.NET Core 2.0 used Microsoft.AspNetCore.All version 2.x. ASP.NET Core 2.1 uses Microsoft.AspNetCore.App without a version specified.
                var isAspNetCore = lines
                    .Where(i => i.Contains("<PackageReference") && i.Contains("\"Microsoft.AspNetCore."))
                    .Any()
                    ;
                return isCoreVersion2x && isAspNetCore;
            }
            return false;
        }

        internal static bool IsNpmAngularFound(string packageJsonFilePath)
        {
            if (File.Exists(packageJsonFilePath))
            {
                var lines = File.ReadAllLines(packageJsonFilePath);
                var isNpmAngularFound = lines
                  .Where(i => i.Contains("@angular/core"))
                  // Although the JSON standard demands double quotes, let's be paranoid.
                  .Select(i => i.Replace("'", "\""))
                  .Where(i => i.Contains("\"@angular/core\""))
                  .Any()
                  ;
                return isNpmAngularFound;
            }
            return false;
        }

        internal static bool IsFileOpened(Project project, string fileName)
        {
            if (FindFileInRootDir(project, fileName, out string filePath))
            {
                return FindWindow(project, filePath);
            }
            return false;
        }

    }
}


text:
<?php

namespace DvsaCommon\Csv;

use DvsaCommon\Date\DateUtils;
use Zend\Http\Headers;
use Zend\Http\PhpEnvironment;

class MotTestLogCsvGenerator
{

    const DATETIME_FORMAT = 'd/m/Y H:i:s';
    const DATETIME_FORMAT_EMERG = 'd/m/Y';

    /** @var string */
    protected $filename;

    /** @var resource */
    protected $csvHandle;

    /** @var array */
    protected $columnHeadings;

    /** @var PhpEnvironment\Response  */
    protected $response;

    public function __construct(PhpEnvironment\Response $response = null)
    {
        $this->response = $response ?? new PhpEnvironment\Response();
    }

    /**
     * @return string
     */
    public function getFilename()
    {
        return $this->filename;
    }

    /**
     * @param string $filename
     *
     * @return void
     */
    public function setFilename($filename)
    {
        $this->filename = $filename;
    }

    /**
     * @return resource
     */
    public function getCsvHandle()
    {
        return $this->csvHandle;
    }

    /**
     * @param resource $csvHandle
     *
     * @return void
     */
    public function setCsvHandle($csvHandle)
    {
        $this->csvHandle = $csvHandle;
    }

    /**
     * @return array|null
     */
    public function getColumnHeadings()
    {
        return $this->columnHeadings;
    }

    /**
     * @param array $columnHeadings
     *
     * @return void
     */
    public function setColumnHeadings($columnHeadings)
    {
        $this->columnHeadings = $columnHeadings;
    }

    /**
     * @return PhpEnvironment\Response
     */
    public function getResponse()
    {
        return $this->response;
    }

    /**
     * @return void
     */
    public function open()
    {
        $headers = (new Headers())->addHeaders([
            'Content-Type' => 'text/csv; charset=utf-8',
            'Content-Disposition' => 'attachment; filename="'.$this->filename.'"',
            'Accept-Ranges' => 'bytes',
            'Cache-Control' => 'no-cache, no-store, max-age=0, must-revalidate',
            'Pragma' => 'no-cache',
        ]);

        $this->response->setHeaders($headers);
        $this->response->sendHeaders();

        $this->csvHandle = fopen('php://output', 'w');

        if (!empty($this->columnHeadings)) {
            fputcsv($this->csvHandle, $this->columnHeadings);
            flush();
        }
    }

    /**
     * @param array $rows
     *
     * @return void
     */
    public function addRows(array $rows)
    {
        foreach ($rows as $row) {
            //  --  date time format for emergency test --
            $testDateFormat = (empty($row['emCode']) ? self::DATETIME_FORMAT : self::DATETIME_FORMAT_EMERG);

            //  --  convert to local time zone  --
            $row['testDateTime'] = DateUtils::toUserTz(new \DateTime($row['testDateTime']))->format($testDateFormat);

            $emRecDateTime = $row['emRecDateTime'];
            if ($emRecDateTime !== null) {
                $row['emRecDateTime'] = DateUtils::toUserTz(new \DateTime($emRecDateTime))
                    ->format(self::DATETIME_FORMAT);
            }

            // Only print primary IP address
            if (isset($row['startedClientIp'])) {
                $ips = explode(', ', $row['startedClientIp']);
                $row['startedClientIp'] = $ips[0];
            }

            if (isset($row['completedClientIp'])) {
                $ips = explode(', ', $row['completedClientIp']);
                $row['completedClientIp'] = $ips[0];
            }

            //="formula" hack preventing Excel from converting columns to Date or Number
            $row['vehicleModel'] = '="'.$row['vehicleModel'].'"';
            $row['testNumber'] = '="'.$row['testNumber'].'"';

            // VIN must use ="<vin>" to prevent Excel truncating numeric VIN longer than 15 digits
            $row['vehicleVIN'] = '="'.$row['vehicleVIN'].'"';

            fputcsv($this->csvHandle, $row);
        }

        flush();
    }

    /**
     * @return void
     */
    public function close()
    {
        fclose($this->csvHandle);
    }
}

redpajama_set_name: RedPajamaGithub


text:
__author__ = 'Gino'

import os
import time

from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait

from common import domain

# Parametrizing the sleep allow me to set run "more defensive" tests when I don' care about speed
SMALL_WAIT = float(os.getenv('SELENIUM_SMALL_WAIT', 2))
MEDIUM_WAIT = float(os.getenv('SELENIUM_MEDIUM_WAIT', 4))
LONG_WAIT = float(os.getenv('SELENIUM_LONG_WAIT', 7))
EXTRA_LONG_WAIT = float(os.getenv('SELENIUM_EXTRA_LONG_WAIT', 11))

class Wait_for_page_load(object):
    def __init__(self, browser):
        self.browser = browser

    def __enter__(self):
        self.old_page = self.browser.find_element_by_tag_name('html')

    def page_has_loaded(self):
        new_page = self.browser.find_element_by_tag_name('html')
        return new_page.id != self.old_page.id

    def __exit__(self, *_):
        wait_for(self.page_has_loaded)

def wait_for_condition_to_be_bigger(condition_function, number):
    start_time = time.time()
    while time.time() < start_time + 14:
        if condition_function() > number:
            return True
        else:
            time.sleep(0.1)
    raise Exception('Timeout waiting for {}'.format(condition_function.__name__))

def wait_for_element_to_be_present(driver, element, timeout=20):
    WebDriverWait(driver, timeout).until(
        EC.presence_of_element_located((element['by'], element['locator']))
    )

def is_element_present(driver, element, timeout=3):
    return element_is_visible(driver, element['by'], element['locator'], time)

# WORK IN PROGRESS

def get_element_when_ready(driver, by, locator, timeout=5, multiple_elements=False, retry=True):
    if element_is_visible(driver, by, locator, timeout):
        if multiple_elements:
            return driver.find_elements(by, locator)
        else:
            return driver.find_element(by, locator)
    else:
        if retry:
            return get_element_when_ready(driver, by, locator, timeout, multiple_elements, retry=False)
        else:
            return False

def element_is_visible(driver, by, locator, timeout):
    try:
        WebDriverWait(driver, timeout).until(EC.visibility_of_element_located((by, locator)))
        return True
    except TimeoutException:
        return False

def element_is_not_visible(driver, by, locator, timeout=8):
    try:
        WebDriverWait(driver, timeout).until_not(EC.visibility_of_element_located((by, locator)))
        return False
    except TimeoutException:
        return False

def set_window_size_big(driver):
    SIZE_BIG = (1200, 900)
    driver.set_window_size(SIZE_BIG[0], SIZE_BIG[1])

def set_window_size_small(driver):
    SIZE_SMALL = (900, 600)
    driver.set_window_size(SIZE_SMALL[0], SIZE_SMALL[1])

def set_mobile_view(mobile, driver):
    if mobile:
        set_window_size_small(driver)
    else:
        set_window_size_big(driver)

def wait_for(condition_function):
    start_time = time.time()
    while time.time() < start_time + 14:
        if condition_function():
            return True
        else:
            time.sleep(0.1)
    raise Exception('Timeout waiting for {}'.format(condition_function.__name__)
                    )

def get_url(stage, url):
    stage_url = (get_domain(stage) + url)
    print("getting url ", stage_url)
    return stage_url

def get_feeds_url(stage, url):
    stage_url = (get_domain(stage, prefix="feeds.") + url)
    print("getting url ", stage_url)
    return stage_url

def get_magic_url(stage, url):
    stage_url = (get_domain(stage, prefix="magic.") + url)
    print("getting url ", stage_url)
    return stage_url

def get_domain(stage, prefix=""):
    return "https://{0}{1}".format(prefix, domain)

def scroll_down_til_the_end(driver):
    last_height = driver.execute_script("return document.body.scrollHeight")
    while True:
        driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
        time.sleep(0.5)
        new_height = driver.execute_script("return document.body.scrollHeight")
        if new_height == last_height:
            break
        last_height = new_height

def change_to_new_window(driver, jump=-1):
    driver.switch_to_window(driver.window_handles[jump])

def sleep(seconds):
    time.sleep(seconds)

def sleep_small():
    time.sleep(SMALL_WAIT)

def sleep_medium():
    time.sleep(MEDIUM_WAIT)

def sleep_long():
    time.sleep(LONG_WAIT)

def sleep_extra_long():
    time.sleep(EXTRA_LONG_WAIT)

def wait_for_alert(driver, alert_message='Time our waiting for alert', maximum_wait=3):
    # WebDriverWait(driver, maximum_wait).until(EC.alert_is_present(), alert_message)
    wait_for(EC.alert_is_present())

def is_safari(driver):
    return driver.name.lower() == 'safari'


text:
package com.kaaprotech.satu.parser;

public enum FieldModifier {
    key, val
}


text:
package config

import (
	"github.com/sensu/uchiwa/uchiwa/auth"
	"github.com/sensu/uchiwa/uchiwa/structs"
)

// Config struct contains []SensuConfig and UchiwaConfig structs
type Config struct {
	Dashboard *GlobalConfig `json:",omitempty"`
	Sensu     []SensuConfig
	Uchiwa    GlobalConfig
}

// SensuConfig struct contains conf about a Sensu API
type SensuConfig struct {
	Name     string
	Host     string
	Port     int
	Ssl      bool
	Insecure bool
	URL      string
	User     string
	Path     string
	Pass     string
	Timeout  int
}

// GlobalConfig struct contains conf about Uchiwa
type GlobalConfig struct {
	Host       string
	Port       int
	LogLevel   string
	Refresh    int
	Pass       string
	User       string
	Users      []auth.User
	Audit      Audit
	Auth       structs.Auth
	Db         Db
	Enterprise bool
	Github     Github
	Gitlab     Gitlab
	Ldap       Ldap
	SSL        SSL
}

// Audit struct contains the config of the Audit logger
type Audit struct {
	Level   string
	Logfile string
}

// Db struct contains the SQL driver configuration
type Db struct {
	Driver string
	Scheme string
}

// Github struct contains the GitHub driver configuration
type Github struct {
	ClientID     string
	ClientSecret string
	Roles        []auth.Role
	Server       string
}

// Gitlab struct contains the Gitlab driver configuration
type Gitlab struct {
	ApplicationID string
	Secret        string
	RedirectURL   string
	Roles         []auth.Role
	Server        string
}

// Ldap struct contains the LDAP driver configuration
type Ldap struct {
	Server               string
	Port                 int
	BaseDN               string
	BindUser             string
	BindPass             string
	GroupBaseDN          string
	GroupObjectClass     string
	GroupMemberAttribute string
	Insecure             bool
	Roles                []auth.Role
	Security             string
	UserAttribute        string
	UserBaseDN           string
	UserObjectClass      string
}

// SSL struct contains the path the SSL certificate and key
type SSL struct {
	CertFile string
	KeyFile  string
}


text:
.class public Ljavax/xml/namespace/QName;
.super Ljava/lang/Object;
.source "QName.java"

# interfaces
.implements Ljava/io/Serializable;

# static fields
.field private static final compatibilitySerialVersionUID:J = 0x3d521a30bc76fdffL

.field private static final defaultSerialVersionUID:J = -0x7e9257d203c42294L

.field private static final serialVersionUID:J

# instance fields
.field private final localPart:Ljava/lang/String;

.field private final namespaceURI:Ljava/lang/String;

.field private prefix:Ljava/lang/String;

.field private transient qNameAsString:Ljava/lang/String;

# direct methods
.method static constructor <clinit>()V
    .locals 4

    .prologue
    .line 89
    const-string v1, "org.apache.xml.namespace.QName.useCompatibleSerialVersionUID"

    invoke-static {v1}, Ljava/lang/System;->getProperty(Ljava/lang/String;)Ljava/lang/String;

    move-result-object v0

    .line 91
    .local v0, "compatPropValue":Ljava/lang/String;
    const-string v1, "1.0"

    invoke-virtual {v1, v0}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z

    move-result v1

    if-nez v1, :cond_0

    const-wide v2, -0x7e9257d203c42294L

    :goto_0
    sput-wide v2, Ljavax/xml/namespace/QName;->serialVersionUID:J

    .line 92
    return-void

    .line 91
    :cond_0
    const-wide v2, 0x3d521a30bc76fdffL    # 2.572492427824108E-13

    goto :goto_0
.end method

.method public constructor <init>(Ljava/lang/String;)V
    .locals 2
    .param p1, "localPart"    # Ljava/lang/String;

    .prologue
    .line 251
    const-string v0, ""

    const-string v1, ""

    invoke-direct {p0, v0, p1, v1}, Ljavax/xml/namespace/QName;-><init>(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V

    .line 255
    return-void
.end method

.method public constructor <init>(Ljava/lang/String;Ljava/lang/String;)V
    .locals 1
    .param p1, "namespaceURI"    # Ljava/lang/String;
    .param p2, "localPart"    # Ljava/lang/String;

    .prologue
    .line 153
    const-string v0, ""

    invoke-direct {p0, p1, p2, v0}, Ljavax/xml/namespace/QName;-><init>(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V

    .line 154
    return-void
.end method

.method public constructor <init>(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V
    .locals 2
    .param p1, "namespaceURI"    # Ljava/lang/String;
    .param p2, "localPart"    # Ljava/lang/String;
    .param p3, "prefix"    # Ljava/lang/String;

    .prologue
    .line 193
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    .line 196
    if-nez p1, :cond_0

    .line 197
    const-string v0, ""

    iput-object v0, p0, Ljavax/xml/namespace/QName;->namespaceURI:Ljava/lang/String;

    .line 203
    :goto_0
    if-nez p2, :cond_1

    .line 204
    new-instance v0, Ljava/lang/IllegalArgumentException;

    const-string v1, "local part cannot be \"null\" when creating a QName"

    invoke-direct {v0, v1}, Ljava/lang/IllegalArgumentException;-><init>(Ljava/lang/String;)V

    throw v0

    .line 199
    :cond_0
    iput-object p1, p0, Ljavax/xml/namespace/QName;->namespaceURI:Ljava/lang/String;

    goto :goto_0

    .line 206
    :cond_1
    iput-object p2, p0, Ljavax/xml/namespace/QName;->localPart:Ljava/lang/String;

    .line 209
    if-nez p3, :cond_2

    .line 210
    new-instance v0, Ljava/lang/IllegalArgumentException;

    const-string v1, "prefix cannot be \"null\" when creating a QName"

    invoke-direct {v0, v1}, Ljava/lang/IllegalArgumentException;-><init>(Ljava/lang/String;)V

    throw v0

    .line 212
    :cond_2
    iput-object p3, p0, Ljavax/xml/namespace/QName;->prefix:Ljava/lang/String;

    .line 213
    return-void
.end method

.method private readObject(Ljava/io/ObjectInputStream;)V
    .locals 1
    .param p1, "in"    # Ljava/io/ObjectInputStream;
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/io/IOException;,
            Ljava/lang/ClassNotFoundException;
        }
    .end annotation

    .prologue
    .line 479
    invoke-virtual {p1}, Ljava/io/ObjectInputStream;->defaultReadObject()V

    .line 480
    iget-object v0, p0, Ljavax/xml/namespace/QName;->prefix:Ljava/lang/String;

    if-nez v0, :cond_0

    .line 481
    const-string v0, ""

    iput-object v0, p0, Ljavax/xml/namespace/QName;->prefix:Ljava/lang/String;

    .line 483
    :cond_0
    return-void
.end method

.method public static valueOf(Ljava/lang/String;)Ljavax/xml/namespace/QName;
    .locals 5
    .param p0, "qNameAsString"    # Ljava/lang/String;

    .prologue
    .line 426
    if-nez p0, :cond_0

    .line 427
    new-instance v1, Ljava/lang/IllegalArgumentException;

    const-string v2, "cannot create QName from \"null\" or \"\" String"

    invoke-direct {v1, v2}, Ljava/lang/IllegalArgumentException;-><init>(Ljava/lang/String;)V

    throw v1

    .line 431
    :cond_0
    invoke-virtual {p0}, Ljava/lang/String;->length()I

    move-result v1

    if-nez v1, :cond_1

    .line 432
    new-instance v1, Ljavax/xml/namespace/QName;

    const-string v2, ""

    const-string v3, ""

    invoke-direct {v1, v2, p0, v3}, Ljavax/xml/namespace/QName;-><init>(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V

    .line 464
    :goto_0
    return-object v1

    .line 439
    :cond_1
    const/4 v1, 0x0

    invoke-virtual {p0, v1}, Ljava/lang/String;->charAt(I)C

    move-result v1

    const/16 v2, 0x7b

    if-eq v1, v2, :cond_2

    .line 440
    new-instance v1, Ljavax/xml/namespace/QName;

    const-string v2, ""

    const-string v3, ""

    invoke-direct {v1, v2, p0, v3}, Ljavax/xml/namespace/QName;-><init>(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V

    goto :goto_0

    .line 447
    :cond_2
    const-string v1, "{}"

    invoke-virtual {p0, v1}, Ljava/lang/String;->startsWith(Ljava/lang/String;)Z

    move-result v1

    if-eqz v1, :cond_3

    .line 448
    new-instance v1, Ljava/lang/IllegalArgumentException;

    new-instance v2, Ljava/lang/StringBuilder;

    invoke-direct {v2}, Ljava/lang/StringBuilder;-><init>()V

    const-string v3, "Namespace URI .equals(XMLConstants.NULL_NS_URI), .equals(\"\"), only the local part, \""

    invoke-virtual {v2, v3}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v2

    const-string v3, ""

    invoke-virtual {v3}, Ljava/lang/String;->length()I

    move-result v3

    add-int/lit8 v3, v3, 0x2

    invoke-virtual {p0, v3}, Ljava/lang/String;->substring(I)Ljava/lang/String;

    move-result-object v3

    invoke-virtual {v2, v3}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v2

    const-string v3, "\", "

    invoke-virtual {v2, v3}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v2

    const-string v3, "should be provided."

    invoke-virtual {v2, v3}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v2

    invoke-virtual {v2}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v2

    invoke-direct {v1, v2}, Ljava/lang/IllegalArgumentException;-><init>(Ljava/lang/String;)V

    throw v1

    .line 457
    :cond_3
    const/16 v1, 0x7d

    invoke-virtual {p0, v1}, Ljava/lang/String;->indexOf(I)I

    move-result v0

    .line 458
    .local v0, "endOfNamespaceURI":I
    const/4 v1, -0x1

    if-ne v0, v1, :cond_4

    .line 459
    new-instance v1, Ljava/lang/IllegalArgumentException;

    new-instance v2, Ljava/lang/StringBuilder;

    invoke-direct {v2}, Ljava/lang/StringBuilder;-><init>()V

    const-string v3, "cannot create QName from \""

    invoke-virtual {v2, v3}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v2

    invoke-virtual {v2, p0}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v2

    const-string v3, "\", missing closing \"}\""

    invoke-virtual {v2, v3}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v2

    invoke-virtual {v2}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v2

    invoke-direct {v1, v2}, Ljava/lang/IllegalArgumentException;-><init>(Ljava/lang/String;)V

    throw v1

    .line 464
    :cond_4
    new-instance v1, Ljavax/xml/namespace/QName;

    const/4 v2, 0x1

    invoke-virtual {p0, v2, v0}, Ljava/lang/String;->substring(II)Ljava/lang/String;

    move-result-object v2

    add-int/lit8 v3, v0, 0x1

    invoke-virtual {p0, v3}, Ljava/lang/String;->substring(I)Ljava/lang/String;

    move-result-object v3

    const-string v4, ""

    invoke-direct {v1, v2, v3, v4}, Ljavax/xml/namespace/QName;-><init>(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V

    goto/16 :goto_0
.end method

# virtual methods
.method public final equals(Ljava/lang/Object;)Z
    .locals 5
    .param p1, "objectToTest"    # Ljava/lang/Object;

    .prologue
    const/4 v1, 0x1

    const/4 v2, 0x0

    .line 314
    if-ne p1, p0, :cond_1

    .line 322
    :cond_0
    :goto_0
    return v1

    .line 318
    :cond_1
    instance-of v3, p1, Ljavax/xml/namespace/QName;

    if-eqz v3, :cond_3

    move-object v0, p1

    .line 319
    check-cast v0, Ljavax/xml/namespace/QName;

    .line 320
    .local v0, "qName":Ljavax/xml/namespace/QName;
    iget-object v3, p0, Ljavax/xml/namespace/QName;->localPart:Ljava/lang/String;

    iget-object v4, v0, Ljavax/xml/namespace/QName;->localPart:Ljava/lang/String;

    invoke-virtual {v3, v4}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z

    move-result v3

    if-eqz v3, :cond_2

    iget-object v3, p0, Ljavax/xml/namespace/QName;->namespaceURI:Ljava/lang/String;

    iget-object v4, v0, Ljavax/xml/namespace/QName;->namespaceURI:Ljava/lang/String;

    invoke-virtual {v3, v4}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z

    move-result v3

    if-nez v3, :cond_0

    :cond_2
    move v1, v2

    goto :goto_0

    .end local v0    # "qName":Ljavax/xml/namespace/QName;
    :cond_3
    move v1, v2

    .line 322
    goto :goto_0
.end method

.method public getLocalPart()Ljava/lang/String;
    .locals 1

    .prologue
    .line 272
    iget-object v0, p0, Ljavax/xml/namespace/QName;->localPart:Ljava/lang/String;

    return-object v0
.end method

.method public getNamespaceURI()Ljava/lang/String;
    .locals 1

    .prologue
    .line 263
    iget-object v0, p0, Ljavax/xml/namespace/QName;->namespaceURI:Ljava/lang/String;

    return-object v0
.end method

.method public getPrefix()Ljava/lang/String;
    .locals 1

    .prologue
    .line 287
    iget-object v0, p0, Ljavax/xml/namespace/QName;->prefix:Ljava/lang/String;

    return-object v0
.end method

.method public final hashCode()I
    .locals 2

    .prologue
    .line 339
    iget-object v0, p0, Ljavax/xml/namespace/QName;->namespaceURI:Ljava/lang/String;

    invoke-virtual {v0}, Ljava/lang/String;->hashCode()I

    move-result v0

    iget-object v1, p0, Ljavax/xml/namespace/QName;->localPart:Ljava/lang/String;

    invoke-virtual {v1}, Ljava/lang/String;->hashCode()I

    move-result v1

    xor-int/2addr v0, v1

    return v0
.end method

.method public toString()Ljava/lang/String;
    .locals 4

    .prologue
    .line 365
    iget-object v0, p0, Ljavax/xml/namespace/QName;->qNameAsString:Ljava/lang/String;

    .line 366
    .local v0, "_qNameAsString":Ljava/lang/String;
    if-nez v0, :cond_0

    .line 367
    iget-object v3, p0, Ljavax/xml/namespace/QName;->namespaceURI:Ljava/lang/String;

    invoke-virtual {v3}, Ljava/lang/String;->length()I

    move-result v2

    .line 368
    .local v2, "nsLength":I
    if-nez v2, :cond_1

    .line 369
    iget-object v0, p0, Ljavax/xml/namespace/QName;->localPart:Ljava/lang/String;

    .line 379
    :goto_0
    iput-object v0, p0, Ljavax/xml/namespace/QName;->qNameAsString:Ljava/lang/String;

    .line 381
    .end local v2    # "nsLength":I
    :cond_0
    return-object v0

    .line 372
    .restart local v2    # "nsLength":I
    :cond_1
    new-instance v1, Ljava/lang/StringBuilder;

    iget-object v3, p0, Ljavax/xml/namespace/QName;->localPart:Ljava/lang/String;

    invoke-virtual {v3}, Ljava/lang/String;->length()I

    move-result v3

    add-int/2addr v3, v2

    add-int/lit8 v3, v3, 0x2

    invoke-direct {v1, v3}, Ljava/lang/StringBuilder;-><init>(I)V

    .line 373
    .local v1, "buffer":Ljava/lang/StringBuilder;
    const/16 v3, 0x7b

    invoke-virtual {v1, v3}, Ljava/lang/StringBuilder;->append(C)Ljava/lang/StringBuilder;

    .line 374
    iget-object v3, p0, Ljavax/xml/namespace/QName;->namespaceURI:Ljava/lang/String;

    invoke-virtual {v1, v3}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    .line 375
    const/16 v3, 0x7d

    invoke-virtual {v1, v3}, Ljava/lang/StringBuilder;->append(C)Ljava/lang/StringBuilder;

    .line 376
    iget-object v3, p0, Ljavax/xml/namespace/QName;->localPart:Ljava/lang/String;

    invoke-virtual {v1, v3}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    .line 377
    invoke-virtual {v1}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v0

    goto :goto_0
.end method


text:
<?php

class Cockpit_Dish_Changeset extends Crunchbutton_Dish_Changeset {}


text:
title: Co-working session
text: This is a co-working session.  Bring a progamming issue you are working on or having trouble with or just show up to learn and help out.  We will get together in groups to work on these problems.  Also we will always have room for beginners and will make sure to have a group working on the basics.
link: https://github.com/rhodyrstats/rhodyrstats.github.io/issues/15
eventlink:
location: "URI, Kingston, RI, Room TBD"
date: 2016-03-25
publish: no
---


text:
package org.apereo.cas.support.events.audit;

import lombok.val;
import org.apereo.inspektr.audit.AuditActionContext;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;

import java.util.Date;

import static org.junit.jupiter.api.Assertions.*;

/**
 * This is {@link CasAuditActionContextRecordedEventTests}.
 *
 * @author Misagh Moayyed
 * @since 6.3.0
 */
@Tag("Simple")
public class CasAuditActionContextRecordedEventTests {

    @Test
    public void verifyOperation() {
        assertDoesNotThrow(new Executable() {
            @Override
            @SuppressWarnings("JdkObsolete")
            public void execute() throws Throwable {
                val ctx = new AuditActionContext("casuser", "TEST", "TEST",
                    "CAS", new Date(), "1.2.3.4",
                    "1.2.3.4");
                new CasAuditActionContextRecordedEvent(this, ctx);
            }
        });
    }

}


text:
package com.hannesdorfmann.mosby.sample.mail.mails;

import com.hannesdorfmann.mosby.sample.mail.base.presenter.BaseRxMailPresenter;
import com.hannesdorfmann.mosby.sample.mail.model.event.MailLabelChangedEvent;
import com.hannesdorfmann.mosby.sample.mail.model.event.MailReceivedEvent;
import com.hannesdorfmann.mosby.sample.mail.model.event.MailSentEvent;
import com.hannesdorfmann.mosby.sample.mail.model.mail.Label;
import com.hannesdorfmann.mosby.sample.mail.model.mail.Mail;
import com.hannesdorfmann.mosby.sample.mail.model.mail.MailProvider;
import de.greenrobot.event.EventBus;
import java.util.List;
import javax.inject.Inject;

/**
 * @author Hannes Dorfmann
 */
public class MailsPresenter extends BaseRxMailPresenter<MailsView, List<Mail>> {

  @Inject public MailsPresenter(MailProvider mailProvider, EventBus eventBus) {
    super(mailProvider, eventBus);
  }

  public void load(boolean pullToRefresh, Label label) {
    subscribe(mailProvider.getMailsOfLabel(label.getName()), pullToRefresh);
  }

  public void onEventMainThread(MailSentEvent event) {
    onEventMainThread(new MailLabelChangedEvent(event.getMail(), event.getMail().getLabel()));
  }

  public void onEventMainThread(MailReceivedEvent event) {
    onEventMainThread(new MailLabelChangedEvent(event.getMail(), event.getMail().getLabel()));
  }

  public void onEventMainThread(MailLabelChangedEvent event) {
    if (isViewAttached()) {
      getView().changeLabel(event.getMail(), event.getLabel());
    }
  }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>AG Constructores</title>
    <link rel="icon" type="image/png" href="img/logo-icon.png">

    <link rel="stylesheet" type="text/css" href="bower_components/bootstrap/dist/css/bootstrap.min.css">

    <link rel="stylesheet" type="text/css" href="style.css">

        <button class="btn btn-block linkButton">Inicio</button>

        <button class="btn btn-block linkButton">Filosofía</button>

        <button class="btn btn-block linkButton" style="padding-left:2px">¿Por qué AG?</button>

        <button class="btn btn-block linkButton">Proyectos</button>

        <button class="btn btn-block linkButton">Contacto</button>

Proyectos

Todos los derechos reservados
AG Constructores, ©2015


text:
package com.gremzor.personpopulatorpro.dao;

import com.gremzor.personpopulatorpro.model.Person;

public interface PersonDAOInterface {
    void onChildAdded(Person person);
    void onChildRemoved(Person person);
    void onChildChanged(Person person);
}


text:
<?php
/**
 * @package WPSEO\Premium\Classes
 */

if ( ! defined( 'WPSEO_VERSION' ) ) {
	header( 'HTTP/1.0 403 Forbidden' );
	die;
}

if ( ! class_exists( 'WP_List_Table' ) ) {
	require_once( ABSPATH . 'wp-admin/includes/class-wp-list-table.php' );
}

/**
 * Class WPSEO_Redirect_Table
 */
class WPSEO_Redirect_Table extends WP_List_Table {

	/**
	 * @var string
	 */
	private $search_string;

	/**
	 * @var string
	 */
	private $type;

	/**
	 * @var mixed
	 */
	private $redirect_manager;

	/**
	 * WPSEO_Redirect_Table constructor
	 *
	 * @param string $type
	 */
	public function __construct( $type ) {
		parent::__construct( array( 'plural' => $type ) );

		$this->type             = $type;
		$class_name             = 'WPSEO_' . strtoupper( $this->type ) . '_Redirect_Manager';
		$this->redirect_manager = new $class_name();

		$this->handle_bulk_action();

		if ( ( $search_string = filter_input( INPUT_GET, 's' ) ) != '' ) {
			$this->search_string = $search_string;
		}
	}

	/**
	 * Search through the items
	 *
	 * @param array $items
	 *
	 * @return array
	 */
	private function do_search( $items ) {
		$results = array();

		if ( is_array( $items ) ) {

			foreach ( $items as $old => $redirect ) {
				if ( false !== stripos( $old, $this->search_string ) || false !== stripos( $redirect['url'], $this->search_string ) ) {
					$results[ $old ] = $redirect;
				}
			}
		}

		return $results;
	}

	/**
	 * Set the table columns
	 *
	 * @return array
	 */
	public function get_columns() {
		$columns = array(
			'cb'   => '<input type="checkbox" />',
			'old'  => $this->type,
			'new'  => __( 'New URL', 'wordpress-seo-premium' ),
			'type' => _x( 'Type', 'noun', 'wordpress-seo-premium' ),
		);

		return $columns;
	}

	/**
	 * Setup the table variables, fetch the items from the database, search, sort and format the items.
	 * Set the items as the WPSEO_Redirect_Table items variable.
	 */
	public function prepare_items() {

		// Setup the columns.
		$columns               = $this->get_columns();
		$hidden                = array();
		$sortable              = $this->get_sortable_columns();
		$this->_column_headers = array( $columns, $hidden, $sortable );

		// Get the items.
		$redirect_items = $this->redirect_manager->get_redirects();

		// Handle the search.
		if ( null != $this->search_string ) {
			$redirect_items = $this->do_search( $redirect_items );
		}

		// Format the data.
		$formatted_items = array();
		if ( is_array( $redirect_items ) && count( $redirect_items ) > 0 ) {
			foreach ( $redirect_items as $old => $redirect ) {
				$formatted_items[] = array( 'old' => $old, 'new' => $redirect['url'], 'type' => $redirect['type'] );
			}
		}

		// Sort the results.
		if ( count( $formatted_items ) > 0 ) {
			usort( $formatted_items, array( $this, 'do_reorder' ) );
		}

		// Get variables needed for pagination.
		$per_page    = $this->get_items_per_page( 'redirects_per_page', 25 );
		$total_items = count( $formatted_items );

		// Set pagination.
		$this->set_pagination_args( array(
			'total_items' => $total_items,
			'total_pages' => ceil( $total_items / $per_page ),
			'per_page'    => $per_page,
		) );

		$current_page = intval( ( ( $paged = filter_input( INPUT_GET, 'paged' ) ) ? $paged : 0 ) );

		// Setting the starting point. If starting point is below 1, overwrite it with value 0, otherwise it will be sliced of at the back.
		$slice_start = ( $current_page - 1 );
		if ( $slice_start < 0 ) {
			$slice_start = 0;
		}

		// Apply 'pagination'.
		$formatted_items = array_slice( $formatted_items, ( $slice_start * $per_page ), $per_page );

		// Set items.
		$this->items = $formatted_items;
	}

	/**
	 * Return the columns that are sortable
	 *
	 * @return array
	 */
	public function get_sortable_columns() {
		$sortable_columns = array(
			'old' => array( 'old', false ),
			'new' => array( 'new', false ),
			'type' => array( 'type', false ),
		);

		return $sortable_columns;
	}

	/**
	 * Reorder the items based on user input
	 *
	 * @param array $a
	 * @param array $b
	 *
	 * @return int
	 */
	public function do_reorder( $a, $b ) {
		// If no sort, default to title.
		$orderby = ( ( $orderby = filter_input( INPUT_GET, 'orderby' ) ) != '' ) ? $orderby : 'old';

		// If no order, default to asc.
		$order = ( ( $order = filter_input( INPUT_GET, 'order') ) != '' ) ? $order : 'asc';

		// Determine sort order.
		$result = strcmp( $a[ $orderby ], $b[ $orderby ] );

		// Send final sort direction to usort.
		return ( $order === 'asc' ) ? $result : ( - $result );
	}

	/**
	 * The old column actions
	 *
	 * @param array $item
	 *
	 * @return string
	 */
	public function column_old( $item ) {
		$actions = array(
			'edit'  => '' . __( 'Edit', 'wordpress-seo-premium' ) . '',
			'trash' => '' . __( 'Delete', 'wordpress-seo-premium' ) . '',
		);

		return sprintf(
			'
%1$s
 %2$s',
			$item['old'],
			$this->row_actions( $actions )
		);
	}

	/**
	 * Checkbox column
	 *
	 * @param array $item
	 *
	 * @return string
	 */
	public function column_cb( $item ) {
		return sprintf(
			'<input type="checkbox" name="wpseo_redirects_bulk_delete[]" value="%s" />', $item['old']
		);
	}

	/**
	 * Default method to display a column
	 *
	 * @param array  $item
	 * @param string $column_name
	 *
	 * @return string
	 */
	public function column_default( $item, $column_name ) {

		switch ( $column_name ) {
			case 'new':
				return "
" . $item[ $column_name ] . '
';
				break;
			case 'type':
				return "
" . $item[ $column_name ] . '
';
				break;
			default:
				return $item[ $column_name ];
		}
	}

	/**
	 * Return available bulk actions
	 *
	 * @return array
	 */
	public function get_bulk_actions() {
		$actions = array(
			'delete' => __( 'Delete', 'wordpress-seo-premium' ),
		);

		return $actions;
	}

	/**
	 * Function that handles bulk action
	 */
	private function handle_bulk_action() {
		if ( filter_input( INPUT_POST, 'action' ) === 'delete' || filter_input( INPUT_POST, 'action2' ) === 'delete' ) {
			if ( ( $redirects_bulk_delete = filter_input( INPUT_POST, 'wpseo_redirects_bulk_delete', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY ) ) && count( $redirects_bulk_delete ) > 0 ) {
				$this->redirect_manager->delete_redirect( $redirects_bulk_delete );
			}
		}

	}

}


text:
$(function() {
    function renderError(msg, e) {
        console.log(msg, e);

        $("#errors").toggle();
        $("#error-msg").html(msg);
    }

    function loadDictionaries() {
        $.get("/list", function(data) {
            if (!data || !data.dictionaries) {
                renderError("Unable to load dictionaries", data);
                return;
            };

            $.each(data.dictionaries, function(i, dict) {
                var opt = "<option value='" + dict.id + "'>" + dict.name + "</option>";

                $("#dictionary").append(opt);
            });
        });
    };

    function displayConcepts(concepts) {
        var html = "
";

        $.each(concepts, function(j, concept) {
            html += "
";
            html += concept.prefLabel.name;
            html += "
";
        });

        html += "
";
        $("#vis").html(html);
    }

    function extractText() {
        var projectId = $("#dictionary :selected").val();
        var language = $("#language :selected").val();
        var text = $("#text").val();

        var query =  "/extract?id=" + projectId + "&language=" + language + "&text=" + text;

        var data = {"id":projectId, "language": language, "text":text}
        $.post("/extract", data).done(function(data) {
            if (!data || !data.extraction) {
                renderError("Unable to extract text", data);
                return;
            }

            $.each(data.extraction.annotations, function(i, annotation) {
                displayConcepts(annotation.concepts);
            });
        }).fail(function(e) {
            renderError("Unable to extract text", e);
        });
    };

    function addDictionary() {
        var name = $("#dict-name").val();
        var text = $("#dict-contents").val();

        $.post("/add", { "name":name, "text":text }).done(function(data) {
            if (!data || !data.id) {
                renderError("Unable to add dictionary", data);
                return;
            }

            $("#vis-dict").html("
Added dictionary with id: " + data.id + "
");
        }).fail(function(e) {
            renderError("Unable to add dictionary", e);
        });
    }

    function addSkos() {
        var url = $("#skos-url").val();

        $.post("/skos", { "url":url }).done(function(data) {
            if (!data || !data.id) {
                renderError("Unable to process rdf dump", data);
                return;
            }

            $("#vis-dict").html("
Added skos dictionary with id: " + data.id + "
");
        }).fail(function(e) {
            renderError("Unable to add dictionary", e);
        });
    }

    function enableDictionaryMode() {
        $("#row-extract").hide();
        $("#row-dictionary").show();
    }

    function enableExtractMode() {
        $("#row-dictionary").hide();
        $("#row-extract").show();
    }

    loadDictionaries();

    $("#extract-mode").click(function() {
        enableExtractMode();
    });

    $("#dict-mode").click(function() {
        enableDictionaryMode();
    });

    $("#submit").click(function() {
        extractText();
        return false;
    });

    $("#submit-dict").click(function() {
        addDictionary();
        return false;
    });

    $("#submit-skos").click(function() {
        addSkos();
        return false;
    });
});


text:
/**
 * Copy this file to the name options.js and change the values below to your preferences. The options.js file is in the
 * .gitignore file so that your sensitive information does not get committed to Git.
 */
"use strict";
module.exports = {
	urls: {
		originUrl		: 'www.example.com',
		analyticUrl		: 'tags.bluekai.com'
	}
};


text:
import com.excilys.ebi.gatling.core.Predef._
import com.excilys.ebi.gatling.http.Predef._
import akka.util.duration._
import bootstrap._

class CreateNodes extends Simulation {
  val httpConf = httpConfig
    .baseURL("http://localhost:7474")
    .acceptHeader("application/json")

  val createNode = """{"query": "start n=node(0) foreach(id in range(1,1000) : create (n))"}"""

  val scn = scenario("Create Nodes")
    .repeat(10) {
    exec(
      http("create node")
        .post("/db/data/cypher")
        .body(createNode)
        .asJSON
        .check(status.is(200)))
      .pause(0 milliseconds, 1 milliseconds)
  }

  setUp(
    scn.users(10).ramp(10).protocolConfig(httpConf)
  )
}


text:
Setup projektu
--------------

.. code-block:: bash

    $ tlmgr init-usertree
    $ sudo apt-get install xzdec
    $ tlmgr install titlesec
    $ tlmgr install framed
    $ tlmgr install threeparttable
    $ tlmgr install wrapfig
    $ tlmgr install upquote
    $ tlmgr install multirow
    $ sudo apt-get install texlive-latex-extra
    $ sudo apt-get install texlive-lang-polish
    $ sudo apt-get install dvipng

.. include:: includes/first.rst

.. include:: includes/second.rst


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Basidiomycetum Rostochiensium 55 (1928)

#### Original name
Daedalea epidryphloeus E.H.L. Krause

### Remarks
null


text:
package com.bytegriffin.get4j.ha;

import java.util.Map;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.leader.LeaderSelector;
import org.apache.curator.framework.recipes.leader.LeaderSelectorListenerAdapter;
import org.apache.curator.shaded.com.google.common.collect.Maps;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.bytegriffin.get4j.probe.ProbeMasterChecker;
import com.bytegriffin.get4j.util.NetHelper;
import com.bytegriffin.get4j.util.Sleep;

/**
 * ProbeMaster选举策略:采用Active-Standby模式

 * 当在Probe模式下抓取同一个seed时,集群中只允许出现一个节点是Probe Master(Active),

 * 其他Probe节点处于Standby。最先启动的Probe机器来充当Master,

 * 一旦Probe Master退出或宕机,程序将自动在当前同一个seed集群

 * 中选举新的Probe充当Master。注意:集群模式下需要每个节点配置probe选项。

 * Interval:集群中只需一个节点配置即可。

 * Probe:集群中所有机器都要配置。
 */
public final class ProbeMasterElection  extends LeaderSelectorListenerAdapter implements ProbeMasterChecker {

	private static final Logger logger = LogManager.getLogger(ProbeMasterElection.class);

	private static final ProbeMasterElection me = new ProbeMasterElection();
	private static final String zk_probe_path_prefix = "/probe/";
	private LeaderSelector leaderSelector;
	private String seedName;
	private static Map<String, ProbeMasterElection> probe_master_map = Maps.newHashMap();
	private static Map<String, LeaderSelector> leader_selector_map = Maps.newHashMap();

	private ProbeMasterElection(){
	}

	public static ProbeMasterElection single(){
		return me;
	}

	static ProbeMasterElection create(CuratorFramework client, String seedName){
		ProbeMasterElection pms = new ProbeMasterElection(client, seedName);
		probe_master_map.put(seedName, pms);
		return pms;
	}

	static boolean checkMaster(String seedName){
		ProbeMasterElection pms =  probe_master_map.get(seedName);
		if(pms == null){
			return false;
		}
		return pms.isActive(seedName);
	}

	/**
	 * 设置选举
	 * @param client
	 * @param seedName
	 */
	private ProbeMasterElection(CuratorFramework client, String seedName) {
		this.seedName = seedName;
        leaderSelector = new LeaderSelector(client, zk_probe_path_prefix + seedName, this);
        leaderSelector.autoRequeue();
        leaderSelector.start();
        leader_selector_map.put(seedName, leaderSelector);
    }

	@Override
	public void takeLeadership(CuratorFramework client) throws Exception {
		logger.info("种子[{}]集群中将节点[{}]被选举为Probe Master。", seedName, NetHelper.getClusterNodeName());
        //循环占用本机充当Master,除非宕机或者退出等情况发生才进行新一轮选举。
		while(true) {
        	Sleep.seconds(Integer.MAX_VALUE);
        }
	}

	/**
	 * 判断本机运行状态是否为Probe Master
	 */
	@Override
	public boolean isActive(String seedName) {
		return leader_selector_map.get(seedName).hasLeadership();
	}
}


text:
from setuptools import setup

setup(name='cloudmock', packages=['cloudmock'])


text:
\documentclass[notitlepage]{article}
\newcounter{qcounter}
\usepackage{graphicx}
\usepackage{array}
\usepackage{booktabs}
\usepackage{fancyhdr}
\pagestyle{empty}
\textwidth	7.00in
\textheight	8.50in
\oddsidemargin	-0.35in
\topmargin	-0.5in
\parindent	0.00in

\begin{document}

 \begin{center}
  \Large{\bf Lab 6}\\
  \Large{\bf Our Sun}\\
  \vspace{0.5cm}
  Names: \vbox{\hrule width 10cm}
 \end{center}

\large{\bf Exercise \#1}
{\bf Station 2}
\begin{itemize}
  \item SOHO Images  ({\it 8 points})
  \begin{itemize}
    \item If the Sun turns by 90 degress in a time $t$, it would complete one revolution of 360 degrees in how much time?
    \vspace{4cm}
    \item Does this match the rotation rate given in your textbook or in lecture? Cite a source for this value.
    \vspace{4cm}
  \end{itemize}
  \item Magnetogram ({\it 7 points})
  \begin{itemize}
    \item What do you notice about the location of {\it sunspots} in the photo and the location of the {\it strongest magnetic fields}, shown by the brightest or darkest colors in the magnetogram?
    \vspace{4cm}
    \item Based on this answer, what do you think causes sunspots to form? Why are they dark?
    \vspace{4cm}
  \end{itemize}
\end{itemize}
{\bf Station 3} ({\it 10 points})
\begin{itemize}
 \item Diameter of the Sun (on paper): \vbox{\hrule width 8cm}

    \vspace{1cm}
    Minimum extent of the corona (on paper): \vbox{\hrule width 8cm}

    \vspace{1cm}

    \item Size of the corona (in reality): \vbox{\hrule width 8cm}

    \vspace{1cm}
    \item How many times larger than the Earth is the corona? \vbox{\hrule width 8cm}

    \vspace{1cm}
\end{itemize}

 {\bf Station 4} ({\it 15 points})
 \begin{itemize}
  \item Diameter of the Sun (on paper): \vbox{\hrule width 8cm}

  \vspace{1cm}
    First prominence distance (on paper): \vbox{\hrule width 8cm}

   \vspace{1cm}
    Second prominence distance (on paper): \vbox{\hrule width 8cm}

   \vspace{1cm}
    How far did the prominence move (on paper)? \vbox{\hrule width 8cm}

  \vspace{1cm}
  \item Diameter of the Sun (in reality): \vbox{\hrule width 8cm}

    \vspace{1cm}
    How far did the prominence move (in reality)? \vbox{\hrule width 8cm}

    \vspace{1cm}
  \item Velocity of the prominence: \vbox{\hrule width 8cm}
    \vspace{1cm}
  \item Time to reach the Earth if a prominence were moving at 2000 km/s:
    \vspace{1cm}
 \end{itemize}

 {\bf Station 5}
 What do you notice about the distribution of sunspots? How long does it take for the pattern to repeat? What does the length of time correspond to? ({\it 3 points})
 \vspace{8cm}

 \large{\bf Exercise \#2}
 \begin{itemize}
  \item Which end of the compass needle (or arrow) seems to be attracted by the north pole of the magnet? ({\it 1 point})
  \vspace{2cm}
  \item Which end of the compass needle is attracted to the south pole of the bar magnet? ({\it 1 point})
  \vspace{2cm}
  \item Which pole is attracted to which pole? ({\it 1 point})
  \vspace{2cm}
  \item What is the actual ``polarity'' of the Earth's ``magnetic North'' pole?
  \vspace{2cm}
  \item Sketch the pattern traced out by the magnetic filings below and \textbf{describe} the pattern in words. ({\it 2 points})
  \vspace{7cm}
  \item What does this imply about sunspots? ({\it 2 points})
  \vspace{3cm}
  \item Draw the field lines \textbf{above} a bar magnet. ({\it 2 points})
  \vspace{7cm}
  \item What are the similarities between your drawing and the loop prominence from station \#1 of Exercise \#1? ({\it 1 point})
  \vspace{3cm}
 \end{itemize}

% \large{\bf Exercise \#3}
% \begin{itemize}
%  \item On the ``Solar Observation Worksheet'', draw what you see on and near the Sun as seen through the special solar telescope. ({\it 8 points})
% \end{itemize}

\end{document}


text:
using Catel.IoC;
using GitMeet;

/// <summary>
/// Used by the ModuleInit. All code inside the Initialize method is ran as soon as the assembly is loaded.
/// </summary>
public static class ModuleInitializer
{
    /// <summary>
    /// Initializes the module.
    /// </summary>
    public static void Initialize()
    {
        ServiceLocatorInitializer.Current.Initialize(ServiceLocator.Default);
    }
}


text:
package org.apache.pinot.server.api;

import java.io.File;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Response;
import org.apache.commons.io.FileUtils;
import org.apache.pinot.common.utils.CommonConstants;
import org.apache.pinot.common.utils.NetUtil;
import org.apache.pinot.core.data.manager.TableDataManager;
import org.apache.pinot.core.transport.ListenerConfig;
import org.apache.pinot.core.transport.TlsConfig;
import org.apache.pinot.server.api.access.AccessControl;
import org.apache.pinot.server.api.access.AccessControlFactory;
import org.apache.pinot.server.starter.ServerInstance;
import org.apache.pinot.server.starter.helix.AdminApiApplication;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import static org.mockito.Mockito.mock;

public class AccessControlTest {
  private static final File INDEX_DIR = new File(FileUtils.getTempDirectory(), "AccessControlTest");
  protected static final String TABLE_NAME = "testTable";

  private final Map<String, TableDataManager> _tableDataManagerMap = new HashMap<>();
  private AdminApiApplication _adminApiApplication;
  protected WebTarget _webTarget;

  @BeforeClass
  public void setUp()
      throws Exception {
    FileUtils.deleteQuietly(INDEX_DIR);
    Assert.assertTrue(INDEX_DIR.mkdirs());

    // Mock the instance data manager
    // Mock the server instance
    ServerInstance serverInstance = mock(ServerInstance.class);

    _adminApiApplication = new AdminApiApplication(serverInstance, new DenyAllAccessFactory());
    _adminApiApplication.start(Collections.singletonList(new ListenerConfig(CommonConstants.HTTP_PROTOCOL, "0.0.0.0",
        CommonConstants.Server.DEFAULT_ADMIN_API_PORT, CommonConstants.HTTP_PROTOCOL, new TlsConfig())));

    _webTarget = ClientBuilder.newClient().target(String.format("http://%s:%d", NetUtil.getHostAddress(),
        CommonConstants.Server.DEFAULT_ADMIN_API_PORT));
  }

  @AfterClass
  public void tearDown() {
    _adminApiApplication.stop();
    FileUtils.deleteQuietly(INDEX_DIR);
  }

  @Test
  public void testAccessDenied() {
    String segmentPath = "/segments/testTable_REALTIME/segment_name";
    // Download any segment will be denied.
    Response response = _webTarget.path(segmentPath).request().get(Response.class);
    Assert.assertNotEquals(response.getStatus(), Response.Status.FORBIDDEN);
  }

  public static class DenyAllAccessFactory implements AccessControlFactory {
    private static final AccessControl DENY_ALL_ACCESS = (httpHeaders, tableName) -> false;

    @Override
    public AccessControl create() {
      return DENY_ALL_ACCESS;
    }
  }
}


text:
title: "Imaging Datasets"
layout: single
sitemap: true
permalink: /imaging-datasets/
author_profile: false
sidebar:
  nav: "docs"
---

{% include base_path %}

The Langlotzlab is currently working with imaging datasets from within and outside of Stanford Medicine:

- 1000 ICU chest radiographs
- 831 bone tumor radiographs annotated by an expert radiologist with 18 features and the pathologic diagnosis
- 4000 digital mammograms annotated with 13 quality attributes
- 4000 pediatric hand radiographs with radiologist bone age
- Soon: 4.4 million Stanford exams, each with a narrative report

There are of course many public datasets and challenges, especially with regard to sharing data. We hope to increase open access to some of these datasets by way of novel infrastructure and sharing methodology. Please reach out to the lab if you would like to learn more or collaborate.


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

#include <stddef.h>
#include <stdint.h>

#include <memory>
#include <string>
#include <utility>
#include <vector>

#include <fuzzer/FuzzedDataProvider.h>

#include "base/check.h"
#include "base/command_line.h"
#include "base/containers/flat_map.h"
#include "base/json/json_reader.h"
#include "base/strings/string_util.h"
#include "components/update_client/protocol_handler.h"
#include "components/update_client/protocol_serializer.h"
#include "third_party/abseil-cpp/absl/types/optional.h"

struct Environment {
  Environment() { CHECK(base::CommandLine::Init(0, nullptr)); }
};

namespace update_client {
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
  static Environment env;

  // Independently, try serializing a Request.
  base::flat_map<std::string, std::string> additional_attributes;
  std::vector<protocol_request::App> apps;

  // Share |data| between |MakeProtocolRequest| args
  FuzzedDataProvider data_provider(data, size);
  const size_t max_arg_size = size / 7;
  auto GetUtf8String = [&data_provider, max_arg_size]() -> std::string {
    std::string s = data_provider.ConsumeRandomLengthString(max_arg_size);
    return base::IsStringUTF8(s) ? s : "";
  };

  protocol_request::Request request = MakeProtocolRequest(
      false, "{" + GetUtf8String() + "}" /* session_id */,
      GetUtf8String() /* prod_id */, GetUtf8String() /* browser_version */,
      GetUtf8String() /* channel */, GetUtf8String() /* os_long_name */,
      GetUtf8String() /* download_preference */,
      absl::nullopt /* domain_joined */, additional_attributes,
      {} /*updater_state_attributes*/, std::move(apps));

  update_client::ProtocolHandlerFactoryJSON factory;
  std::unique_ptr<ProtocolSerializer> serializer = factory.CreateSerializer();
  std::string request_serialized = serializer->Serialize(request);

  // Any request we serialize should be valid JSON.
  CHECK(base::JSONReader::Read(request_serialized));
  return 0;
}
}  // namespace update_client


text:
TEST(MessageTest, testMessageResponseUpdatesSenderAndReceiver)
{
    paxos::Replica from("from_hostname");
    paxos::Replica to("to_hostname");

    paxos::Decree the_decree(from, 1, "", paxos::DecreeType::UserDecree);
    paxos::Message m(the_decree, from, to, paxos::MessageType::RequestMessage);

    paxos::Message response = paxos::Response(m, paxos::MessageType::PromiseMessage);

    ASSERT_EQ(response.from.hostname, m.to.hostname);
    ASSERT_EQ(response.to.hostname, m.from.hostname);
    ASSERT_EQ(response.type, paxos::MessageType::PromiseMessage);
}


text:
// Copyright (c) 2011-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2020 The PIVX developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "rpcconsole.h"
#include "ui_rpcconsole.h"

#include "bantablemodel.h"
#include "clientmodel.h"
#include "peertablemodel.h"
#include "qt/rpcexecutor.h"
#include "walletmodel.h"

#include "chainparams.h"
#include "netbase.h"
#include "util/system.h"

#ifdef ENABLE_WALLET
#include <db_cxx.h>
#endif

#include <QDir>
#include <QKeyEvent>
#include <QMenu>
#include <QScrollBar>
#include <QThread>
#include <QTime>
#include <QStringList>

// TODO: add a scrollback limit, as there is currently none
// TODO: make it possible to filter out categories (esp debug messages when implemented)
// TODO: receive errors and debug messages through ClientModel

const int CONSOLE_HISTORY = 50;
const QSize ICON_SIZE(24, 24);

const int INITIAL_TRAFFIC_GRAPH_MINS = 30;

// Repair parameters
const QString SALVAGEWALLET("-salvagewallet");
const QString RESCAN("-rescan");
const QString ZAPTXES1("-zapwallettxes=1");
const QString ZAPTXES2("-zapwallettxes=2");
const QString UPGRADEWALLET("-upgradewallet");
const QString REINDEX("-reindex");
const QString RESYNC("-resync");

const struct {
    const char* url;
    const char* source;
} ICON_MAPPING[] = {
    {"cmd-request", ":/icons/tx_input"},
    {"cmd-reply", ":/icons/tx_output"},
    {"cmd-error", ":/icons/tx_output"},
    {"misc", ":/icons/tx_inout"},
    {NULL, NULL}};

RPCConsole::RPCConsole(QWidget* parent) : QDialog(parent, Qt::WindowSystemMenuHint | Qt::WindowTitleHint | Qt::WindowCloseButtonHint),
                                          ui(new Ui::RPCConsole),
                                          clientModel(nullptr),
                                          walletModel(nullptr),
                                          historyPtr(0),
                                          cachedNodeid(-1),
                                          peersTableContextMenu(nullptr),
                                          banTableContextMenu(nullptr)
{
    ui->setupUi(this);
    GUIUtil::restoreWindowGeometry("nRPCConsoleWindow", this->size(), this);

#ifndef Q_OS_MAC
    ui->openDebugLogfileButton->setIcon(QIcon(":/icons/export"));
#endif

    // Install event filter for up and down arrow
    ui->lineEdit->installEventFilter(this);
    ui->messagesWidget->installEventFilter(this);

    connect(ui->clearButton, &QPushButton::clicked, this, &RPCConsole::clear);
    connect(ui->btnClearTrafficGraph, &QPushButton::clicked, ui->trafficGraph, &TrafficGraphWidget::clear);

    // Wallet Repair Buttons
    connect(ui->btn_salvagewallet, &QPushButton::clicked, this, &RPCConsole::walletSalvage);
    connect(ui->btn_rescan, &QPushButton::clicked, this, &RPCConsole::walletRescan);
    connect(ui->btn_zapwallettxes1, &QPushButton::clicked, this, &RPCConsole::walletZaptxes1);
    connect(ui->btn_zapwallettxes2, &QPushButton::clicked, this, &RPCConsole::walletZaptxes2);
    connect(ui->btn_upgradewallet, &QPushButton::clicked, this, &RPCConsole::walletUpgrade);
    connect(ui->btn_reindex, &QPushButton::clicked, this, &RPCConsole::walletReindex);
    connect(ui->btn_resync, &QPushButton::clicked, this, &RPCConsole::walletResync);

    // set library version labels
#ifdef ENABLE_WALLET
    ui->berkeleyDBVersion->setText(DbEnv::version(0, 0, 0));
#else

    ui->label_berkeleyDBVersion->hide();
    ui->berkeleyDBVersion->hide();
#endif
    // Register RPC timer interface
    rpcTimerInterface = new QtRPCTimerInterface();
    // avoid accidentally overwriting an existing, non QTThread
    // based timer interface
    RPCSetTimerInterfaceIfUnset(rpcTimerInterface);

    startExecutor();
    setTrafficGraphRange(INITIAL_TRAFFIC_GRAPH_MINS);

    ui->peerHeading->setText(tr("Select a peer to view detailed information."));

    clear();
}

RPCConsole::~RPCConsole()
{
    GUIUtil::saveWindowGeometry("nRPCConsoleWindow", this);
    Q_EMIT stopExecutor();
    RPCUnsetTimerInterface(rpcTimerInterface);
    delete rpcTimerInterface;
    delete ui;
}

bool RPCConsole::eventFilter(QObject* obj, QEvent* event)
{
    if (event->type() == QEvent::KeyPress) // Special key handling
    {
        QKeyEvent* keyevt = static_cast<QKeyEvent*>(event);
        int key = keyevt->key();
        Qt::KeyboardModifiers mod = keyevt->modifiers();
        switch (key) {
        case Qt::Key_Up:
            if (obj == ui->lineEdit) {
                browseHistory(-1);
                return true;
            }
            break;
        case Qt::Key_Down:
            if (obj == ui->lineEdit) {
                browseHistory(1);
                return true;
            }
            break;
        case Qt::Key_PageUp: /* pass paging keys to messages widget */
        case Qt::Key_PageDown:
            if (obj == ui->lineEdit) {
                QApplication::postEvent(ui->messagesWidget, new QKeyEvent(*keyevt));
                return true;
            }
            break;
        case Qt::Key_Return:
        case Qt::Key_Enter:
            // forward these events to lineEdit
            if(obj == autoCompleter->popup()) {
                QApplication::postEvent(ui->lineEdit, new QKeyEvent(*keyevt));
                return true;
            }
            break;
        default:
            // Typing in messages widget brings focus to line edit, and redirects key there
            // Exclude most combinations and keys that emit no text, except paste shortcuts
            if (obj == ui->messagesWidget && ((!mod && !keyevt->text().isEmpty() && key != Qt::Key_Tab) ||
                                                 ((mod & Qt::ControlModifier) && key == Qt::Key_V) ||
                                                 ((mod & Qt::ShiftModifier) && key == Qt::Key_Insert))) {
                ui->lineEdit->setFocus();
                QApplication::postEvent(ui->lineEdit, new QKeyEvent(*keyevt));
                return true;
            }
        }
    }
    return QDialog::eventFilter(obj, event);
}

void RPCConsole::setClientModel(ClientModel* model)
{
    clientModel = model;
    ui->trafficGraph->setClientModel(model);
    if (model && clientModel->getPeerTableModel() && clientModel->getBanTableModel()) {
        // Keep up to date with client
        setNumConnections(model->getNumConnections());
        connect(model, &ClientModel::numConnectionsChanged, this, &RPCConsole::setNumConnections);

        setNumBlocks(model->getNumBlocks());
        connect(model, &ClientModel::numBlocksChanged, this, &RPCConsole::setNumBlocks);

        connect(model, &ClientModel::strMasternodesChanged, this, &RPCConsole::setMasternodeCount);

        updateTrafficStats(model->getTotalBytesRecv(), model->getTotalBytesSent());
        connect(model, &ClientModel::bytesChanged, this, &RPCConsole::updateTrafficStats);

        // set up peer table
        ui->peerWidget->setModel(model->getPeerTableModel());
        ui->peerWidget->verticalHeader()->hide();
        ui->peerWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
        ui->peerWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
        ui->peerWidget->setSelectionMode(QAbstractItemView::SingleSelection);
        ui->peerWidget->setContextMenuPolicy(Qt::CustomContextMenu);
        ui->peerWidget->setColumnWidth(PeerTableModel::Address, ADDRESS_COLUMN_WIDTH);
        ui->peerWidget->setColumnWidth(PeerTableModel::Subversion, SUBVERSION_COLUMN_WIDTH);
        ui->peerWidget->setColumnWidth(PeerTableModel::Ping, PING_COLUMN_WIDTH);
        ui->peerWidget->horizontalHeader()->setStretchLastSection(true);

        // create peer table context menu actions
        QAction* disconnectAction = new QAction(tr("&Disconnect Node"), this);
        QAction* banAction1h      = new QAction(tr("Ban Node for") + " " + tr("1 &hour"), this);
        QAction* banAction24h     = new QAction(tr("Ban Node for") + " " + tr("1 &day"), this);
        QAction* banAction7d      = new QAction(tr("Ban Node for") + " " + tr("1 &week"), this);
        QAction* banAction365d    = new QAction(tr("Ban Node for") + " " + tr("1 &year"), this);

        // create peer table context menu
        peersTableContextMenu = new QMenu();
        peersTableContextMenu->addAction(disconnectAction);
        peersTableContextMenu->addAction(banAction1h);
        peersTableContextMenu->addAction(banAction24h);
        peersTableContextMenu->addAction(banAction7d);
        peersTableContextMenu->addAction(banAction365d);

        connect(banAction1h, &QAction::triggered, [this] { banSelectedNode(60 * 60); });
        connect(banAction24h, &QAction::triggered, [this] { banSelectedNode(60 * 60 * 24); });
        connect(banAction7d, &QAction::triggered, [this] { banSelectedNode(60 * 60 * 24 * 7); });
        connect(banAction365d, &QAction::triggered, [this] { banSelectedNode(60 * 60 * 24 * 365); });

        // peer table context menu signals
        connect(ui->peerWidget, &QTableView::customContextMenuRequested, this, &RPCConsole::showPeersTableContextMenu);
        connect(disconnectAction, &QAction::triggered, this, &RPCConsole::disconnectSelectedNode);

        // peer table signal handling - update peer details when selecting new node
        connect(ui->peerWidget->selectionModel(), &QItemSelectionModel::selectionChanged, this, &RPCConsole::peerSelected);
        // peer table signal handling - update peer details when new nodes are added to the model
        connect(model->getPeerTableModel(), &PeerTableModel::layoutChanged, this, &RPCConsole::peerLayoutChanged);

        // set up ban table
        ui->banlistWidget->setModel(model->getBanTableModel());
        ui->banlistWidget->verticalHeader()->hide();
        ui->banlistWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
        ui->banlistWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
        ui->banlistWidget->setSelectionMode(QAbstractItemView::SingleSelection);
        ui->banlistWidget->setContextMenuPolicy(Qt::CustomContextMenu);
        ui->banlistWidget->setColumnWidth(BanTableModel::Address, BANSUBNET_COLUMN_WIDTH);
        ui->banlistWidget->setColumnWidth(BanTableModel::Bantime, BANTIME_COLUMN_WIDTH);
        ui->banlistWidget->horizontalHeader()->setStretchLastSection(true);

        // create ban table context menu action
        QAction* unbanAction = new QAction(tr("&Unban Node"), this);

        // create ban table context menu
        banTableContextMenu = new QMenu();
        banTableContextMenu->addAction(unbanAction);

        // ban table context menu signals
        connect(ui->banlistWidget, &QTableView::customContextMenuRequested, this, &RPCConsole::showBanTableContextMenu);
        connect(unbanAction, &QAction::triggered, this, &RPCConsole::unbanSelectedNode);

        // ban table signal handling - clear peer details when clicking a peer in the ban table
        connect(ui->banlistWidget, &QTableView::clicked, this, &RPCConsole::clearSelectedNode);
        // ban table signal handling - ensure ban table is shown or hidden (if empty)
        connect(model->getBanTableModel(), &BanTableModel::layoutChanged, this, &RPCConsole::showOrHideBanTableIfRequired);
        showOrHideBanTableIfRequired();

        // Provide initial values
        ui->clientVersion->setText(model->formatFullVersion());
        ui->clientName->setText(model->clientName());
        ui->dataDir->setText(model->dataDir());
        ui->startupTime->setText(model->formatClientStartupTime());
        ui->networkName->setText(QString::fromStdString(Params().NetworkIDString()));

        //Setup autocomplete and attach it
        QStringList wordList;
        std::vector<std::string> commandList = tableRPC.listCommands();
        for (size_t i = 0; i < commandList.size(); ++i)
        {
            wordList << commandList[i].c_str();
            wordList << ("help " + commandList[i]).c_str();
        }

        wordList << "help-console";
        wordList.sort();
        autoCompleter = new QCompleter(wordList, this);
        autoCompleter->setModelSorting(QCompleter::CaseSensitivelySortedModel);
        ui->lineEdit->setCompleter(autoCompleter);

        // clear the lineEdit after activating from QCompleter
        autoCompleter->popup()->installEventFilter(this);
    }
}

void RPCConsole::setWalletModel(WalletModel* model)
{
    walletModel = model;
    if (walletModel) {
        ui->wallet_path->setText(walletModel->getWalletPath());
    }
}

/** Restart wallet with "-salvagewallet" */
void RPCConsole::walletSalvage()
{
    buildParameterlist(SALVAGEWALLET);
}

/** Restart wallet with "-rescan" */
void RPCConsole::walletRescan()
{
    buildParameterlist(RESCAN);
}

/** Restart wallet with "-zapwallettxes=1" */
void RPCConsole::walletZaptxes1()
{
    buildParameterlist(ZAPTXES1);
}

/** Restart wallet with "-zapwallettxes=2" */
void RPCConsole::walletZaptxes2()
{
    buildParameterlist(ZAPTXES2);
}

/** Restart wallet with "-upgradewallet" */
void RPCConsole::walletUpgrade()
{
    buildParameterlist(UPGRADEWALLET);
}

/** Restart wallet with "-reindex" */
void RPCConsole::walletReindex()
{
    buildParameterlist(REINDEX);
}

/** Restart wallet with "-resync" */
void RPCConsole::walletResync()
{
    QString resyncWarning = tr("This will delete your local blockchain folders and the wallet will synchronize the complete Blockchain from scratch.

");
        resyncWarning +=   tr("This needs quite some time and downloads a lot of data.

");
        resyncWarning +=   tr("Your transactions and funds will be visible again after the download has completed.

");
        resyncWarning +=   tr("Do you want to continue?.
");
    QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm resync Blockchain"),
        resyncWarning,
        QMessageBox::Yes | QMessageBox::Cancel,
        QMessageBox::Cancel);

    if (retval != QMessageBox::Yes) {
        // Resync canceled
        return;
    }

    // Restart and resync
    buildParameterlist(RESYNC);
}

/** Build command-line parameter list for restart */
void RPCConsole::buildParameterlist(QString arg)
{
    // Get command-line arguments and remove the application name
    QStringList args = QApplication::arguments();
    args.removeFirst();

    // Remove existing repair-options
    args.removeAll(SALVAGEWALLET);
    args.removeAll(RESCAN);
    args.removeAll(ZAPTXES1);
    args.removeAll(ZAPTXES2);
    args.removeAll(UPGRADEWALLET);
    args.removeAll(REINDEX);

    // Append repair parameter to command line.
    args.append(arg);

    // Send command-line arguments to BitcoinGUI::handleRestart()
    Q_EMIT handleRestart(args);
}

void RPCConsole::clear()
{
    ui->messagesWidget->clear();
    history.clear();
    historyPtr = 0;
    ui->lineEdit->clear();
    ui->lineEdit->setFocus();

    // Add smoothly scaled icon images.
    // (when using width/height on an img, Qt uses nearest instead of linear interpolation)
    for (int i = 0; ICON_MAPPING[i].url; ++i) {
        ui->messagesWidget->document()->addResource(
            QTextDocument::ImageResource,
            QUrl(ICON_MAPPING[i].url),
            QImage(ICON_MAPPING[i].source).scaled(ICON_SIZE, Qt::IgnoreAspectRatio, Qt::SmoothTransformation));
    }

    // Set default style sheet
    ui->messagesWidget->document()->setDefaultStyleSheet(
        "table { }"
        "td.time { color: #808080; padding-top: 3px; } "
        "td.message { font-family: Courier, Courier New, Lucida Console, monospace; font-size: 12px; } " // Todo: Remove fixed font-size
        "td.cmd-request { color: #006060; } "
        "td.cmd-error { color: red; } "
        ".secwarning { color: red; }"
        "b { color: #006060; } ");

#ifdef Q_OS_MAC
    QString clsKey = "(⌘)-L";
#else
    QString clsKey = "Ctrl-L";
#endif

    message(RPCExecutor::CMD_REPLY, (tr("Welcome to the PIVX RPC console.") + "
" +
                        tr("Use up and down arrows to navigate history, and %1 to clear screen.").arg(""+clsKey+"") + "
" +
                        tr("Type %1 for an overview of available commands.").arg("help") + "
" +
                        tr("For more information on using this console type %1.").arg("help-console") +
                        "

" +
                        tr("WARNING: Scammers have been active, telling users to type commands here, stealing their wallet contents. Do not use this console without fully understanding the ramifications of a command.") +
                        ""),
                        true);
}

void RPCConsole::reject()
{
    // Ignore escape keypress if this is not a seperate window
    if (windowType() != Qt::Widget)
        QDialog::reject();
}

void RPCConsole::message(int category, const QString& message, bool html)
{
    QTime time = QTime::currentTime();
    QString timeString = time.toString();
    QString out;
    out += "

" + timeString + "	";
    out += "	";
    out += "";
    if (html)
        out += message;
    else
        out += GUIUtil::HtmlEscape(message, true);
    out += "

";
    ui->messagesWidget->append(out);
}

void RPCConsole::setNumConnections(int count)
{
    if (!clientModel)
        return;

    QString connections = QString::number(count) + " (";
    connections += tr("In:") + " " + QString::number(clientModel->getNumConnections(CONNECTIONS_IN)) + " / ";
    connections += tr("Out:") + " " + QString::number(clientModel->getNumConnections(CONNECTIONS_OUT)) + ")";

    ui->numberOfConnections->setText(connections);
}

void RPCConsole::setNumBlocks(int count)
{
    ui->numberOfBlocks->setText(QString::number(count));
    if (clientModel) {
        ui->lastBlockTime->setText(clientModel->getLastBlockDate().toString());
        ui->lastBlockHash->setText(clientModel->getLastBlockHash());
    }
}

void RPCConsole::setMasternodeCount(const QString& strMasternodes)
{
    ui->masternodeCount->setText(strMasternodes);
}

void RPCConsole::on_lineEdit_returnPressed()
{
    QString cmd = ui->lineEdit->text();
    ui->lineEdit->clear();

    if (!cmd.isEmpty()) {
        message(RPCExecutor::CMD_REQUEST, cmd);
        Q_EMIT cmdRequest(cmd);
        // Remove command, if already in history
        history.removeOne(cmd);
        // Append command to history
        history.append(cmd);
        // Enforce maximum history size
        while (history.size() > CONSOLE_HISTORY)
            history.removeFirst();
        // Set pointer to end of history
        historyPtr = history.size();
        // Scroll console view to end
        scrollToEnd();
    }
}

void RPCConsole::browseHistory(int offset)
{
    historyPtr += offset;
    if (historyPtr < 0)
        historyPtr = 0;
    if (historyPtr > history.size())
        historyPtr = history.size();
    QString cmd;
    if (historyPtr < history.size())
        cmd = history.at(historyPtr);
    ui->lineEdit->setText(cmd);
}

void RPCConsole::startExecutor()
{
    QThread* thread = new QThread;
    RPCExecutor* executor = new RPCExecutor();
    executor->moveToThread(thread);

    // Replies from executor object must go to this object
    connect(executor, &RPCExecutor::reply, this, static_cast<void (RPCConsole::*)(int, const QString&)>(&RPCConsole::message));
    // Requests from this object must go to executor
    connect(this, &RPCConsole::cmdRequest, executor, &RPCExecutor::request);

    // On stopExecutor signal
    // - queue executor for deletion (in execution thread)
    // - quit the Qt event loop in the execution thread
    connect(this, &RPCConsole::stopExecutor, executor, &RPCExecutor::deleteLater);
    connect(this, &RPCConsole::stopExecutor, thread, &QThread::quit);
    // Queue the thread for deletion (in this thread) when it is finished
    connect(thread, &QThread::finished, thread, &QThread::deleteLater);

    // Default implementation of QThread::run() simply spins up an event loop in the thread,
    // which is what we want.
    thread->start();
}

void RPCConsole::on_tabWidget_currentChanged(int index)
{
    if (ui->tabWidget->widget(index) == ui->tab_console) {
        ui->lineEdit->setFocus();
    } else if (ui->tabWidget->widget(index) != ui->tab_peers) {
        clearSelectedNode();
    }
}

void RPCConsole::on_openDebugLogfileButton_clicked()
{
    GUIUtil::openDebugLogfile();
}

void RPCConsole::scrollToEnd()
{
    QScrollBar* scrollbar = ui->messagesWidget->verticalScrollBar();
    scrollbar->setValue(scrollbar->maximum());
}

void RPCConsole::on_sldGraphRange_valueChanged(int value)
{
    const int multiplier = 5; // each position on the slider represents 5 min
    int mins = value * multiplier;
    setTrafficGraphRange(mins);
}

QString RPCConsole::FormatBytes(quint64 bytes)
{
    if (bytes < 1024)
        return QString(tr("%1 B")).arg(bytes);
    if (bytes < 1024 * 1024)
        return QString(tr("%1 KB")).arg(bytes / 1024);
    if (bytes < 1024 * 1024 * 1024)
        return QString(tr("%1 MB")).arg(bytes / 1024 / 1024);

    return QString(tr("%1 GB")).arg(bytes / 1024 / 1024 / 1024);
}

void RPCConsole::setTrafficGraphRange(int mins)
{
    ui->trafficGraph->setGraphRangeMins(mins);
    ui->lblGraphRange->setText(GUIUtil::formatDurationStr(mins * 60));
}

void RPCConsole::updateTrafficStats(quint64 totalBytesIn, quint64 totalBytesOut)
{
    ui->lblBytesIn->setText(FormatBytes(totalBytesIn));
    ui->lblBytesOut->setText(FormatBytes(totalBytesOut));
}

void RPCConsole::showInfo()
{
    ui->tabWidget->setCurrentIndex(0);
    show();
}

void RPCConsole::showConsole()
{
    ui->tabWidget->setCurrentIndex(1);
    show();
}

void RPCConsole::showNetwork()
{
    ui->tabWidget->setCurrentIndex(2);
    show();
}

void RPCConsole::showPeers()
{
    ui->tabWidget->setCurrentIndex(3);
    show();
}

void RPCConsole::showRepair()
{
    ui->tabWidget->setCurrentIndex(4);
    show();
}

void RPCConsole::showConfEditor()
{
    GUIUtil::openConfigfile();
}

void RPCConsole::showMNConfEditor()
{
    GUIUtil::openMNConfigfile();
}

void RPCConsole::peerSelected(const QItemSelection& selected, const QItemSelection& deselected)
{
    Q_UNUSED(deselected);

    if (!clientModel || !clientModel->getPeerTableModel() || selected.indexes().isEmpty())
        return;

    const CNodeCombinedStats* stats = clientModel->getPeerTableModel()->getNodeStats(selected.indexes().first().row());
    if (stats)
        updateNodeDetail(stats);
}

void RPCConsole::peerLayoutChanged()
{
    if (!clientModel || !clientModel->getPeerTableModel())
        return;

    const CNodeCombinedStats* stats = NULL;
    bool fUnselect = false;
    bool fReselect = false;

    if (cachedNodeid == -1) // no node selected yet
        return;

    // find the currently selected row
    int selectedRow = -1;
    QModelIndexList selectedModelIndex = ui->peerWidget->selectionModel()->selectedIndexes();
    if (!selectedModelIndex.isEmpty()) {
        selectedRow = selectedModelIndex.first().row();
    }

    // check if our detail node has a row in the table (it may not necessarily
    // be at selectedRow since its position can change after a layout change)
    int detailNodeRow = clientModel->getPeerTableModel()->getRowByNodeId(cachedNodeid);

    if (detailNodeRow < 0) {
        // detail node dissapeared from table (node disconnected)
        fUnselect = true;
    } else {
        if (detailNodeRow != selectedRow) {
            // detail node moved position
            fUnselect = true;
            fReselect = true;
        }

        // get fresh stats on the detail node.
        stats = clientModel->getPeerTableModel()->getNodeStats(detailNodeRow);
    }

    if (fUnselect && selectedRow >= 0) {
        clearSelectedNode();
    }

    if (fReselect) {
        ui->peerWidget->selectRow(detailNodeRow);
    }

    if (stats)
        updateNodeDetail(stats);
}

void RPCConsole::updateNodeDetail(const CNodeCombinedStats* stats)
{
    // Update cached nodeid
    cachedNodeid = stats->nodeStats.nodeid;

    // update the detail ui with latest node information
    QString peerAddrDetails(QString::fromStdString(stats->nodeStats.addrName) + " ");
    peerAddrDetails += tr("(node id: %1)").arg(QString::number(stats->nodeStats.nodeid));
    if (!stats->nodeStats.addrLocal.empty())
        peerAddrDetails += "
" + tr("via %1").arg(QString::fromStdString(stats->nodeStats.addrLocal));
    ui->peerHeading->setText(peerAddrDetails);
    ui->peerServices->setText(GUIUtil::formatServicesStr(stats->nodeStats.nServices));
    ui->peerLastSend->setText(stats->nodeStats.nLastSend ? GUIUtil::formatDurationStr(GetSystemTimeInSeconds() - stats->nodeStats.nLastSend) : tr("never"));
    ui->peerLastRecv->setText(stats->nodeStats.nLastRecv ? GUIUtil::formatDurationStr(GetSystemTimeInSeconds() - stats->nodeStats.nLastRecv) : tr("never"));
    ui->peerBytesSent->setText(FormatBytes(stats->nodeStats.nSendBytes));
    ui->peerBytesRecv->setText(FormatBytes(stats->nodeStats.nRecvBytes));
    ui->peerConnTime->setText(GUIUtil::formatDurationStr(GetSystemTimeInSeconds() - stats->nodeStats.nTimeConnected));
    ui->peerPingTime->setText(GUIUtil::formatPingTime(stats->nodeStats.dPingTime));
    ui->peerPingWait->setText(GUIUtil::formatPingTime(stats->nodeStats.dPingWait));
    ui->timeoffset->setText(GUIUtil::formatTimeOffset(stats->nodeStats.nTimeOffset));
    ui->peerVersion->setText(QString("%1").arg(QString::number(stats->nodeStats.nVersion)));
    ui->peerSubversion->setText(QString::fromStdString(stats->nodeStats.cleanSubVer));
    ui->peerDirection->setText(stats->nodeStats.fInbound ? tr("Inbound") : tr("Outbound"));
    ui->peerHeight->setText(QString("%1").arg(QString::number(stats->nodeStats.nStartingHeight)));
    ui->peerWhitelisted->setText(stats->nodeStats.fWhitelisted ? tr("Yes") : tr("No"));

    // This check fails for example if the lock was busy and
    // nodeStateStats couldn't be fetched.
    if (stats->fNodeStateStatsAvailable) {
        // Ban score is init to 0
        ui->peerBanScore->setText(QString("%1").arg(stats->nodeStateStats.nMisbehavior));

        // Sync height is init to -1
        if (stats->nodeStateStats.nSyncHeight > -1)
            ui->peerSyncHeight->setText(QString("%1").arg(stats->nodeStateStats.nSyncHeight));
        else
            ui->peerSyncHeight->setText(tr("Unknown"));

        // Common height is init to -1
        if (stats->nodeStateStats.nCommonHeight > -1)
            ui->peerCommonHeight->setText(QString("%1").arg(stats->nodeStateStats.nCommonHeight));
        else
            ui->peerCommonHeight->setText(tr("Unknown"));
    }

    ui->detailWidget->show();
}

void RPCConsole::resizeEvent(QResizeEvent* event)
{
    QWidget::resizeEvent(event);
}

void RPCConsole::showEvent(QShowEvent* event)
{
    QWidget::showEvent(event);

    if (!clientModel || !clientModel->getPeerTableModel())
        return;

    // start PeerTableModel auto refresh
    clientModel->getPeerTableModel()->startAutoRefresh();
    clientModel->startMasternodesTimer();
}

void RPCConsole::hideEvent(QHideEvent* event)
{
    QWidget::hideEvent(event);

    if (!clientModel || !clientModel->getPeerTableModel())
        return;

    // stop PeerTableModel auto refresh
    clientModel->getPeerTableModel()->stopAutoRefresh();
    clientModel->stopMasternodesTimer();
}

void RPCConsole::showBackups()
{
    GUIUtil::showBackups();
}

void RPCConsole::showPeersTableContextMenu(const QPoint& point)
{
    QModelIndex index = ui->peerWidget->indexAt(point);
    if (index.isValid())
    peersTableContextMenu->exec(QCursor::pos());
}

void RPCConsole::showBanTableContextMenu(const QPoint& point)
{
    QModelIndex index = ui->banlistWidget->indexAt(point);
    if (index.isValid())
        banTableContextMenu->exec(QCursor::pos());
}

void RPCConsole::disconnectSelectedNode()
{
    if(!g_connman)
        return;
    // Get currently selected peer address
    NodeId id = GUIUtil::getEntryData(ui->peerWidget, 0, PeerTableModel::NetNodeId).toInt();
    // Find the node, disconnect it and clear the selected node
    if(g_connman->DisconnectNode(id))
        clearSelectedNode();
}

void RPCConsole::banSelectedNode(int bantime)
{
    if (!clientModel || !g_connman)
        return;

    // Get currently selected peer address
    QString strNode = GUIUtil::getEntryData(ui->peerWidget, 0, PeerTableModel::Address).toString();
    // Find possible nodes, ban it and clear the selected node
    std::string nStr = strNode.toStdString();
    std::string addr;
    int port = 0;
    SplitHostPort(nStr, port, addr);

    CNetAddr resolved;
    if (!LookupHost(addr.c_str(), resolved, false))
        return;
    g_connman->Ban(resolved, BanReasonManuallyAdded, bantime);
    clearSelectedNode();
    clientModel->getBanTableModel()->refresh();
}

void RPCConsole::unbanSelectedNode()
{
    if (!clientModel)
        return;

    // Get currently selected ban address
    QString strNode = GUIUtil::getEntryData(ui->banlistWidget, 0, BanTableModel::Address).toString();
    CSubNet possibleSubnet;

    LookupSubNet(strNode.toStdString().c_str(), possibleSubnet);
    if (possibleSubnet.IsValid() && g_connman)
    {
        g_connman->Unban(possibleSubnet);
        clientModel->getBanTableModel()->refresh();
    }
}

void RPCConsole::clearSelectedNode()
{
    ui->peerWidget->selectionModel()->clearSelection();
    cachedNodeid = -1;
    ui->detailWidget->hide();
    ui->peerHeading->setText(tr("Select a peer to view detailed information."));
}

void RPCConsole::showOrHideBanTableIfRequired()
{
    if (!clientModel)
        return;

    bool visible = clientModel->getBanTableModel()->shouldShow();
    ui->banlistWidget->setVisible(visible);
    ui->banHeading->setVisible(visible);
}


text:
@implementation IGCellData
@synthesize type,icon,subTitle,title,value,desc;

#pragma mark - 构造方法
+(instancetype)dataWithType:(int)type andTitle:(NSString*)atitle{
    return [IGCellData dataWithType:type andTitle:atitle icon:nil subTitle:nil desc:nil vaule:nil];
}
+(instancetype)dataWithType:(int)type andTitle:(NSString*)atitle vaule:(NSObject*)avalue{
    return [IGCellData dataWithType:type andTitle:atitle icon:nil subTitle:nil desc:nil vaule:avalue];
}

+(instancetype)dataWithType:(int)type andTitle:(NSString*)atitle subTitle:(NSString*)asubtitle{
    return [IGCellData dataWithType:type andTitle:atitle icon:nil subTitle:asubtitle desc:nil vaule:nil];
}
+(instancetype)dataWithType:(int)type andTitle:(NSString*)atitle subTitle:(NSString*)asubtitle vaule:(NSObject*)avalue{
    return [IGCellData dataWithType:type andTitle:atitle icon:nil subTitle:asubtitle desc:nil vaule:avalue];
}

+(instancetype)dataWithType:(int)type andTitle:(NSString*)atitle icon:(UIImage*)aicon{
    return [IGCellData dataWithType:type andTitle:atitle icon:aicon subTitle:nil desc:nil vaule:nil];
}
+(instancetype)dataWithType:(int)type andTitle:(NSString*)atitle icon:(UIImage*)aicon vaule:(NSObject*)avalue{
    return [IGCellData dataWithType:type andTitle:atitle icon:aicon subTitle:nil desc:nil vaule:avalue];
}

+(instancetype)dataWithType:(int)type andTitle:(NSString*)atitle icon:(UIImage*)aicon subTitle:(NSString*)asubtitle{
    return [IGCellData dataWithType:type andTitle:atitle icon:aicon subTitle:asubtitle desc:nil vaule:nil];
}
+(instancetype)dataWithType:(int)type andTitle:(NSString*)atitle icon:(UIImage*)aicon subTitle:(NSString*)asubtitle vaule:(NSObject*)avalue{
    return [IGCellData dataWithType:type andTitle:atitle icon:aicon subTitle:asubtitle desc:nil vaule:avalue];
}

+(instancetype)dataWithType:(int)type andTitle:(NSString*)atitle icon:(UIImage*)aicon subTitle:(NSString*)asubtitle desc:(NSString*)aDesc vaule:(NSObject*)avalue{
    IGCellData *option = [[IGCellData alloc] init];
    option.type        = type;
    option.title       = atitle;
    option.icon        = aicon;
    option.subTitle    = asubtitle;
    option.value       = avalue;
    option.desc        = aDesc;
    return option;
}

-(NSString *)description{
    return [NSString stringWithFormat:@"\n type -> %d \n title -> %@ \n subTitle -> %@ \n icon -> %@ \n value -> %@ \n desc -> %@\n",type,title,subTitle,icon,value,desc];
}
@end


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="16dp">

    <TextView
        android:id="@+id/labelEvent"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:text="Event:" />

    <Spinner
        android:id="@+id/selectEvent"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/labelEvent"
        android:layout_marginBottom="8dp"
        android:entries="@array/events" />

    <TextView
        android:id="@+id/labelTeam"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/selectEvent"
        android:layout_marginBottom="8dp"
        android:text="Team:" />

    <Spinner
        android:id="@+id/selectTeam"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/labelTeam"
        android:layout_marginBottom="8dp"
        android:entries="@array/teams" />

    <TextView
        android:id="@+id/labelMessage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/selectTeam"
        android:layout_marginBottom="8dp"
        android:text="Message" />

    <EditText
        android:id="@+id/input_message"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/labelMessage"
        android:maxLines="1"
        android:singleLine="true" />

    <Button
        android:id="@+id/buttom_Submit"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/input_message"
        android:layout_marginTop="8dp"
        android:backgroundTint="@color/colorAccent"
        android:text="Submit"
        android:textColor="@android:color/white" />

</RelativeLayout>