text:
package ar.edu.ungs.presentation.base.table;

import java.util.List;

import ar.edu.ungs.business.dto.DepositoDTO;

public class DepositoTableModel extends BaseTableModel<DepositoDTO>{

	private static final long serialVersionUID = 1L;

	private static Object[] COLUMNS = new String[] { "Nombre", "Temp. Max.", "Temp. Min." };

	public DepositoTableModel(List<DepositoDTO> depositos) {
		super(COLUMNS, depositos.size());
		setElementos(depositos);
	}

	@Override
	public int getColumnCount() {
		return COLUMNS.length;
	}

	@Override
	public Object getValueAt(int row, int column) {
		DepositoDTO value = getModelValue(row);
		switch (column) {
		case 0:
			return (value.getNombre() != null ? value.getNombre() : "");
		case 1:
			return (value.getTemperaturaMaxima() != null ? value.getTemperaturaMaxima() : "");
		case 2:
			return (value.getTemperaturaMinima() != null ? value.getTemperaturaMinima() : "");
		default:
			return null;
		}
	}

	@Override
	public void addRow(DepositoDTO item) {
		getElementos().add(item);
		Object[] vector = new Object[3];
		vector[0] = item.getNombre();
		vector[1] = item.getTemperaturaMaxima();
		vector[2] = item.getTemperaturaMinima();
		super.addRow(vector);
	}
}

redpajama_set_name: RedPajamaGithub


text:
(function () {
    'use strict';

    angular
        .module('auth')
        .config(config);

    config.$inject = [
        '$stateProvider',
        '$urlRouterProvider',
        '$locationProvider'
    ];

    function config($stateProvider, $urlRouterProvider, $locationProvider) {
        $urlRouterProvider.otherwise('/login');
        $stateProvider
            .state('home', {
                url: '/home',
                views: {
                    'nav': { templateUrl: 'views/auth/layouts/nav.html' },
                    'content': {
                        templateUrl: 'views/auth/home.html'
                    }
                }
            })
            .state('login', {
                url: '/login',
                views: {
                    'nav': { templateUrl: 'views/auth/layouts/nav.html' },
                    'content': {
                        templateUrl: 'views/auth/login.html'
                    }
                }
            })
            .state('register', {
                url: '/register',
                views: {
                    'nav': { templateUrl: 'views/auth/layouts/nav.html' },
                    'content': {
                        templateUrl: 'views/auth/register.html'
                    }
                }
            })
            .state('forgot', {
                url: '/password/reset',
                views: {
                    'nav': { templateUrl: 'views/auth/layouts/nav.html' },
                    'content': {
                        templateUrl: 'views/auth/passwords/forgot.html'
                    }
                }
            })
            .state('reset', {
                url: '/password/reset/:token',
                views: {
                    'nav': { templateUrl: 'views/auth/layouts/nav.html' },
                    'content': {
                        templateUrl: 'views/auth/passwords/reset.html'
                    }
                }
            });
        $locationProvider.html5Mode(true);
    }
})();


text:
package com.thoughtworks.go.server.util;

import org.eclipse.jetty.http.HttpURI;
import org.eclipse.jetty.server.Request;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.mockito.Mockito.when;

@ExtendWith(MockitoExtension.class)
public class Jetty9RequestTest {
    private Jetty9Request jetty9Request;
    @Mock(strictness = Mock.Strictness.LENIENT)
    private Request request;

    @BeforeEach
    public void setUp() throws Exception {
        jetty9Request = new Jetty9Request(request);
        when(request.getHttpURI()).thenReturn(new HttpURI("foo/bar/baz"));
        when(request.getRootURL()).thenReturn(new StringBuilder("http://junk/"));
    }

    @Test
    public void shouldGetUrl() {
        assertThat(jetty9Request.getUrl(), is("http://junk/foo/bar/baz"));
    }

    @Test
    public void shouldGetUriPath() {
        assertThat(jetty9Request.getUriPath(), is("foo/bar/baz"));
    }

    @Test
    public void shouldGetUriAsString() {
        assertThat(jetty9Request.getUriAsString(), is("foo/bar/baz"));
    }

