text:
@import url("pygment_highlights.css");

/* --- General --- */

body {
  font-family: 'Lora', 'Times New Roman', serif;
  font-size: 18px;
  color: #404040;
  position: relative;
  background: #FFF;
}
p {
  line-height: 1.5;
  margin: 30px 0;
}
p a {
  text-decoration: underline;
  color: #404040;
}
code {
  word-break: break-word;
}
h1,h2,h3,h4,h5,h6 {
  font-family: 'Open Sans', 'Helvetica Neue', Helvetica, Arial, sans-serif;
  font-weight: 800;
}
a {
  text-decoration: underline;
  color: #404040;
}
a:hover,
a:focus {
  color: #0085a1;
}
blockquote {
  color: #808080;
  font-style: italic;
}
hr.small {
  max-width: 100px;
  margin: 15px auto;
  border-width: 4px;
  border-color: inherit;
  border-radius: 3px;
}

.main-explain-area {
  font-family: 'Open Sans', 'Helvetica Neue', Helvetica, Arial, sans-serif;
  padding: 15px inherit;
}

.hideme {
  display: none;
}

::-moz-selection {
  color: white;
  text-shadow: none;
  background: #0085a1;
}
::selection {
  color: white;
  text-shadow: none;
  background: #0085a1;
}
img::selection {
  color: white;
  background: transparent;
}
img::-moz-selection {
  color: white;
  background: transparent;
}

.disqus-comments {
  margin-top: 30px;
}

@media only screen and (min-width: 768px) {
  .disqus-comments {
    margin-top: 40px;
  }
}

/* --- Navbar --- */

.navbar-custom {
  background: #F5F5F5;
  border-bottom: 1px solid #EAEAEA;
  font-family: 'Open Sans', 'Helvetica Neue', Helvetica, Arial, sans-serif;
}

.navbar-custom .nav li a {
  text-transform: uppercase;
  font-size: 13px;
  letter-spacing: 1px;
}

.navbar-custom .navbar-brand,
.navbar-custom .nav li a {
  font-weight: 800;
  color: #404040;
  text-decoration: none;
}

.navbar-custom .navbar-brand:hover,
.navbar-custom .navbar-brand:focus ,
.navbar-custom .nav li a:hover,
.navbar-custom .nav li a:focus {
  color: #0085a1;
}

@media only screen and (min-width: 768px) {
  .navbar-custom {
    padding: 20px 0;
    -webkit-transition: background .5s ease-in-out,padding .5s ease-in-out;
    -moz-transition: background .5s ease-in-out,padding .5s ease-in-out;
    transition: background .5s ease-in-out,padding .5s ease-in-out;
  }

  .navbar-custom.top-nav-short {
    padding: 0;
  }
}

.navbar-custom .avatar-container {
  opacity: 1;
  position: absolute;
  -webkit-transition: opacity 0.5s ease-in-out;
  -moz-transition: opacity 0.5s ease-in-out;
  transition: opacity 0.5s ease-in-out;
  left: 50%;
  width: 50px;
  margin-top: -25px;
}
.navbar-custom .avatar-container  .avatar-img-border {
  width: 100%;
  border-radius: 50%;
  margin-left: -50%;
  display: inline-block;
  box-shadow: 0 0 8px rgba(0, 0, 0, .8);
  -webkit-box-shadow: 0 0 5px rgba(0, 0, 0, .8);
  -moz-box-shadow: 0 0 8px rgba(0, 0, 0, .8);
}
.navbar-custom .avatar-container  .avatar-img {
  width: 100%;
  border-radius: 50%;
  display: block;
}

.navbar-custom.top-nav-short .avatar-container{
  opacity: 0;
}

.navbar-custom.top-nav-expanded .avatar-container  {
  display: none;
}

@media only screen and (min-width: 768px) {
  .navbar-custom .avatar-container {
    width: 100px;
    margin-top: -50px;
  }

  .navbar-custom .avatar-container  .avatar-img-border {
    width: 100%;
    box-shadow: 1px 1px 2px rgba(0, 0, 0, .8);
    -webkit-box-shadow: 1px 1px 2px rgba(0, 0, 0, .8);
    -moz-box-shadow: 1px 1px 2px rgba(0, 0, 0, .8);
  }

  .navbar-custom .avatar-container  .avatar-img {
    width: 100%;
  }
}

.nav-search-link .nav-search-icon {
  display: none;
}
.nav-search-link .nav-search-text {
  display: inline;
}
@media only screen and (min-width: 768px) {
  .nav-search-link .nav-search-icon {
    display: inline;
  }
  .nav-search-link .nav-search-text {
    display: none;
  }
}

@media only screen and (max-width: 992px) {
  .navbar-custom .nav li a {
    padding-left: 10px;
	padding-right: 10px;
	font-size: 12px;
  }
}

/* fix in-page anchors to not be behind fixed header */
:target:before {
    content: "";
    display: block;
    height: 50px; /* navbar height */
    margin: -50px 0 0;
}

/* Multi-level navigation links */
.navbar-custom .nav .navlinks-container {
  position: relative;
}
.navbar-custom .nav .navlinks-parent:after {
  content: " \25BC";
}
.navbar-custom .nav .navlinks-children {
  width: 100%;
  display: none;
  word-break: break-word;
}
.navbar-custom .nav .navlinks-container .navlinks-children a {
  display: block;
  padding: 10px;
  padding-left: 30px;
  background: #f5f5f5;
  text-decoration: none !important;
  border-width: 0 1px 1px 1px;
  font-weight: normal;
}
@media only screen and (max-width: 767px) {
  .navbar-custom .nav .navlinks-container.show-children {
    background: #eee;
  }
  .navbar-custom .nav .navlinks-container.show-children .navlinks-children {
    display: block;
  }
}
@media only screen and (min-width: 768px) {
  .navbar-custom .nav .navlinks-container:hover {
    background: #eee;
  }
  .navbar-custom .nav .navlinks-container:hover .navlinks-children {
    display: block;
  }
  .navbar-custom .nav .navlinks-children {
    position: absolute;
    text-align: center;
  }
  .navbar-custom .nav .navlinks-container .navlinks-children a {
    padding-left: 10px;
    border: 1px solid #eaeaea;
    border-width: 0 1px 1px;
  }
}

/* --- Footer --- */

footer {
  padding: 30px 0;
  background: #F5F5F5;
  border-top: 1px #EAEAEA solid;
  margin-top: 35px;
  font-size: 14px;
}

footer a {
  color: #404040;
  text-decoration: none;
}

footer .list-inline {
  margin: 0;
  padding: 0;
}
footer .copyright {
  font-family: Open Sans;
  text-align: center;
  margin-bottom: 0;
}
footer .theme-by {
  text-align: center;
  margin: 10px 0 0;
}

@media only screen and (min-width: 768px) {
  footer {
    padding: 50px 0;
	margin-top: 50px;
  }
  footer .footer-links {
    font-size: 18px;
  }
  footer .copyright {
    font-size: 16px;
  }
}

/* --- Post preview --- */

.post-preview {
  padding: 20px 0;
  border-bottom: 1px solid #eee;
}

@media only screen and (min-width: 768px) {
  .post-preview {
    padding: 35px 0;
  }
}

.post-preview:last-child {
  border-bottom: 0;
}

.post-preview a {
  text-decoration: none;
  color: #404040;
}

.post-preview a:focus,
.post-preview a:hover {
  text-decoration: none;
  color: #0085a1;
}

.post-preview .post-title {
  font-size: 30px;
  margin-top: 0;
}
.post-preview .post-subtitle {
  margin: 0;
  font-weight: 300;
  margin-bottom: 10px;
}
.post-preview .post-meta,
.post-heading .post-meta {
  color: #808080;
  font-size: 18px;
  font-style: italic;
  margin: 0 0 10px;
}
.post-preview .post-entry {
  font-family: 'Open Sans', 'Helvetica Neue', Helvetica, Arial, sans-serif;
}
.post-preview .post-read-more {
  font-weight: 800;
}

@media only screen and (min-width: 768px) {
  .post-preview .post-title {
    font-size: 36px;
  }
}

/* --- Post and page headers --- */

.intro-header {
  margin: 80px 0 20px;
  position: relative;
}
.intro-header.big-img {
  background: no-repeat center center;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  background-size: cover;
  -o-background-size: cover;
  margin-top: 51px; /* The small navbar is 50px tall + 1px border */
  margin-bottom: 35px;
}
.intro-header.big-img  .big-img-transition {
  position: absolute;
  width: 100%;
  height: 100%;
  opacity: 0;
  background: no-repeat center center;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  background-size: cover;
  -o-background-size: cover;
  -webkit-transition: opacity 1s linear;
  -moz-transition: opacity 1s linear;
  transition: opacity 1s linear;
}
.intro-header .page-heading {
  text-align: center;
}
.intro-header.big-img .page-heading,
.intro-header.big-img .post-heading {
  padding: 100px 0;
  color: #FFF;
  text-shadow: 1px 1px 3px #000;
}
.intro-header .page-heading h1 {
  margin-top: 0;
  font-size: 50px;
}
.intro-header .post-heading h1 {
  margin-top: 0;
  font-size: 35px;
}
.intro-header .page-heading .page-subheading,
.intro-header .post-heading .post-subheading {
  font-size: 27px;
  line-height: 1.1;
  display: block;
  font-family: 'Open Sans', 'Helvetica Neue', Helvetica, Arial, sans-serif;
  font-weight: 300;
  margin: 10px 0 0;
}
.intro-header .post-heading .post-subheading {
  margin-bottom: 20px;
}
.intro-header.big-img .page-heading .page-subheading,
.intro-header.big-img .post-heading .post-subheading {
  font-weight: 400;
}
.intro-header.big-img .page-heading hr {
  box-shadow: 1px 1px 3px #000;
  -webkit-box-shadow: 1px 1px 3px #000;
  -moz-box-shadow: 1px 1px 3px #000;
}
.intro-header.big-img .post-heading .post-meta {
  color: #EEE;
}
.intro-header.big-img .img-desc {
  background: rgba(30, 30, 30, 0.6);
  position: absolute;
  padding: 5px 10px;
  font-size: 11px;
  color: #EEE;
  font-family: 'Open Sans', 'Helvetica Neue', Helvetica, Arial, sans-serif;
  right: 0;
  bottom: 0;
  display: none;
}
@media only screen and (min-width: 768px) {
  .intro-header {
    margin-top: 130px;
  }
  .intro-header.big-img {
    margin-top: 91px;  /* Full navbar is small navbar + 20px padding on each side when expanded */
  }
  .intro-header.big-img .page-heading,
  .intro-header.big-img .post-heading  {
    padding: 150px 0;
  }
  .intro-header .page-heading h1 {
    font-size: 80px;
  }
  .intro-header .post-heading h1 {
    font-size: 50px;
  }
  .intro-header.big-img .img-desc {
    font-size: 14px;
  }
}

.header-section.has-img .no-img {
  margin-top: 0;
  background: #FCFCFC;
  margin: 0 0 40px;
  padding: 20px 0;
  box-shadow: 0 0 5px #AAA;
}
/* Many phones are 320 or 360px, so make sure images are a proper aspect ratio in those cases */
.header-section.has-img .intro-header.no-img {
  display: none;
}
@media only screen and (max-width: 365px) {
  .header-section.has-img .intro-header.no-img {
    display: block;
  }
  .intro-header.big-img {
    width: 100%;
    height: 220px;
  }
  .intro-header.big-img .page-heading,
  .intro-header.big-img .post-heading {
    display: none;
  }
  .header-section.has-img .big-img {
    margin-bottom: 0;
  }
}
@media only screen and (max-width: 325px) {
  .intro-header.big-img {
    height: 200px;
  }
}

/* --- Blog post --- */

.blog-post :first-child {
  margin-top: 0;
}

.blog-post .caption {
  text-align: center;
  font-size: 14px;
  padding: 10px;
  font-style: italic;
  margin: 0;
  display: block;
  border-bottom-right-radius: 5px;
  border-bottom-left-radius: 5px;
}

.blog-post img {
  max-width: 100%;
}

.blog-post hr {
  max-width: 25%;
  border-width: 4px;
  border-radius: 3px;
  border-color: #808080;
}

.blog-tags {
  font-family: 'Open Sans', 'Helvetica Neue', Helvetica, Arial, sans-serif;
  color: #999;
  font-size: 15px;
  margin-bottom: 30px;
}

/* --- Pager --- */

.pager li a {
  font-family: 'Open Sans', 'Helvetica Neue', Helvetica, Arial, sans-serif;
  text-transform: uppercase;
  font-size: 14px;
  font-weight: 800;
  letter-spacing: 1px;
  padding: 10px 5px;
  background: #FFF;
  border-radius: 0;
  color: #404040;
  text-decoration: none;
}
@media only screen and (min-width: 768px) {
  .pager li a {
    padding: 15px 25px;
  }
}
.pager li a:hover,
.pager li a:focus {
  color: #FFF;
  background: #0085a1;
  border: 1px solid #0085a1;
}

