text:
USE TelerikAcademy

--1. Write a SQL query to find the names and salaries of the employees that take the minimal salary in the company.Use a nested SELECT statement.
SELECT FirstName, LastName, Salary
FROM Employees
WHERE Salary =
		(SELECT MIN(Salary) FROM Employees)

--2. Write a SQL query to find the names and salaries of the employees that have a salary that is up to 10% higher than the minimal salary for the company.
SELECT FirstName, LastName, Salary
FROM Employees
WHERE Salary <
		(SELECT MIN(Salary)*1.1 FROM Employees)

--3. Write a SQL query to find the full name, salary and department of the employees that take the minimal salary in their department.
SELECT d.Name AS [Department name], e.FirstName + ' ' + e.LastName AS Fullname, e.Salary
FROM Employees e, Departments d
WHERE Salary =
		(SELECT MIN(Salary)
		FROM Employees s
		WHERE s.DepartmentID = d.DepartmentID)
ORDER BY d.Name

--4. Write a SQL query to find the average salary in the department #1.
SELECT AVG(Salary) AS [Average salary]
FROM Employees
WHERE DepartmentID = 1

--5. Write a SQL query to find the average salary in the "Sales" department.
SELECT AVG(Salary) AS [Average salary]
FROM Employees e
	JOIN Departments d
		ON e.DepartmentID = d.DepartmentID
	WHERE d.Name = 'Sales'

--6. Write a SQL query to find the number of employees in the "Sales" department.
SELECT COUNT(*) AS [Number of employees]
FROM Employees e
	JOIN Departments d
		ON e.DepartmentID = d.DepartmentID
	WHERE d.Name = 'Sales'

--7. Write a SQL query to find the number of all employees that have manager.
SELECT COUNT(ManagerId) AS [Employees with manager]
FROM Employees

--8. Write a SQL query to find the number of all employees that have no manager.
SELECT COUNT(*) AS [Employees without manager]
FROM Employees
WHERE ManagerID IS NULL

--9. Write a SQL query to find all departments and the average salary for each of them.
SELECT d.Name, AVG(e.Salary) AS [Average salary]
FROM Employees e
	JOIN Departments d
		ON e.DepartmentID = d.DepartmentID
	GROUP BY d.Name

--10. Write a SQL query to find the count of all employees in each department and for each town.
SELECT COUNT(*) AS [Count of employees], d.Name AS [Department], t.Name AS [Town]
FROM Employees e
	JOIN Departments d
		ON e.DepartmentID = d.DepartmentID
	JOIN Addresses a
		ON e.AddressID = a.AddressID
	JOIN Towns t
		ON a.TownID = t.TownID
	GROUP BY t.Name, d.Name
	ORDER BY t.Name

--11. Write a SQL query to find all managers that have exactly 5 employees. Display their first name and last name.
SELECT e.FirstName, e.LastName
FROM Employees e
	JOIN Employees emp
		ON e.ManagerID = emp.ManagerID
	GROUP BY e.EmployeeID, e.FirstName, e.LastName
	HAVING COUNT(e.EmployeeID) = 5

--12. Write a SQL query to find all employees along with their managers. For employees that do not have manager display the value "(no manager)".
SELECT e.FirstName + ' ' + e.LastName AS [Employee name], ISNULL(emp.FirstName + ' ' + emp.LastName, '(no manager)') AS [Manager name]
FROM Employees e
	LEFT JOIN Employees emp
		ON e.ManagerID = emp.EmployeeID
	ORDER BY [Manager name]

--13. Write a SQL query to find the names of all employees whose last name is exactly 5 characters long. Use the built-in LEN(str) function.
SELECT FirstName, LastName
FROM Employees
WHERE LEN(LastName) = 5

--14. Write a SQL query to display the current date and time in the following format "day.month.year hour:minutes:seconds:milliseconds".
SELECT FORMAT(GETDATE(), 'dd.MM.yyyy HH:mm:ss:fff')

--15. Write a SQL statement to create a table Users. Users should have username, password, full name and last login time.
--Choose appropriate data types for the table fields. Define a primary key column with a primary key constraint.
--Define the primary key column as identity to facilitate inserting records.
--Define unique constraint to avoid repeating usernames.
--Define a check constraint to ensure the password is at least 5 characters long.
CREATE TABLE Users (
	UserId int IDENTITY PRIMARY KEY,
	Username nvarchar(50) NOT NULL UNIQUE,
	Password nvarchar(30) NOT NULL CHECK(LEN(Password) > 5),
	FullName nvarchar(150) NOT NULL,
	LastLoginTime datetime
)
GO

--16. Write a SQL statement to create a view that displays the users from the Users table that have been in the system today.
GO
CREATE VIEW LoggedToday AS
SELECT Username
FROM Users
WHERE DATEDIFF(DAY, LastLoginTime, GETDATE()) = 0
GO

--17. Write a SQL statement to create a table Groups. Groups should have unique name (use unique constraint). Define primary key and identity column.
CREATE TABLE Groups (
	GroupId int IDENTITY,
	Name nvarchar(100) NOT NULL UNIQUE,
	CONSTRAINT PK_Groups PRIMARY KEY(GroupId)
)
GO

