text:
package com.likya.tlossw.web.definitions.helpers;

import java.math.BigInteger;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;

import javax.faces.model.SelectItem;

import org.apache.xmlbeans.GDuration;
import org.apache.xmlbeans.XmlCursor;

import com.likya.tlos.model.xmlbeans.common.CalendarsDocument.Calendars;
import com.likya.tlos.model.xmlbeans.common.DatetimeType;
import com.likya.tlos.model.xmlbeans.common.TriggerDocument.Trigger;
import com.likya.tlos.model.xmlbeans.common.TypeOfTimeType;
import com.likya.tlos.model.xmlbeans.data.EventTypeDefDocument.EventTypeDef;
import com.likya.tlos.model.xmlbeans.data.JsPlannedTimeDocument.JsPlannedTime;
import com.likya.tlos.model.xmlbeans.data.ManagementDocument.Management;
import com.likya.tlos.model.xmlbeans.data.PeriodInfoDocument.PeriodInfo;
import com.likya.tlossw.web.definitions.JSBasePanelMBean;
import com.likya.tlossw.web.utils.DefinitionUtils;

public class ManagementTabBean {

	private JSBasePanelMBean jsBasePanelMBean;
	// time management
	private boolean useManagement = false;

	private boolean isPeriodic;
	private String trigger;
	private String eventTypeDef;

	private boolean useCalendarDef = false;
	private Collection<SelectItem> calendarNameList = null;
	private String[] calendarList;
	private Date specificDate;
	private String startDate;
	private String startTime;
	private String stopTime;

	private String jobTimeOutValue;
	//private String jobTimeOutUnit;

	private String expectedTime;
	//private String expectedTimeUnit;

	private String tolerancePercentage;
	private String minPercentage;

	private boolean defineStopTime = false;

	private String selectedTZone;

	private boolean relativeTimeOption = false;

	private String selectedTypeOfTime;

	private boolean isScenario = false;

	/* periodic job */
	private String periodTime;
	private int maxCount;
	private boolean relativeStart = true;

	public ManagementTabBean(JSBasePanelMBean jsBasePanelMBean, boolean isScenario, boolean isPeriodic) {
		super();
		this.isScenario = isScenario;
		this.jsBasePanelMBean = jsBasePanelMBean;
		this.isPeriodic = isPeriodic;
	}

	public void resetTab() {

		startDate = "";
		startTime = "";
		defineStopTime = false;
		stopTime = "";
		useCalendarDef = false;
		periodTime = "";
		maxCount = 0;
		relativeStart = true;

		selectedTZone = new String("Europe/Istanbul");
		selectedTypeOfTime = new String("Actual");
		relativeTimeOption = false;
		jobTimeOutValue = "3";
		//jobTimeOutUnit = Unit.HOURS.toString();
		expectedTime = "";
		//expectedTimeUnit = Unit.HOURS.toString();
		tolerancePercentage = "10";
		minPercentage = "10";

		isPeriodic = false;
		trigger = Trigger.TIME.toString();
		eventTypeDef = EventTypeDef.FILE.toString();

	}

	public void fillManagement(Management management) {

		Calendars calendars = Calendars.Factory.newInstance();

		Calendar jobStartDate = management.getTimeManagement().getJsPlannedTime().getStartTime().getDate();
		startDate = "";
		if (jobStartDate != null) {
			String dateOutputFormat = new String("dd.MM.yyyy");
			startDate = DefinitionUtils.dateToStringDate(jobStartDate.getTime(), selectedTZone, dateOutputFormat);
		}

		if (useCalendarDef) {
			for (int i = 0; i < calendarList.length; i++) {
					calendars.addCalendarId(new BigInteger(calendarList[i]));
			}

		}
		management.getTimeManagement().setCalendars(calendars);

		if (!startDate.isEmpty()) {
			Calendar date = Calendar.getInstance();
			date.setTime(specificDate);management.getTimeManagement().getJsPlannedTime().getStartTime().getDate();
			management.getTimeManagement().getJsPlannedTime().getStartTime().setDate(date);
		}
		management.setTrigger(Trigger.Enum.forString(trigger));

		// event tabanli bir is ise event turunu set ediyor
		if (trigger.equals(Trigger.EVENT.toString())) {
			management.setEventTypeDef(EventTypeDef.Enum.forString(eventTypeDef));
		}

		// periyodik is ise onunla ilgili alanlari dolduruyor

		// boolean isPeriodic = management.getPeriodInfo() != null ? true : false;

		if (isPeriodic) {
			if (management.getPeriodInfo() == null) {
				management.addNewPeriodInfo();
			}
			PeriodInfo periodInfo = management.getPeriodInfo();
			periodInfo.setComment("No Comment");
			// periodInfo.setStep(DefinitionUtils.dateToXmlTime(periodTime, jobBasePanelBean.getTimeManagementTabBean().getSelectedTZone()));

			String myArr[] = periodTime.split(":");
			String gDurationStr = "PT" + myArr[0] + "H" + myArr[1] + "M" + myArr[2] + "S";

			GDuration gDuration = new GDuration(gDurationStr);

			periodInfo.setStep(gDuration);
			if (maxCount > 0) {
				periodInfo.setMaxCount(BigInteger.valueOf(maxCount));
			}

			periodInfo.setRelativeStart(relativeStart);
		}

		// ekrandan starttime girildiyse onu set ediyor
		if (startTime != null && !startTime.equals("")) {

			if (management.getTimeManagement().getJsPlannedTime() == null) {
				JsPlannedTime jsPlannedTime = JsPlannedTime.Factory.newInstance();
				DatetimeType startTimeX = DatetimeType.Factory.newInstance();
				jsPlannedTime.setStartTime(startTimeX);
				management.getTimeManagement().setJsPlannedTime(jsPlannedTime);
			}

			JsPlannedTime jsPlannedTime = management.getTimeManagement().getJsPlannedTime();
			jsPlannedTime.getStartTime().setTime(DefinitionUtils.dateToXmlTime(startTime, selectedTZone));

			// ekrandan stoptime girildiyse onu set ediyor, bunu starttime
			// girildiyse kontrol ediyor cunku start time olmadan stop time
			// tanimi yapilmiyor
			if (defineStopTime) {
				DatetimeType jsStopTime = DatetimeType.Factory.newInstance();
				jsStopTime.setTime(DefinitionUtils.dateToXmlTime(stopTime, selectedTZone));

				jsPlannedTime.setStopTime(jsStopTime);

			} else if (jsPlannedTime.getStopTime() != null) {
				XmlCursor xmlCursor = jsPlannedTime.getStopTime().newCursor();
				xmlCursor.removeXml();
			}

		} else if (management.getTimeManagement().getJsPlannedTime() != null) {
			XmlCursor xmlCursor = management.getTimeManagement().getJsPlannedTime().newCursor();
			xmlCursor.removeXml();
		}
		management.getTimeManagement().setJsRelativeTimeOption(relativeTimeOption);

		if (jobTimeOutValue != null && !jobTimeOutValue.equals("")) {
			if (management.getTimeControl().getJsTimeOut() == null) {
				DatetimeType jsTimeOut = DatetimeType.Factory.newInstance();
				management.getTimeControl().setJsTimeOut(jsTimeOut);
			}
			management.getTimeControl().getJsTimeOut().setTime(DefinitionUtils.dateToXmlTime(jobTimeOutValue, "Zulu"));
		}

		if (tolerancePercentage != null && !tolerancePercentage.equals("")) {
			management.getTimeControl().setTolerancePercentage(Integer.parseInt(tolerancePercentage));
		}

		if (minPercentage != null && !minPercentage.equals("")) {
			management.getTimeControl().setMinPercentage(Integer.parseInt(minPercentage));
		}

		// expectedTime girildiyse ilgili alanlar set ediliyor
		if (expectedTime != null && !expectedTime.equals("")) {
			DatetimeType jsExpectedTime = DatetimeType.Factory.newInstance();
			jsExpectedTime.setTime(DefinitionUtils.dateToXmlTime(expectedTime, "Zulu"));

			management.getTimeControl().setExpectedTime(jsExpectedTime);

		} else if (management.getTimeControl().getExpectedTime() != null) {
			XmlCursor xmlCursor = management.getTimeControl().getExpectedTime().newCursor();
			xmlCursor.removeXml();
		}

		management.getTimeManagement().setTimeZone(selectedTZone);
		management.getTimeManagement().setTypeOfTime(TypeOfTimeType.Enum.forString(selectedTypeOfTime));

		System.out.println("nedir" + management.getTimeManagement().toString());
	}

	public void fillManagementTab(Management management) {

		if (management.getTimeManagement() != null && management.getTimeManagement().getCalendars() != null && management.getTimeManagement().getCalendars().sizeOfCalendarIdArray() > 0) {
			useCalendarDef = true;
			int sizeOfArray = management.getTimeManagement().getCalendars().sizeOfCalendarIdArray();
			calendarList = new String[sizeOfArray];
			for (int i = 0; i < sizeOfArray; i++) {
				calendarList[i] = management.getTimeManagement().getCalendars().getCalendarIdArray(i).toString();
			}
		} else {
			useCalendarDef = false;
		}

		if(management.getTrigger() != null) {
		  trigger = management.getTrigger().toString();
		} else {
			trigger = "";
		}
		isPeriodic = management.getPeriodInfo() != null ? true : false;

		if (trigger.equals(Trigger.EVENT.toString())) {
			eventTypeDef = management.getEventTypeDef().toString();
		}

		if (isPeriodic) {
			PeriodInfo periodInfo = management.getPeriodInfo();
			// String timeOutputFormat = new String("HH:mm:ss");
			periodTime = DefinitionUtils.getDurationString(periodInfo.getStep());
			// periodTime = DefinitionUtils.calendarToStringTimeFormat(periodInfo.getStep(), jobBasePanelBean.getTimeManagementTabBean().getSelectedTZone(), timeOutputFormat);
			// periodTime = periodInfo.getStep().getHour() + ":" + periodInfo.getStep().getMinute() + ":" + periodInfo.getStep().getSecond();
			if (periodInfo.getMaxCount() != null) {
				maxCount = periodInfo.getMaxCount().intValue();
			}

			relativeStart = periodInfo.getRelativeStart();
		}

		String timeOutputFormat = new String("HH:mm:ss.SSS");
		String timeOutputFormatHms = new String("HH:mm:ss");

		useManagement = false;
		if (management != null && management.getTimeManagement() != null) {
			useManagement = true;

			if (management.getTimeManagement().getJsPlannedTime() != null)
				if (management.getTimeManagement().getJsPlannedTime().getStartTime() != null) {

					Calendar jobStartTime = management.getTimeManagement().getJsPlannedTime().getStartTime().getTime();
					Calendar jobStartDate = management.getTimeManagement().getJsPlannedTime().getStartTime().getDate();

					// DateTimeZone zone = DateTimeZone.forID(selectedTZone);
					// DateTimeFormatter dtf = DateTimeFormat.forPattern("HH:mm:ss.SSSZZ");
					// LocalTime localStartTime = dtf.parseLocalTime(jobStartTime);
					//
					// DateTimeFormatter formatter = DateTimeFormat.forPattern("HH:mm:ss");
					// String jobLocalStartTime = localStartTime.toDateTimeToday(zone).toString(formatter);

					startTime = DefinitionUtils.calendarTimeToStringTimeFormat(jobStartTime, selectedTZone, timeOutputFormat);

					if (jobStartDate != null) {
						String dateOutputFormat = new String("dd.MM.yyyy");
						startDate = DefinitionUtils.dateToStringDate(jobStartDate.getTime(), selectedTZone, dateOutputFormat);
					}
				}
			if (management.getTimeManagement().getJsPlannedTime().getStopTime() != null) {
				defineStopTime = true;

				Calendar jobStopTime = management.getTimeManagement().getJsPlannedTime().getStopTime().getTime();
				// LocalTime jobLocalStopTime = new LocalTime( jobStopTime);
				stopTime = DefinitionUtils.calendarTimeToStringTimeFormat(jobStopTime, selectedTZone, timeOutputFormat);
				// stopTime = jobLocalStopTime.toString();
				// LocalTime localStopTime = dtf.parseLocalTime(jobStopTime);
				//
				// String jobLocalStopTime = localStopTime.toDateTimeToday(zone).toString(formatter);

			}

			if (management.getTimeManagement().getJsRelativeTimeOption()) {
				relativeTimeOption = management.getTimeManagement().getJsRelativeTimeOption();
			}

			if (management.getTimeManagement().getTimeZone() != null)
				selectedTZone = management.getTimeManagement().getTimeZone();

			if (management.getTimeManagement().getTypeOfTime() != null)
				selectedTypeOfTime = management.getTimeManagement().getTypeOfTime().toString();

		}

		if (management != null && management.getTimeControl() != null) {

			DatetimeType jsTimeOutTime = management.getTimeControl().getJsTimeOut();

			if ( jsTimeOutTime.getTime() != null) {
				jobTimeOutValue = DefinitionUtils.calendarTimeToStringTimeFormat(jsTimeOutTime.getTime(), "Zulu", timeOutputFormatHms);
			}

			if (management.getTimeControl().getExpectedTime() != null) {
				DatetimeType jsExpectedTime = management.getTimeControl().getExpectedTime();

				if (jsExpectedTime.getTime() != null) {
					expectedTime = DefinitionUtils.calendarTimeToStringTimeFormat( jsExpectedTime.getTime(), "Zulu", timeOutputFormatHms ); ;
				}
			}

			// job taniminda bu alan yoksa degeri sifir geliyor
			if (management.getTimeControl().getTolerancePercentage() > 0) {
				tolerancePercentage = management.getTimeControl().getTolerancePercentage() + "";
			}

			// job taniminda bu alan yoksa degeri sifir geliyor
			if (management.getTimeControl().getMinPercentage() > 0) {
				minPercentage = management.getTimeControl().getMinPercentage() + "";
			}

			useManagement = true;
		}
	}

