text:
<?php

/**
 * This is a test class for the ClassLoaderCallbackInterface
 */
class TestClassWithCallback implements ClassLoaderCallbackInterface {
	/**
	 * Flag variable to store, if the class loader callback has been called.
	 * @var bool default false
	 */
	protected static $hadCallback = false;
	/**
	 * Class loader callback
	 */
	public static function onClassLoaded() {
		self::$hadCallback = true;
	}
	/**
	 * Query function if the class loader callback has been called
	 * @return bool
	 */
	public static function getHadCallback() {
		return self::$hadCallback;
	}
}

redpajama_set_name: RedPajamaGithub


text:
var gulp = require('gulp'),
  nodemon = require('gulp-nodemon'),
  plumber = require('gulp-plumber'),
  livereload = require('gulp-livereload'),
  less = require('gulp-less');

gulp.task('less', function () {
  gulp.src('./public/css/*.less')
    .pipe(plumber())
    .pipe(less())
    .pipe(gulp.dest('./public/css'))
    .pipe(livereload());
});

gulp.task('watch', function() {
  gulp.watch('./public/css/*.less', ['less']);
});

gulp.task('develop', function () {
  livereload.listen();
  nodemon({
    script: 'app.js',
    ext: 'js coffee nunjucks',
    stdout: false
  }).on('readable', function () {
    this.stdout.on('data', function (chunk) {
      if(/^Express server listening on port/.test(chunk)){
        livereload.changed(__dirname);
      }
    });
    this.stdout.pipe(process.stdout);
    this.stderr.pipe(process.stderr);
  });
});

gulp.task('default', [
  'less',
  'develop',
  'watch'
]);


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
T-Index
</TITLE>

<META NAME="date" CONTENT="2010-05-28">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
      Use
      Tree
      Deprecated
    Index
      Help

 PREV LETTER
 NEXT LETTER

  FRAMES
 NO FRAMES

  All Classes

A B C D E F G H I K L M N O P R S T U V W X

T

table(Object...) -
Method in class net.sf.sahi.client.BrowserElements

tableHeader(Object...) -
Method in class net.sf.sahi.client.BrowserElements

test() -
Method in class net.sf.sahi.client.BrowserCondition

text() -
Method in class net.sf.sahi.client.ElementStub

Returns the inner text of an element.

 same as getText().

 Internally calls browser.getText(this);

textarea(Object...) -
Method in class net.sf.sahi.client.BrowserElements

textbox(Object...) -
Method in class net.sf.sahi.client.BrowserElements

title() -
Method in class net.sf.sahi.client.Browser

toString() -
Method in class net.sf.sahi.client.ElementStub

toString() -
Method in exception net.sf.sahi.client.ExecutionException

      Overview
      Package
      Class
      Use
      Tree
      Deprecated
    Index
      Help

 PREV LETTER
 NEXT LETTER

  FRAMES
 NO FRAMES

  All Classes

A B C D E F G H I K L M N O P R S T U V W X


text:
<!DOCTYPE html>

    <title>GoInstant GoAngular Component Example</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet">

user: {{last.user}} - description: {{last.description}}

          <input enter="addTodo()" ng-model="newTodo" type="text" class="form-control" />

            <button enter="addTodo()" ng-click="addTodo()" class="btn btn-default" type="button">Add Todo</button>

              {{todo.description}}
              <button ng-click="remove(todo.$name)" class="pull-right btn btn-xs btn-danger">x</button>

GoAngular Todo

Current User: <input type="text" ng-model="users.$local.displayName"/>

{{provider.name}}

              Logout

All Users

{{user.displayName}} - {{ user.id }}


text:
This is [my] personal GitHub repository with useful pieces of code and hobby projects.
Some of the projects are work related, others' are features that I develop and document in GitHub.

All of the content goes under the *[The MIT License (MIT)]*.

**To clone the repository to a local machine, please use the following command:**
```
git clone https://github.com/djuptho/dev_portfolio.git
```
When you have cloned the repository make sure to `git pull` to get the newest updates.
# Repository contents

#### Adblock Detection

This code detects if the user is using an ad blocking plugin. By combining my code with some custom Javascript for your platform you can track ad block usage and e.g. provide ("force") alternative ads to the users.

**Platform**: Desktop
**Made with**: Javascript, HTML, CSS
**Live demo**: http://djuptho.com/dev/adblock/

