text:
using System;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Web;

namespace GCrawler
{
    internal static class ContentManager
    {
        private static readonly string ContentDirectory = AppDomain.CurrentDomain.BaseDirectory + "\\Content";
        private static readonly SHA1 _shaCalculator = SHA1.Create();

        static ContentManager()
        {
            if (!Directory.Exists(ContentDirectory))
            {
                Directory.CreateDirectory(ContentDirectory);
                Tracer.WriteInformation("Content directory created.");
            }
        }

        public static void SaveContent(Item item, Uri source)
        {
            // Check whether the content already exists with a different filename.
            string base64Hash;
            using (FileStream fileStream = File.OpenRead(item.TempFilename))
            {
                byte[] hash = _shaCalculator.ComputeHash(fileStream);
                base64Hash = Convert.ToBase64String(hash);
                if (CheckHashIsInUse(base64Hash))
                {
                    return;
                }
            }

            // Generate a valid filename.
            string filename = "[" + base64Hash + "]_" + source.Segments.Last();
            filename = HttpUtility.UrlDecode(filename);
            foreach (char invalidChar in Path.GetInvalidFileNameChars())
            {
                filename = filename.Replace(invalidChar, '_');
            }

            filename = Path.Combine(ContentDirectory, filename);

            try
            {
                Tracer.WriteVerbose("Saving content from '{0}' as '{1}'.", source, filename);
                File.Copy(item.TempFilename, filename);
                Tracer.WriteInformation("Content from '{0}' saved as '{1}'.", source, filename);
            }
            catch (Exception exception)
            {
                Tracer.WriteWarning("Could not save content from '{0}' as {1}'. {2}", source, filename, exception.Message);
            }
        }

        private static bool CheckHashIsInUse(string base64Hash)
        {
            string pattern = string.Format("[{0}]*", base64Hash);
            return Directory.GetFiles(ContentDirectory, pattern, SearchOption.TopDirectoryOnly).Any();
        }
    }
}


text:
Informações a respeito do nível do Rio dos Sinos.

Mais informações posteriormente.

redpajama_set_name: RedPajamaGithub


text:
layout: post
title: "php设计模式-模版方法模式"
subtitle: ""
author: "RryLee"
date:   2015-11-12
tags:
    - php
    - 设计模式
---

* content
{:toc}

# 概述

