text:
import React, {Component, PropTypes} from "react";
import {Surface} from "gl-react-dom";
import ImageEffects from "./ImageEffects";

const vdomForContent = ({ uri, mainType, type }, onLoadSize) =>
  mainType === "video" ?
  <video loop autoPlay onLoad={e => onLoadSize(e.target.videoWidth, e.target.videoHeight)}>
    <source type={type} src={uri} />
  </video> :
  uri ?
   onLoadSize(e.target.width, e.target.height)} /> :
  uri;

const contentForDropEvent = e => {
  const file = e.dataTransfer.files[0];
  if (file) {
    return {
      uri: URL.createObjectURL(file),
      type: file.type,
      mainType: file.type.split("/")[0]
    };
  }
  const text = e.dataTransfer.getData("text");
  if (text && text.match(/http[s]?:\/\//)) {
    return { uri: text };
  }
  return { uri: null };
};

const styles = {
  dropDescr: {
    opacity: 0.3,
    fontStyle: "italic"
  },
  links: {
    paddingTop: 10
  },
  link: {
    color: "#09F",
    fontSize: "0.8em",
    marginRight: 4
  }
};

const width = 400;
const height = 300;

export default class Viewport extends Component {

  constructor (props) {
    super(props);
  }

  onDrop = e => {
    const { onLoadNewContent } = this.props;
    e.preventDefault();
    e.stopPropagation();
    onLoadNewContent(contentForDropEvent(e));
  };

  onDragEnter = e => {
    e.preventDefault();
    e.stopPropagation();
  };

  onDragOver = e => {
    e.preventDefault();
    e.stopPropagation();
  };

  onLoadSize = (width, height) => {
    const { content, onLoadNewContent } = this.props;
    onLoadNewContent({ ...content, width, height });
  };

  onClickUrl = e => {
    const { onLoadNewContent } = this.props;
    e.preventDefault();
    onLoadNewContent({ uri: e.target.href });
  };

  captureFrame = opts =>
    this.refs.surface.captureFrame(opts);

  render () {
    const {
      onDrop,
      onDragOver,
      onDragEnter,
      onLoadSize,
      onClickUrl,
      props: { content, effects }
    } = this;
    let w = width, h = height;
    const ratio = content.width && content.height ? content.height/content.width : 1;
    if (ratio < 1)
      h = w * ratio;
    else
      w = h / ratio;

    return

        <Surface ref="surface" width={w} height={h} autoRedraw={content.mainType === "video"} opaque={false}>
          <ImageEffects width={w} height={h} {...effects}>
            {vdomForContent(content, onLoadSize)}
          </ImageEffects>
        </Surface>

^ Drop here an Image, Video or Image URL...

{
        "wxqlQkh,G2Whuq3,0bUSEBX,giP58XN,8OdPTjK,iKdXwVm,IvpoR40,zJIxPEo,CKlmtPs,fnMylHI,vGXYiYy,MnOB9Le,YqsZKgc,0BJobQo,Otbz312".split(",")
        .map(id => <a
          onClick={onClickUrl}
          href={`http://i.imgur.com/${id}.jpg`}
          target="_blank"
          style={styles.link}>{id} )
      }

;
  }
}

Viewport.propTypes = {
  content: PropTypes.object.isRequired,
  effects: PropTypes.object.isRequired,
  onLoadNewContent: PropTypes.func.isRequired
};

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace JHWEB\GrupoBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Grupo
 *
 * @ORM\Table(name="grupo")
 * @ORM\Entity
 */
class Grupo
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="detalle", type="text")
     */
    private $detalle;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="fecha", type="date")
     */
    private $fecha;

    /**
     * @ORM\ManyToMany(targetEntity="JHWEB\UsuarioBundle\Entity\Usuario", inversedBy="grupos")
     * @ORM\JoinTable(name="usuarios_grupos")
     */
    private $usuarios;

    public function __construct() {
        $this->usuarios = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set detalle
     *
     * @param string $detalle
     * @return Grupo
     */
    public function setDetalle($detalle)
    {
        $this->detalle = $detalle;

        return $this;
    }

    /**
     * Get detalle
     *
     * @return string
     */
    public function getDetalle()
    {
        return $this->detalle;
    }

    /**
     * Set fecha
     *
     * @param \DateTime $fecha
     * @return Grupo
     */
    public function setFecha($fecha)
    {
        $this->fecha = $fecha;

        return $this;
    }

    /**
     * Get fecha
     *
     * @return \DateTime
     */
    public function getFecha()
    {
        return $this->fecha;
    }

    /**
     * Add usuarios
     *
     * @param \JHWEB\UsuarioBundle\Entity\Usuario $usuarios
     * @return Grupo
     */
    public function addUsuario(\JHWEB\UsuarioBundle\Entity\Usuario $usuarios)
    {
        $this->usuarios[] = $usuarios;

        return $this;
    }

    /**
     * Remove usuarios
     *
     * @param \JHWEB\UsuarioBundle\Entity\Usuario $usuarios
     */
    public function removeUsuario(\JHWEB\UsuarioBundle\Entity\Usuario $usuarios)
    {
        $this->usuarios->removeElement($usuarios);
    }

    /**
     * Get usuarios
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getUsuarios()
    {
        return $this->usuarios;
    }
}


text:
import { Component, Inject } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';

export class State {
    constructor(public name: string,
                public population: string,
                public flag: string) {
    }
}

@Component({
    selector: 'jhi-dialog',
    templateUrl: './dialog.component.html',
})
export class DialogComponent{

    constructor(
                public dialogRef: MatDialogRef<DialogComponent>,
                @Inject(MAT_DIALOG_DATA) public data: any) {}

    onNoClick(): void {
        this.dialogRef.close();
    }

}


text:
package com.ibm.couchdb.implicits

import com.ibm.couchdb.spec.Fixtures
import org.http4s.Status
import org.specs2.mutable._
import org.specs2.specification.AllExpectations
import upickle.default.Aliases.{R, W}
import upickle.default.{read => pickleR, write => pickleW}

class UpickleImplicitsSpec extends Specification
    with AllExpectations
    with Fixtures
    with UpickleImplicits {

  val map0  = Map[String, String]()
  val json0 = "{}"

  val map1  = Map[String, String]("key1" -> "val1", "key2" -> "val2")
  val json1 = "{\"key1\":\"val1\",\"key2\":\"val2\"}"

  val map2  = Map[String, Int]("key1" -> 1, "key2" -> 2)
  val json2 = "{\"key1\":1,\"key2\":2}"

  val map3  = Map[String, (String, Int)]("key1" -> (("key1", 1)), "key2" -> (("key2", 2)))
  val json3 = "{\"key1\":[\"key1\",1],\"key2\":[\"key2\",2]}"

  val map4  = Map[String, FixPerson](
    "key1" -> FixPerson("Alice", 25), "key2" -> FixPerson("Bob", 30))
  val json4 = "{\"key1\":{\"name\":\"Alice\",\"age\":25},\"key2\":{\"name\":\"Bob\",\"age\":30}}"

  private def testRoundtrip[D](obj: D)(implicit r: R[D], w: W[D]) = {
    pickleR[D](pickleW(obj)) mustEqual obj
  }

  "Custom upickle Reader and Writer instances" >> {

    "Write and read Map[String, D]" >> {
      pickleW(map0) mustEqual json0
      pickleW(map1) mustEqual json1
      pickleW(map2) mustEqual json2
      pickleW(map3) mustEqual json3
      pickleW(map4) mustEqual json4
    }

    "Read Map[String, D] from JSON" >> {
      pickleR[Map[String, String]](json0) mustEqual map0
      pickleR[Map[String, String]](json1) mustEqual map1
      pickleR[Map[String, Int]](json2) mustEqual map2
      pickleR[Map[String, (String, Int)]](json3) mustEqual map3
      pickleR[Map[String, FixPerson]](json4) mustEqual map4
    }

    "Write and read an Status" >> {
      testRoundtrip[Status](Status.Ok)
    }
  }
}


text:
package ie.rkie.sm.db;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

/**
 * A player represents the link between a user and a game. The playOrder
 * property allows the controller to know which player has the next move.
 */
@Entity
@Table(name="players")
public class Player {

	@Id
	@GeneratedValue
	private Integer id;

	@ManyToOne
	@JoinColumn(name="gid")
	private Game game;

	@ManyToOne
	@JoinColumn(name="username")
	private User user;

	private int playOrder;

	public Player() {
		super();
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public Game getGame() {
		return game;
	}

	public void setGame(Game game) {
		this.game = game;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public int getPlayOrder() {
		return playOrder;
	}

	public void setPlayOrder(int playOrder) {
		this.playOrder = playOrder;
	}

}


text:
@interface FPActivityView : UIView

- (id)initWithFrame:(CGRect)frame andActivityBar:(UIImage*)image;

-(void)start;
-(void)stop;

@end


text: <script src="iframe.js"></script>


text:
/**
 * @fileOverview
 * instance controls from native
 *
 * - fire event
 * - callback
 * - refresh
 * - destroy
 *
 * corresponded with the API of instance manager (framework.js)
 */
import { extend, typof } from '../../util/index'

/**
 * Refresh an app with data to its root component options.
 * @param  {object} app
 * @param  {any}    data
 */
export function refresh (app, data) {
  console.debug(`[JS Framework] Refresh with`, data, `in instance[${app.id}]`)
  const vm = app.vm
  if (vm && data) {
    if (typeof vm.refreshData === 'function') {
      vm.refreshData(data)
    }
    else {
      extend(vm, data)
    }
    app.differ.flush()
    app.doc.taskCenter.send('dom', { action: 'refreshFinish' }, [])
    return
  }
  return new Error(`invalid data "${data}"`)
}

/**
 * Destroy an app.
 * @param  {object} app
 */
export function destroy (app) {
  console.debug(`[JS Framework] Destory an instance(${app.id})`)

  if (app.vm) {
    destroyVm(app.vm)
  }

  app.id = ''
  app.options = null
  app.blocks = null
  app.vm = null
  app.doc.taskCenter.destroyCallback()
  app.doc.destroy()
  app.doc = null
  app.customComponentMap = null
  app.commonModules = null
}

/**
 * Destroy an Vm.
 * @param {object} vm
 */
export function destroyVm (vm) {
  delete vm._app
  delete vm._computed
  delete vm._css
  delete vm._data
  delete vm._ids
  delete vm._methods
  delete vm._options
  delete vm._parent
  delete vm._parentEl
  delete vm._rootEl

  // remove all watchers
  if (vm._watchers) {
    let watcherCount = vm._watchers.length
    while (watcherCount--) {
      vm._watchers[watcherCount].teardown()
    }
    delete vm._watchers
  }

  // destroy child vms recursively
  if (vm._childrenVms) {
    let vmCount = vm._childrenVms.length
    while (vmCount--) {
      destroyVm(vm._childrenVms[vmCount])
    }
    delete vm._childrenVms
  }

  console.debug(`[JS Framework] "destroyed" lifecycle in Vm(${vm._type})`)
  vm.$emit('hook:destroyed')

  delete vm._type
  delete vm._vmEvents
}

/**
 * Get a JSON object to describe the document body.
 * @param  {object} app
 * @return {object}
 */
export function getRootElement (app) {
  const doc = app.doc || {}
  const body = doc.body || {}
  return body.toJSON ? body.toJSON() : {}
}

/**
 * Fire an event from renderer. The event has type, an event object and an
 * element ref. If the event comes with some virtual-DOM changes, it should
 * have one more parameter to describe the changes.
 * @param  {object} app
 * @param  {string} ref
 * @param  {type}   type
 * @param  {object} e
 * @param  {object} domChanges
 */
export function fireEvent (app, ref, type, e, domChanges) {
  console.debug(`[JS Framework] Fire a "${type}" event on an element(${ref}) in instance(${app.id})`)
  if (Array.isArray(ref)) {
    ref.some((ref) => {
      return fireEvent(app, ref, type, e) !== false
    })
    return
  }
  const el = app.doc.getRef(ref)
  if (el) {
    const result = app.doc.fireEvent(el, type, e, domChanges)
    app.differ.flush()
    app.doc.taskCenter.send('dom', { action: 'updateFinish' }, [])
    return result
  }
  return new Error(`invalid element reference "${ref}"`)
}

/**
 * Make a callback for a certain app.
 * @param  {object}   app
 * @param  {number}   callbackId
 * @param  {any}      data
 * @param  {boolean}  ifKeepAlive
 */
export function callback (app, callbackId, data, ifKeepAlive) {
  console.debug(`[JS Framework] Invoke a callback(${callbackId}) with`, data, `in instance(${app.id})`)
  const result = app.doc.taskCenter.callback(callbackId, data, ifKeepAlive)
  updateActions(app)
  app.doc.taskCenter.send('dom', { action: 'updateFinish' }, [])
  return result
}

/**
 * Collect all virtual-DOM mutations together and send them to renderer.
 * @param  {object} app
 */
export function updateActions (app) {
  app.differ.flush()
}

/**
 * Call all tasks from an app to renderer (native).
 * @param  {object} app
 * @param  {array}  tasks
 */
export function callTasks (app, tasks) {
  let result

  /* istanbul ignore next */
  if (typof(tasks) !== 'array') {
    tasks = [tasks]
  }

  tasks.forEach(task => {
    result = app.doc.taskCenter.send(
      'module',
      {
        module: task.module,
        method: task.method
      },
      task.args
    )
  })

  return result
}


text:
package com.microsoft.windowsazure.mobileservices.zumoe2etestapp;

public class Constants {
    public static final String PREFERENCE_MOBILE_SERVICE_URL = "pref_mobile_service_url";

    public static final String PREFERENCE_CONTAINER_URL = "pref_storage_container_url";

    public static final String PREFERENCE_BASE64_TOKEN = "pref_storage_base64_token";

    public static final String PREFERENCE_RUNTIME_VERSION = "pref_runtime_version";

}


text:
from datetime import date

#Core Django Imports
from django import forms
from django.forms.models import inlineformset_factory
#Third Party apps imports

#Imports local apps
from .models import Menu, MenuItems, UserSelectedLunch, Subscribers

class MenuForm(forms.ModelForm):
	day = forms.DateField(label='Menu date', input_formats=['%d-%m-%Y'])

	class Meta:
		model = Menu
		fields = '__all__'

MenuItemsFormSet = inlineformset_factory(Menu, MenuItems, fields=('name','menu',))

class MenuSelectForm(forms.ModelForm):

	class Meta:
		model = UserSelectedLunch
		fields = '__all__'

class SubscribersForm(forms.ModelForm):

	class Meta:
		model = Subscribers
		fields = '__all__'


text:
Arrow Function

class City{
  constructor(name){
    this.name = name;
  }
  createStreet(streetName){
    let addresses = [1,2,3].map((address) => {
      return `${address} ${streetName} ${this.name}`
    })

    return addresses
  }
}

const city = new City("Tomville")
console.log(city.createStreet("Main St."))
//["1 Main St. Tomville", "2 Main St. Tomville", "3 Main St. Tomville"]

shorter syntax

multiple lines you must use brackets

this is equal to the outer this


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest
    package="com.xargsgrep.portknocker"
    xmlns:android="http://schemas.android.com/apk/res/android"
    >

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme"
        android:allowBackup="true"
        >

        <activity
            android:name=".activity.HostListActivity"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
            <intent-filter android:label="@string/app_name">
                <action android:name="android.intent.action.VIEW" />
                <action android:name="android.intent.action.EDIT" />
                <category android:name="android.intent.category.DEFAULT" />
                <data android:scheme="file"/>
                <data android:mimeType="application/octet-stream"/>
                <data android:mimeType="application/json" />
            </intent-filter>
            <intent-filter android:label="@string/app_name">
                <action android:name="android.intent.action.VIEW" />
                <action android:name="android.intent.action.EDIT" />
                <category android:name="android.intent.category.DEFAULT" />
                <data android:scheme="content"/>
                <data android:mimeType="application/octet-stream"/>
                <data android:mimeType="application/json"/>
            </intent-filter>
        </activity>

        <activity
            android:name=".activity.EditHostActivity"
            android:label="@string/app_name"
            />

        <activity
            android:name=".activity.SettingsActivity"
            android:label="@string/app_name"
            />

        <activity
            android:name=".activity.SettingsActivityCompat"
            android:label="@string/app_name"
            />

        <activity android:name=".widget.ConfigureWidgetActivity">
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_CONFIGURE"/>
            </intent-filter>
        </activity>

        <receiver
            android:name=".widget.HostWidget1x1"
            android:label="@string/widget1x1_name"
            >
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE"/>
            </intent-filter>

            <meta-data
                android:name="android.appwidget.provider"
                android:resource="@xml/widget1x1"
                />
        </receiver>
        <receiver
            android:name=".widget.HostWidget2x1"
            android:label="@string/widget2x1_name"
            >
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE"/>
            </intent-filter>

            <meta-data
                android:name="android.appwidget.provider"
                android:resource="@xml/widget2x1"
                />
        </receiver>
        <receiver
            android:name=".widget.HostWidget3x1"
            android:label="@string/widget3x1_name"
            >
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE"/>
            </intent-filter>

            <meta-data
                android:name="android.appwidget.provider"
                android:resource="@xml/widget3x1"
                />
        </receiver>
        <receiver
            android:name=".widget.HostWidget4x1"
            android:label="@string/widget4x1_name"
            >
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE"/>
            </intent-filter>

            <meta-data
                android:name="android.appwidget.provider"
                android:resource="@xml/widget4x1"
                />
        </receiver>

        <activity
            android:name="com.ipaulpro.afilechooser.FileChooserActivity"
            android:enabled="@bool/use_activity"
            android:exported="true"
            android:icon="@drawable/ic_chooser"
            android:label="@string/choose_file"
            >
            <intent-filter>
                <action android:name="android.intent.action.GET_CONTENT"/>

                <category android:name="android.intent.category.DEFAULT"/>
                <category android:name="android.intent.category.OPENABLE"/>

                <data android:mimeType="*/*"/>
            </intent-filter>
        </activity>

        <provider
            android:name="com.ianhanniballake.localstorage.LocalStorageProvider"
            android:authorities="com.xargsgrep.portknocker.documents"
            android:enabled="@bool/use_provider"
            android:exported="true"
            android:grantUriPermissions="true"
            android:permission="android.permission.MANAGE_DOCUMENTS"
            >
            <intent-filter>
                <action android:name="android.content.action.DOCUMENTS_PROVIDER"/>
            </intent-filter>
        </provider>

        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="com.xargsgrep.portknocker.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_provider_paths" />
        </provider>

    </application>

</manifest>


text:
package org.apache.flink.formats.avro.typeutils;

import io.confluent.kafka.schemaregistry.ParsedSchema;
import io.confluent.kafka.schemaregistry.avro.AvroSchema;
import org.apache.avro.Schema;
import org.apache.avro.Schema.Parser;
import org.apache.avro.reflect.Nullable;
import pl.touk.nussknacker.engine.schemedkafka.schemaregistry.confluent.client.AvroSchemaWithJsonPayload;
import pl.touk.nussknacker.engine.schemedkafka.schemaregistry.confluent.client.OpenAPIJsonSchema;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
 * This is copy of Flinks class with changed visibility.
 *
 * A wrapper for Avro {@link Schema}, that is Java serializable.
 */
public final class NkSerializableParsedSchema<T extends ParsedSchema> implements Serializable {

    private static final long serialVersionUID = 2;
    private static final byte avroSchemaType = 1;
    private static final byte jsonSchemaType = 2;
    private static final byte avroSchemaWithJsonPayloadType = 3;

    private transient @Nullable T schema;

    public NkSerializableParsedSchema() {
    }

    public NkSerializableParsedSchema(T schema) {
        this.schema = schema;
    }

    public T getParsedSchema() {
        return schema;
    }

    private void writeObject(ObjectOutputStream oos) throws IOException {
        if (schema == null) {
            oos.writeBoolean(false);
        } else {
            oos.writeBoolean(true);
            if (schema instanceof AvroSchema) {
                oos.writeByte(avroSchemaType);
                oos.writeUTF(((AvroSchema) schema).rawSchema().toString(false));
            } else if (schema instanceof OpenAPIJsonSchema) {
                oos.writeByte(jsonSchemaType);
                oos.writeUTF(((OpenAPIJsonSchema) schema).rawSchema().toString());
            } else if (schema instanceof AvroSchemaWithJsonPayload) {
                oos.writeByte(avroSchemaWithJsonPayloadType);
                oos.writeUTF(((AvroSchemaWithJsonPayload) schema).rawSchema().toString());
            }
            else {
                throw new IllegalStateException("Shouldn't happen. Unsupported schema type: " + schema.schemaType());
            }
        }
    }

    @SuppressWarnings("unchecked")
    private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException {
        if (ois.readBoolean()) {
            byte schemaType = ois.readByte();
            switch (schemaType) {
                case avroSchemaType:
                    String avroSchemaStr = ois.readUTF();
                    this.schema = (T) new AvroSchema(new Parser().parse(avroSchemaStr));
                    break;
                case jsonSchemaType:
                    String jsonSchemaStr = ois.readUTF();
                    this.schema = (T) new OpenAPIJsonSchema(jsonSchemaStr);
                    break;
                case avroSchemaWithJsonPayloadType:
                    String avroSchema = ois.readUTF();
                    this.schema = (T) new AvroSchemaWithJsonPayload(new AvroSchema(avroSchema));
                    break;
                default:
                    throw new IllegalStateException("Shouldn't happen. Unsupported schema type: " + schemaType);
            }
        } else {
            this.schema = null;
        }
    }
}


text:
#pragma once

#include "map/api_mark_point.hpp"
#include "map/booking_filter_params.hpp"
#include "map/booking_filter_processor.hpp"
#include "map/bookmark.hpp"
#include "map/bookmark_manager.hpp"
#include "map/caching_address_getter.hpp"
#include "map/discovery/discovery_manager.hpp"
#include "map/displacement_mode_manager.hpp"
#include "map/feature_vec_model.hpp"
#include "map/local_ads_manager.hpp"
#include "map/mwm_url.hpp"
#include "map/notifications/notification_manager.hpp"
#include "map/place_page_info.hpp"
#include "map/power_management/power_manager.hpp"
#include "map/power_management/power_management_schemas.hpp"
#include "map/purchase.hpp"
#include "map/routing_manager.hpp"
#include "map/routing_mark.hpp"
#include "map/search_api.hpp"
#include "map/search_mark.hpp"
#include "map/tips_api.hpp"
#include "map/track.hpp"
#include "map/traffic_manager.hpp"
#include "map/transit/transit_reader.hpp"
#include "map/user.hpp"

#include "drape_frontend/gui/skin.hpp"
#include "drape_frontend/drape_api.hpp"
#include "drape_frontend/drape_engine.hpp"
#include "drape_frontend/user_event_stream.hpp"

#include "drape/drape_global.hpp"
#include "drape/graphics_context_factory.hpp"

#include "kml/type_utils.hpp"

#include "ugc/api.hpp"

#include "editor/new_feature_categories.hpp"
#include "editor/user_stats.hpp"

#include "indexer/caching_rank_table_loader.hpp"
#include "indexer/data_header.hpp"
#include "indexer/data_source.hpp"
#include "indexer/data_source_helpers.hpp"
#include "indexer/map_object.hpp"
#include "indexer/map_style.hpp"

#include "search/city_finder.hpp"
#include "search/displayed_categories.hpp"
#include "search/mode.hpp"
#include "search/query_saver.hpp"
#include "search/result.hpp"
#include "search/reverse_geocoder.hpp"

#include "storage/downloading_policy.hpp"
#include "storage/storage.hpp"

#include "tracking/reporter.hpp"

#include "partners_api/banner.hpp"
#include "partners_api/booking_api.hpp"
#include "partners_api/locals_api.hpp"
#include "partners_api/promo_api.hpp"
#include "partners_api/taxi_engine.hpp"

#include "metrics/eye_info.hpp"

#include "platform/country_defines.hpp"
#include "platform/location.hpp"
#include "platform/platform.hpp"

#include "routing/router.hpp"
#include "routing/routing_session.hpp"

#include "geometry/rect2d.hpp"
#include "geometry/screenbase.hpp"

#include "base/deferred_task.hpp"
#include "base/macros.hpp"
#include "base/strings_bundle.hpp"
#include "base/thread_checker.hpp"

#include "std/cstdint.hpp"
#include "std/function.hpp"
#include "std/list.hpp"
#include "std/set.hpp"
#include "std/shared_ptr.hpp"
#include "std/string.hpp"
#include "std/target_os.hpp"
#include "std/unique_ptr.hpp"
#include "std/utility.hpp"
#include "std/vector.hpp"

#include <boost/optional.hpp>

namespace osm
{
class EditableMapObject;
}

namespace search
{
struct EverywhereSearchParams;
struct ViewportSearchParams;
}

namespace storage
{
class CountryInfoGetter;
struct DownloaderSearchParams;
}

namespace routing { namespace turns{ class Settings; } }

namespace platform
{
class NetworkPolicy;
}

namespace ads
{
class Engine;
}

namespace descriptions
{
class Loader;
}

namespace notifications
{
class NotificationCandidate;
}

/// Uncomment line to make fixed position settings and
/// build version for screenshots.
//#define FIXED_LOCATION

struct FrameworkParams
{
  bool m_enableLocalAds = true;
  bool m_enableDiffs = true;

  FrameworkParams() = default;
  FrameworkParams(bool enableLocalAds, bool enableDiffs)
    : m_enableLocalAds(enableLocalAds)
    , m_enableDiffs(enableDiffs)
  {}
};

class Framework : public SearchAPI::Delegate,
                  public RoutingManager::Delegate,
                  public TipsApi::Delegate,
                  private power_management::PowerManager::Subscriber
{
  DISALLOW_COPY(Framework);

#ifdef FIXED_LOCATION
  class FixedPosition
  {
    pair<double, double> m_latlon;
    double m_dirFromNorth;
    bool m_fixedLatLon, m_fixedDir;

  public:
    FixedPosition();

    void GetLat(double & l) const { if (m_fixedLatLon) l = m_latlon.first; }
    void GetLon(double & l) const { if (m_fixedLatLon) l = m_latlon.second; }

    void GetNorth(double & n) const { if (m_fixedDir) n = m_dirFromNorth; }
    bool HasNorth() const { return m_fixedDir; }

  } m_fixedPos;
#endif

private:
  // Must be first member in Framework and must be destroyed first in Framework destructor.
  unique_ptr<Platform::ThreadRunner> m_threadRunner = make_unique<Platform::ThreadRunner>();

protected:
  using TDrapeFunction = function<void (df::DrapeEngine *)>;

  StringsBundle m_stringsBundle;

  model::FeaturesFetcher m_model;

  // The order matters here: DisplayedCategories may be used only
  // after classificator is loaded by |m_model|.
  unique_ptr<search::DisplayedCategories> m_displayedCategories;

  // The order matters here: storage::CountryInfoGetter and
  // m_model::FeaturesFetcher must be initialized before
  // search::Engine and, therefore, destroyed after search::Engine.
  unique_ptr<storage::CountryInfoGetter> m_infoGetter;

  LocalAdsManager m_localAdsManager;

  // The order matters here: ugc::Api should be destroyed after
  // SearchAPI and notifications::NotificationManager.
  unique_ptr<ugc::Api> m_ugcApi;

  unique_ptr<SearchAPI> m_searchAPI;

  search::QuerySaver m_searchQuerySaver;

  ScreenBase m_currentModelView;
  m2::RectD m_visibleViewport;

  using TViewportChangedFn = df::DrapeEngine::ModelViewChangedHandler;
  TViewportChangedFn m_viewportChangedFn;

  drape_ptr<df::DrapeEngine> m_drapeEngine;

  double m_startForegroundTime = 0.0;
  double m_startBackgroundTime = 0.0;

  StorageDownloadingPolicy m_storageDownloadingPolicy;
  storage::Storage m_storage;
  bool m_enabledDiffs;

  location::TMyPositionModeChanged m_myPositionListener;
  df::DrapeEngine::UserPositionPendingTimeoutHandler m_myPositionPendingTimeoutListener;

  unique_ptr<BookmarkManager> m_bmManager;

  SearchMarks m_searchMarks;

  unique_ptr<booking::Api> m_bookingApi = make_unique<booking::Api>();
  unique_ptr<locals::Api> m_localsApi = make_unique<locals::Api>();
  unique_ptr<promo::Api> m_promoApi = make_unique<promo::Api>();

  df::DrapeApi m_drapeApi;

  bool m_isRenderingEnabled;

  // Note. |m_powerManager| should be declared before |m_routingManager|
  power_management::PowerManager m_powerManager;

  TransitReadManager m_transitManager;

  // Note. |m_routingManager| should be declared before |m_trafficManager|
  RoutingManager m_routingManager;

  TrafficManager m_trafficManager;
  User m_user;

  booking::filter::FilterProcessor m_bookingFilterProcessor;
  booking::AvailabilityParams m_bookingAvailabilityParams;

  /// This function will be called by m_storage when latest local files
  /// is downloaded.
  void OnCountryFileDownloaded(storage::CountryId const & countryId,
                               storage::LocalFilePtr const localFile);

  /// This function will be called by m_storage before latest local files
  /// is deleted.
  bool OnCountryFileDelete(storage::CountryId const & countryId,
                           storage::LocalFilePtr const localFile);

  /// This function is called by m_model when the map file is deregistered.
  void OnMapDeregistered(platform::LocalCountryFile const & localFile);

  void ClearAllCaches();

  void OnViewportChanged(ScreenBase const & screen);

  void InitTransliteration();

public:
  explicit Framework(FrameworkParams const & params = {});
  virtual ~Framework();

  /// Get access to booking api helpers
  booking::Api * GetBookingApi(platform::NetworkPolicy const & policy);
  booking::Api const * GetBookingApi(platform::NetworkPolicy const & policy) const;
  taxi::Engine * GetTaxiEngine(platform::NetworkPolicy const & policy);
  locals::Api * GetLocalsApi(platform::NetworkPolicy const & policy);
  promo::Api * GetPromoApi(platform::NetworkPolicy const & policy) const;
  ugc::Api * GetUGCApi() { return m_ugcApi.get(); }
  ugc::Api const * GetUGCApi() const { return m_ugcApi.get(); }

  df::DrapeApi & GetDrapeApi() { return m_drapeApi; }

  User & GetUser() { return m_user; }
  User const & GetUser() const { return m_user; }

  /// Migrate to new version of very different data.
  bool IsEnoughSpaceForMigrate() const;
  storage::CountryId PreMigrate(ms::LatLon const & position,
                                storage::Storage::ChangeCountryFunction const & change,
                                storage::Storage::ProgressFunction const & progress);
  void Migrate(bool keepDownloaded = true);

  /// \returns true if there're unsaved changes in map with |countryId| and false otherwise.
  /// \note It works for group and leaf node.
  bool HasUnsavedEdits(storage::CountryId const & countryId);

  /// Registers all local map files in internal indexes.
  void RegisterAllMaps();

  /// Deregisters all registered map files.
  void DeregisterAllMaps();

  /// Registers a local map file in internal indexes.
  pair<MwmSet::MwmId, MwmSet::RegResult> RegisterMap(
      platform::LocalCountryFile const & localFile);
  //@}

  /// Shows group or leaf mwm on the map.
  void ShowNode(storage::CountryId const & countryId);

  // TipsApi::Delegate override.
  /// Checks, whether the country which contains the specified point is loaded.
  bool IsCountryLoaded(m2::PointD const & pt) const override;
  /// Checks, whether the country is loaded.
  bool IsCountryLoadedByName(string const & name) const;
  //@}

  void InvalidateRect(m2::RectD const & rect);

  /// @name Get any country info by point.
  //@{
  storage::CountryId GetCountryIndex(m2::PointD const & pt) const;

  string GetCountryName(m2::PointD const & pt) const;
  //@}

  enum class DoAfterUpdate
  {
    Nothing,
    AutoupdateMaps,
    AskForUpdateMaps,
    Migrate
  };

  DoAfterUpdate ToDoAfterUpdate() const;

  storage::Storage & GetStorage() { return m_storage; }
  storage::Storage const & GetStorage() const { return m_storage; }
  search::DisplayedCategories const & GetDisplayedCategories();
  storage::CountryInfoGetter & GetCountryInfoGetter() { return *m_infoGetter; }
  StorageDownloadingPolicy & GetDownloadingPolicy() { return m_storageDownloadingPolicy; }

  DataSource const & GetDataSource() const { return m_model.GetDataSource(); }

  SearchAPI & GetSearchAPI();
  SearchAPI const & GetSearchAPI() const;

  /// @name Bookmarks, Tracks and other UserMarks
  //@{
  /// Scans and loads all kml files with bookmarks in WritableDir.
  void LoadBookmarks();

  /// @return Created bookmark category id.
  kml::MarkGroupId AddCategory(string const & categoryName);

  kml::MarkGroupId LastEditedBMCategory() { return GetBookmarkManager().LastEditedBMCategory(); }
  kml::PredefinedColor LastEditedBMColor() const { return GetBookmarkManager().LastEditedBMColor(); }

  void ShowBookmark(kml::MarkId id);
  void ShowBookmark(Bookmark const * bookmark);
  void ShowTrack(kml::TrackId trackId);
  void ShowFeatureByMercator(m2::PointD const & pt);
  void ShowBookmarkCategory(kml::MarkGroupId categoryId, bool animation = true);

  void AddBookmarksFile(string const & filePath, bool isTemporaryFile);

  BookmarkManager & GetBookmarkManager();
  BookmarkManager const & GetBookmarkManager() const;

  // Utilities
  void VisualizeMwmsBordersInRect(m2::RectD const & rect);
  void VisualizeRoadsInRect(m2::RectD const & rect);
  void VisualizeCityBoundariesInRect(m2::RectD const & rect);
  void VisualizeCityRoadsInRect(m2::RectD const & rect);

  ads::Engine const & GetAdsEngine() const;
  void DisableAdProvider(ads::Banner::Type const type, ads::Banner::Place const place);

public:
  // SearchAPI::Delegate overrides:
  void RunUITask(function<void()> fn) override;
  void SetSearchDisplacementModeEnabled(bool enabled) override;
  void ShowViewportSearchResults(search::Results::ConstIter begin,
                                 search::Results::ConstIter end, bool clear) override;
  void ShowViewportSearchResults(search::Results::ConstIter begin,
                                 search::Results::ConstIter end, bool clear,
                                 booking::filter::Types types) override;
  void ClearViewportSearchResults() override;
  // SearchApi::Delegate and TipsApi::Delegate override.
  boost::optional<m2::PointD> GetCurrentPosition() const override;
  bool ParseSearchQueryCommand(search::SearchParams const & params) override;
  search::ProductInfo GetProductInfo(search::Result const & result) const override;
  double GetMinDistanceBetweenResults() const override;

private:
  void ActivateMapSelection(bool needAnimation,
                            df::SelectionShape::ESelectedObject selectionType,
                            place_page::Info const & info);
  void InvalidateUserMarks();

public:
  void DeactivateMapSelection(bool notifyUI);
  /// Used to "refresh" UI in some cases (e.g. feature editing).
  void UpdatePlacePageInfoForCurrentSelection();

  void DrawMwmBorder(std::string const & mwmName, std::vector<m2::RegionD> const & regions,
                     bool withVertices);

  /// Called to notify UI that object on a map was selected (UI should show Place Page, for example).
  using TActivateMapSelectionFn = function<void (place_page::Info const &)>;
  /// Called to notify UI that object on a map was deselected (UI should hide Place Page).
  /// If switchFullScreenMode is true, ui can [optionally] enter or exit full screen mode.
  using TDeactivateMapSelectionFn = function<void (bool /*switchFullScreenMode*/)>;
  void SetMapSelectionListeners(TActivateMapSelectionFn const & activator,
                                TDeactivateMapSelectionFn const & deactivator);

  void ResetLastTapEvent();

  void InvalidateRendering();
  void EnableDebugRectRendering(bool enabled);

  void EnableChoosePositionMode(bool enable, bool enableBounds, bool applyPosition, m2::PointD const & position);
  void BlockTapEvents(bool block);

  using TCurrentCountryChanged = function<void(storage::CountryId const &)>;
  storage::CountryId const & GetLastReportedCountry() { return m_lastReportedCountry; }
  /// Guarantees that listener is called in the main thread context.
  void SetCurrentCountryChangedListener(TCurrentCountryChanged const & listener);

  std::vector<std::string> GetRegionsCountryIdByRect(m2::RectD const & rect, bool rough) const;
  vector<MwmSet::MwmId> GetMwmsByRect(m2::RectD const & rect, bool rough) const;
  MwmSet::MwmId GetMwmIdByName(string const & name) const;

  // Use only for debug purposes!
  vector<FeatureID> FindFeaturesByIndex(uint32_t featureIndex) const;

  void ReadFeatures(function<void(FeatureType &)> const & reader,
                    vector<FeatureID> const & features);

private:
  struct TapEvent
  {
    enum class Source
    {
      User,
      Search,
      Other
    };

    TapEvent(df::TapInfo const & info, Source source)
      : m_info(info)
      , m_source(source)
    {}

    df::TapInfo const m_info;
    Source const m_source;
  };

  unique_ptr<TapEvent> m_lastTapEvent;
  bool m_isViewportInitialized = false;

  void OnTapEvent(TapEvent const & tapEvent);
  /// outInfo is valid only if return value is not df::SelectionShape::OBJECT_EMPTY.
  df::SelectionShape::ESelectedObject OnTapEventImpl(TapEvent const & tapEvent,
                                                     place_page::Info & outInfo);
  unique_ptr<TapEvent> MakeTapEvent(m2::PointD const & center, FeatureID const & fid,
                                    TapEvent::Source source) const;
  UserMark const * FindUserMarkInTapPosition(df::TapInfo const & tapInfo) const;
  FeatureID FindBuildingAtPoint(m2::PointD const & mercator) const;

  void UpdateMinBuildingsTapZoom();

  int m_minBuildingsTapZoom;

  TActivateMapSelectionFn m_activateMapSelectionFn;
  TDeactivateMapSelectionFn m_deactivateMapSelectionFn;

  /// Here we store last selected feature to get its polygons in case of adding organization.
  mutable FeatureID m_selectedFeature;

private:
  vector<m2::TriangleD> GetSelectedFeatureTriangles() const;

public:

  /// @name GPS location updates routine.
  //@{
  void OnLocationError(location::TLocationError error);
  void OnLocationUpdate(location::GpsInfo const & info);
  void OnCompassUpdate(location::CompassInfo const & info);
  void SwitchMyPositionNextMode();
  /// Should be set before Drape initialization. Guarantees that fn is called in main thread context.
  void SetMyPositionModeListener(location::TMyPositionModeChanged && fn);
  void SetMyPositionPendingTimeoutListener(df::DrapeEngine::UserPositionPendingTimeoutHandler && fn);

private:
  void OnUserPositionChanged(m2::PointD const & position, bool hasPosition);
  //@}

public:
  struct DrapeCreationParams
  {
    dp::ApiVersion m_apiVersion = dp::ApiVersion::OpenGLES2;
    float m_visualScale = 1.0f;
    int m_surfaceWidth = 0;
    int m_surfaceHeight = 0;
    gui::TWidgetsInitInfo m_widgetsInitInfo;

    bool m_hasMyPositionState = false;
    location::EMyPositionMode m_initialMyPositionState = location::PendingPosition;

    bool m_isChoosePositionMode = false;
    df::Hints m_hints;
  };

  void CreateDrapeEngine(ref_ptr<dp::GraphicsContextFactory> contextFactory, DrapeCreationParams && params);
  ref_ptr<df::DrapeEngine> GetDrapeEngine();
  bool IsDrapeEngineCreated() const { return m_drapeEngine != nullptr; }
  void DestroyDrapeEngine();
  /// Called when graphics engine should be temporarily paused and then resumed.
  void SetRenderingEnabled(ref_ptr<dp::GraphicsContextFactory> contextFactory = nullptr);
  void SetRenderingDisabled(bool destroySurface);

  void SetGraphicsContextInitializationHandler(df::OnGraphicsContextInitialized && handler);

  void OnRecoverSurface(int width, int height, bool recreateContextDependentResources);
  void OnDestroySurface();

  void UpdateVisualScale(double vs);

  /// Sets the distance between the bottom edge of the arrow and the bottom edge of the visible viewport
  /// in follow routing mode or resets it to the default value.
  void UpdateMyPositionRoutingOffset(bool useDefault, int offsetY);

private:
  /// Depends on initialized Drape engine.
  void SaveViewport();
  /// Depends on initialized Drape engine.
  void LoadViewport();

  df::OnGraphicsContextInitialized m_onGraphicsContextInitialized;

public:
  void ConnectToGpsTracker();
  void DisconnectFromGpsTracker();

  void SetMapStyle(MapStyle mapStyle);
  void MarkMapStyle(MapStyle mapStyle);
  MapStyle GetMapStyle() const;

  void SetupMeasurementSystem();

  void SetWidgetLayout(gui::TWidgetsLayoutInfo && layout);

  void PrepareToShutdown();

  void SetDisplacementMode(DisplacementModeManager::Slot slot, bool show);

private:
  void InitCountryInfoGetter();
  void InitUGC();
  void InitSearchAPI();
  void InitDiscoveryManager();

  DisplacementModeManager m_displacementModeManager;

  bool m_connectToGpsTrack; // need to connect to tracker when Drape is being constructed

  void OnUpdateCurrentCountry(m2::PointD const & pt, int zoomLevel);

  storage::CountryId m_lastReportedCountry;
  TCurrentCountryChanged m_currentCountryChanged;

  void OnUpdateGpsTrackPointsCallback(vector<pair<size_t, location::GpsTrackInfo>> && toAdd,
                                      pair<size_t, size_t> const & toRemove);

  CachingRankTableLoader m_popularityLoader;

  unique_ptr<descriptions::Loader> m_descriptionsLoader;

public:
  using SearchRequest = search::QuerySaver::SearchRequest;

  // When search in viewport is active or delayed, restarts search in
  // viewport. When |forceSearch| is false, request is skipped when it
  // is similar to the previous request in the current
  // search-in-viewport session.
  void PokeSearchInViewport(bool forceSearch = true);

  // Search everywhere.
  bool SearchEverywhere(search::EverywhereSearchParams const & params);

  // Search in the viewport.
  bool SearchInViewport(search::ViewportSearchParams const & params);

  // Search for maps by countries or cities.
  bool SearchInDownloader(storage::DownloaderSearchParams const & params);

  // Search for bookmarks by query string.
  bool SearchInBookmarks(search::BookmarksSearchParams const & params);

  void CancelSearch(search::Mode mode);
  void CancelAllSearches();

  // Moves viewport to the search result and taps on it.
  void SelectSearchResult(search::Result const & res, bool animation);

  // Cancels all searches, stops location follow and then selects
  // search result.
  void ShowSearchResult(search::Result const & res, bool animation = true);

  size_t ShowSearchResults(search::Results const & results);

  using SearchMarkPostProcessing = function<void(SearchMarkPoint & mark)>;

  void FillSearchResultsMarks(bool clear, search::Results const & results);
  void FillSearchResultsMarks(search::Results::ConstIter begin, search::Results::ConstIter end,
                                bool clear, SearchMarkPostProcessing fn = nullptr);
  list<SearchRequest> const & GetLastSearchQueries() const { return m_searchQuerySaver.Get(); }
  void SaveSearchQuery(SearchRequest const & query) { m_searchQuerySaver.Add(query); }
  void ClearSearchHistory() { m_searchQuerySaver.Clear(); }

  /// Calculate distance and direction to POI for the given position.
  /// @param[in]  point             POI's position;
  /// @param[in]  lat, lon, north   Current position and heading from north;
  /// @param[out] distance          Formatted distance string;
  /// @param[out] azimut            Azimut to point from (lat, lon);
  /// @return true  If the POI is near the current position (distance < 25 km);
  bool GetDistanceAndAzimut(m2::PointD const & point,
                            double lat, double lon, double north,
                            string & distance, double & azimut);

  /// @name Manipulating with model view
  //@{
  inline m2::PointD PtoG(m2::PointD const & p) const { return m_currentModelView.PtoG(p); }
  inline m2::PointD P3dtoG(m2::PointD const & p) const { return m_currentModelView.PtoG(m_currentModelView.P3dtoP(p)); }
  inline m2::PointD GtoP(m2::PointD const & p) const { return m_currentModelView.GtoP(p); }
  inline m2::PointD GtoP3d(m2::PointD const & p) const { return m_currentModelView.PtoP3d(m_currentModelView.GtoP(p)); }

  /// Show all model by it's world rect.
  void ShowAll();

  m2::PointD GetPixelCenter() const;
  m2::PointD GetVisiblePixelCenter() const;

  m2::PointD const & GetViewportCenter() const;
  void SetViewportCenter(m2::PointD const & pt, int zoomLevel = -1, bool isAnim = true);

  m2::RectD GetCurrentViewport() const;
  void SetVisibleViewport(m2::RectD const & rect);

  /// - Check minimal visible scale according to downloaded countries.
  void ShowRect(m2::RectD const & rect, int maxScale = -1, bool animation = true,
                bool useVisibleViewport = false);
  void ShowRect(m2::AnyRectD const & rect, bool animation = true, bool useVisibleViewport = false);

  void GetTouchRect(m2::PointD const & center, uint32_t pxRadius, m2::AnyRectD & rect);

  void SetViewportListener(TViewportChangedFn const & fn);

#if defined(OMIM_OS_MAC) || defined(OMIM_OS_LINUX)
  using TGraphicsReadyFn = df::DrapeEngine::GraphicsReadyHandler;
  void NotifyGraphicsReady(TGraphicsReadyFn const & fn);
#endif

  void StopLocationFollow();

  /// Resize event from window.
  void OnSize(int w, int h);

  enum EScaleMode
  {
    SCALE_MAG,
    SCALE_MAG_LIGHT,
    SCALE_MIN,
    SCALE_MIN_LIGHT
  };

  void Scale(EScaleMode mode, bool isAnim);
  void Scale(EScaleMode mode, m2::PointD const & pxPoint, bool isAnim);
  void Scale(double factor, bool isAnim);
  void Scale(double factor, m2::PointD const & pxPoint, bool isAnim);

  /// Moves the viewport a distance of factorX * viewportWidth and factorY * viewportHeight.
  /// E.g. factorX == 1.0 moves the map one screen size to the right, factorX == -0.5 moves the map
  /// half screen size to the left, factorY == -2.0 moves the map two sizes down,
  /// factorY = 1.5 moves the map one and a half size up.
  void Move(double factorX, double factorY, bool isAnim);

  void Rotate(double azimuth, bool isAnim);

  void TouchEvent(df::TouchEvent const & touch);
  //@}

  int GetDrawScale() const;

  void RunFirstLaunchAnimation();

  /// Set correct viewport, parse API, show balloon.
  bool ShowMapForURL(string const & url);
  url_scheme::ParsedMapApi::ParsingResult ParseAndSetApiURL(string const & url);

  struct ParsedRoutingData
  {
    ParsedRoutingData(vector<url_scheme::RoutePoint> const & points, routing::RouterType type)
      : m_points(points), m_type(type)
    {
    }
    vector<url_scheme::RoutePoint> m_points;
    routing::RouterType m_type;
  };

  ParsedRoutingData GetParsedRoutingData() const;
  url_scheme::SearchRequest GetParsedSearchRequest() const;

private:
  /// @returns true if command was handled by editor.
  bool ParseEditorDebugCommand(search::SearchParams const & params);

  /// @returns true if command was handled by drape.
  bool ParseDrapeDebugCommand(string const & query);

  /// This function can be used for enabling some experimental features for routing.
  bool ParseRoutingDebugCommand(search::SearchParams const & params);

  void FillFeatureInfo(FeatureID const & fid, place_page::Info & info) const;
  /// @param customTitle, if not empty, overrides any other calculated name.
  void FillPointInfo(m2::PointD const & mercator, string const & customTitle, place_page::Info & info) const;
  void FillInfoFromFeatureType(FeatureType & ft, place_page::Info & info) const;
  void FillApiMarkInfo(ApiMarkPoint const & api, place_page::Info & info) const;
  void FillSearchResultInfo(SearchMarkPoint const & smp, place_page::Info & info) const;
  void FillMyPositionInfo(place_page::Info & info, df::TapInfo const & tapInfo) const;
  void FillRouteMarkInfo(RouteMarkPoint const & rmp, place_page::Info & info) const;
  void FillRoadTypeMarkInfo(RoadWarningMark const & roadTypeMark, place_page::Info & info) const;

public:
  void FillBookmarkInfo(Bookmark const & bmk, place_page::Info & info) const;
  void ResetBookmarkInfo(Bookmark const & bmk, place_page::Info & info) const;

  search::ReverseGeocoder::Address GetAddressAtPoint(m2::PointD const & pt) const;

  /// Get "best for the user" feature at given point even if it's invisible on the screen.
  /// Ignores coastlines and prefers buildings over other area features.
  /// @returns invalid FeatureID if no feature was found at the given mercator point.
  FeatureID GetFeatureAtPoint(m2::PointD const & mercator) const;
  template <typename TFn>
  void ForEachFeatureAtPoint(TFn && fn, m2::PointD const & mercator) const
  {
    indexer::ForEachFeatureAtPoint(m_model.GetDataSource(), fn, mercator, 0.0);
  }

  osm::MapObject GetMapObjectByID(FeatureID const & fid) const;

  void MemoryWarning();
  void EnterBackground();
  void EnterForeground();

  /// Set the localized strings bundle
  inline void AddString(string const & name, string const & value)
  {
    m_stringsBundle.SetString(name, value);
  }

  StringsBundle const & GetStringsBundle();

  /// [in] lat, lon - last known location
  /// [out] lat, lon - predicted location
  static void PredictLocation(double & lat, double & lon, double accuracy,
                              double bearing, double speed, double elapsedSeconds);

public:
  string CodeGe0url(Bookmark const * bmk, bool addName);
  string CodeGe0url(double lat, double lon, double zoomLevel, string const & name);

  /// @name Api
  //@{
  string GenerateApiBackUrl(ApiMarkPoint const & point) const;
  url_scheme::ParsedMapApi const & GetApiDataHolder() const { return m_ParsedMapApi; }

private:
  url_scheme::ParsedMapApi m_ParsedMapApi;

public:
  //@}

  /// @name Data versions
  //@{
  bool IsDataVersionUpdated();
  void UpdateSavedDataVersion();
  int64_t GetCurrentDataVersion() const;
  //@}

public:
  void AllowTransliteration(bool allowTranslit);
  bool LoadTransliteration();
  void SaveTransliteration(bool allowTranslit);

  void Allow3dMode(bool allow3d, bool allow3dBuildings);
  void Save3dMode(bool allow3d, bool allow3dBuildings);
  void Load3dMode(bool & allow3d, bool & allow3dBuildings);

  void SetLargeFontsSize(bool isLargeSize);
  void SaveLargeFontsSize(bool isLargeSize);
  bool LoadLargeFontsSize();

  bool LoadAutoZoom();
  void AllowAutoZoom(bool allowAutoZoom);
  void SaveAutoZoom(bool allowAutoZoom);

  TrafficManager & GetTrafficManager();

  LocalAdsManager & GetLocalAdsManager();

  TransitReadManager & GetTransitManager();

  bool LoadTrafficEnabled();
  void SaveTrafficEnabled(bool trafficEnabled);

  bool LoadTrafficSimplifiedColors();
  void SaveTrafficSimplifiedColors(bool simplified);

  bool LoadTransitSchemeEnabled();
  void SaveTransitSchemeEnabled(bool enabled);

  dp::ApiVersion LoadPreferredGraphicsAPI();
  void SavePreferredGraphicsAPI(dp::ApiVersion apiVersion);

public:
  template <typename ResultCallback>
  uint32_t Discover(discovery::ClientParams && params, ResultCallback const & onResult,
                    discovery::Manager::ErrorCalback const & onError) const
  {
    CHECK(m_discoveryManager.get(), ());
    return m_discoveryManager->Discover(GetDiscoveryParams(move(params)), onResult, onError);
  }

  discovery::Manager::Params GetDiscoveryParams(discovery::ClientParams && clientParams) const;

  std::string GetDiscoveryLocalExpertsUrl() const;

private:
  m2::PointD GetDiscoveryViewportCenter() const;

public:
  /// Routing Manager
  RoutingManager & GetRoutingManager() { return m_routingManager; }
  RoutingManager const & GetRoutingManager() const { return m_routingManager; }
protected:
  /// RoutingManager::Delegate
  void OnRouteFollow(routing::RouterType type) override;
  void RegisterCountryFilesOnRoute(shared_ptr<routing::NumMwmIds> ptr) const override;

public:
  /// @name Editor interface.
  //@{
  /// Initializes feature for Create Object UI.
  /// @returns false in case when coordinate is in the ocean or mwm is not downloaded.
  bool CanEditMap() const;

  bool CreateMapObject(m2::PointD const & mercator, uint32_t const featureType, osm::EditableMapObject & emo) const;
  /// @returns false if feature is invalid or can't be edited.
  bool GetEditableMapObject(FeatureID const & fid, osm::EditableMapObject & emo) const;
  osm::Editor::SaveResult SaveEditedMapObject(osm::EditableMapObject emo);
  void DeleteFeature(FeatureID const & fid) const;
  osm::NewFeatureCategories GetEditorCategories() const;
  bool RollBackChanges(FeatureID const & fid);
  void CreateNote(osm::MapObject const & mapObject, osm::Editor::NoteProblemType const type,
                  string const & note);
  //@}

public:
  //@{
  // User statistics.

  editor::UserStats GetUserStats(string const & userName) const
  {
    return m_userStatsLoader.GetStats(userName);
  }

  // Reads user stats from server or gets it from cache calls |fn| on success.
  void UpdateUserStats(string const & userName, editor::UserStatsLoader::UpdatePolicy policy,
                       editor::UserStatsLoader::OnUpdateCallback fn)
  {
    m_userStatsLoader.Update(userName, policy, fn);
  }

  void DropUserStats(string const & userName) { m_userStatsLoader.DropStats(userName); }

private:
  editor::UserStatsLoader m_userStatsLoader;
  //@}

public:
  storage::CountriesVec GetTopmostCountries(ms::LatLon const & latlon) const;

private:
  unique_ptr<search::CityFinder> m_cityFinder;
  CachingAddressGetter m_addressGetter;
  unique_ptr<ads::Engine> m_adsEngine;
  // The order matters here: storage::CountryInfoGetter and
  // search::CityFinder must be initialized before
  // taxi::Engine and, therefore, destroyed after taxi::Engine.
  unique_ptr<taxi::Engine> m_taxiEngine;

  void InitCityFinder();
  void InitTaxiEngine();

  void SetPlacePageLocation(place_page::Info & info);

  void FillLocalExperts(FeatureType & ft, place_page::Info & info) const;

  void FillDescription(FeatureType & ft, place_page::Info & info) const;

public:
  // UGC.
  void UploadUGC(User::CompleteUploadingHandler const & onCompleteUploading);
  void GetUGC(FeatureID const & id, ugc::Api::UGCCallback const & callback);
private:
  // Filters user's reviews.
  ugc::Reviews FilterUGCReviews(ugc::Reviews const & reviews) const;

public:
  void FilterResultsForHotelsQuery(booking::filter::Tasks const & filterTasks,
                                   search::Results const & results, bool inViewport) override;
  void FilterHotels(booking::filter::Tasks const & filterTasks,
                    vector<FeatureID> && featureIds) override;
  void OnBookingFilterParamsUpdate(booking::filter::Tasks const & filterTasks) override;

  booking::AvailabilityParams GetLastBookingAvailabilityParams() const;

private:
  // m_discoveryManager must be bellow m_searchApi, m_localsApi
  unique_ptr<discovery::Manager> m_discoveryManager;

public:
  std::unique_ptr<Purchase> const & GetPurchase() const { return m_purchase; }
  std::unique_ptr<Purchase> & GetPurchase() { return m_purchase; }

private:
  std::unique_ptr<Purchase> m_purchase;
  TipsApi m_tipsApi;
  notifications::NotificationManager m_notificationManager;

public:
  TipsApi const & GetTipsApi() const;

  // TipsApi::Delegate override.
  bool HaveTransit(m2::PointD const & pt) const override;
  double GetLastBackgroundTime() const override;

  bool MakePlacePageInfo(notifications::NotificationCandidate const & notification,
                         place_page::Info & info) const;

  power_management::PowerManager & GetPowerManager() { return m_powerManager; }

  // PowerManager::Subscriber override.
  void OnPowerFacilityChanged(power_management::Facility const facility, bool enabled) override;
  void OnPowerSchemeChanged(power_management::Scheme const actualScheme) override;

  notifications::NotificationManager & GetNotificationManager();
};


text:
'use strict'

import SCNGeometry from './SCNGeometry'
import SCNGeometryElement from './SCNGeometryElement'
import SCNGeometryPrimitiveType from './SCNGeometryPrimitiveType'
import SCNGeometrySource from './SCNGeometrySource'
import SCNMaterial from './SCNMaterial'
import SCNVector3 from './SCNVector3'

/**
 * A torus, or ring-shaped geometry.
 * @access public
 * @extends {SCNGeometry}
 * @see https://developer.apple.com/documentation/scenekit/scntorus
 */
export default class SCNTorus extends SCNGeometry {
  // Creating a Torus

  /**
   * Creates a torus geometry with the specified ring radius and pipe radius.
   * @access public
   * @constructor
   * @param {number} ringRadius - The major radius of the torus, defining its circular ring in the x- and z-axis dimensions of its local coordinate space.
   * @param {number} pipeRadius - The minor radius of the torus, defining the pipe that encircles the ring.
   * @desc The torus is centered in its local coordinate system. For example, if you create a torus whose ring radius is 5.0 and pipe radius is 1.0, it extends from -6.0 to 6.0 (with a hole through the center from -4.0 to 4.0) in the x- and z-axes and from -1.0 to 1.0 in the y-axis.
   * @see https://developer.apple.com/documentation/scenekit/scntorus/1523833-init
   */
  constructor(ringRadius = 0.5, pipeRadius = 0.25) {
    super([], [])

    // Adjusting a Torus' Dimensions

    /**
     * The major radius of the torus, defining a circle in the x- and z-axis dimensions. Animatable.
     * @type {number}
     * @see https://developer.apple.com/documentation/scenekit/scntorus/1522906-ringradius
     */
    this.ringRadius = ringRadius

    /**
     * The minor radius of the torus, defining the pipe that encircles the torus ring. Animatable.
     * @type {number}
     * @see https://developer.apple.com/documentation/scenekit/scntorus/1522623-piperadius
     */
    this.pipeRadius = pipeRadius

    // Configuring Torus Properties

    /**
     * The number of subdivisions around the torus ring. Animatable.
     * @type {number}
     * @see https://developer.apple.com/documentation/scenekit/scntorus/1523598-ringsegmentcount
     */
    this.ringSegmentCount = 48

    /**
     * The number of subdivisions around the torus pipe. Animatable.
     * @type {number}
     * @see https://developer.apple.com/documentation/scenekit/scntorus/1522807-pipesegmentcount
     */
    this.pipeSegmentCount = 24

    this._createGeometry()
    this.materials.push(new SCNMaterial())
  }

  _createGeometry() {
    const sourceData = []
    const indexData = []
    const vectorCount = (this.ringSegmentCount + 1) * (this.pipeSegmentCount + 1)

    for(let ri=0; ri<=this.ringSegmentCount; ri++){
      const r = 2.0 * ri * Math.PI / this.ringSegmentCount
      const sinr = Math.sin(r)
      const cosr = Math.cos(r)
      const cx = -sinr * this.ringRadius
      const cz = -cosr * this.ringRadius
      const tx = ri / this.ringSegmentCount

      for(let pi=0; pi<=this.pipeSegmentCount; pi++){
        const pr = 2.0 * pi * Math.PI / this.pipeSegmentCount
        const sinp = Math.sin(pr)
        const cosp = Math.cos(pr)
        const x = cx + this.pipeRadius * sinr * cosp
        const y = -this.pipeRadius * sinp
        const z = cz + this.pipeRadius * cosr * cosp

        // vertex
        sourceData.push(x, y, z)

        // normal
        sourceData.push(sinr * cosp, -sinp, cosr * cosp)

        // texcoord
        const tz = 1.0 - pi / this.pipeSegmentCount
        sourceData.push(tx, tz)
      }
    }

    const vertexSource = new SCNGeometrySource(
      sourceData, // data
      SCNGeometrySource.Semantic.vertex, // semantic
      vectorCount, // vectorCount
      true, // floatComponents
      3, // componentsPerVector
      4, // bytesPerComponent
      0, // offset
      32 // sride
    )

    const normalSource = new SCNGeometrySource(
      sourceData, // data
      SCNGeometrySource.Semantic.normal, // semantic
      vectorCount, // vectorCount
      true, // floatComponents
      3, // componentsPerVector
      4, // bytesPerComponent
      12, // offset
      32 // stride
    )

    const texcoordSource = new SCNGeometrySource(
      sourceData, // data
      SCNGeometrySource.Semantic.texcoord, // semantic
      vectorCount, // vectorCount
      true, // floatComponents
      2, // componentsPerVector
      4, // bytesPerComponent
      24, // offset
      32 // stride
    )

    const indexLen = this.ringSegmentCount * this.pipeSegmentCount
    let base = 0
    for(let i=0; i<indexLen; i++){
      const i2 = base + this.pipeSegmentCount + 1
      indexData.push(base, i2+1, base+1)
      indexData.push(base, i2, i2+1)
      base += 1
      if((i+1) % this.pipeSegmentCount === 0){
        base += 1
      }
    }

    const element = new SCNGeometryElement(indexData, SCNGeometryPrimitiveType.triangles)

    this._geometryElements = [element]
    this._geometrySources = [vertexSource, normalSource, texcoordSource]
    this.boundingBox = {
      min: new SCNVector3(-this.radius, -this.radius, -this.radius),
      max: new SCNVector3(this.radius, this.radius, this.radius)
    }
  }
}


text:
{-# LANGUAGE DeriveDataTypeable, DeriveFunctor, DeriveFoldable,
             DeriveTraversable #-}

--------------------------------------------------------------------------------
-- | Boolean formulas without quantifiers and without negation.
-- Such a formula consists of variables, conjunctions (and), and disjunctions (or).
--
-- This module is used to represent minimal complete definitions for classes.
--
module BooleanFormula (
        BooleanFormula(..), LBooleanFormula,
        mkFalse, mkTrue, mkAnd, mkOr, mkVar,
        isFalse, isTrue,
        eval, simplify, isUnsatisfied,
        implies, impliesAtom,
        pprBooleanFormula, pprBooleanFormulaNice
  ) where

import Data.List ( nub, intersperse )
import Data.Data

import MonadUtils
import Outputable
import Binary
import SrcLoc

----------------------------------------------------------------------
-- Boolean formula type and smart constructors
----------------------------------------------------------------------

type LBooleanFormula a = Located (BooleanFormula a)

data BooleanFormula a = Var a | And [LBooleanFormula a] | Or [LBooleanFormula a]
                      | Parens (LBooleanFormula a)
  deriving (Eq, Data, Functor, Foldable, Traversable)

mkVar :: a -> BooleanFormula a
mkVar = Var

mkFalse, mkTrue :: BooleanFormula a
mkFalse = Or []
mkTrue = And []

-- Convert a Bool to a BooleanFormula
mkBool :: Bool -> BooleanFormula a
mkBool False = mkFalse
mkBool True  = mkTrue

-- Make a conjunction, and try to simplify
mkAnd :: Eq a => [LBooleanFormula a] -> BooleanFormula a
mkAnd = maybe mkFalse (mkAnd' . nub) . concatMapM fromAnd
  where
  -- See Note [Simplification of BooleanFormulas]
  fromAnd :: LBooleanFormula a -> Maybe [LBooleanFormula a]
  fromAnd (L _ (And xs)) = Just xs
     -- assume that xs are already simplified
     -- otherwise we would need: fromAnd (And xs) = concat <$> traverse fromAnd xs
  fromAnd (L _ (Or [])) = Nothing
     -- in case of False we bail out, And [..,mkFalse,..] == mkFalse
  fromAnd x = Just [x]
  mkAnd' [x] = unLoc x
  mkAnd' xs = And xs

mkOr :: Eq a => [LBooleanFormula a] -> BooleanFormula a
mkOr = maybe mkTrue (mkOr' . nub) . concatMapM fromOr
  where
  -- See Note [Simplification of BooleanFormulas]
  fromOr (L _ (Or xs)) = Just xs
  fromOr (L _ (And [])) = Nothing
  fromOr x = Just [x]
  mkOr' [x] = unLoc x
  mkOr' xs = Or xs

{-
Note [Simplification of BooleanFormulas]
~~~~~~~~~~~~~~~~~~~~~~
The smart constructors (`mkAnd` and `mkOr`) do some attempt to simplify expressions. In particular,
 1. Collapsing nested ands and ors, so
     `(mkAnd [x, And [y,z]]`
    is represented as
     `And [x,y,z]`
    Implemented by `fromAnd`/`fromOr`
 2. Collapsing trivial ands and ors, so
     `mkAnd [x]` becomes just `x`.
    Implemented by mkAnd' / mkOr'
 3. Conjunction with false, disjunction with true is simplified, i.e.
     `mkAnd [mkFalse,x]` becomes `mkFalse`.
 4. Common subexpression elimination:
     `mkAnd [x,x,y]` is reduced to just `mkAnd [x,y]`.

This simplification is not exhaustive, in the sense that it will not produce
the smallest possible equivalent expression. For example,
`Or [And [x,y], And [x]]` could be simplified to `And [x]`, but it currently
is not. A general simplifier would need to use something like BDDs.

The reason behind the (crude) simplifier is to make for more user friendly
error messages. E.g. for the code
  > class Foo a where
  >     {-# MINIMAL bar, (foo, baq | foo, quux) #-}
  > instance Foo Int where
  >     bar = ...
  >     baz = ...
  >     quux = ...
We don't show a ridiculous error message like
    Implement () and (either (`foo' and ()) or (`foo' and ()))
-}

----------------------------------------------------------------------
-- Evaluation and simplification
----------------------------------------------------------------------

isFalse :: BooleanFormula a -> Bool
isFalse (Or []) = True
isFalse _ = False

isTrue :: BooleanFormula a -> Bool
isTrue (And []) = True
isTrue _ = False

eval :: (a -> Bool) -> BooleanFormula a -> Bool
eval f (Var x)  = f x
eval f (And xs) = all (eval f . unLoc) xs
eval f (Or xs)  = any (eval f . unLoc) xs
eval f (Parens x) = eval f (unLoc x)

-- Simplify a boolean formula.
-- The argument function should give the truth of the atoms, or Nothing if undecided.
simplify :: Eq a => (a -> Maybe Bool) -> BooleanFormula a -> BooleanFormula a
simplify f (Var a) = case f a of
  Nothing -> Var a
  Just b  -> mkBool b
simplify f (And xs) = mkAnd (map (\(L l x) -> L l (simplify f x)) xs)
simplify f (Or xs) = mkOr (map (\(L l x) -> L l (simplify f x)) xs)
simplify f (Parens x) = simplify f (unLoc x)

-- Test if a boolean formula is satisfied when the given values are assigned to the atoms
-- if it is, returns Nothing
-- if it is not, return (Just remainder)
isUnsatisfied :: Eq a => (a -> Bool) -> BooleanFormula a -> Maybe (BooleanFormula a)
isUnsatisfied f bf
    | isTrue bf' = Nothing
    | otherwise  = Just bf'
  where
  f' x = if f x then Just True else Nothing
  bf' = simplify f' bf

-- prop_simplify:
--   eval f x == True   <==>  isTrue  (simplify (Just . f) x)
--   eval f x == False  <==>  isFalse (simplify (Just . f) x)

-- If the boolean formula holds, does that mean that the given atom is always true?
impliesAtom :: Eq a => BooleanFormula a -> a -> Bool
Var x  `impliesAtom` y = x == y
And xs `impliesAtom` y = any (\x -> (unLoc x) `impliesAtom` y) xs
           -- we have all of xs, so one of them implying y is enough
Or  xs `impliesAtom` y = all (\x -> (unLoc x) `impliesAtom` y) xs
Parens x `impliesAtom` y = (unLoc x) `impliesAtom` y

implies :: Eq a => BooleanFormula a -> BooleanFormula a -> Bool
x `implies` Var y  = x `impliesAtom` y
x `implies` And ys = all (implies x . unLoc) ys
x `implies` Or ys  = any (implies x . unLoc) ys
x `implies` Parens y  = x `implies` (unLoc y)

----------------------------------------------------------------------
-- Pretty printing
----------------------------------------------------------------------

-- Pretty print a BooleanFormula,
-- using the arguments as pretty printers for Var, And and Or respectively
pprBooleanFormula' :: (Rational -> a -> SDoc)
                   -> (Rational -> [SDoc] -> SDoc)
                   -> (Rational -> [SDoc] -> SDoc)
                   -> Rational -> BooleanFormula a -> SDoc
pprBooleanFormula' pprVar pprAnd pprOr = go
  where
  go p (Var x)  = pprVar p x
  go p (And []) = cparen (p > 0) $ empty
  go p (And xs) = pprAnd p (map (go 3 . unLoc) xs)
  go _ (Or  []) = keyword $ text "FALSE"
  go p (Or  xs) = pprOr p (map (go 2 . unLoc) xs)
  go p (Parens x) = go p (unLoc x)

-- Pretty print in source syntax, "a | b | c,d,e"
pprBooleanFormula :: (Rational -> a -> SDoc) -> Rational -> BooleanFormula a -> SDoc
pprBooleanFormula pprVar = pprBooleanFormula' pprVar pprAnd pprOr
  where
  pprAnd p = cparen (p > 3) . fsep . punctuate comma
  pprOr  p = cparen (p > 2) . fsep . intersperse vbar

-- Pretty print human in readable format, "either `a' or `b' or (`c', `d' and `e')"?
pprBooleanFormulaNice :: Outputable a => BooleanFormula a -> SDoc
pprBooleanFormulaNice = pprBooleanFormula' pprVar pprAnd pprOr 0
  where
  pprVar _ = quotes . ppr
  pprAnd p = cparen (p > 1) . pprAnd'
  pprAnd' [] = empty
  pprAnd' [x,y] = x <+> text "and" <+> y
  pprAnd' xs@(_:_) = fsep (punctuate comma (init xs)) <> text ", and" <+> last xs
  pprOr p xs = cparen (p > 1) $ text "either" <+> sep (intersperse (text "or") xs)

instance (OutputableBndr a) => Outputable (BooleanFormula a) where
  ppr = pprBooleanFormulaNormal

pprBooleanFormulaNormal :: (OutputableBndr a)
                        => BooleanFormula a -> SDoc
pprBooleanFormulaNormal = go
  where
    go (Var x)    = pprPrefixOcc x
    go (And xs)   = fsep $ punctuate comma (map (go . unLoc) xs)
    go (Or [])    = keyword $ text "FALSE"
    go (Or xs)    = fsep $ intersperse vbar (map (go . unLoc) xs)
    go (Parens x) = parens (go $ unLoc x)

----------------------------------------------------------------------
-- Binary
----------------------------------------------------------------------

instance Binary a => Binary (BooleanFormula a) where
  put_ bh (Var x)    = putByte bh 0 >> put_ bh x
  put_ bh (And xs)   = putByte bh 1 >> put_ bh xs
  put_ bh (Or  xs)   = putByte bh 2 >> put_ bh xs
  put_ bh (Parens x) = putByte bh 3 >> put_ bh x

  get bh = do
    h <- getByte bh
    case h of
      0 -> Var    <$> get bh
      1 -> And    <$> get bh
      2 -> Or     <$> get bh
      _ -> Parens <$> get bh


text:
@ExportPackage
package com.yahoo.vespa.model.builder.xml.dom;

import com.yahoo.osgi.annotation.ExportPackage;


text:
(function() {

    var browseModule = angular.module('angularify-browse', [
        'ngRoute',
        'spotify'
    ]);

    browseModule.directive('browseAlbum', function() {
        return {
            restrict : 'E',
            templateUrl : 'modules/browse/directives-browse-album.html',
            scope : {
                albumId : '=id'
            },
            controller : function($scope, $routeParams, SpotifyService) {
                var id = ($routeParams && $routeParams.albumId) ? $routeParams.albumId : $scope.albumId;
                SpotifyService.album(id).then(function(response) {
                    $scope.album = response.data;
                });
            }
        }
    });
}());


text:
// @flow
/* eslint-disable max-len */
import {
  getRoles,
  isAuthorizeDirectiveDefined
} from 'create-graphql-server-authorization';

import { lcFirst, ucFirst } from './capitalization';
import generatePerField from './generatePerField';

import {
  CREATE,
  USER_LITERAL,
  ROLE_FIELD_DEFAULT,
  SINGULAR,
  PAGINATED,
  MODEL,
  RESOLVER,
  SCHEMA
 } from './constants';

/**
 * gets context for later template compilation
 * reads schema and determines data context for code replacements
 * @public
 * @param {Object} inputSchema - schema of the type
 * @param {string} User - name of the user model for User model context
 * @param {string} codeType - to distinguish MODEL/RESOLVER runs
 * @return {Object} templateContext - data context for template compilation
 *
 * @property {boolean} authorize - if authorization logic is there
 * @property {boolean} isUserType- if it is the User type
 * @property {string} typeName - name of the type with starting lower case
 * @property {string} TypeName - name of the type with starting upper case
 * @property {string} User - name of the user model
 * @property {Object} userRoles - authorizations matrix for userRole
 * @property {Object} docRoles - authorization matrix for docRole
 * @property {string} firstUserRole - the role for protectFields
 * @property {string} roleField - field name where the userRole is stored
 * @property {array} singularFields - fields array
 * @property {array} paginatedFields - fields array
 * @property {object} schema - schema definition
 */

export default function getContext(
  inputSchema = {}, User = USER_LITERAL, codeType = MODEL) {
  // for field generation
  // prepare template context for later compilation
  const authorize = isAuthorizeDirectiveDefined(inputSchema);

  // read TypeName out of inputSchema
  const TypeName = inputSchema.definitions[0].name.value;
  const typeName = lcFirst(TypeName);
  const isUserType = TypeName === User;

  // getting the role definitions out of the @authorize directive
  const { userRoles, docRoles, roleFieldName } = getRoles(
    authorize,
    inputSchema
  );

  // get generated fields for resolvers and models
  const { singularFields, paginatedFields } = getFields(inputSchema, codeType);

  // prepare protectFields only on for the "User" type as an example
  // roleField shouldn't be empty
  // it checks, if the field is there
  // it takes the first found userRole into the protectFields as a suggestion
  // to the programmer, assuming this is the most important role,
  // with higher authorization (see in README.md)
  const firstUserRole = userRoles[CREATE][0] ? userRoles[CREATE][0] : ``;
  const roleField = roleFieldName
    ? `${roleFieldName}`
    : `${ROLE_FIELD_DEFAULT}`;

  // create proper strings for the roles, for template injection
  Object.keys(userRoles).forEach(mode => {
    userRoles[mode] = prepareString(userRoles[mode]);
  });
  Object.keys(userRoles).forEach(mode => {
    docRoles[mode] = prepareString(docRoles[mode]);
  });

  // this is the returned data context for the later template processing
  return {
    authorize,
    isUserType,
    typeName,
    TypeName,
    User,
    userRoles,
    docRoles,
    firstUserRole,
    roleField,
    singularFields,
    paginatedFields
  };
}

/**
 * prepares contexts for singular and paginated field associations
 * @param {Object} inputSchema - schema of the type
 * @param {string} codeType - to distinguish between MODEL/RESOLVER
 * @return {Object} fields - fields for associations
 * @property singularFields - fields for singular associations
 * @property paginatedFields - fields for paginated associations
 */

function getFields(inputSchema, codeType) {
  const type = inputSchema.definitions[0];

  // prepare singular and paginated field arrays for the field templates
  const singularFields = [];
  const paginatedFields = [];

  // generators for the different field association types:
  const generators = {

    // singular association @belongsTo
    belongsTo(replacements) {
      const field = buildFieldContext(SINGULAR, replacements, codeType);
      singularFields.push(field);
      return field;
    },

    // paginated association @belongsToMany
    belongsToMany(replacements) {
      const { typeName, fieldName } = replacements;
      const field = buildFieldContext(PAGINATED, {
        ...replacements,
        query: `_id: { $in: ${typeName}.${fieldName}Ids || [] }`
      }, codeType);
      paginatedFields.push(field);
      return field;
    },

    // paginated association @hasMany
    hasMany(replacements, { as }) {
      const { typeName } = replacements;
      const field = buildFieldContext(PAGINATED, {
        ...replacements,
        query: `${as || typeName}Id: ${typeName}._id`
      }, codeType);
      paginatedFields.push(field);
      return field;
    },

    // paginated association @hasAndBelongsToMany
    hasAndBelongsToMany(replacements, { as }) {
      const { typeName } = replacements;
      const field = buildFieldContext(PAGINATED, {
        ...replacements,
        query: `${as || typeName}Ids: ${typeName}._id`
      }, codeType);
      paginatedFields.push(field);
      return field;
    }
  };

  generatePerField(type, generators);

  return { singularFields, paginatedFields };
}

/**
 * builds a field's context
 *
 * @param {string} fieldtype - SINGULAR or PAGINATED field type
 * @param {object} context - context for the template partial
 *
 * @property {string} typeName - name of the type
 * @property {string} fieldName - name of the field
 * @property {string} argsStr - arguments of the field
 * @property {string} ReturnTypeName - type to build association with
 * @property {string} query - query for the data access to the referenced type
 *
 * @param {string} codeType - to distinguish between MODEL/RESOLVER
 * @return {Object} field - field for an association
 *
 * @property {string} fieldType - SINGULAR or PAGINATED
 * @property {string} fieldName - name of the field
 * @property {string} typeName - name of the type with first lower character
 * @property {string} TypeName -  name of the type with first upper character
 * @property {string} ReturnTypeName - name of the type to associate
 * @property {string} argsString - argument string for parameters
 * @property {string} argsFields - fields to pass on to the association
 * @property {string} query - which fields to query during association
 */

function buildFieldContext(fieldType, {
  typeName, fieldName, argsStr, ReturnTypeName, query }, codeType) {
  // clone the string
  let argFields = (' ' + argsStr).slice(1);

  // populate some arguments with defaults
  const argsWithDefaultsStr = argsStr
    .replace('lastCreatedAt', 'lastCreatedAt = 0')
    .replace('limit', 'limit = 10');

  // prepares a fields string to pass on to the referenced type
  if (fieldType === PAGINATED && argFields !== '') {
    argFields = argFields.replace('{ ', '{ baseQuery, ');
  }

  // returns the build field context
  return {
    fieldType: fieldType || '',
    fieldName: fieldName || '',
    typeName: typeName || '',
    TypeName: ucFirst(typeName) || '',
    ReturnTypeName: ReturnTypeName || '',
    argsString: argsWithDefaultsStr || '',
    argsFields: argFields || '',
    query: query || ''
  };
}

/**
 * prepare roles for code generator
 * convert array to String value
 * replace " by '
 * @private
 * @param {array} role - name of role
 * @return {string} roleString - role string
 */

function prepareString(role) {
  return JSON.stringify(role).replace(/"/g, "'").replace(/,/g, ', ');
}


text:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content=" Static site generator for Grunt.js and Yeoman. Assemble makes it dead simple to build modular sites, blogs, gh-pages, components and documentation from reusable templates and data.">
    <meta name="author" content="http://twitter.com/jonschlinkert">
    <title>
      Dates | Assemble
    </title>

    <link rel="stylesheet" href="../assets/css/assemble.css">
    <link rel="stylesheet" href="../assets/css/markdown.css">

    <link href='http://fonts.googleapis.com/css?family=Open+Sans:400italic,600italic,400,300,600,700' rel='stylesheet' type='text/css'>

    <link rel="apple-touch-icon" href="../assets/img/light/apple-touch-icon.png">
    <link rel="apple-touch-icon" sizes="114x114" href="../assets/img/light/apple-touch-icon-114x114.png">
    <link rel="apple-touch-icon" sizes="120x120" href="../assets/img/light/apple-touch-icon-120x120.png">
    <link rel="apple-touch-icon" sizes="144x144" href="../assets/img/light/apple-touch-icon-144x144.png">
    <link rel="apple-touch-icon" sizes="152x152" href="../assets/img/light/apple-touch-icon-152x152.png">
    <link rel="apple-touch-icon" sizes="57x57" href="../assets/img/light/apple-touch-icon-57x57.png">
    <link rel="apple-touch-icon" sizes="72x72" href="../assets/img/light/apple-touch-icon-72x72.png">
    <link rel="apple-touch-icon" sizes="76x76" href="../assets/img/light/apple-touch-icon-76x76.png">
    <link rel="shortcut icon" href="../assets/img/light/favicon.ico" type="image/x-icon">

          <button class="navbar-toggle" type="button" data-toggle="collapse" data-target=".bs-navbar-collapse">

          </button>
          ASSEMBLE

              Docs

              Plugins

              Helpers

              Blog

              GitHub Repo

              helpers /  Dates

                Overview

              Special Helpers

                Compose

                Aggregate

              Categories

                Code

                Collections

                Comparison

                Content

                Data

                Dates

                HTML

                Inflections

                Logging

                Markdown

                Math

                Miscellaneous

                Numbers

                Path

                Readme

                Strings

                URL

Dates

{{formatDate}}

Formats a date into a string given a format. Accepts any value that can be passed to new Date(). This helper is a port of the formatDate-js  library by Michael Baldry.

Parameters: format String, required

The format string, according to these tokens:
                strftime

Given this data:

date = new  Date()

And these templates:

{{formatDate date "%m/%d/%Y"}}
{{formatDate date "%I:%M%p"}}
{{formatDate date "%F"}}
{{formatDate date "%Y%m%dT%H%M%S%z"}}

The output would be:

07/26/2012
11:38PM
2012-07-26
20120726T233805-0004

{{moment}}

A helper to master time! Combining the powers of Assemble, Handlebars.js and Moment.js. This helper leverages Moment.js to provide ultimate control over manipulating time and dates in your templates.

Quickstart

Install the helper:

npm i helper-moment --save-dev

Now add the helper to Assemble's options:

assemble: {
  options: {
    // Assemble will automatically resolve the path
    helpers: ['helper-moment', 'foo/*.js' ]
  }
}

Options

The moment.js lib has plenty of features and options, these examples are just the tip of the iceberg of what
              moment.js can do.

Tips

Remember that:

{{moment method=null}} means moment().method(), and

{{moment somedate method="something"}} means moment(somedate).method("something").

Also, the handlebars syntax does not allow you pass certain values (like arrays and objects) directly from the tag, so you may need to use YAML frontmatter or supply JSON/YAML data to run those.

Usage Examples

Optional YAML Front Matter

YAML front matter is not required, but we'll use it hear to supply our example data for purposes of demonstration:

---
example: <%= new  Date ("Sun Jun 30 2011 01:53:23 GMT+0300 (EEST)" ) %>
exampletextdate: 'Sun, 30 Jun 2012 11:19:15 +0300'
inputformats: ["ddd, DD MMM YYYY HH:mm:ss ZZ", "MMMM YYYY"]
daysadd:
  days: 5
timeago:
  years: 5
duration:
  hours: 2
  minutes: 33}
---
Unix timestamp of now
{{moment }}

Results in:

1372599296756

Current time with formatting

{{moment  format ="HH:mm:ss" }}

Results in:

16:34:56

Specific time with formatting

{{moment  example  format ="HH:mm:ss" }}

Results in:

01:53:23

Specific unix timestamp with formatting

{{moment  unixtimestamp  format ="HH:mm:ss" }}

Results in:

19:17:56

Specific datetime with formatting

{{moment  example  format ="dddd, DD MMMM YYYY HH:mm:ss ZZ" }}

Results in:

Sunday, 30 June 2013 01:53:23 +0300

Language support

{{moment  example  lang ="fi"  format ="dddd, DD MMMM YYYY HH:mm:ss ZZ" }}

Results in:

sunnuntai, 30 kesäkuu 2013 01:53:23 +0300

Is the added date valid?

{{moment  example  isValid =null }}

Results in:

true

Input as a string, with defined format

{{moment  [exampletextdate,"ddd, DD MMM YYYY HH:mm:ss ZZ" ] format ="MMMM YYYY" }}

Results in:

June 2013

Multiple formats

When multiple formats are used, moment.js attempts to use the "correct" one

{{moment  [exampletextdate,formats ] format ="MMMM YYYY" }}

Results in:

June 2013

Specific datetime with formatting, converted to UTC

{{moment  example  UTC =null  format ="dddd, DD MMMM YYYY HH:mm:ss ZZ" }}

Results in:

Saturday, 29 June 2013 22:53:23 +0000

Getters and setters

Example: get week of year, depends on lang (see
              moment.js documentation for more details)

The week number in Finland is {{moment  example  lang ="fi"  week =null }}

Results in:

The week number in Finland is 26

              Manipulating

See the
              moment.js/manipulating documentation for more details.

add days

{{moment  example  format ="dddd" }} -{{moment  example  add =daysadd  format ="dddd" }}

Results in:

Sunday-Friday

subtract years

{{moment  example  subtract =timeago  format ="YYYY" }} -{{moment  example  format ="YYYY" }}

Results in:

2008-2013

startOf month

{{moment  example  startOf ="month"  format ="dddd, DD MMMM YYYY HH:mm:ss ZZ" }}

Results in:

Saturday, 01 June 2013 00:00:00 +0300

endOf week

{{moment  example  endOf ="week"  format ="dddd, DD MMMM YYYY HH:mm:ss ZZ" }}

Results in:

Saturday, 06 July 2013 23:59:59 +0300

Time from now

After this page is rendered, the week will end {{moment  endOf ="week"  fromNow =null }}

Results in:

After this page is rendered, the week will end in 6 days

Time from X

This helper was coded {{moment  from =example }}

Results in:

This helper was coded in 15 hours

Calendar time

The coding started {{moment  example  calendar =null }}

Results in:

The coding started Today at 1:53 AM

Diff

The difference between those two moments is {{moment  diff =example }}

Results in:

The difference between those two moments is 52893769

Days in Month

This month has {{moment  daysInMonth =null }}  days

Results in:

This month has 30 days

Days in Month

This month has {{moment  daysInMonth =null }}  days

Results in:

This month has 30 days

Duration, with humanization

The event will last {{duration  duration  humanize =null }}

Results in:

The event will last 3 hours

Contributing

In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code using
              grunt.

Author

Mikko Tapionlinna

                github.com/Arkkimaagi

License

Copyright (c) 2013 Mikko Tapionlinna, contributors. Released under the MIT license

This file was generated on Sunday, October 13, 2013.

{{now}}

Returns the current date.

Parameters: format String - The format string, according to these tokens:

                http://www.ruby-doc.org/core-1.9.3/Time.html#method-i-strftime
               (Optional)

Template:

{{now}}
{{now "%m/%d/%Y"}}

Renders to:

Thu Jul 26 2012 23:41:02 GMT-0400 (AST)
07/26/2012

{{timeago}}

Returns a human-readable time phrase from the given date.

Parameters: none

Data:

date = 'Thu Jul 22 2012 23:41:02 GMT-0400 (AST)'

Template:

{{timeago date}}

Renders to:

4 days ago

              See the template for this page →

Find an error?
                Let us know →


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Zentbl. Bakt. ParasitKde, Abt. II 107: 527 (1954)

#### Original name
Mortierella baccata E. Wolf

### Remarks
null


text:
namespace Xavalon.XamlStyler.Options
{
    public enum VisualStateManagerRule
    {
        None,
        First,
        Last,
    }
}


text:
<!DOCTYPE html>

	<meta charset="UTF-8">
	<title>案例</title>
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="stylesheet" type="text/css" href="stylesheets/normalize.css" media="screen">
	<link rel='stylesheet' type='text/css' href='https://fonts.googleapis.com/css?family=Open+Sans:400,700'>
	<link rel="stylesheet" type="text/css" href="stylesheets/stylesheet.css" media="screen">
	<link rel="stylesheet" type="text/css" href="stylesheets/github-light.css" media="screen">

首页

HTML5

CSS3

Javascript

NodeJS

React

Vue

			Welcome to GitHub Pages.

This automatic page generator is the easiest way to create beautiful pages for all of your projects. Author your page content here using GitHub Flavored Markdown, select a template crafted by a designer, and publish. After your page is generated, you can check out the new gh-pages branch locally. If you're using GitHub Desktop, simply sync your repository and you'll see the new branch.

			Designer Templates

We've crafted some handsome templates for you to use. Go ahead and click 'Continue to layouts' to browse through them. You can easily go back to edit your page before publishing. After publishing your page, you can revisit the page generator and switch to another theme. Your Page content will be preserved.

			Creating pages manually

If you prefer to not use the automatic generator, push a branch named gh-pages to your repository to create a page manually. In addition to supporting regular HTML content, GitHub Pages support Jekyll, a simple, blog aware static site generator. Jekyll makes it easy to create site-wide headers and footers without having to copy them across every page. It also offers intelligent blog support and other advanced templating features.

			Authors and Contributors

You can @mention a GitHub username to generate a link to their profile. The resulting <a> element will link to the contributor's GitHub Profile. For example: In 2007, Chris Wanstrath (@defunkt), PJ Hyett (@pjhyett), and Tom Preston-Werner (@mojombo) founded GitHub.

			Support or Contact

Having trouble with Pages? Check out our
			documentation or
			contact support and we'll help you sort it out.

			Mydemo is maintained by FantasyLian.

			This page was generated by GitHub Pages using the Cayman theme by Jason Long.


text:
package com.miguelgaeta.bootstrap.mg_recycler;

import android.support.v7.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

import rx.functions.Func1;

/**
 * Created by Miguel Gaeta on 5/6/15.
 */
@SuppressWarnings("unused")
public abstract class MGRecyclerAdapterSimple extends MGRecyclerAdapter {

    // Data list that powers the adapter.
    private MGRecyclerDataList<MGRecyclerDataPayload.Contract> data = MGRecyclerDataList.create(this, new ArrayList<MGRecyclerDataPayload.Contract>(), new Func1<MGRecyclerDataPayload.Contract, String>() {
        @Override
        public String call(MGRecyclerDataPayload.Contract o) {
            return o.getKey();
        }
    });

    /**
     * This adapter streamlines common recycler view operations
     * and boiler plate code.
     */
    public MGRecyclerAdapterSimple(RecyclerView recycler) {
        super(recycler);
    }

    @Override
    public int getItemViewType(int position) {

        return data.get().get(position).getType();
    }

    @Override
    public int getItemCount() {

        return data.get().size();
    }

    /**
     * Add a callback action for when the
     * underlying data is updated.
     */
    public void setUpdate(MGRecyclerData.DataUpdated<List<MGRecyclerDataPayload.Contract>> updated) {

        data.setUpdated(updated);
    }

    /**
     * Get data item object at specified position.
     */
    public Object getItem(int position) {

        return data.get().get(position).getItem();
    }

    /**
     * Provide a new data set to the adapter.  Will take
     * care of updating the data set automatically.
     */
    public void setData(List<MGRecyclerDataPayload.Contract> data) {

        this.data.set(data);
    }

    public void unsubscribeFromUpdates() {

        data.unsubscribeFromUpdates();
    }
}


text:
package org.i3xx.cloud.data.object.service;

import java.util.List;

import org.i3xx.cloud.data.object.domain.Obid;
import org.i3xx.cloud.data.object.domain.ObidRepository;
import org.i3xx.cloud.data.object.util.UuidTool;

public class CreateObjectServiceImpl implements CreateObjectService {

	ObidRepository obidRepository;

	public CreateObjectServiceImpl(ObidRepository obidRepository) {
		this.obidRepository = obidRepository;
	}

	/**
	 * @param classname
	 * @param uuidUser
	 * @param uuidOwner
	 * @return
	 */
	public String createObject(String classname, String uuidUser, String uuidOwner) {
		long currentTime = System.currentTimeMillis();
		String uuid = UuidTool.getOne();

		Obid obid = new Obid();

		obid.setUuid(uuid);
		obid.setClassname(classname);

		obid.setHistory(uuid);

		obid.setCreatetimestamp(currentTime);
		obid.setTransid(0);
		obid.setObtimestamp(currentTime);

		obid.setCreateuser(uuidUser);
		obid.setObuser(uuidUser);
		obid.setOwner(uuidOwner);
		obid.setLabel("");

		obidRepository.save(obid);

		return obid.getUuid();
	}

	/**
	 * Clones an Object with the exception of a new random generated UUID.
	 * The other fields are copied as they are, also the time fields.
	 *
	 * @param origin the Object to clone
	 * @return
	 */
	public String cloneObject(Obid origin) {
		String uuid = UuidTool.getOne();
		boolean isCurrentState = origin.getHistory()==null || origin.getHistory().equals("") ||
				origin.getUuid().equals(origin.getHistory());

		Obid obid = new Obid();

		obid.setUuid(uuid);
		obid.setClassname(origin.getClassname());
		obid.setName(origin.getName());

		obid.setHistory( isCurrentState ? uuid : origin.getHistory() );

		obid.setCreatetimestamp(origin.getCreatetimestamp());
		obid.setTransid(origin.getTransid());
		obid.setObtimestamp(origin.getObtimestamp());

		obid.setCreateuser(origin.getCreateuser());
		obid.setObuser(origin.getObuser());
		obid.setOwner(origin.getOwner());
		obid.setLabel(origin.getLabel());

		obidRepository.save(obid);

		return obid.getUuid();
	}

	/**
	 * @param uuid
	 * @return
	 */
	public Obid getOne(String uuid) {
		List<Obid> list = obidRepository.queryByUuid(uuid);
		if(list.size()==0) {
			return null;
		}else if(list.size()==1) {
			return list.get(0);
		}else{
			//should not happen
			return list.get(0);
		}
	}

	/**
	 * @param uuid
	 * @return
	 */
	public List<Obid> getAll(String uuid) {
		List<Obid> list = obidRepository.queryByUuid(uuid);
		return list;
	}

	/**
	 * @param uuid
	 * @return
	 */
	public Obid findOne(Long guid) {
		return obidRepository.findOne(guid);
	}
}


text:
 ![Our sweet logo designed by Dominic Flask](http://www.startupwichita.com/assets/tophandlogo-02-4bd31d8d294b67de4cc32b2c5141d6a9.png?style="align:center")
# StartupWichita.com
Ruby on Rails application for communities, their news, events, and resources; built for what Wichita, Kansas needed in their tech and startup scene.

Well, hello there. My name is [Kenton Hansen](http://startupwichita.com/profile/kenton-hansen). You might remember me from such works as **"Startup Weekend Wichita"** or **"The Labor Party."** Today, however, I'm here to talk about this web application started at a Hackathon in March 2014 with [devICT](http://devict.org).

The projects beta was completed and launched about three months later at [startupwichita.com](http://startupwichita.com), and we as a community have been contributing to its development since then.

## Find an Issue?
Please report any problems you might encounter by [creating an Issue](https://github.com/StartupWichita/startupwichita.com/issues).

## Requirements

- ruby version 2.2.0
- ImageMagick or GraphicsMagick command-line tool (used in
  [minimagick](https://github.com/minimagick/minimagick) gem)
- bundler

## Installation and Setup

Clone the repo and `cd` into the directory.

```ruby
git clone https://github.com/StartupWichita/startupwichita.com.git
cd startupwichita.com
```

Then run `bundle install`
Run the mirgations `rake db:migrate`
Start server `rails s`

**We use sqlite3 as database. Data seeding is also included in the migrations.**

### Alternatively, use docker-compose

Assuming you have docker and docker-compose installed on your system.

`docker-compose up` - builds the image, runs migrations and seeding, and starts server. Should be accessible at port 3000 once running.

To run commands in the context of the app, use: `docker-compose run app <your cmd>`. For example: `docker-compose run app bundle exec rake db:migrate`.

## We would love for you to use this app for your community or to contribute:

### Pull requests generally

 - **The smaller the proposed change, the better.** If you'd like to propose two unrelated changes, submit two pull requests.
 - **The more information, the better.** Make judicious use of the pull request body. Describe what changes were made, why you made them, and what impact they will have for users.
 - Pull requests are easy and fun. If this is your first pull request, it may help to understand GitHub Flow.
 - If you're submitting a code contribution, be sure to read the code contributions section below.

 ### Submitting a pull request via github.com
 1. Navigate to the file within StartupWichita/startupwichita.com that you'd like to edit.
 2. Click the pencil icon in the top right corner to edit the file
 3. Make your proposed changes
 4. Click "Propose file change"
 5. Click "Create pull request"
 6. Add a descriptive title and detailed description for your proposed change. The more information the better.
 7. Click "Create pull request"

 That's it! You'll be automatically subscribed to receive updates as others review your proposed change and provide feedback.

 ### Submitting a pull request via Git command line
 1. Fork the project by clicking "Fork" in the top right corner of StartupWichita/startupwichita.com.
 2. Clone the repository locally `git clone https://github.com/StartupWichita/startupwichita.com.git`
 3. Create a new, descriptively named branch to contain your change <br> `git checkout -b name_of_your_branch`
 4. Push the branch up `git push origin name_of_your_branch`
 5. Create a pull request by visiting https://github.com/your-username/startupwichita.com and following the instructions at the top of the screen.