.pager {
  margin: 10px 0 0;
}

.pager.blog-pager {
  margin-top: 0;
}

@media only screen and (min-width: 768px) {
  .pager.blog-pager  {
    margin-top: 10px;
  }
}

/* --- Tables --- */

.blog-post table {
  padding: 0;
}
.blog-post table tr {
  border-top: 1px solid #cccccc;
  background-color: #ffffff;
  margin: 0;
  padding: 0;
}
.blog-post table tr:nth-child(2n) {
  background-color: #f8f8f8;
}
.blog-post table tbody tr:hover {
  background-color: #eaeaea;
}
.blog-post table tr th {
  font-weight: bold;
  border: 1px solid #cccccc;
  text-align: left;
  margin: 0;
  padding: 6px 13px;
}
.blog-post table tr td {
  border: 1px solid #cccccc;
  text-align: left;
  margin: 0;
  padding: 6px 13px;
}
.blog-post table tr th :first-child,
.blog-post table tr td :first-child {
  margin-top: 0;
}
.blog-post table tr th :last-child,
.blog-post table tr td :last-child {
  margin-bottom: 0;
}

/* --- Share section --- */

.share-section {
  padding: 30px 15px 35px;
  margin-top: 40px;
  margin-bottom: 40px;
  box-shadow: 0 0 10px #e7e7e7 inset;
  background: #fcfcfc;
  text-align: center;
}

.share-section .share-title {
  margin-top: 0;
  font-size: 30px;
}

.share-section .share-buttons {
  margin-top: 15px;
}

.share-section .share-buttons a {
  font-family: 'Open Sans', 'Helvetica Neue', Helvetica, Arial, sans-serif;
  padding: 10px 5px;
  background: #FFF;
  border-radius: 0;
  color: #404040;
  text-decoration: none;
  margin-left: 20px;
  display: inline-block;
  border: 1px solid #ddd;
  font-size: 14px;
}

.share-section .share-buttons a:hover,
.share-section .share-buttons a:focus {
  color: #FFF;
  background: #0085a1;
  border-color: #0085a1;
  transform: scale(1.1);
  -ms-transform: scale(1.1);
  -moz-transform: scale(1.1);
  -webkit-transform: scale(1.1);
  transition: transform 250ms;
  -moz-transition: -moz-transform 250ms;
  -webkit-transition: -webkit-transform 250ms;
}

.share-section .share-buttons a:first-child {
  margin-left: 0;
}

@media only screen and (min-width: 768px) {
  .share-section {
    margin-top: 50px;
    margin-bottom: 50px;
  }
  .share-section .share-title {
    font-size: 45px;
  }
  .share-section .share-buttons {
    margin-top: 30px;
  }
  .share-section .share-buttons a {
    padding: 15px 25px;
    margin-left: 30px;
    font-size: 18px;
  }
}

@media only screen and (max-width: 500px) {
  .share-section .share-buttons a {
    display: block;
    margin-left: 0;
    margin-top: 10px;
  }
  .share-section .share-buttons a:first-child {
    margin-top: 0;
  }
}

/* --- Code blocks --- */

