text:
package net.selenate.common.comms.res;

import net.selenate.common.exceptions.SeNullArgumentException;

public final class SeResScriptExecute implements SeCommsRes {
  private static final long serialVersionUID = 45749879L;

  private final String result;

  public SeResScriptExecute(final String result) {
    this.result = result;
    validate();
  }

  public String getResult() {
    return result;
  }

  public SeResScriptExecute withResult(final String newResult) {
    return new SeResScriptExecute(newResult);
  }

  private void validate() {
    if (result == null) {
      throw new SeNullArgumentException("Result");
    }
  }

  @Override
  public String toString() {
    return String.format("SeResScriptExecute(%s)", result);
  }

  @Override
  public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result
        + ((this.result == null) ? 0 : this.result.hashCode());
    return result;
  }

  @Override
  public boolean equals(Object obj) {
    if (this == obj)
      return true;
    if (obj == null)
      return false;
    if (getClass() != obj.getClass())
      return false;
    SeResScriptExecute other = (SeResScriptExecute) obj;
    if (result == null) {
      if (other.result != null)
        return false;
    } else if (!result.equals(other.result))
      return false;
    return true;
  }
}


text:
package com.datatorrent.demos.twitter;

import java.net.URI;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.conf.Configuration;

import com.google.common.collect.Maps;

import com.datatorrent.api.Context;
import com.datatorrent.api.DAG;
import com.datatorrent.api.DAG.Locality;
import com.datatorrent.api.Operator;
import com.datatorrent.api.Operator.OutputPort;
import com.datatorrent.api.StreamingApplication;
import com.datatorrent.api.annotation.ApplicationAnnotation;

import com.datatorrent.contrib.twitter.TwitterSampleInput;
import com.datatorrent.lib.algo.UniqueCounter;
import com.datatorrent.lib.appdata.schemas.SchemaUtils;
import com.datatorrent.lib.appdata.snapshot.AppDataSnapshotServerMap;
import com.datatorrent.lib.io.ConsoleOutputOperator;
import com.datatorrent.lib.io.PubSubWebSocketAppDataQuery;
import com.datatorrent.lib.io.PubSubWebSocketAppDataResult;

/**
 * Twitter Demo Application:

 * This demo application samples random public status from twitter, send to url
 * extractor.

 * Top 10 url(s) mentioned in tweets in last 5 mins are displayed on every
 * window count (500ms).

 *

 *
 * Real Time Calculation :

 * This application calculates top 10 url mentioned in tweets in last 5
 * minutes across a 1% random tweet sampling on a rolling window basis.

 *

 * Before running this application, you need to have a Twitter API account
 * and configure the authentication. For launch from CLI, those go into ~/.dt/dt-site.xml:
 *

 * {@code
 * <?xml version="1.0" encoding="UTF-8"?>
 * <?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
 * <configuration>
 *
 *   <property> <name>dt.operator.TweetSampler.consumerKey</name>
 *   <value>TBD</value> </property>
 *
 *   <property> <name>dt.operator.TweetSampler.consumerSecret</name>
 *   <value>TBD</value> </property>
 *
 *   <property> <name>dt.operator.TweetSampler.accessToken</name>
 *   <value>TBD</value> </property>
 *
 *   <property> <name>dt.operator.TweetSampler.accessTokenSecret</name>
 *   <value>TBD</value> </property>
 * </configuration>
 * }
 *

 * Custom Attributes:

 * topCounts operator :
 *

 *
Top Count : 10, number of top unique url to be reported.

 *
Sliding window count : 600, report over last 5 min (600 * .5 / 60 mins)

 *
window slide value : 1

 *

 *

 * Running Java Test or Main app in IDE:
 *
 *

 * LocalMode.runApp(new Application(), 600000); // 10 min run
 *

 *
 * Run Success :

 * For successful deployment and run, user should see following output on
 * console:
 *
 *

 * topURLs: {http://goo.gl/V0R05=2, http://etsy.me/10r1Yg3=6, http://tinyurl.com/88b5jqb=2, http://www.justunfollow.com=4, http://fllwrs.com=2, http://goo.gl/a9Sjp=2, http://goo.gl/iKeVH=2, http://Unfollowers.me=7, http://freetexthost.com/j3y03la4g3=2, http://uranaitter.com=4}
 * topURLs: {http://goo.gl/V0R05=2, http://etsy.me/10r1Yg3=6, http://tinyurl.com/88b5jqb=2, http://www.justunfollow.com=4, http://fllwrs.com=2, http://goo.gl/a9Sjp=2, http://goo.gl/iKeVH=2, http://Unfollowers.me=7, http://freetexthost.com/j3y03la4g3=2, http://uranaitter.com=4}
 * topURLs: {http://goo.gl/V0R05=2, http://etsy.me/10r1Yg3=6, http://tinyurl.com/88b5jqb=2, http://www.justunfollow.com=4, http://fllwrs.com=2, http://goo.gl/a9Sjp=2, http://goo.gl/iKeVH=2, http://Unfollowers.me=7, http://freetexthost.com/j3y03la4g3=2, http://uranaitter.com=4}
 * topURLs: {http://goo.gl/V0R05=2, http://etsy.me/10r1Yg3=6, http://tinyurl.com/88b5jqb=2, http://www.justunfollow.com=4, http://fllwrs.com=2, http://goo.gl/a9Sjp=2, http://goo.gl/iKeVH=2, http://Unfollowers.me=7, http://freetexthost.com/j3y03la4g3=2, http://uranaitter.com=4}
 * topURLs: {http://goo.gl/V0R05=2, http://etsy.me/10r1Yg3=6, http://tinyurl.com/88b5jqb=2, http://www.justunfollow.com=4, http://fllwrs.com=2, http://goo.gl/a9Sjp=2, http://goo.gl/iKeVH=2, http://Unfollowers.me=7, http://freetexthost.com/j3y03la4g3=2, http://uranaitter.com=4}
 * topURLs: {http://goo.gl/V0R05=2, http://etsy.me/10r1Yg3=6, http://tinyurl.com/88b5jqb=2, http://www.justunfollow.com=4, http://fllwrs.com=2, http://goo.gl/a9Sjp=2, http://goo.gl/iKeVH=2, http://Unfollowers.me=7, http://freetexthost.com/j3y03la4g3=2, http://uranaitter.com=4}
 * topURLs: {http://goo.gl/V0R05=2, http://etsy.me/10r1Yg3=6, http://tinyurl.com/88b5jqb=2, http://www.justunfollow.com=4, http://fllwrs.com=2, http://goo.gl/a9Sjp=2, http://goo.gl/iKeVH=2, http://Unfollowers.me=7, http://freetexthost.com/j3y03la4g3=2, http://uranaitter.com=4}
 * 2013-06-17 14:38:55,201 [main] INFO  stram.StramLocalCluster run - Application finished.
 * 2013-06-17 14:38:55,201 [container-2] INFO  stram.StramChild processHeartbeatResponse - Received shutdown request
 *

 *
 * Scaling Options :

 * User can scale application by setting intial partition size > 1 on count
 * unique operator.

 *

 *
 * Application DAG :

 *

 *

 *
 * Streaming Window Size : 500ms(default)

 * Operator Details :

 *

 *
The twitterFeed operator :  This operator samples random public
 * statues from twitter and emits to application.

 * Class : com.datatorrent.demos.twitter.TwitterSampleInput

 * StateFull : No, window count 1

 *

 *
The urlExtractor operator :  This operator extracts url from
 * random sampled statues from twitter.

 * Class : {@link com.datatorrent.demos.twitter.TwitterStatusURLExtractor}

 * StateFull : No, window count 1

 *

 *
The uniqueCounter operator :  This operator aggregates count for each
 * url extracted from random samples.

 * Class : {@link com.datatorrent.lib.algo.UniqueCounter}

 * StateFull : No, window count 1

 *

 *
 The topCounts operator :  This operator caluculates top url in last 1
 * min sliding window count 1.

 * Class : com.datatorrent.lib.algo.WindowedTopCounter

 * StateFull : Yes, sliding window count 120 (1 min)

 *

 *
The operator Console:  This operator just outputs the input tuples
 * to the console (or stdout).

 *

 *

 *
 * @since 0.3.2
 */
