text:
package com.mirkogrcic.gui;

import com.mirkogrcic.gui.util.Point;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JPanel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ImagePanel extends JPanel implements MouseListener, MouseMotionListener, KeyListener {
    private final static Logger logger = LoggerFactory.getLogger(com.mirkogrcic.Application.class.getName());
    private final static double initialScale = 0.3d;
    private final static double scaleStep = 0.05;
    private final static double scaleFineStep = 0.01;
    private final static double locXStep = 30d;
    private final static double locYStep = 30d;

    private Image image;
    private double scale;
    private Point location;  // Location in panel (center based)
    private Point frozenMotionLocation;   // Location in panel (center based)
    private Point mouseDownLocation;  // Location in panel (top-left based)

    private boolean fineScale;

    public ImagePanel(Image image){
        this.image = image;
        this.scale = initialScale;
        this.location = new Point();

        this.fineScale = false;

        this.setFocusable(true);
        this.requestFocus();

        addMouseListener(this);
        addMouseMotionListener(this);
        addKeyListener(this);
    }

    @Override
    protected void paintComponent(Graphics graphics) {
        super.paintComponent(graphics);

        double iw, ih;  // Image
        double pw, ph;  // Panel
        double locx, locy;

        if( this.image != null ) {
            iw = image.getWidth(null) * scale;
            ih = image.getHeight(null) * scale;

            pw = this.getWidth();
            ph = this.getHeight();

            // Limit it so there is no empty space
            if( iw < pw ){
                // Image smaller than window, center it
                location.x = 0;
            }else{
                location.x = Math.min(location.x, iw/2 - pw/2);
                location.x = Math.max(location.x, -(iw/2 - pw/2));
            }
            if( ih < ph ){
                // Image smaller than window, center it
                location.y = 0;
            }else{
                location.y = Math.min(location.y, ih/2 - ph/2);
                location.y = Math.max(location.y, -(ih/2 - ph/2));
            }

            // Calculate location from center
            locx = location.x + pw/2 - iw/2;
            locy = location.y + ph/2 - ih/2;

            graphics.drawImage(this.image, (int)locx, (int)locy, (int)iw, (int)ih, null);
        }

    }

    @Override
    public void keyTyped(KeyEvent keyEvent) {

    }

    @Override
    public void keyPressed(KeyEvent keyEvent) {
        switch (keyEvent.getKeyCode()) {
            case KeyEvent.VK_CONTROL:
                this.fineScale = true;
                break;
        }
    }

    @Override
    public void keyReleased(KeyEvent keyEvent) {
        switch (keyEvent.getKeyCode()){
            case KeyEvent.VK_CONTROL:
                this.fineScale = false;
                break;

            case KeyEvent.VK_R:
                this.scale = initialScale;
                this.location.reset();
                break;

            case KeyEvent.VK_PLUS:
                this.scale += fineScale ? scaleFineStep : scaleStep;
                break;
            case KeyEvent.VK_MINUS:
                this.scale -= fineScale ? scaleFineStep : scaleStep;
                break;

            case KeyEvent.VK_UP:
            case KeyEvent.VK_KP_UP:
                location.y -= locYStep;
                break;
            case KeyEvent.VK_DOWN:
            case KeyEvent.VK_KP_DOWN:
                location.y += locYStep;
                break;
            case KeyEvent.VK_LEFT:
            case KeyEvent.VK_KP_LEFT:
                location.x -= locXStep;
                break;
            case KeyEvent.VK_RIGHT:
            case KeyEvent.VK_KP_RIGHT:
                location.x += locXStep;
                break;
        }
        repaint();
    }

    @Override
    public void mouseClicked(MouseEvent mouseEvent) {

    }

    @Override
    public void mousePressed(MouseEvent mouseEvent) {
        frozenMotionLocation = location.clone();
        mouseDownLocation = new Point(mouseEvent.getX(), mouseEvent.getY());
    }

    @Override
    public void mouseReleased(MouseEvent mouseEvent) {

    }

    @Override
    public void mouseEntered(MouseEvent mouseEvent) {

    }

    @Override
    public void mouseExited(MouseEvent mouseEvent) {

    }

    @Override
    public void mouseDragged(MouseEvent mouseEvent) {
        final double space = 0.8;
        final double iw = image.getWidth(null) * scale;
        final double ih = image.getHeight(null) * scale;
        final double pw = this.getWidth();
        final double ph = this.getHeight();

        final Point mouseLocation = new Point(mouseEvent.getX(), mouseEvent.getY());

        Point panelDiff = mouseLocation.getDiff(mouseDownLocation);

        location.set(frozenMotionLocation);
        location.add(panelDiff);

        this.repaint();

    }

    @Override
    public void mouseMoved(MouseEvent mouseEvent) {

    }
}


text:
package sagan.blog.support;

import sagan.blog.PostFormat;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;

@Service
@Profile("!original")
public class FormatAwarePostContentRenderer extends PostContentRenderer {

    private Map<PostFormat, MarkdownService> renderers = new HashMap<>();

    @Autowired
    public FormatAwarePostContentRenderer(@Qualifier("pegdown") MarkdownService markdownService) {
        super(markdownService);
        renderers.put(PostFormat.ASCIIDOC, new AsciidoctorMarkdownService());
    }

    public String render(String content, PostFormat format) {
        MarkdownService renderer = renderers.get(format);
        if (renderer == null) {
            return super.render(content);
        }
        return renderer.renderToHtml(content);
    }

}

redpajama_set_name: RedPajamaGithub