pre {
  font-size: 16px;
  line-height: 1.5em;
  background: #FAFAFA;
  background-image: linear-gradient(#FAFAFA 50%, #FDFDFD 50%);
  background-position: 0px 10px;
  background-repeat: repeat;
  background-size: 3em 3em;
  border-left: 7px solid #444;
}

pre code {
  white-space: pre;
}


text:
import {
  GraphQLObjectType,
  GraphQLNonNull,
  GraphQLString,
  GraphQLBoolean,
  GraphQLList,
} from 'graphql/type';

export default new GraphQLObjectType({
  name: 'Meta',
  description: 'Blog post metadata',
  fields: () => ({
    title: {
      type: new GraphQLNonNull(GraphQLString),
      description: 'Title of the blog post',
    },
    slug: {
      type: new GraphQLNonNull(GraphQLString),
      description: 'Slug of the blog post',
    },
    date: {
      type: new GraphQLNonNull(GraphQLString),
      description: 'Date of the blog post',
    },
    comments: {
      type: GraphQLBoolean,
      description: 'Choose if we want to show comments or not',
    },
    categories: {
      type: new GraphQLList(GraphQLString),
      description: 'Blog post categories',
    },
    tags: {
      type: new GraphQLList(GraphQLString),
      description: 'Blog post tags',
    },
  })
});

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Tests\dLdL\ChatbotPlatform\Event;

use dLdL\ChatbotPlatform\ChatbotMessengers;
use dLdL\ChatbotPlatform\Event\MessageEvent;
use dLdL\ChatbotPlatform\Message\Message;
use PHPUnit\Framework\TestCase;

class MessageEventTest extends TestCase
{
    /**
     * @expectedException \InvalidArgumentException
     * @expectedExceptionMessage Reply must have original message discussion ID
     */
    public function testInvalidReply()
    {
        $replyEvent = new MessageEvent(new Message(ChatbotMessengers::AJAX, '12345', 'Michel', 'Albert'));

        $replyEvent->setReply(new Message(ChatbotMessengers::AJAX, '54321', 'Albert', 'Michel'));
    }
}


text:
module('system/run_loop/schedule_test');

test('scheduling item in queue should defer until finished', function() {
  var cnt = 0;

  Ember.run(function() {
    Ember.run.schedule('actions', function() { cnt++; });
    Ember.run.schedule('actions', function() { cnt++; });
    equal(cnt, 0, 'should not run action yet') ;
  });

  equal(cnt, 2, 'should flush actions now');

});

test('nested runs should queue each phase independently', function() {
  var cnt = 0;

  Ember.run(function() {
    Ember.run.schedule('actions', function() { cnt++; });
    equal(cnt, 0, 'should not run action yet') ;

    Ember.run(function() {
      Ember.run.schedule('actions', function() { cnt++; });
    });
    equal(cnt, 1, 'should not run action yet') ;

  });

  equal(cnt, 2, 'should flush actions now');

});

test('prior queues should be flushed before moving on to next queue', function() {
  var order = [];

  Ember.run(function() {
    Ember.run.schedule('sync', function() {
      order.push('sync');
    });
    Ember.run.schedule('actions', function() {
      order.push('actions');
      Ember.run.schedule('actions', function() {
        order.push('actions');
      });
      Ember.run.schedule('sync', function() {
        order.push('sync');
      });
    });
    Ember.run.schedule('timers', function() {
      order.push('timers');
    });
  });

  deepEqual(order, ['sync', 'actions', 'sync', 'actions', 'timers']);
});


text:
package de.tudarmstadt.lt.sentimentClassification;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * Created by krayush on 15-06-2015.
 */
public class EntityFeatureH {
    List<LinkedHashMap<Integer, Double>> trainingFeature;
    List<LinkedHashMap<Integer, Double>> testFeature;
    String rootDirectory;

    EntityFeatureH(String rootDirectory) throws IOException {
        this.rootDirectory = rootDirectory;
        trainingFeature = new ArrayList<LinkedHashMap<Integer, Double>>();
        testFeature = new ArrayList<LinkedHashMap<Integer, Double>>();

        trainingFeature = generateFeatureTrain(rootDirectory + "\\dataset\\dataset_sentimentClassification\\Train_Hotels_Cleansed.txt");
        testFeature = generateFeatureTest(rootDirectory + "\\dataset\\dataset_sentimentClassification\\Test_Hotels_Cleansed.txt");

        getTrainingList();
    }

    private List<LinkedHashMap<Integer, Double>> generateFeatureTest(String fileName) throws IOException {
        List<LinkedHashMap<Integer, Double>> featureVector = new ArrayList<LinkedHashMap<Integer, Double>>();
        File file = new File(fileName);
        BufferedReader reader = new BufferedReader(new FileReader(file));

        LinkedHashMap<String, Integer> entityMap = new LinkedHashMap<String, Integer>();

        entityMap.put("GENERAL", 1);
        entityMap.put("PRICE", 2);
        entityMap.put("PRICES", 2);
        entityMap.put("QUALITY", 3);
        entityMap.put("OPERATION_PERFORMANCE", 3);
        entityMap.put("USABILITY", 4);
        entityMap.put("DESIGN_FEATURES", 5);
        entityMap.put("PORTABILITY", 4);
        entityMap.put("COMFORT", 4);
        entityMap.put("CONNECTIVITY", 3);
        entityMap.put("MISCELLANEOUS", 6);

        //entityMap.put("GENERAL", 1.0);
        //entityMap.put("PRICES", 2.0);
        //entityMap.put("QUALITY", 3.0);
        entityMap.put("STYLE_OPTIONS", 7);
        entityMap.put("CLEANLINESS", 6);
        //entityMap.put("MISCELLANEOUS", 5.0);

        String line;
        int count = 0;
        while ((line = reader.readLine()) != null) {
            String words[] = line.split("\\|");
            String entity[] = words[5].split("#");
            if (entityMap.containsKey(entity[1])) {
                featureVector.add(count, new LinkedHashMap<Integer, Double>());
                //featureVector.get(count).put(1, entityMap.get(entity[0]));
                featureVector.get(count).put(entityMap.get(entity[1]), 1.0);
                count++;
            } else {
                System.out.println("Error: " + entity[1] + count + "ABC");
            }
        }
        return featureVector;
    }

    private List<LinkedHashMap<Integer, Double>> generateFeatureTrain(String fileName) throws IOException {
        List<LinkedHashMap<Integer, Double>> featureVector = new ArrayList<LinkedHashMap<Integer, Double>>();
        File file = new File(fileName);
        BufferedReader reader = new BufferedReader(new FileReader(file));

        LinkedHashMap<String, Integer> entityMap = new LinkedHashMap<String, Integer>();

        entityMap.put("GENERAL", 1);
        entityMap.put("PRICE", 2);
        entityMap.put("PRICES", 2);
        entityMap.put("QUALITY", 3);
        entityMap.put("OPERATION_PERFORMANCE", 3);
        entityMap.put("USABILITY", 4);

        entityMap.put("DESIGN_FEATURES", 5);
        entityMap.put("PORTABILITY", 4);
        entityMap.put("CONNECTIVITY", 3);
        entityMap.put("MISCELLANEOUS", 6);

        //entityMap.put("GENERAL", 1.0);
        //entityMap.put("PRICES", 2.0);
        //entityMap.put("QUALITY", 3.0);
        entityMap.put("STYLE_OPTIONS", 7);
        entityMap.put("CLEANLINESS", 6);
        //entityMap.put("MISCELLANEOUS", 5.0);

        String line;
        int count = 0;
        while ((line = reader.readLine()) != null) {
            String words[] = line.split("\\|");
            String entity[];
            if (count < 1200) {
                entity = words[4].split("#");
            } else {
                entity = words[5].split("#");
            }

            if (entityMap.containsKey(entity[1])) {
                featureVector.add(count, new LinkedHashMap<Integer, Double>());
                //featureVector.get(count).put(1, entityMap.get(entity[0]));
                featureVector.get(count).put(entityMap.get(entity[1]), 1.0);
                count++;
            } else {
                System.out.println("Error: " + entity[1] + count + "ABC");
            }
        }
        return featureVector;
    }

    public List<LinkedHashMap<Integer, Double>> getTrainingList() {
        //System.out.println(trainingFeature.size());
        /*for(int i=0; i<trainingFeature.size(); i++)
        {
            System.out.println(trainingFeature.get(i));
        }*/
        return this.trainingFeature;
    }

    public List<LinkedHashMap<Integer, Double>> getTestList() {
        //System.out.println(trainingFeature.size());
        return this.testFeature;
    }

    public int getFeatureCount() {
        //System.out.println(trainingFeature.get(0).size());
        return trainingFeature.get(0).size();
    }

    /*public static void main(String[] args) throws IOException {
        EntityFeature ef = new EntityFeature("D:\\Course\\Semester VII\\Internship\\aspectCategorization");
    }*/
}


text:
using ::testing::_;
using ::testing::ElementsAre;
using ::testing::InvokeArgument;
using ::testing::Unused;

namespace ash {

namespace {

bool expect_bool(dbus::MessageReader* reader) {
  bool result;
  EXPECT_TRUE(reader->PopBool(&result));
  return result;
}

int16_t expect_int16(dbus::MessageReader* reader) {
  int16_t result;
  EXPECT_TRUE(reader->PopInt16(&result));
  return result;
}

uint32_t expect_uint32(dbus::MessageReader* reader) {
  uint32_t result;
  EXPECT_TRUE(reader->PopUint32(&result));
  return result;
}

int32_t expect_int32(dbus::MessageReader* reader) {
  int32_t result;
  EXPECT_TRUE(reader->PopInt32(&result));
  return result;
}

std::string expect_string(dbus::MessageReader* reader) {
  std::string result;
  EXPECT_TRUE(reader->PopString(&result));
  return result;
}

double expect_double(dbus::MessageReader* reader) {
  double result;
  EXPECT_TRUE(reader->PopDouble(&result));
  return result;
}

}  // namespace

class GesturePropertiesServiceProviderTest : public testing::Test {
 public:
  GesturePropertiesServiceProviderTest() {
    mock_service_ = std::make_unique<MockGesturePropertiesService>();
    ON_CALL(*mock_service_, ListDevices(_))
        .WillByDefault(Invoke(
            this, &GesturePropertiesServiceProviderTest::FakeListDevices));
    ON_CALL(*mock_service_, ListProperties(_, _))
        .WillByDefault(Invoke(
            this, &GesturePropertiesServiceProviderTest::FakeListProperties));
    ON_CALL(*mock_service_, GetProperty(_, _, _))
        .WillByDefault(Invoke(
            this, &GesturePropertiesServiceProviderTest::FakeGetProperty));
    ON_CALL(*mock_service_, SetProperty(_, _, _, _))
        .WillByDefault(Invoke(
            this, &GesturePropertiesServiceProviderTest::FakeSetProperty));

    service_provider_ = std::make_unique<GesturePropertiesServiceProvider>();
    service_provider_->set_service_for_test(mock_service_.get());
  }

  ~GesturePropertiesServiceProviderTest() override { test_helper_.TearDown(); }

  void FakeListDevices(
      ui::ozone::mojom::GesturePropertiesService::ListDevicesCallback
          callback) {
    std::move(callback).Run(list_devices_response_);
  }

  void FakeListProperties(
      Unused,
      ui::ozone::mojom::GesturePropertiesService::ListPropertiesCallback
          callback) {
    std::move(callback).Run(list_properties_response_);
  }

  void FakeGetProperty(
      Unused,
      Unused,
      ui::ozone::mojom::GesturePropertiesService::GetPropertyCallback
          callback) {
    std::move(callback).Run(get_property_read_only_,
                            std::move(get_property_response_));
  }

  void FakeSetProperty(
      Unused,
      Unused,
      ui::ozone::mojom::GesturePropValuePtr values,
      ui::ozone::mojom::GesturePropertiesService::SetPropertyCallback
          callback) {
    set_property_values_ = std::move(values);
    std::move(callback).Run(set_property_error_code_);
  }

 protected:
  void CallDBusMethod(std::string name,
                      dbus::MethodCall* method_call,
                      std::unique_ptr<dbus::Response>& response) {
    test_helper_.SetUp(
        chromeos::kGesturePropertiesServiceName,
        dbus::ObjectPath(chromeos::kGesturePropertiesServicePath),
        chromeos::kGesturePropertiesServiceInterface, name,
        service_provider_.get());
    response = test_helper_.CallMethod(method_call);
    ASSERT_TRUE(response);
  }

  void CallWithoutParameters(std::string name,
                             std::unique_ptr<dbus::Response>& response) {
    dbus::MethodCall* method_call = new dbus::MethodCall(
        chromeos::kGesturePropertiesServiceInterface, name);
    CallDBusMethod(name, std::move(method_call), response);
  }

  void CallGetProperty(int32_t device_id,
                       std::string name,
                       std::unique_ptr<dbus::Response>& response) {
    dbus::MethodCall* method_call = new dbus::MethodCall(
        chromeos::kGesturePropertiesServiceInterface,
        chromeos::kGesturePropertiesServiceGetPropertyMethod);
    dbus::MessageWriter writer(method_call);
    writer.AppendInt32(device_id);
    writer.AppendString(name);
    CallDBusMethod(chromeos::kGesturePropertiesServiceGetPropertyMethod,
                   std::move(method_call), response);
  }

  void CheckMethodErrorsWithNoParameters(std::string name) {
    std::unique_ptr<dbus::Response> response = nullptr;
    CallWithoutParameters(name, response);
    EXPECT_EQ(dbus::Message::MESSAGE_ERROR, response->GetMessageType());
  }

  base::test::SingleThreadTaskEnvironment task_environment_;

  base::flat_map<int, std::string> list_devices_response_ = {};
  std::vector<std::string> list_properties_response_ = {};
  bool get_property_read_only_ = true;
  ui::ozone::mojom::GesturePropValuePtr get_property_response_ = nullptr;

  ui::ozone::mojom::GesturePropValuePtr set_property_values_ = nullptr;
  ui::ozone::mojom::SetGesturePropErrorCode set_property_error_code_ =
      ui::ozone::mojom::SetGesturePropErrorCode::SUCCESS;

  std::unique_ptr<MockGesturePropertiesService> mock_service_;

  std::unique_ptr<GesturePropertiesServiceProvider> service_provider_;
  chromeos::ServiceProviderTestHelper test_helper_;

  DISALLOW_COPY_AND_ASSIGN(GesturePropertiesServiceProviderTest);
};

TEST_F(GesturePropertiesServiceProviderTest, ListDevicesEmpty) {
  list_devices_response_ = {};
  EXPECT_CALL(*mock_service_, ListDevices(_));

  std::unique_ptr<dbus::Response> response = nullptr;
  CallWithoutParameters(chromeos::kGesturePropertiesServiceListDevicesMethod,
                        response);

  dbus::MessageReader reader(response.get());
  EXPECT_EQ(0u, expect_uint32(&reader));
  dbus::MessageReader array_reader(nullptr);
  ASSERT_TRUE(reader.PopArray(&array_reader));
  EXPECT_FALSE(array_reader.HasMoreData());
  EXPECT_FALSE(reader.HasMoreData());
}

TEST_F(GesturePropertiesServiceProviderTest, ListDevicesSuccess) {
  list_devices_response_ = {
      {4, "dev 1"},
      {7, "dev 2"},
  };
  EXPECT_CALL(*mock_service_, ListDevices(_));

  std::unique_ptr<dbus::Response> response = nullptr;
  CallWithoutParameters(chromeos::kGesturePropertiesServiceListDevicesMethod,
                        response);

  dbus::MessageReader reader(response.get());
  EXPECT_EQ(2u, expect_uint32(&reader));
  dbus::MessageReader array_reader(nullptr);
  ASSERT_TRUE(reader.PopArray(&array_reader));

  dbus::MessageReader dict_entry_reader(nullptr);
  ASSERT_TRUE(array_reader.PopDictEntry(&dict_entry_reader));
  EXPECT_EQ(4, expect_int32(&dict_entry_reader));
  EXPECT_EQ("dev 1", expect_string(&dict_entry_reader));

  ASSERT_TRUE(array_reader.PopDictEntry(&dict_entry_reader));
  EXPECT_EQ(7, expect_int32(&dict_entry_reader));
  EXPECT_EQ("dev 2", expect_string(&dict_entry_reader));

  EXPECT_FALSE(array_reader.HasMoreData());
  EXPECT_FALSE(reader.HasMoreData());
}

TEST_F(GesturePropertiesServiceProviderTest, ListPropertiesEmpty) {
  list_properties_response_ = {};
  EXPECT_CALL(*mock_service_, ListProperties(4, _));

  std::unique_ptr<dbus::Response> response = nullptr;
  dbus::MethodCall* method_call = new dbus::MethodCall(
      chromeos::kGesturePropertiesServiceInterface,
      chromeos::kGesturePropertiesServiceListPropertiesMethod);
  dbus::MessageWriter writer(method_call);
  writer.AppendInt32(4);
  CallDBusMethod(chromeos::kGesturePropertiesServiceListPropertiesMethod,
                 std::move(method_call), response);

  dbus::MessageReader reader(response.get());
  EXPECT_EQ(0u, expect_uint32(&reader));
  dbus::MessageReader array_reader(nullptr);
  ASSERT_TRUE(reader.PopArray(&array_reader));
  EXPECT_FALSE(array_reader.HasMoreData());
  EXPECT_FALSE(reader.HasMoreData());
}

TEST_F(GesturePropertiesServiceProviderTest, ListPropertiesSuccess) {
  list_properties_response_ = {"prop 1", "prop 2"};
  EXPECT_CALL(*mock_service_, ListProperties(4, _));

  std::unique_ptr<dbus::Response> response = nullptr;
  dbus::MethodCall* method_call = new dbus::MethodCall(
      chromeos::kGesturePropertiesServiceInterface,
      chromeos::kGesturePropertiesServiceListPropertiesMethod);
  dbus::MessageWriter writer(method_call);
  writer.AppendInt32(4);
  CallDBusMethod(chromeos::kGesturePropertiesServiceListPropertiesMethod,
                 std::move(method_call), response);

  dbus::MessageReader reader(response.get());
  EXPECT_EQ(2u, expect_uint32(&reader));
  dbus::MessageReader array_reader(nullptr);
  ASSERT_TRUE(reader.PopArray(&array_reader));
  EXPECT_EQ("prop 1", expect_string(&array_reader));
  EXPECT_EQ("prop 2", expect_string(&array_reader));
  EXPECT_FALSE(array_reader.HasMoreData());
  EXPECT_FALSE(reader.HasMoreData());
}

TEST_F(GesturePropertiesServiceProviderTest, ListPropertiesMissingParameter) {
  CheckMethodErrorsWithNoParameters(
      chromeos::kGesturePropertiesServiceListPropertiesMethod);
}

TEST_F(GesturePropertiesServiceProviderTest, GetPropertySuccessInts) {
  get_property_read_only_ = false;
  get_property_response_ =
      ui::ozone::mojom::GesturePropValue::NewInts({1, 2, 4});
  EXPECT_CALL(*mock_service_, GetProperty(4, "prop 1", _));

  std::unique_ptr<dbus::Response> response = nullptr;
  CallGetProperty(4, "prop 1", response);

  dbus::MessageReader reader(response.get());
  EXPECT_EQ(false, expect_bool(&reader));
  EXPECT_EQ(3u, expect_uint32(&reader));
  dbus::MessageReader variant_reader(nullptr);
  ASSERT_TRUE(reader.PopVariant(&variant_reader));
  dbus::MessageReader array_reader(nullptr);
  ASSERT_TRUE(variant_reader.PopArray(&array_reader));
  EXPECT_EQ(1, expect_int32(&array_reader));
  EXPECT_EQ(2, expect_int32(&array_reader));
  EXPECT_EQ(4, expect_int32(&array_reader));
  EXPECT_FALSE(array_reader.HasMoreData());
  EXPECT_FALSE(reader.HasMoreData());
}

TEST_F(GesturePropertiesServiceProviderTest, GetPropertySuccessShorts) {
  get_property_read_only_ = false;
  get_property_response_ =
      ui::ozone::mojom::GesturePropValue::NewShorts({1, 2, 4});
  EXPECT_CALL(*mock_service_, GetProperty(4, "prop 1", _));

  std::unique_ptr<dbus::Response> response = nullptr;
  CallGetProperty(4, "prop 1", response);

  dbus::MessageReader reader(response.get());
  EXPECT_EQ(false, expect_bool(&reader));
  EXPECT_EQ(3u, expect_uint32(&reader));
  dbus::MessageReader variant_reader(nullptr);
  ASSERT_TRUE(reader.PopVariant(&variant_reader));
  dbus::MessageReader array_reader(nullptr);
  ASSERT_TRUE(variant_reader.PopArray(&array_reader));
  EXPECT_EQ(1, expect_int16(&array_reader));
  EXPECT_EQ(2, expect_int16(&array_reader));
  EXPECT_EQ(4, expect_int16(&array_reader));
  EXPECT_FALSE(array_reader.HasMoreData());
  EXPECT_FALSE(reader.HasMoreData());
}

TEST_F(GesturePropertiesServiceProviderTest, GetPropertySuccessBools) {
  get_property_read_only_ = false;
  get_property_response_ =
      ui::ozone::mojom::GesturePropValue::NewBools({true, false});
  EXPECT_CALL(*mock_service_, GetProperty(4, "prop 1", _));

  std::unique_ptr<dbus::Response> response = nullptr;
  CallGetProperty(4, "prop 1", response);

  dbus::MessageReader reader(response.get());
  EXPECT_EQ(false, expect_bool(&reader));
  EXPECT_EQ(2u, expect_uint32(&reader));
  dbus::MessageReader variant_reader(nullptr);
  ASSERT_TRUE(reader.PopVariant(&variant_reader));
  dbus::MessageReader array_reader(nullptr);
  ASSERT_TRUE(variant_reader.PopArray(&array_reader));
  EXPECT_EQ(true, expect_bool(&array_reader));
  EXPECT_EQ(false, expect_bool(&array_reader));
  EXPECT_FALSE(array_reader.HasMoreData());
  EXPECT_FALSE(reader.HasMoreData());
}

TEST_F(GesturePropertiesServiceProviderTest, GetPropertySuccessStr) {
  get_property_read_only_ = false;
  get_property_response_ = ui::ozone::mojom::GesturePropValue::NewStr("llama");
  EXPECT_CALL(*mock_service_, GetProperty(4, "prop 1", _));

  std::unique_ptr<dbus::Response> response = nullptr;
  CallGetProperty(4, "prop 1", response);

  dbus::MessageReader reader(response.get());
  EXPECT_EQ(false, expect_bool(&reader));
  EXPECT_EQ(1u, expect_uint32(&reader));
  dbus::MessageReader variant_reader(nullptr);
  ASSERT_TRUE(reader.PopVariant(&variant_reader));
  EXPECT_EQ("llama", expect_string(&variant_reader));
  EXPECT_FALSE(reader.HasMoreData());
}

TEST_F(GesturePropertiesServiceProviderTest, GetPropertySuccessReals) {
  get_property_read_only_ = false;
  get_property_response_ =
      ui::ozone::mojom::GesturePropValue::NewReals({3.14, 6.28});
  EXPECT_CALL(*mock_service_, GetProperty(4, "prop 1", _));

  std::unique_ptr<dbus::Response> response = nullptr;
  CallGetProperty(4, "prop 1", response);

  dbus::MessageReader reader(response.get());
  EXPECT_EQ(false, expect_bool(&reader));
  EXPECT_EQ(2u, expect_uint32(&reader));
  dbus::MessageReader variant_reader(nullptr);
  ASSERT_TRUE(reader.PopVariant(&variant_reader));
  dbus::MessageReader array_reader(nullptr);
  ASSERT_TRUE(variant_reader.PopArray(&array_reader));
  EXPECT_EQ(3.14, expect_double(&array_reader));
  EXPECT_EQ(6.28, expect_double(&array_reader));
  EXPECT_FALSE(array_reader.HasMoreData());
  EXPECT_FALSE(reader.HasMoreData());
}

TEST_F(GesturePropertiesServiceProviderTest, GetPropertyPropertyDoesntExist) {
  get_property_read_only_ = true;
  get_property_response_ = nullptr;
  EXPECT_CALL(*mock_service_, GetProperty(4, "prop 1", _));

  std::unique_ptr<dbus::Response> response = nullptr;
  CallGetProperty(4, "prop 1", response);
  EXPECT_EQ(dbus::Message::MESSAGE_ERROR, response->GetMessageType());
}

TEST_F(GesturePropertiesServiceProviderTest, GetPropertyMissingParameters) {
  CheckMethodErrorsWithNoParameters(
      chromeos::kGesturePropertiesServiceGetPropertyMethod);
}

TEST_F(GesturePropertiesServiceProviderTest, SetPropertySuccessInts) {
  EXPECT_CALL(*mock_service_, SetProperty(4, "prop 1", _, _));
  std::unique_ptr<dbus::Response> response = nullptr;
  dbus::MethodCall* method_call = new dbus::MethodCall(
      chromeos::kGesturePropertiesServiceInterface,
      chromeos::kGesturePropertiesServiceSetPropertyMethod);
  dbus::MessageWriter writer(method_call);
  writer.AppendInt32(4);
  writer.AppendString("prop 1");
  dbus::MessageWriter array_writer(nullptr);
  writer.OpenArray("i", &array_writer);
  array_writer.AppendInt32(1);
  array_writer.AppendInt32(2);
  array_writer.AppendInt32(4);
  writer.CloseContainer(&array_writer);
  CallDBusMethod(chromeos::kGesturePropertiesServiceSetPropertyMethod,
                 std::move(method_call), response);
  EXPECT_NE(dbus::Message::MESSAGE_ERROR, response->GetMessageType());
  EXPECT_THAT(set_property_values_->get_ints(), ElementsAre(1, 2, 4));
}

TEST_F(GesturePropertiesServiceProviderTest, SetPropertySuccessShorts) {
  EXPECT_CALL(*mock_service_, SetProperty(4, "prop 1", _, _));
  std::unique_ptr<dbus::Response> response = nullptr;
  dbus::MethodCall* method_call = new dbus::MethodCall(
      chromeos::kGesturePropertiesServiceInterface,
      chromeos::kGesturePropertiesServiceSetPropertyMethod);
  dbus::MessageWriter writer(method_call);
  writer.AppendInt32(4);
  writer.AppendString("prop 1");
  dbus::MessageWriter array_writer(nullptr);
  writer.OpenArray("n", &array_writer);
  array_writer.AppendInt16(1);
  array_writer.AppendInt16(2);
  array_writer.AppendInt16(4);
  writer.CloseContainer(&array_writer);
  CallDBusMethod(chromeos::kGesturePropertiesServiceSetPropertyMethod,
                 std::move(method_call), response);
  EXPECT_NE(dbus::Message::MESSAGE_ERROR, response->GetMessageType());
  EXPECT_THAT(set_property_values_->get_shorts(), ElementsAre(1, 2, 4));
}

TEST_F(GesturePropertiesServiceProviderTest, SetPropertySuccessBools) {
  EXPECT_CALL(*mock_service_, SetProperty(4, "prop 1", _, _));
  std::unique_ptr<dbus::Response> response = nullptr;
  dbus::MethodCall* method_call = new dbus::MethodCall(
      chromeos::kGesturePropertiesServiceInterface,
      chromeos::kGesturePropertiesServiceSetPropertyMethod);
  dbus::MessageWriter writer(method_call);
  writer.AppendInt32(4);
  writer.AppendString("prop 1");
  dbus::MessageWriter array_writer(nullptr);
  writer.OpenArray("b", &array_writer);
  array_writer.AppendBool(true);
  array_writer.AppendBool(false);
  writer.CloseContainer(&array_writer);
  CallDBusMethod(chromeos::kGesturePropertiesServiceSetPropertyMethod,
                 std::move(method_call), response);
  EXPECT_NE(dbus::Message::MESSAGE_ERROR, response->GetMessageType());
  EXPECT_THAT(set_property_values_->get_bools(), ElementsAre(true, false));
}

TEST_F(GesturePropertiesServiceProviderTest, SetPropertySuccessStr) {
  EXPECT_CALL(*mock_service_, SetProperty(4, "prop 1", _, _));
  std::unique_ptr<dbus::Response> response = nullptr;
  dbus::MethodCall* method_call = new dbus::MethodCall(
      chromeos::kGesturePropertiesServiceInterface,
      chromeos::kGesturePropertiesServiceSetPropertyMethod);
  dbus::MessageWriter writer(method_call);
  writer.AppendInt32(4);
  writer.AppendString("prop 1");
  writer.AppendString("llamas");
  CallDBusMethod(chromeos::kGesturePropertiesServiceSetPropertyMethod,
                 std::move(method_call), response);
  EXPECT_NE(dbus::Message::MESSAGE_ERROR, response->GetMessageType());
  EXPECT_EQ(set_property_values_->get_str(), "llamas");
}

TEST_F(GesturePropertiesServiceProviderTest, SetPropertySuccessReals) {
  EXPECT_CALL(*mock_service_, SetProperty(4, "prop 1", _, _));
  std::unique_ptr<dbus::Response> response = nullptr;
  dbus::MethodCall* method_call = new dbus::MethodCall(
      chromeos::kGesturePropertiesServiceInterface,
      chromeos::kGesturePropertiesServiceSetPropertyMethod);
  dbus::MessageWriter writer(method_call);
  writer.AppendInt32(4);
  writer.AppendString("prop 1");
  dbus::MessageWriter array_writer(nullptr);
  writer.OpenArray("d", &array_writer);
  array_writer.AppendDouble(3.14);
  array_writer.AppendDouble(6.28);
  writer.CloseContainer(&array_writer);
  CallDBusMethod(chromeos::kGesturePropertiesServiceSetPropertyMethod,
                 std::move(method_call), response);
  EXPECT_NE(dbus::Message::MESSAGE_ERROR, response->GetMessageType());
  EXPECT_THAT(set_property_values_->get_reals(), ElementsAre(3.14, 6.28));
}

TEST_F(GesturePropertiesServiceProviderTest, SetPropertyError) {
  set_property_error_code_ =
      ui::ozone::mojom::SetGesturePropErrorCode::UNKNOWN_ERROR;
  EXPECT_CALL(*mock_service_, SetProperty(4, "prop 1", _, _));
  std::unique_ptr<dbus::Response> response = nullptr;

  dbus::MethodCall* method_call = new dbus::MethodCall(
      chromeos::kGesturePropertiesServiceInterface,
      chromeos::kGesturePropertiesServiceSetPropertyMethod);
  dbus::MessageWriter writer(method_call);
  writer.AppendInt32(4);
  writer.AppendString("prop 1");
  writer.AppendString("llamas");
  CallDBusMethod(chromeos::kGesturePropertiesServiceSetPropertyMethod,
                 std::move(method_call), response);
  EXPECT_EQ(dbus::Message::MESSAGE_ERROR, response->GetMessageType());
}

TEST_F(GesturePropertiesServiceProviderTest, SetPropertyNoData) {
  std::unique_ptr<dbus::Response> response = nullptr;

  dbus::MethodCall* method_call = new dbus::MethodCall(
      chromeos::kGesturePropertiesServiceInterface,
      chromeos::kGesturePropertiesServiceSetPropertyMethod);
  dbus::MessageWriter writer(method_call);
  writer.AppendInt32(4);
  writer.AppendString("prop 1");
  CallDBusMethod(chromeos::kGesturePropertiesServiceSetPropertyMethod,
                 std::move(method_call), response);
  EXPECT_EQ(dbus::Message::MESSAGE_ERROR, response->GetMessageType());
}

TEST_F(GesturePropertiesServiceProviderTest, SetPropertyMissingParameters) {
  CheckMethodErrorsWithNoParameters(
      chromeos::kGesturePropertiesServiceSetPropertyMethod);
}

}  // namespace ash


text:
/* Get Programming with JavaScript
 * Listing 7.13
 * Shorthand properties and argument destructuring
 */

const buildPlanet = function (name, position, type, radius, rank) {
    return {
        name,
        position,
        type,
        radius,
        sizeRank: rank
    };
};

const getPlanetInfo = ({name, position}) => `${name.toUpperCase()}: planet ${position}`;

const planet1 = buildPlanet("Jupiter", 5, "Gas Giant", 69911, 1);
const planet2 = buildPlanet("Neptune", 8, "Ice Giant", 24622, 4);

console.log(getPlanetInfo(planet1));
console.log(getPlanetInfo(planet2));

/* Further Adventures
 *
 * 1) Create a getPlanetInfo2 function that
 *    uses destructuring to gather other planet
 *    properties and returns a different string
 *    of info.
 *
 */


text:
' Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

Imports System.Collections.Immutable
Imports System.Threading
Imports System.Threading.Tasks
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.CodeAnalysis.EditAndContinue
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.Shared.TestHooks
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.VisualStudio.LanguageServices.Implementation.TaskList
Imports Roslyn.Test.Utilities
Imports Roslyn.Utilities

Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.EditAndContinue
    Public Class EditAndContinueWorkspaceServiceTests
        <WpfFact>
        Public Async Function ReadOnlyDocumentTest() As Task
            Dim diagnosticService As IDiagnosticAnalyzerService = New EditAndContinueTestHelper.TestDiagnosticAnalyzerService()
            Dim encService As IEditAndContinueWorkspaceService = New EditAndContinueWorkspaceService(diagnosticService)
            Dim workspace = Await EditAndContinueTestHelper.CreateTestWorkspaceAsync()
            Dim currentSolution = workspace.CurrentSolution
            Dim project = currentSolution.Projects(0)

            Dim sessionReason As SessionReadOnlyReason
            Dim projectReason As ProjectReadOnlyReason
            Dim isReadOnly As Boolean

            ' not yet start
            isReadOnly = encService.IsProjectReadOnly(project.Id, sessionReason, projectReason)

            Assert.Equal(ProjectReadOnlyReason.None, projectReason)
            Assert.Equal(SessionReadOnlyReason.None, sessionReason)
            Assert.Equal(False, isReadOnly)

            ' run mode
            encService.StartDebuggingSession(workspace.CurrentSolution)
            isReadOnly = encService.IsProjectReadOnly(project.Id, sessionReason, projectReason)

            Assert.Equal(ProjectReadOnlyReason.None, projectReason)
            Assert.Equal(SessionReadOnlyReason.Running, sessionReason)
            Assert.Equal(True, isReadOnly)

            ' edit mode
            Dim activeStatement = New Dictionary(Of DocumentId, ImmutableArray(Of ActiveStatementSpan))()
            Dim projectStates = ImmutableArray.Create(Of KeyValuePair(Of ProjectId, ProjectReadOnlyReason))(New KeyValuePair(Of ProjectId, ProjectReadOnlyReason)(project.Id, ProjectReadOnlyReason.None))

            encService.StartEditSession(currentSolution, activeStatement, projectStates.ToImmutableDictionary(), stoppedAtException:=False)
            isReadOnly = encService.IsProjectReadOnly(project.Id, sessionReason, projectReason)
            Assert.Equal(ProjectReadOnlyReason.None, projectReason)
            Assert.Equal(SessionReadOnlyReason.None, sessionReason)
            Assert.Equal(False, isReadOnly)

            ' end edit session
            encService.EndEditSession()
            isReadOnly = encService.IsProjectReadOnly(project.Id, sessionReason, projectReason)
            Assert.Equal(ProjectReadOnlyReason.None, projectReason)
            Assert.Equal(SessionReadOnlyReason.Running, sessionReason)
            Assert.Equal(True, isReadOnly)

            ' break mode and stop at exception
            encService.StartEditSession(currentSolution, activeStatement, projectStates.ToImmutableDictionary(), stoppedAtException:=True)
            isReadOnly = encService.IsProjectReadOnly(project.Id, sessionReason, projectReason)
            Assert.Equal(ProjectReadOnlyReason.None, projectReason)
            Assert.Equal(SessionReadOnlyReason.StoppedAtException, sessionReason)
            Assert.Equal(True, isReadOnly)
        End Function

        <WpfFact>
        Public Async Function NotLoadedTest() As Task
            Dim diagnosticService As IDiagnosticAnalyzerService = New EditAndContinueTestHelper.TestDiagnosticAnalyzerService()
            Dim encService As IEditAndContinueWorkspaceService = New EditAndContinueWorkspaceService(diagnosticService)
            Dim workspace = Await EditAndContinueTestHelper.CreateTestWorkspaceAsync()
            Dim currentSolution = workspace.CurrentSolution
            Dim project = currentSolution.Projects(0)

            Dim sessionReason As SessionReadOnlyReason
            Dim projectReason As ProjectReadOnlyReason
            Dim isReadOnly As Boolean

            ' run mode
            encService.StartDebuggingSession(workspace.CurrentSolution)

            ' edit mode
            Dim activeStatement = New Dictionary(Of DocumentId, ImmutableArray(Of ActiveStatementSpan))()
            Dim projectStates = ImmutableArray.Create(Of KeyValuePair(Of ProjectId, ProjectReadOnlyReason))(New KeyValuePair(Of ProjectId, ProjectReadOnlyReason)(project.Id, ProjectReadOnlyReason.NotLoaded))

            encService.StartEditSession(currentSolution, activeStatement, projectStates.ToImmutableDictionary(), stoppedAtException:=False)
            isReadOnly = encService.IsProjectReadOnly(project.Id, sessionReason, projectReason)
            Assert.Equal(ProjectReadOnlyReason.NotLoaded, projectReason)
            Assert.Equal(SessionReadOnlyReason.None, sessionReason)
            Assert.Equal(True, isReadOnly)
        End Function

        <WpfFact>
        Public Async Function MetaDataNotAvailableTest() As Task
            Dim diagnosticService As IDiagnosticAnalyzerService = New EditAndContinueTestHelper.TestDiagnosticAnalyzerService()
            Dim encService As IEditAndContinueWorkspaceService = New EditAndContinueWorkspaceService(diagnosticService)
            Dim workspace = Await EditAndContinueTestHelper.CreateTestWorkspaceAsync()
            Dim currentSolution = workspace.CurrentSolution
            Dim project = currentSolution.Projects(0)

            Dim sessionReason As SessionReadOnlyReason
            Dim projectReason As ProjectReadOnlyReason
            Dim isReadOnly As Boolean

            ' run mode
            encService.StartDebuggingSession(workspace.CurrentSolution)

            ' edit mode with empty project
            Dim activeStatement = New Dictionary(Of DocumentId, ImmutableArray(Of ActiveStatementSpan))()
            Dim projectStates = ImmutableDictionary.Create(Of ProjectId, ProjectReadOnlyReason)

            encService.StartEditSession(currentSolution, activeStatement, projectStates, stoppedAtException:=False)
            isReadOnly = encService.IsProjectReadOnly(project.Id, sessionReason, projectReason)
            Assert.Equal(ProjectReadOnlyReason.MetadataNotAvailable, projectReason)
            Assert.Equal(SessionReadOnlyReason.None, sessionReason)
            Assert.Equal(True, isReadOnly)
        End Function
    End Class

End Namespace


text:
#import <UIKit/UIKit.h>

/** Tint color name. */
typedef NSString *MDCPaletteTint NS_EXTENSIBLE_STRING_ENUM;

/** The name of the tint 50 color when creating a custom palette. */
CG_EXTERN const MDCPaletteTint _Nonnull MDCPaletteTint50Name;

/** The name of the tint 100 color when creating a custom palette. */
CG_EXTERN const MDCPaletteTint _Nonnull MDCPaletteTint100Name;

/** The name of the tint 200 color when creating a custom palette. */
CG_EXTERN const MDCPaletteTint _Nonnull MDCPaletteTint200Name;

/** The name of the tint 300 color when creating a custom palette. */
CG_EXTERN const MDCPaletteTint _Nonnull MDCPaletteTint300Name;

/** The name of the tint 400 color when creating a custom palette. */
CG_EXTERN const MDCPaletteTint _Nonnull MDCPaletteTint400Name;

/** The name of the tint 500 color when creating a custom palette. */
CG_EXTERN const MDCPaletteTint _Nonnull MDCPaletteTint500Name;

/** The name of the tint 600 color when creating a custom palette. */
CG_EXTERN const MDCPaletteTint _Nonnull MDCPaletteTint600Name;

/** The name of the tint 700 color when creating a custom palette. */
CG_EXTERN const MDCPaletteTint _Nonnull MDCPaletteTint700Name;

/** The name of the tint 800 color when creating a custom palette. */
CG_EXTERN const MDCPaletteTint _Nonnull MDCPaletteTint800Name;

/** The name of the tint 900 color when creating a custom palette. */
CG_EXTERN const MDCPaletteTint _Nonnull MDCPaletteTint900Name;

/** Accent color name. */
typedef NSString *MDCPaletteAccent NS_EXTENSIBLE_STRING_ENUM;

/** The name of the accent 100 color when creating a custom palette. */
CG_EXTERN const MDCPaletteAccent _Nonnull MDCPaletteAccent100Name;

/** The name of the accent 200 color when creating a custom palette. */
CG_EXTERN const MDCPaletteAccent _Nonnull MDCPaletteAccent200Name;

/** The name of the accent 400 color when creating a custom palette. */
CG_EXTERN const MDCPaletteAccent _Nonnull MDCPaletteAccent400Name;

/** The name of the accent 700 color when creating a custom palette. */
CG_EXTERN const MDCPaletteAccent _Nonnull MDCPaletteAccent700Name;

/**
 A palette of Material colors.

 Material palettes have a set of named tint colors and an optional set of named accent colors. This
 class provides access to the pre-defined set of Material palettes. MDCPalette objects are
 immutable; it is safe to use them from multiple threads in your app.

 @see https://material.io/go/design-color-theming#color-color-palette
 */
@interface MDCPalette : NSObject

/** The red palette. */
@property(class, nonatomic, readonly, strong, nonnull) MDCPalette *redPalette;

/** The pink palette. */
@property(class, nonatomic, readonly, strong, nonnull) MDCPalette *pinkPalette;

/** The purple palette. */
@property(class, nonatomic, readonly, strong, nonnull) MDCPalette *purplePalette;

/** The deep purple palette. */
@property(class, nonatomic, readonly, strong, nonnull) MDCPalette *deepPurplePalette;

/** The indigo palette. */
@property(class, nonatomic, readonly, strong, nonnull) MDCPalette *indigoPalette;

/** The blue palette. */
@property(class, nonatomic, readonly, strong, nonnull) MDCPalette *bluePalette;

/** The light blue palette. */
@property(class, nonatomic, readonly, strong, nonnull) MDCPalette *lightBluePalette;

/** The cyan palette. */
@property(class, nonatomic, readonly, strong, nonnull) MDCPalette *cyanPalette;

/** The teal palette. */
@property(class, nonatomic, readonly, strong, nonnull) MDCPalette *tealPalette;

/** The green palette. */
@property(class, nonatomic, readonly, strong, nonnull) MDCPalette *greenPalette;

/** The light green palette. */
@property(class, nonatomic, readonly, strong, nonnull) MDCPalette *lightGreenPalette;

/** The lime palette. */
@property(class, nonatomic, readonly, strong, nonnull) MDCPalette *limePalette;

/** The yellow palette. */
@property(class, nonatomic, readonly, strong, nonnull) MDCPalette *yellowPalette;

/** The amber palette. */
@property(class, nonatomic, readonly, strong, nonnull) MDCPalette *amberPalette;

/** The orange palette. */
@property(class, nonatomic, readonly, strong, nonnull) MDCPalette *orangePalette;

/** The deep orange palette. */
@property(class, nonatomic, readonly, strong, nonnull) MDCPalette *deepOrangePalette;

/** The brown palette (no accents). */
@property(class, nonatomic, readonly, strong, nonnull) MDCPalette *brownPalette;

/** The grey palette (no accents). */
@property(class, nonatomic, readonly, strong, nonnull) MDCPalette *greyPalette;

/** The blue grey palette (no accents). */
@property(class, nonatomic, readonly, strong, nonnull) MDCPalette *blueGreyPalette;

/**
 Returns a palette generated from a single target 500 tint color.

 TODO(ajsecord): Document the algorithm used to generate the palette.

 @param target500Color The target "500" color in the palette.
 @return A palette generated with a 500 color matching the target color.
 */
+ (nonnull instancetype)paletteGeneratedFromColor:(nonnull UIColor *)target500Color;

/**
 Returns a palette with a custom set of tints and accents.

 The tints dictionary must have values for each key matching MDCPaletteTint.*Name. The accents
 dictionary, if specified, may have entries for each key matching MDCPaletteAccent.*Name. Missing
 accent values will cause an assert in debug mode and will return +[UIColor clearColor] in release
 mode when the corresponding property is acccessed.

 @param tints A dictionary mapping MDCPaletteTint.*Name keys to UIColors.
 @param accents An optional dictionary mapping MDCPaletteAccent.*Name keys to UIColors.
 @return An palette containing the custom colors.
 */
+ (nonnull instancetype)paletteWithTints:(nonnull NSDictionary<MDCPaletteTint, UIColor *> *)tints
                                 accents:
                                     (nullable NSDictionary<MDCPaletteAccent, UIColor *> *)accents;

/**
 Returns an initialized palette object with a custom set of tints and accents.

 The tints dictionary must have values for each key matching MDCPaletteTint.*Name. The accents
 dictionary, if specified, may have entries for each key matching MDCPaletteAccent.*Name. Missing
 accent values will cause an assert in debug mode and will return +[UIColor clearColor] in release
 mode when the corresponding property is acccessed.

 @param tints A dictionary mapping MDCPaletteTint.*Name keys to UIColors.
 @param accents An optional dictionary mapping MDCPaletteAccent.*Name keys to UIColors.
 @return An initialized MDCPalette object containing the custom colors.
 */
- (nonnull instancetype)initWithTints:(nonnull NSDictionary<MDCPaletteTint, UIColor *> *)tints
                              accents:(nullable NSDictionary<MDCPaletteAccent, UIColor *> *)accents;

/** The 50 tint color, the lightest tint of the palette. */
@property(nonatomic, nonnull, readonly) UIColor *tint50;

/** The 100 tint color. */
@property(nonatomic, nonnull, readonly) UIColor *tint100;

/** The 200 tint color. */
@property(nonatomic, nonnull, readonly) UIColor *tint200;

/** The 300 tint color. */
@property(nonatomic, nonnull, readonly) UIColor *tint300;

/** The 400 tint color. */
@property(nonatomic, nonnull, readonly) UIColor *tint400;

/** The 500 tint color, the representative tint of the palette. */
@property(nonatomic, nonnull, readonly) UIColor *tint500;

/** The 600 tint color. */
@property(nonatomic, nonnull, readonly) UIColor *tint600;

/** The 700 tint color. */
@property(nonatomic, nonnull, readonly) UIColor *tint700;

/** The 800 tint color. */
@property(nonatomic, nonnull, readonly) UIColor *tint800;

/** The 900 tint color, the darkest tint of the palette. */
@property(nonatomic, nonnull, readonly) UIColor *tint900;

/** The A100 accent color, the lightest accent color. */
@property(nonatomic, nullable, readonly) UIColor *accent100;

/** The A200 accent color. */
@property(nonatomic, nullable, readonly) UIColor *accent200;

/** The A400 accent color. */
@property(nonatomic, nullable, readonly) UIColor *accent400;

/** The A700 accent color, the darkest accent color. */
@property(nonatomic, nullable, readonly) UIColor *accent700;

@end


text:
@interface UnitViewController ()

@end

@implementation UnitViewController

#define debug 1

#pragma mark - VIEW
- (void)refreshInterface {
    if (debug == 1) {
        NSLog(@"Running %@ '%@'", self.class, NSStringFromSelector(_cmd));
    }
    if (self.selectedObjectID) {
        CoreDataHelper *cdh = [(AppDelegate *)[[UIApplication sharedApplication] delegate] cdh];
        Unit *unit = (Unit*)[cdh.context existingObjectWithID:self.selectedObjectID error:nil];
        self.nameTextField.text = unit.name;
    }
}

- (void)viewDidLoad {
    if (debug == 1) {
        NSLog(@"Running %@ '%@'", self.class, NSStringFromSelector(_cmd));
    }
    [super viewDidLoad];
    [self hideKeyboardWhenBackgroundIsTapped];
    self.nameTextField.delegate = self;
}

- (void)viewWillAppear:(BOOL)animated {
    if (debug == 1) {
        NSLog(@"Running %@ '%@'", self.class, NSStringFromSelector(_cmd));
    }
    [self refreshInterface];
    [self.nameTextField becomeFirstResponder];
}

- (void)viewDidDisappear:(BOOL)animated {
    if (debug == 1) {
        NSLog(@"Running %@ '%@'", self.class, NSStringFromSelector(_cmd));
    }
    CoreDataHelper *cdh = [(AppDelegate *)[[UIApplication sharedApplication] delegate] cdh];
    [cdh backgroundSaveContext];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"SomethingChanged" object:nil userInfo:nil];
}