对于模版方法模式[后面统称 [Template method](https://en.wikipedia.org/wiki/Template_method_pattern)],维基是这样描述的:

> In software engineering, the template method pattern is a behavioral design pattern that defines the program skeleton of an algorithm in a method, called template method, which defers some steps to subclasses.[1] It lets one redefine certain steps of an algorithm without changing the algorithm's structure.[2] This use of "template" is unrelated to C++ templates.

一句话来讲,就是定义一个算法骨架,子类使用该模版不需要重新定义算法步骤。

Template method 在生活中也可以归纳出来很多,比如踢一场足球和打一场篮球都需要换衣服,组队,运动等一系列的步骤,工人,农民也都需要上班收工。

---

# 场景

当有两个或者多个不同的组件却有相同的解决方法的时候,这个时候可以选择 Template method,比如 laravel 中的第三方授权组件,就是采用的这种设计思想。

---

# Demo

<img class="shadow" src="http://ww3.sinaimg.cn/mw690/baa3278fgw1ey0cpxxzkgj20h10bxdgc.jpg" />

从上图可以看到农民工作和工人工作都遵循的同一个工作流程,接下来一步步写写看:

    class WorkerWork
    {
        public function work()
        {
            $this->eatBreakfast()
                ->changeClothes()
                ->gotoBuilding()
                ->goHome();
        }

        protected function eatBreakfast()
        {
            var_dump('eat breakfast');

            return $this;
        }

        protected function changeClothes()
        {
            var_dump('change the work clothes');

            return $this;
        }

        protected function gotoBuilding()
        {
            var_dump('go to building');

            return $this;
        }

        protected function goHome()
        {
            var_dump('go home');

            return $this;
        }
    }

好了,现在又出现了农民工作

    abstract class FarmerWork
    {
        public function work()
        {
            $this->eatBreakfast()
                ->changeClothes()
                ->gotoFarm()
                ->goHome();
        }

        protected function eatBreakfast()
        {
            var_dump('eat breakfast');

            return $this;
        }

        protected function changeClothes()
        {
            var_dump('change the work clothes');

            return $this;
        }

        protected function gotoFarm()
        {
            var_dump('go to farm');

            return $this;
        }

        protected function goHome()
        {
            var_dump('go home');

            return $this;
        }
    }

这个时候代码以及有一点冗余了,根据上图,很容易的想到解决方案,**使用一个抽象的工作类来定义公共的方法并且约束子类去实现特有的方法**

    abstract class GoWork
    {
        public function work()
        {
            $this->eatBreakfast()
                ->changeClothes()
                ->doOwnPrimaryTask()
                ->goHome();
        }

        protected function eatBreakfast()
        {
            var_dump('eat breakfast');

            return $this;
        }

        protected function changeClothes()
        {
            var_dump('change the work clothes');

            return $this;
        }

        protected function goHome()
        {
            var_dump('go home');

            return $this;
        }

        abstract protected function doOwnPrimaryTask();
    }

    class WorkerWork extends GoWork
    {
        protected function doOwnPrimaryTask()
        {
            var_dump('go to building');

            return $this;
        }
    }

    class FarmerWork extends GoWork
    {
        protected function doOwnPrimaryTask()
        {
            var_dump('go to farm');

            return $this;
        }
    }

    (new WorkerWork)->work();

最后,优雅的解决了问题!

---

# 总结

使用 Template method 能很好的封装功能的不变部分,同时拓展可变部分,易于维护,缺点就是相应的每个功能都需要子类来实现,导致类的个数增加。


text:
<zapaddon>
	<name>Quick Start</name>
	<version>15</version>
	<description>Provides a tab which allows you to quickly test a target application</description>
	<author>ZAP Dev Team</author>
	<url></url>
	<changes>
	<![CDATA[
	Generate the report (arg -quickout) even if view is initialised (Issue 1281).<br>
	Updated for ZAP 2.4
	]]>
	</changes>
	<extensions>
		<extension>org.zaproxy.zap.extension.quickstart.ExtensionQuickStart</extension>
	</extensions>
	<ascanrules/>
	<pscanrules/>
	<filters/>
	<files/>
	<not-before-version>2.4.0</not-before-version>
	<not-from-version/>
</zapaddon>


text:
class TokyoMetro::Factory::Generate::Static::StationsInTokyoMetro::Hash < TokyoMetro::Factory::Generate::Static::MetaClass::Group::Fundamental::FromHash
  include ::TokyoMetro::ClassNameLibrary::Static::StationsInTokyoMetro
end


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

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>com.hazelcast.concurrent.lock.operations (Hazelcast Root 3.3.3 API)</title>
<meta name="date" content="2014-11-12">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

com.hazelcast.concurrent.lock.operations

Classes

AwaitBackupOperation

AwaitOperation

BeforeAwaitBackupOperation

BeforeAwaitOperation

GetLockCountOperation

GetRemainingLeaseTimeOperation

IsLockedOperation

LocalLockCleanupOperation

LockBackupOperation

LockOperation

LockReplicationOperation

SignalBackupOperation

SignalOperation

UnlockBackupOperation

UnlockIfLeaseExpiredOperation

UnlockOperation


text:
@interface WebORBSerializer : NSObject <ISerializer> {
	FlashorbBinaryWriter	*buffer;
	int						version;
}
@property (nonatomic, assign) FlashorbBinaryWriter *buffer;
@property int version;

-(id)initWithWriter:(FlashorbBinaryWriter *)source;
-(id)initWithWriter:(FlashorbBinaryWriter *)source andVersion:(int)ver;
+(id)writer;
+(id)writer:(FlashorbBinaryWriter *)source;
+(id)writer:(FlashorbBinaryWriter *)source andVersion:(int)ver;
@end


text:
package org.csanchez.jenkins.plugins.kubernetes.pipeline;

import static java.util.Arrays.*;
import static org.csanchez.jenkins.plugins.kubernetes.KubernetesTestUtil.*;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.logging.Level;

import hudson.slaves.NodeProvisioner;
import io.fabric8.kubernetes.api.model.NamespaceBuilder;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.jenkins.plugins.kubernetes.NoDelayProvisionerStrategy;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;
import org.csanchez.jenkins.plugins.kubernetes.ContainerEnvVar;
import org.csanchez.jenkins.plugins.kubernetes.ContainerTemplate;
import org.csanchez.jenkins.plugins.kubernetes.KubernetesCloud;
import org.csanchez.jenkins.plugins.kubernetes.KubernetesComputer;
import org.csanchez.jenkins.plugins.kubernetes.KubernetesTestUtil;
import org.csanchez.jenkins.plugins.kubernetes.PodTemplate;
import org.csanchez.jenkins.plugins.kubernetes.model.KeyValueEnvVar;
import org.csanchez.jenkins.plugins.kubernetes.model.SecretEnvVar;
import org.csanchez.jenkins.plugins.kubernetes.model.TemplateEnvVar;
import org.jenkinsci.plugins.workflow.job.WorkflowJob;
import org.jenkinsci.plugins.workflow.job.WorkflowRun;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.rules.TestName;
import org.jvnet.hudson.test.BuildWatcher;
import org.jvnet.hudson.test.JenkinsRuleNonLocalhost;
import org.jvnet.hudson.test.LoggerRule;

import hudson.EnvVars;
import hudson.slaves.EnvironmentVariablesNodeProperty;
import hudson.slaves.NodeProperty;
import hudson.slaves.NodePropertyDescriptor;
import hudson.util.DescribableList;

public abstract class AbstractKubernetesPipelineTest {
    protected static final String CONTAINER_ENV_VAR_VALUE = "container-env-var-value";
    protected static final String POD_ENV_VAR_VALUE = "pod-env-var-value";
    protected static final String GLOBAL = "GLOBAL";

    @ClassRule
    public static BuildWatcher buildWatcher = new BuildWatcher();
    protected KubernetesCloud cloud;

    @Rule
    public JenkinsRuleNonLocalhost r = new JenkinsRuleNonLocalhost();
    @Rule
    public LoggerRule logs = new LoggerRule()
            .recordPackage(KubernetesCloud.class, Level.FINE)
            .recordPackage(NoDelayProvisionerStrategy.class, Level.FINE)
            .record(NodeProvisioner.class, Level.FINE)
            .record(KubernetesAgentErrorCondition.class, Level.FINE);

    @BeforeClass
    public static void isKubernetesConfigured() throws Exception {
        assumeKubernetes();
    }

    @Rule
    public TestName name = new TestName();

    private String projectName;

    protected WorkflowJob p;

    protected WorkflowRun b;

    @Before
    public void defineProjectName() {
        // Add spaces before uppercases
        this.projectName = generateProjectName(name.getMethodName());
    }

    protected String getProjectName() {
        return projectName;
    }

    /**
     * Creates a pipeline job using <methodName>.groovy as pipeline definition,
     * then schedule it and wait for it to start.
     *
     * Resolves $NAME to the method name in order to avoid any hard-coded reference
     * to the method name within the pipeline definition.
     *
     * @return The scheduled pipeline run
     * @throws IOException If something gets wrong when creating the pipeline job
     * @throws ExecutionException If something went wrong while retrieving the run object
     * @throws InterruptedException If the thread gets interrupted while waiting for the run to start
     */
    protected final WorkflowRun createJobThenScheduleRun() throws IOException, ExecutionException, InterruptedException {
        return createJobThenScheduleRun(null);
    }

    /**
     * Creates a pipeline job using <methodName>.groovy as pipeline definition,
     * then schedule it and wait for it to start.
     *
     * Resolves $NAME to the method name in order to avoid any hard-coded reference
     * to the method name within the pipeline definition. Also resolves any reference provided in the given env map.
     *
     * @param env an environment map to resolve in the pipeline script
     * @return The scheduled pipeline run
     * @throws IOException If something gets wrong when creating the pipeline job
     * @throws ExecutionException If something went wrong while retrieving the run object
     * @throws InterruptedException If the thread gets interrupted while waiting for the run to start
     */
    protected final WorkflowRun createJobThenScheduleRun(Map<String, String> env) throws IOException, ExecutionException, InterruptedException {
        b = createPipelineJobThenScheduleRun(r, getClass(), name.getMethodName(), env);
        p = b.getParent();
        return b;
    }

    protected final String loadPipelineDefinition() {
        return KubernetesTestUtil.loadPipelineDefinition(getClass(), name.getMethodName(), null);
    }

    @Before
    public void configureCloud() throws Exception {
        cloud = setupCloud(this, name);
        createSecret(cloud.connect(), cloud.getNamespace());
        cloud.getTemplates().clear();
        cloud.addTemplate(buildBusyboxTemplate("busybox"));

        setupHost(cloud);

        r.jenkins.clouds.add(cloud);

        DescribableList<NodeProperty<?>, NodePropertyDescriptor> list =  r.jenkins.getGlobalNodeProperties();
        EnvironmentVariablesNodeProperty newEnvVarsNodeProperty = new hudson.slaves.EnvironmentVariablesNodeProperty();
        list.add(newEnvVarsNodeProperty);
        EnvVars envVars = newEnvVarsNodeProperty.getEnvVars();
        envVars.put("GLOBAL", "GLOBAL");
        envVars.put("JAVA_HOME_X", "java-home-x");
        r.jenkins.save();
    }

    private PodTemplate buildBusyboxTemplate(String label) {
        // Create a busybox template
        PodTemplate podTemplate = new PodTemplate();
        podTemplate.setLabel(label);
        podTemplate.setTerminationGracePeriodSeconds(0L);

        ContainerTemplate containerTemplate = new ContainerTemplate("busybox", "busybox", "cat", "");
        containerTemplate.setTtyEnabled(true);
        podTemplate.getContainers().add(containerTemplate);
        setEnvVariables(podTemplate);
        return podTemplate;
    }

    protected String loadPipelineScript(String name) {
        return KubernetesTestUtil.loadPipelineScript(getClass(), name);
    }

    private static void setEnvVariables(PodTemplate podTemplate) {
        TemplateEnvVar podSecretEnvVar = new SecretEnvVar("POD_ENV_VAR_FROM_SECRET", "pod-secret", SECRET_KEY, false);
        TemplateEnvVar podSimpleEnvVar = new KeyValueEnvVar("POD_ENV_VAR", POD_ENV_VAR_VALUE);
        podTemplate.setEnvVars(asList(podSecretEnvVar, podSimpleEnvVar));
        TemplateEnvVar containerEnvVariable = new KeyValueEnvVar("CONTAINER_ENV_VAR", CONTAINER_ENV_VAR_VALUE);
        TemplateEnvVar containerEnvVariableLegacy = new ContainerEnvVar("CONTAINER_ENV_VAR_LEGACY",
                CONTAINER_ENV_VAR_VALUE);
        TemplateEnvVar containerSecretEnvVariable = new SecretEnvVar("CONTAINER_ENV_VAR_FROM_SECRET",
                                                                     "container-secret", SECRET_KEY, false);
        podTemplate.getContainers().get(0)
                .setEnvVars(asList(containerEnvVariable, containerEnvVariableLegacy, containerSecretEnvVariable));
    }

    protected void createNamespaceIfNotExist(KubernetesClient client, String namespace) {
        if (client.namespaces().withName(namespace).get() == null) {
            client.namespaces().createOrReplace(
                    new NamespaceBuilder().withNewMetadata().withName(namespace).endMetadata().build());
        }
    }

    protected static List<PodTemplate> podTemplatesWithLabel(String label, List<PodTemplate> templates) {
        return templates.stream().filter(t -> label.equals(t.getLabel())).collect(Collectors.toList());
    }

    @Nonnull
    protected List<KubernetesComputer> getKubernetesComputers() {
        return Arrays.stream(r.jenkins.getComputers())
                .filter(c -> c instanceof KubernetesComputer)
                .map(KubernetesComputer.class::cast)
                .collect(Collectors.toList());
    }
}


text:
import os
from twilio.rest import Client

# Your Account Sid and Auth Token from twilio.com/console
# To set up environmental variables, see http://twil.io/secure
api_key_sid = os.environ['TWILIO_API_KEY']
api_key_secret = os.environ['TWILIO_API_KEY_SECRET']
client = Client(api_key_sid, api_key_secret)

rooms = client.video.rooms.list(status='completed', unique_name='DailyStandup')

for room in rooms:
    print(room.sid)


text:
/**
* this is only needed in the Polyfill demos to distinguish the difference between native placeholders and the polyfill
*/
if(window.location.search && window.location.search == '?demo'){
    window.demo = true;
    document.documentElement.className += ' demo';
}

(function($) {
    var mode = window.demo ? 'OFF' : 'ON',
        link = window.demo ? '?' : '?demo',
        msg = '';
    if('placeholder' in $('<input>')[0]){ // don't run the polyfill when the browser has native support
        msg = 'YOUR CURRENT BROWSER HAS NATIVE SUPPORT! ';
        if(window.placeHolderConfig && window.placeHolderConfig.forceApply){
            msg += "THE POLYFILL WOULD'T NOT RUN BUT IT'S FORCED IN THIS EXAMPLE!";
        }else{
            msg += 'THE POLYFILL WILL NOT RUN!';
        }
        msg += '';
    }else{
        msg = 'Your current Browser does not have native support so the Polyfill will work its magic :-)';
    }
    $('#browserlist').after(msg);
    $('#nav strong').after(' [toggle demo '+mode+']');

    $('#updatetestbutton').click(function(){
        var currentPlaceholer = $('#updatetest').attr('placeholder');
        alert(currentPlaceholer);
        if(currentPlaceholer == 'whatever'){
            $('#updatetest').attr('placeholder','e.g. 42');
        }else{
            $('#updatetest').attr('placeholder','whatever');
        }
    });
})(jQuery);


text:
let fs = require('fs')
let PEG = require('pegjs')
let {assert} = require('chai')

let grammarFile = './shapes.grammar'
let grammar = null
let parser = null
let p = null;
describe('grammar file', function() {
  it ('should exist', function(done) {
    fs.readFile(grammarFile, function (err, data) {
      if (err) throw error
      grammar = data.toString()
      done()
    })
  })
  it ('should compile', () => {
    parser = PEG.buildParser(grammar)
    p = parser.parse
  })

})

describe('grammar rules', function() {
  describe('should recognize objects', function() {
    it ('lines', function() {
      let o = p('20px line')
      assert.propertyVal(o, 'size', 20)
      assert.deepPropertyVal(o, 'shape.type', 'line')
    })
    it ('squares', function() {
      let o = p('30px square')
      assert.propertyVal(o, 'size', 30)
      assert.deepPropertyVal(o, 'shape.type', 'polygon')
      assert.deepPropertyVal(o, 'shape.n', 4)
    })
    it ('circles', function() {
      let o = p('4px circle')
      assert.propertyVal(o, 'size', 4)
      assert.deepPropertyVal(o, 'shape.type', 'circle')
    })

    it ('triangle', function() {
      let o = p('30px triangle')
      assert.propertyVal(o, 'size', 30)
      assert.deepPropertyVal(o, 'shape.type', 'polygon')
      assert.deepPropertyVal(o, 'shape.n', 3)
    })

    it ('pentagon', function() {
      let o = p('30px pentagon')
      assert.propertyVal(o, 'size', 30)
      assert.deepPropertyVal(o, 'shape.type', 'polygon')
      assert.deepPropertyVal(o, 'shape.n', 5)
    })

    it ('hexagon', function() {
      let o = p('30px hexagon')
      assert.propertyVal(o, 'size', 30)
      assert.deepPropertyVal(o, 'shape.type', 'polygon')
      assert.deepPropertyVal(o, 'shape.n', 6)
    })

    it ('ngon', function() {
      let o = p('30px 3gon')
      assert.propertyVal(o, 'size', 30)
      assert.deepPropertyVal(o, 'shape.type', 'polygon')
      assert.deepPropertyVal(o, 'shape.n', 3)
    })
    it ('ngon alt', function() {
      let o = p('30px 5-gon')
      assert.propertyVal(o, 'size', 30)
      assert.deepPropertyVal(o, 'shape.type', 'polygon')
      assert.deepPropertyVal(o, 'shape.n', 5)
    })
    it ('ngon alt2', function() {
      let o = p('30px 10 -gon')
      assert.propertyVal(o, 'size', 30)
      assert.deepPropertyVal(o, 'shape.type', 'polygon')
      assert.deepPropertyVal(o, 'shape.n', 10)
    })
        it ('ngon alt3', function() {
      let o = p('30px 100 gon')
      assert.propertyVal(o, 'size', 30)
      assert.deepPropertyVal(o, 'shape.type', 'polygon')
      assert.deepPropertyVal(o, 'shape.n', 100)
    })

  })
  describe('should recognize angles', function() {
    it ('angle', function() {
      let o = p('20px line angle')
      assert.propertyVal(o, 'size', 20)
      assert.deepPropertyVal(o, 'shape.type', 'line')
      assert.deepPropertyVal(o, 'angle.random', false)
    })
    it ('random angle', function() {
      let o = p('20px line random angle')
      assert.propertyVal(o, 'size', 20)
      assert.deepPropertyVal(o, 'shape.type', 'line')
      assert.deepPropertyVal(o, 'angle.random', true)
    })
  })

  describe('should recognize modifiers', function() {
    it ('angle', function() {
      let o = p('20px line angle influenced by orientation to center ')
      assert.propertyVal(o, 'size', 20)
      assert.deepPropertyVal(o, 'shape.type', 'line')
      assert.deepPropertyVal(o, 'angle.random', false)
      assert.deepPropertyVal(o, 'angle.influence', 'centerOrientation')
    })
    it ('random angle', function() {
      let o = p('20px line random angle influenced by flow field')
      assert.propertyVal(o, 'size', 20)
      assert.deepPropertyVal(o, 'shape.type', 'line')
      assert.deepPropertyVal(o, 'angle.influence', 'flowField')
    })
  })

  describe('should recognize conditions', function() {
    it ('intersecting', function() {
      let o = p('20px line only draw if intersecting')
      assert.propertyVal(o, 'size', 20)
      assert.deepPropertyVal(o, 'shape.type', 'line')
      assert.deepPropertyVal(o, 'condition.intersect', true)
    })
    it ('intersecting alternate', function() {
      let o = p('20px line only draw if intersecting or first')
      assert.propertyVal(o, 'size', 20)
      assert.deepPropertyVal(o, 'shape.type', 'line')
      assert.deepPropertyVal(o, 'condition.intersect', true)
    })
    it ('not intersecting', function() {
      let o = p('20px line only draw if not intersecting or first')
      assert.propertyVal(o, 'size', 20)
      assert.deepPropertyVal(o, 'shape.type', 'line')
      assert.deepPropertyVal(o, 'condition.intersect', false)
    })
    it ('not intersecting alternate', function() {
      let o = p('20px line only draw if not intersecting')
      assert.propertyVal(o, 'size', 20)
      assert.deepPropertyVal(o, 'shape.type', 'line')
      assert.deepPropertyVal(o, 'condition.intersect', false)
    })
    it ('intersecting last 10', function() {
      let o = p('20px line only draw if intersecting last 10 or first')
      assert.propertyVal(o, 'size', 20)
      assert.deepPropertyVal(o, 'shape.type', 'line')
      assert.deepPropertyVal(o, 'condition.intersect', true)
      assert.deepPropertyVal(o, 'condition.last', 10)
    })
    it ('intersecting last 10 alternate', function() {
      let o = p('20px line only draw if intersecting last 10')
      assert.propertyVal(o, 'size', 20)
      assert.deepPropertyVal(o, 'shape.type', 'line')
      assert.deepPropertyVal(o, 'condition.intersect', true)
      assert.deepPropertyVal(o, 'condition.last', 10)
    })
    it ('not intersecting last 50', function() {
      let o = p('20px line only draw if not intersecting last 50 or first')
      assert.propertyVal(o, 'size', 20)
      assert.deepPropertyVal(o, 'shape.type', 'line')
      assert.deepPropertyVal(o, 'condition.intersect', false)
      assert.deepPropertyVal(o, 'condition.last', 50)
    })
    it ('not intersecting last 50 alternate', function() {
      let o = p('20px line only draw if not intersecting last 50')
      assert.propertyVal(o, 'size', 20)
      assert.deepPropertyVal(o, 'shape.type', 'line')
      assert.deepPropertyVal(o, 'condition.intersect', false)
      assert.deepPropertyVal(o, 'condition.last', 50)
    })
    it ('not intersecting short', function() {
      let o = p('20px line not intersecting')
      assert.propertyVal(o, 'size', 20)
      assert.deepPropertyVal(o, 'shape.type', 'line')
      assert.deepPropertyVal(o, 'condition.intersect', false)
    })
    it ('intersecting short', function() {
      let o = p('20px line intersecting')
      assert.propertyVal(o, 'size', 20)
      assert.deepPropertyVal(o, 'shape.type', 'line')
      assert.deepPropertyVal(o, 'condition.intersect', true)
    })
    it ('intersecting last short', function() {
      let o = p('20px line intersecting last 40')
      assert.propertyVal(o, 'size', 20)
      assert.deepPropertyVal(o, 'shape.type', 'line')
      assert.deepPropertyVal(o, 'condition.intersect', true)
      assert.deepPropertyVal(o, 'condition.last', 40)
    })

    it ('touching', function() {
      let o = p('20px line only draw if touching')
      assert.propertyVal(o, 'size', 20)
      assert.deepPropertyVal(o, 'shape.type', 'line')
      assert.deepPropertyVal(o, 'condition.intersect', true)
    })

    it ('not touching', function() {
      let o = p('20px line only draw if not touching')
      assert.propertyVal(o, 'size', 20)
      assert.deepPropertyVal(o, 'shape.type', 'line')
      assert.deepPropertyVal(o, 'condition.intersect', false)
    })

    it ('touching short', function() {
      let o = p('20px line touching')
      assert.propertyVal(o, 'size', 20)
      assert.deepPropertyVal(o, 'shape.type', 'line')
      assert.deepPropertyVal(o, 'condition.intersect', true)
    })
  })

  describe('complex', function() {
    it ('complex1', function() {
      let o = p('20px line random angle only draw if not intersecting last 50')
      assert.propertyVal(o, 'size', 20)
      assert.deepPropertyVal(o, 'shape.type', 'line')
      assert.deepPropertyVal(o, 'angle.random', true)
      assert.deepPropertyVal(o, 'condition.intersect', false)
      assert.deepPropertyVal(o, 'condition.last', 50)
    })
    it ('complex2', function() {
      let o = p('20px line random angle influenced by flow field only draw if not intersecting last 50')
      assert.propertyVal(o, 'size', 20)
      assert.deepPropertyVal(o, 'shape.type', 'line')
      assert.deepPropertyVal(o, 'angle.random', true)
      assert.deepPropertyVal(o, 'angle.influence', 'flowField')
      assert.deepPropertyVal(o, 'condition.intersect', false)
      assert.deepPropertyVal(o, 'condition.last', 50)
    })
    it ('complex1 reordered', function() {
      let o = p('only draw if not intersecting last 50 line 20px random angle ')
      assert.propertyVal(o, 'size', 20)
      assert.deepPropertyVal(o, 'shape.type', 'line')
      assert.deepPropertyVal(o, 'angle.random', true)
      assert.deepPropertyVal(o, 'condition.intersect', false)
      assert.deepPropertyVal(o, 'condition.last', 50)
    })
    it ('complex2 reordered', function() {
      let o = p('random angle influenced by flow field line only draw if not intersecting last 50 20px')
      assert.propertyVal(o, 'size', 20)
      assert.deepPropertyVal(o, 'shape.type', 'line')
      assert.deepPropertyVal(o, 'angle.random', true)
      assert.deepPropertyVal(o, 'angle.influence', 'flowField')
      assert.deepPropertyVal(o, 'condition.intersect', false)
      assert.deepPropertyVal(o, 'condition.last', 50)
    })
    it ('uppercase', function() {
      let o = p('RANDOM ANGLE INFLUENCED BY FLOW FIELD LINE ONLY DRAW IF NOT INTERSECTING LAST 50 20PX')
      assert.propertyVal(o, 'size', 20)
      assert.deepPropertyVal(o, 'shape.type', 'line')
      assert.deepPropertyVal(o, 'angle.random', true)
      assert.deepPropertyVal(o, 'angle.influence', 'flowField')
      assert.deepPropertyVal(o, 'condition.intersect', false)
      assert.deepPropertyVal(o, 'condition.last', 50)
    })
  })

})


text:
<?php

namespace frontend\models;

use Yii;
use frontend\models\Profile;

/**
 * This is the model class for table "gender".
 *
 * @property integer $id
 * @property string $gender_name
 *
 * @property Profile[] $profiles
 */
class Gender extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'gender';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['gender_name'], 'required'],
            [['gender_name'], 'string', 'max' => 255]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', 'ID'),
            'gender_name' => Yii::t('app', 'Gender Name'),
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getProfiles()
    {
        return $this->hasMany(Profile::className(), ['gender_id' => 'id']);
    }
}


