text:
package org.ovirt.engine.ui.webadmin.section.main.presenter;

import org.ovirt.engine.ui.common.presenter.AbstractTabPresenter;
import org.ovirt.engine.ui.common.uicommon.model.MainModelProvider;
import org.ovirt.engine.ui.uicommonweb.models.CommonModel;
import org.ovirt.engine.ui.uicommonweb.models.MainModelSelectionChangeEvent;
import org.ovirt.engine.ui.uicommonweb.models.SearchableListModel;
import com.google.gwt.event.shared.EventBus;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.gwtplatform.mvp.client.View;
import com.gwtplatform.mvp.client.proxy.PlaceManager;
import com.gwtplatform.mvp.client.proxy.TabContentProxyPlace;
import com.gwtplatform.mvp.shared.proxy.PlaceRequest;

/**
 * Base class for main tab presenters.
 *
 * @param <T>
 *            Table row data type or {@code Void} if tab view doesn't provide table widget.
 * @param <M>
 *            Main model type.
 * @param <V>
 *            View type.
 * @param <P>
 *            Proxy type.
 */
public abstract class AbstractMainTabPresenter<T, M extends SearchableListModel, V extends View,
    P extends TabContentProxyPlace<?>> extends AbstractTabPresenter<V, P> {

    protected final PlaceManager placeManager;
    protected final MainModelProvider<T, M> modelProvider;

    @Inject
    private Provider<CommonModel> commonModelProvider;

    public AbstractMainTabPresenter(EventBus eventBus, V view, P proxy,
            PlaceManager placeManager, MainModelProvider<T, M> modelProvider) {
        super(eventBus, view, proxy, MainTabPanelPresenter.TYPE_SetTabContent);
        this.placeManager = placeManager;
        this.modelProvider = modelProvider;
    }

    /**
     * We use manual reveal since we want to prevent users from accessing this presenter when the corresponding main
     * model is not available.
     */
    @Override
    public boolean useManualReveal() {
        return true;
    }

    @Override
    protected void onReveal() {
        super.onReveal();

        // Notify model provider that the tab has been revealed
        modelProvider.onMainTabSelected();
    }

    @Override
    public void prepareFromRequest(PlaceRequest request) {
        super.prepareFromRequest(request);

        // Reveal presenter only when the main model is available
        if (getModel().getIsAvailable()) {
            getProxy().manualReveal(this);
        } else {
            getProxy().manualRevealFailed();
            revealActiveMainModelPresenter();
        }
    }

    protected M getModel() {
        return modelProvider.getModel();
    }

    void revealActiveMainModelPresenter() {
        MainModelSelectionChangeEvent.fire(this, commonModelProvider.get().getSelectedItem());
    }

    /**
     * Returns the place request associated with this main tab presenter.
     */
    protected abstract PlaceRequest getMainTabRequest();

    /**
     * Controls the sub tab panel visibility.
     */
    protected void setSubTabPanelVisible(boolean subTabPanelVisible) {
        UpdateMainContentLayoutEvent.fire(this, subTabPanelVisible);
    }

}


text:
class Boundary
{
public:
	Boundary();
	~Boundary();
	void ChangeBoundary(Axis axis);
	void UndoChangeBoundary();

	int GetLeft();
	int GetRight();
	int GetUp();
	int GetDown();
private:
	std::stack<int> up;
	std::stack<int> down;
	std::stack<int> left;
	std::stack<int> right;
};

redpajama_set_name: RedPajamaGithub


text:
title: March 2020
date: 2020/04/19 13:08
metadata:
    description: 'coreBOS work during March 2020.'
    keywords: 'CRM, vtiger, opensource, corebos'
    author: 'Joe Bordes'
header_image_file: March.png
header_image_height: 320
header_image_width: 560
taxonomy:
    category: blog
    tag: [development, 2020, functionality]
---

wow!

===

 ! Lightning Design System implementations

- CronTasks apply page header and LDS
- Dashboard delete old page header and format graph select box
- Date Fields change calendar icon to LDS
- Debug background-image: the new background makes it hard to see any message sent directly to the screen so we add a debug-friendly background that you can load using the Application_UI_CoverImage global variable: themes/images/content-bg-debug.png
- Export LDS and code formatting
- apply border and bigger text in GenDoc direct compile page
- migrate error alert messages to prompt component
- use LDS popups and modals in Workflow
- apply shadow to entire LDS prompt as opposed to only footer
- apply LDS formatting and modal to convert lead form
- apply LDS to save-report-as and use it both ways this task can be done
- move buttons to the page header and apply LDS styling in Workflow
- apply page header and very basic LDS to Workflow
- apply LDS to workflow condition editor and eliminate jQuery
- apply LDS to workflow form and add fields for mass actions
- fix Audit Trail and Login History LDS background
- apply LDS to Layout Editor field information popup
- apply LDS to test global variable functionality
- add HTML new line to show multiline validations errors correct in new LDS prompt
- display Settings action menu horizontally
- set all views to full width with LDS styling on the table container

 ! Business Question Builder

The Business Question module has been around for a while and has seen some interesting enhancements but the supported query language is complex to generate manually so we created a question builder to make it a little easier. Building on top of the workflow expression editor and the TOAST-UI data table we have been able to cover most of the requirements this project needed. We have to add some documentation on the screen (at least for the type of question properties) and test it to make sure we got most of the combinations correct. A useful addition to the coreBOS Project.

