text:
package org.jasig.portlet.notice.filter;

import java.util.List;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apereo.portal.soffit.Headers;
import org.jasig.portlet.notice.INotificationServiceFilter;
import org.jasig.portlet.notice.INotificationServiceFilterChain;
import org.jasig.portlet.notice.NotificationAction;
import org.jasig.portlet.notice.NotificationCategory;
import org.jasig.portlet.notice.NotificationEntry;
import org.jasig.portlet.notice.NotificationResponse;
import org.springframework.http.HttpHeaders;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.stereotype.Component;

/**
 * This {@link INotificationServiceFilter} sets the apiUrl property on
 * {@link NotificationAction} objects within the {@link NotificationResponse}.
 *
 * @since 4.0
 */
@Component
public class ApiUrlSupportFilter extends AbstractNotificationServiceFilter {

    public static final String AUTHORIZATION_PARAMETER_NAME = "_authorization";

    /**
     * The format strings are as follows:
     *

     *
protocol, host, port (if applicable), and context

     *
action id

     *
notification id

     *
Spring CSRF token

     *

     */
    private static final String REST_API_URL_FORMAT =
            "%s/api/v2/action/%s/%s?_csrf=%s&" + AUTHORIZATION_PARAMETER_NAME + "=%s";

    /**
     * This {@link INotificationServiceFilter} must do its work late in the chain because filters
     * commonly add actions.
     */
    public ApiUrlSupportFilter() {
        // needs to order after {@code ReadStateSupportFilter}
        super(AbstractNotificationServiceFilter.ORDER_VERY_LATE);
    }

    @Override
    public NotificationResponse doFilter(HttpServletRequest request, INotificationServiceFilterChain chain) {

        final NotificationResponse response = chain.doFilter();

        final NotificationResponse rslt = response.cloneIfNotCloned();

        // Add apiUrl values to actions with our copy
        for (NotificationCategory category : rslt.getCategories()) {

            for (NotificationEntry entry : category.getEntries()) {

                final List<NotificationAction> actions = entry.getAvailableActions().stream()
                        .peek(action -> {
                            if (StringUtils.isNotBlank(action.getId())
                                    && action.getTarget() != null
                                    && StringUtils.isNotBlank(action.getTarget().getId())) {
                                // Pick up scheme, host[, port,] and context from the request
                                final String requestUrl = request.getRequestURL().toString();
                                final String contextPath = request.getContextPath();
                                final String urlBase = requestUrl.substring(0,
                                        requestUrl.indexOf(contextPath)) + contextPath;
                                final CsrfToken csrf =
                                        (CsrfToken) request.getAttribute(CsrfToken.class.getName());
                                final String apiUrl = String.format(REST_API_URL_FORMAT,
                                        urlBase,
                                        action.getId(),
                                        action.getTarget().getId(),
                                        csrf != null ? csrf.getToken() : null,
                                        getBearerToken(request));
                                action.setApiUrl(apiUrl);
                            }
                        })
                        .collect(Collectors.toList());
                entry.setAvailableActions(actions);

            }

        }

        return rslt;

    }

    private String getBearerToken(HttpServletRequest request) {
        String rslt = ""; // default
        final String authHeader = request.getHeader(HttpHeaders.AUTHORIZATION);
        if (StringUtils.isNotBlank(authHeader)) {                       // Authorization header is present?
            if (authHeader.startsWith(Headers.BEARER_TOKEN_PREFIX)) {   // Authorization header is a Bearer token?
                rslt = authHeader.substring(Headers.BEARER_TOKEN_PREFIX.length());
            }
        }
        return rslt;
    }

}


text:
package com.cengallut.textual.decoration

import com.cengallut.textual.core.CharGrid

object Border {

  def simple(c: Char): Decoration = new Simple(c)

  def box(box: BoxChar.Box): Decoration = new Box(box)

  private class Simple(border: Char) extends Decoration {
    override def decorate(buffer: CharGrid): Unit = {
      for (x <- 0 until buffer.width) {
        buffer.setChar(x, 0, border)
        buffer.setChar(x, buffer.height - 1, border)
      }
      for (y <- 1 until buffer.height - 1) {
        buffer.setChar(0, y, border)
        buffer.setChar(buffer.width - 1, y, border)
      }
    }
  }

  private class Box(box: BoxChar.Box) extends Decoration {
    override def decorate(buffer: CharGrid): Unit = {
      buffer.setChar(0, 0, box.corner.topLeft)
      buffer.setChar(buffer.width - 1, 0, box.corner.topRight)
      buffer.setChar(buffer.width - 1, buffer.height - 1, box.corner.bottomRight)
      buffer.setChar(0, buffer.height - 1, box.corner.bottomLeft)

      for (x <- 1 until buffer.width - 1) {
        buffer.setChar(x, 0, box.line.horizontal)
        buffer.setChar(x, buffer.height - 1, box.line.horizontal)
      }
      for (y <- 1 until buffer.height - 1) {
        buffer.setChar(0, y, box.line.vertical)
        buffer.setChar(buffer.width - 1, y, box.line.vertical)
      }
    }
  }

  val lightShade = simple(BoxChar.Shade.light)

  val mediumShade = simple(BoxChar.Shade.medium)

  val heavyShade = simple(BoxChar.Shade.heavy)

}

redpajama_set_name: RedPajamaGithub


text:
@class GKPlayer;
@class GKChallenge;

@protocol GKChallengeListener <NSObject>
@optional
- (void)player:(GKPlayer*)player didReceiveChallenge:(GKChallenge*)challenge;
- (void)player:(GKPlayer*)player wantsToPlayChallenge:(GKChallenge*)challenge;
- (void)player:(GKPlayer*)player didCompleteChallenge:(GKChallenge*)challenge issuedByFriend:(GKPlayer*)friendPlayer;
- (void)player:(GKPlayer*)player issuedChallengeWasCompleted:(GKChallenge*)challenge byFriend:(GKPlayer*)friendPlayer;
@end


text:
<?php

namespace PW\BannerBundle\Form\Model;

use Symfony\Component\Validator\Constraints as Assert,
    PW\BannerBundle\Document\Promo;

class CreatePromo
{
    /**
     * @Assert\Type(type="PW\BannerBundle\Document\Promo")
     * @Assert\Valid
     */
    protected $promo;

    /**
     * @param Promo $promo
     */
    public function __construct(Promo $promo = null)
    {
        $this->promo = $promo;
    }

    /**
     * @param Promo $promo
     */
    public function setPromo(Promo $promo)
    {
        $this->promo = $promo;
    }

    /**
     * @return \PW\BannerBundle\Document\Promo
     */
    public function getPromo()
    {
        return $this->promo;
    }
}


text:
@class GGGateLayer;

@interface GGGateView : UIView

- (GGGateLayer *)gateLayer;
@end


text:
var express = require('express');
var bodyParser = require('body-parser')
var optimist = require('optimist');
var util = require('util');
var path = require('path');
var env = require('../../spec/environment.js');

var testApp = express();
var DEFAULT_PORT = process.env.HTTP_PORT || env.webServerDefaultPort;
var testAppDir = path.resolve(__dirname, '..');
var defaultAngular = require(path.join(testAppDir, 'ng1/lib/angular_version.js'));

var argv = optimist.describe('port', 'port').
    default('port', DEFAULT_PORT).
    describe('ngversion', 'version of AngularJS to use').
    default('ngversion', defaultAngular).
    argv;

var angularDir = path.join(testAppDir, 'ng1/lib/angular_v' + argv.ngversion);

var main = function() {
  var port = argv.port;
  testApp.use('/ng1/lib/angular', express.static(angularDir));
  testApp.use(express.static(testAppDir));
  testApp.use(bodyParser.json());
  testApp.use(testMiddleware);
  testApp.listen(port);
  util.puts(["Starting express web server in", testAppDir ,"on port", port].
      join(" "));
};

var storage = {};
var testMiddleware = function(req, res, next) {
  if (/ng[1-2]\/fastcall/.test(req.path)) {
    res.status(200).send('done');
  } else if (/ng[1-2]\/slowcall/.test(req.path)) {
    setTimeout(function() {
      res.status(200).send('finally done');
    }, 5000);
  } else if (/ng[1-2]\/fastTemplateUrl/.test(req.path)) {
    res.status(200).send('fast template contents');
  } else if (/ng[1-2]\/slowTemplateUrl/.test(req.path)) {
    setTimeout(function() {
      res.status(200).send('slow template contents');
    }, 5000);
  } else if (/ng[1-2]\/chat/.test(req.path)) {
    if (req.method === 'GET') {
      var value;
      if (req.query.q) {
        value = storage[req.query.q];
        res.status(200).send(value);
      } else {
        res.status(400).send('must specify query');
      }
    } else if (req.method === 'POST') {
      if (req.body.key == 'newChatMessage') {
        if (!storage['chatMessages']) {
          storage['chatMessages'] = [];
        }
        storage['chatMessages'].push(req.body.value);
        res.sendStatus(200);
      } else if (req.body.key == 'clearChatMessages') {
        storage['chatMessages'] = [];
        res.sendStatus(200);
      } else {
        res.status(400).send('Unknown command');
      }
    } else {
      res.status(400).send('only accepts GET/POST');
    }
  } else {
    return next();
  }
};

main();


text:
package uk.gov.gds.ier.transaction.forces.address

import uk.gov.gds.ier.test._
import uk.gov.gds.ier.model._
import uk.gov.gds.ier.service.{AddressService, WithAddressService}
import uk.gov.gds.ier.transaction.forces.InprogressForces