text:
package com.parse;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import bolts.Task;
import bolts.TaskCompletionSource;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class ParseObjectTest {

  @Rule
  public ExpectedException thrown = ExpectedException.none();

  @After
  public void tearDown() {
    ParseCorePlugins.getInstance().reset();
  }

  @Test
  public void testFromJSONPayload() throws JSONException {
    JSONObject json = new JSONObject(
        "{" +
        "\"className\":\"GameScore\"," +
        "\"createdAt\":\"2015-06-22T21:23:41.733Z\"," +
        "\"objectId\":\"TT1ZskATqS\"," +
        "\"updatedAt\":\"2015-06-22T22:06:18.104Z\"," +
        "\"score\":{" +
            "\"__op\":\"Increment\"," +
            "\"amount\":1" +
            "}," +
        "\"age\":33" +
        "}");

    ParseFieldOperations.registerDefaultDecoders();

    ParseObject parseObject = ParseObject.fromJSONPayload(json, ParseDecoder.get());
    assertEquals("GameScore", parseObject.getClassName());
    assertEquals("TT1ZskATqS", parseObject.getObjectId());
    ParseDateFormat format = ParseDateFormat.getInstance();
    assertTrue(parseObject.getCreatedAt().equals(format.parse("2015-06-22T21:23:41.733Z")));
    assertTrue(parseObject.getUpdatedAt().equals(format.parse("2015-06-22T22:06:18.104Z")));

    Set<String> keys = parseObject.getState().keySet();
    assertEquals(0, keys.size());

    ParseOperationSet currentOperations = parseObject.operationSetQueue.getLast();
    assertEquals(2, currentOperations.size());
  }

  @Test
  public void testFromJSONPayloadWithoutClassname() throws JSONException {
    JSONObject json = new JSONObject("{\"objectId\":\"TT1ZskATqS\"}");
    ParseObject parseObject = ParseObject.fromJSONPayload(json, ParseDecoder.get());
    assertNull(parseObject);
  }

  //region testRevert

  @Test
  public void testRevert() throws ParseException {
    List<Task<Void>> tasks = new ArrayList<>();

    // Mocked to let save work
    ParseCurrentUserController userController = mock(ParseCurrentUserController.class);
    when(userController.getAsync()).thenReturn(Task.<ParseUser>forResult(null));
    ParseCorePlugins.getInstance().registerCurrentUserController(userController);

    // Mocked to simulate in-flight save
    TaskCompletionSource<ParseObject.State> tcs = new TaskCompletionSource();
    ParseObjectController objectController = mock(ParseObjectController.class);
    when(objectController.saveAsync(
        any(ParseObject.State.class),
        any(ParseOperationSet.class),
        anyString(),
        any(ParseDecoder.class)))
        .thenReturn(tcs.getTask());
    ParseCorePlugins.getInstance().registerObjectController(objectController);

    // New clean object
    ParseObject object = new ParseObject("TestObject");
    object.revert("foo");

    // Reverts changes on new object
    object.put("foo", "bar");
    object.put("name", "grantland");
    object.revert();
    assertNull(object.get("foo"));
    assertNull(object.get("name"));

    // Object from server
    ParseObject.State state = mock(ParseObject.State.class);
    when(state.className()).thenReturn("TestObject");
    when(state.objectId()).thenReturn("test_id");
    when(state.keySet()).thenReturn(Collections.singleton("foo"));
    when(state.get("foo")).thenReturn("bar");
    object = ParseObject.from(state);
    object.revert();
    assertFalse(object.isDirty());
    assertEquals("bar", object.get("foo"));

    // Reverts changes on existing object
    object.put("foo", "baz");
    object.put("name", "grantland");
    object.revert();
    assertFalse(object.isDirty());
    assertEquals("bar", object.get("foo"));
    assertFalse(object.isDataAvailable("name"));

    // Shouldn't revert changes done before last call to `save`
    object.put("foo", "baz");
    object.put("name", "nlutsenko");
    tasks.add(object.saveInBackground());
    object.revert();
    assertFalse(object.isDirty());
    assertEquals("baz", object.get("foo"));
    assertEquals("nlutsenko", object.get("name"));

    // Should revert changes done after last call to `save`
    object.put("foo", "qux");
    object.put("name", "grantland");
    object.revert();
    assertFalse(object.isDirty());
    assertEquals("baz", object.get("foo"));
    assertEquals("nlutsenko", object.get("name"));

    // Allow save to complete
    tcs.setResult(state);
    ParseTaskUtils.wait(Task.whenAll(tasks));
  }

  @Test
  public void testRevertKey() throws ParseException {
    List<Task<Void>> tasks = new ArrayList<>();

    // Mocked to let save work
    ParseCurrentUserController userController = mock(ParseCurrentUserController.class);
    when(userController.getAsync()).thenReturn(Task.<ParseUser>forResult(null));
    ParseCorePlugins.getInstance().registerCurrentUserController(userController);

    // Mocked to simulate in-flight save
    TaskCompletionSource<ParseObject.State> tcs = new TaskCompletionSource();
    ParseObjectController objectController = mock(ParseObjectController.class);
    when(objectController.saveAsync(
        any(ParseObject.State.class),
        any(ParseOperationSet.class),
        anyString(),
        any(ParseDecoder.class)))
        .thenReturn(tcs.getTask());
    ParseCorePlugins.getInstance().registerObjectController(objectController);

    // New clean object
    ParseObject object = new ParseObject("TestObject");
    object.revert("foo");

    // Reverts changes on new object
    object.put("foo", "bar");
    object.put("name", "grantland");
    object.revert("foo");
    assertNull(object.get("foo"));
    assertEquals("grantland", object.get("name"));

    // Object from server
    ParseObject.State state = mock(ParseObject.State.class);
    when(state.className()).thenReturn("TestObject");
    when(state.objectId()).thenReturn("test_id");
    when(state.keySet()).thenReturn(Collections.singleton("foo"));
    when(state.get("foo")).thenReturn("bar");
    object = ParseObject.from(state);
    object.revert("foo");
    assertFalse(object.isDirty());
    assertEquals("bar", object.get("foo"));

    // Reverts changes on existing object
    object.put("foo", "baz");
    object.put("name", "grantland");
    object.revert("foo");
    assertEquals("bar", object.get("foo"));
    assertEquals("grantland", object.get("name"));

    // Shouldn't revert changes done before last call to `save`
    object.put("foo", "baz");
    object.put("name", "nlutsenko");
    tasks.add(object.saveInBackground());
    object.revert("foo");
    assertEquals("baz", object.get("foo"));
    assertEquals("nlutsenko", object.get("name"));

    // Should revert changes done after last call to `save`
    object.put("foo", "qux");
    object.put("name", "grantland");
    object.revert("foo");
    assertEquals("baz", object.get("foo"));
    assertEquals("grantland", object.get("name"));

    // Allow save to complete
    tcs.setResult(state);
    ParseTaskUtils.wait(Task.whenAll(tasks));
  }

  //endregion

  //region testGetter

  @Test( expected = IllegalStateException.class )
  public void testGetUnavailable() {
    ParseObject.State state = mock(ParseObject.State.class);
    when(state.className()).thenReturn("TestObject");
    when(state.isComplete()).thenReturn(false);
    ParseObject object = ParseObject.from(state);
    object.get("foo");
  }

  @Test
  public void testGetAvailableIfKeyAvailable() {
    ParseObject.State state = mock(ParseObject.State.class);
    when(state.className()).thenReturn("TestObject");
    when(state.isComplete()).thenReturn(false);
    when(state.availableKeys()).thenReturn(new HashSet<>(Arrays.asList("foo")));
    ParseObject object = ParseObject.from(state);
    object.get("foo");
  }

  @Test
  public void testGetList() throws Exception {
    ParseObject object = new ParseObject("Test");
    JSONArray array = new JSONArray();
    array.put("value");
    array.put("valueAgain");
    object.put("key", array);

    List list = object.getList("key");

    assertEquals(2, list.size());
    assertTrue(list.contains("value"));
    assertTrue(list.contains("valueAgain"));
  }

  @Test
  public void testGetListWithWrongValue() throws Exception {
    ParseObject object = new ParseObject("Test");
    object.put("key", 1);

    assertNull(object.getList("key"));
  }

  @Test
  public void testGetJSONArray() throws Exception {
    ParseObject object = new ParseObject("Test");
    object.put("key", Arrays.asList("value", "valueAgain"));

    JSONArray array = object.getJSONArray("key");

    assertEquals(2, array.length());
    assertEquals("value", array.getString(0));
    assertEquals("valueAgain", array.getString(1));
  }

  @Test
  public void testGetJsonArrayWithWrongValue() throws Exception {
    ParseObject object = new ParseObject("Test");
    object.put("key", 1);

    assertNull(object.getJSONArray("key"));
  }

  @Test
  public void testGetJSONObject() throws Exception {
    ParseObject object = new ParseObject("Test");
    Map<String, String> map = new HashMap<>();
    map.put("key", "value");
    map.put("keyAgain", "valueAgain");
    object.put("key", map);

    JSONObject json = object.getJSONObject("key");

    assertEquals(2, json.length());
    assertEquals("value", json.getString("key"));
    assertEquals("valueAgain", json.getString("keyAgain"));
  }

  @Test
  public void testGetJsonObjectWithWrongValue() throws Exception {
    ParseObject object = new ParseObject("Test");
    object.put("key", 1);

    assertNull(object.getJSONObject("key"));
  }

  @Test
  public void testGetBoolean() throws Exception {
    ParseObject object = new ParseObject("Test");
    object.put("key", true);

    assertTrue(object.getBoolean("key"));
  }

  @Test
  public void testGetBooleanWithWrongValue() throws Exception {
    ParseObject object = new ParseObject("Test");
    object.put("key", 1);

    assertFalse(object.getBoolean("key"));
  }

  @Test
  public void testGetDate() throws Exception {
    ParseObject object = new ParseObject("Test");
    Date date = new Date();
    object.put("key", date);

    assertEquals(date, object.getDate("key"));
  }

  @Test
  public void testGetDateWithWrongValue() throws Exception {
    ParseObject object = new ParseObject("Test");
    object.put("key", 1);

    assertNull(object.getDate("key"));
  }

  @Test
  public void testGetParseGeoPoint() throws Exception {
    ParseObject object = new ParseObject("Test");
    ParseGeoPoint point = new ParseGeoPoint(10, 10);
    object.put("key", point);

    assertEquals(point, object.getParseGeoPoint("key"));
  }

  @Test
  public void testGetParseGeoPointWithWrongValue() throws Exception {
    ParseObject object = new ParseObject("Test");
    object.put("key", 1);

    assertNull(object.getParseGeoPoint("key"));
  }

  @Test
  public void testGetACL() throws Exception {
    ParseObject object = new ParseObject("Test");
    ParseACL acl = new ParseACL();
    object.put("ACL", acl);

    assertEquals(acl, object.getACL());
  }

  @Test
  public void testGetACLWithSharedACL() throws Exception {
    ParseObject object = new ParseObject("Test");
    ParseACL acl = new ParseACL();
    acl.setShared(true);
    acl.setPublicReadAccess(true);
    object.put("ACL", acl);

    ParseACL aclAgain = object.getACL();
    assertTrue(aclAgain.getPublicReadAccess());
  }

  @Test
  public void testGetACLWithNullValue() throws Exception {
    ParseObject object = new ParseObject("Test");

    assertNull(object.getACL());
  }

  @Test
  public void testGetACLWithWrongValue() throws Exception {
    ParseObject object = new ParseObject("Test");
    object.put("ACL", 1);

    thrown.expect(RuntimeException.class);
    thrown.expectMessage("only ACLs can be stored in the ACL key");

    object.getACL();
  }

  @Test
  public void testGetMap() throws Exception {
    ParseObject object = new ParseObject("Test");
    JSONObject json = new JSONObject();
    json.put("key", "value");
    json.put("keyAgain", "valueAgain");
    object.put("key", json);

    Map map = object.getMap("key");

    assertEquals(2, map.size());
    assertEquals("value", map.get("key"));
    assertEquals("valueAgain", map.get("keyAgain"));
  }

  @Test
  public void testGetMapWithWrongValue() throws Exception {
    ParseObject object = new ParseObject("Test");
    object.put("key", 1);

    assertNull(object.getMap("key"));
  }

  @Test
  public void testGetParseUser() throws Exception {
    ParseObject object = new ParseObject("Test");
    ParseUser user = mock(ParseUser.class);
    object.put("key", user);

    assertEquals(user, object.getParseUser("key"));
  }

  @Test
  public void testGetParseUserWithWrongValue() throws Exception {
    ParseObject object = new ParseObject("Test");
    object.put("key", 1);

    assertNull(object.getParseUser("key"));
  }

  @Test
  public void testGetParseFile() throws Exception {
    ParseObject object = new ParseObject("Test");
    ParseFile file = mock(ParseFile.class);
    object.put("key", file);

    assertEquals(file, object.getParseFile("key"));
  }

  @Test
  public void testGetParseFileWithWrongValue() throws Exception {
    ParseObject object = new ParseObject("Test");
    object.put("key", 1);

    assertNull(object.getParseFile("key"));
  }

  @Test
  public void testGetDouble() throws Exception {
    ParseObject object = new ParseObject("Test");
    object.put("key", 1.1);

    assertEquals(1.1, object.getDouble("key"), 0.00001);
  }

  @Test
  public void testGetDoubleWithWrongValue() throws Exception {
    ParseObject object = new ParseObject("Test");
    object.put("key", "str");

    assertEquals(0.0, object.getDouble("key"), 0.00001);
  }

  @Test
  public void testGetLong() throws Exception {
    ParseObject object = new ParseObject("Test");
    object.put("key", 10L);

    assertEquals(10L, object.getLong("key"));
  }

  @Test
  public void testGetLongWithWrongValue() throws Exception {
    ParseObject object = new ParseObject("Test");
    object.put("key", "str");

    assertEquals(0, object.getLong("key"));
  }

  //endregion
}


text:
package com.digium.respokesdktest.functional;

import android.util.Log;

import com.digium.respokesdk.Respoke;
import com.digium.respokesdk.RespokeCall;
import com.digium.respokesdk.RespokeClient;
import com.digium.respokesdk.RespokeDirectConnection;
import com.digium.respokesdk.RespokeEndpoint;
import com.digium.respokesdk.RespokeGroup;
import com.digium.respokesdktest.RespokeTestCase;

import java.util.Date;

public class ConnectionTests extends RespokeTestCase implements RespokeClient.Listener {

    private boolean rateLimitHit;
    RespokeEndpoint endpoint;

    // Test temporarily disabled until socket library issues are resolved
/*
    public void testRateLimiting() {
        // Create a client to test with
        final String testEndpointID = generateTestEndpointID();
        final RespokeClient client = createTestClient(testEndpointID, this);

        endpoint = client.getEndpoint(testEndpointID, false);
        assertNotNull("Should create endpoint instance", endpoint);

        asyncTaskDone = false;

        // Launch 5 simultaneous cascades of presence registration calls to the server, in an effort to hit the rate limit
        sendLoop(1);
        sendLoop(1);
        sendLoop(1);
        sendLoop(1);
        sendLoop(1);

        assertTrue("Test timed out", waitForCompletion(RespokeTestCase.TEST_TIMEOUT));
        assertTrue("Should eventually hit a rate limit error", rateLimitHit);
    }

    public void sendLoop(final Integer attempt) {
        // Generally hits the rate limit around 20 attempts
        if (!rateLimitHit && (attempt < 30)) {
            endpoint.registerPresence(new Respoke.TaskCompletionListener() {
                @Override
                public void onSuccess() {
                    assertTrue("Should be called in UI thread", RespokeTestCase.currentlyOnUIThread());
                    sendLoop(attempt + 1);
                }

                @Override
                public void onError(String errorMessage) {
                    if (!rateLimitHit) {
                        assertTrue("Should indicate a rate limit error. received: " + errorMessage, errorMessage.equals("API rate limit was exceeded"));
                        rateLimitHit = true;
                        asyncTaskDone = true;
                    }
                }
            });
        } else {
            asyncTaskDone = true;
        }
    }
*/

    // RespokeClient.Listener methods

    public void onConnect(RespokeClient sender) {
        asyncTaskDone = true;
    }

    public void onDisconnect(RespokeClient sender, boolean reconnecting) {
        assertTrue("Should not disconnect during testing", false);
        asyncTaskDone = true;
    }

    public void onError(RespokeClient sender, String errorMessage) {
        assertTrue("Should not produce any client errors during endpoint testing", false);
        asyncTaskDone = true;
    }

    public void onCall(RespokeClient sender, RespokeCall call) {
        // Not under test
    }

    public void onIncomingDirectConnection(RespokeDirectConnection directConnection, RespokeEndpoint endpoint) {
        // Not under test
    }

    public void onMessage(String message, RespokeEndpoint endpoint, RespokeGroup group, Date timestamp, Boolean didSend) {
        // Not under test
    }

}


text:
package edu.mit.ll.nics.common.alert;

import java.net.InetAddress;
import java.util.Date;

import org.apache.log4j.Logger;

import edu.mit.ll.nics.common.email.EmailFactory;
import edu.mit.ll.nics.common.email.XmlEmail;

public class EmailAlert {

	private long lastEmail = 0;
	private long timeout = 90000;
	private Logger log = Logger.getLogger(EmailAlert.class.getSimpleName());
	private String className;
	private String defFromEmail;
	private String defToEmail;
	private String destUrl = null;
	private EmailFactory ef = null;

	/**
	 * constructor
	 * @param toEmail - comma separated list of email addresses to send to
	 * @param fromEmail - email address to send from
	 * @param className - class/app that this message should be associated with
	 */
	protected EmailAlert(String toEmail, String fromEmail, String className, EmailFactory ef) {
		this.defToEmail = toEmail;
		this.defFromEmail = fromEmail;
		this.className = className;
		this.ef = ef;
		log.info("Created LDDRS EmailAlert -- sending from: " + fromEmail);
	}