text:
package org.springframework.cloud.stream.binder.kinesis.provisioning;

import java.util.List;

import com.amazonaws.services.kinesis.model.Shard;

import org.springframework.cloud.stream.provisioning.ProducerDestination;

/**
 * The Kinesis-specific {@link ProducerDestination} implementation.
 *
 * @author Artem Bilan
 *
 */
public final class KinesisProducerDestination implements ProducerDestination {

	private final String streamName;

	private final List<Shard> shards;

	KinesisProducerDestination(String streamName, List<Shard> shards) {
		this.streamName = streamName;
		this.shards = shards;
	}

	@Override
	public String getName() {
		return this.streamName;
	}

	@Override
	public String getNameForPartition(int shard) {
		return this.streamName;
	}

	public List<Shard> getShards() {
		return this.shards;
	}

	@Override
	public String toString() {
		return "KinesisProducerDestination{" + "streamName='" + this.streamName + '\''
				+ ", shards=" + this.shards + '}';
	}

}


text:
<?php

return [
    // Components
    'components' => [
        'last_updated' => 'Son Güncelleme: zaman tipi',
        'status'       => [
            1 => 'Çalışıyor',
            2 => 'Performans Problemleri',
            3 => 'Kısmi Kesinti',
            4 => 'Ana Kesinti',
        ],
        'group' => [
            'other' => 'Diğer Bileşenler',
        ],
    ],

    // Incidents
    'incidents' => [
        'none'          => 'Hiçbir olay raporlanmadı',
        'past'          => 'Geçmiş Olaylar',
        'previous_week' => 'Geçen Hafta',
        'next_week'     => 'Gelecek Hafta',
        'scheduled'     => 'Zamanlanmış bakım',
        'scheduled_at'  => ',zamanlanmış :zamandilimi',
        'status'        => [
            0 => 'Zamanlanmış', // TODO: Hopefully remove this.
            1 => 'İnceleniyor',
            2 => 'Tanımlandı',
            3 => 'İzleniyor',
            4 => 'Düzeltildi',
        ],
    ],

    // Service Status
    'service' => [
        'good'  => '[0,1] Sistem çalışır durumda| [2, Inf] Tüm sistemler çalışır durumda',
        'bad'   => '[0,1] Sistemde şu anda sorunlar yaşanıyor [2, Inf] Bazı sistemlerde sorunlar yaşanıyor',
        'major' => '[0,1] Bu serviste büyük bir kesinti yaşıyoruz [2, Inf] Bazı sistemlerde büyük bir kesintisi yaşıyoruz',
    ],

    'api' => [
        'regenerate' => 'API Key\'i yeniden oluştur',
        'revoke'     => 'API Anahtarı geçersiz kıl',
    ],

    // Metrics
    'metrics' => [
        'filter' => [
            'last_hour' => 'Son 1 saat',
            'hourly'    => 'Son 12 saat',
            'weekly'    => 'Hafta',
            'monthly'   => 'Ay',
        ],
    ],

    // Subscriber
    'subscriber' => [
        'subscribe' => 'En son güncelleştirmeleri almak için abone olun',
        'button'    => 'Abone Ol',
        'manage'    => [
            'no_subscriptions' => 'Şu anda tüm güncellemeleri abone oldunuz.',
            'my_subscriptions' => 'You\'re currently subscribed to the following updates.',
        ],
        'email' => [
            'subscribe'          => 'Güncellemeler için abone ol.',
            'subscribed'         => 'Bir email bildirimi almış olmalısın, lütfen aboneliğini onaylamak için kontrol et.',
            'verified'           => 'E mail aboneliğin kabul edildi. Teşekkürler!',
            'manage'             => 'Aboneliğinizi yönetin.',
            'unsubscribe'        => 'E-posta aboneliğinden çık.',
            'unsubscribed'       => 'Email aboneliğin iptal edildi.',
            'failure'            => 'Bazı şeyler yanlış gitti.',
            'already-subscribed' => 'Cannot subscribe :email because they\'re already subscribed.',
            'verify'             => [
                'text'           => "Lütfen email aboneliğinizi onaylayın :app_name Durum Güncellemesi.\n:link\nTeşekkürler",
                'html-preheader' => 'Lütfen email aboneliğinizi :app_name için onaylayın.',
                'html'           => '
Lütfen email aboneliğinizi onaylayın :app_name Durum güncellemesi.

:link

Thank you, :app_name
',
            ],
            'maintenance' => [
                'text'           => "New maintenance has been scheduled on :app_name.\nThank you, :app_name",
                'html-preheader' => 'New maintenance has been scheduled on :app_name.',
                'html'           => '
New maintenance has been scheduled on :app_name.
',
            ],
            'incident' => [
                'text'           => "New incident has been reported on :app_name.\nThank you, :app_name",
                'html-preheader' => 'New incident has been reported on :app_name.',
                'html'           => '
New incident has been reported on :app_name.

Thank you, :app_name
',
            ],
            'component' => [
                'subject'        => 'Component Status Update',
                'text'           => 'The component :component_name has seen a status change. The component is now at :component_human_status.\nThank you, :app_name',
                'html-preheader' => 'Component Update from :app_name',
                'html'           => '
The component :component_name has seen a status change. The component is now at :component_human_status.

Thank you, :app_name
',
                'tooltip-title'  => 'Subscribe to notifications for :component_name.',
            ],
        ],
    ],

    'users' => [
        'email' => [
            'invite' => [
                'text'           => "You have been invited to the team :app_name status page, to sign up follow the next link.\n:link\nThank you, :app_name",
                'html-preheader' => 'You have been invited to the team :app_name.',
                'html'           => '
You have been invited to the team :app_name status page, to sign up follow the next link.

:link

Thank you, :app_name
',
            ],
        ],
    ],

    'signup' => [
        'title'    => 'Kayıt Ol',
        'username' => 'Kullanıcı adı',
        'email'    => 'E-posta',
        'password' => 'Parola',
        'success'  => 'Hesabınız oluşturuldu.',
        'failure'  => 'Kayıt esnasında bir sorun oluştu.',
    ],

    'system' => [
        'update' => 'There is a newer version of Cachet available. You can learn how to update here!',
    ],

    // Modal
    'modal' => [
        'close'     => 'Kapat',
        'subscribe' => [
            'title'  => 'Subscribe to component updates',
            'body'   => 'Enter your email address to subscribe to updates for this component. If you\'re already subscribed, you\'ll already receive emails for this component.',
            'button' => 'Abone Ol',
        ],
    ],

    // Other
    'home'            => 'Ana Sayfa',
    'description'     => 'Stay up to date with the latest service updates from :app.',
    'powered_by'      => ':app Status Page is powered by Cachet.',
    'about_this_site' => 'Bu Site hakkında',
    'rss-feed'        => 'RSS',
    'atom-feed'       => 'Atom',
    'feed'            => 'Status Feed',

];