@ApplicationAnnotation(name = TwitterTopCounterApplication.APP_NAME)
public class TwitterTopCounterApplication implements StreamingApplication
{
  public static final String SNAPSHOT_SCHEMA = "twitterURLDataSchema.json";
  public static final String CONVERSION_SCHEMA = "twitterURLConverterSchema.json";
  public static final String APP_NAME = "TwitterDemo";

  private final Locality locality = null;

  @Override
  public void populateDAG(DAG dag, Configuration conf)
  {
    // Setup the operator to get the data from twitter sample stream injected into the system.
    TwitterSampleInput twitterFeed = new TwitterSampleInput();
    twitterFeed = dag.addOperator("TweetSampler", twitterFeed);

    //  Setup the operator to get the URLs extracted from the twitter statuses
    TwitterStatusURLExtractor urlExtractor = dag.addOperator("URLExtractor", TwitterStatusURLExtractor.class);

    // Setup a node to count the unique urls within a window.
    UniqueCounter<String> uniqueCounter = dag.addOperator("UniqueURLCounter", new UniqueCounter<String>());
    // Get the aggregated url counts and count them over last 5 mins.
    dag.setAttribute(uniqueCounter, Context.OperatorContext.APPLICATION_WINDOW_COUNT, 600);
    dag.setAttribute(uniqueCounter, Context.OperatorContext.SLIDE_BY_WINDOW_COUNT, 1);

    WindowedTopCounter<String> topCounts = dag.addOperator("TopCounter", new WindowedTopCounter<String>());
    topCounts.setTopCount(10);
    topCounts.setSlidingWindowWidth(1);
    topCounts.setDagWindowWidth(1);

    // Feed the statuses from feed into the input of the url extractor.
    dag.addStream("TweetStream", twitterFeed.status, urlExtractor.input).setLocality(Locality.CONTAINER_LOCAL);
    //  Start counting the urls coming out of URL extractor
    dag.addStream("TwittedURLs", urlExtractor.url, uniqueCounter.data).setLocality(locality);
    // Count unique urls
    dag.addStream("UniqueURLCounts", uniqueCounter.count, topCounts.input);

    consoleOutput(dag, "topURLs", topCounts.output, SNAPSHOT_SCHEMA, "url");
  }