	/**
	 * constructor
	 * @param destUrl - the default camel endpoint to send email xml messages to
	 * @param toEmail - comma separated list of email addresses to send to
	 * @param fromEmail - email address to send from
	 * @param className - class/app that this message should be associated with
	 */
	protected EmailAlert(String destUrl, String toEmail, String fromEmail, String className, EmailFactory ef){
		this.destUrl = destUrl;
		this.defToEmail = toEmail;
		this.defFromEmail = fromEmail;
		this.className = className;
		this.ef = ef;
		log.info("Created LDDRS EmailAlert -- sending from: " + fromEmail);
	}

	/**
	 * Send exception to default topic for alerting
	 * @param e - exception to send alert about
	 */
	public void send(Exception e){
		this.send(e, false);
	}

	/**
	 * Send exception to default topic for alerting
	 * @param e - exception to send alert about
	 * @param ignoreTimeout - boolean indicating whether we should ignore the timeout value and just send
	 */
	public void send(Exception e, boolean ignoreTimeout){
		this.send(this.defToEmail, e, ignoreTimeout);
	}

	/**
	 * Send exception to default topic for alerting
	 * @param e - exception to send alert about
	 * @param emailTo - email address to send to
	 */
	public void send(String emailTo, Exception e){
		this.send(emailTo, e, false);
	}

	/**
	 * Send exception to default topic for alerting
	 * @param e - exception to send alert about
	 * @param emailTo - email address to send to
	 * @param ignoreTimeout - boolean indicating whether we should ignore the timeout value and just send
	 */
	public void send(String emailTo, Exception e, boolean ignoreTimeout){
		this.send(this.destUrl, emailTo, e, ignoreTimeout);
	}

	/**
	 * Send exception to destination for alerting
	 * @param dest - destination camel endpoint
	 * @param emailTo - email address to send to
	 * @param e - exception to send alert about
	 */
	public void send(String dest, String emailTo, Exception e){
		this.send(dest, emailTo, e, false);
	}

	/**
	 * Send exception to destination for alerting
	 * @param dest - destination camel endpoint
	 * @param emailTo - email address to send to
	 * @param e - exception to send alert about
	 * @param ignoreTimeout - boolean indicating whether we should ignore the timeout value and just send
	 */
	public void send(String dest, String emailTo, Exception e, boolean ignoreTimeout){
		this.sendString(dest, emailTo, e.getMessage(), ignoreTimeout);
	}

	/**
	 * Send message to default topic for alerting
	 * @param message - message of alert
	 */
	public void sendString(String message){
		this.sendString(message,false);
	}

	/**
	 * Send message to default topic for alerting
	 * @param message - message of alert
	 * @param ignoreTimeout - boolean indicating whether we should ignore the timeout value and just send
	 */
	public void sendString(String message, boolean ignoreTimeout){
		this.sendString(this.defToEmail,message, ignoreTimeout);
	}

	/**
	 * Send message to default topic for alerting
	 * @param message - message of alert
	 * @param emailTo - email address to send to
	 */
	public void sendString(String emailTo, String message){
		this.sendString(emailTo, message, false);
	}

	/**
	 * Send message to default topic for alerting
	 * @param message - message of alert
	 * @param emailTo - email address to send to
	 * @param ignoreTimeout - boolean indicating whether we should ignore the timeout value and just send
	 */
	public void sendString(String emailTo, String message, boolean ignoreTimeout){
		this.sendString(this.destUrl, emailTo, message, ignoreTimeout);
	}

	/**
	 * Send message to destination topic for alerting
	 * @param dest - destination camel endpoint
	 * @param emailTo - email address to send to
	 * @param message - message of alert
	 */
	public void sendString(String dest, String emailTo, String message){
		this.sendString(dest, emailTo, message, false);
	}

	/**
	 * Send message to destination topic for alerting
	 * @param dest - destination camel endpoint
	 * @param emailTo - email address to send to
	 * @param message - message of alert
	 * @param ignoreTimeout - boolean indicating whether we should ignore the timeout value and just send
	 */
	public void sendString(String dest, String emailTo, String message, boolean ignoreTimeout){
		log.debug("in emailAlert");
		String hostname = "unknown";
		try{
			hostname = InetAddress.getLocalHost().getHostName();
		}
		catch (Exception e1) {
			log.error("couldn't get hostname",e1);
		}

		Date nowDate = new Date();
		long now = nowDate.getTime();
		if(now - this.lastEmail > this.timeout || ignoreTimeout){
			log.debug("sending message to " + dest);
			XmlEmail email = ef.createEmail(defFromEmail, emailTo, "Alert from " + this.className + "@" + hostname);
			email.setBody( nowDate.toString() + "\n\n" + message);
			if(dest != null){
				email.send(dest);
			}
			else{
				email.send();
			}
			if(!ignoreTimeout){
				this.lastEmail = now;
			}
			log.debug("sent message");
		}
		else{
			log.debug("not sending message: doesn't meet timeout criteria");
		}
	}

	/**
	 * Set timeout for message delay
	 * @param seconds - number of seconds to delay btwn sending messages (to limit spamming alerts). set to 0 for no delay/limiting
	 */
	public void setTimeout(int seconds){
		this.timeout = seconds * 1000;
	}
}


text:
namespace Eventually.Projections.Messages
{
    public class RebuildProjection
    {
    }
}


text:
package opennlp.tools.cmdline;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
import java.util.regex.Pattern;

import opennlp.tools.parser.AbstractBottomUpParser;
import opennlp.tools.parser.Parse;
import opennlp.tools.parser.Parser;
import opennlp.tools.parser.ParserModel;
import opennlp.tools.util.InvalidFormatException;
import opennlp.tools.util.Span;

/**
 * Class for performing full parsing on English text.
 */
public class TreebankParser {

  private static Pattern untokenizedParenPattern1 = Pattern.compile("([^ ])([({)}])");
  private static Pattern untokenizedParenPattern2 = Pattern.compile("([({)}])([^ ])");

  private static String convertToken(String token) {
    if (token.equals("(")) {
      return "-LRB-";
    }
    else if (token.equals(")")) {
      return "-RRB-";
    }
    else if (token.equals("{")) {
      return "-LCB-";
    }
    else if (token.equals("}")) {
      return "-RCB-";
    }
    return token;
  }

  public static Parse[] parseLine(String line, Parser parser, int numParses) {
    line = untokenizedParenPattern1.matcher(line).replaceAll("$1 $2");
    line = untokenizedParenPattern2.matcher(line).replaceAll("$1 $2");
    StringTokenizer str = new StringTokenizer(line);
    StringBuffer sb = new StringBuffer();
    List<String> tokens = new ArrayList<String>();
    while (str.hasMoreTokens()) {
      String tok = convertToken(str.nextToken());
      tokens.add(tok);
      sb.append(tok).append(" ");
    }
    String text = sb.substring(0, sb.length() - 1);
    Parse p = new Parse(text, new Span(0, text.length()), AbstractBottomUpParser.INC_NODE, 1, 0);
    int start = 0;
    int i=0;
    for (Iterator<String> ti = tokens.iterator(); ti.hasNext();i++) {
      String tok = (String) ti.next();
      p.insert(new Parse(text, new Span(start, start + tok.length()), AbstractBottomUpParser.TOK_NODE, 0,i));
      start += tok.length() + 1;
    }
    Parse[] parses;
    if (numParses == 1) {
      parses = new Parse[] { parser.parse(p)};
    }
    else {
      parses = parser.parse(p,numParses);
    }
    return parses;
  }

  private static void usage() {
    System.err.println("Usage: TreebankParser [-bs n -ap f] model < tokenized_sentences");
    System.err.println("model the parser model.");
    System.err.println("-bs 20: Use a beam size of 20.");
    System.err.println("-ap 0.95: Advance outcomes in with at least 95% of the probability mass.");
    System.err.println("-k 5: Show the top 5 parses.  This will also display their log-probablities.");
    System.exit(1);
  }

  public static void main(String[] args) throws InvalidFormatException, IOException {
    if (args.length == 0) {
      usage();
    }
    boolean showTopK = false;
    int numParses = 1;
    int ai = 0;

    // TODO: Set these parameters on the parser
    int beamSize = AbstractBottomUpParser.defaultBeamSize;
    double advancePercentage = AbstractBottomUpParser.defaultAdvancePercentage;
    while (args[ai].startsWith("-")) {
      if (args[ai].equals("-bs")) {
      	if (args.length > ai+1) {
          try {
            beamSize=Integer.parseInt(args[ai+1]);
            ai++;
          }
          catch(NumberFormatException nfe) {
            System.err.println(nfe);
            usage();
          }
      	}
      	else {
      	  usage();
      	}
      }
      else if (args[ai].equals("-ap")) {
        if (args.length > ai+1) {
          try {
            advancePercentage=Double.parseDouble(args[ai+1]);
            ai++;
          }
          catch(NumberFormatException nfe) {
            System.err.println(nfe);
            usage();
          }
      	}
      	else {
      	  usage();
      	}
      }
      else if (args[ai].equals("-k")) {
        showTopK = true;
        if (args.length > ai+1) {
          try {
            numParses=Integer.parseInt(args[ai+1]);
            ai++;
          }
          catch(NumberFormatException nfe) {
            System.err.println(nfe);
            usage();
          }
      	}
      	else {
      	  usage();
      	}
      }
      else if (args[ai].equals("--")) {
      	ai++;
        break;
      }
      else {
        System.err.println("Unknown option "+args[ai]);
        usage();
      }
      ai++;
    }

    ParserModel model = ParserModel.create(new FileInputStream(args[ai]));
    Parser parser = new opennlp.tools.parser.chunking.Parser(model);

    BufferedReader in;
    if (ai == args.length) {
      in = new BufferedReader(new InputStreamReader(System.in));
    }
    else {
      in = new BufferedReader(new FileReader(args[ai]));
    }
    String line;
    try {
      while (null != (line = in.readLine())) {
        if (line.length() == 0) {
          System.out.println();
        }
        else {
          Parse[] parses = parseLine(line, parser, numParses);
          for (int pi=0,pn=parses.length;pi<pn;pi++) {
            if (showTopK) {
              System.out.print(pi+" "+parses[pi].getProb()+" ");
            }
            parses[pi].show();
          }
        }
      }
    }
    catch (IOException e) {
      System.err.println(e);
    }
  }
}


text:
<!DOCTYPE html>

    <title>Saya</title>
<link rel="icon" href="assets/favicon.png">
<link href='https://fonts.googleapis.com/css?family=Fredericka+the+Great' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Comfortaa' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/dojo/1.10.4/dijit/themes/claro/claro.css">
<link rel="stylesheet" href="css/saya.css">
<link rel="stylesheet" href="css/welcome.css">

Saya

 Anti-spy for Guilds

 Probe Creator

 Generates new probes.

 Inspector

 Inspect data for suspects.


text:
#include "Sample.h"
#include "SkCanvas.h"
#include "SkFont.h"
#include "SkRandom.h"
#include "SkPaint.h"
#include "SkUTF.h"
#if SK_SUPPORT_GPU
#include "GrRectanizer_pow2.h"
#include "GrRectanizer_skyline.h"