	public String getPeriodTime() {
		return periodTime;
	}

	public void setPeriodTime(String periodTime) {
		this.periodTime = periodTime;
	}

	public int getMaxCount() {
		return maxCount;
	}

	public void setMaxCount(int maxCount) {
		this.maxCount = maxCount;
	}

	public boolean isRelativeStart() {
		return relativeStart;
	}

	public void setRelativeStart(boolean relativeStart) {
		this.relativeStart = relativeStart;
	}

	public boolean isUseManagement() {
		return useManagement;
	}

	public void setUseManagement(boolean useManagement) {
		this.useManagement = useManagement;
	}

	public String getStartTime() {
		return startTime;
	}

	public void setStartTime(String startTime) {
		this.startTime = startTime;
	}

	public String getStopTime() {
		return stopTime;
	}

	public void setStopTime(String stopTime) {
		this.stopTime = stopTime;
	}

	public String getJobTimeOutValue() {
		return jobTimeOutValue;
	}

	public void setJobTimeOutValue(String jobTimeOutValue) {
		this.jobTimeOutValue = jobTimeOutValue;
	}

	public String getExpectedTime() {
		return expectedTime;
	}

	public void setExpectedTime(String expectedTime) {
		this.expectedTime = expectedTime;
	}

	public String getTolerancePercentage() {
		return tolerancePercentage;
	}

	public void setTolerancePercentage(String tolerancePercentage) {
		this.tolerancePercentage = tolerancePercentage;
	}

	public String getMinPercentage() {
		return minPercentage;
	}

	public void setMinPercentage(String minPercentage) {
		this.minPercentage = minPercentage;
	}

	public boolean isDefineStopTime() {
		return defineStopTime;
	}

	public void setDefineStopTime(boolean defineStopTime) {
		this.defineStopTime = defineStopTime;
	}

	public Collection<SelectItem> getTzList() {
		return jsBasePanelMBean.getTzList();
	}

	public String getSelectedTZone() {
		return selectedTZone;
	}

	public void setSelectedTZone(String selectedTZone) {
		this.selectedTZone = selectedTZone;
	}

	public boolean getRelativeTimeOption() {
		return relativeTimeOption;
	}

	public void setRelativeTimeOption(boolean relativeTimeOption) {
		this.relativeTimeOption = relativeTimeOption;
	}

	// public Collection<SelectItem> getRelativeTimeOptionList() {
	// return jsBasePanelMBean.getRelativeTimeOptionList();
	// }

	public String getSelectedTypeOfTime() {
		return selectedTypeOfTime;
	}

	public void setSelectedTypeOfTime(String selectedTypeOfTime) {
		this.selectedTypeOfTime = selectedTypeOfTime;
	}

	public Collection<SelectItem> getTypeOfTimeList() {
		return jsBasePanelMBean.getTypeOfTimeList();
	}

	public Collection<SelectItem> getUnitTypeList() {
		return jsBasePanelMBean.getUnitTypeList();
	}

	public boolean isScenario() {
		return isScenario;
	}

	public JSBasePanelMBean getJsBasePanelMBean() {
		return jsBasePanelMBean;
	}

	public void setJsBasePanelMBean(JSBasePanelMBean jsBasePanelMBean) {
		this.jsBasePanelMBean = jsBasePanelMBean;
	}

	public String getStartDate() {
		return startDate;
	}

	public void setStartDate(String startDate) {
		this.startDate = startDate;
	}

	public Date getSpecificDate() {
		if (!startDate.isEmpty())
			specificDate = DefinitionUtils.stringToCalendar(startDate, "dd.MM.yyyy", selectedTZone).getTime();
		return specificDate;
	}

	public void setSpecificDate(Date specificDate) {
		String date = DefinitionUtils.dateToStringDate(specificDate, selectedTZone, "dd.MM.yyyy");
		startDate = date;

		this.specificDate = specificDate;
	}

	public String getEventTypeDef() {
		return eventTypeDef;
	}

	public void setEventTypeDef(String eventTypeDef) {
		this.eventTypeDef = eventTypeDef;
	}

	public Collection<SelectItem> getEventTypeDefList() {
		return jsBasePanelMBean.getEventTypeDefList();
	}

	public Collection<SelectItem> getTriggerList() {
		return jsBasePanelMBean.getTriggerList();
	}

	public boolean isUseCalendarDef() {
		return useCalendarDef;
	}

	public void setUseCalendarDef(boolean useCalendarDef) {
		this.useCalendarDef = useCalendarDef;
	}

	public String[] getCalendarList() {
		return calendarList;
	}

	public void setCalendarList(String[] calendarList) {
		this.calendarList = calendarList;
	}

	public boolean isPeriodic() {
		return isPeriodic;
	}

	public void setPeriodic(boolean isPeriodic) {
		this.isPeriodic = isPeriodic;
	}

	public String getTrigger() {
		return trigger;
	}

	public void setTrigger(String trigger) {
		this.trigger = trigger;
	}

	public Collection<SelectItem> getCalendarNameList() {
		return calendarNameList;
	}

	public void setCalendarNameList(Collection<SelectItem> calendarNameList) {
		this.calendarNameList = calendarNameList;
	}

}


text:
class RedisRestore
  attr_accessor :src_rdb, :src_db

  def initialize(atts={})
    self.src_rdb = atts[:src_rdb] || raise('src_rdb is required')
    self.src_db  = atts[:src_db] || raise('src_db is required')
  end

  def restore
    RedisReload::Reloader.new(reloader_options).reload
  end

  def reloader_options
    {
        rdb_filename: self.src_rdb,
        source_db:    self.src_db,
        redis_host:   Settings.redis_host,
        redis_port:   Settings.redis_port,
        target_db:    Settings.redis_db
    }
  end
end

redpajama_set_name: RedPajamaGithub


text:
.class final Lcom/android/server/power/ShutdownThread$1;
.super Landroid/content/BroadcastReceiver;
.source "ShutdownThread.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/server/power/ShutdownThread;
.end annotation

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

# direct methods
.method constructor <init>()V
    .locals 0

    invoke-direct {p0}, Landroid/content/BroadcastReceiver;-><init>()V

    return-void
.end method

# virtual methods
.method public onReceive(Landroid/content/Context;Landroid/content/Intent;)V
    .locals 8

    const/4 v6, 0x1

    invoke-static {}, Lcom/android/server/power/ShutdownThread;->-get30()Ljava/lang/Object;

    move-result-object v3

    monitor-enter v3

    :try_start_0
    invoke-static {}, Lcom/android/server/power/ShutdownThread;->-get25()Lcom/android/server/power/ShutdownThread;

    move-result-object v2

    invoke-static {v2}, Lcom/android/server/power/ShutdownThread;->-get9(Lcom/android/server/power/ShutdownThread;)Landroid/content/Context;

    move-result-object v2

    invoke-virtual {v2}, Landroid/content/Context;->getResources()Landroid/content/res/Resources;

    move-result-object v2

    invoke-virtual {v2}, Landroid/content/res/Resources;->getConfiguration()Landroid/content/res/Configuration;

    move-result-object v0

    iget v2, v0, Landroid/content/res/Configuration;->semDesktopModeEnabled:I

    if-ne v2, v6, :cond_1

    const/4 v1, 0x1

    :goto_0
    invoke-static {}, Lcom/android/server/power/ShutdownThread;->-get6()Z

    move-result v2

    if-eq v2, v1, :cond_0

    const-string/jumbo v2, "ShutdownThread"

    new-instance v4, Ljava/lang/StringBuilder;

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

    const-string/jumbo v5, "Dex mode different, pre is "

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

    move-result-object v4

    invoke-static {}, Lcom/android/server/power/ShutdownThread;->-get6()Z

    move-result v5

    invoke-virtual {v4, v5}, Ljava/lang/StringBuilder;->append(Z)Ljava/lang/StringBuilder;

    move-result-object v4

    const-string/jumbo v5, ", cur is "

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

    move-result-object v4

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

    move-result-object v4

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

    move-result-object v4

    invoke-static {v2, v4}, Lcom/android/server/power/ShutdownThread$Slog;->d(Ljava/lang/String;Ljava/lang/String;)I

    invoke-static {v1}, Lcom/android/server/power/ShutdownThread;->-set2(Z)Z

    invoke-static {}, Lcom/android/server/power/ShutdownThread;->-get31()I

    move-result v2

    if-ne v2, v6, :cond_2

    const-string/jumbo v2, "ShutdownThread"

    const-string/jumbo v4, "Dex mode is changed, need to create a new dialog for UI"

    invoke-static {v2, v4}, Lcom/android/server/power/ShutdownThread$Slog;->i(Ljava/lang/String;Ljava/lang/String;)I

    invoke-static {}, Lcom/android/server/power/ShutdownThread;->-get25()Lcom/android/server/power/ShutdownThread;

    move-result-object v2

    invoke-static {v2}, Lcom/android/server/power/ShutdownThread;->-get12(Lcom/android/server/power/ShutdownThread;)Landroid/app/ProgressDialog;

    move-result-object v2

    invoke-virtual {v2}, Landroid/app/ProgressDialog;->dismiss()V

    invoke-static {}, Lcom/android/server/power/ShutdownThread;->-get25()Lcom/android/server/power/ShutdownThread;

    move-result-object v2

    invoke-static {}, Lcom/android/server/power/ShutdownThread;->-get25()Lcom/android/server/power/ShutdownThread;

    move-result-object v4

    invoke-static {v4}, Lcom/android/server/power/ShutdownThread;->-get9(Lcom/android/server/power/ShutdownThread;)Landroid/content/Context;

    move-result-object v4

    invoke-static {}, Lcom/android/server/power/ShutdownThread;->-get16()Z

    move-result v5

    invoke-static {}, Lcom/android/server/power/ShutdownThread;->-get21()Ljava/lang/CharSequence;

    move-result-object v6

    invoke-static {}, Lcom/android/server/power/ShutdownThread;->-get22()I

    move-result v7

    invoke-static {v4, v5, v6, v7}, Lcom/android/server/power/ShutdownThread;->-wrap0(Landroid/content/Context;ZLjava/lang/CharSequence;I)Landroid/app/ProgressDialog;

    move-result-object v4

    invoke-static {v2, v4}, Lcom/android/server/power/ShutdownThread;->-set4(Lcom/android/server/power/ShutdownThread;Landroid/app/ProgressDialog;)Landroid/app/ProgressDialog;

    invoke-static {}, Lcom/android/server/power/ShutdownThread;->-get25()Lcom/android/server/power/ShutdownThread;

    move-result-object v2

    invoke-static {v2}, Lcom/android/server/power/ShutdownThread;->-get12(Lcom/android/server/power/ShutdownThread;)Landroid/app/ProgressDialog;

    move-result-object v2

    invoke-virtual {v2}, Landroid/app/ProgressDialog;->show()V
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    :cond_0
    :goto_1
    monitor-exit v3

    return-void

    :cond_1
    const/4 v1, 0x0

    goto :goto_0

    :cond_2
    :try_start_1
    const-string/jumbo v2, "ShutdownThread"

    const-string/jumbo v4, "uncryptStep is NON STARTED"

    invoke-static {v2, v4}, Lcom/android/server/power/ShutdownThread$Slog;->i(Ljava/lang/String;Ljava/lang/String;)I
    :try_end_1
    .catchall {:try_start_1 .. :try_end_1} :catchall_0

    goto :goto_1

    :catchall_0
    move-exception v2

    monitor-exit v3

    throw v2