class AddressSelectMustacheTest
  extends MustacheTestSuite
  with AddressForms
  with AddressSelectMustache
  with WithMockForcesControllers
  with WithAddressService
  with MockitoHelpers {

  val addressService = mock[AddressService]

  when(addressService.lookupPartialAddress("WR26NJ")).thenReturn(List.empty)
  when(mockAddressStep.routing).thenReturn(routes("/register-to-vote/forces/address"))
  when(mockAddressManualStep.routing).thenReturn(routes("/register-to-vote/forces/address/manual"))
  when(mockAddressSelectStep.routing).thenReturn(routes("/register-to-vote/forces/address/select"))

  it should "empty progress form should produce empty Model (selectData)" in {

    val emptyApplicationForm =  addressForm
    val addressModel = mustache.data(
      emptyApplicationForm,
      Call("POST","/register-to-vote/forces/address/select"),
      InprogressForces()
    ).asInstanceOf[SelectModel]

    addressModel.question.title should be("What was your last UK address?")
    addressModel.question.postUrl should be("/register-to-vote/forces/address/select")

    addressModel.lookupUrl should be ("/register-to-vote/forces/address")
    addressModel.manualUrl should be ("/register-to-vote/forces/address/manual")
    addressModel.postcode.value should be ("")
    addressModel.possibleJsonList.value should be ("")
    addressModel.possiblePostcode.value should be ("")
    addressModel.hasAddresses should be (false)
  }

  it should "progress form with valid values should produce Mustache Model with values present (selectData)" in {

    val partiallyFilledApplicationForm = addressForm.fill(InprogressForces(
      address = Some(LastAddress(
        hasAddress = Some(HasAddressOption.YesAndLivingThere),
        address = Some(PartialAddress(
          addressLine = Some("Fake street 123"),
          uprn = Some("1234567"),
          postcode = "WR26NJ",
          manualAddress = None
        ))
      )),
      possibleAddresses = None
    ))

    val addressModel = mustache.data(
      partiallyFilledApplicationForm,
      Call("POST","/register-to-vote/forces/address/select"),
      InprogressForces()
    ).asInstanceOf[SelectModel]

    addressModel.question.title should be("What is your UK address?")
    addressModel.question.postUrl should be("/register-to-vote/forces/address/select")

    addressModel.lookupUrl should be ("/register-to-vote/forces/address")
    addressModel.manualUrl should be ("/register-to-vote/forces/address/manual")
    addressModel.postcode.value should be ("WR26NJ")
    addressModel.possiblePostcode.value should be ("WR26NJ")
    addressModel.hasAddresses should be (false)
  }

  it should "have correct title hasAddress = yes and living there" in {

    val partiallyFilledApplicationForm = addressForm.fill(InprogressForces(
      address = Some(LastAddress(
        hasAddress = Some(HasAddressOption.YesAndLivingThere),
        address = Some(PartialAddress(
          addressLine = Some("Fake street 123"),
          uprn = Some("1234567"),
          postcode = "WR26NJ",
          manualAddress = None
        ))
      )),
      possibleAddresses = None
    ))

    val addressModel = mustache.data(
      partiallyFilledApplicationForm,
      Call("POST","/register-to-vote/forces/address/select"),
      InprogressForces()
    ).asInstanceOf[SelectModel]

    addressModel.question.title should be("What is your UK address?")
  }

  it should "have correct title hasAddress = yes and not living there" in {

    val partiallyFilledApplicationForm = addressForm.fill(InprogressForces(
      address = Some(LastAddress(
        hasAddress = Some(HasAddressOption.YesAndNotLivingThere),
        address = Some(PartialAddress(
          addressLine = Some("Fake street 123"),
          uprn = Some("1234567"),
          postcode = "WR26NJ",
          manualAddress = None
        ))
      )),
      possibleAddresses = None
    ))

    val addressModel = mustache.data(
      partiallyFilledApplicationForm,
      Call("POST","/register-to-vote/forces/address/select"),
      InprogressForces()
    ).asInstanceOf[SelectModel]

    addressModel.question.title should be("What is your UK address?")
  }

  it should "have correct title hasAddress = no" in {

    val partiallyFilledApplicationForm = addressForm.fill(InprogressForces(
      address = Some(LastAddress(
        hasAddress = Some(HasAddressOption.No),
        address = Some(PartialAddress(
          addressLine = Some("Fake street 123"),
          uprn = Some("1234567"),
          postcode = "WR26NJ",
          manualAddress = None
        ))
      )),
      possibleAddresses = None
    ))

    val addressModel = mustache.data(
      partiallyFilledApplicationForm,
      Call("POST","/register-to-vote/forces/address/select"),
      InprogressForces()
    ).asInstanceOf[SelectModel]

    addressModel.question.title should be("What was your last UK address?")
  }
}


text:
#ifndef __BUR_CFG_COMMON_H__
#define __BUR_CFG_COMMON_H__
/* ------------------------------------------------------------------------- */
#define BUR_COMMON_ENV \
"usbscript=usb start && fatload usb 0 ${scradr} usbscript.img &&" \
" source ${scradr}\0" \
"brdefaultip=if test -r ${ipaddr}; then; else" \
" setenv ipaddr 192.168.60.1; setenv serverip 192.168.60.254;" \
" setenv gatewayip 192.168.60.254; setenv netmask 255.255.255.0; fi;\0" \
"netconsole=echo switching to network console ...; " \
"if dhcp; then; else run brdefaultip; fi; setenv ncip ${serverip}; " \
"setcurs 1 9; lcdputs myip; setcurs 10 9; lcdputs ${ipaddr};" \
"setcurs 1 10;lcdputs serverip; setcurs 10 10; lcdputs ${serverip};" \
"setenv stdout nc;setenv stdin nc;setenv stderr nc\0"

#define CONFIG_PREBOOT			"run cfgscr; run brdefaultip"

/* Network defines */
#define CONFIG_BOOTP_DNS		/* Configurable parts of CMD_DHCP */
#define CONFIG_BOOTP_SEND_HOSTNAME
#define CONFIG_BOOTP_GATEWAY
#define CONFIG_BOOTP_SUBNETMASK
#define CONFIG_NET_RETRY_COUNT		10

/* Network console */
#define CONFIG_NETCONSOLE		1
#define CONFIG_BOOTP_MAY_FAIL		/* if we don't have DHCP environment */

#define CONFIG_ENV_OVERWRITE		/* Overwrite ethaddr / serial# */

/* As stated above, the following choices are optional. */
#define CONFIG_SYS_LONGHELP
#define CONFIG_AUTO_COMPLETE
#define CONFIG_CMDLINE_EDITING

/* We set the max number of command args high to avoid HUSH bugs. */
#define CONFIG_SYS_MAXARGS		64

/* Console I/O Buffer Size */
#define CONFIG_SYS_CBSIZE		512

#endif	/* __BUR_CFG_COMMON_H__ */


text:
package io.wcm.config.core.management.util;

import static io.wcm.config.core.management.util.ConversionStringUtils.decodeString;
import static io.wcm.config.core.management.util.ConversionStringUtils.encodeString;
import static io.wcm.config.core.management.util.ConversionStringUtils.splitPreserveAllTokens;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;

import org.junit.Test;

public class ConversionStringUtilsTest {

  @Test
  public void testSplitPreserveAllTokens() {
    assertArrayEquals(new String[0], splitPreserveAllTokens(null, ';'));
    assertArrayEquals(new String[0], splitPreserveAllTokens("", ';'));

    assertArrayEquals(new String[] {
        "aa"
    }, splitPreserveAllTokens("aa", ';'));
    assertArrayEquals(new String[] {
        "aa",
        "bb",
        "cc"
    }, splitPreserveAllTokens("aa;bb;cc", ';'));
    assertArrayEquals(new String[] {
        "aa",
        ""
    }, splitPreserveAllTokens("aa;", ';'));
    assertArrayEquals(new String[] {
        "",
        "aa",
        ""
    }, splitPreserveAllTokens(";aa;", ';'));

    assertArrayEquals(new String[] {
        "aa\\;bb\\;cc"
    }, splitPreserveAllTokens("aa\\;bb\\;cc", ';'));
    assertArrayEquals(new String[] {
        "\\;aa",
        "bb\\;",
        "cc"
    }, splitPreserveAllTokens("\\;aa;bb\\;;cc", ';'));
  }

  @Test
  public void testEncodeString() {
    assertNull(encodeString((String)null));
    assertEquals("", encodeString(""));

    assertEquals("aa", encodeString("aa"));
    assertEquals("aa\\;", encodeString("aa;"));
    assertEquals("\\=a\\;a", encodeString("=a;a"));
    assertEquals("a\\\\\\;a", encodeString("a\\;a"));
  }

  @Test
  public void testDecodeStringString() {
    assertNull(decodeString((String)null));
    assertEquals("", decodeString(""));

    assertEquals("aa", decodeString("aa"));
    assertEquals("aa;", decodeString("aa\\;"));
    assertEquals("=a;a", decodeString("\\=a\\;a"));
    assertEquals("a\\;a", decodeString("a\\\\\\;a"));
  }

}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using URSA.Web;

namespace URSA.Example.WebApplication.Data
{
    /// Describes a person.
    public class Person : IControlledEntity<Guid>
    {
        private string _firstName = String.Empty;
        private string _lastName = String.Empty;
        private IList<string> _favouriteDishes = new List<string>();
        private ICollection<string> _roles = new List<string>();
        private ICollection<Person> _friends = new List<Person>();
        private IList<Person> _superiors = new List<Person>();

        /// Gets or sets the person's identifier.
        [Key]
        public Guid Key { get; set; }

        ///  Gets or sets the person's firstname.
        public string Firstname { get { return _firstName; } set { _firstName = value ?? String.Empty; } }

        ///  Gets or sets the person's lastname.
        public string Lastname { get { return _lastName; } set { _lastName = value ?? String.Empty; } }

        ///  Gets or sets the person's roles.
        public ICollection<string> Roles { get { return _roles; } set { _roles = value ?? new List<string>(); } }

        /// Gets or sets the favourite dishes.
        public IList<string> FavouriteDishes { get { return _favouriteDishes; } set { _favouriteDishes = value ?? new List<string>(); } }

        /// Gets or sets the spouse.
        public Person Spouse { get; set; }

        /// Gets or sets the friends.
        public ICollection<Person> Friends { get { return _friends; } set { _friends = value ?? new List<Person>(); } }

        /// Gets or sets the superiors.
        public IList<Person> Superiors { get { return _superiors; } set { _superiors = value ?? new List<Person>(); } }
    }
}


text:
var _ = require('underscore');
var Backbone = require('backbone');
var cdb = require('cartodb.js');
require('../../../../components/form-components/index');

/**
 * This view is required because a schema change require the Backbone.Form object to be re-created to update the view as expected.
 */
module.exports = cdb.core.View.extend({

  initialize: function (opts) {
    if (!opts.formModel) throw new Error('formModel is required');

    this._formModel = opts.formModel;

    this._formModel.on('changeSchema', this.render, this);
    this.add_related_model(this._formModel);
  },

  render: function () {
    this.clearSubViews();

    this._analysisFormView = new Backbone.Form({
      model: this._formModel,
      template: this._formModel.getTemplate(),
      templateData: _.result(this._formModel, 'getTemplateData')
    });

    this._analysisFormView.bind('change', function () {
      var errors = this.commit({validate: true});
      if (errors) {
        this.model.set('errors', errors);
      } else {
        this.model.unset('errors');
      }
    });

    this.$el.append(this._analysisFormView.render().el);

    this._analysisFormView.trigger('change'); // force change to check for errors on load

    return this;
  },

  /**
   * @override cdb.core.View.prototype.clearSubViews
   */
  clearSubViews: function () {
    if (this._analysisFormView) {
      this._analysisFormView.remove(); // the Backbone.Form equivalent to "view.clean()"
      this._analysisFormView = null;
    }

    return cdb.core.View.prototype.clearSubViews.apply(this, arguments);
  }

});


text:
package edu.ptu.javatest._60_dsa;

import org.junit.Test;

import java.lang.reflect.Field;
import java.util.LinkedList;

