text:
package library.com.github.programmerr47.discogs.parsers;

import java.io.InputStream;
import java.util.List;

/**
 * Basic interface for all parsers from some response from DiscoGS to {@code ParserResult} that
 * specified by some realisation. Assumed that discogs api can be changed like earlier, when
 * it abandon XML response format in favor of JSON.
 * <p/>
 * So if it is needed to provide some new parsers (there are new objects or new response format)
 * all parsers must implement this interface.
 *
 * @author Michael Spitsin
 * @since 2014-09-18
 */
public interface ParserFrom<ParseResult> {

    /**
     * Gets object from {@link String} that represented response.
     *
     * @param objectStr response string
     * @return object if it can be even partially created (when part of objectStr is valid and part is invalid) of null, if not
     */
    ParseResult parseObjectFrom(String objectStr);

    /**
     * Gets object from {@link InputStream} that represented response.
     *
     * @param objectIS response input stream
     * @return object if it can be even partially created (when part of objectIS is valid and part is invalid) of null, if not
     */
    ParseResult parseObjectFrom(InputStream objectIS);

    /**
     * Gets {@link List} of objects from {@link String} that represented response with array of result objects.
     *
     * @param arrayStr response string
     * @return list of objects if it can be even partially created (when part of arrayStr is valid and part is invalid) of null, if not
     */
    List<ParseResult> parseListFrom(String arrayStr);

    /**
     * Gets {@link List} of objects from {@link InputStream} that represented response with array of result objects.
     *
     * @param arrayIS input stream
     * @return list of objects if it can be even partially created (when part of arrayIS is valid and part is invalid) of null, if not
     */
    List<ParseResult> parseListFrom(InputStream arrayIS);
}


text:
namespace Task01.ImplementPriorityQueue
{
    using System;

    public class MyBinaryHeap<T> where T : IComparable<T>
    {
        private const int InitialSize = 16;

        private T[] data;
        private int index;
        private bool isMinComparison;

        public MyBinaryHeap(bool compare)
        {
            this.data = new T[InitialSize];
            this.isMinComparison = compare;
            this.index = 0;
        }

        public int Size
        {
            get
            {
                return this.index;
            }
        }

        public T First
        {
            get
            {
                if (this.data[0] == null)
                {
                    throw new ArgumentNullException("There are no elements in the BinaryHeap");
                }

                return this.data[0];
            }
        }

        public void Add(T element)
        {
            if (this.index == this.data.Length)
            {
                this.Resize();
            }

            this.data[this.index] = element;

            this.ArrangeElementsOnAdd(this.index);

            this.index++;
        }

        public void RemoveFirst()
        {
            var swapper = this.data[0];
            this.data[0] = this.data[this.index - 1];
            this.data[this.index - 1] = swapper;

            this.index--;

            this.ArrangeElementsOnDelete(0);
        }

        private void ArrangeElementsOnDelete(int index)
        {
            var left = (index * 2) + 1;
            var right = left + 1;

            if (left < this.index)
            {
                var comparison = this.data[index].CompareTo(this.data[left]);

                if (this.isMinComparison ? comparison > 0 : comparison < 0)
                {
                    var swapper = this.data[index];
                    this.data[index] = this.data[left];
                    this.data[left] = swapper;

                    this.ArrangeElementsOnDelete(left);
                }
                else if (right < this.index)
                {
                    comparison = this.data[index].CompareTo(this.data[right]);
                    if (this.isMinComparison ? comparison > 0 : comparison < 0)
                    {
                        var swapper = this.data[index];
                        this.data[index] = this.data[right];
                        this.data[right] = swapper;

                        this.ArrangeElementsOnDelete(right);
                    }
                }
            }
        }

        private void ArrangeElementsOnAdd(int index)
        {
            var parentElement = (index - 1) / 2;

            var comparison = this.data[index].CompareTo(this.data[parentElement]);

            if (this.isMinComparison ? comparison < 0 : comparison > 0)
            {
                var swapper = this.data[index];
                this.data[index] = this.data[parentElement];
                this.data[parentElement] = swapper;

                this.ArrangeElementsOnAdd(parentElement);
            }
        }