text:
(async function() {
  // screenshots in content shell are flaky and NO_NAVSTART occurs on bots way more frequently than local
  // ignore the results of the trace-dependent audits, just make sure they ran
  var FLAKY_AUDITS = [
    // metrics
    'first-contentful-paint',
    'first-meaningful-paint',
    'first-cpu-idle',
    'interactive',
    'estimated-input-latency',
    'speed-index',
    'metrics',
    'screenshot-thumbnails',
    // misc trace-based audits
    'load-fast-enough-for-pwa',
    'user-timings',
    'bootup-time',
    // opportunities
    'efficient-animated-content',
    'offscreen-images',
    'redirects',
    'render-blocking-resources',
    'unminified-css',
    'unminified-javascript',
    'unused-css-rules',
    'uses-optimized-images',
    'uses-rel-preload',
    'uses-responsive-images',
    'uses-text-compression',
    'uses-webp-images',
  ];

  TestRunner.addResult('Tests that audits panel works.\n');
  await TestRunner.navigatePromise('resources/audits-basic.html');

  await TestRunner.loadModule('audits_test_runner');
  await TestRunner.showPanel('audits');

  AuditsTestRunner.dumpStartAuditState();

  TestRunner.addResult(`\n=============== Lighthouse Status Updates ===============`);
  AuditsTestRunner.addStatusListener(msg => TestRunner.addResult(msg));
  AuditsTestRunner.getRunButton().click();

  var {artifacts, lhr} = await AuditsTestRunner.waitForResults();
  TestRunner.addResult(`\n=============== Lighthouse Results ===============`);
  TestRunner.addResult(`URL: ${lhr.finalUrl}`);
  TestRunner.addResult(`Version: ${lhr.lighthouseVersion}`);
  TestRunner.addResult(`TestedAsMobileDevice: ${artifacts.TestedAsMobileDevice}`);
  TestRunner.addResult(`ViewportDimensions: ${JSON.stringify(artifacts.ViewportDimensions, null, 2)}`);
  TestRunner.addResult('\n');

  Object.keys(lhr.audits).sort().forEach(auditName => {
    var audit = lhr.audits[auditName];

    if (FLAKY_AUDITS.includes(auditName)) {
      TestRunner.addResult(`${auditName}: flaky`);
    } else if (audit.scoreDisplayMode === 'error') {
      TestRunner.addResult(`${auditName}: ERROR ${audit.errorMessage}`);
    } else if (audit.scoreDisplayMode === 'binary') {
      TestRunner.addResult(`${auditName}: ${audit.score ? 'pass' : 'fail'}`);
    } else {
      TestRunner.addResult(`${auditName}: ${audit.scoreDisplayMode}`);
    }
  });

  const resultsElement = AuditsTestRunner.getResultsElement();
  const auditElements = resultsElement.querySelectorAll('.lh-audit');
  TestRunner.addResult(`\n# of .lh-audit divs: ${auditElements.length}`);

  TestRunner.completeTest();
})();


text:
layout: page
title: Riggs Electronics Award Ceremony
date: 2016-05-24
author: Margaret Simpson
tags: weekly links, java
status: published
summary: Nulla sagittis consectetur imperdiet. Curabitur dictum tellus.
banner: images/banner/leisure-05.jpg
booking:
  startDate: 02/27/2016
  endDate: 02/29/2016
  ctyhocn: LBBTXHX
  groupCode: REAC
published: true
---
Nulla facilisi. Vivamus tincidunt pellentesque congue. Vivamus tempus felis volutpat ligula suscipit lacinia. Etiam ullamcorper, augue consequat pretium vestibulum, ante velit mattis est, vel cursus neque leo a nunc. Vestibulum dignissim felis quis neque pharetra, at condimentum erat bibendum. Duis tempus libero sit amet mi placerat imperdiet. Pellentesque nisi odio, pulvinar et nisl nec, tincidunt commodo nulla.

* Proin ullamcorper tortor eu nunc gravida cursus
* Ut vitae purus nec nibh venenatis aliquet at et lorem
* Duis aliquet sem vel neque convallis, in accumsan augue faucibus.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla ornare mi tortor, ut ullamcorper mauris ultricies at. Vivamus gravida vulputate neque id gravida. Curabitur feugiat, ex vel egestas venenatis, libero diam dignissim nisi, ut ultricies sapien lectus a leo. Suspendisse sit amet aliquet metus. Duis viverra consequat lacinia. Praesent eget gravida diam. Nam malesuada ornare neque vel elementum. Mauris faucibus aliquam hendrerit. Vestibulum ac mi euismod, semper nisl id, malesuada neque. Suspendisse sed est et velit egestas elementum sed eget risus. Vivamus mollis faucibus justo ut tempor. Duis in justo aliquam, sagittis est a, dignissim leo. Nulla porttitor placerat finibus. Vestibulum efficitur elementum metus, ut sagittis risus. Nulla facilisi.


text:
<?php

// No direct access.
defined('_JEXEC') or die;

// Include the component HTML helpers.
JHtml::addIncludePath(JPATH_COMPONENT.'/helpers/html');
JHtml::_('behavior.tooltip');
JHtml::_('behavior.multiselect');

$user		= JFactory::getUser();
$listOrder	= $this->escape($this->state->get('list.ordering'));
$listDirn	= $this->escape($this->state->get('list.direction'));
?>

<form action="<?php echo JRoute::_('index.php?option=com_messages&view=messages'); ?>" method="post" name="adminForm" id="adminForm">
	<fieldset id="filter-bar">

			<?php echo JText::_('JSEARCH_FILTER_LABEL'); ?>
			<input type="text" name="filter_search" id="filter_search" value="<?php echo $this->escape($this->state->get('filter.search')); ?>" title="<?php echo JText::_('COM_MESSAGES_SEARCH_IN_SUBJECT'); ?>" />
			<button type="submit"><?php echo JText::_('JSEARCH_FILTER_SUBMIT'); ?></button>
			<button type="button" onclick="document.id('filter_search').value='';this.form.submit();"><?php echo JText::_('JSEARCH_FILTER_CLEAR'); ?></button>

			<select name="filter_state" class="inputbox" onchange="this.form.submit()">
				<option value=""><?php echo JText::_('JOPTION_SELECT_PUBLISHED');?></option>
				<?php echo JHtml::_('select.options', MessagesHelper::getStateOptions(), 'value', 'text', $this->state->get('filter.state'));?>
			</select>

	</fieldset>

					<input type="checkbox" name="checkall-toggle" value="" title="<?php echo JText::_('JGLOBAL_CHECK_ALL'); ?>" onclick="Joomla.checkAll(this)" />

					<?php echo JHtml::_('grid.sort',  'COM_MESSAGES_HEADING_SUBJECT', 'a.subject', $listDirn, $listOrder); ?>

					<?php echo JHtml::_('grid.sort', 'COM_MESSAGES_HEADING_READ', 'a.state', $listDirn, $listOrder); ?>

					<?php echo JHtml::_('grid.sort', 'COM_MESSAGES_HEADING_FROM', 'a.user_id_from', $listDirn, $listOrder); ?>

					<?php echo JHtml::_('grid.sort', 'JDATE', 'a.date_time', $listDirn, $listOrder); ?>

					<?php echo $this->pagination->getListFooter(); ?>

		<?php foreach ($this->items as $i => $item) :
			$canChange	= $user->authorise('core.edit.state', 'com_messages');
			?>
			<tr class="row<?php echo $i % 2; ?>">

					<?php echo JHtml::_('grid.id', $i, $item->message_id); ?>

					<a href="<?php echo JRoute::_('index.php?option=com_messages&view=message&message_id='.(int) $item->message_id); ?>">
						<?php echo $this->escape($item->subject); ?>

					<?php echo JHtml::_('messages.state', $item->state, $i, $canChange); ?>

					<?php echo $item->user_from; ?>

					<?php echo JHtml::_('date', $item->date_time, JText::_('DATE_FORMAT_LC2')); ?>

			<?php endforeach; ?>

		<input type="hidden" name="task" value="" />
		<input type="hidden" name="boxchecked" value="0" />
		<input type="hidden" name="filter_order" value="<?php echo $listOrder; ?>" />
		<input type="hidden" name="filter_order_Dir" value="<?php echo $listDirn; ?>" />
		<?php echo JHtml::_('form.token'); ?>

</form>


text:
const version = require('../package.json').version;
const makeSpaces = require('../core/util/makeSpaces');

const commandsDescription = {
  test: 'Create test screenshots and compare against the set you previously approved/referenced.',
  approve: 'Promotes all test bitmaps from last test run to reference bitmaps.',
  reference: 'Creates new reference screenshots. Deletes all existing reference files.',
  init: 'Generate BackstopJS boilerplate files in your CWD. NOTE: Overwrites existing config files!',
  remote: 'Launch BackstopJS remote service.',
  openReport: 'View the last test report in your browser.'
};

const optionsDescription = {
  '--config': 'Path to config file name',
  '--filter': 'A RegEx string used to filter by scenario labels when running "test", "reference", or "approve" commands',
  '-h, --help': 'Display usage',
  '-v, --version': 'Display version',
  '-i': 'Prevent deletion of non-matching reference files when running "reference" command (newer matching reference files are still overwritten)'
};

function makeDescription (descriptions) {
  return Object.keys(descriptions)
    .map(function (commandName) {
      return makeSpaces(4) + commandName + spacesBetweenCommandAndDescription(commandName) + descriptions[commandName];
    })
    .join('\n');
}