public class _31_LinkedListTest {
    @Test
    public void testLinked(){
        LinkedList<Object> list = new LinkedList<>();
        for (int i = 0; i < 3; i++) {
            list.add(i);
        }
        try {
            Field first = list.getClass().getDeclaredField("first");
            Field last = list.getClass().getDeclaredField("last");

            last.setAccessible(true);
            Object tailObj = last.get(list);
            printNode(tailObj,"last",false);

            first.setAccessible(true);
            Object headObj = first.get(list);
            printNode(headObj,"first",true);

            Object objIter=tailObj;
            while (objIter != null) {
                printNode(objIter," prev->",false);

//                    Field next = objIter.getClass().getDeclaredField("next");//
                Field prev = objIter.getClass().getDeclaredField("prev");//

                prev.setAccessible(true);
                objIter = prev.get(objIter);

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void printNode(Object nodeObj,String flag,boolean endNewLine)   {
        if (nodeObj == null)
            return;
        try {
            Field next = nodeObj.getClass().getDeclaredField("next");
            Field prev = nodeObj.getClass().getDeclaredField("prev");
            Field item = nodeObj.getClass().getDeclaredField("item");

            System.out.print(" "+flag+" Node" + nodeObj.toString().substring(nodeObj.getClass().getName().length()) + "");

            item.setAccessible(true);
            Object o = item.get(nodeObj);

            System.out.print("("+ o+ " )");

            if (endNewLine)
                System.out.println( );
        } catch ( Exception e) {
            e.printStackTrace();
        }

    }
}


text:
import { Matrix, Point } from '../../../../core';
import { Contours } from '../../../';

declare module '../../../../core' {
    interface Matrix {
        findContours(mode: number, method: number, offset?: Point /* = Point() */): Contours;
    }
}


text:
package io.leopard.burrow.lang;

import java.lang.reflect.Constructor;

import io.leopard.core.exception.InvalidException;

public class ExceptionFinder {

	public static InvalidException invalid(String className, String param) {
		Class<?> clazz;
		try {
			clazz = Class.forName(className);
		}
		catch (ClassNotFoundException e) {
			throw new RuntimeException(e.getMessage(), e);
		}
		try {
			Constructor<?> constructor = clazz.getConstructor(String.class);
			return (InvalidException) constructor.newInstance(param);
		}
		catch (Exception e) {
			throw new RuntimeException(e.getMessage(), e);
		}

	}
}


text:
class ContactUs::ContactsController < ApplicationController

  def create
    @contact = ContactUs::Contact.new(params[:contact_us_contact])

    if !user_signed_in? && Rails.configuration.x.recaptcha.enabled
      unless verify_recaptcha(model: @contact) && @contact.save
        flash[:alert] = _("Captcha verification failed, please retry.")
        render_new_page and return
      end
    end
    if @contact.save
      redirect_to(ContactUs.success_redirect || "/",
                  notice: _("Contact email was successfully sent."))
    else
      flash[:alert] = _("Unable to submit your request")
      render_new_page
    end
  end

  def new
    @contact = ContactUs::Contact.new
    render_new_page
  end

  protected

  def render_new_page
    case ContactUs.form_gem
    when "formtastic"  then render "new_formtastic"
    when "simple_form" then render "new_simple_form"
    else
      render "new"
    end
  end

end


text:
/** Automatically generated file. DO NOT MODIFY */
package com.tisa7.daysmatter;

public final class BuildConfig {
    public final static boolean DEBUG = true;

}


text:
package com.maciejgryka.fyproject;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.nio.ShortBuffer;

import javax.microedition.khronos.opengles.GL10;

class IndicatorIcon {
	private final static int VERTS = 4;

    private IntBuffer mVertexBuffer;

    private IntBuffer mTexBuffer;

    private ShortBuffer mIndexBuffer;

    private FloatBuffer mColorBuffer;
    private int mType;
    private float[] mTranslation;
    private float[] mRotation;

    /**
	 * Creates an IndicatorIcon - textured 2D rectangle.
	 * @param type determines the texture (0 - temperature, 1 - light, 2 - occupancy)
	 * @param translation - position of the indicator (preferably somewhere on the wall)
	 * @param rotation - rotation of the indicator
	 */
    public IndicatorIcon(int type, int value, float translation[], float rotation[]) {
    	mType = type;
    	mTranslation = translation;
    	mRotation = rotation;

    	int one = 0x10000;
    	int side = one/4;
    	// A square of (2*side) size sides
    	int coords[] = {
    			-side, -side, 0,
    			side, -side, 0,
    			side, side, 0,
    			-side, side, 0
    	};

        short[] indices = {
        		1, 2, 3,
        		3, 0, 1
        };

        float color[] = {
        		1.0f, 1.0f, 1.0f, 0f
        };

        color = getColor(type, value);

		float colors[] = {
				color[0], color[1], color[2], color[3],
				color[0], color[1], color[2], color[3],
				color[0], color[1], color[2], color[3],
				color[0], color[1], color[2], color[3],
		};

        // Buffers to be passed to gl*Pointer() functions
        // must be direct, i.e., they must be placed on the
        // native heap where the garbage collector cannot
        // move them.
        //
        // Buffers with multi-byte datatypes (e.g., short, int, float)
        // must have their byte order set to native order
        ByteBuffer vbb = ByteBuffer.allocateDirect(VERTS * 3 * 4);
        vbb.order(ByteOrder.nativeOrder());
        mVertexBuffer = vbb.asIntBuffer();
        mVertexBuffer.put(coords);
        mVertexBuffer.position(0);

        ByteBuffer ibb = ByteBuffer.allocateDirect(indices.length*4);
        ibb.order(ByteOrder.nativeOrder());
        mIndexBuffer = ibb.asShortBuffer();
        mIndexBuffer.put(indices);
        mIndexBuffer.position(0);

        ByteBuffer cbb = ByteBuffer.allocateDirect(colors.length*4);
		cbb.order(ByteOrder.nativeOrder());
		mColorBuffer = cbb.asFloatBuffer();
		mColorBuffer.put(colors);
		mColorBuffer.position(0);

		ByteBuffer tbb = ByteBuffer.allocateDirect(VERTS * 2 * 4);
        tbb.order(ByteOrder.nativeOrder());
        mTexBuffer = tbb.asIntBuffer();
        mTexBuffer.put(0);
        mTexBuffer.put(0);
        mTexBuffer.put(one);
        mTexBuffer.put(0);
        mTexBuffer.put(one);
        mTexBuffer.put(one);
        mTexBuffer.put(0);
        mTexBuffer.put(one);
        mTexBuffer.position(0);
    }
    public void draw(GL10 gl) {
    	gl.glTranslatef(mTranslation[0], mTranslation[1], mTranslation[2]);
    	gl.glRotatef(mRotation[0], mRotation[1], mRotation[2], mRotation[3]);

    	gl.glFrontFace(GL10.GL_CCW);
    	gl.glEnable(GL10.GL_TEXTURE_2D);
    	gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
    	gl.glEnableClientState(GL10.GL_COLOR_ARRAY);

    	gl.glBindTexture(GL10.GL_TEXTURE_2D, mType);
    	gl.glVertexPointer(3, GL10.GL_FIXED, 0, mVertexBuffer);
    	gl.glColorPointer(4, GL10.GL_FLOAT, 0, mColorBuffer);
    	gl.glTexCoordPointer(2, GL10.GL_FIXED, 0, mTexBuffer);
    	gl.glDrawElements(GL10.GL_TRIANGLES, 6, GL10.GL_UNSIGNED_SHORT, mIndexBuffer);

    	gl.glDisableClientState(GL10.GL_COLOR_ARRAY);
    	gl.glDisable(GL10.GL_TEXTURE_2D);

    	gl.glRotatef(-mRotation[0], mRotation[1], mRotation[2], mRotation[3]);
    	gl.glTranslatef(-mTranslation[0], -mTranslation[1], -mTranslation[2]);
    }
    private float[] getColor(int type, int value)
    {
    	float color[] = new float[4];

    	switch (type) {
    	case 1:
    		if (value > 20) {
    			color[0] = 1.0f;
    			color[1] = 0.7f;
    			color[2] = 0.7f;
    			color[3] = 0.0f;
    		} else {
    			color[0] = 0.7f;
    			color[1] = 0.7f;
    			color[2] = 1.0f;
    			color[3] = 0.0f;
    		}
    		break;
    	case 2:
    		if (value > 50) {
    			color[0] = 1.0f;
    			color[1] = 1.0f;
    			color[2] = 0.2f;
    			color[3] = 0.0f;
    		} else {
    			color[0] = 0.5f;
    			color[1] = 0.5f;
    			color[2] = 0.2f;
    			color[3] = 0.0f;
    		}
    		break;
    	default:
    		color[0] = 1.0f;
			color[1] = 1.0f;
			color[2] = 1.0f;
			color[3] = 0.0f;
			break;
    	}
    	return color;
    }
}


text:
A Google Charts API for Python 2 and 3, meant to be used as an alternative to matplotlib. Syntax is similar to MATLAB. The goal of this project is to make an easy to use graphing utility for the most common graphical use cases.

## Python (Web Browser) Screenshot

![Alt text](assets/testGraphOutput.JPG?raw=true "Python example")

## Jupyter Screenshot

![Alt text](assets/SampleJupyterGraph.png?raw=true "Jupyter example")

You can find a Jupyter notebook with examples [here](examples/gpcharts%20test.ipynb). A Python script with examples can be found [here](examples/testGraph.py).

## Installation and use
GooPyCharts can be installed with pip using the following command:

```
pip install gpcharts
```

Alternately, you can put gpcharts.py in your working directory or library path. Then, import gpcharts to your Python code:

```
from gpcharts import figure
```

That's it. To get started, you can plot and display a simple graph with the following code:

```
fig1 = figure()
fig1.plot([8,7,6,5,4])
```

This will open the chart in a Jupyter notebook if you're using one. If you aren't, it will open a webpage in your default browser with the plot.

For more examples, see [testGraph.py](examples/testGraph.py). Examples include scatter plots, adding titles/plot labels, and datetime graphs. For simple bar and histogram examples, see [testGraph_barAndHist.py](examples/testGraph_barAndHist.py). For a jupyter notebook example, see [gpcharts test.ipynb](examples/gpcharts%20test.ipynb). The example does not display properly in Github, but the file should work if you download it and then do "Cell->Run All."

For timeseries, use as your x-axis the following format (as a string): 'yyyy-mm-dd HH:MM:SS'. The 'HH:MM:SS' is optional, but be consistent throughout your input. GooPyCharts will take care of the rest.

Each kind of chart has a number of possible configuration options provided by the Google Chart API and GooPyCharts allows you to use any combination of them via keywork arguments. For example, to show a line chart without a legend and with straight lines between each of the po, you can write:

```
f1 = figure()
f1.plot([1,2], legend="'none'", curveType="'straight'")
```

You can determine the name of the keyword arguments by consulting the [Google Charts API documentation](https://developers.google.com/chart/interactive/docs/customizing_charts) for each chart, such as the [Line Chart](https://developers.google.com/chart/interactive/docs/gallery/linechart#configuration-options). You'll notice that the example strings above are surrounded by single quotes. You are injecting a literal JavaScript option into the chart, so the final drawChart method will have single quotes around the option. This can be somewhat inconvenient, but it is necessary because certain options require dictionaries.

You can use these customization features to overwrite the default options within GooPyCharts. The default GooPyCharts curveType is `'function'`, which produces curved lines, but the example above replaces that with the Google Charts API default, which is not curved.

## Features
- line, scatter, bar, column, and histogram plots
- plot multiple columns in one call
- tooltips
- easy access to best fit line for scatter plots
- full access to the charts' configuration options
- save figure as HTML or PNG
- save data to CSV
- zooming (click and drag to zoom, right-click to reset zoom)
- log scale for y-axis
- automatic datetime/string/numeric detection on x-axis input (a huge pain point in both MATLAB and matplotlib)
- Easy webpage integration (just copy and paste the HTML/Javascript from the output HTML file)
    - To get the HTML in code, cast a `figure` object to `str`. The
      `figure.get_drawChart` method returns just the JavaScript function that
      draws the chart.
- Jupyter notebook integration

## Some Rules
- Headers are column titles. The dependent variable header will be the title of the x axis, and the other headers will appear in the legend.
- If you have headers on your dependent variables, make sure to also have a header on the independent variable.
- The header on the x axis will overwrite the x label. The y label is independent and is not assigned any header.
- If you want to do some fancy math using NumPy and then plot a NumPy array, use the tolist() function to convert the array to a Python list.

## Comparisons to Matplotlib and MATLAB
See the README's [compareToMatplotlib.md](assets/compareToMatplotlib.md) and [compareToMATLAB.md](assets/compareToMATLAB.md).

Please report bugs to me and I'll do my best to fix them in short order.


text:
import sopel
from sopel.tools import SopelMemory
import re
import requests
from bs4 import BeautifulSoup

steamregex = re.compile('.*https?:\/\/store\.steampowered\.com\/app\/(.*?\/)(?:.*?\/)?(?:.*)((?=[\s])|$)')
def setup(bot):
    if not bot.memory.contains('url_callbacks'):
        bot.memory['url_callbacks'] = SopelMemory()
    bot.memory['url_callbacks'][steamregex] = steamirc

def shutdown(bot):
    del bot.memory['url_callbacks'][steamregex]

def getsteamappid(url):
    try:
        bs = BeautifulSoup(requests.get(url).content, "html.parser")
        appid = bs.find_all('a', {'class':'search_result_row'})[0]['data-ds-appid']
    except:
        appid = None
    return appid

def getgameinfo(appid):
    gameinfo = {}
    x = requests.get("http://store.steampowered.com/api/appdetails?appids={}&cc=US".format(appid)).json()
    gameinfo['name'] = x[appid]['data']['name']
    if x[appid]['data']['is_free']:
        gameinfo['price'] = 'Free To Play'
        gameinfo['discount'] = ''
    else:
        if x[appid]['data'].get('price_overview', False):
            gameinfo['price'] = "$"+str(x[appid]['data']['price_overview']['final']/100)
            if x[appid]['data']['price_overview']['discount_percent'] > 0:
                gameinfo['discount'] = x[appid]['data']['price_overview']['discount_percent']
            else:
                gameinfo['discount'] = ''
        else:
            gameinfo['price'] = ''
            gameinfo['discount'] = ''
    if x[appid]['data']['release_date']['coming_soon']:
        gameinfo['release'] = x[appid]['data']['release_date']['date']
    else:
        gameinfo['release'] = ''
    return gameinfo

def getaverageplayers24h(appid):
    try:
        bs = BeautifulSoup(requests.get("http://steamcharts.com/app/{}".format(appid)).content, "html.parser")
        players = bs.find_all('div',{'class':'app-stat'})[1].span.text
    except:
        return ''
    if players == '0':
        players = ''
    return "{:,}".format(int(players)) if players else ''

def getreviewdata(appid):
    review = {}
    try:
        x = requests.get("http://store.steampowered.com/appreviewhistogram/{}?l=english".format(appid)).json()
        review['reviewsummary'] = x['language_breakdown']['english']['summary']['reviewSummaryDesc']
        review['reviewpercentage'] = x['language_breakdown']['english']['summary']['sReviewScoreTooltip'].split('%')[0]+'%'
    except:
        review['reviewsummary'] = ''
        return review
    return review

@sopel.module.commands('steam')
def steam(bot,trigger):
    if trigger.group(2):
        url = "http://store.steampowered.com/search/?term={}".format(trigger.group(2))
        appid = getsteamappid(url)
        if not appid:
            return
        gameinfo = getgameinfo(appid)
        averageplayers = getaverageplayers24h(appid)
        rating = getreviewdata(appid)
        bot.say("[{0}]{1}{2}{3}{4}".format(gameinfo['name'],
                                            " Rating: {} ({}) |".format(rating['reviewsummary'], rating['reviewpercentage']) if rating['reviewsummary'] else '',
                                            " Peak Players 24H: {} |".format(averageplayers) if averageplayers else '',
                                            " Price: {}{} |".format(gameinfo['price'], " (-{}%)".format(gameinfo['discount']) if gameinfo['discount'] else '') if gameinfo['price'] else '',
                                            " Coming soon: {}".format(gameinfo['release']) if gameinfo['release'] else ''))

@sopel.module.rule('.*https?:\/\/store\.steampowered\.com\/app\/(.*?\/)(?:.*?\/)?(?:.*)((?=[\s])|$)')
def steamirc(bot,trigger, match=None):
    match = match or trigger
    appid = match.group(1)[:-1]
    gameinfo = getgameinfo(appid)
    averageplayers = getaverageplayers24h(appid)
    rating = getreviewdata(appid)
    bot.say("[{0}]{1}{2}{3}{4}".format(gameinfo['name'],
                                            " Rating: {} ({}) |".format(rating['reviewsummary'], rating['reviewpercentage']) if rating['reviewsummary'] else '',
                                            " Peak Players 24H: {} |".format(averageplayers) if averageplayers else '',
                                            " Price: {}{} |".format(gameinfo['price'], " (-{}%)".format(gameinfo['discount']) if gameinfo['discount'] else '') if gameinfo['price'] else '',
                                            " Coming soon: {}".format(gameinfo['release']) if gameinfo['release'] else ''))


text:
#ifndef QSGDEPTHSTENCILBUFFER_P_H
#define QSGDEPTHSTENCILBUFFER_P_H

#include <QtCore/qsize.h>
#include <QtGui/private/qopenglcontext_p.h>
#include <QtGui/private/qopenglextensions_p.h>
#include <QtCore/qsharedpointer.h>
#include <QtCore/qhash.h>

QT_BEGIN_NAMESPACE

class QSGDepthStencilBufferManager;

class QSGDepthStencilBuffer
{
public:
    enum Attachment
    {
        NoAttachment = 0x00,
        DepthAttachment = 0x01,
        StencilAttachment = 0x02
    };
    Q_DECLARE_FLAGS(Attachments, Attachment)

    struct Format
    {
        QSize size;
        int samples;
        QSGDepthStencilBuffer::Attachments attachments;
        bool operator == (const Format &other) const;
    };

    QSGDepthStencilBuffer(QOpenGLContext *context, const Format &format);
    virtual ~QSGDepthStencilBuffer();

    // Attaches this depth stencil buffer to the currently bound FBO.
    void attach();
    // Detaches this depth stencil buffer from the currently bound FBO.
    void detach();

    QSize size() const { return m_format.size; }
    int samples() const { return m_format.samples; }
    Attachments attachments() const { return m_format.attachments; }

protected:
    virtual void free() = 0;

    QOpenGLExtensions m_functions;
    QSGDepthStencilBufferManager *m_manager;
    Format m_format;
    GLuint m_depthBuffer;
    GLuint m_stencilBuffer;

    friend class QSGDepthStencilBufferManager;
};

Q_DECLARE_OPERATORS_FOR_FLAGS(QSGDepthStencilBuffer::Attachments)

inline bool QSGDepthStencilBuffer::Format::operator == (const Format &other) const
{
    return size == other.size && samples == other.samples && attachments == other.attachments;
}

class QSGDefaultDepthStencilBuffer : public QSGDepthStencilBuffer
{
public:
    QSGDefaultDepthStencilBuffer(QOpenGLContext *context, const Format &format);
    virtual ~QSGDefaultDepthStencilBuffer();

protected:
    virtual void free();
};

class QSGDepthStencilBufferManager
{
public:
    QSGDepthStencilBufferManager(QOpenGLContext *ctx) : m_context(ctx) { }
    ~QSGDepthStencilBufferManager();
    QOpenGLContext *context() const { return m_context; }
    QSharedPointer<QSGDepthStencilBuffer> bufferForFormat(const QSGDepthStencilBuffer::Format &fmt);
    void insertBuffer(const QSharedPointer<QSGDepthStencilBuffer> &buffer);

private:
    typedef QHash<QSGDepthStencilBuffer::Format, QWeakPointer<QSGDepthStencilBuffer> > Hash;
    QOpenGLContext *m_context;
    Hash m_buffers;

    friend class QSGDepthStencilBuffer;
};

extern uint qHash(const QSGDepthStencilBuffer::Format &format);

QT_END_NAMESPACE

#endif


text:
// ### @tagFeature
describe('A Feature title mismatch', function() {

    /*
        A
        Feature
        Description.
     */

});


text:
package vn.getgreen;

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

import org.json.JSONObject;

import vn.getgreen.PageFragment.PageListener;
import vn.getgreen.common.BaseActivity;
import vn.getgreen.common.DialogBuilder;
import vn.getgreen.common.DialogBuilder.GDialogListener;
import vn.getgreen.enties.Forum;
import vn.getgreen.enties.Permissions;
import vn.getgreen.enties.Post;
import vn.getgreen.enties.Thread;
import vn.getgreen.enties.User;
import vn.getgreen.network.GClient;
import vn.getgreen.network.PostService;
import vn.getgreen.view.GEditText;
import vn.getgreen.view.GImageView;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v13.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Toast;

public class PostsActivity extends BaseActivity implements PageListener{
	private Thread mThread;
	private int NUM_PAGES = 1;
	private PagerAdapter mPagerAdapter;
	private LinearLayout progress;
	private RelativeLayout quickBar;
	private GEditText quickqeply;
	private ProgressBar loading;
	private GImageView showAll;
	private GImageView reply;
	private PostService mPostService;
	private PostService mPostDelete;
	private PostService mPostLike;

	public static final int REQUEST_CODE_NEWPOST = 2;
	public static final int REQUEST_CODE_EDITPOST = 3;
	private int currentPage = 0;
    /**
     * The pager widget, which handles animation and allows swiping horizontally to access previous
     * and next wizard steps.
     */
    private ViewPager mPager;
	public PostsActivity() {
		// TODO Auto-generated constructor stub
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.thread_pager);
		getActionBar().setDisplayHomeAsUpEnabled(true);
		getActionBar().setHomeButtonEnabled(true);

		progress = (LinearLayout) findViewById(R.id.progress);
		quickBar = (RelativeLayout) findViewById(R.id.quickbar);
		quickqeply = (GEditText) findViewById(R.id.quickqeply);
		loading = (ProgressBar) findViewById(R.id.loading);
		showAll = (GImageView) findViewById(R.id.show_all);
		reply = (GImageView) findViewById(R.id.reply);
		mPager = (ViewPager) findViewById(R.id.vPager);

		Intent intent = getIntent();
		if(intent.getSerializableExtra(Thread.class.getName())!= null)
		{
			mThread = (Thread) intent.getSerializableExtra(Thread.class.getName());
			NUM_PAGES = mThread.getThread_post_count() / PostService.LIMIT_POSTS_PER_PAGE;
			if(mThread.getThread_post_count() % PostService.LIMIT_POSTS_PER_PAGE != 0) NUM_PAGES += 1;
			quickBar.setVisibility(User.isLogin(this) ? View.VISIBLE : View.GONE);
			setTitle(mThread.getThread_title());
		}

        mPagerAdapter = new ScreenSlidePagerAdapter(getFragmentManager());
        mPager.setAdapter(mPagerAdapter);

        mPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
            	currentPage = position;
            }
        });
        showAll.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent(PostsActivity.this, NewTopicActivity.class);
				intent.putExtra(NewTopicActivity.MODE_CODE, NewTopicActivity.MODE_NEW_POST);
				intent.putExtra(Thread.class.getName(), mThread);
				startActivityForResult(intent, REQUEST_CODE_NEWPOST);
			}
		});
        mPostService = new PostService(this, this);
        mPostDelete = new PostService(this, this);
        mPostLike = new PostService(this, this);

        reply.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View view) {
				InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				inputMethodManager.hideSoftInputFromWindow(quickqeply.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
				mPostService.createPost(mThread, quickqeply.getText().toString()+"\n\n"+signature);
				quickqeply.getText().clear();
			}
		});
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		menu.findItem(R.id.action_refresh).setVisible(true);
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			onBackPressed();
			break;
		default:
			break;
		}
		return super.onMenuItemSelected(featureId, item);
	}

	@Override
	public void onRefresh() {
		PageFragment fragment = ((ScreenSlidePagerAdapter)mPagerAdapter).getFragment(currentPage);
		fragment.onRefresh();
	}

    private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
    	private Map<Integer, PageFragment> mPageReferenceMap = new HashMap<Integer, PageFragment>();
        public ScreenSlidePagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
        	PageFragment fragment  = PageFragment.create(position, mThread, PostsActivity.this, NUM_PAGES, mImageFetcher);
        	mPageReferenceMap.put(Integer.valueOf(position), fragment);
            return fragment;
        }

        @Override
        public int getCount() {
            return NUM_PAGES;
        }

        @Override
		public void destroyItem(View container, int position, Object object) {
			super.destroyItem(container, position, object);
			mPageReferenceMap.remove(Integer.valueOf(position));
		}

        /**
         * After an orientation change, the fragments are saved in the adapter, and
         * I don't want to double save them: I will retrieve them and put them in my
         * list again here.
         */
        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            PageFragment fragment = (PageFragment) super.instantiateItem(container,
                    position);
            mPageReferenceMap.put(position, fragment);
            return fragment;
        }

        public PageFragment getFragment(int key) {

			return mPageReferenceMap.get(key);
		}
    }
    @Override
    public void onStart(GClient client) {
    	if(client == mPostService)
    	{
    		loading.setVisibility(View.VISIBLE);
    	}
    	super.onStart(client);
    }

    @Override
    public void onFinish(GClient client) {
    	if(client == mPostService)
    	{
    		loading.setVisibility(View.INVISIBLE);
    	}
    	super.onFinish(client);
    }

    @Override
    public void onSuccess(GClient client, JSONObject jsonObject) {
    	if(client == mPostService)
    	{
    		mPager.setCurrentItem(NUM_PAGES - 1, false);
    		onRefresh();
    	}
    	if(client == mPostDelete || client == mPostLike)
    	{
    		onRefresh();
    	}
    	super.onSuccess(client, jsonObject);
    }

	@Override
	public void onLoadComplete(int posts_total, List<Post> post) {
		mThread.setThread_post_count(posts_total);
		NUM_PAGES = mThread.getThread_post_count() / PostService.LIMIT_POSTS_PER_PAGE;
		if(mThread.getThread_post_count() % PostService.LIMIT_POSTS_PER_PAGE != 0) NUM_PAGES += 1;
		mPagerAdapter.notifyDataSetChanged();
	}

	@Override
	public void onStartLoad() {
		// TODO Auto-generated method stub
	}

	@Override
	public void onPrevPage() {
		mPager.setCurrentItem(mPager.getCurrentItem() - 1, true);
	}

	@Override
	public void onFastPrevPage() {
		mPager.setCurrentItem(0, true);
	}

	@Override
	public void onNextPage() {
		mPager.setCurrentItem(mPager.getCurrentItem() + 1, true);
	}

	@Override
	public void onFastNextPage() {
		mPager.setCurrentItem(NUM_PAGES - 1, true);
	}

	@Override
	public void onUserProfile(int user_id) {
		Intent intent = new Intent(this, ProfileActivity.class);
		intent.putExtra(ProfileActivity.KEY_USER_ID, user_id);
		startActivity(intent);
	}

	@Override
	public void onPageBtn() {
		  final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
                  PostsActivity.this,
                  android.R.layout.simple_list_item_1);
		  for(int i = 1; i <= NUM_PAGES; i++)
		  {
			  int begin_post = i*PostService.LIMIT_POSTS_PER_PAGE - PostService.LIMIT_POSTS_PER_PAGE + 1;
			  int end_post = i*PostService.LIMIT_POSTS_PER_PAGE;
			  if (end_post > mThread.getThread_post_count()) {
				end_post = mThread.getThread_post_count();
			  }
			  arrayAdapter.add("Page "+i+ " (" +begin_post + " - " + end_post + " )");
		  }
		new DialogBuilder(this, arrayAdapter, new GDialogListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				mPager.setCurrentItem(which, false);
			}
		});
	}

	@Override
	public void onActionWithPost(final Post post) {
		if(!User.isLogin(this))
		{
			Toast.makeText(this, getResources().getString(R.string.require_login), Toast.LENGTH_SHORT).show();
			return;
		}
		final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
                PostsActivity.this,
                android.R.layout.simple_list_item_1);
		Permissions permissions = post.getPermissions();
		final Resources res = getResources();
		if(post.isPost_is_liked()) arrayAdapter.add(res.getString(R.string.QuickAction_unLike));
		if(permissions.isLike() && !post.isPost_is_liked()) arrayAdapter.add(res.getString(R.string.QuickAction_Like));
		arrayAdapter.add(res.getString(R.string.QuickAction_Quote));
		if(permissions.isEdit()) arrayAdapter.add(res.getString(R.string.QuickAction_Edit));
		if(permissions.isDelete()) arrayAdapter.add(res.getString(R.string.QuickAction_delete));

		new DialogBuilder(this, arrayAdapter, new GDialogListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				String command = arrayAdapter.getItem(which);
				if(command.equals(res.getString(R.string.QuickAction_Like)))
				{
					mPostLike.like(post);
				}
				if(command.equals(res.getString(R.string.QuickAction_unLike)))
				{
					mPostLike.unLike(post);
				}
				if(command.equals(res.getString(R.string.QuickAction_Edit)))
				{
					Intent intent = new Intent(PostsActivity.this, NewTopicActivity.class);
					intent.putExtra(NewTopicActivity.MODE_CODE, NewTopicActivity.MODE_EDIT_POST);
					intent.putExtra(Thread.class.getName(), mThread);
					intent.putExtra(Post.class.getName(), post);
					startActivityForResult(intent, REQUEST_CODE_NEWPOST);
				}
				if(command.equals(res.getString(R.string.QuickAction_delete)))
				{
					mPostDelete.remove(post);
				}
				if(command.equals(res.getString(R.string.QuickAction_Quote)))
				{
					Intent intent = new Intent(PostsActivity.this, NewTopicActivity.class);
					intent.putExtra(NewTopicActivity.MODE_CODE, NewTopicActivity.MODE_NEW_POST_QUOTE);
					intent.putExtra(Thread.class.getName(), mThread);
					intent.putExtra(Post.class.getName(), post);
					startActivityForResult(intent, REQUEST_CODE_NEWPOST);
				}
			}
		});
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(requestCode == REQUEST_CODE_NEWPOST && resultCode == Activity.RESULT_OK)
		{
			onLoadComplete(mThread.getThread_post_count() + 1, null);
			currentPage = NUM_PAGES - 1;
			mPager.setCurrentItem(NUM_PAGES - 1, false);
			onRefresh();
		}
		if(requestCode == REQUEST_CODE_EDITPOST && resultCode == Activity.RESULT_OK)
		{
			onRefresh();
		}

		super.onActivityResult(requestCode, resultCode, data);
	}

}