--18. Write a SQL statement to add a column GroupID to the table Users.
--Fill some data in this new column and as well in the `Groups table.
--Write a SQL statement to add a foreign key constraint between tables Users and Groups tables.
ALTER TABLE Users
ADD GroupId int

ALTER TABLE Users
ADD CONSTRAINT FK_Users_Groups
	FOREIGN KEY (GroupId)
	REFERENCES Groups(GroupId)

--19. Write SQL statements to insert several records in the Users and Groups tables.
INSERT INTO Groups
VALUES
	('Superheros'),
	('Villains'),
	('Others')

INSERT INTO Users
VALUES
	('Batman'
	,'bat123'
	,'Bruce Wayne'
	,'01.01.2015'
	,1),
	('Catwoman'
	,'cat123'
	,'Selina Kyle'
	,'02.02.2015'
	,2),
	('Two-Face'
	,'tface123'
	,'Harvey Dent'
	,'03.03.2015'
	,2)

--20. Write SQL statements to update some of the records in the Users and Groups tables.
UPDATE Users
SET Password='batman123'
WHERE UserId = 1

UPDATE Groups
SET Name='SUPERHEROES'
WHERE GroupId = 1

--21. Write SQL statements to delete some of the records from the Users and Groups tables.
DELETE FROM Groups
WHERE Name='Others'

--22. Write SQL statements to insert in the Users table the names of all employees from the Employees table.
--Combine the first and last names as a full name.
--For username use the first letter of the first name + the last name (in lowercase).
--Use the same for the password, and NULL for last login time.
--I use the first 3 letters of FirstName, because of the constraints for password (to be > 5).
INSERT INTO Users ([Username],[Password],[FullName])
	(SELECT LOWER(CONCAT(LEFT(FirstName,3), '_', LastName)),
		   LOWER(CONCAT(LEFT(FirstName,3), '_', LastName)),
		   CONCAT(FirstName, ' ', LastName)
	FROM Employees)

--23. Write a SQL statement that changes the password to NULL for all users that have not been in the system since 10.03.2010.
UPDATE Users
SET Password = NULL
WHERE DATEDIFF(DAY, LastLoginTime, '2010-3-10 00:00:00') > 0

--24. Write a SQL statement that deletes all users without passwords (NULL password).
DELETE FROM Users
WHERE [Password] IS NULL

--25. Write a SQL query to display the average employee salary by department and job title.
SELECT d.Name AS [Department], e.JobTitle, AVG(e.Salary) AS [Average salary]
FROM Employees e
	JOIN Departments d
		ON e.DepartmentID = d.DepartmentID
	GROUP BY d.Name, e.JobTitle
	ORDER BY d.Name

--26. Write a SQL query to display the minimal employee salary by department and job title along with the name of some of the employees that take it.
SELECT d.Name AS [Department], e.JobTitle, MIN(e.FirstName + ' ' + e.LastName), MIN(e.Salary) AS [Minimal salary]
FROM Employees e
	JOIN Departments d
		ON e.DepartmentID = d.DepartmentID
GROUP BY e.JobTitle, d.Name
ORDER BY d.Name

--27. Write a SQL query to display the town where maximal number of employees work.
SELECT TOP 1 t.Name AS [Town name], COUNT(e.EmployeeID) AS [Count of employees]
FROM Employees e
	JOIN Addresses a
		ON e.AddressID = a.AddressID
	JOIN Towns t
		ON a.TownID = t.TownID
GROUP BY t.Name
ORDER BY [Count of employees] DESC

--28. Write a SQL query to display the number of managers from each town.
SELECT t.Name AS [Town name], COUNT(DISTINCT e.ManagerID) AS [Count of managers]
FROM Employees e
	JOIN Employees m
		ON e.ManagerID = m.EmployeeID
	JOIN Addresses a
		ON e.AddressID = a.AddressID
	JOIN Towns t
		ON a.TownID = t.TownID
GROUP BY t.Name
ORDER BY [Count of managers] DESC

--29. Write a SQL to create table WorkHours to store work reports for each employee (employee id, date, task, hours, comments).
--Don't forget to define identity, primary key and appropriate foreign key.
--Issue few SQL statements to insert, update and delete of some data in the table.
--Define a table WorkHoursLogs to track all changes in the WorkHours table with triggers.
--For each change keep the old record data, the new record data and the command (insert / update / delete).
CREATE TABLE WorkHours(
	Id int PRIMARY KEY IDENTITY,
	EmployeeId int NOT NULL FOREIGN KEY REFERENCES Employees(EmployeeID),
	DateOfReport DATETIME,
	Task nvarchar(500),
	HoursOfWork int,
	Comments nvarchar(500)
)

--Insert data--
DECLARE @counter int
SET @counter = 0

WHILE @counter < 10
BEGIN
	INSERT INTO WorkHours(EmployeeId, DateOfReport, Task, HoursOfWork, Comments)
	VALUES (@counter, GETDATE(), 'task' + CONVERT(VARCHAR(5), @counter), 8, 'comment' + CONVERT(VARCHAR(5), @counter))
	SET @counter = @counter + 1
END
GO

--WorkLogs--
CREATE TABLE WorkHoursLog(
	Id int PRIMARY KEY IDENTITY,
	WorkHoursId int,
	EmployeeId int FOREIGN KEY REFERENCES Employees(EmployeeId),
	DateOfReport DATETIME,
	Task nvarchar(50),
	HoursOfWork int,
	Comments nvarchar(500),
	[Action] varchar(25) NOT NULL
)
GO
-- triggers --

--INSERT--
CREATE TRIGGER trg_WorkHours_Insert
	ON WorkHours
	FOR INSERT
	AS
	INSERT INTO WorkHoursLog(WorkHoursId, EmployeeId, DateOfReport, Task, HoursOfWork, Comments, [Action])
		SELECT Id, EmployeeID, DateOfReport, Task, HoursOfWork, Comments, 'Insert'
		FROM inserted
GO

--DELTETE--
CREATE TRIGGER trg_WorkHours_Delete
	ON WorkHours
	FOR DELETE
	AS
	INSERT INTO WorkHoursLog(WorkHoursId,EmployeeId, DateOfReport, Task, HoursOfWork, Comments, [Action])
		SELECT Id, EmployeeId, DateOfReport, Task, HoursOfWork, Comments, 'Delete'
		FROM deleted
GO

--UPDATE--
CREATE TRIGGER trg_WorkHours_Update ON WorkHours
	FOR UPDATE
	AS
	INSERT INTO WorkHoursLog(WorkHoursId, EmployeeId, DateOfReport, Task, HoursOfWork, Comments, [Action])
		SELECT Id, EmployeeId, DateOfReport, Task, HoursOfWork, Comments, 'UPDATE'
		FROM inserted
GO

--Trigers tests--

--DELETE--
DELETE FROM  WorkHours
WHERE EmployeeId = 2

--INSERT--
DECLARE @counter INT
SET @counter = 11

INSERT INTO WorkHours(EmployeeId, DateOfReport, Task, HoursOfWork, Comments)
VALUES (@counter, GETDATE(), 'task' + CONVERT(VARCHAR(5), @counter), 8, 'comment' + CONVERT(VARCHAR(5), @counter))

--UPDATE--
UPDATE WorkHours
SET HoursOfWork = 9
WHERE HoursOfWork = 8

--30. Start a database transaction, delete all employees from the 'Sales' department along with all dependent records from the pother tables.
--At the end rollback the transaction.
BEGIN TRAN
ALTER TABLE Departments
	DROP CONSTRAINT FK_Departments_Employees
GO

DELETE e
FROM Employees e
	JOIN Departments d
		ON e.DepartmentID = d.DepartmentID
	WHERE d.Name='Sales'
ROLLBACK TRAN

--31. Start a database transaction and drop the table EmployeesProjects. Now how you could restore back the lost table data?
BEGIN TRAN
	DROP TABLE EmployeesProjects
ROLLBACK TRAN

--32. Find how to use temporary tables in SQL Server.
--Using temporary tables backup all records from EmployeesProjects and restore them back after dropping and re-creating the table.
BEGIN TRAN
    SELECT *
        INTO #TempEmployeesProjects
        FROM EmployeesProjects

    DROP TABLE EmployeesProjects

    SELECT *
        INTO EmployeesProjects
        FROM #TempEmployeesProjects

    DROP TABLE #TempEmployeesProjects
ROLLBACK TRAN


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.

using UnityEngine;
using System.Collections;
using HoloToolkit.Unity;

namespace HoloToolkit.Examples.Prototyping
{
    /// <summary>
    /// sets the rotation (eulerAngles) of an object to the selected value in the array.
    /// Add RotateToValue for animaiton and easing, auto detected.
    /// </summary>
    public class CycleRotation : CycleArray<Vector3>
    {
        [Tooltip("use the local rotation - overrides the UseLocalTransform value of RotateToValue")]
        public bool UseLocalRotation = false;

        private RotateToValue mRotation;

        protected override void Awake()
        {
            mRotation = GetComponent<RotateToValue>();

            base.Awake();
        }

        /// <summary>
        /// set the rotation from the vector 3 euler angle
        /// </summary>
        /// <param name="index"></param>
        public override void SetIndex(int index)
        {
            base.SetIndex(index);

            // get the rotation and convert it to a Quaternion
            Vector3 item = Array[Index];

            Quaternion rotation = Quaternion.identity;
            rotation.eulerAngles = item;

            // set the rotation
            if (mRotation != null)
            {
                mRotation.ToLocalTransform = UseLocalRotation;
                mRotation.TargetValue = rotation;
                mRotation.StartRunning();
            }
            else
            {
                if (UseLocalRotation)
                {
                    TargetObject.transform.localRotation = rotation;
                }
                else
                {
                    TargetObject.transform.rotation = rotation;
                }
            }
        }

    }
}

redpajama_set_name: RedPajamaGithub


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

<title>MergeIterator.Reducer (apache-cassandra API)</title>
<meta name="date" content="2016-04-28">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.apache.cassandra.utils

Class MergeIterator.Reducer<In,Out>

java.lang.Object

org.apache.cassandra.utils.MergeIterator.Reducer<In,Out>

Direct Known Subclasses:

CompactionIterable.Reducer, LazilyCompactedRow.Reducer

Enclosing class:

MergeIterator<In,Out>

public abstract static class MergeIterator.Reducer<In,Out>
extends java.lang.Object

Accumulator that collects values of type A, and outputs a value of type B.

Constructor Summary

Constructors

Constructor and Description

MergeIterator.Reducer()

Method Summary

Methods

Modifier and Type
Method and Description

void
close()

May be overridden by implementations that require cleaning up after use

protected abstract Out
getReduced()

protected void
onKeyChange()

Called at the beginning of each new key, before any reduce is called.

abstract void
reduce(In current)

combine this object with the previous ones.

boolean
trivialReduceIsTrivial()

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

MergeIterator.Reducer

public MergeIterator.Reducer()

Method Detail

trivialReduceIsTrivial

public boolean trivialReduceIsTrivial()

Returns:

true if Out is the same as In for the case of a single source iterator

reduce

public abstract void reduce(In current)

combine this object with the previous ones.
 intermediate state is up to your implementation.

getReduced

protected abstract Out getReduced()

Returns:

The last object computed by reduce

onKeyChange

protected void onKeyChange()

Called at the beginning of each new key, before any reduce is called.
 To be overridden by implementing classes.

close

public void close()

May be overridden by implementations that require cleaning up after use

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2016 The Apache Software Foundation


text:
import Ember from 'ember';

export default Ember.Component.extend({
  requestObject  : null,
  requestJSON    : null,
  responseObject : null,
  responseJSON   : null,

  init() {
    this._super(...arguments);

    // Pretty-ify the JSON
    this.set('requestJSON', JSON.stringify(JSON.parse(this.get('requestObject')),null,2));
    this.set('responseJSON', JSON.stringify(JSON.parse(this.get('responseObject')),null,2));
  },

  actions: {
    dismiss: function() {
      this.sendAction('dismiss');
    }
  },
});


text:
/**
 * @author Pavel Kirienko <pavel.kirienko@gmail.com>
 */

#include <drivers/drv_hrt.h>
#include "baro.hpp"
#include <cmath>

const char *const UavcanBarometerBridge::NAME = "baro";

UavcanBarometerBridge::UavcanBarometerBridge(uavcan::INode &node) :
	UavcanCDevSensorBridgeBase("uavcan_baro", "/dev/uavcan/baro", BARO_BASE_DEVICE_PATH, ORB_ID(sensor_baro)),
	_sub_air_pressure_data(node),
	_sub_air_temperature_data(node),
	_reports(2, sizeof(baro_report))
{ }

int UavcanBarometerBridge::init()
{
	int res = device::CDev::init();

	if (res < 0) {
		return res;
	}

	res = _sub_air_pressure_data.start(AirPressureCbBinder(this, &UavcanBarometerBridge::air_pressure_sub_cb));

	if (res < 0) {
		DEVICE_LOG("failed to start uavcan sub: %d", res);
		return res;
	}

	res = _sub_air_temperature_data.start(AirTemperatureCbBinder(this, &UavcanBarometerBridge::air_temperature_sub_cb));

	if (res < 0) {
		DEVICE_LOG("failed to start uavcan sub: %d", res);
		return res;
	}

	return 0;
}

ssize_t UavcanBarometerBridge::read(struct file *filp, char *buffer, size_t buflen)
{
	unsigned count = buflen / sizeof(struct baro_report);
	struct baro_report *baro_buf = reinterpret_cast<struct baro_report *>(buffer);
	int ret = 0;

	/* buffer must be large enough */
	if (count < 1) {
		return -ENOSPC;
	}

	while (count--) {
		if (_reports.get(baro_buf)) {
			ret += sizeof(*baro_buf);
			baro_buf++;
		}
	}

	/* if there was no data, warn the caller */
	return ret ? ret : -EAGAIN;
}

int UavcanBarometerBridge::ioctl(struct file *filp, int cmd, unsigned long arg)
{
	switch (cmd) {
	case BAROIOCSMSLPRESSURE: {
			if ((arg < 80000) || (arg > 120000)) {
				return -EINVAL;

			} else {
				DEVICE_LOG("new msl pressure %u", _msl_pressure);
				_msl_pressure = arg;
				return OK;
			}
		}

	case BAROIOCGMSLPRESSURE: {
			return _msl_pressure;
		}

	case SENSORIOCSPOLLRATE: {
			// not supported yet, pretend that everything is ok
			return OK;
		}

	case SENSORIOCSQUEUEDEPTH: {
			/* lower bound is mandatory, upper bound is a sanity check */
			if ((arg < 1) || (arg > 100)) {
				return -EINVAL;
			}

			irqstate_t flags = px4_enter_critical_section();

			if (!_reports.resize(arg)) {
				px4_leave_critical_section(flags);
				return -ENOMEM;
			}

			px4_leave_critical_section(flags);

			return OK;
		}

	default: {
			return CDev::ioctl(filp, cmd, arg);
		}
	}
}

void UavcanBarometerBridge::air_temperature_sub_cb(const
		uavcan::ReceivedDataStructure<uavcan::equipment::air_data::StaticTemperature> &msg)
{
	last_temperature_kelvin = msg.static_temperature;
}

void UavcanBarometerBridge::air_pressure_sub_cb(const
		uavcan::ReceivedDataStructure<uavcan::equipment::air_data::StaticPressure> &msg)
{
	baro_report report;

	/*
	 * FIXME HACK
	 * This code used to rely on msg.getMonotonicTimestamp().toUSec() instead of HRT.
	 * It stopped working when the time sync feature has been introduced, because it caused libuavcan
	 * to use an independent time source (based on hardware TIM5) instead of HRT.
	 * The proper solution is to be developed.
	 */
	report.timestamp   = hrt_absolute_time();
	report.temperature = last_temperature_kelvin - 273.15F;
	report.pressure    = msg.static_pressure / 100.0F;  // Convert to millibar
	report.error_count = 0;

	/* TODO get device ID for sensor */
	report.device_id = 0;

	/*
	 * Altitude computation
	 * Refer to the MS5611 driver for details
	 */
	const double T1 = 15.0 + 273.15; // temperature at base height in Kelvin
	const double a  = -6.5 / 1000;   // temperature gradient in degrees per metre
	const double g  = 9.80665;       // gravity constant in m/s/s
	const double R  = 287.05;        // ideal gas constant in J/kg/K

	const double p1 = _msl_pressure / 1000.0;      // current pressure at MSL in kPa
	const double p = double(msg.static_pressure) / 1000.0; // measured pressure in kPa

	report.altitude = (((std::pow((p / p1), (-(a * R) / g))) * T1) - T1) / a;

	// add to the ring buffer
	_reports.force(&report);

	publish(msg.getSrcNodeID().get(), &report);
}


text:
(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module unless amdModuleId is set
    define('simditor-date-button', ["jquery","simditor"], function (a0,b1) {
      return (root['DateButton'] = factory(a0,b1));
    });
  } else if (typeof module === 'object' && module.exports) {
    // Node. Does not work with strict CommonJS, but
    // only CommonJS-like environments that support module.exports,
    // like Node.
    module.exports = factory(require("jquery"),require("simditor"));
  } else {
    root['SimditorDateButton'] = factory(root["jQuery"],root["Simditor"]);
  }
}(this, function ($, Simditor) {

var DateButton,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

DateButton = (function(superClass) {
  extend(DateButton, superClass);

  function DateButton() {
    return DateButton.__super__.constructor.apply(this, arguments);
  }

  DateButton.prototype.name = 'date';

  DateButton.prototype.icon = 'none fa fa-clock-o';

  DateButton.prototype.htmlTag = 'span';

  DateButton.prototype.needFocus = true;

  DateButton.prototype._status = function() {};

  DateButton.prototype.command = function() {
    var $newBlock, $nextBlock, $rootBlock, $span;
    $rootBlock = this.editor.selection.rootNodes().first();
    $nextBlock = $rootBlock.next();
    if ($nextBlock.length > 0) {
      this.editor.selection.save();
    } else {
      $newBlock = $('<p/>').append(this.editor.util.phBr);
    }
    $span = $('<span/>').text(this._getDate()).insertAfter($rootBlock);
    if ($newBlock) {
      $newBlock.insertAfter($span);
      this.editor.selection.setRangeAtStartOf($newBlock);
    } else {
      this.editor.selection.restore();
    }
    return this.editor.trigger('valuechanged');
  };

  DateButton.prototype._getDate = function() {
    var day, fulldate, month, now, parse, time, year;
    now = new Date();
    day = now.getDate();
    month = now.getMonth() + 1;
    year = now.getFullYear();
    parse = function(n) {
      if (n > 9) {
        return n;
      } else {
        return "0" + n;
      }
    };
    fulldate = [parse(day), parse(month), year].join('/');
    time = now.toString().match(/\d\d:\d\d:\d\d/)[0];
    return fulldate + " " + time + " ";
  };

  return DateButton;

})(Simditor.Button);

Simditor.Toolbar.addButton(DateButton);

return DateButton;

}));


text:
package dtos.report

import models.qlkh.Task
import play.api.libs.json.Json

/**
 * The Class TaskDto.
 *
 * @author Nguyen Duc Dung
 * @since 4/15/14 2:44 PM
 *
 */
case class TaskDto(
                    id: Long,
                    name: String,
                    code: String,
                    donVi: String,
                    soLan: Option[Double] = None,
                    dinhMuc: Double,
                    hidden: Boolean,
                    children: List[TaskDto] = Nil
                    )

object TaskDto {

  implicit val jsonFormat = Json.format[TaskDto]

}


text:
package org.apache.commons.httpclient.params;

/**
 * This class represents a collection of HTTP protocol parameters applicable to
 * {@link org.apache.commons.httpclient.HostConfiguration instances of HostConfiguration}.
 * Protocol parameters may be linked together to form a hierarchy. If a particular
 * parameter value has not been explicitly defined in the collection itself, its
 * value will be drawn from the parent collection of parameters.
 *
 * @author Oleg Kalnichevski
 *
 * @version $Revision: 480424 $
 *
 * @since 3.0
 */
public class HostParams extends DefaultHttpParams {

    /**
     * Defines the request headers to be sent per default with each request.
     *

     * This parameter expects a value of type {@link java.util.Collection}. The
     * collection is expected to contain {@link org.apache.commons.httpclient.Header}s.
     *

     */
    public static final String DEFAULT_HEADERS = "http.default-headers";

    /**
     * Creates a new collection of parameters with the collection returned
     * by {@link #getDefaultParams()} as a parent. The collection will defer
     * to its parent for a default value if a particular parameter is not
     * explicitly set in the collection itself.
     *
     * @see #getDefaultParams()
     */
    public HostParams() {
        super();
    }

    /**
     * Creates a new collection of parameters with the given parent.
     * The collection will defer to its parent for a default value
     * if a particular parameter is not explicitly set in the collection
     * itself.
     *
     * @param defaults the parent collection to defer to, if a parameter
     * is not explictly set in the collection itself.
     *
     * @see #getDefaultParams()
     */
    public HostParams(HttpParams defaults) {
        super(defaults);
    }

    /**
     * Sets the virtual host name.
     *
     * @param hostname The host name
     */
    public void setVirtualHost(final String hostname) {
        setParameter(HttpMethodParams.VIRTUAL_HOST, hostname);
    }

    /**
     * Returns the virtual host name.
     *
     * @return The virtual host name
     */
    public String getVirtualHost() {
        return (String) getParameter(HttpMethodParams.VIRTUAL_HOST);
    }

}


text:
package com.test.web;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 *
 * @author Administrator jdbc练习
 */
public class JDBCTest {

	private static Connection con;
	private static Statement st;
	private static PreparedStatement pst;
	private static ResultSet rs;
	private static String sql = "select * from t_user";
	private static String url="jdbc:mysql://localhost:3306/crm?useUnicode=true&characterEncoding=utf-8";
	public static void getCollection() {
		try {
			Class.forName("com.mysql.jdbc.Driver");
			String url = "jdbc:mysql://localhost:3306/crm?useUnicode=true&characterEncoding=utf-8";
			con = DriverManager.getConnection(url, "root", "123456");
			st = con.createStatement();
			rs = st.executeQuery(sql);
			while(rs.next()){
				System.out.println(rs.getInt("id")+"----"+rs.getString("username"));
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			try {
				if(rs!=null){
					rs.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
			try {
				if(st!=null){
					st.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
			try {
				if(con!=null){
					con.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	public static void getCollection(String sql){
		try {
			Class.forName("com.mysql.jdbc.Driver");
			con = DriverManager.getConnection(url, "root", "123456");
			pst = con.prepareStatement(sql);
			rs = pst.executeQuery();
			while(rs.next()){
				System.out.println(rs.getInt("id")+"----"+rs.getString("username"));
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			try {
				if(rs!=null){
					rs.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
			try {
				if(st!=null){
					st.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
			try {
				if(con!=null){
					con.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	public static void main(String[] args) {
		getCollection();
		getCollection(sql);

	}
}


text:
local sprite = require "sprite"

local spriteOverlay = { type = "spriteOverlay" }
spriteOverlay.class = spriteOverlay

--- Creates a spriteOverlay. Can take the form of a sprite or the args table that would be passed to a sprite.
--- @tparam table|sprite spriteInstOrArgs Either a sprite to be turned into a spriteOverlay or the args table used to make a sprite.
--- @tparam sprite|nil parent (Optional) The parent of the spriteOverlay.
--- @return The created spriteOverlay.
function spriteOverlay:new(spriteInstOrArgs, parent)
    local args, spriteInst
    assert(type(spriteInstOrArgs) == "table", ("Table expected, got %s."):format(type(spriteInstOrArgs)))
    if spriteInstOrArgs.extends and spriteInstOrArgs:extends "sprite" then
        spriteInst = spriteInstOrArgs
    else
        args = spriteInstOrArgs
        parent = parent and parent or args.parent
        spriteInst = sprite:new(args) --If it's not a sprite, assume it's an args table to create a sprite.
    end
    assert(spriteInst:extends "sprite", ("Sprite expected, got %s."):format(type(spriteInst) == "table" and spriteInst.type or type(spriteInst)))

    --Don't allow the sprite class to be messed with.
    assert(spriteInst.class == sprite, "Cannot create spriteOverlay from sprite class, must be an instance!")

    if parent then
        spriteInst.parent = parent
    end
    spriteInst.group = "overlay" --Make sure it doesn't get drawn by default.
    spriteInst.class = spriteOverlay
    return spriteInst
end

--- Attaches this spriteOverlay onto the given sprite. Will error if a sprite is already attached.
--- @tparam sprite sprite The sprite this spriteOverlay should be attached to.
--- @tparam string|number key The key used when inserting this into its parent.
--- @return nil
function spriteOverlay:attach(parent, key)
    assert(self ~= spriteOverlay, ("Cannot modify class!"))
    if self.parent then
        self:detach()
    end
    parent.overlays = parent.overlays or {}
    parent.overlayKeys = parent.overlayKeys or {}
    key = key or #parent.overlays + 1
    parent.overlays[key] = parent

    --Add to the keys using insertion sort.
    for i = 1, #parent.overlayKeys do
        if parent.overlayKeys[i] > key then
            table.insert(parent.overlayKeys, i, key)
        elseif i == #parent.overlayKeys then
            parent.overlayKeys[i + 1] = key
        end
    end

    self.parent = parent
end

--- Detaches this spriteOverlay from the sprite it's currently attached to. Will error if no sprite is attached.
--- @return nil
function spriteOverlay:detach()
    assert(self.parent, "SpriteOverlay cannot detach, has no parent!")
    local parent = self.parent
    for key, overlay in parent.overlays do
        if overlay == self then
            table.remove(parent.overlays, key)
            break
        elseif not next(parent.overlays, key) then
            error(("spriteOverlay (ID#%d) is not attached correctly to its parent (ID#%d)."):format(self.Id, parent.Id))
        end
    end
    self.parent = nil
end

--- Draws this spriteOverlay using the same drawing behavior as sprite._draw, but uses values relative to the parent.

--- x, y, and rotation are additive (self value + parent value),

--- w and h are multiplicative (self value * parent value),

--- flipHorizontal and flipVertical are XOR'd (self value ~= parent value),

--- ox and oy are multiplied by the spriteOverlay's width/height after multiplication (self value * w/h).
--- @return nil
function spriteOverlay:draw()
    local x, y, w, h, rotation, flipHorizontal, flipVertical, ox, oy
    local parent = self.parent
    assert(parent, ("Sprite Overlay \"%s\" has no parent!"):format(self.imagePath))
    x = self.x + parent.x
    y = self.y + parent.y
    w = self.w * parent.w
    h = self.h * parent.h
    rotation = self.rotation + parent.rotation
    flipHorizontal = self.flipHorizontal ~= parent.flipHorizontal
    flipVertical = self.flipVertical ~= parent.flipVertical
    ox = self.ox * w / self.sx
    oy = self.oy * h / self.sy

    --_draw is inherited from sprite.
    return self:_draw(x, y, w, h, rotation, flipHorizontal, flipVertical, ox, oy)
end

return setmetatable(spriteOverlay, { __index = sprite, __call = spriteOverlay.new })


text:
package com.net;

public class NetType {

	public static final int CONST_ADDRESS = 0;
	public static final int CONST_VALID = 1;
	public static final int CONST_RATIO = 2;

	public int id;
	public int idx;
	public String addr;
	public int ratio;
	public boolean local;
	public boolean valid;

	public NetType(int id, int idx) {
		this.id = id;
		this.idx = idx;
		this.addr = "";
		this.ratio = 1;
		this.local = false;
		this.valid = false;
	}
}


text:
<?php
/**
 * Crystal DBAL
 *
 * An open source application for database manipulation
 *
 * @package		Crystal DBAL
 * @author		Martin Rusev
 * @link		http://crystal-project.net
 * @since		Version 0.1
 * @version     0.5
 */

// ------------------------------------------------------------------------
class Crystal_Query_Groupby
{

    function __construct($method, $groupby)
    {

    	$this->query->type = 'groupby';

		if(is_array($groupby) && !empty($groupby))
		{

				$this->query->sql = " GROUP BY";

				$filtered_params = Crystal_Parser_String::parse($groupby[0]);

				print_r($filtered_params);
				/** SINGLE PARAMETER HERE */
				if(is_string($filtered_params['string']))
				{
					$this->query->sql .= " ?";
					$this->query->params = $filtered_params['string'];

				}
				elseif(is_array($filtered_params) && !empty($filtered_params))
				{

					end($filtered_params);
					$last_element = key($filtered_params);
					reset($filtered_params);

					foreach($filtered_params as $key => $value)
					{

						$this->query->sql .= " ?";
						$this->query->params[] = $value;

						if($key != $last_element){  $this->query->sql .= ','; }

					}

				}
				else
				{
					throw new Crystal_Query_Exception('Invalid parameters in the group_by function');
				}

	        }

	    return $this->query;

    }

}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.controlador;

import com.bean.AlbumLogica;
import com.bean.ImagenLogica;
import com.bean.PerfilLogica;
import com.bean.PublicacionLogica;
import com.bean.SessionLogica;
import com.entidad.Album;
import com.entidad.Imagen;
import com.entidad.Perfil;
import com.entidad.Publicacion;
import com.util.Mensaje;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.view.ViewScoped;
import org.primefaces.model.UploadedFile;

/**
 *
 * @author ferna
 */
@ManagedBean(name="cPublicacion")
@ViewScoped
public class cPublicacion implements Serializable{

     private List<Album> arrAlbumSinDetalle;//Lista de albumes sin detalle,usado en una nueva publicacion
     private Publicacion objNPublicacion;//Objeto utilizado para la nueva publicacion
    private UploadedFile archivo; //Archivo del FileUpload de la nueva publicacion
    private List<Publicacion> arrPublicaciones;//Lista de publicaciones de un album, usado al ver las publicaciones de un album
    private int codAlbumParaPublicaciones=-1;
    //Vista de un Album(cualquier usuario autor o visitante)
    private Album objAlbumActualDetallado;
    private Perfil objPerfilPropietarioAlbumActual;
    private int codPerfilDePerticion=-1;

    /**
     * Creates a new instance of cAlbum
     */
    public cPublicacion() {
        this.objAlbumActualDetallado=new Album();
        this.arrAlbumSinDetalle=new ArrayList<Album>();
        this.objNPublicacion=new Publicacion();
        this.objPerfilPropietarioAlbumActual=new Perfil();
        this.codAlbumParaPublicaciones=-1;
        this.codPerfilDePerticion=-1;
    }

    /**
     * Metodo para llenar la lista de albumes
     * @return La lista de albumes que pertenecen al usuario de la session
     **/
    public List<Album> doCargarAlbumSinDetalle(){
        int codPerfil=new SessionLogica().obtenerUsuarioSession().getObjPerfil().getCodPerfil();
        this.arrAlbumSinDetalle=new AlbumLogica().BuscarAlbumUsuario(codPerfil);
        return this.arrAlbumSinDetalle;
    }

    public List<Album> getArrAlbumSinDetalle() {
        return arrAlbumSinDetalle;
    }

    public void setArrAlbumSinDetalle(List<Album> arrAlbumSinDetalle) {
        this.arrAlbumSinDetalle = arrAlbumSinDetalle;
    }

    public Publicacion getObjNPublicacion() {
        return objNPublicacion;
    }

    public void setObjNPublicacion(Publicacion objPublicacion) {
        this.objNPublicacion = objPublicacion;
    }

    public UploadedFile getArchivo() {
        return archivo;
    }

    public void setArchivo(UploadedFile archivo) {
        this.archivo = archivo;
    }

    public List<Publicacion> getArrPublicaciones() {
        return arrPublicaciones;
    }

    public void setArrPublicaciones(List<Publicacion> arrPublicaciones) {
        this.arrPublicaciones = arrPublicaciones;
    }

    public Perfil getObjPerfilPropietarioAlbumActual() {
        return objPerfilPropietarioAlbumActual;
    }

    public void setObjPerfilPropietarioAlbumActual(Perfil objPerfilPropietarioAlbumActual) {
        this.objPerfilPropietarioAlbumActual = objPerfilPropietarioAlbumActual;
    }

    /**
     * Metodo utilizado para almacenar una nueva publicacion
     **/
   public void publicarPost(){

       ImagenLogica imL=new ImagenLogica();

       //Pasa al objeto la imagen del fileUpload
       imL.getObjImagen().setImagen(this.archivo);

       //Guarda la imagen del nuevo post y se obtiene el nombre final de la imagen
       String nombreImagenPost=imL.guardarImgPost();

       //Inserta el nombre de la imagen al objeto de la nueva publicacion
       this.objNPublicacion.setImagenPub(nombreImagenPost);

       //Ingresa la nueva publicacion en la BD
       if(new PublicacionLogica().publicarPost(objNPublicacion)){
           //Mensaje satisfactorio
           Mensaje.msg("Ey Fliver!","Publicación exitosa");
           //Limpia el objeto
           this.retaurarPublicacion();
       }else{
           //Mensaje de error
           Mensaje.msg("Ups Fliver","Algo salió mal");
       }

   }

   //Restaura el objeto publicacion
   public void retaurarPublicacion(){
       this.objNPublicacion=new Publicacion();
   }

    public void verPublicacionesDeAlbumes(){
        if(this.codAlbumParaPublicaciones!=-1 && this.codPerfilDePerticion!=-1){
             this.objAlbumActualDetallado=new AlbumLogica().buscarAlbDetPorCodigoAlbum(this.codAlbumParaPublicaciones);
             this.objPerfilPropietarioAlbumActual=new PerfilLogica().buscarPerfilPorCodigo(this.codPerfilDePerticion);
             if(this.objAlbumActualDetallado!=null && this.objPerfilPropietarioAlbumActual!=null){
                this.arrPublicaciones= new PublicacionLogica().buscarPublicacionesDeAlbum(this.codAlbumParaPublicaciones);
             }else{
                 new SessionLogica().redirigirA("/user/404.xhtml");
             }

        }else{
            new SessionLogica().redirigirA("/user/404.xhtml");
        }
    }

    public int getCodAlbumParaPublicaciones() {
        return codAlbumParaPublicaciones;
    }

    public void setCodAlbumParaPublicaciones(int codAlbumParaPublicaciones) {
        this.codAlbumParaPublicaciones = codAlbumParaPublicaciones;
    }

    public Album getObjAlbumActualDetallado() {
        return objAlbumActualDetallado;
    }

    public void setObjAlbumActualDetallado(Album objAlbumActualDetallado) {
        this.objAlbumActualDetallado = objAlbumActualDetallado;
    }

    public int getCodPerfilDePerticion() {
        return codPerfilDePerticion;
    }

    public void setCodPerfilDePerticion(int codPerfilDePerticion) {
        this.codPerfilDePerticion = codPerfilDePerticion;
    }

    public boolean verfificarDueñoDelbumOPublicacion(){
        if(this.codPerfilDePerticion==new SessionLogica().obtenerUsuarioSession().getObjPerfil().getCodPerfil()){
            return true;
        }else{
            return false;
        }
    }

}


text:
<?php

$lang = 'pl';

$tagsBodyBasic = 'preload device--mobile scope--inside'; // platform-ios

$tagsNav = '';
$tagsTemplate = 'template--contentlist template--campaigns';

?>

<!DOCTYPE html>
<html lang="<?php echo $lang ?>">

  <?php include "components/head.php" ?>

<body class="<?php echo $tagsBodyBasic . ' ' . $tagsNav . ' ' . $tagsTemplate ?>">

  <?php include "components/bof-scripts.php" ?>

    <?php include 'components/nav.php' ?>

      <?php
      $headerIcon = 'rg-diary';
      $headerTitle = 'Pamiętnik kampanii';
      include("components/elements/diary_header.php");
      ?>

        <?php
        $inputName = "input";
        include("components/elements/answer_longform.php");
        ?>

        <?php
        $title = "Moi rozmówcy";
        $questions = ["Liczba moich rozmówców", "Tyle osób, nie słyszało o produkcie"];
        $questionsOriginals = ["Podaj liczbę rozmówców?", "Ilu, nie znało produktu?"];
        include("components/elements/diary_block_numbers.php");
        ?>

        <?php
        $items = [['Próbki',1], ['Kupony',5], ['Ulotki', 10]];
        $title = "Prezenty dla znajomych";
        include("components/elements/diary_dropdown.php");
        ?>

        <?php
        $card = 0;
        include("components/elements/diary_load_image_cards.php");
        ?>

          <button class="button-diary" type="button" name="button">Wyczyść</button>
          <button class="button-diary" type="button" name="button">Zapisz</button>

      <?php
      $headerIcon = 'rg-stack';
      $headerTitle = 'Poprzednie wpisy';
      include("components/elements/diary_header.php");
      ?>

3 sie 2016

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eveniet itaque nulla, neque illo, nesciunt expedita? Consequatur, praesentium quas maxime reprehenderit autem atque, architecto alias velit tempora eos dignissimos, odio adipisci!

3 sie 2016

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eveniet itaque nulla, neque illo, nesciunt expedita? Consequatur, praesentium quas maxime reprehenderit autem atque, architecto alias velit tempora eos dignissimos, odio adipisci!

    <?php include 'components/footer.php' ?>

  <?php
  include 'components/eof-scripts.php'
  ?>


text:
using System;
using ProtoBuf;
using TypeAlias;
using Xunit;

namespace Akka.Interfaced.ProtobufSerializer.Tests
{
    public class TestDefaultValue
    {
        [Fact]
        public void Test_Serialize_MessageContainingDefaultValues()
        {
            var serializer = new ProtobufSerializer(null);

            var msg = new IDefault_PayloadTable.CallWithDefault_Invoke { a = 2, b = 2, c = "Test" };
            var obj = new RequestMessage { InvokePayload = msg };

            var bytes = serializer.ToBinary(obj);
            var obj2 = (RequestMessage)serializer.FromBinary(bytes, null);
            var msg2 = (IDefault_PayloadTable.CallWithDefault_Invoke)obj2.InvokePayload;

            Assert.Equal(msg.a, msg2.a);
            Assert.Equal(msg.b, msg2.b);
            Assert.Equal(msg.c, msg2.c);
        }

        [Fact]
        public void Test_Check_SizeReduction_When_MessageContainingDefaultValues()
        {
            var serializer = new ProtobufSerializer(null);

            var msg1 = new IDefault_PayloadTable.Call_Invoke { a = 1, b = 2, c = "Test" };
            var msg2 = new IDefault_PayloadTable.CallWithDefault_Invoke { a = 1, b = 2, c = "Test" };

            var bytes1 = serializer.ToBinary(new RequestMessage { InvokePayload = msg1 });
            var bytes2 = serializer.ToBinary(new RequestMessage { InvokePayload = msg2 });

            Assert.InRange(bytes2.Length, 0, bytes1.Length - 1);
        }
    }
}


text:
// Copyright (C) 2005 Xito.org. http://www.xito.org
//
// This file is part of Xito(tm).
//
// This Software is licensed under the terms of the
// COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0
//
// To view the complete Terms of this license visit:
// http://www.opensource.org/licenses/cddl1.txt
//
// COVERED SOFTWARE IS PROVIDED UNDER THIS LICENSE ON AN AS IS BASIS, WITHOUT
// WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT
// LIMITATION, WARRANTIES THAT THE COVERED SOFTWARE IS FREE OF DEFECTS,
// MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE OR NON-INFRINGING. THE ENTIRE
// RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED SOFTWARE IS WITH YOU.
// SHOULD ANY COVERED SOFTWARE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT THE
// INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY
// NECESSARY SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY
// CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. NO USE OF ANY COVERED
// SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS DISCLAIMER.

package org.xito.launcher;

public interface LauncherActionCreatedListener {

   /**
    * A Launcher Action was created
    * @param action
    */
   public void launcherActionCreated(LauncherAction action);

}


text:
using System;

using Public.Common.Lib.Visuals;

namespace Eshunna.Lib
{
    public class ImageScaler
    {
        #region Static

        public static double MaximumDimensionScaleFactorGet(ImageSize from, ImageSize to)
        {
            int maxFromDimensionSize = from.Width > from.Height ? from.Width : from.Height;
            int maxToDimensionSize = to.Width > to.Height ? to.Width : to.Height;

            double maxFromDbl = Convert.ToDouble(maxFromDimensionSize);
            double maxToDbl = Convert.ToDouble(maxToDimensionSize);

            double output = maxToDbl / maxFromDbl;
            return output;
        }

        #endregion
    }
}


text:
class UInput {
private:
	int fd; // Handle for uinput file ops

	int open(const char *uinput_path);
	void openAll();
  void setup(const char *dev_name, const std::map<const __u16,  std::list<__u16> > & keys);
	void create();

	void destroy();

	// TODO Add something like
	// onUInputEvent(

public:
  UInput(const char *dev_name, const std::map<const __u16,  std::list<__u16> > & keys);
	virtual ~UInput();

	void send_event(__u16 type, __u16 code, __s32 value) const;
	void sync() const;
};

#endif //uinput_h


text:
#include <aws/glue/model/GetJobRunRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Glue::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

GetJobRunRequest::GetJobRunRequest() :
    m_jobNameHasBeenSet(false),
    m_runIdHasBeenSet(false),
    m_predecessorsIncluded(false),
    m_predecessorsIncludedHasBeenSet(false)
{
}

Aws::String GetJobRunRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_jobNameHasBeenSet)
  {
   payload.WithString("JobName", m_jobName);

  }

  if(m_runIdHasBeenSet)
  {
   payload.WithString("RunId", m_runId);

  }

  if(m_predecessorsIncludedHasBeenSet)
  {
   payload.WithBool("PredecessorsIncluded", m_predecessorsIncluded);

  }

  return payload.View().WriteReadable();
}

Aws::Http::HeaderValueCollection GetJobRunRequest::GetRequestSpecificHeaders() const
{
  Aws::Http::HeaderValueCollection headers;
  headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "AWSGlue.GetJobRun"));
  return headers;

}


text:
from behave import *

# Common to this feature
@when('I visit my activation page "{url}"')
def impl(context, url):
    context.browser.visit(context.config.server_url + '/accounts/activate/' + url )

# Unique to Scenario: Invited user visits page to activate account
@then('I see the activate account form, prepopulated with my data')
def impl(context):
    assert context.browser.find_by_css('.activate-account').visible
    assert context.browser.find_by_name('full_name').value == 'Inactive User'

# Unique to Scenario: Invited user activates their account
@when('I activate my account')
def impl(context):
    context.execute_steps('''
        when I enter "First Last" into the "full name" field
         and I enter "pass" into the "password" field
         and I enter "pass" into the "confirm password" field
         and I submit the form
    ''')

@then('I see a welcome modal')
def impl(context):
    assert context.browser.find_by_css('.welcome-message').visible


text:
<?php

// Require the base class.
require_once dirname(__DIR__) . '/BaseExample.php';

/**
 * This example returns all files available to the specified user profile.
 */
class GetAllFiles extends BaseExample
{
    /**
     * {@inheritdoc}
     * @see BaseExample::getInputParameters()
     * @return array
     */
    protected function getInputParameters()
    {
        return [['name' => 'user_profile_id',
                 'display' => 'User Profile ID',
                 'required' => true]];
    }

    /**
     * {@inheritdoc}
     * @see BaseExample::run()
     */
    public function run()
    {
        $values = $this->formValues;

        print '
Listing all report files
';

        $this->printResultsTableHeader('Files');

        do {
            $files = $this->service->files->listFiles(
                $values['user_profile_id'],
                ['pageToken' => $pageToken]
            );

            foreach ($files['items'] as $file) {
                $url = $file['urls']['browserUrl'];
                $file['download'] = 'Link';
                $this->printResultsTableRow($file);
            }

            $pageToken = $files['nextPageToken'];
        } while (!empty($files['items']) && !empty($pageToken));

        $this->printResultsTableFooter();
    }

    /**
     * {@inheritdoc}
     * @see BaseExample::getName()
     * @return string
     */
    public static function getName()
    {
        return 'Get All Files';
    }

    /**
     * {@inheritdoc}
     * @see BaseExample::getResultsTableHeaders()
     * @return array
     */
    public function getResultsTableHeaders()
    {
        return ['id' => 'File ID',
                'fileName' => 'File Name',
                'reportId' => 'Report ID',
                'format' => 'File Format',
                'status' => 'Status',
                'download' => 'Download'];
    }
}


text:
if [ ! "${lobster_args[2]}" ]; then
  lobster_error "Usage show config {varname}"
  lobster_exit 1
fi

eval value=\$${lobster_args[2]}
lobster_echo "\"${lobster_args[2]}\" is set to $(lobster_success $value)"


text:
<?php defined('APP_DIR') OR exit("No direct script access allowed\n");

class Progress extends ClipLibrary{

  // Types of progress available.
  const PERCENT = 1;
  const BAR = 2;
  const BAR_RATE_ITEMS = 3;
  const BAR_RATE_SECONDS = 4;

  /**
   * Type of progress.
   * Default to Progress::PERCENT
   */
  private $type = Progress::PERCENT;

  /**
   * Total number of items.
   */
  private $total = NULL;

  /**
   * Number of items done
   */
  private $done = 0;

  /**
   * Last printed line.
   * For performance reasons the progress is only printed
   * if different than last one.
   */
  private $last_printed = NULL;

  /**
   * Data to be printed.
   */
  private $current_printed = NULL;

  /**
   * Number of times information was printed.
   */
  private $num_prints = 0;

  /**
   * Lock to prevent changing data after the progress started.
   */
  private $locked = FALSE;

  /**
   * Status of the progress. Finished or not.
   */
  private $finished = FALSE;

  /**
   * Time of the first update.
   */
  private $time_start = NULL;

  /**
   * Time of the last update.
   */
  private $time_end = NULL;

  /**
   * Dumps the status of the Progress
   *
   * @return string
   */
  function __toString() {
    $dump = "Total time (sec):\t" . $this->getTotalTime() . "\n";
    $dump .= "Total items:\t\t" . $this->total . "\n";
    $dump .= "Rate (items/sec):\t" . $this->getItemsPerSecond() . "\n";
    $dump .= "Rate (secs/item):\t" . $this->getSecondsPerItem() . "\n";
    $dump .= "Number prints:\t\t" . $this->getNumPrints() . "\n";

    return $dump;
  }

  /**
   * Sets the type of Progress.
   * Available types:
   * Progress::BAR, Progress::PERCENT, Progress::BAR_RATE_ITEMS, Progress::BAR_RATE_SECONDS
   *
   * @param int $type
   *
   * @return Progress
   *   Returns object to allow chaining.
   *
   * @throw Exception
   *   If the trying to change type after the Progress started.
   *   If trying to set an invalid Progress type.
   */
  public function type($type){
   if ($this->locked) {
     throw new ClipLibraryException("After the progress is updated, the settings can't be changed.");
   }

   if (!in_array($type, array(Progress::BAR, Progress::PERCENT, Progress::BAR_RATE_ITEMS, Progress::BAR_RATE_SECONDS))) {
     throw new ClipLibraryException("Invalid Progress type.");
   }

   $this->type =  $type;
   return $this;
  }

  /**
   * Sets the total for the progress.
   *
   * @param int $total
   *
   * @return Progress
   *   Returns object to allow chaining.
   *
   * @throw Exception
   *   If the trying to change type after the Progress started.
   */
  public function total($total) {
    if ($this->locked) {
      throw new ClipLibraryException("After the progress is updated, the settings can't be changed.");
    }

    if ($total < 1) {
      throw new ClipLibraryException("Progress total can't be lower than 1.");
    }

    $this->total = $total;
    return $this;
  }

  /**
   * Returns the total amount of time the progress took to complete.
   * If the progress is not finished yet, will return the elapsed time.
   *
   * @return float
   */
  public function getTotalTime() {
    if ($this->time_start == NULL) {
      // No update was made.
      return 0;
    }
    elseif ($this->time_end == NULL) {
      // Elapsed time.
    	return microtime(TRUE) - $this->time_start;
    }
    else {
      // Total time.
      return $this->time_end - $this->time_start;
    }
  }

  /**
   * Returns the amount of items processed per second.
   *
   * @return float
   */
  public function getItemsPerSecond() {
    // x items per second.
    return $this->getTotalTime() == 0 ? $this->done : $this->done / $this->getTotalTime();
  }

  /**
   * Returns the amount of seconds needed to process one item.
   *
   * @return float
   */
  public function getSecondsPerItem() {
    // x seconds per item.
    return $this->done == 0 ? 0 : $this->getTotalTime() / $this->done;
  }

  /**
   * Return the number of times progress was printed.
   *
   * @return int
   */
  public function getNumPrints() {
    return $this->num_prints;
  }

  /**
   * Resets the progress to allow a new usage.
   *
   * @return Progress
   *   Returns object to allow chaining.
   */
  public function reset() {
    $this->locked = FALSE;
    $this->done = 0;
    $this->total = NULL;
    $this->last_printed = NULL;
    $this->current_printed = NULL;
    $this->num_prints = 0;
    $this->finished = FALSE;
    $this->time_start = NULL;
    $this->time_end = NULL;

    return $this;
  }

  /**
   * Computes the progress based on the type.
   * By default, and for performance reasons the progress is only printed
   * if there were any changes.
   *
   * @param int $value
   *   The new progress value.
   * @param boolean $force_update
   *   Forces the printing of the progress even if there are no changes.
   *   Has a huge impact on performance.
   *   Default to FALSE.
   */
  public function update($value, $force_update = FALSE) {
    if ($this->total === NULL) {
      throw new ClipLibraryException("Progress total value was not set.");
    }

    // After the first update lock the progress.
    if (!$this->locked) {
      $this->locked = TRUE;
      $this->time_start = microtime(TRUE);
    }

    // Finished. Do nothing.
    if ($this->finished) {
      return FALSE;
    }

    // Total value fail safe.
    if ($value >= $this->total) {
      $this->done = $this->total;
      // Set the progress to finish but still allow one last execution.
      $this->finished = TRUE;
    }
    else {
      // Set the current value.
      $this->done = $value;
    }

    // Render depending on the type.
    switch ($this->type) {
      case Progress::PERCENT:
        $this->computePercent();
        break;
      case Progress::BAR:
        $this->computeBar();
        break;
      case Progress::BAR_RATE_ITEMS:
        $this->computeBarRateItems();
        break;
      case Progress::BAR_RATE_SECONDS:
        $this->computeBarRateSeconds();
        break;
    }

    // Print only if something changed.
    // Printing takes a huge impact on performance, so print the
    // least amount of times possible.
    if ($this->current_printed != $this->last_printed || $force_update) {
      // Only print \r if is not the first line.
      if ($this->last_printed !== NULL) {
        p("\r");
      }

      p($this->current_printed);
      // Store the number of prints just because.
      $this->num_prints++;

      // If the string to be printed is smaller then the one printed
      // before, add spaces.
      $length_diff = strlen($this->last_printed) - strlen($this->current_printed);
      if ($length_diff > 0) {
        p(str_repeat(" ", $length_diff));
      }

      // Store the last printed value.
      $this->last_printed = $this->current_printed;
    }

    // This means it's the last iteration.
    if ($this->finished) {
      // Print a new line.
      pl();
      $this->time_end = microtime(TRUE);
    }
  }

  /**
   * Compose the PERCENT progress type.
   * Sets the current_printed value.
   */
  private function computePercent() {
    $this->current_printed = $this->drawPercent();
  }

  /**
   * Compose the BAR progress type.
   * Sets the current_printed value.
   */
  private function computeBar() {
    $this->current_printed = $this->drawBar() . " " . $this->drawPercent();
  }

  /**
   * Compose the BAR_RATE_ITEMS progress type.
   * Sets the current_printed value.
   */
  private function computeBarRateItems() {
    $this->current_printed = $this->drawBar() . " " . $this->drawPercent() . "    " . round($this->getItemsPerSecond()) . " items per second";
  }

  /**
   * Compose the BAR_RATE_SECONDS progress type.
   * Sets the current_printed value.
   */
  private function computeBarRateSeconds() {
    $this->current_printed = $this->drawBar() . " " . $this->drawPercent() . "    " . round($this->getSecondsPerItem(), 2) . " seconds per item";
  }

  /**
   * Calc percentage.
   *
   * @param int $precision
   *   Rounding precision.
   *
   * @return string
   *   Percent value: 12.34 %
   */
  private function drawPercent($precision = 2) {
    return round($this->done / $this->total * 100, 2) . ' %';
  }

  /**
   * Prepares a progress bar.
   *
   * @param int $size
   *   Bar size
   *
   * @return string
   *   Bar: [======>     ]
   */
  private function drawBar($size = 45) {
    $perc = (double)($this->done / $this->total);
    $bar = floor($perc * $size);

    $status_bar = "[";
    $status_bar .= str_repeat("=", $bar);
    if ($bar < $size) {
        $status_bar .= ">";
        $status_bar .= str_repeat(" ", $size - $bar);
    } else {
        $status_bar .= "=";
    }
    $status_bar .= "]";

    return $status_bar;
  }
}

?>


text:
namespace {

static download::AutoResumptionHandler* g_auto_resumption_handler = nullptr;

// The delay to wait for after a chrome restart before resuming all pending
// downloads so that tab loading doesn't get impacted.
const base::TimeDelta kAutoResumeStartupDelay =
    base::TimeDelta::FromSeconds(10);

// The interval at which various download updates are grouped together for
// computing the params for the task scheduler.
const base::TimeDelta kBatchDownloadUpdatesInterval =
    base::TimeDelta::FromSeconds(1);

// The delay to wait for before immediately retrying a download after it got
// interrupted due to network reasons.
const base::TimeDelta kDownloadImmediateRetryDelay =
    base::TimeDelta::FromSeconds(1);

// The task type to use for scheduling a task.
const download::DownloadTaskType kResumptionTaskType =
    download::DownloadTaskType::DOWNLOAD_AUTO_RESUMPTION_TASK;

// The window start time after which the system should fire the task.
const int64_t kWindowStartTimeSeconds = 0;

// The window end time before which the system should fire the task.
const int64_t kWindowEndTimeSeconds = 24 * 60 * 60;

bool IsMetered(network::mojom::ConnectionType type) {
  switch (type) {
    case network::mojom::ConnectionType::CONNECTION_2G:
    case network::mojom::ConnectionType::CONNECTION_3G:
    case network::mojom::ConnectionType::CONNECTION_4G:
      return true;
    case network::mojom::ConnectionType::CONNECTION_ETHERNET:
    case network::mojom::ConnectionType::CONNECTION_WIFI:
    case network::mojom::ConnectionType::CONNECTION_UNKNOWN:
    case network::mojom::ConnectionType::CONNECTION_NONE:
    case network::mojom::ConnectionType::CONNECTION_BLUETOOTH:
      return false;
  }
  NOTREACHED();
  return false;
}

bool IsConnected(network::mojom::ConnectionType type) {
  switch (type) {
    case network::mojom::ConnectionType::CONNECTION_UNKNOWN:
    case network::mojom::ConnectionType::CONNECTION_NONE:
    case network::mojom::ConnectionType::CONNECTION_BLUETOOTH:
      return false;
    default:
      return true;
  }
}

}  // namespace

namespace download {

AutoResumptionHandler::Config::Config()
    : auto_resumption_size_limit(0),
      is_auto_resumption_enabled_in_native(false) {}

// static
void AutoResumptionHandler::Create(
    std::unique_ptr<download::NetworkStatusListener> network_listener,
    std::unique_ptr<download::TaskManager> task_manager,
    std::unique_ptr<Config> config) {
  DCHECK(!g_auto_resumption_handler);
  g_auto_resumption_handler = new AutoResumptionHandler(
      std::move(network_listener), std::move(task_manager), std::move(config));
}

// static
AutoResumptionHandler* AutoResumptionHandler::Get() {
  return g_auto_resumption_handler;
}

AutoResumptionHandler::AutoResumptionHandler(
    std::unique_ptr<download::NetworkStatusListener> network_listener,
    std::unique_ptr<download::TaskManager> task_manager,
    std::unique_ptr<Config> config)
    : network_listener_(std::move(network_listener)),
      task_manager_(std::move(task_manager)),
      config_(std::move(config)) {
  network_listener_->Start(this);
}

AutoResumptionHandler::~AutoResumptionHandler() {
  network_listener_->Stop();
}

void AutoResumptionHandler::SetResumableDownloads(
    const std::vector<download::DownloadItem*>& downloads) {
  resumable_downloads_.clear();
  for (auto* download : downloads) {
    if (!IsAutoResumableDownload(download))
      continue;
    resumable_downloads_.insert(std::make_pair(download->GetGuid(), download));
    download->RemoveObserver(this);
    download->AddObserver(this);
  }

  base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
      FROM_HERE,
      base::BindOnce(&AutoResumptionHandler::ResumePendingDownloads,
                     weak_factory_.GetWeakPtr()),
      kAutoResumeStartupDelay);
}

bool AutoResumptionHandler::IsActiveNetworkMetered() const {
  return IsMetered(network_listener_->GetConnectionType());
}

void AutoResumptionHandler::OnNetworkChanged(
    network::mojom::ConnectionType type) {
  if (!IsConnected(type))
    return;

  ResumePendingDownloads();
}

void AutoResumptionHandler::OnDownloadStarted(download::DownloadItem* item) {
  item->RemoveObserver(this);
  item->AddObserver(this);

  OnDownloadUpdated(item);
}

void AutoResumptionHandler::OnDownloadUpdated(download::DownloadItem* item) {
  if (IsAutoResumableDownload(item))
    resumable_downloads_[item->GetGuid()] = item;
  else
    resumable_downloads_.erase(item->GetGuid());

  if (item->GetState() == download::DownloadItem::INTERRUPTED &&
      IsAutoResumableDownload(item) && SatisfiesNetworkRequirements(item)) {
    downloads_to_retry_.insert(item);
    base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
        FROM_HERE,
        base::BindOnce(&AutoResumptionHandler::ResumeDownloadImmediately,
                       weak_factory_.GetWeakPtr()),
        kDownloadImmediateRetryDelay);
    return;
  }
  RecomputeTaskParams();
}

void AutoResumptionHandler::OnDownloadRemoved(download::DownloadItem* item) {
  resumable_downloads_.erase(item->GetGuid());
  RecomputeTaskParams();
}

void AutoResumptionHandler::OnDownloadDestroyed(download::DownloadItem* item) {
  resumable_downloads_.erase(item->GetGuid());
  downloads_to_retry_.erase(item);
}

void AutoResumptionHandler::ResumeDownloadImmediately() {
  for (auto* download : std::move(downloads_to_retry_)) {
    if (SatisfiesNetworkRequirements(download))
      download->Resume(false);
    else
      RecomputeTaskParams();
  }
  downloads_to_retry_.clear();
}

void AutoResumptionHandler::OnStartScheduledTask(
    download::TaskFinishedCallback callback) {
  task_manager_->OnStartScheduledTask(kResumptionTaskType, std::move(callback));
  ResumePendingDownloads();
}

bool AutoResumptionHandler::OnStopScheduledTask() {
  task_manager_->OnStopScheduledTask(kResumptionTaskType);
  RescheduleTaskIfNecessary();
  return false;
}

void AutoResumptionHandler::RecomputeTaskParams() {
  if (recompute_task_params_scheduled_)
    return;

  recompute_task_params_scheduled_ = true;
  base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
      FROM_HERE,
      base::BindOnce(&AutoResumptionHandler::RescheduleTaskIfNecessary,
                     weak_factory_.GetWeakPtr()),
      kBatchDownloadUpdatesInterval);
}

void AutoResumptionHandler::RescheduleTaskIfNecessary() {
  if (!config_->is_auto_resumption_enabled_in_native)
    return;

  recompute_task_params_scheduled_ = false;

  bool has_resumable_downloads = false;
  bool has_actionable_downloads = false;
  bool can_download_on_metered = false;
  for (auto iter = resumable_downloads_.begin();
       iter != resumable_downloads_.end(); ++iter) {
    download::DownloadItem* download = iter->second;
    if (!IsAutoResumableDownload(download))
      continue;

    has_resumable_downloads = true;
    has_actionable_downloads |= SatisfiesNetworkRequirements(download);
    can_download_on_metered |= download->AllowMetered();
    if (can_download_on_metered)
      break;
  }

  if (!has_actionable_downloads)
    task_manager_->NotifyTaskFinished(kResumptionTaskType, false);

  if (!has_resumable_downloads) {
    task_manager_->UnscheduleTask(kResumptionTaskType);
    return;
  }

  download::TaskManager::TaskParams task_params;
  task_params.require_unmetered_network = !can_download_on_metered;
  task_params.window_start_time_seconds = kWindowStartTimeSeconds;
  task_params.window_end_time_seconds = kWindowEndTimeSeconds;
  task_manager_->ScheduleTask(kResumptionTaskType, task_params);
}

void AutoResumptionHandler::ResumePendingDownloads() {
  if (!config_->is_auto_resumption_enabled_in_native)
    return;

  for (auto iter = resumable_downloads_.begin();
       iter != resumable_downloads_.end(); ++iter) {
    download::DownloadItem* download = iter->second;
    if (!IsAutoResumableDownload(download))
      continue;

    if (SatisfiesNetworkRequirements(download))
      download->Resume(false);
  }
}

bool AutoResumptionHandler::SatisfiesNetworkRequirements(
    download::DownloadItem* download) {
  if (!IsConnected(network_listener_->GetConnectionType()))
    return false;

  return download->AllowMetered() || !IsActiveNetworkMetered();
}

bool AutoResumptionHandler::IsAutoResumableDownload(
    download::DownloadItem* item) {
  if (!item || item->IsDangerous())
    return false;

  switch (item->GetState()) {
    case download::DownloadItem::IN_PROGRESS:
      return !item->IsPaused();
    case download::DownloadItem::COMPLETE:
    case download::DownloadItem::CANCELLED:
      return false;
    case download::DownloadItem::INTERRUPTED:
      return !item->IsPaused() &&
             IsInterruptedDownloadAutoResumable(
                 item, config_->auto_resumption_size_limit);
    case download::DownloadItem::MAX_DOWNLOAD_STATE:
      NOTREACHED();
  }

  return false;
}

// static
bool AutoResumptionHandler::IsInterruptedDownloadAutoResumable(
    download::DownloadItem* download_item,
    int auto_resumption_size_limit) {
  DCHECK_EQ(download::DownloadItem::INTERRUPTED, download_item->GetState());
  if (download_item->IsDangerous())
    return false;

  if (!download_item->GetURL().SchemeIsHTTPOrHTTPS())
    return false;

  if (download_item->GetBytesWasted() > auto_resumption_size_limit)
    return false;

  int interrupt_reason = download_item->GetLastReason();
  DCHECK_NE(interrupt_reason, download::DOWNLOAD_INTERRUPT_REASON_NONE);
  return interrupt_reason ==
             download::DOWNLOAD_INTERRUPT_REASON_NETWORK_TIMEOUT ||
         interrupt_reason ==
             download::DOWNLOAD_INTERRUPT_REASON_NETWORK_FAILED ||
         interrupt_reason ==
             download::DOWNLOAD_INTERRUPT_REASON_NETWORK_DISCONNECTED ||
         interrupt_reason == download::DOWNLOAD_INTERRUPT_REASON_CRASH;
}

}  // namespace download


text:
package org.apache.hadoop.yarn.server.resourcemanager.scheduler;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.classification.InterfaceAudience.Private;
import org.apache.hadoop.classification.InterfaceStability.Unstable;
import org.apache.hadoop.yarn.api.records.ApplicationAttemptId;
import org.apache.hadoop.yarn.api.records.ApplicationId;
import org.apache.hadoop.yarn.api.records.Container;
import org.apache.hadoop.yarn.api.records.Priority;
import org.apache.hadoop.yarn.api.records.Resource;
import org.apache.hadoop.yarn.api.records.ResourceRequest;
import org.apache.hadoop.yarn.server.resourcemanager.recovery.ApplicationsStore.ApplicationStore;
import org.apache.hadoop.yarn.server.resourcemanager.resource.Resources;
import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptState;
import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNode;
import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNodeImpl;

/**
 * This class keeps track of all the consumption of an application. This also
 * keeps track of current running/completed containers for the application.
 */
@Private
@Unstable
public class AppSchedulingInfo {

  private static final Log LOG = LogFactory.getLog(AppSchedulingInfo.class);
  private final ApplicationAttemptId applicationAttemptId;
  final ApplicationId applicationId;
  private final String queueName;
  Queue queue;
  final String user;
  private final AtomicInteger containerIdCounter = new AtomicInteger(0);

  final Set<Priority> priorities = new TreeSet<Priority>(
      new org.apache.hadoop.yarn.server.resourcemanager.resource.Priority.Comparator());
  final Map<Priority, Map<String, ResourceRequest>> requests =
    new HashMap<Priority, Map<String, ResourceRequest>>();

  //private final ApplicationStore store;
  private final ActiveUsersManager activeUsersManager;

  /* Allocated by scheduler */
  boolean pending = true; // for app metrics

  public AppSchedulingInfo(ApplicationAttemptId appAttemptId,
      String user, Queue queue, ActiveUsersManager activeUsersManager,
      ApplicationStore store) {
    this.applicationAttemptId = appAttemptId;
    this.applicationId = appAttemptId.getApplicationId();
    this.queue = queue;
    this.queueName = queue.getQueueName();
    this.user = user;
    //this.store = store;
    this.activeUsersManager = activeUsersManager;
  }

  public ApplicationId getApplicationId() {
    return applicationId;
  }

  public ApplicationAttemptId getApplicationAttemptId() {
    return applicationAttemptId;
  }

  public String getQueueName() {
    return queueName;
  }

  public String getUser() {
    return user;
  }

  public synchronized boolean isPending() {
    return pending;
  }

  /**
   * Clear any pending requests from this application.
   */
  private synchronized void clearRequests() {
    priorities.clear();
    requests.clear();
    LOG.info("Application " + applicationId + " requests cleared");
  }

  public int getNewContainerId() {
    return this.containerIdCounter.incrementAndGet();
  }

  /**
   * The ApplicationMaster is updating resource requirements for the
   * application, by asking for more resources and releasing resources acquired
   * by the application.
   *
   * @param requests
   *          resources to be acquired
   */
  synchronized public void updateResourceRequests(
      List<ResourceRequest> requests) {
    QueueMetrics metrics = queue.getMetrics();
    // Update resource requests
    for (ResourceRequest request : requests) {
      Priority priority = request.getPriority();
      String hostName = request.getHostName();
      boolean updatePendingResources = false;
      ResourceRequest lastRequest = null;

      if (hostName.equals(RMNode.ANY)) {
        if (LOG.isDebugEnabled()) {
          LOG.debug("update:" + " application=" + applicationId + " request="
              + request);
        }
        updatePendingResources = true;

        // Premature optimization?
        // Assumes that we won't see more than one priority request updated
        // in one call, reasonable assumption... however, it's totally safe
        // to activate same application more than once.
        // Thus we don't need another loop ala the one in decrementOutstanding()
        // which is needed during deactivate.
        if (request.getNumContainers() > 0) {
          activeUsersManager.activateApplication(user, applicationId);
        }
      }

      Map<String, ResourceRequest> asks = this.requests.get(priority);

      if (asks == null) {
        asks = new HashMap<String, ResourceRequest>();
        this.requests.put(priority, asks);
        this.priorities.add(priority);
      } else if (updatePendingResources) {
        lastRequest = asks.get(hostName);
      }

      asks.put(hostName, request);
      if (updatePendingResources) {

        // Similarly, deactivate application?
        if (request.getNumContainers() <= 0) {
          LOG.info("checking for deactivate... ");
          checkForDeactivation();
        }

        int lastRequestContainers = lastRequest != null ? lastRequest
            .getNumContainers() : 0;
        Resource lastRequestCapability = lastRequest != null ? lastRequest
            .getCapability() : Resources.none();
        metrics.incrPendingResources(user, request.getNumContainers()
            - lastRequestContainers, Resources.subtractFrom( // save a clone
            Resources.multiply(request.getCapability(), request
                .getNumContainers()), Resources.multiply(lastRequestCapability,
                lastRequestContainers)));
      }
    }
  }

  synchronized public Collection<Priority> getPriorities() {
    return priorities;
  }

  synchronized public Map<String, ResourceRequest> getResourceRequests(
      Priority priority) {
    return requests.get(priority);
  }

  synchronized public ResourceRequest getResourceRequest(Priority priority,
      String nodeAddress) {
    Map<String, ResourceRequest> nodeRequests = requests.get(priority);
    return (nodeRequests == null) ? null : nodeRequests.get(nodeAddress);
  }

  public synchronized Resource getResource(Priority priority) {
    ResourceRequest request = getResourceRequest(priority, RMNode.ANY);
    return request.getCapability();
  }

  /**
   * Resources have been allocated to this application by the resource
   * scheduler. Track them.
   *
   * @param type
   *          the type of the node
   * @param node
   *          the nodeinfo of the node
   * @param priority
   *          the priority of the request.
   * @param request
   *          the request
   * @param container
   *          the containers allocated.
   */
  synchronized public void allocate(NodeType type, SchedulerNode node,
      Priority priority, ResourceRequest request, Container container) {
    if (type == NodeType.NODE_LOCAL) {
      allocateNodeLocal(node, priority, request, container);
    } else if (type == NodeType.RACK_LOCAL) {
      allocateRackLocal(node, priority, request, container);
    } else {
      allocateOffSwitch(node, priority, request, container);
    }
    QueueMetrics metrics = queue.getMetrics();
    if (pending) {
      // once an allocation is done we assume the application is
      // running from scheduler's POV.
      pending = false;
      metrics.incrAppsRunning(this, user);
    }
    LOG.debug("allocate: user: " + user + ", memory: "
        + request.getCapability());
    metrics.allocateResources(user, 1, request.getCapability());
  }

  /**
   * The {@link ResourceScheduler} is allocating data-local resources to the
   * application.
   *
   * @param allocatedContainers
   *          resources allocated to the application
   */
  synchronized private void allocateNodeLocal(SchedulerNode node, Priority priority,
      ResourceRequest nodeLocalRequest, Container container) {
    // Update consumption and track allocations
    allocate(container);

    // Update future requirements
    nodeLocalRequest.setNumContainers(nodeLocalRequest.getNumContainers() - 1);
    if (nodeLocalRequest.getNumContainers() == 0) {
      this.requests.get(priority).remove(node.getHostName());
    }

    ResourceRequest rackLocalRequest = requests.get(priority).get(
        node.getRackName());
    rackLocalRequest.setNumContainers(rackLocalRequest.getNumContainers() - 1);
    if (rackLocalRequest.getNumContainers() == 0) {
      this.requests.get(priority).remove(node.getRackName());
    }

    decrementOutstanding(requests.get(priority).get(RMNode.ANY));
  }

  /**
   * The {@link ResourceScheduler} is allocating data-local resources to the
   * application.
   *
   * @param allocatedContainers
   *          resources allocated to the application
   */
  synchronized private void allocateRackLocal(SchedulerNode node, Priority priority,
      ResourceRequest rackLocalRequest, Container container) {

    // Update consumption and track allocations
    allocate(container);

    // Update future requirements
    rackLocalRequest.setNumContainers(rackLocalRequest.getNumContainers() - 1);
    if (rackLocalRequest.getNumContainers() == 0) {
      this.requests.get(priority).remove(node.getRackName());
    }

    decrementOutstanding(requests.get(priority).get(RMNode.ANY));
  }

  /**
   * The {@link ResourceScheduler} is allocating data-local resources to the
   * application.
   *
   * @param allocatedContainers
   *          resources allocated to the application
   */
  synchronized private void allocateOffSwitch(SchedulerNode node, Priority priority,
      ResourceRequest offSwitchRequest, Container container) {

    // Update consumption and track allocations
    allocate(container);

    // Update future requirements
    decrementOutstanding(offSwitchRequest);
  }

  synchronized private void decrementOutstanding(
      ResourceRequest offSwitchRequest) {
    int numOffSwitchContainers = offSwitchRequest.getNumContainers() - 1;

    // Do not remove ANY
    offSwitchRequest.setNumContainers(numOffSwitchContainers);

    // Do we have any outstanding requests?
    // If there is nothing, we need to deactivate this application
    if (numOffSwitchContainers == 0) {
      checkForDeactivation();
    }
  }

  synchronized private void checkForDeactivation() {
    boolean deactivate = true;
    for (Priority priority : getPriorities()) {
      ResourceRequest request = getResourceRequest(priority, RMNodeImpl.ANY);
      if (request.getNumContainers() > 0) {
        deactivate = false;
        break;
      }
    }
    if (deactivate) {
      activeUsersManager.deactivateApplication(user, applicationId);
    }
  }

  synchronized private void allocate(Container container) {
    // Update consumption and track allocations
    //TODO: fixme sharad
    /* try {
        store.storeContainer(container);
      } catch (IOException ie) {
        // TODO fix this. we shouldnt ignore
      }*/

    LOG.debug("allocate: applicationId=" + applicationId + " container="
        + container.getId() + " host="
        + container.getNodeId().toString());
  }

  synchronized public void stop(RMAppAttemptState rmAppAttemptFinalState) {
    // clear pending resources metrics for the application
    QueueMetrics metrics = queue.getMetrics();
    for (Map<String, ResourceRequest> asks : requests.values()) {
      ResourceRequest request = asks.get(RMNode.ANY);
      if (request != null) {
        metrics.decrPendingResources(user, request.getNumContainers(),
            Resources.multiply(request.getCapability(), request
                .getNumContainers()));
      }
    }
    metrics.finishApp(this, rmAppAttemptFinalState);

    // Clear requests themselves
    clearRequests();
  }

  public synchronized void setQueue(Queue queue) {
    this.queue = queue;
  }
}


text:
Bleed is a Ruby gem which tracks the coupling of your objects during testing.

It aims to provide helpful feedback for refactoring.

This is not ready for production, still in the initial phases.

Many thanks to [Jeff Berg](http://github.com/TheJeff) and [Planning Center](http://get.planningcenteronline.com) for providing free time to work on this.

## Installation

Add this line to your application's Gemfile:

    # do not use outside of the test environment
    gem 'bleed', :group => :test

And then execute:

    $ bundle

## Usage

In your spec_helper.rb

    # near the top
    require 'bleed'

    RSpec.configure do |config|
      config.before(:suite) do
        # activate for the objects you want to observe
        Bleed.activate(Deck,Card,User)
      end

      config.after(:suite) do
        # choose one or both
        Bleed.coupling_report!
        Bleed.calling_report!
      end
    end

Calling report will look like:

    Deck->foo called Card->bar 27 times
    Deck->bazz called Card->bazz,Card->bar 15 times
    ...

Coupling report will look like:

    Deck calls Card 350 times
    Card calls User 700 times
    ...

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
<?php

namespace Tests\Observers;

use Illuminate\Foundation\Testing\DatabaseTransactions;

class OpeninghoursObserverTest extends \BrowserKitTestCase
{
    use DatabaseTransactions;

    /**
     * @test
     * @group observers
     */
    public function testItTriggersMakeSyncJobsForExternalServicesWhenOpeninghoursAreSaved()
    {
        $this->app->singleton('VestaService', function () {
            $mock = $this->createMock(\App\Services\VestaService::class, ['makeSyncJobsForExternalServices']);
            $mock->expects($this->once())
                ->method('makeSyncJobsForExternalServices');

            return $mock;
        });

        $openinghours = \App\Models\Openinghours::first();
        $openinghours->label = 'testLabel';
        $openinghours->save();
    }

    /**
     * @test
     * @group observers
     */
    public function testItTriggersMakeSyncJobsForExternalServicesWhenOpeninghoursAreDeleted()
    {
        $this->app->singleton('VestaService', function () {
            $mock = $this->createMock(\App\Services\VestaService::class, ['makeSyncJobsForExternalServices']);
            $mock->expects($this->once())
                ->method('makeSyncJobsForExternalServices');

            return $mock;
        });

        $openinghours = \App\Models\Openinghours::first();
        $openinghours->delete();
    }
}


text:
require 'aruba/cucumber'

module ArubaExt
  def run(cmd)
    super(cmd =~ /^rspec/ ? "bin/#{cmd}" : cmd)
  end
end

World(ArubaExt)

Before do
  @aruba_timeout_seconds = 30
end

unless File.directory?('./tmp/example_app')
  system "rake generate:app generate:stuff"
end

def aruba_path(file_or_dir)
  File.expand_path("../../../#{file_or_dir.sub('example_app','aruba')}", __FILE__)
end

def example_app_path(file_or_dir)
  File.expand_path("../../../#{file_or_dir}", __FILE__)
end

def write_symlink(file_or_dir)
  source = example_app_path(file_or_dir)
  target = aruba_path(file_or_dir)
  system "ln -s #{source} #{target}"
end

def copy(file_or_dir)
  source = example_app_path(file_or_dir)
  target = aruba_path(file_or_dir)
  system "cp -r #{source} #{target}"
end

Before do
  steps %Q{
    Given a directory named "spec"
  }

  Dir['tmp/example_app/*'].each do |file_or_dir|
    if !(file_or_dir =~ /spec$/)
      write_symlink(file_or_dir)
    end
  end

  ["spec/spec_helper.rb", "spec/rails_helper.rb"].each do |file_or_dir|
    write_symlink("tmp/example_app/#{file_or_dir}")
  end
end


text:
<?php

namespace Chadicus\Marvel\Api;

use DominionEnterprises\Util;

/**
 * Class for iterating index response to the Marvel API. Collections are readonly.
 */
class Collection implements \Iterator, \Countable
{
    /**
     * API Client.
     *
     * @var Client
     */
    private $client;

    /**
     * Limit to give to API.
     *
     * @var integer
     */
    private $limit;

    /**
     * Offset to give to API.
     *
     * @var integer
     */
    private $offset;

    /**
     * Resource name for collection.
     *
     * @var string
     */
    private $resource;

    /**
     * Array of filters to pass to API.
     *
     * @var array
     */
    private $filters;

    /**
     * Total number of elements in the collection.
     *
     * @var integer
     */
    private $total;

    /**
     * Pointer in the paginated results.
     *
     * @var integer
     */
    private $position;

    /**
     * A paginated set of elements from the API.
     *
     * @var null|array
     */
    private $results;

    /**
     * A custom callable to return a defined type when iterating over the collection.
     *
     * @var callable
     */
    private $loader;

    /**
     * Create a new collection.
     *
     * @param Client   $client   A client connection to the API.
     * @param string   $resource The name of API resource to request.
     * @param array    $filters  A key value pair array of search filters.
     * @param callable $loader   A custom callable to use when iterating over the collection.
     */
    final public function __construct(Client $client, string $resource, array $filters = [], callable $loader = null)
    {
        $this->client = $client;
        $this->resource = $resource;
        $this->filters = $filters;
        $this->loader = $loader ?: function ($input) {
            return $input;
        };
        $this->rewind();
    }

    /**
     * Return the count elements in this collection, @see Countable::count().
     *
     * @return integer
     */
    final public function count()
    {
        if ($this->position === -1) {
            $this->next();
        }

        return $this->total;
    }

    /**
     * Rewind the Iterator to the first element, @see Iterator::rewind().
     *
     * @return void
     */
    final public function rewind()
    {
        $this->results = null;
        $this->offset = 0;
        $this->total = 0;
        $this->limit = 0;
        $this->position = -1;
    }

    /**
     * Return the key of the current element, @see Iterator::key().
     *
     * @return integer
     */
    final public function key()
    {
        if ($this->position === -1) {
            $this->next();
        }

        Util::ensure(false, empty($this->results), '\OutOfBoundsException', ['Collection contains no elements']);
        return $this->offset + $this->position;
    }

    /**
     * Checks if current position is valid, @see Iterator::valid().
     *
     * @return boolean
     */
    final public function valid()
    {
        if ($this->position === -1) {
            $this->next();
        }

        return $this->offset + $this->position < $this->total;
    }

    /**
     * Move forward to next element, @see Iterator::next().
     *
     * @return void
     */
    final public function next()
    {
        ++$this->position;

        if ($this->position < $this->limit) {
            return;
        }

        $this->offset += $this->limit;
        $this->filters['offset'] = $this->offset;
        $this->filters['limit'] = $this->limit === 0 ? 20 : $this->limit;
        $dataWrapper = $this->client->search($this->resource, $this->filters);

        //Limit should be the total number returned, not the specified limit in the query params
        $this->limit = $dataWrapper->getData()->getCount();
        $this->total = $dataWrapper->getData()->getTotal();
        $this->results = $dataWrapper->getData()->getResults();
        $this->position = 0;
    }

    /**
     * Return the current element, @see Iterator::current().
     *
     * @return mixed Returns the element in the results array or a custom type defined by $loader.
     */
    final public function current()
    {
        if ($this->position === -1) {
            $this->next();
        }

        Util::ensure(
            true,
            array_key_exists($this->position, $this->results),
            '\OutOfBoundsException',
            ['Collection contains no element at current position']
        );

        return call_user_func_array($this->loader, [$this->results[$this->position]]);
    }
}


text:
<?php

namespace app\models;

/**
 * This is the ActiveQuery class for [[ImagesProperty]].
 *
 * @see ImagesProperty
 */
class ImagesPropertyQuery extends \yii\db\ActiveQuery
{
    /*public function active()
    {
        return $this->andWhere('[[status]]=1');
    }*/

    /**
     * @inheritdoc
     * @return ImagesProperty[]|array
     */
    public function all($db = null)
    {
        return parent::all($db);
    }

    /**
     * @inheritdoc
     * @return ImagesProperty|array|null
     */
    public function one($db = null)
    {
        return parent::one($db);
    }
}


text:
@interface NSColor (CSS)

- (NSString *)cssColor;

@end


text:
package org.apache.beam.runners.dataflow.worker;

import static org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Preconditions.checkArgument;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import org.apache.beam.runners.dataflow.options.DataflowWorkerHarnessOptions;
import org.apache.beam.sdk.fn.JvmInitializers;
import org.apache.beam.sdk.io.FileSystems;
import org.apache.beam.sdk.util.BackOff;
import org.apache.beam.sdk.util.BackOffUtils;
import org.apache.beam.sdk.util.FluentBackoff;
import org.apache.beam.sdk.util.Sleeper;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.annotations.VisibleForTesting;
import org.joda.time.Duration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * This is the batch harness for executing Dataflow jobs where the worker and user/Java SDK code are
 * running together in the same process.
 */
public class DataflowBatchWorkerHarness {
  private static final Logger LOG = LoggerFactory.getLogger(DataflowBatchWorkerHarness.class);
  private final DataflowWorkerHarnessOptions pipelineOptions;

  private DataflowBatchWorkerHarness(DataflowWorkerHarnessOptions pipelineOptions) {
    this.pipelineOptions = pipelineOptions;
    checkArgument(
        !pipelineOptions.isStreaming(),
        "%s instantiated with pipeline options indicating a streaming job",
        getClass().getSimpleName());
  }

  /** Creates the worker harness and then runs it. */
  public static void main(String[] args) throws Exception {
    // Call user-defined initialization immediately upon starting, as is guaranteed in
    // JvmInitializer
    JvmInitializers.runOnStartup();
    DataflowWorkerHarnessHelper.initializeLogging(DataflowBatchWorkerHarness.class);
    DataflowWorkerHarnessOptions pipelineOptions =
        DataflowWorkerHarnessHelper.initializeGlobalStateAndPipelineOptions(
            DataflowBatchWorkerHarness.class);
    DataflowBatchWorkerHarness batchHarness = new DataflowBatchWorkerHarness(pipelineOptions);
    DataflowWorkerHarnessHelper.configureLogging(pipelineOptions);
    JvmInitializers.runBeforeProcessing(pipelineOptions);
    batchHarness.run();
  }

  public static DataflowBatchWorkerHarness from(DataflowWorkerHarnessOptions pipelineOptions) {
    return new DataflowBatchWorkerHarness(pipelineOptions);
  }

  /** Initializes the worker and starts the actual read loop (in {@link #processWork}). */
  public void run() throws InterruptedException {
    // Configure standard file systems.
    FileSystems.setDefaultPipelineOptions(pipelineOptions);

    DataflowWorkUnitClient client = new DataflowWorkUnitClient(pipelineOptions, LOG);
    BatchDataflowWorker worker =
        BatchDataflowWorker.forBatchIntrinsicWorkerHarness(client, pipelineOptions);

    worker.startStatusServer();
    processWork(pipelineOptions, worker, Sleeper.DEFAULT);
  }

  // ExponentialBackOff parameters for the task retry strategy.
  private static final long BACKOFF_INITIAL_INTERVAL_MILLIS = 5000; // 5 second
  @VisibleForTesting static final long BACKOFF_MAX_INTERVAL_MILLIS = 5 * 60 * 1000; // 5 min.

  /** Helper for initializing the BackOff used for retries. */
  private static BackOff createBackOff() {
    return FluentBackoff.DEFAULT
        .withInitialBackoff(Duration.millis(BACKOFF_INITIAL_INTERVAL_MILLIS))
        .withMaxBackoff(Duration.millis(BACKOFF_MAX_INTERVAL_MILLIS))
        .backoff();
  }

  private static int chooseNumberOfThreads(DataflowWorkerHarnessOptions pipelineOptions) {
    if (pipelineOptions.getNumberOfWorkerHarnessThreads() != 0) {
      return pipelineOptions.getNumberOfWorkerHarnessThreads();
    }
    return Math.max(Runtime.getRuntime().availableProcessors(), 1);
  }

  /** A thread that repeatedly fetches and processes work units from the Dataflow service. */
  private static class WorkerThread implements Callable<Boolean> {
    // sleeper is used to sleep the appropriate amount of time
    WorkerThread(final BatchDataflowWorker worker, final Sleeper sleeper) {
      this.worker = worker;
      this.sleeper = sleeper;
      this.backOff = createBackOff();
    }

    @Override
    public Boolean call() {
      boolean success = true;
      try {
        do { // We loop getting and processing work.
          success = doWork();
          if (success) {
            backOff.reset();
          }
          // Sleeping a while if there is a problem with the work, then go on with the next work.
        } while (success || BackOffUtils.next(sleeper, backOff));
      } catch (IOException e) { // Failure of BackOff.
        LOG.error("Already tried several attempts at working on tasks. Aborting.", e);
      } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        LOG.error("Interrupted during thread execution or sleep.", e);
      } catch (Throwable t) {
        LOG.error("Thread {} died.", Thread.currentThread().getId(), t);
      }
      return false;
    }

    private boolean doWork() {
      try {
        LOG.debug("Thread starting getAndPerformWork.");
        boolean success = worker.getAndPerformWork();
        LOG.debug("{} processing one WorkItem.", success ? "Finished" : "Failed");
        return success;
      } catch (IOException e) { // If there is a problem getting work.
        LOG.info("There was a problem getting work.", e);
        return false;
      } catch (Exception e) { // These exceptions are caused by bugs within the SDK
        LOG.error("There was an unhandled error caused by the Dataflow SDK.", e);
        return false;
      }
    }

    private final BatchDataflowWorker worker;
    private final Sleeper sleeper;
    private final BackOff backOff;
  }

  @VisibleForTesting
  static void processWork(
      DataflowWorkerHarnessOptions pipelineOptions,
      final BatchDataflowWorker worker,
      Sleeper sleeper)
      throws InterruptedException {
    int numThreads = chooseNumberOfThreads(pipelineOptions);
    ExecutorService executor = pipelineOptions.getExecutorService();
    final List<Callable<Boolean>> tasks = new ArrayList<>();

    LOG.debug("Starting {} worker threads", numThreads);
    // We start the appropriate number of threads.
    for (int i = 0; i < numThreads; ++i) {
      tasks.add(new WorkerThread(worker, sleeper));
    }

    LOG.debug("Waiting for {} worker threads", numThreads);
    // We wait forever unless there is a big problem.
    executor.invokeAll(tasks);
    LOG.error("All threads died.");
  }
}


text:
<?php

// bootstrap emergence
require('bootstrap.inc.php');
Site::$debug = true;
Site::initialize($_SERVER['SITE_ROOT'], explode(':', $_SERVER['HTTP_HOST'])[0]);


text:
from os import path
from setuptools import setup, find_packages

this_directory = path.abspath(path.dirname(__file__))
with open(path.join(this_directory, "README.md"), encoding="utf-8") as f:
    long_description = f.read()

setup(name="hwt",
      version="3.7",
      description="hdl synthesis toolkit",
      long_description=long_description,
      long_description_content_type="text/markdown",
      url="https://github.com/Nic30/hwt",
      author="Michal Orsak",
      author_email="michal.o.socials@gmail.com",
      classifiers=[
        "Development Status :: 4 - Beta",
        "Intended Audience :: Developers",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
        "Programming Language :: Python :: 3 :: Only",
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 3.6",
        "Programming Language :: Python :: 3.7",
        "Programming Language :: Python :: 3.8",
        "Programming Language :: Python :: 3.9",
        "Topic :: Scientific/Engineering :: Electronic Design Automation (EDA)",
        "Topic :: System :: Hardware",
        "Topic :: System :: Emulators",
        "Topic :: Utilities"],
      install_requires=[
          "hdlConvertorAst>=0.6",  # conversions to SystemVerilog, VHDL
          "ipCorePackager>=0.5",  # generator of IPcore packages (IP-xact, ...)
          "hwtSimApi>=1.0",  # simulator API
          "pyDigitalWaveTools>=1.0",  # simulator output dump
      ],
      license="MIT",
      packages=find_packages(),
      zip_safe=True
)


text:
import type {Vocabulary} from "../types"

export const metadataVocabulary: Vocabulary = [
  "title",
  "description",
  "default",
  "deprecated",
  "readOnly",
  "writeOnly",
  "examples",
]

export const contentVocabulary: Vocabulary = [
  "contentMediaType",
  "contentEncoding",
  "contentSchema",
]