#pragma mark - TEXTFIELD
- (void)textFieldDidEndEditing:(UITextField *)textField {
    if (debug==1) {
        NSLog(@"Running %@ '%@'", self.class, NSStringFromSelector(_cmd));
    }
    CoreDataHelper *cdh =
    [(AppDelegate *)[[UIApplication sharedApplication] delegate] cdh];
    Unit *unit =
    (Unit*)[cdh.context existingObjectWithID:self.selectedObjectID
                                       error:nil];
    if (textField == self.nameTextField) {
        unit.name = self.nameTextField.text;
        [[NSNotificationCenter defaultCenter]
         postNotificationName:@"SomethingChanged"
         object:nil];
    }
}

#pragma mark - INTERACTION
- (IBAction)done:(id)sender {
    if (debug==1) {
        NSLog(@"Running %@ '%@'", self.class, NSStringFromSelector(_cmd));
    }
    [self hideKeyboard];
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)hideKeyboardWhenBackgroundIsTapped {
    if (debug==1) {
        NSLog(@"Running %@ '%@'", self.class, NSStringFromSelector(_cmd));
    }
    UITapGestureRecognizer *tgr =
    [[UITapGestureRecognizer alloc] initWithTarget:self
                                            action:@selector(hideKeyboard)];
    [tgr setCancelsTouchesInView:NO];
    [self.view addGestureRecognizer:tgr];
}
- (void)hideKeyboard {
    if (debug==1) {
        NSLog(@"Running %@ '%@'", self.class, NSStringFromSelector(_cmd));
    }
    [self.view endEditing:YES];
}