        private void Resize()
        {
            var newData = new T[this.data.Length * 2];
            Array.Copy(this.data, newData, this.data.Length);
            this.data = newData;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.yidu.novel.entity.base;

import java.io.Serializable;

/**
 * This is an object that contains data related to the t_chapter table.
 * Do not modify this class because it will be overwritten if the configuration file
 * related to this class is modified.
 *
 * @hibernate.class
 *  table="t_chapter"
 */

public abstract class BaseTChapter  implements Serializable {

	public static String REF = "TChapter";
	public static String PROP_ARTICLENO = "articleno";
	public static String PROP_PUBLISHTIME = "publishtime";
	public static String PROP_MODIFYUSERNO = "modifyuserno";
	public static String PROP_CHAPTERNAME = "chaptername";
	public static String PROP_DELETEFLAG = "deleteflag";
	public static String PROP_ISVIP = "isvip";
	public static String PROP_CHAPTERNO = "chapterno";
	public static String PROP_CHAPTERTYPE = "chaptertype";
	public static String PROP_MODIFYTIME = "modifytime";
	public static String PROP_POSTDATE = "postdate";
	public static String PROP_SIZE = "size";
	public static String PROP_ARTICLENAME = "articlename";
	public static String PROP_FEE = "fee";

	// constructors
	public BaseTChapter () {
		initialize();
	}

	/**
	 * Constructor for primary key
	 */
	public BaseTChapter (int chapterno) {
		this.setChapterno(chapterno);
		initialize();
	}

	protected void initialize () {}

	private int hashCode = Integer.MIN_VALUE;

	// primary key
	private int chapterno;

	// fields
	private java.lang.Integer articleno;
	private java.lang.String articlename;
	private java.lang.Short chaptertype;
	private java.lang.String chaptername;
	private java.lang.Integer size;
	private java.lang.Boolean isvip;
	private java.util.Date postdate;
	private java.lang.Boolean deleteflag;
	private java.util.Date publishtime;
	private java.lang.Integer modifyuserno;
	private java.util.Date modifytime;
  private  java.lang.Integer fee;

	/**
	 * Return the unique identifier of this class
     * @hibernate.id
     *  generator-class="sequence"
     *  column="chapterno"
     */
	public int getChapterno () {
		return chapterno;
	}

	/**
	 * Set the unique identifier of this class
	 * @param chapterno the new ID
	 */
	public void setChapterno (int chapterno) {
		this.chapterno = chapterno;
		this.hashCode = Integer.MIN_VALUE;
	}

	/**
	 * Return the value associated with the column: articleno
	 */
	public java.lang.Integer getArticleno () {
		return articleno;
	}

	/**
	 * Set the value related to the column: articleno
	 * @param articleno the articleno value
	 */
	public void setArticleno (java.lang.Integer articleno) {
		this.articleno = articleno;
	}

	/**
	 * Return the value associated with the column: articlename
	 */
	public java.lang.String getArticlename () {
		return articlename;
	}

	/**
	 * Set the value related to the column: articlename
	 * @param articlename the articlename value
	 */
	public void setArticlename (java.lang.String articlename) {
		this.articlename = articlename;
	}

	/**
	 * Return the value associated with the column: chaptertype
	 */
	public java.lang.Short getChaptertype () {
		return chaptertype;
	}

	/**
	 * Set the value related to the column: chaptertype
	 * @param chaptertype the chaptertype value
	 */
	public void setChaptertype (java.lang.Short chaptertype) {
		this.chaptertype = chaptertype;
	}

	/**
	 * Return the value associated with the column: chaptername
	 */
	public java.lang.String getChaptername () {
		return chaptername;
	}

	/**
	 * Set the value related to the column: chaptername
	 * @param chaptername the chaptername value
	 */
	public void setChaptername (java.lang.String chaptername) {
		this.chaptername = chaptername;
	}

	/**
	 * Return the value associated with the column: size
	 */
	public java.lang.Integer getSize () {
		return size;
	}

	/**
	 * Set the value related to the column: size
	 * @param size the size value
	 */
	public void setSize (java.lang.Integer size) {
		this.size = size;
	}

	/**
	 * Return the value associated with the column: isvip
	 */
	public java.lang.Boolean isIsvip () {
		return isvip;
	}

	/**
	 * Set the value related to the column: isvip
	 * @param isvip the isvip value
	 */
	public void setIsvip (java.lang.Boolean isvip) {
		this.isvip = isvip;
	}

	/**
	 * Return the value associated with the column: postdate
	 */
	public java.util.Date getPostdate () {
		return postdate;
	}

	/**
	 * Set the value related to the column: postdate
	 * @param postdate the postdate value
	 */
	public void setPostdate (java.util.Date postdate) {
		this.postdate = postdate;
	}

	/**
	 * Return the value associated with the column: deleteflag
	 */
	public java.lang.Boolean isDeleteflag () {
		return deleteflag;
	}

	/**
	 * Set the value related to the column: deleteflag
	 * @param deleteflag the deleteflag value
	 */
	public void setDeleteflag (java.lang.Boolean deleteflag) {
		this.deleteflag = deleteflag;
	}

	/**
	 * Return the value associated with the column: publishtime
	 */
	public java.util.Date getPublishtime () {
		return publishtime;
	}

	/**
	 * Set the value related to the column: publishtime
	 * @param publishtime the publishtime value
	 */
	public void setPublishtime (java.util.Date publishtime) {
		this.publishtime = publishtime;
	}

	/**
	 * Return the value associated with the column: modifyuserno
	 */
	public java.lang.Integer getModifyuserno () {
		return modifyuserno;
	}

	/**
	 * Set the value related to the column: modifyuserno
	 * @param modifyuserno the modifyuserno value
	 */
	public void setModifyuserno (java.lang.Integer modifyuserno) {
		this.modifyuserno = modifyuserno;
	}

	/**
	 * Return the value associated with the column: modifytime
	 */
	public java.util.Date getModifytime () {
		return modifytime;
	}

	/**
	 * Set the value related to the column: modifytime
	 * @param modifytime the modifytime value
	 */
	public void setModifytime (java.util.Date modifytime) {
		this.modifytime = modifytime;
	}

	public boolean equals (Object obj) {
		if (null == obj) return false;
		if (!(obj instanceof org.yidu.novel.entity.TChapter)) return false;
		else {
			org.yidu.novel.entity.TChapter tChapter = (org.yidu.novel.entity.TChapter) obj;
			return (this.getChapterno() == tChapter.getChapterno());
		}
	}

	public int hashCode () {
		if (Integer.MIN_VALUE == this.hashCode) {
			return (int) this.getChapterno();
		}
		return this.hashCode;
	}

	public String toString () {
		return super.toString();
	}

	public java.lang.Integer getFee() {
		return fee;
	}

	public void setFee(java.lang.Integer fee) {
		this.fee = fee;
	}

}


text:
### [1295\. Find Numbers with Even Number of Digits](https://leetcode.com/problems/find-numbers-with-even-number-of-digits/)

Difficulty: **Easy**

Given an array `nums` of integers, return how many of them contain an **even number** of digits.

**Example 1:**

```
Input: nums = [12,345,2,6,7896]
Output: 2
Explanation:
12 contains 2 digits (even number of digits).
345 contains 3 digits (odd number of digits).
2 contains 1 digit (odd number of digits).
6 contains 1 digit (odd number of digits).
7896 contains 4 digits (even number of digits).
Therefore only 12 and 7896 contain an even number of digits.
```

**Example 2:**

```
Input: nums = [555,901,482,1771]
Output: 1
Explanation:
Only 1771 contains an even number of digits.
```

**Constraints:**

*   `1 <= nums.length <= 500`
*   `1 <= nums[i] <= 10^5`

#### Solution

Language: **JavaScript**

```javascript
/**
 * @param {number[]} nums
 * @return {number}
 */
var findNumbers = function(nums) {
    return nums.reduce(
        (count, num) => count += ((num + '').length % 2 === 0 ? 1 : 0),
        0
    )
};
```


text:
/** @babel */

import os from "os";
import path from "path";
import semver from "semver";
import {BufferedProcess} from "atom";

/*
A collection of methods for retrieving information about the user's system for
bug report purposes.
*/

const DEV_PACKAGE_PATH = path.join("dev", "packages");

export default {

	// OS version strings lifted from https://github.com/lee-dohm/bug-report
	async getOSVersion() {
		let info;
		try {
			switch (os.platform()) {
				case "darwin":
					info = await this.macVersionText();
					break;
				case "win32":
					info = await this.winVersionText();
					break;
				case "linux":
					info = await this.linuxVersionText();
					break;
				default:
					// do nothing
			}
		} catch (ex) {
			// fail silently
		}
		if (info) {
			return info;
		}
		return `${os.platform()} ${os.release()}`;
	},

	async macVersionText() {
		const info = await this.macVersionInfo();
		if (!info || !info.ProductName || !info.ProductVersion) {
			return;
		}
		return `${info.ProductName} ${info.ProductVersion}`;
	},

	macVersionInfo() {
		return new Promise(resolve => {
			let stdout = "";
			const plistBuddy = new BufferedProcess({
				command: "/usr/libexec/PlistBuddy",
				args: [
					"-c",
					"Print ProductVersion",
					"-c",
					"Print ProductName",
					"/System/Library/CoreServices/SystemVersion.plist",
				],
				stdout(output) {
					stdout += output;
				},
				exit() {
					const [ProductVersion, ProductName] = stdout.trim().split("\n");
					resolve({ProductVersion, ProductName});
				},
			});

			plistBuddy.onWillThrowError(function ({handle}) {
				handle();
				resolve();
			});
		});
	},

	async linuxVersionText() {
		const info = await this.linuxVersionInfo();
		if (!info || !info.DistroName || !info.DistroVersion) {
			return;
		}
		return `${info.DistroName} ${info.DistroVersion}`;
	},

	linuxVersionInfo() {
		return new Promise(resolve => {
			let stdout = "";

			const lsbRelease = new BufferedProcess({
				command: "lsb_release",
				args: ["-ds"],
				stdout(output) {
					stdout += output;
				},
				exit() {
					const [DistroName, DistroVersion] = stdout.trim().split(" ");
					resolve({DistroName, DistroVersion});
				},
			});

			lsbRelease.onWillThrowError(function ({handle}) {
				handle();
				resolve({});
			});
		});
	},

	winVersionText() {
		return new Promise(resolve => {
			const data = [];
			const systemInfo = new BufferedProcess({
				command: "systeminfo",
				stdout(oneLine) {
					data.push(oneLine);
				},
				exit() {
					const info = data.join("\n");
					const version = /OS.+(Microsoft.+)$/im.exec(info);
					let undef;
					resolve(version ? version[1] : undef);
				},
			});

			systemInfo.onWillThrowError(function ({handle}) {
				handle();
				resolve();
			});
		});
	},

	/*
  Section: Installed Packages
  */

	async getNonCorePackages() {
		const nonCorePackages = atom.packages.getAvailablePackageMetadata().filter(p => !atom.packages.isBundledPackage(p.name));
		const devPackageNames = atom.packages.getAvailablePackagePaths().filter(p => p.includes(DEV_PACKAGE_PATH)).map(p => path.basename(p));
		return nonCorePackages.map((pack) => `${pack.name} ${pack.version} ${devPackageNames.includes(pack.name) ? "(dev)" : ""}`);
	},

	async getLatestAtomData() {
		const githubHeaders = new Headers({
			accept: "application/vnd.github.v3+json",
			contentType: "application/json",
		});
		const response = await fetch("https://atom.io/api/updates", {headers: githubHeaders});

		if (!response.ok) {
			throw response.statusCode;
		}

		const data = await response.json();
		return data;
	},

	async checkAtomUpToDate() {
		const latestAtomData = await this.getLatestAtomData();
		const version = atom.getVersion();
		const installedVersion = version.replace(/-.*$/, "");
		const latestVersion = latestAtomData.name;
		const upToDate = installedVersion && semver.gte(installedVersion, latestVersion);
		return {upToDate, latestVersion, installedVersion};
	},

	getPackageVersion(packageName) {
		const pack = atom.packages.getLoadedPackage(packageName);
		return pack && pack.metadata.version;
	},

	getPackageVersionShippedWithAtom(packageName) {
		return require(path.join(atom.getLoadSettings().resourcePath, "package.json")).packageDependencies[packageName];
	},

	async getLatestPackageData(packageName) {
		const githubHeaders = new Headers({
			accept: "application/vnd.github.v3+json",
			contentType: "application/json",
		});
		const response = await fetch(`https://atom.io/api/packages/${packageName}`, {headers: githubHeaders});

		if (!response.ok) {
			throw response.statusCode;
		}

		const data = await response.json();
		return data;
	},

	async checkPackageUpToDate(packageName) {
		const latestPackageData = await this.getLatestPackageData(packageName);
		const installedVersion = this.getPackageVersion(packageName);
		let upToDate = installedVersion && semver.gte(installedVersion, latestPackageData.releases.latest);
		const latestVersion = latestPackageData.releases.latest;
		const versionShippedWithAtom = this.getPackageVersionShippedWithAtom(packageName);

		const isCore = versionShippedWithAtom;
		if (isCore) {
			// A core package is out of date if the version which is being used
			// is lower than the version which normally ships with the version
			// of Atom which is running. This will happen when there's a locally
			// installed version of the package with a lower version than Atom's.
			upToDate = installedVersion && semver.gte(installedVersion, versionShippedWithAtom);
		}

		return {isCore, upToDate, latestVersion, installedVersion, versionShippedWithAtom};
	},
};


text:
require 'rubygems'
require 'sinatra'
require 'sinatra/reloader'
require 'sinatra/activerecord'

set :database, "sqlite3:leprosorium.db"

class Post < ActiveRecord::Base
	 has_many :comments, dependent: :destroy
	 validates :content, presence: true, length: { minimum: 3 }

class Comment < ActiveRecord::Base
	 belongs_to :post
	 validates :content, presence: true
end

before do
	@posts = Post.order 'created_at desc'
end

get '/' do
	erb :index
end

get '/new' do
	@p = Post.new
	erb :new
end

post '/new' do
	@p = Post.new params[:post]
	if @p.save
		#erb "Пост опубликован!"
		redirect to "/post/#{@p.id}"
	else
		@error = @p.errors.full_messages.first
		erb :new
	end

end

get '/post/:post_id' do

	if @post = (Post.find params[:post_id])
		return erb :details
	else
		redirect to '/'
	end
end

post '/post/:post_id' do

	@post = Post.find params[:post_id]
	@c = @post.comments.create params[:comment]

	if @c.save
		#erb "Пост опубликован!"
		redirect to "/post/#{@post.id}"
	else
		@error = @c.errors.full_messages.first
		erb :details
	end

end


text:
goog.provide('shaka.offline.indexeddb.V1StorageCell');

goog.require('goog.asserts');
goog.require('shaka.log');
goog.require('shaka.offline.indexeddb.DBConnection');
goog.require('shaka.util.Error');
goog.require('shaka.util.ManifestParserUtils');
goog.require('shaka.util.PublicPromise');

/**
 * The V1StorageCell is for all stores that follow the shaka.externs V2 offline
 * types. This storage cell will only work for version 1 indexed db database
 * schemes.
 *
 * @implements {shaka.extern.StorageCell}
 */
shaka.offline.indexeddb.V1StorageCell = class {
  /**
   * @param {IDBDatabase} connection
   * @param {string} segmentStore
   * @param {string} manifestStore
   */
  constructor(connection, segmentStore, manifestStore) {
    /** @private {!shaka.offline.indexeddb.DBConnection} */
    this.connection_ = new shaka.offline.indexeddb.DBConnection(connection);

    /** @private {string} */
    this.segmentStore_ = segmentStore;
    /** @private {string} */
    this.manifestStore_ = manifestStore;
  }

  /**
   * @override
   */
  destroy() { return this.connection_.destroy(); }

  /**
   * @override
   */
  hasFixedKeySpace() {
    // We do not allow adding new values to V1 databases.
    return true;
  }

  /**
   * @override
   */
  addSegments(segments) { return this.rejectAdd_(this.segmentStore_); }

  /**
   * @override
   */
  removeSegments(keys, onRemove) {
    return this.remove_(this.segmentStore_, keys, onRemove);
  }

  /**
   * @override
   */
  getSegments(keys) {
    const convertSegmentData =
        shaka.offline.indexeddb.V1StorageCell.convertSegmentData_;

    return this.get_(this.segmentStore_, keys).then((segments) => {
      return segments.map(convertSegmentData);
    });
  }

  /**
   * @override
   */
  addManifests(manifests) { return this.rejectAdd_(this.manifestStore_); }

  /**
   * @override
   */
  updateManifestExpiration(key, newExpiration) {
    let op = this.connection_.startReadWriteOperation(this.manifestStore_);
    let store = op.store();

    let p = new shaka.util.PublicPromise();

    store.get(key).onsuccess = (event) => {
      // Make sure a defined value was found. Indexeddb treats "no value found"
      // as a success with an undefined result.
      let manifest = event.target.result;

      // Indexeddb does not fail when you get a value that is not in the
      // database. It will return an undefined value. However, we expect
      // the value to never be null, so something is wrong if we get a
      // falsey value.
      if (manifest) {
        // Since this store's scheme uses in-line keys, we don't need to specify
        // the key with |put|.
        goog.asserts.assert(
            manifest.key == key,
            'With in-line keys, the keys should match');

        manifest.expiration = newExpiration;
        store.put(manifest);

        p.resolve();
      } else {
        p.reject(new shaka.util.Error(
            shaka.util.Error.Severity.CRITICAL,
            shaka.util.Error.Category.STORAGE,
            shaka.util.Error.Code.KEY_NOT_FOUND,
            'Could not find values for ' + key));
      }
    };

    // Only return our promise after the operation completes.
    return op.promise().then(() => p);
  }

  /**
   * @override
   */
  removeManifests(keys, onRemove) {
    return this.remove_(this.manifestStore_, keys, onRemove);
  }

  /**
   * @override
   */
  getManifests(keys) {
    const convertManifest =
        shaka.offline.indexeddb.V1StorageCell.convertManifest_;

    return this.get_(this.manifestStore_, keys).then((manifests) => {
      return manifests.map(convertManifest);
    });
  }

  /**
   * @override
   */
  getAllManifests() {
    const convertManifest =
        shaka.offline.indexeddb.V1StorageCell.convertManifest_;

    let op = this.connection_.startReadOnlyOperation(this.manifestStore_);
    let store = op.store();

    let values = {};

    store.openCursor().onsuccess = (event) => {
      // When we reach the end of the data that the cursor is iterating
      // over, |event.target.result| will be null to signal the end of the
      // iteration.
      // https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/continue
      let cursor = event.target.result;
      if (!cursor) {
        return;
      }

      values[cursor.key] = convertManifest(cursor.value);

      // Go to the next item in the store, which will cause |onsuccess| to be
      // called again.
      cursor.continue();
    };

    // Wait until the operation completes or else values may be missing from
    // |values|.
    return op.promise().then(() => values);
  }

  /**
   * @param {string} storeName
   * @return {!Promise}
   * @private
   */
  rejectAdd_(storeName) {
    return Promise.reject(new shaka.util.Error(
      shaka.util.Error.Severity.CRITICAL,
      shaka.util.Error.Category.STORAGE,
      shaka.util.Error.Code.NEW_KEY_OPERATION_NOT_SUPPORTED,
      'Cannot add new value to ' + storeName));
  }

  /**
   * @param {string} storeName
   * @param {!Array.<number>} keys
   * @param {function(number)} onRemove
   * @return {!Promise}
   * @private
   */
  remove_(storeName, keys, onRemove) {
    let op = this.connection_.startReadWriteOperation(storeName);
    let store = op.store();

    keys.forEach((key) => {
      store.delete(key).onsuccess = () => onRemove(key);
    });

    return op.promise();
  }

  /**
   * @param {string} storeName
   * @param {!Array.<number>} keys
   * @return {!Promise.<!Array.<T>>}
   * @template T
   * @private
   */
  get_(storeName, keys) {
    let op = this.connection_.startReadOnlyOperation(storeName);
    let store = op.store();

    let values = {};
    let missing = [];

    // Use a map to store the objects so that we can reorder the results to
    // match the order of |keys|.
    keys.forEach((key) => {
      store.get(key).onsuccess = (event) => {
        let value = event.target.result;
        // Make sure a defined value was found. Indexeddb treats no-value found
        // as a success with an undefined result.
        if (value == undefined) {
          missing.push(key);
        }

        values[key] = value;
      };
    });

    // Wait until the operation completes or else values may be missing from
    // |values|. Use the original key list to convert the map to a list so that
    // the order will match.
    return op.promise().then(() => {
      if (missing.length) {
        return Promise.reject(new shaka.util.Error(
            shaka.util.Error.Severity.CRITICAL,
            shaka.util.Error.Category.STORAGE,
            shaka.util.Error.Code.KEY_NOT_FOUND,
            'Could not find values for ' + missing
        ));
      }

      return keys.map((key) => values[key]);
    });
  }

  /**
   * @param {!Object} old
   * @return {shaka.extern.ManifestDB}
   * @private
   */
  static convertManifest_(old) {
    // Old Manifest Format:
    // {
    //   key: number,
    //   originalManifestUri: string,
    //   duration: number,
    //   size: number,
    //   expiration: number,
    //   periods: !Array.<shakaExtern.PeriodDB>,
    //   sessionIds: !Array.<string>,
    //   drmInfo: ?shakaExtern.DrmInfo,
    //   appMetadata: Object
    //  }

    goog.asserts.assert(
        old.originalManifestUri != null,
        'Old manifest format should have an originalManifestUri field');
    goog.asserts.assert(
        old.duration != null,
        'Old manifest format should have a duration field');
    goog.asserts.assert(
        old.size != null,
        'Old manifest format should have a size field');
    goog.asserts.assert(
        old.periods != null,
        'Old manifest format should have a periods field');
    goog.asserts.assert(
        old.sessionIds != null,
        'Old manifest format should have a session ids field');
    goog.asserts.assert(
        old.appMetadata != null,
        'Old manifest format should have an app metadata field');

    const convertPeriod = shaka.offline.indexeddb.V1StorageCell.convertPeriod_;

    return {
      originalManifestUri: old.originalManifestUri,
      duration: old.duration,
      size: old.size,
      expiration: old.expiration == null ? Infinity : old.expiration,
      periods: old.periods.map(convertPeriod),
      sessionIds: old.sessionIds,
      drmInfo: old.drmInfo,
      appMetadata: old.appMetadata
    };
  }

  /**
   * @param {!Object} old
   * @return {shaka.extern.PeriodDB}
   * @private
   */
  static convertPeriod_(old) {
    // Old Period Format:
    // {
    //   startTime: number,
    //   streams: !Array.<shakaExtern.StreamDB>
    // }

    goog.asserts.assert(
      old.startTime != null,
      'Old period format should have a start time field');
    goog.asserts.assert(
      old.streams != null,
      'Old period format should have a streams field');

    const convertStream = shaka.offline.indexeddb.V1StorageCell.convertStream_;
    const fillMissingVariants =
        shaka.offline.indexeddb.V1StorageCell.fillMissingVariants_;

    // In the case that this is really old (like really old, like dinosaurs
    // roaming the Earth old) there may be no variants, so we need to add those.
    fillMissingVariants(old);

    old.streams.forEach((stream) => {
      const message = 'After filling in missing variants, ' +
                      'each stream should have variant ids';
      goog.asserts.assert(stream.variantIds, message);
    });

    return {
      startTime: old.startTime,
      streams: old.streams.map(convertStream)
    };
  }

  /**
   * @param {!Object} old
   * @return {shaka.extern.StreamDB}
   * @private
   */
  static convertStream_(old) {
    // Old Stream Format
    // {
    //   id: number,
    //   primary: boolean,
    //   presentationTimeOffset: number,
    //   contentType: string,
    //   mimeType: string,
    //   codecs: string,
    //   frameRate: (number|undefined),
    //   kind: (string|undefined),
    //   language: string,
    //   label: ?string,
    //   width: ?number,
    //   height: ?number,
    //   initSegmentUri: ?string,
    //   encrypted: boolean,
    //   keyId: ?string,
    //   segments: !Array.<shakaExtern.SegmentDB>,
    //   variantIds: ?Array.<number>
    // }

    goog.asserts.assert(
        old.id != null,
        'Old stream format should have an id field');
    goog.asserts.assert(
        old.primary != null,
        'Old stream format should have a primary field');
    goog.asserts.assert(
        old.presentationTimeOffset != null,
        'Old stream format should have a presentation time offset field');
    goog.asserts.assert(
        old.contentType != null,
        'Old stream format should have a content type field');
    goog.asserts.assert(
        old.mimeType != null,
        'Old stream format should have a mime type field');
    goog.asserts.assert(
        old.codecs != null,
        'Old stream format should have a codecs field');
    goog.asserts.assert(
        old.language != null,
        'Old stream format should have a language field');
    goog.asserts.assert(
        old.encrypted != null,
        'Old stream format should have an encrypted field');
    goog.asserts.assert(
        old.segments != null,
        'Old stream format should have a segments field');

    const getKeyFromUri =
        shaka.offline.indexeddb.V1StorageCell.getKeyFromSegmentUri_;
    const convertSegment =
        shaka.offline.indexeddb.V1StorageCell.convertSegment_;

    let initSegmentKey = old.initSegmentUri ?
                      getKeyFromUri(old.initSegmentUri) :
                      null;

    return {
      id: old.id,
      primary: old.primary,
      presentationTimeOffset: old.presentationTimeOffset,
      contentType: old.contentType,
      mimeType: old.mimeType,
      codecs: old.codecs,
      frameRate: old.frameRate,
      kind: old.kind,
      language: old.language,
      label: old.label,
      width: old.width,
      height: old.height,
      initSegmentKey: initSegmentKey,
      encrypted: old.encrypted,
      keyId: old.keyId,
      segments: old.segments.map(convertSegment),
      variantIds: old.variantIds
    };
  }

  /**
   * @param {!Object} old
   * @return {shaka.extern.SegmentDB}
   * @private
   */
  static convertSegment_(old) {
    // Old Segment Format
    // {
    //   startTime: number,
    //   endTime: number,
    //   uri: string
    // }

    goog.asserts.assert(
        old.startTime != null,
        'The old segment format should have a start time field');
    goog.asserts.assert(
        old.endTime != null,
        'The old segment format should have an end time field');
    goog.asserts.assert(
        old.uri != null,
        'The old segment format should have a uri field');

    const V1StorageCell = shaka.offline.indexeddb.V1StorageCell;
    const getKeyFromUri = V1StorageCell.getKeyFromSegmentUri_;

    // Since we don't want to use the uri anymore, we need to parse the key
    // from it.
    let dataKey = getKeyFromUri(old.uri);

    return {
      startTime: old.startTime,
      endTime: old.endTime,
      dataKey: dataKey
    };
  }

  /**
   * @param {!Object} old
   * @return {shaka.extern.SegmentDataDB}
   * @private
   */
  static convertSegmentData_(old) {
    // Old Segment Format:
    // {
    //   key: number,
    //   data: ArrayBuffer
    // }

    goog.asserts.assert(
        old.key != null,
        'The old segment data format should have a key field');
    goog.asserts.assert(
        old.data != null,
        'The old segment data format should have a data field');

    return {data: old.data};
  }

  /**
   * @param {string} uri
   * @return {number}
   * @private
   */
  static getKeyFromSegmentUri_(uri) {
    let parts = null;

    // Try parsing the uri as the original Shaka Player 2.0 uri.
    parts = /^offline:[0-9]+\/[0-9]+\/([0-9]+)$/.exec(uri);
    if (parts) {
      return Number(parts[1]);
    }

    // Just before Shaka Player 2.3 the uri format was changed to remove some
    // of the un-used information from the uri and make the segment uri and
    // manifest uri follow a similar format. However the old storage system
    // was still in place, so it is possible for Storage V1 Cells to have
    // Storage V2 uris.
    parts = /^offline:segment\/([0-9]+)$/.exec(uri);
    if (parts) {
      return Number(parts[1]);
    }

    throw new shaka.util.Error(
        shaka.util.Error.Severity.CRITICAL,
        shaka.util.Error.Category.STORAGE,
        shaka.util.Error.Code.MALFORMED_OFFLINE_URI,
        'Could not parse uri ' + uri);
  }

  /**
   * Take a period and check if the streams need to have variants generated.
   * Before Shaka Player moved to its variants model, there were no variants.
   * This will fill missing variants into the given object.
   *
   * @param {!Object} period
   * @private
   */
  static fillMissingVariants_(period) {
    const AUDIO = shaka.util.ManifestParserUtils.ContentType.AUDIO;
    const VIDEO = shaka.util.ManifestParserUtils.ContentType.VIDEO;

    // There are three cases:
    //  1. All streams' variant ids are null
    //  2. All streams' variant ids are non-null
    //  3. Some streams' variant ids are null and other are non-null
    // Case 3 is invalid and should never happen in production.

    let audio = period.streams.filter((s) => s.contentType == AUDIO);
    let video = period.streams.filter((s) => s.contentType == VIDEO);

    // Case 2 - There is nothing we need to do, so let's just get out of here.
    if (audio.every((s) => s.variantIds) && video.every((s) => s.variantIds)) {
      return;
    }

    // Case 3... We don't want to be in case three.
    goog.asserts.assert(
        audio.every((s) => !s.variantIds),
        'Some audio streams have variant ids and some do not.');
    goog.asserts.assert(
        video.every((s) => !s.variantIds),
        'Some video streams have variant ids and some do not.');

    // Case 1 - Populate all the variant ids (putting us back to case 2).
    // Since all the variant ids are null, we need to first make them into
    // valid arrays.
    audio.forEach((s) => { s.variantIds = []; });
    video.forEach((s) => { s.variantIds = []; });

    let nextId = 0;

    // It is not possible in Shaka Player's pre-variant world to have audio-only
    // and video-only content mixed in with audio-video content. So we can
    // assume that there is only audio-only or video-only if one group is empty.

    // Everything is video-only content - so each video stream gets to be its
    // own variant.
    if (video.length && !audio.length) {
      shaka.log.debug('Found video-only content. Creating variants for video.');
      let variantId = nextId++;
      video.forEach((s) => { s.variantIds.push(variantId); });
    }

    // Everything is audio-only content - so each audio stream gets to be its
    // own variant.
    if (!video.length && audio.length) {
      shaka.log.debug('Found audio-only content. Creating variants for audio.');
      let variantId = nextId++;
      audio.forEach((s) => { s.variantIds.push(variantId); });
    }

    // Everything is audio-video content.
    if (video.length && audio.length) {
      shaka.log.debug('Found audio-video content. Creating variants.');
      audio.forEach((a) => {
        video.forEach((v) => {
          let variantId = nextId++;
          a.variantIds.push(variantId);
          v.variantIds.push(variantId);
        });
      });
    }
  }
};


text:
Groep Aanmaken

Hier kunt u de details van een nieuwe Unix groep invoeren.
Kies de naam van de groep zorgvuldig omdat die niet meer kan worden gewijzigd
als de groep eenmaal is aangemaakt!


text:
from GenericMeasure import GenericMeasure
from GenericAvgMeasure import GenericAvgMeasure

import Units

class DeliveredMessages(GenericMeasure):
	def __init__(self, period, simulationTime, broadcastTable):
		GenericMeasure.__init__(self, r"DEBUG peer.ReliableBroadcast  - Peer [0-9]+ delivered message (\(.*?\)) ([0-9]+\,[0-9]+).*?", period, simulationTime, Units.MESSAGES)

		self.__broadcastTable = broadcastTable

	def parseInc(self, line):
		m = self.getProg().match(line)
		if m is not None:
			messageID = m.group(1)
			startTime = self.__broadcastTable[messageID]
			time  = float(m.group(2).replace(',','.'))
			return (startTime, time)

class ReliableBroadcastedMessages(GenericMeasure):
	def __init__(self, period, simulationTime):
		GenericMeasure.__init__(self, r"DEBUG peer.ReliableBroadcast  - Peer [0-9]+ reliable broadcasting message (\(.*?\)).*?([0-9]+\,[0-9]+).*?", period, simulationTime, Units.MESSAGES)

		self.__broadcastTable = {}

	def parseInc(self, line):
		m = self.getProg().match(line)
		if m is not None:
			messageID = m.group(1)
			time  = float(m.group(2).replace(',','.'))
			self.__broadcastTable[messageID] = time

	def getBroadcastTable(self):
		return self.__broadcastTable

class DeliveringTime(GenericAvgMeasure):
	"""The average time used to deliver a message"""

	def __init__(self, period, simulationTime):
		GenericAvgMeasure.__init__(self, period, simulationTime, Units.SECONDS)

		self.__broadcastedMessages = ReliableBroadcastedMessages(period, simulationTime)
		self.__deliveredMessages = DeliveredMessages(period, simulationTime, self.__broadcastedMessages.getBroadcastTable())

	def parseLine(self, line):
		self.__broadcastedMessages.parseInc(line)
		result = self.__deliveredMessages.parseInc(line)
		if result is not None:
			broadcastTime, deliveredTime = result
			elapsedTime = deliveredTime - broadcastTime
			self.periodicAvgValues.addValue(elapsedTime, broadcastTime)


text:
"""
Provides the various special functions as UFuncs
"""
from . import _ufuncs
_token = "sf_"
_tokl  = len(_token)

for _name in dir(_ufuncs):
    if _name[:_tokl] == _token:
        _shortname = _name[_tokl:]
        _cmd = "%s = _ufuncs.%s" % (_shortname, _name)
        #printy cmd
        exec(_cmd)
del _token
del _tokl
del _shortname
del _name
del _cmd


text:
package edu.utexas.cycic.presenter;

import org.mo.closure.v1.Closure;

import edu.utah.sci.cyclist.core.event.notification.EventBus;
import edu.utah.sci.cyclist.core.presenter.ViewPresenter;
import edu.utah.sci.cyclist.core.ui.View;

public class InstitutionCorralViewPresenter extends ViewPresenter {

	public InstitutionCorralViewPresenter(EventBus bus) {
		super(bus);
	}

	public void addNotificationHandlers(){

	}

    public View getView() {
        return (View) super.getView();
    }

    public void setView(View view) {
        super.setView(view);

            getView().setOnSelectAction(new Closure.V0() {
                @Override
                public void call() {
                    onViewSelected(getView());              }
            });
    }

    public void onViewSelected(View view) {
        super.onViewSelected(view);
    }
}


text:
package com.ibm.wuhan.bus.web.controller;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ibm.wuhan.bus.service.impl.BusLineBusinessService;

/**
 * Servlet implementation class ListBusLineInfoServlet
 */
@WebServlet("/bus/ListBusLineInfoServlet")
public class ListBusLineInfoServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public ListBusLineInfoServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		BusLineBusinessService service = new BusLineBusinessService();
		Map map = service.getAllBus();
		request.setAttribute("map", map);

		request.getRequestDispatcher("/WEB-INF/jsp/listbusline.jsp").forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}


text:
Introduced `Collecting` façade to support additional collectors.

* `Collecting.flat` can be used to flat a `Stream` of `Iterable`s, as an example:
```
Stream.of(Arrays.asList(1, 2, 3), Arrays.asList(4, 5)).collect(Collecting.flat()); // yields [1, 2, 3, 4, 5]
```
* `Collecting.reverse` useful to invert the order of a finite stream.
```
Stream.of(1, 2, 3).collect(Collecting.reverse()); // yields [3, 2, 1]
```

Introduced `Strategies` façade with the following methods (:warning: still to test!):
* `Function<T, R> firstMatch(Clause<T, R>... clauses)` to apply the first clause matching a condition
* `Function<T, Optional<R>> maybeFirstMatch(Clause<T, R>... clauses)` to apply optionally the first clause matching a condition
* `Function<T, List<R>> allMatches(Clause<T, R>... clauses)` to apply all clauses matching a condition
* also for binary functions

Added methods to `Maps` class to transform all keys and/or all values of the passed map, given a mapper function:
* `Map<W, V> mapKeys(Map<K, V> input, Function<K, W> keysMapper)` to transform all keys of the passed map applying the passed mapper function
* `Map<W, V> mapKeys(Map<K, V> input, Function<K, W> keysMapper, BinaryOperator<V> valueMerger)` to transform all keys of the passed map applying the passed mapper function. If the key is already present into the map, the passed value merger is applied to the value
* `Map<K, W> mapValues(Map<K, V> input, Function<V, W> valuesMapper)` to transform all values of the passed map applying the passed mapper function
* `Map<KK, VV> mapKeysAndValues(Map<K, V> input, Function<K, KK> keysMapper, Function<V, VV> valuesMapper)` to transform all keys and all values of the passed map applying the passed mapper functions
* `Map<KK, VV> mapKeysAndValues(Map<K, V> input, Function<K, KK> keysMapper, Function<V, VV> valuesMapper, BinaryOperator<VV> valueMerger)` to transform all keys and all values of the passed map applying the passed mapper functions. If the key is already present into the map, the passed value merger is applied to the value

### Refactors

Some better names:
* renamed `Multiplexing.batch` in `unchain` (`BatchingIterator` -> `UnchainIterator`)
* renamed `Multiplexing.unchain` in `unchainShortest` (`UnchainIterator` -> `UnchainShortestIterator`)
* renamed `Multiplexing.unchainWithExactChannelSize` in `unchainLongest` (`UnchainWithExactChannelSizeIterator` -> `UnchainLongestIterator`)

`Multiplexing.flatten` and `chain` accepts varargs.

## 8.0

### Additions

Introduced the `Sequences` façade, in order to simplify the usage of sequential streams.
A `Sequence` has the following additional methods:
* Consumers: `toList`, `toSet`, `toMap`, `first`, `maybeFirst`, `one`, `maybeOne`, `last`, `maybeLast`, `nth`, `maybeNth`, `at`, `maybeAt`
* Filtering: `take`, `takeLast`, `takeAtMostLast`, `takeWhile`, `drop`, `dropWhile`, `slice`, `distinctBy`
* Multiplexing: `chain`
* Applications: `tap`

Added the following new methods:
* `Optional<LT> Either::left()` method to get the left part of the `Either`
* `Function<Either<LT, RT>, Either<LR, RR>> Eithers::lift(Function<LT, LR> left, Function<RT, RR> right)` to lift functions working on the components of an `Either` into a single function working on either
* `Function<Box<T>, Box<R>> Boxes::lift(Function<T, R> function)` to lift a function to another working on box values
* `Maybe<T> Maybes::toMaybe(Optional<T> optional)` to convert an `Optional` to a `Maybe`
* `Pair<T2, T1> Pair::flip()`
* `Triple<T3, T2, T1> Triple::flip()`
* `Triple<T2, T3, T1> Triple::rotateLeft()`
* `Triple<T3, T1, T2> Triple::rotateRight()`

### Refactors

Replaced functional interfaces with built-in ones in package `java.util.function`:
* `Delegate` -> `Function`
* `BinaryDelegate` -> `BiFunction`
* `Provider` -> `Supplier`
* `Predicate` -> `Predicate`
* `BinaryPredicate` -> `BiPredicate`
* `Action` -> `Consumer`
* `BinaryAction` -> `BiConsumer`
* `Proposition` -> `BooleanSupplier`

Used `java.util.Optional` instead of `Maybe`.

Uniformed named with standard library:
* `Maybe.fmap` -> `Maybe.map`
* `Maybe.value` -> `Maybe.get`
* `Maybe.hasValue` -> `Maybe.isPresent`
* `Box.fmap` -> `Box.map`
* `Box.hasContent` -> `Box.isPresent`
* `Either.fmap` -> `Either.map`
* `Either.maybe` -> `Either.right`
* `Pair.fmap` -> `Pair.map`
* `Triple.fmap` -> `Triple.map`
* `TernaryDelegate` -> `TriFunction`
* `TernaryPredicate` -> `TriPredicate`

Removed useless functors:
* `Identity` -> use `Function.identity()` or `x -> x`
* `DropMaybe` -> use `Maybes::drop`
* `EitherToMaybe` -> use `Eithers::right`
* `PureMaybe` -> use `Optional::of`
* `LiftMaybe` -> use `Optional::ofNullable`
* `PureEither` -> use `Either::right`
* `PureBox` -> use `Box::of`
* `MaybeRight` -> use `Eithers::right`
* `MaybeOrElse` -> use lambda
* `MaybeLeft` -> use `Either::left`
* `MaybeIteratorTransformer` -> use `MaybeIterator::new`
* `IsNothing` -> use `Maybes::isEmpty`
* `IsJust` -> use `Optional::isPresent`
* `FromJust` -> use `Optional::get`
* `FmapMaybe` -> invoke `Maybes.lift`
* `FMapBox` -> invoke `Boxes.lift`
* `FlipEither` -> use `Either::flip`
* `FlipPair` -> use `Pair::flip`
* `FlipTriple` -> use `Triple::flip`
* `PairFirst` -> use `Pair::first`
* `PairSecond` -> use `Pair::second`
* `TripleFirst` -> use `Triple::first`
* `TripleSecond` -> use `Triple::second`
* `TripleThird` -> use `Triple::third`
* `TripleRotateLeft` -> use `Triple::rotateLeft`
* `TripleRotateRight` -> use `Triple::rotateRight`
* `Max` -> use `BinaryOperator.maxBy`
* `Min` -> use `BinaryOperator.minBy`
* `Negator` -> invoke `predicate.negate()`
* `Equals` -> invoke `Predicate.isEqual()`
* `NotEquals` -> invoke `Predicate.isEqual().negate()`
* `HasNext` -> use `Iterator::hasNext`
* `IteratorPlucker` -> use `Iterable::iterator`
* `ClassPlucker` -> use `Object::getClass`


text:
package pkg

import (
	"os"
	"os/exec"
)

//Execute runs a command
func Execute(command string, args []string) error {
	cmd := exec.Command(command, args...)
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	err := cmd.Run()
	return err
}


text:
from __future__ import print_function

# FUNCTIONS

def addNums(a, b):
    """ Adds two numbers and returns the result. """