  public static void consoleOutput(DAG dag, String operatorName, OutputPort<List<Map<String, Object>>> topCount, String schemaFile, String alias)
  {
    String gatewayAddress = dag.getValue(DAG.GATEWAY_CONNECT_ADDRESS);
    if (!StringUtils.isEmpty(gatewayAddress)) {
      URI uri = URI.create("ws://" + gatewayAddress + "/pubsub");

      AppDataSnapshotServerMap snapshotServer = dag.addOperator("SnapshotServer", new AppDataSnapshotServerMap());

      Map<String, String> conversionMap = Maps.newHashMap();
      conversionMap.put(alias, WindowedTopCounter.FIELD_TYPE);
      String snapshotServerJSON = SchemaUtils.jarResourceFileToString(schemaFile);

      snapshotServer.setSnapshotSchemaJSON(snapshotServerJSON);
      snapshotServer.setTableFieldToMapField(conversionMap);

      PubSubWebSocketAppDataQuery wsQuery = new PubSubWebSocketAppDataQuery();
      wsQuery.setUri(uri);
      snapshotServer.setEmbeddableQueryInfoProvider(wsQuery);

      PubSubWebSocketAppDataResult wsResult = dag.addOperator("QueryResult", new PubSubWebSocketAppDataResult());
      wsResult.setUri(uri);
      Operator.InputPort<String> queryResultPort = wsResult.input;

      dag.addStream("MapProvider", topCount, snapshotServer.input);
      dag.addStream("Result", snapshotServer.queryResult, queryResultPort);
    } else {
      ConsoleOutputOperator operator = dag.addOperator(operatorName, new ConsoleOutputOperator());
      operator.setStringFormat(operatorName + ": %s");

      dag.addStream("MapProvider", topCount, operator.input);
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
package org.yidu.novel.service.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.transaction.annotation.Transactional;
import org.yidu.novel.bean.ArticleSearchBean;
import org.yidu.novel.dto.CategoryCountDTO;
import org.yidu.novel.entity.TArticle;
import org.yidu.novel.service.ArticleService;
import org.yidu.novel.utils.Pagination;
import org.yidu.novel.utils.Utils;

public class ArticleServiceImpl extends HibernateSupportServiceImpl implements ArticleService {

    @Override
    public List<TArticle> find(final ArticleSearchBean searchBean) {

        // 初期SQL做成
        StringBuffer hql = new StringBuffer();
        hql.append("From TArticle WHERE deleteflag=false  ");
        List<Object> params = new ArrayList<Object>();

        buildCondtion(searchBean, hql, params);

        Pagination pagination = searchBean.getPagination();
        // 添加排序信息
        if (pagination != null) {
            hql.append(pagination.getSortInfo());
            return this.findByRange(hql.toString(), pagination.getStart(), pagination.getPageSize(), params);
        } else {
            hql.append("ORDER BY articleno");
            return this.find(hql.toString(), params);
        }
    }

    /**
     * 创建检索条件
     *
     * @param searchBean
     *            检索条件
     * @param hql
     *            HQL
     * @param params
     *            参数
     */
    private void buildCondtion(ArticleSearchBean searchBean, StringBuffer hql, List<Object> params) {
        // 小说号条件追加
        if (searchBean.getArticleno() != 0) {
            hql.append(" AND articleno = ? ");
            params.add(searchBean.getArticleno());
        }
        // 小说名条件追加
        if (StringUtils.isNotEmpty(searchBean.getArticlename())) {
            hql.append(" AND articlename = ? ");
            params.add(searchBean.getArticlename());
        }
        // 拼音条件追加
        if (StringUtils.isNotEmpty(searchBean.getPinyin())) {
            hql.append(" AND pinyin = ? ");
            params.add(searchBean.getPinyin());
        }
        // 小说名条件追加
        if (searchBean.getFromArticleno() != 0) {
            hql.append(" AND articleno > ? ");
            params.add(searchBean.getFromArticleno());
        }
        // 小说作者条件追加
        if (StringUtils.isNotEmpty(searchBean.getAuthor())) {
            hql.append(" AND author = ? ");
            params.add(searchBean.getAuthor());
        }

        // 小说种别追加
        if (searchBean.getCategory() != null && searchBean.getCategory() != 0) {
            hql.append(" AND category = ? ");
            params.add(searchBean.getCategory());
        }

        // 完本标识追加
        if (searchBean.getFullflag() != null && searchBean.getFullflag()) {
            hql.append(" AND fullflag = TRUE ");
        }

        // 小说编号数组追加
        if (StringUtils.isNotEmpty(searchBean.getArticlenos())) {
            hql.append(" AND articleno in ( " + searchBean.getArticlenos() + " )  ");
        }

        // 条件追加
        if (StringUtils.isNotEmpty(searchBean.getKey())) {
            // 文章名
            hql.append(" AND  (LOWER(articlename) like '%"
                    + StringEscapeUtils.escapeSql(searchBean.getKey().toLowerCase()) + "%' OR LOWER(author) like '%"
                    + StringEscapeUtils.escapeSql(searchBean.getKey().toLowerCase()) + "%' )");
        }

        if (searchBean.getAuthorid() != null && searchBean.getAuthorid() > 0) {
            // 作者号指定的话,添加作者号
            hql.append(" AND authorid = ? ");
            params.add(searchBean.getAuthorid());
        }

        if (Utils.isDefined(searchBean.getTag())) {
            // 标签指定的话,添加标签条件
            hql.append(" AND articlename like '%"
                    + StringEscapeUtils.escapeSql(searchBean.getTag()) + "%'");
        }

        if (searchBean.getPageType() != ArticleSearchBean.PageType.authorPage
                && searchBean.getPageType() != ArticleSearchBean.PageType.adminPage) {
            // 非作者和管理员界面的话过滤空小说
            hql.append(" AND lastupdate is not null ");
            hql.append(" AND lastchapterno is not null ");
        }
    }

    @Override
    public TArticle getByNo(final int articleno) {
        return this.get(TArticle.class, articleno);
    }

    @Override
    public void deleteByNo(final int articleno) {
        TArticle article = getByNo(articleno);
        this.delete(article);

    }

    @Override
    public void save(TArticle article) {
        this.saveOrUpdate(article);
    }

    @Override
    public Integer getCount(ArticleSearchBean searchBean) {
        StringBuffer hql = new StringBuffer();
        List<Object> params = new ArrayList<Object>();
        hql.append("SELECT count(*) FROM TArticle where deleteflag = false ");
        buildCondtion(searchBean, hql, params);
        return this.getIntResult(hql.toString(), params);
    }

    @Override
    public List<CategoryCountDTO> getCountPerCategory() {
        String sql = " SELECT category,count(*) FROM t_article where deleteflag = false group by category ";
        return this.yiduJdbcTemplate.query(sql, new BeanPropertyRowMapper<CategoryCountDTO>(CategoryCountDTO.class));
    }

    @Override
    public void updateVisitStatistic(int articleno) {
        String sql = "update TArticle set   dayvisit  = dayvisit +1 , weekvisit= weekvisit +1 ,"
                + "monthvisit =monthvisit+1 , allvisit = allvisit +1 where articleno =  ? ";
        this.sqlQuery(sql, articleno);
    }

    @Override
    public void updateVoteStatistic(int articleno) {
        String sql = "update TArticle set  dayvote  = dayvote +1 , weekvote= weekvote +1 ,"
                + "monthvote =monthvote+1 , allvote = allvote +1 where articleno =  ? ";
        this.sqlQuery(sql, articleno);
    }

    @Override
    @Transactional
    public void cleanStatistics() {
        logger.info("cleanStatistics start");
        String sql = "update t_article set dayvote = 0 ,dayvisit = 0";
        Calendar cal = Calendar.getInstance();
        int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
        // 每周一清空周统计信息
        if (dayOfWeek == Calendar.MONDAY) {
            sql += ",weekvote = 0,weekvisit=0";
        }
        // 每月1号清空月统计信息
        int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
        if (dayOfMonth == 1) {
            sql += ",monthvote = 0,monthvisit=0";
        }
        this.yiduJdbcTemplate.update(sql);
        logger.info("cleanStatistics end");
    }

    @Override
    public TArticle findByPinyinRegularRxpressions(String pinyin) {
        String sql = "SELECT * FROM t_article where pinyin ~ '^" + pinyin + "[\\d]*$' order by pinyin desc;";
        List<TArticle> articleList = this.yiduJdbcTemplate.query(sql, new BeanPropertyRowMapper<TArticle>(
                TArticle.class));
        if (articleList != null && articleList.size() > 0) {
            return articleList.get(0);
        }
        return null;
    }

    @Override
    public Integer getCountByJDBC(ArticleSearchBean searchBean) {
        StringBuffer sql = new StringBuffer();
        List<Object> params = new ArrayList<Object>();
        sql.append("SELECT count(*) FROM t_article where deleteflag = false ");
        buildCondtion(searchBean, sql, params);
        return yiduJdbcTemplate.queryForObject(sql.toString(), params.toArray(), Integer.class);
    }

    @Override
    public List<TArticle> findRecommendArticleList(final int category, int articleno, final int count) {
        List<Object> params = new ArrayList<Object>();
        params.add(articleno);
        StringBuffer hql = new StringBuffer();
        hql.append("FROM TArticle where articleno > ? and deleteflag = false ");
        if (category != 0) {
            hql.append(" AND  category = ?  ");
            params.add(category);
        }
        hql.append(" AND lastupdate is not null ");
        hql.append(" AND lastchapterno is not null ");
        hql.append("  order by articleno  ");
        return this.findByRange(hql.toString(), 1, count, params);
    }

    @Override
    public List<TArticle> findRandomRecommendArticleList(final int count) {
        List<Object> params = new ArrayList<Object>();
        StringBuffer sql = new StringBuffer();
        // 为了提升性能,没有用hibernate,写了nactiveSQL
        sql.append(" SELECT * ");
        sql.append(" FROM  ( ");
        sql.append("    SELECT DISTINCT 1 + floor(random() * (select max(articleno) from t_article) )::integer AS articleno ");
        sql.append("    FROM   generate_series(1, 50) g ");
        sql.append("    ) r ");
        sql.append(" JOIN   t_article USING (articleno) ");
        sql.append(" where  deleteflag = false ");
        sql.append(" AND lastupdate is not null  ");
        sql.append(" AND lastchapterno is not null ");
        sql.append("LIMIT  ?");
        params.add(count);

        return this.yiduJdbcTemplate.query(sql.toString(), params.toArray(), new BeanPropertyRowMapper<TArticle>(
                TArticle.class));
    }

    @Override
    public List<TArticle> findRelativeArticleList(List<String> keys, String sortCol, boolean isAsc, int limitNum) {

        List<Object> params = new ArrayList<Object>();
        params.addAll(keys);
        params.add(sortCol);

        String cond = "";
        boolean isFirst = true;
        for (int i = 0; i < keys.size(); i++) {
            if (isFirst) {
                cond += " ?  % articlename ";
                isFirst = false;
            } else {
                cond += (" OR ?  % articlename ");
            }
        }
        String sql = "SELECT * FROM t_article where " + cond + "  order by ?  " + (isAsc ? "ASC" : "DESC") + " limit "
                + limitNum;
        return this.yiduJdbcTemplate.query(sql, params.toArray(), new BeanPropertyRowMapper<TArticle>(TArticle.class));
    }
}


text:
title: Option 4 - «Subscription to the print edition of»
keywords: Tasks
sidebar: guide-tasks_sidebar
toc: true
permalink: en/gt_flexberry-ember-case-04.html
lang: en
autotranslated: true
hash: 5fb1a8bd81c91e437afb561cc6e33854b9cb61707bebbf080e46b7897f76a660
summary: the Variant end-to-end specifications for the design and development using the framework Flexberry Ember
---

## Job

In the framework of the practical part of the course you will have developed end-to-end example: application «Subscription to the print edition of» (IP for automation of accounting of subscribers to the printed edition).

The first part of the practical exercises will be devoted to the development of basic technologies, such as C#, databases, client technology, etc., the second part will include a study of the possibilities of the platform Flexberry to efficiently create applications.

## General description of the subject area

Paper Newspapers and magazines delivered by subscription. You have to develop a web application in which you can select a publication and subscribe to it. The unit of time for a subscription is a calendar month. You can subscribe for any number of months from 1 to 6 within six months or by 12 (January to December). The subscription for the following month is issued not later than the 15th day of the current month. In the case of a subscription in whole on half (January - June or July - December) the user receives a 5% discount. An annual subscription costs 10% cheaper.
Each edition has a number of releases in a month or in six months. If the publication is published every month, the subscription is possible only for months when the edition comes out. The months in which the edition comes out are not included in the calculation of discounts.
The application are publishers, who are filling the information available to subscribers Newspapers and magazines, confirmed the receipt of money for the subscription, and translate it as "Delivered". Postal workers see information about the subscription and execute the delivery of publications from publishers to subscribers, noting the fact of delivery (delivered this month). Subscribers use the application to subscribe.

Specifications:

* The application is realized as [SPA -] (https://ru.wikipedia.org/wiki/Одностраничное_приложение) bakenda on the C# and EmberJS on the frontend.
* Data is stored in the database Postgres.

## Practical task no 1 - server development (C#, .NET ASP.NET)

Will be required for implementation:

* Microsoft Visual Studio 2017
* Git for Windows

### Job

You want to implement the algorithm for calculating the price based on the input data:
* The subscription price for one month
* Months absence edition
* The months that the user has selected to subscribe
The output should be represented by the subscription price with the discount, if applicable, and report the amount of the discount that was received.
The implementation should be done .net-libraries and to prepare unit tests (xUnit), to demonstrate the percentage of code coverage from unit tests (the more the better).

### Providing performance verification

The implemented solution (Visual Studio Solution) to put it all in a repository on GitHub (the solution must compile and run). A link to the repository to provide the teachers of the course.

## Practical exercise No. 2 - Client-side development (HTML, CSS, JS, jQuery)

Will be required for implementation:

* Code editor for client development: Visual Studio Code
* Git for Windows

### Job

With use of opportunities HTML, CSS, JS, jQuery mark up a form, which is used to specify the months for which he wants to subscribe the user. Months need to check. Months of absence of the publication needs to be blocked for selection. To prepare a static switch for selecting publications, calendar year and semester subscription (subscription for the whole year is available when the semester is not selected). Implement additional buttons "to Sign up for the half and Sign up for a year", which will put the appropriate checkboxes, skipping blocked.

### to deliver results

Implemented project to place in a repository on GitHub in the form of resident pages GitHub Pages that allows you to view the finished result. A link to the published repository and thus the project to provide teachers of the course.

## Practical exercise No. 3 - Client-side development using a SPA-framework (EmberJS)

Will be required for implementation:

* Code editor for client development: Visual Studio Code
* Git for Windows

### Job

You want to implement EmberJS application, which will be implemented form, which is used to specify the months for which he wants to subscribe the user.
To develop in the form of an Ember component, the controls that implement the logic of select the checkboxes of the months for which to subscribe. Months of absence of the publication needs to be blocked for selection. To prepare a static switch for selecting publications, calendar year and semester subscription (subscription for the whole year is available when the semester is not selected). Implement additional buttons "to Sign up for the half and Sign up for a year", which will put the appropriate checkboxes, skipping blocked. To embed this component on the form.

In EmberJS-utilities are required to implement the algorithm for calculating the price based on the input data:
* The subscription price for one month
* Months absence edition
* The months that the user has selected to subscribe
The output should be represented by the subscription price with the discount, if applicable, and report the amount of the discount that was received.

To use this component in EmberJS-utility when you change any parameter and recalculate to display the subscription cost to the user.

### to deliver results

Implemented project to place in a repository on GitHub in the form of EmberJS project and published the app to GitHub Pages, which allow you to view the finished result. A link to the published repository and thus the project to provide teachers of the course.

## Practical assignment No. 4 Database

Will be required for implementation:

* Postgres
* pgAdmin
* Git for Windows

### Job

For the specified subject area to implement the database, fill the database with scripts (at least 5 records per table). Implement scripts to create constraints, indexes.

Prepare SQL scripts to obtain the following information:

1. Display the top 5 publishers by revenue for periodicals for the year
2. Display the top 5 subscribers, who spend the maximum amount of money per subscription on average per year
3. To obtain the name of the publication, which is least of all
4. Display all rooms and publication in the order received on the specified subscription key
5. Find users who subscribe to the same publication at least 3 years in a row

### to deliver results

Implemented scripts to create the database and fill a backup of the database commit in the GitHub repository. A link to the repository to provide the teachers of the course.

## the Practical task №5 - IC Design

Will be required for implementation:

* Flexberry Designer

### Job

Draw a UML diagram for the designated subject area. The composition of the diagrams is determined by the trainees, but should provide a full description of the subject area.

### to deliver results

The result is uploaded in the format of a CRP stage of Flexberry Designer. Stage (a file with the extension *.CRP) should commit to the repository on GitHub, the link to provide the teachers of the course.

## Practical task №6 - the Object design and generation applications

Will be required for implementation:

* Flexberry Designer
* Microsoft Visual Studio 2017
* Postgres
* Git for Windows

### Job

To accomplish the object design and the generation of Ember-application for the described subject area. As a basis to use the previously implemented the UML model. Generation of the application and the database must be executed by means Flexberry Designer, the application must meet the requirements and be fully functional. Submission must be high quality customized signatures to classes and attributes on the forms should be adequate. The list of forms and attribute composition must correspond to the subject area and cover all of the required business function.

### to deliver results

The generated application and the scripts to create the database should be put in a repository on GitHub. To provide teachers with a reference to the repository.

## Practical task №7 - Development of business logic applications

Will be required for implementation:

* Flexberry Designer
* Microsoft Visual Studio 2017
* Postgres
* Git for Windows

### Job

In generated using Flexberry Designer application is required to implement the following business logic.

1. To implement a business server that will monitor the limit to create the subscription for the following month no later than the 15th of the month.
2. To implement a business server, which will create objects of delivery for the specified subscription when it is saved.
3. To implement a business server to restrict editing the subscription, if it is put in the status "Delivered".
4. To add a stored field in the class Publication, which will display the subscription cost for half of the year.
5. To add a stored field in the class Publication, which will display the subscription cost for a year.

### to deliver results

Modified business logic should be included in the development application and sakimichan in the appropriate repository. Link to the repository is available for inspection by the course instructors.

## Practical exercise No. 8 - Development of the UI application logic

Will be required for implementation:

* Microsoft Visual Studio 2017
* Postgres
* Code editor for client development: Visual Studio Code
* Git for Windows

### Job

Tie the previously implemented EmberJS additional forms and components of data from the database.
To transfer the generated application and implement the integration of the form to create the subscription with the business logic of the application. On the form controls whether the data should be taken from the database (through ORM and Lookup). Fill data shall also work with the saving.
You want to configure a beautiful look for all forms of application. To improve the visual design theme. Implement shortcuts on the desktop application for quick access to frequently used functions.
Implement additional forms, which will display the results of a query of the jobs database.

### to deliver results

Modified UI logic should be included in the development application and sakimichan in the appropriate repository. Link to the repository is available for inspection by the course instructors.

## Practical assignment No. 9 Functional subsystems Flexberry

Will be required for implementation:

* Flexberry Designer
* Microsoft Visual Studio 2017
* Code editor for client development: Visual Studio Code
* Postgres
* Git for Windows

### Job

The implemented application to configure the subsystem powers. Users publishing and mail will start the application administrator, subscribers register on their own (simplified scheme). Authorization form-based. To create a hierarchy of roles, add transactions to view information about the delivery and to grant rights to administrators only. To configure the roles and assign these roles to users.
To configure the auditing subsystem. In the developed application, all changes to data objects must be recorded in the audit. In the navigation menu, you should add forms of audit that should only be shown to administrators.

### to deliver results

The revised application must be seamicro in the appropriate repository. Additionally, the repository must be added to the SQL scripts that need to perform to run an application with a subsystem of powers and audit. Link to the repository is available for inspection by the course instructors.


text:
var Action = require('./Action');

module.exports = ExplosiveArrow = function (data, level) {
	if (data == null) {
		Action.call(this, level, "explosive-arrow", 4000, 700);

		this.data.angle = 0;
		this.data.speed = 0.8;
		this.data.triggered = false;
	}
	else {
		Action.call(this, data.level, "explosive-arrow", data.cooldown, 700);
		this.data = data;
	}
}

ExplosiveArrow.prototype = new Action();
ExplosiveArrow.prototype.constructor = ExplosiveArrow;

ExplosiveArrow.prototype.getName = function () {
	return "Explosive Arrow";
}

ExplosiveArrow.prototype.getTooltip = function() {
	return "Arrow that explodes upon impact (AoE)";
}

ExplosiveArrow.prototype.getActiveTooltipData = function() {
	return this.getArrowHit() + " arrow damage
" + this.getExplosionHit() + " exploding damage
";
}

ExplosiveArrow.prototype.getArrowHit = function() {
	return 3 + this.data.level * 2;
}

ExplosiveArrow.prototype.getExplosionHit = function() {
	return 5 + this.data.level * 2;
}

ExplosiveArrow.prototype.update = function (fromSprite, delta) {
	this.data.manaCost = 4 + this.data.level * 4;

	if (this.data.triggered && delta != null) {

		if (global != null && global.level != null) {
			if (this.data.triggeredState == 1) {
				this.moveProjectile(delta);

				for (var i = 0; i < global.level.spriteList.length; i++) {
					if (fromSprite.data.isPlayer != global.level.spriteList[i].data.isPlayer) {
						var distance = Math.sqrt(Math.pow(this.data.x - global.level.spriteList[i].data.x, 2) + Math.pow(this.data.y - global.level.spriteList[i].data.y, 2));

						if (distance < global.level.spriteList[i].data.minDistance) {
							global.level.spriteList[i].hit(this.getArrowHit(), fromSprite, false);
							this.data.triggeredState = 2;
							fromSprite.broadcastState();
						}
					}
				}
			}
			else if (this.data.triggeredState == 2) {
				this.data.triggeredState = 3;

				for (var i = 0; i < global.level.spriteList.length; i++) {
					if (fromSprite.data.isPlayer != global.level.spriteList[i].data.isPlayer) {
						if (this.getDistance(this.data.x, this.data.y, global.level.spriteList[i].data.x, global.level.spriteList[i].data.y) < this.data.distance) {
							global.level.spriteList[i].hit(this.getExplosionHit(), fromSprite, false);
						}
					}
				}
			}
		}
		else {
			if (this.data.triggeredState == 1) {
				this.moveProjectile(delta);

				game.ctx.beginPath();
		    	game.ctx.arc(this.data.x, this.data.y, 4, 0, 2 * Math.PI, false);
				game.ctx.fillStyle = "brown";
		    	game.ctx.fill();
		    	game.ctx.closePath();
		    }
		    else {
				game.ctx.save();
				game.ctx.beginPath();
				game.ctx.arc(this.data.x, this.data.y, this.data.distance * 0.8, 0, 2 * Math.PI, false);
				game.ctx.globalAlpha = 0.2;
				game.ctx.fillStyle = lavaPattern;
				game.ctx.fill();
				game.ctx.closePath();
				game.ctx.restore();
		    }
		}

		if (this.data.triggeredTime + 500 < (new Date()).getTime() && this.data.triggeredState == 1) {
			this.data.triggered = false;
		}
		else if (this.data.triggeredTime + 1000 < (new Date()).getTime()) {
			this.data.triggered = false;
		}
	}
}

ExplosiveArrow.prototype.triggerEvent = function (fromSprite, mouseX, mouseY, toSprite) {
	var success = false;

	if (fromSprite.data.isPlayer != toSprite.data.isPlayer) {
		success = true;

		this.data.distance = 50 + 3 * this.data.level;
		this.data.triggered = true;
		this.data.triggeredState = 1;

		this.data.angle = (Math.PI/180) * this.getAngle(fromSprite.data.x, fromSprite.data.y, toSprite.data.x, toSprite.data.y);
		this.data.x = fromSprite.data.x;
		this.data.y = fromSprite.data.y;
	}

	return success;
}


text:
package com.example.newbook4;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.widget.Toast;

public class BaseActivity extends Activity {
	protected Context ctx;

	protected RequestQueue requestQueue = null;

	protected MyApplication myApplication;

	protected BaseInfo baseInfo;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ctx = this;
		requestQueue = Volley.newRequestQueue(ctx);
		myApplication = (MyApplication) getApplication();
		baseInfo = myApplication.baseInfo;

	}

	protected void showToast(final String strToast) {

		runOnUiThread(new Runnable() {
			public void run() {
				Toast.makeText(ctx, strToast, Toast.LENGTH_SHORT).show();
			}

		});
	}
}


text:
Neurohackweek

Summer school for neuroimaging and data science

University of Washington eScience Institute

September 4th-8th, 2017


text:
package org.apache.hadoop.hdfs.server.namenode;

import io.hops.metadata.HdfsStorageFactory;
import io.hops.metadata.hdfs.TablesDef;
import io.hops.metadata.hdfs.dal.INodeDataAccess;
import io.hops.transaction.handler.HDFSOperationType;
import io.hops.transaction.handler.LightWeightRequestHandler;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hdfs.DFSConfigKeys;
import org.apache.hadoop.hdfs.DistributedFileSystem;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.apache.hadoop.hdfs.MiniDFSNNTopology;
import org.apache.hadoop.io.IOUtils;
import org.junit.Test;

import java.io.IOException;
import java.util.Random;
import org.apache.hadoop.hdfs.client.HdfsClientConfigKeys;

import static org.junit.Assert.assertTrue;

public class TestLeaseRestart {

  Configuration getConf(){
    Configuration conf = new Configuration();
    conf.setInt(DFSConfigKeys.DFS_CLIENT_FAILOVER_MAX_ATTEMPTS_KEY, /*default 15*/ 1);
    conf.setInt(DFSConfigKeys.DFS_CLIENT_RETRY_MAX_ATTEMPTS_KEY, /*default 10*/ 1);
    conf.setInt(DFSConfigKeys.DFS_CLIENT_FAILOVER_SLEEPTIME_BASE_KEY, /*default 500*/ 500);
    conf.setInt(DFSConfigKeys.DFS_CLIENT_FAILOVER_SLEEPTIME_MAX_KEY, /*default 15000*/1000);
    conf.setInt(DFSConfigKeys.DFS_CLIENT_FAILOVER_CONNECTION_RETRIES_KEY, /*default 0*/ 0);
    conf.setInt(DFSConfigKeys.DFS_CLIENT_FAILOVER_CONNECTION_RETRIES_ON_SOCKET_TIMEOUTS_KEY,
            /*default 0*/0);
    conf.setInt(DFSConfigKeys.IPC_CLIENT_CONNECT_MAX_RETRIES_ON_SOCKET_TIMEOUTS_KEY, /*default
    45*/ 2);
    conf.setInt(DFSConfigKeys.IPC_CLIENT_CONNECT_MAX_RETRIES_KEY, /*default 10*/ 1);
    conf.set(HdfsClientConfigKeys.Retry.POLICY_SPEC_KEY,"1000,2");

    return conf;
  }

  /*
  After cluster failure, we ended up in a situation where for some
  leases there were no corresponding inodes. Which resulted in an NPE
  and the NN failed to start. We have yet to find the cause of orphan
  leases. This JIRA only fixed the NPE symptom of the cause.
   */
  @Test
  public void testMissingInodeLease() throws Exception {
    final int NN_COUNT=1;
    final String fileName="testFile";
    MiniDFSCluster cluster = new MiniDFSCluster.Builder(getConf())
            .nnTopology(MiniDFSNNTopology.simpleHOPSTopology(NN_COUNT))
            .numDataNodes(1).format(true).build();

    cluster.setLeasePeriod(3*1000, 5*1000);
    Random rand = new Random(System.currentTimeMillis());
    DistributedFileSystem fs = cluster.getFileSystem(rand.nextInt(NN_COUNT));
    FSDataOutputStream out = fs.create(new Path("/"+fileName));
    try {
      out.write(1);
      out.hflush();
      cluster.shutdownNameNodes();
      fs.getClient().getLeaseRenewer().interruptAndJoin();
      IOUtils.closeStream(out);
      fs.getClient().close();

      new LightWeightRequestHandler(HDFSOperationType.TEST) {
        @Override
        public Object performTask() throws IOException {
          INodeDataAccess da = (INodeDataAccess) HdfsStorageFactory.getDataAccess(INodeDataAccess.class);
          da.deleteInode(fileName);
          return null;
        }
      }.handle();

      cluster.restartNameNodes();
      cluster.setLeasePeriod(3*1000, 5*1000);

      Thread.sleep(10000);

      assertTrue("The lease should eventually be removed by the lease manager",
              cluster.getNamesystem().getLeaseManager().getNumSortedLeases()==0);

      // remove the inode for the file
    } catch (IOException e ){
      e.printStackTrace();
    } finally {
      cluster.shutdown();
    }
  }

}


text:
package test.it;

import com.irwin13.igen.config.ConfigLoader;
import com.irwin13.igen.config.IgenConfig;
import com.irwin13.igen.config.YamlConfigLoader;
import org.junit.Assert;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import java.util.Arrays;

/**
 * Created by irwin on 24/03/17.
 */
@Category(IntegrationTest.class)
public class ConfigTest {

    // @Test(groups = "IntegrationTest")
    @Test
    public void shouldReadConfigSuccessfully() {
        ConfigLoader configLoader = new YamlConfigLoader();
        IgenConfig config = configLoader.loadConfig("test-config.yaml");

        Assert.assertNotNull(config);
        Assert.assertEquals("igen-example", config.getAppName());
        Assert.assertEquals("1.0", config.getAppVersion());
        Assert.assertEquals("postgresql", config.getDbVendor());
        Assert.assertEquals("pg", config.getDbDriver());
        Assert.assertEquals("db", config.getDbUrl());
        Assert.assertEquals("pglocal", config.getDbUser());
        Assert.assertEquals("pglocal", config.getDbPass());
        Assert.assertEquals(2, config.getTableList().size());
        Assert.assertTrue(config.getTableList().containsAll(Arrays.asList("USER", "ORG")));
        Assert.assertEquals("template", config.getTemplateFolder());
        Assert.assertEquals("freemarker", config.getTemplateEngine());
    }

    // @Test(expectedExceptions = RuntimeException.class, groups = "IntegrationTest")
    @Test(expected = RuntimeException.class)
    public void shouldThrowRuntimeException() {
        ConfigLoader configLoader = new YamlConfigLoader();
        IgenConfig config = configLoader.loadConfig("not-exists.yaml");
        Assert.assertNull(config);
    }
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.sunshine</groupId>
    <artifactId>sparkdemo</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>sparkdemo</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <scala.version>2.10.3</scala.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.scala-lang</groupId>
            <artifactId>scala-compiler</artifactId>
            <version>${scala.version}</version>
            <scope>compile</scope>
        </dependency>

        <!--spark -->

        <dependency>
            <groupId>org.apache.spark</groupId>
            <artifactId>spark-core_2.10</artifactId>
            <version>1.0.0</version>
        </dependency>

        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-client</artifactId>
            <version>2.4.0</version>
        </dependency>

        <dependency>
            <groupId>org.apache.spark</groupId>
            <artifactId>spark-streaming_2.10</artifactId>
            <version>1.0.0</version>
        </dependency>

        <!-- logging -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.6</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.6</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
    </dependencies>

    <build>
        <defaultGoal>install</defaultGoal>
        <sourceDirectory>src/main/scala</sourceDirectory>
        <testSourceDirectory>src/test/scala</testSourceDirectory>

        <plugins>

            <!-- the Maven compiler plugin will compile Java source files -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.5.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <version>2.6</version>
                <configuration>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>

            <!-- the Maven Scala plugin will compile Scala source files -->
            <plugin>
                <groupId>net.alchim31.maven</groupId>
                <artifactId>scala-maven-plugin</artifactId>
                <version>3.1.6</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>compile</goal>
                            <goal>testCompile</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

            <!-- configure the eclipse plugin to generate eclipse project descriptors for a Scala project -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-eclipse-plugin</artifactId>
                <version>2.9</version>
                <configuration>
                    <projectnatures>
                        <projectnature>org.scala-ide.sdt.core.scalanature</projectnature>
                        <projectnature>org.eclipse.jdt.core.javanature</projectnature>
                    </projectnatures>
                    <buildcommands>
                        <buildcommand>org.scala-ide.sdt.core.scalabuilder</buildcommand>
                    </buildcommands>
                    <classpathContainers>
                        <classpathContainer>org.scala-ide.sdt.launching.SCALA_CONTAINER</classpathContainer>
                        <classpathContainer>org.eclipse.jdt.launching.JRE_CONTAINER</classpathContainer>
                    </classpathContainers>
                    <excludes>
                        <exclude>org.scala-lang:scala-library</exclude>
                        <exclude>org.scala-lang:scala-compiler</exclude>
                    </excludes>
                    <sourceIncludes>
                        <sourceInclude>**/*.scala</sourceInclude>
                        <sourceInclude>**/*.java</sourceInclude>
                    </sourceIncludes>
                </configuration>
            </plugin>

        </plugins>
    </build>
</project>


text:
namespace apps {

struct FileHandler {
  FileHandler();
  ~FileHandler();
  FileHandler(const FileHandler& file_handler);

  // Represents a single file handler "accept" entry, mapping a MIME type to a
  // set of file extensions that can be handled by the handler.
  struct AcceptEntry {
    AcceptEntry();
    ~AcceptEntry();
    AcceptEntry(const AcceptEntry& accept_entry);

    base::Value AsDebugValue() const;

    // A MIME type that can be handled by the file handler.
    std::string mime_type;

    // A set of one or more file extensions that can be handled by the file
    // handler, corresponding to the MIME type.
    base::flat_set<std::string> file_extensions;
  };

  base::Value AsDebugValue() const;

  // The URL that will be navigated to when dispatching on a file with a
  // matching MIME type or file extension.
  GURL action;

  // The user-visible name for the file type, e.g. "ACME Word Processor document
  // file". May be empty.
  std::u16string display_name;

  // A collection of MIME type to file extensions mappings that the handler
  // will match on.
  using Accept = std::vector<AcceptEntry>;
  Accept accept;

  // The icons defined for this file handler, to be used as file type
  // association icons in OS surfaces. The sizes in `downloaded_icons`, when
  // present, represent the actual size of a bitmap that was downloaded.
  std::vector<IconInfo> downloaded_icons;
};
using FileHandlers = std::vector<FileHandler>;

// Get a set of all MIME types supported by any of |file_handlers|.
std::set<std::string> GetMimeTypesFromFileHandlers(
    const FileHandlers& file_handlers);

// Get a set of all MIME types supported by |file_handler|.
std::set<std::string> GetMimeTypesFromFileHandler(
    const FileHandler& file_handler);

// Get a set of all file extensions supported by any of |file_handlers|.
std::set<std::string> GetFileExtensionsFromFileHandlers(
    const FileHandlers& file_handlers);

// Get a set of all file extensions supported by |file_handler|.
std::set<std::string> GetFileExtensionsFromFileHandler(
    const FileHandler& file_handler);

bool operator==(const FileHandler::AcceptEntry& accept_entry1,
                const FileHandler::AcceptEntry& accept_entry2);
bool operator==(const FileHandler& file_handler1,
                const FileHandler& file_handler2);

bool operator!=(const FileHandler::AcceptEntry& accept_entry1,
                const FileHandler::AcceptEntry& accept_entry2);
bool operator!=(const FileHandler& file_handler1,
                const FileHandler& file_handler2);

}  // namespace apps

#endif  // COMPONENTS_SERVICES_APP_SERVICE_PUBLIC_CPP_FILE_HANDLER_H_


text:
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')

class Accountable::ConfirmationsController < AuthHelpers::Controller::Confirmable
  layout nil
end

describe Accountable::ConfirmationsController do
  mock_models :accountable

  describe :get => :new do
    expects :new, :on => Accountable, :returns => mock_accountable
    should_assign_to :accountable, :with => mock_accountable
  end

  describe :post => :create, :accountable => {'these' => 'params'} do
    expects :find_and_resend_confirmation_instructions, :on => Accountable, :with => {'these' => 'params'}, :returns => mock_accountable

    describe "with valid params" do
      expects :errors, :on => mock_accountable, :returns => []

      should_assign_to :accountable, :with => mock_accountable
      should_redirect_to { new_accountable_session_url }
      should_set_the_flash :notice, :to => "We sent confirmation instructions to your email, please check your inbox."
    end

    describe "with invalid params" do
      expects :errors, :on => mock_accountable, :returns => ['invalid']

      should_assign_to :accountable, :with => mock_accountable
      should_render_template 'new'
    end
  end

  describe :get => :show, :accountable => {'these' => 'params'} do
    expects :find_and_confirm, :on => Accountable, :with => {'these' => 'params'}, :returns => mock_accountable

    describe "with valid params" do
      expects :errors, :on => mock_accountable, :returns => []

      should_redirect_to proc { new_accountable_session_url }, :with_expectations => true
      should_set_the_flash :notice, :to => "Accountable was successfully confirmed."
    end

    describe "with invalid params" do
      before(:each) do
        mock_accountable.stub!(:errors).and_return(mock_error = mock("error"))
        mock_error.stub!(:empty?).and_return(false)
        mock_error.stub!(:on).with(:perishable_token).and_return("is invalid")
      end

      should_redirect_to "/accountable/confirmations/new"
      should_set_the_flash :error, :to => "is invalid"
    end
  end

end


text:
Hooks
=====

_See the [Plugins documentation](Plugins.md) for how to implement hooks._

_Parameters marked as 'editable' can be modified within the callback to change the value outside the plugin._

Publishing
----------

- ### willPublishPost

	Called before publishing a new post

	#### Params

	- \Blight\Interfaces\Models\Post **post**: The post being published

- ### didPublishPost

	Called after publishing a new post

	#### Params

	- \Blight\Interfaces\Models\Post **post**: The post being published

	#### Notes

	- The URL the post was published to can be accessed through the `$post->getPermalink()` method

Output
------

- ### postBodyRaw

	Called when building a post's body, before processing Markdown and typography

	#### Params

	- \Blight\Interfaces\Models\Post **post**: The post being rendered
	- bool **isSummary**: Whether the body content requested is the post's summary
	- string **content**: _(editable)_ The raw Markdown content of the post

- ### postBodyProcessed

	Called when building a post's body, after processing Markdown and typography

	#### Params

	- \Blight\Interfaces\Models\Post **post**: The post being rendered
	- bool **isSummary**: Whether the body content requested is the post's summary
	- string **content**: _(editable)_ The processed HTML content of the post

- ### pageBodyRaw

	Called when building a page's body, before processing Markdown and typography

	#### Params

	- \Blight\Interfaces\Models\Page **page**: The page being rendered
	- string **content**: _(editable)_ The raw Markdown content of the page

- ### pageBodyProcessed

	Called when building a page's body, after processing Markdown and typography

	#### Params

	- \Blight\Interfaces\Models\Page **page**: The page being rendered
	- string **content**: _(editable)_ The processed HTML content of the page

- ### feedPost

	Called when building a post's content in an RSS feed

	#### Params

	- string **feed_type**: The feed format type – either `'atom'` or `'rss'`
	- \Blight\Interfaces\Models\Post **post**: The post being rendered
	- string **title**: _(editable)_ The title of the post
	- string **link**: _(editable)_ The URL for the post to link to. For linked posts, this defaults to the external link.
	- \stdClass **author**: _(editable)_ The author of the post. An object with the properties `name`, `url` and `email`
	- \DateTime **date_published**: _(editable)_ The publish date of the post
	- \DateTime **date_updated**: _(editable)_ The last-updated date of the post
	- string **guid**: _(editable)_ Either the RSS GUID or Atom ID for the post. Defaults to the post's permalink.
	- bool **guid_is_permalink**: _(editable)_
	- string **content**: _(editable)_ The post's raw Markdown content
	- string **summary**: _(editable)_ The post's plaintext summary, or null if not set
	- string **append**: _(editable)_ A string to append to the post content. Defaults to a permalink for linked posts.
	- bool **process_content**: _(editable)_ Whether to process the content as Markdown

- ### renderStyles

	Allows adding styles to rendered pages

	#### Params

	- \Blight\Interfaces\Models\Packages\Theme **theme**: The current theme
	- \Blight\Interfaces\Models\Template **template**: The current template
	- string **name**: The name of the template being rendered
	- array **styles**: _(editable)_ An array of styles

		**External:**

			$styles[]	= '/path/to/styles.css';
			$styles[]	= array('href' => '/path/to/styles.css', 'media' => 'print');

		**Embedded:**

			$styles[]	= 'body { background: #fff; }';

- ### renderScripts

	Allows adding scripts to rendered pages

	#### Params

	- \Blight\Interfaces\Models\Packages\Theme **theme**: The current theme
	- \Blight\Interfaces\Models\Template **template**: The current template
	- string **name**: The name of the template being rendered
	- array **scripts**: _(editable)_ An array of scripts

		**External:**

			$styles[]	= '/path/to/scripts.js';
			$styles[]	= array('src' => '/path/to/scripts.js', 'async' => 'async');

		**Embedded:**

			$styles[]	= 'alert("Scripts");';

- ### processTypography

	Called when applying typographical fixes and helper classes to a block of HTML

	#### Params

	- string **html**: _(editable)_ The HTML being processed


text:
require 'spec_helper'

describe   Spree::Admin::ShippingMethodsController,:type=>"controller" do
  #include Devise::TestHelpers
  describe " ZonesController" do
    def valid_attributes
      {
        :name=>"sedin 2 way", :zone_id=>@pro.to_param, :display_on=>"", :calculator_type=>"Spree::Calculator::FlatPercentItemTotal",:shipping_category_id=>"727197546"
      }
    end

    def mock_user(stubs={})
      @mock_user ||= mock_model(Spree::User, stubs).as_null_object
    end
    before(:each) do
      controller.stub!(:check_http_authorization).and_return(true)
      @pro=Spree::Zone.create(:name=>"railscfactory",:description=>"software concern")
      request.env['warden'] = mock(Warden, :authenticate => mock_user,:authenticate! => mock_user)
      @current_user = 1
    end
    describe "To get the index of the ShippingMethod controller" do
      it "should be successful" do
        get :index,:format=>:json
        response.code.should == "200"
      end
      it "should get the ShippingMethod" do
        store = Spree::ShippingMethod.create! valid_attributes
        get :show, {:id => store.to_param, :format => :json}
        response.code.should == "200"
      end
      it "should get the ShippingMethod" do
        store = Spree::ShippingMethod.create! valid_attributes
        get :show, {:id => 9, :format => :json}
        response.code.should == "200"
      end
      it "should be successful create ShippingMethod" do
        post :create , :shipping_method => {:name=>"sedin 2 way", :zone_id=>@pro.to_param, :display_on=>"", :calculator_type=>"Spree::Calculator::FlexiRate"}, :format => :json
        response.code.should == "201"
      end
      it "should be successful create ShippingMethod" do
        post :create , :shipping_method => {:name=>"sedin 2 way", :zone_id=>"", :display_on=>"", :calculator_type=>"Spree::Calculator::FlexiRate"}, :format => :json
        response.code.should == "200"
      end
      it "should be successful update ShippingMethod" do
        store = Spree::ShippingMethod.create! valid_attributes
        put :update , :id=>store.to_param,:shipping_method => {:name=>"production"}, :format => :json
        response.code.should == "201"
      end
      it "should be successful update ShippingMethod" do
        store = Spree::ShippingMethod.create! valid_attributes
        put :update , :id=>9,:shipping_method => {:name=>""}, :format => :json
        response.code.should == "200"
      end
      it "should delete the ShippingMethod" do
        store = Spree::ShippingMethod.create! valid_attributes
        get :destroy, {:id => store.to_param,:format => :json}
        response.code.should == "200"
      end
    end
  end
end


text:
#include "defs.h"
#include "symtab.h"
#include "gdbtypes.h"
#include "m2-lang.h"

/* FIXME:  For now, just explicitly declare c_val_print and use it instead */

int
m2_val_print (struct type *type, char *valaddr, int embedded_offset,
	      CORE_ADDR address, struct ui_file *stream, int format,
	      int deref_ref, int recurse, enum val_prettyprint pretty)
{
  extern int c_val_print (struct type *, char *, int, CORE_ADDR,
			  struct ui_file *, int, int, int,
			  enum val_prettyprint);
  return (c_val_print (type, valaddr, 0, address, stream, format, deref_ref,
		       recurse, pretty));
}


text:
package com.hribol.bromium.common.generation.replay.functions;

import com.github.jknack.handlebars.Handlebars;
import com.google.inject.Inject;
import com.hribol.bromium.common.generation.common.JsFunctionProvider;
import com.hribol.bromium.common.generation.helper.StepAndWebDriverActionConfiguration;
import com.hribol.bromium.common.generation.replay.invocations.ReplayFunctionInvocation;

import java.io.IOException;

public class ReplayFunctionProvider implements JsFunctionProvider<
        StepAndWebDriverActionConfiguration,
        ReplayFunctionInvocation,
        ReplayFunction
        > {

    private Handlebars handlebars;

    @Inject
    public ReplayFunctionProvider(Handlebars handlebars) {
        this.handlebars = handlebars;
    }

    @Override
    public ReplayFunction get(String jsFunctionName) throws IOException {
        return new FromResourcesReplayFunction(jsFunctionName, handlebars);
    }
}


text:
describe ManageIQ::Providers::Inflector::Methods do
  context "#provider_name" do
    it "returns name for an instance" do
      manager = ManageIQ::Providers::Amazon::CloudManager.new
      expect(manager.provider_name).to eq('Amazon')
    end

    it "returns name for a class" do
      manager = ManageIQ::Providers::Amazon::CloudManager
      expect(manager.provider_name).to eq('Amazon')
    end

    it "returns name for a vm" do
      vm = ManageIQ::Providers::Amazon::CloudManager::Vm.new
      expect(vm.provider_name).to eq('Amazon')
    end
  end
end


text:
"""
Simple class that just handles environment persitence.
"""
__all__ = ['BaseObject']

class BaseObject():
    """
    Base class for all classes that needs to handle an environment
    """

    def __init__(self, **kw):
        """
        Base contructor, just caches the environment

        Keyword arguments:
            env -- cached environment
        """
        self._env = None
        self.env = str(kw.get('env',None))

    @property
    def env(self):
        """
        Returns the environment
        """
        return self._env

    @env.setter
    def env(self, value):
        """
        Sets the environment
        """
        self._env = value