text:
#include "forkBlock.h"

#include <qrutils/interpreter/thread.h>

using namespace qReal::interpretation::blocks;

void ForkBlock::run()
{
	for (const QString &threadId : mThreadStartBlocks.keys()) {
		emit newThread(mThreadStartBlocks[threadId], threadId);
	}

	emit done(mNextBlockId);
}

bool ForkBlock::initNextBlocks()
{
	const IdList links = mGraphicalModelApi->graphicalRepoApi().outgoingLinks(id());
	QStringList createdIds;

	if (links.size() < 2) {
		error(tr("There must be at least two outgoing links"));
		return false;
	}

	foreach (const Id &linkId, links) {
		const Id targetBlockId = mGraphicalModelApi->graphicalRepoApi().otherEntityFromLink(linkId, id());
		if (targetBlockId.isNull()) {
			error(tr("Outgoing link is not connected"));
			return false;
		}

		QString threadId = mLogicalModelApi->propertyByRoleName(mGraphicalModelApi->logicalId(linkId), "Guard")
				.toString();
		if (threadId.isEmpty()) {
			threadId = QUuid::createUuid().toString();
			createdIds << threadId;
		}

		if (mThreadStartBlocks.contains(threadId)) {
			error(tr("Cannot create two threads with the same id %1").arg(threadId));
			return false;
		}

		mThreadStartBlocks[threadId] = targetBlockId;
	}

	if (mThreadStartBlocks.contains(mThread->id())) {
		mNextBlockId = mThreadStartBlocks[mThread->id()];
		mThreadStartBlocks.remove(mThread->id());
	} else if (!createdIds.isEmpty()) {
		mNextBlockId = mThreadStartBlocks[createdIds[0]];
		mThreadStartBlocks.remove(createdIds[0]);
	} else {
		error(tr("There must be a link that has its 'Guard' property set to the current thread id %1")
				.arg(mThread->id()));
		return false;
	}

	return true;
}