// This slide visualizes the various GrRectanizer-derived classes behavior
// for various input sets
//  'j' will cycle through the various rectanizers
//          Pow2 -> GrRectanizerPow2
//          Skyline -> GrRectanizerSkyline
//  'h' will cycle through the various rect sets
//          Rand -> random rects from 2-256
//          Pow2Rand -> random power of 2 sized rects from 2-256
//          SmallPow2 -> 128x128 rects
class RectanizerView : public Sample {
public:
    RectanizerView()
        : fCurRandRect(0)
        , fCurRectanizer(0) {
        for (int i = 0; i < 3; ++i) {
           fRects[i].setReserve(kNumRandRects);
        }
        fRectLocations.setReserve(kNumRandRects);

        SkRandom random;
        for (int i = 0; i < kNumRandRects; ++i) {
            *fRects[0].append() = SkISize::Make(random.nextRangeU(kMinRectSize, kMaxRectSize),
                                                random.nextRangeU(kMinRectSize, kMaxRectSize));
            *fRects[1].append() = SkISize::Make(
                        GrNextPow2(random.nextRangeU(kMinRectSize, kMaxRectSize)),
                        GrNextPow2(random.nextRangeU(kMinRectSize, kMaxRectSize)));
            *fRects[2].append() = SkISize::Make(128, 128);
            *fRectLocations.append() = SkIPoint16::Make(0, 0);
        }

        fCurRects = &fRects[0];

        fRectanizers.push_back(
            std::unique_ptr<GrRectanizer>(new GrRectanizerPow2(kWidth, kHeight)));
        fRectanizers.push_back(
            std::unique_ptr<GrRectanizer>(new GrRectanizerSkyline(kWidth, kHeight)));
    }

protected:
    bool onQuery(Sample::Event* evt) override {
        if (Sample::TitleQ(*evt)) {
            Sample::TitleR(evt, "Rectanizer");
            return true;
        }
        SkUnichar uni;
        if (Sample::CharQ(*evt, &uni)) {
            char utf8[SkUTF::kMaxBytesInUTF8Sequence];
            size_t size = SkUTF::ToUTF8(uni, utf8);
            // Only consider events for single char keys
            if (1 == size) {
                switch (utf8[0]) {
                case kCycleRectanizerKey:
                    this->cycleRectanizer();
                    return true;
                case kCycleRectsKey:
                    this->cycleRects();
                    return true;
                default:
                    break;
                }
            }
        }
        return this->INHERITED::onQuery(evt);
    }

    void onDrawContent(SkCanvas* canvas) override {
        if (fCurRandRect < kNumRandRects) {
            if (fRectanizers[fCurRectanizer]->addRect((*fCurRects)[fCurRandRect].fWidth,
                                                      (*fCurRects)[fCurRandRect].fHeight,
                                                      &fRectLocations[fCurRandRect])) {
                ++fCurRandRect;
            }
        }

        SkFont blackBigFont;
        blackBigFont.setSize(20);
        SkPaint blackStroke;
        blackStroke.setStyle(SkPaint::kStroke_Style);
        SkPaint redFill;
        redFill.setColor(SK_ColorRED);

        SkRect r = SkRect::MakeWH(SkIntToScalar(kWidth), SkIntToScalar(kHeight));

        canvas->clear(SK_ColorWHITE);
        canvas->drawRect(r, blackStroke);

        long totArea = 0;
        for (int i = 0; i < fCurRandRect; ++i) {
            r = SkRect::MakeXYWH(SkIntToScalar(fRectLocations[i].fX),
                                 SkIntToScalar(fRectLocations[i].fY),
                                 SkIntToScalar((*fCurRects)[i].fWidth),
                                 SkIntToScalar((*fCurRects)[i].fHeight));
            canvas->drawRect(r, redFill);
            canvas->drawRect(r, blackStroke);
            totArea += (*fCurRects)[i].fWidth * (*fCurRects)[i].fHeight;
        }

        SkString str;

        str.printf("%s-%s: tot Area: %ld %%full: %.2f (%.2f) numTextures: %d/%d",
                   this->getRectanizerName(),
                   this->getRectsName(),
                   totArea,
                   100.0f * fRectanizers[fCurRectanizer]->percentFull(),
                   100.0f * totArea / ((float)kWidth*kHeight),
                   fCurRandRect,
                   kNumRandRects);
        canvas->drawString(str, 50, kHeight + 50, blackBigFont, SkPaint());

        str.printf("Press \'j\' to toggle rectanizer");
        canvas->drawString(str, 50, kHeight + 100, blackBigFont, SkPaint());

        str.printf("Press \'h\' to toggle rects");
        canvas->drawString(str, 50, kHeight + 150, blackBigFont, SkPaint());
    }

private:
    static const int kWidth = 1024;
    static const int kHeight = 1024;
    static const int kNumRandRects = 200;
    static const char kCycleRectanizerKey = 'j';
    static const char kCycleRectsKey = 'h';
    static const int kMinRectSize = 2;
    static const int kMaxRectSize = 256;

    int                                     fCurRandRect;
    SkTDArray<SkISize>                      fRects[3];
    SkTDArray<SkISize>*                     fCurRects;
    SkTDArray<SkIPoint16>                   fRectLocations;
    SkTArray<std::unique_ptr<GrRectanizer>> fRectanizers;
    int                                     fCurRectanizer;

    const char* getRectanizerName() const {
        if (!fCurRectanizer) {
            return "Pow2";
        } else {
            return "Skyline";
        }
    }

    void cycleRectanizer() {
        fCurRectanizer = (fCurRectanizer + 1) % fRectanizers.count();

        fRectanizers[fCurRectanizer]->reset();
        fCurRandRect = 0;
    }

    const char* getRectsName() const {
        if (fCurRects == &fRects[0]) {
            return "Rand";
        } else if (fCurRects == &fRects[1]) {
            return "Pow2Rand";
        } else {
            return "SmallPow2";
        }
    }

    void cycleRects() {
        if (fCurRects == &fRects[0]) {
            fCurRects = &fRects[1];
        } else if (fCurRects == &fRects[1]) {
            fCurRects = &fRects[2];
        } else {
            fCurRects = &fRects[0];
        }

        fRectanizers[fCurRectanizer]->reset();
        fCurRandRect = 0;
    }

    typedef Sample INHERITED;
};

//////////////////////////////////////////////////////////////////////////////

DEF_SAMPLE( return new RectanizerView(); )

#endif


text:
package de.intarsys.tools.tree;

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

/**
 * A generic {@link PropertiesNode} to collect predefined property children.
 * These are for example created by the parent node directly.
 *
 */
public class DeclaredPropertiesNode extends PropertiesNode {

	private List<CommonNode> properties = new ArrayList<CommonNode>();

	public DeclaredPropertiesNode(CommonNode parent, Object object) {
		super(parent, object);
	};

	public void addPropertyNode(CommonNode node) {
		properties.add(node);
		updateChildren();
	}

	public void clearPropertyNodes() {
		properties.clear();
		unlinkChildren();
	}

	@Override
	protected void createPropertyNodes(List<CommonNode> pProperties) {
		pProperties.addAll(properties);
	}

	public boolean isEmpty() {
		return properties.size() == 0;
	}

	public void removePropertyNode(CommonNode node) {
		properties.remove(node);
		node.unlink();
		updateChildren();
	}
}


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

describe "select_date" do
  it "should send the values for each individual date component" do
    with_html <<-HTML

      <form action="/appointments" method="post">
        Date

        <select id="appointment_date_1i" name="appointment[date(1i)]">
          <option value="2003">2003</option>
        </select>
        <select id="appointment_date_2i" name="appointment[date(2i)]">
          <option value="12">December</option>
        </select>
        <select id="appointment_date_3i" name="appointment[date(3i)]">
          <option value="25">25</option>
        </select>
        <input type="submit" />
      </form>

    HTML
    webrat_session.should_receive(:post).with("/appointments",
      "appointment" => {"date(1i)" => '2003', "date(2i)" => "12", "date(3i)" => "25"})
    select_date "December 25, 2003", :from => "Date"
    click_button
  end

  it "should accept a date object" do
    with_html <<-HTML

      <form action="/appointments" method="post">
        date

        <select id="appointment_date_1i" name="appointment[date(1i)]">
          <option value="2003">2003</option>
        </select>
        <select id="appointment_date_2i" name="appointment[date(2i)]">
          <option value="12">December</option>
        </select>
        <select id="appointment_date_3i" name="appointment[date(3i)]">
          <option value="25">25</option>
        </select>
        <input type="submit" />
      </form>

    HTML
    webrat_session.should_receive(:post).with("/appointments",
      "appointment" => {"date(1i)" => '2003', "date(2i)" => "12", "date(3i)" => "25"})
    select_date Date.parse("December 25, 2003"), :from => "date"
    click_button
  end

  it "should work when no label is specified" do
    with_html <<-HTML

      <form action="/appointments" method="post">
        <select id="appointment_date_1i" name="appointment[date(1i)]">
          <option value="2003">2003</option>
        </select>
        <select id="appointment_date_2i" name="appointment[date(2i)]">
          <option value="12">December</option>
        </select>
        <select id="appointment_date_3i" name="appointment[date(3i)]">
          <option value="25">25</option>
        </select>
        <input type="submit" />
      </form>

    HTML
    webrat_session.should_receive(:post).with("/appointments",
      "appointment" => {"date(1i)" => '2003', "date(2i)" => "12", "date(3i)" => "25"})
    select_date "December 25, 2003"
    click_button
  end

  it "should fail if the specified label is not found" do
    with_html <<-HTML

      <form method="post" action="/appointments">
        <select name="month"><option>January</option></select>
        <input type="submit" />
      </form>

    HTML

    lambda { select_date "December 25, 2003", :from => "date" }.should raise_error(Webrat::NotFoundError)
  end

end


text:
<resources>

    <string name="app_name">小马输入法</string>

</resources>


text:
<?php

namespace GD;

use Behat\Gherkin\Gherkin;
use Behat\Gherkin\Keywords\CucumberKeywords;
use Behat\Gherkin\Lexer;
use Behat\Gherkin\Loader\GherkinFileLoader;
use Behat\Gherkin\Loader\YamlFileLoader;
use Behat\Gherkin\Parser;
use GD\Exceptions\MustSetFileNameAndPath;
use GD\Helpers\AppendBrowserFile;
use GD\Helpers\AppendFile;
use GD\Helpers\BuildOutContent;
use GD\Helpers\WriteBrowserFile;
use GD\Helpers\WritePHPUnitFile;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Support\Facades\App;
use Symfony\Component\Yaml\Yaml;

class GherkinToDusk extends BaseGherkinToDusk
{
    use BuildOutContent;

    protected $component = false;

    protected $string_contents = null;

    /**
     * Yml Content of a test yml
     * @var string
     */
    protected $feature_content;

    /**
     * @var \Behat\Gherkin\Node\FeatureNode
     */
    protected $parsed_feature;

    /**
     *
     */
    protected $dusk_class_and_methods;

    /**
     * @var WritePHPUnitFile
     */
    protected $write_unit_test;

    /**
     * @var AppendFile
     */
    protected $append_unit_test;

    /**
     * @var WriteBrowserFile
     */
    protected $write_browser_test;

    /**
     * @var \GD\Helpers\AppendBrowserFile
     */
    protected $append_browser_test;

    public function appendFeatures()
    {
        $this->loadFileContent();
        $this->buildDuskTestName();
        $this->passThroughParser();
        $this->breakIntoMethods();

        switch ($this->context) {
            case 'unit':
            case 'domain':
                $this->featureAppendToUnit();
                break;
            case 'ui':
            case 'browser':
                $this->featureAppendToBrowser();
                break;
            default:
                //more coming soon
                break;
        }
    }

    public function initializeFeature()
    {
        $this->loadFileContent();

        $this->buildDuskTestName();

        $this->passThroughParser();

        $this->breakIntoMethods();

        switch ($this->context) {
            case 'unit':
            case 'domain':
                $this->featureToUnit();
                break;
            case 'ui':
            case 'browser':
                $this->featureToBrowser();
                break;
            default:
                //more coming soon
                break;
        }
    }

