text:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using QuadTreeLib;

namespace QuadTreeTestProject
{
    [TestClass]
    public class VectorTest
    {
        [TestMethod]
        public void TestVector()
        {
            //Assemble
            Vector vect = new Vector(10, 20);

            //Assert
            Assert.AreEqual(vect.X, 10);
            Assert.AreEqual(vect.Y, 20);

            //Act
            vect.X = 20;
            vect.Y = 10;

            //Assert
            Assert.AreEqual(vect.X, 20);
            Assert.AreEqual(vect.Y, 10);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
import React, {Component} from 'react';
import ReactDOM from 'react-dom';

import QueueAnim from 'rc-queue-anim';

import httpManager from '../API/httpManager';
import hitokotoDriver from '../API/hitokotoDriver';
import indexedDBManager from '../API/IndexedDBManager';
import showNotification from '../API/showNotification';

import PublicHitokoto from '../component/PublicHitokoto'
import FullPageCard from '../component/FullPageCard'
import Pagination from '../component/Pagination';
import Loading from '../component/Loading'

class Review extends Component {
  constructor(props) {
    super(props);
    this.state = {
      hitokotos: [],
      passed: [],
      inited: false,
      error: null,
      total: 1,
      current: 1
    }

    this.getNeedReviewHitokotos = this.getNeedReviewHitokotos.bind(this);

    this.allow = this.allow.bind(this);
    this.regret = this.regret.bind(this);
    this.reject = this.reject.bind(this);
    this.detail = this.detail.bind(this);
    this.refresh = this.refresh.bind(this);
  }
  componentWillMount() {
    this.getNeedReviewHitokotos(1);
  }
  refresh() {
    this.getNeedReviewHitokotos(this.state.current, this.state.total);
  }
  getNeedReviewHitokotos(page, perpage = 10) {

    let element = ReactDOM.findDOMNode(this);
    if (element) {
      if (element.scrollIntoView) {
        element.scrollIntoView({behavior: 'smooth', block: "start", inline: "nearest"});
      } else {
        element.scrollTop = 0;
      }
    }

    this.setState({inited: false})
    httpManager.API_Admin_getNeedReviewHitokotos(page, perpage).then(result => {
      this.setState({
        inited: true,
        error: null,
        hitokotos: result.hitokotos,
        passed: new Array(result.hitokotos.length).fill(null),
        current: result.currentPage,
        total: result.totalPage
      });
    }).catch(e => {
      showNotification('获取失败!' + e.message || e, 'error');
      this.setState({
        error: e.message || e || '获取句集内容失败!',
        inited: false
      });
    })
  }
  allow(evt) {
    let index = evt.target.getAttribute('data-index');
    let hitokoto = this.state.hitokotos[index];
    httpManager.API_Admin_changeHitokotoState(hitokoto._id, 'public').then(res => {
      //
      this.setState(state => {
        state.passed[index] = true;
        return state;
      });
    })
  }
  regret(evt) {
    let index = evt.target.getAttribute('data-index');
    let hitokoto = this.state.hitokotos[index];
    httpManager.API_Admin_changeHitokotoState(hitokoto._id, 'reviewing').then(res => {
      //

      this.setState(state => {
        state.passed[index] = null;
        return state;
      });
    })
  }
  reject(evt) {
    let index = evt.target.getAttribute('data-index');
    let hitokoto = this.state.hitokotos[index];
    httpManager.API_Admin_changeHitokotoState(hitokoto._id, 'rejected').then(res => {
      //

      this.setState(state => {
        state.passed[index] = false;
        return state;
      });
    })
  }
  detail(evt) {
    let index = evt.target.getAttribute('data-index');
    let hitokoto = this.state.hitokotos[index];
    showNotification(JSON.stringify(hitokoto, null, 2), 'info', true);
  }

  userNameClickProxy(index) {
    let target = this.state.hitokotos[index];
    if (target.creator_id && target.creator) {
      window.trickyUid = target.creator_id;
      this.props.history.push('/explore/' + target.creator);
    } else {
      showNotification('无法跳转到用户详情,可能句子不是本网站的。');
    }
  }
  collectionClickProxy(index) {
    let target = this.state.hitokotos[index];
    if (target.creator_id && target.creator && target.collection) {
      window.trickyUid = target.creator_id;
      this.props.history.push('/explore/' + target.creator + '/' + target.collection);
    } else {
      showNotification('无法跳转到句集详情,可能句子不是本网站的。');
    }
  }
  render() {

    let hitokotos = this.state.hitokotos,
      ListToShow = null;
    if (this.state.inited) {
      if (hitokotos.length == 0) {
        ListToShow = (

没有待审核的句子!

这里什么都没有

        )
      } else {
        let passed = this.state.passed;
        ListToShow = hitokotos.map((hitokoto, index) => (
          <PublicHitokoto
            key={hitokoto._id}
            data={hitokoto}
            usernameProxy={() => this.userNameClickProxy(index)}
            collectionProxy={() => this.collectionClickProxy(index)}>
            <button data-index={index} onClick={this.detail}>详细信息</button>
            {passed[index] === null
              ? [(
                  <button key={index + 'pass'} data-index={index} onClick={this.allow}>通过</button>
                ), (
                  <button
                    key={index + 'block'}
                    data-index={index}
                    className="color-red"
                    onClick={this.reject}>驳回</button>
                )]
              : (
                <button data-index={index} onClick={this.regret}>需要再考虑一次</button>
              )}
          </PublicHitokoto>
        ))
      }
    }

    return (
      <FullPageCard cardname="审核">
        <QueueAnim
          ease='easeOutQuart'
          animConfig={[
          {
            opacity: [1, 0]
          }, {
            left: '0',
            right: '0',
            position: 'absolute',
            opacity: [1, 0]
          }
        ]}>
          {this.state.inited
            ? null
            : <Loading
              error={this.state.error}
              retry={() => {
              this.getNeedReviewHitokotos(this.state.current)
            }}
              key="loading"/>}

{ListToShow}

        </QueueAnim>

          <button onClick={this.refresh}>刷新本页</button>

        <Pagination
          current={this.state.current || 1}
          total={this.state.total || 1}
          limit={10}
          func={this.getNeedReviewHitokotos}></Pagination>
      </FullPageCard>
    )
  }
}
export default Review


text:
package main

func an_int() int {
	// Return expression is not an int
	return
}


text:
package org.apache.cassandra.db.guardrails;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

import org.junit.After;
import org.junit.Test;

import org.apache.cassandra.ServerTestUtils;
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.db.Keyspace;
import org.apache.cassandra.locator.AbstractEndpointSnitch;
import org.apache.cassandra.locator.IEndpointSnitch;
import org.apache.cassandra.locator.InetAddressAndPort;
import org.apache.cassandra.locator.Replica;
import org.apache.cassandra.service.ClientWarn;
import org.apache.cassandra.service.StorageService;
import org.assertj.core.api.Assertions;

import static java.lang.String.format;

public class GuardrailMaximumReplicationFactorTest extends ThresholdTester
{
    private static final int MAXIMUM_REPLICATION_FACTOR_WARN_THRESHOLD = 2;
    private static final int MAXIMUM_REPLICATION_FACTOR_FAIL_THRESHOLD = 4;
    private static final int DISABLED_GUARDRAIL = -1;

    public GuardrailMaximumReplicationFactorTest()
    {
        super(MAXIMUM_REPLICATION_FACTOR_WARN_THRESHOLD,
              MAXIMUM_REPLICATION_FACTOR_FAIL_THRESHOLD,
              Guardrails.maximumReplicationFactor,
              Guardrails::setMaximumReplicationFactorThreshold,
              Guardrails::getMaximumReplicationFactorWarnThreshold,
              Guardrails::getMaximumReplicationFactorFailThreshold);
    }

    @After
    public void cleanupTest() throws Throwable
    {
        execute("DROP KEYSPACE IF EXISTS ks");
        DatabaseDescriptor.setDefaultKeyspaceRF(1);
    }

    @Override
    protected long currentValue()
    {
        return Long.parseLong((Keyspace.open("ks").getReplicationStrategy()).configOptions.get("datacenter1"));
    }

    @Override
    protected List<String> getWarnings()
    {
        List<String> warnings = ClientWarn.instance.getWarnings();

        // filtering out non-guardrails produced warnings
        return warnings == null
               ? Collections.emptyList()
               : warnings.stream()
                         .filter(w -> !w.contains("keyspace ks is higher than the number of nodes 1 for datacenter1") &&
                                      !w.contains("When increasing replication factor you need to run a full (-full) repair to distribute the data") &&
                                      !w.contains("keyspace ks is higher than the number of nodes") &&
                                      !w.contains("Your replication factor 3 for keyspace ks is higher than the number of nodes 2 for datacenter datacenter2"))
                         .collect(Collectors.toList());
    }

    @Test
    public void testMaxKeyspaceRFDisabled() throws Throwable
    {
        guardrails().setMaximumReplicationFactorThreshold(DISABLED_GUARDRAIL, DISABLED_GUARDRAIL);
        assertMaxThresholdValid("CREATE KEYSPACE ks WITH replication = { 'class': 'NetworkTopologyStrategy', 'datacenter1': 6}");
        assertMaxThresholdValid("ALTER KEYSPACE ks WITH replication = { 'class' : 'NetworkTopologyStrategy', 'datacenter1': 10}");
    }

    @Test
    public void testSimpleStrategyCreate() throws Throwable
    {
        guardrails().setMaximumReplicationFactorThreshold(MAXIMUM_REPLICATION_FACTOR_WARN_THRESHOLD, MAXIMUM_REPLICATION_FACTOR_FAIL_THRESHOLD);
        assertWarns("CREATE KEYSPACE ks WITH replication = { 'class': 'SimpleStrategy', 'replication_factor': 3}", 3);
        execute("DROP KEYSPACE IF EXISTS ks");
        assertFails("CREATE KEYSPACE ks WITH replication = { 'class': 'SimpleStrategy', 'replication_factor': 5}", 5);
    }

    @Test
    public void testSimpleStrategyAlter() throws Throwable
    {
        guardrails().setMaximumReplicationFactorThreshold(MAXIMUM_REPLICATION_FACTOR_WARN_THRESHOLD, MAXIMUM_REPLICATION_FACTOR_FAIL_THRESHOLD);
        execute("CREATE KEYSPACE ks WITH replication = { 'class': 'SimpleStrategy', 'replication_factor': 2}");
        assertWarns("ALTER KEYSPACE ks WITH replication = { 'class': 'SimpleStrategy', 'replication_factor': 3}", 3);
        assertFails("ALTER KEYSPACE ks WITH replication = { 'class': 'SimpleStrategy', 'replication_factor': 5}", 5);
    }

    @Test
    public void testMultipleDatacenter() throws Throwable
    {
        IEndpointSnitch snitch = DatabaseDescriptor.getEndpointSnitch();
        DatabaseDescriptor.setEndpointSnitch(new AbstractEndpointSnitch()
        {
            public static final String RACK1 = ServerTestUtils.RACK1;

            @Override
            public String getRack(InetAddressAndPort endpoint) { return RACK1; }

            @Override
            public String getDatacenter(InetAddressAndPort endpoint) { return "datacenter2"; }

            @Override
            public int compareEndpoints(InetAddressAndPort target, Replica a1, Replica a2) { return 0; }
        });

        List<String> twoWarnings = Arrays.asList(format("The keyspace ks has a replication factor of 3, above the warning threshold of %s.", MAXIMUM_REPLICATION_FACTOR_WARN_THRESHOLD),
                                                 format("The keyspace ks has a replication factor of 3, above the warning threshold of %s.", MAXIMUM_REPLICATION_FACTOR_WARN_THRESHOLD));

        StorageService.instance.getTokenMetadata().updateHostId(UUID.randomUUID(), InetAddressAndPort.getByName("127.0.0.255"));
        guardrails().setMaximumReplicationFactorThreshold(MAXIMUM_REPLICATION_FACTOR_WARN_THRESHOLD, MAXIMUM_REPLICATION_FACTOR_FAIL_THRESHOLD);
        assertValid("CREATE KEYSPACE ks WITH replication = { 'class' : 'NetworkTopologyStrategy', 'datacenter1': 2, 'datacenter2' : 2}");
        execute("DROP KEYSPACE IF EXISTS ks");
        assertWarns("CREATE KEYSPACE ks WITH replication = { 'class': 'NetworkTopologyStrategy', 'datacenter1': 2, 'datacenter2' : 3}", 3);
        execute("DROP KEYSPACE IF EXISTS ks");
        assertWarns("CREATE KEYSPACE ks WITH replication = { 'class' : 'NetworkTopologyStrategy', 'datacenter1': 3, 'datacenter2' : 3}", twoWarnings);
        execute("DROP KEYSPACE IF EXISTS ks");
        assertFails("CREATE KEYSPACE ks WITH replication = { 'class' : 'NetworkTopologyStrategy', 'datacenter1': 2, 'datacenter2' : 5}", 5);
        execute("DROP KEYSPACE IF EXISTS ks");
        assertFails("CREATE KEYSPACE ks WITH replication = { 'class' : 'NetworkTopologyStrategy', 'datacenter1': 5, 'datacenter2' : 5}", 5);
        execute("DROP KEYSPACE IF EXISTS ks");

        execute("CREATE KEYSPACE ks WITH replication = { 'class' : 'NetworkTopologyStrategy', 'datacenter1': 1, 'datacenter2' : 1}");
        assertValid("ALTER KEYSPACE ks WITH replication = { 'class' : 'NetworkTopologyStrategy', 'datacenter1': 2, 'datacenter2' : 2}");
        assertWarns("ALTER KEYSPACE ks WITH replication = { 'class' : 'NetworkTopologyStrategy', 'datacenter1': 2, 'datacenter2' : 3}", 3);
        assertWarns("ALTER KEYSPACE ks WITH replication = { 'class' : 'NetworkTopologyStrategy', 'datacenter1': 3, 'datacenter2' : 3}", twoWarnings);
        assertFails("ALTER KEYSPACE ks WITH replication = { 'class' : 'NetworkTopologyStrategy', 'datacenter1': 2, 'datacenter2' : 5}", 5);
        assertFails("ALTER KEYSPACE ks WITH replication = { 'class' : 'NetworkTopologyStrategy', 'datacenter1': 5, 'datacenter2' : 5}", 5);

        DatabaseDescriptor.setEndpointSnitch(snitch);
    }

    @Test
    public void testMaxKeyspaceRFOnlyWarnBelow() throws Throwable
    {
        guardrails().setMaximumReplicationFactorThreshold(MAXIMUM_REPLICATION_FACTOR_WARN_THRESHOLD, DISABLED_GUARDRAIL);
        assertMaxThresholdValid("CREATE KEYSPACE ks WITH replication = { 'class': 'NetworkTopologyStrategy', 'datacenter1': 2}");
        assertMaxThresholdValid("ALTER KEYSPACE ks WITH replication = { 'class': 'NetworkTopologyStrategy', 'datacenter1': 1}");
    }

    @Test
    public void testMaxKeyspaceRFOnlyWarnAbove() throws Throwable
    {
        guardrails().setMaximumReplicationFactorThreshold(MAXIMUM_REPLICATION_FACTOR_WARN_THRESHOLD, DISABLED_GUARDRAIL);
        assertWarns("CREATE KEYSPACE ks WITH replication = { 'class': 'NetworkTopologyStrategy', 'datacenter1': 3}", 3);
        assertWarns("ALTER KEYSPACE ks WITH replication = { 'class': 'NetworkTopologyStrategy', 'datacenter1': 4}", 4);
    }

    @Test
    public void testMaxKeyspaceRFOnlyFailBelow() throws Throwable
    {
        guardrails().setMaximumReplicationFactorThreshold(DISABLED_GUARDRAIL, MAXIMUM_REPLICATION_FACTOR_FAIL_THRESHOLD);
        assertMaxThresholdValid("CREATE KEYSPACE ks WITH replication = { 'class': 'NetworkTopologyStrategy', 'datacenter1': 2}");
        assertMaxThresholdValid("ALTER KEYSPACE ks WITH replication = { 'class': 'NetworkTopologyStrategy', 'datacenter1': 3}");
    }

    @Test
    public void testMaxKeyspaceRFOnlyFailAbove() throws Throwable
    {
        guardrails().setMaximumReplicationFactorThreshold(DISABLED_GUARDRAIL, MAXIMUM_REPLICATION_FACTOR_FAIL_THRESHOLD);
        assertFails("CREATE KEYSPACE ks WITH replication = { 'class': 'NetworkTopologyStrategy', 'datacenter1': 5}", 5);
    }

    @Test
    public void testMaxKeyspaceRFOnlyFailAboveAlter() throws Throwable
    {
        guardrails().setMaximumReplicationFactorThreshold(DISABLED_GUARDRAIL, MAXIMUM_REPLICATION_FACTOR_FAIL_THRESHOLD);
        execute("CREATE KEYSPACE ks WITH replication = { 'class': 'NetworkTopologyStrategy', 'datacenter1': 3}");
        assertFails("ALTER KEYSPACE ks WITH replication = { 'class': 'NetworkTopologyStrategy', 'datacenter1': 6}", 6);
    }

    @Test
    public void testMaxKeyspaceRFWarnBelow() throws Throwable
    {
        guardrails().setMaximumReplicationFactorThreshold(MAXIMUM_REPLICATION_FACTOR_WARN_THRESHOLD, MAXIMUM_REPLICATION_FACTOR_FAIL_THRESHOLD);
        assertMaxThresholdValid("CREATE KEYSPACE ks WITH replication = { 'class': 'NetworkTopologyStrategy', 'datacenter1': 1}");
        assertMaxThresholdValid("ALTER KEYSPACE ks WITH replication = { 'class': 'NetworkTopologyStrategy', 'datacenter1': 2}");
    }

    @Test
    public void testMaxKeyspaceRFWarnFailBetween() throws Throwable
    {
        guardrails().setMaximumReplicationFactorThreshold(MAXIMUM_REPLICATION_FACTOR_WARN_THRESHOLD, MAXIMUM_REPLICATION_FACTOR_FAIL_THRESHOLD);
        assertWarns("CREATE KEYSPACE ks WITH replication = { 'class': 'NetworkTopologyStrategy', 'datacenter1': 3}", 3);
        assertWarns("ALTER KEYSPACE ks WITH replication = { 'class': 'NetworkTopologyStrategy', 'datacenter1': 4}", 4);
    }

    @Test
    public void testMaxKeyspaceRFFailAbove() throws Throwable
    {
        guardrails().setMaximumReplicationFactorThreshold(MAXIMUM_REPLICATION_FACTOR_WARN_THRESHOLD, MAXIMUM_REPLICATION_FACTOR_FAIL_THRESHOLD);
        assertFails("CREATE KEYSPACE ks WITH replication = { 'class': 'NetworkTopologyStrategy', 'datacenter1': 5}", 5);
    }

    @Test
    public void testMaxKeyspaceRFFailAboveAlter() throws Throwable
    {
        guardrails().setMaximumReplicationFactorThreshold(MAXIMUM_REPLICATION_FACTOR_WARN_THRESHOLD, MAXIMUM_REPLICATION_FACTOR_FAIL_THRESHOLD);
        execute("CREATE KEYSPACE ks WITH replication = { 'class': 'NetworkTopologyStrategy', 'datacenter1': 4}");
        assertFails("ALTER KEYSPACE ks WITH replication = { 'class': 'NetworkTopologyStrategy', 'datacenter1': 5}", 5);
    }

    @Test
    public void testMaxRFLesserThanDefaultRF()
    {
        DatabaseDescriptor.setDefaultKeyspaceRF(3);
        Assertions.assertThatThrownBy(() -> guardrails().setMaximumReplicationFactorThreshold(1, 2))
                  .isInstanceOf(IllegalArgumentException.class)
                  .hasMessageContaining("maximum_replication_factor_fail_threshold to be set (2) cannot be lesser than default_keyspace_rf (3)");

        DatabaseDescriptor.setDefaultKeyspaceRF(1);
        guardrails().setMaximumReplicationFactorThreshold(1, 2);
        Assertions.assertThatThrownBy(() -> DatabaseDescriptor.setDefaultKeyspaceRF(3))
                  .isInstanceOf(IllegalArgumentException.class)
                  .hasMessageContaining("default_keyspace_rf to be set (3) cannot be greater than maximum_replication_factor_fail_threshold (2)");
    }

    private void assertWarns(String query, int rf) throws Throwable
    {
        assertWarns(query, format("The keyspace ks has a replication factor of %d, above the warning threshold of %s.",
                                  rf, MAXIMUM_REPLICATION_FACTOR_WARN_THRESHOLD));
    }

    private void assertFails(String query, int rf) throws Throwable
    {
        assertFails(query, format("The keyspace ks has a replication factor of %d, above the failure threshold of %s.",
                                  rf, MAXIMUM_REPLICATION_FACTOR_FAIL_THRESHOLD));
    }
}


text:
#ifndef HEADER_CURL_TOOL_LIBINFO_H
#define HEADER_CURL_TOOL_LIBINFO_H

#include "tool_setup.h"

/* global variable declarations, for libcurl run-time info */

extern curl_version_info_data *curlinfo;
extern long built_in_protos;

CURLcode get_libcurl_info(void);

#endif /* HEADER_CURL_TOOL_LIBINFO_H */


text:
#include <gtest/gtest.h>
#include <boost/test/floating_point_comparison.hpp>
#include <Core/Math/MiscMath.h>

using namespace SCIRun;

TEST(FloatComparisonTest, BoostCheck)
{
  namespace btt = boost::test_tools;
  //namespace btt = boost::math::fpc;
  btt::close_at_tolerance<double> comp(btt::percent_tolerance(1e-5));
  EXPECT_TRUE(comp(1, 1));
  EXPECT_FALSE(comp(1.0/3, 0.33333));
  EXPECT_TRUE(comp(1.0/3, 0.333333333));
}

TEST(InfinityTests, IsFiniteTest)
{
  EXPECT_FALSE(IsFinite(std::numeric_limits<double>::infinity()));
  EXPECT_FALSE(IsFinite(-std::numeric_limits<double>::infinity()));
  EXPECT_FALSE(IsFinite(std::numeric_limits<double>::quiet_NaN()));
  EXPECT_FALSE(IsFinite(std::numeric_limits<double>::signaling_NaN()));
  EXPECT_TRUE(IsFinite(0.3));
}

TEST(InfinityTests, IsInfiniteTest)
{
  EXPECT_TRUE(IsInfinite(std::numeric_limits<double>::infinity()));
  EXPECT_TRUE(IsInfinite(-std::numeric_limits<double>::infinity()));
  EXPECT_FALSE(IsInfinite(std::numeric_limits<double>::quiet_NaN()));
  EXPECT_FALSE(IsInfinite(std::numeric_limits<double>::signaling_NaN()));
  EXPECT_FALSE(IsInfinite(0.3));
}

TEST(NanTests, IsNanTest)
{
  EXPECT_FALSE(IsNan(std::numeric_limits<double>::infinity()));
  EXPECT_FALSE(IsNan(-std::numeric_limits<double>::infinity()));
  EXPECT_TRUE(IsNan(std::numeric_limits<double>::quiet_NaN()));
  EXPECT_TRUE(IsNan(std::numeric_limits<double>::signaling_NaN()));
  EXPECT_FALSE(IsNan(0.3));
}


text:
using StoryTeller.DataModel.Model;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Documents;

namespace StoryTeller.ViewModel
{
    public delegate void SceneNavigateRequest(object sender, IScene scene);
    public delegate void ScenePickerRequest(object sender, ScenePickerRequestArgs args);
    public delegate void SceneBonusChanged();
    public delegate void SceneTagsChanged(SceneViewModel sender);

    public class SceneViewModel : ISceneContentHolder, INotifyPropertyChanged
    {
        public event SceneNavigateRequest NavigateRequest;
        public event ScenePickerRequest PickSceneRequest;
        public event SceneBonusChanged BonusSceneChanged;
        public event SceneTagsChanged SceneTagsChanged;
        private ObservableCollection<SceneTag> _tags;

        public IScene CurrentScene { get; set; }

        public bool HasImage
        {
            get
            {
                bool result = false;
                if (null != CurrentScene)
                {
                    RichTextBlock richBlock = new StoryTeller.Converter.StringToRtf().Convert(CurrentScene.Content.Content, null, null, null) as RichTextBlock;
                    if (null != richBlock)
                    {
                        foreach (Block block in richBlock.Blocks)
                        {
                            Paragraph p = block as Paragraph;
                            if (null != p)
                            {
                                foreach (Inline inline in p.Inlines)
                                {
                                    if (ImageInline.IsImageInline(inline))
                                    {
                                        result = true;
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }

                return result;
            }
        }

        public bool HasText
        {
            get
            {
                bool result = false;
                if (null != CurrentScene)
                {
                    RichTextBlock richBlock = new StoryTeller.Converter.StringToRtf().Convert(CurrentScene.Content.Content, null, null, null) as RichTextBlock;
                    if (null != richBlock)
                    {
                        foreach (Block block in richBlock.Blocks)
                        {
                            Paragraph p = block as Paragraph;
                            if (null != p)
                            {
                                foreach (Inline inline in p.Inlines)
                                {
                                    Run run;
                                    if (ImageInline.IsImageInline(inline))
                                    {
                                        continue;
                                    }
                                    else if (null != (run = inline as Run))
                                    {
                                        if (!string.IsNullOrWhiteSpace(run.Text))
                                        {
                                            result = true;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                return result;
            }
        }

        public ObservableCollection<SceneTag> Tags
        {
            get
            {
                return _tags;
            }
            set
            {
                _tags = value;
            }
        }

        public bool IsBonus
        {
            get
            {
                return CurrentScene.IsBonusScene;
            }
            set
            {
                CurrentScene.IsBonusScene = value;
                BonusSceneChanged();
            }
        }

        private void NotifyBonusScenesChanged()
        {

        }

        public SceneViewModel(IScene currentScene)
        {
            this.CurrentScene = currentScene;
            _tags = null;
            if (null != currentScene)
            {
                _tags = new ObservableCollection<SceneTag>(currentScene.Tags);
            }
            else
            {
                _tags = new ObservableCollection<SceneTag>();
            }

            _tags.CollectionChanged += _tags_CollectionChanged;
        }

        void _tags_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
            {
                foreach (SceneTag newTag in e.NewItems)
                {
                    CurrentScene.Tags.Add(newTag);
                }
                //SceneTagsChanged(this);
            }
        }

        public void LinkClicked(string linkId)
        {
            InteractiveScene interactiveScene = CurrentScene as InteractiveScene;
            if (null != interactiveScene)
            {
                IScene linkedScene = interactiveScene.LookupSceneByLinkId(linkId);
                if (null != linkedScene)
                {
                    OnNavigateRequest(linkedScene);
                }
                else if (interactiveScene.Type == SceneType.Interactive && interactiveScene.PossibleScenes.Count > 0)
                {
                    OnPickSceneRequest(linkId);
                }
            }
        }

        private void OnPickSceneRequest(string linkId)
        {
            if (null != PickSceneRequest)
            {
                ScenePickerRequestArgs args = new ScenePickerRequestArgs();
                args.LinkId = linkId;
                args.SenderChain.Add(this);
                PickSceneRequest(this, args);
            }
        }

        private void OnNavigateRequest(IScene scene)
        {
            if (null != NavigateRequest)
            {
                NavigateRequest(this, scene);
            }
        }

        internal void CreateLinkAt(Windows.UI.Xaml.Documents.TextPointer start, Windows.UI.Xaml.Documents.TextPointer end)
        {
            throw new NotImplementedException();
        }

        IList<SceneTag> ISceneContentHolder.Tags
        {
            get { return _tags; }
        }

        public SceneContentType Type
        {
            get
            {
                return CurrentScene.Content.Type;
            }
            set
            {
                CurrentScene.Content.Type = value;
            }
        }

        public string Content
        {
            get
            {
                return CurrentScene.Content.Content;
            }
            set
            {
                CurrentScene.Content.Content = value;
                OnPropertyChanged("Content");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged(string propertyChanged)
        {
            if (null != PropertyChanged)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyChanged));
            }
        }
    }
}


text:
"""Test the transfer pulse sequence task.

"""
import os
from time import sleep
from collections import OrderedDict

import enaml
import pytest
from enaml.widgets.api import Window
from exopy.tasks.api import RootTask
from exopy.tasks.tasks.instr_task import (PROFILE_DEPENDENCY_ID,
                                          DRIVER_DEPENDENCY_ID)
from exopy.testing.util import handle_dialog, show_widget, handle_question

with enaml.imports():
    from exopy.instruments.manifest import InstrumentManagerManifest
    from exopy.tasks.manifest import TasksManagerManifest
    from exopy.tasks.tasks.base_views import RootTaskView

from exopy_pulses.pulses.pulse import Pulse
from exopy_pulses.pulses.utils.sequences_io import save_sequence_prefs
from exopy_pulses.pulses.sequences.base_sequences\
    import RootSequence
from exopy_pulses.testing.context import DummyContext
from exopy_pulses.tasks.tasks.instrs.transfer_sequence_task\
    import TransferPulseSequenceTask
with enaml.imports():
    from exopy_pulses.tasks.tasks.instrs.views.transfer_sequence_task_view\
         import (TransferPulseSequenceView, validate_context_driver_pair,
                 load_sequence)
    from exopy_pulses.tasks.manifest import PulsesTasksManifest

with enaml.imports():
    from .contributions import PulsesContributions

p_id = PROFILE_DEPENDENCY_ID
d_id = DRIVER_DEPENDENCY_ID

class FalseStarter(object):
    """False instrument starter used for testing.

    """
    finalize_called = False

    def __init__(self, should_pass=True):
        self.should_pass = should_pass

    def check_infos(self, driver_cls, connection, settings):
        return self.should_pass, 'Message'

    def start(self, driver_cls, connection, settings):
        return object()

    def stop(self, driver):
        FalseStarter.stop_called = True

@pytest.fixture
def workbench(pulses_workbench):
    """Simply register the contributions for testing.

    """
    pulses_workbench.register(PulsesContributions())
    return pulses_workbench

def sequence():
    """Create a sequence.

    """
    root = RootSequence()
    context = DummyContext(sampling=0.5)
    root.context = context

    root.external_vars = OrderedDict({'a': None})
    root.local_vars = OrderedDict({'b': '2*{a}'})

    pulse1 = Pulse(def_1='1.0', def_2='{a}', def_mode=str('Start/Stop'))
    pulse2 = Pulse(def_1='{a} + 1.0', def_2='3.0')
    pulse3 = Pulse(def_1='{2_stop} + 0.5', def_2='10 + {b}')
    for i, c in enumerate((pulse1, pulse2, pulse3)):
        root.add_child_item(i, c)

    return root

@pytest.fixture
def task(tmpdir):
    """Transfer sequence task for testing.

    """
    root = RootTask()
    root.run_time = {d_id: {'d': (object, FalseStarter())},
                     p_id: {'p': {'connections': {'c': {}, 'c2': {}},
                                  'settings': {'s': {}}}}}
    path = os.path.join(str(tmpdir), 'test.pulse.ini')
    seq = sequence()
    save_sequence_prefs(path, seq.preferences_from_members())
    task = TransferPulseSequenceTask(sequence=seq, sequence_path=path,
                                     sequence_timestamp=os.path.getmtime(path),
                                     sequence_vars=OrderedDict({'a': '1.5'}),
                                     name='Test',
                                     selected_instrument=('p', 'd', 'c', 's'))
    root.add_child_task(0, task)
    return task

@pytest.fixture
def task_view(task, workbench):
    """Transfer sequence task view for testing.

    """
    workbench.register(TasksManagerManifest())
    core = workbench.get_plugin('enaml.workbench.core')
    cmd = 'exopy.pulses.get_context_infos'
    c_infos = core.invoke_command(
            cmd,  dict(context_id='exopy_pulses.DummyContext'))
    c_infos.instruments = set(['exopy_pulses.TestDriver'])
    task.selected_instrument = ('p', 'exopy_pulses.TestDriver', 'c', 's')
    root_view = RootTaskView(task=task.root, core=core)
    view = TransferPulseSequenceView(task=task, root=root_view)
    return view

def test_task_traversal(task):
    """Test that the task does yield the sequence.

    """
    components = list(task.traverse())
    assert task.sequence in components

    task.sequence = None
    components = list(task.traverse())
    assert None not in components

def test_dependencies_analysis(workbench, task):
    """Test analysing dependencies.

    We must ensure that instruments are there as this task does not rely on the
    common mechanism.

    """
    workbench.register(PulsesTasksManifest())
    workbench.register(TasksManagerManifest())
    workbench.register(InstrumentManagerManifest())
    core = workbench.get_plugin('enaml.workbench.core')
    build, runtime = core.invoke_command('exopy.app.dependencies.analyse',
                                         dict(obj=task,
                                              dependencies=['build',
                                                            'runtime']))
    print(runtime.errors)
    assert not build.errors and not runtime.errors
    assert len(runtime.dependencies) == 2

def test_task_saving_building(workbench, task):
    """Test saving and rebuilbing the sequence.

    """
    workbench.register(PulsesTasksManifest())
    workbench.register(TasksManagerManifest())
    core = workbench.get_plugin('enaml.workbench.core')
    deps = core.invoke_command('exopy.app.dependencies.analyse',
                               dict(obj=task, dependencies=['build']))
    deps = core.invoke_command('exopy.app.dependencies.collect',
                               dict(dependencies=deps.dependencies,
                                    kind='build'))

    task.update_preferences_from_members()
    prefs = task.preferences
    task2 = TransferPulseSequenceTask.build_from_config(prefs,
                                                        deps.dependencies)

    assert task2.sequence
    assert task2.sequence.context
    assert task2.sequence.items

    # Try to build a task missing a sequence.
    del task.sequence
    task.update_preferences_from_members()
    prefs = task.preferences
    del deps.dependencies['exopy.pulses.item']
    task3 = TransferPulseSequenceTask.build_from_config(prefs,
                                                        deps.dependencies)

    assert not task3.sequence

def test_update_of_task_database_entries(task):
    """Test that changing of context does trigger the expected update.

    """
    class FancyContext(DummyContext):
        def list_sequence_infos(self):
            return {'dummy': True}

    task.sequence.context = FancyContext()
    assert task.database_entries == {'instrument': '', 'dummy': True}

    task.sequence = sequence()
    assert task.database_entries == {'instrument': '', 'test': False}

    task.sequence.context = FancyContext()
    assert task.database_entries == {'instrument': '', 'dummy': True}

def test_task_check1(task):
    """Test that if there is not problem tests pass.

    """
    res, traceback = task.check()
    print(traceback)
    assert res
    assert not traceback

def test_task_check2(task):
    """Test handling errors in variable evaluation.

    """
    task.sequence_vars = OrderedDict({'a': '+*'})
    res, traceback = task.check()
    assert not res
    assert 'root/Test-a' in traceback

def test_task_check3(task):
    """Test handling an evaluation error.

    """
    task.sequence.local_vars = OrderedDict()
    res, traceback = task.check()
    assert not res
    assert 'root/Test-compil' in traceback

def test_task_check4(task, monkeypatch):
    """Test handling a compilation error.

    """
    def fail_compil(*args, **kwargs):
        return False, {}, {'test': ''}
    monkeypatch.setattr(DummyContext, 'compile_and_transfer_sequence',
                        fail_compil)
    res, traceback = task.check()
    assert not res
    assert 'root/Test-compil' in traceback
    assert 'test' in traceback['root/Test-compil']

def test_task_check5(task):
    """Test that we get a warning on outdated sequence.

    """
    task.sequence_timestamp = -1
    res, traceback = task.check()
    assert res
    assert 'root/Test-outdated' in traceback

def test_task_check6(task):
    """Test handling an absence of sequence.

    """
    task.sequence = None
    res, traceback = task.check()
    assert not res
    assert 'root/Test-sequence' in traceback

def test_task_perform1(task):
    """Test performing the task when everything goes right.

    """
    assert task.get_from_database('Test_test') is False
    task.perform()
    assert task.get_from_database('Test_test')

def test_task_perform2(task):
    """Test handling error in sequence evaluation.

    """
    task.sequence.local_vars = OrderedDict()
    with pytest.raises(Exception):
        task.perform()

def test_task_perform3(task, monkeypatch):
    """Test handling error in sequence compilation and transfer.

    """
    def fail_compil(*args, **kwargs):
        return False, {}, {'test': ''}
    monkeypatch.setattr(DummyContext, 'compile_and_transfer_sequence',
                        fail_compil)
    with pytest.raises(Exception):
        task.perform()

def test_view_validate_driver_context(exopy_qtbot, task_view):
    """Test the validation of a context/driver pair.

    """
    task_view.task.selected_instrument = ('p', 'exopy_pulses.TestDriver',
                                          'c', 's')

    validate_context_driver_pair(task_view.root.core,
                                 task_view.task.sequence.context,
                                 task_view.task, task_view)

    assert not Window.windows
    assert task_view.task.selected_instrument[0]

    task_view.task.selected_instrument = ('p', '__dummy__',
                                          'c', 's')
    with handle_dialog(exopy_qtbot, 'accept'):
        validate_context_driver_pair(task_view.root.core,
                                     task_view.task.sequence.context,
                                     task_view.task, task_view)

    assert not task_view.task.selected_instrument[0]

def test_load_refresh_save(task_view, monkeypatch, exopy_qtbot, dialog_sleep):
    """Test loading a sequence, refreshing, modifying and saving.

    """
    from enaml.widgets.api import FileDialogEx

    @classmethod
    def get_filename(cls, parent, current_path, name_filters):
        return task_view.task.sequence_path
    monkeypatch.setattr(FileDialogEx, 'get_open_file_name', get_filename)

    task_view.task.sequence_timestamp = -1

    show_widget(exopy_qtbot, task_view)
    # Check detection of outdated sequence
    assert task_view.widgets()[4].style_class

    old_seq = task_view.task.sequence
    task_view.task.sequence_vars = OrderedDict([('a', '1*23'), ('c', '1')])
    # Load
    task_view.widgets()[2].clicked = True

    def assert_exec():
        assert task_view.task.sequence is not old_seq
        assert task_view.task.sequence_vars == OrderedDict({'a': '1*23'})
        assert not task_view.widgets()[4].style_class
    exopy_qtbot.wait_until(assert_exec)

    old_seq = task_view.task.sequence
    task_view.task.sequence_vars = OrderedDict()
    # Refresh
    with handle_question(exopy_qtbot, 'no'):
        task_view.widgets()[4].clicked = True
    assert task_view.task.sequence is old_seq
    with handle_question(exopy_qtbot, 'yes'):
        task_view.widgets()[4].clicked = True
    assert task_view.task.sequence is not old_seq
    assert task_view.task.sequence_vars == OrderedDict({'a': ''})

    old_timestamp = task_view.task.sequence_timestamp
    # Save
    btn = task_view.widgets()[5]
    actions = btn.menu().items()
    with handle_question(exopy_qtbot, 'no'):
        btn.clicked = True
        actions[0].triggered = True
    assert task_view.task.sequence_timestamp == old_timestamp
    with handle_question(exopy_qtbot, 'yes'):
        btn.clicked = True
        actions[0].triggered = True
    sleep(0.1)
    assert task_view.task.sequence_timestamp != old_timestamp

    @classmethod
    def get_save_filename1(cls, parent, current_path, name_filters):
        return ''

    new_path = task_view.task.sequence_path.rstrip('.pulse.ini')
    new_path += '2'

    @classmethod
    def get_save_filename2(cls, parent, current_path, name_filters):
        return new_path

    old_timestamp = task_view.task.sequence_timestamp
    # Save as
    monkeypatch.setattr(FileDialogEx, 'get_save_file_name', get_save_filename1)
    btn.clicked = True
    actions[1].triggered = True
    assert task_view.task.sequence_timestamp == old_timestamp

    monkeypatch.setattr(FileDialogEx, 'get_save_file_name', get_save_filename2)
    btn.clicked = True
    actions[1].triggered = True
    assert task_view.task.sequence_timestamp != old_timestamp
    assert task_view.task.sequence_path == new_path + '.pulse.ini'

def test_load_refresh_save2(task_view, monkeypatch, exopy_qtbot):
    """Test loading a sequence, refreshing, modifying and saving.

    Test handling the case of an empty sequence_path

    """
    from enaml.widgets.api import FileDialogEx

    @classmethod
    def get_filename(cls, parent, current_path, name_filters):
        return task_view.task.sequence_path
    monkeypatch.setattr(FileDialogEx, 'get_open_file_name', get_filename)

    task_view.task.sequence_path = ''

    show_widget(exopy_qtbot, task_view)

    task_view.task.sequence_vars = OrderedDict()
    # Refresh
    button = task_view.widgets()[4]
    assert not button.enabled

    def false_load(*args, **kwargs):
        raise Exception()

    with enaml.imports():
        from exopy_pulses.tasks.tasks.instrs.views\
            import transfer_sequence_task_view
    old = transfer_sequence_task_view.load_sequence
    monkeypatch.setattr(transfer_sequence_task_view, 'load_sequence',
                        false_load)
    with handle_question(exopy_qtbot, 'OK'):
        button.clicked = True

    monkeypatch.setattr(transfer_sequence_task_view, 'load_sequence', old)

    # Save
    btn = task_view.widgets()[5]
    actions = btn.menu().items()
    assert not actions[0].enabled

def test_handling_error_in_loading(task_view, exopy_qtbot, monkeypatch):
    """Test handling an error when re-building the sequence.

    """
    from enaml.workbench.core.core_plugin import CorePlugin
    old = CorePlugin.invoke_command

    def false_invoke(self, cmd, *args, **kwargs):
        if cmd == 'exopy.pulses.build_sequence':
            raise Exception()
        else:
            old(self, cmd, *args, **kwargs)

    monkeypatch.setattr(CorePlugin, 'invoke_command', false_invoke)

    with handle_dialog(exopy_qtbot, 'accept'):
        load_sequence(task_view.root.core, task_view.task, task_view,
                      task_view.task.sequence_path)

@pytest.mark.timeout(10)
def test_changing_context_sequence(task_view, exopy_qtbot):
    """Test changing the context of a sequence.

    This should trigger a new validation of the driver.

    """
    show_widget(exopy_qtbot, task_view)
    task = task_view.task
    task.selected_instrument = ('p', 'exopy_pulses.TestDriver', 'c', 's')

    task.sequence.context = None
    assert task.selected_instrument[0]

    task.selected_instrument = ('p', '__dummy__',  'c', 's')
    with handle_question(exopy_qtbot, 'yes'):
        task.sequence.context = DummyContext()
    assert not task.selected_instrument[0]

    # Test changing the sequence.
    task.selected_instrument = ('p', '__dummy__',  'c', 's')
    with handle_question(exopy_qtbot, 'yes'):
        task.sequence = sequence()
    assert not task.selected_instrument[0]

    # Check  the observer has been installed on the new sequence.
    task.selected_instrument = ('p', 'exopy_pulses.TestDriver', 'c', 's')

    task.sequence.context = None
    assert task.selected_instrument[0]

    task.selected_instrument = ('p', '__dummy__',  'c', 's')
    with handle_question(exopy_qtbot, 'yes'):
        task.sequence.context = DummyContext()
    assert not task.selected_instrument[0]

def test_profile_filtering(task_view):
    """Test filtering the valid profiles based on context specifications.

    """
    from atom.api import Atom, Value

    class DInfos(Atom):
        id = Value()

    class MInfos(Atom):
        drivers = Value()

    class PInfos(Atom):
        model = Value()

    p1 = PInfos(model=MInfos(drivers=[DInfos(id='__dummy__'),
                                      DInfos(id='exopy_pulses.TestDriver')]))
    p2 = PInfos(model=MInfos(drivers=[DInfos(id='dummy2')]))

    assert task_view.filter_profiles({'p1': p1, 'p2': p2}) == ['p1']

    del task_view.task.sequence.context

    assert (sorted(task_view.filter_profiles({'p1': p1, 'p2': p2})) ==
            ['p1', 'p2'])

def test_drivers_filtering(task_view):
    """Test filtering the valid drivers based on context specifications.

    """
    from atom.api import Atom, Value

    class DInfos(Atom):
        id = Value()

    d = DInfos(id='exopy_pulses.TestDriver')

    drivers = task_view.filter_drivers([DInfos(id='__dummy__'), d])
    assert drivers == [d]

    del task_view.task.sequence.context

    assert len(task_view.filter_drivers([DInfos(id='__dummy__'), d])) == 2


text:
package com.google.cloud.bigtable.hbase;

import static com.google.cloud.bigtable.hbase.IntegrationTests.*;

import org.apache.commons.lang.ArrayUtils;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.client.Append;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.util.Bytes;
import org.junit.Assert;
import org.junit.Test;

import java.util.List;

public class TestAppend extends AbstractTest {
  /**
   * Requirement 5.1 - Append values to one or more columns within a single row.
   */
  @Test
  public void testAppend() throws Exception {
    // Initialize
    Table table = getConnection().getTable(TABLE_NAME);
    byte[] rowKey = dataHelper.randomData("rowKey-");
    byte[] qualifier = dataHelper.randomData("qualifier-");
    byte[] value1 = dataHelper.randomData("value1-");
    byte[] value2 = dataHelper.randomData("value1-");
    byte[] value1And2 = ArrayUtils.addAll(value1, value2);

    // Put then append
    Put put = new Put(rowKey).addColumn(COLUMN_FAMILY, qualifier, value1);
    table.put(put);
    Append append = new Append(rowKey).add(COLUMN_FAMILY, qualifier, value2);
    Result result = table.append(append);
    Cell cell = result.getColumnLatestCell(COLUMN_FAMILY, qualifier);
    Assert.assertArrayEquals("Expect concatenated byte array", value1And2,
      CellUtil.cloneValue(cell));

    // Test result
    Get get = new Get(rowKey).addColumn(COLUMN_FAMILY, qualifier);
    get.setMaxVersions(5);
    result = table.get(get);
    Assert.assertEquals("There should be two versions now", 2, result.size());
    List<Cell> cells = result.getColumnCells(COLUMN_FAMILY, qualifier);
    Assert.assertArrayEquals("Expect concatenated byte array", value1And2,
      CellUtil.cloneValue(cells.get(0)));
    Assert.assertArrayEquals("Expect original value still there", value1,
      CellUtil.cloneValue(cells.get(1)));
  }

  @Test
  public void testAppendToEmptyCell() throws Exception {
    // Initialize
    Table table = getConnection().getTable(TABLE_NAME);
    byte[] rowKey = dataHelper.randomData("rowKey-");
    byte[] qualifier = dataHelper.randomData("qualifier-");
    byte[] value = dataHelper.randomData("value1-");

    // Put then append
    Append append = new Append(rowKey).add(COLUMN_FAMILY, qualifier, value);
    table.append(append);

    // Test result
    Get get = new Get(rowKey).addColumn(COLUMN_FAMILY, qualifier);
    get.setMaxVersions(5);
    Result result = table.get(get);
    Assert.assertEquals("There should be one version now", 1, result.size());
    Cell cell = result.getColumnLatestCell(COLUMN_FAMILY, qualifier);
    Assert.assertArrayEquals("Expect append value is entire value", value, CellUtil.cloneValue(cell));
  }

  @Test
  public void testAppendNoResult() throws Exception {
    // Initialize
    Table table = getConnection().getTable(TABLE_NAME);
    byte[] rowKey = dataHelper.randomData("rowKey-");
    byte[] qual = dataHelper.randomData("qualifier-");
    byte[] value1 = dataHelper.randomData("value-");
    byte[] value2 = dataHelper.randomData("value-");

    // Put then append
    Put put = new Put(rowKey).addColumn(COLUMN_FAMILY, qual, value1);
    table.put(put);
    Append append = new Append(rowKey).add(COLUMN_FAMILY, qual, value2);
    append.setReturnResults(false);
    Result result = table.append(append);
    Assert.assertNull("Should not return result", result);
  }

  @Test
  public void testAppendToMultipleColumns() throws Exception {
    // Initialize
    Table table = getConnection().getTable(TABLE_NAME);
    byte[] rowKey = dataHelper.randomData("rowKey-");
    byte[] qualifier1 = dataHelper.randomData("qualifier1-");
    byte[] qualifier2 = dataHelper.randomData("qualifier2-");
    byte[] value1 = dataHelper.randomData("value1-");
    byte[] value2 = dataHelper.randomData("value2-");

    // Put then append
    Append append =
        new Append(rowKey)
            .add(COLUMN_FAMILY, qualifier1, value1)
            .add(COLUMN_FAMILY, qualifier2, value2);
    table.append(append);

    // Test result
    Get get = new Get(rowKey).addFamily(COLUMN_FAMILY);
    get.setMaxVersions(5);
    Result result = table.get(get);
    Assert.assertEquals("There should be two cells", 2, result.size());
    Cell cell1 = result.getColumnLatestCell(COLUMN_FAMILY, qualifier1);
    Assert.assertEquals(
        Bytes.toString(value1),
        Bytes.toString(CellUtil.cloneValue(cell1)));
    Cell cell2 = result.getColumnLatestCell(COLUMN_FAMILY, qualifier2);
    Assert.assertEquals(
        Bytes.toString(value2),
        Bytes.toString(CellUtil.cloneValue(cell2)));
  }

  @Test
  public void testAppendToMultipleFamilies() throws Exception {
    // Initialize
    Table table = getConnection().getTable(TABLE_NAME);
    byte[] rowKey = dataHelper.randomData("rowKey-");
    byte[] qualifier1 = dataHelper.randomData("qualifier1-");
    byte[] value1 = dataHelper.randomData("value1-");
    byte[] value2 = dataHelper.randomData("value2-");

    // Put then append
    Append append =
        new Append(rowKey)
            .add(COLUMN_FAMILY, qualifier1, value1)
            .add(COLUMN_FAMILY2, qualifier1, value2);
    table.append(append);

    // Test result
    Get get = new Get(rowKey)
        .addFamily(COLUMN_FAMILY)
        .addFamily(COLUMN_FAMILY2);
    get.setMaxVersions(5);
    Result result = table.get(get);
    Assert.assertEquals("There should be two cells", 2, result.size());
    Cell cell1 = result.getColumnLatestCell(COLUMN_FAMILY, qualifier1);
    Assert.assertNotNull(cell1);
    Assert.assertEquals(
        Bytes.toString(value1),
        Bytes.toString(CellUtil.cloneValue(cell1)));
    Cell cell2 = result.getColumnLatestCell(COLUMN_FAMILY2, qualifier1);
    Assert.assertNotNull(cell2);
    Assert.assertEquals(
        Bytes.toString(value2),
        Bytes.toString(CellUtil.cloneValue(cell2)));
  }

  @Test
  public void testAppendMultiFamilyEmptyQualifier() throws Exception {
    // Initialize
    Table table = getConnection().getTable(TABLE_NAME);
    byte[] rowKey = dataHelper.randomData("rowKey-");
    byte[] qualifier1 = new byte[0];
    byte[] value1 = dataHelper.randomData("value1-");
    byte[] value2 = dataHelper.randomData("value2-");

    // Put then append
    Append append =
        new Append(rowKey)
            .add(COLUMN_FAMILY, qualifier1, value1)
            .add(COLUMN_FAMILY2, qualifier1, value2);
    table.append(append);

    // Test result
    Get get = new Get(rowKey).addFamily(COLUMN_FAMILY).addFamily(COLUMN_FAMILY2);
    get.setMaxVersions(5);
    Result result = table.get(get);
    Assert.assertEquals("There should be two cells", 2, result.size());
    Cell cell1 = result.getColumnLatestCell(COLUMN_FAMILY, qualifier1);
    Assert.assertEquals(
        Bytes.toString(value1),
        Bytes.toString(CellUtil.cloneValue(cell1)));
    Cell cell2 = result.getColumnLatestCell(COLUMN_FAMILY2, qualifier1);
    Assert.assertEquals(
        Bytes.toString(value2),
        Bytes.toString(CellUtil.cloneValue(cell2)));
  }
}


text: AlgoliaSearch = Npm.require('algoliasearch');


text:
package containerserver

import (
	"database/sql"
	"fmt"
	"strings"
)

const (
	policyStatTableScript = `
		CREATE TABLE policy_stat (
			storage_policy_index INTEGER PRIMARY KEY,
			object_count INTEGER DEFAULT 0,
			bytes_used INTEGER DEFAULT 0
		);`

	policyStatTriggerScript = `
		CREATE TRIGGER object_insert_policy_stat AFTER INSERT ON object
		BEGIN
			UPDATE policy_stat
			SET object_count = object_count + (1 - new.deleted),
				bytes_used = bytes_used + new.size
			WHERE storage_policy_index = new.storage_policy_index;
			INSERT INTO policy_stat (
				storage_policy_index, object_count, bytes_used)
			SELECT new.storage_policy_index,
				   (1 - new.deleted),
				   new.size
			WHERE NOT EXISTS(
				SELECT changes() as change
				FROM policy_stat
				WHERE change <> 0
			);
			UPDATE container_info
			SET hash = chexor(hash, new.name, new.created_at);
		END;
		CREATE TRIGGER object_delete_policy_stat AFTER DELETE ON object
		BEGIN
			UPDATE policy_stat
			SET object_count = object_count - (1 - old.deleted),
				bytes_used = bytes_used - old.size
			WHERE storage_policy_index = old.storage_policy_index;
			UPDATE container_info
			SET hash = chexor(hash, old.name, old.created_at);
		END;`

	containerInfoTableScript = `
		CREATE TABLE container_info (
			account TEXT,
			container TEXT,
			created_at TEXT,
			put_timestamp TEXT DEFAULT '0',
			delete_timestamp TEXT DEFAULT '0',
			reported_put_timestamp TEXT DEFAULT '0',
			reported_delete_timestamp TEXT DEFAULT '0',
			reported_object_count INTEGER DEFAULT 0,
			reported_bytes_used INTEGER DEFAULT 0,
			hash TEXT default '00000000000000000000000000000000',
			id TEXT,
			status TEXT DEFAULT '',
			status_changed_at TEXT DEFAULT '0',
			metadata TEXT DEFAULT '{}',
			x_container_sync_point1 INTEGER DEFAULT -1,
			x_container_sync_point2 INTEGER DEFAULT -1,
			storage_policy_index INTEGER DEFAULT 0,
			reconciler_sync_point INTEGER DEFAULT -1
		);`

	containerStatViewScript = `
		CREATE VIEW container_stat
		AS SELECT ci.account, ci.container, ci.created_at,
			ci.put_timestamp, ci.delete_timestamp,
			ci.reported_put_timestamp, ci.reported_delete_timestamp,
			ci.reported_object_count, ci.reported_bytes_used, ci.hash,
			ci.id, ci.status, ci.status_changed_at, ci.metadata,
			ci.x_container_sync_point1, ci.x_container_sync_point2,
			ci.reconciler_sync_point,
			ci.storage_policy_index,
			coalesce(ps.object_count, 0) AS object_count,
			coalesce(ps.bytes_used, 0) AS bytes_used
		FROM container_info ci LEFT JOIN policy_stat ps
		ON ci.storage_policy_index = ps.storage_policy_index;
		CREATE TRIGGER container_stat_update
		INSTEAD OF UPDATE ON container_stat
		BEGIN
			UPDATE container_info
			SET account = NEW.account,
				container = NEW.container,
				created_at = NEW.created_at,
				put_timestamp = NEW.put_timestamp,
				delete_timestamp = NEW.delete_timestamp,
				reported_put_timestamp = NEW.reported_put_timestamp,
				reported_delete_timestamp = NEW.reported_delete_timestamp,
				reported_object_count = NEW.reported_object_count,
				reported_bytes_used = NEW.reported_bytes_used,
				hash = NEW.hash,
				id = NEW.id,
				status = NEW.status,
				status_changed_at = NEW.status_changed_at,
				metadata = NEW.metadata,
				x_container_sync_point1 = NEW.x_container_sync_point1,
				x_container_sync_point2 = NEW.x_container_sync_point2,
				storage_policy_index = NEW.storage_policy_index,
				reconciler_sync_point = NEW.reconciler_sync_point;
		END;`

	objectTableScript = `
		CREATE TABLE object (
				ROWID INTEGER PRIMARY KEY AUTOINCREMENT,
				name TEXT,
				created_at TEXT,
				size INTEGER,
				content_type TEXT,
				etag TEXT,
				deleted INTEGER DEFAULT 0,
				storage_policy_index INTEGER DEFAULT 0
			);
		CREATE INDEX ix_object_deleted_name ON object (deleted, name);
		CREATE TRIGGER object_update BEFORE UPDATE ON object
			BEGIN
				SELECT RAISE(FAIL, 'UPDATE not allowed; DELETE and INSERT');
			END;`

	syncTableScript = `
		CREATE TABLE outgoing_sync (
				remote_id TEXT UNIQUE,
				sync_point INTEGER,
				updated_at TEXT DEFAULT 0
			);
		CREATE TABLE incoming_sync (
				remote_id TEXT UNIQUE,
				sync_point INTEGER,
				updated_at TEXT DEFAULT 0
			);
		CREATE TRIGGER outgoing_sync_insert AFTER INSERT ON outgoing_sync
			BEGIN
				UPDATE outgoing_sync
				SET updated_at = STRFTIME('%s', 'NOW')
				WHERE ROWID = new.ROWID;
			END;
		CREATE TRIGGER outgoing_sync_update AFTER UPDATE ON outgoing_sync
			BEGIN
				UPDATE outgoing_sync
				SET updated_at = STRFTIME('%s', 'NOW')
				WHERE ROWID = new.ROWID;
			END;
		CREATE TRIGGER incoming_sync_insert AFTER INSERT ON incoming_sync
			BEGIN
				UPDATE incoming_sync
				SET updated_at = STRFTIME('%s', 'NOW')
				WHERE ROWID = new.ROWID;
			END;
		CREATE TRIGGER incoming_sync_update AFTER UPDATE ON incoming_sync
			BEGIN
				UPDATE incoming_sync
				SET updated_at = STRFTIME('%s', 'NOW')
				WHERE ROWID = new.ROWID;
			END;`

	policyMigrateColumns = `account, container, created_at, put_timestamp, delete_timestamp, reported_put_timestamp,
		reported_object_count, reported_bytes_used, hash, id, status, status_changed_at, metadata,
		x_container_sync_point1, x_container_sync_point2`

	policyMigrateScript = policyStatTableScript +
		"INSERT INTO policy_stat (storage_policy_index, object_count, bytes_used) SELECT 0, object_count, bytes_used FROM container_stat;" +
		"ALTER TABLE object ADD COLUMN storage_policy_index INTEGER DEFAULT 0;" +
		"DROP TRIGGER object_insert;" +
		"DROP TRIGGER object_delete;" +
		policyStatTriggerScript +
		containerInfoTableScript +
		"INSERT INTO container_info (" + policyMigrateColumns + ") SELECT " + policyMigrateColumns + " FROM container_stat;" +
		"DROP TABLE IF EXISTS container_stat;" +
		containerStatViewScript

	syncPointMigrateScript = `
		ALTER TABLE container_stat ADD COLUMN x_container_sync_point1 INTEGER DEFAULT -1;
		ALTER TABLE container_stat ADD COLUMN x_container_sync_point2 INTEGER DEFAULT -1;`

	metadataMigrateScript = "ALTER TABLE container_stat ADD COLUMN metadata DEFAULT '{}';"

	pragmaScript = `
		PRAGMA synchronous = NORMAL;
		PRAGMA cache_size = -4096;
		PRAGMA temp_store = MEMORY;
		PRAGMA journal_mode = WAL;
		PRAGMA busy_timeout = 25000;`
)

func schemaMigrate(db *sql.DB) (bool, error) {
	hasDeletedNameIndex := false
	hasSyncPoints := false
	hasMetadata := false
	hasPolicyStat := false

	tx, err := db.Begin()
	if err != nil {
		return false, err
	}
	defer tx.Rollback()

	// We just pull the schema out of sqlite_master and look at it to get the current state of the database.
	rows, err := tx.Query("SELECT name, sql FROM sqlite_master WHERE name in ('policy_stat', 'ix_object_deleted_name', 'container_stat')")
	if err != nil {
		return false, err
	}
	for rows.Next() {
		var name, sql string
		if err := rows.Scan(&name, &sql); err != nil {
			return false, err
		}
		if name == "policy_stat" {
			hasPolicyStat = true
		} else if name == "ix_object_deleted_name" {
			hasDeletedNameIndex = true
		} else if name == "container_stat" {
			hasSyncPoints = strings.Contains(sql, "x_container_sync_point1")
			hasMetadata = strings.Contains(sql, "metadata")
		}
	}
	if err := rows.Err(); err != nil {
		return hasDeletedNameIndex, err
	}
	if err := rows.Close(); err != nil {
		return hasDeletedNameIndex, err
	}

	if hasSyncPoints && hasMetadata && hasPolicyStat {
		return hasDeletedNameIndex, nil
	}

	if !hasSyncPoints {
		if _, err := tx.Exec(syncPointMigrateScript); err != nil {
			return hasDeletedNameIndex, fmt.Errorf("Adding sync_point columns: %v", err)
		}
	}
	if !hasMetadata {
		if _, err := tx.Exec(metadataMigrateScript); err != nil {
			return hasDeletedNameIndex, fmt.Errorf("Adding metadata column: %v", err)
		}
	}
	if !hasPolicyStat {
		if _, err = tx.Exec(policyMigrateScript); err != nil {
			return hasDeletedNameIndex, fmt.Errorf("Performing policy migration: %v", err)
		}
	}
	return hasDeletedNameIndex, tx.Commit()
}


text:
A basic vimrc for teaching with some base plugins for python and go.

## Config Setup

To install the vimrc, from inside of this directory run: `cp vimrc ~/.vimrc`

## vim-plug

We are going to use [vim-plug](https://github.com/junegunn/vim-plug). Before anything, run the command below.

```
curl -fLo ~/.vim/autoload/plug.vim --create-dirs \
    https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim
```

To install plugins: `:PlugInstall`
To update plugins: `:PlugUpdate`
To update vim-plug: `:PlugUpgrade`

## Modes

There three main modes of vim. Normal, Insert and Visual are key.

* Normal is the base mode of things. You will run commands through normal mode.
    * to return to normal mode from insert or visual mode, press `esc`
* Insert is where you can insert characters into a file
    * To enter insert mode from vim, press `i`
* Visual/visual block is where you can select/modify multiple lines
    * To enter visual mode: press `v`

## Helpful commands

Every command is ran with `:` or the colon in normal mode.

1. quit: `q`
2. write: `w`
3. exit: `x`
4. force: `!` Ex (quit without saving): `:q!`
5. Search: `/`
6. Search and Replace: `%s/{regex}/{replacement}/{modifiers}`:W

## NERDTree
To open NERDTree: Press `\` then `tab`

When opening files, you have options: press `enter`

## Themes

[themes](http://vimcolors.com/)
`color {theme_name}`

[airline-themes](https://github.com/vim-airline/vim-airline/wiki/Screenshots)
`let g:airline_theme='colorline'`


text:
package hitGox

import (
	"encoding/json"
	"fmt"

	just "github.com/toby3d/hitGox/tools"
	f "github.com/valyala/fasthttp"
)

// UpdateChatSettings update chat settings for channel.
//
// Editors can modify this API, except the whisper setting.
func (account *Account) UpdateChatSettings(channel string, subImages, whisper bool) (*just.Status, error) {
	var changes = struct {
		UserID    string `json:"user_id"`
		SubImages bool   `json:"sub_images"`
		Whisper   bool   `json:"whisper"`
	}{account.UserID, subImages, whisper}

	dst, err := json.Marshal(&changes)
	if err != nil {
		return nil, err
	}

	var args f.Args
	args.Add("authToken", account.AuthToken)

	url := fmt.Sprintf(APIEndpoint, fmt.Sprint("chat/settings/", channel))
	resp, err := just.POST(dst, url, &args)
	if err != nil {
		return nil, err
	}

	return just.FixStatus(resp), nil
}


text:
import imageCompression from 'browser-image-compression';

console.log('imageCompression', imageCompression.version);


text:
# frozen_string_literal: true

# rubocop:disable Layout/LineLength

require File.expand_path('spec_helper', __dir__)

module Danger
  describe Danger::DangerXcodeSummary do
    it 'should be a plugin' do
      expect(Danger::DangerXcodeSummary.new(nil)).to be_a Danger::Plugin
    end

    describe 'with Dangerfile' do
      before do
        @dangerfile = testing_dangerfile
        @xcode_summary = @dangerfile.xcode_summary
        @xcode_summary.env.request_source.pr_json = JSON.parse(File.read('spec/fixtures/pr_json.json'))
        @xcode_summary.project_root = '/Users/marcelofabri/SwiftLint/'
      end

      it 'fail if file does not exist' do
        @xcode_summary.report('spec/fixtures/inexistent_file.xcresult')
        expect(@dangerfile.status_report[:errors]).to eq ['summary file not found']
      end

      context 'reporting' do
        it 'formats compile warnings' do
          @xcode_summary.report('spec/fixtures/swiftlint.xcresult')
          expect(@dangerfile.status_report[:warnings]).to eq [
            "**Carthage/Checkouts/Yams/Sources/Yams/Tag.swift#L88**: Legacy Hashing Violation: Prefer using the `hash(into:)` function instead of overriding `hashValue` (legacy_hashing)",
            "**Carthage/Checkouts/Yams/Sources/Yams/Tag.swift#L109**: Legacy Hashing Violation: Prefer using the `hash(into:)` function instead of overriding `hashValue` (legacy_hashing)",
            "**Carthage/Checkouts/Yams/Sources/Yams/Decoder.swift#L102**: Colon Violation: Colons should be next to the identifier when specifying a type and next to the key in dictionary literals. (colon)",
            "**Carthage/Checkouts/Yams/Sources/Yams/Node.swift#L191**: Legacy Hashing Violation: Prefer using the `hash(into:)` function instead of overriding `hashValue` (legacy_hashing)",
            "**Carthage/Checkouts/Yams/Sources/Yams/Representer.swift#L187**: Todo Violation: TODOs should be resolved (Support `Float80`). (todo)",
            "**Carthage/Checkouts/Yams/Sources/Yams/Encoder.swift#L139**: Colon Violation: Colons should be next to the identifier when specifying a type and next to the key in dictionary literals. (colon)",
            "**Carthage/Checkouts/Yams/Sources/Yams/Parser.swift#L441**: File Line Length Violation: File should contain 400 lines or less: currently contains 441 (file_length)",
            "**Carthage/Checkouts/Yams/Sources/Yams/Constructor.swift#L405**: Todo Violation: TODOs should be resolved (YAML supports keys other than ...). (todo)",
            "**Carthage/Checkouts/Yams/Sources/Yams/Constructor.swift#L430**: Todo Violation: TODOs should be resolved (Should raise error on other th...). (todo)",
            "**Carthage/Checkouts/Yams/Sources/Yams/Constructor.swift#L450**: Todo Violation: TODOs should be resolved (YAML supports Hashable element...). (todo)",
            "**Carthage/Checkouts/Yams/Sources/Yams/Constructor.swift#L478**: Todo Violation: TODOs should be resolved (Should raise error if subnode ...). (todo)",
            "**Carthage/Checkouts/Yams/Sources/Yams/Constructor.swift#L492**: Todo Violation: TODOs should be resolved (Should raise error if subnode ...). (todo)",
            "**Carthage/Checkouts/Yams/Sources/Yams/Emitter.swift#L340**: Todo Violation: TODOs should be resolved (Support tags). (todo)",
            "**Carthage/Checkouts/Yams/Tests/YamsTests/SpecTests.swift#L379**: Todo Violation: TODOs should be resolved (YAML supports keys other than ...). (todo)",
            "**Carthage/Checkouts/Yams/Tests/YamsTests/SpecTests.swift#L714**: Todo Violation: TODOs should be resolved (local tag parsing). (todo)",
            "**Carthage/Checkouts/Yams/Tests/YamsTests/EncoderTests.swift#L924**: Colon Violation: Colons should be next to the identifier when specifying a type and next to the key in dictionary literals. (colon)",
            "**Carthage/Checkouts/Yams/Tests/YamsTests/EncoderTests.swift#L937**: Colon Violation: Colons should be next to the identifier when specifying a type and next to the key in dictionary literals. (colon)",
            "**Carthage/Checkouts/Yams/Tests/YamsTests/EncoderTests.swift#L253**: Superfluous Disable Command Violation: 'unused_private_declaration' is not a valid SwiftLint rule. Please remove it from the disable command. (superfluous_disable_command)",
            "**Carthage/Checkouts/SWXMLHash/Source/XMLIndexer+XMLIndexerDeserializable.swift#L538**: 'public' modifier is redundant for instance method declared in a public extension",
            "**Carthage/Checkouts/SWXMLHash/Source/XMLIndexer+XMLIndexerDeserializable.swift#L552**: 'public' modifier is redundant for instance method declared in a public extension",
            "**Carthage/Checkouts/Result/Result/NoError.swift#L8**: Will never be executed"
          ]
        end

        it 'ignores file when ignored_files matches' do
          @xcode_summary.ignored_files = 'Carthage/**/Yams/**'
          @xcode_summary.report('spec/fixtures/swiftlint.xcresult')
          expect(@dangerfile.status_report[:warnings]).to eq [
            "**Carthage/Checkouts/SWXMLHash/Source/XMLIndexer+XMLIndexerDeserializable.swift#L538**: 'public' modifier is redundant for instance method declared in a public extension",
            "**Carthage/Checkouts/SWXMLHash/Source/XMLIndexer+XMLIndexerDeserializable.swift#L552**: 'public' modifier is redundant for instance method declared in a public extension",
            "**Carthage/Checkouts/Result/Result/NoError.swift#L8**: Will never be executed"
          ]
        end

        it 'ignores file when ignored_files is an array and matches' do
          @xcode_summary.ignored_files = ['Carthage/**/Yams/**', 'Carthage/**/SWXMLHash/**']
          @xcode_summary.report('spec/fixtures/swiftlint.xcresult')
          expect(@dangerfile.status_report[:warnings]).to eq [
            "**Carthage/Checkouts/Result/Result/NoError.swift#L8**: Will never be executed"
          ]
        end

        it 'formats test errors' do
          @xcode_summary.report('spec/fixtures/swiftlint.xcresult')
          expect(@dangerfile.status_report[:errors]).to eq [
            "**SwiftLintFrameworkTests.ColonRuleTests.testColonWithoutApplyToDictionaries()**: XCTAssertEqual failed: (\"0\") is not equal to (\"1\")
  Tests/SwiftLintFrameworkTests/TestHelpers.swift#L169"
          ]
        end

        it 'formats errors' do
          @xcode_summary.report('spec/fixtures/build_error.xcresult')
          expect(@dangerfile.status_report[:errors]).to eq [
            'Testing cancelled because the build failed.',
            "**Source/SwiftLintFramework/Extensions/QueuedPrint.swift#L13**: Use of unresolved identifier 'queue'",
            "**Source/SwiftLintFramework/Extensions/QueuedPrint.swift#L17**: Use of unresolved identifier 'queue'"
          ]
        end

        it 'report warning and error counts' do
          result = @xcode_summary.warning_error_count('spec/fixtures/build_error.xcresult')
          expect(result).to eq '{"warnings":21,"errors":3}'
        end

        context 'with inline_mode' do
          before do
            @xcode_summary.inline_mode = true
          end

          it 'asserts errors on the line' do
            allow(@xcode_summary).to receive(:fail)
            @xcode_summary.report('spec/fixtures/build_error.xcresult')
            expect(@xcode_summary).to have_received(:fail).with(
              instance_of(String),
              sticky: false,
              file: 'Source/SwiftLintFramework/Extensions/QueuedPrint.swift',
              line: 13
            )
            expect(@xcode_summary).to have_received(:fail).with(
              instance_of(String),
              sticky: false,
              file: 'Source/SwiftLintFramework/Extensions/QueuedPrint.swift',
              line: 17
            )
            expect(@xcode_summary).to have_received(:fail).with(
              'Testing cancelled because the build failed.',
              sticky: false
            )
          end

          it 'asserts warning on the line' do
            allow(@xcode_summary).to receive(:warn)
            @xcode_summary.report('spec/fixtures/swiftlint.xcresult')
            expect(@xcode_summary).to have_received(:warn).with(
              instance_of(String),
              sticky: false,
              file: 'Carthage/Checkouts/SWXMLHash/Source/XMLIndexer+XMLIndexerDeserializable.swift',
              line: 538
            )
          end
        end

        context 'with ignores_warnings' do
          before do
            @xcode_summary.ignores_warnings = true
          end

          it 'shows no warnings' do
            @xcode_summary.report('spec/fixtures/swiftlint.xcresult')
            expect(@dangerfile.status_report[:warnings]).to eq []
          end

          it 'shows errors' do
            @xcode_summary.report('spec/fixtures/build_error.xcresult')
            expect(@dangerfile.status_report[:warnings]).to eq []
            expect(@dangerfile.status_report[:errors].count).to_not eq 0
          end

          it 'reports warning and error counts with no warnings' do
            result = @xcode_summary.warning_error_count('spec/fixtures/build_error.xcresult')
            expect(result).to eq '{"warnings":0,"errors":3}'
          end
        end

        context 'with ignored_results' do
          before do
            @xcode_summary.ignored_results do |result|
              result.message.include?('public extension') || result.message.include?('unresolved')
            end
          end

          it 'asserts no errors' do
            @xcode_summary.report('spec/fixtures/build_error.xcresult')
            expect(@dangerfile.status_report[:errors].count).to eq 1
          end

          it 'asserts no warnings' do
            @xcode_summary.report('spec/fixtures/swiftlint.xcresult')
            expect(@dangerfile.status_report[:warnings].count).to eq 19
          end

          it 'report warning and error counts' do
            result = @xcode_summary.warning_error_count('spec/fixtures/build_error.xcresult')
            expect(result).to eq '{"warnings":19,"errors":1}'
          end
        end

        context 'without strict' do
          before do
            @xcode_summary.strict = false
          end

          it 'shows errors as warnings' do
            @xcode_summary.report('spec/fixtures/build_error.xcresult')
            expect(@dangerfile.status_report[:warnings].count).to_not eq 0
            expect(@dangerfile.status_report[:errors]).to eq []
          end

          it 'report warning and error counts' do
            result = @xcode_summary.warning_error_count('spec/fixtures/build_error.xcresult')
            expect(result).to eq '{"warnings":21,"errors":3}'
          end
        end
      end
    end

    # Second environment with different request_source
    describe 'with bitbucket request_source' do
      before do
        @dangerfile = testing_bitbucket_dangerfile
        @xcode_summary = @dangerfile.xcode_summary
        @xcode_summary.env.request_source.pr_json = JSON.parse(File.read('spec/fixtures/bitbucket_pr.json'), symbolize_names: true)
        @xcode_summary.project_root = '/Users/diogo/src/danger-xcode_summary'
      end

      describe 'where request source' do
        it 'should be bitbucket' do
          path = @xcode_summary.send(:format_path, 'lib/xcode_summary/plugin.rb', 3)
          expect(path).to eq 'lib/xcode_summary/plugin.rb'
        end
      end
    end
  end
end
# rubocop:enable Layout/LineLength


text:
title: District partnerships
nav: educate_nav
---
# Partner with Code.org to bring K-12 computer science to your district

Code.org partners with school districts across the country to suppport and expand computer science learning in schools. Partnerships include high quality [computer science curriculum](/educate/curriculum), [professional development](/educate/professional-development), online and in person supports, marketing materials, and more.

## Our Goals

- Expanding *access* to high-quality computer science education to all students
- Establishing a computer science program that will grow and be sustained within the district beyond the term of our partnership

[<button>Begin your application</button>](https://form.jotform.com/51276687185972)

## The Application Process

Applying for a district partnership is a relatively thorough process. You can read through the materials here, but we expect it to be a collaborative process between you and our district outreach team.

1. [Determine if you qualify](/educate/qualify).
1. [Fill out our interest form](https://form.jotform.com/51276687185972). Someone from our outreach team will follow up with you.
1. Review the full application: [download Word doc](/files/district_partnership_application.docx) or [see Google doc](https://docs.google.com/document/d/1wGk4LPrFsA5sKxxD2S173WsJC8QX8tfWuPcyJLhgDPk/edit?usp=sharing)
1. Meet with Code.org's outreach team as you complete your application. Here's [a detailed term sheet](/educate/districtterms) that describes what you need to do and what we will do as part of the partnership.
1. Submit your completed application to us via email at <district@code.org>.

[<button>Start your application</button>](https://form.jotform.com/51276687185972)

## Deadlines

Here are our deadlines for Applications. Applications received earlier will receive higher priorty.

- Window 1: Applications need to be in by June 30th.
- Window 2: Applications need to be in by August 31st.
- Window 3: Applications need to be in by October 31st.
- Window 4: Applications accepted on a rolling basis.

## Information on Curriculum and PD

- Courses for grades K-5 ([Quick Overview](/files/K5onepager.pdf)/[Curriculum](/educate/k5)/[PD Model](https://docs.google.com/document/d/1qMtoBjiH7WX_dC_xB54D5W5WJ3bJCnRBA8YBYltInLY/edit?usp=sharing))
- Computer Science in Algebra ([Quick Overview](/files/CSinAlgebra_one_pager.pdf)/[Curriculum](/curriculum/algebra)/[PD Model](https://docs.google.com/document/d/1afDNY70MrWkBTQGuGoaOXBQjfIzHH1FVzKNYOIv7vMU/edit?usp=sharing))
- Computer Science in Science ([Quick Overview](/files/CSinScience_one_pager.pdf)/[Curriculum](/curriculum/science)/[PD Model](https://docs.google.com/document/d/111v2O8rsK3iRl4ZeuZxPdwpHLkALyLjtmv7iuQmlYio/edit?usp=sharing))
- Exploring Computer Science ([Quick Overview](/files/ECS_one_pager.pdf)/[Curriculum](http://www.exploringcs.org/curriculum)/[PD Model](https://docs.google.com/document/d/1RbP0u41DgxGL1bTcMDaxe3pc4vQ-WaxHajZ2m53Zato/edit?usp=sharing))
- Computer Science Principles ([Quick Overview](/files/CSP_one_pager.pdf)/[Curriculum](/educate/csp)/[PD Model](https://docs.google.com/document/d/1SSMhd4dvnl1BTlYngl4Pky0JfkFmMmalFkePVpAijgE/edit?usp=sharing))
- Computer Science Discoveries *available for 2017-18 school year* ([Quick Overview](/educate/csd)/Curriculum and PD Model in development)

## Existing partners (including all 7 of the largest US school districts)

[col-50]

- New York City Department of Education (NY)
- Los Angeles Unified School District (CA)
- Chicago Public Schools (IL)
- Miami-Dade County Public Schools (FL)
- Clark County School District (NV)
- Broward County Public Schools (FL)
- Houston Independent School District (TX)
- Montgomery County Public Schools (MD)
- [See all 90 partner districts](/educate/partner-districts)

[/col-50]

[col-50]

[/col-50]

## What teachers say about Code.org

<%= view :pd_quotes %>

Please contact <district@code.org> for more information.


text:
package com.xinqihd.sns.gameserver.transport.admin;

import com.xinqihd.sns.gameserver.bootstrap.Bootstrap;

/**
 * Print the help message.
 * @author wangqi
 *
 */
public class ShutdownCommand implements Command {

	public static final String COMMAND = "shutdown";

	private static final String RESPONSE = "Shutdown server! \n>";

	@Override
	public String execute(String[] args) {
		Bootstrap.exit(RESPONSE, 0);
		return RESPONSE;
	}

	/**
	 * Get the help content
	 */
	public String toString() {
		return "shutdown: shutdown the whole server.";
	}

}


text: Basic Architecture For Android App


text:
package org.apache.olingo.odata2.core.rest;

import java.util.List;
import java.util.Locale;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.ServletConfig;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

import org.apache.olingo.odata2.api.ODataServiceFactory;
import org.apache.olingo.odata2.api.commons.HttpStatusCodes;
import org.apache.olingo.odata2.api.ep.EntityProviderException;
import org.apache.olingo.odata2.api.exception.ODataApplicationException;
import org.apache.olingo.odata2.api.processor.ODataErrorCallback;
import org.apache.olingo.odata2.api.processor.ODataErrorContext;
import org.apache.olingo.odata2.api.processor.ODataResponse;
import org.apache.olingo.odata2.core.commons.ContentType;
import org.apache.olingo.odata2.core.ep.ProviderFacadeImpl;

/**
 * Creates an error response according to the format defined by the OData standard
 * if an exception occurs that is not handled elsewhere.
 *
 */
@Provider
public class ODataExceptionMapperImpl implements ExceptionMapper<Exception> {

  private static final String DOLLAR_FORMAT = "$format";
  private static final String DOLLAR_FORMAT_JSON = "json";

  private static final Locale DEFAULT_RESPONSE_LOCALE = Locale.ENGLISH;

  @Context
  UriInfo uriInfo;
  @Context
  HttpHeaders httpHeaders;
  @Context
  ServletConfig servletConfig;
  @Context
  HttpServletRequest servletRequest;
  @Context
  Application app;

  @Override
  public Response toResponse(final Exception exception) {
    ODataResponse response;
    try {
      if (exception instanceof WebApplicationException) {
        response = handleWebApplicationException(exception);
      } else {
        response = handleException(exception);
      }
    } catch (Exception e) {
      response = ODataResponse.entity("Exception during error handling occured!")
          .contentHeader(ContentType.TEXT_PLAIN.toContentTypeString())
          .status(HttpStatusCodes.INTERNAL_SERVER_ERROR).build();
    }
    // Convert OData response to JAX-RS response.
    return RestUtil.convertResponse(response);
  }

  private ODataResponse handleException(final Exception exception) {

    ODataExceptionWrapper exceptionWrapper =
        new ODataExceptionWrapper(uriInfo, httpHeaders, getErrorHandlerCallback());
    return exceptionWrapper.wrapInExceptionResponse(exception);
  }

  private ODataResponse handleWebApplicationException(final Exception exception) throws ClassNotFoundException,
      InstantiationException, IllegalAccessException, EntityProviderException {
    ODataErrorContext errorContext = createErrorContext((WebApplicationException) exception);
    ODataErrorCallback callback = getErrorHandlerCallback();
    return callback == null ?
        new ProviderFacadeImpl().writeErrorDocument(errorContext) : executeErrorCallback(errorContext, callback);
  }

  private ODataResponse executeErrorCallback(final ODataErrorContext errorContext, final ODataErrorCallback callback) {
    ODataResponse oDataResponse;
    try {
      oDataResponse = callback.handleError(errorContext);
    } catch (ODataApplicationException e) {
      oDataResponse = handleException(e);
    }
    return oDataResponse;
  }

  private ODataErrorContext createErrorContext(final WebApplicationException exception) {
    ODataErrorContext context = new ODataErrorContext();
    if (uriInfo != null) {
      context.setRequestUri(uriInfo.getRequestUri());
    }
    if (httpHeaders != null && httpHeaders.getRequestHeaders() != null) {
      MultivaluedMap<String, String> requestHeaders = httpHeaders.getRequestHeaders();
      Set<Entry<String, List<String>>> entries = requestHeaders.entrySet();
      for (Entry<String, List<String>> entry : entries) {
        context.putRequestHeader(entry.getKey(), entry.getValue());
      }
    }
    context.setContentType(getContentType().toContentTypeString());
    context.setException(exception);
    context.setErrorCode(null);
    context.setMessage(exception.getMessage());
    context.setLocale(DEFAULT_RESPONSE_LOCALE);
    HttpStatusCodes statusCode = HttpStatusCodes.fromStatusCode(exception.getResponse().getStatus());
    context.setHttpStatus(statusCode);
    if (statusCode == HttpStatusCodes.METHOD_NOT_ALLOWED) {
      // RFC 2616, 5.1.1: " An origin server SHOULD return the status code
      // 405 (Method Not Allowed) if the method is known by the origin server
      // but not allowed for the requested resource, and 501 (Not Implemented)
      // if the method is unrecognized or not implemented by the origin server."
      // Since all recognized methods are handled elsewhere, we unconditionally
      // switch to 501 here for not-allowed exceptions thrown directly from
      // JAX-RS implementations.
      context.setHttpStatus(HttpStatusCodes.NOT_IMPLEMENTED);
      context.setMessage("The request dispatcher does not allow the HTTP method used for the request.");
      context.setLocale(Locale.ENGLISH);
    }
    return context;
  }

  private ContentType getContentType() {
    ContentType contentType = getContentTypeByUriInfo();
    if (contentType == null) {
      contentType = getContentTypeByAcceptHeader();
    }
    return contentType;
  }

  private ContentType getContentTypeByUriInfo() {
    ContentType contentType = null;
    if (uriInfo != null && uriInfo.getQueryParameters() != null) {
      MultivaluedMap<String, String> queryParameters = uriInfo.getQueryParameters();
      if (queryParameters.containsKey(DOLLAR_FORMAT)) {
        String contentTypeString = queryParameters.getFirst(DOLLAR_FORMAT);
        if (DOLLAR_FORMAT_JSON.equals(contentTypeString)) {
          contentType = ContentType.APPLICATION_JSON;
        } else {
          // Any format mentioned in the $format parameter other than json results in an application/xml content type
          // for error messages due to the OData V2 Specification.
          contentType = ContentType.APPLICATION_XML;
        }
      }
    }
    return contentType;
  }

  private ContentType getContentTypeByAcceptHeader() {
    for (MediaType type : httpHeaders.getAcceptableMediaTypes()) {
      if (ContentType.isParseable(type.toString())) {
        ContentType convertedContentType = ContentType.create(type.toString());
        if (convertedContentType.isWildcard()
            || ContentType.APPLICATION_XML.equals(convertedContentType)
            || ContentType.APPLICATION_XML_CS_UTF_8.equals(convertedContentType)
            || ContentType.APPLICATION_ATOM_XML.equals(convertedContentType)
            || ContentType.APPLICATION_ATOM_XML_CS_UTF_8.equals(convertedContentType)) {
          return ContentType.APPLICATION_XML;
        } else if (ContentType.APPLICATION_JSON.equals(convertedContentType)
            || ContentType.APPLICATION_JSON_CS_UTF_8.equals(convertedContentType)) {
          return ContentType.APPLICATION_JSON;
        }
      }
    }
    return ContentType.APPLICATION_XML;
  }

  private ODataErrorCallback getErrorHandlerCallback() {
    final ODataServiceFactory serviceFactory =
        ODataRootLocator.createServiceFactoryFromContext(app, servletRequest, servletConfig);
    return serviceFactory.getCallback(ODataErrorCallback.class);
  }
}


text:
{-# LANGUAGE CPP #-}
-- | Settings are centralized, as much as possible, into this file. This
-- includes database connection settings, static file locations, etc.
-- In addition, you can configure a number of different aspects of Yesod
-- by overriding methods in the Yesod typeclass. That instance is
-- declared in the Autofocus.hs file.
module Settings
    ( hamletFile
    , cassiusFile
    , juliusFile
    , connStr
    , ConnectionPool
    , withConnectionPool
    , runConnectionPool
    , approot
    , staticroot
    , staticdir
    ) where

import qualified Text.Hamlet as H
import qualified Text.Cassius as H
import qualified Text.Julius as H
import Language.Haskell.TH.Syntax
import Database.Persist.Sqlite
import Yesod (MonadInvertIO)

-- | The base URL for your application. This will usually be different for
-- development and production. Yesod automatically constructs URLs for you,
-- so this value must be accurate to create valid links.
approot :: String
#ifdef PRODUCTION
-- You probably want to change this. If your domain name was "yesod.com",
-- you would probably want it to be:
-- > approot = "http://www.yesod.com"
-- Please note that there is no trailing slash.
approot = "http://localhost:3000"
#else
approot = "http://localhost:3000"
#endif

-- | The location of static files on your system. This is a file system
-- path. The default value works properly with your scaffolded site.
staticdir :: FilePath
staticdir = "static"

-- | The base URL for your static files. As you can see by the default
-- value, this can simply be "static" appended to your application root.
-- A powerful optimization can be serving static files from a separate
-- domain name. This allows you to use a web server optimized for static
-- files, more easily set expires and cache values, and avoid possibly
-- costly transference of cookies on static files. For more information,
-- please see:
--   http://code.google.com/speed/page-speed/docs/request.html#ServeFromCookielessDomain
--
-- If you change the resource pattern for StaticR in Autofocus.hs, you will
-- have to make a corresponding change here.
--
-- To see how this value is used, see urlRenderOverride in Autofocus.hs
staticroot :: String
staticroot = approot ++ "/static"

-- | The database connection string. The meaning of this string is backend-
-- specific.
connStr :: String
#ifdef PRODUCTION
connStr = "production.db3"
#else
connStr = "debug.db3"
#endif

-- | Your application will keep a connection pool and take connections from
-- there as necessary instead of continually creating new connections. This
-- value gives the maximum number of connections to be open at a given time.
-- If your application requests a connection when all connections are in
-- use, that request will fail. Try to choose a number that will work well
-- with the system resources available to you while providing enough
-- connections for your expected load.
--
-- Also, connections are returned to the pool as quickly as possible by
-- Yesod to avoid resource exhaustion. A connection is only considered in
-- use while within a call to runDB.
connectionCount :: Int
connectionCount = 10

-- The rest of this file contains settings which rarely need changing by a
-- user.

-- The following three functions are used for calling HTML, CSS and
-- Javascript templates from your Haskell code. During development,
-- the "Debug" versions of these functions are used so that changes to
-- the templates are immediately reflected in an already running
-- application. When making a production compile, the non-debug version
-- is used for increased performance.
--
-- You can see an example of how to call these functions in Handler/Root.hs
--
-- Note: due to polymorphic Hamlet templates, hamletFileDebug is no longer
-- used; to get the same auto-loading effect, it is recommended that you
-- use the devel server.

hamletFile :: FilePath -> Q Exp
hamletFile x = H.hamletFile $ "hamlet/" ++ x ++ ".hamlet"

cassiusFile :: FilePath -> Q Exp
#ifdef PRODUCTION
cassiusFile x = H.cassiusFile $ "cassius/" ++ x ++ ".cassius"
#else
cassiusFile x = H.cassiusFileDebug $ "cassius/" ++ x ++ ".cassius"
#endif

juliusFile :: FilePath -> Q Exp
#ifdef PRODUCTION
juliusFile x = H.juliusFile $ "julius/" ++ x ++ ".julius"
#else
juliusFile x = H.juliusFileDebug $ "julius/" ++ x ++ ".julius"
#endif

-- The next two functions are for allocating a connection pool and running
-- database actions using a pool, respectively. It is used internally
-- by the scaffolded application, and therefore you will rarely need to use
-- them yourself.
withConnectionPool :: MonadInvertIO m => (ConnectionPool -> m a) -> m a
withConnectionPool = withSqlitePool connStr connectionCount

runConnectionPool :: MonadInvertIO m => SqlPersist m a -> ConnectionPool -> m a
runConnectionPool = runSqlPool