text:
// Copyright 2017 The Bazel Authors. 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 com.google.devtools.build.lib.rules.genrule;

import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.actions.CommandLines;
import com.google.devtools.build.lib.actions.CompositeRunfilesSupplier;
import com.google.devtools.build.lib.actions.MutableActionGraph.ActionConflictException;
import com.google.devtools.build.lib.analysis.AliasProvider;
import com.google.devtools.build.lib.analysis.CommandHelper;
import com.google.devtools.build.lib.analysis.ConfigurationMakeVariableContext;
import com.google.devtools.build.lib.analysis.ConfiguredTarget;
import com.google.devtools.build.lib.analysis.FileProvider;
import com.google.devtools.build.lib.analysis.FilesToRunProvider;
import com.google.devtools.build.lib.analysis.RuleConfiguredTargetBuilder;
import com.google.devtools.build.lib.analysis.RuleConfiguredTargetFactory;
import com.google.devtools.build.lib.analysis.RuleContext;
import com.google.devtools.build.lib.analysis.Runfiles;
import com.google.devtools.build.lib.analysis.RunfilesProvider;
import com.google.devtools.build.lib.analysis.ShToolchain;
import com.google.devtools.build.lib.analysis.TransitiveInfoCollection;
import com.google.devtools.build.lib.analysis.configuredtargets.RuleConfiguredTarget.Mode;
import com.google.devtools.build.lib.analysis.stringtemplate.ExpansionException;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.collect.nestedset.NestedSet;
import com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder;
import com.google.devtools.build.lib.collect.nestedset.Order;
import com.google.devtools.build.lib.packages.TargetUtils;
import com.google.devtools.build.lib.rules.cpp.CcCommon.CcFlagsSupplier;
import com.google.devtools.build.lib.rules.cpp.CppHelper;
import com.google.devtools.build.lib.rules.java.JavaRuntimeInfo;
import com.google.devtools.build.lib.syntax.Type;
import com.google.devtools.build.lib.util.LazyString;
import com.google.devtools.build.lib.vfs.PathFragment;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * A base implementation of genrule, to be used by specific implementing rules which can change some
 * of the semantics around when the execution info and inputs are changed.
 */
