text:
* TOC
{:toc}

{% include templates/solution-templates.md %}

Smart Office template represents a basic work space monitoring and management solution.
With this template you get an interactive dashboard with the ability to control HVAC system,
and have a high-level report of key metrics necessary for effective and proactive office management.

{% include images-gallery.html imageCollection="solution-highlights" %}

### Dashboard

As part of this solution, we have created the "Smart Office" dashboard that displays data from multiple devices. You may use the dashboard to:

* observe office sensors and their location;
* browse indoor temperature and power consumption history;
* monitor temperature alarms;
* control HVAC (requires connected device);
* observe specific details for each sensor.

The dashboard has multiple states. The main state displays the list of the devices, their location on the office map as well as the list of their alarms.
You may drill down to the device details state by clicking on the table row. The device details are specific to the device type.

You may always customize the "Smart Office" dashboard using dashboard development [guide](/docs/{{docsPrefix}}user-guide/dashboards/).

### Devices

We have already created "Office" asset and 4 devices related to it. We have also loaded demo data for those devices.
See solution [instructions](/docs/{{docsPrefix}}solution-templates/overview/#install-solution-template) for the list of created devices and their credentials.

Solution expects specific telemetry from each device based on its type.
You may find payload examples below.

**Energy meter**

Payload example:

```json
{"voltage":  220, "frequency":  60, "amperage": 16, "power": 3000, "energy": 300 }
```
{: .copy-code}

**Water meter**

Payload example:

```json
{"water": 2.3, "voltage": 3.9 }
```
{: .copy-code}

**Smart sensor**

Payload example:

```json
{"co2": 500, "tvoc": 0.3, "temperature": 22.5, "humidity": 50, "occupancy": true}
```
{: .copy-code}

**HVAC**

Payload example:

```json
{"airFlow": 300, "targetTemperature": 21.5, "enabled": true}
```
{: .copy-code}

HVAC device also accepts commands from the dashboard to enable/disable air conditioning as well as set target temperature.
The commands are sent using the platform [RPC API](/docs/{{docsPrefix}}user-guide/rpc/).

You may find the exact commands to send data on behalf of created devices in the solution [instructions](/docs/{{docsPrefix}}solution-templates/overview/#install-solution-template).
See [connecting devices](/docs/{{docsPrefix}}getting-started-guides/connectivity/) for various connectivity options to connect real devices.

### Alarms

Alarms are generated using two Alarm rules in the "smart-sensor" [device profile](/docs/{{docsPrefix}}user-guide/device-profiles/).


text:
module VideoHelper
  def stub_yt
    url = OpenStruct.new(thumbnail_url: 'https://i.ytimg.com/vi/2iOQ053s_oM/mqdefault.jpg')
    allow(Yt::Video).to receive(:new).and_return(url)
    allow(url).to receive(:thumbnail_url).and_return(url.thumbnail)
  end
end

redpajama_set_name: RedPajamaGithub


text:
@interface YALCreditCardNumberFormatter : NSObject <YALFormatter>

@end


text:
package com.unionpaysmart.data.sdk.model.bill.request;

import com.unionpaysmart.data.sdk.model.base.request.BaseRequest;
import com.unionpaysmart.data.sdk.valid.annotation.NotBlank;

/**
 * 账单下载 输入参数
 *
 * @author Nie Xiongding
 * @since 2015年3月3日 上午9:45:58
 */
public class BillDownloadRequest extends BaseRequest {
    @NotBlank
    private String uuid; // 文件标识符
    private String resType; // 返回值状态类型

    /**
     * @return uuid
     */
    public String getUuid() {
        return uuid;
    }

    /**
     * @param uuid
     *     文件标识符 <b>必填</b>
     */
    public void setUuid(String uuid) {
        this.uuid = uuid;
    }

    /**
     * @return resType
     */
    public String getResType() {
        return resType;
    }

    /**
     * @param resType
     *     返回值状态类型
     */
    public void setResType(String resType) {
        this.resType = resType;
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Atti Ist. bot. Univ. Lab. crittog. Pavia 3(3): 177 (1927)

#### Original name
Septoria galii Curzi & Barbaini

### Remarks
null


text:
package com.proinnovate.sysconfws

import language.reflectiveCalls
import java.io.{InputStreamReader, BufferedReader}
import scala.collection.mutable.ListBuffer
import scala.reflect.runtime.{universe => ru}

object PackList {

  lazy val packageNames = packages.keys

  lazy val packages: Map[String,Pack] = packClassNames.map(packObjectByClassName).map(x => (x.name, x)).toMap

  // PRIVATE

  private lazy val packClassNames: Seq[String] = {
    val is = java.lang.Thread.currentThread.getContextClassLoader.getResourceAsStream("com/proinnovate/sysconfws/pack")

    val reader = new BufferedReader(new InputStreamReader(is, "UTF-8"))
    val classes = ListBuffer[String]()
    var line = reader.readLine()
    while (line != null) {
      classes += line
      line = reader.readLine()
    }
    is.close()
    classes.map(x => x.substring(0, x.length - 6)).filter(_.endsWith("$")).map(x => x.substring(0,x.length - 1))
  }

  private def packObjectByClassName(name: String): Pack = {
    val rm = ru.runtimeMirror(getClass.getClassLoader)
    val module = rm.staticModule(s"com.proinnovate.sysconfws.pack.$name")
    val obj = rm.reflectModule(module)
    obj.instance.asInstanceOf[Pack]
  }

}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using manualisator.DBSchema;

namespace manualisator
{
    public partial class SelectManualsToGenerate : Form
    {
        private readonly List<Manual> ManualsToGenerate;

        public SelectManualsToGenerate(Dictionary<long, Manual> manualByID, List<Manual> manualsToGenerate)
        {
            InitializeComponent();
            ManualsToGenerate = manualsToGenerate;

            // need to sort the list alphabetically
            foreach (Manual m in manualByID.Values.OrderBy(m => m.Device))
            {
                var item = listView1.Items.Add(m.Device);
                item.SubItems.Add(m.Language);
                item.SubItems.Add(m.Title1);
                item.SubItems.Add(m.Title2);
                item.Tag = m;
            }
            btOK.Enabled = false;
            lbWarning.Text = "Sie müssen mindestens ein Handbuch auswählen.";
        }

        private void listView1_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
        {
            bool enabled = listView1.SelectedItems.Count > 0;

            lbWarning.Visible = !enabled;
            btOK.Enabled = enabled;

        }

        private void btOK_Click(object sender, EventArgs e)
        {
            foreach(ListViewItem item in listView1.SelectedItems)
            {
                ManualsToGenerate.Add(item.Tag as Manual);
            }
            DialogResult = DialogResult.OK;
            Close();
        }

        private void listView1_DoubleClick(object sender, EventArgs e)
        {
            if(listView1.SelectedItems.Count > 0)
            {
                btOK_Click(sender, e);
            }
        }
    }
}


text:
package de.hpi.ingestion.dataimport.wikidata

import com.holdenkarau.spark.testing.SharedSparkContext
import org.scalatest.{FlatSpec, Matchers}

class TagEntitiesTest extends FlatSpec with SharedSparkContext with Matchers {
    "Shorter paths" should "be added" in {
        val oldClasses = TestData.oldClassMap()
        val newClasses = TestData.newClassMap()
        val classMap = TagEntities.addShorterPaths(newClasses, oldClasses)
        val expectedMap = TestData.classMap()
        classMap shouldEqual expectedMap
    }

    "Subclass map" should "be built" in {
        val entries = sc.parallelize(TestData.subclassOfProperties())
        val classMap = TagEntities.buildSubclassMap(entries, TestData.classesToTag())
        val expectedMap = TestData.classMap()
        classMap shouldEqual expectedMap
    }

    it should "be properly reduced" in {
        val reducedSubclasses = TestData.reducableClassMaps().reduce(TagEntities.mergeSubclassMaps)
        val expectedSubclasses = TestData.classMap()
        reducedSubclasses shouldEqual expectedSubclasses
    }

    "Wikidata entity" should "be properly translated into SubclassEntry" in {
        val entries = TestData.classWikidataEntities()
            .map(TagEntities.translateToSubclassEntry)
        val expectedEntries = TestData.subclassEntries()
        entries shouldEqual expectedEntries
    }

    "Instance-of entities" should "be updated" in {
        val job = new TagEntities
        val pathKey = job.settings("wikidataPathProperty")
        val entries = sc.parallelize(TestData.subclassEntries())
        val updatedEntries = TagEntities.updateEntities(entries, TestData.classMap(), pathKey).collect.toSet
        val expectedEntries = TestData.updatedInstanceOfProperties().toSet
        updatedEntries shouldEqual expectedEntries
    }

    it should "be updated correctly" in {
        val job = new TagEntities
        val pathKey = job.settings("wikidataPathProperty")
        val entries = TestData.validInstanceOfProperties()
            .map(TagEntities.updateInstanceOfProperty(_, TestData.classMap(), pathKey))
        val expectedEntries = TestData.updatedInstanceOfProperties()
        entries shouldEqual expectedEntries
    }
}


text:
DROP TABLE IF EXISTS snowplow_intermediary.visitors_source;
CREATE TABLE snowplow_intermediary.visitors_source
  DISTKEY (blended_user_id) -- Optimized to join on other snowplow_intermediary.visitors_X tables
  SORTKEY (blended_user_id) -- Optimized to join on other snowplow_intermediary.visitors_X tables
AS (
  SELECT
    *
  FROM (
    SELECT -- Select campaign and referer data from the earliest row (using dvce_tstamp)
      a.blended_user_id,
      a.mkt_source,
      a.mkt_medium,
      a.mkt_term,
      a.mkt_content,
      a.mkt_campaign,
      a.refr_source,
      a.refr_medium,
      a.refr_term,
      a.refr_urlhost,
      a.refr_urlpath,
      RANK() OVER (PARTITION BY a.blended_user_id
        ORDER BY a.mkt_source, a.mkt_medium, a.mkt_term, a.mkt_content, a.mkt_campaign, a.refr_source, a.refr_medium,
          a.refr_term, a.refr_urlhost, a.refr_urlpath) AS rank
    FROM snowplow_intermediary.events_enriched_final AS a
    INNER JOIN snowplow_intermediary.visitors_basic AS b
      ON  a.blended_user_id = b.blended_user_id
      AND a.dvce_tstamp = b.dvce_min_tstamp -- Replaces the FIRST VALUE window function in SQL
    GROUP BY 1,2,3,4,5,6,7,8,9,10,11 -- Aggregate identital rows (that happen to have the same dvce_tstamp)
  )
  WHERE rank = 1 -- If there are different rows with the same dvce_tstamp, rank and pick the first row
);


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Cnestis emarginata De Wild. & T.Durand

### Remarks
null


text:
pub mod os {
    pub const FAMILY: &str = "cloudabi";
    pub const OS: &str = "cloudabi";
    pub const DLL_PREFIX: &str = "lib";
    pub const DLL_SUFFIX: &str = ".so";
    pub const DLL_EXTENSION: &str = "so";
    pub const EXE_SUFFIX: &str = "";
    pub const EXE_EXTENSION: &str = "";
}


text:
<?php

namespace PHPExiftool\Driver\Tag\GeoTiff;

use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;

/**
 * @ExclusionPolicy("all")
 */
class ProjFalseEasting extends AbstractTag
{

    protected $Id = 3082;

    protected $Name = 'ProjFalseEasting';

    protected $FullName = 'GeoTiff::Main';

    protected $GroupName = 'GeoTiff';

    protected $g0 = 'GeoTiff';

    protected $g1 = 'GeoTiff';

    protected $g2 = 'Location';

    protected $Type = '?';

    protected $Writable = false;

    protected $Description = 'Proj False Easting';
}


text:
BIN = $(npm bin)
SRC = $(wildcard lib/*.js)
BUILD = $(subst lib,build,$(SRC))

build:
	@mkdir -p build
	@$(MAKE) $(BUILD)

build/%.js: lib/%.js
	@$(BIN)regenerator --include-runtime $< > $@

clean:
	@rm -rf build

test:
	$(BIN)mocha --require gnode \
		--harmony-generators \
		--require should \
		--reporter spec

.PHONY: test clean


text:
package com.bzu.yhd.pocketcampus.widget.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.text.TextUtils;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.view.ViewConfiguration;

import com.bzu.yhd.pocketcampus.R;

import java.io.Closeable;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class Util {

    /**
     * @return 状态栏高度
     */
    public static int getStatusBarHeight() {
        int result = 0;
        int resourceId = Resources.getSystem().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = Resources.getSystem().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    /**
     * 获取版本号
     *
     * @return 当前应用的版本号
     */

    public static String getVersion(Context context) {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            return info.versionName;
        } catch (Exception e) {
            e.printStackTrace();
            return context.getString(R.string.can_not_find_version_name);
        }
    }

    /**
     * @return 版本号
     */
    public static int getVersionCode(Context context) {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            return info.versionCode;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 只关注是否联网
     */
    public static boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager =
                (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }

    public static String trimCity(String city) {
        if (city.endsWith("市")) {
            return city.substring(0, city.lastIndexOf("市"));
        }
        if (city.endsWith("区")) {
            return city.substring(0, city.lastIndexOf("区"));
        }
        if (city.endsWith("县")) {
            return city.substring(0, city.lastIndexOf("县"));
        }
        if (city.endsWith("镇")) {
            return city.substring(0, city.lastIndexOf("镇"));
        }
        if (city.endsWith("乡")) {
            return city.substring(0, city.lastIndexOf("乡"));
        }

        return city;
    }

    /**
     * 判断当前日期是星期几
     *
     * @param pTime 修要判断的时间
     * @return dayForWeek 判断结果
     * @Exception 发生异常
     */
    public static String dayForWeek(String pTime) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        c.setTime(format.parse(pTime));
        int dayForWeek;
        String week = "";
        dayForWeek = c.get(Calendar.DAY_OF_WEEK);
        switch (dayForWeek) {
            case 1:
                week = "星期日";
                break;
            case 2:
                week = "星期一";
                break;
            case 3:
                week = "星期二";
                break;
            case 4:
                week = "星期三";
                break;
            case 5:
                week = "星期四";
                break;
            case 6:
                week = "星期五";
                break;
            case 7:
                week = "星期六";
                break;
        }
        return week;
    }

    /**
     * 安全的 String 返回
     *
     * @param prefix 默认字段
     * @param obj 拼接字段 (需检查)
     */
    public static String safeText(String prefix, String obj) {
        if (TextUtils.isEmpty(obj)) return "";
        return TextUtils.concat(prefix, obj).toString();
    }

    public static String safeText(String msg) {
        if (null == msg) {
            return "";
        }
        return safeText("", msg);
    }

    /**
     * 天气代码 100 为晴 101-213 500-901 为阴 300-406为雨
     *
     * @param code 天气代码
     * @return 天气情况
     */
    public static String getWeatherType(int code) {
        if (code == 100) {
            return "晴";
        }
        if ((code >= 101 && code <= 213) || (code >= 500 && code <= 901)) {
            return "阴";
        }
        if (code >= 300 && code <= 406) {
            return "雨";
        }
        return "错误";
    }

    /**
     * 匹配掉错误信息
     */
    public static String replaceCity(String city) {
        city = safeText(city).replaceAll("(?:省|市|自治区|特别行政区|地区|盟)", "");
        return city;
    }

    /**
     * 匹配掉无关信息
     */

    public static String replaceInfo(String city) {
        city = safeText(city).replace("API没有", "");
        return city;
    }

    /**
     * Java 中有一个 Closeable 接口,标识了一个可关闭的对象,它只有一个 close 方法.
     */
    public static void closeQuietly(Closeable closeable) {
        if (null != closeable) {
            try {
                closeable.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取顶部status bar 高度
     */
    public static int getStatusBarHeight(Activity mActivity) {
        Resources resources = mActivity.getResources();
        int resourceId = resources.getIdentifier("status_bar_height", "dimen", "android");
        int height = resources.getDimensionPixelSize(resourceId);
        PLog.i("Status height:" + height);
        return height;
    }

    /**
     * 获取底部 navigation bar 高度
     */
    public static int getNavigationBarHeight(Activity mActivity) {
        Resources resources = mActivity.getResources();
        int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
        int height = resources.getDimensionPixelSize(resourceId);
        PLog.i("Navi height:" + height);
        return height;
    }

    /**
     *
     * @param context
     * @param dipValue
     * @return
     */
    public static int dip2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    @SuppressLint("NewApi")
    public static boolean checkDeviceHasNavigationBar(Context activity) {
        //通过判断设备是否有返回键、菜单键(不是虚拟键,是手机屏幕外的按键)来确定是否有navigation bar
        boolean hasMenuKey = ViewConfiguration.get(activity)
            .hasPermanentMenuKey();
        boolean hasBackKey = KeyCharacterMap
            .deviceHasKey(KeyEvent.KEYCODE_BACK);
        return !hasMenuKey && !hasBackKey;
    }

    public static void copyToClipboard(String info, Context context) {
        ClipboardManager manager = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData clipData = ClipData.newPlainText("msg", info);
        manager.setPrimaryClip(clipData);
        ToastUtil.showShort(String.format("[%s] 已经复制到剪切板啦( •̀ .̫ •́ )✧", info));
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

    Copyright (c) 2008-2016, Massachusetts Institute of Technology (MIT)
    All rights reserved.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions are met:

    1. Redistributions of source code must retain the above copyright notice, this
    list of conditions and the following disclaimer.

    2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

    3. Neither the name of the copyright holder nor the names of its contributors
    may be used to endorse or promote products derived from this software without
    specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
    AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
    IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
    DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
    FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
    DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
    SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
    CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
    OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
    OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

-->
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

	<context-param>
		<param-name>webAppRootKey</param-name>
		<param-value>webapp.root.papi</param-value>
	</context-param>

	<context-param>
		<param-name>log4jConfigLocation</param-name>
		<param-value>WEB-INF/log4j.xml</param-value>
	</context-param>

	<listener>
		<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
	</listener>

	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<listener>
		<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
	</listener>

	<servlet>
		<servlet-name>RestServiceV1</servlet-name>
		<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
		<init-param>
			<param-name>config-location</param-name>
			<param-value>classpath:cxf-rest-service.xml</param-value>
		</init-param>
		<init-param>
			<param-name>jaxrs.providers</param-name>
			<param-value>org.apache.cxf.jaxrs.provider.SONProvider</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>RestServiceV1</servlet-name>
		<url-pattern>/v1/*</url-pattern>
	</servlet-mapping>

	<resource-ref>
    	<description>Connection Pool</description>
	    <res-ref-name>jboss/sadisplayDatasource</res-ref-name>
	    <res-type>javax.sql.Datasource</res-type>
	    <res-auth>Container</res-auth>
	</resource-ref>
</web-app>


text:
<?php echo Form::open(array("class"=>"form-horizontal activity col-md-8 col-md-offset-2")); ?>
	<fieldset>

			<?php echo Form::label('Type', 'type', array('class'=>'control-label')); ?>

	         <?php echo Form::select('type', Input::post('type', isset($activity) ? $activity->type : ''), Model_Type::getTypeOptions(),
	                    array('class' => 'type form-control')); ?>

	        <?php echo Form::checkbox('is_wholeday', 1, Input::post('is_wholeday', isset($activity) ? $activity->isWholeday : '')); ?>
			<?php echo Form::label('Whole Day Activity', 'is_wholeday', array('class'=>'control-label')); ?>

			<?php echo Form::label('Date of Activity', 'date', array('class'=>'control-label')); ?>
				<?php //echo Form::input('date', Input::post('date', isset($activity) ? $activity->date : ''), array('class' => 'col-md-4 form-control', 'placeholder'=>'Date', 'type' => 'date')); ?>

		    	<input type="text" class="form-control" name="date" value="<?= Input::post('date', isset($activity) ? $activity->date : ''); ?>"></input>

		<div class="form-group end_date" <?= Input::post('is_wholeday', isset($activity) && $activity->isWholeday) ? 'hidden' : ''; ?>>
			<?php echo Form::label('Activity Until', 'end_date', array('class'=>'control-label')); ?>
				<?php //echo Form::input('date', Input::post('date', isset($activity) ? $activity->date : ''), array('class' => 'col-md-4 form-control', 'placeholder'=>'Date', 'type' => 'date')); ?>

		    	<input type="text" class="form-control" name="end_date" value="<?= Input::post('end_date', isset($activity) ? $activity->end_date : ''); ?>"></input>

	        <?php echo Form::checkbox('is_institutional', 1, Input::post('is_institutional', isset($activity) ? $activity->is_institutional : '')); ?>
			<?php echo Form::label('Is Institutional', 'is_institutional', array('class'=>'control-label')); ?>

			<?php echo Form::label('Subject', 'subject_id', array('class'=>'control-label')); ?>
	        <?php echo Form::select('subject_id', Input::post('subject_id', isset($activity) ? $activity->subject_id : ''), Model_Subject::getSubjectOptions(),
	                    array('class' => 'subject form-control')); ?>

			<?php echo Form::label('Activity', 'activity_content', array('class'=>'control-label')); ?>

				<?php echo Form::textarea('activity_content', Input::post('activity_content', isset($activity) ? $activity->activity_content : ''), array('class' => 'col-md-8 form-control', 'rows' => 8, 'placeholder'=>'Activity content')); ?>

			<?php echo Form::submit('submit', 'Save', array('class' => 'btn btn-primary')); ?>
			<?php echo Html::anchor('site/activities', 'Back', array('class' => 'btn btn-primary')); ?>

	</fieldset>

<?php echo Form::close(); ?>


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Home</title>

April, 2016

Functional Programming

        For my first post I want to start a collection of resources I have come across that
        help to describe and explain functional programming. Last summer I accepted an internship
        position at Mentor Graphics, and my team lead,
        Joe Barnes, suggested a MOOC (Massive Open Online Course) to help prepare me and get my
        feet wet with Scala and the functional programming paradigm in general. He recommended I start
        with Functional Programming
        Principles in Scala, a course instructed by Martin Odersky, designer of the Scala language,
        on Coursera. This course was my first exposure to functional programming in any way.

        In the last nine or so months, I feel like I have been exposed to and experienced "a whole new
        world." I have fallen in love with FP (functional programming). But along the way I've really
        had to learn what exactly is functional programming. Not only for my own understanding,
        but I've had conversations with my classmates, with typically the same experience as
        I had before, and needed to be able to properly explain my new found discovery of
        awesomeness. Discussion also began in the monthly functional meet-up group,
        HuntFunc, on how to have meaningful
        conversations with others new to the functional programming paradigm.

        I will come back to more language specific resources in a moment. Each language has its
        pros and cons, but we need to understand the defining characteristics of this usually
        unfamiliar paradigm before we try to compare the various tools that try to execute it.
        Kris Jenkins wrote two great posts in December on the topic. Part 1:

        What is Functional Programming? and Part 2:

        Which Programming Languages are Functional?. These two are my new favorite posts
        and emphasise how in the FP world complexity and side-effects are evil and the importance
        of avoiding them and striving for more pure functions.

        Programming languages can be typically viewed on a scale of how functional it is. Scala
        is considered a hybrid language, that allows for object-oriented and functional paradigms,
        and is often looked at as a bridge from OO (Java, in particular) to FP. From the Scala world,
        the courses that I mentioned earlier (and a few more) are being transitioned to the new
        ScalaCenter, which will soon offer a Scala
        mini-degree offered on Coursera. On the paradigm scale, Haskell is located closer to the functional
        side. Although I have yet to finish this ebook, Christopher Allen and Julie Moronuki have
        introduced Haskell Programming from First Principles,
        and it is looking very promising so far.

        I think this will be enough of my rambling for my first blog post. I think I may delve further
        into the various programming languages that are closer to the functional programming side of
        the paradigm scale next time and discuss various differences they have, such as static or
        dynamic typing. Thanks for reading!


text:
.. include:: ../global.rst

Audio :modname:`plexapi.audio`
------------------------------
.. automodule:: plexapi.audio
    :members:
    :show-inheritance:


text:
<?php

/**
 * Data object to describe a join between two tables, for example
 * <pre>
 * table_a LEFT JOIN table_b ON table_a.id = table_b.a_id
 * </pre>
 *
 * @author     Francois Zaninotto (Propel)
 * @author     Hans Lellelid <hans@xmpl.org> (Propel)
 * @author     Kaspars Jaudzems <kaspars.jaudzems@inbox.lv> (Propel)
 * @author     Frank Y. Kim <frank.kim@clearink.com> (Torque)
 * @author     John D. McNally <jmcnally@collab.net> (Torque)
 * @author     Brett McLaughlin <bmclaugh@algx.net> (Torque)
 * @author     Eric Dobbs <eric@dobbse.net> (Torque)
 * @author     Henning P. Schmiedehausen <hps@intermeta.de> (Torque)
 * @author     Sam Joseph <sam@neurogrid.com> (Torque)
 * @package    propel.util
 */
class Join
{
  // default comparison type
	const EQUAL = "=";

	// the left parts of the join condition
	protected $left = array();

	// the right parts of the join condition
	protected $right = array();

	// the comparison operators for each pair of columns in the join condition
	protected $operator = array();

	// the type of the join (LEFT JOIN, ...), or null for an implicit join
	protected $joinType = null;

	// the number of conditions in the join
	protected $count = 0;

	/**
	 * Constructor
	 * Use it preferably with no arguments, and then use addCondition() and setJoinType()
	 * Syntax with arguments used mainly for backwards compatibility
	 *
	 * @param string $leftColumn  The left column of the join condition
	 *                            (may contain an alias name)
	 * @param string $rightColumn The right column of the join condition
	 *                            (may contain an alias name)
	 * @param string $joinType    The type of the join. Valid join types are null (implicit join),
	 *                            Criteria::LEFT_JOIN, Criteria::RIGHT_JOIN, and Criteria::INNER_JOIN
	 */
	public function __construct($leftColumn = null, $rightColumn = null, $joinType = null)
	{
		if(!is_null($leftColumn)) {
		  if (!is_array($leftColumn)) {
		    // simple join
		    $this->addCondition($leftColumn, $rightColumn);
		  } else {
		    // join with multiple conditions
		    if (count($leftColumn) != count($rightColumn) ) {
			    throw new PropelException("Unable to create join because the left column count isn't equal to the right column count");
		    }
		    foreach ($leftColumn as $key => $value)
		    {
		      $this->addCondition($value, $rightColumn[$key]);
		    }
		  }
		  $this->setJoinType($joinType);
		}
	}

	/**
	 * Join condition definition
	 *
	 * @param string $left     The left column of the join condition
	 *                         (may contain an alias name)
	 * @param string $right    The right column of the join condition
	 *                         (may contain an alias name)
	 * @param string $joinType The type of the join. Valid join types are null (implicit join),
	 *                         Criteria::LEFT_JOIN, Criteria::RIGHT_JOIN, and Criteria::INNER_JOIN
	 */
	public function addCondition($left, $right, $operator = self::EQUAL)
	{
		$this->left[] = $left;
		$this->right[] = $right;
		$this->operator[] = $operator;
		$this->count++;
	}

	/**
	 * Retrieve the number of conditions in the join
	 *
	 * @return integer The number of conditions in the join
	 */
	public function countConditions()
	{
	  return $this->count;
	}

	/**
	 * Return an array of the join conditions
	 *
	 * @return array An array of arrays representing (left, comparison, right) for each condition
	 */
	public function getConditions()
	{
	  $conditions = array();
	  for ($i=0; $i < $this->count; $i++) {
	    $conditions[] = array(
	      'left'     => $this->getLeftColumn($i),
	      'operator' => $this->getOperator($i),
	      'right'    => $this->getRightColumn($i)
	    );
	  }
	  return $conditions;
	}

  /**
   * @return     the comparison operator for the join condition
   */
  public function getOperator($index = 0)
  {
    return $this->operator[$index];
  }

	public function getOperators()
	{
	  return $this->operator;
	}

	/**
	 * Set the join type
	 *
	 * @param string  $joinType The type of the join. Valid join types are
	 *        null (adding the join condition to the where clause),
	 *        Criteria::LEFT_JOIN(), Criteria::RIGHT_JOIN(), and Criteria::INNER_JOIN()
	 */
	public function setJoinType($joinType = null)
	{
	  $this->joinType = $joinType;
	}

	/**
	 * Get the join type
	 *
	 * @return string The type of the join, i.e. Criteria::LEFT_JOIN(), ...,
	 *         or null for adding the join condition to the where Clause
	 */
	public function getJoinType()
	{
		return $this->joinType;
	}

	/**
	 * @return     the left column of the join condition
	 */
	public function getLeftColumn($index = 0)
	{
		return $this->left[$index];
	}

	/**
	 * @return     all right columns of the join condition
	 */
	public function getLeftColumns()
	{
		return $this->left;
	}

	public function getLeftColumnName($index = 0)
	{
		return substr($this->left[$index], strrpos($this->left[$index], '.') + 1);
	}

	public function getLeftTableName($index = 0)
	{
		return substr($this->left[$index], 0, strrpos($this->left[$index], '.'));
	}

	/**
	 * @return     the right column of the join condition
	 */
	public function getRightColumn($index = 0)
	{
		return $this->right[$index];
	}

	/**
	 * @return     all right columns of the join condition
	 */
	public function getRightColumns()
	{
		return $this->right;
	}

	public function getRightColumnName($index = 0)
	{
		return substr($this->right[$index], strrpos($this->right[$index], '.') + 1);
	}

	public function getRightTableName($index = 0)
	{
		return substr($this->right[$index], 0, strrpos($this->right[$index], '.'));
	}

	/**
	 * returns a String representation of the class,
	 * mainly for debugging purposes
	 *
	 * @return string     A String representation of the class
	 */
	public function toString()
	{
		$result = '';
		if ($this->joinType !== null)
		{
			$result .= $this->joinType . ' : ';
		}
		foreach ($$this->getConditions() as $index => $condition)
		{
		  $result .= implode($condition);
		  if ($index + 1 < $this->count) {
				$result .= ' AND ';
			}
		}
    $result .= '(ignoreCase not considered)';

		return $result;
	}
}


text:
using SFML.Graphics;
using Andromeda.System;

namespace Andromeda.Entities.Components.UI
{
    /// <summary>
    /// Information about a texture
    /// </summary>
    public class UITexture
    {
        Texture texture;

        public Texture Texture
        {
            get => texture;
            set => texture = value;
        }

        public static implicit operator Texture(UITexture textureInfo)
        {
            return textureInfo.Texture;
        }

        public string Id
        {
            get => TextureManager.Instance.FindId(Texture);
            set => texture = TextureManager.Instance.Get(value);
        }

        public UITexture(Texture texture)
        {
            this.texture = texture;
        }

        public UITexture(string textureId)
        {
            texture = TextureManager.Instance.Get(textureId);
        }
    }
}


text:
package com.linecorp.armeria.it.metric;

import static com.linecorp.armeria.common.thrift.ThriftSerializationFormats.BINARY;
import static org.assertj.core.api.Assertions.assertThat;

import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import org.junit.AfterClass;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.DisableOnDebug;
import org.junit.rules.TestRule;
import org.junit.rules.Timeout;

import com.codahale.metrics.Counting;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Sampling;

import com.linecorp.armeria.client.ClientBuilder;
import com.linecorp.armeria.client.ClientFactory;
import com.linecorp.armeria.client.ClientFactoryBuilder;
import com.linecorp.armeria.client.metric.MetricCollectingClient;
import com.linecorp.armeria.common.RpcRequest;
import com.linecorp.armeria.common.RpcResponse;
import com.linecorp.armeria.common.logging.RequestLogAvailability;
import com.linecorp.armeria.common.metric.DropwizardMeterRegistries;
import com.linecorp.armeria.common.metric.MeterIdPrefixFunction;
import com.linecorp.armeria.server.ServerBuilder;
import com.linecorp.armeria.server.metric.MetricCollectingService;
import com.linecorp.armeria.server.thrift.THttpService;
import com.linecorp.armeria.service.test.thrift.main.HelloService.Iface;
import com.linecorp.armeria.testing.server.ServerRule;

import io.micrometer.core.instrument.dropwizard.DropwizardMeterRegistry;

public class DropwizardMetricsIntegrationTest {

    private static final DropwizardMeterRegistry registry = DropwizardMeterRegistries.newRegistry();
    private static final MetricRegistry dropwizardRegistry = registry.getDropwizardRegistry();

    private static CountDownLatch latch;

    @ClassRule
    public static final ServerRule server = new ServerRule() {
        @Override
        protected void configure(ServerBuilder sb) throws Exception {
            sb.meterRegistry(registry);
            sb.service("/helloservice", THttpService.of((Iface) name -> {
                if ("world".equals(name)) {
                    return "success";
                }
                throw new IllegalArgumentException("bad argument");
            }).decorate((delegate, ctx, req) -> {
                ctx.log().addListener(log -> latch.countDown(),
                                      RequestLogAvailability.COMPLETE);
                return delegate.serve(ctx, req);
            }).decorate(MetricCollectingService.newDecorator(
                    MeterIdPrefixFunction.ofDefault("armeria.server.HelloService"))));
        }
    };

    private static final ClientFactory clientFactory =
            new ClientFactoryBuilder().meterRegistry(registry).build();

    @AfterClass
    public static void closeClientFactory() {
        clientFactory.close();
    }

    @Rule
    public final TestRule globalTimeout = new DisableOnDebug(new Timeout(30, TimeUnit.SECONDS));

    @Test
    public void normal() throws Exception {
        latch = new CountDownLatch(14);

        makeRequest("world");
        makeRequest("world");
        makeRequest("space");
        makeRequest("world");
        makeRequest("space");
        makeRequest("space");
        makeRequest("world");

        // Wait until all RequestLogs are collected.
        latch.await();

        dropwizardRegistry.getMeters().keySet().forEach(System.out::println);
        assertThat(dropwizardRegistry.getMeters()
                                     .get(clientMetricNameWithStatusAndResult("requests", 200, "failure"))
                                     .getCount()).isEqualTo(3L);
        assertThat(dropwizardRegistry.getMeters()
                                     .get(serverMetricNameWithStatusAndResult("requests", 200, "failure"))
                                     .getCount()).isEqualTo(3L);
        assertThat(dropwizardRegistry.getMeters()
                                     .get(clientMetricNameWithStatusAndResult("requests", 200, "success"))
                                     .getCount()).isEqualTo(4L);
        assertThat(dropwizardRegistry.getMeters()
                                     .get(serverMetricNameWithStatusAndResult("requests", 200, "success"))
                                     .getCount()).isEqualTo(4L);

        assertTimer("requestDuration", 7);
        assertHistogram("requestLength", 7);
        assertTimer("responseDuration", 7);
        assertHistogram("responseLength", 7);
        assertTimer("totalDuration", 7);
    }

    private static void assertHistogram(String property, int expectedCount) {
        assertSummary(dropwizardRegistry.getHistograms(), property, expectedCount);
    }

    private static void assertTimer(String property, int expectedCount) {
        assertSummary(dropwizardRegistry.getTimers(), property, expectedCount);
    }

    private static void assertSummary(Map<String, ?> map, String property, int expectedCount) {
        assertThat(((Counting) map.get(clientMetricNameWithStatus(property, 200))).getCount())
                .isEqualTo(expectedCount);
        assertThat(((Sampling) map.get(clientMetricNameWithStatus(property, 200))).getSnapshot().getMean())
                .isPositive();
        assertThat(((Counting) map.get(serverMetricNameWithStatus(property, 200))).getCount())
                .isEqualTo(expectedCount);
        assertThat(((Sampling) map.get(serverMetricNameWithStatus(property, 200))).getSnapshot().getMean())
                .isPositive();
    }

    private static String serverMetricName(String property) {
        return MetricRegistry.name("armeria", "server", "HelloService", property,
                                   "hostnamePattern:*", "method:hello", "pathMapping:exact:/helloservice");
    }

    private static String serverMetricNameWithStatus(String property, int status) {
        return serverMetricName(property) + ".status:" + status;
    }

    private static String serverMetricNameWithStatusAndResult(String property, int status, String result) {
        return serverMetricName(property) + ".result:" + result + ".status:" + status;
    }

    private static String clientMetricName(String property) {
        return MetricRegistry.name("armeria", "client", "HelloService", property,
                                   "method:hello");
    }

    private static String clientMetricNameWithStatus(String prop, int status) {
        return clientMetricName(prop) + ".status:" + status;
    }

    private static String clientMetricNameWithStatusAndResult(String prop, int status, String result) {
        return clientMetricName(prop) + ".result:" + result + ".status:" + status;
    }

    private static void makeRequest(String name) {
        Iface client = new ClientBuilder(server.uri(BINARY, "/helloservice"))
                .factory(clientFactory)
                .decorator(RpcRequest.class, RpcResponse.class,
                           (delegate, ctx, req) -> {
                               ctx.log().addListener(unused -> latch.countDown(),
                                                     RequestLogAvailability.COMPLETE);
                               return delegate.execute(ctx, req);
                           })
                .decorator(RpcRequest.class, RpcResponse.class,
                           MetricCollectingClient.newDecorator(
                                   MeterIdPrefixFunction.ofDefault("armeria.client.HelloService")))
                .build(Iface.class);
        try {
            client.hello(name);
        } catch (Throwable t) {
            // Ignore, we will count these up
        }
    }
}


text:
// Type definitions for azure-storage-node v0.10.0
// Project: https://github.com/Azure/azure-storage-node
// Definitions by: Maxime LUCE <https://github.com/SomaticIT/>
// Definitions: https://github.com/typed-contrib/azure-storage-node

/**
* @class
* The Logger class is used to write log information.
*/
declare class Logger {
    /**
   * The log level. Refer to the Logger.LogLevels for available log levels.
   * @name  Logger#level
   * @type  {string}
   * @see Logger.LogLevels
   */
    level: string;

    /**
    * @constructor
    * Creates a new Logger object
    * @param {string} [level]           The log level. Refer to Logger.LogLevels.
    * @param {object} [loggerFunction]  The function to write log information.
    */
    constructor(level?: string, loggerFunction?: (level: string, msg: string) => void);

    log(level: string, msg: string): void;
    emergency(msg: string): void;
    critical(msg: string): void;
    alert(msg: string): void;
    error(msg: string): void;
    warn(msg: string): void;
    notice(msg: string): void;
    info(msg: string): void;
    debug(msg: string): void;

    /**
    * The available log levels.
    *
    * @const
    * @enum {string}
    */
    static LogLevels: {
        /**
        * System is unusable.
        */
        EMERGENCY: 'emergency',

        /**
        * Action must be taken immediately.
        */
        ALERT : 'alert',

        /**
        * Critical condition.
        */
        CRITICAL : 'critical',

        /**
        * Error condition.
        */
        ERROR : 'error',

        /**
        * Warning condition.
        */
        WARNING : 'warning',

        /**
        * Normal but significant condition.
        */
        NOTICE : 'notice',

        /**
        * Purely informational message.
        */
        INFO : 'info',

        /**
        * Application debug messages.
        */
        DEBUG : 'debug'
    };
}

export = Logger;


text:
<!DOCTYPE html>

		<meta charset="utf-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<title>Digitalstrom</title>

Digitalstrom

				<input value="dssadmin" id="login-name">
				<input value="" id="login-password" placeholder="password">
				<button id="login-send">Login</button>

Docs: jSon
			Apps

Lamps


text:
const { autoUpdater } = require('electron-updater')
const events = require('events')
const fetch = require('node-fetch')
const compareVersions = require('compare-versions')
const currentVersion = require('../build-config').version

const networkSpeed = require('./network-speed')
const store = require('../store')
const logger = require('../logger')

// MapeoUpdater emits the 'error' event when there is an internal error with
// updating. We wrap electron-updater to control the API surface.
// Never use electron-updater directly in downstream modules.

const PERSISTED_STORE_KEY = 'updater.channel'
const VALID_CHANNELS = ['beta', 'latest', 'alpha']
const RELEASE_SERVER = 'https://releases.mapeo.app'
// We proxy our auto-updates through Cloudflare, so we treat the release server
// as a generic http server.
const PUBLISH_CONFIG = {
  provider: 'generic',
  url:
    RELEASE_SERVER +
    (process.env.ARCH === 'ia32' ? '/desktop/ia32' : '/desktop'),
  useMultipleRangeRequest: false
}

class MapeoUpdater extends events.EventEmitter {
  constructor () {
    super()
    // Settings
    autoUpdater.setFeedURL(PUBLISH_CONFIG)
    autoUpdater.channel = this.channel
    autoUpdater.autoDownload = false
    autoUpdater.logger = logger
    autoUpdater.autoInstallOnAppQuit = true
    autoUpdater.allowDowngrade = false
    this._onerror = this._onerror.bind(this)

    autoUpdater.on('error', this._onerror)
  }

  get channel () {
    let channel
    try {
      channel = store.get(PERSISTED_STORE_KEY)
    } catch (err) {
      // defaults to 'latest' when unset
      channel = autoUpdater.channel
    }
    if (channel !== autoUpdater.channel) autoUpdater.channel = channel
    return channel
  }

  set channel (value) {
    if (VALID_CHANNELS.indexOf(value) === -1) {
      logger.error('[UPDATER] Invalid channel', value)
      return
    }
    store.set(PERSISTED_STORE_KEY, value)
    autoUpdater.channel = value
    logger.info('[UPDATER] Channel updated to', updater.channel)
  }

  async _getReleaseSummary (version) {
    let releaseSummary
    try {
      const baseUrl = `https://releases.mapeo.app/desktop/${version}/SUMMARY`
      releaseSummary = await fetch(baseUrl)
    } catch (err) {
      logger.error('[UPDATER] Error getting release notes', err)
      releaseSummary = null
    }
    return releaseSummary
  }

  async _getDownloadSpeed () {
    let downloadSpeed
    try {
      downloadSpeed = await networkSpeed.download()
      logger.info('[UPDATER] Got download speed', downloadSpeed)
    } catch (err) {
      logger.error('[UPDATER] Error getting download speed', err)
      downloadSpeed = null
    }
    return downloadSpeed
  }

  updateAvailable (onupdate) {
    autoUpdater.on(
      'update-available',
      async ({ version, files, path, sha512, releaseDate }) => {
        // this is a hack for a bug when you switch between channels,
        // it'll continue to say there is an update available when there is not
        // anymore
        if (compareVersions(version, currentVersion) <= 0) {
          return logger.info(
            'Version',
            version,
            'was less than curent version',
            currentVersion,
            'ignoring update'
          )
        }
        // TODO: Expose this in the UI somehow.
        if (!this.isActive()) {
          this.emit('update-inactive')
          return logger.info(
            '[UPDATER] Must use an AppImage, dmg, or exe for automatic updates.'
          )
        }

        var downloadSpeed = await this._getDownloadSpeed()

        var args = {
          version,
          files,
          path,
          sha512,
          releaseDate,
          downloadSpeed,
          releaseSummary: null // TODO: this._getReleaseSummary(version)
        }

        onupdate(args)
      }
    )
  }

  updateNotAvailable (cb) {
    autoUpdater.on('update-not-available', cb)
  }

  downloadProgress (onprogress) {
    autoUpdater.on('download-progress', progress => {
      logger.info('[UPDATER] Progress', progress)
      onprogress({
        progress: progress
      })
    })
  }

  updateDownloaded (cb) {
    autoUpdater.on('update-downloaded', cb)
  }

  periodicUpdates (interval) {
    const FOUR_HOURS = 1000 * 60 * 60 * 4
    setInterval(async () => {
      this.checkForUpdates()
    }, interval || FOUR_HOURS)
    this.checkForUpdates()
  }

  downloadUpdate () {
    if (!this.isActive()) return this._onerror(new Error('Cannot download.'))
    logger.info('[UPDATER] Download initiated.')
    var promise = autoUpdater.downloadUpdate()

    promise
      .then(() => logger.error('[UPDATER] Download successful.'))
      .catch(this._onerror)
    return promise
  }

  isActive () {
    return autoUpdater.isUpdaterActive()
  }

  checkForUpdates (cb) {
    if (!cb) cb = () => {}
    try {
      var promise = autoUpdater.checkForUpdates()
      promise.then(update => cb(null, update)).catch(this._onerror)
    } catch (err) {
      // TODO: error codes for internationalization.
      var error = new Error('[UPDATER] Could not check for updates.', err)
      this._onerror(error)
    }
  }

  _onerror (err) {
    logger.error('[UPDATER]', err)
    this.emit('error', err)
  }

  quitAndInstall () {
    autoUpdater.quitAndInstall()
  }
}

var updater
if (!updater) updater = new MapeoUpdater()

module.exports = updater


text:
DVBCQFM2 ;;ALB-CIOFO/ECF - FOOT MISCELLANEOUS QUESTIONNAIRE ; 20/JUNE/2011
 ;;2.7;AMIE;**173**;Apr 10, 1995;Build 2
 ;
TXT ;
 ;; Your patient is applying to the U. S. Department of Veterans Affairs (VA) for
 ;; disability benefits.  VA will consider the information you provide on this
 ;; questionnaire as part of their evaluation in processing the Veteran's claim.
 ;;
 ;; 1. Diagnosis
 ;; Does the Veteran now have or has he/she ever had a foot condition (other
 ;; than flatfoot)?
 ;; ___ Yes   ___ No
 ;;
 ;; If yes, indicate diagnosis/es: (check all that apply) and complete
 ;; appropriate section(s).
 ;; Provide only diagnoses that pertain to foot conditions other than flatfoot:
 ;;   ___ Morton's neuroma      ICD code: ______ Date of diagnosis: ___________
 ;;   ___ Metatarsalgia         ICD code: ______ Date of diagnosis: ___________
 ;;   ___ Hammer toes           ICD code: ______ Date of diagnosis: ___________
 ;;   ___ Hallux valgus         ICD code: ______ Date of diagnosis: ___________
 ;;   ___ Hallux rigidus        ICD code: ______ Date of diagnosis: ___________
 ;;   ___ Claw foot (pes cavus) ICD code: ______ Date of diagnosis: ___________
 ;;   ___ Malunion/nonunion of tarsal/metatarsal bones
 ;;                             ICD code: ______ Date of diagnosis: ___________
 ;;   ___ Foot injuries (specify): ____________
 ;;                             ICD code: ______ Date of diagnosis: ___________
 ;;   ___ Other foot conditions (specify): _____
 ;;                             ICD code: ______ Date of diagnosis: ___________
 ;;
 ;; NOTE: If the Veteran has flatfoot, also complete the Flatfoot Questionnaire.
 ;;
 ;; 2. Medical history
 ;; Describe the history (including onset and course) of the Veteran's current
 ;; foot condition (brief summary): ____________________________________________
 ;;
 ;; 3. Morton's neuroma (Morton's disease) and metatarsalgia
 ;; a. Does the Veteran have Morton's neuroma?
 ;; ___ Yes   ___ No
 ;; If yes, indicate side affected:  ___ Right ___ Left ___ Both
 ;;
 ;; b. Does the Veteran have metatarsalgia?
 ;; ___ Yes   ___ No
 ;; If yes, indicate side affected:  ___ Right ___ Left ___ Both
 ;;
 ;; 4. Hammer toe
 ;; Does the Veteran have hammer toes?
 ;; ___ Yes   ___ No
 ;;     If yes, which toes are affected on each side?
 ;;     Right:
 ;;     ___ None        ___ Great toe    ___ Second toe
 ;;     ___ Third toe   ___ Fourth toe   ___ Little toe
 ;;     Left:
 ;;     ___ None        ___ Great toe    ___ Second toe
 ;;     ___ Third toe   ___ Fourth toe   ___ Little toe
 ;;
 ;; 5. Hallux valgus
 ;; Does the Veteran now have or has he/she ever had hallux valgus?
 ;; ___ Yes   ___ No
 ;; If yes, complete the following:
 ;;
 ;; a. Does the Veteran have symptoms due to a hallux valgus condition?
 ;; ___ Yes   ___ No
 ;; If yes, indicate severity (check all that apply):
 ;;    ___ Mild or moderate symptoms
 ;;          Side affected:  ___ Right ___ Left ___ Both
 ;;    ___ Severe symptoms, with function equivalent to amputation of great toe
 ;;          Side affected:  ___ Right ___ Left ___ Both
 ;;
 ;; b. Has the Veteran had surgery for hallux valgus?
 ;; ___ Yes   ___ No
 ;; If yes, indicate type of surgery and side affected:
 ;;    ___ Resection of metatarsal head
 ;;          Date of surgery: ________________
 ;;          Side affected:  ___ Right  ___ Left  ___ Both
 ;;    ___ Metatarsal osteotomy/metatarsal head osteotomy (equivalent to
 ;;        metatarsal head resection)
 ;;          Date of surgery: ________________
 ;;          Side affected:  ___ Right  ___ Left  ___ Both
 ;;    ___ Other surgery for hallux valgus, describe: _________
 ;;          Date of surgery: ________________
 ;;          Side affected:  ___ Right  ___ Left  ___ Both
 ;;
 ;; 6. Hallux rigidus
 ;; Does the Veteran have hallux rigidus?
 ;; ___ Yes   ___ No
 ;; If yes, does the Veteran have symptoms due to hallux rigidus?
 ;; ___ Yes   ___ No
 ;; If yes, indicate severity (check all that apply):
 ;;    ___ Mild or moderate symptoms
 ;;          Side affected:  ___ Right  ___ Left  ___ Both
 ;;    ___ Severe symptoms, with function equivalent to amputation of great toe
 ;;          Side affected:  ___ Right  ___ Left  ___ Both
 ;;
 ;; 7. Pes cavus (claw foot)
 ;; Does the Veteran have acquired claw foot (pes cavus)?
 ;; ___ Yes   ___ No
 ;; If yes, complete the following:
 ;;
 ;; a. Effect on toes due to pes cavus (check all that apply)
 ;;    ___ None                              ___ Right   ___ Left   ___ Both
 ;;    ___ Great toe dorsiflexed             ___ Right   ___ Left   ___ Both
 ;;    ___ All toes tending to dorsiflexion  ___ Right   ___ Left   ___ Both
 ;;    ___ All toes hammer toes              ___ Right   ___ Left   ___ Both
 ;;    ___ Other, describe (if there is an effect on toes due to other etiology
 ;;        than pes cavus, indicate other etiology): ___________________________
 ;;
 ;; b. Pain and tenderness due to pes cavus (check all that apply)
 ;;   ___ None                               ___ Right   ___ Left   ___ Both
 ;;   ___ Definite tenderness under metatarsal heads
 ;;                                          ___ Right   ___ Left   ___ Both
 ;;   ___ Marked tenderness under metatarsal heads
 ;;                                          ___ Right   ___ Left   ___ Both
 ;;   ___ Very painful callosities           ___ Right   ___ Left   ___ Both
 ;;   ___ Other, describe (if the Veteran has pain and tenderness due to other
 ;;       etiology than pes cavus, indicate other etiology): ___________________
 ;;
 ;; c. Effect on plantar fascia due to pes cavus (check all that apply)
 ;;   ___ None                               ___ Right   ___ Left   ___ Both
 ;;   ___ Shortened plantar fascia           ___ Right   ___ Left   ___ Both
 ;;   ___ Marked contraction of plantar fascia with
 ;;       dropped forefoot                   ___ Right   ___ Left   ___ Both
 ;;   ___ Other, describe (if there is an effect on plantar fascia due to other
 ;;       etiology than pes cavus, indicate other etiology): ___________________
 ;;
 ;; d. Dorsiflexion and varus deformity due to pes cavus (check all that apply)
 ;;   ___ None                               ___ Right   ___ Left   ___ Both
 ;;   ___ Some limitation of dorsiflexion at ankle
 ;;                                          ___ Right   ___ Left   ___ Both
 ;;   ___ Limitation of dorsiflexion at ankle to right angle
 ;;                                          ___ Right   ___ Left   ___ Both
 ;;   ___ Marked varus deformity             ___ Right   ___ Left   ___ Both
 ;;   ___ Other, describe (if the Veteran has dorsiflexion and varus deformity
 ;;       due to other etiology than pes cavus, indicate other etiology): ______
 ;;       ______________________________________________________________________
 ;;
 ;; 8. Malunion or nonunion of tarsal or metatarsal bones
 ;; Does the Veteran have malunion or nonunion of tarsal or metatarsal bones?
 ;; ___ Yes   ___ No
 ;;     Indicate severity and side affected:
 ;;     ___ Moderate             ___ Right ___ Left ___ Both
 ;;     ___ Moderately severe    ___ Right ___ Left ___ Both
 ;;     ___ Severe               ___ Right ___ Left ___ Both
 ;;
 ;; 9. Foot injuries
 ;; Does the Veteran have any other foot injuries?
 ;; ___ Yes   ___ No
 ;; If yes, describe: __________________________________________________________
 ;; If yes, indicate severity and side affected:
 ;;     ___ Moderate             ___ Right ___ Left ___ Both
 ;;     ___ Moderately severe    ___ Right ___ Left ___ Both
 ;;     ___ Severe               ___ Right ___ Left ___ Both
 ;;^TOF^
 ;; 10. Bilateral weak foot
 ;; NOTE: For VA purposes, bilateral weak foot is a symptomatic condition
 ;; secondary to many constitutional conditions characterized by atrophy of
 ;; the musculature, disturbed circulation and weakness.
 ;;
 ;; Is there evidence of bilateral weak foot?
 ;; ___ Yes   ___ No
 ;; If yes, describe and report underlying condition: __________________________
 ;;
 ;; 11. Other pertinent physical findings, complications, conditions, signs
 ;; and/or symptoms
 ;; a. Does the Veteran have any scars (surgical or otherwise) related to any
 ;; conditions or to the treatment of any conditions listed in the Diagnosis
 ;; section above?
 ;; ___ Yes   ___ No
 ;; If yes, are any of the scars painful and/or unstable, or is the total area
 ;; of all related scars greater than 39 square cm (6 square inches)?
 ;;    ___ Yes   ___ No
 ;;        If yes, also complete a Scars Questionnaire.
 ;;
 ;; b. Does the Veteran have any other pertinent physical findings,
 ;; complications, conditions, signs and/or symptoms related to any
 ;; conditions listed in the Diagnosis section above?
 ;; ___ Yes   ___ No
 ;; If yes, describe (brief summary): __________________________________________
 ;;
 ;; 12. Assistive devices
 ;; a. Does the Veteran use any assistive devices as a normal mode of
 ;; locomotion, although occasional locomotion by other methods may be possible?
 ;; ___ Yes   ___ No
 ;; If yes, identify assistive devices used (check all that apply and indicate
 ;; frequency):
 ;;   ___ Wheelchair  Frequency of use: __ Occasional   __ Regular   __ Constant
 ;;   ___ Brace(s)    Frequency of use: __ Occasional   __ Regular   __ Constant
 ;;   ___ Crutch(es)  Frequency of use: __ Occasional   __ Regular   __ Constant
 ;;   ___ Cane(s)     Frequency of use: __ Occasional   __ Regular   __ Constant
 ;;   ___ Walker      Frequency of use: __ Occasional   __ Regular   __ Constant
 ;;   ___ Other: _______________________________________________________________
 ;;                   Frequency of use: __ Occasional   __ Regular   __ Constant
 ;;
 ;; b. If the Veteran uses any assistive devices, specify the condition and
 ;; identify the assistive device used for each condition: ______________________
 ;;
 ;; ____________________________________________________________________________
 ;;^TOF^
 ;; 13. Remaining effective function of the extremities
 ;; Due to the Veteran's foot condition, is there functional impairment of an
 ;; extremity such that no effective function remains other than that which would
 ;; be equally well served by an amputation with prosthesis? (Functions of the
 ;; upper extremity include grasping, manipulation, etc., while functions for the
 ;; lower extremity include balance and propulsion, etc.)
 ;; ___ Yes, functioning is so diminished that amputation with prosthesis would
 ;;     equally serve the Veteran.
 ;; ___ No
 ;; If yes, indicate extremities for which this applies:
 ;;     ___ Right lower    ___ Left lower
 ;;
 ;;     For each checked extremity, describe loss of effective function, identify
 ;;     the condition causing loss of function, and provide specific examples
 ;; (brief summary): ___________________________________________________________
 ;;
 ;; 14. Diagnostic Testing
 ;; The diagnosis of degenerative arthritis (osteoarthritis) or traumatic
 ;; arthritis must be confirmed by imaging studies. Once such arthritis has been
 ;; documented, no further imaging studies are required by VA, even if arthritis
 ;; has worsened.
 ;;
 ;; a. Have imaging studies of the foot been performed and are the results
 ;; available?
 ;; ___ Yes   ___ No
 ;; If yes, are there abnormal findings?
 ;; ___ Yes   ___ No
 ;;     If yes, indicate findings:
 ;;        ___ Degenerative or traumatic arthritis
 ;;            Foot: ___ Right   ___ Left   ___ Both
 ;;            Is degenerative or traumatic arthritis documented in multiple
 ;;            joints of the same foot?
 ;;            ___ Yes   ___ No
 ;;            If yes, indicate: ___ Right   ___ Left   ___ Both
 ;;       ___ Other.  Describe: ________________________________________________
 ;;            Foot: ___ Right   ___ Left   ___ Both
 ;;
 ;; b. Are there any other significant diagnostic test findings and/or results?
 ;; ___ Yes   ___ No
 ;;     If yes, provide type of test or procedure, date and results (brief
 ;;     summary):
 ;;     ________________________________________________________________________
 ;;^TOF^
 ;; 15. Functional impact
 ;; Does the Veteran's foot condition impact his or her ability to work?
 ;; ___ Yes   ___ No
 ;; If yes, describe the impact of each of the Veteran's foot conditions
 ;; providing one or more examples: ____________________________________________
 ;;
 ;; 16. Remarks, if any: _______________________________________________________
 ;; ____________________________________________________________________________
 ;;
 ;; Physician signature: _____________________________________ Date: ___________
 ;;
 ;; Physician printed name: ____________________________________________________
 ;;
 ;; Medical license #: _________________________________________________________
 ;;
 ;; Physician address: _________________________________________________________
 ;;
 ;; Phone: _____________________________     FAX: ______________________________
 ;;
 ;; NOTE: VA may request additional medical information, including additional
 ;; examinations if necessary to complete VA's review of the Veteran's application.
 ;;^END^
 Q


text:
<?php

namespace WNC\Bundle\OrganizerBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * Organization
 *
 * @ORM\Table("wnc_organization")
 * @ORM\Entity(repositoryClass="WNC\Bundle\OrganizerBundle\Entity\OrganizerRepository")
 *
 */
class Organization
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

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

    /**
     * @var string
     *
     * @ORM\Column(name="event_location", type="string", length=255)
     */
    private $event_location;

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

    /**
     * @ORM\OneToOne(targetEntity="Application\Sonata\UserBundle\Entity\User", inversedBy="organization")
     * @ORM\JoinColumn(name="contact_id", referencedColumnName="id")
     */
    private $contact;

     /**
     * @Gedmo\Slug(fields={"community"})
     * @ORM\Column(length=64, unique=true)
     */
    private $slug;

    /**
     * @var string
     *
     * @ORM\Column(name="community", type="string", length=255)
     */
    private $community;

    /**
     * @var string
     *
     * @ORM\Column(name="state", type="string", length=255)
     */
    private $state;

    /**
     * @ORM\OneToMany(targetEntity="Participant", mappedBy="organization")
     */
    private $participants;

    public function __construct()
    {
        $this->participants = new ArrayCollection();
    }

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

    /**
     * Set name
     *
     * @param string $name
     * @return Organization
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

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

    /**
     * Set event_location
     *
     * @param string $eventLocation
     * @return Organization
     */
    public function setEventLocation($eventLocation)
    {
        $this->event_location = $eventLocation;

        return $this;
    }

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

    /**
     * Set event_time
     *
     * @param \DateTime $eventTime
     * @return Organization
     */
    public function setEventTime($eventTime)
    {
        $this->event_time = $eventTime;

        return $this;
    }

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

    /**
     * Set contact
     *
     * @param \Application\Sonata\UserBundle\Entity\User $contact
     * @return Organization
     */
    public function setContact(\Application\Sonata\UserBundle\Entity\User $contact = null)
    {
        $this->contact = $contact;

        return $this;
    }

    /**
     * Get contact
     *
     * @return \Application\Sonata\UserBundle\Entity\User
     */
    public function getContact()
    {
        return $this->contact;
    }

    /**
     * Set slug
     *
     * @param string $slug
     * @return Organization
     */
    public function setSlug($slug)
    {
        $this->slug = $slug;

        return $this;
    }

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

    public function __toString() {
      return $this->name;
    }

    /**
     * Set community
     *
     * @param string $community
     * @return Organization
     */
    public function setCommunity($community)
    {
        $this->community = $community;

        return $this;
    }

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

    /**
     * Set state
     *
     * @param string $state
     * @return Organization
     */
    public function setState($state)
    {
        $this->state = $state;

        return $this;
    }

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

    /**
     * Add participants
     *
     * @param \WNC\Bundle\OrganizerBundle\Entity\Participant $participants
     * @return Organization
     */
    public function addParticipant(\WNC\Bundle\OrganizerBundle\Entity\Participant $participants)
    {
        $this->participants[] = $participants;

        return $this;
    }

    /**
     * Remove participants
     *
     * @param \WNC\Bundle\OrganizerBundle\Entity\Participant $participants
     */
    public function removeParticipant(\WNC\Bundle\OrganizerBundle\Entity\Participant $participants)
    {
        $this->participants->removeElement($participants);
    }

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


text:
"""Tests for `tf.data.Dataset.cache()`."""
import functools
import os
from os import path
import shutil
import tempfile

from absl.testing import parameterized
import numpy as np
from tensorflow.python.checkpoint import checkpoint as trackable_utils
from tensorflow.python.checkpoint import checkpoint_management
from tensorflow.python.data.experimental.ops import random_access
from tensorflow.python.data.kernel_tests import checkpoint_test_base
from tensorflow.python.data.kernel_tests import test_base
from tensorflow.python.data.ops import dataset_ops
from tensorflow.python.data.ops import options as options_lib
from tensorflow.python.eager import context
from tensorflow.python.framework import combinations
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import errors
from tensorflow.python.framework import ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import variables
from tensorflow.python.platform import test

class FileCacheTest(test_base.DatasetTestBase, parameterized.TestCase):

  def setUp(self):
    super(FileCacheTest, self).setUp()
    self.tmp_dir = tempfile.mkdtemp()
    self.cache_prefix = path.join(self.tmp_dir, "cache")

  def tearDown(self):
    if self.tmp_dir:
      shutil.rmtree(self.tmp_dir, ignore_errors=True)
    super(FileCacheTest, self).tearDown()

  @combinations.generate(test_base.default_test_combinations())
  def testCacheDatasetPassthrough(self):
    components = (np.array([1, 2, 3, 4]), np.array([5, 6, 7, 8]),
                  np.array([9.0, 10.0, 11.0, 12.0]))

    def dataset_fn(count=5, filename=None):
      repeat_dataset = (
          dataset_ops.Dataset.from_tensor_slices(components).repeat(count))
      if filename:
        return repeat_dataset.cache(filename)
      else:
        return repeat_dataset

    self.assertEqual(
        tuple([c.shape[1:] for c in components]),
        dataset_ops.get_legacy_output_shapes(dataset_fn()))

    get_next = self.getNext(dataset_fn())

    # First run without caching to collect the "ground truth".
    elements = []
    for _ in range(20):
      elements.append(self.evaluate(get_next()))
    with self.assertRaises(errors.OutOfRangeError):
      self.evaluate(get_next())

    # Assert that the cached dataset has the same elements as the
    # "ground truth".
    get_next = self.getNext(dataset_fn(filename=self.cache_prefix))
    cached_elements = []
    for _ in range(20):
      cached_elements.append(self.evaluate(get_next()))
    with self.assertRaises(errors.OutOfRangeError):
      self.evaluate(get_next())
    self.assertAllEqual(elements, cached_elements)

    # Re-initialize with an empty upstream (to throw errors.OutOfRangeError
    # if we didn't use the cache).
    get_next = self.getNext(dataset_fn(count=0, filename=self.cache_prefix))
    replayed_elements = []
    for _ in range(20):
      replayed_elements.append(self.evaluate(get_next()))
    with self.assertRaises(errors.OutOfRangeError):
      self.evaluate(get_next())
    self.assertEqual(cached_elements, replayed_elements)

    # Re-initialize with an empty upstream and a missing cache file (should
    # throw errors.OutOfRangeError immediately).
    get_next = self.getNext(
        dataset_fn(count=0, filename=self.cache_prefix + "nonsense"))
    with self.assertRaises(errors.OutOfRangeError):
      self.evaluate(get_next())

  @combinations.generate(test_base.default_test_combinations())
  def testConcurrentWriters(self):
    components = (np.array([1, 2, 3, 4]), np.array([5, 6, 7, 8]),
                  np.array([9.0, 10.0, 11.0, 12.0]))

    cache_dataset1 = (
        dataset_ops.Dataset.from_tensor_slices(components).cache(
            self.cache_prefix))
    cache_dataset2 = (
        dataset_ops.Dataset.from_tensor_slices(components).cache(
            self.cache_prefix))

    get_next1 = self.getNext(cache_dataset1)
    get_next2 = self.getNext(cache_dataset2)

    self.evaluate(get_next1())  # this should succeed

    with self.assertRaises(errors.AlreadyExistsError):
      self.evaluate(get_next2())

    self.evaluate(get_next1())  # this should continue to succeed

  @combinations.generate(test_base.default_test_combinations())
  def testConcurrentReaders(self):
    components = (np.array([1, 2, 3, 4]), np.array([5, 6, 7, 8]),
                  np.array([9.0, 10.0, 11.0, 12.0]))

    cache_dataset1 = (
        dataset_ops.Dataset.from_tensor_slices(components).cache(
            self.cache_prefix))
    cache_dataset2 = (
        dataset_ops.Dataset.from_tensor_slices(components).cache(
            self.cache_prefix))

    get_next1 = self.getNext(cache_dataset1)
    get_next2 = self.getNext(cache_dataset2)

    elements = []
    for _ in range(4):
      elements.append(self.evaluate(get_next1()))
    with self.assertRaises(errors.OutOfRangeError):
      self.evaluate(get_next1())

    # Re-initialize
    get_next1 = self.getNext(cache_dataset1, requires_initialization=True)
    get_next2 = self.getNext(cache_dataset2, requires_initialization=True)

    # Reading concurrently should succeed.
    elements_itr1 = []
    elements_itr2 = []
    elements_itr2.append(self.evaluate(get_next2()))
    elements_itr1.append(self.evaluate(get_next1()))
    elements_itr2.append(self.evaluate(get_next2()))
    elements_itr1.append(self.evaluate(get_next1()))
    # Intentionally reversing the order
    elements_itr1.append(self.evaluate(get_next1()))
    elements_itr2.append(self.evaluate(get_next2()))
    elements_itr1.append(self.evaluate(get_next1()))
    elements_itr2.append(self.evaluate(get_next2()))

    with self.assertRaises(errors.OutOfRangeError):
      self.evaluate(get_next2())

    with self.assertRaises(errors.OutOfRangeError):
      self.evaluate(get_next1())

    self.assertAllEqual(elements, elements_itr1)
    self.assertAllEqual(elements, elements_itr2)

  @combinations.generate(test_base.default_test_combinations())
  def testReadingPastEndOfSequence(self):
    dataset = dataset_ops.Dataset.range(10).cache(self.cache_prefix)
    dataset = dataset.map(lambda a: a).batch(4).repeat(2)
    expected_output = [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9]] * 2
    self.assertDatasetProduces(dataset, expected_output)

  @combinations.generate(test_base.default_test_combinations())
  def testCacheZipped(self):
    def make_dataset(i):
      cache_path = self.cache_prefix + "_" + str(i)
      return dataset_ops.Dataset.range(100).shuffle(100).cache(cache_path)

    datasets = [make_dataset(i) for i in range(3)]
    dataset = dataset_ops.Dataset.zip(tuple(datasets))
    first_order = self.getDatasetOutput(dataset)
    second_order = self.getDatasetOutput(dataset)
    self.assertEqual(first_order, second_order)

  @combinations.generate(test_base.default_test_combinations())
  def testCleaningUpCacheFiles(self):

    def do_test(i):
      dataset = dataset_ops.Dataset.range(10).cache(self.cache_prefix)
      get_next = self.getNext(dataset)
      for _ in range(i):
        try:
          self.evaluate(get_next())
        except errors.OutOfRangeError:
          break

    if not context.executing_eagerly():
      self.skipTest(
          "Test requires eager mode for iterators to be deconstructed")

    for i in [0, 3, 10, 12, 15]:
      do_test(i)

class MemoryCacheTest(test_base.DatasetTestBase, parameterized.TestCase):

  @combinations.generate(test_base.default_test_combinations())
  def testCacheDatasetPassthrough(self):
    with ops.device("cpu:0"):
      repeat_count = variables.Variable(constant_op.constant(10, dtypes.int64))
      dataset = dataset_ops.Dataset.range(3).flat_map(
          lambda x: dataset_ops.Dataset.from_tensors(x).repeat(repeat_count))

      options = options_lib.Options()
      options.experimental_optimization.inject_prefetch = False
      dataset = dataset.with_options(options)

      cached_dataset = dataset.cache().repeat(2)
      uncached_dataset = dataset.repeat(2)

      self.evaluate(repeat_count.initializer)
      # Needs to be initializable to capture the variable.
      cached_next = self.getNext(cached_dataset, requires_initialization=True)
      uncached_next = self.getNext(
          uncached_dataset, requires_initialization=True)
      for i in range(3):
        for _ in range(10):
          self.assertEqual(self.evaluate(cached_next()), i)
          self.assertEqual(self.evaluate(uncached_next()), i)

      self.evaluate(repeat_count.assign(0))

      # The uncached iterator should now be empty.
      with self.assertRaises(errors.OutOfRangeError):
        self.evaluate(uncached_next())

      # The cached iterator replays from cache.
      for i in range(3):
        for _ in range(10):
          self.assertEqual(self.evaluate(cached_next()), i)

      # The cached iterator should now be empty.
      with self.assertRaises(errors.OutOfRangeError):
        self.evaluate(cached_next())

  @combinations.generate(test_base.default_test_combinations())
  def testEmptyCacheReading(self):
    components = (np.array([1, 2, 3, 4]), np.array([5, 6, 7, 8]),
                  np.array([9.0, 10.0, 11.0, 12.0]))

    repeat_dataset = (
        dataset_ops.Dataset.from_tensor_slices(components).repeat(0))
    cache_dataset = repeat_dataset.cache()

    self.assertDatasetProduces(cache_dataset, expected_output=[])

  @combinations.generate(test_base.default_test_combinations())
  def testConcurrentReaders(self):

    dataset_fn = lambda: dataset_ops.Dataset.range(5).cache()
    d1 = dataset_fn().map(lambda x: x + 1)
    d2 = dataset_fn().map(lambda x: x + 6)

    get_next1 = self.getNext(d1)

    self.assertEqual(1, self.evaluate(get_next1()))
    self.assertEqual(2, self.evaluate(get_next1()))
    self.assertEqual(3, self.evaluate(get_next1()))

    get_next2 = self.getNext(d2)

    self.assertEqual(6, self.evaluate(get_next2()))
    self.assertEqual(7, self.evaluate(get_next2()))
    self.assertEqual(4, self.evaluate(get_next1()))  # interleave execution
    self.assertEqual([8, 5],
                     [self.evaluate(get_next2()),
                      self.evaluate(get_next1())])
    self.assertEqual(9, self.evaluate(get_next2()))
    self.assertEqual(10, self.evaluate(get_next2()))

    with self.assertRaises(errors.OutOfRangeError):
      self.evaluate(get_next2())
    with self.assertRaises(errors.OutOfRangeError):
      self.evaluate(get_next1())

  @combinations.generate(test_base.default_test_combinations())
  def testCacheTakeRepeat(self):
    dataset = dataset_ops.Dataset.range(10).cache().take(5).repeat(2)

    expected_output = [0, 1, 2, 3, 4, 0, 1, 2, 3, 4]
    self.assertDatasetProduces(dataset, expected_output=expected_output)

  @combinations.generate(test_base.default_test_combinations())
  def testCacheRepeatEpochs(self):
    counter = variables.Variable(0)
    self.evaluate(counter.initializer)

    def increment_fn(x):
      counter.assign_add(1)
      return x

    dataset = dataset_ops.Dataset.range(10).map(increment_fn).cache().repeat(2)
    options = options_lib.Options()
    options.experimental_optimization.inject_prefetch = False
    dataset = dataset.with_options(options)
    get_next = self.getNext(dataset, requires_initialization=True)

    # first epoch
    for i in range(10):
      self.assertEqual(i, self.evaluate(counter))
      self.assertEqual(i, self.evaluate(get_next()))
    # second epoch
    for i in range(10):
      self.assertEqual(10, self.evaluate(counter))
      self.assertEqual(i, self.evaluate(get_next()))
    with self.assertRaises(errors.OutOfRangeError):
      self.evaluate(get_next())

  @combinations.generate(combinations.combine(tf_api_version=2, mode="eager"))
  def testCacheIterationEpochs(self):
    counter = variables.Variable(0)
    self.evaluate(counter.initializer)

    def increment_fn(x):
      counter.assign_add(1)
      return x

    dataset = dataset_ops.Dataset.range(10).map(increment_fn).cache()
    options = options_lib.Options()
    options.experimental_optimization.inject_prefetch = False
    dataset = dataset.with_options(options)

    # first epoch
    i = 0
    for elem in dataset:
      self.assertEqual(i, self.evaluate(elem))
      i += 1
      self.assertEqual(i, self.evaluate(counter))

    # second epoch
    i = 0
    for elem in dataset:
      self.assertEqual(10, self.evaluate(counter))
      self.assertEqual(i, self.evaluate(elem))
      i += 1

  @combinations.generate(combinations.combine(tf_api_version=2, mode="eager"))
  def testCacheV2ResourceCapture(self):

    def make_dataset():
      ids = dataset_ops.Dataset.range(10)
      ids = ids.cache()

      def interleave_fn(dataset, _):
        return dataset

      dataset = dataset_ops.Dataset.range(1)
      dataset = dataset.interleave(functools.partial(interleave_fn, ids))
      return dataset

    results = []
    for elem in make_dataset():
      results.append(elem.numpy())

    self.assertAllEqual(results, range(10))

  @combinations.generate(combinations.combine(tf_api_version=2, mode="eager"))
  def testCacheV2ConcurrentIterators(self):

    dataset = dataset_ops.Dataset.range(10).cache()

    it1 = iter(dataset)
    it2 = iter(dataset)

    for i in range(10):
      self.assertEqual(next(it1), i)
      self.assertEqual(next(it2), i)

  @combinations.generate(combinations.combine(tf_api_version=2, mode="eager"))
  def testCacheKnownCardinality(self):

    # Check that a dataset which produces random permutation of range(10) ends
    # up being cached when we read all of its element but do not reach EOF.
    dataset = dataset_ops.Dataset.range(10)
    dataset = dataset.shuffle(10, reshuffle_each_iteration=True).cache()

    it = iter(dataset)

    results = []
    for _ in range(10):
      results.append(next(it))

    it = iter(dataset)
    for i in range(10):
      self.assertEqual(next(it), results[i])

  @combinations.generate(test_base.eager_only_combinations())
  def testCheckpointFinishedCache(self):
    num_elements = 10
    ds = dataset_ops.Dataset.range(num_elements)
    ds = ds.cache()

    iterator = iter(ds)
    for i in range(num_elements):
      self.assertEqual(next(iterator).numpy(), i)
    ckpt = trackable_utils.Checkpoint(iterator=iterator)
    manager = checkpoint_management.CheckpointManager(
        ckpt, self.get_temp_dir(), max_to_keep=1)
    manager.save()
    manager.restore_or_initialize()
    with self.assertRaises(StopIteration):
      next(iterator)

  @combinations.generate(test_base.default_test_combinations())
  def testName(self):
    dataset = dataset_ops.Dataset.from_tensors(42).cache(name="cache")
    self.assertDatasetProduces(dataset, [42])

class CacheCheckpointTest(checkpoint_test_base.CheckpointTestBase,
                          parameterized.TestCase):

  def setUp(self):
    super(CacheCheckpointTest, self).setUp()
    self.range_size = 10
    self.num_repeats = 3
    self.num_outputs = self.range_size * self.num_repeats
    self.cache_file_prefix = "test"

  def make_dataset_fn(self, is_memory):
    if is_memory:
      filename = ""
    else:
      filename = os.path.join(self.get_temp_dir(), self.cache_file_prefix)

    def ds_fn():
      return dataset_ops.Dataset.range(self.range_size).cache(filename).repeat(
          self.num_repeats)

    return ds_fn

  def expected_outputs(self):
    return list(range(self.range_size)) * self.num_repeats

  @combinations.generate(
      combinations.times(test_base.default_test_combinations(),
                         combinations.combine(is_memory=[True, False])))
  def testCheckpointBeforeOneEpoch(self, is_memory):
    ds_fn = self.make_dataset_fn(is_memory)

    # Generate 5 entries from iterator and save checkpoint.
    outputs = self.gen_outputs(ds_fn, [], 5, verify_exhausted=False)
    self.assertSequenceEqual(outputs, range(5))

    # Restore from checkpoint and produce the rest of the elements from the
    # iterator.
    outputs.extend(
        self.gen_outputs(
            ds_fn, [],
            self.num_outputs - 5,
            ckpt_saved=True,
            verify_exhausted=False))
    self.assertSequenceEqual(outputs, self.expected_outputs())

  @combinations.generate(
      combinations.times(test_base.default_test_combinations(),
                         combinations.combine(is_memory=[True, False])))
  def testCheckpointBeforeOneEpochThenRunFewSteps(self, is_memory):
    ds_fn = self.make_dataset_fn(is_memory)

    # Generate 8 entries from iterator but save checkpoint after producing 5.
    outputs = self.gen_outputs(
        ds_fn, [5], 8, verify_exhausted=False, save_checkpoint_at_end=False)
    self.assertSequenceEqual(outputs, range(8))

    outputs = outputs[:5]
    outputs.extend(
        self.gen_outputs(
            ds_fn, [],
            self.num_outputs - 5,
            ckpt_saved=True,
            verify_exhausted=False))
    self.assertSequenceEqual(outputs, self.expected_outputs())

  @combinations.generate(
      combinations.times(test_base.default_test_combinations(),
                         combinations.combine(is_memory=[True, False])))
  def testCheckpointAfterOneEpoch(self, is_memory):
    ds_fn = self.make_dataset_fn(is_memory)

    # Generate 15 entries from iterator and save checkpoint.
    outputs = self.gen_outputs(ds_fn, [], 15, verify_exhausted=False)
    self.assertSequenceEqual(outputs, list(range(10)) + list(range(5)))

    # Restore from checkpoint and produce the rest of the elements from the
    # iterator.
    outputs.extend(
        self.gen_outputs(
            ds_fn, [],
            self.num_outputs - 15,
            ckpt_saved=True,
            verify_exhausted=False))
    self.assertSequenceEqual(outputs, self.expected_outputs())

  @combinations.generate(
      combinations.times(test_base.default_test_combinations(),
                         combinations.combine(is_memory=[True, False])))
  def testCheckpointAfterOneEpochThenRunFewSteps(self, is_memory):
    ds_fn = self.make_dataset_fn(is_memory)

    # Generate 18 entries from iterator but save checkpoint after producing 15.
    outputs = self.gen_outputs(
        ds_fn, [15], 18, verify_exhausted=False, save_checkpoint_at_end=False)
    self.assertSequenceEqual(outputs, list(range(10)) + list(range(8)))

    outputs = list(range(10)) + list(range(5)) + self.gen_outputs(
        ds_fn, [],
        self.num_outputs - 15,
        ckpt_saved=True,
        verify_exhausted=False)
    self.assertSequenceEqual(outputs, list(range(10)) * 3)

  @combinations.generate(
      combinations.times(test_base.default_test_combinations(),
                         combinations.combine(is_memory=[True, False])))
  def testCheckpointBeforeOneEpochButRunCompleteEpoch(self, is_memory):
    ds_fn = self.make_dataset_fn(is_memory)

    # Generate 13 entries from iterator but save checkpoint after producing 5.
    outputs = self.gen_outputs(
        ds_fn, [5], 13, verify_exhausted=False, save_checkpoint_at_end=False)
    self.assertSequenceEqual(outputs, list(range(10)) + list(range(3)))

    # Since we ran for more than one epoch, the cache was completely written.
    # The ckpt was saved when the iterator was in cache-write mode. Test that
    # the iterator falls back to read mode after restoring if the cache has
    # been completely written.

    outputs = list(range(5)) + self.gen_outputs(
        ds_fn, [],
        self.num_outputs - 5,
        ckpt_saved=True,
        verify_exhausted=False)
    self.assertSequenceEqual(outputs, list(range(10)) * 3)

  @combinations.generate(
      combinations.times(test_base.default_test_combinations(),
                         combinations.combine(is_memory=[True, False])))
  def testCheckpointUnusedWriterIterator(self, is_memory):
    ds_fn = self.make_dataset_fn(is_memory)

    # Checkpoint before get_next is called even once.
    outputs = self.gen_outputs(ds_fn, [], 0, verify_exhausted=False)
    self.assertSequenceEqual(outputs, [])

    outputs = self.gen_outputs(
        ds_fn, [], self.num_outputs, ckpt_saved=True, verify_exhausted=False)
    self.assertSequenceEqual(outputs, list(range(10)) * 3)

  @combinations.generate(
      combinations.times(test_base.default_test_combinations(),
                         combinations.combine(is_memory=[True, False])))
  def testCheckpointUnusedMidwayWriterIterator(self, is_memory):
    ds_fn = self.make_dataset_fn(is_memory)

    # Produce 5 elements and checkpoint.
    outputs = self.gen_outputs(ds_fn, [], 5, verify_exhausted=False)
    self.assertSequenceEqual(outputs, range(5))

    # Restore from checkpoint, then produce no elements and checkpoint.
    outputs.extend(
        self.gen_outputs(ds_fn, [], 0, ckpt_saved=True, verify_exhausted=False))
    self.assertSequenceEqual(outputs, range(5))

    # Restore from checkpoint and produce rest of the elements.
    outputs.extend(
        self.gen_outputs(
            ds_fn, [],
            self.num_outputs - 5,
            ckpt_saved=True,
            verify_exhausted=False))
    self.assertSequenceEqual(outputs, list(range(10)) * 3)

  @combinations.generate(
      combinations.times(test_base.default_test_combinations(),
                         combinations.combine(is_memory=[True, False])))
  def testUnusedCheckpointError(self, is_memory):
    ds_fn = self.make_dataset_fn(is_memory)

    # Produce 5 elements and save ckpt.
    outputs = self.gen_outputs(ds_fn, [], 5, verify_exhausted=False)
    self.assertSequenceEqual(outputs, range(5))

    if is_memory:
      outputs = self.gen_outputs(
          ds_fn, [], self.num_outputs, verify_exhausted=False)
      self.assertSequenceEqual(outputs, self.expected_outputs())
    else:
      # Since the complete cache has not been written, a new iterator which does
      # not restore the checkpoint will throw an error since there is a partial
      # cache shard.
      with self.assertRaises(errors.AlreadyExistsError):
        outputs = self.gen_outputs(
            ds_fn, [], self.num_outputs, verify_exhausted=False)

  @combinations.generate(
      combinations.times(test_base.default_test_combinations(),
                         combinations.combine(is_memory=[True, False])))
  def testIgnoreCheckpointIfCacheWritten(self, is_memory):
    ds_fn = self.make_dataset_fn(is_memory)

    # Produce 15 elements and save ckpt. This will write the complete cache.
    outputs = self.gen_outputs(ds_fn, [], 15, verify_exhausted=False)
    self.assertSequenceEqual(outputs, list(range(10)) + list(range(5)))

    # Build the iterator again but do not restore from ckpt. Since the cache
    # has already been written we should be able to use it.
    outputs = self.gen_outputs(
        ds_fn, [], self.num_outputs, verify_exhausted=False)
    self.assertSequenceEqual(outputs, list(range(10)) * 3)

class CacheRandomAccessTest(test_base.DatasetTestBase, parameterized.TestCase):

  @combinations.generate(
      combinations.times(test_base.default_test_combinations(),
                         combinations.combine(index=[-1, 3, 4])))
  def testInvalidIndex(self, index):
    dataset = dataset_ops.Dataset.from_tensor_slices([1, 2, 3]).cache()
    with self.assertRaises(errors.OutOfRangeError):
      self.evaluate(random_access.at(dataset, index))

  @combinations.generate(test_base.default_test_combinations())
  def testCacheRangeDataset(self):
    dataset = dataset_ops.Dataset.range(10).cache()
    expected_elements = list(range(10))
    self.verifyRandomAccess(dataset, expected_elements)

  @combinations.generate(test_base.default_test_combinations())
  def testCacheOneDimensionalElements(self):
    tensor = [1, 2, 3]
    dataset = dataset_ops.Dataset.from_tensor_slices(tensor).cache()
    self.verifyRandomAccess(dataset, tensor)

  @combinations.generate(test_base.default_test_combinations())
  def testCacheTwoDimensionalElements(self):
    tensor = [[1, 2], [3, 4]]
    dataset = dataset_ops.Dataset.from_tensor_slices(tensor).cache()
    self.verifyRandomAccess(dataset, tensor)

  @combinations.generate(test_base.default_test_combinations())
  def testCacheThreeComponents(self):
    dataset = dataset_ops.Dataset.from_tensor_slices(
        ([1, 2], [3, 4], [5, 6])).cache()
    expected = [(1, 3, 5), (2, 4, 6)]
    self.verifyRandomAccess(dataset, expected)

  @combinations.generate(test_base.default_test_combinations())
  def testCacheInputDatasetNotRandomlyAccessible(self):
    dataset = dataset_ops.Dataset.range(10)
    initial_state = constant_op.constant(0, dtypes.int64)
    scan_func = lambda state, i: (state + i, state + i)
    dataset = dataset.scan(
        initial_state=initial_state, scan_func=scan_func).cache()
    expected = [0, 1, 3, 6, 10, 15, 21, 28, 36, 45]
    self.verifyRandomAccess(dataset, expected)

  @combinations.generate(test_base.default_test_combinations())
  def testCacheInputDatasetUnknownCardinality(self):
    dataset = dataset_ops.Dataset.range(20).filter(
        lambda x: math_ops.equal(x % 2, 0)).cache()
    expected = [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
    self.verifyRandomAccess(dataset, expected)

  @combinations.generate(test_base.default_test_combinations())
  def testCacheInputDatasetInfiniteCardinality(self):
    dataset = dataset_ops.Dataset.range(20).filter(
        lambda x: math_ops.equal(x % 2, 0)).repeat(-1).cache()
    expected = [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 0, 2]
    # Since the dataset has infinite cardinality, random access with caching
    # will cache through the requested index. In this case, random access
    # with caching will cache through index 11.
    self.verifyRandomAccessInfiniteCardinality(dataset, expected)

if __name__ == "__main__":
  test.main()


text:
require 'spec_helper'

RSpec.describe BlogPostHelper, :type => :helper do
  describe "blog_post_tags" do
    let(:blog_post) { build(:blog_post, :tag_list => ["some-tag"]) }

    it "returns a link to the blog post tag page" do
      expected_link = 'Some Tag'
      expect(helper.blog_post_tags(blog_post)).to eq(expected_link)
    end
  end

  describe "blog_post_url_with_analytics" do
    let(:date) { Time.local(2015, 02, 05, 12, 0, 0) }
    let(:blog_post) { build(:blog_post, :title => "Blog Post Title", :published_at => date) }

    it "returns an empty string if blog post is unpublished" do
      allow(blog_post).to receive(:published?).and_return(false)
      expect(helper.blog_post_url_with_analytics(blog_post, "", "")).to eq("")
    end

    it "returns a link with the ga params if blog post is published" do
      allow(blog_post).to receive(:published?).and_return(true)
      expect(helper.blog_post_url_with_analytics(blog_post, "facebook", "direct_facebook")).
        to eq("http://test.host/blog/blog-post-title?utm_campaign=blog_post_05_02_2015&utm_medium=direct_facebook&utm_source=facebook")
    end
  end
end


text:
'use strict';

describe('Controller: HealthTrackerCtrl', function () {

  // load the controller's module
  beforeEach(module('quickInitApp'));

  var HealthTrackerCtrl,
    scope;

  // Initialize the controller and a mock scope
  beforeEach(inject(function ($controller, $rootScope) {
    scope = $rootScope.$new();
    HealthTrackerCtrl = $controller('HealthTrackerCtrl', {
      $scope: scope
    });
  }));
});


text:
var Token = require('../../tokenizer/token');

var serializeAll = require('../../writer/one-time').all;

var FONT_FACE_SCOPE = '@font-face';

function removeDuplicateFontAtRules(tokens) {
  var fontAtRules = [];
  var token;
  var key;
  var i, l;

  for (i = 0, l = tokens.length; i < l; i++) {
    token = tokens[i];

    if (token[0] != Token.AT_RULE_BLOCK && token[1][0][1] != FONT_FACE_SCOPE) {
      continue;
    }

    key = serializeAll([token]);

    if (fontAtRules.indexOf(key) > -1) {
      token[2] = [];
    } else {
      fontAtRules.push(key);
    }
  }
}

module.exports = removeDuplicateFontAtRules;