// Number of spaces to echo before writing description
const leftPaddingOfDescription = Object.keys(commandsDescription)
  .concat(Object.keys(optionsDescription))
  .map(function (string) {
    return string.length;
  })
  .reduce(function maxReducer (max, length) {
    return Math.max(max, length);
  }, 0);

function spacesBetweenCommandAndDescription (commandName) {
  return makeSpaces(2 + leftPaddingOfDescription - commandName.length);
}

const usage = '\
Welcome to BackstopJS ' + version + ' CLI\n\
\n\
Commands:\n\
' + makeDescription(commandsDescription) + '\n\
\n\
Options:\n\
' + makeDescription(optionsDescription) + '\n\
\n';

module.exports = usage;


text:
using System;
using CsvHelper.Configuration;
using NYCMobileDev.TransitApp.Domain.GTFS.Static.Subway.Entities;

namespace NYCMobileDev.TransitApp.Infrastructure.GTFS.Static.Subway.FileSystem.Mappings
{
    public sealed class StopMap : CsvClassMap<Stop>
    {
        public StopMap()
        {
            Map(m => m.StopId).Index(0);
            Map(m => m.StopName).Index(1);
            Map(m => m.StopLat).Index(2);
            Map(m => m.StopLng).Index(3);
            Map(m => m.LocationType).Index(4);
            Map(m => m.ParentStationId).Index(5);
        }
    }
}


text:
"""Provides the constants needed for the component."""

DOMAIN = "button"
SERVICE_PRESS = "press"


text:
package main

import (
	"errors"
	"flag"
	"fmt"
	"github.com/salesforce/rmux"
	. "github.com/salesforce/rmux/log"
	"net"
	"os"
	"runtime"
	"runtime/pprof"
	"strconv"
	"strings"
	"sync"
	"syscall"
	"github.com/salesforce/rmux/graphite"
	"time"
)

const DEFAULT_POOL_SIZE = 20

var host = flag.String("host", "localhost", "The host to listen for incoming connections on")
var port = flag.Int("port", 6379, "The port to listen for incoming connections on")
var socket = flag.String("socket", "", "The socket to listen for incoming connections on.  If this is provided, host and port are ignored")
var maxProcesses = flag.Int("maxProcesses", 0, "The number of processes to use.  If this is not defined, go's default is used.")
var poolSize = flag.Int("poolSize", DEFAULT_POOL_SIZE, "The size of the connection pools to use")
var tcpConnections = flag.String("tcpConnections", "localhost:6380 localhost:6381", "TCP connections (destination redis servers) to multiplex over")
var unixConnections = flag.String("unixConnections", "", "Unix connections (destination redis servers) to multiplex over")
var localTimeout = flag.Int64("localTimeout", 0, "Timeout to set locally in milliseconds (read+write)")
var localReadTimeout = flag.Int64("localReadTimeout", 0, "Timeout to set locally in milliseconds (read)")
var localWriteTimeout = flag.Int64("localWriteTimeout", 0, "Timeout to set locally (write)")
var remoteTimeout = flag.Int64("remoteTimeout", 0, "Timeout to set for remote redises (connect+read+write)")
var remoteReadTimeout = flag.Int64("remoteReadTimeout", 0, "Timeout to set for remote redises (read)")
var remoteWriteTimeout = flag.Int64("remoteWriteTimeout", 0, "Timeout to set for remote redises (write)")
var remoteConnectTimeout = flag.Int64("remoteConnectTimeout", 0, "Timeout to set for remote redises (connect)")
var cpuProfile = flag.String("cpuProfile", "", "Direct CPU Profile to target file")
var configFile = flag.String("config", "", "Configuration file (JSON)")
var doDebug = flag.Bool("debug", false, "Debug mode")
var graphiteServer = flag.String("graphite", "", "Graphite statsd endpoint")
var doTiming = flag.Bool("timing", false, "Send command timings to graphite")
var failover = flag.Bool("failover", false, "Failover to another connection pool if target pool is down in mux mode")
var useSyslog = flag.Bool("useSyslog", true, "If true, outputs to syslog as well as stdout")

func main() {
	flag.Parse()

	var configs []PoolConfig
	var err error

	if *cpuProfile != "" {
		f, err := os.Create(*cpuProfile)
		terminateIfError(err, "Error when creating cpu profile file: %s\r\n")

		pprof.StartCPUProfile(f)
		defer pprof.StopCPUProfile()
	}

	if *doDebug {
		SetLogLevel(LOG_DEBUG)
	} else {
		SetLogLevel(LOG_INFO)
	}
	UseSyslog(*useSyslog)

	if *graphiteServer != "" {
		Info("Enabling graphite stats")
		err := graphite.SetEndpoint(*graphiteServer)
		if err != nil {
			Error("Error when setting graphite endpoint: %s", err)
		}
	}

	if *doTiming {
		Info("Enabling graphite timings")
		graphite.EnableTimings()
	}

	if *configFile != "" {
		configs, err = ReadConfigFromFile(*configFile)
	} else {
		configs, err = configureFromArgs()
	}
	terminateIfError(err, "Error parsing configuration options: %s\r\n")

	rmuxInstances, err := createInstances(configs)
	terminateIfError(err, "Error creating rmux instances: %s\r\n")

	Info("Starting %d rmux instances", len(rmuxInstances))

	start(rmuxInstances)
}

func configureFromArgs() ([]PoolConfig, error) {
	var arrTcpConnections []string
	if *tcpConnections != "" {
		arrTcpConnections = strings.Split(*tcpConnections, " ")
	} else {
		arrTcpConnections = []string{}
	}

	var arrUnixConnections []string
	if *unixConnections != "" {
		arrUnixConnections = strings.Split(*unixConnections, " ")
	} else {
		arrUnixConnections = []string{}
	}

	config := []PoolConfig{{
		Host:         *host,
		Port:         *port,
		Socket:       *socket,
		MaxProcesses: *maxProcesses,
		PoolSize:     *poolSize,
		Failover:     *failover,

		TcpConnections:  arrTcpConnections,
		UnixConnections: arrUnixConnections,

		LocalTimeout:      *localTimeout,
		LocalReadTimeout:  *localReadTimeout,
		LocalWriteTimeout: *localWriteTimeout,

		RemoteTimeout:        *remoteTimeout,
		RemoteReadTimeout:    *remoteReadTimeout,
		RemoteWriteTimeout:   *remoteWriteTimeout,
		RemoteConnectTimeout: *remoteConnectTimeout,
	}}

	return config, nil
}

func createInstances(configs []PoolConfig) (rmuxInstances []*rmux.RedisMultiplexer, err error) {
	rmuxInstances = make([]*rmux.RedisMultiplexer, len(configs))

	defer func() {
		if err != nil {
			for _, instance := range rmuxInstances {
				if instance == nil {
					continue
				}

				instance.Listener.Close()
			}

			rmuxInstances = nil
		}
	}()

	for i, config := range configs {
		var rmuxInstance *rmux.RedisMultiplexer

		if config.MaxProcesses > 0 {
			Info("Max processes increased to: %d from: %d", config.MaxProcesses, runtime.GOMAXPROCS(config.MaxProcesses))
		}

		if config.PoolSize < 1 {
			Info("Pool size must be positive - defaulting to %d", DEFAULT_POOL_SIZE)
			config.PoolSize = DEFAULT_POOL_SIZE
		}

		if config.Socket != "" {
			syscall.Umask(0111)
			Info("Initializing rmux server on socket %s", config.Socket)
			rmuxInstance, err = rmux.NewRedisMultiplexer("unix", config.Socket, config.PoolSize)
		} else {
			Info("Initializing rmux server on host: %s and port: %d", config.Host, config.Port)
			rmuxInstance, err = rmux.NewRedisMultiplexer("tcp", net.JoinHostPort(config.Host, strconv.Itoa(config.Port)), config.PoolSize)
		}

		rmuxInstances[i] = rmuxInstance

		if err != nil {
			return
		}

		rmuxInstance.Failover = config.Failover

		if config.LocalTimeout != 0 {
			timeout := time.Duration(config.LocalTimeout) * time.Millisecond
			rmuxInstance.ClientReadTimeout = timeout
			rmuxInstance.ClientWriteTimeout = timeout
			Info("Setting local client read and write timeouts to: %s", timeout)
		}

		if config.LocalReadTimeout != 0 {
			timeout := time.Duration(config.LocalReadTimeout) * time.Millisecond
			rmuxInstance.ClientReadTimeout = timeout
			Info("Setting local client read timeout to: %s", timeout)
		}

		if config.LocalWriteTimeout != 0 {
			timeout := time.Duration(config.LocalWriteTimeout) * time.Millisecond
			rmuxInstance.ClientWriteTimeout = timeout
			Info("Setting local client write timeout to: %s", timeout)
		}

		if config.RemoteTimeout != 0 {
			duration := time.Duration(config.RemoteTimeout) * time.Millisecond
			rmuxInstance.EndpointConnectTimeout = duration
			rmuxInstance.EndpointReadTimeout = duration
			rmuxInstance.EndpointWriteTimeout = duration
			Info("Setting remote redis connect, read, and write timeouts to: %s", duration)
		}

		if config.RemoteConnectTimeout != 0 {
			duration := time.Duration(config.RemoteConnectTimeout) * time.Millisecond
			rmuxInstance.EndpointConnectTimeout = duration
			Info("Setting remote redis connect timeout to: %s", duration)
		}

		if config.RemoteReadTimeout != 0 {
			duration := time.Duration(config.RemoteReadTimeout) * time.Millisecond
			rmuxInstance.EndpointReadTimeout = duration
			Info("Setting remote redis read timeouts to: %s", duration)
		}

		if config.RemoteWriteTimeout != 0 {
			duration := time.Duration(config.RemoteWriteTimeout) * time.Millisecond
			rmuxInstance.EndpointWriteTimeout = duration
			Info("Setting remote redis write timeout to: %s", duration)
		}

		if len(config.TcpConnections) > 0 {
			for _, tcpConnection := range config.TcpConnections {
				Info("Adding tcp (destination) connection: %s", tcpConnection)
				rmuxInstance.AddConnection("tcp", tcpConnection)
			}
		}

		if len(config.UnixConnections) > 0 {
			for _, unixConnection := range config.UnixConnections {
				Info("Adding unix (destination) connection: %s", unixConnection)
				rmuxInstance.AddConnection("unix", unixConnection)
			}
		}

		if rmuxInstance.PrimaryConnectionPool == nil {
			err = errors.New("You must have at least one connection defined")
			return
		}
	}

	return rmuxInstances, nil
}

func start(rmuxInstances []*rmux.RedisMultiplexer) {
	var waitGroup sync.WaitGroup

	defer func() {
		for _, rmuxInstance := range rmuxInstances {
			rmuxInstance.Listener.Close()
		}
	}()

	for i, rmuxInstance := range rmuxInstances {
		waitGroup.Add(1)

		go func(instance *rmux.RedisMultiplexer) {
			defer waitGroup.Done()

			err := instance.Start()
			if err != nil {
				fmt.Fprintf(os.Stderr, "Error starting rmux instance %d: %s", i, err)
				return
			}
		}(rmuxInstance)
	}

	waitGroup.Wait()
}

// Terminates the program if the passed in error does not evaluate to nil.
// err will be the first value of formatted string
func terminateIfError(err error, format string, a ...interface{}) {
	if err != nil {
		allArgs := append([]interface{}{err}, a...)

		Error(format, allArgs...)
		os.Exit(1)
	}
}