.end method


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs.Host.Executors;
using Microsoft.Azure.WebJobs.Host.Queues;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Azure.Storage.Queues;
using Azure.Storage.Queues.Models;
using System.Linq;
using Moq;
using Azure;
using Azure.WebJobs.Extensions.Storage.Common.Tests;
using NUnit.Framework;
using Azure.Core.TestFramework;
using Azure.WebJobs.Extensions.Storage.Queues;

namespace Microsoft.Azure.WebJobs.Host.FunctionalTests
{
    public class QueueProcessorTests : LiveTestBase<WebJobsTestEnvironment>
    {
        private QueueServiceClient _queueServiceClient;
        private QueueClient _queue;
        private QueueClient _poisonQueue;
        private QueueProcessor _processor;
        private QueuesOptions _queuesOptions;
        private static QueueProcessorTests.TestFixture _fixture;

        [OneTimeSetUp]
        public void OneTimeSetUp()
        {
            _fixture = new TestFixture();
        }

        [OneTimeTearDown]
        public void OneTimeTearDown()
        {
            _fixture.Dispose();
        }

        [SetUp]
        public void SetUp()
        {
            _queueServiceClient = _fixture.QueueClient;
            _queue = _fixture.Queue;
            _poisonQueue = _fixture.PoisonQueue;

            _queuesOptions = new QueuesOptions();
            QueueProcessorFactoryContext context = new QueueProcessorFactoryContext(_queue, null, _queuesOptions);
            _processor = new QueueProcessor(context);
        }

        [Test]
        public void Constructor_DefaultsValues()
        {
            var options = new QueuesOptions
            {
                BatchSize = 32,
                MaxDequeueCount = 2,
                NewBatchThreshold = 100,
                VisibilityTimeout = TimeSpan.FromSeconds(30),
                MaxPollingInterval = TimeSpan.FromSeconds(15)
            };
            QueueProcessorFactoryContext context = new QueueProcessorFactoryContext(_queue, null, options);
            QueueProcessor localProcessor = new QueueProcessor(context);

            Assert.AreEqual(options.BatchSize, localProcessor.BatchSize);
            Assert.AreEqual(options.MaxDequeueCount, localProcessor.MaxDequeueCount);
            Assert.AreEqual(options.NewBatchThreshold, localProcessor.NewBatchThreshold);
            Assert.AreEqual(options.VisibilityTimeout, localProcessor.VisibilityTimeout);
            Assert.AreEqual(options.MaxPollingInterval, localProcessor.MaxPollingInterval);
        }

        [Test]
        public async Task CompleteProcessingMessageAsync_Success_DeletesMessage()
        {
            await _queue.SendMessageAsync("Test Message");

            QueueMessage message = (await _queue.ReceiveMessagesAsync(1)).Value.FirstOrDefault();

            FunctionResult result = new FunctionResult(true);
            await _processor.CompleteProcessingMessageAsync(message, result, CancellationToken.None);

            message = (await _queue.ReceiveMessagesAsync(1)).Value.FirstOrDefault();
            Assert.Null(message);
        }

        [Test]
        public async Task CompleteProcessingMessageAsync_FailureWithoutPoisonQueue_DoesNotDeleteMessage()
        {
            await _queue.SendMessageAsync("Test Message");

            QueueMessage message = (await _queue.ReceiveMessagesAsync(1)).Value.FirstOrDefault();
            string id = message.MessageId;

            FunctionResult result = new FunctionResult(false);
            await _processor.CompleteProcessingMessageAsync(message, result, CancellationToken.None);

            // make the message visible again so we can verify it wasn't deleted
            await _queue.UpdateMessageAsync(message.MessageId, message.PopReceipt, visibilityTimeout: TimeSpan.Zero);

            message = (await _queue.ReceiveMessagesAsync(1)).Value.FirstOrDefault();
            Assert.NotNull(message);
            Assert.AreEqual(id, message.MessageId);
        }

        [Test]
        public async Task CompleteProcessingMessageAsync_MaxDequeueCountExceeded_MovesMessageToPoisonQueue()
        {
            QueueProcessorFactoryContext context = new QueueProcessorFactoryContext(_queue, null, _queuesOptions, _poisonQueue);
            QueueProcessor localProcessor = new QueueProcessor(context);

            bool poisonMessageHandlerCalled = false;
            localProcessor.MessageAddedToPoisonQueue += (sender, e) =>
                {
                    Assert.AreSame(sender, localProcessor);
                    Assert.AreSame(_poisonQueue, e.PoisonQueue);
                    Assert.NotNull(e.Message);
                    poisonMessageHandlerCalled = true;
                };

            string messageContent = Guid.NewGuid().ToString();
            QueueMessage message = null;
            await _queue.SendMessageAsync(messageContent);

            FunctionResult result = new FunctionResult(false);
            for (int i = 0; i < context.MaxDequeueCount; i++)
            {
                message = (await _queue.ReceiveMessagesAsync(1)).Value.FirstOrDefault();
                await localProcessor.CompleteProcessingMessageAsync(message, result, CancellationToken.None);
            }

            message = (await _queue.ReceiveMessagesAsync(1)).Value.FirstOrDefault();
            Assert.Null(message);

            QueueMessage poisonMessage = (await _poisonQueue.ReceiveMessagesAsync(1)).Value.FirstOrDefault();
            Assert.NotNull(poisonMessage);
            Assert.AreEqual(messageContent, poisonMessage.MessageText);
            Assert.True(poisonMessageHandlerCalled);
        }

        [Test]
        public async Task CompleteProcessingMessageAsync_Failure_AppliesVisibilityTimeout()
        {
            var queuesOptions = new QueuesOptions
            {
                // configure a non-zero visibility timeout
                VisibilityTimeout = TimeSpan.FromMinutes(5)
            };
            Mock<QueueClient> queueClientMock = new Mock<QueueClient>();
            TimeSpan updatedVisibilityTimeout = TimeSpan.Zero;

            queueClientMock.Setup(x => x.UpdateMessageAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<TimeSpan>(), It.IsAny<CancellationToken>()))
                .Callback((string messageId, string popReceipt, string messageText, TimeSpan visibilityTimeout, CancellationToken cancellationToken) =>
                {
                    updatedVisibilityTimeout = visibilityTimeout;
                })
                .ReturnsAsync(Response.FromValue(QueuesModelFactory.UpdateReceipt("x", DateTimeOffset.UtcNow.AddMinutes(5)), null));

            QueueProcessorFactoryContext context = new QueueProcessorFactoryContext(queueClientMock.Object, null, queuesOptions, _poisonQueue);
            QueueProcessor localProcessor = new QueueProcessor(context);

            string messageContent = Guid.NewGuid().ToString();
            await _queue.SendMessageAsync(messageContent);

            var functionResult = new FunctionResult(false);
            QueueMessage message = (await _queue.ReceiveMessagesAsync(1)).Value.FirstOrDefault();
            await localProcessor.CompleteProcessingMessageAsync(message, functionResult, CancellationToken.None);

            Assert.AreEqual(queuesOptions.VisibilityTimeout, updatedVisibilityTimeout);
        }

        [Test]
        public async Task BeginProcessingMessageAsync_MaxDequeueCountExceeded_MovesMessageToPoisonQueue()
        {
            QueueProcessorFactoryContext context = new QueueProcessorFactoryContext(_queue, null, _queuesOptions, _poisonQueue);
            QueueProcessor localProcessor = new QueueProcessor(context);

            bool poisonMessageHandlerCalled = false;
            localProcessor.MessageAddedToPoisonQueue += (sender, e) =>
            {
                Assert.AreSame(sender, localProcessor);
                Assert.AreSame(_poisonQueue, e.PoisonQueue);
                Assert.NotNull(e.Message);
                poisonMessageHandlerCalled = true;
            };

            string messageContent = Guid.NewGuid().ToString();
            await _queue.SendMessageAsync(messageContent);
            QueueMessage messageFromCloud = (await _queue.ReceiveMessagesAsync(1)).Value.FirstOrDefault();
            for (int i = 0; i < context.MaxDequeueCount; i++)
            {
                await _queue.UpdateMessageAsync(messageFromCloud.MessageId, messageFromCloud.PopReceipt, visibilityTimeout: TimeSpan.FromMilliseconds(0));
                messageFromCloud = (await _queue.ReceiveMessagesAsync(1)).Value.FirstOrDefault();
            }

            Assert.AreEqual(6, messageFromCloud.DequeueCount);
            bool continueProcessing = await localProcessor.BeginProcessingMessageAsync(messageFromCloud, CancellationToken.None);
            Assert.False(continueProcessing);

            QueueMessage poisonMessage = (await _poisonQueue.ReceiveMessagesAsync(1)).Value.FirstOrDefault();
            Assert.NotNull(poisonMessage);
            Assert.AreEqual(messageContent, poisonMessage.MessageText);
            Assert.True(poisonMessageHandlerCalled);
        }

        public class TestFixture : IDisposable
        {
            private const string TestQueuePrefix = "queueprocessortests";

            public TestFixture()
            {
                IHost host = new HostBuilder()
                    .ConfigureDefaultTestHost(b =>
                    {
                        b.AddAzureStorageQueues();
                    })
                    .Build();

                var queueServiceClientProvider = host.Services.GetService<QueueServiceClientProvider>();
                QueueServiceClient client = queueServiceClientProvider.GetHost();
                QueueClient = client;

                string queueName = string.Format("{0}-{1}", TestQueuePrefix, Guid.NewGuid());
                Queue = client.GetQueueClient(queueName);
                Queue.CreateIfNotExists();

                string poisonQueueName = string.Format("{0}-poison", queueName);
                PoisonQueue = client.GetQueueClient(poisonQueueName);
                PoisonQueue.CreateIfNotExists();
            }

            public QueueClient Queue
            {
                get;
                private set;
            }

            public QueueClient PoisonQueue
            {
                get;
                private set;
            }

            public QueueServiceClient QueueClient
            {
                get;
                private set;
            }

            public void Dispose()
            {
                var result = QueueClient.GetQueues(prefix: TestQueuePrefix);
                var tasks = new List<Task>();

                foreach (var queue in result)
                {
                    tasks.Add(QueueClient.GetQueueClient(queue.Name).DeleteAsync());
                }

                Task.WaitAll(tasks.ToArray());
            }
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Threading;
using dnlib.IO;
using dnlib.DotNet.MD;
using dnlib.DotNet.Pdb;

namespace dnlib.DotNet {
	///
	/// Type of resource
	///
	public enum ResourceType {
		///
		/// It's a <see cref="EmbeddedResource"/>
		///
		Embedded,

		///
		/// It's a <see cref="AssemblyLinkedResource"/>
		///
		AssemblyLinked,

		///
		/// It's a <see cref="LinkedResource"/>
		///
		Linked,
	}

	///
	/// Resource base class
	///
	public abstract class Resource : IMDTokenProvider, IHasCustomAttribute, IHasCustomDebugInformation {
		private protected uint rid;
		private protected uint? offset;
		UTF8String name;
		ManifestResourceAttributes flags;

		/// <inheritdoc/>
		public MDToken MDToken => new MDToken(Table.ManifestResource, rid);

		/// <inheritdoc/>
		public uint Rid {
			get => rid;
			set => rid = value;
		}