    c = a + b

    return c

# Calling a function
print(addNums(5, 8))

# Input for the decimalHour function: 05:29:45

def decimalHour(time_string):
    """ Converts time from the 24hrs hh:mm:ss format to HH.hhh format. """

    hh, mm, ss = time_string.split(':')

    hh, mm, ss = map(float, (hh, mm, ss))

    result = ((ss/60) + mm)/60 + hh

    return result

# Call the function
print(decimalHour('05:29:45'))

# Call a function without the arguments
print(decimalHour)

def UTCdecimal(time_string, timezone=0):
    """ Converts time from the 24hrs hh:mm:ss to decimal hours, with respect to the timezone. """

    # Get the decimal time
    result = decimalHour(time_string) + timezone

    # Return the time (handle midnight wraparound)
    return result % 24

# Calling without parameters (time of the Trinity test on July 16, 1945)
print(UTCdecimal('05:29:45'))

# Calling with the timezone parameter (time in London, UK at the time of the Trinity test)
print(UTCdecimal('05:29:45', timezone=-7))

### Local and global variables

# Global vs local variables

def test(var):
    print('Input:', var)

    # This change will not influence the value of 'var' outside the function!
    var = 20

    print('Changed:', var)

    return 0

var = 10

test(var)

print('Global:', var)

### Unpacking function arguments from a list

def isTriangle(a, b, c):
    """ Checks if the given triangle sides can form a triangle. """