text:
CREATE EVENT SESSION [AlwaysOn_health] ON SERVER
ADD EVENT [sqlserver].[alwayson_ddl_executed],
ADD EVENT [sqlserver].[availability_group_lease_expired],
ADD EVENT [sqlserver].[availability_replica_automatic_failover_validation],
ADD EVENT [sqlserver].[availability_replica_manager_state_change],
ADD EVENT [sqlserver].[availability_replica_state_change],
ADD EVENT [sqlserver].[lock_redo_blocked],
ADD EVENT [sqlserver].[error_reported]
    (
    WHERE ([error_number]=(9691) OR [error_number]=(35204) OR [error_number]=(9693) OR [error_number]=(26024) OR [error_number]=(28047) OR [error_number]=(26023) OR [error_number]=(9692) OR [error_number]=(28034) OR [error_number]=(28036) OR [error_number]=(28048) OR [error_number]=(28080) OR [error_number]=(28091) OR [error_number]=(26022) OR [error_number]=(9642) OR [error_number]=(35201) OR [error_number]=(35202) OR [error_number]=(35206) OR [error_number]=(35207) OR [error_number]=(26069) OR [error_number]=(26070) OR [error_number]>(41047) AND [error_number]<(41056) OR [error_number]=(41142) OR [error_number]=(41144) OR [error_number]=(1480) OR [error_number]=(823) OR [error_number]=(824) OR [error_number]=(829) OR [error_number]=(35264) OR [error_number]=(35265))
    )
ADD TARGET [package0].[event_file]
    (
    SET filename = N'AlwaysOn_health.xel',
        max_file_size = 5,
        max_rollover_files = 4
    )
WITH  (
        MAX_MEMORY = 4 MB,
        EVENT_RETENTION_MODE = ALLOW_SINGLE_EVENT_LOSS,
        MAX_DISPATCH_LATENCY = 30 SECONDS,
        MEMORY_PARTITION_MODE = NONE,
        TRACK_CAUSALITY = OFF,
        STARTUP_STATE = OFF
      );


text:
function varargout = prtScoreConfusionMatrix(guess, truth, possibleTruthValues, classNames)
%[confMat,occurances] = prtScoreConfusionMatrix(guess,truth)
% prtScoreConfusionMatrix Plot or return the confusion matrix
%
%   CONFMAT = prtScoreConfusionMatrix(GUESS, TRUTH) returns the confusion matrix that
%   results from comparing  GUESS as compared to the truth in TRUTH.
%   GUESS and TRUTH should both be Nx1 vectors. The elements of both TRUTH
%   and GUESS should be binary or interger class labels.
%
%   prtScoreConfustionMatrix(GUESS,TRUTH) called without any output
%   arguments plots the confusion matrix.
%
%    Example:
%    TestDataSet = prtDataGenMary;        % Create some test and
%    TrainingDataSet = prtDataGenMary;   % training data
%    classifier = prtClassMap;             % Create a classifier
%    classifier.internalDecider = prtDecisionMap;
%    classifier = classifier.train(TrainingDataSet);    % Train
%    classified = run(classifier, TestDataSet);
%    %  Display the confusion matrix
%    prtScoreConfusionMatrix(classified, TestDataSet)
%
%    See also: prtScoreRoc, prtScoreRmse, prtScoreRocNfa,
%    prtScorePercentCorrect, prtScoreAuc

% Copyright (c) 2014 CoVar Applied Technologies
%
% Permission is hereby granted, free of charge, to any person obtaining a
% copy of this software and associated documentation files (the
% "Software"), to deal in the Software without restriction, including
% without limitation the rights to use, copy, modify, merge, publish,
% distribute, sublicense, and/or sell copies of the Software, and to permit
% persons to whom the Software is furnished to do so, subject to the
% following conditions:
%
% The above copyright notice and this permission notice shall be included
% in all copies or substantial portions of the Software.
%
% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
% OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
% MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
% NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
% DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
% OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
% USE OR OTHER DEALINGS IN THE SOFTWARE.

% guess = [0;0;1;2;3;]; truth = [0;1;1;4;3;];
% prtScoreConfusionMatrix(guess,truth)
% prtScoreConfusionMatrix(guess,truth,[0 1 2 3 4])
% prtScoreConfusionMatrix(guess,truth,[0 1 2 3 4],{'A','B','C','D','E'})
% prtScoreConfusionMatrix(prtDataSetClass(guess,guess,'classNames',{'0','1','2','3'}),prtDataSetClass(nan(size(truth,1),1),truth,'classNames',{'A','B','C','D'}))
% prtScoreConfusionMatrix(prtDataSetClass(guess,guess,'classNames',{'0','1','2','3'}),prtDataSetClass(nan(size(truth,1),1),truth,'classNames',{'A','B','C','D'}),0:4,{'aa','bb','cc','dd','ee'})

if (nargin == 1 || isempty(truth)) && isa(guess,'prtDataSetClass')
    truth = guess;
end

[guess, truth, allClassNames, uniqueTruthValues, guessClassNames, truthClassNames, uClassesGuess, uClassesTruth] = prtUtilScoreParseFirstTwoInputs(guess,truth); %#ok<ASGLU>

assert(size(guess,2)==1,'guess should be a prtDataSet with 1 feature or a vector');

% Parse 3rd and 4th inputs
%% These inputs are used to
if nargin < 3 || isempty(possibleTruthValues)
    % Nothing do to keep from above
    %uClassesTruth = possiblGuessValues;
    %uClassesGuess = possiblGuessValues;
else
    % if you supplied possiblTruthValues we will make a square matrix with
    % these values. It is possible here that values in truth do not match those
    % in possibleGuessValues this will result in confusion matrices that do not
    % sum to 100% accross the rows.

    %uClassesTruth = intersect(possibleTruthValues,uClassesTruth);
    uClassesTruth = possibleTruthValues;
    uClassesGuess = possibleTruthValues;
end
if nargin < 4 || isempty(classNames)
    % Nothing to do  already have everything we need from above

    if nargin >= 3 && ~isempty(possibleTruthValues)
        % You supplied possibleTruthValues but not classNames
        % We need to generate appropriate classNames
        possibleTruthValues = possibleTruthValues(:);
        tempDs = prtDataSetClass(nan(size(possibleTruthValues,1),1),possibleTruthValues);
        classNames = tempDs.classNames;

        guessClassNames = classNames;
        truthClassNames = classNames;
    else
        % You didn't supply classNames or possibleTruthValues
        % everything is known from above
    end
else
    % You supplied classNames
    if nargin < 3 || isempty(possibleTruthValues)
        % You didn't supply possibleTruthValues
        % We will assume that you want the default joint truth values, but
        % we must check the dimensionality
        assert(length(uniqueTruthValues) == length(classNames),'prt:prtScoreConfusionMatrix:badInput','length of classNames does not match the number of unique values contained in both guess and truth');

        uClassesTruth = uniqueTruthValues;
        uClassesGuess = uniqueTruthValues;

        truthClassNames = classNames;
        guessClassNames = classNames;
    else
        % You supplied both must check the dimensionality
        assert(length(possibleTruthValues) == length(classNames),'prt:prtScoreConfusionMatrix:badInput','length of classNames must match the length of possibleTruthValues');

        uClassesTruth = possibleTruthValues;
        uClassesGuess = possibleTruthValues;

        truthClassNames = classNames;
        guessClassNames = classNames;

    end
end

if length(truth) ~= length(guess)
    error('prt:prtScoreConfusionMatrix:badInputs','guess and truth inputs must be the same length, or they must be prtDataSets with the same number of observations.')
end

nUClassesTruth = length(uClassesTruth);
nUClassesGuess = length(uClassesGuess);

confusionMat = zeros([nUClassesTruth,nUClassesGuess]);
occurances = zeros(nUClassesTruth,1);

for iTruthNum = 1:nUClassesTruth
    iTruth = uClassesTruth(iTruthNum);
    iTruthLocs = truth == iTruth;
    for jRespNum = 1:nUClassesGuess
        jResp = uClassesGuess(jRespNum);
        confusionMat(iTruthNum,jRespNum) = sum(guess(iTruthLocs) == jResp);
    end
    occurances(iTruthNum) = sum(iTruthLocs);
end

varargout = {};
if nargout
    varargout = {confusionMat, occurances};
else
    %prtUtilPlotConfusionMatrix(bsxfun(@rdivide,confusionMat,occurances),guessClassNames,truthClassNames);
    prtUtilPlotConfusionMatrix(confusionMat,guessClassNames,truthClassNames);

    pc = prtScorePercentCorrect(guess,truth);
    title(sprintf('%.2f%% Correct',pc*100));

end


text:
double Sonar_Reading = 5;
void update_sonar_data(const sensor_msgs::PointCloud::ConstPtr& msg)
{
  Sonar_Reading = (msg)->points[15].x;
}

class RobotDriver
{
private:
  //! The node handle we'll be using
  ros::NodeHandle nh_;
  //! We will be publishing to the "cmd_vel" topic to issue commands
  ros::Publisher cmd_vel_pub_;
  //! We will be listening to TF transforms as well
  tf::TransformListener listener_;
  //  We will be subscribing to distance and heading to be covered that is calculated by python script
  ros::Subscriber subscriber_for_sonar_data;
public:

  //! ROS node initialization
  RobotDriver(ros::NodeHandle &nh)
  {
    nh_ = nh;
    //set up the publisher for the cmd_vel topic
    cmd_vel_pub_ = nh_.advertise<geometry_msgs::Twist>("cmd_vel", 1);
    subscriber_for_sonar_data = nh_.subscribe("/atrvjr/sonar_cloud_body",1,update_sonar_data);
  }

  //! Drive forward a specified distance based on odometry information
  bool driveForwardOdom(double distance, double speed)
  {
    //wait for the listener to get the first message
    listener_.waitForTransform("/base_link", "odom",
                               ros::Time(0), ros::Duration(1.0));

    //we will record transforms here
    tf::StampedTransform start_transform;
    tf::StampedTransform current_transform;

    //record the starting transform from the odometry to the base frame
    listener_.lookupTransform("/base_link", "odom",
                              ros::Time(0), start_transform);

    //we will be sending commands of type "twist"
    geometry_msgs::Twist base_cmd;
    //the command will be to go forward at 0.25 m/s
    base_cmd.linear.y = base_cmd.angular.z = 0;
    base_cmd.linear.x = speed;

    ros::Rate rate(10.0);
    bool done = false;
    while (!done && nh_.ok())
    {
      //send the drive command
      cmd_vel_pub_.publish(base_cmd);
      rate.sleep();
      //get the current transform
      try
      {
        listener_.lookupTransform("/base_link", "odom",
                                  ros::Time(0), current_transform);
      }
      catch (tf::TransformException ex)
      {
        ROS_ERROR("%s",ex.what());
        break;
      }
      //see how far we've traveled
      tf::Transform relative_transform =
        start_transform.inverse() * current_transform;
      double dist_moved = relative_transform.getOrigin().length();

      if(dist_moved > distance) done = true;
    }
    if (done)
    {
	base_cmd.linear.y = base_cmd.angular.z = 0;
    	base_cmd.linear.x = 0.0;
    	//send the drive command
    	cmd_vel_pub_.publish(base_cmd);
    	rate.sleep();
	return true;
    }
    return false;
  }

};