[plugin:youtube](https://youtu.be/pjRks-8txX8)

- layout and design, starting functionality
- Question Builder field editor functionality
- builder field editor
- add management fields and save as new button on Builder
- construct SQL and show in the editor
- question builder results: data table and answer
- show, copy and toggle SQL and WSQuery
- test SQL
- toggle sections by clicking on the header
- avoid block toggle on button click and make SQL editor bigger
- update fields on module change and add a message to SQL editor
- add support for getSetting and functions with quotes
- Builder order and group by
- correctly format SQL select and data columns naming
- change setype to correct name: getEntity
- set question module in the expression editor
- getAnswer with no saved record: passing in the context
- getSQL with no saved record: passing in the context.
- load chartjs CSS after library update
- load mermaid graph without document load event for cases when we load via ajax
- missing smarty class variable in executeScript
- move notification div below buttons
- support for direct SQL Query in getAnswer
- update query on limit change

 ! Import/Export Menu Settings

[Elifuraha Giliad](https://github.com/Egiliad) implements a very useful functionality that permits us to easily save, export, load and apply menu layouts. We can now, for example, set up a menu layout in one coreBOS and load and apply it in another one with a few clicks.

![Global Search Not Found](cbmenuie.gif)

 ! ElasticSearch Integration

[Lorida Cito](https://github.com/loridacito) adds this month an Elastic Search integration option that will seamlessly send the information we want to our ES install every time a record is saved. You can read about it in [the documentation wiki](https://corebos.com/documentation/doku.php?id=en:integrations:elasticsearchnative&noprocess=1).

 ! ModTracker enhancements

[Luke](https://github.com/Luke1982) uses the ModTracker "View History" action to test the [TOAST UI Grid](https://nhn.github.io/tui.grid/latest/) component and update the view to LDS. The test turns out to work very well, both for the data table as for the LDS migration and we push it a little further adding some functionality and bug fixes. Next month also sees yet another enhancement in this section... non-stop.

![ModTracker changes table](ModTrackerHistoryTable.png)

- implementing LDS and Toast UI
- activate highlight always but only on text fields
- document getChangedRecords and getRecordFieldChanges and fix this last one
- method to retrieve the history of changes of a field
- correctly show owner and boolean fields
- avoid incorrect SQL with a negative offset
- do not repeat last tracker record
- eliminate warnings and format code
- rename javascript translation array to avoid conflicts because it is loaded everywhere
- separate highlight from normal difference and use field formatting class to obtain the value based on uitype
- separate postvalue and highlight in two columns for better visualization

 ! coreBOS Universal Unique Record Identifier (UUID)

I add a type 5 UUID for each record in the application which makes it easier to share information between different installations of coreBOS. This is really useful thinking about having various installs managing different parts of a company and syncing information as they need it.

This change required modifying the web service API to support the new record identifier.

I will write a full blog post about this and the goal of the project shortly.

- add memory limit exhaustion control to changeset for a large set of records
- return cbUUID for each reference value
- support cbUUID in all reference fields of web service
- getUUIDfromWSID and avoid warning on crmid not found
- return cbUUID in Web Service GetRelatedRecords
- correctly filter Groups from non-cbUUID supported entities
- return cbUUID in web service operations
- vtws_getReferenceValue: return correct cbUUID value for Users module and support for email parentid multivalued field
- add cbUUID as soon as possible
- add code to avoid warnings when the input parameter is empty

 ! Other Features and New Stuff

- show no data found message when Global Search returns no results
![Global Search Not Found](GlobalSearchNotFound.png)
- inform of PHP max upload limit in Application_Upload_MaxSize global variable
![Global Variable Max Upload Message](GVMaxUploadMsg.png)
- support value/percentage on home page and reports graphs. These are configurable with global variables
  - Graph_ColorScheme
  - Graph_DataLabels
  - Graph_DataLabels_Color
![Home Charts Percentage](HomeChartsPercentage.png)
  - color scheme ChartJS plugin and Graph_ColorScheme global variable to choose which one to use
  - ChartJS Datalabels plugin
  - add support for labels on some dashboard graphs and disable it on all the others

 ! Implementor/Developer enhancements

- Debug background-image: the new background makes it hard to see any message sent directly to the screen so we add a debug-friendly background that you can load using the Application_UI_CoverImage global variable: themes/images/content-bg-debug.png
- more intelligent test record ID detection in Business Maps testMap functionality
- apply less strict cleaning process in the email body to support strange HTML (outlook)
- a better naming convention for GenDoc saved and attached documents with the **Workflow_Email_GenDoc_Attachment_Name** global variable that permits us to use the autonumber field instead of title as attachment name
- correctly detect GenDoc PDF conversion active for new docker conversion support in email workflow task
- get/set/del Settings methods for workflow expressions
- support for getSetting for URL and Auth token in RunWebserviceWorkflowTask
- support User.* fields in Autocomplete business maps
- use httpS in Google Measurement Protocol call
- support getprice hook in Issue and ReceiptCards
- setting and unsetting related list module for UIType 10 field in Layout Editor
- add module information for each Home report widget and eliminate query_result usage
- fix web service set correct actual_price on getProductServiceAutocomplete when the price is modified by the hook

- add the module name to "not found" exception in Webservice for easier debugging
- add a parameter to keep GROUP BY in stripTailCommandsFromQuery and optimize function (DatabaseUtils)
- retrieve_entity_info parameter to throw an exception instead of die on not found error permitting better control over a process where a record may have been deleted
- change the Email update web service method to accept only status fields updates
- return reference information for parentid multi-valued email field when getting the information from web service
- eliminate warning and add some helpers for relations in web service Emails
- DataTransform::sanitizeReferences correctly sanitize special email parent_id field
- load i18n javascript strings functionality. Searches for a [language.js file](https://github.com/tsolucio/corebos/blob/master/modules/ModTracker/language/en_us.js) that contains a mod_alert_arr object with translation strings.

``` js
loadJS('index.php?module=ModTracker&action=ModTrackerAjax&file=getjslanguage');
loadJS('index.php?module=cbQuestion&action=cbQuestionAjax&file=getjslanguage').then(
```

- **MemoryLimitManager** class that permits us to control if a script is consuming too much memory. We set a limit, then ask if it has been reached, permitting us to stop a process and have it restart again with a fresh memory stack. You can see an example in [the coreBOS UUID changeset.](https://github.com/tsolucio/corebos/blob/master/build/changeSets/2020/addcbuuid.php)
- [readableBytes](https://github.com/tsolucio/corebos/blob/master/include/utils/CommonUtils.php#L3618) utility function that converts a number of bytes into a readable format e.g KB, MB, GB, TB, YB
- [numberBytes](https://github.com/tsolucio/corebos/blob/master/include/utils/CommonUtils.php#L3628) utility function to convert a given numeric string with optional byte size magnitude to a number of bytes
- **vtws_getEntityName** to get Module Name from a web service module ID
- add limited support for assigned_user fields in QueryGenerator
- rewrite web service to SQL method with validation information and permission check
- fix **GetRelatedRecords** web service method to return same results for tickets comments and ModComments
- fix **GetRelatedRecords** web service method: limit/offset were in wrong order
- add a function to inform of supported SQL methods: cbexpsql_supportedFunctions
- return also user ID in getPortalUserInfo call
- enhance previousUser to permit retrieving any user in the stack
- trigger change event on popup field expression edit
- **Tests:** keep getting some love and care as we fix things and add coverage.

 ! coreBOS UI Components

Following Luke's lead, we create a Smarty and javascript set of UI Components to use throughout the application to make it easier to apply LDS styling and programming in general.

- setup components infrastructure, move ldsmodal and ldsprompt and globally load data table
- create a directory for Smarty components and move menu functions there
- TOAST-UI: move to components directory
- Modal: support save button action
- Prompt: support for other themes (warning, success, ...)
- add Tooltip Information Smarty component
- ButtonIcon and DateButton Components
- Smarty LDS modal component and migrate Edit/Show Cron with it
- Prompt: bigger message text
- Tooltip: convert to block-based component

 ! coreBOS Mass Actions

This month sees the arrival of a side project we have been working on for some time now. It isn't finished yet but we get the first visual effects of the project in the workflow system.

The Mass Actions project will bring the possibility to launch any combination of workflow tasks against a set of records, permitting us to send mass emails, web service calls, generate image fields or simply apply complex updates. Stay tuned as this functionality lands.

- add conditions option to record set selection
- expression editor on top of new fieldsets
- extract userID from WSID when creating an entity if it is the case
- hide mass action recordset if not needed
- hide record set tab in tasks
- limit access for non-admin users
- migrate tooltips to new component format
- retrieve correct current user in workflows
- we have to manually launch all click events now that the save button is outside the form (page header)

![coreBOS Mass Actions](corebosmassactions.png)

 ! coreBOS Standard Code Formatting, Security, and Optimizations

- coreBOS Standard code Formatting: Application, Calendar, Charts and Chart Reports, CRMEntity, Dashboard, Elastic Search, Emails, GenDoc, Global Variable, Inventory, Mobile, ModTracker, LDSComponents, Reports, QueryGenerator, Webservice, Settings, export, Workflow
- eliminate warnings in Recycle Bin and PBX Manager
- avoid warning in user privileges by adding isAdmin check on hasGlobalViewPermission
- avoid warning when trying to show empty related fields in Tooltip
- add Memory Limit Manager library to CI checks
- update ChartJS library to 2.9.3, load latest CSS and avoid bundle which is discontinued
- update LDS to 2.11.6 Spring '20
- optimization eliminates loop for a direct database query in Create
- optimization ElasticSearch: only execute handler and load dependencies if an index exists for module launching handler
- optimization eliminates unused variable in HelpDesk
- optimization eliminates obsolete Calendar reference and unused code in ModTracker
- optimization reduce SQL results and eliminate warning in ModTracker
- optimization simplify evaluation and eliminate query_result in vtlib_isEntityModule
- optimization move Workflow javascript to script so it gets cached
- optimize DataTransform::sanitizeReferences
- eliminate old Calendar support from Webservice
- delete old Calendar Workflows and Tasks
- eliminate obsolete Events module and it's references
- avoid loading already loaded library and apply cbSR to Global Search
- I set up and try phpDocumentor
  - create a configuration file
  - eliminate incorrect TODO in modules that create false positives in phpDocumentor
  - the results are not very good
- PHP 7.4 changes in ModTracker and Calendar
- security: do not send ModTracker history data if the user does not have permission
- security: clean input variables and apply cbSR in Retrieve

 ! Others

- eliminate redundant parenthesis in Workflow
- fix a very long-standing error to support filters on graphs section/bar navigation. When you click on a section in a graph it will now take you to the correctly filtered set of records.
- correct response time calculation in the footer
- fix special characters support when creating document folders
- convert input-image to image to avoid click on enter
- fix PageHeader by converting cancel button to a button not a submit
- avoid warning in Workflow expression editor if called from outside the workflow environment
- eliminate duplicate HTML IDs in Workflow
- eliminate absolute radio CSS in tui-grid
- hide page header and tabs in print mode
![coreBOS Print Detail View](coreBOSPrint.png)
- eliminate advertising.svg from service worker as it trashes it when adblocking is active
- fix Reports: avoid inserting empty date filter row if no filter is present
- fix Reports: error getting the number of elements of an array using num_rows
- set correct Calendar reminder state value
- avoid sending HelpDesk notification emails when no related account/contact exist
- hide create button in Integrations page header
- Leads Conversion: add block screen on conversion and adapt conversion check when accounts and/or contacts are inactive
- eliminate totals row from Global Search results to correctly detect when we find only one record
- automatically recalculate and set the sequence of Cron Tasks on load. orderTasks method
- send module name not translated label to Export validation settings check
- move status div into the body so we can block screen in the popup edit
- add minimal page header when in a popup view
- add initial coreBOS Updater support for manual updates. Add new field appcs for this purpose. This functionality should be available soon.
- Mobile fixes
  - add a missing parameter to avoid warning
  - change http protocol to httpS
  - set default language to the default language of the application (config.inc)
- constant translation effort:
  - Ranieri from Slemernet spends a lot of time translating the pt_br files and catching a lot of hardcoded strings we still had around. Thank you very much!
    - Accounts, Messges, Potentials, Service Contracts, Main application, Business Maps, Contacts, Cron Tasks, Elastic Search, Filter Management, Mobile, Picklist, Utilities, Settings, Workflow, SMS
  - Components: ldsmodal and ldsprompt support for i18n
  - add "failed" label to List View
  - translate Import/Export functionality in Menu
  - translate hardcoded strings in Mobile and Utilities
  - translate new functionality in ModTracker. Dutch translations
  - use the correct label for translation in Workflow
  - recover removed translations and remove some duplicate translations from Utilities

![March Insights](corebosgithub2003.png)

**Thanks for reading.**


text:
#ifndef __ATK_STREAMABLE_CONTENT_H__
#define __ATK_STREAMABLE_CONTENT_H__

#include <atk/atkobject.h>

#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */

#define ATK_TYPE_STREAMABLE_CONTENT           (atk_streamable_content_get_type ())
#define ATK_IS_STREAMABLE_CONTENT(obj)        G_TYPE_CHECK_INSTANCE_TYPE ((obj), ATK_TYPE_STREAMABLE_CONTENT)
#define ATK_STREAMABLE_CONTENT(obj)           G_TYPE_CHECK_INSTANCE_CAST ((obj), ATK_TYPE_STREAMABLE_CONTENT, AtkStreamableContent)
#define ATK_STREAMABLE_CONTENT_GET_IFACE(obj) (G_TYPE_INSTANCE_GET_INTERFACE ((obj), ATK_TYPE_STREAMABLE_CONTENT, AtkStreamableContentIface))

#ifndef _TYPEDEF_ATK_STREAMABLE_CONTENT
#define _TYPEDEF_ATK_STREAMABLE_CONTENT
typedef struct _AtkStreamableContent AtkStreamableContent;
#endif
typedef struct _AtkStreamableContentIface AtkStreamableContentIface;

struct _AtkStreamableContentIface
{
  GTypeInterface parent;

  /*
   * Get the number of mime types supported by this object
   */
  gint                      (* get_n_mime_types)  (AtkStreamableContent     *streamable);
  /*
   * Gets the specified mime type supported by this object.
   * The mime types are 0-based so the first mime type is
   * at index 0, the second at index 1 and so on.
   *
   * This assumes that the strings for the mime types are stored in the
   * AtkStreamableContent. Alternatively the G_CONST_RETURN could be removed
   * and the caller would be responsible for calling g_free() on the
   * returned value.
   */
  G_CONST_RETURN gchar*     (* get_mime_type)     (AtkStreamableContent     *streamable,
                                                   gint                     i);
  /*
   * Is one possible implementation for this method that it constructs the
   * content appropriate for the mime type and then creates a temporary
   * file containing the content, opens the file and then calls
   * g_io_channel_unix_new_fd().
   */
  GIOChannel*               (* get_stream)        (AtkStreamableContent     *streamable,
                                                   const gchar              *mime_type);

  AtkFunction               pad1;
  AtkFunction               pad2;
  AtkFunction               pad3;
  AtkFunction               pad4;
};
GType                  atk_streamable_content_get_type (void);

gint                   atk_streamable_content_get_n_mime_types (AtkStreamableContent     *streamable);

G_CONST_RETURN gchar*  atk_streamable_content_get_mime_type    (AtkStreamableContent     *streamable,
                                                                gint                     i);
GIOChannel*             atk_streamable_content_get_stream       (AtkStreamableContent     *streamable,
                                                                 const gchar              *mime_type);

#ifdef __cplusplus
}
#endif /* __cplusplus */

#endif /* __ATK_STREAMABLE_CONTENT_H__ */


text:
var itemCChecked = true;

function onOpen() {
  // Call onAddCustomMenuItems whenever the gadget needs to list menu items.
  // This will happen when the user right clicks on the gadget or clicks the
  // menu button on the gadget.
  pluginHelper.onAddCustomMenuItems = onAddCustomMenuItems;
}

function onAddCustomMenuItems(menu) {
  // Add each item. Note that this needs to be done each time this function is
  // called.
  menu.AddItem(ITEM_A, 0, onItemAClick);
  menu.AddItem(ITEM_B, gddMenuItemFlagGrayed, null);
  menu.AddItem(ITEM_C, itemCChecked ? gddMenuItemFlagChecked : 0, onItemCClick);
}

function onItemAClick() {
  view.alert(ITEM_A_CLICKED);
}

function onItemCClick() {
  // Reverse the checkmark status of the item
  itemCChecked = !itemCChecked;
}


text:
package com.github.spbp.setup.data;

public enum Data
{
    WORKSPACE_DIR,
    LAYOUT,
    AUTHOR,
    URL,
    DISPLAY_NAME,
    ID,
    DESCRIPTION,
    MAIN_PACKAGE,
    LICENSE,
    LICENSE_HEADERS,
    GITIGNORE,
    README,

    INSTALL_SCREEN,
    INSTALL_STATUS
}


text:
{% extends "base.html" %}
{% load crispy_forms_tags %}
{% block title %}COLLEGE ASSIST : Departments{% endblock %}

{% block head %}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

{%  endblock %}
{% block content %}

{{ department.name }}

Course Name	Course Code	Semester

        {% for course in courses %}

{{ course.course.name }}	{{ course.course.code }}	{{ course.semester }}

        {% endfor %}

{% endblock %}


text:
<!DOCTYPE html>

<title>OffscreenCanvas test: 2d.filter.canvasFilterObject.componentTransfer.linear.tentative</title>

2d.filter.canvasFilterObject.componentTransfer.linear.tentative

Test pixels on CanvasFilter() componentTransfer with linear type


text:
<?php namespace Illuminate\Foundation\Testing;

use Illuminate\View\View;
use Illuminate\Auth\UserInterface;

abstract class TestCase extends \PHPUnit_Framework_TestCase {

	/**
	 * The Illuminate application instance.
	 *
	 * @var \Illuminate\Foundation\Application
	 */
	protected $app;

	/**
	 * The HttpKernel client instance.
	 *
	 * @var \Illuminate\Foundation\Testing\Client
	 */
	protected $client;

	/**
	 * Setup the test environment.
	 *
	 * @return void
	 */
	public function setUp()
	{
		if ( ! $this->app)
		{
			$this->refreshApplication();
		}
	}

	/**
	 * Refresh the application instance.
	 *
	 * @return void
	 */
	protected function refreshApplication()
	{
		$this->app = $this->createApplication();

		$this->client = $this->createClient();

		$this->app->setRequestForConsoleEnvironment();

		$this->app->boot();
	}

	/**
	 * Creates the application.
	 *
	 * Needs to be implemented by subclasses.
	 *
	 * @return \Symfony\Component\HttpKernel\HttpKernelInterface
	 */
	abstract public function createApplication();

	/**
	 * Call the given URI and return the Response.
	 *
	 * @param  string  $method
	 * @param  string  $uri
	 * @param  array   $parameters
	 * @param  array   $files
	 * @param  array   $server
	 * @param  string  $content
	 * @param  bool    $changeHistory
	 * @return \Illuminate\Http\Response
	 */
	public function call()
	{
		call_user_func_array(array($this->client, 'request'), func_get_args());

		return $this->client->getResponse();
	}

	/**
	 * Call the given HTTPS URI and return the Response.
	 *
	 * @param  string  $method
	 * @param  string  $uri
	 * @param  array   $parameters
	 * @param  array   $files
	 * @param  array   $server
	 * @param  string  $content
	 * @param  bool    $changeHistory
	 * @return \Illuminate\Http\Response
	 */
	public function callSecure()
	{
		$parameters = func_get_args();

		$parameters[1] = 'https://localhost/'.ltrim($parameters[1], '/');

		return call_user_func_array(array($this, 'call'), $parameters);
	}

	/**
	 * Call a controller action and return the Response.
	 *
	 * @param  string  $method
	 * @param  string  $action
	 * @param  array   $wildcards
	 * @param  array   $parameters
	 * @param  array   $files
	 * @param  array   $server
	 * @param  string  $content
	 * @param  bool    $changeHistory
	 * @return \Illuminate\Http\Response
	 */
	public function action($method, $action, $wildcards = array(), $parameters = array(), $files = array(), $server = array(), $content = null, $changeHistory = true)
	{
		$uri = $this->app['url']->action($action, $wildcards, true);

		return $this->call($method, $uri, $parameters, $files, $server, $content, $changeHistory);
	}

	/**
	 * Call a named route and return the Response.
	 *
	 * @param  string  $method
	 * @param  string  $name
	 * @param  array   $routeParameters
	 * @param  array   $parameters
	 * @param  array   $files
	 * @param  array   $server
	 * @param  string  $content
	 * @param  bool    $changeHistory
	 * @return \Illuminate\Http\Response
	 */
	public function route($method, $name, $routeParameters = array(), $parameters = array(), $files = array(), $server = array(), $content = null, $changeHistory = true)
	{
		$uri = $this->app['url']->route($name, $routeParameters);

		return $this->call($method, $uri, $parameters, $files, $server, $content, $changeHistory);
	}

	/**
	 * Assert that the client response has an OK status code.
	 *
	 * @return void
	 */
	public function assertResponseOk()
	{
		$response = $this->client->getResponse();

		$actual = $response->getStatusCode();

		return $this->assertTrue($response->isOk(), 'Expected status code 200, got ' .$actual);
	}

	/**
	 * Assert that the client response has a given code.
	 *
	 * @param  int  $code
	 * @return void
	 */
	public function assertResponseStatus($code)
	{
		return $this->assertEquals($code, $this->client->getResponse()->getStatusCode());
	}

	/**
	 * Assert that the response view has a given piece of bound data.
	 *
	 * @param  string|array  $key
	 * @param  mixed  $value
	 * @return void
	 */
	public function assertViewHas($key, $value = null)
	{
		if (is_array($key)) return $this->assertViewHasAll($key);

		$response = $this->client->getResponse()->original;

		if ( ! $response instanceof View)
		{
			return $this->assertTrue(false, 'The response was not a view.');
		}

		if (is_null($value))
		{
			$this->assertArrayHasKey($key, $response->getData());
		}
		else
		{
			$this->assertEquals($value, $response->$key);
		}
	}

	/**
	 * Assert that the view has a given list of bound data.
	 *
	 * @param  array  $bindings
	 * @return void
	 */
	public function assertViewHasAll(array $bindings)
	{
		foreach ($bindings as $key => $value)
		{
			if (is_int($key))
			{
				$this->assertViewHas($value);
			}
			else
			{
				$this->assertViewHas($key, $value);
			}
		}
	}

	/**
	 * Assert whether the client was redirected to a given URI.
	 *
	 * @param  string  $uri
	 * @param  array   $with
	 * @return void
	 */
	public function assertRedirectedTo($uri, $with = array())
	{
		$response = $this->client->getResponse();

		$this->assertInstanceOf('Illuminate\Http\RedirectResponse', $response);

		$this->assertEquals($this->app['url']->to($uri), $response->headers->get('Location'));

		$this->assertSessionHasAll($with);
	}

	/**
	 * Assert whether the client was redirected to a given route.
	 *
	 * @param  string  $name
	 * @param  array   $parameters
	 * @param  array   $with
	 * @return void
	 */
	public function assertRedirectedToRoute($name, $parameters = array(), $with = array())
	{
		$this->assertRedirectedTo($this->app['url']->route($name, $parameters), $with);
	}

	/**
	 * Assert whether the client was redirected to a given action.
	 *
	 * @param  string  $name
	 * @param  array   $parameters
	 * @param  array   $with
	 * @return void
	 */
	public function assertRedirectedToAction($name, $parameters = array(), $with = array())
	{
		$this->assertRedirectedTo($this->app['url']->action($name, $parameters), $with);
	}

	/**
	 * Assert that the session has a given list of values.
	 *
	 * @param  string|array  $key
	 * @param  mixed  $value
	 * @return void
	 */
	public function assertSessionHas($key, $value = null)
	{
		if (is_array($key)) return $this->assertSessionHasAll($key);

		if (is_null($value))
		{
			$this->assertTrue($this->app['session.store']->has($key), "Session missing key: $key");
		}
		else
		{
			$this->assertEquals($value, $this->app['session.store']->get($key));
		}
	}

	/**
	 * Assert that the session has a given list of values.
	 *
	 * @param  array  $bindings
	 * @return void
	 */
	public function assertSessionHasAll(array $bindings)
	{
		foreach ($bindings as $key => $value)
		{
			if (is_int($key))
			{
				$this->assertSessionHas($value);
			}
			else
			{
				$this->assertSessionHas($key, $value);
			}
		}
	}

	/**
	 * Assert that the session has errors bound.
	 *
	 * @param  string|array  $bindings
	 * @param  mixed  $format
	 * @return void
	 */
	public function assertSessionHasErrors($bindings = array(), $format = null)
	{
		$this->assertSessionHas('errors');

		$bindings = (array)$bindings;

		$errors = $this->app['session.store']->get('errors');

		foreach ($bindings as $key => $value)
		{
			if (is_int($key))
			{
				$this->assertTrue($errors->has($value), "Session missing error: $value");
			}
			else
			{
				$this->assertContains($value, $errors->get($key, $format));
			}
		}
	}

	/**
	 * Assert that the session has old input.
	 *
	 * @return void
	 */
	public function assertHasOldInput()
	{
		$this->assertSessionHas('_old_input');
	}

	/**
	 * Set the session to the given array.
	 *
	 * @param  array  $data
	 * @return void
	 */
	public function session(array $data)
	{
		$this->startSession();

		foreach ($data as $key => $value)
		{
			$this->app['session']->put($key, $value);
		}
	}

	/**
	 * Flush all of the current session data.
	 *
	 * @return void
	 */
	public function flushSession()
	{
		$this->startSession();

		$this->app['session']->flush();
	}

	/**
	 * Start the session for the application.
	 *
	 * @return void
	 */
	protected function startSession()
	{
		if ( ! $this->app['session']->isStarted())
		{
			$this->app['session']->start();
		}
	}

	/**
	 * Set the currently logged in user for the application.
	 *
	 * @param  \Illuminate\Auth\UserInterface  $user
	 * @param  string  $driver
	 * @return void
	 */
	public function be(UserInterface $user, $driver = null)
	{
		$this->app['auth']->driver($driver)->setUser($user);
	}

	/**
	 * Seed a given database connection.
	 *
	 * @param  string  $class
	 * @return void
	 */
	public function seed($class = 'DatabaseSeeder')
	{
		$this->app['artisan']->call('db:seed', array('--class' => $class));
	}

	/**
	 * Create a new HttpKernel client instance.
	 *
	 * @param  array  $server
	 * @return \Symfony\Component\HttpKernel\Client
	 */
	protected function createClient(array $server = array())
	{
		return new Client($this->app, $server);
	}

}


text:
package com.newsblur.serialization;

import java.lang.reflect.Type;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

import android.text.TextUtils;
import android.util.Log;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;

public class DateStringTypeAdapter implements JsonDeserializer<Date> {

	private final DateFormat df;

    public DateStringTypeAdapter() {
        // API sends dates like 2012-07-23 02:43:02
        df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // API doesn't indicate TZ, but it is UTC
        df.setTimeZone(TimeZone.getTimeZone("UTC"));
    }

	@Override
	public Date deserialize(JsonElement element, Type type, JsonDeserializationContext arg2) throws JsonParseException {
			try {
				if (element == null || TextUtils.isEmpty(element.getAsString())) {
					return new Date();
				} else {
					String dateString = element.getAsString();
					if (dateString.length() > 19) {
						dateString = dateString.substring(0, 19);
					}
					return df.parse(dateString);
				}
			} catch (ParseException e) {
				Log.e("DateTypeAdapter", e.getLocalizedMessage());
				return new Date();
			}
	}

}


text:
package com.shoppingmart.service;

import java.util.List;

import com.shoppingmart.entities.UserProfile;

public interface UserProfileService {

    UserProfile findById(int id);

    UserProfile findByType(String type);

    List<UserProfile> findAll();
}


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />

    <title>Four X Four</title>
    <meta name="description" content="" />

    <meta name="HandheldFriendly" content="True" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <link rel="shortcut icon" href="https://scriptindex.github.io/favicon.ico">

    <link rel="stylesheet" type="text/css" href="//scriptindex.github.io/themes/casper/assets/css/screen.css?v=1584662994928" />
    <link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Merriweather:300,700,700italic,300italic|Open+Sans:700,400" />

    <link rel="canonical" href="https://scriptindex.github.io/2018/01/28/Four-X-Four.html" />
    <meta name="referrer" content="origin" />

    <meta property="og:site_name" content="New Letters" />
    <meta property="og:type" content="article" />
    <meta property="og:title" content="Four X Four" />
    <meta property="og:description" content="A few times, a few times. Green leaves green trees Green beans green limes. That&#8217;s nice that&#8217;s good That&#8217;s green that&#8217;s nice. Good times good rhymes Good signs good vibes. -scriptindex, 28/01/18 sun" />
    <meta property="og:url" content="https://scriptindex.github.io/2018/01/28/Four-X-Four.html" />
    <meta property="article:published_time" content="2018-01-28T00:00:00.000Z" />
    <meta property="article:tag" content="poetry" />

    <meta name="twitter:card" content="summary" />
    <meta name="twitter:title" content="Four X Four" />
    <meta name="twitter:description" content="A few times, a few times. Green leaves green trees Green beans green limes. That&#8217;s nice that&#8217;s good That&#8217;s green that&#8217;s nice. Good times good rhymes Good signs good vibes. -scriptindex, 28/01/18 sun" />
    <meta name="twitter:url" content="https://scriptindex.github.io/2018/01/28/Four-X-Four.html" />

    <meta name="generator" content="HubPress" />
    <link rel="alternate" type="application/rss+xml" title="New Letters" href="https://scriptindex.github.io/rss/" />
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.10.0/styles/atom-one-dark.min.css">

Four X Four

                <time class="post-date" datetime="2018-01-28">28 January 2018</time>  on poetry

A few times, a few times.

Green leaves

green trees

Green beans

green limes.

That’s nice

that’s good

That’s green

that’s nice.

Good times

good rhymes

Good signs

good vibes.

-scriptindex, 28/01/18 sun

                scriptindex's Picture

scriptindex

starting something new

Share this post

                    Twitter

                    Facebook

                    Google+

          Please enable JavaScript to view the comments powered by Disqus.
          comments powered by Disqus

New Letters © 2020

Proudly published with HubPress


text:
* Defining software requirements
* Performing software design
* Software construction
* Software testing
* Software maintenance tasks
* Software project management

## Software development always includes the following activities:
* Requirements analysis
* Design
* Construction
* Testing

## Software requirements define the functionality of the system:
* Two kinds of requirements
  * Functional requirements
  * Non-functional requirements
* Requirements analysis starts from a vision about the system
  * Customers don't know what they need!
  * Requirements come roughly and are specified and extended iteratively
* The outcome is the Software Requirements Specification (SRS) or set of User Stories
* Prototyping is often used, especially for the user interface (UI)
* Requirements specifications are too heavy
  * Does not work well in dynamic projects that change their requirements every day
* Agile development needs agile requirements
  * Split into small iterations
* How to split the requirements?
  * Use simple, informal requirements description
  * User story: a small feature that brings some value to the end-user
* User story
  * User needs to accomplish something
  * Written informal (in words / images / sketches)
  * Looks like use-case but is different (less formal)
* User stories have
  * Actor (who?)
  * Goal (what?, why?)
  * Other info
  * Owner, estimate, …
* It is always hard to describe and document the requirements in comprehensive way
  * Good requirements save time and money
* Requirements always change during the project!
  * Good requirements reduces the changes
  * Prototypes significantly reduce changes
  * Agile methodologies are flexible to changes
  * Incremental development in small iterations

## Software Architecture and Software Design:
* Software design is a technical description (blueprints) about how the system will implement the requirements
  * Detailed Design
    * Describes the internal module structure
    * Interfaces, data design, process design
  * Object-Oriented Design
    * Describes the classes, their responsibilities, relationships, dependencies, and interactions
  * Internal Class Design
    * Methods, responsibilities, algorithms and interactions between them
* The system architecture describes:
  * How the system will be decomposed into subsystems (modules)
  * Responsibilities of each module
  * Interaction between the modules
  * Platforms and technologies

![Software Architecture Diagram](https://github.com/huytrongnguyen/aspnet5/blob/master/css/imgs/software-architecture-diagram.png)

* The Software Design Document (SDD)
  * Formal description of the architecture and design of the system
  * It contains:
    * Architectural design
      * Modules and their interaction (diagram)
    * For each module
      * Process design (diagrams)
      * Data design (E/R diagram)
      * Interfaces design (class diagram)

## Software Construction
* During the software construction phase developers create the software
  * Sometimes called implementation phase
* It includes:
  * Internal method design
  * Writing the source code
  * Writing unit tests (optionally)
  * Testing and debugging
  * Integration
* Coding is the process of writing the programming code (the source code)
  * The code strictly follows the design
  * Developers perform internal method design as part of coding
* The source code is the output of the software construction process
  * Written by developers
  * Can include unit tests
* Testing checks whether the developed software conforms to the requirements
  * Aims to identify defects (bugs)
* Developers test the code after writing it
  * At least run it to see the results
  * Unit testing works better
  * Units tests can be repeated many times
* System testing is done by the QA engineers
  * Unit testing is done by developers
* Debugging aims to find the source of already identified defect and to fix it
Performed by developers
* Steps in debugging:
  * Find the defect in the code
    * Identify the source of the problem
    * Identify the exact place in the code causing it
  * Fix the defect
  * Test to check if the fix is working correctly
* Integration is putting all pieces together
  * Compile, run and deploy the modules as a single system
  * Test to identify defects
* Integration strategies
  * Big bang, top-down and bottom-up
  * Continuous integration
* Inexperienced developers consider coding the core of development
  * In most projects coding is only 20% of the project activities!
  * The important decisions are taken during the requirements analysis and design
  * Documentation, testing, integration, maintenance, etc. are often disparaged
* Software engineering is not just coding!
  * Programmer != software engineer

##Software Verification and Testing
* What is software verification?
  * It checks whether the developed software conforms to the requirements
  * Performed by the Software Quality Assurance Engineers (QA engineers)
* Two approaches:
  * Formal reviews and inspections
  * Different kinds of testing
* Cannot certify absence of defects!
  * Can only decrease their rates
* Testing checks whether the developed software conforms to the requirements
* Testing aims to find defects (bugs)
  * Black-box and white-box tests
  * Unit tests, integration tests, system tests, acceptance tests
  * Stress tests, load tests, regression tests
  * Tester engineers can use automated test tools to record and execute tests
* Software Testing Process
  * Test planning
    * Establish test strategy and test plan
    * During requirements and design phases
  * Test development
    * Test procedures, test scenarios, test cases, test scripts
  * Test execution
  * Test reporting
  * Retesting the defects
* The test plan is a formal document that describes how tests will be performed
  * List of test activities to be performed to ensure meeting the requirements
  * Features to be tested, testing approach, schedule, acceptance criteria
* Test scenarios and test cases
  * Test scenarios – stories to be tested
  * Test cases – tests of single function

## Software Project Management
* Project management is the discipline of organizing and managing work and resources in order to successfully complete a project
* Successfully means within defined scope, quality, time and cost constraints
* Software project management
  * Management discipline about planning, monitoring and controlling software projects
* Project planning
  * Identify the scope, estimate the work involved, and create a project schedule
* Project monitoring and control
  * Keep the team up to date on the project's progress and handle problems

## Development Methodologies
* A development methodology is a set of practices and procedures for organizing the software development process
  * A set of rules that developers have to follow
  * A set of conventions the organization decides to follow
  * A systematical, engineering approach for organizing and managing software projects
* Back in history
  * The "Waterfall" Process
  * Old-fashioned, not used today
  * Rational Unified Process (RUP)
  * Microsoft Solutions Framework (MSF)
* Modern development methodologies
  * Agile development processes
  * Scrum, Kanban, Lean Development, Extreme Programming (XP), etc.
* Agile Methodologies
  * Scrum
  * Kanban
  * eXtreme Programming (XP)
  * ...
* Scrum is an iterative incremental framework for managing complex projects
* Scrum roles:
  * Scrum Master – maintains the Scrum processes
  * Product Owner – represents the stakeholders
  * Team – a group of about 7 people
    * The team does the actual development: analysis, design, implementation, testing, etc.
* Scrum Terminology
  * Sprint
    * An iteration in the	Scrum development
    * Usually few weeks
  * Product Backlog
    * All features that have to be developed
  * Sprint Backlog
    * All features planned for the current sprint

![Scrum Process Framework](https://github.com/huytrongnguyen/aspnet5/blob/master/css/imgs/scrum-process-framework.png)

* Scrum Practices
  * Sprint Planning Meeting
    * At the beginning of the sprint cycle
    * Establish the Sprint backlog
  * Daily Scrum stand-up meeting
    * Each day during the sprint – project status from each team member
    * Timeboxed to 15 minutes
  * Sprint Review Meeting
    * Review the work completed / not completed


text:
<?php

namespace Improv;

use Hoa\Iterator\Recursive\Map;
use Improv\Configuration\Mapper;
use Improv\Configuration\Test\AbstractTestCase;
use Improv\Configuration\Test\Fixtures\Maps\TestMap;

/**
 * @covers \Improv\Configuration\Mapper
 */
class MapperTest extends AbstractTestCase
{

    /**
     * @test
     */
    public function returnOriginalValueIfNoFunction()
    {
        self::assertSame('Original Value', (new Mapper())->map('Original Value'));
    }

    /**
     * @test
     */
    public function mappingValues()
    {
        $original_value = 'baloney';
        $mapped_value   = 'YENOLAB';

        $sut            = new Mapper();

        $sut->using(function ($value) {
            return strrev(strtoupper($value));
        });

        self::assertSame($mapped_value, $sut->map($original_value));
    }

    /**
     * @test
     */
    public function mappedValuesAreCached()
    {
        $original_value = 'Original Value';
        $mapped_value   = 'Mapped Value';
        $test_map       = $this->createMock(TestMap::class);

        // Once verifies the usage of instance cache
        $test_map->expects(self::once())
            ->method('__invoke')
            ->with($original_value)
            ->willReturn($mapped_value);

        $sut = new Mapper();

        $sut->using($test_map);

        self::assertSame($mapped_value, $sut->map($original_value));
        self::assertSame($mapped_value, $sut->map($original_value));
    }

    /**
     * @test
     * @dataProvider toIntDataProvider
     */
    public function toInt($original, $expected)
    {
        $sut = new Mapper();
        $sut->toInt();

        self::assertSame($expected, $sut->map($original));
    }

    /**
     * @test
     * @dataProvider toBoolDataProvider
     */
    public function toBool($original, $expected)
    {
        $sut = new Mapper();
        $sut->toBool();

        self::assertSame($expected, $sut->map($original));
    }

    /**
     * @return array
     */
    public function toIntDataProvider()
    {
        return [
            [ '1234',   1234 ],
            [ '12.34',  12 ],
            [ ' 12.3 ', 12 ],
        ];
    }

    /**
     * @return array
     */
    public function toBoolDataProvider()
    {
        return [
            [ 'true',  true ],
            [ 'false', false ],
            [ true,    true ],
            [ false,   false ],
            [ '1',     true ],
            [ '0',     false ],
            [ 1,       true ],
            [ 0,       false ],
            [ 'a',     false ],
            [ 'abc',   false ],
            [ '11',    false ],
            [ 11,      false ],
        ];
    }
}


text:
package org.springframework.boot.cloudfoundry;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.boot.context.config.ConfigFileApplicationListener;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.boot.json.JsonParser;
import org.springframework.boot.json.JsonParserFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.core.Ordered;
import org.springframework.core.env.CommandLinePropertySource;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.util.StringUtils;

/**
 * An {@link ApplicationListener} that knows where to find VCAP (a.k.a. Cloud Foundry)
 * meta data in the existing environment. It parses out the VCAP_APPLICATION and
 * VCAP_SERVICES meta data and dumps it in a form that is easily consumed by
 * {@link Environment} users. If the app is running in Cloud Foundry then both meta data
 * items are JSON objects encoded in OS environment variables. VCAP_APPLICATION is a
 * shallow hash with basic information about the application (name, instance id, instance
 * index, etc.), and VCAP_SERVICES is a hash of lists where the keys are service labels
 * and the values are lists of hashes of service instance meta data. Examples are:
 *
 *

 * VCAP_APPLICATION: {"instance_id":"2ce0ac627a6c8e47e936d829a3a47b5b","instance_index":0,
 *   "version":"0138c4a6-2a73-416b-aca0-572c09f7ca53","name":"foo",
 *   "uris":["foo.cfapps.io"], ...}
 * VCAP_SERVICES: {"rds-mysql-1.0":[{"name":"mysql","label":"rds-mysql-1.0","plan":"10mb",
 *   "credentials":{"name":"d04fb13d27d964c62b267bbba1cffb9da","hostname":"mysql-service-public.clqg2e2w3ecf.us-east-1.rds.amazonaws.com",
 *   "host":"mysql-service-public.clqg2e2w3ecf.us-east-1.rds.amazonaws.com","port":3306,"user":"urpRuqTf8Cpe6",
 *   "username":"urpRuqTf8Cpe6","password":"pxLsGVpsC9A5S"}
 * }]}
 *

 *
 * These objects are flattened into properties. The VCAP_APPLICATION object goes straight
 * to {@code vcap.application.*} in a fairly obvious way, and the VCAP_SERVICES object is
 * unwrapped so that it is a hash of objects with key equal to the service instance name
 * (e.g. "mysql" in the example above), and value equal to that instances properties, and
 * then flattened in the same way. E.g.
 *
 *

 * vcap.application.instance_id: 2ce0ac627a6c8e47e936d829a3a47b5b
 * vcap.application.version: 0138c4a6-2a73-416b-aca0-572c09f7ca53
 * vcap.application.name: foo
 * vcap.application.uris[0]: foo.cfapps.io
 *
 * vcap.services.mysql.name: mysql
 * vcap.services.mysql.label: rds-mysql-1.0
 * vcap.services.mysql.credentials.name: d04fb13d27d964c62b267bbba1cffb9da
 * vcap.services.mysql.credentials.port: 3306
 * vcap.services.mysql.credentials.host: mysql-service-public.clqg2e2w3ecf.us-east-1.rds.amazonaws.com
 * vcap.services.mysql.credentials.username: urpRuqTf8Cpe6
 * vcap.services.mysql.credentials.password: pxLsGVpsC9A5S
 * ...
 *

 *
 * N.B. this initializer is mainly intended for informational use (the application and
 * instance ids are particularly useful). For service binding you might find that Spring
 * Cloud is more convenient and more robust against potential changes in Cloud Foundry.
 *
 * @author Dave Syer
 */
public class VcapApplicationListener implements
		ApplicationListener<ApplicationEnvironmentPreparedEvent>, Ordered {

	private static final Log logger = LogFactory.getLog(VcapApplicationListener.class);

	private static final String VCAP_APPLICATION = "VCAP_APPLICATION";

	private static final String VCAP_SERVICES = "VCAP_SERVICES";

	// Before ConfigFileApplicationListener so values there can use these ones
	private int order = ConfigFileApplicationListener.DEFAULT_ORDER - 1;

	private final JsonParser parser = JsonParserFactory.getJsonParser();

	public void setOrder(int order) {
		this.order = order;
	}

	@Override
	public int getOrder() {
		return this.order;
	}

	@Override
	public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
		ConfigurableEnvironment environment = event.getEnvironment();
		if (!environment.containsProperty(VCAP_APPLICATION)
				&& !environment.containsProperty(VCAP_SERVICES)) {
			return;
		}
		Properties properties = new Properties();
		addWithPrefix(properties, getPropertiesFromApplication(environment),
				"vcap.application.");
		addWithPrefix(properties, getPropertiesFromServices(environment),
				"vcap.services.");
		MutablePropertySources propertySources = environment.getPropertySources();
		if (propertySources
				.contains(CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME)) {
			propertySources.addAfter(
					CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME,
					new PropertiesPropertySource("vcap", properties));
		}
		else {
			propertySources.addFirst(new PropertiesPropertySource("vcap", properties));
		}
	}

	private void addWithPrefix(Properties properties, Properties other, String prefix) {
		for (String key : other.stringPropertyNames()) {
			String prefixed = prefix + key;
			properties.setProperty(prefixed, other.getProperty(key));
		}
	}

	private Properties getPropertiesFromApplication(Environment environment) {
		Properties properties = new Properties();
		try {
			Map<String, Object> map = this.parser.parseMap(environment.getProperty(
					VCAP_APPLICATION, "{}"));
			extractPropertiesFromApplication(properties, map);
		}
		catch (Exception ex) {
			logger.error("Could not parse VCAP_APPLICATION", ex);
		}
		return properties;
	}

	private Properties getPropertiesFromServices(Environment environment) {
		Properties properties = new Properties();
		try {
			Map<String, Object> map = this.parser.parseMap(environment.getProperty(
					VCAP_SERVICES, "{}"));
			extractPropertiesFromServices(properties, map);
		}
		catch (Exception ex) {
			logger.error("Could not parse VCAP_SERVICES", ex);
		}
		return properties;
	}

	private void extractPropertiesFromApplication(Properties properties,
			Map<String, Object> map) {
		if (map != null) {
			flatten(properties, map, "");
		}
	}

	private void extractPropertiesFromServices(Properties properties,
			Map<String, Object> map) {
		if (map != null) {
			for (Object services : map.values()) {
				@SuppressWarnings("unchecked")
				List<Object> list = (List<Object>) services;
				for (Object object : list) {
					@SuppressWarnings("unchecked")
					Map<String, Object> service = (Map<String, Object>) object;
					String key = (String) service.get("name");
					if (key == null) {
						key = (String) service.get("label");
					}
					flatten(properties, service, key);
				}
			}
		}
	}

	@SuppressWarnings("unchecked")
	private void flatten(Properties properties, Map<String, Object> input, String path) {
		for (Entry<String, Object> entry : input.entrySet()) {
			String key = getFullKey(path, entry.getKey());
			Object value = entry.getValue();
			if (value instanceof Map) {
				// Need a compound key
				flatten(properties, (Map<String, Object>) value, key);
			}
			else if (value instanceof Collection) {
				// Need a compound key
				Collection<Object> collection = (Collection<Object>) value;
				properties.put(key,
						StringUtils.collectionToCommaDelimitedString(collection));
				int count = 0;
				for (Object item : collection) {
					String itemKey = "[" + (count++) + "]";
					flatten(properties, Collections.singletonMap(itemKey, item), key);
				}
			}
			else if (value instanceof String) {
				properties.put(key, value);
			}
			else if (value instanceof Number) {
				properties.put(key, value.toString());
			}
			else if (value instanceof Boolean) {
				properties.put(key, value.toString());
			}
			else {
				properties.put(key, value == null ? "" : value);
			}
		}
	}

	private String getFullKey(String path, String key) {
		if (!StringUtils.hasText(path)) {
			return key;
		}
		if (key.startsWith("[")) {
			return path + key;
		}
		return path + "." + key;
	}

}


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/action_search"
        android:hint="@string/search_station_name_hint"
        android:icon="@drawable/search"
        android:orderInCategory="1"
        android:title="@string/search"
        app:actionViewClass="android.support.v7.widget.SearchView"
        app:showAsAction="always" />
</menu>


text:
<?xml version="1.0" encoding="UTF-8"?>
<jcr:root xmlns:jcr="http://www.jcp.org/jcr/1.0" xmlns:nt="http://www.jcp.org/jcr/nt/1.0"
    jcr:primaryType="nt:unstructured"
    jcr:title="Bulk Workflow Manager"
    jcr:description="Execute AEM Workflow at scale."
    icon="workflow"
    href="/acs-commons.html/etc/acs-commons/bulk-workflow-manager"
    id="acs-commons__bulk-workflow-manager"
    target="_blank"/>


text:
// Generated from /POI/java/org/apache/poi/poifs/macros/VBAMacroReader.java
#include <org/apache/poi/poifs/macros/VBAMacroReader_Module.hpp>

#include <java/io/ByteArrayOutputStream.hpp>
#include <java/lang/NullPointerException.hpp>
#include <org/apache/poi/util/IOUtils.hpp>
#include <Array.hpp>

template<typename T>
static T* npc(T* t)
{
    if(!t) throw new ::java::lang::NullPointerException();
    return t;
}

poi::poifs::macros::VBAMacroReader_Module::VBAMacroReader_Module(const ::default_init_tag&)
    : super(*static_cast< ::default_init_tag* >(0))
{
    clinit();
}

poi::poifs::macros::VBAMacroReader_Module::VBAMacroReader_Module()
    : VBAMacroReader_Module(*static_cast< ::default_init_tag* >(0))
{
    ctor();
}

void poi::poifs::macros::VBAMacroReader_Module::read(::java::io::InputStream* in) /* throws(IOException) */
{
    auto const out = new ::java::io::ByteArrayOutputStream();
    ::poi::util::IOUtils::copy(in, out);
    npc(out)->close();
    buf = npc(out)->toByteArray_();
}

extern java::lang::Class *class_(const char16_t *c, int n);

java::lang::Class* poi::poifs::macros::VBAMacroReader_Module::class_()
{
    static ::java::lang::Class* c = ::class_(u"org.apache.poi.poifs.macros.VBAMacroReader.Module", 49);
    return c;
}

java::lang::Class* poi::poifs::macros::VBAMacroReader_Module::getClass0()
{
    return class_();
}


text:
package com.company.professor;

import com.company.professor.DaoSession;
import de.greenrobot.dao.DaoException;

// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT. Enable "keep" sections if you want to edit.
/**
 * Entity mapped to table "stat_names".
 */
public class StatNames {

    private long StatId;
    private long LocalLanguageId;
    /** Not-null value. */
    private String Name;

    /** Used to resolve relations */
    private transient DaoSession daoSession;

    /** Used for active entity operations. */
    private transient StatNamesDao myDao;

    private Stats Stats;
    private Long Stats__resolvedKey;

    private Languages Languages;
    private Long Languages__resolvedKey;

    public StatNames() {
    }

    public StatNames(long StatId) {
        this.StatId = StatId;
    }

    public StatNames(long StatId, long LocalLanguageId, String Name) {
        this.StatId = StatId;
        this.LocalLanguageId = LocalLanguageId;
        this.Name = Name;
    }

    /** called by internal mechanisms, do not call yourself. */
    public void __setDaoSession(DaoSession daoSession) {
        this.daoSession = daoSession;
        myDao = daoSession != null ? daoSession.getStatNamesDao() : null;
    }

    public long getStatId() {
        return StatId;
    }

    public void setStatId(long StatId) {
        this.StatId = StatId;
    }

    public long getLocalLanguageId() {
        return LocalLanguageId;
    }

    public void setLocalLanguageId(long LocalLanguageId) {
        this.LocalLanguageId = LocalLanguageId;
    }

    /** Not-null value. */
    public String getName() {
        return Name;
    }

    /** Not-null value; ensure this value is available before it is saved to the database. */
    public void setName(String Name) {
        this.Name = Name;
    }

    /** To-one relationship, resolved on first access. */
    public Stats getStats() {
        long __key = this.StatId;
        if (Stats__resolvedKey == null || !Stats__resolvedKey.equals(__key)) {
            if (daoSession == null) {
                throw new DaoException("Entity is detached from DAO context");
            }
            StatsDao targetDao = daoSession.getStatsDao();
            Stats StatsNew = targetDao.load(__key);
            synchronized (this) {
                Stats = StatsNew;
            	Stats__resolvedKey = __key;
            }
        }
        return Stats;
    }

    public void setStats(Stats Stats) {
        if (Stats == null) {
            throw new DaoException("To-one property 'StatId' has not-null constraint; cannot set to-one to null");
        }
        synchronized (this) {
            this.Stats = Stats;
            StatId = Stats.getId();
            Stats__resolvedKey = StatId;
        }
    }

    /** To-one relationship, resolved on first access. */
    public Languages getLanguages() {
        long __key = this.LocalLanguageId;
        if (Languages__resolvedKey == null || !Languages__resolvedKey.equals(__key)) {
            if (daoSession == null) {
                throw new DaoException("Entity is detached from DAO context");
            }
            LanguagesDao targetDao = daoSession.getLanguagesDao();
            Languages LanguagesNew = targetDao.load(__key);
            synchronized (this) {
                Languages = LanguagesNew;
            	Languages__resolvedKey = __key;
            }
        }
        return Languages;
    }

    public void setLanguages(Languages Languages) {
        if (Languages == null) {
            throw new DaoException("To-one property 'LocalLanguageId' has not-null constraint; cannot set to-one to null");
        }
        synchronized (this) {
            this.Languages = Languages;
            LocalLanguageId = Languages.getId();
            Languages__resolvedKey = LocalLanguageId;
        }
    }

    /** Convenient call for {@link AbstractDao#delete(Object)}. Entity must attached to an entity context. */
    public void delete() {
        if (myDao == null) {
            throw new DaoException("Entity is detached from DAO context");
        }
        myDao.delete(this);
    }

    /** Convenient call for {@link AbstractDao#update(Object)}. Entity must attached to an entity context. */
    public void update() {
        if (myDao == null) {
            throw new DaoException("Entity is detached from DAO context");
        }
        myDao.update(this);
    }

    /** Convenient call for {@link AbstractDao#refresh(Object)}. Entity must attached to an entity context. */
    public void refresh() {
        if (myDao == null) {
            throw new DaoException("Entity is detached from DAO context");
        }
        myDao.refresh(this);
    }

}


text:
class DefaultConfig(object):
    GRAB_SPIDER_MODULES = ['spider']
    GRAB_SAVE_FATAL_ERRORS = True
    GRAB_SAVE_TASK_ADD_ERRORS = True
    GRAB_SAVE_FINAL_STATS = True
    GRAB_THREAD_NUMBER = 1
    GRAB_NETWORK_TRY_LIMIT = 10
    GRAB_TASK_TRY_LIMIT = 10
    GRAB_DISPLAY_TIMING = True
    GRAB_DISPLAY_STATS = True
    GRAB_ACTIVATE_VIRTUALENV = False
    GRAB_DJANGO_SETTINGS = None

default_config = DefaultConfig()


text:
<?php

namespace Magento\Customer\Test\TestCase;

use Magento\Config\Test\Fixture\ConfigData;
use Magento\Customer\Test\Fixture\Address;
use Magento\Customer\Test\Page\CustomerAccountIndex;
use Magento\Customer\Test\Page\CustomerAddressEdit;
use Magento\Customer\Test\Fixture\Customer;

/**
 * Preconditions:
 * 1. Enable VAT functionality.
 * 2. Create customer.
 *
 * Steps:
 * 1. Go to frontend.
 * 2. Login with customer account.
 * 3. Go to My Account > Address Book.
 * 4. Update Default Billing Address with specified VAT number.
 * 5. Save Customer Address.
 * 6. Perform assertions.
 *
 * @group VAT_ID_(CS)
 * @ZephyrId MAGETWO-12447
 */
class ApplyVatIdTest extends AbstractApplyVatIdTest
{
    /* tags */
    const MVP = 'no';
    const DOMAIN = 'CS';
    const TEST_TYPE = '3rd_party_test';
    /* end tags */

    /**
     * Customer account page.
     *
     * @var CustomerAccountIndex
     */
    protected $customerAccountIndex;

    /**
     * Customer account edit address page.
     *
     * @var CustomerAddressEdit
     */
    protected $customerAddressEdit;

    /**
     * Inject pages.
     *
     * @param CustomerAccountIndex $customerAccountIndex
     * @param CustomerAddressEdit $customerAddressEdit
     * @return void
     */
    public function __inject(CustomerAccountIndex $customerAccountIndex, CustomerAddressEdit $customerAddressEdit)
    {
        $this->customerAccountIndex = $customerAccountIndex;
        $this->customerAddressEdit = $customerAddressEdit;
    }

    /**
     * Enable Automatic Assignment of Customers to Appropriate VAT Group.
     *
     * @param Customer $customer
     * @param Address $vatId
     * @param ConfigData $vatConfig
     * @param string $configData
     * @param string $customerGroup
     * @return array
     */
    public function test(
        Customer $customer,
        Address $vatId,
        ConfigData $vatConfig,
        $configData,
        $customerGroup
    ) {
        // Preconditions
        $this->configData = $configData;
        $this->customer = $customer;
        $this->objectManager->create(
            'Magento\Config\Test\TestStep\SetupConfigurationStep',
            ['configData' => $this->configData]
        )->run();
        $this->customer->persist();
        $this->prepareVatConfig($vatConfig, $customerGroup);

        // Steps
        $this->objectManager->create(
            'Magento\Customer\Test\TestStep\LoginCustomerOnFrontendStep',
            ['customer' => $this->customer]
        )->run();
        $this->customerAccountIndex->getDashboardAddress()->editBillingAddress();
        $this->customerAddressEdit->getEditForm()->fill($vatId);
        $this->customerAddressEdit->getEditForm()->saveAddress();

        return ['customer' => $this->customer];
    }
}


text:
/* http://keith-wood.name/calculator.html
   Serbian initialisation for the jQuery calculator extension
   Written by Željko Tadić November 2013. */
(function($) { // hide the namespace
	$.calculator.regionalOptions['sr'] = {
		decimalChar: ',',
		buttonText: '...', buttonStatus: 'Отвори калкулатор',
		closeText: 'затвори', closeStatus: 'Затвори калкулатор',
		useText: 'користи', useStatus: 'Користи тренутну вредност',
		eraseText: 'Обриши', eraseStatus: 'Обриши вредност из поља и затвори калкулатор',
		backspaceText: 'BS', backspaceStatus: 'Обриши задњу знаменку',
		clearErrorText: 'CE', clearErrorStatus: 'Обриши задњи број',
		clearText: 'CA', clearStatus: 'Ресетуј калкулатор',
		memClearText: 'MC', memClearStatus: 'Обриши из меморије',
		memRecallText: 'MR', memRecallStatus: 'Користи вредност из меморије',
		memStoreText: 'MS', memStoreStatus: 'Похрани вредност у меморију',
		memAddText: 'M+', memAddStatus: 'Додај у меморију',
		memSubtractText: 'M-', memSubtractStatus: 'Одузми из меморије',
		base2Text: 'Bin', base2Status: 'Бинарни систем',
		base8Text: 'Oct', base8Status: 'Октални систем',
		base10Text: 'Dec', base10Status: 'Децимални систем',
		base16Text: 'Hex', base16Status: 'Хексадецимални систем',
		degreesText: 'Deg', degreesStatus: 'Степени',
		radiansText: 'Rad', radiansStatus: 'Радијани',
		isRTL: false};
	$.calculator.setDefaults($.calculator.regionalOptions['sr']);
})(jQuery);


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('wagtail_personalisation', '0002_auto_20161205_1623'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='queryrule',
            name='query_parameter',
        ),
        migrations.RemoveField(
            model_name='queryrule',
            name='query_value',
        ),
        migrations.AddField(
            model_name='queryrule',
            name='parameter',
            field=models.SlugField(default='test', max_length=20, verbose_name='The query parameter to search for'),
            preserve_default=False,
        ),
        migrations.AddField(
            model_name='queryrule',
            name='value',
            field=models.SlugField(default='test', max_length=20, verbose_name='The value of the parameter to match'),
            preserve_default=False,
        ),
    ]


text:
#include "config.h"
#include "QtWebPageLoadClient.h"

#include "QtWebError.h"
#include "qquickwebview_p_p.h"

using namespace WebCore;

namespace WebKit {

QtWebPageLoadClient::QtWebPageLoadClient(WKPageRef pageRef, QQuickWebView* webView)
    : m_webView(webView)
{
    WKPageLoaderClient loadClient;
    memset(&loadClient, 0, sizeof(WKPageLoaderClient));
    loadClient.version = kWKPageLoaderClientCurrentVersion;
    loadClient.clientInfo = this;
    loadClient.didStartProvisionalLoadForFrame = didStartProvisionalLoadForFrame;
    loadClient.didReceiveServerRedirectForProvisionalLoadForFrame = didReceiveServerRedirectForProvisionalLoadForFrame;
    loadClient.didFailProvisionalLoadWithErrorForFrame = didFailProvisionalLoadWithErrorForFrame;
    loadClient.didCommitLoadForFrame = didCommitLoadForFrame;
    loadClient.didFinishLoadForFrame = didFinishLoadForFrame;
    loadClient.didFailLoadWithErrorForFrame = didFailLoadWithErrorForFrame;
    loadClient.didSameDocumentNavigationForFrame = didSameDocumentNavigationForFrame;
    loadClient.didReceiveTitleForFrame = didReceiveTitleForFrame;
    loadClient.didStartProgress = didStartProgress;
    loadClient.didChangeProgress = didChangeProgress;
    loadClient.didFinishProgress = didFinishProgress;
    loadClient.didChangeBackForwardList = didChangeBackForwardList;
    WKPageSetPageLoaderClient(pageRef, &loadClient);
}

void QtWebPageLoadClient::didStartProvisionalLoad(const WTF::String& url)
{
    m_webView->d_func()->provisionalLoadDidStart(url);
}

void QtWebPageLoadClient::didReceiveServerRedirectForProvisionalLoad(const WTF::String& url)
{
    m_webView->d_func()->didReceiveServerRedirectForProvisionalLoad(url);
}

void QtWebPageLoadClient::didCommitLoad()
{
    PageViewportController* pvc = m_webView->d_func()->viewportController();
    if (pvc)
        pvc->didCommitLoad();
    m_webView->d_func()->loadDidCommit();
}

void QtWebPageLoadClient::didSameDocumentNavigation()
{
    m_webView->d_func()->didSameDocumentNavigation();
}

void QtWebPageLoadClient::didReceiveTitle()
{
    m_webView->d_func()->titleDidChange();
}

void QtWebPageLoadClient::didChangeProgress(int loadProgress)
{
    m_webView->d_func()->loadProgressDidChange(loadProgress);
}

void QtWebPageLoadClient::didChangeBackForwardList()
{
    m_webView->d_func()->backForwardListDidChange();
}

void QtWebPageLoadClient::dispatchLoadSucceeded()
{
    m_webView->d_func()->loadDidSucceed();
}

void QtWebPageLoadClient::dispatchLoadStopped()
{
    m_webView->d_func()->loadDidStop();
}

void QtWebPageLoadClient::dispatchLoadFailed(WebFrameProxy* frame, const QtWebError& error)
{
    if (error.isCancellation()) {
        dispatchLoadStopped();
        return;
    }

    int errorCode = error.errorCode();

    if (errorCode == kWKErrorCodeFrameLoadInterruptedByPolicyChange || errorCode == kWKErrorCodePlugInWillHandleLoad) {
        // The active url might have changed
        m_webView->emitUrlChangeIfNeeded();

        // Make sure that LoadStartedStatus has a counterpart when e.g. requesting a download.
        dispatchLoadSucceeded();

        return;
    }

    // We set the unreachable url unconditionally so that the current
    // active url of the webview when the loadingChanged signal is
    // emitted reflects the failed url, not the previously committed
    // url. This also ensures that if the user does not do a loadHtml
    // with an error page and and unreachable url as a reponse to the
    // failed load, we can still detect the failed url for reloads.
    frame->setUnreachableURL(error.url());
    m_webView->emitUrlChangeIfNeeded();

    m_webView->d_func()->loadDidFail(error);
}

static QtWebPageLoadClient* toQtWebPageLoadClient(const void* clientInfo)
{
    ASSERT(clientInfo);
    return reinterpret_cast<QtWebPageLoadClient*>(const_cast<void*>(clientInfo));
}

void QtWebPageLoadClient::didStartProvisionalLoadForFrame(WKPageRef, WKFrameRef frame, WKTypeRef, const void* clientInfo)
{
    if (!WKFrameIsMainFrame(frame))
        return;
    toQtWebPageLoadClient(clientInfo)->didStartProvisionalLoad(toImpl(frame)->provisionalURL());
}

void QtWebPageLoadClient::didReceiveServerRedirectForProvisionalLoadForFrame(WKPageRef, WKFrameRef frame, WKTypeRef, const void* clientInfo)
{
    if (!WKFrameIsMainFrame(frame))
        return;

    WebFrameProxy* wkframe = toImpl(frame);
    toQtWebPageLoadClient(clientInfo)->didReceiveServerRedirectForProvisionalLoad(wkframe->provisionalURL());
}

void QtWebPageLoadClient::didFailProvisionalLoadWithErrorForFrame(WKPageRef, WKFrameRef frame, WKErrorRef error, WKTypeRef, const void* clientInfo)
{
    if (!WKFrameIsMainFrame(frame))
        return;
    toQtWebPageLoadClient(clientInfo)->dispatchLoadFailed(toImpl(frame), error);
}

void QtWebPageLoadClient::didCommitLoadForFrame(WKPageRef, WKFrameRef frame, WKTypeRef, const void* clientInfo)
{
    if (!WKFrameIsMainFrame(frame))
        return;
    toQtWebPageLoadClient(clientInfo)->didCommitLoad();
}

void QtWebPageLoadClient::didFinishLoadForFrame(WKPageRef, WKFrameRef frame, WKTypeRef, const void* clientInfo)
{
    if (!WKFrameIsMainFrame(frame))
        return;
    toQtWebPageLoadClient(clientInfo)->dispatchLoadSucceeded();
}

void QtWebPageLoadClient::didFailLoadWithErrorForFrame(WKPageRef, WKFrameRef frame, WKErrorRef error, WKTypeRef, const void* clientInfo)
{
    if (!WKFrameIsMainFrame(frame))
        return;
    toQtWebPageLoadClient(clientInfo)->dispatchLoadFailed(toImpl(frame), error);
}

void QtWebPageLoadClient::didSameDocumentNavigationForFrame(WKPageRef, WKFrameRef frame, WKSameDocumentNavigationType type, WKTypeRef userData, const void* clientInfo)
{
    if (!WKFrameIsMainFrame(frame))
        return;
    toQtWebPageLoadClient(clientInfo)->didSameDocumentNavigation();
}

void QtWebPageLoadClient::didReceiveTitleForFrame(WKPageRef, WKStringRef title, WKFrameRef frame, WKTypeRef, const void* clientInfo)
{
    if (!WKFrameIsMainFrame(frame))
        return;
    toQtWebPageLoadClient(clientInfo)->didReceiveTitle();
}

void QtWebPageLoadClient::didStartProgress(WKPageRef, const void* clientInfo)
{
    toQtWebPageLoadClient(clientInfo)->didChangeProgress(0);
}

void QtWebPageLoadClient::didChangeProgress(WKPageRef page, const void* clientInfo)
{
    toQtWebPageLoadClient(clientInfo)->didChangeProgress(WKPageGetEstimatedProgress(page) * 100);
}

void QtWebPageLoadClient::didFinishProgress(WKPageRef, const void* clientInfo)
{
    toQtWebPageLoadClient(clientInfo)->didChangeProgress(100);
}

void QtWebPageLoadClient::didChangeBackForwardList(WKPageRef, WKBackForwardListItemRef, WKArrayRef, const void *clientInfo)
{
    toQtWebPageLoadClient(clientInfo)->didChangeBackForwardList();
}

} // namespace Webkit


text:
package voldemort.store.analyzer;

import java.io.DataInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;

import voldemort.client.ClientConfig;
import voldemort.client.protocol.RequestFormatType;
import voldemort.store.parser.AccessNode;
import voldemort.store.parser.ClientNode;
import voldemort.store.parser.TrackLogParser;
import voldemort.store.socket.SocketAndStreams;
import voldemort.store.socket.SocketDestination;
import voldemort.store.socket.SocketPool;
import voldemort.utils.ByteUtils;
import voldemort.versioning.VectorClock;

import com.google.common.collect.Maps;

public class AnalyzerMaster {

    private final Logger logger;

    private TrackLogParser parser;
    private final SocketPool socketPool;
    private List<SocketDestination> destList;
    private Map<String, ClientNode> clientsMap;

    public AnalyzerMaster(ClientConfig config, TrackLogParser parser) {
        this.logger = Logger.getLogger(AnalyzerMaster.class.getName());
        socketPool = new SocketPool(config.getMaxConnectionsPerNode(),
                                    config.getConnectionTimeout(TimeUnit.MILLISECONDS),
                                    config.getSocketTimeout(TimeUnit.MILLISECONDS),
                                    config.getSocketBufferSize(),
                                    config.getSocketKeepAlive());
        destList = new ArrayList<SocketDestination>();
        this.parser = parser;
    }

    public void addDestination(String host, int port) {
        SocketDestination dest = new SocketDestination(host, port, RequestFormatType.VOLDEMORT_V2);
        destList.add(dest);
    }

    public void init() throws IOException {
        parser.init();

        Map<String, ClientNode> clients = parser.getClientNode();
        logger.info(parser.getLastVersion());
        if(clients.containsKey(parser.getClient())) {
            clients.get(parser.getClient()).setVersion(parser.getLastVersion());
        }

        for(SocketDestination dest: destList) {
            SocketAndStreams sas = socketPool.checkout(dest);
            byte[] cmdBytes = ByteUtils.getBytes("init", "UTF-8");
            sas.getOutputStream().writeByte(cmdBytes.length);
            sas.getOutputStream().write(cmdBytes);
            sas.getOutputStream().flush();
            int length = sas.getInputStream().readByte();
            byte[] respBytes = new byte[length];
            ByteUtils.read(sas.getInputStream(), respBytes);
            String resp = ByteUtils.getString(respBytes, "UTF-8");
            if(resp.equals("done")) {
                logger.info(dest + "done");
            }
        }

        clientsMap = Maps.newHashMap();
        for(String key: clients.keySet()) {
            clientsMap.put(key, clients.get(key));
        }
        updateClientHistory();

    }

    public boolean updateClientHistory() throws IOException {
        boolean needIter = false;

        for(SocketDestination dest: destList) {
            SocketAndStreams sas = socketPool.checkout(dest);
            byte[] cmdBytes = ByteUtils.getBytes("update", "UTF-8");
            sas.getOutputStream().writeByte(cmdBytes.length);
            sas.getOutputStream().write(cmdBytes);
            sas.getOutputStream().flush();

            byte[] clientBytes = getClientBytes();
            sas.getOutputStream().writeInt(clientBytes.length);
            sas.getOutputStream().write(clientBytes);
            sas.getOutputStream().flush();

            int isUpdated = sas.getInputStream().readByte();
            if(isUpdated == 1) {
                logger.info("update from client");
                needIter = true;
                List<ClientNode> slaveClients = getClientFromBytes(sas.getInputStream());
                updateClientsMap(slaveClients);
            }

            int length = sas.getInputStream().readByte();
            byte[] respBytes = new byte[length];
            ByteUtils.read(sas.getInputStream(), respBytes);
            String resp = ByteUtils.getString(respBytes, "UTF-8");
            if(resp.equals("done")) {
                logger.info(dest + "done");
            }
        }

        Map<String, ClientNode> clients = parser.getClientNode();

        boolean nextIter = false;
        if(needIter)
            for(ClientNode client: clientsMap.values()) {
                logger.info("update client: " + client);
                if(clients.containsKey(client.getClient())) {
                    logger.info("current version:" + clients.get(client.getClient()));
                    if(clients.get(client.getClient()).setVersion(client.getVersion())) {
                        nextIter = true;
                        logger.info("update!");
                    }
                }
            }
        if(nextIter)
            logger.info("need more iterations");
        return nextIter;
    }

    public void updateClientsMap(List<ClientNode> clients) {
        for(ClientNode c: clients) {
            if(clientsMap.containsKey(c.getClient())) {
                VectorClock newVersion = VectorClock.forwardMerge(c.getVersion(),
                                                                  clientsMap.get(c.getClient())
                                                                            .getVersion());
                clientsMap.put(c.getClient(), new ClientNode(c.getClient(), newVersion));

            } else {
                clientsMap.put(c.getClient(), c);
            }
        }
    }

    public byte[] getClientBytes() {
        Collection<ClientNode> clients = parser.getClientNode().values();
        int length = 0;
        for(ClientNode c: clients) {
            logger.info(c + " " + c.sizeInBytes() + " bytes.");
            length += c.sizeInBytes();
        }
        byte[] serialized = new byte[length];

        int pos = 0;
        for(ClientNode c: clients) {
            System.arraycopy(c.toBytes(), 0, serialized, pos, c.sizeInBytes());
            pos += c.sizeInBytes();
        }
        return serialized;
    }

    public List<ClientNode> getClientFromBytes(DataInputStream in) throws IOException {
        int valueSize = in.readInt();
        byte[] valueBytes = new byte[valueSize];
        ByteUtils.read(in, valueBytes);
        int offset = 0;
        // logger.info("reading " + valueSize + " bytes.");
        ArrayList<ClientNode> clientList = new ArrayList<ClientNode>();
        while(offset < valueSize) {
            ClientNode client = new ClientNode(valueBytes, offset);
            // logger.info(client + " " + client.sizeInBytes() + " bytes.");
            offset += client.sizeInBytes();
            clientList.add(client);
        }

        return clientList;
    }

    public void outputDirtyKeys() {
        Map<String, ClientNode> clients = parser.getClientNode();

        logger.info("dirty keys");
        for(ClientNode client: clients.values()) {
            ArrayList<AccessNode> nodeList = client.getClientOp();
            for(AccessNode node: nodeList) {
                if(node.isDirty()) {
                    String key = ByteUtils.getString(node.getKey().get(), "UTF-8");
                    logger.info(node.getClient() + " : " + key);
                } else {
                    String key = ByteUtils.getString(node.getKey().get(), "UTF-8");
                    logger.info(node.getClient() + " not dirty : " + key);
                }
            }
        }
    }
}


text:
Simple mysql client on php. Lightweight replacement for the classic client.

## Installation

Just clone it. And don't forget make this script executable.

```
chmod u+x myphp
```

## Usage

```
./myphp --help
Usage: php ./MyPhp.php [OPTIONS] [database]
  --help Display this help and exit.
  -e     Execute command and quit.
  -h     Connect to host.
  -p     Password to use when connecting to server. If password is
         not given it's asked from the tty.
  -P     Port number to use for connection. Default is 3306.
  -u     User for login.
```

```
./myphp -h HOST -pPASSWORD -e "SHOW TABLES" -u USER -P 3306 DATABASE
+--------------------+
| Tables_in_DATABASE |
+--------------------+
| table_1            |
| table_2            |
+--------------------+
```

or more interactively way

```
./myphp -p -P 3306
host: HOST
username: USERNAME
password: PASSWORD
> USE DATABASE
Empty result
> SHOW TABLES
+--------------------+
| Tables_in_DATABASE |
+--------------------+
| table_1            |
| table_2            |
+--------------------+
> WRONG QUERY
Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the
right syntax to use near 'WRONG QUERY' at line 1
> quit
```

Also you can upload the `MyPhp.php` from your machine on any host via ssh. Really the script `myphp` is just a pretty
look alias.

```
[username@localhost ~]$ scp MyPhp.php username@remotehost:~
[username@localhost ~]$ ssh username@remotehost
[username@remotehost ~]$ php MyPhp.php #and so on
```


text:
package com.yiwen.coolweather.gson;

import com.google.gson.annotations.SerializedName;

/**
 * User: Yiwen(https://github.com/yiwent)
 * Date: 2017-04-04
 * Time: 10:02
 * FIXME
 */
public class Now {

    @SerializedName("tmp")
    public String temperature;

    @SerializedName("cond")
    public More   more;

    public class More {

        @SerializedName("txt")
        public String info;

    }
}


text:
namespace BellTowerEscape.Server
{
    public interface IGameCommand
    {

    }
}


text:
namespace rx
{

class WindowSurfaceVkGGP : public WindowSurfaceVk
{
  public:
    WindowSurfaceVkGGP(const egl::SurfaceState &surfaceState, EGLNativeWindowType window);

  private:
    egl::Error swapWithFrameToken(const gl::Context *context,
                                  EGLFrameTokenANGLE frameToken) override;
    angle::Result createSurfaceVk(vk::Context *context, gl::Extents *extentsOut) override;
    angle::Result getCurrentWindowSize(vk::Context *context, gl::Extents *extentsOut) override;
};

}  // namespace rx

#endif  // LIBANGLE_RENDERER_VULKAN_GGP_WINDOWSURFACEVKGGP_H_


text:
<!DOCTYPE html>

	<meta charset="utf-8" />
	<title>jmpress.js | cube example</title>

	<meta name="description" content="jmpress.js is a jQuery plugin to build a website on the infinite canvas">
	<meta name="author" content="Kyle Robinson Young @shama & Tobias Koppers @sokra" />
	<meta name="viewport" content="width=device-width, maximum-scale=1.0, initial-scale=1.0, user-scalable=yes" />
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />

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

		FRONT

		RIGHT

		BACK

		LEFT

		TOP

		BOTTOM


text:
<ion-header>

  <ion-navbar>
    <ion-title>New User Registration</ion-title>
  </ion-navbar>

</ion-header>

<ion-content class="login-content" padding>
  <button ion-button (click)='registerProvider()'>Service Providers click here</button>
  <div class="login-box">

    <form (ngSubmit)="register()" #registerForm="ngForm">
      <ion-row>
        <ion-col>
          <ion-list inset>

            <ion-item>
              <input type="text" placeholder="First Name" name="first_name" [(ngModel)]="registerCredentials.client.first_name">
            </ion-item>

            <ion-item>
              <input type="text" placeholder="Last Name" name="last_name" [(ngModel)]="registerCredentials.client.last_name">
            </ion-item>

            <ion-item>
              <input type="text" placeholder="Phone Number" name="last_name" [(ngModel)]="registerCredentials.client.phone_number">
            </ion-item>

            <ion-item>
              <input type="password" placeholder="Password" name="password" [(ngModel)]="registerCredentials.client.password" required>
            </ion-item>

          </ion-list>
        </ion-col>
      </ion-row>

      <ion-row>
        <ion-col class="signup-col">
          <button ion-button class="submit-btn" full type="submit" [disabled]="!registerForm.form.valid">Next</button>
        </ion-col>
      </ion-row>

    </form>
  </div>
</ion-content>


text:
Gather data. Skip boiler plate code.

Use Gatherable to dynamically create active record
models, controllers for those models, and routes for those controllers.
You can even use Gatherable to create Javascript objects to talk to your
new routes.

Gatherable was conceived with the purpose of gathering information about
the user experience. The idea is to gather various data points and link them
via a global identifier, so that relations between them can later be
analyzed

## Getting Started

### Include the gem in your Gemfile

`gem 'gatherable'`

### Define what to gather

In the root of your project, run

`rails generate gatherable initializer`

This will create following `config/initializers/gatherable.rb` file

```
Gatherable.configure do |c|
  c.global_identifier = :gatherable_id

  # c.data_point :data_point_name, :data_point_type, OPTIONS - see below
  c.data_point :price, :decimal

  #c.data_table :table_name, { column_name: :column_type, column_name2: :column_type }, OPTIONS - see below
  c.data_table :requested_loan_amount, { requested_loan_amount: :decimal, total_cost: :decimal, monthly_repayment_amount: :decimal }

  #  for both data tables and data points, you'll automatically get a primary key 'table_name_id',
  #  an indexed global identifier, and timestamps

  #If want your db schema to be something besides 'gatherable', uncomment the line below
  #c.schema_name = 'foo_bar'
end
```

Name your `global_identifier` however you want (you have ta have
one, sorry), and whatever data points you want to collect. Each data
point will later become its own table (see [below](#generate-migrations)).
Should you want more complex tables, use the `data_table` syntax shown above.

### Generate migrations
Gatherable will auto-generate the migrations to support the data points
you want to collect. The generated tables will live in a created
`gatherable` schema.

`rails generate gatherable migrations`

(you'll also want to run the migrations, of course)

### Mount the engine
In `config/routes.rb`, mount the gatherable engine. It'll look something
like this:

```
Rails.application.routes.draw do
  #whatever routes your app already has
  mount Gatherable::Engine => "/gatherable"
end
```

### Gather!

Models, controllers, and routes are dynamically defined when you configure
gatherable, so you're ready to roll!

For each data point you're collecting, there are up to five controller
methods already defined for you (you get to choose, see the [options section](#options)).

For a data point called `price`, the routes for these methods would look
like this:

```
GET    /prices(.:format)               =>  #index
POST   /prices(.:format)               =>  #create
GET    /prices/:price_id(.:format)     =>  #show
PUT    /prices/:price_id(.:format)     =>  #update
DELETE /prices/:price_id(.:format)     =>  #destroy
```

The `create` and `update` methods for gatherable data points requires a
specific param format, like so:

```
{ data_point_name: { attr_1: 'foo', attr_2: 'bar' } }
```

#### Use the given js file
Add the following line to your `application.js` file:
```
  //= require gatherable
```
This gives you a js object that makes ajax calls to the routes mentioned
above. The method signatures look like this:
```
  create: function(gatherableVar, options, globalIdentifier = null)
  show: function(gatherableVar, id, globalIdentifier = null)
  update: function(gatherableVar, id, options, globalIdentifier = null)
  index: function(gatherableVar, globalIdentifier = null)
  destroy: function(gatherableVar, id, globalIdentifier = null)

  # gatherableVar - the name of the data point / table
  # options a {column_name: value} js object
  # globalIdentifier: needed if you've explicitly made it a part of your routes (see prefixed_resources, below)
```
### Seeing the magic

If you want to customize the models or controllers that Gatherable
dynamically defines, simply generate them:

```
rails generate gatherable models
rails generate gatherable controllers
rails generate gatherable javascripts
```

### Options
Both `data_point`s and `data_table`s take an optional options hash.
Valid keys and values are outlined below.

* `:new_record_strategy`
  * `:insert` - when a new record is `POST`ed, insert it into the db
  * `:update` - instead of immediately inserting, see if there already
    exists a record with the same global id. Yes? update it. No? insert
  * defaults to `:insert`
  * see [below](#saving-some-space) for more information
* `:controller_actions` - an array containing any of the following:
  * `index`
  * `show`
  * `create`
  * `update`
  * `destroy`
  * defaults to `[:show, :create]`

The configuration also has additional options, enumerated below

*  `prefixed_resources` -
  Gatherable ties data points together using your `global_identifier`.
Adding a resource (data point) to the `prefixed_resources` array means
that the routes for that resources will all start with the
global_identifier, i.e.
  `GET /:session_id/prices`

  For the full list of routes, see the [gather!](#gather) section above

*  `auth_method`
  *If* you're using prefixed resources, you can ensure the
`global_identifier` value being passed is equivalent to the one for this
user's session; `auth_method = :session`

  If you're not using prefixed resources, gatherable uses sessions
behind the scenes to ensure that a user can only view / manipulate their own
data.

### Saving some space
If you're using this to track user interactions, you may find that this
engine creates quite a bit of data. In order to alleviate that, you can
use `new_record_strategy` for your data points / tables

`data_point :price, :decimal, new_record_strategy: :update #default is
:insert`

When using the `update` strategy, models will try to find a record with
the same `global_identifier` and update it. A record will be inserted if
there are none with a matching `gatherable_id`

Conversely, the `insert` strategy will not add an `updated_at` column to
your migrations, since you'll be inserting a new record each time

#### Credit
This was written partially on [Enova's](http://www.enova.com/) time /
dime


text:
template <class T>
class HeadNode : public Node <T>
{
protected:
	int ItemCount;		//item count	//wanted to use "item" member from Node class to hold count of items, but this does not work if Node is of type string

	Node<T> *last;		//pointer to last node

public:
	//Constructors
	HeadNode()
	{
		ItemCount = 0;
		last = nullptr;
	}

	HeadNode(const int &localItemCount)
	{
		ItemCount = localItemCount;
	}

	HeadNode(const int &localItemCount, Node<T> *headPointer)
	{
		ItemCount = localItemCount;
		next = headPointer;
	}

	HeadNode(const int &localItemCount, Node<T> *headPointer, Node<T> *tailPointer)
	{
		ItemCount = localItemCount;
		next = headPointer;
		last = tailPointer;
	}

	//Mutators
	void setItemCount(const int &localItemCount)
	{
		ItemCount = localItemCount;
	}

	void setLast(Node<T> *tailPointer)
	{
		last = tailPointer;
	}

	//Accessors
	int getItemCount() const
	{
		return ItemCount;
	}

	Node<T> *getLast() const
	{
		return last;
	}
};

#endif