@end


text:
from collections import OrderedDict

try:
    from django.db.models.options import get_verbose_name
except ImportError:
    from django.utils.text import camel_case_to_spaces as get_verbose_name
from django.db import models
from django.apps import apps

class Options(object):
    def __init__(self, meta, help_text=None):
        self.use_sites = meta.pop('use_sites', False)
        self.use_i18n = meta.pop('use_i18n', False)
        self.use_redirect = meta.pop('use_redirect', False)
        self.use_cache = meta.pop('use_cache', False)
        self.groups = meta.pop('groups', {})
        self.seo_views = meta.pop('seo_views', [])
        self.verbose_name = meta.pop('verbose_name', None)
        self.verbose_name_plural = meta.pop('verbose_name_plural', None)
        self.backends = list(meta.pop('backends', ('path', 'modelinstance', 'model', 'view')))
        self._set_seo_models(meta.pop('seo_models', []))
        self.bulk_help_text = help_text
        self.original_meta = meta
        self.models = OrderedDict()
        self.name = None
        self.elements = None
        self.metadata = None

    def get_model(self, name):
        try:
            return self.models[name]
        except KeyError:
            return None

    def _update_from_name(self, name):
        self.name = name
        self.verbose_name = self.verbose_name or get_verbose_name(name)
        self.verbose_name_plural = self.verbose_name_plural or self.verbose_name + 's'

    def _register_elements(self, elements):
        """ Takes elements from the metadata class and creates a base model for all backend models .
        """
        self.elements = elements

        for key, obj in elements.items():
            obj.contribute_to_class(self.metadata, key)

        # Create the common Django fields
        fields = {}
        for key, obj in elements.items():
            if obj.editable:
                field = obj.get_field()
                if not field.help_text:
                    if key in self.bulk_help_text:
                        field.help_text = self.bulk_help_text[key]
                fields[key] = field

        # 0. Abstract base model with common fields
        base_meta = type('Meta', (), self.original_meta)
        class BaseMeta(base_meta):
            abstract = True
            app_label = 'seo'
        fields['Meta'] = BaseMeta
        # Do we need this?
        fields['__module__'] = __name__ #attrs['__module__']
        self.MetadataBaseModel = type('%sBase' % self.name, (models.Model,), fields)

    def _add_backend(self, backend):
        """ Builds a subclass model for the given backend """
        md_type = backend.verbose_name
        base = backend().get_model(self)
        # TODO: Rename this field
        new_md_attrs = {'_metadata': self.metadata, '__module__': __name__ }

        new_md_meta = {}
        new_md_meta['verbose_name'] = '%s (%s)' % (self.verbose_name, md_type)
        new_md_meta['verbose_name_plural'] = '%s (%s)' % (self.verbose_name_plural, md_type)
        new_md_meta['unique_together'] = base._meta.unique_together
        new_md_attrs['Meta'] = type("Meta", (), new_md_meta)
        new_md_attrs['_metadata_type'] = backend.name
        model = type("%s%s"%(self.name,"".join(md_type.split())), (base, self.MetadataBaseModel), new_md_attrs.copy())
        self.models[backend.name] = model
        # This is a little dangerous, but because we set __module__ to __name__, the model needs tobe accessible here
        globals()[model.__name__] = model

    def _set_seo_models(self, value):
        """ Gets the actual models to be used. """
        seo_models = []
        for model_name in value:
            if "." in model_name:
                app_label, model_name = model_name.split(".", 1)
                model = apps.get_model(app_label, model_name)
                if model:
                    seo_models.append(model)
            else:
                app = models.get_app(model_name)
                if app:
                    seo_models.extend(apps.get_models(app))

        self.seo_models = seo_models