bool sonar_safe()
{
  std::cout << Sonar_Reading <<std::endl;

  if (Sonar_Reading < 1.0)
  {
    return false;
  }

  return true;
}

int main(int argc, char** argv)
{
  //init the ROS node
  ros::init(argc, argv, "sonar_drive");
  ros::NodeHandle nh;
  RobotDriver driver(nh);
  ros::Publisher sonar_cmd_pub = nh.advertise<std_msgs::Bool>("/atrvjr/cmd_sonar_power", 10);

  std_msgs::Bool sonar_command;

  sonar_command.data = true; //turn on sonars
  sonar_cmd_pub.publish(sonar_command);
  std::cout << "Waiting 5 seconds" << std::endl;
  sleep(5);
  sonar_cmd_pub.publish(sonar_command);
  ros::spinOnce();
  do
  {
	driver.driveForwardOdom(1,0.5);
	ros::spinOnce(); //get new data

  }while (sonar_safe()); //check whether the sonars have detected an obstacle

sonar_command.data = false; //shut off sonars
sonar_cmd_pub.publish(sonar_command);
std::cout << "Sonars detected obstacle" << std::endl;

return 0;
}


text:
export type Context = Record<string, unknown>;
export type Contexts = Record<string, Context>;


text:
from urlparse import urlparse
from aux.api import http

class SOAPRequest(object):

    def __init__(self, url, headers, soap_content):
        self.url = url
        self.soap_ns = 'soapenv'
        self.headers = headers
        # self.soap_headers = soap_headers
        self.soap_content = soap_content
        self.body = self._request()

    def __str__(self):
        return self._request()

    def _request(self):
        return """<%s:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" >
<%s:Header/>
<%s:Body>
%s
</%s:Body>
</%s:Envelope>""" % (self.soap_ns,
                     self.soap_ns,
                     self.soap_ns,
                     self.soap_content,
                     self.soap_ns,
                     self.soap_ns)

    def send(self):
        response = http.post(self.url,
                             headers=self.headers,
                             body=self.body)
        return SOAPResponse(http_response=response)

class SOAPResponse(object):

    def __init__(self, http_response=None):
        if http_response is not None:
            self.http_response = http_response
        self.body = self.soap2json(self.http_response.body)

    def soap2json(self, xml):
        # print xml

        return xml

    def __str__(self):
        return self.http_response.body

# class SOAP(object):

#     def __init__(self):
#         pass

#     def send(self, request):
#         return SOAPResponse(http.post(self.url,
#                                       header=self.headers,
#                                       body=self.body))

# request = '''
# POST https://aux.protojour.com/ws/test-ws HTTP/1.1
# Accept-Encoding: gzip,deflate
# Content-Type: text/xml;charset=UTF-8
# SOAPAction: ""
# Authorization: Basic abcdefghijklmnopqrstuvwx
# Content-Length: 352
# Host: aux.protojour.com
# Connection: Keep-Alive
# User-Agent: Apache-HttpClient/4.1.1 (java 1.5)

# <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns="test" xmlns:com="test">
#    <soapenv:Header/>
#    <soapenv:Body>
#       <ns:ListSomething max="25">
#       </ns:ListSomething>
#    </soapenv:Body>
# </soapenv:Envelope>
# '''

# response = '''
# HTTP/1.1 200 OK
# Server: nginx/1.5.4
# Date: Wed, 12 Feb 2014 09:58:13 GMT
# Content-Type: text/xml;charset=utf-8
# Content-Length: 4734
# Connection: keep-alive
# Set-Cookie: JSESSIONID=oijoij6E0C7479C4CF531A5842241F47; Path=/; HttpOnly
# X-Request-Received: 1392199092003
# Accept: text/xml, text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
# SOAPAction: ""
# X-Src-Nginx: aux.protojour.com

# <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
# <SOAP-ENV:Header/><SOAP-ENV:Body></SOAP-ENV:Body></SOAP-ENV:Envelope>
# '''


text:
{% extends 'emails/base.html' %}

{% block preview_text %}
Address changed for your Email Congress account.
{% endblock %}

{% block content %}

You successfully updated the information for your email address!

                Contact your members of Congress at:

                    {% for member in members_of_congress %}

{{ member.email }}

                    {% endfor %}

                Or contact all of them at once using myreps@emailcongress.us

If this was not you, please disable these changed by updating your information.

Thank you for using Email Congress to contact Congress!

The Sunlight Foundation

{% endblock %}


text:
title: "Various flow control"
---

## If-expression

Squiggle has keywords `if` and `else`, but they're actually like JavaScript's ternary operator (`p ? x : y`), with the exception that Squiggle throws an error if the value being checked is not a boolean.

Note that the `else` clause is **not** optional. It must be present in all if-expressions.

```squiggle
console.log(
  if true then
    3
  else
    4
  end
)
```

This will log `3` to the console.

If you have more than two cases, you can use `elseif`:

```squiggle
def numberToEnglish(n) do
  if n == 1 then "one"
  elseif n == 2 then "two"
  elseif n == 3 then "three"
  elseif n == 4 then "four"
  else "some other number"
  end
end

console.log(numberToEnglish(2))
```

This would be better written with a match-expression, but more on that in a
later chapter.

## Try-expression

The keyword `try` is used to catch exceptions. Unlike JavaScript, Squiggle's
`try` produces values that can be used, rather than merely executing statements.

It is used before an expression, like `try f()` or `try foo.bar()`. The result
of a try expression is a length 2 array that looks like either `["ok", value]`
or `["fail", error]`. You can manually inspect these values using brackets, or ideally use `match` to cover both cases, like this:

```squiggle
let {JSON} = global

def safeParse(text) do
  match try JSON.parse(text)
  case ["ok", obj] then obj
  case ["fail", _] then {}
  end
end

def show(text) do
  console.log(safeParse(text))
end

show("[1, 2]")
#=> [1, 2]

show("json error")
#=> {}
```

## Error- and throw- expressions

Squiggle has two keywords for throwing exceptions.

The most important is `error`. It is used like:

```squiggle
error "Oopsy!"
```

It throws an instance of JavaScript's `Error` with the message passed.

There is also `throw` which takes an exception and throws it:

```squiggle
match try someFunction()
case ["ok", value] then
  # use the value
case ["fail", err] then
  # do some clean up
  throw err
end
```

This form is not advised, except for re-throwing exceptions caught elsewhere, since the form `error` is much shorter.


text:
/* global describe, it, expect, beforeEach, spyOn */

require('../bootstrap').bootstrap(__dirname + '/..');

var _ = require('underscore');

var requirejs = require('requirejs'),
    Util = requirejs('util');

describe('The class manager', function() {
    var fooFlag = false,
        Ancestor = Util.Class.define({
            foo: function() {
                fooFlag = true;
            }
        }),
        ancestor = new Ancestor();

    beforeEach(function() {
        fooFlag = false;
    });

    it('allows descendants to inherit their parents properties', function() {
        var Descendant = Util.extend(Ancestor, {
                bar: function() {
                }
            }),
            descendant = new Descendant();

        expect(ancestor.foo).toBeDefined();
        expect(ancestor.bar).not.toBeDefined();
        expect(descendant.foo).toBeDefined();
        expect(descendant.bar).toBeDefined();
        expect(descendant.hasOwnProperty('foo')).not.toBe(true);
    });

    it ('allows descendants to override their parent properties', function() {
        var anotherFlag = false,
            Descendant = Util.extend(Ancestor, {
                foo: function() {
                    anotherFlag = true;
                }
            }),
            descendant = new Descendant();

            descendant.foo();

            expect(anotherFlag).toBe(true);
            expect(fooFlag).toBe(false);
    });
});

describe('The generated constructor', function() {
    it('calls the create method', function() {
        var NewClass = Util.define({
                create: function(arg) {
                    this.arg = arg;
                }
            }),
            newClassInstance = new NewClass(10);

        expect(newClassInstance.arg).toBe(10);
    });
});

describe('The property annotation', function() {
    var TestClass = Util.define({
            properties: ['readWrite', 'anotherProp', 'customGetterSetter',
                {field: '_readOnly', getter: true},
                {field: '_writeOnly', setter: true},
                {field: '_named', getter: 'getThing', setter: 'setThing'},
            ],

            _readOnly: true,
            _customGetterSetter: true,

            getCustomGetterSetter: function() {
                return 10;
            },

            setCustomGetterSetter: function() {
                this._customGetterSetter = 20;
            }
        }),
        testInstance;

    beforeEach(function() {
        testInstance = new TestClass();
    });

    it('allows to autogenerate getters and setters', function() {
        expect(testInstance.getReadWrite()).toBeNull();
        testInstance.setReadWrite(true);
        expect(testInstance.getReadWrite()).toBe(true);
    });

    it('getters and setters can be enabled individually', function() {
        expect(testInstance.getReadOnly).toBeDefined();
        expect(testInstance.setReadOnly).not.toBeDefined();
        expect(testInstance.getWriteOnly).not.toBeDefined();
        expect(testInstance.setWriteOnly).toBeDefined();
        expect(testInstance.getReadOnly()).toBe(true);
        expect(testInstance._writeOnly).toBeNull();
        testInstance.setWriteOnly(true);
        expect(testInstance._writeOnly).toBe(true);
    });

    it('manually defined getters / setter have precedence over the autogenerated functions', function() {
        expect(testInstance.getCustomGetterSetter()).toBe(10);
        testInstance.setCustomGetterSetter(false);
        expect(testInstance._customGetterSetter).toBe(20);
    });

    it('getter / setter names can be customized', function() {
        expect(testInstance.getThing()).toBeNull();
        testInstance.setThing(true);
        expect(testInstance.getThing()).toBe(true);
    });

    it('autogenerated setters can be chained', function() {
        testInstance.setReadWrite(10).setAnotherProp(20);
        expect(testInstance.getReadWrite()).toBe(10);
        expect(testInstance.getAnotherProp()).toBe(20);
    });
});

describe('The mixins annotation', function() {
    it('copies all properties of the mixin class to the class prototype', function() {
        var Source = Util.define({
                foo: 1
            }),
            NewClass = Util.define({
                mixins: [Source]
            }),
            newClass = new NewClass();

        expect(newClass.foo).toBeDefined();
        expect(newClass.hasOwnProperty('foo')).toBe(false);
    });

    it('mixins can be either constructors, instances or plain objects', function() {
        var SourceClass = Util.define({
                foo: 1
            }),
            sourceInstance = new SourceClass(),
            plainSource = {
                foo: 1
            },
            NewClass1 = Util.define({
                mixins: [SourceClass]
            }),
            NewClass2 = Util.define({
                mixins: [sourceInstance]
            }),
            NewClass3 = Util.define({
                mixins: [plainSource]
            });

            expect((new NewClass1()).foo).toBeDefined();
            expect((new NewClass2()).foo).toBeDefined();
            expect((new NewClass3()).foo).toBeDefined();
    });

    it('does descend into the mixin\'s prototype and flattens the hierarchy', function() {
        var SourceBase = Util.define({
                foo: 1
            }),
            Source = Util.extend(SourceBase, {
                bar: 1
            }),
            NewClass = Util.define({
                mixins: [Source]
            });

        expect(NewClass.prototype.hasOwnProperty('foo')).toBe(true);
        expect(NewClass.prototype.hasOwnProperty('bar')).toBe(true);
    });

    it('does not override properties defined in the same class, but '
            + 'overrides properties defined on the prototype', function() {
        var base = {bar: 1},
            TargetClass1 = Util.define({
                mixins: [base],
                bar: 20
            }),
            TargetClass2 = Util.extend(TargetClass1, {
                mixins: [base]
            });

        expect((new TargetClass1()).bar).toBe(20);
        expect((new TargetClass2()).bar).toBe(1);
    });
});