		///
		/// Gets/sets the offset of the resource
		///
		public uint? Offset {
			get => offset;
			set => offset = value;
		}

		///
		/// Gets/sets the name
		///
		public UTF8String Name {
			get => name;
			set => name = value;
		}

		///
		/// Gets/sets the flags
		///
		public ManifestResourceAttributes Attributes {
			get => flags;
			set => flags = value;
		}

		///
		/// Gets the type of resource
		///
		public abstract ResourceType ResourceType { get; }

		///
		/// Gets/sets the visibility
		///
		public ManifestResourceAttributes Visibility {
			get => flags & ManifestResourceAttributes.VisibilityMask;
			set => flags = (flags & ~ManifestResourceAttributes.VisibilityMask) | (value & ManifestResourceAttributes.VisibilityMask);
		}

		///
		/// <c>true</c> if <see cref="ManifestResourceAttributes.Public"/> is set
		///
		public bool IsPublic => (flags & ManifestResourceAttributes.VisibilityMask) == ManifestResourceAttributes.Public;

		///
		/// <c>true</c> if <see cref="ManifestResourceAttributes.Private"/> is set
		///
		public bool IsPrivate => (flags & ManifestResourceAttributes.VisibilityMask) == ManifestResourceAttributes.Private;

		/// <inheritdoc/>
		public int HasCustomAttributeTag => 18;

		///
		/// Gets all custom attributes
		///
		public CustomAttributeCollection CustomAttributes {
			get {
				if (customAttributes is null)
					InitializeCustomAttributes();
				return customAttributes;
			}
		}
		///
		protected CustomAttributeCollection customAttributes;
		/// Initializes <see cref="customAttributes"/>
		protected virtual void InitializeCustomAttributes() =>
			Interlocked.CompareExchange(ref customAttributes, new CustomAttributeCollection(), null);

		/// <inheritdoc/>
		public bool HasCustomAttributes => CustomAttributes.Count > 0;

		/// <inheritdoc/>
		public int HasCustomDebugInformationTag => 18;

		///
		/// Gets all custom debug infos
		///
		public IList<PdbCustomDebugInfo> CustomDebugInfos {
			get {
				if (customDebugInfos is null)
					InitializeCustomDebugInfos();
				return customDebugInfos;
			}
		}
		///
		protected IList<PdbCustomDebugInfo> customDebugInfos;
		/// Initializes <see cref="customDebugInfos"/>
		protected virtual void InitializeCustomDebugInfos() =>
			Interlocked.CompareExchange(ref customDebugInfos, new List<PdbCustomDebugInfo>(), null);

		/// <inheritdoc/>
		public bool HasCustomDebugInfos => CustomDebugInfos.Count > 0;

		///
		/// Constructor
		///
		/// <param name="name">Name</param>
		/// <param name="flags">flags</param>
		protected Resource(UTF8String name, ManifestResourceAttributes flags) {
			this.name = name;
			this.flags = flags;
		}
	}

	///
	/// A resource that is embedded in a .NET module. This is the most common type of resource.
	///
	public class EmbeddedResource : Resource {
		readonly DataReaderFactory dataReaderFactory;
		readonly uint resourceStartOffset;
		readonly uint resourceLength;

		///
		/// Gets the length of the data
		///
		public uint Length => resourceLength;

		/// <inheritdoc/>
		public override ResourceType ResourceType => ResourceType.Embedded;

		///
		/// Constructor
		///
		/// <param name="name">Name of resource</param>
		/// <param name="data">Resource data</param>
		/// <param name="flags">Resource flags</param>
		public EmbeddedResource(UTF8String name, byte[] data, ManifestResourceAttributes flags = ManifestResourceAttributes.Private)
			: this(name, ByteArrayDataReaderFactory.Create(data, filename: null), 0, (uint)data.Length, flags) {
		}

		///
		/// Constructor
		///
		/// <param name="name">Name of resource</param>
		/// <param name="dataReaderFactory">Data reader factory</param>
		/// <param name="offset">Offset of resource data</param>
		/// <param name="length">Length of resource data</param>
		/// <param name="flags">Resource flags</param>
		public EmbeddedResource(UTF8String name, DataReaderFactory dataReaderFactory, uint offset, uint length, ManifestResourceAttributes flags = ManifestResourceAttributes.Private)
			: base(name, flags) {
			this.dataReaderFactory = dataReaderFactory ?? throw new ArgumentNullException(nameof(dataReaderFactory));
			resourceStartOffset = offset;
			resourceLength = length;
		}

		///
		/// Gets a data reader that can access the resource
		///
		/// <returns></returns>
		public DataReader CreateReader() => dataReaderFactory.CreateReader(resourceStartOffset, resourceLength);

		/// <inheritdoc/>
		public override string ToString() => $"{UTF8String.ToSystemStringOrEmpty(Name)} - size: {(resourceLength)}";
	}

	sealed class EmbeddedResourceMD : EmbeddedResource, IMDTokenProviderMD {
		/// The module where this instance is located
		readonly ModuleDefMD readerModule;

		readonly uint origRid;

		/// <inheritdoc/>
		public uint OrigRid => origRid;

		/// <inheritdoc/>
		protected override void InitializeCustomAttributes() {
			var list = readerModule.Metadata.GetCustomAttributeRidList(Table.ManifestResource, origRid);
			var tmp = new CustomAttributeCollection(list.Count, list, (list2, index) => readerModule.ReadCustomAttribute(list[index]));
			Interlocked.CompareExchange(ref customAttributes, tmp, null);
		}

		/// <inheritdoc/>
		protected override void InitializeCustomDebugInfos() {
			var list = new List<PdbCustomDebugInfo>();
			readerModule.InitializeCustomDebugInfos(new MDToken(MDToken.Table, origRid), new GenericParamContext(), list);
			Interlocked.CompareExchange(ref customDebugInfos, list, null);
		}

		public EmbeddedResourceMD(ModuleDefMD readerModule, ManifestResource mr, byte[] data)
			: this(readerModule, mr, ByteArrayDataReaderFactory.Create(data, filename: null), 0, (uint)data.Length) {
		}

		public EmbeddedResourceMD(ModuleDefMD readerModule, ManifestResource mr, DataReaderFactory dataReaderFactory, uint offset, uint length)
			: base(mr.Name, dataReaderFactory, offset, length, mr.Flags) {
			this.readerModule = readerModule;
			origRid = rid = mr.Rid;
			this.offset = mr.Offset;
		}
	}

	///
	/// A reference to a resource in another assembly
	///
	public class AssemblyLinkedResource : Resource {
		AssemblyRef asmRef;

		/// <inheritdoc/>
		public override ResourceType ResourceType => ResourceType.AssemblyLinked;

		///
		/// Gets/sets the assembly reference
		///
		public AssemblyRef Assembly {
			get => asmRef;
			set => asmRef = value ?? throw new ArgumentNullException(nameof(value));
		}

		///
		/// Constructor
		///
		/// <param name="name">Name of resource</param>
		/// <param name="asmRef">Assembly reference</param>
		/// <param name="flags">Resource flags</param>
		public AssemblyLinkedResource(UTF8String name, AssemblyRef asmRef, ManifestResourceAttributes flags)
			: base(name, flags) => this.asmRef = asmRef ?? throw new ArgumentNullException(nameof(asmRef));

		/// <inheritdoc/>
		public override string ToString() => $"{UTF8String.ToSystemStringOrEmpty(Name)} - assembly: {asmRef.FullName}";
	}

	sealed class AssemblyLinkedResourceMD : AssemblyLinkedResource, IMDTokenProviderMD {
		/// The module where this instance is located
		readonly ModuleDefMD readerModule;

		readonly uint origRid;

		/// <inheritdoc/>
		public uint OrigRid => origRid;

		/// <inheritdoc/>
		protected override void InitializeCustomAttributes() {
			var list = readerModule.Metadata.GetCustomAttributeRidList(Table.ManifestResource, origRid);
			var tmp = new CustomAttributeCollection(list.Count, list, (list2, index) => readerModule.ReadCustomAttribute(list[index]));
			Interlocked.CompareExchange(ref customAttributes, tmp, null);
		}

		/// <inheritdoc/>
		protected override void InitializeCustomDebugInfos() {
			var list = new List<PdbCustomDebugInfo>();
			readerModule.InitializeCustomDebugInfos(new MDToken(MDToken.Table, origRid), new GenericParamContext(), list);
			Interlocked.CompareExchange(ref customDebugInfos, list, null);
		}

		public AssemblyLinkedResourceMD(ModuleDefMD readerModule, ManifestResource mr, AssemblyRef asmRef) : base(mr.Name, asmRef, mr.Flags) {
			this.readerModule = readerModule;
			origRid = rid = mr.Rid;
			offset = mr.Offset;
		}
	}

	///
	/// A resource that is stored in a file on disk
	///
	public class LinkedResource : Resource {
		FileDef file;

		/// <inheritdoc/>
		public override ResourceType ResourceType => ResourceType.Linked;

		///
		/// Gets/sets the file
		///
		public FileDef File {
			get => file;
			set => file = value ?? throw new ArgumentNullException(nameof(value));
		}

		///
		/// Gets/sets the hash
		///
		public byte[] Hash {
			get => file.HashValue;
			set => file.HashValue = value;
		}

		///
		/// Gets/sets the file name
		///
		public UTF8String FileName => file is null ? UTF8String.Empty : file.Name;

		///
		/// Constructor
		///
		/// <param name="name">Name of resource</param>
		/// <param name="file">The file</param>
		/// <param name="flags">Resource flags</param>
		public LinkedResource(UTF8String name, FileDef file, ManifestResourceAttributes flags)
			: base(name, flags) => this.file = file;

		/// <inheritdoc/>
		public override string ToString() => $"{UTF8String.ToSystemStringOrEmpty(Name)} - file: {UTF8String.ToSystemStringOrEmpty(FileName)}";
	}

	sealed class LinkedResourceMD : LinkedResource, IMDTokenProviderMD {
		/// The module where this instance is located
		readonly ModuleDefMD readerModule;

		readonly uint origRid;

		/// <inheritdoc/>
		public uint OrigRid => origRid;

		/// <inheritdoc/>
		protected override void InitializeCustomAttributes() {
			var list = readerModule.Metadata.GetCustomAttributeRidList(Table.ManifestResource, origRid);
			var tmp = new CustomAttributeCollection(list.Count, list, (list2, index) => readerModule.ReadCustomAttribute(list[index]));
			Interlocked.CompareExchange(ref customAttributes, tmp, null);
		}

		/// <inheritdoc/>
		protected override void InitializeCustomDebugInfos() {
			var list = new List<PdbCustomDebugInfo>();
			readerModule.InitializeCustomDebugInfos(new MDToken(MDToken.Table, origRid), new GenericParamContext(), list);
			Interlocked.CompareExchange(ref customDebugInfos, list, null);
		}