    protected function featureToBrowser()
    {
        $this->checkIfFileExists();

        $this->getWriteBrowserTest()->writeTest(
            $this->getDestinationFolderRoot(),
            $this->getDuskTestName(),
            $this->getDuskClassAndMethods()
        );
    }

    protected function featureAppendToBrowser()
    {
        $this->getAppendBrowserTest()->writeTest(
            $this->getDestinationFolderRoot(),
            $this->getDuskTestName(),
            $this->getDuskClassAndMethods()
        );
    }

    protected function featureAppendToUnit()
    {
        $this->getAppendUnitTest()->writeTest(
            $this->getDestinationFolderRoot(),
            $this->getDuskTestName(),
            $this->getDuskClassAndMethods()
        );
    }

    protected function featureToUnit()
    {
        $this->checkIfFileExists();

        $this->getWriteUnitTest()->writeTest(
            $this->getDestinationFolderRoot(),
            $this->getDuskTestName(),
            $this->getDuskClassAndMethods()
        );
    }

    /**
     * @return boolean
     */
    public function isComponent()
    {
        return $this->component;
    }

    /**
     * @param boolean $component
     */
    public function setComponent($component)
    {
        $this->component = $component;
    }

    /**
     * @return mixed
     */
    public function getFeatureContent()
    {
        return $this->feature_content;
    }

    /**
     * @param mixed $feature_content
     */
    public function setFeatureContent($feature_content)
    {
        $this->feature_content = $feature_content;
    }

    private function loadFileContent()
    {
        $this->feature_content =
            $this->getFilesystem()->get($this->getFullPathToFileAndFileName());
    }

    private function passThroughParser()
    {
        $this->parsed_feature = $this->getParser()->parse($this->feature_content);
    }

    /**
     * @return \Behat\Gherkin\Node\FeatureNode
     */
    public function getParsedFeature()
    {
        return $this->parsed_feature;
    }

    /**
     * @param \Behat\Gherkin\Node\FeatureNode $parsed_feature
     */
    public function setParsedFeature($parsed_feature)
    {
        $this->parsed_feature = $parsed_feature;
    }

    private function breakIntoMethods()
    {
        $this->iterateOverScenariosAndBuildUpClassMethods();
    }

    private function iterateOverScenariosAndBuildUpClassMethods()
    {
        /** @var  $feature \Behat\Gherkin\Node\ScenarioNode */
        foreach ($this->parsed_feature->getScenarios() as $scenario_index => $scenario) {
            $parent_method_name = ucfirst(camel_case($scenario->getTitle()));

            $parent_method_name_camelized_and_prefix_test = sprintf('test%s', $parent_method_name);

            $this->dusk_class_and_methods[$scenario_index] = [
                'parent' => $parent_method_name_camelized_and_prefix_test,
                'parent_content' => $this->getParentLevelContent($parent_method_name_camelized_and_prefix_test)
            ];

            $this->buildOutSteps($scenario, $scenario_index);
        }
    }

    /**
     * @param $scenario \Behat\Gherkin\Node\ScenarioNode
     */
    protected function buildOutSteps($scenario, $scenario_index)
    {
        foreach ($scenario->getSteps() as $step_index => $step) {
            $method_name = camel_case(sprintf("%s %s", $step->getKeyword(), $step->getText()));
            $step_method_name_camalized = camel_case(sprintf("%s %s", $step->getKeyword(), $step->getText()));
            $this->dusk_class_and_methods[$scenario_index]['steps'][$step_index]['name'] =
                $method_name;
            $this->dusk_class_and_methods[$scenario_index]['steps'][$step_index] =
                $this->getStepLevelContent($step_method_name_camalized);
        }
    }

    /**
     * @return mixed
     */
    public function getDuskClassAndMethods()
    {
        return $this->dusk_class_and_methods;
    }

    /**
     * @param mixed $dusk_class_and_methods
     */
    public function setDuskClassAndMethods($dusk_class_and_methods)
    {
        $this->dusk_class_and_methods = $dusk_class_and_methods;
    }

    public function getWriteBrowserTest()
    {

        if (!$this->write_browser_test) {
            $this->setWriteBrowserTest();
        }

        return $this->write_browser_test;
    }

    /**
     * @param null $write_browser_test
     * @return GherkinToDusk
     * @internal param WritePHPUnitFile $write_unit_test
     */
    public function setWriteBrowserTest($write_browser_test = null)
    {
        if (!$write_browser_test) {
            $write_browser_test = new WriteBrowserFile();
        }

        $this->write_browser_test = $write_browser_test;
        return $this;
    }

    public function getWriteUnitTest()
    {

        if (!$this->write_unit_test) {
            $this->setWriteUnitTest();
        }

        return $this->write_unit_test;
    }

    /**
     * @param WritePHPUnitFile $write_unit_test
     * @return GherkinToDusk
     */
    public function setWriteUnitTest($write_unit_test = null)
    {
        if (!$write_unit_test) {
            $write_unit_test = new WritePHPUnitFile();
        }

        $this->write_unit_test = $write_unit_test;
        return $this;
    }

    /**
     * @return $append_unit_test AppendFile
     */
    public function getAppendUnitTest()
    {

        if (!$this->append_unit_test) {
            $this->setAppendUnitTest();
        }

        return $this->append_unit_test;
    }

    /**
     * @param AppendFile $append_unit_test
     * @return GherkinToDusk
     */
    public function setAppendUnitTest($append_unit_test = null)
    {
        if (!$append_unit_test) {
            $append_unit_test = new AppendFile();
        }

        $this->append_unit_test = $append_unit_test;
        return $this;
    }

    private function checkIfFileExists()
    {
        if ($this->filesystem->exists($this->fullPathToDestinationFile())) {
            $path = $this->fullPathToDestinationFile();
            $message = sprintf("The test file exists already %s please use `append` command", $path);
            throw new \GD\Exceptions\TestFileExists($message);
        }
    }

    /**
     * @return Helpers\AppendBrowserFile
     */
    public function getAppendBrowserTest()
    {
        if (!$this->append_browser_test) {
            $this->setAppendBrowserTest();
        }

        return $this->append_browser_test;
    }

    /**
     * @param Helpers\AppendBrowserFile $append_browser_test
     * @return $this
     */
    public function setAppendBrowserTest($append_browser_test = null)
    {
        if (!$append_browser_test) {
            $append_browser_test = new AppendBrowserFile();
        }

        $this->append_browser_test = $append_browser_test;
        return $this;
    }
}


text:
import React from 'react';
import {Spring} from 'react-motion';
import {Url} from 'component-router';
import styles from './Filter.css';

const Opened = React.createClass({
  shouldComponentUpdate() {
    return false;
  },

  render() {
    return (

Filters

        <Url query={{filter: 'closed'}}>←</Url>

    );
  }
});

const Closed = React.createClass({
  shouldComponentUpdate() {
    return false;
  },

  render() {
    return (
      <Url query={{filter: 'opened'}}>
        →
      </Url>
    );
  }
});

const Content = React.createClass({
  propTypes: {
    width: React.PropTypes.number,
    isOpened: React.PropTypes.bool
  },

  shouldComponentUpdate({isOpened, width}) {
    return isOpened !== this.props.isOpened || width !== this.props.width;
  },

  render() {
    const {isOpened, width} = this.props;

    return (

        {isOpened ? <Opened /> : <Closed />}

    );
  }
});

const Filter = React.createClass({
  propTypes: {
    isOpened: React.PropTypes.bool
  },

  shouldComponentUpdate({isOpened}) {
    return isOpened !== this.props.isOpened;
  },

  render() {
    const {isOpened} = this.props;

    return (
      <Spring endValue={{val: isOpened ? Math.min(window.innerWidth / 5, 550) : 65}}>
        {({val: width}) => (
          <Content width={width} isOpened={isOpened} />
        )}
      </Spring>
    );
  }
});

export default Filter;


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

#import "GSCXScannerIssueExpandableTableViewDelegate.h"

#import "GSCXScannerIssueExpandableTableViewCell.h"
#import "GSCXScannerIssueExpandableTableViewHeader.h"
#import "GSCXUtils.h"
#import <GTXiLib/GTXiLib.h>
NS_ASSUME_NONNULL_BEGIN

NSString *const kGSCXScannerIssueExpandableTableViewCellReuseIdentifier =
    @"kGSCXScannerIssueExpandableTableViewCellReuseIdentifier";

NSString *const kGSCXScannerIssueExpandableTableViewHeaderReuseIdentifier =
    @"kGSCXScannerIssueExpandableTableViewHeaderReuseIdentifier";

/**
 * The error displayed when @c GSCXScannerIssueExpandableTableViewDelegate dequeues a cell that is
 * of the wrong type.
 */
static NSString *const kGSCXScannerIssueExpandableTableViewDelegateIncorrectCellClassError =
    @"Error in GSCXScannerIssueExpandableTableViewDelegate: cell must be of type "
    @"GSCXScannerIssueExpandableTableViewCell";

/**
 * The error displayed when @c GSCXScannerIssueExpandableTableViewDelegate dequeues a header that is
 * of the wrong type.
 */
static NSString *const kGSCXScannerIssueExpandableTableViewDelegateIncorrectHeaderClassError =
    @"Error in GSCXScannerIssueExpandableTableViewDelegate: header must be of type "
    @"GSCXScannerIssueExpandableTableViewHeader";

@interface GSCXScannerIssueExpandableTableViewDelegate ()

/**
 * The sections to display in the table view.
 */
@property(copy, nonatomic, readonly) NSArray<GSCXScannerIssueTableViewSection *> *sections;

/**
 * Invoked when a user taps a row in the table view.
 */
@property(copy, nonatomic) GSCXScannerIssueExpandableTableViewDelegateSelectionBlock selectionBlock;

/**
 * The text color for cells. Defaults to @c whiteColor.
 */
@property(strong, nonatomic) UIColor *textColor;

/**
 * The background color for cells. Defaults to @c blackColor.
 */
@property(strong, nonatomic) UIColor *backgroundColor;

@end

@implementation GSCXScannerIssueExpandableTableViewDelegate

- (instancetype)initWithSections:(NSArray<GSCXScannerIssueTableViewSection *> *)sections
                  selectionBlock:
                      (GSCXScannerIssueExpandableTableViewDelegateSelectionBlock)selectionBlock {
  self = [super init];
  if (self) {
    _sections = [sections copy];
    _selectionBlock = selectionBlock;
    _textColor = [UIColor whiteColor];
    _backgroundColor = [UIColor blackColor];
  }
  return self;
}

- (void)registerClassesForReuseOnTableView:(UITableView *)tableView {
  [tableView registerClass:[GSCXScannerIssueExpandableTableViewCell class]
      forCellReuseIdentifier:kGSCXScannerIssueExpandableTableViewCellReuseIdentifier];
  [tableView registerClass:[GSCXScannerIssueExpandableTableViewHeader class]
      forHeaderFooterViewReuseIdentifier:kGSCXScannerIssueExpandableTableViewHeaderReuseIdentifier];
}