describe('The base class Util.Base', function() {

    describe('provides the getConfig method which', function() {
        var NewClass = Util.extend(Util.Base, {
                properties: ['foo', 'bar'],

                setBarCalled: false,

                create: function(config) {
                    this.getConfig(config, ['foo', 'bar', 'baz']);
                },

                setBar: function(bar) {
                    this._bar = bar;
                    this.setBarCalled = true;
                }
            });

            it('is a convenience function for initializing properties from a config object', function() {
                var instance = new NewClass({foo: 1, bar: 2});

                expect(instance.getFoo()).toBe(1);
                expect(instance.getBar()).toBe(2);
            });

            it('does not enforce existence of the configured properties', function() {
                expect(function() {new NewClass({});}).not.toThrow();
            });

            it('uses setters where applicable...', function() {
                var instance = new NewClass({bar: 1});

                expect(instance.setBarCalled).toBe(true);
            });

            it('... and prefixes the property with an underscore _ otherwise', function() {
                var instance = new NewClass({baz: 1});

                expect(instance._baz).toBe(1);
            });
    });

    it('provides stub create and destroy methods', function() {
        expect(_.isFunction(Util.Base.prototype.create)).toBe(true);
        expect(_.isFunction(Util.Base.prototype.destroy)).toBe(true);
    });

});


text:
using namespace gpos;

SIZE_T CCustomAllocator::m_ulTotalMemoryAllocation = 0;
SIZE_T CCustomAllocator::m_ulLastMemoryAllocation = 0;

void*
CCustomAllocator::fnAlloc
  (
    SIZE_T ulAlloc
  )
{
  m_ulTotalMemoryAllocation += ulAlloc;
  m_ulLastMemoryAllocation = ulAlloc;

  return clib::PvMalloc(ulAlloc);
}

void
CCustomAllocator::fnFree
  (
    void* pMem
  )
{
  m_ulTotalMemoryAllocation -= m_ulLastMemoryAllocation;

  return clib::Free(pMem);
}

BOOL
gpos::FUseCustomAllocator
  (
    CMainArgs* pma
  )
{
  CHAR ch = '\0';
  bool fUseCustom  = false;
  while (pma->FGetopt(&ch))
  {
    switch(ch)
    {
      case 'c':
        fUseCustom = true;
        break;
      default:
        // ignore other arguments
        break;
    }
  }
  // Reset the optargs
  optind = 1;
  return fUseCustom;
}

//---------------------------------------------------------------------------
//	@function:
//		CMemoryPoolAllocTest::EresUnittest
//
//	@doc:
//		unit test driver
//
//---------------------------------------------------------------------------
GPOS_RESULT
CMemoryPoolAllocTest::EresUnittest() {
	CUnittest rgut[] =
		{
		GPOS_UNITTEST_FUNC(CMemoryPoolAllocTest::EresUnittest_AllocFree)
		};

	// execute unit tests
	return CUnittest::EresExecute(rgut, GPOS_ARRAY_SIZE(rgut));

}

//---------------------------------------------------------------------------
//	@function:
//		CMemoryPoolAllocTest::EresUnittest_AllocFree
//
//	@doc:
//	  Unit test to test a simple allocation and free through custom allocator
//
//---------------------------------------------------------------------------
GPOS_RESULT
CMemoryPoolAllocTest::EresUnittest_AllocFree() {
  CMemoryPoolAlloc customAlloc(CCustomAllocator::fnAlloc, CCustomAllocator::fnFree);

  SIZE_T ulTotalMemoryAllocated = CCustomAllocator::UlGetTotalMemoryAllocation();
  void * pMem = customAlloc.PvAllocate(100, __FILE__, __LINE__);
  GPOS_RTL_ASSERT
    (
      (ulTotalMemoryAllocated + 100) ==
      CCustomAllocator::UlGetTotalMemoryAllocation()
    );
  customAlloc.Free(pMem);
  GPOS_RTL_ASSERT
    (
     ulTotalMemoryAllocated ==
     CCustomAllocator::UlGetTotalMemoryAllocation()
     );
  return GPOS_OK;
}

// EOF


text:
package io.cattle.platform.process.progress;

import io.cattle.platform.engine.process.ProcessState;

public interface ProcessProgressInstance {

    void init(ProcessState state, int... checkpointWeights);

    void checkPoint(String name);

    void progress(Integer progress);

    void messsage(String message);

    String getCurrentCheckpoint();

}


text:
package com.chip8java.emulator.common;

import org.apache.commons.io.IOUtils;

import java.io.*;
import java.util.logging.Logger;

public class IO
{
    // The logger for the class
    private final static Logger LOGGER = Logger.getLogger(IO.class.getName());

    /**
     * Attempts to open the specified filename as an InputStream. Will return null if there is
     * an error.
     *
     * @param filename The String containing the full path to the filename to open
     * @return An opened InputStream, or null if there is an error
     */
    public static InputStream openInputStream(String filename) {
        try {
            return new FileInputStream(new File(filename));
        } catch (Exception e) {
            LOGGER.severe("Error opening file: " + e.getMessage());
            return null;
        }
    }

    /**
     * Attempts to open the specified resource as an InputStream. Will return null if there is
     * an error.
     *
     * @param filename The String containing the full path to the filename to open
     * @return An opened InputStream, or null if there is an error
     */
    public static InputStream openInputStreamFromResource(String filename) {
        try {
            return IO.class.getClassLoader().getResourceAsStream(filename);
        } catch (Exception e) {
            LOGGER.severe("Error opening resource file: " + e.getMessage());
            return null;
        }
    }

    /**
     * Closes an open input or output stream.
     *
     * @param stream the stream to close
     */
    public static boolean closeStream(Closeable stream) {
        try {
            stream.close();
            return true;
        } catch (Exception e) {
            LOGGER.severe("Error closing stream: " + e.getMessage());
            return false;
        }
    }

    /**
     * Copies an array of bytes to an array of shorts, starting at the offset
     * in the target memory array.
     *
     * @param stream the stream with the bytes to copy
     * @param target the target short array
     * @param offset where in the target array to copy bytes to
     * @return true if the source was not null, false otherwise
     */
    public static boolean copyStreamToShortArray(InputStream stream, short[] target, int offset) {
        int byteCounter = offset;
        byte[] source;

        if (target == null) {
            return false;
        }

        try {
            source = IOUtils.toByteArray(stream);
        } catch (Exception e) {
            LOGGER.severe("Error copying stream: " + e.getMessage());
            return false;
        }

        if (source.length > (target.length - offset)) {
            return false;
        }

        for (byte data : source) {
            target[byteCounter] = data;
            byteCounter++;
        }

        return true;
    }
}


text:
layout:     post
title:      "Jallunvalajat ry perustettu"
subtitle:   Perustamiskokous saatiin päätökseen jallunhuuruisissa tunnelmissa.
date:       2014-12-12 12:00:57
header-img: "img/jallu75.jpg"
categories: uutiset
---

Jallunvalajat ry näki päivänvalon joulukuun yhdentenätoista Jallun vuonna 2014. Yhdistyksen sääntö- sekä perustamiskokoukset pidettiin alkuillasta ja ensimmäinen hallitus saatiin valituksi hieman myöhemmin. Hallitus koostuu kokeneista jallunjuojista.

>Kierros jallua, olkaapa hyvät!

Jalluradio ja pikkulinnut kertovat, että Jallunvalajien ensimmäistä tapahtumaa, perinteistä Jalluaattoa, juhlitaan sunnuntaina 21.12. vielä tuntemattomassa paikassa. Lippujen kysyntä on ollut uskomatonta, vaikkei lipunmyynti ole vielä alkanutkaan. Jallunvalajien hallitus etsii parhaillaan tarpeeksi suurta tilaa tyydyttääkseen jallunjanoisten tarpeet.


text:
module SteamClubAPI
  class PlayerResource < Resource
    attr_reader :parser, :custom_url, :steam_id64_url

    def initialize(options = {})
      super
      @steam_id64_url = options.fetch :steam_id64_url, default_steam_id64_url
      @custom_url = options.fetch :custom_url, default_custom_url
      @parser = options.fetch :parser, default_parser
    end

    def self.search(query, options = {})
      type = case query
      when /^(?<num>\d+)$/
        :steam_id64
      else
        :custom
      end

      new(options).search(type, query)
    end

    def search(type, query)
      url = url_for(type)
      return false unless url

      parser.parse request(:get, resource_name: url.gsub('{{query}}', query))
    end

    private

    def url_for(type)
      type_url = "#{type}_url"
      send(type_url) if respond_to?(type_url)
    end

    def default_steam_id64_url
      "http://steamcommunity.com/profiles/{{query}}?xml=1"
    end

    def default_custom_url
      "http://steamcommunity.com/id/{{query}}?xml=1"
    end

    def default_parser
      SteamClubAPI::Parsers::PlayerParser
    end
  end
end


text:
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>demo on Dominic Motuka</title>
    <link>https://daumie.github.io/hugo_blog/tags/demo/</link>
    <description>Recent content in demo on Dominic Motuka</description>
    <generator>Hugo -- gohugo.io</generator>
    <language>en-us</language>
    <copyright>This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License.</copyright>
    <lastBuildDate>Mon, 24 Dec 2018 12:29:41 +0800</lastBuildDate>

	<atom:link href="https://daumie.github.io/hugo_blog/tags/demo/index.xml" rel="self" type="application/rss+xml" />

    <item>
      <title>The "figure" Shortcode</title>
      <link>https://daumie.github.io/hugo_blog/posts/the-figure-shortcode/</link>
      <pubDate>Mon, 24 Dec 2018 12:29:41 +0800</pubDate>

      <guid>https://daumie.github.io/hugo_blog/posts/the-figure-shortcode/</guid>
      <description>Hugo has figure shortcode built in, so you can easily add figcaptions or hyperlink rel attributes to images. Documentations can be found here:
https://gohugo.io/content-management/shortcodes/#figure
This theme has 3 CSS classes made for figure elements:
 big: images will break the width limit of main content area. left: images will float to the left. right: images will float to the right.  If a figure has no class set, the image will behave just like a normal markdown image: !</description>
    </item>

    <item>
      <title>Post With Featured Image</title>
      <link>https://daumie.github.io/hugo_blog/posts/post-with-featured-image/</link>
      <pubDate>Mon, 01 Oct 2018 16:15:09 +0800</pubDate>

      <guid>https://daumie.github.io/hugo_blog/posts/post-with-featured-image/</guid>
      <description>Just define the image URL in the content's front matter, the featured image will be displayed as the background.
For example:
---images:-https://picsum.photos/1024/768/?random--- This is an array, you can set multiple urls, only the first url will be used. These images is also used in Twitter Cards and the Open Graph metadata.</description>
    </item>

    <item>
      <title>Typography</title>
      <link>https://daumie.github.io/hugo_blog/posts/typography/</link>
      <pubDate>Sat, 29 Sep 2018 11:36:33 +0800</pubDate>

      <guid>https://daumie.github.io/hugo_blog/posts/typography/</guid>
      <description>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</description>
    </item>

  </channel>
</rss>