    if c > (a+b):
        return False

    elif b > (a+c):
        return False

    elif a > (b+c):
        return False

    return True

triangle_sides = [2, 3, 4]

# Unpacking list as function arguments with * (star)
print('Is ', triangle_sides, 'a triangle:', isTriangle(*triangle_sides))

###################################

### DISCUSSION BREAK

# Python philosophy
# PEP20: The Zen of Python
"""
>> import this
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
"""

# Style guide we are using: https://developer.lsst.io/coding/python_style_guide.html

# How to name things:
# - variable_name
# - functionName
# - ClassName
# - CONSTANTS

###################################

# NUMPY!

# Importing numpy
import numpy as np

# 2 points in 3D space
a = [[5, 1, 8], [3, 4, 6]]

print(a)

# Converting the list to a numpy array
a = np.array(a)

print(a)

# Atrubutes of a numpy array
print('Shape:', a.shape)
print('Dimensions:', a.ndim)
print('Type:', a.dtype)
print('Total number of elements:', a.size)

# Creating an array of zeros
b = np.zeros((3, 3))

print(b)
print(b.dtype)

# Creating an array of ones, forcing the type to int
c = np.ones((3, 3), dtype=np.int32)

print(c)

# Identity matrix
idm = np.eye(3)
print(idm)

# Converting the string list to a float list
num_lst = ['1.20', '2.15', '3.78', '4.05']

num_lst = np.array(num_lst).astype(np.float64)

print(num_lst)

# Creating a range of numbers from 0 to 100 as an array, with step 0.5
arr = np.arange(0, 100, 0.5)

print (arr)

# Creating a range of numbers - another approach
arr2 = np.linspace(0, 2, 9)

print(arr2)

# Reshaping an array
arr2 = arr2.reshape((3, 3))

print(arr2)

###################################

### Operations between arrays/matrices

# Adding a scalar to an array
a = np.zeros((3, 3))
a = a + 5
print(a)

# Multiplying by a scalar
a = a*3
print(a)

# Raising to a power
a = a**2
print(a)

a = np.zeros((3, 3)) + 2
b = np.zeros_like(a) + 3

# Multiplying matrices, element-wise
print(a*b)

# Dot product (matrix product)
print(np.dot(a, b))

# Some unary operations
a = np.arange(1, 101)
print('Sum:', np.sum(a))
print('Min:', np.min(a))
print('Max:', np.max(a))
print('Mean:', np.mean(a))
print('Median:', np.median(a))
print('Stddev:', np.std(a))

###################################

arr = np.linspace(1, 5, 20)

### Mathematical functions

# Square root
print(np.sqrt(arr))

# Sine
print(np.sin(arr))

# Cosine
print(np.cos(arr))

# Exponential
print(np.exp(arr))

###################################

### INTRO TO MATPLOTLIB

# Basic anatomy of a plot: https://matplotlib.org/_images/anatomy1.png

import matplotlib.pyplot as plt

# Sine function in the range x=[0, 10]
x = np.linspace(0, 10, 100)
y = np.sin(x)

### Basic plotting

plt.plot(x, y)

# plt.show()

# Adding a 1 sigma above mean line
plt.plot(x, np.zeros_like(x) + np.mean(y) + np.std(y), linestyle='--', color='red')

# plt.show()

# Adding a title and labels
plt.title('My first plot')
plt.xlabel('X')
plt.ylabel('Y')

# plt.show()

# Adding a grid
plt.grid()

plt.show()

# Clearing a plot
plt.clf()
plt.close()


text:
package org.apache.helix.messaging;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.helix.ClusterMessagingService;
import org.apache.helix.ConfigAccessor;
import org.apache.helix.Criteria;
import org.apache.helix.HelixDataAccessor;
import org.apache.helix.HelixManager;
import org.apache.helix.InstanceType;
import org.apache.helix.PropertyKey.Builder;
import org.apache.helix.manager.zk.ZKHelixDataAccessor;
import org.apache.helix.messaging.handling.AsyncCallbackService;
import org.apache.helix.messaging.handling.HelixTaskExecutor;
import org.apache.helix.messaging.handling.MessageHandlerFactory;
import org.apache.helix.model.ConfigScope;
import org.apache.helix.model.LiveInstance;
import org.apache.helix.model.Message;
import org.apache.helix.model.Message.MessageType;
import org.apache.helix.model.builder.ConfigScopeBuilder;
import org.apache.helix.monitoring.mbeans.MessageQueueMonitor;
import org.apache.helix.monitoring.mbeans.ParticipantStatusMonitor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DefaultMessagingService implements ClusterMessagingService {
  private final HelixManager _manager;
  private final CriteriaEvaluator _evaluator;
  private final HelixTaskExecutor _taskExecutor;
  // TODO:rename to factory, this is not a service
  private final AsyncCallbackService _asyncCallbackService;

  private static Logger _logger = LoggerFactory.getLogger(DefaultMessagingService.class);
  ConcurrentHashMap<String, MessageHandlerFactory> _messageHandlerFactoriestobeAdded =
      new ConcurrentHashMap<>();

  public DefaultMessagingService(HelixManager manager) {
    _manager = manager;
    _evaluator = new CriteriaEvaluator();

    boolean isParticipant = false;
    if (manager.getInstanceType() == InstanceType.PARTICIPANT || manager.getInstanceType() == InstanceType.CONTROLLER_PARTICIPANT) {
      isParticipant = true;
    }

    _taskExecutor = new HelixTaskExecutor(
        new ParticipantStatusMonitor(isParticipant, manager.getInstanceName()),
        new MessageQueueMonitor(manager.getClusterName(), manager.getInstanceName()));
    _asyncCallbackService = new AsyncCallbackService();
    _taskExecutor.registerMessageHandlerFactory(MessageType.TASK_REPLY.name(),
        _asyncCallbackService);
  }

  @Override
  public int send(Criteria recipientCriteria, final Message messageTemplate) {
    return send(recipientCriteria, messageTemplate, null, -1);
  }

  @Override
  public int send(final Criteria recipientCriteria, final Message message,
      AsyncCallback callbackOnReply, int timeOut) {
    return send(recipientCriteria, message, callbackOnReply, timeOut, 0);
  }

  @Override
  public int send(final Criteria recipientCriteria, final Message message,
      AsyncCallback callbackOnReply, int timeOut, int retryCount) {
    Map<InstanceType, List<Message>> generateMessage = generateMessage(recipientCriteria, message);
    int totalMessageCount = 0;
    for (List<Message> messages : generateMessage.values()) {
      totalMessageCount += messages.size();
    }
    _logger.info("Send " + totalMessageCount + " messages with criteria " + recipientCriteria);
    if (totalMessageCount == 0) {
      return 0;
    }
    String correlationId = null;
    if (callbackOnReply != null) {
      int totalTimeout = timeOut * (retryCount + 1);
      if (totalTimeout < 0) {
        totalTimeout = -1;
      }
      callbackOnReply.setTimeout(totalTimeout);
      correlationId = UUID.randomUUID().toString();
      for (List<Message> messages : generateMessage.values()) {
        callbackOnReply.setMessagesSent(messages);
      }
      _asyncCallbackService.registerAsyncCallback(correlationId, callbackOnReply);
    }

    HelixDataAccessor targetDataAccessor = getRecipientDataAccessor(recipientCriteria);
    for (InstanceType receiverType : generateMessage.keySet()) {
      List<Message> list = generateMessage.get(receiverType);
      for (Message tempMessage : list) {
        tempMessage.setRetryCount(retryCount);
        tempMessage.setExecutionTimeout(timeOut);
        tempMessage.setSrcInstanceType(_manager.getInstanceType());
        if (correlationId != null) {
          tempMessage.setCorrelationId(correlationId);
        }
        tempMessage.setSrcClusterName(_manager.getClusterName());

        Builder keyBuilder = targetDataAccessor.keyBuilder();
        if (receiverType == InstanceType.CONTROLLER) {
          targetDataAccessor
              .setProperty(keyBuilder.controllerMessage(tempMessage.getId()), tempMessage);
        } else if (receiverType == InstanceType.PARTICIPANT) {
          targetDataAccessor
              .setProperty(keyBuilder.message(tempMessage.getTgtName(), tempMessage.getId()),
                  tempMessage);
        }
      }
    }

      if (callbackOnReply != null) {
        // start timer if timeout is set
        callbackOnReply.startTimer();
      }
      return totalMessageCount;
  }

  private HelixDataAccessor getRecipientDataAccessor(final Criteria recipientCriteria) {
    HelixDataAccessor dataAccessor = _manager.getHelixDataAccessor();
    String clusterName = recipientCriteria.getClusterName();
    if (clusterName != null && !clusterName.equals(_manager.getClusterName())) {
      // for cross cluster message, create new DataAccessor for sending message.
      /*
        TODO On frequent cross clsuter messaging request, keeping construct data accessor may cause
        performance issue. We should consider adding cache in this service or HelixManager. --JJ
       */
      dataAccessor = new ZKHelixDataAccessor(clusterName, dataAccessor.getBaseDataAccessor());
    }
    return dataAccessor;
  }

  public Map<InstanceType, List<Message>> generateMessage(final Criteria recipientCriteria,
      final Message message) {
    Map<InstanceType, List<Message>> messagesToSendMap = new HashMap<InstanceType, List<Message>>();
    InstanceType instanceType = recipientCriteria.getRecipientInstanceType();

    HelixDataAccessor targetDataAccessor = getRecipientDataAccessor(recipientCriteria);

      List<Message> messages = Collections.EMPTY_LIST;
      if (instanceType == InstanceType.CONTROLLER) {
        messages = generateMessagesForController(message);
      } else if (instanceType == InstanceType.PARTICIPANT) {
        messages =
            generateMessagesForParticipant(recipientCriteria, message, targetDataAccessor);
      }
      messagesToSendMap.put(instanceType, messages);
      return messagesToSendMap;
  }

  private List<Message> generateMessagesForParticipant(Criteria recipientCriteria, Message message,
      HelixDataAccessor targetDataAccessor) {
    List<Message> messages = new ArrayList<Message>();
    List<Map<String, String>> matchedList =
        _evaluator.evaluateCriteria(recipientCriteria, targetDataAccessor);

    if (!matchedList.isEmpty()) {
      Map<String, String> sessionIdMap = new HashMap<String, String>();
      if (recipientCriteria.isSessionSpecific()) {
        Builder keyBuilder = targetDataAccessor.keyBuilder();
        // For backward compatibility, allow partial read for the live instances.
        // Note that this may cause the pending message to be sent with null target session Id.
        List<LiveInstance> liveInstances =
            targetDataAccessor.getChildValues(keyBuilder.liveInstances(), false);

        for (LiveInstance liveInstance : liveInstances) {
          sessionIdMap.put(liveInstance.getInstanceName(), liveInstance.getEphemeralOwner());
        }
      }
      for (Map<String, String> map : matchedList) {
        String id = UUID.randomUUID().toString();
        Message newMessage = new Message(message.getRecord(), id);
        String srcInstanceName = _manager.getInstanceName();
        String tgtInstanceName = map.get("instanceName");
        // Don't send message to self
        if (recipientCriteria.isSelfExcluded() && srcInstanceName.equalsIgnoreCase(tgtInstanceName)) {
          continue;
        }
        newMessage.setSrcName(srcInstanceName);
        newMessage.setTgtName(tgtInstanceName);
        newMessage.setResourceName(map.get("resourceName"));
        newMessage.setPartitionName(map.get("partitionName"));
        if (recipientCriteria.isSessionSpecific()) {
          newMessage.setTgtSessionId(sessionIdMap.get(tgtInstanceName));
        }
        messages.add(newMessage);
      }
    }
    return messages;
  }

  private List<Message> generateMessagesForController(Message message) {
    List<Message> messages = new ArrayList<Message>();
    String id = (message.getMsgId() == null) ? UUID.randomUUID().toString() : message.getMsgId();
    Message newMessage = new Message(message.getRecord(), id);
    newMessage.setMsgId(id);
    newMessage.setSrcName(_manager.getInstanceName());
    newMessage.setTgtName(InstanceType.CONTROLLER.name());
    messages.add(newMessage);
    return messages;
  }

  @Override
  public synchronized void registerMessageHandlerFactory(String type,
      MessageHandlerFactory factory) {
    registerMessageHandlerFactory(Collections.singletonList(type), factory);
  }

  @Override
  public synchronized void registerMessageHandlerFactory(List<String> types,
      MessageHandlerFactory factory) {
    if (_manager.isConnected()) {
      for (String type : types) {
        registerMessageHandlerFactoryInternal(type, factory);
      }
    } else {
      for (String type : types) {
        _messageHandlerFactoriestobeAdded.put(type, factory);
      }
    }
  }

  public synchronized void onConnected() {
    for (String type : _messageHandlerFactoriestobeAdded.keySet()) {
      registerMessageHandlerFactoryInternal(type, _messageHandlerFactoriestobeAdded.get(type));
    }
    _messageHandlerFactoriestobeAdded.clear();
  }

  void registerMessageHandlerFactoryInternal(String type, MessageHandlerFactory factory) {
    _logger.info("registering msg factory for type " + type);
    int threadpoolSize = HelixTaskExecutor.DEFAULT_PARALLEL_TASKS;
    String threadpoolSizeStr = null;
    String key = type + "." + HelixTaskExecutor.MAX_THREADS;

    ConfigAccessor configAccessor = _manager.getConfigAccessor();
    if (configAccessor != null) {
      ConfigScope scope = null;

      // Read the participant config and cluster config for the per-message type thread pool size.
      // participant config will override the cluster config.

      if (_manager.getInstanceType() == InstanceType.PARTICIPANT
          || _manager.getInstanceType() == InstanceType.CONTROLLER_PARTICIPANT) {
        scope =
            new ConfigScopeBuilder().forCluster(_manager.getClusterName())
                .forParticipant(_manager.getInstanceName()).build();
        threadpoolSizeStr = configAccessor.get(scope, key);
      }

      if (threadpoolSizeStr == null) {
        scope = new ConfigScopeBuilder().forCluster(_manager.getClusterName()).build();
        threadpoolSizeStr = configAccessor.get(scope, key);
      }
    }

    if (threadpoolSizeStr != null) {
      try {
        threadpoolSize = Integer.parseInt(threadpoolSizeStr);
        if (threadpoolSize <= 0) {
          threadpoolSize = 1;
        }
      } catch (Exception e) {
        _logger.error("", e);
      }
    }

    _taskExecutor.registerMessageHandlerFactory(type, factory, threadpoolSize);
    // Self-send a no-op message, so that the onMessage() call will be invoked
    // again, and
    // we have a chance to process the message that we received with the new
    // added MessageHandlerFactory
    // before the factory is added.
    sendNopMessageInternal();
  }

  @Deprecated
  public void sendNopMessage() {
    sendNopMessageInternal();
  }

  private void sendNopMessageInternal() {
    try {
      Message nopMsg = new Message(MessageType.NO_OP, UUID.randomUUID().toString());
      nopMsg.setSrcName(_manager.getInstanceName());

      HelixDataAccessor accessor = _manager.getHelixDataAccessor();
      Builder keyBuilder = accessor.keyBuilder();

      if (_manager.getInstanceType() == InstanceType.CONTROLLER
          || _manager.getInstanceType() == InstanceType.CONTROLLER_PARTICIPANT) {
        nopMsg.setTgtName(InstanceType.CONTROLLER.name());
        accessor.setProperty(keyBuilder.controllerMessage(nopMsg.getId()), nopMsg);
      }

      if (_manager.getInstanceType() == InstanceType.PARTICIPANT
          || _manager.getInstanceType() == InstanceType.CONTROLLER_PARTICIPANT) {
        nopMsg.setTgtName(_manager.getInstanceName());
        accessor.setProperty(keyBuilder.message(nopMsg.getTgtName(), nopMsg.getId()), nopMsg);
      }
    } catch (Exception e) {
      _logger.error(e.toString());
    }
  }

  public HelixTaskExecutor getExecutor() {
    return _taskExecutor;
  }

  @Override
  // TODO if the manager is not Participant or Controller, no reply, so should fail immediately
  public int sendAndWait(Criteria recipientCriteria, Message message, AsyncCallback asyncCallback,
      int timeOut, int retryCount) {
    int messagesSent = send(recipientCriteria, message, asyncCallback, timeOut, retryCount);
    if (messagesSent > 0) {
      synchronized (asyncCallback) {
        while (!asyncCallback.isDone() && !asyncCallback.isTimedOut()) {
          try {
            asyncCallback.wait();
          } catch (InterruptedException e) {
            _logger.error(e.toString());
            asyncCallback.setInterrupted(true);
            break;
          }
        }
      }
    } else {
      _logger.warn("No messages sent. For Criteria:" + recipientCriteria);
    }
    return messagesSent;
  }

  @Override
  public int sendAndWait(Criteria recipientCriteria, Message message, AsyncCallback asyncCallback,
      int timeOut) {
    return sendAndWait(recipientCriteria, message, asyncCallback, timeOut, 0);
  }
}


text:
#include "config.h"
#include "DRTDesktopNotificationPresenter.h"

#include "DumpRenderTree.h"
#include "LayoutTestController.h"
#include <JavaScriptCore/JSStringRef.h>
#include <JavaScriptCore/JSStringRefBSTR.h>
#include <WebCore/NotificationPresenter.h>

DRTDesktopNotificationPresenter::DRTDesktopNotificationPresenter()
    : m_refCount(1) {}

HRESULT STDMETHODCALLTYPE DRTDesktopNotificationPresenter::QueryInterface(REFIID riid, void** ppvObject)
{
    *ppvObject = 0;
    if (IsEqualGUID(riid, IID_IUnknown))
        *ppvObject = static_cast<DRTDesktopNotificationPresenter*>(this);
    else if (IsEqualGUID(riid, IID_IWebDesktopNotificationsDelegate))
        *ppvObject = static_cast<DRTDesktopNotificationPresenter*>(this);
    else
        return E_NOINTERFACE;

    AddRef();
    return S_OK;
}

ULONG STDMETHODCALLTYPE DRTDesktopNotificationPresenter::AddRef()
{
    return ++m_refCount;
}

ULONG STDMETHODCALLTYPE DRTDesktopNotificationPresenter::Release()
{
    ULONG newRef = --m_refCount;
    if (!newRef)
        delete(this);

    return newRef;
}

HRESULT STDMETHODCALLTYPE DRTDesktopNotificationPresenter::showDesktopNotification(
    /* [in] */ IWebDesktopNotification* notification)
{
    BSTR title, text, url;
    BOOL html;

    if (!notification->isHTML(&html) && html) {
        notification->contentsURL(&url);
        printf("DESKTOP NOTIFICATION: contents at %S\n", url ? url : L"");
    } else {
        notification->iconURL(&url);
        notification->title(&title);
        notification->text(&text);
        printf("DESKTOP NOTIFICATION: icon %S, title %S, text %S\n",
            url ? url : L"",
            title ? title : L"",
            text ? text : L"");
    }

    // In this stub implementation, the notification is displayed immediately;
    // we dispatch the display event to mimic that.
    notification->notifyDisplay();

    return S_OK;
}

HRESULT STDMETHODCALLTYPE DRTDesktopNotificationPresenter::cancelDesktopNotification(
    /* [in] */ IWebDesktopNotification* notification)
{
    BSTR identifier;
    BOOL html;
    notification->isHTML(&html);
    if (html)
        notification->contentsURL(&identifier);
    else
        notification->title(&identifier);

    printf("DESKTOP NOTIFICATION CLOSED: %S\n", identifier ? identifier : L"");
    notification->notifyClose(false);

    return S_OK;
}

HRESULT STDMETHODCALLTYPE DRTDesktopNotificationPresenter::notificationDestroyed(
    /* [in] */ IWebDesktopNotification* notification)
{
    // Since in these tests events happen immediately, we don't hold on to
    // Notification pointers.  So there's no cleanup to do.
    return S_OK;
}

HRESULT STDMETHODCALLTYPE DRTDesktopNotificationPresenter::checkNotificationPermission(
        /* [in] */ BSTR origin,
        /* [out, retval] */ int* result)
{
#if ENABLE(NOTIFICATIONS)
    JSStringRef jsOrigin = JSStringCreateWithBSTR(origin);
    bool allowed = ::gLayoutTestController->checkDesktopNotificationPermission(jsOrigin);

    if (allowed)
        *result = WebCore::NotificationPresenter::PermissionAllowed;
    else
        *result = WebCore::NotificationPresenter::PermissionDenied;

    JSStringRelease(jsOrigin);
#endif
    return S_OK;
}

HRESULT STDMETHODCALLTYPE DRTDesktopNotificationPresenter::requestNotificationPermission(
        /* [in] */ BSTR origin)
{
    printf("DESKTOP NOTIFICATION PERMISSION REQUESTED: %S\n", origin ? origin : L"");
    return S_OK;
}


text:
typedef struct ATP_DictionaryImpl
{
    char m_key[c_ATP_Dictionary_keySize + 1];
    Value m_value;
    UT_hash_handle hh;
} ATP_DictionaryImpl;

void ATP_dictionaryInit(ATP_Dictionary *p_dict)
{
    *p_dict = NULL;
}

void ATP_dictionaryDestroy(ATP_Dictionary *p_dict)
{
    if (p_dict != NULL)
    {
        ATP_DictionaryImpl *it;
        ATP_DictionaryImpl *l_tmp;

        HASH_ITER(hh, *p_dict, it, l_tmp)
        {
            HASH_DEL(*p_dict, it);
            Value_changeType(&it->m_value, e_ATP_ValueType_none);
            free(it);
        }

        *p_dict = NULL;
    }
}

void ATP_dictionaryRemove(ATP_Dictionary *p_dict, const char *p_key)
{
    ATP_DictionaryImpl *l_entry = NULL;
    HASH_FIND_STR(*p_dict, p_key, l_entry);
    if (l_entry != NULL)
    {
        // remove existing entry
        ATP_dictionaryErase(p_dict, l_entry);
    }
}

unsigned int ATP_dictionaryCount(ATP_Dictionary *p_dict)
{
    return HASH_COUNT(*p_dict);
}

static ATP_DictionaryImpl *createEntry(const char *p_key)
{
    ATP_DictionaryImpl *l_entry;
    if (strlen(p_key) > c_ATP_Dictionary_keySize)
    {
        ERR("Key '%s' is too long (max. %u characters)\n", p_key, c_ATP_Dictionary_keySize);
        return NULL;
    }

    l_entry = malloc(sizeof(ATP_DictionaryImpl));
    if (l_entry == NULL)
    {
        PERR();
        exit(EX_OSERR);
    }

    strncpy(l_entry->m_key, p_key, c_ATP_Dictionary_keySize + 1);
    l_entry->m_value.m_type = e_ATP_ValueType_none;
    return l_entry;
}

ATP_Dictionary ATP_dictionaryDuplicate(const ATP_Dictionary *p_dict)
{
    if (p_dict != NULL)
    {
        ATP_DictionaryImpl *it;
        ATP_DictionaryImpl *l_tmp;
        ATP_Dictionary l_result;

        ATP_dictionaryInit(&l_result);
        HASH_ITER(hh, *p_dict, it, l_tmp)
        {
            ATP_DictionaryImpl *l_copy = createEntry(it->m_key);
            if (l_copy == NULL)
            {
                ATP_dictionaryDestroy(&l_result);
                return NULL;
            }

            Value_copy(&l_copy->m_value, &it->m_value);
            HASH_ADD_STR(l_result, m_key, l_copy);
        }

        return l_result;
    }

    return NULL;
}

static ATP_DictionaryImpl *findOrCreateEntry(ATP_Dictionary *p_dict, const char *p_key)
{
    ATP_DictionaryImpl *l_entry;
    HASH_FIND_STR(*p_dict, p_key, l_entry);
    if (l_entry == NULL)
    {
        l_entry = createEntry(p_key);
        if (l_entry == NULL)
        {
            return NULL;
        }

        HASH_ADD_STR(*p_dict, m_key, l_entry);
    }

    return l_entry;
}

int ATP_dictionarySetString(ATP_Dictionary *p_dict, const char *p_key, const char *p_value)
{
    ATP_DictionaryImpl *l_entry = findOrCreateEntry(p_dict, p_key);
    if (l_entry == NULL)
    {
        return 0;
    }

    return ATP_dictionaryItSetString(l_entry, p_value);
}

int ATP_dictionarySetUint(ATP_Dictionary *p_dict, const char *p_key, unsigned long long p_value)
{
    ATP_DictionaryImpl *l_entry = findOrCreateEntry(p_dict, p_key);
    if (l_entry == NULL)
    {
        return 0;
    }

    return ATP_dictionaryItSetUint(l_entry, p_value);
}

int ATP_dictionarySetInt(ATP_Dictionary *p_dict, const char *p_key, signed long long p_value)
{
    ATP_DictionaryImpl *l_entry = findOrCreateEntry(p_dict, p_key);
    if (l_entry == NULL)
    {
        return 0;
    }

    return ATP_dictionaryItSetInt(l_entry, p_value);
}

int ATP_dictionarySetDouble(ATP_Dictionary *p_dict, const char *p_key, double p_value)
{
    ATP_DictionaryImpl *l_entry = findOrCreateEntry(p_dict, p_key);
    if (l_entry == NULL)
    {
        return 0;
    }

    return ATP_dictionaryItSetDouble(l_entry, p_value);
}

int ATP_dictionarySetBool(ATP_Dictionary *p_dict, const char *p_key, int p_value)
{
    ATP_DictionaryImpl *l_entry = findOrCreateEntry(p_dict, p_key);
    if (l_entry == NULL)
    {
        return 0;
    }

    return ATP_dictionaryItSetBool(l_entry, p_value);
}

int ATP_dictionarySetDict(ATP_Dictionary *p_dict, const char *p_key, ATP_Dictionary p_value)
{
    ATP_DictionaryImpl *l_entry = findOrCreateEntry(p_dict, p_key);
    if (l_entry == NULL)
    {
        return 0;
    }

    return ATP_dictionaryItSetDict(l_entry, p_value);
}

int ATP_dictionarySetArray(ATP_Dictionary *p_dict, const char *p_key, ATP_Array p_value)
{
    ATP_DictionaryImpl *l_entry = findOrCreateEntry(p_dict, p_key);
    if (l_entry == NULL)
    {
        return 0;
    }

    return ATP_dictionaryItSetArray(l_entry, p_value);
}

int ATP_dictionaryGetString(ATP_Dictionary *p_dict, const char *p_key, const char **p_value)
{
    ATP_DictionaryImpl *l_entry;
    HASH_FIND_STR(*p_dict, p_key, l_entry);
    if (l_entry == NULL)
    {
        return 0;
    }

    return ATP_dictionaryItGetString(l_entry, p_value);
}

int ATP_dictionaryGetUint(ATP_Dictionary *p_dict, const char *p_key, unsigned long long *p_value)
{
    ATP_DictionaryImpl *l_entry;
    HASH_FIND_STR(*p_dict, p_key, l_entry);
    if (l_entry == NULL)
    {
        return 0;
    }

    return ATP_dictionaryItGetUint(l_entry, p_value);
}

int ATP_dictionaryGetInt(ATP_Dictionary *p_dict, const char *p_key, signed long long *p_value)
{
    ATP_DictionaryImpl *l_entry;
    HASH_FIND_STR(*p_dict, p_key, l_entry);
    if (l_entry == NULL)
    {
        return 0;
    }

    return ATP_dictionaryItGetInt(l_entry, p_value);
}

int ATP_dictionaryGetDouble(ATP_Dictionary *p_dict, const char *p_key, double *p_value)
{
    ATP_DictionaryImpl *l_entry;
    HASH_FIND_STR(*p_dict, p_key, l_entry);
    if (l_entry == NULL)
    {
        return 0;
    }

    return ATP_dictionaryItGetDouble(l_entry, p_value);
}

int ATP_dictionaryGetBool(ATP_Dictionary *p_dict, const char *p_key, int *p_value)
{
    ATP_DictionaryImpl *l_entry;
    HASH_FIND_STR(*p_dict, p_key, l_entry);
    if (l_entry == NULL)
    {
        return 0;
    }

    return ATP_dictionaryItGetBool(l_entry, p_value);
}

int ATP_dictionaryGetDict(ATP_Dictionary *p_dict, const char *p_key, ATP_Dictionary **p_value)
{
    ATP_DictionaryImpl *l_entry;
    HASH_FIND_STR(*p_dict, p_key, l_entry);
    if (l_entry == NULL)
    {
        return 0;
    }

    return ATP_dictionaryItGetDict(l_entry, p_value);
}

int ATP_dictionaryGetArray(ATP_Dictionary *p_dict, const char *p_key, ATP_Array **p_value)
{
    ATP_DictionaryImpl *l_entry;
    HASH_FIND_STR(*p_dict, p_key, l_entry);
    if (l_entry == NULL)
    {
        return 0;
    }

    return ATP_dictionaryItGetArray(l_entry, p_value);
}

ATP_DictionaryIterator ATP_dictionaryBegin(ATP_Dictionary *p_dict)
{
    return *p_dict;
}

int ATP_dictionaryHasNext(ATP_DictionaryIterator p_iterator)
{
    return (p_iterator != NULL);
}

ATP_DictionaryIterator ATP_dictionaryNext(ATP_DictionaryIterator p_iterator)
{
    return p_iterator->hh.next;
}

ATP_DictionaryIterator ATP_dictionaryErase(ATP_Dictionary *p_dict, ATP_DictionaryIterator p_iterator)
{
    ATP_DictionaryIterator l_next = p_iterator->hh.next;

    HASH_DEL(*p_dict, p_iterator);
    Value_changeType(&p_iterator->m_value, e_ATP_ValueType_none);
    free(p_iterator);

    return l_next;
}

const char *ATP_dictionaryGetKey(ATP_DictionaryIterator p_iterator)
{
    return p_iterator->m_key;
}

ATP_ValueType ATP_dictionaryGetType(ATP_DictionaryIterator p_iterator)
{
    return p_iterator->m_value.m_type;
}

int ATP_dictionaryItSetString(ATP_DictionaryIterator p_iterator, const char *p_value)
{
    DBG("setting '%s': '%s'\n", p_iterator->m_key, p_value);
    Value_changeType(&p_iterator->m_value, e_ATP_ValueType_string);
    utstring_bincpy(&p_iterator->m_value.m_value.m_string, p_value, strlen(p_value));
    return 1;
}

int ATP_dictionaryItSetUint(ATP_DictionaryIterator p_iterator, unsigned long long p_value)
{
    DBG("setting '%s': %llu\n", p_iterator->m_key, p_value);
    Value_changeType(&p_iterator->m_value, e_ATP_ValueType_uint);
    p_iterator->m_value.m_value.m_uint = p_value;
    return 1;
}

int ATP_dictionaryItSetInt(ATP_DictionaryIterator p_iterator, signed long long p_value)
{
    DBG("setting '%s': %lld\n", p_iterator->m_key, p_value);
    Value_changeType(&p_iterator->m_value, e_ATP_ValueType_int);
    p_iterator->m_value.m_value.m_int = p_value;
    return 1;
}

int ATP_dictionaryItSetDouble(ATP_DictionaryIterator p_iterator, double p_value)
{
    DBG("setting '%s': %f\n", p_iterator->m_key, p_value);
    Value_changeType(&p_iterator->m_value, e_ATP_ValueType_double);
    p_iterator->m_value.m_value.m_double = p_value;
    return 1;
}

int ATP_dictionaryItSetBool(ATP_DictionaryIterator p_iterator, int p_value)
{
    DBG("setting '%s': %s\n", p_iterator->m_key, (p_value ? "true" : "false"));
    Value_changeType(&p_iterator->m_value, e_ATP_ValueType_bool);
    p_iterator->m_value.m_value.m_bool = (p_value != 0);
    return 1;
}

int ATP_dictionaryItSetDict(ATP_DictionaryIterator p_iterator, ATP_Dictionary p_value)
{
    DBG("setting '%s': <dictionary>\n", p_iterator->m_key);
    Value_changeType(&p_iterator->m_value, e_ATP_ValueType_dict);
    p_iterator->m_value.m_value.m_dict = p_value;
    return 1;
}

int ATP_dictionaryItSetArray(ATP_DictionaryIterator p_iterator, ATP_Array p_value)
{
    DBG("setting '%s': <array>\n", p_iterator->m_key);
    Value_changeType(&p_iterator->m_value, e_ATP_ValueType_array);
    p_iterator->m_value.m_value.m_array = p_value;
    return 1;
}

int ATP_dictionaryItGetString(ATP_DictionaryIterator p_iterator, const char **p_value)
{
    if (p_iterator->m_value.m_type == e_ATP_ValueType_string)
    {
        *p_value = utstring_body(&p_iterator->m_value.m_value.m_string);
        return 1;
    }

    return 0;
}

int ATP_dictionaryItGetUint(ATP_DictionaryIterator p_iterator, unsigned long long *p_value)
{
    if (p_iterator->m_value.m_type == e_ATP_ValueType_uint)
    {
        *p_value = p_iterator->m_value.m_value.m_uint;
        return 1;
    }

    return 0;
}

int ATP_dictionaryItGetInt(ATP_DictionaryIterator p_iterator, signed long long *p_value)
{
    if (p_iterator->m_value.m_type == e_ATP_ValueType_int)
    {
        *p_value = p_iterator->m_value.m_value.m_int;
        return 1;
    }

    return 0;
}

int ATP_dictionaryItGetDouble(ATP_DictionaryIterator p_iterator, double *p_value)
{
    if (p_iterator->m_value.m_type == e_ATP_ValueType_double)
    {
        *p_value = p_iterator->m_value.m_value.m_double;
        return 1;
    }

    return 0;
}

int ATP_dictionaryItGetBool(ATP_DictionaryIterator p_iterator, int *p_value)
{
    if (p_iterator->m_value.m_type == e_ATP_ValueType_bool)
    {
        *p_value = p_iterator->m_value.m_value.m_bool;
        return 1;
    }

    return 0;
}

int ATP_dictionaryItGetDict(ATP_DictionaryIterator p_iterator, ATP_Dictionary **p_value)
{
    if (p_iterator->m_value.m_type == e_ATP_ValueType_dict)
    {
        *p_value = &p_iterator->m_value.m_value.m_dict;
        DBG("dictionary member is %p\n", p_iterator->m_value.m_value.m_dict);
        return 1;
    }

    return 0;
}

int ATP_dictionaryItGetArray(ATP_DictionaryIterator p_iterator, ATP_Array **p_value)
{
    if (p_iterator->m_value.m_type == e_ATP_ValueType_array)
    {
        *p_value = &p_iterator->m_value.m_value.m_array;
        DBG("array member is %p\n", p_iterator->m_value.m_value.m_array);
        return 1;
    }

    return 0;
}


text: Helper functions with dealing with Go template files.


text:
<?xml version="1.0" encoding="UTF-8"?>
<!-- Licensed to David Pilato (the "Author") under one or more contributor
	license agreements. See the NOTICE file distributed with this work for additional
	information regarding copyright ownership. Author licenses this file to you
	under the Apache License, Version 2.0 (the "License"); you may not use this
	file except in compliance with the License. You may obtain a copy of the
	License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by
	applicable law or agreed to in writing, software distributed under the License
	is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
	KIND, either express or implied. See the License for the specific language
	governing permissions and limitations under the License. -->

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:util="http://www.springframework.org/schema/util"
	xmlns:elasticsearch="http://www.pilato.fr/schema/elasticsearch"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd
		http://www.pilato.fr/schema/elasticsearch http://www.pilato.fr/schema/elasticsearch/elasticsearch-0.2.xsd">