		public LinkedResourceMD(ModuleDefMD readerModule, ManifestResource mr, FileDef file) : base(mr.Name, file, mr.Flags) {
			this.readerModule = readerModule;
			origRid = rid = mr.Rid;
			offset = mr.Offset;
		}
	}
}


text:
namespace blink {

// Verify that the parameter is a link-extension which according to spec doesn't
// have to have a value.
static bool IsExtensionParameter(LinkHeader::LinkParameterName name) {
  return name >= LinkHeader::kLinkParameterUnknown;
}

static LinkHeader::LinkParameterName ParameterNameFromString(
    base::StringPiece name) {
  if (base::EqualsCaseInsensitiveASCII(name, "rel"))
    return LinkHeader::kLinkParameterRel;
  if (base::EqualsCaseInsensitiveASCII(name, "anchor"))
    return LinkHeader::kLinkParameterAnchor;
  if (base::EqualsCaseInsensitiveASCII(name, "crossorigin"))
    return LinkHeader::kLinkParameterCrossOrigin;
  if (base::EqualsCaseInsensitiveASCII(name, "title"))
    return LinkHeader::kLinkParameterTitle;
  if (base::EqualsCaseInsensitiveASCII(name, "media"))
    return LinkHeader::kLinkParameterMedia;
  if (base::EqualsCaseInsensitiveASCII(name, "type"))
    return LinkHeader::kLinkParameterType;
  if (base::EqualsCaseInsensitiveASCII(name, "rev"))
    return LinkHeader::kLinkParameterRev;
  if (base::EqualsCaseInsensitiveASCII(name, "referrerpolicy"))
    return LinkHeader::kLinkParameterReferrerPolicy;
  if (base::EqualsCaseInsensitiveASCII(name, "hreflang"))
    return LinkHeader::kLinkParameterHreflang;
  if (base::EqualsCaseInsensitiveASCII(name, "as"))
    return LinkHeader::kLinkParameterAs;
  if (base::EqualsCaseInsensitiveASCII(name, "nonce"))
    return LinkHeader::kLinkParameterNonce;
  if (base::EqualsCaseInsensitiveASCII(name, "integrity"))
    return LinkHeader::kLinkParameterIntegrity;
  if (base::EqualsCaseInsensitiveASCII(name, "imagesrcset"))
    return LinkHeader::kLinkParameterImageSrcset;
  if (base::EqualsCaseInsensitiveASCII(name, "imagesizes"))
    return LinkHeader::kLinkParameterImageSizes;
  if (base::EqualsCaseInsensitiveASCII(name, "anchor"))
    return LinkHeader::kLinkParameterAnchor;

  // "header-integrity" and "variants" and "variant-key" are used only for
  // SignedExchangeSubresourcePrefetch.
  if (base::EqualsCaseInsensitiveASCII(name, "header-integrity"))
    return LinkHeader::kLinkParameterHeaderIntegrity;
  if (base::EqualsCaseInsensitiveASCII(name, kSignedExchangeVariantsHeader))
    return LinkHeader::kLinkParameterVariants;
  if (base::EqualsCaseInsensitiveASCII(name, kSignedExchangeVariantKeyHeader))
    return LinkHeader::kLinkParameterVariantKey;

  if (RuntimeEnabledFeatures::BlockingAttributeEnabled() &&
      base::EqualsCaseInsensitiveASCII(name, "blocking")) {
    return LinkHeader::kLinkParameterBlocking;
  }

  return LinkHeader::kLinkParameterUnknown;
}

void LinkHeader::SetValue(LinkParameterName name, const String& value) {
  if (name == kLinkParameterRel && !rel_)
    rel_ = value.DeprecatedLower();
  else if (name == kLinkParameterAnchor)
    anchor_ = value;
  else if (name == kLinkParameterCrossOrigin)
    cross_origin_ = value;
  else if (name == kLinkParameterAs)
    as_ = value.DeprecatedLower();
  else if (name == kLinkParameterType)
    mime_type_ = value.DeprecatedLower();
  else if (name == kLinkParameterMedia)
    media_ = value.DeprecatedLower();
  else if (name == kLinkParameterNonce)
    nonce_ = value;
  else if (name == kLinkParameterIntegrity)
    integrity_ = value;
  else if (name == kLinkParameterImageSrcset)
    image_srcset_ = value;
  else if (name == kLinkParameterImageSizes)
    image_sizes_ = value;
  else if (name == kLinkParameterHeaderIntegrity)
    header_integrity_ = value;
  else if (name == kLinkParameterVariants)
    variants_ = value;
  else if (name == kLinkParameterVariantKey)
    variant_key_ = value;
  else if (name == kLinkParameterBlocking)
    blocking_ = value;
  else if (name == kLinkParameterReferrerPolicy)
    referrer_policy_ = value;
}

template <typename Iterator>
LinkHeader::LinkHeader(Iterator begin, Iterator end) : is_valid_(true) {
  std::string url;
  std::unordered_map<std::string, absl::optional<std::string>> params;
  is_valid_ = link_header_util::ParseLinkHeaderValue(begin, end, &url, &params);
  if (!is_valid_)
    return;

  url_ = String(&url[0], url.length());
  for (const auto& param : params) {
    LinkParameterName name = ParameterNameFromString(param.first);
    if (!IsExtensionParameter(name) && !param.second)
      is_valid_ = false;
    std::string value = param.second.value_or("");
    SetValue(name, String(&value[0], value.length()));
  }
  // According to Section 5.2 of RFC 5988, "anchor" parameters in Link headers
  // must be either respected, or the entire header must be ignored:
  // https://tools.ietf.org/html/rfc5988#section-5.2
  // Blink uses "anchor" parameters only for SignedExchangeSubresourcePrefetch
  // and the rel is "alternate".
  if (anchor_.has_value() && rel_ != "alternate")
    is_valid_ = false;
}

LinkHeaderSet::LinkHeaderSet(const String& header) {
  if (header.IsNull())
    return;

  DCHECK(header.Is8Bit()) << "Headers should always be 8 bit";
  std::string header_string(reinterpret_cast<const char*>(header.Characters8()),
                            header.length());
  for (const auto& value : link_header_util::SplitLinkHeader(header_string))
    header_set_.push_back(LinkHeader(value.first, value.second));
}

}  // namespace blink


text:
{% extends 'filizver/filizver_base.html' %}
{% block title %}{% blocktrans with profile.user.username as username %}{{ username }}'s profile.{% endblocktrans %}{% endblock %}
{% load relationship_tags %}

{% block main %}

      {% block profile_details %}
      {% thumbnail profile.get_picture_url "128x128" as im %}

      {% endthumbnail %}

{{ profile.user.topic_set.count }} {% trans "Topics" %}

{{ profile.user.entry_set.count }} {% trans "Entries" %}

{{ profile.user.relationships.following.count }} {% trans "Following" %}

{{ profile.user.relationships.followers.count }} {% trans "Followers" %}

      {% if request.user != profile.user %}