text:
namespace mettle::log {

  counter::counter(indenting_ostream &out)
    : out_(out) {}

  void counter::started_run() {
    tests_ = 0;
    passes_ = 0;
    skips_ = 0;
    failures_ = 0;
    print_counter();
  }

  void counter::ended_run() {
    out_ << std::endl;
  }

  void counter::started_suite(const std::vector<std::string> &) {}
  void counter::ended_suite(const std::vector<std::string> &) {}

  void counter::started_test(const test_name &) {}

  void counter::passed_test(const test_name &, const test_output &,
                            test_duration) {
    tests_++;
    passes_++;
    print_counter();
  }

  void counter::failed_test(const test_name &, const std::string &,
                            const test_output &, test_duration) {
    tests_++;
    failures_++;
    print_counter();
  }

  void counter::skipped_test(const test_name &, const std::string &) {
    tests_++;
    skips_++;
    print_counter();
  }

  void counter::started_file(const test_file &) {}
  void counter::ended_file(const test_file &) {}

  void counter::failed_file(const test_file &, const std::string &) {
    tests_++;
    failures_++;
    print_counter();
  }

  void counter::print_counter() {
    using namespace term;
    format all(sgr::bold);
    format passed(sgr::bold, fg(color::green));
    format skipped(sgr::bold, fg(color::blue));
    format failed(sgr::bold, fg(color::red));

    out_ << "\r[ " << all     << std::setw(3) << tests_    << reset()
         << " | "  << passed  << std::setw(3) << passes_   << reset()
         << " | "  << skipped << std::setw(3) << skips_    << reset()
         << " | "  << failed  << std::setw(3) << failures_ << reset()
         << " ]"   << std::flush;
  }

} // namespace mettle::log


text:
__all__ = ['prompt']

import sys

class prompt(object):
    """How to use
    with prompt('start something!', 'complete!!') as p:
        for something:
            do something
            p.progress()
    """
    def __init__(self, start_msg='start', end_msg='finished.', progress_msg='.'):
        self.s = start_msg
        self.p = progress_msg
        self.e = end_msg

    def __enter__(self):
        print(self.s, end=' ')
        return self

    def __exit__(self, type, value, traceback):
        print(self.e)
        sys.stdout.flush()

    def progress(self, msg=None):
        if msg:
            sys.stdout.write(msg)
        else:
            sys.stdout.write(self.p)
        sys.stdout.flush()


text:
class MapsTest : public CppUnit::TestFixture
{
public:
    void setUp();
    void tearDown();
    CPPUNIT_TEST_SUITE(MapsTest);
    CPPUNIT_TEST(basic);
    CPPUNIT_TEST(paths);
    CPPUNIT_TEST_SUITE_END();
private:
    void basic();
    void paths();

    boost::shared_ptr<blieng::BliengState> _state;
};

#endif


text:
package com.emf.flickring.manager;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.BlockingQueue;

import lombok.extern.slf4j.Slf4j;

import com.emf.flickring.deploy.DeployModule.Constant;
import com.google.common.base.Charsets;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.io.Files;

@Slf4j
public class AlbumConfigHandler implements Runnable {

  /** End of queue. Means that no other file will be processed by the queue controller. */
  public static final File EOQ = new File("file://end-of-queue");

  private final BlockingQueue<File> queue;

  public AlbumConfigHandler(final BlockingQueue<File> queue) {
    Preconditions.checkNotNull(queue);
    this.queue = queue;
  }

  @Override
  public void run() {
    log.info("Album controller is started.");
    try {
      File photo = null;
      while (notEndOfQueue(photo = queue.take())) {
        log.info("{} was taken", photo.getAbsolutePath());
        final String photoName = photo.getName();
        final File parentDir = photo.getParentFile();
        final File controllerFile = new File(parentDir, Constant.DIR_CONTROLLER_FILE_NAME);
        try {
          if (!controllerFile.exists()) {
              Files.touch(controllerFile);
              log.info("Controller file was created {}", controllerFile.getAbsolutePath());
          }
          Files.append(photoName + System.getProperty("line.separator"), controllerFile, Charsets.UTF_8);
          log.info("File name appended to the controller file.");
        } catch (IOException e) {
          log.error("Could not update controller file " + controllerFile.getAbsolutePath(), e);
        }
      }
    } catch (InterruptedException ex) {
      log.error("Queue processing was interrupted.", ex);
    }
    log.info("Album controller will exit.");
  }

  private boolean notEndOfQueue(final File file) {
    final String name1 = file.getAbsolutePath();
    final String name2 = EOQ.getAbsolutePath();
    return !name1.equals(name2);
  }

  /**
   * Checks the current controller file for the photo name. If found indicates photo was uploaded.
   * @return TRUE if photo was uploaded. FALSE otherwise.
   */
  public static boolean isUploaded(final File photo) {
    final File controllerFile = new File(photo.getParentFile(), Constant.DIR_CONTROLLER_FILE_NAME);
    if (!controllerFile.exists()) {
      return false;
    }
    try {
      final List<String> lines = Files.readLines(controllerFile, Charsets.UTF_8);
      for (String line : lines) {
        if (!Strings.isNullOrEmpty(line) && line.equals(photo.getName())) {
          return true;
        }
      }
      return false;
    } catch (IOException e) {
      log.error("Could not read controller file", e);
    }
    return true; // In the case of not being  able to determine if file is uploaded, return TRUE to prevent duplicity.
  }
}


text:
package io.github.galop_proxy.galop.proxy;

import io.github.galop_proxy.galop.configuration.TargetConfiguration;

import javax.inject.Inject;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;

import static io.github.galop_proxy.api.commons.Preconditions.checkNotNull;

final class TargetSocketFactoryImpl implements TargetSocketFactory {

    private final TargetConfiguration configuration;

    @Inject
    TargetSocketFactoryImpl(final TargetConfiguration configuration) {
        this.configuration = checkNotNull(configuration, "configuration");
    }