    <util:properties id="esproperties1" location="classpath:models/multinodes-namespace/esnode1.properties"/>
    <util:properties id="esproperties2" location="classpath:models/multinodes-namespace/esnode2.properties"/>

    <elasticsearch:node id="testNode1" properties="esproperties1" />
    <elasticsearch:node id="testNode2" properties="esproperties2" />

    <util:properties id="esproperties3" location="classpath:models/multinodes-namespace/esclient-transport.properties"/>
	<elasticsearch:client id="testNodeClient" esNodes="localhost:9300,localhost:9301" properties="esproperties3"/>

</beans>


text:
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-comp-4120',
  templateUrl: './comp-4120.component.html',
  styleUrls: ['./comp-4120.component.css']
})
export class Comp4120Component implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}


text:
A SettingPackageFilter is a SettingFilter used to select settings from a given list of packages: a setting is kept only if the package in which it is defined is present in the given package list

Instance Variables
	packages:		<Collection>

packages
	- The collection of PackageInfo the filter is currently using


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <attr name="colorDrawerItemText" format="color"/>

    <!-- Colors -->
    <attr name="colorAccentDark" format="color"/>
    <attr name="colorLectureText" format="color"/>
    <attr name="colorLectureAccent" format="color"/>
    <attr name="colorLectureBackground" format="color"/>

    <!-- Styles-->
    <attr name="tabstripStyle" format="reference"/>
    <attr name="flatRadioButtonStyle" format="reference"/>

    <!-- Drawables (workaround unsupported color references with API < 21) -->
    <attr name="drawableMenuItemBg" format="reference"/>
    <attr name="drawableButtonShape" format="reference"/>