    @Test
    public void shouldSetRequestUri() {
        HttpURI requestUri = new HttpURI("foo/bar/baz");
        when(request.getHttpURI()).thenReturn(requestUri);
        jetty9Request.setRequestURI("foo/junk?a=b&c=d");
        assertThat(requestUri.getPath(), is("foo/junk"));
        assertThat(requestUri.getQuery(), is("a=b&c=d"));
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Xamarin.Forms;
using XPlatformFeedReader.Pages;

namespace XPlatformFeedReader {
	public class App : Application {
		public App() {
			// The root page of your application
			MainPage = new FeedOverview();

		}

		protected override void OnStart() {
			// Handle when your app starts
		}

		protected override void OnSleep() {
			// Handle when your app sleeps
		}

		protected override void OnResume() {
			// Handle when your app resumes
		}
	}
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Consp. fung. (Leipzig) 332 (1805)

#### Original name
Peziza nigripes var. sylvatica Alb. & Schwein.

### Remarks
null


text:
title: "Event [0]"
href: Event_0
class: intest
subtitle: WAITING FOR TEST
layout: default
modal-id: 126
date: 2017-05-21
img: event_0_gameplay.jpg
thumbnail: event_0.jpg
alt: image-alt
game-date:
developer:
category:
multiplayer:
description: WORK IN PROGRESS
---


text:
<?php

namespace Keevitaja\TranslationsModule\Commands;

use Illuminate\Translation\Translator;
use Keevitaja\TranslationsModule\Bundle\Contract\BundleRepositoryInterface;

class AddTranslationLines
{
    /**
     * Add translation lines to Laravel Translator system
     *
     * @param \Keevitaja\TranslationsModule\Bundle\Contract\BundleRepositoryInterface $bundle
     * @param \Illuminate\Translation\Translator $translator
     *
     * @return void
     */
    public function handle(BundleRepositoryInterface $bundle, Translator $translator)
    {
        $locales = config('streams::locales.enabled', []);
        $default = config('streams::locales.default');
        $container = [];

        $cacheExpires = config('keevitaja.module.translations::configuration.cache_expires');

        $bundles = cache()->remember('keevitaja.translations', $cacheExpires, function() use($bundle) {
            return $bundle->all()->load('translatables', 'translatables.translations');
        });

        foreach($locales as $locale) {
            foreach ($bundles as $b) {
                foreach ($b->translatables as $t) {
                    $key = $b->slug.'.'.$t->slug;

                    $translated = $t->translate($locale);

                    if (isset($translated->string)) {
                        $container[$locale][$key] = $translated->string;
                    } else {
                        $translated = $t->translate($default);

                        if (isset($translated->string)) {
                            $container[$locale][$key] = $translated->string;
                        }
                    }
                }
            }
        }

        foreach ($container as $locale => $lines) {
            $translator->addLines($lines, $locale);
        }
    }
}


text:
layout: post
title: Developing Web Apps in Haskell
tags: haskell web-UI
---
Find a way to develop web apps using Haskell.

Ideally, should be able to develop an app using Haskell, which can then be
compiled into a web app, running HTML + CSS + JS.

Alternatively, should be able to run in a desktop environment having bindings
to webkit or similars.

Should Haskell be compiled to JS or should Haskell have a binding to JS, just
like it would porbably have bindings to HTML and CSS?

Check out GHCJS and reflex (and reflex.dom).

Also this: https://www.reddit.com/r/haskell/comments/3wxggs/whats_the_best_way_to_create_gui_for_haskell/


text:
package org.opencloudb.net;

import java.nio.channels.CompletionHandler;

import org.apache.log4j.Logger;
import org.opencloudb.MycatServer;

/**
 * @author mycat
 */
public final class AIOConnector implements SocketConnector,
		CompletionHandler<Void, BackendAIOConnection> {
	private static final Logger LOGGER = Logger.getLogger(AIOConnector.class);
	private static final ConnectIdGenerator ID_GENERATOR = new ConnectIdGenerator();

	public AIOConnector() {

	}

	@Override
	public void completed(Void result, BackendAIOConnection attachment) {
		finishConnect(attachment);
	}

	@Override
	public void failed(Throwable exc, BackendAIOConnection conn) {
		conn.onConnectFailed(exc);
	}

	private void finishConnect(BackendAIOConnection c) {
		try {
			if (c.finishConnect()) {
				c.setId(ID_GENERATOR.getId());
				NIOProcessor processor = MycatServer.getInstance()
						.nextProcessor();
				c.setProcessor(processor);
				c.register();
			}
		} catch (Throwable e) {
			c.onConnectFailed(e);
			LOGGER.info("connect err " + e);
			c.close(e.toString());
		}
	}

	/**
	 * 后端连接ID生成器
	 *
	 * @author mycat
	 */
	private static class ConnectIdGenerator {

		private static final long MAX_VALUE = Long.MAX_VALUE;

		private long connectId = 0L;
		private final Object lock = new Object();

		private long getId() {
			synchronized (lock) {
				if (connectId >= MAX_VALUE) {
					connectId = 0L;
				}
				return ++connectId;
			}
		}
	}

}


text:
class AddFieldsForSpamDetection < ActiveRecord::Migration
  def change
    add_column :users, :spammer, :boolean
    add_column :users, :spam_count, :integer, default: 0
    add_index :users, :spammer
  end
end


text:
PERMISSIONS = {
  '*': ('create', # can create an object
        'read',   # can read an object, viewing it's details
        'update', # can update an object
        'delete', # can delete an object,
        'list'),  # can view a list of the objects
  'animals.animal': ('add_offspring',),
}

# assigns the permissions that each group should have, here creating an Administrator group with
# authority to create and change users
GROUP_PERMISSIONS = {
    "Administrator": ('auth.user.*',)
}


text:
var interestController = require('./interestController.js');

module.exports = function (app) {
  app.route('/:idea_id')
    .post(interestController.newInterest)
    .get(interestController.allInterests);

  app.route('/:interest_id')
    .delete(interestController.deleteInterest);
};


text:
namespace HanRuEdu.LDAL
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;

    [MetadataType(typeof(EDU_OAXT_51_A01_DXJL_metadata))]
    public partial class EDU_OAXT_51_A01_DXJL
    {
        public EDU_OAXT_51_A01_DXJL()
        {
            Sender = "";
            Recipien = "";
            RecipienNumber = "";
            Date = DateTime.Now;
            Content = "";
        }
        public class EDU_OAXT_51_A01_DXJL_metadata
        {
            [Required(ErrorMessage = "±ØÌî")]
            [Display(Name = "񅧏")]
            public Int32 ID { get; set; }

            [Required(ErrorMessage = "±ØÌî")]
            [Display(Name = "ѧУ")]
            public Int32 SCHOOLID { get; set; }

            [Required(ErrorMessage = "±ØÌî",AllowEmptyStrings = true)]
            [Display(Name = "·¢ËÍÈË")]
            [StringLength(200)]
            [DisplayFormat(ConvertEmptyStringToNull = false)]
            public String Sender { get; set; }

            [Required(ErrorMessage = "±ØÌî",AllowEmptyStrings = true)]
            [Display(Name = "ÊÕ¼þÈË")]
            [DisplayFormat(ConvertEmptyStringToNull = false)]
            public String Recipien { get; set; }

            [Required(ErrorMessage = "±ØÌî",AllowEmptyStrings = true)]
            [Display(Name = "ÊÕ¼þÈ˺ÅÂë")]
            [DisplayFormat(ConvertEmptyStringToNull = false)]
            public String RecipienNumber { get; set; }

            [Required(ErrorMessage = "±ØÌî")]
            [Display(Name = "·¢ËÍʱ¼ä")]
            public DateTime Date { get; set; }

            [Required(ErrorMessage = "±ØÌî",AllowEmptyStrings = true)]
            [Display(Name = "ÐÅÏ¢ÄÚÈÝ")]
            [DisplayFormat(ConvertEmptyStringToNull = false)]
            public String Content { get; set; }

        }
    }
}


text:
gin::WrapperInfo PDFPluginPlaceholder::kWrapperInfo = {gin::kEmbedderNativeGin};

// static
PDFPluginPlaceholder* PDFPluginPlaceholder::CreatePDFPlaceholder(
    content::RenderFrame* render_frame,
    const blink::WebPluginParams& params) {
  std::string html_data = GetPDFPlaceholderHTML(params.url);
  return new PDFPluginPlaceholder(render_frame, params, html_data);
}

PDFPluginPlaceholder::PDFPluginPlaceholder(content::RenderFrame* render_frame,
                                           const blink::WebPluginParams& params,
                                           const std::string& html_data)
    : plugins::PluginPlaceholderBase(render_frame, params, html_data) {}

PDFPluginPlaceholder::~PDFPluginPlaceholder() {}

v8::Local<v8::Value> PDFPluginPlaceholder::GetV8Handle(v8::Isolate* isolate) {
  return gin::CreateHandle(isolate, this).ToV8();
}

gin::ObjectTemplateBuilder PDFPluginPlaceholder::GetObjectTemplateBuilder(
    v8::Isolate* isolate) {
  gin::ObjectTemplateBuilder builder =
      gin::Wrappable<PDFPluginPlaceholder>::GetObjectTemplateBuilder(isolate)
          .SetMethod<void (PDFPluginPlaceholder::*)()>(
              "openPDF", &PDFPluginPlaceholder::OpenPDFCallback);

  if (base::CommandLine::ForCurrentProcess()->HasSwitch(
          switches::kEnablePluginPlaceholderTesting)) {
    builder.SetMethod<void (PDFPluginPlaceholder::*)()>(
        "notifyPlaceholderReadyForTesting",
        &PDFPluginPlaceholder::NotifyPlaceholderReadyForTestingCallback);
  }

  return builder;
}

void PDFPluginPlaceholder::OpenPDFCallback() {
  ReportPDFLoadStatus(PDFLoadStatus::kViewPdfClickedInPdfPluginPlaceholder);
  mojo::AssociatedRemote<chrome::mojom::PluginHost> plugin_host;
  render_frame()->GetRemoteAssociatedInterfaces()->GetInterface(
      plugin_host.BindNewEndpointAndPassReceiver());
  plugin_host->OpenPDF(GetPluginParams().url);
}


text:
var express = require('express');
var spawn   = require('child_process').spawn;
var app = express();
var fs = require('fs');
var PORT = 8001;
var nodemailer = require('nodemailer');
var Cron = require('./model/cron/cron.js');
var bodyParser = require('body-parser');
var Db = require('./controller/db/db.js');
var Report = require('./model/report/report.js');
var cors = require('cors');

app.use(cors());
app.use(express.static(__dirname));
app.use(bodyParser.json());

/*******************************/
/* POST */
/*******************************/

app.post('/cron/', function(req, res){
  var cronAux = new Cron(req.body);
  cronAux.save(Db.localDb, res);
});

/*******************************/
/* GET */
/*******************************/

app.get('/', function(req, res){
  res.header('Access-Control-Allow-Origin', "*")
  res.json({"resPONSE":"working"});
});

app.get('/cron/', function(req, res){
  res.header('Access-Control-Allow-Origin', "*")
  Cron.listAll(Db.localDb, function(err, resp){
    if (err) res.json({"error": err})
    res.json(resp);
  });
});

app.get('/cron/:id', function(req, res){
  if(req.params.id !== undefined && req.params.id !== ""){
    Cron.getOne(Db.localDb, req.params.id, function(err, resp){
      if (err) res.json({"error": err})
      res.json(resp);
    })
  } else
    res.json({"error": "missing id"});
});

app.get('/report/', function(req, res){
  res.header('Access-Control-Allow-Origin', "*")
  Report.listAll(Db.localDb, function(err, resp){
    if (err) res.json({"error": err})
    res.json(resp);
  });
});

app.get('/report/:id', function(req, res){
  if(req.params.id !== undefined && req.params.id !== ""){
    Report.getOne(Db.localDb, req.params.id, function(err, resp){
      if (err) res.json({"error": err})
      res.json(resp);
    })
  } else
    res.json({"error": "missing id"});
});

/*******************************/
/* PUT */
/*******************************/

app.put('/cron/:id', function(req, res){
  if(req.params.id !== undefined && req.params.id !== ""){
    Cron.updateOne(Db.localDb, req.params.id, req.body, function(err, resp){
      if (err) res.json({"error": err})
      res.json(resp);
    })
  } else
    res.json({"error": "missing id"});
});

/*******************************/
/* DELETE */
/*******************************/

app.delete('/cron/:id', function(req, res){
  Cron.deleteOne(Db.localDb, req.params, res);
})

app.delete('/report/:id', function(req, res){
  Report.deleteOne(Db.localDb, req.params, res);
})

app.listen(PORT);


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

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

  <!-- JSF configuration -->

  <!-- Indicates the stage of the initialized application. Set the project stage to "Development", "UnitTest", "SystemTest", or "Production". See http://myfaces.apache.org/core20/myfaces-impl/webconfig.html#javax_faces_PROJECT_STAGE -->
  <context-param>
    <param-name>javax.faces.PROJECT_STAGE</param-name>
    <param-value>Debug</param-value>
  </context-param>

  <!-- Strip XML comments out of Facelets before delivering to the client. See http://myfaces.apache.org/core20/myfaces-impl/webconfig.html#javax_faces_FACELETS_SKIP_COMMENTS -->
  <context-param>
    <param-name>javax.faces.FACELETS_SKIP_COMMENTS</param-name>
    <param-value>true</param-value>
  </context-param>

  <!-- JSF Servlet is defined to container. -->
  <servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <!-- Mapping with servlet and url for the http requests. -->
  <servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>/faces/*</url-pattern>
  </servlet-mapping>

  <!-- /JSF configuration -->

  <!-- Web application configuration -->
  <session-config>
    <session-timeout>30</session-timeout>
  </session-config>

  <welcome-file-list>
    <welcome-file>faces/index.xhtml</welcome-file>
  </welcome-file-list>

  <display-name>oss-process-scrum</display-name>

  <!-- FIXME
  Workaround for IllegalStateException: Cannot create a session after the response has been committed
  See http://stackoverflow.com/a/8072445 for additional workarounds.
  -->
  <context-param>
    <param-name>com.sun.faces.writeStateAtFormEnd</param-name>
    <param-value>false</param-value>
  </context-param>

  <!-- MIME type mapping for WOFF and EOT fonts. See http://www.w3.org/TR/WOFF/#appendix-b https://developer.mozilla.org/en/CSS/@font-face#Notes https://developer.mozilla.org/en/About_WOFF -->
  <mime-mapping>
    <extension>woff</extension>
    <mime-type>application/font-woff</mime-type>
  </mime-mapping>

  <mime-mapping>
    <extension>eot</extension>
    <mime-type>application/octet-stream</mime-type>
  </mime-mapping>
</web-app>


text:
package com.chen.jdbc.service;

import com.chen.jdbc.dao.ForumDao;
import com.chen.jdbc.domain.Forum;
import org.springframework.stereotype.Service;

/**
 * Created by LeifChen on 2017/6/7.
 */
@Service
public class ForumService {

    private ForumDao forumDao;

    public void setForumDao(ForumDao forumDao) {
        this.forumDao = forumDao;
    }

    // 初始化
    public void initForum() {
        forumDao.initDb();
    }

    // 插入记录
    public void addForum(Forum forum) {
        forumDao.addForum(forum);
    }

}


text:
---
layout: post
title: Labyrinth TDD
excerpt: "A TDD exercise from SQLi Team to complete in less than 3H"
tags: [TDD, java, architecture, eng]
comments: true
image:
  feature: header/tech/red-green.jpg
---

## Introduction

This is another TDD exercise from SQLi Team to complete in less than 3H.

It was quite challenging, I got stuck at the 5th or the 6th test, I wasn't able to go further without breaking the already passed tests... and this is the point, never trust your feelings in software development, trusts your TDDs instead.

Here is the main TDD class:

{% highlight java %}

public class LabyrinthShould {

    /**
     * each letter represent a room
     * each | represent a gate between two room
     * each $ represent a gate with a sensor on
     **/
    @Test
    public void be_Walkable_Till_The_End() {
        Labyrinth labyrinth = new Labyrinth("A$B", "A$C", "C|E", "B$D", "B|E", "E$F", "D$F", "F|G");
        labyrinth.popIn("A");
        labyrinth.walkTo("B");
        labyrinth.walkTo("E");
        labyrinth.walkTo("F");
        labyrinth.walkTo("G");
    }

    @Test(expected = IllegalMoveException.class)
    public void refuse_Illegal_Move() {
        Labyrinth labyrinth = new Labyrinth("A$B", "A$C", "B$D");
        labyrinth.popIn("A");
        labyrinth.walkTo("B");
        labyrinth.walkTo("E"); // room E does not exist in the labyrinth
    }

    @Test(expected = IllegalMoveException.class)
    public void refuse_Move_Without_Path() {
        Labyrinth labyrinth = new Labyrinth("A$B", "A$C", "B$D");
        labyrinth.popIn("A");
        labyrinth.walkTo("B");
        labyrinth.walkTo("C"); // Can not reach C from B
    }

    @Test
    public void allow_Cyclic_Path() {
        Labyrinth labyrinth = new Labyrinth("A$B", "A$C", "C|E", "B$D", "B|E", "E$F", "D$F", "F|G");
        labyrinth.popIn("A");
        labyrinth.walkTo("B");
        labyrinth.walkTo("D");
        labyrinth.walkTo("F");
        labyrinth.walkTo("E");
        labyrinth.walkTo("B");
        labyrinth.walkTo("D");
        labyrinth.walkTo("F");
        labyrinth.walkTo("G");
    }

    @Test
    public void allow_Back_And_Forth() {
        Labyrinth labyrinth = new Labyrinth("A$B", "A$C", "C|E", "B$D", "B|E", "E$F", "D$F", "F|G");
        labyrinth.popIn("A");
        labyrinth.walkTo("C");
        labyrinth.walkTo("A");
        labyrinth.walkTo("B");
        labyrinth.walkTo("D");
    }

    @Test
    public void allow_Walker_To_Close_Passed_Door() {
        Labyrinth labyrinth = new Labyrinth("A$B", "A$C", "C|E", "B$D", "B|E", "E$F", "D$F", "F|G");
        labyrinth.popIn("A");
        labyrinth.walkTo("B");
        labyrinth.walkTo("D");
        labyrinth.walkTo("F");
        labyrinth.closeLastDoor();
        labyrinth.walkTo("G");
    }

    @Test(expected = DoorAlreadyClosedException.class)
    public void allow_Walker_To_Close_Only_Last_Door() {
        Labyrinth labyrinth = new Labyrinth("A$B", "A$C", "C|E", "B$D", "B|E", "E$F", "D$F", "F|G");
        labyrinth.popIn("A");
        labyrinth.walkTo("B");
        labyrinth.walkTo("D");
        labyrinth.walkTo("F");
        labyrinth.closeLastDoor();
        labyrinth.closeLastDoor();
        labyrinth.walkTo("G");
    }

    @Test(expected = ClosedDoorException.class)
    public void not_Allow_Closed_Door_Crossing() {
        Labyrinth labyrinth = new Labyrinth("A$B", "A$C", "C|E", "B$D", "B|E", "E$F", "D$F", "F|G");
        labyrinth.popIn("A");
        labyrinth.walkTo("B");
        labyrinth.walkTo("D");
        labyrinth.closeLastDoor();
        labyrinth.walkTo("F");
        labyrinth.walkTo("E");
        labyrinth.walkTo("B");
        labyrinth.walkTo("D");
        labyrinth.walkTo("F");
        labyrinth.walkTo("G");
    }

    @Test(expected = ClosedDoorException.class)
    public void not_Allow_Turn_Back_Through_Closed_Door() {
        Labyrinth labyrinth = new Labyrinth("A$B", "A$C", "C|E", "B$D", "B|E", "E$F", "D$F", "F|G");
        labyrinth.popIn("A");
        labyrinth.walkTo("B");
        labyrinth.walkTo("D");
        labyrinth.closeLastDoor();
        labyrinth.walkTo("B");
    }

    @Test
    public void follow_Walker() {
        Labyrinth labyrinth = new Labyrinth("A$B", "A$C", "B$D", "D$E", "D$F", "F$H", "D$F");
        labyrinth.popIn("A");
        labyrinth.walkTo("B");
        assertThat(labyrinth.readSensors()).isEqualTo("AB");
        labyrinth.walkTo("D");
        assertThat(labyrinth.readSensors()).isEqualTo("AB;BD");
        labyrinth.walkTo("F");
        assertThat(labyrinth.readSensors()).isEqualTo("AB;BD;DF");
    }

    @Test
    public void follow_Walker_Through_Unmonitored_Path() {
        Labyrinth labyrinth = new Labyrinth("A$B", "A$C", "C|E", "B$D", "B|E", "E$F", "D$F", "F|G");
        labyrinth.popIn("A");
        labyrinth.walkTo("B");
        assertThat(labyrinth.readSensors()).isEqualTo("AB");
        labyrinth.walkTo("E");
        labyrinth.walkTo("F");
        assertThat(labyrinth.readSensors()).isEqualTo("AB;EF");
        labyrinth.walkTo("G");
        assertThat(labyrinth.readSensors()).isEqualTo("AB;EF");
    }
}

{% endhighlight %}

You can find my first solution (under the time pressure) in this [GitHub repo](https://github.com/fayway/LabyrinthTDD){:target="_blank"}

## TODO

Now that all tests are green, next step is to refactor my mess in better SOLID Clean Code.


text:
<?php
class API extends CI_Controller {

	// function __construct()
	// {
	// 	parent::__construct();
	// 	 // $this->load->model('user_dashboard_model');

	// }
	 public function view(){
	      $golfdata = json_decode(
    	file_get_contents("https://api.sportradar.us/golf-t1/schedule/pga/2015/tournaments/schedule.json?api_key=rwppn9ub7aqmde94djw23ggm")
		);

            if (empty($golfdata))
        {
            show_404();
        }else{

	 		// $data['data'] = array($this->$golfdata);
	 		$data['data'] = array('golfdata' => $golfdata);
	 		// $data['title'] = 'Home';
	 		// $data['content'] = 'Welcome to my website';

            $this->load->view('templates/header_li');
            $this->load->view('pages/user_dashboard', $data);
            $this->load->view('templates/footer');
        }

	}
}


text:
// Copyright 2012 Google Inc. 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.

package v201308.orderservice;

import com.google.api.ads.dfp.lib.DfpService;
import com.google.api.ads.dfp.lib.DfpServiceLogger;
import com.google.api.ads.dfp.lib.DfpUser;
import com.google.api.ads.dfp.v201308.Order;
import com.google.api.ads.dfp.v201308.OrderServiceInterface;

/**
 * This example creates new orders. To determine which orders exist, run
 * GetAllOrdersExample.java. To determine which companies are advertisers, run
 * GetCompaniesByStatementExample.java. To get salespeople and traffickers, run
 * GetAllUsersExample.java.
 *
 * Tags: OrderService.createOrders
 *
 * @author api.arogal@gmail.com (Adam Rogal)
 */
public class CreateOrdersExample {
  public static void main(String[] args) {
    try {
      // Log SOAP XML request and response.
      DfpServiceLogger.log();

      // Get DfpUser from "~/dfp.properties".
      DfpUser user = new DfpUser();

      // Get the OrderService.
      OrderServiceInterface orderService =
          user.getService(DfpService.V201308.ORDER_SERVICE);

      // Set the advertiser (company), salesperson, and trafficker to assign to
      // each order.
      Long advertiserId = Long.parseLong("INSERT_ADVERTISER_COMPANY_ID_HERE");
      Long salespersonId = Long.parseLong("INSERT_SALESPERSON_ID_HERE");
      Long traffickerId = Long.parseLong("INSERT_TRAFFICKER_ID_HERE");

      // Create an array to store local order objects.
      Order[] orders = new Order[5];

      for (int i = 0; i < 5; i++) {
        Order order = new Order();
        order.setName("Order #" + i);
        order.setAdvertiserId(advertiserId);
        order.setSalespersonId(salespersonId);
        order.setTraffickerId(traffickerId);

        orders[i] = order;
      }

      // Create the orders on the server.
      orders = orderService.createOrders(orders);

      if (orders != null) {
        for (Order order : orders) {
          System.out.println("An order with ID \""
              + order.getId() + "\" and named \"" + order.getName() + "\" was created.");
        }
      } else {
        System.out.println("No orders created.");
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}


text:
"use strict";

var fs = require('graceful-fs');
var bowerJson = require('bower-json');
var async = require('async');

function snap() {

    // Read project Bower file
    bowerJson.read('./bower.json', {validate: false}, function (err, json) {
        if (err) {
            console.error('There was an error reading the file');
            console.error(err.message);
            return;
        }

        var updatedVersions = [];
        var dependencies = json.dependencies;

        async.forEachOf(json.dependencies, function (version, dependency, seriesCallback) {

                var filename = 'bower_components/' + dependency + '/.bower.json';

                // Now that we got the filename, we can read its contents
                bowerJson.read(filename, {validate: false}, function (err, jsonComponent) {
                    if (err) {
                        console.error('There was an error reading the file');
                        console.error(err.message);
                        seriesCallback(null);
                        return;
                    }

                    //console.log(dependency + ' : ' + version + ' -> ' + jsonComponent.version);
                    updatedVersions.push({dependency: dependency, version: jsonComponent.version});
                    seriesCallback(null);
                });
            },
            function (err) {

                // Update package versions
                for (var i = 0; i < updatedVersions.length; i++) {
                    for (var key in dependencies) {
                        if (updatedVersions[i].dependency === key) {
                            dependencies[key] = updatedVersions[i].version;
                            break;
                        }
                    }
                }

                // Persist
                var outputFilename = 'bower.json';

                fs.writeFile(outputFilename, JSON.stringify(json, null, 4), function (err) {
                    if (err) {
                        console.log(err);
                    } else {
                        console.log("JSON saved to " + outputFilename);
                    }
                });
            });
    });
}

module.exports = snap;


text:
using namespace std;

const int main_minimum_lambda = 120;

int main(int argc, char** argv) {
  // generate a keyset
  TFheGateBootstrappingParameterSet* params =
      new_default_gate_bootstrapping_parameters(main_minimum_lambda);

  // generate a random key
  // Note: In real applications, a cryptographically secure seed needs to be
  // used.
  uint32_t seed[] = {314, 1592, 657};
  tfhe_random_generator_setSeed(seed, 3);
  TFheGateBootstrappingSecretKeySet* key =
      new_random_gate_bootstrapping_secret_keyset(params);
  const TFheGateBootstrappingCloudKeySet* cloud_key = &key->cloud;

  // create inputs.
  int x = 4052;
  int y = 913;

  cout << "inputs are " << x << " and " << y << ", sum: " << x + y << endl;
  // Encrypt data
  auto ciphertext_x = Tfhe<int>::Encrypt(x, key);
  auto ciphertext_y = Tfhe<int>::Encrypt(y, key);

  cout << "Encryption done" << endl;

  cout << "Initial state check by decryption: " << endl;
  // Decrypt results.
  cout << ciphertext_x.Decrypt(key);
  cout << "  ";
  cout << ciphertext_y.Decrypt(key);

  cout << "\n";

  cout << "\t\t\t\t\tServer side computation:" << endl;
  // Perform addition
  Tfhe<int> cipher_result(params);
  XLS_CHECK_OK(
      simple_sum(cipher_result, ciphertext_x, ciphertext_y, cloud_key));

  cout << "\t\t\t\t\tComputation done" << endl;

  cout << "Decrypted result: " << cipher_result.Decrypt(key) << "\n";

  cout << "Decryption done" << endl;
}


text:
var http = require("http"); // node.js is importing the http library. Httpt library is able to run as a webserver. with this we will have object  called http that has all capabilities of http library.

http.createServer(function (request, response) { // object http calls a method "createserver" which will start a webserver.

	console.log("Request received."); // consloe.log will show up clients request on console (terminal)
   // Send the HTTP header
   // HTTP Status: 200 : OK
   // Content Type: text/plain
   response.writeHead(200, {'Content-Type': 'text/plain'});

   // Send the response body as "Hello World"
   response.end('Hello World\n');
}).listen(8081);

// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');


text:
package sword.langbook.db

import org.scalatest.{FlatSpec, Matchers}
import sword.db.MemoryStorageManager

class LinkedStorageManagerTest extends FlatSpec with Matchers {

  private def newManager = {
    LinkedStorageManager(defs => new MemoryStorageManager(defs))
  }

  behavior of "LinkedStorageManager"

  it can "be created" in {
    newManager
  }

  it should "not repeat field definitions across registers" in {
    val regDefs = newManager.registerDefinitions
    val fields = regDefs.flatMap(_.fields)
    fields.toSet.size shouldBe fields.size
  }

  it can "insert a concept" in {
    val manager = newManager
    manager.concepts shouldBe empty

    val conceptOption = Concept.from(manager, "MyConcept")
    conceptOption shouldBe defined

    val concepts = manager.concepts
    concepts.size shouldBe 1
    concepts.values.head shouldBe conceptOption.get
  }

  it can "insert a symbol" in {
    val manager = newManager
    manager.symbols shouldBe empty

    val symbolOption = Symbol.from(manager, 'a')
    symbolOption shouldBe defined

    val symbols = manager.symbols
    symbols.size shouldBe 1
    symbols.values.head shouldBe symbolOption.get
  }

  private def checkAllSymbolsInserted(manager: LinkedStorageManager, text: String, newCharCount: Int) = {
    val initCharCount = manager.symbols.size

    val arrayOption = SymbolArray.from(manager, text)
    arrayOption shouldBe defined

    val symbols = manager.symbols
    symbols.size shouldBe (initCharCount + newCharCount)

    val unicodes = symbols.values.map(_.unicode).toSet
    for (char <- text) {
      unicodes.contains(char.toInt) shouldBe true
    }

    arrayOption.get.size shouldBe text.length
    arrayOption.get.map(_.unicode).zip(text.map(_.toInt)).foreach {
      case (given, expected) =>
        given shouldBe expected
    }
  }

  it can "insert a symbol array for all different chars" in {
    val manager = newManager
    manager.symbols shouldBe empty

    checkAllSymbolsInserted(manager, "Hola", 4)
  }

  it can "insert a symbol array for some repeated chars" in {
    val manager = newManager
    manager.symbols shouldBe empty

    checkAllSymbolsInserted(newManager, "Hello", 4)
  }

  it should "not add new symbols on adding the same symbol array again" in {
    val manager = newManager
    manager.symbols shouldBe empty

    checkAllSymbolsInserted(manager, "Hola", 4)
    checkAllSymbolsInserted(manager, "Hola", 0)
  }

  it should "only insert missing symbols on adding a second symbol array" in {
    val manager = newManager
    manager.symbols shouldBe empty

    checkAllSymbolsInserted(manager, "Hola", 4)
    checkAllSymbolsInserted(manager, "Hello", 1) // Only 'e' was missing
  }

  it can "insert a word" in {
    val manager = newManager
    val kanji = Concept.from(manager, "kanji").flatMap(Alphabet.from(manager, _)).get
    val japanese = Concept.from(manager, "Japanese").flatMap(Language.from(manager, _, "ja", kanji)).get
    val word = Word.from(manager, japanese).get
    word.language shouldBe japanese
  }

  it should "recognise words linked to the same concept as synonym only if they belong to the same language" in {
    val manager = newManager
    val latin = Concept.from(manager, "Latin").flatMap(Alphabet.from(manager,_)).get
    val english = Concept.from(manager, "English").flatMap(Language.from(manager, _, "en", latin)).get

    val bigWord = Word.from(manager, english).get
    val largeWord = Word.from(manager, english).get

    bigWord.synonyms shouldBe empty
    largeWord.synonyms shouldBe empty

    bigWord.concepts shouldBe empty
    val concept = Concept.from(manager, "Big").get
    bigWord.concepts += concept
    bigWord.concepts.size shouldBe 1
    bigWord.concepts.head shouldBe concept

    bigWord.synonyms shouldBe empty
    largeWord.synonyms shouldBe empty

    largeWord.concepts shouldBe empty
    largeWord.concepts += concept
    largeWord.concepts.size shouldBe 1
    largeWord.concepts.head shouldBe concept

    bigWord.synonyms should not contain bigWord
    largeWord.synonyms should not contain largeWord

    bigWord.synonyms should contain (largeWord)
    largeWord.synonyms should contain (bigWord)
  }

  it should "recognise words linked to the same concept as synonym only if they belong to the same language (reusing set instances)" in {
    val manager = newManager
    val latin = Concept.from(manager, "Latin").flatMap(Alphabet.from(manager,_)).get
    val english = Concept.from(manager, "English").flatMap(Language.from(manager, _, "en", latin)).get

    val bigWord = Word.from(manager, english).get
    val largeWord = Word.from(manager, english).get

    val bigSynonyms = bigWord.synonyms
    val largeSynonyms = largeWord.synonyms
    val bigConcepts = bigWord.concepts
    val largeConcepts = largeWord.concepts

    bigSynonyms shouldBe empty
    largeSynonyms shouldBe empty
    bigConcepts shouldBe empty

    val concept = Concept.from(manager, "Big").get
    bigConcepts += concept
    bigConcepts.size shouldBe 1
    bigConcepts.head shouldBe concept

    bigSynonyms shouldBe empty
    largeSynonyms shouldBe empty

    largeConcepts shouldBe empty
    largeConcepts += concept
    largeConcepts.size shouldBe 1
    largeConcepts.head shouldBe concept

    bigSynonyms should not contain bigWord
    largeSynonyms should not contain largeWord

    bigSynonyms should contain (largeWord)
    largeSynonyms should contain (bigWord)
  }

  it should "not recognise words linked to the same concept as translation if they belong to the same language" in {
    val manager = newManager
    val latin = Concept.from(manager, "Latin").flatMap(Alphabet.from(manager, _)).get
    val english = Concept.from(manager, "English").flatMap(Language.from(manager, _, "en", latin)).get

    val bigWord = Word.from(manager, english).get
    val largeWord = Word.from(manager, english).get

    bigWord.concepts shouldBe empty
    val concept = Concept.from(manager, "Big").get
    bigWord.concepts += concept
    largeWord.concepts += concept

    bigWord.translations shouldBe empty
    largeWord.translations shouldBe empty
  }

  it should "recognise words linked to the same concept as translations only if they belong to different languages" in {
    val manager = newManager
    val latin = Concept.from(manager, "Latin").flatMap(Alphabet.from(manager,_)).get
    val english = Concept.from(manager, "English").flatMap(Language.from(manager, _, "en", latin)).get
    val spanish = Concept.from(manager, "Spanish").flatMap(Language.from(manager, _, "es", latin)).get

    val enWord = Word.from(manager, english).get
    val spWord = Word.from(manager, spanish).get

    enWord.translations shouldBe empty
    spWord.translations shouldBe empty

    enWord.concepts shouldBe empty
    val concept = Concept.from(manager, "White").get
    enWord.concepts += concept
    enWord.concepts.size shouldBe 1
    enWord.concepts.head shouldBe concept

    enWord.translations shouldBe empty
    spWord.translations shouldBe empty

    spWord.concepts shouldBe empty
    spWord.concepts += concept
    spWord.concepts.size shouldBe 1
    spWord.concepts.head shouldBe concept

    enWord.translations should not contain enWord
    spWord.translations should not contain spWord

    enWord.translations should contain (spWord)
    spWord.translations should contain (enWord)
  }

  it should "recognise words linked to the same concept as translation only if they belong to different languages (reusing set instances)" in {
    val manager = newManager
    val latin = Concept.from(manager, "Latin").flatMap(Alphabet.from(manager,_)).get
    val english = Concept.from(manager, "English").flatMap(Language.from(manager, _,"en",  latin)).get
    val spanish = Concept.from(manager, "Spanish").flatMap(Language.from(manager, _,"es",  latin)).get

    val enWord = Word.from(manager, english).get
    val spWord = Word.from(manager, spanish).get

    val enTranslations = enWord.translations
    val spTranslations = spWord.translations
    val enConcepts = enWord.concepts
    val spConcepts = spWord.concepts

    enTranslations shouldBe empty
    spTranslations shouldBe empty
    enConcepts shouldBe empty

    val concept = Concept.from(manager, "White").get
    enConcepts += concept
    enConcepts.size shouldBe 1
    enConcepts.head shouldBe concept

    enTranslations shouldBe empty
    spTranslations shouldBe empty

    spConcepts shouldBe empty
    spConcepts += concept
    spConcepts.size shouldBe 1
    spConcepts.head shouldBe concept

    enTranslations should not contain enWord
    spTranslations should not contain spWord

    enTranslations should contain (spWord)
    spTranslations should contain (enWord)
  }

  it should "not recognise words linked to the same concept as synonyms if they belong to different languages" in {
    val manager = newManager
    val latin = Concept.from(manager, "Latin").flatMap(Alphabet.from(manager,_)).get
    val english = Concept.from(manager, "English").flatMap(Language.from(manager, _, "en", latin)).get
    val spanish = Concept.from(manager, "Spanish").flatMap(Language.from(manager, _, "es", latin)).get

    val enWord = Word.from(manager, english).get
    val spWord = Word.from(manager, spanish).get

    enWord.concepts shouldBe empty
    val concept = Concept.from(manager, "White").get
    enWord.concepts += concept
    spWord.concepts += concept

    enWord.synonyms shouldBe empty
    spWord.synonyms shouldBe empty
  }
}


text:
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type

DOCUMENTATION = """
---
cliconf: slxos
short_description: Use slxos cliconf to run command on Extreme SLX-OS platform
description:
  - This slxos plugin provides low level abstraction apis for
    sending and receiving CLI commands from Extreme SLX-OS network devices.
version_added: "2.6"
"""

import re
import json

from itertools import chain

from ansible.module_utils._text import to_bytes, to_text
from ansible.module_utils.network.common.utils import to_list
from ansible.plugins.cliconf import CliconfBase

class Cliconf(CliconfBase):

    def get_device_info(self):
        device_info = {}

        device_info['network_os'] = 'slxos'
        reply = self.get('show version')
        data = to_text(reply, errors='surrogate_or_strict').strip()

        match = re.search(r'SLX\-OS Operating System Version: (\S+)', data)
        if match:
            device_info['network_os_version'] = match.group(1)

        reply = self.get('show chassis')
        data = to_text(reply, errors='surrogate_or_strict').strip()

        match = re.search(r'^Chassis Name:(\s+)(\S+)', data, re.M)
        if match:
            device_info['network_os_model'] = match.group(2)

        reply = self.get('show running-config | inc "switch-attributes host-name"')
        data = to_text(reply, errors='surrogate_or_strict').strip()

        match = re.search(r'switch-attributes host-name (\S+)', data, re.M)
        if match:
            device_info['network_os_hostname'] = match.group(1)

        return device_info

    def get_config(self, source='running', flags=None):
        if source not in ('running', 'startup'):
            raise ValueError("fetching configuration from %s is not supported" % source)
        if source == 'running':
            cmd = 'show running-config'
        else:
            cmd = 'show startup-config'

        flags = [] if flags is None else flags
        cmd += ' '.join(flags)
        cmd = cmd.strip()

        return self.send_command(cmd)

    def edit_config(self, command):
        for cmd in chain(['configure terminal'], to_list(command), ['end']):
            if isinstance(cmd, dict):
                command = cmd['command']
                prompt = cmd['prompt']
                answer = cmd['answer']
                newline = cmd.get('newline', True)
            else:
                command = cmd
                prompt = None
                answer = None
                newline = True

            self.send_command(command, prompt, answer, False, newline)

    def get(self, command, prompt=None, answer=None, sendonly=False, check_all=False):
        return self.send_command(command=command, prompt=prompt, answer=answer, sendonly=sendonly, check_all=check_all)

    def get_capabilities(self):
        result = super(Cliconf, self).get_capabilities()
        return json.dumps(result)


text:
package com.studio4plus.homerplayer.util;

import java.io.File;
import java.io.FileFilter;

public class OrFilter implements FileFilter {

    private final FileFilter[] filters;

    public OrFilter(FileFilter... filters) {
        this.filters = filters;
    }

    @Override
    public boolean accept(File pathname) {
        for (FileFilter filter : filters) {
            if (filter.accept(pathname))
                return true;
        }
        return false;
    }
}


text:
import 'jest';

import formatDate from '../src/formatDate';

const fixer = require('../dist');

const accessKey = process.env.FIXER_API_KEY;

const someDate = new Date();
const formattedDate = formatDate(someDate);

describe('#forDate', () => {
  it('should get data based date as a string', async () => {
    const result = await fixer.forDate(formattedDate, {
      access_key: accessKey
    });

    expect(result).toMatchObject({
      base: 'EUR',
      date: formattedDate,
      rates: expect.objectContaining({
        USD: expect.any(Number),
        EUR: 1,
        GBP: expect.any(Number)
      }),
      success: true,
      timestamp: expect.any(Number)
    });
  });

  it('should get data based on Date instance', async () => {
    const result = await fixer.forDate(someDate, {
      access_key: accessKey
    });

    expect(result).toMatchObject({
      base: 'EUR',
      date: formattedDate,
      rates: expect.objectContaining({
        USD: expect.any(Number),
        EUR: 1,
        GBP: expect.any(Number)
      }),
      success: true,
      timestamp: expect.any(Number)
    });
  });

  describe('default instance updated with accessKey', () => {
    it('should get latest data', async () => {
      fixer.set({ accessKey });
      const result = await fixer.latest();

      expect(result).toMatchObject({
        base: 'EUR',
        date: formattedDate,
        rates: expect.objectContaining({
          USD: expect.any(Number),
          EUR: 1,
          GBP: expect.any(Number)
        }),
        success: true,
        timestamp: expect.any(Number)
      });
    });
  });
});


text:
var readlineSync = require('readline-sync');

var weight = readlineSync.question('Weight (kg): ');
var height = readlineSync.question('Height (m): ');

console.log("\nBMI: %s\n", require('../main.js').bmi(weight = weight, height = height));


text:
require 'spec_helper'

describe 'openstack::logrotate' do

  let(:default_params) { {
    :role     => 'client',
    :rotation => 'weekly',
    :keep     => '4',
    :minsize  => '30M',
    :maxsize  => '100M',
    :debug    => false,
  } }

  let(:params) { {} }

  shared_examples_for 'logrotate configuration' do
    let :p do
      default_params.merge(params)
    end

    it 'contains openstack::logrotate' do
      should contain_class('openstack::logrotate')
    end

    context 'with default params' do
      it 'configures with the default params' do
        should contain_file('/etc/logrotate.d/fuel.nodaily')
        should contain_file('/etc/logrotate.d/puppet')
        should contain_file('/etc/logrotate.d/upstart').with_ensure('absent')
        ['logrotate-tabooext',
         'logrotate-compress',
         'logrotate-delaycompress',
         'logrotate-minsize',
         'logrotate-maxsize',].each do |item|
          should contain_file_line(item)
        end
        should contain_cron('fuel-logrotate').with_minute('*/30')
      end
    end

    context 'with debug = true' do
      let :params do
        { :debug => true }
      end

      it 'configures debug' do
        should contain_cron('fuel-logrotate').with_minute('*/10')
      end
    end
  end

  context 'on Debian platforms' do
    let :facts do
      { :osfamily => 'Debian',
        :operatingsystem => 'Debian',
        :hostname => 'hostname.example.com', }
    end

    it_configures 'logrotate configuration'
  end

  context 'on RedHat platforms' do
    let :facts do
      { :osfamily => 'RedHat',
        :operatingsystem => 'RedHat',
        :hostname => 'hostname.example.com', }
    end

    it_configures 'logrotate configuration'
  end

end


text:
Back to top

          Paper
          Professor Hu

Part of KOP-DPI. Powered by Django and Postgres and Processing.js.

Code licensed under MIT License.

    {% include "script.inc.html" %}


text:
package com.alibaba.json.bvt.serializer.filters;

import java.util.HashMap;
import java.util.Map;

import org.junit.Assert;

import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.NameFilter;
import com.alibaba.fastjson.serializer.SerializeWriter;

import junit.framework.TestCase;

public class NameFilterTest_boolean_field extends TestCase {

    public void test_namefilter() throws Exception {
        NameFilter filter = new NameFilter() {

            public String process(Object source, String name, Object value) {
                if (value != null) {
                    Assert.assertTrue(value instanceof Boolean);
                }

                if (name.equals("id")) {
                    return "ID";
                }

                return name;
            }

        };

        SerializeWriter out = new SerializeWriter();
        JSONSerializer serializer = new JSONSerializer(out);
        serializer.getNameFilters().add(filter);

        Bean a = new Bean();
        serializer.write(a);

        String text = out.toString();
        Assert.assertEquals("{\"ID\":false}", text);
    }

    public void test_namefilter_1() throws Exception {
        NameFilter filter = new NameFilter() {

            public String process(Object source, String name, Object value) {
                if (name.equals("id")) {
                    return "ID";
                }

                return name;
            }

        };

        SerializeWriter out = new SerializeWriter();
        JSONSerializer serializer = new JSONSerializer(out);
        serializer.getNameFilters().add(filter);

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", true);
        serializer.write(map);

        String text = out.toString();
        Assert.assertEquals("{\"ID\":true}", text);
    }

    public static class Bean {

        public boolean id;
        public String  name;

    }
}


text:
{% from 'events/papers/reviewing/timeline.html' import render_paper_content, render_paper_metadata %}

{% macro render_paper_section(contribution) %}
    {% set paper = contribution.paper %}
    {% set can_submit = contribution.can_submit_proceedings(session.user) %}
    {% set show_paper = paper and paper.accepted_revision %}
    {% set show_paper_status = paper and can_submit %}
    {% set show_paper_submission = contribution.event.cfp.is_open and can_submit %}

    {% if show_paper or show_paper_status or show_paper_submission %}

{% trans %}Peer reviewing{% endtrans %}

{% trans %}Paper{% endtrans %}

                    {% if show_paper and paper.state.name == 'accepted' %}
                        {{ render_paper_metadata(paper, contribution_page=true) }}
                    {% endif %}

            {% if show_paper %}
                {{ render_paper_content(paper, contribution_page=true) }}
            {% endif %}

            {% if show_paper_status and paper.state.name != 'accepted' %}
                {{ _render_paper_status_box(paper) }}
            {% elif not show_paper and show_paper_submission %}
                {{ _render_paper_submission_box(contribution) }}
            {% endif %}

    {% endif %}
{% endmacro %}

{% macro render_editables_section(contribution) %}
    {% set can_create_editable = contribution.allowed_types_for_editable|length > 0 %}
    {% set can_submit = contribution.can_submit_proceedings(session.user) %}
    {% set enabled_editables = contribution.enabled_editables %}
    {% set has_enabled_types = enabled_editables|length > 0 %}

    {% if can_submit and (has_enabled_types or can_create_editable) %}

{% trans %}Editing{% endtrans %}

            {% if has_enabled_types %}

                    {% for editable in enabled_editables -%}

                                {{ editable.type.title }}: {{ editable.state.title }}

                                    {%- trans %}Go to timeline{% endtrans -%}

                    {%- endfor %}

            {% endif %}
            {% if can_create_editable %}

                                    {% trans %}Submission is open{% endtrans %}

                                    {% trans %}You can submit files for editing{% endtrans %}

            {% endif %}

    {% endif %}
{% endmacro %}

{% macro _render_paper_status_box(paper) %}
    {% set state_mapping = {'submitted': '',
                            'rejected': 'danger',
                            'to_be_corrected': 'warning'} %}

                {{ _render_paper_status(paper) }}

                    {%- trans %}Go to timeline{% endtrans -%}

{% endmacro %}

{% macro _render_paper_submission_box(contribution) %}

                    {%- trans %}The call for papers is open{% endtrans -%}

                    {%- trans %}You can submit a paper.{% endtrans -%}

                    {%- trans %}Submit paper{% endtrans -%}

{% endmacro %}

{% macro _render_paper_status(paper) %}
    {% set revision = paper.last_revision %}
    {% if paper.state.name == 'submitted' %}

            {%- trans %}Your paper is under review{% endtrans -%}

            {%- trans %}Please wait until the reviewers come back to you{% endtrans -%}

    {% elif paper.state.name == 'rejected' %}

            {%- trans %}Your paper was rejected{% endtrans -%}

            {%- trans %}You can check the review history in the timeline{% endtrans -%}

    {% elif paper.state.name == 'to_be_corrected' %}

            {%- trans %}Your paper needs to be corrected{% endtrans -%}

            {%- trans %}Please check the review and submit a revised version{% endtrans -%}

    {% endif %}
{% endmacro %}

{% macro _render_file_type_section(revision_files, file_type) %}

{{ file_type.name }}

                {% for rev_file in revision_files %}
                    {% set file = rev_file.file %}
                    {% set download_url = rev_file.download_url %}
                    {% set icon = icon_from_mimetype(file.content_type, 'icon-file-filled') %}

                                {{ file.filename }}

                {% endfor %}

{% endmacro %}

{% macro render_proceedings_section(contribution) %}

{% trans %}Proceedings{% endtrans %}

        {% for editable in contribution.enabled_editables if editable.published_revision -%}
            {% set published_revision = editable.published_revision %}
            {% set spotlight_file = published_revision.get_spotlight_file() %}
            {% set published_files = published_revision.get_published_files() %}
            {% if spotlight_file or published_files %}

{{ editable.type.title }}

                    {% if spotlight_file %}
                        {% set icon = icon_from_mimetype(spotlight_file.file.content_type, 'icon-file-filled') %}

                                    {{ spotlight_file.file.filename }}

                    {% else %}
                        {% for file_type, files in published_files.items() %}
                            {{ _render_file_type_section(files, file_type) }}
                        {% endfor %}
                    {% endif %}

            {% endif %}
        {%- endfor %}

{% endmacro %}


text:
import { Injectable } from '@angular/core';

import { Http, Response, Headers, RequestOptions } from '@angular/http';

import { Observable } from 'rxjs/Rx';
import { Subject }    from 'rxjs/Subject';

// Import RxJs required methods
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';

const QUERY_URL = 'https://dev26267.service-now.com/api/now/table/incident?sysparm_query=active%3Dtrue%5Estate%3D1%5EORstate%3D2';
const QUERY_URL2 = 'https://acip-demo.mybluemix.net/rest/askquestion/q/why%20I%20have%20liquid%20drops%20aldiva%20app';

@Injectable()
export class SnowExtractService {

    activeSnowTicket: any = {};

    constructor(private http: Http) {
        console.log( 'SnowExtractService initialized...');
     }

/*
    query( ): Observable<any> {

        let headers = new Headers({ 'Content-Type': 'application/json',
                                    'Authorization': 'Basic YWRtaW46QGMxVDIwMTc='});
        let options = new RequestOptions({ headers: headers });

        return this.http.get(QUERY_URL, options)
           .map((res:Response) => res.json())
           .catch((error:any) => Observable.throw(error.json().error || 'Server error'));
    }
*/
    getTickets() {
        let headers = new Headers({ 'Authorization': 'Basic YWRtaW46QGMxVDIwMTc='});
        let options = new RequestOptions({ headers: headers });

        let headers2 = new Headers({ 'clientInfo': 'ACIPRest',
                                     'Authorization': 'Basic YWNpcGVuZHVzZXI6cGFzc3dvcmQ='});
        let options2 = new RequestOptions({ headers: headers });

        console.log('Get Tickets Now...')

/*
        return this.http.get(QUERY_URL, options)
            .map((res:Response) => res.json())
            .catch((error:any) => Observable.throw(error.json().error || 'Server error'));
*/
        return this.http.get('https://jsonplaceholder.typicode.com/posts')
            .map((res:Response) => res.json());
/*
        return this.http.get(QUERY_URL2, options2)
            .map((res:Response) => res.json());

*/
    }

}


text:
package com.mauriciotogneri.tensiontunnel2.entities.behaviors;

import com.mauriciotogneri.mandy.input.Input;
import com.mauriciotogneri.mandy.screen.Camera;
import com.mauriciotogneri.tensiontunnel2.types.RotationDirection;

import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.Body;

public class OrbitingBehavior implements EnemyBehavior
{
    private float currentAngle;

    private final float startAngle;
    private final float centerX;
    private final float centerY;
    private final float radius;
    private final float angularSpeed;
    private final RotationDirection rotationDirection;

    public OrbitingBehavior(float centerX, float centerY, float startAngle, float radius, float angularSpeed, RotationDirection rotationDirection)
    {
        this.startAngle = startAngle;
        this.centerX = centerX;
        this.centerY = centerY;
        this.radius = radius;
        this.angularSpeed = angularSpeed;
        this.rotationDirection = rotationDirection;
    }

    @Override
    public void onUpdate(Body body, float delta, Input input, Camera camera)
    {
        updateAngle(delta, angularSpeed, rotationDirection);
        updatePosition(body, currentAngle, radius, centerX, centerY);
    }

    @Override
    public void onStart(Body body)
    {
    }

    @Override
    public void onStop(Body body)
    {
    }

    @Override
    public void onReset(Body body)
    {
        currentAngle = startAngle;

        updatePosition(body, currentAngle, radius, centerX, centerY);
    }

    private void updateAngle(float delta, float speed, RotationDirection rotationDirection)
    {
        if (rotationDirection == RotationDirection.CLOCKWISE)
        {
            currentAngle -= (delta * speed);
        }
        else if (rotationDirection == RotationDirection.COUNTER_CLOCKWISE)
        {
            currentAngle += (delta * speed);
        }

        currentAngle = (currentAngle % 360);
    }

    private void updatePosition(Body body, float angle, float radius, float centerX, float centerY)
    {
        float angleRadians = (float) Math.toRadians(angle);

        float x = ((float) Math.cos(angleRadians) * radius) + centerX;
        float y = ((float) Math.sin(angleRadians) * radius) + centerY;

        body.setTransform(new Vec2(x, y), body.getAngle());
    }
}


text:
typedef void (^sharedCompletion)(BOOL fin);

@interface AnimationViewController : UIViewController

@end


text:
<?php

namespace Admingenerator\GeneratorBundle\Generator\Action\Batch;

use Admingenerator\GeneratorBundle\Builder\Admin\BaseBuilder;
use Admingenerator\GeneratorBundle\Generator\Action;

/**
 * This class describes batch Delete action
 * @author cedric Lombardot
 * @author Piotr Gołębiewski <loostro@gmail.com>
 */
class DeleteAction extends Action
{
    public function __construct($name, BaseBuilder $builder)
    {
        parent::__construct($name, 'batch');

        $this->setIcon('fa-times');
        $this->setLabel('action.batch.delete.label');
        $this->setConfirm('action.batch.delete.confirm');
        $this->setCsrfProtected(true);

        $this->setOptions(array(
            'success' => 'action.batch.delete.success',
            'error' => 'action.batch.delete.success',
            'i18n' => 'Admingenerator'
        ));
    }
}


text:
layout: post
author:
title: "Finding chatbots on Skype for iOS it's easier now"
date: 2016-07-20 15:58:00 -0300
categories: hot
thumb: 2016-07-20-SS1.png
comments: true
---
Microsoft announced that now, Skype Users can discover bots on the Skype iOS app more easily.
If you already installed the version 6.20 in your iPhone, it's just tap on the bot icon recent header, see bellow a Skype version 6.20 update screenshot, by Microsoft.

![SS1]({{ site.url }}/img/posts/2016-07-20-SS1.png)

Before, you had to go to the contacts page, his Add Contact, and toggle to the Bots section to the right of the People section. __I real pain in the neck!__

[Read more here.](http://venturebeat.com/2016/07/20/its-now-a-little-easier-to-find-chatbots-to-talk-to-on-skype-for-ios/)


text:
.. _technical

Technical Introduction
======================

The basic features for 'Crowdata' are

* Store a set of documents (PDF or other formats supported by `Document Cloud <http://www.documentcloud.org>`_)

* Define a form, via the admin, for the information that wants to be extracted from the documents.

* Present users with a document and the form to allow anybody, that is registered to the website, to send us the information they see in the document.

* Have access to download the CSV of all the information extracted from the PDFs by the users.


text:
set(JXR_PREV_MODULE_PATH ${CMAKE_MODULE_PATH})
list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_LIST_DIR})

if(NOT JXR_LIBRARIES)
  _find_package(${ARGS})
endif()

set(CMAKE_MODULE_PATH ${JXR_PREV_MODULE_PATH})


text:
namespace dclass   // open namespace
{

// Foward declarations
class HashGenerator;
class File;
class Class;
class Field;

// A Struct provides type composition by combining multiple Fields each with their own type.
//     Structs may have both anonymous and named Fields.
class Struct : public DistributedType
{
  public:
    Struct(File* file, const std::string &name);
    virtual ~Struct();

    // as_struct returns this as a Struct if it is a Struct, or NULL otherwise.
    virtual Struct* as_struct();
    virtual const Struct* as_struct() const;

    // as_class returns this Struct as a Class if it is a Class, or NULL otherwise.
    virtual Class* as_class();
    virtual const Class* as_class() const;

    // get_id returns a unique index number associated with this struct.
    inline unsigned int get_id() const;
    // get_name returns the name of this struct.
    inline const std::string& get_name() const;
    // get_file returns the File object that contains the struct.
    inline File* get_file();
    inline const File* get_file() const;

    // get_num_fields returns the number of fields in the struct.
    inline size_t get_num_fields() const;
    // get_field returns the <n>th field of the struct.
    inline Field* get_field(unsigned int n);
    inline const Field* get_field(unsigned int n) const;

    // get_field_by_id returns the field with the index <id>, or NULL if no such field exists.
    inline Field* get_field_by_id(unsigned int id);
    inline const Field* get_field_by_id(unsigned int id) const;
    // get_field_by_name returns the field with <name>, or NULL if no such field exists.
    inline Field* get_field_by_name(const std::string& name);
    inline const Field* get_field_by_name(const std::string& name) const;

    // add_field adds a new Field to the struct.
    //     Returns false if the field could not be added to the struct.
    virtual bool add_field(Field* field);

    // generate_hash accumulates the properties of this type into the hash.
    virtual void generate_hash(HashGenerator &hashgen) const;

  protected:
    Struct(File* file);

    // set_id sets the index number associated with this struct.
    void set_id(unsigned int id);
    friend class File;

    File *m_file;
    unsigned int m_id;
    std::string m_name;

    std::vector<Field*> m_fields;
    std::unordered_map<std::string, Field*> m_fields_by_name;
    std::unordered_map<unsigned int, Field*> m_fields_by_id;
};

} // close namespace dclass
#include "Struct.ipp"


text:
package org.spongepowered.common.data.property.store.item;

import net.minecraft.item.ItemStack;
import net.minecraft.potion.PotionEffect;
import net.minecraft.potion.PotionUtils;
import org.spongepowered.api.data.property.item.ApplicableEffectProperty;
import org.spongepowered.common.data.property.store.common.AbstractItemStackPropertyStore;

import java.util.HashSet;
import java.util.List;
import java.util.Optional;

public class ApplicableEffectPropertyStore extends AbstractItemStackPropertyStore<ApplicableEffectProperty> {

    @SuppressWarnings("unchecked")
    @Override
    public Optional<ApplicableEffectProperty> getFor(final ItemStack propertyHolder) {
        final List<PotionEffect> effectsFromStack = PotionUtils.getEffectsFromStack(propertyHolder);
        if (effectsFromStack.isEmpty()) {
            return Optional.empty();
        }
        return Optional.of(new ApplicableEffectProperty(new HashSet<>((List < org.spongepowered.api.effect.potion.PotionEffect >) (List<?>) effectsFromStack)));
    }

}


text:
'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	Schema = mongoose.Schema;

/**
 * Validation
 */
function validateLength (v) {
	// a custom validation function for checking string length to be used by the model
	return v.length <= 40;
}

/**
 * Product Schema
 */
var ProductSchema = new Schema({
	category: {
		type: Schema.Types.ObjectId,
		ref: 'Category',
		required: 'invalid category'
	},
	created: {
		type: Date,
		default: Date.now
	},
	name: {
		type: String,
		default: '',
		trim: true,
		required: 'name cannot be blank',
		validate: [validateLength, 'name must be 40 chars in length or less']
	},
	quantityPerUnit: {
		type: String
	},
	unitPrice: {
		type: Number,
		default: 0
	},
	unitsInStock: {
		type: Number,
		default: 0,
		min: 0
	},
	unitsOnOrder: {
		type: Number,
		default: 0,
		min: 0
	},
	discontinued: {
		type: Boolean,
		default: false
	}
});

mongoose.model('Product', ProductSchema);


text:
 <%=t ( "buttons/stack") %>

        <form class="vzb-howtostack vzb-dialog-paragraph">
             <input type="radio" name="stack" value="none"> <%=t ( "mount/stacking/none") %>
             <input type="radio" name="stack" value="geo.world_4region"> <%=t ( "mount/stacking/region") %>
             <input type="radio" name="stack" value="all"> <%=t ( "mount/stacking/world") %>
        </form>

        <form class="vzb-howtomerge vzb-dialog-paragraph">

 <%=t ( "hints/mount/howtomerge") %>

             <input type="radio" name="merge" value="none"> <%=t ( "mount/merging/none") %>
             <input type="radio" name="merge" value="grouped"> <%=t ( "mount/merging/region") %>
             <input type="radio" name="merge" value="stacked"> <%=t ( "mount/merging/world") %>
        </form>

        <form class="vzb-manual-sorting">

 <%=t ( "mount/manualSorting") %>

        </form>

OK


text:
package org.littlewings.javaee7.extension

import scala.collection.mutable

import javax.enterprise.event.Observes
import javax.enterprise.inject.spi._

class MyExtension extends Extension {
  val classes: mutable.Set[Class[_]] = mutable.Set.empty

  def collectClasses(@Observes pat: ProcessAnnotatedType[_]): Unit = {
    val annotatedType = pat.getAnnotatedType
    classes += annotatedType.getJavaClass
  }
}


text:
require_relative 'forca'
jogo_da_forca


text:
Docker build command:
docker build -t strong-cluster-control .

Docker run command:
docker run -it strong-cluster-control


text:
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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.
// ----------------------------------------------------------------------------------

using System;
using Microsoft.Azure.Commands.Automation.Cmdlet;
using Microsoft.Azure.Commands.Automation.Common;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.WindowsAzure.Commands.Common.Test.Mocks;
using Microsoft.WindowsAzure.Commands.Test.Utilities.Common;
using Moq;

namespace Microsoft.Azure.Commands.Automation.Test.UnitTests
{
    [TestClass]
    public class GetAzureAutomationRunbookDefinitionTest : TestBase
    {
        private Mock<IAutomationClient> mockAutomationClient;

        private MockCommandRuntime mockCommandRuntime;

        private GetAzureAutomationRunbookDefinition cmdlet;

        [TestInitialize]
        public void SetupTest()
        {
            this.mockAutomationClient = new Mock<IAutomationClient>();
            this.mockCommandRuntime = new MockCommandRuntime();
            this.cmdlet = new GetAzureAutomationRunbookDefinition
                              {
                                  AutomationClient = this.mockAutomationClient.Object,
                                  CommandRuntime = this.mockCommandRuntime
                              };
        }

        [TestMethod]
        public void GetAzureAutomationRunbookDefinitionByRunbookIdWithoutSlotSuccessfull()
        {
            // Setup
            string accountName = "automation";
            var runbookId = new Guid();

            this.mockAutomationClient.Setup(f => f.ListRunbookDefinitionsByRunbookId(accountName, runbookId, null));

            // Test
            this.cmdlet.AutomationAccountName = accountName;
            this.cmdlet.Id = runbookId;
            this.cmdlet.ExecuteCmdlet();

            // Assert
            this.mockAutomationClient.Verify(f => f.ListRunbookDefinitionsByRunbookId(accountName, runbookId, null), Times.Once());
        }

        [TestMethod]
        public void GetAzureAutomationRunbookDefinitionByRunbookIdSlotDraftSuccessfull()
        {
            // Setup
            string accountName = "automation";
            var runbookId = new Guid();

            this.mockAutomationClient.Setup(f => f.ListRunbookDefinitionsByRunbookId(accountName, runbookId, true));

            // Test
            this.cmdlet.AutomationAccountName = accountName;
            this.cmdlet.Id = runbookId;
            this.cmdlet.Slot = "Draft";
            this.cmdlet.ExecuteCmdlet();

            // Assert
            this.mockAutomationClient.Verify(f => f.ListRunbookDefinitionsByRunbookId(accountName, runbookId, true), Times.Once());
        }

        [TestMethod]
        public void GetAzureAutomationRunbookDefinitionByRunbookNameWithoutSlotSuccessfull()
        {
            // Setup
            string accountName = "automation";
            string runbookName = "runbook";

            this.mockAutomationClient.Setup(f => f.ListRunbookDefinitionsByRunbookName(accountName, runbookName, null));

            // Test
            this.cmdlet.AutomationAccountName = accountName;
            this.cmdlet.Name = runbookName;
            this.cmdlet.ExecuteCmdlet();

            // Assert
            this.mockAutomationClient.Verify(f => f.ListRunbookDefinitionsByRunbookName(accountName, runbookName, null), Times.Once());
        }

        [TestMethod]
        public void GetAzureAutomationRunbookDefinitionByRunbookNameSlotPublishedSuccessfull()
        {
            // Setup
            string accountName = "automation";
            string runbookName = "runbook";

            this.mockAutomationClient.Setup(f => f.ListRunbookDefinitionsByRunbookName(accountName, runbookName, false));

            // Test
            this.cmdlet.AutomationAccountName = accountName;
            this.cmdlet.Name = runbookName;
            this.cmdlet.Slot = "Published";
            this.cmdlet.ExecuteCmdlet();

            // Assert
            this.mockAutomationClient.Verify(f => f.ListRunbookDefinitionsByRunbookName(accountName, runbookName, false), Times.Once());
        }

        [TestMethod]
        public void GetAzureAutomationRunbookDefinitionByRunbookVersionIdWithoutSlotSuccessfull()
        {
            // Setup
            string accountName = "automation";
            var runbookVersionId = new Guid();

            this.mockAutomationClient.Setup(
                f => f.ListRunbookDefinitionsByRunbookVersionId(accountName, runbookVersionId, null));

            // Test
            this.cmdlet.AutomationAccountName = accountName;
            this.cmdlet.VersionId = runbookVersionId;
            this.cmdlet.ExecuteCmdlet();

            // Assert
            this.mockAutomationClient.Verify(f => f.ListRunbookDefinitionsByRunbookVersionId(accountName, runbookVersionId, null), Times.Once());
        }
    }
}


text:
@implementation Employee

@dynamic birthDate;
@dynamic employeeId;
@dynamic firstName;
@dynamic lastName;
@dynamic company;

@end


text:
package com.anshdeep.dailytech.data.network;

import com.anshdeep.dailytech.util.Constants;

/**
 * Created by ansh on 20/10/17.
 */

public class ApiEndPoint {

    public static final String ENDPOINT_ARTICLES = Constants.BASE_URL
            + "articles";

    private ApiEndPoint() {
        // This class is not publicly instantiable
    }
}


text:
/*!
 * Angular Material Design
 * https://github.com/angular/material
 * @license MIT
 * v1.1.0-rc.5-master-7f01138
 */
/*  Only used with Theme processes */
html.md-THEME_NAME-theme, body.md-THEME_NAME-theme {
  color: '{{foreground-1}}';
  background-color: '{{background-color}}'; }

md-dialog.md-THEME_NAME-theme {
  border-radius: 4px;
  background-color: '{{background-hue-1}}';
  color: '{{foreground-1}}'; }
  md-dialog.md-THEME_NAME-theme.md-content-overflow .md-actions, md-dialog.md-THEME_NAME-theme.md-content-overflow md-dialog-actions {
    border-top-color: '{{foreground-4}}'; }


text:
FROM openjdk:8-jre-alpine
VOLUME /tmp
ARG DEPENDENCY=build/libs/dependency
COPY ${DEPENDENCY}/BOOT-INF/lib /app/lib
COPY ${DEPENDENCY}/META-INF /app/META-INF
COPY ${DEPENDENCY}/BOOT-INF/classes /app
ENTRYPOINT ["java","-cp","app:app/lib/*","amu.zhcet.CoreApplication"]


text:
PONY_EXTERN_C_BEGIN

typedef struct messageq_t
{
  PONY_ATOMIC(pony_msg_t*) head;
  pony_msg_t* tail;
} messageq_t;

void ponyint_messageq_init(messageq_t* q);

void ponyint_messageq_destroy(messageq_t* q);

bool ponyint_messageq_push(messageq_t* q, pony_msg_t* m);

pony_msg_t* ponyint_messageq_pop(messageq_t* q);

bool ponyint_messageq_markempty(messageq_t* q);

PONY_EXTERN_C_END

#endif


text:
using CYC.DigitalHub.CodingStandards.CSharp.ViewModels.DataController;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Net.Http;

/// <summary>
/// This controller is an example of a WebApi2 controller that you would use to send json/xml to a client.
/// A client might be an clientside app or a server, anything that consumes your data.
/// </summary>

// We use route based attributes wherever possible as it is easier to reference and clearer.
// WebApi controllers should always sit behind the api keyword. http://localhost:5000/api/Data in this case.
[Route("api/[controller]")]
public class DataController : Controller
{
    /// <summary>
    /// Get 10 random numbers
    /// </summary>
    /// <returns>10 random integer values.</returns>

    // This is the default get action so we need to map it using root value
    // The [action] route maps to /api/data/get too so you can be specific in your consumer if you prefer.
    [Route("")]
    [Route("[action]")]
    [HttpGet]
    public IEnumerable<DataApiUserViewModel> Get()
    {
        // Only comment complicated code, try to keep code simple so it is effectively self commenting.
        var random = new Random();
        var returnValue = new List<DataApiUserViewModel>();

        // Counter variables can be a single letter, usually an i.
        // If nesting for loops then provide more meaningful variable names to avoid confusion
        for (var i = 0; i < 10; i++)
        {
            returnValue.Add(new DataApiUserViewModel
            {
                Id = random.Next(),
                JobTitle = "Developer",
                Name = "Data API user"
            });
        }

        return returnValue;
    }

    /// <summary>
    /// Get a DataController user by id
    /// </summary>
    /// <param name="id">User Id</param>
    /// <returns></returns>
    [Route("{id}")]
    [Route("[action]/{id}")]
    [HttpGet]
    public DataApiUserViewModel Get(int id)
    {
        // This would most likely be returned from a service that is searching a DB / cache solution.
        return new DataApiUserViewModel
        {
            Id = id,
            Name = "Data API user",
            JobTitle = "Developer"
        };
    }

    /// <summary>
    /// Create a new User
    /// </summary>
    /// <param name="user">User that should be created</param>
    /// <returns>HTTP status code indicating outcome</returns>
    [Route("")]
    [Route("[action]")]
    [Route("create")]
    [HttpPost]
    public IActionResult Post([FromBody]DataApiUserViewModel user)
    {
        // Where possible use data annotations to perform validation
        if (!ModelState.IsValid)
        {
            // Return a 409 conflict if the information passed was not in a usable form (validation etc).
            // See https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.10
            return StatusCode(409);
        }

        // Processing logic to store the new user would be called here.
        // ...

        // Successful POST returns 200 OK.
        return Ok();
    }

    [Route("")]
    [Route("[action]")]
    [Route("update")]
    [HttpPut]
    public IActionResult Put([FromBody]DataApiUserUpdateViewModel user)
    {
        if(!ModelState.IsValid)
        {
            return StatusCode(409);
        }

        // We would normally have logic here to ensure the user exists.
        // In this case, we're just seeing if the id is odd or even.
        if (user.Id % 2 == 0)
        {
            // If the user does not exist return 404 not found.
            return NotFound();
        }

        // Processing logic to update user would be called here.
        // ...

        //Successful PUT returns 200 OK
        return Ok();
    }
}


text:
namespace OpenApoc
{

class GameState;
class Form;
class Label;
class Organisation;

class BribeScreen : public Stage
{
  private:
	sp<Form> menuform;
	sp<GameState> state;

	sp<Label> labelFunds;
	sp<Label> labelRelation;
	sp<Label> labelOffer;

	StateRef<Organisation> organisation;
	// Sum of the bribe.
	int bribe = 0;

	// Update info about deal.
	void updateInfo();
	// Get the offer of a bribe.
	UString getOfferString(int itWillCost, const UString &newAttitude) const;

  public:
	BribeScreen(sp<GameState> state);
	~BribeScreen() override;
	// Stage control
	void begin() override;
	void pause() override;
	void resume() override;
	void finish() override;
	void eventOccurred(Event *e) override;
	void update() override;
	void render() override;
	bool isTransition() override;
};

}; // namespace OpenApoc


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
let _ = require('lodash');
let messages = require('../../../src/protos/msgtemplates_v1_pb');
const pip_services3_commons_node_1 = require("pip-services3-commons-node");
const pip_services3_commons_node_2 = require("pip-services3-commons-node");
const pip_services3_commons_node_3 = require("pip-services3-commons-node");
const pip_services3_commons_node_4 = require("pip-services3-commons-node");
class MessageTemplatesGrpcConverterV1 {
    static fromError(err) {
        if (err == null)
            return null;
        let description = pip_services3_commons_node_3.ErrorDescriptionFactory.create(err);
        let obj = new messages.ErrorDescription();
        obj.setType(description.type);
        obj.setCategory(description.category);
        obj.setCode(description.code);
        obj.setCorrelationId(description.correlation_id);
        obj.setStatus(description.status);
        obj.setMessage(description.message);
        obj.setCause(description.cause);
        obj.setStackTrace(description.stack_trace);
        MessageTemplatesGrpcConverterV1.setMap(obj.getDetailsMap(), description.details);
        return obj;
    }
    static toError(obj) {
        if (obj == null || (obj.getCategory() == "" && obj.getMessage() == ""))
            return null;
        let description = {
            type: obj.getType(),
            category: obj.getCategory(),
            code: obj.getCode(),
            correlation_id: obj.getCorrelationId(),
            status: obj.getStatus(),
            message: obj.getMessage(),
            cause: obj.getCause(),
            stack_trace: obj.getStackTrace(),
            details: MessageTemplatesGrpcConverterV1.getMap(obj.getDetailsMap())
        };
        return pip_services3_commons_node_4.ApplicationExceptionFactory.create(description);
    }
    static setMap(map, values) {
        if (values == null)
            return;
        if (_.isFunction(values.toObject))
            values = values.toObject();
        if (_.isArray(values)) {
            for (let entry of values) {
                if (_.isArray(entry))
                    map[entry[0]] = entry[1];
            }
        }
        else {
            if (_.isFunction(map.set)) {
                for (let propName in values) {
                    if (values.hasOwnProperty(propName))
                        map.set(propName, values[propName]);
                }
            }
            else {
                for (let propName in values) {
                    if (values.hasOwnProperty(propName))
                        map[propName] = values[propName];
                }
            }
        }
    }
    static getMap(map) {
        let values = {};
        MessageTemplatesGrpcConverterV1.setMap(values, map);
        return values;
    }
    static toJson(value) {
        if (value == null || value == "")
            return null;
        return JSON.stringify(value);
    }
    static fromJson(value) {
        if (value == null || value == "")
            return null;
        return JSON.parse(value);
    }
    static fromPagingParams(paging) {
        if (paging == null)
            return null;
        let obj = new messages.PagingParams();
        obj.setSkip(paging.skip);
        obj.setTake(paging.take);
        obj.setTotal(paging.total);
        return obj;
    }
    static toPagingParams(obj) {
        if (obj == null)
            return null;
        let paging = new pip_services3_commons_node_2.PagingParams(obj.getSkip(), obj.getTake(), obj.getTotal());
        return paging;
    }
    static fromMessageTemplate(template) {
        if (template == null)
            return null;
        let obj = new messages.MessageTemplate();
        obj.setId(template.id);
        obj.setName(template.name);
        obj.setFrom(template.from);
        MessageTemplatesGrpcConverterV1.setMap(obj.getSubjectMap(), template.subject);
        MessageTemplatesGrpcConverterV1.setMap(obj.getTextMap(), template.text);
        MessageTemplatesGrpcConverterV1.setMap(obj.getHtmlMap(), template.html);
        obj.setStatus(template.status);
        return obj;
    }
    static toMessageTemplate(obj) {
        if (obj == null)
            return null;
        let template = {
            id: obj.getId(),
            name: obj.getName(),
            from: obj.getFrom(),
            subject: new pip_services3_commons_node_1.MultiString(),
            text: new pip_services3_commons_node_1.MultiString(),
            html: new pip_services3_commons_node_1.MultiString(),
            status: obj.getStatus()
        };
        MessageTemplatesGrpcConverterV1.setMap(template.subject, obj.getSubjectMap());
        MessageTemplatesGrpcConverterV1.setMap(template.text, obj.getTextMap());
        MessageTemplatesGrpcConverterV1.setMap(template.html, obj.getHtmlMap());
        return template;
    }
    static fromMessageTemplatePage(page) {
        if (page == null)
            return null;
        let obj = new messages.MessageTemplatePage();
        obj.setTotal(page.total);
        let data = _.map(page.data, MessageTemplatesGrpcConverterV1.fromMessageTemplate);
        obj.setDataList(data);
        return obj;
    }
    static toMessageTemplatePage(obj) {
        if (obj == null)
            return null;
        let data = _.map(obj.getDataList(), MessageTemplatesGrpcConverterV1.toMessageTemplate);
        let page = {
            total: obj.getTotal(),
            data: data
        };
        return page;
    }
}
exports.MessageTemplatesGrpcConverterV1 = MessageTemplatesGrpcConverterV1;
//# sourceMappingURL=MessageTemplatesGrpcConverterV1.js.map


text:
.. nested_sampling documentation master file, created by
   sphinx-quickstart on Sun Nov 30 12:26:21 2014.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

nested sampling : the Python parallel nested sampling algorithm
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

Source code: https://github.com/js850/nested_sampling

Documentation: http://js850.github.io/nested_sampling

Flexible and efficient Python implementation of the nested sampling algorithm.
This implementation is geared towards allowing statistical physicists to use this
method for thermodynamic analysis but is also being used by astrophysicists.

This implementation uses the language of statistical mechanics (partition function,
phase space, configurations, energy, density of states) rather than the language
of Bayesian sampling (likelihood, prior, evidence). This is simply for convenience,
the method is the same.

The package goes beyond the bare implementation of the method providing:

* built-in parallelisation on single computing node (max total number of cpu threads on a single machine)

* built-in Pyro4-based parallelisation by distributed computing, ideal to run calculations on a cluster or across a network

*  ability to save and restart from checkpoint binary files, ideal for very long calculations

* scripts to compute heat capacities and perform error analysis

* integration with the `MCpele  <https://pele-python.github.io/mcpele/>`_ package to implement efficient Monte Carlo walkers.

.. figure:: nested_sampling.jpg
  :align: left
  :scale: 90%

  Figure 1: Snapshot of a Nested Sampling iteration on a multimodal surface. Each contour
  line corresponds to a past maximum energy (log-likelihood) constraint. The inner most
  contour line corresponds to the current constraint and the corresponding sample is removed
  (crossed in red) and replaced by walking a copy of a randomly selected replica (walk trajectory
  is the dashed line and the red point is the new configuration that satisfies the tighter constraint).
  The bottom panel shows the fraction of phase space corresponding to each sample and the
  iterative contractions (corresponding to the contours) are shown by the horizontal lines.
  Note that the nested sampling contraction of phase space is constant in the log of phase space
  volume. The full animation can be run from the example folder.

nested sampling has been authored by Stefano Martiniani Jacob D. Stevenson at the University of Cambridge.
The project is publicly available under the GNU general public licence.

Tutorials
-----------
.. toctree::
   :maxdepth: 3

   getting_started

Reference
---------

.. toctree::
   :maxdepth: 2

   NestedSampling

.. toctree::
   :maxdepth: 2

   MonteCarloWalker

.. toctree::
   :maxdepth: 2

   Models

.. toctree::
   :maxdepth: 2

   PyroParallelisation

.. toctree::
   :maxdepth: 2

   Utils

Modules
+++++++
.. toctree::
   :maxdepth: 1

   nested_sampling

Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`


text:
package org.trustedanalytics.sparktk.models.timeseries.arima

import org.scalatest.Matchers
import org.trustedanalytics.sparktk.testutils.TestingSparkContextWordSpec

class ArimaModelTest extends TestingSparkContextWordSpec with Matchers {
  // Time series values for testing
  val ts = List(12.88969427, 13.54964408, 13.8432745, 12.13843611, 12.81156092, 14.2499628, 15.12102595)

  "train" should {
    "throw an exception for a null or empty ts vector" in {
      intercept[IllegalArgumentException] {
        // null ts list should throw an exception
        ArimaModel.train(null, 0, 0, 0)
      }

      intercept[IllegalArgumentException] {
        // empty ts list should throw an exception
        ArimaModel.train(List[Double](), 0, 0, 0)
      }
    }

    "throw an exception for an invalid method" in {
      intercept[IllegalArgumentException] {
        // null method string should throw an exception
        ArimaModel.train(ts, 1, 0, 1, true, null)
      }
      intercept[IllegalArgumentException] {
        // empty string method should throw an exception
        ArimaModel.train(ts, 1, 0, 1, true, "")
      }
      intercept[IllegalArgumentException] {
        // "bogus" string shoudl throw an exception
        ArimaModel.train(ts, 1, 0, 1, true, "bogus")
      }
    }

    "train model when passed valid parameters" in {
      val trainResult = ArimaModel.train(ts, 1, 0, 1)
      // Check coefficients
      assert(trainResult.arimaModel.coefficients.sameElements(Array(9.864444620964322, 0.2848511106449633, 0.47346114378593795)))
    }
  }

  "predict" should {
    "throw an exception for a negative value for futurePeriods" in {
      val trainResult = ArimaModel.train(ts, 1, 0, 1)

      intercept[IllegalArgumentException] {
        trainResult.predict(-1)
      }
    }

    "predict the same amount of values as the ts when futurePeriods is zero" in {
      val trainResult = ArimaModel.train(ts, 1, 0, 1)

      val predictResult = trainResult.predict(0)
      assert(predictResult.length == ts.length)
      assert(predictResult.sameElements(Seq(12.674342627141744,
        13.638048984791693,
        13.682219498657313,
        13.883970022400577,
        12.49564914570843,
        13.66340392811346,
        14.201275185574925)))
    }

    "predict more values when the futurePeriods is greater than zero" in {
      val trainResult = ArimaModel.train(ts, 1, 0, 1)

      val predictResult = trainResult.predict(5)
      assert(predictResult.length == (ts.length + 5)) // we should get back 5 extra values
      assert(predictResult.sameElements(Seq(12.674342627141744,
        13.638048984791693,
        13.682219498657313,
        13.883970022400577,
        12.49564914570843,
        13.66340392811346,
        14.201275185574925,
        14.345159879072785,
        13.950679344897772,
        13.838311126610202,
        13.806302914829793,
        13.797185340154384)))
    }
  }

}