public abstract class GenRuleBase implements RuleConfiguredTargetFactory {

  private static final ImmutableList<String> CROSSTOOL_MAKE_VARIABLES = ImmutableList.of("CC",
      "CC_FLAGS", "AR", "NM", "OBJCOPY", "STRIP", "GCOVTOOL");

  private static final ImmutableList<String> JDK_MAKE_VARIABLES = ImmutableList.of("JAVABASE",
      "JAVA");

  private static Pattern matchesMakeVariables(Iterable<String> variables) {
    return Pattern.compile("\\$\\((" + Joiner.on("|").join(variables) + ")\\)");
  }

  private static final Pattern CROSSTOOL_MAKE_VARIABLE_PATTERN =
      matchesMakeVariables(CROSSTOOL_MAKE_VARIABLES);
  private static final Pattern JDK_MAKE_VARIABLE = matchesMakeVariables(JDK_MAKE_VARIABLES);

  protected static boolean requiresCrosstool(String command) {
    return CROSSTOOL_MAKE_VARIABLE_PATTERN.matcher(command).find();
  }

  protected boolean requiresJdk(String command) {
    return JDK_MAKE_VARIABLE.matcher(command).find();
  }

  /**
   * Returns a {@link Map} of execution info, which will be used in later processing to construct
   * the actual command line that will be executed.
   *
   *
GenRule implementations can override this method to include additional specific information
   * needed.
   */
  protected Map<String, String> getExtraExecutionInfo(RuleContext ruleContext, String command) {
    return ImmutableMap.of();
  }

  /**
   * Returns {@code true} if the rule should be stamped.
   *
   *
Genrule implementations can set this based on the rule context, including by defining their
   * own attributes over and above what is present in {@link GenRuleBaseRule}.
   */
  protected abstract boolean isStampingEnabled(RuleContext ruleContext);

  /**
   * Updates the {@link RuleConfiguredTargetBuilder} that is used for this rule.
   *
   *
GenRule implementations can override this method to enhance and update the builder without
   * needing to entirely override the {@link com.google.devtools.build.lib.packages.RuleClass.ConfiguredTargetFactory#create} method.
   */
  protected RuleConfiguredTargetBuilder updateBuilder(
      RuleConfiguredTargetBuilder builder,
      RuleContext ruleContext,
      NestedSet<Artifact> filesToBuild) {
    return builder;
  }

  @Override
  public ConfiguredTarget create(RuleContext ruleContext)
      throws InterruptedException, RuleErrorException, ActionConflictException {
    NestedSet<Artifact> filesToBuild =
        NestedSetBuilder.wrap(Order.STABLE_ORDER, ruleContext.getOutputArtifacts());
    NestedSetBuilder<Artifact> resolvedSrcsBuilder = NestedSetBuilder.stableOrder();

    if (filesToBuild.isEmpty()) {
      ruleContext.attributeError("outs", "Genrules without outputs don't make sense");
    }
    if (ruleContext.attributes().get("executable", Type.BOOLEAN)
        && Iterables.size(filesToBuild) > 1) {
      ruleContext.attributeError(
          "executable",
          "if genrules produce executables, they are allowed only one output. "
              + "If you need the executable=1 argument, then you should split this genrule into "
              + "genrules producing single outputs");
    }

    ImmutableMap.Builder<Label, NestedSet<Artifact>> labelMap = ImmutableMap.builder();
    for (TransitiveInfoCollection dep : ruleContext.getPrerequisites("srcs", Mode.TARGET)) {
      // This target provides specific types of files for genrules.
      GenRuleSourcesProvider provider = dep.getProvider(GenRuleSourcesProvider.class);
      NestedSet<Artifact> files = (provider != null)
          ? provider.getGenruleFiles()
          : dep.getProvider(FileProvider.class).getFilesToBuild();
      resolvedSrcsBuilder.addTransitive(files);
      labelMap.put(AliasProvider.getDependencyLabel(dep), files);
    }
    NestedSet<Artifact> resolvedSrcs = resolvedSrcsBuilder.build();

    CommandHelper commandHelper =
        new CommandHelper(
            ruleContext, ruleContext.getPrerequisites("tools", Mode.HOST), labelMap.build());

    if (ruleContext.hasErrors()) {
      return null;
    }

    String baseCommand = ruleContext.attributes().get("cmd", Type.STRING);
    // Expand template variables and functions.
    String command = ruleContext
        .getExpander(new CommandResolverContext(ruleContext, resolvedSrcs, filesToBuild))
        .withExecLocations(commandHelper.getLabelMap())
        .expand("cmd", baseCommand);

    // Heuristically expand things that look like labels.
    if (ruleContext.attributes().get("heuristic_label_expansion", Type.BOOLEAN)) {
      command = commandHelper.expandLabelsHeuristically(command);
    }

    // Add the genrule environment setup script before the actual shell command.
    command = String.format("source %s; %s",
        ruleContext.getPrerequisiteArtifact("$genrule_setup", Mode.HOST).getExecPath(),
        command);

    String messageAttr = ruleContext.attributes().get("message", Type.STRING);
    String message = messageAttr.isEmpty() ? "Executing genrule" : messageAttr;
    Label label = ruleContext.getLabel();
    LazyString progressMessage =
        new LazyString() {
          @Override
          public String toString() {
            return message + " " + label;
          }
        };

    Map<String, String> executionInfo = Maps.newLinkedHashMap();
    executionInfo.putAll(TargetUtils.getExecutionInfo(ruleContext.getRule()));

    if (ruleContext.attributes().get("local", Type.BOOLEAN)) {
      executionInfo.put("local", "");
    }

    executionInfo.putAll(getExtraExecutionInfo(ruleContext, baseCommand));

    NestedSetBuilder<Artifact> inputs = NestedSetBuilder.stableOrder();
    inputs.addTransitive(resolvedSrcs);
    inputs.addAll(commandHelper.getResolvedTools());
    FilesToRunProvider genruleSetup =
        ruleContext.getPrerequisite("$genrule_setup", Mode.HOST, FilesToRunProvider.class);
    inputs.addTransitive(genruleSetup.getFilesToRun());
    PathFragment shExecutable = ShToolchain.getPathOrError(ruleContext);
    if (ruleContext.hasErrors()) {
      return null;
    }
    List<String> argv =
        commandHelper.buildCommandLine(
            shExecutable,
            command,
            inputs,
            ".genrule_script.sh",
            ImmutableMap.copyOf(executionInfo));

    // TODO(bazel-team): Make the make variable expander pass back a list of these.
    if (requiresCrosstool(baseCommand)) {
      // If cc is used, silently throw in the crosstool filegroup as a dependency.
      inputs.addTransitive(
          CppHelper.getToolchainUsingDefaultCcToolchainAttribute(ruleContext)
              .getCrosstoolMiddleman());
    }
    if (requiresJdk(baseCommand)) {
      // If javac is used, silently throw in the jdk filegroup as a dependency.
      // Note we expand Java-related variables with the *host* configuration.
      inputs.addTransitive(JavaRuntimeInfo.forHost(ruleContext).javaBaseInputsMiddleman());
    }

    if (isStampingEnabled(ruleContext)) {
      inputs.add(ruleContext.getAnalysisEnvironment().getStableWorkspaceStatusArtifact());
      inputs.add(ruleContext.getAnalysisEnvironment().getVolatileWorkspaceStatusArtifact());
    }

    ruleContext.registerAction(
        new GenRuleAction(
            ruleContext.getActionOwner(),
            ImmutableList.copyOf(commandHelper.getResolvedTools()),
            inputs.build(),
            filesToBuild,
            CommandLines.of(argv),
            ruleContext.getConfiguration().getActionEnvironment(),
            ImmutableMap.copyOf(executionInfo),
            new CompositeRunfilesSupplier(commandHelper.getToolsRunfilesSuppliers()),
            progressMessage));

    RunfilesProvider runfilesProvider = RunfilesProvider.withData(
        // No runfiles provided if not a data dependency.
        Runfiles.EMPTY,
        // We only need to consider the outputs of a genrule
        // No need to visit the dependencies of a genrule. They cross from the target into the host
        // configuration, because the dependencies of a genrule are always built for the host
        // configuration.
        new Runfiles.Builder(
            ruleContext.getWorkspaceName(),
            ruleContext.getConfiguration().legacyExternalRunfiles())
            .addTransitiveArtifacts(filesToBuild)
            .build());

    RuleConfiguredTargetBuilder builder = new RuleConfiguredTargetBuilder(ruleContext)
        .setFilesToBuild(filesToBuild)
        .setRunfilesSupport(null, getExecutable(ruleContext, filesToBuild))
        .addProvider(RunfilesProvider.class, runfilesProvider);

    builder = updateBuilder(builder, ruleContext, filesToBuild);
    return builder.build();
  }

  /**
   * Returns the executable artifact, if the rule is marked as executable and there is only one
   * artifact.
   */
  private static Artifact getExecutable(RuleContext ruleContext, NestedSet<Artifact> filesToBuild) {
    if (!ruleContext.attributes().get("executable", Type.BOOLEAN)) {
      return null;
    }
    if (Iterables.size(filesToBuild) == 1) {
      return Iterables.getOnlyElement(filesToBuild);
    }
    return null;
  }