- (void)setTextColor:(UIColor *)textColor
     backgroundColor:(UIColor *)backgroundColor
         onTableView:(UITableView *)tableView {
  self.textColor = textColor;
  self.backgroundColor = backgroundColor;
  for (GSCXScannerIssueExpandableTableViewCell *cell in tableView.visibleCells) {
    GTX_ASSERT([cell isKindOfClass:[GSCXScannerIssueExpandableTableViewCell class]],
               kGSCXScannerIssueExpandableTableViewDelegateIncorrectCellClassError);
    cell.backgroundColor = self.backgroundColor;
    for (UIView *subview in cell.suggestionStack.arrangedSubviews) {
      if (![subview isKindOfClass:[UILabel class]]) {
        continue;
      }
      UILabel *label = (UILabel *)subview;
      label.textColor = self.textColor;
    }
  }
  for (NSInteger i = 0; i < [self numberOfSectionsInTableView:tableView]; i++) {
    GSCXScannerIssueExpandableTableViewHeader *header =
        (GSCXScannerIssueExpandableTableViewHeader *)[tableView headerViewForSection:i];
    if (header == nil) {
      // There is no way to access only the visible headers. nil represents a non-visible header,
      // so it is skipped.
      continue;
    }
    GTX_ASSERT([header isKindOfClass:[GSCXScannerIssueExpandableTableViewHeader class]],
               kGSCXScannerIssueExpandableTableViewDelegateIncorrectHeaderClassError);
    header.textLabel.textColor = self.textColor;
    [header.expandIcon setTintColor:self.textColor];
  }
}

#pragma mark - UITableViewDataSource

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  GSCXScannerIssueExpandableTableViewCell *cell = [tableView
      dequeueReusableCellWithIdentifier:kGSCXScannerIssueExpandableTableViewCellReuseIdentifier];
  GTX_ASSERT([cell isKindOfClass:[GSCXScannerIssueExpandableTableViewCell class]],
             kGSCXScannerIssueExpandableTableViewDelegateIncorrectCellClassError);
  if (![cell isKindOfClass:[GSCXScannerIssueExpandableTableViewCell class]]) {
    NSLog(kGSCXScannerIssueExpandableTableViewDelegateIncorrectCellClassError);
    return nil;
  }
  cell.accessibilityIdentifier = [GSCXScannerIssueExpandableTableViewDelegate
      gscx_accessibilityIdentifierForRowAtIndexPath:indexPath];
  cell.backgroundColor = self.backgroundColor;
  GSCXScannerIssueTableViewRow *row = self.sections[indexPath.section].rows[indexPath.row];
  [self gscx_addSuggestionsToCell:cell fromRow:row];
  [cell setNeedsUpdateConstraints];
  return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
  return kGSCXMinimumTouchTargetSize;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
  return (NSInteger)[self.sections count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  return self.sections[section].expanded ? [self.sections[section] numberOfRows] : 0;
}

#pragma mark - UITableViewDelegate

- (nullable UITableViewHeaderFooterView *)tableView:(UITableView *)tableView
                             viewForHeaderInSection:(NSInteger)section {
  GSCXScannerIssueExpandableTableViewHeader *header =
      [tableView dequeueReusableHeaderFooterViewWithIdentifier:
                     kGSCXScannerIssueExpandableTableViewHeaderReuseIdentifier];
  GTX_ASSERT([header isKindOfClass:[GSCXScannerIssueExpandableTableViewHeader class]],
             kGSCXScannerIssueExpandableTableViewDelegateIncorrectHeaderClassError);
  if (![header isKindOfClass:[GSCXScannerIssueExpandableTableViewHeader class]]) {
    NSLog(kGSCXScannerIssueExpandableTableViewDelegateIncorrectHeaderClassError);
    return nil;
  }
  header.accessibilityIdentifier = [GSCXScannerIssueExpandableTableViewDelegate
      gscx_accessibilityIdentifierForHeaderInSection:section];
  [self gscx_setTextOfHeader:header forSection:self.sections[section]];
  [self gscx_setExpandFlagsOfHeader:header
                         forSection:self.sections[section]
                            atIndex:section
                          tableView:tableView];
  [header setNeedsUpdateConstraints];
  return header;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  GSCXScannerIssueTableViewRow *row = self.sections[indexPath.section].rows[indexPath.row];
  self.selectionBlock(row.originalResult, row.originalElementIndex);
}

- (void)tableView:(UITableView *)tableView
    willDisplayHeaderView:(UIView *)view
               forSection:(NSInteger)section {
  GTX_ASSERT([view isKindOfClass:[GSCXScannerIssueExpandableTableViewHeader class]],
             kGSCXScannerIssueExpandableTableViewDelegateIncorrectHeaderClassError);
  GSCXScannerIssueExpandableTableViewHeader *header =
      (GSCXScannerIssueExpandableTableViewHeader *)view;
  header.textLabel.textColor = self.textColor;
  [header.expandIcon setTintColor:self.textColor];
}

#pragma mark - Private

/**
 * Adds a label to @c cell.suggestionStack with @c text if @c text is not nil.
 *
 * @param text The text to add to @c cell, if it exists.
 * @param cell The cell to add the text to.
 */
- (void)gscx_addLabelWithTextIfNonnull:(nullable NSString *)text
                                toCell:(GSCXScannerIssueExpandableTableViewCell *)cell {
  if (text == nil) {
    return;
  }
  UILabel *label = [[UILabel alloc] init];
  label.text = text;
  label.numberOfLines = 0;
  label.font = [UIFont preferredFontForTextStyle:UIFontTextStyleSubheadline];
  label.textColor = self.textColor;
  [cell.suggestionStack addArrangedSubview:label];
}

/**
 * Adds text describing each suggestion in @c row to @c cell. Removes previous suggestions, if any.
 *
 * @param cell The cell to add labels to.
 * @param row The row representing @c cell.
 */
- (void)gscx_addSuggestionsToCell:(GSCXScannerIssueExpandableTableViewCell *)cell
                          fromRow:(GSCXScannerIssueTableViewRow *)row {
  for (UIView *subview in cell.suggestionStack.subviews) {
    [subview removeFromSuperview];
  }
  [self gscx_addLabelWithTextIfNonnull:row.rowTitle toCell:cell];
  [self gscx_addLabelWithTextIfNonnull:row.rowSubtitle toCell:cell];
  for (NSUInteger i = 0; i < [row.suggestionTitles count]; i++) {
    [self gscx_addLabelWithTextIfNonnull:row.suggestionTitles[i] toCell:cell];
    [self gscx_addLabelWithTextIfNonnull:row.suggestionContents[i] toCell:cell];
  }
}

/**
 * Sets the text and accessibility properties of @c header for the data in @c section.
 *
 * @param header The header to set the text of.
 * @param section The section representing @c header.
 */
- (void)gscx_setTextOfHeader:(GSCXScannerIssueExpandableTableViewHeader *)header
                  forSection:(GSCXScannerIssueTableViewSection *)section {
  header.textLabel.text =
      [NSString stringWithFormat:@"%@ (%ld)", section.title, (long)[section numberOfSuggestions]];
  if (section.numberOfSuggestions == 0) {
    header.accessibilityLabel =
        [NSString stringWithFormat:@"%@ with no suggestions", section.title];
  } else if (section.numberOfSuggestions == 1) {
    header.accessibilityLabel = [NSString stringWithFormat:@"%@ with 1 suggestion", section.title];
  } else {
    header.accessibilityLabel =
        [NSString stringWithFormat:@"%@ with %ld suggestions", section.title,
                                   (long)[section numberOfSuggestions]];
  }
}

/**
 * Sets the properties relating to expansion on @c header.
 *
 * @param header The header to set the expansion properties of.
 * @param section The section representing @c header.
 * @param sectionIndex The index of @c section.
 * @param tableView The table view displaying the header.
 */
- (void)gscx_setExpandFlagsOfHeader:(GSCXScannerIssueExpandableTableViewHeader *)header
                         forSection:(GSCXScannerIssueTableViewSection *)section
                            atIndex:(NSInteger)sectionIndex
                          tableView:(UITableView *)tableView {
  header.expanded = section.expanded;
  header.expandable = section.numberOfSuggestions == 0 ? NO : YES;
  __weak __typeof__(self) weakSelf = self;
  __weak __typeof__(tableView) weakTableView = tableView;
  header.expandHeaderToggled = ^(BOOL isExpanded) {
    __typeof__(self) strongSelf = weakSelf;
    __typeof__(tableView) strongTableView = weakTableView;
    if (strongSelf == nil || strongTableView == nil) {
      return;
    }
    strongSelf.sections[sectionIndex].expanded = isExpanded;
    UITableViewRowAnimation animation = UIAccessibilityIsReduceMotionEnabled()
                                            ? UITableViewRowAnimationNone
                                            : UITableViewRowAnimationFade;
    [strongTableView reloadSections:[NSIndexSet indexSetWithIndex:sectionIndex]
                   withRowAnimation:animation];
  };
}

/**
 * Returns the accessibility identifier for the header view in the given section.
 *
 * @param section The index of the section of the header to get the accessibility identifier of.
 * @return The accessibility identifier for the header view in @c section.
 */
+ (NSString *)gscx_accessibilityIdentifierForHeaderInSection:(NSInteger)section {
  return [NSString
      stringWithFormat:@"GSCXScannerIssueExpandableTableViewDelegate_Header_%ld", (long)section];
}

/**
 * Returns the accessibility identifier for the row at the given index path.
 *
 * @param indexPath The index path of the row.
 * @return The accessibility identifier for the row at @c indexPath.
 */
+ (NSString *)gscx_accessibilityIdentifierForRowAtIndexPath:(NSIndexPath *)indexPath {
  return [NSString stringWithFormat:@"GSCXScannerIssueExpandableTableViewDelegate_Row_%ld_%ld",
                                    (long)indexPath.section, (long)indexPath.row];
}

@end

NS_ASSUME_NONNULL_END


text:
<?php

namespace SonarSoftware\CustomerPortalFramework\Controllers;

use Exception;
use InvalidArgumentException;
use SonarSoftware\CustomerPortalFramework\Helpers\HttpHelper;
use SonarSoftware\CustomerPortalFramework\Models\Ticket;

class AccountTicketController
{
    private $httpHelper;
    /**
     * AccountAuthenticationController constructor.
     */
    public function __construct()
    {
        $this->httpHelper = new HttpHelper();
    }

    /*
     * GET functions
     */
    /**
     * Get all the public tickets for an account (see https://sonar.software/apidoc/index.html#api-Tickets-GetEntityTickets)
     * @param $accountID
     * @param int $page
     * @return mixed
     * @throws \SonarSoftware\CustomerPortalFramework\Exceptions\ApiException
     */
    public function getTickets($accountID, $page = 1)
    {
        $result = $this->httpHelper->get("/accounts/" . intval($accountID) . "/tickets", $page);
        $tickets = [];
        foreach ($result as $datum)
        {
            if ($datum->type !== "public")
            {
                continue;
            }
            $ticket = new Ticket([
                'subject' => $datum->subject,
                'ticket_group_id' => $datum->ticket_group_id,
                'user_id' => $datum->user_id,
                'account_id' => $datum->assignee_id,
                'priority' => $datum->priority,
                'open' => $datum->open,
                'inbound_email_account_id' => $datum->inbound_email_account_id,
                'email_address' => $datum->email_address,
                'ticket_id' => $datum->id,
                'last_reply_incoming' => $datum->last_reply_incoming,
            ]);
            array_push($tickets, $ticket);
        }

        return $tickets;
    }

    /**
     * Get all the replies on a ticket (see https://sonar.software/apidoc/index.html#api-Tickets-GetTicketReplies)
     * @param Ticket $ticket
     * @param int $page
     * @return mixed
     * @throws \SonarSoftware\CustomerPortalFramework\Exceptions\ApiException
     */
    public function getReplies(Ticket $ticket, $page = 1)
    {
        return $this->httpHelper->get("/tickets/" . intval($ticket->getTicketID()) . "/ticket_replies", $page);
    }

    /*
     * POST functions
     */