        {# decide whether or not the current user is following this user #}

        {% if_relationship request.user profile.user "following" %}

          {# they are following them, so show a "remove" url #}
          Unfollow

        {% else %}

          {# they are not following them, so show a link to start following #}
          Follow

        {% endif_relationship %}

      {% else %}

This is you!

      {% endif %}

      {% for topic in profile.user.topic_set.all %}

{{ topic }}

      {% endfor %}

          {% block profile_definition_list %}
            {% if profile.user.get_full_name %}

{% trans "Name" %}

{{ profile.user.get_full_name }}

            {% endif %}
            {% if profile.age %}

{% trans "Age" %}

{{ profile.age }}

            {% endif %}
            {% if profile.website %}

{% trans "website" %}

{{ profile.website|urlize }}

            {% endif %}
            {% if profile.location %}

{% trans "Location" %}

{{ profile.location }}

            {% endif %}
            {% if profile.about_me %}

{% trans "About me" %}

{{ profile.about_me }}

            {% endif %}
          {% endblock %}

      {% endblock %}

{% endblock %}


text: Users = new Mongo.Collection('users');


text:
steal('funcunit',function(){

module("Naxx.Bookmark.List", {
	setup: function(){
		S.open("//naxx/bookmark/list/list.html");
	}
});

test("delete bookmarks", function(){
	S('#create').click()

	// wait until grilled cheese has been added
	S('h3:contains(Grilled Cheese X)').exists();

	S.confirm(true);
	S('h3:last a').click();

	S('h3:contains(Grilled Cheese)').missing(function(){
		ok(true,"Grilled Cheese Removed")
	});

});

});


text:
$(function() {
    $('.SatoriDateField').datepick({dateFormat : 'yyyy-mm-dd'});
});


text:
<?php

namespace CotaPreco\Action;

use Symfony\Component\Routing\Route;

/**
 * @author Andrey K. Vital <andreykvital@gmail.com>
 */
final class ResolveableActionRoute extends Route
{
    /**
     * @param string          $method
     * @param array           $path
     * @param string|callable $action
     */
    public function __construct($method, $path, $action)
    {
        parent::__construct(
            $path,
            [
                'action' => $action
            ],
            [],
            [],
            null,
            [],
            $method,
            null
        );
    }
}


text:
/**
 * Created by bobtian on 16/2/3.
 */

function routes($stateProvider) {
    $stateProvider.state('domMultipleElements', {
        url: '/dom-multi-elements',
        templateUrl: './components/advanced/dom-multiple-elements/dme.tpl.html',
        controller: 'DomMultipleElementsController',
        controllerAs: 'dme'
    })
}

routes.$inject = ['$stateProvider'];

export default routes;


text:
package ncai.funcs;

/**
 * @author Petr Ivanov
 *
 */
public class GetThreadInfo01n extends Thread{
    public native void TestFunction();
    public native void TestFunction1();
    public static native boolean stopsignal();
    public static native void resumeagent();

    static boolean NoLibrary = false;
    static {
        try{
            System.loadLibrary("GetThreadInfo01n");
        }
        catch(Throwable e){
            NoLibrary = true;
        }
    }

    GetThreadInfo01n(String name)
    {
        super(name);
    }

    static public void main(String args[]) {
        if(NoLibrary) return;
        new GetThreadInfo01n("java_thread1").start();
        new GetThreadInfo01n("java_thread2").start();
        new GetThreadInfo01n("java_thread3").start();
        special_method();
        return;
    }

    public void test_java_func1(){
        System.out.println("thread - java func1\n");
        TestFunction1();
    }

    public void test_java_func2(){
        System.out.println("thread - java func2\n");
        test_java_func3();
    }

    public void test_java_func3(){
        System.out.println("thread - java func3\n");
    }

    static public void special_method() {
        /*
         * Transfer control to native part.
         */
        try {
            throw new InterruptedException();
        } catch (Throwable tex) { }
        return;
    }

    public void run() {
        System.out.println("thread - java run\n");
        test_java_func1();
    }
}


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/ads/googleads/v10/services/payments_account_service.proto

package com.google.ads.googleads.v10.services;

public interface ListPaymentsAccountsRequestOrBuilder extends
    // @@protoc_insertion_point(interface_extends:google.ads.googleads.v10.services.ListPaymentsAccountsRequest)
    com.google.protobuf.MessageOrBuilder {

  /**
   *

   * Required. The ID of the customer to apply the PaymentsAccount list operation to.
   *

   *
   * string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];
   * @return The customerId.
   */
  java.lang.String getCustomerId();
  /**
   *

   * Required. The ID of the customer to apply the PaymentsAccount list operation to.
   *

   *
   * string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];
   * @return The bytes for customerId.
   */
  com.google.protobuf.ByteString
      getCustomerIdBytes();
}


text:
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Device.Location;

namespace Transit.Models
{
	public class ShapePoint
	{
		[Key]
		[ScaffoldColumn(false)]
		public int id { get; set; }

		[Required]
		[DisplayName("Shape")]
		public int? shapeId { get; set; }

		[Required]
		[DisplayName("Lat")]
		public double latitude { get; set; }

		[Required]
		[DisplayName("Long")]
		public double longitude { get; set; }

		[DisplayName("Coordinate")]
		[ScaffoldColumn(false)]
		[ReadOnly(true)]
		public GeoCoordinate coordinate { get { return new GeoCoordinate { Longitude = longitude, Latitude = latitude }; } }

		[Required]
		[DisplayName("Order")]
		[Range(0,99999999, ErrorMessage= "Order/sequence must be a non-negative number.")]
		public int sequence { get; set; }

		[DisplayName("Distance")]
		[Required(AllowEmptyStrings= true)]
		[Range(0,999999999, ErrorMessage= "Distance must be a non-negative number.")]
		public double? distanceTraveled { get; set; }
	}
}


text:
"""Output the placement report from Google Ads to BigQuery."""
import base64
import json
from datetime import datetime, timedelta
import logging
import os
import sys
from typing import Any, Dict, Optional, Tuple
from google.ads.googleads.client import GoogleAdsClient
import jsonschema
import pandas as pd
from utils import gcs
from utils import pubsub

logging.basicConfig(stream=sys.stdout)
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)

# The Google Cloud project containing the GCS bucket
GOOGLE_CLOUD_PROJECT = os.environ.get('GOOGLE_CLOUD_PROJECT')
# The bucket to write the data to
APE_GCS_DATA_BUCKET = os.environ.get('APE_GCS_DATA_BUCKET')
# The pub/sub topic to send the success message to
APE_YOUTUBE_PUBSUB_TOPIC = os.environ.get('APE_YOUTUBE_PUBSUB_TOPIC')

# The schema of the JSON in the event payload
message_schema = {
    'type': 'object',
    'properties': {
        'sheet_id': {'type': 'string'},
        'customer_id': {'type': 'string'},
        'lookback_days': {'type': 'number'},
        'gads_filters': {'type': 'string'},
    },
    'required': ['sheet_id', 'customer_id', 'lookback_days', 'gads_filters', ]
}

def main(event: Dict[str, Any], context: Dict[str, Any]) -> None:
    """The entry point: extract the data from the payload and starts the job.

    The pub/sub message must match the message_schema object above.

    Args:
        event: A dictionary representing the event data payload.
        context: An object containing metadata about the event.
    """
    del context
    logger.info('Google Ads Reporting Service triggered.')
    logger.info('Message: %s', event)
    message = base64.b64decode(event['data']).decode('utf-8')
    logger.info('Decoded message: %s', message)
    message_json = json.loads(message)
    logger.info('JSON message: %s', message_json)

    # Will raise jsonschema.exceptions.ValidationError if the schema is invalid
    jsonschema.validate(instance=message_json, schema=message_schema)

    start_job(
        message_json.get('sheet_id'),
        message_json.get('customer_id'),
        message_json.get('lookback_days'),
        message_json.get('gads_filters'),
    )

    logger.info('Done')

def start_job(
        sheet_id: str,
        customer_id: str,
        lookback_days: int,
        gads_filters: str,
) -> None:
    """Start the job to run the report from Google Ads & output it.

    Args:
        sheet_id: the ID of the Google Sheet containing the config.
        customer_id: the customer ID to fetch the Google Ads data for.
        lookback_days: the number of days from today to look back when fetching
            the report.
        gads_filters: the filters to apply to the Google Ads report query
    """
    logger.info('Starting job to fetch data for %s', customer_id)
    report_df = get_report_df(customer_id, lookback_days, gads_filters)
    write_results_to_gcs(report_df, customer_id)
    send_messages_to_pubsub(customer_id, sheet_id)
    logger.info('Job complete')

def get_report_df(
        customer_id: str,
        lookback_days: int,
        gads_filters: str) -> pd.DataFrame:
    """Run the placement report in Google Ads & return a Dataframe of the data.

    Args:
        customer_id: the customer ID to fetch the Google Ads data for.
        lookback_days: the number of days from today to look back when fetching
            the report.
        gads_filters: the filters to apply to the Google Ads report query

    Returns:
        A Pandas DataFrame containing the report results.
    """
    logger.info('Getting report stream for %s', customer_id)
    now = datetime.now()
    client = GoogleAdsClient.load_from_env(version='v11')
    ga_service = client.get_service("GoogleAdsService")

    query = get_report_query(lookback_days, gads_filters)
    search_request = client.get_type("SearchGoogleAdsStreamRequest")
    search_request.customer_id = customer_id
    search_request.query = query
    stream = ga_service.search_stream(search_request)

    # The client and iterator needs to be in the same function, as per
    # https://github.com/googleads/google-ads-python/issues/384#issuecomment-791639397
    # So this can't be refactored out
    logger.info('Processing response stream')
    data = []
    for batch in stream:
        for row in batch.results:
            data.append([
                now,
                row.customer.id,
                row.group_placement_view.placement,
                row.group_placement_view.target_url,
                row.metrics.impressions,
                row.metrics.cost_micros,
                row.metrics.conversions,
                row.metrics.video_view_rate,
                row.metrics.video_views,
                row.metrics.clicks,
                row.metrics.average_cpm,
                row.metrics.ctr,
                row.metrics.all_conversions_from_interactions_rate,
            ])
    return pd.DataFrame(data, columns=[
        'datetime_updated',
        'customer_id',
        'channel_id',
        'placement_target_url',
        'impressions',
        'cost_micros',
        'conversions',
        'video_view_rate',
        'video_views',
        'clicks',
        'average_cpm',
        'ctr',
        'all_conversions_from_interactions_rate',
    ])

def get_report_query(lookback_days: int,
                     gads_filters: Optional[str] = None) -> str:
    """Build and return the Google Ads report query.

    Args:
        lookback_days: the number of days from today to look back when fetching
            the report.
        gads_filters: the filters to apply to the Google Ads report query

    Return:
        The Google Ads query.
    """
    logger.info('Getting report query')
    date_from, date_to = get_query_dates(lookback_days)
    where_query = ''
    if gads_filters is not None:
        where_query = f'AND {gads_filters}'
    query = f"""
        SELECT
            customer.id,
            group_placement_view.placement,
            group_placement_view.target_url,
            metrics.impressions,
            metrics.cost_micros,
            metrics.conversions,
            metrics.video_views,
            metrics.video_view_rate,
            metrics.clicks,
            metrics.average_cpm,
            metrics.ctr,
            metrics.all_conversions_from_interactions_rate
        FROM
            group_placement_view
        WHERE group_placement_view.placement_type = "YOUTUBE_CHANNEL"
            AND campaign.advertising_channel_type = "VIDEO"
            AND segments.date BETWEEN "{date_from}" AND "{date_to}"
            {where_query}
    """
    logger.info(query)
    return query

def get_query_dates(lookback_days: int,
                    today: datetime = None) -> Tuple[str, str]:
    """Return a tuple of string dates in %Y-%m-%d format for the GAds report.

    Google Ads queries require a string date in the above format. This function
    will lookback X days from today, and return this date as a string.

    Args:
        lookback_days: the number of days from today to look back when fetching
            the report.
        today: the date representing today. If no date is provided
            datetime.today() is used.

    Return:
        The string date
    """
    logger.info('Getting query dates')
    dt_format = '%Y-%m-%d'
    if today is None:
        today = datetime.today()
    date_from = today - timedelta(days=lookback_days)
    return (
        date_from.strftime(dt_format),
        today.strftime(dt_format),
    )

def write_results_to_gcs(report_df: pd.DataFrame, customer_id: str) -> None:
    """Write the report dataframe to GCS as a CSV file

    Args:
        report_df: the dataframe based on the Google Ads report.
        customer_id: the customer ID to fetch the Google Ads data for.
    """
    logger.info('Writing results to GCS: %s', APE_GCS_DATA_BUCKET)
    number_of_rows = len(report_df.index)
    logger.info('There are %s rows', number_of_rows)
    if number_of_rows > 0:
        blob_name = f'google_ads_report/{customer_id}.csv'
        logger.info('Blob name: %s', blob_name)
        gcs.upload_blob_from_df(
            df=report_df,
            blob_name=blob_name,
            bucket=APE_GCS_DATA_BUCKET)
        logger.info('Blob uploaded to GCS')
    else:
        logger.info('There is nothing to write to GCS')

def send_messages_to_pubsub(customer_id: str, sheet_id: str) -> None:
    """Push the customer ID to pub/sub when the job completes.

    Args:
        customer_id: the customer ID to fetch the Google Ads data for.
        sheet_id: the ID of the Google Sheet containing the config.
    """
    message_dict = {
        'customer_id': customer_id,
        'sheet_id': sheet_id,
    }
    logger.info('Sending message to pub/sub:', message_dict)
    pubsub.send_dict_to_pubsub(
        message_dict=message_dict,
        topic=APE_YOUTUBE_PUBSUB_TOPIC,
        gcp_project=GOOGLE_CLOUD_PROJECT)
    logger.info('Message published')


text:
/*
 * Controls for Sigma25
 *
 * @author Edouard Lafargue, ed@lafargue.name
 */

define(function (require) {
    "use strict";

    var $ = require('jquery'),
        _ = require('underscore'),
        Backbone = require('backbone'),
        utils = require('app/utils'),
        template = require('js/tpl/instruments/sigma25/Sigma25NumView.js');

    return Backbone.View.extend({

        initialize: function (options) {
            linkManager.on('input', this.showInput, this);
        },

        events: {
        },

        render: function () {
            var self = this;
            console.log('Main render of Sigma25 numeric view');
            this.$el.html(template());
            return this;
        },

        onClose: function () {
            console.log("Sigma25 numeric view closing...");
            linkManager.off('input', this.showInput, this);
        },

        showInput: function (data) {
            if (data.channels)
                return;

            if (data.gain != undefined) {
                $('#gain', this.el).val(parseInt(data.gain,10));
                linkManager.sendCommand('b');  // Bias
            } else
            if (data.serial != undefined) {
                $('#serial', this.el).val(data.serial);
                linkManager.sendCommand('l');  // LLD Channel
            } else
            if (data.lld_channel != undefined) {
                $('#lld_channel', this.el).val(data.lld_channel);
                linkManager.startLiveStream(this.model.get('liveviewperiod'));
            } else
            if (data.bias != undefined) {
                $('#bias', this.el).val(data.bias);
                linkManager.sendCommand('n');  // Serial number
            }

        },

    });
});


text:
package utils

import (
	"bufio"
	"bytes"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"os/exec"
	"runtime"
	"strings"
	"syscall"
	"time"

	log "github.com/Sirupsen/logrus"
)

const (
	TimeStampLayout          = "2006-01-02T15:04:05.000000-07:00"
	TimeLayoutYYYYMMDDHHMMSS = "20060102150405"
	RetriesFactor            = 3
)

func extractExitCode(err error) int {
	if err != nil {
		switch err.(type) {
		case *exec.ExitError:
			return err.(*exec.ExitError).Sys().(syscall.WaitStatus).ExitStatus()
		case *os.PathError:
			return 127
		}
	}
	return 0
}

func ExecCode(code string, path string, filename string) (output string, exitCode int, startedAt time.Time, finishedAt time.Time) {
	var err error
	var tmp *os.File

	if runtime.GOOS == "windows" {
		tmp, err = os.Create(fmt.Sprintf("%s/%s.bat", path, filename))
	} else {
		tmp, err = os.Create(fmt.Sprintf("%s/%s", path, filename))
	}

	if err != nil {
		log.Fatalf("Error creating temp file: %v", err)
	}

	defer tmp.Close()

	_, err = tmp.WriteString(code)
	if err != nil {
		log.Fatalf("Error writing to file: %v", err)
	}

	os.Chmod(tmp.Name(), 0777)
	if err != nil {
		log.Fatalf("Error changing permission to file: %v", err)
	}

	return RunFile(tmp.Name())
}

func RunFile(command string) (output string, exitCode int, startedAt time.Time, finishedAt time.Time) {

	var cmd *exec.Cmd

	var b bytes.Buffer
	buffer := bufio.NewWriter(&b)

	if runtime.GOOS == "windows" {
		log.Infof("Command: %s", command)
		cmd = exec.Command("cmd", "/C", command)
	} else {
		log.Infof("Command: %s %s", "/bin/sh", command)
		cmd = exec.Command("/bin/sh", command)
	}

	stdout, err := cmd.StdoutPipe()
	if err != nil {
		log.Fatal(err)
	}

	stderr, err := cmd.StderrPipe()
	if err != nil {
		log.Fatal(err)
	}

	multi := io.MultiReader(stdout, stderr)

	startedAt = time.Now()
	if err = cmd.Start(); err != nil {
		log.Fatal(err)
	}

	io.Copy(buffer, multi)

	//go io.Copy(buffer, stderr)
	//go io.Copy(buffer, stdout)

	err = cmd.Wait()
	finishedAt = time.Now()
	exitCode = extractExitCode(err)

	if err = buffer.Flush(); err != nil {
		log.Fatal(err)
	}
	output = b.String()

	log.Debugf("Starting Time: %s", startedAt.Format(TimeStampLayout))
	log.Debugf("End Time: %s", finishedAt.Format(TimeStampLayout))
	log.Debugf("Output")
	log.Debugf("")
	log.Debugf("%s", output)
	log.Debugf("")
	log.Infof("Exit Code: %d", exitCode)
	return
}

func RunCmd(command string) (output string, exitCode int, startedAt time.Time, finishedAt time.Time) {

	var cmd *exec.Cmd

	if runtime.GOOS == "windows" {
		log.Infof("Command: %s", command)
		cmd = exec.Command("cmd", "/C", command)
	} else {
		log.Infof("Command: %s %s", "/bin/sh -c", command)
		cmd = exec.Command("/bin/sh", "-c", command)
	}

	startedAt = time.Now()
	bytes, err := cmd.CombinedOutput()
	finishedAt = time.Now()
	output = strings.TrimSpace(string(bytes))
	exitCode = extractExitCode(err)

	log.Debugf("Starting Time: %s", startedAt.Format(TimeStampLayout))
	log.Debugf("End Time: %s", finishedAt.Format(TimeStampLayout))
	log.Debugf("Output")
	log.Debugf("")
	log.Debugf("%s", output)
	log.Debugf("")
	log.Infof("Exit Code: %d", exitCode)
	return
}

// Save script/command in a temp file
func createCommandWithFilename(command string) (cmd *exec.Cmd, cmdFileName string) {

	cmdFileName = strings.Join([]string{time.Now().Format(TimeLayoutYYYYMMDDHHMMSS), "_", RandomString(10)}, "")
	if runtime.GOOS == "windows" {
		cmdFileName = strings.Join([]string{cmdFileName, ".bat"}, "")
	}

	// Writes content to file
	if err := ioutil.WriteFile(cmdFileName, []byte(command), 0600); err != nil {
		log.Fatalf("Error creating temp file: %v", err)
	}

	// Creates command
	if runtime.GOOS == "windows" {
		cmd = exec.Command("cmd", "/C", cmdFileName)
	} else {
		cmd = exec.Command("/bin/sh", cmdFileName)
	}
	return
}

// Remove temp file
func deleteTmpCommandFilename(cmdFileName string) {
	err := os.Remove(cmdFileName)
	if err != nil {
		log.Warn("Temp file cannot be removed", err.Error())
	}
}

// RunTracedCmd executes the received command and manages two output pipes (output and error)
// It shouldn't throw any exception/error or stop the process.
func RunTracedCmd(command string) (exitCode int, stdOut string, stdErr string, startedAt time.Time, finishedAt time.Time) {
	log.Debug("RunTracedCmd")

	// Saves script/command in a temp file
	var cmd, cmdFileName = createCommandWithFilename(command)

	// Removes temp file
	defer deleteTmpCommandFilename(cmdFileName)

	stdoutIn, err := cmd.StdoutPipe()
	if err != nil {
		log.Error("cmd.StdoutPipe() failed: ", err)
	}

	stderrIn, err := cmd.StderrPipe()
	if err != nil {
		log.Error("cmd.StderrPipe() failed: ", err)
	}

	var errStdout, errStderr error
	var stdoutBuf, stderrBuf bytes.Buffer
	stdout := io.MultiWriter(os.Stdout, &stdoutBuf)
	stderr := io.MultiWriter(os.Stderr, &stderrBuf)

	if err = cmd.Start(); err != nil {
		log.Error("cmd.Start() failed: ", err)
	}

	go func() {
		_, errStdout = io.Copy(stdout, stdoutIn)
	}()

	go func() {
		_, errStderr = io.Copy(stderr, stderrIn)
	}()

	if err = cmd.Wait(); err != nil {
		log.Error("cmd.Wait() failed: ", err)
	}

	if errStdout != nil {
		log.Error("failed to capture stdout: ", errStdout)
	}

	if errStderr != nil {
		log.Error("failed to capture stderr: ", errStderr)
	}

	exitCode = extractExitCode(err)
	stdOut = string(stdoutBuf.Bytes())
	stdErr = string(stderrBuf.Bytes())
	startedAt = time.Now()
	finishedAt = time.Now()

	log.Infof("Exit Code: %d", exitCode)
	log.Debugf("Stdout: %s", stdOut)
	log.Debugf("Stderr: %s", stdErr)
	log.Debugf("Starting Time: %s", startedAt.Format(TimeStampLayout))
	log.Debugf("End Time: %s", finishedAt.Format(TimeStampLayout))
	return
}

// thresholdTime  > 0 continuous report
// thresholdLines > 0 bootstrapping
func RunContinuousCmd(fn func(chunk string) error, command string, thresholdTime int, thresholdLines int) (int, error) {
	log.Debug("RunContinuousCmd")

	// Saves script/command in a temp file
	var cmd, cmdFileName = createCommandWithFilename(command)

	// Removes temp file
	defer deleteTmpCommandFilename(cmdFileName)

	// Gets the pipe command
	stdout, err := cmd.StdoutPipe()
	if err != nil {
		return 1, fmt.Errorf("cannot get pipe command %v", err)
	}
	log.Info("==> Executing: ", strings.Join(cmd.Args, " "))

	// Start command asynchronously
	if err = cmd.Start(); err != nil {
		return 1, fmt.Errorf("cannot start the specified command %v", err)
	}

	chunk := ""
	nLines, nTime := 0, 0
	timeStart := time.Now()

	scanner := bufio.NewScanner(bufio.NewReader(stdout))
	for scanner.Scan() {
		chunk = strings.Join([]string{chunk, scanner.Text(), "\n"}, "")
		nLines++
		nTime = int(time.Now().Sub(timeStart).Seconds())
		if (thresholdTime > 0 && nTime >= thresholdTime) || (thresholdLines > 0 && nLines >= thresholdLines) {
			if err := fn(chunk); err == nil {
				chunk = ""
			}
			nLines, nTime = 0, 0
			timeStart = time.Now()
		}
	}

	if err := scanner.Err(); err != nil {
		log.Error("==> Error: ", err.Error())
		chunk = strings.Join([]string{chunk, err.Error()}, "")
	}

	if len(chunk) > 0 {
		log.Debug("Processing the last pending chunk")
		if err := fn(chunk); err != nil {
			log.Error("Cannot process the last chunk", err.Error())
		}
	}

	err = cmd.Wait()
	exitCode := extractExitCode(err)

	return exitCode, nil
}

func Retry(attempts int, sleep time.Duration, fn func() error) error {
	log.Debug("Retry")

	if err := fn(); err != nil {
		if attempts--; attempts > 0 {
			log.Debug("Waiting to retry: ", sleep)
			time.Sleep(sleep)
			return Retry(attempts, RetriesFactor*sleep, fn)
		}
		return err
	}
	return nil
}


text:
==============
Stackube Scope
==============

A multi-tenant and secure Kubernetes deployment enabled by OpenStack
core components.

Not another "Kubernetes on OpenStack" project
=============================================

Stackube is a standard upstream Kubernetes deployment with:

#. Mixed container runtime of Docker (Linux container) and HyperContainer (hypervisor-based container)

#. Keystone for tenant management

#. Neutron for container network

#. Cinder for persistent volume

The main difference between Stackube with existing container service
project in OpenStack foundation (e.g. Magnum) is: **Stackube works
alongside OpenStack, not on OpenStack**.

This means:

#. Only standalone vanilla OpenStack components are required

#. Traditional VMs are not required because HyperContainer will provide hypervisor level isolation for containerized workloads.

#. All the components mentioned above are managed by Kubernetes plugin API.

What's inside Stackube repo?
============================

#. Keystone RBAC plugin

#. Neutron CNI plugin

   * With a k8s Network object controller

#. Standard k8s upstream Cinder plugin with block device mode

#. Deployment scripts and guide

#. Other documentations

Please note:

#. Plugins above will be deployed as system Pod and DaemonSet.

#. All other Kubernetes volumes are also supported in Stackube, while k8s Cinder plugin with block device mode can provide better performance in mixed runtime which will be preferred by default.

What's the difference between other plugin projects?
====================================================

#. Kuryr

   * This is a Neutron network plugin for Docker network model, which is not directly supported in Kubernetes. Kuryr can provide CNI interface, but Stackube also requires tenant aware network management which is not included in Kuryr. We will evaluate and propose our multi-tenant model to kuryr-kubernetes as a long term effort, then we can move to use kuryr-kubernetes as the default network plugin.

#. Fuxi

   * This is a Cinder volume plugin for Docker volume model, which is not supported in latest CRI based Kubernetes (using k8s volume plugin for now, and soon CSI). Also, Stackube prefers a "block-device to Pod" mode in volume plugin when HyperContainer runtime is enabled, which is not supported in Fuxi.

#. K8s-cloud-provider

   * This is a "Kubernetes on OpenStack" integration which requires full functioning OpenStack deployment.

#. Zun

   * This is a OpenStack API container service, while Stackube exposes well-known Kubernetes API and does not require full OpenStack deployment.

As summary, one distinguishable difference is that plugins in Stackube
are designed to enable hard multi-tenancy in Kubernetes as a whole
solution, while the other OpenStack plugin projects do not address this
and solely focus on just integrating with Kubernetes/Docker as-is. There
are many gaps to fill when use them to build a real multi-tenant cloud,
for example, how tenants cooperate with networks in k8s.

Another difference is Stackube use mixed container runtimes mode of k8s
to enable secure runtime, which is not in scope of existing foundation
projects. In fact, all plugins in Stackube should work well for both
Docker and HyperContainer.

The architecture of Stackube is fully decoupled and it would be easy for
us (and we'd like to) integrate it with any OpenStack-Kubernetes plugin.
But right now, we hope to keep everything as simple as possible and
focus on the core components.

Deployment workflow
=========================================

-----------------
On control nodes
-----------------

Install standalone Keystone, Neutron, Cinder (ceph rbd).
This can be done by any existing tools like devstack, RDO etc.

----------------
On other nodes
----------------

1. Install neutron L2 agents

   This can be done by any existing tools like devstack, RDO etc.

2. Install Kubernetes

   * Including container runtimes, CRI shims, CNI etc
   * This can be done by any existing tools like kubeadm etc

3. Deploy Stackube

::

  kubectl create -f stackube-configmap.yaml
  kubectl create -f deployment/stackube-proxy.yaml
  kubectl create -f deployment/stackube.yaml

This will deploy all Stackube plugins as Pods and DaemonSets to the
cluster. You can also deploy all these components in a single node.

After that, users can use Kubernetes API to manage containers with
hypervisor isolation, Neutron network, Cinder volume and tenant
awareness.


text:
/*
 *
 *  Top 20 Array Interview Questions
 *
 *  http://javarevisited.blogspot.com/2015/06/top-20-array-interview-questions-and-answers.html
 *
 */

// find a missing number in an integer array of 1 to 100
function findMissingNumber(array) {

    let expectedSum = 0,
        actualSum = 0,
        difference;

    // sum up the integers from 1 to 10
    for (let i = 1; i <= array.length; i++) {
        expectedSum = expectedSum + i;
    }
    console.log("the total expected sum is: " + expectedSum);

    // add up the sum of the array
    for (let j = 0; j < array.length; j++) {
        actualSum = actualSum + array[j];
    }
    console.log("the total actual sum is: " + actualSum);

    // calculate the difference
    difference = expectedSum - actualSum;
    console.log("the missing number is " + difference);
    return difference;

}
// findMissingNumber([1, 2, 3, 0, 5, 6, 7, 8, 9, 10]);

/*
 * find the duplicate number on an integer array (do not assume it is sorted)
 *
 * o(n) time and o(1) space
 *
 * in a single pass through the vector, compute the sum of all the numbers, and the sum of the squares of all the numbers
 * subract the sum of all numbers from n(n-1) / 2, call this A
 * subract the sum of the squares from n(n-1)(2n-1/length), divide this by A, call result B
 * number was removed is (B + A)/2, number that was replaced is (B - A)/2
 *
 */
function findDuplicate(array) {

    // edge case
    if (array.length <= 1) {
        return 0;
    }

    // sort out array...
    array.sort();

    // define length
    let len = array.length;

    // define sum of vector
    let sumVector = array.reduce((a, b) => a + b, 0);
    console.log('sum of vector: ' + sumVector);

    // define A
    let ay = sumVector - (len * len - 1) / 2;
    console.log('a: ' + ay);

    // define sum of squares
    let sumSquares = array.reduce((a, b) => a ^ 2 + b ^ 2, 0);
    console.log('sum of squares: ' + sumSquares);

    // define B
    let by = sumSquares - (len * len - 1 * 2 * len - 1) / len;
    console.log('b: ' + by);
}
// findDuplicate([0, 1, 1, 2, 3, 5]);

console.log([0, 1, 1, 2, 3, 5].reduce((a, b) => a = a ^ 2 + b ^ 2, 0));


text:
"""
Backport of PEP 562.

https://pypi.org/search/?q=pep562

Licensed under MIT
Copyright (c) 2018 Isaac Muse <isaacmuse@gmail.com>

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.
"""
from __future__ import unicode_literals
import sys
from collections import namedtuple
import re

__all__ = ('Pep562',)

RE_VER = re.compile(
    r'''(?x)
    (?P<major>\d+)(?:\.(?P<minor>\d+))?(?:\.(?P<micro>\d+))?
    (?:(?P<type>a|b|rc)(?P<pre>\d+))?
    (?:\.post(?P<post>\d+))?
    (?:\.dev(?P<dev>\d+))?
    '''
)

REL_MAP = {
    ".dev": "",
    ".dev-alpha": "a",
    ".dev-beta": "b",
    ".dev-candidate": "rc",
    "alpha": "a",
    "beta": "b",
    "candidate": "rc",
    "final": ""
}

DEV_STATUS = {
    ".dev": "2 - Pre-Alpha",
    ".dev-alpha": "2 - Pre-Alpha",
    ".dev-beta": "2 - Pre-Alpha",
    ".dev-candidate": "2 - Pre-Alpha",
    "alpha": "3 - Alpha",
    "beta": "4 - Beta",
    "candidate": "4 - Beta",
    "final": "5 - Production/Stable"
}

PRE_REL_MAP = {"a": 'alpha', "b": 'beta', "rc": 'candidate'}

class Version(namedtuple("Version", ["major", "minor", "micro", "release", "pre", "post", "dev"])):
    """
    Get the version (PEP 440).

    A biased approach to the PEP 440 semantic version.

    Provides a tuple structure which is sorted for comparisons `v1 > v2` etc.
      (major, minor, micro, release type, pre-release build, post-release build, development release build)
    Release types are named in is such a way they are comparable with ease.
    Accessors to check if a development, pre-release, or post-release build. Also provides accessor to get
    development status for setup files.

    How it works (currently):

    - You must specify a release type as either `final`, `alpha`, `beta`, or `candidate`.
    - To define a development release, you can use either `.dev`, `.dev-alpha`, `.dev-beta`, or `.dev-candidate`.
      The dot is used to ensure all development specifiers are sorted before `alpha`.
      You can specify a `dev` number for development builds, but do not have to as implicit development releases
      are allowed.
    - You must specify a `pre` value greater than zero if using a prerelease as this project (not PEP 440) does not
      allow implicit prereleases.
    - You can optionally set `post` to a value greater than zero to make the build a post release. While post releases
      are technically allowed in prereleases, it is strongly discouraged, so we are rejecting them. It should be
      noted that we do not allow `post0` even though PEP 440 does not restrict this. This project specifically
      does not allow implicit post releases.
    - It should be noted that we do not support epochs `1!` or local versions `+some-custom.version-1`.

    Acceptable version releases:

    ```
    Version(1, 0, 0, "final")                    1.0
    Version(1, 2, 0, "final")                    1.2
    Version(1, 2, 3, "final")                    1.2.3
    Version(1, 2, 0, ".dev-alpha", pre=4)        1.2a4
    Version(1, 2, 0, ".dev-beta", pre=4)         1.2b4
    Version(1, 2, 0, ".dev-candidate", pre=4)    1.2rc4
    Version(1, 2, 0, "final", post=1)            1.2.post1
    Version(1, 2, 3, ".dev")                     1.2.3.dev0
    Version(1, 2, 3, ".dev", dev=1)              1.2.3.dev1
    ```

    """

    def __new__(cls, major, minor, micro, release="final", pre=0, post=0, dev=0):
        """Validate version info."""

        # Ensure all parts are positive integers.
        for value in (major, minor, micro, pre, post):
            if not (isinstance(value, int) and value >= 0):
                raise ValueError("All version parts except 'release' should be integers.")

        if release not in REL_MAP:
            raise ValueError("'{}' is not a valid release type.".format(release))

        # Ensure valid pre-release (we do not allow implicit pre-releases).
        if ".dev-candidate" < release < "final":
            if pre == 0:
                raise ValueError("Implicit pre-releases not allowed.")
            elif dev:
                raise ValueError("Version is not a development release.")
            elif post:
                raise ValueError("Post-releases are not allowed with pre-releases.")

        # Ensure valid development or development/pre release
        elif release < "alpha":
            if release > ".dev" and pre == 0:
                raise ValueError("Implicit pre-release not allowed.")
            elif post:
                raise ValueError("Post-releases are not allowed with pre-releases.")

        # Ensure a valid normal release
        else:
            if pre:
                raise ValueError("Version is not a pre-release.")
            elif dev:
                raise ValueError("Version is not a development release.")

        return super(Version, cls).__new__(cls, major, minor, micro, release, pre, post, dev)

    def _is_pre(self):
        """Is prerelease."""

        return self.pre > 0

    def _is_dev(self):
        """Is development."""

        return bool(self.release < "alpha")

    def _is_post(self):
        """Is post."""

        return self.post > 0

    def _get_dev_status(self):  # pragma: no cover
        """Get development status string."""

        return DEV_STATUS[self.release]

    def _get_canonical(self):
        """Get the canonical output string."""

        # Assemble major, minor, micro version and append `pre`, `post`, or `dev` if needed..
        if self.micro == 0:
            ver = "{}.{}".format(self.major, self.minor)
        else:
            ver = "{}.{}.{}".format(self.major, self.minor, self.micro)
        if self._is_pre():
            ver += '{}{}'.format(REL_MAP[self.release], self.pre)
        if self._is_post():
            ver += ".post{}".format(self.post)
        if self._is_dev():
            ver += ".dev{}".format(self.dev)

        return ver

def parse_version(ver, pre=False):
    """Parse version into a comparable Version tuple."""

    m = RE_VER.match(ver)

    # Handle major, minor, micro
    major = int(m.group('major'))
    minor = int(m.group('minor')) if m.group('minor') else 0
    micro = int(m.group('micro')) if m.group('micro') else 0

    # Handle pre releases
    if m.group('type'):
        release = PRE_REL_MAP[m.group('type')]
        pre = int(m.group('pre'))
    else:
        release = "final"
        pre = 0

    # Handle development releases
    dev = m.group('dev') if m.group('dev') else 0
    if m.group('dev'):
        dev = int(m.group('dev'))
        release = '.dev-' + release if pre else '.dev'
    else:
        dev = 0

    # Handle post
    post = int(m.group('post')) if m.group('post') else 0

    return Version(major, minor, micro, release, pre, post, dev)

class Pep562(object):
    """
    Backport of PEP 562 <https://pypi.org/search/?q=pep562>.

    Wraps the module in a class that exposes the mechanics to override `__dir__` and `__getattr__`.
    The given module will be searched for overrides of `__dir__` and `__getattr__` and use them when needed.
    """

    def __init__(self, name):
        """Acquire `__getattr__` and `__dir__`, but only replace module for versions less than Python 3.7."""

        self._module = sys.modules[name]
        self._get_attr = getattr(self._module, '__getattr__', None)
        self._get_dir = getattr(self._module, '__dir__', None)
        sys.modules[name] = self

    def __dir__(self):
        """Return the overridden `dir` if one was provided, else apply `dir` to the module."""

        return self._get_dir() if self._get_dir else dir(self._module)

    def __getattr__(self, name):
        """Attempt to retrieve the attribute from the module, and if missing, use the overridden function if present."""

        try:
            return getattr(self._module, name)
        except AttributeError:
            if self._get_attr:
                return self._get_attr(name)
            raise

__version_info__ = Version(1, 0, 0, "final")
__version__ = __version_info__._get_canonical()


text:
package fi.nls.oskari.util;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.util.Map;

/**
 * Created by TMIKKOLAINEN on 30.12.2014.
 */
public class CSVStreamer implements TabularFileStreamer {
    private char delimiter = ',';

    public char getDelimiter() {
        return delimiter;
    }

    public void setDelimiter(char delimiter) {
        this.delimiter = delimiter;
    }

    @Override
    public void writeToStream(String[] headers, Object[][] data, Map<String, Object> additionalFields, OutputStream out) throws IOException {
        int i;
        // Write BOM, Excel won't use UTF-8 without it...
        out.write(239);
        out.write(187);
        out.write(191);
        OutputStreamWriter writer = new OutputStreamWriter(out, Charset.forName("UTF-8"));
        // We can't use .withHeader(headers) as that requires the headers to be unique
        final CSVPrinter printer = new CSVPrinter(
                writer,
                CSVFormat.DEFAULT.withDelimiter(getDelimiter())
        );
        printer.printRecord(headers);
        for (i = 0; i < data.length; i++) {
            printer.printRecord(data[i]);
        }

        if (!additionalFields.isEmpty()) {
            printer.printRecord(new String[0]);
        }
        for (Map.Entry<String, Object> entry : additionalFields.entrySet())
        {
            printer.printRecord(entry.getKey(), entry.getValue());
        }
        writer.flush();
        writer.close();
        printer.close();
    }
}


text:
package au.com.mineauz.minigamesregions.menuitems;

import au.com.mineauz.minigames.MinigameUtils;
import au.com.mineauz.minigames.menu.*;
import au.com.mineauz.minigamesregions.conditions.ConditionInterface;
import au.com.mineauz.minigamesregions.conditions.Conditions;
import au.com.mineauz.minigamesregions.executors.NodeExecutor;
import au.com.mineauz.minigamesregions.executors.RegionExecutor;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;

import java.util.*;

public class MenuItemConditionAdd extends MenuItem{

    private RegionExecutor rexec;
    private NodeExecutor nexec;

    public MenuItemConditionAdd(String name, Material displayItem, RegionExecutor exec) {
        super(name, displayItem);
        this.rexec = exec;
    }

    public MenuItemConditionAdd(String name, Material displayItem, NodeExecutor exec) {
        super(name, displayItem);
        this.nexec = exec;
    }

    @Override
    public ItemStack onClick(){
        Menu m = new Menu(6, "Conditions", getContainer().getViewer());
        m.setPreviousPage(getContainer());
        Map<String, Menu> cats = new HashMap<>();
        List<String> cons = new ArrayList<>(Conditions.getAllConditionNames());
        Collections.sort(cons);
        for(String con : cons){
            if((Conditions.getConditionByName(con).useInNodes() && nexec != null) ||
                    (Conditions.getConditionByName(con).useInRegions() && rexec != null)){
                String catname = Conditions.getConditionByName(con).getCategory();
                if(catname == null)
                    catname = "misc conditions";
                catname.toLowerCase();
                Menu cat = null;
                if(!cats.containsKey(catname)){
                    cat = new Menu(6, MinigameUtils.capitalize(catname), getContainer().getViewer());
                    cats.put(catname, cat);
                    m.addItem(new MenuItemPage(MinigameUtils.capitalize(catname), Material.CHEST, cat));
                    cat.addItem(new MenuItemPage("Back",MenuUtility.getBackMaterial(), m), cat.getSize() - 9);
                }
                else
                    cat = cats.get(catname);
                MenuItemCustom c = new MenuItemCustom(MinigameUtils.capitalize(con), Material.PAPER);
                final String fcon = con;
                c.setClick(object -> {
                    ConditionInterface condition = Conditions.getConditionByName(fcon);
                    if(rexec != null){
                        rexec.addCondition(condition);
                        getContainer().addItem(new MenuItemCondition(MinigameUtils.capitalize(fcon), Material.PAPER, rexec, condition));
                    }
                    else{
                        nexec.addCondition(condition);
                        getContainer().addItem(new MenuItemCondition(MinigameUtils.capitalize(fcon), Material.PAPER, nexec, condition));
                    }
                    getContainer().displayMenu(getContainer().getViewer());
                    return null;
                });
                cat.addItem(c);
            }
        }
        m.addItem(new MenuItemPage("Back",MenuUtility.getBackMaterial(), getContainer()), m.getSize() - 9);
        m.displayMenu(getContainer().getViewer());
        return null;
    }

}


text:
package eu.hyvar.feature.mapping.resource.hymapping.grammar;

public enum HymappingCardinality {

	ONE, PLUS, QUESTIONMARK, STAR;

}


text:
import org.lwjgl.opengl.{DisplayMode, Display}
import org.newdawn.slick.SlickException
import org.newdawn.slick.tiled.TiledMap
import org.scalatest._

/**
 * Created by waynesayonara on 11.11.14.
 */
trait UISpec {
    //TODO: Init GL Context in a headless way and only once
    Display.setDisplayMode(new DisplayMode(1, 1))
    Display.create()
}