    @Override
    public Socket create() throws IOException {

        final InetAddress address = configuration.getAddress();
        final int port = configuration.getPort().getValue();
        final int timeout = configuration.getConnectionTimeout();

        final Socket socket = new Socket();
        socket.connect(new InetSocketAddress(address, port), timeout);
        return socket;

    }

}


text:
parfil
======

Particle filter playground


text:
const fs = require(`fs-extra`)
const { spawnSync } = require(`child_process`)
const path = require(`path`)
const os = require(`os`)
const _ = require(`lodash`)
const {
  ON_PRE_BOOTSTRAP_FILE_PATH,
  ON_POST_BUILD_FILE_PATH,
} = require(`../utils/constants`)
const { selectConfiguration } = require(`../utils/select-configuration`)
const { loadState } = require(`../utils/load-state`)
const { diff } = require(`../utils/nodes-diff`)

const getNodesSubStateByPlugins = (state, pluginNamesArray) =>
  _.mapValues(state.nodes, stateShard => {
    const filteredMap = new Map()

    stateShard.forEach(node => {
      if (pluginNamesArray.includes(node.internal.owner)) {
        filteredMap.set(node.id, node)
      }
    })

    return filteredMap
  })

const getDiskCacheSnapshotSubStateByPlugins = (state, pluginNamesArray) =>
  _.mapValues(state.diskCacheSnapshot, stateShard =>
    _.pick(stateShard, pluginNamesArray)
  )

jest.setTimeout(100000)

const gatsbyBin = path.join(`node_modules`, `gatsby`, `cli.js`)

const { compareState } = require(`../utils/nodes-diff`)

const stdio = `inherit`

const build = ({ updatePlugins } = {}) => {
  spawnSync(process.execPath, [gatsbyBin, `clean`], { stdio })
  selectConfiguration(1)

  let processOutput

  // First run, get state
  processOutput = spawnSync(process.execPath, [gatsbyBin, `build`], {
    stdio,
    env: {
      ...process.env,
      NODE_ENV: `production`,
    },
  })

  if (processOutput.status !== 0) {
    throw new Error(`Gatsby exited with non zero code`)
  }

  const preBootstrapStateFromFirstRun = loadState(ON_PRE_BOOTSTRAP_FILE_PATH)

  const postBuildStateFromFirstRun = loadState(ON_POST_BUILD_FILE_PATH)

  if (updatePlugins) {
    // Invalidations
    selectConfiguration(2)
  }

  // Second run, get state and compare with state from previous run
  processOutput = spawnSync(process.execPath, [gatsbyBin, `build`], {
    stdio,
    env: {
      ...process.env,
      NODE_ENV: `production`,
    },
  })

  if (processOutput.status !== 0) {
    throw new Error(`Gatsby exited with non zero code`)
  }

  const preBootstrapStateFromSecondRun = loadState(ON_PRE_BOOTSTRAP_FILE_PATH)

  const postBuildStateFromSecondRun = loadState(ON_POST_BUILD_FILE_PATH)

  return {
    nodes: {
      preBootstrapStateFromFirstRun: preBootstrapStateFromFirstRun.nodes,
      postBuildStateFromFirstRun: postBuildStateFromFirstRun.nodes,
      preBootstrapStateFromSecondRun: preBootstrapStateFromSecondRun.nodes,
      postBuildStateFromSecondRun: postBuildStateFromSecondRun.nodes,
    },
    diskCacheSnapshot: {
      preBootstrapStateFromFirstRun:
        preBootstrapStateFromFirstRun.diskCacheSnapshot,
      postBuildStateFromFirstRun: postBuildStateFromFirstRun.diskCacheSnapshot,
      preBootstrapStateFromSecondRun:
        preBootstrapStateFromSecondRun.diskCacheSnapshot,
      postBuildStateFromSecondRun:
        postBuildStateFromSecondRun.diskCacheSnapshot,
    },
    queryResults: {
      firstRun: postBuildStateFromFirstRun.queryResults,
      secondRun: postBuildStateFromSecondRun.queryResults,
    },
  }
}

beforeAll(async () => {
  selectConfiguration(1)
})

afterAll(() => {
  // go back to initial
  selectConfiguration(1)

  // delete saved states
  if (fs.existsSync(ON_PRE_BOOTSTRAP_FILE_PATH)) {
    fs.unlinkSync(ON_PRE_BOOTSTRAP_FILE_PATH)
  }
  if (fs.existsSync(ON_POST_BUILD_FILE_PATH)) {
    fs.unlinkSync(ON_POST_BUILD_FILE_PATH)
  }
})

describe(`nothing changed between gatsby runs`, () => {
  let states

  beforeAll(() => {
    states = build({
      updatePlugins: false,
    })
  })

  describe(`Nodes`, () => {
    it(`nodes are persisted between builds when nothing changes`, () => {
      const {
        nodes: {
          preBootstrapStateFromFirstRun,
          postBuildStateFromFirstRun,
          preBootstrapStateFromSecondRun,
          postBuildStateFromSecondRun,
        },
      } = states

      expect(preBootstrapStateFromFirstRun.size).toEqual(0)
      // sanity check to make sure there are any nodes after first run
      expect(postBuildStateFromFirstRun.size).toBeGreaterThan(0)
      // no nodes where invalidated if nothing changes
      expect(postBuildStateFromFirstRun).toEqual(preBootstrapStateFromSecondRun)
      // final nodes store is the same after first and second run
      expect(postBuildStateFromFirstRun).toEqual(postBuildStateFromSecondRun)
    })
  })
})

describe(`Some plugins changed between gatsby runs`, () => {
  let states

  beforeAll(() => {
    states = build({
      updatePlugins: true,
    })
  })

  describe(`Nodes`, () => {
    const getNodesTestArgs = (states, plugins) => {
      const nodesSubState = getNodesSubStateByPlugins(states, plugins)

      return {
        ...nodesSubState,
        compareState,
      }
    }

    it(`Sanity checks`, () => {
      // preconditions - we expect our cache to be empty on first run
      expect(states.nodes.preBootstrapStateFromFirstRun.size).toEqual(0)
    })

    describe(`Source plugins without transformers`, () => {
      it(`Not changing plugin doesn't invalidate nodes created by it`, () => {
        const {
          plugins,
          nodesTest,
        } = require(`../plugins/source/no-changes/scenario`)

        nodesTest(getNodesTestArgs(states, plugins))
      })

      it(`Adding plugin adds new node`, () => {
        const {
          plugins,
          nodesTest,
        } = require(`../plugins/source/plugin-added/scenario`)

        nodesTest(getNodesTestArgs(states, plugins))
      })

      it(`Removing plugin clears nodes owned by it`, () => {
        const {
          plugins,
          nodesTest,
        } = require(`../plugins/source/plugin-removed/scenario`)

        nodesTest(getNodesTestArgs(states, plugins))
      })

      it(`Changing plugin clears nodes owned by it and recreate nodes`, () => {
        const {
          plugins,
          nodesTest,
        } = require(`../plugins/source/plugin-changed/scenario`)

        nodesTest(getNodesTestArgs(states, plugins))
      })
    })

    describe(`Source plugins with transformers (child nodes)`, () => {
      describe(`Changes to source plugins`, () => {
        it(`Adding source plugin cause transformers to create child nodes`, () => {
          const {
            plugins,
            nodesTest,
          } = require(`../plugins/source-and-transformers-child-nodes/source-added/scenario`)

          nodesTest(getNodesTestArgs(states, plugins))
        })

        it(`Removing source plugin invalidate nodes owned by it and all children nodes`, () => {
          const {
            plugins,
            nodesTest,
          } = require(`../plugins/source-and-transformers-child-nodes/source-removed/scenario`)

          nodesTest(getNodesTestArgs(states, plugins))
        })

        it(`Changing source plugin invalidate nodes owned by it and all children nodes and recreates all nodes`, () => {
          const {
            plugins,
            nodesTest,
          } = require(`../plugins/source-and-transformers-child-nodes/source-changed/scenario`)

          nodesTest(getNodesTestArgs(states, plugins))
        })
      })

      describe(`Changes to transformer plugins`, () => {
        it(`Adding transformer adds child nodes to existing nodes`, () => {
          const {
            plugins,
            nodesTest,
          } = require(`../plugins/source-and-transformers-child-nodes/transformer-added/scenario`)

          nodesTest(getNodesTestArgs(states, plugins))
        })

        it(`Removing transformer clear nodes owned by it and remove children from parent nodes`, () => {
          const {
            plugins,
            nodesTest,
          } = require(`../plugins/source-and-transformers-child-nodes/transformer-removed/scenario`)

          nodesTest(getNodesTestArgs(states, plugins))
        })

        it(`Changing transformer clears and recreates nodes owned by it`, () => {
          const {
            plugins,
            nodesTest,
          } = require(`../plugins/source-and-transformers-child-nodes/transformer-changed/scenario`)

          nodesTest(getNodesTestArgs(states, plugins))
        })
      })
    })

    describe(`Source plugins with transformers (node fields)`, () => {
      describe(`Changes to source plugins`, () => {
        it(`Adding source plugin creates a node with fields`, () => {
          const {
            plugins,
            nodesTest,
          } = require(`../plugins/source-and-transformers-node-fields/source-added/scenario`)

          nodesTest(getNodesTestArgs(states, plugins))
        })

        it(`Changing source plugin clears and recreates nodes owned by it`, () => {
          const {
            plugins,
            nodesTest,
          } = require(`../plugins/source-and-transformers-node-fields/source-changed/scenario`)

          nodesTest(getNodesTestArgs(states, plugins))
        })
      })

      describe(`Changes to transformer plugins`, () => {
        it(`Adding transformer adds fields to node created by source plugin`, () => {
          const {
            plugins,
            nodesTest,
          } = require(`../plugins/source-and-transformers-node-fields/transformer-added/scenario`)

          nodesTest(getNodesTestArgs(states, plugins))
        })

        it(`Removing transformer removes fields from node created by source plugin`, () => {
          const {
            plugins,
            nodesTest,
          } = require(`../plugins/source-and-transformers-node-fields/transformer-removed/scenario`)

          nodesTest(getNodesTestArgs(states, plugins))
        })

        it(`Changing transformer removes fields from node created by source plugin and recreate fields`, () => {
          const {
            plugins,
            nodesTest,
          } = require(`../plugins/source-and-transformers-node-fields/transformer-changed/scenario`)

          nodesTest(getNodesTestArgs(states, plugins))
        })
      })
    })
  })

  describe(`Persisted key-value store (cache)`, () => {
    it(`Preserve disk cache if owner plugin did not changed`, () => {
      const {
        persistedKeyValueStoreTest,
        plugins,
      } = require(`../plugins/key-value-cache/no-changes/scenario`)

      persistedKeyValueStoreTest(
        getDiskCacheSnapshotSubStateByPlugins(states, plugins)
      )
    })

    it(`Removing owner plugin clears disk cache`, () => {
      const {
        persistedKeyValueStoreTest,
        plugins,
      } = require(`../plugins/key-value-cache/plugin-removed/scenario`)

      persistedKeyValueStoreTest(
        getDiskCacheSnapshotSubStateByPlugins(states, plugins)
      )
    })

    it(`Adding owner plugin creates disk cache`, () => {
      const {
        persistedKeyValueStoreTest,
        plugins,
      } = require(`../plugins/key-value-cache/plugin-added/scenario`)

      persistedKeyValueStoreTest(
        getDiskCacheSnapshotSubStateByPlugins(states, plugins)
      )
    })

    it(`Changing owner plugin clears disk cache and recreates it`, () => {
      const {
        persistedKeyValueStoreTest,
        plugins,
      } = require(`../plugins/key-value-cache/plugin-changed/scenario`)

      persistedKeyValueStoreTest(
        getDiskCacheSnapshotSubStateByPlugins(states, plugins)
      )
    })
  })

  describe(`Query results`, () => {
    const getQueryResultTestArgs = scenarioName => {
      if (os.platform() === "win32") {
        scenarioName = scenarioName.replace("/", "\\")
      }

      const result = {
        dataFirstRun: states.queryResults.firstRun[scenarioName].data,
        dataSecondRun: states.queryResults.secondRun[scenarioName].data,
        typesFirstRun: states.queryResults.firstRun[scenarioName].types,
        typesSecondRun: states.queryResults.secondRun[scenarioName].types,
      }

      if (result.dataFirstRun && result.dataSecondRun) {
        result.dataDiff = diff(result.dataFirstRun, result.dataSecondRun)
      }

      if (result.typesFirstRun && result.typesSecondRun) {
        result.typesDiff = diff(result.typesFirstRun, result.typesSecondRun)
      }

      return result
    }

    describe(`Source plugins without transformers`, () => {
      it(`Not changing plugin doesn't change query results`, () => {
        const scenarioName = `source/no-changes`
        const { queriesTest } = require(`../plugins/${scenarioName}/scenario`)

        queriesTest(getQueryResultTestArgs(scenarioName))
      })

      it(`Adding plugin adds a type to schema`, () => {
        const scenarioName = `source/plugin-added`
        const { queriesTest } = require(`../plugins/${scenarioName}/scenario`)

        queriesTest(getQueryResultTestArgs(scenarioName))
      })

      it(`Removing plugin removes a type from schema`, () => {
        const scenarioName = `source/plugin-removed`
        const { queriesTest } = require(`../plugins/${scenarioName}/scenario`)

        queriesTest(getQueryResultTestArgs(scenarioName))
      })

      it(`Changing plugin invalidates query results`, () => {
        const scenarioName = `source/plugin-changed`
        const { queriesTest } = require(`../plugins/${scenarioName}/scenario`)

        queriesTest(getQueryResultTestArgs(scenarioName))
      })
    })

    describe(`Source plugins with transformers`, () => {
      describe(`Changes to source plugins`, () => {
        it(`Adding source plugin creates parent and child types in schema and they are queryable on second run`, () => {
          const scenarioName = `source-and-transformers-child-nodes/source-added`
          const { queriesTest } = require(`../plugins/${scenarioName}/scenario`)

          queriesTest(getQueryResultTestArgs(scenarioName))
        })

        it(`Removing source plugin removes parent and child types from schema and they are queryable on first run`, () => {
          const scenarioName = `source-and-transformers-child-nodes/source-removed`
          const { queriesTest } = require(`../plugins/${scenarioName}/scenario`)

          queriesTest(getQueryResultTestArgs(scenarioName))
        })

        it(`Changing source plugin adjust schema and query result changes just certain fields`, () => {
          const scenarioName = `source-and-transformers-child-nodes/source-changed`
          const { queriesTest } = require(`../plugins/${scenarioName}/scenario`)

          queriesTest(getQueryResultTestArgs(scenarioName))
        })
      })

      describe(`Changes to transformer plugins`, () => {
        it(`Adding transformer plugin adds child type to schema and updates query result`, () => {
          const scenarioName = `source-and-transformers-child-nodes/transformer-added`
          const { queriesTest } = require(`../plugins/${scenarioName}/scenario`)

          queriesTest(getQueryResultTestArgs(scenarioName))
        })

        it(`Removing transformer plugin removes child type from schema and updates query result`, () => {
          const scenarioName = `source-and-transformers-child-nodes/transformer-removed`
          const { queriesTest } = require(`../plugins/${scenarioName}/scenario`)

          queriesTest(getQueryResultTestArgs(scenarioName))
        })

        it(`Changing transformer plugin adjusts schema and query result changes just certain fields`, () => {
          const scenarioName = `source-and-transformers-child-nodes/transformer-changed`
          const { queriesTest } = require(`../plugins/${scenarioName}/scenario`)

          queriesTest(getQueryResultTestArgs(scenarioName))
        })
      })
    })

    describe(`Source plugins with transformers (node fields)`, () => {
      describe(`Changes to source plugins`, () => {
        it(`Adding source plugin creates node and node field types in schema and they are queryable on second run`, () => {
          const scenarioName = `source-and-transformers-node-fields/source-added`
          const { queriesTest } = require(`../plugins/${scenarioName}/scenario`)

          queriesTest(getQueryResultTestArgs(scenarioName))
        })

        it(`Changing source plugin adjusts schema and they are queryable on second run`, () => {
          const scenarioName = `source-and-transformers-node-fields/source-changed`
          const { queriesTest } = require(`../plugins/${scenarioName}/scenario`)

          queriesTest(getQueryResultTestArgs(scenarioName))
        })
      })

      describe(`Changes to transformer plugins`, () => {
        it(`Adding transformer plugin adds fields type to schema and updates query result`, () => {
          const scenarioName = `source-and-transformers-node-fields/transformer-added`
          const { queriesTest } = require(`../plugins/${scenarioName}/scenario`)

          queriesTest(getQueryResultTestArgs(scenarioName))
        })

        it(`Removing transformer plugin removes fields type from schema and updates query result`, () => {
          const scenarioName = `source-and-transformers-node-fields/transformer-removed`
          const { queriesTest } = require(`../plugins/${scenarioName}/scenario`)

          queriesTest(getQueryResultTestArgs(scenarioName))
        })

        it(`Changing transformer plugin adjusts schema and query result changes just certain fields`, () => {
          const scenarioName = `source-and-transformers-node-fields/transformer-changed`
          const { queriesTest } = require(`../plugins/${scenarioName}/scenario`)

          queriesTest(getQueryResultTestArgs(scenarioName))
        })
      })
    })
  })
})