    /**
     * Create a new ticket. The first input from the customer will be posted as an incoming reply.
     * @param Ticket $ticket
     * @param $author
     * @param $authorEmail
     * @return mixed
     * @throws \SonarSoftware\CustomerPortalFramework\Exceptions\ApiException
     */
    public function createTicket(Ticket $ticket, $author, $authorEmail)
    {
        if (filter_var($authorEmail, FILTER_VALIDATE_EMAIL) === false)
        {
            throw new InvalidArgumentException($authorEmail . " is not a valid email address.");
        }

        $result = $this->httpHelper->post("/tickets", [
            'subject' => $ticket->getSubject(),
            'type' => 'public',
            'inbound_email_account_id' => $ticket->getInboundEmailAccountID(),
            'ticket_group_id' => $ticket->getTicketGroupID(),
            'user_id' => $ticket->getUserID(),
            'assignee' => 'accounts',
            'assignee_id' => $ticket->getAccountID(),
            'email_address' => $ticket->getEmailAddress(),
            'priority' => $ticket->getPriority(),
            'comment' => "Created via the customer portal framework.",
        ]);

        $this->httpHelper->post("/tickets/" . $result->id . "/ticket_replies", [
            'text' => $ticket->getDescription(),
            'incoming' => true,
            'author' => $author,
            'author_email' => $authorEmail,
        ]);

        return $result;
    }

    /**
     * Post a reply to an existing ticket
     * @param Ticket $ticket
     * @param $replyText
     * @param $author
     * @param $authorEmail
     * @return mixed
     * @throws \SonarSoftware\CustomerPortalFramework\Exceptions\ApiException
     */
    public function postReply(Ticket $ticket, $replyText, $author, $authorEmail)
    {
        if (filter_var($authorEmail, FILTER_VALIDATE_EMAIL) === false)
        {
            throw new InvalidArgumentException($authorEmail . " is not a valid email address.");
        }

        try {
            $this->httpHelper->patch("/tickets/{$ticket->getTicketID()}",[
                'open' => true,
            ]);
        }
        catch (Exception $e)
        {
            //
        }

        return $this->httpHelper->post("/tickets/{$ticket->getTicketID()}/ticket_replies",[
            'text' => $replyText,
            'incoming' => true,
            'author' => $author,
            'author_email' => $authorEmail,
        ]);
    }
}


text:
<?php

namespace Caffeinated\Beverage\Contracts;

/**
 * This is the Validator.
 *
 * @package        Caffeinated\Beverage
 * @author         Caffeinated Dev Team
 * @copyright      Copyright (c) 2015, Caffeinated
 * @license        https://tldrlegal.com/license/mit-license MIT License
 */
interface Validator
{

}


text:
define('mp-01-web/tests/unit/controllers/create-vote-test', ['exports', 'ember-qunit'], function (exports, _emberQunit) {

  (0, _emberQunit.moduleFor)('controller:create-vote', 'Unit | Controller | create vote', {
    // Specify the other units that are required for this test.
    // needs: ['controller:foo']
  });

  // Replace this with your real tests.
  (0, _emberQunit.test)('it exists', function (assert) {
    var controller = this.subject();
    assert.ok(controller);
  });
});


text:
import assignToEmpty from './assign';

const request = (url, options = {}) => {
  Object.freeze(options);
  const defaults = {
    method: 'GET',
    mode: 'cors',
    headers: {
      'content-type': 'application/json;charset=UTF-8',
      'authorization': 'Bearer ' + window.token
    }
  };

  return fetch(url, assignToEmpty(defaults, options)).then(response => {
    if (response.status >= 300) {
      return new Promise((resolve, reject) => response.json().then(reject));
    }

    if (response.status === 204) {
      return new Promise((resolve) => resolve());
    }

    return new Promise((resolve) => resolve(response.json()));
  });
};

export default request;


text:
Counter-Strike: Global Offensive Configs
=======================================

Files usually found at