  /**
   * Implementation of {@link ConfigurationMakeVariableContext} used to expand variables in a
   * genrule command string.
   */
  protected static class CommandResolverContext extends ConfigurationMakeVariableContext {

    private final RuleContext ruleContext;
    private final NestedSet<Artifact> resolvedSrcs;
    private final NestedSet<Artifact> filesToBuild;

    public CommandResolverContext(
        RuleContext ruleContext,
        NestedSet<Artifact> resolvedSrcs,
        NestedSet<Artifact> filesToBuild) {
      super(
          ruleContext,
          ruleContext.getRule().getPackage(),
          ruleContext.getConfiguration(),
          ImmutableList.of(new CcFlagsSupplier(ruleContext)));
      this.ruleContext = ruleContext;
      this.resolvedSrcs = resolvedSrcs;
      this.filesToBuild = filesToBuild;
    }

    public RuleContext getRuleContext() {
      return ruleContext;
    }

    @Override
    public String lookupVariable(String variableName) throws ExpansionException {
      if (variableName.equals("SRCS")) {
        return Artifact.joinExecPaths(" ", resolvedSrcs);
      }

      if (variableName.equals("<")) {
        return expandSingletonArtifact(resolvedSrcs, "$<", "input file");
      }

      if (variableName.equals("OUTS")) {
        return Artifact.joinExecPaths(" ", filesToBuild);
      }

      if (variableName.equals("@")) {
        return expandSingletonArtifact(filesToBuild, "$@", "output file");
      }

      if (variableName.equals("@D")) {
        // The output directory. If there is only one filename in outs,
        // this expands to the directory containing that file. If there are
        // multiple filenames, this variable instead expands to the
        // package's root directory in the genfiles tree, even if all the
        // generated files belong to the same subdirectory!
        if (Iterables.size(filesToBuild) == 1) {
          Artifact outputFile = Iterables.getOnlyElement(filesToBuild);
          PathFragment relativeOutputFile = outputFile.getExecPath();
          if (relativeOutputFile.segmentCount() <= 1) {
            // This should never happen, since the path should contain at
            // least a package name and a file name.
            throw new IllegalStateException(
                "$(@D) for genrule " + ruleContext.getLabel() + " has less than one segment");
          }
          return relativeOutputFile.getParentDirectory().getPathString();
        } else {
          PathFragment dir;
          if (ruleContext.getRule().hasBinaryOutput()) {
            dir = ruleContext.getConfiguration().getBinFragment();
          } else {
            dir = ruleContext.getConfiguration().getGenfilesFragment();
          }
          PathFragment relPath =
              ruleContext.getRule().getLabel().getPackageIdentifier().getSourceRoot();
          return dir.getRelative(relPath).getPathString();
        }
      }

      return super.lookupVariable(variableName);
    }

    /**
     * Returns the path of the sole element "artifacts", generating an exception with an informative
     * error message iff the set is not a singleton. Used to expand "$<", "$@".
     */
    private final String expandSingletonArtifact(Iterable<Artifact> artifacts,
        String variable,
        String artifactName)
        throws ExpansionException {
      if (Iterables.isEmpty(artifacts)) {
        throw new ExpansionException("variable '" + variable
            + "' : no " + artifactName);
      } else if (Iterables.size(artifacts) > 1) {
        throw new ExpansionException("variable '" + variable
            + "' : more than one " + artifactName);
      }
      return Iterables.getOnlyElement(artifacts).getExecPathString();
    }
  }
}


text:
import { createAction, handleActions } from 'redux-actions'
import { keys as _keys } from 'lodash'

// @Dev Hack: Mock data
// import { mockTeamState } from './__mock__'

const initialState = {
  entities: {}
}

export const createTeamAction = createAction('CREATE_TEAM')
export const createTeamSuccessAction = createAction('CREATE_TEAM_SUCCESS')
export const createTeamFailureAction = createAction('CREATE_TEAM_FAILURE')

export const joinTeamAction = createAction('JOIN_TEAM')
export const joinTeamSuccessAction = createAction('JOIN_TEAM_SUCCESS')
export const joinTeamFailureAction = createAction('JOIN_TEAM_FAILURE')

export const readTeamsAction = createAction('READ_TEAMS')
export const readTeamsSuccessAction = createAction('READ_TEAMS_SUCCESS')
export const readTeamsFailureAction = createAction('READ_TEAMS_FAILURE')

export const deleteTeamAction = createAction('DELETE_TEAM')
export const deleteTeamSuccessAction = createAction('DELETE_TEAM_SUCCESS')
export const deleteTeamFailureAction = createAction('DELETE_TEAM_FAILURE')

export const setTeamEntitiesAction = createAction('SET_TEAM_ENTITIES')

export const resetTeamEntitiesAction = createAction('CLEAR_TEAM_ENTITIES')

export const teamReducer = handleActions({

  [`${deleteTeamSuccessAction}`]: (state, action) => {
    if (!action.payload) {
      return state
    }

    const { teamId } = action.payload

    if (!teamId) {
      return state
    }

    const nextEntitiesKeys = _keys(state.entities)
      .filter((id) => id !== teamId)

    const nextStateEntities = nextEntitiesKeys
      .reduce((stateEntities, entityKey) => {
        stateEntities[entityKey] = state.entities[entityKey]
        return stateEntities
      }, {})

    return {
      ...state,
      entities: nextStateEntities
    }
  },

  [`${setTeamEntitiesAction}`]: (state, action) => {
    if (!action.payload) {
      return state
    }

    const { entities } = action.payload

    if (!entities) {
      return state
    }

    const entitiesKeys = _keys(entities)

    const nextStateEntities = entitiesKeys
      .reduce((stateEntities, entityKey) => {
        return {
          ...stateEntities,
          [entityKey]: {
            ...stateEntities[entityKey],
            ...entities[entityKey]
          }
        }
      }, state.entities)

    return {
      ...state,
      entities: nextStateEntities
    }
  },

  [`${resetTeamEntitiesAction}`]: (state, action) => {
    return {
      ...initialState
    }
  }

}, initialState)


text:
describe('github-star API: gitHubStar.repository.star', function() {
    require('./common')('star').starUnstar();
});


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
in Hiratsuka, Kaneko & Nagasawa, Rep. Tottori Mycol. Inst. 18: 161 (1980)

#### Original name
Aecidium formosanum Syd. & P. Syd., 1913

### Remarks
null


text:
import asynchat
import re
import string
import sys
import time

from lib.log import debug, info, warning, exception
from lib.msgs import insert_silences, encode_msg
import res
from serverroom import Anonymous, InTheLobby, OrganizingAGame, WaitingForTheGameToStart, Game

class ConnectionToClient(asynchat.async_chat):

    is_disconnected = False
    login = None
    version = None
    game = None

    def __init__(self, server, (connection, address)):
        info("Connected: %s:%s" % address)
        asynchat.async_chat.__init__(self, connection)
        self.id = server.get_next_id()
        self.set_terminator('\n')
        self.server = server
        self.inbuffer = ''
        self.address = address
        self.state = Anonymous()
        self.push(":")
        self.t1 = time.time()

    def collect_incoming_data(self, data):
        self.inbuffer += data

    def _execute_command(self, data):
        args = string.split(data)
        if args[0] not in self.state.allowed_commands:
            warning("action not allowed: %s" % args[0])
            return
        cmd = "cmd_" + args[0]
        if hasattr(self, cmd):
            getattr(self, cmd)(args[1:])
        else:
            warning("action unknown: %s" % args[0])

    def found_terminator(self):
        data = string.replace(self.inbuffer, "\r", "")
        debug("server data from %s: %s", self.login, data)
        self.inbuffer = ''
        try:
            self._execute_command(data)
        except SystemExit:
            raise
        except:
            exception("error executing command: %s" % data)

    def handle_close(self):
        try:
            debug("ConnectionToClient.handle_close")
        except:
            pass
        try:
            self.server.remove_client(self)
        except SystemExit:
            raise
        except:
            try:
                exception("error")
            except:
                pass
        self.close()

    def handle_error(self):
        try:
            debug("ConnectionToClient.handle_error %s", sys.exc_info()[0])
        except:
            pass
        if sys.exc_info()[0] in [SystemExit, KeyboardInterrupt]:
            sys.exit()
        else:
            self.handle_close()

    def send_invitations(self):
        self.push("invitations %s\n" %
            " ".join([
            ",".join([str(x) for x in [g.id, g.admin.login] + g.scenario.title])
            for g in self.server.games if self in g.guests]))

    def send_maps(self):
        if self.server.can_create(self):
            self.push("maps %s\n" %
                      " ".join([",".join([str(y) for y in x.title])
                                for x in res.worlds_multi()]))
        else:
            self.push("maps \n")

    def send_e(self, event):
        self.push("e %s\n" % event)

    def is_compatible(self, client):
        return self.version == client.version

    # "anonymous" commands

    def _unique_login(self, client_login):
        login = client_login
        n = 2
        # "ai" (or "npc_ai") is reserved
        # (used to forbid cheatmode in multiplayer games)
        while login in [x.login for x in self.server.clients] + ["ai", "npc_ai"]:
            login = client_login + "%s" % n
            n += 1
        return login

    def _get_version_and_login_from_data(self, data):
        try:
            version, login = data.split(" ", 1)
        except:
            warning("can't extract version and login: %s" % data)
            return (None, None)
        if re.match("^[a-zA-Z0-9]{1,20}$", login) == None:
            warning("bad login: %s" % login)
            return (version, None)
        if len(self.server.clients) >= self.server.nb_clients_max:
            warning("refused client %s: too many clients." % login)
            return (version, None)
        return (version, self._unique_login(login))

    def _send_server_status_msg(self):
        msg = []
        for c in self.server.clients:
            if c.is_compatible(self):
                msg.append(c.login)
        self.send_msg(insert_silences(msg))
        for g in self.server.games:
            if g.started:
                self.send_msg(g.get_status_msg())

    def _accept_client_after_login(self):
        self.delay = time.time() - self.t1
        info("new player: IP=%s login=%s version=%s delay=%s" %
             (self.address[0], self.login, self.version, self.delay))
        # welcome client to server
        self.push("ok!\n")
        self.push("welcome %s %s\n" % (self.login, self.server.login))
        self.server.clients.append(self)
        # move client to lobby
        self.state = InTheLobby()
        # alert lobby and game admins
        for c in self.server.available_players() + self.server.game_admins():
            if c.is_compatible(self):
                c.send_e("new_player,%s" % self.login)
        self._send_server_status_msg()
        for g in self.server.games:
            g.notify_connection_of(self)
        self.server.log_status()

    def cmd_login(self, args):
        self.version, self.login = self._get_version_and_login_from_data(" ".join(args))
        if self.login is not None:
            self._accept_client_after_login()
            self.server.update_menus()
        else:
            info("incorrect login")
            self.handle_close() # disconnect client

    # "in the lobby" commands

    def cmd_create(self, args):
        if self.server.can_create(self):
            self.state = OrganizingAGame()
            self.push("game_admin_menu\n")
            scs = res.worlds_multi()
            scenario = scs[int(args[0])]
            self.push("map %s\n" % scenario.pack())
            speed = float(args[1])
            is_public = len(args) >= 3 and args[2] == "public"
            self.server.games.append(Game(scenario, speed, self.server,
                    self, is_public))
            self.server.update_menus()
        else:
            warning("game not created (max number reached)")
            self.send_msg([4057])

    def cmd_register(self, args):
        game = self.server.get_game_by_id(args[0])
        if game is not None and game.can_register():
            self.state = WaitingForTheGameToStart()
            self.push("game_guest_menu\n")
            self.push("map %s\n" % game.scenario.pack())
            game.register(self)
            self.server.update_menus()
        else:
            self.send_msg([1029]) # hostile sound

    def cmd_quit(self, unused_args):
        # When the client wants to quit, he first sends "quit" to the server.
        # Then the server knows he musn't send commands anymore. He warns the
        # client: "ok, you can quit". Then the client closes the connection
        # and then, and only then, the server forgets the client.
        self.push("quit\n")
        # self.is_quitting = True

    # "organizing a game" commands

    def cmd_cancel_game(self, unused_args):
        self.game.cancel()
        self.server.update_menus()

    def cmd_invite(self, args):
        guest = self.server.get_client_by_login(args[0])
        if guest and guest in self.server.available_players() and guest.is_compatible(self):
            self.game.invite(guest)
            self.server.update_menus()
        else:
            self.send_msg([1029]) # hostile sound

    def cmd_invite_easy(self, unused_args):
        self.game.invite_computer("easy")
        self.send_menu() # only the admin

    def cmd_invite_aggressive(self, unused_args):
        self.game.invite_computer("aggressive")
        self.send_menu() # only the admin

    def cmd_move_to_alliance(self, args):
        self.game.move_to_alliance(args[0], args[1])
        self.send_menu() # only the admin

    def cmd_start(self, unused_args):
        self.game.start() # create chosen world
        self.server.update_menus()

    def cmd_faction(self, args):
        self.game.set_faction(args[0], args[1])
        self.server.update_menus()

    # "waiting for the game to start" commands

    def cmd_unregister(self, unused_args):
        self.game.unregister(self)
        self.server.update_menus()

    # "playing" commands

    def cmd_orders(self, args):
        self.game.orders(self, args)

    def cmd_quit_game(self, unused_args):
        self.game.quit_game(self)
        self.server.update_menus()

    def cmd_abort_game(self, unused_args):
        self.game.abort_game(self)
        self.server.update_menus()

    # wrapper

    def send_menu(self):
        self.state.send_menu(self)

    # misc

    def send_msg(self, msg):
        self.push("msg %s\n" % encode_msg(msg))

    def login_to_send(self):
        return self.login

    def cmd_debug_info(self, args):
        info(" ".join(args))

    def cmd_say(self, args):
        msg = [self.login] + [4287] + [" ".join(args)]
        if self.game is not None:
            self.game.broadcast(msg)
        else:
            for p in self.server.available_players():
                p.send_msg(msg)


