text:
OSA-Prep is a starter collection of playbooks for preparation of the OSA Project. It will take bare-metal (or virtual hosts if you choose), and prepare them for an OSA multi-node deployment. It will also [eventually] provision side-car initiatives such as the deployment of Ceph-Ansible, Elasticsearch/Logstash/Kibana, Nagios and other tooling.

## Quickstart: Steps to deploy
  1. Create your base-machine with Ubuntu 14.04 LTE
  2. Edit the inventory file according to your deployment
  3. Create `/etc/hosts` for each of your servers by running `./setup-hosts.sh -i inventory.ini`
  4. Run the playbooks `./setup.sh -i inventory.ini`
  5. At this point, if you are setting up bridges, bonds or vlan interfaces, it is best to reboot your machine after step 4.
  6. Log into the deployment host.
  7. `sudo su -`, and create a `root` ssh-key with the following command: `ssh-keygen -t rsa -b 4096 -C "{{deploy-host}}@{{domain}}"`. Add the `/root/.ssh/id_rsa.pub` contents to each of your target hosts in `/root/.ssh/authorized_keys`.
  8. Add id_rsa.pub to each of the hosts (see notes below).
  9. Configure all of your options according to lengthy list at:
  [Mitaka - Chapter 4. Configuration Guides](http://docs.openstack.org/developer/openstack-ansible/mitaka/install-guide/configure.html).
  10. Once completed, run the syntax check tool against your configuration files: `openstack-ansible setup-infrastructure.yml --syntax-check`
  11. Set up the hosts according to your environment configuration (from `/opt/openstack-ansible/playbooks` directory): `openstack-ansible setup-hosts.yml`.
  12. If using HAproxy (as opposed to a hardware LB), make sure it is HA with the following command (from `/opt/openstack-ansible/playbooks` directory): `ansible-galaxy install -r ../ansible-role-requirements.yml`.
  13. Run the playbooks to deploy HAproxy (from `/opt/openstack-ansible/playbooks` directory): `openstack-ansible haproxy-install.yml`.
  14. Run the infrastructure playbooks (from `/opt/openstack-ansible/playbooks` directory): `openstack-ansible setup-infrastructure.yml`.
  15. Verify the database clusters:
  ```
  ansible galera_container -m shell -a "mysql \
  -h localhost -e 'show status like \"%wsrep_cluster_%\";'"
  ```
  16. Run the Openstack Setup playbooks: `openstack-ansible setup-openstack.yml`

## Using This Project
These playbooks are designed to build infrastructure within an Openstack environment for testing various components of the OSA project (a highly customizable version Openstack within Openstack). If you'd like to use this project for your own purposes, then you should prepare your Ansible deployment environment like so:

Create entries in your ~/.ssh/config file for each of your servers like so:
  ```
  Host osad-compute01
    User ubuntu
    Hostname osad-compute01
    IdentityFile <home-dir>/user/.ssh/<ssh-key>
    StrictHostKeyChecking no
  ```

Next create a corresponding entry in `/etc/hosts` on your deployment host. If your deployment host is also a target host, than `/etc/hosts` will be generated for you. Lastly, create DNS entries in your production environment and ensure that DNS is resolving for each of your hosts.

One helpful command will be the `ansible-playbook --list-tags` command. Use as shown below:
```
$ ansible-playbook site.yml --list-tags

playbook: site.yml

  play #1 (all): 	TAGS: [osa-deploy-prep]
      TASK TAGS: [osa-deploy-prep, att-full-dist-upgrade, att-install-prereqs]

  play #2 (all): 	TAGS: [osa-deploy-tools]
      TASK TAGS: [osa-deploy-tools]

  play #3 (deploy-host): 	TAGS: [osa-deploy-host]
      TASK TAGS: [osa-deploy-host]

  play #4 (target-host): 	TAGS: [osa-target-host]
      TASK TAGS: [osa-target-host]

  play #5 (target-host): 	TAGS: [osa-deploy-networking]
      TASK TAGS: [networking-dir-create, osa-deploy-networking, att-network-deploy]

  play #6 (target-host): 	TAGS: [osa-deploy-networking]
      TASK TAGS: [networking-dir-create, osa-deploy-networking, att-network-deploy]

  play #7 (logging-host): 	TAGS: [osa-deploy-networking]
      TASK TAGS: [networking-dir-create, osa-deploy-networking, att-network-deploy]

$
```
This command will show you all plays and associated tags within the project. This will help as we clean up our deployment. You can use it like so:
```
$ ./setup.sh -i inventory.ini --tags att-network-deploy --limit=host-logs01
```

If you would like `/etc/hosts` generated for each member of the inventory file (`inventory.ini`), then you can run the following command once:
```
$ ./setup-hosts -i inventory.ini
```

### Create Host Variable Files
Use the templates included in the `host_vars` directory for the type of deployment you are using. Currently there are two supported deployments: Multi-Node with Multi-NIC servers (mm), and Multi-Node with Single-NIC servers (ms). Others will be included in the future to include Single-Node with Multi-NIC deployment types and finally Single-Node with Single-NIC (better referred to as AIO, or all-in-one deployments).

Copy the deployment template for your server type (you can have mixed types depending on your switch/routing scenario), and complete the required information. Once completed, move to the next section.

### Testing your deployment
Use the following command to test your deployment:
`ansible all -m ping -i inventory.ini`

## TODO:
* Automate distribution the `/root/id_rsa.pub` key on the deployment server to each of the target hosts. More information can be found [HERE](http://docs.openstack.org/developer/openstack-ansible/install-guide/targethosts-prepare.html#deploying-ssh-keys). During this deployment, I manually did this task to verify it worked as expected:  `scp ~/.ssh/id_rsa.pub host-logs01:/root/.ssh/`.
* Use secrets management like [HashiCorp Vault](https://github.com/hashicorp/vault).
* Start exploring [NAPALM](https://github.com/napalm-automation/napalm) for network automation of ISO, JunOS, FortiOS, PANOS and other gear.
* Gather Ceph Configuration facts and add that into our deployment.
* Configure other services automatically, such as Swift, Ceph, Alarming, etc.
* Enable the following settings for each user (`/home/{{user}}/.bashrc`)
        ```
        force_color_prompt=yes
        alias dir='dir --color=auto'
        alias vdir='vdir --color=auto'
        ```
Why(?): Besides the aesthetics, colors can prevent mistakes.
* Add ssh keys for root automatically to deployment host.
* Add deployment host root public key to `/root/.ssh/authorized_keys` automatically.


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.42000
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace GeoMagGUI.Properties {
    using System;

    /// <summary>
    ///   A strongly-typed resource class, for looking up localized strings, etc.
    /// </summary>
    // This class was auto-generated by the StronglyTypedResourceBuilder
    // class via a tool like ResGen or Visual Studio.
    // To add or remove a member, edit your .ResX file then rerun ResGen
    // with the /str option, or rebuild your VS project.
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    internal class Resources {

        private static global::System.Resources.ResourceManager resourceMan;

        private static global::System.Globalization.CultureInfo resourceCulture;

        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        internal Resources() {
        }

        /// <summary>
        ///   Returns the cached ResourceManager instance used by this class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Resources.ResourceManager ResourceManager {
            get {
                if (object.ReferenceEquals(resourceMan, null)) {
                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("GeoMagGUI.Properties.Resources", typeof(Resources).Assembly);
                    resourceMan = temp;
                }
                return resourceMan;
            }
        }

        /// <summary>
        ///   Overrides the current thread's CurrentUICulture property for all
        ///   resource lookups using this strongly typed resource class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Globalization.CultureInfo Culture {
            get {
                return resourceCulture;
            }
            set {
                resourceCulture = value;
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to ApplicationPreferences.json.
        /// </summary>
        internal static string File_Name_Application_Preferences_JSON {
            get {
                return ResourceManager.GetString("File_Name_Application_Preferences_JSON", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to MagneticModels.json.
        /// </summary>
        internal static string File_Name_Magnetic_Model_JSON {
            get {
                return ResourceManager.GetString("File_Name_Magnetic_Model_JSON", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to All Supported Coefficient Files (*.cof;*.dat)|*.cof;*.dat.
        /// </summary>
        internal static string File_Type_All_Coeff_Files {
            get {
                return ResourceManager.GetString("File_Type_All_Coeff_Files", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Text File  (Tab delimited) (*.txt)|*.txt.
        /// </summary>
        internal static string File_Type_Text_Tab {
            get {
                return ResourceManager.GetString("File_Type_Text_Tab", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to assets.
        /// </summary>
        internal static string Folder_Assets {
            get {
                return ResourceManager.GetString("Folder_Assets", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to coefficient.
        /// </summary>
        internal static string Folder_Coeffient {
            get {
                return ResourceManager.GetString("Folder_Coeffient", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to documentation.
        /// </summary>
        internal static string Folder_Documentation {
            get {
                return ResourceManager.GetString("Folder_Documentation", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Byte[].
        /// </summary>
        internal static byte[] IGRF12 {
            get {
                object obj = ResourceManager.GetObject("IGRF12", resourceCulture);
                return ((byte[])(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Byte[].
        /// </summary>
        internal static byte[] LICENSE {
            get {
                object obj = ResourceManager.GetObject("LICENSE", resourceCulture);
                return ((byte[])(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap Location_icon_16 {
            get {
                object obj = ResourceManager.GetObject("Location_icon_16", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Drawing.Icon similar to (Icon).
        /// </summary>
        internal static System.Drawing.Icon Magnet {
            get {
                object obj = ResourceManager.GetObject("Magnet", resourceCulture);
                return ((System.Drawing.Icon)(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Byte[].
        /// </summary>
        internal static byte[] README {
            get {
                object obj = ResourceManager.GetObject("README", resourceCulture);
                return ((byte[])(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Byte[].
        /// </summary>
        internal static byte[] WMM2015 {
            get {
                object obj = ResourceManager.GetObject("WMM2015", resourceCulture);
                return ((byte[])(obj));
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace App\Database;

use App\Controllers\StatsController;
use App\Errors\UserEvents;

class QueryBuilder extends Connection {

    /**
     * @var array
     * Possible query types
     */
    protected $queryTypes = [
        "select", "insert", "update", "delete", "truncate"
    ];

    /**
     * @var QueryCommands
     * QueryCommands instance
     */
    public $queryCommands;

    /**
     * @var string
     * Type of the query
     */
    public $queryType = "";

    /**
     * @var string
     * Final generated query to execution
     */
    public $resultQuery = "";

    /**
     * @var array
     * Query value bindings
     */
    public $queryBinds = [];

    /**
     * @var bool
     * First where
     */
    public $firstWhere = true;

    /**
     * @var mixed
     * Query output
     */
    public $output = "";

    /**
     * @var string
     * Get insert ID response
     */
    public $insertID = "";

    /**
     * QueryBuilder constructor.
     * Creates QueryCommands Instance
     */
    public function __construct() {

        // Create query and return instance
        $this->queryCommands = new QueryCommands($this);
        return $this;

    }

    /**
     * Prepares query for execution
     */
    public function execQuery() {

        if(empty($this->queryType) || !in_array($this->queryType, $this->queryTypes))
            new UserEvents(16);  // Invalid database query

        // Parse user input to the SQL Query
        $this->createQuery();

        // Execute
        $launcher = new QueryLauncher;
        $this->output = $launcher->launch($this, $this->queryCommands->getID);

        // Save insert ID into its variable
        if($this->queryCommands->getID)
            $this->insertID = $this->output;

    }

    /**
     * Creates SQL Query from user input
     */
    public function createQuery() {

        // Determine Query Type and create SQL Query
        switch($this->queryType) {
            case "select":
                // Create select query
                $this->createSelectQuery();
                break;
            case "insert":
                // Create insert query
                $this->createInsertQuery();
                break;
            case "update":
                // Create update query
                $this->createUpdateQuery();
                break;
            case "delete":
                // Create delete query
                $this->createDeleteQuery();
                break;
            case "truncate":
                // Create truncate query
                $this->createTruncateQuery();
                break;
            default:
                // Create Error > Undefined query type
                break;
        }

    }

    /**
     * Create Select type query
     */
    public function createSelectQuery() {

        /*
         * ---------- SELECT QUERY PROTOTYPE ----------
         * SELECT DISTINCT columns \w aggregates     OK
         * FROM table                                OK
         * JOINS table ON column1 = column2          OK
         * WHERE column = :param AND / OR / HAVING   OK
         * ORDER BY column                           OK
         * GROUP BY column                           OK
         * LIMITS / FIRST, OFFSETS                   OK
         */

        /*
         * Create Query
         */
        $query = "SELECT ";

        if($this->queryCommands->distinct)
            $query .= "DISTINCT ";

        $columns = implode(", ", $this->queryCommands->values);

        $separator = ", ";
        if(empty($columns))
            $separator = "";

        if(!empty($this->queryCommands->count)) {
            $columns .= $separator . "COUNT(" . $this->queryCommands->count . ") AS count";
            $separator = ", ";
        }

        if(!empty($this->queryCommands->max)) {
            $columns .= $separator . "MAX(" . $this->queryCommands->max . ")";
            $separator = ", ";
        }

        if(!empty($this->queryCommands->min)) {
            $columns .= $separator . "MIN(" . $this->queryCommands->min . ")";
            $separator = ", ";
        }

        if(!empty($this->queryCommands->average)) {
            $columns .= $separator . "AVG(" . $this->queryCommands->average . ")";
            $separator = ", ";
        }

        if(!empty($this->queryCommands->sum))
            $columns .= $separator . "SUM(" . $this->queryCommands->sum . ")";

        $query .= $columns . " ";

        $table = "FROM " . $this->queryCommands->table;

        $query .= $table . " ";
        $query .= $this->createJoins();

        $whereQuery = $this->createWhere();
        if($whereQuery !== "WHERE ")
            $query .= $whereQuery;

        $orderBy = $this->queryCommands->orderBy;
        $orderRandom = $this->queryCommands->orderRandom;
        $orderQuery = "";

        if(!empty($orderBy["column"]) && !$orderRandom) {

            $asc = "DESC ";
            if($orderBy['asc'])
                $asc = "ASC ";

            $orderQuery .= "ORDER BY " . $orderBy["column"] . " " . $asc;

        } else if($orderRandom && empty($orderBy["column"])) {

            // Random order
            $orderQuery .= "ORDER BY RAND() ";

        }

        $query .= $orderQuery;

        $groupBy = $this->queryCommands->groupBy;
        $groupQuery = "";

        if(!empty($groupBy["column"])) {

            $groupQuery = "GROUP BY :group ";
            $this->queryBinds[":group"] = $groupBy["column"];

        }

        $query .= $groupQuery;

        $limit = $this->queryCommands->limit;
        $first = $this->queryCommands->first;
        $offset = $this->queryCommands->offset;

        if($first)
            $limit = 1;

        if($limit > 0)
            $query .= "LIMIT " . $limit . " ";

        if($offset > 0)
            $query .= "OFFSET " . $offset . " ";

        // SELECT QUERY PREPARED
        $this->resultQuery = trim($query);

    }

    /**
     * Create Insert type query
     */
    public function createInsertQuery() {

        /*
         * ---------- INSERT QUERY PROTOTYPE ----------
         * INSERT INTO table (columns, ...)          OK
         * JOINS table ON column1 = column2          OK
         * VALUES (values, ...)                      OK
         */

        $query = "INSERT INTO ";

        $table = $this->queryCommands->table;
        $query .= $table . " ";

        $insert = $this->queryCommands->insert;
        $columns = [];
        $values = [];
        foreach($insert[0] as $row) {
            foreach($row as $column => $val) {
                $columns[] = $column;
                $values[] = $val;
            }
        }

        $columns = "(`" . implode("`, `", $columns) . "`) ";
        $i = 0;
        $binds = [];
        foreach($values as $value) {
            $binds[] = ":insert" . $i;
            $this->queryBinds[":insert" . $i] = $value;
            $i++;
        }

        $values = "(" . implode(", ", $binds) . ") ";

        $query .= $columns;

        $joins = $this->createJoins();
        $query .= $joins;

        $query .= "VALUES " . $values;
        $this->resultQuery = trim($query);

    }

    /**
     * Create Update type query
     */
    public function createUpdateQuery() {

        /*
         * ---------- UPDATE QUERY PROTOTYPE ----------
         * UPDATE table
         * JOINS table ON column1 = column2
         * SET column1 = value, ...
         * WHERE column1 = value AND / OR
         */

        $query = "UPDATE ";

        $table = $this->queryCommands->table;
        $query .= $table . " ";

        $joins = $this->createJoins();
        $query .= $joins;

        $query .= "SET ";

        $sets = "";
        $update = $this->queryCommands->update;
        $i = 0;
        foreach($update as $column => $value) {
            $sets .= $column . " = :update" . $i . ", ";
            $this->queryBinds[":update" . $i] = $value;
            $i++;
        }

        $sets = rtrim($sets, ", ") . " ";
        $query .= $sets;

        $where = $this->createWhere();
        $query .= $where;

        $this->resultQuery = $query;

    }

    /**
     * Create Delete type query
     */
    public function createDeleteQuery() {

        /*
        * ---------- DELETE QUERY PROTOTYPE ----------
        * DELETE FROM table
        * WHERE column1 = value AND / OR
        */

        $query = "DELETE FROM ";

        $table = $this->queryCommands->table;
        $query .= $table . " ";

        $where = $this->createWhere();
        $query .= $where;

        $query = trim($query);
        $this->resultQuery = $query;

    }

    /**
     * Create Truncate type query
     */
    public function createTruncateQuery() {

        /*
        * ---------- TRUNCATE QUERY PROTOTYPE ----------
        * TRUNCATE table
        */

        $query = "TRUNCATE " . $this->queryCommands->table;
        $this->resultQuery = $query;

    }

    /**
     * @return string
     * Create join clauses
     */
    public function createJoins() {

        $innerJoin = $this->queryCommands->innerJoin;
        $leftJoin = $this->queryCommands->leftJoin;
        $rightJoin = $this->queryCommands->rightJoin;

        $joins = "";

        if(!empty($innerJoin["tables"])) {

            foreach($innerJoin["tables"] as $key => $table)
                $joins .= "INNER JOIN " . $table . " ON " . $innerJoin["columns"][$key] . " = " . $innerJoin["keys"][$key] . " ";

        }

        if(!empty($leftJoin["tables"])) {

            foreach($leftJoin["tables"] as $key => $table) {

                $outer = "";
                if($leftJoin["outer"][0])
                    $outer = "OUTER ";

                $joins .= "LEFT " . $outer . "JOIN " . $table . " ON " . $leftJoin["columns"][$key] . " = " . $leftJoin["keys"][$key] . " ";

            }

        }

        if(!empty($rightJoin["tables"])) {

            foreach($rightJoin["tables"] as $key => $table) {

                $outer = "";
                if($rightJoin["outer"][0])
                    $outer = "OUTER ";

                $joins .= "RIGHT " . $outer . "JOIN " . $table . " ON " . $rightJoin["columns"][$key] . " = " . $rightJoin["keys"][$key] . " ";

            }

        }

        return $joins;

    }

    /**
     * @return string
     * Create where clauses
     */
    public function createWhere() {

        $whereQuery = "WHERE ";

        $where = $this->queryCommands->where;                   // OK
        $whereBetween = $this->queryCommands->whereBetween;     // OK
        $whereIn = $this->queryCommands->whereIn;               // OK
        $whereNull = $this->queryCommands->whereNull;           // OK
        $whereDate = $this->queryCommands->whereDate;           // OK
        $whereColumns = $this->queryCommands->whereColumns;     // OK
        $orWhere = $this->queryCommands->orWhere;               // OK
        $having = $this->queryCommands->having;                 // OK

        $and = false;
        if(!empty($where["columns"])) {

            foreach($where["columns"] as $key => $column) {

                $separator = "";
                if($and)
                    $separator = "AND ";

                $whereQuery .= $separator . "(`" . $column . "` " . $where["operators"][0][$key] . " :where" . $key . ") ";
                $this->queryBinds[":where" . $key] = $where["values"][$key];
                $and = true;

            }

        }

        if(!empty($whereBetween["column"])) {

            $separator = "";
            if($and)
                $separator = "AND ";

            if(!$whereBetween["invert"]) {

                $whereQuery .= $separator . "(`" . $whereBetween["column"] . "` BETWEEN :whereBetweenMin AND :whereBetweenMax) ";
                $this->queryBinds[":whereBetweenMin"] = $whereBetween["min"];
                $this->queryBinds[":whereBetweenMax"] = $whereBetween["max"];

            } else {

                $whereQuery .= $separator . "(`" . $whereBetween["column"] . "` < :whereBetweenMin OR " . $whereBetween["column"] . " > :whereBetweenMax) ";
                $this->queryBinds[":whereBetweenMin"] = $whereBetween["min"];
                $this->queryBinds[":whereBetweenMax"] = $whereBetween["max"];

            }

            $and = true;

        }

        if(!empty($whereIn["column"])) {

            $separator = "";
            if($and)
                $separator = "AND ";

            $invert = "";
            if($whereIn["invert"])
                $invert = " NOT";

            $values = "('" . implode("', '", $whereIn["values"]) . "') ";
            $whereQuery .= $separator . $whereIn["column"] . $invert . " IN " . $values;
            $and = true;

        }

        if(!empty($whereNull["column"])) {

            $separator = "";
            if($and)
                $separator = "AND ";

            $invert = "";
            if($whereNull["invert"])
                $invert = "NOT ";

            $whereQuery .= $separator . "(`" . $whereNull["column"] . "` IS " . $invert . "NULL) ";
            $and = true;

        }

        if(!empty($whereDate["type"])) {

            $separator = "";
            if($and)
                $separator = "AND ";

            $whereQuery .= $separator . strtoupper($whereDate["type"]) . "(`" . $whereDate["column"] . "` = :whereDate) ";

            $this->queryBinds[":whereDate"] = $whereDate["value"];
            $and = true;

        }

        if(!empty($whereColumns["columns"])) {

            foreach($whereColumns["columns"] as $key => $column) {

                $separator = "";
                if($and)
                    $separator = "AND ";

                $whereQuery .= $separator . "(`" . $column . "` " . $whereColumns["operators"][$key] . " :whereColumns" . $key . ") ";
                $this->queryBinds[":whereColumns" . $key] = $orWhere["values"][$key];
                $and = true;

            }

        }

        if(!empty($orWhere["columns"])) {

            $separator = "OR ";
            $and = true;

            foreach($orWhere["columns"] as $key => $column) {

                if(empty($separator))
                    $separator = "AND ";

                $whereQuery .= $separator . "(`" . $column . "` " . $orWhere["operators"][$key] . " :orWhere" . $key . ") ";
                $this->queryBinds[":orWhere" . $key] = $orWhere["values"][$key];

                $separator = "AND ";

            }

        }

        if(!empty($having["key"])) {

            $whereQuery .= "HAVING " . $having["key"] . " " . $having["operator"] . " :having ";
            $this->queryBinds[":having"] = $having["value"];

        }

        return $whereQuery;

    }

}


text:
package org.hisp.dhis.android.trackercapture.ui.rows.selectprogram;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import org.hisp.dhis.android.sdk.persistence.Dhis2Application;
import org.hisp.dhis.android.trackercapture.R;
import org.hisp.dhis.android.trackercapture.fragments.selectprogram.OnTrackedEntityColumnClick;
import org.hisp.dhis.android.trackercapture.ui.rows.upcomingevents.EventRowType;

/**
 * Created by erling on 5/8/15.
 */
public class TrackedEntityInstanceColumnNamesRow implements TrackedEntityInstanceRow
{
    private String mFirstItem;
    private String mSecondItem;
    private String mThirdItem;

    @Override
    public View getView(LayoutInflater inflater, View convertView, ViewGroup container) {
        View view;
        ViewHolder holder;

        if (convertView == null) {
            view = inflater.inflate(R.layout.listview_column_names_item, container, false);
            holder = new ViewHolder(
                    (TextView) view.findViewById(R.id.first_column_name),
                    (TextView) view.findViewById(R.id.second_column_name),
                    (TextView) view.findViewById(R.id.third_column_name),
                    (TextView) view.findViewById(R.id.status_column),
                    new OnInternalColumnRowClickListener()
            );
            view.setTag(holder);
        } else {
            view = convertView;
            holder = (ViewHolder) view.getTag();
        }

        holder.firstItem.setText(mFirstItem);
        holder.firstItem.setOnClickListener(holder.listener);
        holder.secondItem.setText(mSecondItem);
        holder.secondItem.setOnClickListener(holder.listener);
        holder.thirdItem.setText(mThirdItem);
        holder.thirdItem.setOnClickListener(holder.listener);
        holder.statusItem.setOnClickListener(holder.listener);

        return view;
    }

    @Override
    public int getViewType() {
        return EventRowType.COLUMN_NAMES_ROW.ordinal();
    }

    @Override
    public long getId() {
        return -1;
    }

    @Override
    public boolean isEnabled() {
        return false;
    }

    @Override
    public TrackedEntityInstanceItemRow getItemRow() {
        return null;
    }

    public void setSecondItem(String secondItem) {
        this.mSecondItem = secondItem;
    }

    public void setFirstItem(String firstItem) {
        this.mFirstItem = firstItem;
    }

    public void setThirdItem(String mThirdItem) {
        this.mThirdItem = mThirdItem;
    }

    private static class ViewHolder {
        public final TextView firstItem;
        public final TextView secondItem;
        public final TextView thirdItem;
        public final TextView statusItem;
        public final OnInternalColumnRowClickListener listener;

        private ViewHolder(TextView firstItem,
                           TextView secondItem,
                           TextView thirdItem,
                           TextView statusItem,
                           OnInternalColumnRowClickListener listener) {
            this.firstItem = firstItem;
            this.secondItem = secondItem;
            this.thirdItem = thirdItem;
            this.statusItem = statusItem;
            this.listener = listener;
        }
    }

    private static class OnInternalColumnRowClickListener implements View.OnClickListener
    {
        @Override
        public void onClick(View view)
        {
            if(view.getId() == R.id.first_column_name)
                    Dhis2Application.getEventBus().post(new OnTrackedEntityColumnClick(OnTrackedEntityColumnClick.FIRST_COLUMN));

            else if(view.getId() == R.id.second_column_name)
                    Dhis2Application.getEventBus().post(new OnTrackedEntityColumnClick(OnTrackedEntityColumnClick.SECOND_COLUMN));

            else if (view.getId() == R.id.third_column_name)
                    Dhis2Application.getEventBus().post(new OnTrackedEntityColumnClick(OnTrackedEntityColumnClick.THIRD_COLUMN));

            else if(view.getId() == R.id.status_column)
                    Dhis2Application.getEventBus().post(new OnTrackedEntityColumnClick(OnTrackedEntityColumnClick.STATUS_COLUMN));
        }

    }

}


text:
title: "Perjantain tunnille"
tags: läksyt rub12.5
---

Lue teksti 6 ja tee siiihen liittyvä aukkosuomennos työvihkon sivulta 12.

Jos haluat palautteen vikasta aineesta, palauta perjantaina, muuten maanantaina.

Huolehdi työvihkon s. 11 tehdyksi kurssin loppuun mennessä.


text:
module Api
  module Docs
    module Models
      class OutputBug
        # :nocov:
        include Swagger::Blocks

        swagger_schema :OutputBug do
          key :required, [:bug_id, :bug_status, :resolution, :bug_severity,
                          :product, :component, :assigned_to, :reporter,
                          :short_desc, :created_at, :updated_at]
          property :bug_id do
            key :type, :integer
            key :format, :int64
            key :description, 'Bug ID from bugzilla.altlinux.org'
          end
          property :bug_status do
            key :type, :string
            key :description, 'Bug status'
          end
          property :resolution do
            key :type, :string
            key :description, 'Bug resolution'
          end
          property :bug_severity do
            key :type, :string
            key :description, 'Bug severity'
          end
          property :product do
            key :type, :string
            key :description, 'Bug product'
          end
          property :component do
            key :type, :string
            key :description, 'Bug component'
          end
          property :assigned_to do
            key :type, :string
            key :description, 'Bug assigned to'
          end
          property :reporter do
            key :type, :string
            key :description, 'Bug reporter'
          end
          property :short_desc do
            key :type, :string
            key :description, 'Bug short description'
          end
          property :created_at do
            key :type, :string
            key :format, :'date-time'
            key :description, 'Created at in ISO8601 format'
          end
          property :updated_at do
            key :type, :string
            key :format, :'date-time'
            key :description, 'Updated at in ISO8601 format'
          end
        end
        # :nocov:
      end
    end
  end
end


text:
#include "OVR_OSX_Display.h"
#include "Kernel/OVR_Log.h"

#include <ApplicationServices/ApplicationServices.h>
#include <CoreFoundation/CoreFoundation.h>
#include <CoreFoundation/CFString.h>
#include <IOKit/graphics/IOGraphicsLib.h>

//-------------------------------------------------------------------------------------
// ***** Display enumeration Helpers

namespace OVR {

// FIXME Code duplication with windows.
#define EDID_LENGTH                             0x80

#define EDID_HEADER                             0x00
#define EDID_HEADER_END                         0x07

#define ID_MANUFACTURER_NAME                    0x08
#define ID_MANUFACTURER_NAME_END                0x09

#define EDID_STRUCT_VERSION                     0x12
#define EDID_STRUCT_REVISION                    0x13

#define ESTABLISHED_TIMING_1                    0x23
#define ESTABLISHED_TIMING_2                    0x24
#define MANUFACTURERS_TIMINGS                   0x25

#define DETAILED_TIMING_DESCRIPTIONS_START      0x36
#define DETAILED_TIMING_DESCRIPTION_SIZE        18
#define NO_DETAILED_TIMING_DESCRIPTIONS         4

#define DETAILED_TIMING_DESCRIPTION_1           0x36
#define DETAILED_TIMING_DESCRIPTION_2           0x48
#define DETAILED_TIMING_DESCRIPTION_3           0x5a
#define DETAILED_TIMING_DESCRIPTION_4           0x6c

#define MONITOR_NAME            0xfc
#define MONITOR_LIMITS          0xfd
#define MONITOR_SERIAL			0xff

#define UNKNOWN_DESCRIPTOR      -1
#define DETAILED_TIMING_BLOCK   -2

#define DESCRIPTOR_DATA         5

const UByte edid_v1_header[] = { 0x00, 0xff, 0xff, 0xff,
	                            0xff, 0xff, 0xff, 0x00 };

const UByte edid_v1_descriptor_flag[] = { 0x00, 0x00 };

// FIXME Code duplication with windows. Refactor.
static int blockType( UByte* block )
{
	if ( !strncmp( (const char*)edid_v1_descriptor_flag, (const char*)block, 2 ) )
	{
		// descriptor
		if ( block[ 2 ] != 0 )
			return UNKNOWN_DESCRIPTOR;
		return block[ 3 ];
	}
    else
    {
		return DETAILED_TIMING_BLOCK;
	}
}

static char* getMonitorName( UByte const* block )
{
	static char name[ 13 ];
	unsigned    i;
	UByte const* ptr = block + DESCRIPTOR_DATA;

	for( i = 0; i < 13; i++, ptr++ )
	{
		if ( *ptr == 0xa )
		{
			name[ i ] = 0;
			return name;
		}

		name[ i ] = *ptr;
	}

	return name;
}

// FIXME Code duplication with windows. Refactor.
static bool parseEdid( UByte* edid, OVR::OSX::DisplayEDID& edidResult )
{
    unsigned i;
    UByte* block;
    const char* monitor_name = "Unknown";
    UByte checksum = 0;

    for( i = 0; i < EDID_LENGTH; i++ )
        checksum += edid[ i ];

    // Bad checksum, fail EDID
    if (  checksum != 0  )
        return false;

    if ( strncmp( (const char*)edid+EDID_HEADER, (const char*)edid_v1_header, EDID_HEADER_END+1 ) )
    {
        // First bytes don't match EDID version 1 header
        return false;
    }

    // OVR_DEBUG_LOG_TEXT(( "\n# EDID version %d revision %d\n",
    //                     (int)edid[EDID_STRUCT_VERSION],(int)edid[EDID_STRUCT_REVISION] ));

    // Monitor name and timings

    char serialNumber[14];
    memset( serialNumber, 0, 14 );

    block = edid + DETAILED_TIMING_DESCRIPTIONS_START;

    for( i = 0; i < NO_DETAILED_TIMING_DESCRIPTIONS; i++,
        block += DETAILED_TIMING_DESCRIPTION_SIZE )
    {

        if ( blockType( block ) == MONITOR_NAME )
        {
            monitor_name = getMonitorName( block );
        }

        if( blockType( block ) == MONITOR_SERIAL )
        {
            memcpy( serialNumber, block + 5, 13 );
            break;
        }
    }

    UByte vendorString[4] = {0};

    vendorString[0] = (edid[8] >> 2 & 31) + 64;
    vendorString[1] = ((edid[8] & 3) << 3) | (edid[9] >> 5) + 64;
    vendorString[2] = (edid[9] & 31) + 64;

    edidResult.ModelNumber  = *(UInt16*)&edid[10];
    edidResult.MonitorName  = OVR::String(monitor_name);
    edidResult.VendorName   = OVR::String((const char*)vendorString);
    edidResult.SerialNumber = OVR::String(serialNumber);

    // printf( "\tIdentifier \"%s\"\n", monitor_name );
    // printf( "\tVendorName \"%s\"\n", vendorString );
    // printf( "\tModelName \"%s\"\n", monitor_name );
    // printf( "\tModelNumber %d\n", edidResult.ModelNumber );
    // printf( "\tSerialNumber \"%s\"\n", edidResult.SerialNumber.ToCStr() );

    // FIXME: Get timings as well, though they aren't very useful here
    // except for the vertical refresh rate, presumably

    return true;
}

static int discoverExtendedRifts(OVR::OSX::DisplayDesc* descriptorArray, int inputArraySize, bool edidInfo)
{
    OVR_UNUSED(edidInfo);
    int result = 0;

    static bool reportDiscovery = true;
    OVR_UNUSED(reportDiscovery);

    CGDirectDisplayID Displays[32];
    uint32_t NDisplays = 0;
    CGGetOnlineDisplayList(32, Displays, &NDisplays);

    for (unsigned int i = 0; i < NDisplays; i++)
    {
        CGDirectDisplayID dispId = Displays[i];

        io_service_t port = CGDisplayIOServicePort(dispId);
        CFDictionaryRef DispInfo = IODisplayCreateInfoDictionary(port, kNilOptions);

        // Display[i]

        uint32_t vendor = CGDisplayVendorNumber(dispId);
        uint32_t product = CGDisplayModelNumber(dispId);

        CGRect desktop = CGDisplayBounds(dispId);
        Vector2i desktopOffset(desktop.origin.x, desktop.origin.y);

        if (vendor == 16082 && ( (product == 1)||(product == 2)||(product == 3) ) ) // 7" or HD
        {
            if( result >= inputArraySize )
            {
                CFRelease(DispInfo);
                return result;
            }

            int width  = static_cast<int>(CGDisplayPixelsWide(dispId));
            int height = static_cast<int>(CGDisplayPixelsHigh(dispId));
            Sizei monitorResolution(width, height);

            // Obtain and parse EDID data.
            CFDataRef data =
                (CFDataRef)CFDictionaryGetValue(DispInfo, CFSTR(kIODisplayEDIDKey));
            if (!data)
            {
                CFRelease(DispInfo);
                OVR::LogError("[OSX Display] Unable to obtain EDID for Oculus product %d", product);
                continue;
            }
            UByte* edid = (UByte*)CFDataGetBytePtr(data);
            OSX::DisplayEDID edidResult;
            parseEdid( edid, edidResult );

            OVR::OSX::DisplayDesc& desc = descriptorArray[result++];
            desc.DisplayID                  = dispId;
            desc.ModelName                  = edidResult.MonitorName;   // User friendly string.
            desc.EdidSerialNumber           = edidResult.SerialNumber;
            desc.LogicalResolutionInPixels  = monitorResolution;
            desc.NativeResolutionInPixels   = monitorResolution;
            desc.DesktopDisplayOffset       = desktopOffset;
            desc.Rotation                   = 0;

            auto roughEqual = [](double a, double b) -> bool
            {
                return fabs(a - b) < 1.0;
            };

            switch (product)
            {
                    case 3: desc.DeviceTypeGuess = HmdType_DK2;       break;
                    case 2: desc.DeviceTypeGuess = HmdType_DKHDProto; break;
                    case 1: desc.DeviceTypeGuess = HmdType_DK1;       break;

                default:
                    case 0: desc.DeviceTypeGuess = HmdType_Unknown;   break;
            }

            bool portraitDevice = (desc.DeviceTypeGuess == HmdType_DK2);
            double rotation = fabs(CGDisplayRotation(dispId));
            if (roughEqual(rotation, 0))
            {
                desc.Rotation = portraitDevice ? 270 : 0;
            }
            else if (roughEqual(rotation, 90))
            {
                desc.Rotation = portraitDevice ? 0 : 90;
            }
            else if (roughEqual(rotation, 180))
            {
                desc.Rotation = portraitDevice ? 90 : 180;
            }
            else if (roughEqual(rotation, 270))
            {
                desc.Rotation = portraitDevice ? 180 : 270;
            }

            // Hard-coded defaults in case the device doesn't have the data itself.
            // DK2 prototypes (0003) or DK HD Prototypes (0002)
            if (product == 3 || product == 2)
            {
                desc.LogicalResolutionInPixels  = Sizei(1920, 1080);
                desc.NativeResolutionInPixels   = Sizei(1080, 1920);
            }
            else
            {
                desc.LogicalResolutionInPixels  = monitorResolution;
                desc.NativeResolutionInPixels   = monitorResolution;
            }

            //OVR_DEBUG_LOG_TEXT(("Display Found %x:%x\n", vendor, product));
        }
        CFRelease(DispInfo);
    }

    return result;
}

//-------------------------------------------------------------------------------------
// ***** Display

bool Display::Initialize()
{
    // Nothing to initialize. OS X only supports compatibility mode.
    return true;
}

void Display::Shutdown()
{
}

bool Display::GetDriverMode(bool& driverInstalled, bool& compatMode, bool& hideDK1Mode)
{
    driverInstalled = false;
    compatMode = true;
    hideDK1Mode = false;
    return true;
}

bool Display::SetDriverMode(bool /*compatMode*/, bool /*hideDK1Mode*/)
{
    return false;
}

DisplaySearchHandle* Display::GetDisplaySearchHandle()
{
	return new OSX::OSXDisplaySearchHandle();
}

bool Display::InCompatibilityMode( bool displaySearch )
{
	OVR_UNUSED( displaySearch );
    return true;
}

int Display::GetDisplayCount( DisplaySearchHandle* handle, bool extended, bool applicationOnly, bool edidInfo )
{
    OVR_UNUSED(applicationOnly);

	static int extendedCount = -1;

	OSX::OSXDisplaySearchHandle* localHandle = (OSX::OSXDisplaySearchHandle*)handle;
    if (localHandle == NULL)
    {
        OVR::LogError("[OSX Display] No search handle passed into GetDisplayCount. Return 0 rifts.");
        return 0;
    }

    if (extendedCount == -1 || extended)
    {
        extendedCount = discoverExtendedRifts(localHandle->cachedDescriptorArray, OSX::OSXDisplaySearchHandle::DescArraySize, edidInfo);
    }

	localHandle->extended = true;
	localHandle->extendedDisplayCount = extendedCount;
	int totalCount = extendedCount;

    /// FIXME: Implement application mode for OS X.
    localHandle->application = false;
    localHandle->applicationDisplayCount = 0;

    localHandle->displayCount = totalCount;

    return totalCount;
}

Ptr<Display> Display::GetDisplay( int index, DisplaySearchHandle* handle )
{
    Ptr<Display> result = NULL;

    if (index < 0)
    {
        OVR::LogError("[OSX Display] Invalid index given to GetDisplay.");
        return NULL;
    }

	OSX::OSXDisplaySearchHandle* localHandle = (OSX::OSXDisplaySearchHandle*)handle;
    if (localHandle == NULL)
    {
        OVR::LogError("[OSX Display] No search handle passed into GetDisplay. Return 0 rifts.");
        return NULL;
    }

    if (localHandle->extended)
    {
        if (index >= 0 && index < (int)localHandle->extendedDisplayCount)
        {
            return *new OSX::OSXDisplayGeneric(localHandle->cachedDescriptorArray[index]);
        }

        // index -= localHandle->extendedDisplayCount;
    }

    if (localHandle->application)
    {
        OVR::LogError("[OSX Display] Mac does not support application displays.");
    }

    return result;
}
} // namespace OVR


text:
using UnityEngine;
using UnityEditor;

namespace Klak.Wiring
{
    [CanEditMultipleObjects]
    [CustomEditor(typeof(Noise))]
    public class NoiseEditor : Editor
    {
        SerializedProperty _frequency;
        SerializedProperty _octaves;
        SerializedProperty _bias;
        SerializedProperty _amplitude;
        SerializedProperty _outputEvent;

        void OnEnable()
        {
            _frequency = serializedObject.FindProperty("_frequency");
            _octaves = serializedObject.FindProperty("_octaves");
            _bias = serializedObject.FindProperty("_bias");
            _amplitude = serializedObject.FindProperty("_amplitude");
            _outputEvent = serializedObject.FindProperty("_outputEvent");
        }

        public override void OnInspectorGUI()
        {
            serializedObject.Update();

            EditorGUILayout.PropertyField(_frequency);
            EditorGUILayout.PropertyField(_octaves);

            EditorGUILayout.Space();

            EditorGUILayout.PropertyField(_bias);
            EditorGUILayout.PropertyField(_amplitude);

            EditorGUILayout.Space();

            EditorGUILayout.HelpBox(
                "Output = (Noise + Bias) * Amplitude",
                MessageType.None, true
            );

            EditorGUILayout.Space();

            EditorGUILayout.PropertyField(_outputEvent);

            serializedObject.ApplyModifiedProperties();
        }
    }
}


text:
layout: post
title: Qualifying Exam
filePath: 20170924-qualifyingExam.jpg
tags: [mike, siyan, thisacademiclife]
description: Mike actually passed it last year on the first try. It took me 2 times though...
---


text:
#ifndef TENSORFLOW_STREAM_EXECUTOR_ROCM_ROCM_PLATFORM_H_
#define TENSORFLOW_STREAM_EXECUTOR_ROCM_ROCM_PLATFORM_H_

#include <memory>
#include <vector>

#include "absl/synchronization/mutex.h"
#include "tensorflow/core/platform/thread_annotations.h"
#include "tensorflow/stream_executor/executor_cache.h"
#include "tensorflow/stream_executor/lib/statusor.h"
#include "tensorflow/stream_executor/multi_platform_manager.h"
#include "tensorflow/stream_executor/platform.h"
#include "tensorflow/stream_executor/platform/port.h"
#include "tensorflow/stream_executor/stream_executor_internal.h"
#include "tensorflow/stream_executor/stream_executor_pimpl.h"
#include "tensorflow/stream_executor/trace_listener.h"

namespace stream_executor {
namespace gpu {

// Opaque and unique identifier for the ROCM platform plugin.
// This is needed so that plugins can refer to/identify this platform without
// instantiating a ROCmPlatform object.
extern const Platform::Id kROCmPlatformId;

// ROCm-specific platform plugin, registered as a singleton value via module
// initializer.
class ROCmPlatform : public Platform {
 public:
  ROCmPlatform();
  ~ROCmPlatform() override;

  // ROCmPlatform-specific functionality
  // Returns the number of distinct buses / NUMA nodes on the machine.
  int BusCount();

  // Returns the bus/NUMA node for the specified device ordinal.
  int DeviceToBus(int device_ordinal);

  // Returns the lowest-ordinal-number StreamExecutor on the specified bus.
  port::StatusOr<StreamExecutor*> FirstExecutorForBus(int bus_ordinal);

  // Platform interface implementation:
  // Returns the same value as kROCmPlatform above.
  Platform::Id id() const override;

  // Returns -1 as a sentinel on internal failure (and logs the error).
  int VisibleDeviceCount() const override;

  const string& Name() const override;

  port::StatusOr<std::unique_ptr<DeviceDescription>> DescriptionForDevice(
      int ordinal) const override;

  port::StatusOr<StreamExecutor*> ExecutorForDevice(int ordinal) override;

  port::StatusOr<StreamExecutor*> ExecutorForDeviceWithPluginConfig(
      int ordinal, const PluginConfig& config) override;

  port::StatusOr<StreamExecutor*> GetExecutor(
      const StreamExecutorConfig& config) override;

  port::StatusOr<std::unique_ptr<StreamExecutor>> GetUncachedExecutor(
      const StreamExecutorConfig& config) override;

  void RegisterTraceListener(std::unique_ptr<TraceListener> listener) override;

  void UnregisterTraceListener(TraceListener* listener) override;

 private:
  // Determines the number of NUMA nodes and the assignment of executor to each.
  void InspectNumaNodes();

  // This platform's name.
  string name_;

  // mutex that guards internal state.
  mutable absl::Mutex mu_;

  // Cache of created executors.
  ExecutorCache executor_cache_;

  // The smallest NUMA node value for any device managed by this machine
  // manager. Used, along with limit_numa_node_, to convert NUMA nodes into bus
  // ordinals. The NUMA node space occupied by GPUs is assumed to be dense./
  int min_numa_node_;

  // Larger than the NUMA node value for any device managed by this machine
  // manager.
  int limit_numa_node_;

  SE_DISALLOW_COPY_AND_ASSIGN(ROCmPlatform);
};

}  // namespace gpu
}  // namespace stream_executor

#endif  // TENSORFLOW_STREAM_EXECUTOR_ROCM_ROCM_PLATFORM_H_


text: from designatedashboard.api import designate  # noqa