`..\Steam\SteamApps\common\Counter-Strike Global Offensive\csgo\cfg\`


text:
package pl.java.scalatech.collection;

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

import org.junit.Test;

import com.google.common.collect.HashMultiset;
import com.google.common.collect.Multiset;

import lombok.extern.slf4j.Slf4j;
import pl.java.scalatech.common.DataPrepareTest;

@Slf4j
public class OrDefaultTest extends DataPrepareTest {
    @Test
    public void shouldMapCountOldApproach() {
        Map<String, Long> map = new HashMap<>();
        for (String s : names) {
            Long count = map.get(s);
            map.put(s, count == null ? 1L : count + 1);
        }
        log.info("{}", map);
    }

    @Test
    public void shouldDefaultOrNull() {
        Map<String, Long> map = new HashMap<>();
        for (String s : names) {
            map.put(s, 1 + map.getOrDefault(s, 0L));
        }
        log.info("{}", map);
    }

    @Test
    public void shouldGuavaMultiMapWork() {
        Multiset<String> wordsMultiset = HashMultiset.create();
        wordsMultiset.addAll(names);
        log.info("{}", wordsMultiset);
    }
}


text:
package com.artificial.cachereader.fs;

import com.artificial.cachereader.GameType;
import com.artificial.cachereader.wrappers.rt4.loaders.ItemDefinitionLoader;
import com.artificial.cachereader.wrappers.rt4.loaders.NpcDefinitionLoader;
import com.artificial.cachereader.wrappers.rt4.loaders.ObjectDefinitionLoader;
import com.artificial.cachereader.wrappers.rt4.loaders.ScriptLoader;
import com.artificial.cachereader.wrappers.rt4.loaders.WidgetLoader;

public class RT4CacheSystem extends CacheSystem<RT4CacheSystem> {
    public final ItemDefinitionLoader itemLoader;
    public final ObjectDefinitionLoader objectLoader;
    public final NpcDefinitionLoader npcLoader;
    public final ScriptLoader scriptLoader;
    public final WidgetLoader widgetLoader;

    public RT4CacheSystem() {
        super(GameType.RT4);
        addLoader(scriptLoader = new ScriptLoader(this));
        addLoader(itemLoader = new ItemDefinitionLoader(this));
        addLoader(objectLoader = new ObjectDefinitionLoader(this));
        addLoader(npcLoader = new NpcDefinitionLoader(this));
        addLoader(widgetLoader = new WidgetLoader(this));
    }
}


text:
from heat.common import exception
from heat.common.i18n import _
from heat.engine import attributes
from heat.engine import properties
from heat.engine import resource
from heat.engine import support

class Host(resource.Resource):
    """A resource to manage Blazar hosts.

    Host resource manages the physical hosts for the lease/reservation
    within OpenStack.

    # TODO(asmita): Based on an agreement with Blazar team, this resource
    class does not support updating host resource as currently Blazar does
    not support to delete existing extra_capability keys while updating host.
    Also, in near future, when Blazar team will come up with a new alternative
    API to resolve this issue, we will need to modify this class.
    """

    support_status = support.SupportStatus(version='12.0.0')

    PROPERTIES = (
        NAME, EXTRA_CAPABILITY,
    ) = (
        'name', 'extra_capability',
    )

    ATTRIBUTES = (
        HYPERVISOR_HOSTNAME, HYPERVISOR_TYPE, HYPERVISOR_VERSION,
        VCPUS, CPU_INFO, MEMORY_MB, LOCAL_GB,
        SERVICE_NAME, RESERVABLE, STATUS, TRUST_ID,
        EXTRA_CAPABILITY_ATTR, CREATED_AT, UPDATED_AT,
    ) = (
        'hypervisor_hostname', 'hypervisor_type', 'hypervisor_version',
        'vcpus', 'cpu_info', 'memory_mb', 'local_gb',
        'service_name', 'reservable', 'status', 'trust_id',
        'extra_capability', 'created_at', 'updated_at',
    )

    properties_schema = {
        NAME: properties.Schema(
            properties.Schema.STRING,
            _('The name of the host.'),
            required=True,
        ),
        EXTRA_CAPABILITY: properties.Schema(
            properties.Schema.MAP,
            _('The extra capability of the host.'),
        )
    }

    attributes_schema = {
        HYPERVISOR_HOSTNAME: attributes.Schema(
            _('The hypervisor name of the host.'),
            type=attributes.Schema.STRING,
        ),
        HYPERVISOR_TYPE: attributes.Schema(
            _('The hypervisor type the host.'),
            type=attributes.Schema.STRING,
        ),
        HYPERVISOR_VERSION: attributes.Schema(
            _('The hypervisor version of the host.'),
            type=attributes.Schema.INTEGER,
        ),
        VCPUS: attributes.Schema(
            _('The number of the VCPUs of the host.'),
            type=attributes.Schema.INTEGER,
        ),
        CPU_INFO: attributes.Schema(
            _('Information of the CPU of the host.'),
            type=attributes.Schema.MAP,
        ),
        MEMORY_MB: attributes.Schema(
            _('Megabytes of the memory of the host.'),
            type=attributes.Schema.INTEGER,
        ),
        LOCAL_GB: attributes.Schema(
            _('Gigabytes of the disk of the host.'),
            type=attributes.Schema.INTEGER,
        ),
        SERVICE_NAME: attributes.Schema(
            _('The compute service name of the host.'),
            type=attributes.Schema.STRING,
        ),
        RESERVABLE: attributes.Schema(
            _('The flag which represents whether the host is reservable '
              'or not.'),
            type=attributes.Schema.BOOLEAN,
        ),
        STATUS: attributes.Schema(
            _('The status of the host.'),
            type=attributes.Schema.STRING,
        ),
        TRUST_ID: attributes.Schema(
            _('The UUID of the trust of the host operator.'),
            type=attributes.Schema.STRING,
        ),
        EXTRA_CAPABILITY_ATTR: attributes.Schema(
            _('The extra capability of the host.'),
            type=attributes.Schema.MAP,
        ),
        CREATED_AT: attributes.Schema(
            _('The date and time when the host was created. '
              'The date and time format must be "CCYY-MM-DD hh:mm".'),
            type=attributes.Schema.STRING,
        ),
        UPDATED_AT: attributes.Schema(
            _('The date and time when the host was updated. '
              'The date and time format must be "CCYY-MM-DD hh:mm".'),
            type=attributes.Schema.STRING
        ),
    }

    default_client_name = 'blazar'

    entity = 'host'

    def _parse_extra_capability(self, args):
        if self.NAME in args[self.EXTRA_CAPABILITY]:
            # Remove "name" key if present in the extra_capability property.
            del args[self.EXTRA_CAPABILITY][self.NAME]
        args.update(args[self.EXTRA_CAPABILITY])
        args.pop(self.EXTRA_CAPABILITY)
        return args

    def handle_create(self):
        args = dict((k, v) for k, v in self.properties.items()
                    if v is not None)

        if self.EXTRA_CAPABILITY in args:
            args = self._parse_extra_capability(args)

        host = self.client_plugin().create_host(**args)
        self.resource_id_set(host['id'])

        return host['id']

    def _resolve_attribute(self, name):
        if self.resource_id is None:
            return
        host = self.client_plugin().get_host(self.resource_id)
        try:
            return host[name]
        except KeyError:
            raise exception.InvalidTemplateAttribute(resource=self.name,
                                                     key=name)

def resource_mapping():
    return {
        'OS::Blazar::Host': Host
    }


text:
namespace TABS_UserControls.usercontrols {

    public partial class send_idea {

        /// <summary>
        /// lblSchoolName control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label lblSchoolName;

        /// <summary>
        /// lblFullName control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label lblFullName;

        /// <summary>
        /// lblJob control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label lblJob;

        /// <summary>
        /// lblEmail control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label lblEmail;

        /// <summary>
        /// txtComment control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.TextBox txtComment;

        /// <summary>
        /// btnSubmit control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Button btnSubmit;
    }
}


text:
<!doctype html>
<html ng-app="UHNPopup">
<head>
	<title>Uselessly HN</title>
	<link rel="stylesheet" href="css/main.css">
	<link rel="stylesheet" href="lib/semantic.min.css">
	<script src="js/popup.js"></script>
	<script src="lib/jquery-2.1.1.min.js"></script>
	<script src="lib/angular.min.js"></script>
	<script src="lib/semantic.min.js"></script>
</head>
<body>

</body>
</html>


text:
package uk.gov.dvsa.motr.web.validator;

import java.time.LocalDate;

public class MotDueDateValidator {
    private LocalDate now;

    public MotDueDateValidator(LocalDate now) {

        this.now = now;
    }

    public boolean isDueDateValid(LocalDate motDueDate) {

        return (motDueDate != null) && (motDueDate.isAfter(now) || motDueDate.isEqual(now));
    }
}


text:
using Xunit;
using hihapi.Models;

namespace hihapi.unittest.Home
{
    [Collection("HIHAPI_UnitTests#1")]
    public class HomeDefineTest
    {
        private SqliteDatabaseFixture fixture = null;

        public HomeDefineTest(SqliteDatabaseFixture fixture)
        {
            this.fixture = fixture;
        }

        [Fact]
        public void TestCase_CheckValid()
        {
            var home = new HomeDefine();
            var context = this.fixture.GetCurrentDataContext();
            var isvalid = home.IsValid(context);

            Assert.False(isvalid);
        }
    }
}


text:
package edu.gemini.qpt.ui.view.variant;

import static edu.gemini.qpt.ui.util.SharedIcons.ADD;
import static edu.gemini.qpt.ui.util.SharedIcons.ADD_DISABLED;
import static edu.gemini.qpt.ui.util.SharedIcons.ARROW_DOWN;
import static edu.gemini.qpt.ui.util.SharedIcons.ARROW_DOWN_DISABLED;
import static edu.gemini.qpt.ui.util.SharedIcons.ARROW_UP;
import static edu.gemini.qpt.ui.util.SharedIcons.ARROW_UP_DISABLED;
import static edu.gemini.qpt.ui.util.SharedIcons.DUP_VARIANT;
import static edu.gemini.qpt.ui.util.SharedIcons.DUP_VARIANT_DIS;
import static edu.gemini.qpt.ui.util.SharedIcons.REMOVE;
import static edu.gemini.qpt.ui.util.SharedIcons.REMOVE_DISABLED;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.List;
import java.util.logging.Logger;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;

import edu.gemini.qpt.core.Schedule;
import edu.gemini.qpt.core.Variant;
import edu.gemini.qpt.ui.CommonActions;
import edu.gemini.qpt.ui.util.ScrollPanes;
import edu.gemini.qpt.ui.util.SimpleToolbar;
import edu.gemini.qpt.ui.util.SimpleToolbar.IconButton;
import edu.gemini.qpt.ui.util.SimpleToolbar.StaticText;
import edu.gemini.qpt.ui.view.variant.edit.DeleteAction;
import edu.gemini.qpt.ui.view.variant.edit.PasteAction;
import edu.gemini.ui.gface.GSelection;
import edu.gemini.ui.gface.GSelectionBroker;
import edu.gemini.ui.gface.GTableViewer;
import edu.gemini.ui.gface.GViewer;
import edu.gemini.ui.workspace.IShell;
import edu.gemini.ui.workspace.IViewAdvisor;
import edu.gemini.ui.workspace.IViewContext;
import edu.gemini.ui.workspace.util.Factory;

public class VariantViewAdvisor implements IViewAdvisor, PropertyChangeListener, ActionListener {

	private static final Logger LOGGER = Logger.getLogger(VariantViewAdvisor.class.getName());

	private IViewContext context;

	// This viewer is the main thing here.
	private GTableViewer<Schedule, Variant, VariantAttribute> viewer  =
		new GTableViewer<Schedule, Variant, VariantAttribute>(new VariantController());

	// UI Stuff
	private final JScrollPane scroll = Factory.createStrippedScrollPane(viewer.getTable());
	private final JButton add = new IconButton(ADD, ADD_DISABLED);
	private final JButton del = new IconButton(REMOVE, REMOVE_DISABLED);
	private final JButton dup = new IconButton(DUP_VARIANT, DUP_VARIANT_DIS);
	private final JButton up = new IconButton(ARROW_UP, ARROW_UP_DISABLED);
	private final JButton down = new IconButton(ARROW_DOWN, ARROW_DOWN_DISABLED);
	private final JLabel text = new StaticText("Double-click a variant to edit it.");
	private final JPanel toolbar = new SimpleToolbar();
	private final JPanel content = new JPanel(new BorderLayout());

	// All buttons in one place
	private final JButton[] buttons = { add, del, dup, up, down };

	public VariantViewAdvisor() {

		// Set up the viewer.
		viewer.setColumns(VariantAttribute.Name, VariantAttribute.IQ, VariantAttribute.CC, VariantAttribute.WV, VariantAttribute.Wind, VariantAttribute.LGS);
		viewer.addPropertyChangeListener(GViewer.PROP_SELECTION, this);
		viewer.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		viewer.setColumnSize(VariantAttribute.IQ, 25);
		viewer.setColumnSize(VariantAttribute.CC, 25);
		viewer.setColumnSize(VariantAttribute.WV, 25);
        viewer.setColumnSize(VariantAttribute.Wind, 60);
        viewer.setColumnSize(VariantAttribute.LGS, 25);
		viewer.getTable().addMouseListener(doubleClickToEditListener);
		viewer.setDecorator(new VariantDecorator());

		// Set the viewport size for the scrollpane
		ScrollPanes.setViewportHeight(scroll, 11);

		// Set up the toolbar.
		for (JButton b: buttons) {
			b.setEnabled(false);
			b.addActionListener(this);
			toolbar.add(b);
		}
		toolbar.add(text);

		// Put it all together.
		content.add(scroll, BorderLayout.CENTER);
		content.add(toolbar, BorderLayout.SOUTH);

	}

	@SuppressWarnings("serial")
	public void open(IViewContext viewContext) {

		context = viewContext;
		context.setTitle("Plan Variants");
		context.setContent(content);
		context.getShell().addPropertyChangeListener(IShell.PROP_MODEL, this);

		context.addRetargetAction(CommonActions.PASTE, new PasteAction(context.getShell(), viewer, true));
		context.addRetargetAction(CommonActions.DELETE, new DeleteAction(context.getShell(), viewer));

	}

	public void close(IViewContext context) {
		viewer.setModel(null);
	}

	public void setFocus() {
		viewer.getTable().requestFocus();
	}

	@SuppressWarnings("unchecked")
	public void propertyChange(PropertyChangeEvent pce) {

		if (pce.getPropertyName().equals(IShell.PROP_MODEL)) {

			// Set the new model
			Schedule schedule = (Schedule) pce.getNewValue();
			viewer.setModel(schedule);

			// Disable buttons if model is null. Add is enabled if schedule is non-null.
			if (schedule == null) {
				for (JButton b: buttons)
					b.setEnabled(false);
			} else {
				add.setEnabled(true);
			}

			// This is an odd case where the selection is actually relevant to
			// the model, so we need to push an initial selection down into
			// the view.
			if (schedule != null) {
				Variant v = schedule.getCurrentVariant();
				if (v != null) {
					viewer.setSelection(new GSelection<Variant>(v));
				}
			}

		}

		if (pce.getPropertyName().equals(GSelectionBroker.PROP_SELECTION)) {

			if (pce.getSource() == viewer) {

				// User clicked on something (somewhere)
				GSelection<Variant> sel = viewer.getSelection();
				Schedule schedule = viewer.getModel();

				// Set the current variant and assert it as our selection.
				if (schedule != null) {
					schedule.setCurrentVariant(sel.isEmpty() ? null : sel.first());
					LOGGER.fine("Asserting new selection: " + sel);
					context.getShell().setSelection(sel);
				}

				// Set button enablement (except for add, which is enabled based on the schedul
				// being null or not -- see the PROP_MODEL handler above).
				if (sel.isEmpty()) {

					// All disabled.
					up.setEnabled(false);
					down.setEnabled(false);
					dup.setEnabled(false);
					del.setEnabled(false);

				} else {

					// Dup and del are enabled.
					dup.setEnabled(true);
					del.setEnabled(true);

					// Up and down depend on the selection AND the position in the list,
					// so we need to call this method both here AND when the reorder methods
					// are called (since they change the position but not the selection).
					setUpDownEnabledState(sel);

				}

			}

		}

	}

	private void setUpDownEnabledState(GSelection<Variant> sel) {

		// Should never be empty
		assert !sel.isEmpty();

		// Up and down depend on whether we have selected the first or last variant.
		// Remember that the viewer is not sorting or filtering any of the variants; we
		// are viewing the full model list in the model-specified order. So we can just
		// look at the model to figure this out.
		Schedule schedule = viewer.getModel();
		Variant v = sel.first();
		List<Variant> all = schedule.getVariants();
		up.setEnabled(v != all.get(0));
		down.setEnabled(v != all.get(all.size() - 1));

	}

	public void actionPerformed(ActionEvent e) {

		// Collect some info to get started.
		Object source = e.getSource();
		GSelection<Variant> sel = viewer.getSelection();
		Variant v = sel.isEmpty() ? null : sel.first();
		Schedule schedule = viewer.getModel();

		// Force a repaint of the action if it's a button. This is an AWT bug.
		if (source instanceof JButton)
			((JButton) source).repaint();

		if (source == add) {

			// Add a new variant. Selection will not change but position might.
			VariantEditor ve = new VariantEditor(context.getShell().getPeer());
			if (JOptionPane.CANCEL_OPTION != ve.showNew("Untitled", (byte) 0, (byte) 0, (byte) 0))
				schedule.addVariant(ve.getVariantName(), ve.getVariantConditions(), ve.getVariantWindConstraint(), ve.getVariantLgsConstraint());
			setUpDownEnabledState(sel);

		} else if (source == del) {

			// Delete the selected variant. Selection will change.
			if (JOptionPane.NO_OPTION == JOptionPane.showConfirmDialog(context.getShell().getPeer(),
						"Do you really want to remove this variant?",
						"Confirm Remove", JOptionPane.YES_NO_OPTION))
					return;

			schedule.removeVariant(v);

		} else if (source == up) {

			// Move up. Selection will not change but position will.
			schedule.moveVariant(v, -1);
			setUpDownEnabledState(sel);

		} else if (source == down) {

			// Move down. Selection will not change but position will.
			schedule.moveVariant(v, 1);
			setUpDownEnabledState(sel);

		} else if (source == dup) {

			// Duplicate. Selection will not change but position might.
			Variant dup = schedule.duplicateVariant(v);
			dup.setName("Copy of " + dup.getName());
			setUpDownEnabledState(sel);

		}

	}

	private final MouseListener doubleClickToEditListener = new MouseAdapter() {
		@Override
		public void mouseClicked(MouseEvent e) {
			if (e.getClickCount() == 2) {
				GSelection<Variant> sel = viewer.getSelection();
				if (sel.size() == 1) {
					VariantEditor ve = new VariantEditor(context.getShell().getPeer());
					Variant v = sel.first();
					if (JOptionPane.CANCEL_OPTION != ve.showEditor(v)) {
						v.setName(ve.getVariantName());
						v.setConditions(ve.getVariantConditions());
						v.setWindConstraint(ve.getVariantWindConstraint());
                        v.setLgsConstraint(ve.getVariantLgsConstraint());
					}
				}
			}
		}
	};

}


text:
efform_onload = function () {

}

button_f2_onclick = function() {
 var limit = document.getElementById( "inqu_status-0-size" );
 var grid = efform.getGrid( "ef_grid_p" );
 grid.setOffset(0);
 grid.setLimit ( eval(limit.options[limit.selectedIndex].value) );

 var from = document.getElementById( "inqu_status-0-from" );
 from.value = 0;

 efpage.submitMetadata( grid );
}

button_f3_onclick = function() {
  efpage.goNext("ef_grid_p");
}