text:
class GUI
{
public:
	GUI();
	~GUI();

	virtual void GUI::blank();
	virtual void GUI::draw();

	virtual void GUI::process(Creature* currentCreature);

	int xCoord;
	int yCoord;

	int layer;

	color_t color;

	std::string displayString;

};


text:
FROM       riddopic/alpine
MAINTAINER Stefano Harding <riddopic@gmail.com>

EXPOSE 80 443
ENV GOMAXPROCS=2
ADD root /
RUN apk add --update nginx openssh && \
    rm -rf /var/cache/apk/* && \
    mkdir -p /tmp/nginx && \
    chown -R nginx:www-data /tmp/nginx && \
    ln -sf /dev/stdout /var/log/nginx/access.log && \
    ln -sf /dev/stderr /var/log/nginx/error.log


text:
#import <SparkKit/SparkKit.h>

#pragma mark Notifications

SPARK_EXPORT
NSString * const SparkEntryManagerWillAddEntryNotification;
SPARK_EXPORT
NSString * const SparkEntryManagerDidAddEntryNotification;

SPARK_EXPORT
NSString * const SparkEntryManagerWillUpdateEntryNotification;
SPARK_EXPORT
NSString * const SparkEntryManagerDidUpdateEntryNotification;

SPARK_EXPORT
NSString * const SparkEntryManagerWillRemoveEntryNotification;
SPARK_EXPORT
NSString * const SparkEntryManagerDidRemoveEntryNotification;

SPARK_EXPORT
NSString * const SparkEntryManagerDidChangeEntryStatusNotification;

@class SparkObject;
@class SparkLibrary, SparkEntry;
@class SparkAction, SparkTrigger, SparkApplication;

SPARK_OBJC_EXPORT
@interface SparkEntryManager : NSObject

- (instancetype)initWithLibrary:(SparkLibrary *)aLibrary;

@property(nonatomic, readonly) SparkLibrary *library;
@property(nonatomic, readonly) NSUndoManager *undoManager;

#pragma mark Management
- (SparkEntry *)entryWithUID:(SparkUID)uid;

- (void)enumerateEntriesUsingBlock:(void (^)(SparkEntry *entry, BOOL *stop))block;

/* add a new root entry */
- (SparkEntry *)addEntryWithAction:(SparkAction *)anAction trigger:(SparkTrigger *)aTrigger application:(SparkApplication *)aApplication;

- (void)removeEntry:(SparkEntry *)anEntry;
- (void)removeEntriesInArray:(NSArray *)theEntries;

#pragma mark Queries
//- (NSArray *)entriesForAction:(SparkUID)anAction;
- (NSArray *)entriesForTrigger:(SparkTrigger *)aTrigger;
- (NSArray *)entriesForApplication:(SparkApplication *)anApplication;

/* Orphan check */
- (BOOL)containsEntryForAction:(SparkAction *)anAction;
- (BOOL)containsEntryForTrigger:(SparkTrigger *)aTrigger;
/* Editor Queries */
- (BOOL)containsEntryForApplication:(SparkApplication *)anApplication;

/* Daemon queries */
- (BOOL)containsRegistredEntryForTrigger:(SparkTrigger *)aTrigger;

- (SparkEntry *)activeEntryForTrigger:(SparkTrigger *)aTrigger application:(SparkApplication *)anApplication;

/* First, search for specifics actions */
/* If not found, search for a default action */
/* If default action found, search default action child for anApplication. If one exists, returns NULL, else returns default */
- (SparkEntry *)resolveEntryForTrigger:(SparkTrigger *)aTrigger application:(SparkApplication *)anApplication;

@end

@interface SparkEntryManager ()
/* Private, use to dereference weak */
@property(nonatomic, assign) SparkLibrary *library;

@end


text:
SimpleAlertView (SCLAlertViewカスタマイズ版)
===========
※変更点
- アイコンの削除
- Alert,Loadingの2スタイルに統合し、色指定をラップ化
- Loadingスタイルにアクティビティインジケーター追加
- 色指定をUIIntからUIColorに変更

|.Alert|.Loading|
|---|---|
|![BackgroundImage](https://raw.githubusercontent.com/ya-s-u/SCLAlertView-Swift/master/screenshots/IMG_4450.PNG)|![BackgroundImage](https://raw.githubusercontent.com/ya-s-u/SCLAlertView-Swift/master/screenshots/IMG_4451.PNG) |

thanks :bow:

SCLAlertView
===========

Animated Alert View written in Swift, which can be used as a `UIAlertView` or `UIAlertController` replacement. Since `UIAlertView` is deprecated and `UIAlertController` only works on iOS 8.x or above, if you have a Swift project where you want to support iOS 7.x too, SCLAlertView is an ideal substitution.

![BackgroundImage](https://raw.githubusercontent.com/vikmeup/SCPopUpView/master/successScreenshot.png)_
![BackgroundImage](https://raw.githubusercontent.com/vikmeup/SCPopUpView/master/editScreenshot.png)

###Easy to use
```swift
// Get started
let alertview : SCLAlertViewResponder = SCLAlertView().showSuccess(self, title: "Hello World", subTitle: "This is a more descriptive text.")

// Upon displaying, change/close view
alertview.setTitle("New Title") // Rename title
alertview.setSubTitle("New description") // Rename subtitle
alertview.close() // Close view

// Alternative alert types
SCLAlertView().showError(self, title: "Hello Error", subTitle: "This is a more descriptive error text.") // Error
SCLAlertView().showNotice(self, title: "Hello Notice", subTitle: "This is a more descriptive notice text.") // Notice
SCLAlertView().showWarning(self, title: "Hello Warning", subTitle: "This is a more descriptive warning text.") // Warning
SCLAlertView().showInfo(self, title: "Hello Info", subTitle: "This is a more descriptive info text.") // Info
SCLAlertView().showEdit(self, title: "Hello Edit", subTitle: "This is a more descriptive info text.") // Edit

// Advanced
SCLAlertView().showTitle(
    view: self, // Parent view controller
    title: "Congratulations", // Title of view
    subTitle: "Operation successfully completed.", // String of view
    duration: kDefaultAnimationDuration, // Duration to show before closing automatically, default: 2.0
    completeText: "Done", // Optional button value, default: ""
    style: .Success // Styles - see below.
)

// Add buttons
let alert = SCLAlertView()
alert.addButton("First Button", target:self, selector:Selector("firstButton"))
alert.addButton("Second Button") {
    println("Second button tapped")
}
alert.showSuccess(self, title: "Button View", subTitle: "This alert view has buttons")

// Add a text field
let alert = SCLAlertView()
let txt = alert.addTextField(title:"Enter your name")
alert.addButton("Show Name") {
    println("Text value: \(txt.text)")
}
alert.showEdit(self, title: "Edit View", subTitle: "This alert view shows a text box")
```

####Alert View Styles
```swift
enum SCLAlertViewStyle: Int {
    case Success, Error, Notice, Warning, Info, Edit, Wait
}
```

### Installation

SCLAlertView is available through [CocoaPods](http://cocoapods.org).

To install add the following line to your Podfile:

    pod 'SCLAlertView'

### Collaboration
I tried to build an easy to use API, while beeing flexible enough for multiple variations, but I'm sure there are ways of improving and adding more features, so feel free to collaborate with ideas, issues and/or pull requests.

###Incoming improvements
- More animations
- Performance tests

Has been developed initially for the [Scroll Feed](https://itunes.apple.com/us/app/scroll-feed/id842422195?ls=1&mt=8) app

- Design [@SherzodMx](https://twitter.com/SherzodMx) Sherzod Max
- Development [@hackua](https://twitter.com/hackua) Viktor Radchenko
- Improvements by [@bih](http://github.com/bih) Bilawal Hameed, [@rizjoj](http://github.com/rizjoj) Riz Joj