</resources>


text:
cask "schism-tracker" do
  version "20220905"
  sha256 "61919abd757c59e927dbbaf1d30a00e88b3d6973380a793498ab32f415022fde"

  url "https://github.com/schismtracker/schismtracker/releases/download/#{version}/schismtracker-#{version}-macos.zip"
  name "Schism Tracker"
  desc "Oldschool sample-based music composition tool"
  homepage "https://github.com/schismtracker/schismtracker"

  app "Schism Tracker.app"
end


text:
'use strict';

// Orders controller
angular.module('ecom').controller('OrdersController', [
    '$scope', '$stateParams', '$location', 'Authorisation', 'Orders', '$state', 'Checkout', 'Authentication',
	function($scope, $stateParams, $location, Authorisation, Orders, $state, Checkout, Authentication) {
		$scope.Authorisation = Authorisation;

		// Remove existing Order
		$scope.remove = function( order ) {
			if ( order ) { order.$remove();

				for (var i in $scope.orders ) {
					if ($scope.orders [i] === order ) {
						$scope.orders.splice(i, 1);
					}
				}
			} else {
				$scope.order.$remove(function() {
					$location.path('orders');
				});
			}
		};

		// Update existing Order
		$scope.update = function() {
			var order = $scope.order ;

			order.$update(function() {
				$location.path('orders/' + order._id);
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		// Find a list of Orders
		$scope.find = function() {
			$scope.orders = Orders.query();
		};

		// Find existing Order
		$scope.findOne = function() {
			$scope.order = Orders.get({
				orderId: $stateParams.orderId
			});
		};

		$scope.getOrderHistory = function() {
			$scope.history = Orders.history({
				userId: Authentication.user._id
			})
			.$promise
			.then(function(history) {
			    $scope.history = history;
			    if (history.length > 0) {
			        $scope.active = history[0].id;
			    }
			})
			.catch(function(err) { $scope.error = err.data.message; });
		};

		$scope.recalculate = function() {
		    var order = $scope.order;

		    order
		        .$recalculate()
		        .then(function(doc) { $scope.order = doc; })
		        .catch(function(err) { $scope.error = err.data.message; });
		};

		$scope.recalculateWithLookup = function() {
		    var order = $scope.order;

		    order
		        .$recalculateWithLookup()
		        .then(function(doc) { $scope.order = doc; })
		        .catch(function(err) { $scope.error = err.data.message; });
		};

		$scope.close = function() {
		    var order = $scope.order;

		    Checkout
		        .close({ orderId: order._id, method: order.payments[0].method })
		        .$promise
		        .then(function(doc) { $scope.order = doc; })
		        .catch(function(err) { $scope.error = err.data.message; });
		};

	}
])
.directive('orderItems', function() {
    return {
        templateUrl: 'modules/ecom/templates/order-items.client.template.html'
    };
})
.filter('reverse', function() {
    return function(items) {
        return items.slice().reverse();
    };
});


text:
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <ctype.h>
#include <limits.h>
#include "port.h"
#include "ploader.h"
#include "osint.h"

#ifndef TRUE
#define TRUE    1
#define FALSE   0
#endif

/* port prefix */
#if defined(CYGWIN) || defined(WIN32) || defined(MINGW)
  #define PORT_PREFIX ""
#elif defined(LINUX)
  #ifdef RASPBERRY_PI
    #define PORT_PREFIX "ttyAMA"
  #else
    #define PORT_PREFIX "ttyUSB"
  #endif
#elif defined(MACOSX)
  #define PORT_PREFIX "cu.usbserial-"
#else
  #define PORT_PREFIX ""
#endif

/* defaults */
#define BAUD_RATE       115200

/* constants */
#define HUB_MEMORY_SIZE 32768

static PL_state state;

static void Usage(void);
static uint8_t *ReadEntireFile(char *name, long *pSize);

int main(int argc, char *argv[])
{
    char actualPort[PATH_MAX], *var, *val, *port, *p;
    int baudRate, baudRate2, verbose, terminalMode, pstMode, i;
    int loadType = LOAD_TYPE_RUN;
    int loadTypeOptionSeen = FALSE;
    int actionSpecified = FALSE;
    char *file = NULL;
    long imageSize;
    uint8_t *image;

    /* initialize */
    baudRate = baudRate2 = BAUD_RATE;
    verbose = terminalMode = pstMode = FALSE;
    port = NULL;

    /* initialize the loader port */
    InitPortState(&state);

    /* process the position-independent arguments */
    for (i = 1; i < argc; ++i) {

        /* handle switches */
        if (argv[i][0] == '-') {
            switch (argv[i][1]) {
            case 'b':
                if (argv[i][2])
                    p = &argv[i][2];
                else if (++i < argc)
                    p = argv[i];
                else
                    Usage();
                if (*p != ':')
                    baudRate = baudRate2 = atoi(p);
                if ((p = strchr(p, ':')) != NULL) {
                    if (*++p != ':' && *p != '\0')
                        baudRate2 = atoi(p);
                }
                break;
            case 'D':
                if (argv[i][2])
                    p = &argv[i][2];
                else if (++i < argc)
                    p = argv[i];
                else
                    Usage();
                if ((var = strtok(p, "=")) != NULL) {
                    if ((val = strtok(NULL, "")) != NULL) {
                        if (strcmp(var, "reset") == 0)
                            use_reset_method(val);
                        else
                            Usage();
                    }
                    else
                        Usage();
                }
                else
                    Usage();
                break;
            case 'e':
                if (!loadTypeOptionSeen) {
                    loadTypeOptionSeen = TRUE;
                    loadType = 0;
                }
                loadType |= LOAD_TYPE_EEPROM;
                break;
            case 'p':
                if (argv[i][2])
                    port = &argv[i][2];
                else if (++i < argc)
                    port = argv[i];
                else
                    Usage();
#if defined(CYGWIN) || defined(WIN32) || defined(LINUX)
                if (isdigit((int)port[0])) {
#if defined(CYGWIN) || defined(WIN32)
                    static char buf[10];
                    sprintf(buf, "COM%d", atoi(port));
                    port = buf;
#endif
#if defined(LINUX)
                    static char buf[64];
                    sprintf(buf, "/dev/%s%d", PORT_PREFIX, atoi(port));
                    port = buf;
#endif
                }
#endif
#if defined(MACOSX)
                if (port[0] != '/') {
                    static char buf[64];
                    sprintf(buf, "/dev/%s-%s", PORT_PREFIX, port);
                    port = buf;
                }
#endif
                break;
            case 'P':
                ShowPorts(&state, PORT_PREFIX);
                actionSpecified = TRUE;
                break;
            case 'r':
                if (!loadTypeOptionSeen) {
                    loadTypeOptionSeen = TRUE;
                    loadType = 0;
                }
                loadType |= LOAD_TYPE_RUN;
                break;
            case 'T':
                pstMode = TRUE;
                // fall through
            case 't':
                terminalMode = TRUE;
                actionSpecified = TRUE;
                break;
            case 'v':
                verbose = TRUE;
                break;
            case '?':
                /* fall through */
            default:
                Usage();
                break;
            }
        }

        /* handle the input filename */
        else {
            if (file)
                Usage();
            file = argv[i];
            actionSpecified = TRUE;
        }
    }

    /* complain about nothing to do */
    if (!actionSpecified) {
        printf("error: must specify either a file to load or -t\n");
        return 1;
    }

    /* open the serial port */
    if (file || terminalMode) {
        switch (InitPort(&state, PORT_PREFIX, port, baudRate, verbose, actualPort)) {
        case CHECK_PORT_OK:
            printf("Found propeller version %d on %s\n", state.version, actualPort);
            break;
        case CHECK_PORT_OPEN_FAILED:
            printf("error: opening serial port '%s'\n", port);
            perror("Error is ");
            return 1;
        case CHECK_PORT_NO_PROPELLER:
            if (port)
                printf("error: no propeller chip on port '%s'\n", port);
            else
                printf("error: can't find a port with a propeller chip\n");
            return 1;
        }
    }

    /* check for a file to load */
    if (file) {

        /* read the entire file into a buffer */
        if (!(image = ReadEntireFile(file, &imageSize))) {
            printf("error: reading '%s'\n", file);
            return 1;
        }

        /* make sure the file isn't too big for hub memory */
        if (imageSize > HUB_MEMORY_SIZE) {
            printf("error: image too big for hub memory\n");
            return 1;
        }

        /* load the file from the memory buffer */
        printf("Loading '%s' (%ld bytes)\n", file, imageSize);
        switch (PL_LoadSpinBinary(&state, loadType, image, imageSize)) {
        case LOAD_STS_OK:
            printf("OK\n");
            break;
        case LOAD_STS_ERROR:
            printf("Error\n");
            return 1;
        case LOAD_STS_TIMEOUT:
            printf("Timeout\n");
            return 1;
        default:
            printf("Internal error\n");
            return 1;
        }
    }

    /* enter terminal mode if requested */
    if (terminalMode) {
        printf("[ Entering terminal mode. Type ESC or Control-C to exit. ]\n");
        fflush(stdout);
        if (baudRate2 != baudRate)
            serial_baud(baudRate2);
        terminal_mode(FALSE, pstMode);
    }

    return 0;
}

/* Usage - display a usage message and exit */
static void Usage(void)
{
printf("\
p1load - a simple loader for the propeller - %s, %s\n\
usage: p1load\n\
         [ -b baud ]               baud rate (default is %d)\n\
         [ -D var=val ]            set variable value\n\
         [ -e ]                    write a bootable image to EEPROM\n\
         [ -p port ]               serial port (default is to auto-detect the port)\n\
         [ -P ]                    list available serial ports\n\
         [ -r ]                    run the program after loading (default)\n\
         [ -t ]                    enter terminal mode after running the program\n\
         [ -T ]                    enter PST-compatible terminal mode\n\
         [ -v ]                    verbose output\n\
         [ -? ]                    display a usage message and exit\n\
         file                      file to load\n", VERSION, __DATE__, BAUD_RATE);
#ifdef RASPBERRY_PI
printf("\
\n\
This version supports resetting the Propeller with a GPIO pin with option: -Dreset=gpio,pin,level\n\
where \"pin\" is the GPIO number to use and \"level\" is the logic level, 0 or 1. This defaults to\n\
GPIO 17 and level 0.\n\
");
#endif
    exit(1);
}

/* ReadEntireFile - read an entire file into an allocated buffer */
static uint8_t *ReadEntireFile(char *name, long *pSize)
{
    uint8_t *buf;
    long size;
    FILE *fp;

    /* open the file in binary mode */
    if (!(fp = fopen(name, "rb")))
        return NULL;

    /* get the file size */
    fseek(fp, 0L, SEEK_END);
    size = ftell(fp);
    fseek(fp, 0L, SEEK_SET);

    /* allocate a buffer for the file contents */
    if (!(buf = (uint8_t *)malloc(size))) {
        fclose(fp);
        return NULL;
    }

    /* read the contents of the file into the buffer */
    if (fread(buf, 1, size, fp) != size) {
        free(buf);
        fclose(fp);
        return NULL;
    }

    /* close the file ad return the buffer containing the file contents */
    *pSize = size;
    fclose(fp);
    return buf;
}