text:
<?php
require "../news/NewsDB.class.php";
class NewsService extends NewsDB{
	/* Метод возвращает новость по её идентификатору */
	function getNewsById($id){
		try{
			$sql = "SELECT id, title,
					(SELECT name FROM category WHERE category.id=msgs.category) as category, description, source, datetime
					FROM msgs
					WHERE id = $id";
			$result = $this->db->query($sql);
			if (!is_object($result))
				throw new Exception($this->_db->lastErrorMsg());
			return base64_encode(serialize($this->db2Arr($result)));
		}catch(Exception $e){
			throw new SoapFault('getNewsById', $e->getMessage());
		}
	}
	/* Метод считает количество всех новостей */
	function getNewsCount(){
		try{
			$sql = "SELECT count(*) FROM msgs";
			$result = $this->db->querySingle($sql);
			if (!$result)
				throw new Exception($this->_db->lastErrorMsg());
			return $result;
		}catch(Exception $e){
			throw new SoapFault('getNewsCount', $e->getMessage());
		}
	}
	/* Метод считает количество новостей в указанной категории */
	function getNewsCountByCat($cat_id){
		try{
			$sql = "SELECT count(*) FROM msgs WHERE category=$cat_id";
			$result = $this->db->querySingle($sql);
			if (!$result)
				throw new Exception($this->_db->lastErrorMsg());
			return $result;
		}catch(Exception $e){
			throw new SoapFault('getNewsCountByCat', $e->getMessage());
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
package edu.csun.ecs.cs.multitouchj.ui.test;

import java.awt.Color;
import java.io.File;
import java.net.URL;
import java.util.Date;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.lwjgl.input.Keyboard;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;

import edu.csun.ecs.cs.multitouchj.objectobserver.ObjectObserver;
import edu.csun.ecs.cs.multitouchj.objectobserver.motej.ObjectObserverMoteJ;
import edu.csun.ecs.cs.multitouchj.objectobserver.mouse.ObjectObserverMouse;
import edu.csun.ecs.cs.multitouchj.ui.control.FramedControl;
import edu.csun.ecs.cs.multitouchj.ui.control.TexturedControl;
import edu.csun.ecs.cs.multitouchj.ui.control.TouchableControl;
import edu.csun.ecs.cs.multitouchj.ui.event.WindowManagerCalibratorEvent;
import edu.csun.ecs.cs.multitouchj.ui.event.WindowManagerCalibratorListener;
import edu.csun.ecs.cs.multitouchj.ui.geometry.Point;
import edu.csun.ecs.cs.multitouchj.ui.geometry.Size;
import edu.csun.ecs.cs.multitouchj.ui.graphic.CursorCollectionDefault;
import edu.csun.ecs.cs.multitouchj.ui.graphic.DisplayManager;
import edu.csun.ecs.cs.multitouchj.ui.graphic.WindowManager;
import edu.csun.ecs.cs.multitouchj.ui.graphic.image.Texture;
import edu.csun.ecs.cs.multitouchj.utility.FrameMeter;

/**
 * @author Atsuya Takagi
 *
 * $Id: PhotoTest.java 80 2009-03-15 07:21:37Z Atsuya Takagi $
 */
public class PhotoTest implements WindowManagerCalibratorListener {
    private static final String IMAGE_DIRECTORY = "../Resources/PhotoTest";
    private static final long ANIMATION_TIME = 1000;
    private static Log log = LogFactory.getLog(PhotoTest.class);
    private boolean isRunning;
    private boolean isCalibrated;
    private boolean calibrationRequested;
    private DisplayMode displayMode;
    private LinkedList<TouchableControl> touchableControls;
    private Hashtable<TouchableControl, Point> desiredPositions;
    private Hashtable<TouchableControl, Float> desiredAngles;
    private Hashtable<TouchableControl, Size> desiredSizes;
    private long animationTimeStarted;
    private boolean animationStart;
    private String imageDirectory;

    public PhotoTest() {
        touchableControls = new LinkedList<TouchableControl>();
        desiredPositions = new Hashtable<TouchableControl, Point>();
        desiredAngles = new Hashtable<TouchableControl, Float>();
        desiredSizes = new Hashtable<TouchableControl, Size>();
    }

    /* (non-Javadoc)
     * @see edu.csun.ecs.cs.multitouchj.ui.event.WindowManagerCalibratorListener#calibrated(edu.csun.ecs.cs.multitouchj.ui.event.WindowManagerCalibratorEvent)
     */
    public void calibrated(WindowManagerCalibratorEvent event) {
        isCalibrated = true;
    }

    public void run(Map<String, String> parameters) {
        DisplayManager.create();
        DisplayManager displayManager = DisplayManager.getInstance();
        ObjectObserver objectObserver = new ObjectObserverMoteJ();
        WindowManager windowManager = null;

        try {
            for(DisplayMode mode : displayManager.getAvailableDisplayModes()) {
                log.info(mode.getWidth()+"x"+mode.getHeight()+":"+mode.getBitsPerPixel());
            }
            displayMode = displayManager.getDisplayMode(800, 600, 32);
            displayManager.createDisplay(displayMode);
            Keyboard.create();

            objectObserver.initialize(parameters);

            WindowManager.create(displayManager, objectObserver);
            windowManager = WindowManager.getInstance();
            windowManager.getWindowManagerCalibrator().addWindowManagerCalibratorListener(this);

            /*
            panel.setColor(Color.WHITE);
            panel.setPosition(new Point(200.0f, 100.0f));
            panel.setSize(new Size(400.0f, 200.0f));
            //panel.setTexture(new URL("file:///Users/axt/Documents/Development/Eclipse/MultiTouchJ/Resources/Machine.png"));
            panel.setTexture(new URL("file:///Users/atsuya/Documents/Development/Eclipse/MultiTouchJ/Resources/Syougi.jpg"));
            panel.setSize(new Size(400.0f, 200.0f));
            panel.setOpacity(0.8f);
            panel.setRotation(-370.0f);
            */

            FrameMeter frameMeter = new FrameMeter();
            calibrationRequested = true;
            isCalibrated = false;
            isRunning = true;
            animationStart = false;
            while(isRunning) {
                if(Display.isCloseRequested()) {
                    break;
                }

                while(Keyboard.next()) {
                    switch(Keyboard.getEventKey()) {
                        case Keyboard.KEY_F:
                            if(Keyboard.getEventKeyState()) {
                                displayManager.setFullScreen(!displayManager.isFullScreen());
                            }
                            break;
                        case Keyboard.KEY_ESCAPE:
                            isRunning = false;
                            break;
                        case Keyboard.KEY_C:
                            calibrationRequested = true;
                            break;
                        case Keyboard.KEY_I:
                            //resetPhotos();
                            initiateAnimation();
                            break;
                    }
                }

                if(calibrationRequested) {
                    windowManager.calibrate();
                    calibrationRequested = false;
                    isCalibrated = false;
                } else if(isCalibrated) {
                    windowManager.setCursorCollection(new CursorCollectionDefault());

                    log.info("Loading images...");
                    loadImages();
                    isCalibrated = false;

                    initiateAnimation();
                }

                if(animationStart) {
                    animateControls();
                }

                if(frameMeter.update()) {
                    displayManager.setWindowTitle(frameMeter.getFps()+" fps");
                }
                windowManager.update();
                Thread.sleep(30);
            }
        } catch(Exception exception) {
            exception.printStackTrace();
        } finally {
            try {
                if(windowManager != null) {
                    windowManager.destroy();
                }
                Keyboard.destroy();
                displayManager.destroy();
            } catch(Exception exception) {
                exception.printStackTrace();
            }
        }
    }

    private void loadImages() throws Exception {
        File imageDirectory = new File(IMAGE_DIRECTORY);
        for(File file : imageDirectory.listFiles()) {
            if(file.getName().endsWith(".jpg")) {
                TouchableControl panel = new TouchableControl();
                panel.setTexture(new URL("file://"+file.getAbsolutePath()));
                panel.setMargin(10.0f);
                touchableControls.add(panel);
            }
        }
    }

    private void animateControls() {
        long time = new Date().getTime();
        long timeElapsed = (time - animationTimeStarted);
        if(timeElapsed >= ANIMATION_TIME) {
            animationStart = false;
        } else {
            for(TouchableControl touchableControl : touchableControls) {
                float ratio = (timeElapsed / (float)ANIMATION_TIME);

                Point position = desiredPositions.get(touchableControl);
                Size size = desiredSizes.get(touchableControl);
                float angle = desiredAngles.get(touchableControl);
                touchableControl.setPosition(new Point((position.getX() * ratio), (position.getY() * ratio)));
                touchableControl.setSize(new Size((size.getWidth() * ratio), (size.getHeight() * ratio)));
                touchableControl.setRotation((angle * ratio));
            }
        }
    }

    private void initiateAnimation() {
        desiredPositions.clear();
        desiredAngles.clear();
        desiredSizes.clear();

        Random xRandom = new Random();
        Random yRandom = new Random();
        Random angleRandom = new Random();
        for(TouchableControl touchableControl : touchableControls) {
            float x = xRandom.nextInt(displayMode.getWidth() - 30);
            float y = yRandom.nextInt(displayMode.getHeight() - 30);
            Point position = new Point(x, y);

            Texture texture = touchableControl.getTexture();
            Size size = new Size((texture.getImage().getWidth() / 2.0f), (texture.getImage().getHeight() / 2.0f));

            float angle = (float)angleRandom.nextInt(360);

            desiredPositions.put(touchableControl, position);
            desiredAngles.put(touchableControl, angle);
            desiredSizes.put(touchableControl, size);
        }

        animationTimeStarted = new Date().getTime();
        animationStart = true;
    }

    public static void main(String[] args) {
        LinkedList<String> arguments = new LinkedList<String>();
        for(String argument : args) {
            arguments.add(argument);
        }

        TreeMap<String, String> parameters = new TreeMap<String, String>();
        if(arguments.contains("-ix")) {
            parameters.put(ObjectObserverMoteJ.Parameter.InverseX.toString(), "");
        }
        if(arguments.contains("-iy")) {
            parameters.put(ObjectObserverMoteJ.Parameter.InverseY.toString(), "");
        }

        PhotoTest photoTest = new PhotoTest();
        photoTest.run(parameters);
    }
}


text:
import { TestBed, async, inject } from '@angular/core/testing';
import { MockBackend } from '@angular/http/testing';
import { HttpModule, Http, Response, ResponseOptions, XHRBackend } from '@angular/http';

import { CourseService } from './course.service';
import { Course } from './course';

export const COURSES: Course[] = [
    { _id: '1', course_code: 'AAA1234', course_name: 'Test Course1', teacher_id: '1' },
    { _id: '2', course_code: 'BBB5678', course_name: 'Test Course2', teacher_id: '3' },
    { _id: '3', course_code: 'CCC0910', course_name: 'Test Course3', teacher_id: '2' },
];

export const STUDENTS = [
    { student_name: 'Test Student1' },
    { student_name: 'Test Student2' },
    { student_name: 'Test Student3' },
    { student_name: 'Test Student4' },
    { student_name: 'Test Student5' },
];

describe('CourseService', () => {
    beforeEach(() => {
        TestBed.configureTestingModule({
            imports: [HttpModule],
            providers: [
                CourseService,
                { provide: XHRBackend, useClass: MockBackend }
            ]
        });
    });

    it('should be created', inject([CourseService, XHRBackend], (service: CourseService, mockBackend) => {
        expect(service).toBeTruthy();
    }));

    describe('getCourse()', () => {
        it('should get course data', inject([CourseService, XHRBackend], (courseService, mockBackend) => {
            const mockResponse = { data: COURSES[0] };
            mockBackend.connections.subscribe(connection => {
                connection.mockRespond(new Response(new ResponseOptions({
                    body: JSON.stringify(mockResponse)
                })));
                expect(connection.request.url).toBe('api/courses/1');
            });
            courseService.getCourse(1).then((res) => {
                expect(res).toEqual(COURSES[0]);
            });
        }));

        it('should return error', inject([CourseService, XHRBackend], (courseService, mockBackend) => {
            mockBackend.connections.subscribe((connection => {
                connection.mockError(new Error('some error'));
            }));
            courseService.getCourse(1).then((res) => {
                expect(res).toBeDefined();
            });
        }));
    });

    describe('getCourses()', () => {
        it('should get an array of course data', inject([CourseService, XHRBackend], (courseService, mockBackend) => {
            const mockResponse = { data: COURSES };
            mockBackend.connections.subscribe(connection => {
                connection.mockRespond(new Response(new ResponseOptions({
                    body: JSON.stringify(mockResponse)
                })));
                expect(connection.request.url).toBe('api/courses');
            });
            courseService.getCourses().then((res) => {
                expect(res).toEqual(COURSES);
            });
        }));

        it('should return error', inject([CourseService, XHRBackend], (courseService, mockBackend) => {
            mockBackend.connections.subscribe((connection => {
                connection.mockError(new Error('some error'));
            }));
            courseService.getCourses().then((res) => {
                expect(res).toBeDefined();
            });
        }));
    });

    describe('getStudentsByCourse()', () => {
        it('should get an array of student data', inject([CourseService, XHRBackend], (courseService, mockBackend) => {
            const mockResponse = { data: STUDENTS };
            mockBackend.connections.subscribe(connection => {
                connection.mockRespond(new Response(new ResponseOptions({
                    body: JSON.stringify(mockResponse)
                })));
                expect(connection.request.url).toBe('api/courses/undefined/students');
            });
            courseService.getStudentsByCourse().then((res) => {
                expect(res).toEqual(STUDENTS);
            });
        }));

        it('should return error', inject([CourseService, XHRBackend], (courseService, mockBackend) => {
            mockBackend.connections.subscribe((connection => {
                connection.mockError(new Error('some error'));
            }));
            courseService.getStudentsByCourse().then((res) => {
                expect(res).toBeDefined();
            });
        }));
    });

    describe('createCourse()', () => {
        it('should return error', inject([CourseService, XHRBackend], (courseService, mockBackend) => {
            mockBackend.connections.subscribe((connection => {
                connection.mockError(new Error('some error'));
            }));
            courseService.createCourse(COURSES[0]).then((res) => {
                expect(res).toBeDefined();
            });
        }));
    });

    describe('deleteCourse()', () => {
        it('should return error', inject([CourseService, XHRBackend], (courseService, mockBackend) => {
            mockBackend.connections.subscribe((connection => {
                connection.mockError(new Error('some error'));
            }));
            courseService.deleteCourse(1).then((res) => {
                expect(res).toBeDefined();
            });
        }));
    });

    describe('updateCourse()', () => {
        it('should return error', inject([CourseService, XHRBackend], (courseService, mockBackend) => {
            mockBackend.connections.subscribe((connection => {
                connection.mockError(new Error('some error'));
            }));
            courseService.updateCourse(COURSES[0]).then((res) => {
                expect(res).toBeDefined();
            });
        }));
    });

});


text:
package org.apache.ambari.server.serveraction.upgrades;

import java.util.Map;
import java.util.concurrent.ConcurrentMap;

import org.apache.ambari.server.AmbariException;
import org.apache.ambari.server.actionmanager.HostRoleStatus;
import org.apache.ambari.server.agent.CommandReport;
import org.apache.ambari.server.orm.entities.RepositoryVersionEntity;
import org.apache.ambari.server.orm.entities.UpgradeEntity;
import org.apache.ambari.server.serveraction.AbstractServerAction;
import org.apache.ambari.server.state.Cluster;
import org.apache.ambari.server.state.Clusters;
import org.apache.ambari.server.state.Config;
import org.apache.ambari.server.utils.VersionUtils;

import com.google.inject.Inject;

/**
 * During stack upgrade,
 * if stack HDP >=2.6.3 and old value org.apache.zeppelin.notebook.repo.VFSNotebookRepo
 * update zeppelin.notebook.storage
 * to org.apache.zeppelin.notebook.repo.FileSystemNotebookRepo
 * if stack HDP >=2.6.3 and no zeppelin.config.fs.dir
 * set zeppelin.config.fs.dir to conf
 */
public class FixNotebookStorage extends AbstractServerAction {

  public static final String ZEPPELIN_NOTEBOOK_STORAGE = "zeppelin.notebook.storage";
  public static final String ZEPPELIN_CONF = "zeppelin-config";
  public static final String ORG_APACHE_ZEPPELIN_NOTEBOOK_REPO_VFSNOTEBOOK_REPO = "org.apache.zeppelin.notebook.repo.VFSNotebookRepo";
  public static final String REC_VERSION = "2.6.3.0";
  public static final String ORG_APACHE_ZEPPELIN_NOTEBOOK_REPO_FILE_SYSTEM_NOTEBOOK_REPO = "org.apache.zeppelin.notebook.repo.FileSystemNotebookRepo";
  public static final String ZEPPELIN_CONFIG_FS_DIR = "zeppelin.config.fs.dir";
  public static final String ZEPPELIN_CONFIG_FS_DIR_VALUE = "conf";

  @Inject
  private Clusters clusters;

  @Override
  public CommandReport execute(ConcurrentMap<String, Object> requestSharedDataContext)
      throws AmbariException, InterruptedException {
    String clusterName = getExecutionCommand().getClusterName();
    Cluster cluster = clusters.getCluster(clusterName);
    UpgradeEntity upgrade = cluster.getUpgradeInProgress();
    RepositoryVersionEntity repositoryVersionEntity = upgrade.getRepositoryVersion();
    String targetVersion = repositoryVersionEntity.getVersion();

    Config config = cluster.getDesiredConfigByType(ZEPPELIN_CONF);
    if (config == null || VersionUtils.compareVersions(targetVersion, REC_VERSION) < 0) {
      return createCommandReport(0, HostRoleStatus.COMPLETED, "{}",
          String.format("%s change not required", ZEPPELIN_NOTEBOOK_STORAGE), "");
    }
    Map<String, String> properties = config.getProperties();
    String oldContent = properties.get(ZEPPELIN_NOTEBOOK_STORAGE);
    String newContent = ORG_APACHE_ZEPPELIN_NOTEBOOK_REPO_FILE_SYSTEM_NOTEBOOK_REPO;

    String output = "";
    if (!properties.containsKey(ZEPPELIN_CONFIG_FS_DIR)) {
      properties.put(ZEPPELIN_CONFIG_FS_DIR, ZEPPELIN_CONFIG_FS_DIR_VALUE);
      output += String.format("set %s to %s\n",
          ZEPPELIN_NOTEBOOK_STORAGE, ORG_APACHE_ZEPPELIN_NOTEBOOK_REPO_FILE_SYSTEM_NOTEBOOK_REPO);
    }
    if (ORG_APACHE_ZEPPELIN_NOTEBOOK_REPO_VFSNOTEBOOK_REPO.equals(oldContent)) {
      properties.put(ZEPPELIN_NOTEBOOK_STORAGE, newContent);
      output += String.format("set %s to %s\n",
          ZEPPELIN_CONFIG_FS_DIR, ZEPPELIN_CONFIG_FS_DIR_VALUE);
    }
    if (output.isEmpty()) {
      output = "change not required";
    }
    config.setProperties(properties);
    config.save();
    return createCommandReport(0, HostRoleStatus.COMPLETED, "{}",
        output, "");
  }
}


text:
from time import sleep
import unittest2 as unittest

from tweepy.api import API
from tweepy.auth import OAuthHandler
from tweepy.models import Status
from tweepy.streaming import Stream, StreamListener

from config import create_auth
from test_utils import mock_tweet
from mock import MagicMock, patch

class MockStreamListener(StreamListener):
    def __init__(self, test_case):
        super(MockStreamListener, self).__init__()
        self.test_case = test_case
        self.status_count = 0
        self.status_stop_count = 0
        self.connect_cb = None

    def on_connect(self):
        if self.connect_cb:
            self.connect_cb()

    def on_timeout(self):
        self.test_case.fail('timeout')
        return False

    def on_error(self, code):
        print("response: %s" % code)
        return True

    def on_status(self, status):
        self.status_count += 1
        self.test_case.assertIsInstance(status, Status)
        if self.status_stop_count == self.status_count:
            return False

class TweepyStreamTests(unittest.TestCase):
    def setUp(self):
        self.auth = create_auth()
        self.listener = MockStreamListener(self)
        self.stream = Stream(self.auth, self.listener, timeout=3.0)

    def tearDown(self):
        self.stream.disconnect()

    def test_userstream(self):
        # Generate random tweet which should show up in the stream.
        def on_connect():
            API(self.auth).update_status(mock_tweet())

        self.listener.connect_cb = on_connect
        self.listener.status_stop_count = 1
        self.stream.userstream()
        self.assertEqual(self.listener.status_count, 1)

    def test_userstream_with_params(self):
        # Generate random tweet which should show up in the stream.
        def on_connect():
            API(self.auth).update_status(mock_tweet())

        self.listener.connect_cb = on_connect
        self.listener.status_stop_count = 1
        self.stream.userstream(_with='user', replies='all', stall_warnings=True)
        self.assertEqual(self.listener.status_count, 1)

    def test_sample(self):
        self.listener.status_stop_count = 10
        self.stream.sample()
        self.assertEquals(self.listener.status_count,
                          self.listener.status_stop_count)

    def test_filter_track(self):
        self.listener.status_stop_count = 5
        phrases = ['twitter']
        self.stream.filter(track=phrases)
        self.assertEquals(self.listener.status_count,
                          self.listener.status_stop_count)

    def test_track_encoding(self):
        s = Stream(None, None)
        s._start = lambda async: None
        s.filter(track=[u'Caf\xe9'])

        # Should be UTF-8 encoded
        self.assertEqual(u'Caf\xe9'.encode('utf8'), s.parameters['track'])

    def test_follow_encoding(self):
        s = Stream(None, None)
        s._start = lambda async: None
        s.filter(follow=[u'Caf\xe9'])

        # Should be UTF-8 encoded
        self.assertEqual(u'Caf\xe9'.encode('utf8'), s.parameters['follow'])

class TweepyStreamBackoffTests(unittest.TestCase):
    def setUp(self):
        #bad auth causes twitter to return 401 errors
        self.auth = OAuthHandler("bad-key", "bad-secret")
        self.auth.set_access_token("bad-token", "bad-token-secret")
        self.listener = MockStreamListener(self)
        self.stream = Stream(self.auth, self.listener)

    def tearDown(self):
        self.stream.disconnect()

    def test_exp_backoff(self):
        self.stream = Stream(self.auth, self.listener, timeout=3.0,
                             retry_count=1, retry_time=1.0, retry_time_cap=100.0)
        self.stream.sample()
        # 1 retry, should be 4x the retry_time
        self.assertEqual(self.stream.retry_time, 4.0)

    def test_exp_backoff_cap(self):
        self.stream = Stream(self.auth, self.listener, timeout=3.0,
                             retry_count=1, retry_time=1.0, retry_time_cap=3.0)
        self.stream.sample()
        # 1 retry, but 4x the retry_time exceeds the cap, so should be capped
        self.assertEqual(self.stream.retry_time, 3.0)

    mock_resp = MagicMock()
    mock_resp.return_value.status = 420
    @patch('httplib.HTTPConnection.getresponse', mock_resp)
    def test_420(self):
        self.stream = Stream(self.auth, self.listener, timeout=3.0, retry_count=0,
                             retry_time=1.0, retry_420=1.5, retry_time_cap=20.0)
        self.stream.sample()
        # no retries, but error 420, should be double the retry_420, not double the retry_time
        self.assertEqual(self.stream.retry_time, 3.0)


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" android:enterFadeDuration="200" android:exitFadeDuration="200">

    <item android:color="@color/mainDarkShade" android:state_pressed="true" />
    <item android:color="@color/mainDarkShade" android:state_focused="true" />
    <item android:color="@color/mainDarkShade" android:state_selected="true" />
    <item android:color="@color/mainLightShade" />

</selector>


text:
@interface GameMenuPageAchieve : GameMenuPage
{
    CCMenu *menu;
    CCLabelBMFont *label1;
}

@end


text:
package net.yeputons.spbau.spring2016.torrent.protocol;

import java.io.IOException;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.util.ArrayList;
import java.util.List;

public class ListRequest extends ServerRequest<List<FileEntry>> {
    public static final int REQUEST_ID = 1;

    @Override
    public boolean equals(Object o) {
        return o != null && getClass() == o.getClass();
    }

    @Override
    public int hashCode() {
        return 0;
    }

    @Override
    public List<FileEntry> makeRequest(DataInputStream in, DataOutputStream out) throws IOException {
        out.writeByte(REQUEST_ID);

        int count = in.readInt();
        List<FileEntry> entries = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            entries.add(FileEntry.readFrom(in));
        }
        return entries;
    }

    public static ListRequest readFrom(DataInputStream in) throws IOException {
        return new ListRequest();
    }

    @Override
    public void answerTo(DataOutputStream out, List<FileEntry> data) throws IOException {
        out.writeInt(data.size());
        for (FileEntry e : data) {
            e.writeTo(out);
        }
    }

    @Override
    public void visit(ServerRequestVisitor visitor) throws IOException {
        visitor.accept(this);
    }
}


text:
package com.terradue.warhol.urltemplate;

import java.util.Map;

final class TextAppender
    implements Appender
{

    private final String textFragment;

    public TextAppender( final String textFragment )
    {
        this.textFragment = textFragment;
    }

    @Override
    public void append( StringBuilder buffer, Map<String, String> variables )
    {
        buffer.append( textFragment );
    }

    @Override
    public String toString()
    {
        return textFragment;
    }

}


text:
package com.frontlinedubai.dao.impl;

import com.frontlinedubai.dao.CategoryDao;
import com.frontlinedubai.model.Category;
import com.frontlinedubai.model.Menu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository
public class CategoryDaoImpl implements CategoryDao {

    private NamedParameterJdbcTemplate template;

    private RowMapper<Category> categoryRowMapper = (rs, rowNum) -> {
        Category category = new Category();
        category.setId(rs.getInt("id"));
        category.setName(rs.getString("name"));
        category.setDescription(rs.getString("description"));
        return category;
    };

    @Autowired
    public CategoryDaoImpl(DataSource dataSource) {
        template = new NamedParameterJdbcTemplate(dataSource);
    }

    @Override
    public List<Category> getAllCategories() {
        Map<String, Object> params = new HashMap<String, Object>();
        String sql = "SELECT * FROM category";

        List<Category> list = template.query(
                sql,
                params,
                categoryRowMapper);

        return list;
    }
}