text:
.. module:: alchemlyb.convergence

Assessing convergence
=====================

For a result to be valid, we need to ensure that longer simulation time would not result in different results, i.e., that our results are *converged*. The :mod:`alchemlyb.convergence`  module provides functions to assess the convergence of free energy estimates or other quantities.

Time Convergence
----------------
One way of determining the simulation end point is to compute and plot the
forward and backward convergence of the estimate using
:func:`~alchemlyb.convergence.forward_backward_convergence` and
:func:`~alchemlyb.visualisation.plot_convergence` [Klimovich2015]_. ::

    >>> from alchemtest.gmx import load_benzene
    >>> from alchemlyb.parsing.gmx import extract_u_nk
    >>> from alchemlyb.visualisation import plot_convergence
    >>> from alchemlyb.convergence import forward_backward_convergence

    >>> bz = load_benzene().data
    >>> data_list = [extract_u_nk(xvg, T=300) for xvg in bz['Coulomb']]
    >>> df = forward_backward_convergence(data_list, 'mbar')
    >>> ax = plot_convergence(df)
    >>> ax.figure.savefig('dF_t.pdf')

Will give a plot looks like this

.. figure:: images/dF_t.png

   A convergence plot of showing that the forward and backward has converged
   fully.

Fractional equilibration time
-----------------------------
Another way of assessing whether the simulation has converged is to check the
energy files. In [Fan2021]_ (and [Fan2020]_), :math:`R_c` and
:math:`A_c` are two criteria of checking the
convergence. :func:`~alchemlyb.convergence.fwdrev_cumavg_Rc` takes a decorrelated
:class:`pandas.Series` as input and gives the metric
:math:`R_c`, which is 0 for fully-equilibrated
simulation and 1 for fully-unequilibrated simulation. ::

    >>> from alchemtest.gmx import load_ABFE
    >>> from alchemlyb.parsing.gmx import extract_dHdl
    >>> from alchemlyb.preprocessing import decorrelate_dhdl, dhdl2series
    >>> from alchemlyb.convergence import fwdrev_cumavg_Rc
    >>> from alchemlyb.visualisation import plot_convergence

    >>> file = load_ABFE().data['ligand'][0]
    >>> dhdl = extract_dHdl(file, T=300)
    >>> decorrelated = decorrelate_dhdl(dhdl, remove_burnin=True)
    >>> R_c, running_average = fwdrev_cumavg_Rc(dhdl2series(decorrelated), tol=2)
    >>> print(R_c)
    0.04
    >>> ax = plot_convergence(running_average, final_error=2)
    >>> ax.set_ylabel("$\partial H/\partial\lambda$ (in kT)")

Will give a plot like this.

.. figure:: images/R_c.png

The :func:`~alchemlyb.convergence.A_c` on the other hand, takes in a list of
decorrelated :class:`pandas.Series` and gives a metric of how converged the set
is, where 0 fully-unequilibrated and 1.0 is fully-equilibrated. ::

    >>> from alchemlyb.convergence import A_c
    >>> dhdl_list = []
    >>> for file in load_ABFE().data['ligand']:
    >>>     dhdl = extract_dHdl(file, T=300)
    >>>     decorrelated = decorrelate_dhdl(dhdl, remove_burnin=True)
    >>>     decorrelated = dhdl2series(decorrelated)
    >>>     dhdl_list.append(decorrelated)
    >>> value = A_c(dhdl_list, tol=2)
    0.7085

Convergence functions
---------------------

Convergence functions are available from :mod:`alchemlyb.convergence`. Internally, they are imported from submodules, as documented below.

.. currentmodule:: alchemlyb.convergence

.. autosummary::
    :toctree: convergence

    convergence


text:
import React from 'react';
import {COLORS, WORKFLOW_GRID} from '../../styles';
import {PlusButton} from "./PlusButton";

export const EditableArrowBlock = ({ onClick }) => {
    return(
        <div style={{
            paddingTop: '14px',
            width: WORKFLOW_GRID.ARROW_BLOCK_WIDTH + 'px'
        }}>
            <div
                style={{
                textAlign: 'center',
                fontSize: '33px',
                color: COLORS.PRIMARY,
                paddingBottom: '2px'
            }}>
                →
            </div>
            <PlusButton onClick={onClick}/>
        </div>
    );
};


text:
<?php

namespace Realboard\Component\Database\DBInstance\DBInterface;

interface ServiceHandlerInterface
{
    /**
     * @param \Realboard\Component\Database\DBInstance\DBInterface\AuthenticationInterface           $authentication
     * @param array|\Realboard\Component\Database\DBInstance\DBInterface\ConnectionStringInterface[] $connectionStrings
     */
    public function __construct(AuthenticationInterface $authentication, array $connectionStrings = array(), $logDir = null);

    /**
     * Get DBInstance Response Data.
     *
     * @param array  $config
     * @param string $sql
     * @param int    $limit
     * @param int    $offset
     * @param bool   $single
     * @param string $key
     * @param string $responseType
     *
     * @return array
     */
    public function getResult(array $config = array(), $sql = '', $limit = 0, $offset = 0, $single = false, $key = null, $responseType = null);

    /**
     * [getAvailableDrivers description].
     *
     * @return [type] [description]
     */
    public function getAvailableDrivers();
}


text:
<?php

namespace Ice\ExternalUserBundle\Form\Type;

use Symfony\Component\Form\FormBuilderInterface,
    Symfony\Component\OptionsResolver\OptionsResolverInterface,
    Symfony\Component\Form\AbstractType;

class SetPasswordFormType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('plainPassword', 'text', array(
                'description' => 'Plain text password. Encoded before User is persisted.',
                'required' => true,
            ))
        ;
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Ice\ExternalUserBundle\Entity\User',
            'csrf_protection' => false,
            'validation_groups' => array('rest_set_password'),
        ));
    }

    public function getName()
    {
        return '';
    }
}


text:
//
// Copyright (c) Microsoft.  All rights reserved.
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//    http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.

namespace Microsoft.Azure.Management.ApiManagement.Tests.ScenarioTests.ResourceProviderTests
{
    using global::ApiManagement.Tests;
    using Microsoft.Azure.Management.ApiManagement.Models;
    using Microsoft.Azure.Management.Resources;
    using Microsoft.Azure.Test;
    using Microsoft.WindowsAzure.Management;
    using Xunit;

    public partial class ResourceProviderFunctionalTests : TestBase, IUseFixture<TestsFixture>
    {
        private ManagementClient _managmentClient;
        private ResourceManagementClient _resourceManagementClient;
        private ApiManagementClient _apiManagementClient;

        public string Location { get; set; }
        public string ResourceGroupName { get; set; }
        public string ApiManagementServiceName { get; set; }

        public ManagementClient ManagmentClient
        {
            get
            {
                if (_managmentClient == null)
                {
                    _managmentClient = ApiManagementHelper.GetManagementClient();
                }
                return _managmentClient;
            }
        }

        public ResourceManagementClient ResourceManagementClient
        {
            get
            {
                if (_resourceManagementClient == null)
                {
                    _resourceManagementClient = ApiManagementHelper.GetResourceManagementClient();
                }
                return _resourceManagementClient;
            }
        }

        public ApiManagementClient ApiManagementClient
        {
            get
            {
                if (_apiManagementClient == null)
                {
                    _apiManagementClient = ApiManagementHelper.GetApiManagementClient();
                }
                return _apiManagementClient;
            }
        }

        public void SetFixture(TestsFixture testsFixture)
        {
        }

        protected void TryCreateApiService(SkuType skuType = SkuType.Developer)
        {
            this.ResourceGroupName = this.ResourceManagementClient.TryGetResourceGroup(Location);
            this.Location = this.ManagmentClient.TryGetLocation("West US");

            if (string.IsNullOrWhiteSpace(ResourceGroupName))
            {
                ResourceGroupName = TestUtilities.GenerateName("Api-Default");
                this.ResourceManagementClient.TryRegisterResourceGroup(Location, ResourceGroupName);
            }

            ApiManagementServiceName = TestUtilities.GenerateName("hydraapimservice");
            this.ApiManagementClient.TryCreateApiService(ResourceGroupName, ApiManagementServiceName, Location, skuType);
        }
    }
}