![](https://github.com/djuptho/dev_portfolio/blob/master/resources/adblock_screens.png?raw=true)

#### Live Clock

When using multiple computers screens (e.g. when playing games) it's neat to have a clear live clock one of the screens. The clock updates every second. Remember that this feature requires PHP and needs to be running on a server.

The background artwork is taken from http://eu.battle.net/wow/en/media/fanart/

**Platform**: Desktop
**Made with**: PHP, Javascript, HTML, CSS
**Live demo**: http://djuptho.com/dev/clock/

![](https://github.com/djuptho/dev_portfolio/blob/master/resources/clock_ui.png?raw=true)

#### Device Tilt Detection (spirit level)

This feature works on smartphones and tells you the direction (tilt) of the device. This also works as a spirit level meter. The Javascript is commonly used in rich media mobile advertising.

**Platform**: Mobile
**Made with**: Javascript, HTML, CSS
**Live demo**: http://djuptho.com/dev/device/device_detection/

![](https://github.com/djuptho/dev_portfolio/blob/master/resources/device_detection.png?raw=true)

#### Location Coordinates

By clicking the button (and allowing the page to use your location) it will tell you your location. By combining this data to a database you could translate the location to a country or city. This can be used for a more personalized user experience.

**Platform**: Desktop/Mobile
**Made with**: Javascript, HTML, CSS
**Live demo**: http://djuptho.com/dev/location_coordinates/

![](https://github.com/djuptho/dev_portfolio/blob/master/resources/location_coordinates.gif?raw=true)

#### Social Share

Sharing web pages in social media is something many sites have implemented for a long time. This special feature works on mobile devices and appears in the lower part of the screen when scrolling down. This could be useful e.g. on a news site.

**Platform**: Mobile
**Made with**: Javascript, HTML, CSS
**Live demo**: http://djuptho.com/dev/share/

![](https://github.com/djuptho/dev_portfolio/blob/master/resources/social_share.gif?raw=true)

#### Spotify Prototype

I got dared to make a version of Spotify. This simple web application has a few features and plays a piece of classical music. Works pretty good on a smartphone.

*Copyright of application: Spotify*

**Platform**: Mobile
**Made with**: Javascript, HTML, CSS
**Live demo**: http://djuptho.com/dev/spotify/

![](https://raw.githubusercontent.com/djuptho/dev_portfolio/master/resources/spotify.gif)

#### Hover Tooltip

Many sites have round images with links that appear as tooltips when hovering over them.
I made this work with CSS3 animations without any Javascript.

**Platform**: Desktop
**Made with**: HTML, CSS
**Live demo**: http://djuptho.com/dev/tooltip/

![](https://raw.githubusercontent.com/djuptho/dev_portfolio/master/resources/tooltip.gif)

#### Easily order a public transportation ticket

In my region (Helsinki, Finland) it's possible to buy a public transportation ticket through SMS. Bookmark this page on your phone's home screen and easily buy e.g. a train ticket in just two a few clicks.

![](http://djuptho.com/dev/hsl_ticket/apple-icon-72x72.png)

**Platform**: Mobile (Android, iOS)
**Made with**: Javascript, HTML, CSS
**Live demo**: http://djuptho.com/dev/hsl_ticket/

*More information on SMS-tickets (HSL):* https://www.hsl.fi/en/tickets-and-fares/sms-ticket

![](https://github.com/djuptho/dev_portfolio/blob/master/resources/redirect_sms.gif?raw=true)

#### Am I Online?

When using public wireless internet connections at airports, hotels etc. it's nice to know if the connection is stable and works properly. By using my mobile application, you easily know if you have a connection or not :)

![](http://djuptho.com/dev/amionline/apple-icon-72x72.png)

**Platform**: Mobile
**Made with**: Javascript, HTML, CSS, HTML5 Cache Manifest
**Live demo**: http://djuptho.com/dev/amionline/

![](https://github.com/djuptho/dev_portfolio/blob/master/resources/online_checker.png)

#### Countdown Timer

A countdown timer can be an effective way to evoke actions e.g. on a marketing landingpage. Configure the desired date in the PHP-file and customize the CSS-file according to your needs.

**Platform**: Desktop/Mobile
**Made with**: PHP, HTML, CSS
**Live demo**: http://djuptho.com/dev/countdown_timer/

![](https://github.com/djuptho/dev_portfolio/blob/master/resources/timer.png)

#### Caps Lock Detection

When a user is logging in to a service it's nice to detect and inform the user if CAPS LOCK is detected. This minimizes confusion from a user point of view.

**Platform**: Desktop
**Made with**: Javascript, HTML, CSS
**Live demo**: http://djuptho.com/dev/capslock/

![](https://github.com/djuptho/dev_portfolio/blob/master/resources/capslock.gif)

#### Preventing image right clicks

Sometimes images on your web page are too precious for you to let go of. By using this short code you can disable right clicks on images on the site. This helps preventing users from saving images.

**Platform**: Desktop
**Made with**: Javascript, HTML, CSS
**Live demo**: http://djuptho.com/dev/rightclick/

![](https://github.com/djuptho/dev_portfolio/blob/master/resources/rightclick.jpg)

#### Get and copy your IP address with one click

With this piece of code the user can retrieve his/her IP address easily and copy it with just one click.

**Platform**: Desktop
**Made with**: PHP, Javascript, CSS
**Live demo**: http://djuptho.com/dev/copy_ip/

![](https://github.com/djuptho/dev_portfolio/blob/master/resources/copy_ip.gif)

#### RWD Checker

RWD Checker is a handy tool for Web Designers and Developers. Use this extension to easily check the usability of your responsive site on different screen sizes. Special thanks to Responsinator.com :)

**Platform**: Google Chrome Extension
**Made with**: Javascript, HTML, CSS, JSON
**Live demo and download**: https://goo.gl/LiMDDr

![](https://github.com/djuptho/dev_portfolio/blob/master/resources/rwd_promo.png)

#### Lorem Ipsum Extension

This extension helps Developers to find placeholder content for their web development projects.
Simply copy and paste the content provided by the plugin and add this to your code.

All of the content is free-to-use in non-commercial projects. Special thanks to Lorempixel.com :)

**Platform**: Google Chrome Extension
**Made with**: Javascript, HTML, CSS, JSON
**Live demo and download**: https://goo.gl/nhFrtB

![](https://github.com/djuptho/dev_portfolio/blob/master/resources/lorem_promo.png)

#### Time Travel Extension

The Time Travel extension is a tool for everyone with an interest in internet history.
The extension takes you back in time, displaying copies of the web page since the day the web page was created.

Special thanks to Archive.org :)

**Platform**: Google Chrome Extension
**Made with**: Javascript, HTML, CSS, JSON
**Live demo and download**: https://goo.gl/a5HnNK

![](https://github.com/djuptho/dev_portfolio/blob/master/resources/time_travel_extension.jpg)

#### Light CMS using Google Sheet API

By using the Google Sheet API one can build a connection between a Google Sheet and a web page through a simple JSON call.
This can be used in prototypes or other web pages where a light, easy-to-maintain, CMS is of benefit.

Example data is taken from NHL.com.

**Platform**: Desktop, Mobile
**Made with**: Javascript, HTML, CSS
**Live demo**: http://djuptho.com/dev/sheetdb/

![](https://github.com/djuptho/dev_portfolio/blob/master/resources/sheetdb.png)

#### Page length scroll detector

Many blogs and news sites has an indicator in the top section of a page explaining how far the user has scrolled.
Here's a simple example made in JavaScript tidied up with a bit of CSS.

**Platform**: Desktop, Mobile
**Made with**: Javascript, HTML, CSS
**Live demo**: http://djuptho.com/dev/scroll_length/

![](https://github.com/djuptho/dev_portfolio/blob/master/resources/scroll_length_detector.gif)

#### Check for tab activity

With this small Javascript utility you can check if users have the browser window focused.
If the window is not focused, a few page titles are changed in the tab of the browser.

**Platform**: Desktop
**Made with**: Javascript, HTML, CSS
**Live demo**: http://djuptho.com/dev/tab_focus/

![](https://github.com/djuptho/dev_portfolio/blob/master/resources/tab_focus.gif)

#### Detect exit intent

Detecting exit intent on web pages can be a way for companies to engage users on their sites. This tiny piece of jQuery detects when users are about to leave the page on desktop devices.

**Platform**: Desktop
**Made with**: jQuery, HTML
**Live demo**: http://djuptho.com/dev/exit_intent/

![](https://github.com/djuptho/dev_portfolio/blob/master/resources/exit_intent.gif)

#### Python Scraper to JSON

This Python script scrapes a selected web page and its content and stores it in a JSON format. The JSON data can be parsed on any web page as presented in this simple example.

**Platform**: Desktop, Mobile
**Made with**: Python, jQuery, JSON, HTML , CSS
**Live demo**: http://djuptho.com/dev/json/demo/

![](https://github.com/djuptho/dev_portfolio/blob/master/resources/scraper_json.png)

#### Microsoft Teams channel email integration

With the public Unicafe lunch menu API (University of Helsinki), a daily email message can be compiled, configured and sent with PHP to a Microsoft Teams channel of choice. The JSON data set is parsed, formatted and pushes the lunch menu of the day to an array.

**Platform**: Microsoft Teams integration
**Made with**: PHP, JSON, Crontab, Bash (sh)

![](https://github.com/djuptho/dev_portfolio/blob/master/resources/unicafe.png)

#### Light CMS using Google Sheet API

By using the Google Sheet API one can build a connection between a Google Sheet and a web page through a simple JSON call. In this version a Google Form survey works as the interface for submitting data.

Example data is taken from Amazon.de.

**Made with**: Javascript, HTML, CSS
**Live demo**: http://djuptho.com/dev/sheetdb2/

![](https://github.com/djuptho/dev_portfolio/blob/master/resources/sheetdb2_mvp.png)

#### Form Password Show

To improve user experience when logging in, it is adviced that forms have a functionality to display the password when requested. In this demo three layouts are presented with icons and labels to display a users password. The third layout has a custom checkbox implementation using CSS/Javascript.

**Made with**: Javascript, HTML, CSS
**Live demo**: http://djuptho.com/dev/password_show/
![](https://github.com/djuptho/dev_portfolio/blob/master/resources/password_show.png)

[my]: <http://djuptho.com>
[The MIT License (MIT)]: <http://choosealicense.com/licenses/mit/>


text:
package org.opentravel.git;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.ErrorHandler;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.opentravel.otm.forum2016.MockContentServlet;

/**
 * Launches an in-process Jetty server to handle live mock service requests.
 */
public class JettyTestServer {

	private static final int SERVER_PORT = 8080;

    private Server jettyServer;

    /**
     * Launches the Jetty server.
     *
     * @throws Exception  thrown if the server cannot be started
     */
    public synchronized void start() throws Exception {
        if (jettyServer != null) {
            throw new IllegalStateException( "The Jetty server is already running." );
        }
        ServletContextHandler context = new ServletContextHandler( ServletContextHandler.SESSIONS );

		context.setContextPath( "/mock-content" );
        context.addServlet(new ServletHolder( new MockContentServlet() ), "/*" );

        jettyServer = new Server( SERVER_PORT );

        ErrorHandler errH = new ErrorHandler();
        errH.setShowStacks( true );

        jettyServer.setHandler( context );
        context.setErrorHandler( errH );
        jettyServer.start();
    }

    /**
     * Shuts down the Jetty server.
     *
     * @throws Exception  thrown if the server cannot be shut down
     */
    public synchronized void stop() throws Exception {
        if (jettyServer == null) {
            throw new IllegalStateException( "The Jetty server is not running." );
        }
        jettyServer.stop();
        jettyServer = null;
    }

    /**
     * Returns the base URL to be used when accessing the Jetty server.
     *
     * @return String
     */
    public String getBaseUrl() {
    	return "http://localhost:" + SERVER_PORT + "/jaxrs-otm-prototype/service";
    }

    /**
     * Main method that launches the Jetty test server from the command line.
     *
     * @param args  the command-line arguments
     */
    public static void main(String[] args) {
    	try {
    		new JettyTestServer().start();
    		System.out.println("Jetty Server running on port " + SERVER_PORT);

    		while (true) {
    			Thread.sleep( 100000L );
    		}

    	} catch (Throwable t) {
    		t.printStackTrace( System.out );
    	}
    }
}


text:
#define _POSIX_C_SOURCE 200809L
#define _BSD_SOURCE				// for the usleep
#include <string.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <pthread.h>

#include "ocpayload.h"

#include "things_def.h"
#include "things_common.h"
#include "things_queue.h"
#include "things_logger.h"
#include "things_malloc.h"
#include "cacommon.h"
#include "things_string_util.h"
#include "things_resource.h"
#include "../utils/inc/things_network.h"
#include "things_api.h"
#include "things_types.h"
#include "things_server_builder.h"
#include "things_data_manager.h"

#include "things_req_handler.h"
#include "things_hashmap.h"

#include "things_thread.h"
#ifdef __ST_THINGS_RTOS__
#include "ctype.h"
#include "things_rtos_util.h"
#endif

#define TAG "[things_reqhdlr]"

static handle_request_func_type g_handle_request_get_cb = NULL;
static handle_request_func_type g_handle_request_set_cb = NULL;

extern things_server_builder_s *g_builder;

static queue_s *gp_oic_req_queue;
static int g_handle_res_cnt = 0;
static char **g_handle_res_list = NULL;
static handle_request_func_type g_handle_req_cb = NULL;
static get_notify_obs_uri_cb g_get_notify_obs_uri = NULL;

static handle_request_interface_cb g_handle_request_interface_cb = NULL;

static stop_softap_func_type g_stop_soft_ap_cb = NULL;

static pthread_t g_req_handle;

static int g_quit_flag = 0;

OCEntityHandlerResult things_abort(pthread_t *h_thread_abort, things_es_enrollee_abort_e level);

/**
 * Return : 0 (Invalid Request), 1 (Resource Supporting Interface)
 * Need refactoring later...
 */
static int verify_request(OCEntityHandlerRequest *eh_request, const char *uri, int req_type)
{
	int result = 0;
	things_resource_s *pst_temp_resource = NULL;

	if (g_builder == NULL) {
		THINGS_LOG_ERROR(THINGS_ERROR, TAG, "Server Builder is not registered..");
		goto EXIT_VALIDATION;
	}

	things_resource_s *resource = things_create_resource_inst(eh_request->requestHandle,
								  eh_request->resource,
								  eh_request->query,
								  eh_request->payload);	//g_builder->get_resource(g_builder, uri);
	things_resource_s *child = NULL;
	/*! Added by st_things for memory Leak fix
	 */
	pst_temp_resource = resource;
	if (resource == NULL) {
		THINGS_LOG_V_ERROR(THINGS_ERROR, TAG, "Resource Not found : %s ", uri);
		goto EXIT_VALIDATION;
	}

	THINGS_LOG_D(THINGS_DEBUG, TAG, "Query in the Request : %s", eh_request->query);

	//  Verify received request in valid or not..
	// 1. If there's no interface type in the request ..
	if ((strstr(eh_request->query, "if=") == NULL)
		|| (strstr(eh_request->query, OIC_INTERFACE_BASELINE) != NULL)
		|| (true == resource->things_is_supporting_interface_type(resource, eh_request->query))) {
		result = 1;
	}
	// 2. If request type == POST(OC_REST_POST == 4),
	//    then validate the attributes kyes in the request
	if (result == 1 && req_type == OC_REST_POST) {
		//  Reseting the result value to apply
		// the result of additional verification
		result = 0;

		//  If the given resource does not have sensor nor read interface type..
		if (!(resource->things_is_supporting_interface_type(resource, OIC_INTERFACE_SENSOR))
			&& !(resource->things_is_supporting_interface_type(resource, OC_RSRVD_INTERFACE_READ))) {
			//  If no query or..
			//       query with "supporting interface types"  then...
			if ((strstr(eh_request->query, "if=") == NULL)
				|| ((strstr(eh_request->query, "if=") != NULL)
					&& (resource->things_is_supporting_interface_type(resource, eh_request->query))
				   )
			   ) {
				//  Verify request(Attributes.) with Validator func implemented
				const int num = resource->things_get_num_of_res_types(resource);

				THINGS_LOG_D(THINGS_DEBUG, TAG, "# of RT :%d", num);

				if (resource->size > 1) {
					// Remove "rep" wrapper
					things_resource_s *res = resource;
					things_representation_s *tRep = NULL;
					things_representation_s *tchild_rep = NULL;

					for (int iter = 0; iter < resource->size; ++iter) {
						tchild_rep = things_create_representation_inst(NULL);
						res->things_get_representation(res, &tRep);
						tRep->things_get_object_value(tRep, OC_RSRVD_REPRESENTATION, tchild_rep);
						res->things_set_representation(res, tchild_rep);

						res = res->things_get_next(res);
					}

					for (int iter = 0; iter < resource->size; ++iter) {
						child = NULL;

						if (resource->uri == NULL) {
							THINGS_LOG_ERROR(THINGS_ERROR, TAG, "Resource URI is NULL.");
							result = OC_EH_ERROR;
							goto EXIT_VALIDATION;
						}

						child = g_builder->get_resource(g_builder, resource->uri);

						if (NULL == child) {
							THINGS_LOG_ERROR(THINGS_ERROR, TAG, "Not Existing Child Resource.");
							result = OC_EH_ERROR;
							goto EXIT_VALIDATION;
						}
						if (NULL == resource->rep) {
							THINGS_LOG_ERROR(THINGS_ERROR, TAG, "things_representation_s is NULL.");
							result = OC_EH_ERROR;
							goto EXIT_VALIDATION;

						}

						if (num > 0) {
							for (int i = 0; i < num; i++) {

								result |= dm_validate_attribute_in_request(resource->things_get_res_type(child, i), (const void *) /*eh_request->payload */resource->rep->payload);
								if (!result) {
									goto EXIT_VALIDATION;
								}
							}
						}

						resource = resource->things_get_next(resource);

						// if(targetUri != NULL)   things_free(targetUri);
					}
				} else {
					if (num > 0) {
						for (int iter = 0; iter < num; iter++) {
							// if it's okey in any case then....it's valid..
							result |= dm_validate_attribute_in_request(resource->things_get_res_type(resource, iter), (const void *)eh_request->payload);
						}
					}
				}
			}
		}
	}

EXIT_VALIDATION:

	/*! Added by st_things for memory Leak fix
	 */
	things_release_resource_inst(pst_temp_resource);

	THINGS_LOG_D(THINGS_DEBUG, TAG, "Validation Result.(%d)", result);

	return result;
}

OCEntityHandlerResult send_response(OCRequestHandle request_handle, OCResourceHandle resource, OCEntityHandlerResult result, const char *uri, void *payload)
{
	THINGS_LOG_D(THINGS_DEBUG, TAG, THINGS_FUNC_ENTRY);
	OCEntityHandlerResult eh_result = OC_EH_OK;
	OCEntityHandlerResponse response = { 0, 0, OC_EH_ERROR, 0, 0, {}, {0}, false };

	THINGS_LOG_D(THINGS_DEBUG, TAG, "Creating Response with Request Handle : %x,Resource Handle : %x", request_handle, resource);

	response.numSendVendorSpecificHeaderOptions = 0;
	memset(response.sendVendorSpecificHeaderOptions, 0, sizeof response.sendVendorSpecificHeaderOptions);
	memset(response.resourceUri, 0, sizeof(response.resourceUri));

	if (NULL != request_handle && NULL != resource) {
		response.requestHandle = request_handle;	//eh_request->request_handle;
		response.resourceHandle = resource;	//eh_request->resource;
		response.persistentBufferFlag = 0;
		response.ehResult = result;
		if (payload != NULL) {
			THINGS_LOG_D(THINGS_DEBUG, TAG, "Payload is Not NULL");
			response.payload = (OCPayload *) payload;
		} else {
			THINGS_LOG_D(THINGS_DEBUG, TAG, "No Payload");
			response.payload = NULL;
		}

		THINGS_LOG_V(THINGS_INFO, TAG, "\t\t\tRes. : %s ( %d )", (response.ehResult == OC_EH_OK ? "NORMAL" : "ERROR"), response.ehResult);

		OCStackResult ret = OCDoResponse(&response);
		THINGS_LOG_V(THINGS_INFO, TAG, "\t\t\tMsg. Out? : (%s)", (ret == OC_STACK_OK) ? "SUCCESS" : "FAIL");
		if (ret != OC_STACK_OK) {
			eh_result = OC_EH_ERROR;
		}
	} else {
		eh_result = OC_EH_ERROR;
	}

	// THINGS_LOG_D(THINGS_DEBUG, TAG, THINGS_FUNC_EXIT);
	return eh_result;
}

static bool is_number(char *str)
{
	int len = strlen(str);
	for (int index = 0; index < len; index++) {
		if (!isdigit(str[index])) {
			THINGS_LOG_D_ERROR(THINGS_ERROR, TAG, "It's NOT NUMBER : %s", str);
			return false;
		}
	}
	THINGS_LOG_D(THINGS_DEBUG, TAG, "It is NUMBER : %s", str);
	return true;
}

/**
 * This functions will replace thie ConverAPInfo(~~ )
 */
static OCEntityHandlerResult convert_ap_infor(things_resource_s *target_resource, access_point_info_s **p_list, int list_cnt)
{

	OCEntityHandlerResult eh_result = OC_EH_ERROR;

	things_representation_s *rep = NULL;

	if (!(list_cnt == 0 || p_list == NULL)) {

		if (target_resource->rep == NULL) {
			rep = things_create_representation_inst(NULL);
			target_resource->things_set_representation(target_resource, rep);
		} else {
			rep = target_resource->rep;
		}

		things_representation_s **child_rep = (things_representation_s **) things_malloc(list_cnt * sizeof(things_representation_s *));

		for (int iter = 0; iter < list_cnt; iter++) {

			THINGS_LOG_D(THINGS_DEBUG, TAG, "e_ssid : %s", p_list[iter]->e_ssid);
			THINGS_LOG_D(THINGS_DEBUG, TAG, "security_key : %s", p_list[iter]->security_key);
			THINGS_LOG_D(THINGS_DEBUG, TAG, "auth_type : %s", p_list[iter]->auth_type);
			THINGS_LOG_D(THINGS_DEBUG, TAG, "enc_type : %s", p_list[iter]->enc_type);
			THINGS_LOG_D(THINGS_DEBUG, TAG, "channel : %s", p_list[iter]->channel);
			THINGS_LOG_D(THINGS_DEBUG, TAG, "signal_level : %s", p_list[iter]->signal_level);
			THINGS_LOG_D(THINGS_DEBUG, TAG, "bss_id : %s", p_list[iter]->bss_id);

			child_rep[iter] = things_create_representation_inst(NULL);
			child_rep[iter]->things_set_value(child_rep[iter], SEC_ATTRIBUTE_AP_CHANNAL, p_list[iter]->channel);
			child_rep[iter]->things_set_value(child_rep[iter], SEC_ATTRIBUTE_AP_ENCTYPE, p_list[iter]->enc_type);
			child_rep[iter]->things_set_value(child_rep[iter], SEC_ATTRIBUTE_AP_MACADDR, p_list[iter]->bss_id);
			child_rep[iter]->things_set_value(child_rep[iter], SEC_ATTRIBUTE_AP_MAXRATE, "MAX_RATE");
			child_rep[iter]->things_set_value(child_rep[iter], SEC_ATTRIBUTE_AP_RSSI, p_list[iter]->signal_level);
			child_rep[iter]->things_set_value(child_rep[iter], SEC_ATTRIBUTE_AP_SECTYPE, p_list[iter]->auth_type);
			child_rep[iter]->things_set_value(child_rep[iter], SEC_ATTRIBUTE_AP_SSID, p_list[iter]->e_ssid);
		}

		rep->things_set_arrayvalue(rep, SEC_ATTRIBUTE_AP_ITEMS, list_cnt, child_rep);

		for (int iter = 0; iter < list_cnt; iter++) {
			/*! Changed by st_things for memory Leak fix
			 */
			things_release_representation_inst(child_rep[iter]);
			child_rep[iter] = NULL;
		}
		things_free(child_rep);
		child_rep = NULL;

		eh_result = OC_EH_OK;
	}

	return eh_result;
}

/**
 * This functions will be deprecated~!!!
 */
static OCEntityHandlerResult get_ap_scan_result(things_resource_s *target_resource)
{
	THINGS_LOG_D(THINGS_DEBUG, TAG, THINGS_FUNC_ENTRY);

	OCEntityHandlerResult eh_result = OC_EH_ERROR;

	access_point_info_s **p_list = NULL;
	int list_cnt = 0;
	int result = 0;

	// p_list = (access_point_info_s**)things_malloc(sizeof(access_point_info_s*) *MAX_NUM_AP);

	result = things_get_ap_list(&p_list, &list_cnt);
	if (result) {
		THINGS_LOG_D(THINGS_DEBUG, TAG, "Get Access points list!!! %d ", list_cnt);
		if (list_cnt > 0) {
			//eh_result = ConvertAPInfo(target_resource, p_list, list_cnt);
			eh_result = convert_ap_infor(target_resource, p_list, list_cnt);
		} else if (list_cnt == 0) {
			THINGS_LOG_D(THINGS_DEBUG, TAG, "0 Access points!!!! %d ", list_cnt);
			eh_result = OC_EH_OK;
		} else {
			eh_result = OC_EH_ERROR;
		}
	} else {
		THINGS_LOG_V(THINGS_ERROR, TAG, "GET AP Searching List FUNC Failed!!!!");
	}

	if (p_list != NULL) {
		for (int i = 0; i < list_cnt; i++) {
			things_free(p_list[i]);
		}
		things_free(p_list);
	}

	return eh_result;
}

/**
 * This functions will replace the get_ap_scan_result(~~)
 */
static OCEntityHandlerResult get_provisioning_info(things_resource_s *target_resource)
{
	OCEntityHandlerResult eh_result = OC_EH_ERROR;

	// if(eh_result == OC_EH_OK)
	{

		const char *deviceID = OCGetServerInstanceIDString();
		const char *deviceRT = dm_get_things_device_type(0);
		bool isOwned = false;
		bool isReset = things_get_reset_mask(RST_ALL_FLAG);
		/* if(!isReset) { */
		/*  isReset = 1; */
		/* } */

		if (OC_STACK_OK != OCGetDeviceOwnedState(&isOwned)) {
			THINGS_LOG_V_ERROR(THINGS_ERROR, TAG, "Failed to get device owned state, Informing as UNOWNED~!!!!");
			isOwned = false;
		}
		if (target_resource->rep == NULL) {
			/*! Added by st_things for memory Leak fix
			 */
			things_representation_s *pstRep = NULL;
			pstRep = things_create_representation_inst(NULL);
			target_resource->things_set_representation(target_resource, pstRep);
		}

		things_representation_s *child_rep[1] = { NULL };

		child_rep[0] = things_create_representation_inst(NULL);
		child_rep[0]->things_set_value(child_rep[0], SEC_ATTRIBUTE_PROV_TARGET_ID, deviceID);
		child_rep[0]->things_set_value(child_rep[0], SEC_ATTRIBUTE_PROV_TARGET_RT, deviceRT);

		// child_rep[0]->things_set_bool_value(child_rep[0], SEC_ATTRIBUTE_PROV_TARGET_OWNED, isOwned);
		child_rep[0]->things_set_bool_value(child_rep[0], SEC_ATTRIBUTE_PROV_TARGET_PUBED, dm_is_rsc_published());

		target_resource->rep->things_set_arrayvalue(target_resource->rep, SEC_ATTRIBUTE_PROV_TARGETS, 1, child_rep);

		target_resource->rep->things_set_bool_value(target_resource->rep, SEC_ATTRIBUTE_PROV_TARGET_OWNED, isOwned);

		target_resource->rep->things_set_value(target_resource->rep, SEC_ATTRIBUTE_PROV_EZSETDI, deviceID);

		target_resource->rep->things_set_bool_value(target_resource->rep, SEC_ATTRIBUTE_PROV_RESET, isReset);

		target_resource->rep->things_set_int_value(target_resource->rep, SEC_ATTRIBUTE_PROV_ABORT, 0);
		/*! Added by st_things for memory Leak fix
		 */
		if (NULL != child_rep[0]) {
			things_release_representation_inst(child_rep[0]);
		}

		eh_result = OC_EH_OK;
	}

	return eh_result;
}

static OCEntityHandlerResult trigger_reset_request(things_resource_s *target_resource, bool reset)
{
	OCEntityHandlerResult eh_result = OC_EH_ERROR;
	things_resource_s *clone_resource = NULL;
	bool isOwned;

	OCGetDeviceOwnedState(&isOwned);
	if (isOwned == false) {
		return OC_EH_NOT_ACCEPTABLE;
	}

	THINGS_LOG_V(THINGS_DEBUG, TAG, "==> RESET : %s", (reset == true ? "YES" : "NO"));

	if (reset == true) {
		int res = -1;

		clone_resource = clone_resource_inst(target_resource);
		res = things_reset((void *)clone_resource, RST_NEED_CONFIRM);

		switch (res) {
		case 1:
			THINGS_LOG(THINGS_DEBUG, TAG, "Reset Thread create is success.");
			eh_result = OC_EH_SLOW;
			break;
		case 0:
			THINGS_LOG(THINGS_INFO, TAG, "Already Run Reset-Process.");
			eh_result = OC_EH_NOT_ACCEPTABLE;
		default:
			things_release_resource_inst(clone_resource);
			clone_resource = NULL;
			break;
		}
	} else {
		THINGS_LOG_D(THINGS_DEBUG, TAG, "reset = %d, So, can not reset start.", reset);
		eh_result = OC_EH_OK;
	}

	return eh_result;
}

static OCEntityHandlerResult trigger_stop_ap_request(things_resource_s *target_resource, bool stop_ap)
{
	OCEntityHandlerResult eh_result = OC_EH_ERROR;

	THINGS_LOG_V(THINGS_DEBUG, TAG, "==> STOP SOFT AP : %s", (stop_ap == true ? "YES" : "NO"));

	if (stop_ap == true) {
		if (NULL != g_stop_soft_ap_cb) {
			if (1 == g_stop_soft_ap_cb(stop_ap)) {
				THINGS_LOG_V(THINGS_DEBUG, TAG, "Stop Soft AP notified Successfully");
				eh_result = OC_EH_OK;
			} else {
				THINGS_LOG_V(THINGS_DEBUG, TAG, "Stop Soft AP notified, BUT DENIED");
				eh_result = OC_EH_ERROR;
			}
		}
	} else {
		THINGS_LOG_D(THINGS_DEBUG, TAG, "stop_ap = %d, So, can not stop AP.", stop_ap);
		eh_result = OC_EH_OK;
	}

	return eh_result;
}

static OCEntityHandlerResult trigger_abort_request(things_resource_s *target_resource, things_es_enrollee_abort_e abort_es)
{
	OCEntityHandlerResult eh_result = OC_EH_ERROR;
	static pthread_t h_thread_abort = NULL;

	THINGS_LOG_V(THINGS_DEBUG, TAG, "==> ABORT Easy Setup : %d", abort_es);

	switch (abort_es) {
	case ABORT_BEFORE_RESET_CONFIRM:	// before Reset Confirm.
	case ABORT_BEFORE_SEC_CONFIRM:	// After Reset Confirm & before Security Confirm.
	case ABORT_BEFORE_DATA_PROVISIONING:	// After Security Confirm
		THINGS_LOG_V(THINGS_DEBUG, TAG, "Forwarding abort-level to st_things App.(Level: %d)", abort_es);
		eh_result = things_abort(&h_thread_abort, abort_es);
		break;
	default:
		THINGS_LOG_D(THINGS_DEBUG, TAG, "abort_es = %d, So, Don't need any-process", abort_es);
		eh_result = OC_EH_OK;
		break;
	}

	return eh_result;
}

static OCEntityHandlerResult set_provisioning_info(things_resource_s *target_resource)
{
	OCEntityHandlerResult eh_result = OC_EH_ERROR;

	bool reset = false;
	bool stop_ap = false;
	int64_t abort_es = 0;

	if (target_resource->rep->things_get_bool_value(target_resource->rep, SEC_ATTRIBUTE_PROV_RESET, &reset) == true) {
		eh_result = trigger_reset_request(target_resource, reset);
	} else if (target_resource->rep->things_get_bool_value(target_resource->rep, SEC_ATTRIBUTE_PROV_TERMINATE_AP, &stop_ap) == true) {
		eh_result = trigger_stop_ap_request(target_resource, stop_ap);
	} else if (target_resource->rep->things_get_int_value(target_resource->rep, SEC_ATTRIBUTE_PROV_ABORT, &abort_es) == true) {
		eh_result = trigger_abort_request(target_resource, (things_es_enrollee_abort_e) abort_es);
	} else {
		THINGS_LOG_V_ERROR(THINGS_ERROR, TAG, "Get Value is failed.(RESET NOR TERMINATE NOR ABORT)");
		return eh_result;
	}

	return eh_result;
}

static OCEntityHandlerResult get_device_or_platform_info_result(things_resource_s *target_resource, char *device_id)
{
	OCEntityHandlerResult eh_result = OC_EH_ERROR;

	if (strlen(device_id) > 0 && is_number(device_id)) {
		int num = atoi(device_id);

		// 1. Get the resource with uri
		things_resource_s *resource = dm_get_resource_instance(target_resource->uri, num);
		if (resource) {
			// 2. Clone the Payload of the resource
			OCPayloadDestroy((OCPayload *) target_resource->rep->payload);
			target_resource->rep->payload = NULL;
			target_resource->rep->payload = OCRepPayloadClone(resource->rep->payload);

			eh_result = OC_EH_OK;
		}
	} else {
		THINGS_LOG_V_ERROR(THINGS_ERROR, TAG, "Invalid Device ID : %s", device_id);
	}

	return eh_result;
}

static OCEntityHandlerResult process_post_request(things_resource_s **target_res)
{
	OCEntityHandlerResult eh_result = OC_EH_ERROR;

	things_resource_s *target_resource = *target_res;

	if (strstr(target_resource->uri, URI_SEC) != NULL && strstr(target_resource->uri, URI_PROVINFO) != NULL) {
		// 1. Post request for the Easy-Setup reset
		eh_result = set_provisioning_info(target_resource);
	}
#ifndef __ST_THINGS_RTOS__
	else if (strstr(target_resource->uri, URI_INFORMATION) != NULL) {
		// X. Get request for the Access point list(Will be deprecated!!!!)
		eh_result = SetDeviceInfoResult(target_resource);
	} else if (strstr(target_resource->uri, URI_ACTIONS) != NULL) {
		// 2. Post request on the schedule resource
		THINGS_LOG_D(THINGS_DEBUG, TAG, "#####00 IN process_post_request pQuery : %s", target_resource->query);
		eh_result = SetActionResource(target_resource);
	} else if (strstr(target_resource->uri, URI_FILE) != NULL && strstr(target_resource->uri, URI_TRANSFER) != NULL) {
		// 3. Post request on the sharable file(s) to update the blob data
		eh_result = SetFileTransferResource(target_resource);
	} else if (strstr(target_resource->uri, URI_CONTENTS) != NULL && strstr(target_resource->uri, URI_RENDERER) != NULL) {
		// 4. Post request for the storing Blob data of files
		eh_result = SetContentsRendererMetadataResult(target_resource);
	} else if (strstr(target_resource->uri, URI_OIC) != NULL && strstr(target_resource->uri, URI_WK_MAINTENANCE) != NULL) {
		// 5. Post request for the trigger device maintenance functions
		eh_result = SetDeviceMaintenanceResult(target_resource);
	} else if (strstr(target_resource->uri, URI_BIXBY) != NULL) {
		// 6. Post request for handling bixby request
		eh_result = SetBixbyRequestResult(target_resource);
	}
#endif
	else {
#ifndef __ST_THINGS_RTOS__
		// 7. Post request on the other reosurce(s)
		int handled = 0;
		if (NULL != g_handle_res_list) {
			int iter = 0;
			for (iter = 0; iter < g_handle_res_cnt; iter++) {
				if (strstr(target_resource->uri, g_handle_res_list[iter])) {
					THINGS_LOG_D(THINGS_INFO, TAG, "Handling %s with things_resource_s Based CB", target_resource->uri);

					int ret = g_handle_req_cb(target_resource->req_type, target_resource);
					if (1 == ret) {
						eh_result = OC_EH_OK;
						handled = 1;
					} else {
						THINGS_LOG_D_ERROR(THINGS_ERROR, TAG, "Handled as ERROR from App.");
					}

					break;
				}
			}
		}
		if (handled == 0) {
			THINGS_LOG_D(THINGS_INFO, TAG, "Handling %s with things_info_s Converting Based CB", target_resource->uri);

			eh_result = PostResourceData(target_res);
		}
#else

		// Post request for application resources
		if (g_handle_request_set_cb != NULL) {
			int ret = g_handle_request_set_cb(target_resource);
			if (1 == ret) {
				eh_result = OC_EH_OK;
			} else {
				THINGS_LOG_D_ERROR(THINGS_ERROR, TAG, "Handled as ERROR from App.");
			}
		} else {
			THINGS_LOG_V(THINGS_ERROR, TAG, "g_handle_request_set_cb is not registered");
		}
#endif
	}

	return eh_result;
}

static OCEntityHandlerResult process_get_request(things_resource_s *target_resource)
{

	OCEntityHandlerResult eh_result = OC_EH_ERROR;

	char *device_id = NULL;

	device_id = strrchr(target_resource->uri, '/') + 1;
	THINGS_LOG_D(THINGS_DEBUG, TAG, "Get Device ID in Resources URI = %s", device_id);

	things_representation_s *rep = things_create_representation_inst(NULL);
	target_resource->things_set_representation(target_resource, rep);

	if (strstr(target_resource->uri, URI_SEC) != NULL && strstr(target_resource->uri, URI_PROVINFO) != NULL) {
		// 1. Get request for the Access point list
		eh_result = get_provisioning_info(target_resource);
	}
#ifndef __ST_THINGS_RTOS__
	else if (strstr(target_resource->uri, URI_INFORMATION) != NULL) {
		// X. Get request for the Access point list(Will be deprecated!!!!)
		eh_result = GetDeviceInfoResult(target_resource);
	} else if (strstr(target_resource->uri, URI_SEC) != NULL && strstr(target_resource->uri, URI_ACCESSPOINTLIST) != NULL) {
		// X. Get request for the Access point list(Will be deprecated!!!!)
		eh_result = get_ap_scan_result(target_resource);
	} else if (strstr(target_resource->uri, URI_FILE) != NULL && strstr(target_resource->uri, URI_LIST) != NULL) {
		// 3. Get request for the list of files which can be transfered to the Client
		eh_result = GetFileListResult(target_resource);
	} else if (strstr(target_resource->uri, URI_FILE) != NULL && strstr(target_resource->uri, URI_TRANSFER) != NULL) {
		// 4. Get request for the Blob data of files
		eh_result = GetFileBlobValueResult(target_resource);
	} else if (strstr(target_resource->uri, URI_ACTIONS) != NULL) {
		// 5. Get request for the list of schedules
		eh_result = GetActionResource(target_resource);
	} else if ((strstr(target_resource->uri, URI_CONTENTS) != NULL && strstr(target_resource->uri, URI_PROVIDER) != NULL)
			   || (strstr(target_resource->uri, URI_CONTENTS) != NULL && strstr(target_resource->uri, URI_RENDERER) != NULL)
			  ) {
		// 7. Get request for the Blob data of files
		eh_result = GetContentsMetadataResult(target_resource);
	} else if (strstr(target_resource->uri, URI_OIC) != NULL && strstr(target_resource->uri, URI_WK_MAINTENANCE) != NULL) {
		// 8. Get request for the device maintenance information
		eh_result = GetDeviceMaintenanceResult(target_resource);
	}
#endif
	else if (strstr(target_resource->uri, URI_SEC) != NULL && strstr(target_resource->uri, URI_ACCESSPOINTLIST) != NULL) {
		// X. Get request for the Access point list(Will be deprecated!!!!)
		eh_result = get_ap_scan_result(target_resource);
	} else if (strstr(target_resource->uri, OC_RSRVD_DEVICE_URI) != NULL || strstr(target_resource->uri, OC_RSRVD_PLATFORM_URI) != NULL) {
		// 9. Get request for the device maintenance information
		eh_result = get_device_or_platform_info_result(target_resource, device_id);
	} else {
#ifndef __ST_THINGS_RTOS__
		THINGS_LOG_D(THINGS_DEBUG, TAG, "HELLO WORLD");
		// 10. Get request on the other resources
		int handled = 0;
		if (NULL != g_handle_res_list) {
			THINGS_LOG_D(THINGS_DEBUG, TAG, "HELLO WORLD");
			int iter = 0;
			for (iter = 0; iter < g_handle_res_cnt; iter++) {
				THINGS_LOG_D(THINGS_DEBUG, TAG, "%s  : %s ", target_resource->uri, g_handle_res_list[iter]);
				if (strstr(target_resource->uri, g_handle_res_list[iter])) {
					THINGS_LOG_D(THINGS_INFO, TAG, "Handling %s with things_resource_s Based CB", target_resource->uri);
					int ret = g_handle_req_cb(target_resource->req_type, target_resource);
					if (1 == ret) {
						eh_result = OC_EH_OK;
						handled = 1;
					} else {
						THINGS_LOG_D_ERROR(THINGS_ERROR, TAG, "Handled as ERROR from App.");
					}

					break;
				}
			}
		}
		if (handled == 0) {
			THINGS_LOG_D(THINGS_INFO, TAG, "Handling %s with things_info_s Converting Based CB", target_resource->uri);

			eh_result = GetResourceData(target_resource);
		}
#else
		// Post request for application resources
		if (g_handle_request_get_cb != NULL) {
			int ret = g_handle_request_get_cb(target_resource);
			if (1 == ret) {
				eh_result = OC_EH_OK;
			} else {
				THINGS_LOG_D_ERROR(THINGS_ERROR, TAG, "Handled as ERROR from App.");
			}
		} else {
			THINGS_LOG_V(THINGS_ERROR, TAG, "g_handle_request_get_cb is not registered");
		}
#endif
	}

	return eh_result;
}

static bool is_can_not_response_case(things_resource_s *target_resource, OCMethod req_type, OCEntityHandlerResult eh_result)
{
	THINGS_LOG_D(THINGS_DEBUG, TAG, THINGS_FUNC_ENTRY);

	bool res = false;

	if (target_resource == NULL) {
		THINGS_LOG_ERROR(THINGS_ERROR, TAG, "Invalid argument.(target_resource=NULL)");
		return true;
	}

	THINGS_LOG_D(THINGS_DEBUG, TAG, "target_resource->uri=%s", target_resource->uri);
	if (strstr(target_resource->uri, URI_SEC) != NULL && strstr(target_resource->uri, URI_PROVINFO) != NULL) {
		if (req_type == OC_REST_POST && eh_result == OC_EH_SLOW) {
			res = true;
		}
	}

	THINGS_LOG_D(THINGS_DEBUG, TAG, "result = %d", res);
	THINGS_LOG_D(THINGS_DEBUG, TAG, THINGS_FUNC_EXIT);
	return res;
}

static void *message_handling_loop(void *param)
{
	THINGS_LOG_D(THINGS_DEBUG, TAG, THINGS_FUNC_ENTRY);

	int req_type = -1;
	// char* uri = NULL;
	things_resource_s *target_resource = NULL;
	OCEntityHandlerResult eh_result = OC_EH_ERROR;

	while (!g_quit_flag) {
		//THINGS_LOG_D(THINGS_INFO, TAG, "[Req.HDLoop] Looping.");

		//while(gOicReqQueue.length(&gOicReqQueue) > 0)
		while (gp_oic_req_queue->length(gp_oic_req_queue) > 0) {
			eh_result = OC_EH_ERROR;

			//target_resource = gOicReqQueue.pop(&gOicReqQueue, &req_type);
			target_resource = gp_oic_req_queue->pop(gp_oic_req_queue, &req_type);
			if (NULL == target_resource) {
				THINGS_LOG_D(THINGS_DEBUG, TAG, "Request Item is NULL.");
				continue;
			}
			// RequestInfo* info = CreateRequestInfo(req_type, 0,
			//                             target_resource->request_handle,
			//                             target_resource->resource_handle);

			// duplicate_string (info->frameId, &target_resource->cmd_id);

			THINGS_LOG_D(THINGS_DEBUG, TAG, "Request Handle : %x, Resource Handle : %x", target_resource->request_handle, target_resource->resource_handle);

			// THINGS_LOG_D(THINGS_DEBUG, TAG, "Request on cmd_id. %s",
			//                         target_resource->cmd_id);
			target_resource->req_type = req_type;

			if (req_type == OC_REST_GET) {
				THINGS_LOG_V(THINGS_INFO, TAG, "\t\tReq. : GET on %s", target_resource->uri);
				THINGS_LOG_V(THINGS_INFO, TAG, "\t\tQuery: %s", target_resource->query);
				eh_result = process_get_request(target_resource);

			} else if (req_type == OC_REST_POST) {
				THINGS_LOG_V(THINGS_INFO, TAG, "\t\tReq. : POST on  %s", target_resource->uri);
				THINGS_LOG_V(THINGS_INFO, TAG, "\t\tQuery: %s", target_resource->query);
				eh_result = process_post_request(&target_resource);
			} else {
				THINGS_LOG_V_ERROR(THINGS_ERROR, TAG, " Invalid Request Received : %d", req_type);
			}
			THINGS_LOG_D(THINGS_DEBUG, TAG, " @@@@@ target_resource ->size : %d", target_resource->size);
			// THINGS_LOG_D(THINGS_DEBUG, TAG, " @@@@@ target_resource ->cmd_id : %s", target_resource->cmd_id);

			if (is_can_not_response_case(target_resource, req_type, eh_result) == false) {
				if (eh_result != OC_EH_OK && eh_result != OC_EH_SLOW) {
					THINGS_LOG_V_ERROR(THINGS_ERROR, TAG, "Handing Request Failed, Sending ERROR Response");

					things_resource_s *temp = g_builder->get_resource(g_builder, target_resource->uri);
					const char *rt = temp->things_get_res_type(temp, 0);
					if (0 == strncmp(rt, SEC_RTYPE_TEMPERATURE, strlen(SEC_RTYPE_TEMPERATURE)) || 0 == strncmp(rt, OIC_RTYPE_TEMPERATURE, strlen(OIC_RTYPE_TEMPERATURE))) {
						OCRepPayload *rep_payload = target_resource->things_get_rep_payload(target_resource);
						send_response(target_resource->request_handle, target_resource->resource_handle, OC_EH_ERROR, target_resource->uri, rep_payload);
					} else {
						send_response(target_resource->request_handle, target_resource->resource_handle, eh_result, target_resource->uri, NULL);
					}
				} else {
					OCRepPayload *rep_payload = target_resource->things_get_rep_payload(target_resource);

					eh_result = send_response(target_resource->request_handle,	// reqInfo->reqHandle,
											  target_resource->resource_handle,	// reqInfo->resHandle,
											  target_resource->error, target_resource->uri, rep_payload);

					/*! Added by st_things for memory Leak fix
					 */
					//if(OC_EH_ERROR == eh_result)
					//{
					OCPayloadDestroy((OCPayload *) rep_payload);
					rep_payload = NULL;
					//}
				}
			}
			// Need to design How to release memory allocated for the things_resource_s list.
			things_release_resource_inst(target_resource);

			usleep(100 * 1000);
		}						// End Of While Loop

		things_control_queue_empty();

		usleep(100 * 1000);
	}							// End Of While Loop
	THINGS_LOG_D(THINGS_DEBUG, TAG, "[Req.HDLoop] Leaving loop...");

	return NULL;
}

void notify_result_of_reset(things_resource_s *target_resource, bool result)
{
	THINGS_LOG(THINGS_DEBUG, TAG, THINGS_FUNC_ENTRY);

	OCEntityHandlerResult eh_result = OC_EH_ERROR;

	if (target_resource == NULL) {
		THINGS_LOG(THINGS_DEBUG, TAG, "Not exist remote-client.");
		return;
	}

	if (result == true) {		// reset Success.
		OCRepPayload *rep_payload = target_resource->things_get_rep_payload(target_resource);

		eh_result = send_response(target_resource->request_handle,	// reqInfo->reqHandle,
								  target_resource->resource_handle,	// reqInfo->resHandle,
								  target_resource->error, target_resource->uri, rep_payload);

		/*! Added by st_things for memory Leak fix
		 */
//        if(OC_EH_ERROR == eh_result)
//        {
		OCPayloadDestroy((OCPayload *) rep_payload);
		rep_payload = NULL;
//        }
	} else {
		THINGS_LOG_V_ERROR(THINGS_ERROR, TAG, "Handing Request Failed, Sending ERROR Response");

		send_response(target_resource->request_handle, target_resource->resource_handle, eh_result, target_resource->uri, NULL);
	}

	things_release_resource_inst(target_resource);

	THINGS_LOG(THINGS_DEBUG, TAG, THINGS_FUNC_EXIT);
}

int notify_things_observers(const char *uri, const char *query)
{
	THINGS_LOG_D(THINGS_DEBUG, TAG, THINGS_FUNC_ENTRY);

	int res = 0;

	THINGS_LOG_D(THINGS_DEBUG, TAG, "uri = %s", uri);
	if (NULL != uri) {
		int remainLen = MAX_RESOURCE_LEN - 1;
		char tempUri[MAX_RESOURCE_LEN] = { 0 };

		if (NULL != g_get_notify_obs_uri) {
			char *temp = g_get_notify_obs_uri(uri, query);
			if (NULL != temp) {
				things_strncpy(tempUri, temp, remainLen);
				remainLen -= strnlen(tempUri, MAX_RESOURCE_LEN - 1);
				things_free(temp);
			}
		}

		if (strnlen(tempUri, MAX_RESOURCE_LEN - 1) < 1) {
			things_strncpy(tempUri, uri, remainLen);
			remainLen -= strnlen(tempUri, MAX_RESOURCE_LEN - 1);
		}

		THINGS_LOG_D(THINGS_DEBUG, TAG, "%s resource notifies to observers.", tempUri);

		for (int iter = 0; iter < g_builder->res_num; iter++) {
			if (strstr(g_builder->gres_arr[iter]->uri, tempUri) != NULL) {
				OCStackResult ret2 = OCNotifyAllObservers((OCResourceHandle) g_builder->gres_arr[iter]->resource_handle,
									 OC_MEDIUM_QOS);

				THINGS_LOG_D(THINGS_DEBUG, TAG, "%s resource has notified to observers.", g_builder->gres_arr[iter]->uri);

				if (OC_STACK_OK == ret2) {
					THINGS_LOG(THINGS_INFO, TAG, "Success: Sent notification to Observers");
				} else {
					THINGS_LOG_D(THINGS_INFO, TAG, "Failed: No Observers to notify : %d ", ret2);
				}
				res = 1;
				break;
			}
		}

#ifndef __ST_THINGS_RTOS__
		// if(res)
		{
			// Need to refactor later support the number bigger then 9
			char *device_num = strrchr(uri, '/');
			char res_uri[128] = { 0 };

			memset(res_uri, 0, (size_t) 128);
			strncat(res_uri, URI_DEVICE_COL, strlen(URI_DEVICE_COL));
			strncat(res_uri, device_num, strlen(device_num));

			THINGS_LOG_D(THINGS_DEBUG, TAG, "Target Collection URI : %s", res_uri);

			things_resource_s *temp = g_builder->get_resource(g_builder, res_uri);
			if (temp) {
				OCStackResult ret3 = OCNotifyAllObservers((OCResourceHandle) temp->resource_handle,
									 OC_MEDIUM_QOS);

				if (OC_STACK_OK == ret3) {
					THINGS_LOG(THINGS_INFO, TAG, "Sent notification to Observers");
				} else {
					THINGS_LOG_D(THINGS_INFO, TAG, "No Observers to notify : %d ", ret3);
				}
			}
		}
#endif

	}

	THINGS_LOG_D(THINGS_DEBUG, TAG, THINGS_FUNC_EXIT);
	return res;
}

OCEntityHandlerResult handle_message(things_resource_s *target_resource)
{
	OCEntityHandlerResult eh_result = OC_EH_ERROR;

	if (NULL == target_resource) {
		THINGS_LOG_D(THINGS_DEBUG, TAG, "Request Item is NULL.");
		return OC_EH_ERROR;
	}

	THINGS_LOG_D(THINGS_DEBUG, TAG, "Request Handle : %x, Resource Handle : %x", target_resource->request_handle, target_resource->resource_handle);

	// THINGS_LOG_D(THINGS_DEBUG, TAG, "Request on cmd_id. %s",
	//                         target_resource->cmd_id);

	if (target_resource->req_type == OC_REST_GET) {
		THINGS_LOG_V(THINGS_INFO, TAG, "\t\tReq. : GET on %s", target_resource->uri);
		THINGS_LOG_V(THINGS_INFO, TAG, "\t\tQuery: %s", target_resource->query);
		eh_result = process_get_request(target_resource);

	} else if (target_resource->req_type == OC_REST_POST) {
		THINGS_LOG_V(THINGS_INFO, TAG, "\t\tReq. : POST on  %s", target_resource->uri);
		THINGS_LOG_V(THINGS_INFO, TAG, "\t\tQuery: %s", target_resource->query);
		eh_result = process_post_request(&target_resource);
	} else {
		THINGS_LOG_V_ERROR(THINGS_ERROR, TAG, " Invalid Request Received : %d", target_resource->req_type);
	}
	THINGS_LOG_D(THINGS_DEBUG, TAG, " @@@@@ target_resource ->size : %d", target_resource->size);
	// THINGS_LOG_D(THINGS_DEBUG, TAG, " @@@@@ target_resource ->cmd_id : %s", target_resource->cmd_id);

	if (is_can_not_response_case(target_resource, target_resource->req_type, eh_result) == false) {
		if (eh_result != OC_EH_OK && eh_result != OC_EH_SLOW) {
			THINGS_LOG_V_ERROR(THINGS_ERROR, TAG, "Handing Request Failed, Sending ERROR Response");

			things_resource_s *temp = g_builder->get_resource(g_builder, target_resource->uri);
			const char *rt = temp->things_get_res_type(temp, 0);
			if (0 == strncmp(rt, SEC_RTYPE_TEMPERATURE, strlen(SEC_RTYPE_TEMPERATURE)) || 0 == strncmp(rt, OIC_RTYPE_TEMPERATURE, strlen(OIC_RTYPE_TEMPERATURE))) {
				OCRepPayload *rep_payload = target_resource->things_get_rep_payload(target_resource);
				send_response(target_resource->request_handle, target_resource->resource_handle, OC_EH_ERROR, target_resource->uri, rep_payload);
			} else {
				send_response(target_resource->request_handle, target_resource->resource_handle, eh_result, target_resource->uri, NULL);
			}
			eh_result = OC_EH_OK;
		} else {
			OCRepPayload *rep_payload = target_resource->things_get_rep_payload(target_resource);

			eh_result = send_response(target_resource->request_handle,	// reqInfo->reqHandle,
									  target_resource->resource_handle,	// reqInfo->resHandle,
									  target_resource->error, target_resource->uri, rep_payload);

			/*! Added by st_things for memory Leak fix
			 */
			//if(OC_EH_ERROR == eh_result)
			//{
			OCPayloadDestroy((OCPayload *) rep_payload);
			rep_payload = NULL;
			//}
		}
	}
	//  Need to design How to release memory allocated for the things_resource_s list.
	things_release_resource_inst(target_resource);

	return eh_result;
}

OCEntityHandlerResult entity_handler(OCEntityHandlerFlag flag, OCEntityHandlerRequest *entity_handler_request, void *callback)
{
	THINGS_LOG_D(THINGS_INFO, TAG, THINGS_FUNC_ENTRY);
	OCEntityHandlerResult eh_result = OC_EH_ERROR;

	// Validate pointer
	if (!entity_handler_request) {
		THINGS_LOG_ERROR(THINGS_ERROR, TAG, "Invalid request pointer");
		return eh_result;
	}

	const char *uri = OCGetResourceUri(entity_handler_request->resource);

	// Observe Request Handling
	if (flag & OC_OBSERVE_FLAG) {
		if (OC_OBSERVE_REGISTER == entity_handler_request->obsInfo.action) {
			THINGS_LOG_V(THINGS_INFO, TAG, "Observe Requset on : %s ", uri);
			// 1. Check whether it's Observe request on the Collection Resource
			if (NULL != strstr(uri, URI_DEVICE_COL)) {
				//2. Check whether the query carriese the if=oic.if.b
				if ((strstr(entity_handler_request->query, OIC_INTERFACE_BATCH) == NULL)) {
					//3. If not batch then error
					THINGS_LOG_V_ERROR(THINGS_ERROR, TAG, "Collection Resource Requires BATCH for Observing : %s", entity_handler_request->query);
					eh_result = OC_EH_BAD_REQ;
					goto RESPONSE_ERROR;
				} else {
					THINGS_LOG_V_ERROR(THINGS_ERROR, TAG, "Receiving Observe Request Collection Resource");
				}
			}
		} else if (OC_OBSERVE_DEREGISTER == entity_handler_request->obsInfo.action) {
			THINGS_LOG_V(THINGS_INFO, TAG, "CancelObserve Request on : %s", uri);
		}
	}
	// Get/Post Request Handling
	if (flag & OC_REQUEST_FLAG) {
		THINGS_LOG_D(THINGS_INFO, TAG, "Req. URI  : %s", uri);
		THINGS_LOG_D(THINGS_INFO, TAG, "Req. TYPE : %d", entity_handler_request->method);

		if (things_get_reset_mask(RST_CONTROL_MODULE_DISABLE) == true) {
			THINGS_LOG(THINGS_INFO, TAG, "Control Module Disable.");
			eh_result = OC_EH_NOT_ACCEPTABLE;
		} else if ((OC_REST_GET == entity_handler_request->method)
				   || (OC_REST_POST == entity_handler_request->method)) {
			THINGS_LOG_D(THINGS_INFO, TAG, "Request Handle : %x, Resource Handle : %x", entity_handler_request->requestHandle, entity_handler_request->resource);
			if (verify_request(entity_handler_request, uri, (int)entity_handler_request->method) > 0) {
				//  IoTivity Stack Destroy the payload after receving result from this function
				//       Therefore, we need to copy/clone the payload for the later use..
				things_resource_s *resource = things_create_resource_inst(entity_handler_request->requestHandle,
											  entity_handler_request->resource,
											  entity_handler_request->query,
											  entity_handler_request->payload);
				resource->things_set_dev_addr(resource, &(entity_handler_request->devAddr));
				resource->req_type = entity_handler_request->method;
				//resource->set_uri(resource, uri);

//                THINGS_LOG_D(THINGS_DEBUG, TAG, "About to Queue a received Request~!!!!");
//
//                //gOicReqQueue.push(&gOicReqQueue, resource, entity_handler_request->method);
//                gp_oic_req_queue->push(gp_oic_req_queue, resource, entity_handler_request->method);
//                eh_result = OC_EH_SLOW;
				eh_result = handle_message(resource);
			} else {
				THINGS_LOG_V_ERROR(THINGS_ERROR, TAG, "Invalid Query in the Request : %s", entity_handler_request->query);
			}
		} else if (OC_REST_DELETE == entity_handler_request->method || OC_REST_PUT == entity_handler_request->method) {
			THINGS_LOG_ERROR(THINGS_ERROR, TAG, "Delete/PUT Req. Handling is not supported Yet");
		} else {
			THINGS_LOG_D(THINGS_DEBUG, TAG, "Received unsupported method from client");
		}

	}

RESPONSE_ERROR:

	if (eh_result != OC_EH_SLOW && eh_result != OC_EH_OK) {
		//  If the result is OC_EH_ERROR, the stack will remove the
		//       received request in the stack.
		//       If the reusult is OC_EH_SLOW, then the request will be
		//       stored in the stack till the response goes out
		eh_result = send_response(entity_handler_request->requestHandle, entity_handler_request->resource, eh_result, uri, NULL);
		// Currently this code will not do anything...
		//      Need to refactor later..
	}

	THINGS_LOG_D(THINGS_DEBUG, TAG, THINGS_FUNC_EXIT);

	return eh_result;
}

void init_handler()
{
	g_quit_flag = false;

}

void deinit_handler()
{
	g_quit_flag = true;

	int iter = 0;
	if (g_handle_res_list != NULL) {
		for (iter = 0; iter < g_handle_res_cnt; iter++) {
			if (g_handle_res_list[iter] != NULL) {
				things_free(g_handle_res_list[iter]);
				g_handle_res_list[iter] = NULL;
			}
		}
		things_free(g_handle_res_list);
		g_handle_res_list = NULL;
	}
	g_handle_res_cnt = 0;
}

struct things_request_handler_s *get_handler_instance()
{
	struct things_request_handler_s *handler = (things_request_handler_s *) things_malloc(sizeof(things_request_handler_s));

	if (handler == NULL) {
		THINGS_LOG_ERROR(THINGS_ERROR, TAG, "Not Enough Memory");
		return NULL;
	} else {
		handler->entity_handler = &entity_handler;
		handler->init_module = &init_handler;
		handler->deinit_module = &deinit_handler;
		handler->notify_things_observers = &notify_things_observers;
		return handler;
	}
}

void release_handler_instance(struct things_request_handler_s *handler)
{
	if (handler) {
		handler->deinit_module();
		things_free(handler);
	}
}

int register_stop_softap_cb(stop_softap_func_type func)
{
	if (NULL != func) {
		g_stop_soft_ap_cb = func;
		return 1;
	} else {
		return 0;
	}
}

int register_handle_request_func(handle_request_func_type get_func, handle_request_func_type set_func)
{
	if (NULL != get_func && NULL != set_func) {
		g_handle_request_get_cb = get_func;
		g_handle_request_set_cb = set_func;
	} else {
		return 0;
	}
	return 1;
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.9.1"/>
<title>V8 API Reference Guide for node.js v0.11.2: v8::CpuProfiler Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

V8 API Reference Guide for node.js v0.11.2

Main Page

Namespaces

Classes

Files

Examples

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Hierarchy

Class Members

v8

CpuProfiler

Public Member Functions |
List of all members

v8::CpuProfiler Class Reference

#include <v8-profiler.h>

Public Member Functions

 	V8_DEPRECATED (static int GetProfilesCount())

int 	GetProfileCount ()

 	V8_DEPRECATED (static const CpuProfile *GetProfile(int index, Handle< Value > security_token=Handle< Value >()))

const CpuProfile * 	GetCpuProfile (int index, Handle< Value > security_token=Handle< Value >())

 	V8_DEPRECATED (static const CpuProfile *FindProfile(unsigned uid, Handle< Value > security_token=Handle< Value >()))

const CpuProfile * 	FindCpuProfile (unsigned uid, Handle< Value > security_token=Handle< Value >())

 	V8_DEPRECATED (static void StartProfiling(Handle< String > title, bool record_samples=false))

void 	StartCpuProfiling (Handle< String > title, bool record_samples=false)

 	V8_DEPRECATED (static const CpuProfile *StopProfiling(Handle< String > title, Handle< Value > security_token=Handle< Value >()))

const CpuProfile * 	StopCpuProfiling (Handle< String > title, Handle< Value > security_token=Handle< Value >())

 	V8_DEPRECATED (static void DeleteAllProfiles())

void 	DeleteAllCpuProfiles ()

Detailed Description

Interface for controlling CPU profiling. Instance of the profiler can be retrieved using v8::Isolate::GetCpuProfiler.

Member Function Documentation

          void v8::CpuProfiler::DeleteAllCpuProfiles
          (
          	)

Deletes all existing profiles, also cancelling all profiling activity. All previously returned pointers to profiles and their contents become invalid after this call.

          const CpuProfile* v8::CpuProfiler::FindCpuProfile
          (
          unsigned
          uid,

          Handle< Value >
          security_token = Handle< Value >()

          )

Returns a profile by uid.

          const CpuProfile* v8::CpuProfiler::GetCpuProfile
          (
          int
          index,

          Handle< Value >
          security_token = Handle< Value >()

          )

Returns a profile by index.

          int v8::CpuProfiler::GetProfileCount
          (
          	)

Returns the number of profiles collected (doesn't include profiles that are being collected at the moment of call.)

          void v8::CpuProfiler::StartCpuProfiling
          (
          Handle< String >
          title,

          bool
          record_samples = false

          )

Starts collecting CPU profile. Title may be an empty string. It is allowed to have several profiles being collected at once. Attempts to start collecting several profiles with the same title are silently ignored. While collecting a profile, functions from all security contexts are included in it. The token-based filtering is only performed when querying for a profile.

|record_samples| parameter controls whether individual samples should be recorded in addition to the aggregated tree.

          const CpuProfile* v8::CpuProfiler::StopCpuProfiling
          (
          Handle< String >
          title,

          Handle< Value >
          security_token = Handle< Value >()

          )

Stops collecting CPU profile with a given title and returns it. If the title given is empty, finishes the last profile started.

          v8::CpuProfiler::V8_DEPRECATED
          (
          static int
          GetProfilesCount()	)

A note on security tokens usage. As scripts from different origins can run inside a single V8 instance, it is possible to have functions from different security contexts intermixed in a single CPU profile. To avoid exposing function names belonging to other contexts, filtering by security token is performed while obtaining profiling results.Deprecated. Use GetProfileCount instead.

          v8::CpuProfiler::V8_DEPRECATED
          (
          static const CpuProfile *
          GetProfileint index, Handle< Value > security_token=Handle< Value >()	)

Deprecated. Use GetCpuProfile instead.

          v8::CpuProfiler::V8_DEPRECATED
          (
          static const CpuProfile *
          FindProfileunsigned uid, Handle< Value > security_token=Handle< Value >()	)

Deprecated. Use FindProfile instead.

          v8::CpuProfiler::V8_DEPRECATED
          (
          static void
          StartProfilingHandle< String > title, bool record_samples=false	)

Deprecated. Use StartCpuProfiling instead.

          v8::CpuProfiler::V8_DEPRECATED
          (
          static const CpuProfile *
          StopProfilingHandle< String > title, Handle< Value > security_token=Handle< Value >()	)

Deprecated. Use StopCpuProfiling instead.

          v8::CpuProfiler::V8_DEPRECATED
          (
          static void
          DeleteAllProfiles()	)

Deprecated. Use DeleteAllCpuProfiles instead.

The documentation for this class was generated from the following file:

deps/v8/include/v8-profiler.h

<address class="footer">
Generated on Tue Aug 11 2015 23:45:56 for V8 API Reference Guide for node.js v0.11.2 by

 1.8.9.1
</address>


text:
#include <stdlib.h>
#include <assert.h>
#include "libpng/png.h"
#include "graphics/FsImage2D.h"
#include "sys/io/FsVFS.h"

#define FS_PNG_SIG_BITS 8

NS_FS_BEGIN

static bool fs_png_check(const unsigned char* buf,unsigned int len)
{
	return png_sig_cmp((png_byte*)buf,(png_size_t)0,len)==0;
}

static void fs_png_read_data(png_structp png_ptr,png_bytep data,png_size_t length)
{
	png_size_t check;
	FsFile* file=(FsFile*)png_get_io_ptr(png_ptr);
	check=file->read(data,length);
	if(check!=length)
	{
		png_error(png_ptr,"Read Error");
	}
}
static void fs_png_flush(png_structp png_ptr)
{
}

static void fs_png_write_data(png_structp png_ptr,png_bytep data,png_size_t length)
{
	png_size_t check;

	FsFile* file=(FsFile*)png_get_io_ptr(png_ptr);
	check=file->write(data,length);

	if(check!=length)
	{
		FS_TRACE_WARN("Write Error,Except %d Bytes,But Only %d Bytes Write",length,check);
		png_error(png_ptr,"write Error");
	}
}

static void fs_png_cexcept_error(png_structp png_ptr,png_const_charp msg)
{
	if(png_ptr)
	{
		FS_TRACE_WARN("libpng error: %s\n",msg);
	}

}

Image2D* FsUtil_PngReader(FsFile* file)
{
	png_structp png_ptr=NULL;
	png_infop info_ptr=NULL;

	png_uint_32 width=0,height=0;
	int bit_depth=0, color_type=0;
	double gamma;
	png_uint_32 channels=0;
	png_uint_32 row_bytes=0;

	png_byte*  image_data=NULL;
	png_byte** row_pointers=NULL;
	png_uint_32 i,col,row;

	unsigned char sig_bytes[FS_PNG_SIG_BITS];
	file->read(sig_bytes,FS_PNG_SIG_BITS);
	if(!fs_png_check(sig_bytes,FS_PNG_SIG_BITS))
	{
		FS_TRACE_WARN("File Is Not Png Format");
		return NULL;
	}

	png_ptr=png_create_read_struct(PNG_LIBPNG_VER_STRING,NULL,
			(png_error_ptr)fs_png_cexcept_error,(png_error_ptr)NULL);

	if(!png_ptr)
	{
		FS_TRACE_WARN("Can't Alloc Memory For Png_ptr");
		return NULL;
	}
	info_ptr=png_create_info_struct(png_ptr);
	if(!info_ptr)
	{
		png_destroy_read_struct(&png_ptr,NULL,NULL);
		FS_TRACE_WARN("Can't Alloc Memory For Png_info");
		return NULL;
	}

	if(setjmp(png_jmpbuf(png_ptr)))
	{
		png_destroy_read_struct(&png_ptr,&info_ptr,NULL);
		if(image_data)
		{
			free(image_data);
			image_data=NULL;

		}
		if(row_pointers)
		{
			free(row_pointers);
			image_data=NULL;
		}
		FS_TRACE_WARN("Load Png Error");
		return NULL;
	}

	/* set custom io read func */
	png_set_read_fn(png_ptr,(png_voidp)file,fs_png_read_data);

	/* already read the 8 signature byte */
	png_set_sig_bytes(png_ptr,FS_PNG_SIG_BITS);

	/* read  the file information */
	png_read_info(png_ptr,info_ptr);

	/* get size and bit-depth of the PNG-image */
	png_get_IHDR(png_ptr,info_ptr,
			&width,&height,&bit_depth,&color_type,
			NULL,NULL,NULL);

	/* downgrade 16-bit images to 8 bit */
	if(bit_depth==16)
	{
		png_set_strip_16(png_ptr);
	}

	/* transform paletted image into full-color rgb*/
	if(color_type==PNG_COLOR_TYPE_PALETTE)
	{
		png_set_expand(png_ptr);
	}

	/* expand imaged to bit-depth 8 (only applicable for grayscale images*/
	if(color_type==PNG_COLOR_TYPE_GRAY&&bit_depth<8)
	{
		png_set_expand(png_ptr);
	}
	/* transform transparency maps into full alpha-channel */
	if(png_get_valid(png_ptr,info_ptr,PNG_INFO_tRNS))
	{
		png_set_tRNS_to_alpha(png_ptr);
	}

	/* transform grayscale images into full-color*/
	if(color_type==PNG_COLOR_TYPE_GRAY||
			color_type==PNG_COLOR_TYPE_GRAY_ALPHA)
	{
		png_set_gray_to_rgb(png_ptr);
	}

	/* only if file has a file gamma, we do a correction */
	if(png_get_gAMA(png_ptr,info_ptr,&gamma))
	{
		png_set_gamma(png_ptr,(double)2.2,gamma);
	}

	/* all transformations have been registered; now update info_ptr data,
	 * get row_bytes and channels,and allocate image memory */
	png_read_update_info(png_ptr,info_ptr);

	/* get the new color-type and bit-depth(after expansion/stripping)*/
	png_get_IHDR(png_ptr,info_ptr,&width,&height,&bit_depth,&color_type,
			NULL,NULL,NULL);

	//channels=png_get_channels(png_ptr,info_ptr);

	if (color_type==PNG_COLOR_TYPE_RGB)
	{
		channels=3;
	}
	else if (color_type==PNG_COLOR_TYPE_RGB_ALPHA)
	{
		channels=4;
	}
	else
	{
		channels=0;
		FS_TRACE_WARN("Channels Unkowns");
		png_error(png_ptr,"Channels Unkowns");
	}

	/* row_bytes=(width * channels * bit_depth/8) */
	row_bytes=png_get_rowbytes(png_ptr,info_ptr);

	assert(bit_depth==8);
	assert(row_bytes==width*channels*bit_depth/8);

	image_data=(png_bytep) malloc(row_bytes*height*sizeof(png_byte));
	if(image_data==NULL)
	{
		FS_TRACE_WARN("Can't Alloc Memory For Image Data");
		png_error(png_ptr,"Can't Alloc Memory For image_data");

	}

	row_pointers=(png_bytepp) malloc(height* sizeof(png_bytep));
	if(row_pointers==NULL)
	{
		FS_TRACE_WARN("Can't Alloc Memory For Row Pointers");
		png_error(png_ptr,"Can't Alloc Memory For row_pointers");
	}

	for(i=0;i<height;i++)
	{
		row_pointers[i]=image_data+i*row_bytes;
	}

	/* now read the whole image */
	png_read_image(png_ptr,row_pointers);

	/* read rest of file and get additional chunks in info_ptr*/
	png_read_end(png_ptr,NULL);

	/* clean up */
	free(row_pointers);
	row_pointers=NULL;
	png_destroy_read_struct(&png_ptr,&info_ptr,(png_infopp)NULL);

	Image2D* img=NULL;
	if(channels==3)
	{
		img=Image2D::create(width,height,Image2D::PIXEL_RGB888);
	}
	else
	{
		assert(channels==4);
		img=Image2D::create(width,height,Image2D::PIXEL_RGBA8888);
	}

	//FS_TRACE_WARN("width=%d,height=%d,channels=%d",width,height,channels);

	png_bytep src=image_data;

	for(row=0;row<height;row++)
	{
		for(col=0;col<width;col++)
		{
			unsigned char v[4]={0,0,0,255};
			for(i=0;i<channels;i++)
			{
				v[i]=*src++;
			}
			img->setColor(col,row,Color(v[0],v[1],v[2],v[3]));
		}
	}
	if(image_data)
	{
		free(image_data);
	}
	return img;
}

int FsUtil_PngWriter(FsFile* file,Image2D* img)
{
	png_uint_32 width=0,height=0,col=0,row=0,row_bytes=0;
	png_uint_32 bit_depth=0,i=0,channels=0;
	png_int_32	color_type=0;

	png_structp png_ptr=NULL;
	png_infop info_ptr=NULL;

	png_byte* png_pixels=NULL;
	png_byte** row_pointers=NULL;

	png_byte* pix_ptr=NULL;

	/* create png_struct */
	png_ptr=png_create_write_struct(PNG_LIBPNG_VER_STRING,NULL,
			(png_error_ptr)fs_png_cexcept_error,(png_error_ptr)NULL);
	if(!png_ptr)
	{
		FS_TRACE_WARN("Can't Alloc Memory For png_ptr");
		return -1;
	}

	/* create png_info_struct */
	info_ptr=png_create_info_struct(png_ptr);
	if(!info_ptr)
	{
		FS_TRACE_WARN("Can't Alloc Memory For info_ptr");
		png_destroy_write_struct(&png_ptr,(png_infopp)NULL);
		return -1;
	}

	/* set long jmp */
	if(setjmp(png_jmpbuf(png_ptr)))
	{
		if(png_pixels)
		{
			free(png_pixels);
		}
		if(row_pointers)
		{
			free(row_pointers);
		}
		png_destroy_write_struct(&png_ptr,&info_ptr);
		return -1;
	}

	/* get color_type,channels,bit_depth*/
	if(img->getPixelFormat()==Image2D::PIXEL_RGB888)
	{
		color_type=PNG_COLOR_TYPE_RGB;
		channels=3;
		bit_depth=8;
	}
	else  if(img->getPixelFormat()==Image2D::PIXEL_RGBA8888)
	{
		color_type=PNG_COLOR_TYPE_RGB_ALPHA;
		channels=4;
		bit_depth=8;
	}
	else
	{
		png_error(png_ptr,"Can't Handle Image2D PixelFormat");
	}

	width=img->getWidth();
	height=img->getHeight();
	row_bytes=width*channels*(bit_depth/8);

	png_pixels=(png_byte*) malloc(row_bytes*height*sizeof(png_byte));
	if(png_pixels==NULL)
	{
		png_error(png_ptr,"Can't Alloc Memory For png_pixels");
	}

	pix_ptr=png_pixels;
	for(row=0;row<height;row++)
	{
		for(col=0;col<width;col++)
		{
			Color c=img->getColor(col,row);
			png_byte  v[4]={c.r,c.g,c.b,c.a};
			for(i=0;i<channels;i++)
			{
				*pix_ptr++=v[i];
			}
		}
	}

	/* set io func */
	png_set_write_fn(png_ptr,(png_voidp)file,fs_png_write_data,fs_png_flush);

	/* set png infomation */
	png_set_IHDR(png_ptr,info_ptr,width,height,bit_depth,color_type,
			PNG_INTERLACE_NONE,PNG_COMPRESSION_TYPE_BASE,
			PNG_FILTER_TYPE_BASE);

	/* write the file header information */
	png_write_info(png_ptr,info_ptr);

	/* allocate memory for row_pointers */
	row_pointers=(png_bytepp) malloc(height* sizeof(png_bytep));
	if(row_pointers==NULL)
	{
		png_error(png_ptr,"Can't Alloc Memory For row_pointers");
	}

	for(i=0;i<height;i++)
	{
		row_pointers[i]=png_pixels+i*row_bytes;
	}

	/* write out the entire image data in one call */
	png_write_image(png_ptr,row_pointers);

	/* write the additional chuncks to the png file */
	png_write_end(png_ptr,info_ptr);

	png_destroy_write_struct(&png_ptr,&info_ptr);
	if(row_pointers)
	{
		free(row_pointers);
	}
	if(png_pixels)
	{
		free(png_pixels);
	}

	return 0;
}

Image2D* FsUtil_PngReader(const char* filename)
{
	FsFile* file=VFS::createFile(filename);
	if(file==NULL)
	{
		FS_TRACE_WARN("Can't Open File(%s) For Image2D",filename);
		return NULL;
	}
	Image2D* ret=FsUtil_PngReader(file);
	file->decRef();
	return ret;
}

bool FsUtil_CheckPng(FsFile* file)
{
	int length=file->getLength();

	if(length< 8 )
	{
		return false;
	}

	uint8_t data[8];
	file->read(data,8);
	file->seek(0,FsFile::FS_SEEK_SET);

	return fs_png_check(data,8);
}

NS_FS_END


text:
[![Join the chat at https://gitter.im/angular/angular-cli](https://badges.gitter.im/angular/angular-cli.svg)](https://gitter.im/angular/angular-cli?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

[![Build Status][travis-badge]][travis-badge-url]
[![Dependency Status][david-badge]][david-badge-url]
[![devDependency Status][david-dev-badge]][david-dev-badge-url]
[![npm][npm-badge]][npm-badge-url]

Prototype of a CLI for Angular applications based on the [ember-cli](http://www.ember-cli.com/) project.

## Note

This project is very much still a work in progress.

The CLI is now in beta.
If you wish to collaborate while the project is still young, check out [our issue list](https://github.com/angular/angular-cli/issues).

Before submitting new issues, have a look at [issues marked with the `type: faq` label](https://github.com/angular/angular-cli/issues?utf8=%E2%9C%93&q=is%3Aissue%20label%3A%22type%3A%20faq%22%20).

## Webpack update

We changed the build system between beta.10 and beta.14, from SystemJS to Webpack.
And with it comes a lot of benefits.
To take advantage of these, your app built with the old beta will need to migrate.

You can update your `beta.10` projects to `beta.14` by following [these instructions](https://github.com/angular/angular-cli/wiki/Upgrading-from-Beta.10-to-Beta.14).

## Prerequisites

Both the CLI and generated project have dependencies that require Node 4 or higher, together
with NPM 3 or higher.

## Table of Contents

* [Installation](#installation)
* [Usage](#usage)
* [Generating a New Project](#generating-and-serving-an-angular2-project-via-a-development-server)
* [Generating Components, Directives, Pipes and Services](#generating-components-directives-pipes-and-services)
* [Generating a Route](#generating-a-route)
* [Creating a Build](#creating-a-build)
* [Build Targets and Environment Files](#build-targets-and-environment-files)
* [Base tag handling in index.html](#base-tag-handling-in-indexhtml)
* [Bundling](#bundling)
* [Running Unit Tests](#running-unit-tests)
* [Running End-to-End Tests](#running-end-to-end-tests)
* [Proxy To Backend](#proxy-to-backend)
* [Deploying the App via GitHub Pages](#deploying-the-app-via-github-pages)
* [Linting code](#linting-code)
* [Commands autocompletion](#commands-autocompletion)
* [Project assets](#project-assets)
* [Global styles](#global-styles)
* [CSS preprocessor integration](#css-preprocessor-integration)
* [3rd Party Library Installation](#3rd-party-library-installation)
* [Global Library Installation](#global-library-installation)
* [Updating angular-cli](#updating-angular-cli)
* [Development Hints for hacking on angular-cli](#development-hints-for-hacking-on-angular-cli)

## Installation

**BEFORE YOU INSTALL:** please read the [prerequisites](#prerequisites)
```bash
npm install -g angular-cli
```

## Usage

```bash
ng help
```

### Generating and serving an Angular2 project via a development server

```bash
ng new PROJECT_NAME
cd PROJECT_NAME
ng serve
```
Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files.

You can configure the default HTTP port and the one used by the LiveReload server with two command-line options :

```bash
ng serve --host 0.0.0.0 --port 4201 --live-reload-port 49153
```

### Generating Components, Directives, Pipes and Services

You can use the `ng generate` (or just `ng g`) command to generate Angular components:

```bash
ng generate component my-new-component
ng g component my-new-component # using the alias

# components support relative path generation
# if in the directory src/app/feature/ and you run
ng g component new-cmp
# your component will be generated in src/app/feature/new-cmp
# but if you were to run
ng g component ../newer-cmp
# your component will be generated in src/app/newer-cmp
```
You can find all possible blueprints in the table below:

Scaffold  | Usage
---       | ---
Component | `ng g component my-new-component`
Directive | `ng g directive my-new-directive`
Pipe      | `ng g pipe my-new-pipe`
Service   | `ng g service my-new-service`
Class     | `ng g class my-new-class`
Interface | `ng g interface my-new-interface`
Enum      | `ng g enum my-new-enum`
Module    | `ng g module my-module`

### Generating a route

The CLI supports routing in several ways:

- We include the `@angular/router` NPM package when creating or initializing a project.

- When you generate a module, you can use the `--routing` option like `ng g module my-module --routing`  to create a separate file `my-module-routing.module.ts` to store the module routes.

  The file includes an empty `Routes` object that you can fill with routes to different components and/or modules.

  The `--routing` option also generates a default component with the same name as the module.

- You can use the `--routing` option with `ng new` to create a `app-routing.module.ts` file when you create or initialize a project.

<!-- DeleteSection1 Start here to remove upon next release -->
### Creating a build

```bash
ng build
```

The build artifacts will be stored in the `dist/` directory.

### Build Targets and Environment Files

`ng build` can specify both a build target (`--target=production` or `--target=development`) and an
environment file to be used with that build (`--environment=dev` or `--environment=prod`).
By default, the development build target and environment are used.

The mapping used to determine which environment file is used can be found in `angular-cli.json`:

```json
"environments": {
  "source": "environments/environment.ts",
  "dev": "environments/environment.ts",
  "prod": "environments/environment.prod.ts"
}
```

These options also apply to the serve command. If you do not pass a value for `environment`,
it will default to `dev` for `development` and `prod` for `production`.

```bash
# these are equivalent
ng build --target=production --environment=prod
ng build --prod --env=prod
ng build --prod
# and so are these
ng build --target=development --environment=dev
ng build --dev --e=dev
ng build --dev
ng build
```

You can also add your own env files other than `dev` and `prod` by doing the following:
- create a `src/environments/environment.NAME.ts`
- add `{ "NAME": 'src/environments/environment.NAME.ts' }` to the `apps[0].environments` object in `angular-cli.json`
- use them via the `--env=NAME` flag on the build/serve commands.

### Base tag handling in index.html

When building you can modify base tag (`<base href="/">`) in your index.html with `--base-href your-url` option.

```bash
# Sets base tag href to /myUrl/ in your index.html
ng build --base-href /myUrl/
ng build --bh /myUrl/
```

### Bundling

All builds make use of bundling, and using the `--prod` flag in  `ng build --prod`
or `ng serve --prod` will also make use of uglifying and tree-shaking functionality.

### Running unit tests

```bash
ng test
```

Tests will execute after a build is executed via [Karma](http://karma-runner.github.io/0.13/index.html), and it will automatically watch your files for changes. You can run tests a single time via `--watch=false` or `--single-run`.

You can run tests with coverage via `--code-coverage`. The coverage report will be in the `coverage/` directory.

Linting during tests is also available via the `--lint` flag. See [Linting code](#linting-code) chapter for more information.

### Running end-to-end tests

```bash
ng e2e
```

Before running the tests make sure you are serving the app via `ng serve`.

End-to-end tests are run via [Protractor](https://angular.github.io/protractor/).

### Proxy To Backend
Using the proxying support in webpack's dev server we can highjack certain urls and send them to a backend server.
We do this by passing a file to `--proxy-config`

Say we have a server running on `http://localhost:3000/api` and we want all calls to `http://localhost:4200/api` to go to that server.

We create a file next to projects `package.json` called `proxy.conf.json`
with the content

```json
{
  "/api": {
    "target": "http://localhost:3000",
    "secure": false
  }
}
```

You can read more about what options are available here [webpack-dev-server proxy settings](https://webpack.github.io/docs/webpack-dev-server.html#proxy)

and then we edit the `package.json` file's start script to be

```json
"start": "ng serve --proxy-config proxy.conf.json",
```

now run it with `npm start`

### Deploying the app via GitHub Pages

You can deploy your apps quickly via:

```bash
ng github-pages:deploy --message "Optional commit message"
```

This will do the following:

- creates GitHub repo for the current project if one doesn't exist
- rebuilds the app in production mode at the current `HEAD`
- creates a local `gh-pages` branch if one doesn't exist
- moves your app to the `gh-pages` branch and creates a commit
- edit the base tag in index.html to support GitHub Pages
- pushes the `gh-pages` branch to GitHub
- returns back to the original `HEAD`

Creating the repo requires a token from GitHub, and the remaining functionality
relies on ssh authentication for all git operations that communicate with github.com.
To simplify the authentication, be sure to [setup your ssh keys](https://help.github.com/articles/generating-ssh-keys/).

If you are deploying a [user or organization page](https://help.github.com/articles/user-organization-and-project-pages/), you can instead use the following command:

```bash
ng github-pages:deploy --user-page --message "Optional commit message"
```

This command pushes the app to the `master` branch on the GitHub repo instead
of pushing to `gh-pages`, since user and organization pages require this.

### Linting code

You can lint your app code by running `ng lint`.
This will use the `lint` npm script that in generated projects uses `tslint`.

You can modify the these scripts in `package.json` to run whatever tool you prefer.

<!-- DeleteSection1 End here -->

 <!-- consider removing autocompletion from readme -->
### Commands autocompletion

To turn on auto completion use the following commands:

For bash:
```bash
ng completion --bash >> ~/.bashrc
source ~/.bashrc
```

For zsh:
```bash
ng completion --zsh >> ~/.zshrc
source ~/.zshrc
```

Windows users using gitbash:
```bash
ng completion --bash >> ~/.bash_profile
source ~/.bash_profile
```

### Project assets

You use the `assets` array in `angular-cli.json` to list files or folders you want to copy as-is when building your project:
```json
"assets": [
  "assets",
  "favicon.ico"
]
```

<!-- DeleteSection2 Start here to remove upon next release -->
### Global styles

The `styles.css` file allows users to add global styles and supports
[CSS imports](https://developer.mozilla.org/en/docs/Web/CSS/@import).

If the project is created with the `--style=sass` option, this will be a `.sass`
file instead, and the same applies to `scss/less/styl`.

You can add more global styles via the `apps[0].styles` property in `angular-cli.json`.

### CSS Preprocessor integration

Angular-CLI supports all major CSS preprocessors:
- sass/scss ([http://sass-lang.com/](http://sass-lang.com/))
- less ([http://lesscss.org/](http://lesscss.org/))
- stylus ([http://stylus-lang.com/](http://stylus-lang.com/))

To use these preprocessors simply add the file to your component's `styleUrls`:

```javascript
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'app works!';
}
```

When generating a new project you can also define which extension you want for
style files:

```bash
ng new sassy-project --style=sass
```

Or set the default style on an existing project:

```bash
ng set defaults.styleExt scss
```

### 3rd Party Library Installation

Simply install your library via `npm install lib-name --save` and import it in your code.

If the library does not include typings, you can install them using npm:

```bash
npm install d3 --save
npm install @types/d3 --save-dev
```

If the library doesn't have typings available at `@types/`, you can still use it by
manually adding typings for it:

1. First, create a `typings.d.ts` file in your `src/` folder. This file will be automatically included as global type definition.

2. Then, in `src/typings.d.ts`, add the following code:

  ```typescript
  declare module 'typeless-package';
  ```

3. Finally, in the component or file that uses the library, add the following code:

  ```typescript
  import * as typelessPackage from 'typeless-package';
  typelessPackage.method();
  ```

Done. Note: you might need or find useful to define more typings for the library that you're trying to use.

### Global Library Installation

Some javascript libraries need to be added to the global scope, and loaded as if
they were in a script tag. We can do this using the `apps[0].scripts` and
`apps[0].styles` properties of `angular-cli.json`.

As an example, to use [Bootstrap 4](http://v4-alpha.getbootstrap.com/) this is
what you need to do:

First install Bootstrap from `npm`:

```bash
npm install bootstrap@next
```

Then add the needed script files to `apps[0].scripts`:

```json
"scripts": [
  "../node_modules/jquery/dist/jquery.js",
  "../node_modules/tether/dist/js/tether.js",
  "../node_modules/bootstrap/dist/js/bootstrap.js"
],
```

Finally add the Bootstrap CSS to the `apps[0].styles` array:
```json
"styles": [
  "../node_modules/bootstrap/dist/css/bootstrap.css",
  "styles.css"
],
```

Restart `ng serve` if you're running it, and Bootstrap 4 should be working on
your app.

<!-- DeleteSection2 End here -->

### Updating angular-cli

To update `angular-cli` to a new version, you must update both the global package and your project's local package.

Global package:
```bash
npm uninstall -g angular-cli
npm cache clean
npm install -g angular-cli@latest
```

Local project package:
```bash
rm -rf node_modules dist # use rmdir on Windows
npm install --save-dev angular-cli@latest
npm install
ng update
```

Running `ng update` will check for changes in all the auto-generated files created by `ng new` and allow you to update yours. You are offered four choices for each changed file: `y` (overwrite), `n` (don't overwrite), `d` (show diff between your file and the updated file) and `h` (help).

Carefully read the diffs for each code file, and either accept the changes or incorporate them manually after `ng update` finishes.

**The main cause of errors after an update is failing to incorporate these updates into your code**.

You can find more details about changes between versions in [CHANGELOG.md](https://github.com/angular/angular-cli/blob/master/CHANGELOG.md).

## Development Hints for hacking on angular-cli

### Working with master

```bash
git clone https://github.com/angular/angular-cli.git
cd angular-cli
npm link
```

`npm link` is very similar to `npm install -g` except that instead of downloading the package
from the repo, the just cloned `angular-cli/` folder becomes the global package.
Any changes to the files in the `angular-cli/` folder will immediately affect the global `angular-cli` package,
allowing you to quickly test any changes you make to the cli project.

Now you can use `angular-cli` via the command line:

```bash
ng new foo
cd foo
npm link angular-cli
ng serve
```

`npm link angular-cli` is needed because by default the globally installed `angular-cli` just loads
the local `angular-cli` from the project which was fetched remotely from npm.
`npm link angular-cli` symlinks the global `angular-cli` package to the local `angular-cli` package.
Now the `angular-cli` you cloned before is in three places:
The folder you cloned it into, npm's folder where it stores global packages and the `angular-cli` project you just created.

You can also use `ng new foo --link-cli` to automatically link the `angular-cli` package.

Please read the official [npm-link documentation](https://www.npmjs.org/doc/cli/npm-link.html)
and the [npm-link cheatsheet](http://browsenpm.org/help#linkinganynpmpackagelocally) for more information.

## License

MIT

[travis-badge]: https://travis-ci.org/angular/angular-cli.svg?branch=master
[travis-badge-url]: https://travis-ci.org/angular/angular-cli
[david-badge]: https://david-dm.org/angular/angular-cli.svg
[david-badge-url]: https://david-dm.org/angular/angular-cli
[david-dev-badge]: https://david-dm.org/angular/angular-cli/dev-status.svg
[david-dev-badge-url]: https://david-dm.org/angular/angular-cli?type=dev
[npm-badge]: https://img.shields.io/npm/v/angular-cli.svg
[npm-badge-url]: https://www.npmjs.com/package/angular-cli


text:
package com.navid.gamemanager;

import com.navid.gamemanager.controller.DomainMapper;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;
import org.thymeleaf.templateresolver.TemplateResolver;

import java.util.Arrays;

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        ApplicationContext ctx = SpringApplication.run(Application.class, args);
    }

    @Bean
    DomainMapper createDomainMapper() {
        return DomainMapper.INSTANCE;
    }

}


text:
name: Pakistan
permalink: "/categories/pakistan/"
layout: category
---


text:
This format validates that the value is a string representation of a port number between *1* and *65,535*.
Note: the value can't be zero as that is a reserved port.


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button_on"
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="On" />

    <Button
        android:id="@+id/button_off"
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="Off" />

    <Button
        android:id="@+id/button_close"
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="Close" />

</LinearLayout>


text:
package org.assertj.core.groups;

import static org.assertj.core.util.IterableUtil.toArray;
import static org.assertj.core.util.Lists.newArrayList;

import java.util.List;

import org.assertj.core.api.AbstractIterableAssert;
import org.assertj.core.api.AbstractObjectArrayAssert;
import org.assertj.core.api.iterable.Extractor;

/**
 * Understands how to retrieve fields or values from a collection/array of objects.
 *

 * You just have to give the field/property name or an {@link Extractor} implementation, a collection/array of objects
 * and it will extract the list of field/values from the given objects.
 *
 * @author Joel Costigliola
 * @author Mateusz Haligowski
 *
 */
public class FieldsOrPropertiesExtractor {

  /**
   * Call {@link #extract(Iterable, Extractor)} after converting objects to an iterable.
   *

   * Behavior is described in javadoc {@link AbstractObjectArrayAssert#extracting(Extractor)}
   * @param <F> type of elements to extract a value from
   * @param <T> the extracted value type
   * @param objects the elements to extract a value from
   * @param extractor the extractor function
   * @return the extracted values
   */
  public static <F, T> T[] extract(F[] objects, Extractor<? super F, T> extractor) {
    checkObjectToExtractFromIsNotNull(objects);
    List<T> result = extract(newArrayList(objects), extractor);
    return toArray(result);
  }

  /**
   * Behavior is described in {@link AbstractIterableAssert#extracting(Extractor)}
   * @param <F> type of elements to extract a value from
   * @param <T> the extracted value type
   * @param objects the elements to extract a value from
   * @param extractor the extractor function
   * @return the extracted values
   */
  public static <F, T> List<T> extract(Iterable<? extends F> objects, Extractor<? super F, T> extractor) {
    checkObjectToExtractFromIsNotNull(objects);
    List<T> result = newArrayList();

    for (F object : objects) {
      final T newValue = extractor.extract(object);
      result.add(newValue);
    }

    return result;
  }

  private static void checkObjectToExtractFromIsNotNull(Object object) {
    if (object == null) throw new AssertionError("Expecting actual not to be null");
  }

}


text:
An article 2
############

:date: 2017-12-08
:summary: Article 2 summary.
:collapse_first: True

The content, not expanded as this is a second article.


text:
package playn.tests.core;

import java.util.Arrays;

import pythagoras.f.FloatMath;
import react.RFuture;
import react.Slot;
import react.UnitSlot;

import playn.core.*;
import playn.core.Pointer;
import playn.scene.*;

public class ImageScalingTest extends Test {

  private static final Texture.Config MIPMAPPED = new Texture.Config(
    true, false, false, GL20.GL_LINEAR, GL20.GL_LINEAR, true);

  private boolean paused = false;
  private float elapsed;

  public ImageScalingTest (TestsGame game) {
    super(game, "ImageScaling",
          "Tests use of min/mag filters and mipmapping when scaling images.");
  }

  @Override public void init () {
    Image princess = game.assets.getImage("images/princess.png");
    Image star     = game.assets.getImage("images/star.png");

    RFuture.collect(Arrays.asList(princess.state, star.state)).onSuccess(imgs -> {
      // the second princess and (64x64) star images are mipmapped
      float phwidth = princess.width()/2f, phheight = princess.height()/2f;
      ImageLayer player1 = new ImageLayer(princess);
      player1.setOrigin(phwidth, phheight);
      game.rootLayer.addAt(player1, 100, 100);
      ImageLayer player2 = new ImageLayer(princess.createTexture(MIPMAPPED));
      player2.setOrigin(phwidth, phheight);
      game.rootLayer.addAt(player2, 250, 100);

      float shwidth = star.width()/2, shheight = star.height()/2;
      ImageLayer slayer1 = new ImageLayer(star);
      slayer1.setOrigin(shwidth, shheight);
      game.rootLayer.addAt(slayer1, 100, 250);
      ImageLayer slayer2 = new ImageLayer(star.createTexture(MIPMAPPED));
      slayer2.setOrigin(shwidth, shheight);
      game.rootLayer.addAt(slayer2, 250, 250);

      conns.add(game.pointer.events.connect(event -> {
        switch (event.kind) {
        case START: paused = true; break;
        case END:
        case CANCEL: paused = false; break;
        }
      }));

      conns.add(game.paint.connect(clock -> {
        if (!paused) {
          elapsed += clock.dt/1000f;
          float scale = Math.abs(FloatMath.sin(elapsed));
          player1.setScale(scale);
          player2.setScale(scale);
          slayer1.setScale(scale);
          slayer2.setScale(scale);
        }
      }));
    });
  }
}