text:
var unorderedList = [
    {
        name: 'Wolves',
        position: 2
    },
    {
        name: 'Villa',
        position: 4
    },
    {
        name: 'WBA',
        position: 1
    },
    {
        name: 'Birmingham',
        position: 3
    }
];

var sortByPositionStrategy = {
    sort: function() {
        unorderedList.sort(function(obj1, obj2){
            return obj1.position - obj2.position;
        });
    }
};

var sortByNameStrategy = {
    sort: function () {
        unorderedList.sort(function (obj1, obj2) {
            return obj1.name > obj2.name;
        });
    }
};

var footballTeams = {
    teams: unorderedList,
    sort: function() {
        this.strategy.sort();
    },
    strategy: sortByNameStrategy
};

console.info('unordered teams');
console.log(footballTeams.teams);

console.info('team name sorted teams');
footballTeams.sort();
console.log(footballTeams.teams);

console.info('position sorted teams');
footballTeams.strategy = sortByPositionStrategy;
footballTeams.sort();
console.log(footballTeams.teams);

redpajama_set_name: RedPajamaGithub


text:
$(function() {
	//
	// Enabling miniColors
	//

	$(".color-picker").miniColors({
		letterCase: 'uppercase',
		change: function(hex, rgb) {
			logData('change', hex, rgb);
		},
		open: function(hex, rgb) {
			logData('open', hex, rgb);
		},
		close: function(hex, rgb) {
			logData('close', hex, rgb);
		}
	});

	//
	// Only for the demo
	//

	function logData(type, hex, rgb) {
		$("#console").prepend(type + ': HEX = ' + hex + ', RGB = (' + rgb.r + ', ' + rgb.g + ', ' + rgb.b + ')
');
	}

	$("#disable").click( function() {
		$("#console").prepend('disable
');
		$(".color-picker").miniColors('disabled', true);
		$("#disable").prop('disabled', true);
		$("#enable").prop('disabled', false);
	});

	$("#enable").click( function() {
		$("#console").prepend('enable
');
		$(".color-picker").miniColors('disabled', false);
		$("#disable").prop('disabled', false);
		$("#enable").prop('disabled', true);
	});

	$("#makeReadonly").click( function() {
		$("#console").prepend('readonly = true
');
		$(".color-picker").miniColors('readonly', true);
		$("#unmakeReadonly").prop('disabled', false);
		$("#makeReadonly").prop('disabled', true);
	});

	$("#unmakeReadonly").click( function() {
		$("#console").prepend('readonly = false
');
		$(".color-picker").miniColors('readonly', false);
		$("#unmakeReadonly").prop('disabled', true);
		$("#makeReadonly").prop('disabled', false);
	});

	$("#destroy").click( function() {
		$("#console").prepend('destroy
');
		$(".color-picker").miniColors('destroy');
		$("INPUT[type=button]:not(#create)").prop('disabled', true);
		$("#destroy").prop('disabled', true);
		$("#create").prop('disabled', false);
	});

	$("#create").click( function() {
		$("#console").prepend('create
');
		$(".color-picker").miniColors({
			letterCase: 'uppercase',
			change: function(hex, rgb) {
				logData('change', hex, rgb);
			},
			open: function(hex, rgb) {
				logData('open', hex, rgb);
			},
			close: function(hex, rgb) {
				logData('close', hex, rgb);
			}
		});
		$("#makeReadonly, #disable, #destroy, #randomize").prop('disabled', false);
		$("#destroy").prop('disabled', false);
		$("#create").prop('disabled', true);
	});

	$("#randomize").click( function() {
		$(".color-picker").miniColors('value', '#' + Math.floor(Math.random() * 16777215).toString(16));
	});

});

// functions by usman start
	function cs_toggle(id){
		$("#"+id).toggle("slow");
	}

// functions by usman end


text:
Given("sample_new.yml file を作成したい") do

end

When("{string} と入力する") do |string|

end

Then("sample_new file が作成される") do
  MyHelp::Control.new.init_help("sample_new")
end


text:
package io.github.carlomicieli.scalakoans

import org.scalatest._
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner

@RunWith(classOf[JUnitRunner])
class AboutUniformAccessPrinciple extends FunSuite with ShouldMatchers {

  class CalculatesAgeUsingMethod(var currentYear: Int, birthYear: Int) {
    def age = currentYear - birthYear

    // calculated when method is called
  }

  class CalculatesAgeUsingProperty(var currentYear: Int, birthYear: Int) {
    val ageAsVal = currentYear - birthYear
    var ageAsVar = currentYear - birthYear
    lazy val ageAsLazy = currentYear - birthYear
    // calculated at instantiation, returns property when called
  }

  test("Can access age as parameterless method") {
    val me = new CalculatesAgeUsingMethod(2010, 2003)
    me.age should be(7)

    //! @#?! "Int does not take parameters"
    //! me.age() should be (7)
  }

  test("What happens when I update current year using method") {
    val me = new CalculatesAgeUsingMethod(2010, 2003)

    me.currentYear = 2011
    me.age should be(8)
  }

  test("Can access age as property") {
    val me = new CalculatesAgeUsingProperty(2010, 2003)
    me.ageAsVal should be(7)
    me.ageAsVar should be(7)
  }

  test("What happens when I update current year using property") {
    val me = new CalculatesAgeUsingProperty(2010, 2003)

    me.currentYear = 2011
    me.ageAsVal should be(7)
    me.ageAsVar should be(7)
    me.ageAsLazy should be(8)
  }
}


text:
title: "Основы ООП"
permalink: /bonus-2/01_oop_basics/
---

### Задания

Задания находятся в [репозитории](https://github.com/pyneng/pyneng-online-bonus-2/tree/master/exercises/01_oop_basics).

* Задания 1.1x про класс Topology. Тут достаточно знаний по основам Python
* Задания 1.2x и 1.3x про класс CiscoSSH. Тут уже надо знать как работать с netmiko, а в задании 1.2b нужен TextFSM

### Презентация

* [Основы ООП](https://gitpitch.com/natenka/pyneng-slides/py3-oop-1-basics#/). [PDF версия](https://github.com/pyneng/pyneng-online-bonus/raw/master/presentations/01_oop_basics.pdf)

### Дополнительные ресурсы

* Раздел "Объектно-ориентированное программирование" в книге "A Byte of Python": [русская версия](https://wombat.org.ua/AByteOfPython/object_oriented_programming.html), [английская версия](https://python.swaroopch.com/oop.html)
* [Отличный туториал по ООП (англ)](https://www.python-course.eu/python3_object_oriented_programming.php)
* Special Method Names:
  * [Dive Into Python 3](http://www.diveintopython3.net/special-method-names.html)
  * [Python docs](https://docs.python.org/3.6/reference/datamodel.html#specialnames)


text:
package scala.swing.examples

import java.awt.Insets

import scala.swing.GridBagPanel._
import scala.swing._

object GridBagDemo extends SimpleSwingApplication {
  lazy val ui: GridBagPanel = new GridBagPanel {
    val c = new Constraints
    val shouldFill = true
    if (shouldFill) {
      c.fill = Fill.Horizontal
    }

    val button1 = new Button("Button 1")

    c.weightx   = 0.5

    c.fill      = Fill.Horizontal
    c.gridx     = 0
    c.gridy     = 0
    layout(button1) = c

    val button2 = new Button("Button 2")
    c.fill      = Fill.Horizontal
    c.weightx   = 0.5
    c.gridx     = 1
    c.gridy     = 0
    layout(button2) = c

    val button3 = new Button("Button 3")
    c.fill      = Fill.Horizontal
    c.weightx   = 0.5
    c.gridx     = 2
    c.gridy     = 0
    layout(button3) = c

    val button4 = new Button("Long-Named Button 4")
    c.fill      = Fill.Horizontal
    c.ipady     = 40 //make this component tall
    c.weightx   = 0.0
    c.gridwidth = 3
    c.gridx     = 0
    c.gridy     = 1
    layout(button4) = c

    val button5 = new Button("5")
    c.fill      = Fill.Horizontal
    c.ipady     = 0 //reset to default
    c.weighty   = 1.0 //request any extra vertical space
    c.anchor    = Anchor.PageEnd
    c.insets    = new Insets(10, 0, 0, 0) //top padding
    c.gridx     = 1 //aligned with button 2
    c.gridwidth = 2 //2 columns wide
    c.gridy     = 2 //third row
    layout(button5) = c
  }

  def top: Frame = new MainFrame {
    title = "GridBag Demo"
    contents = ui
  }
}


text:
package db

import (
	"database/sql"
	"encoding/json"
	"time"

	"code.cloudfoundry.org/lager"
	sq "github.com/Masterminds/squirrel"
	"github.com/concourse/concourse/atc"
	"github.com/concourse/concourse/atc/db/lock"
)

type LastCheck struct {
	StartTime time.Time
	EndTime   time.Time
	Succeeded bool
}

//counterfeiter:generate . ResourceConfigScope

// ResourceConfigScope represents the relationship between a possible pipeline resource and a resource config.
// When a resource is specified to have a unique version history either through its base resource type or its custom
// resource type, it results in its generated resource config to be scoped to the resource. This relationship is
// translated into its row in the resource config scopes table to have both the resource id and resource config id
// populated. When a resource has a shared version history, its resource config is not scoped to the (or any) resource
// and its row in the resource config scopes table will have the resource config id populated but a NULL value for
// the resource id. Resource versions will therefore be directly dependent on a resource config scope.
type ResourceConfigScope interface {
	ID() int
	ResourceID() *int
	ResourceConfig() ResourceConfig

	SaveVersions(SpanContext, []atc.Version) error
	FindVersion(atc.Version) (ResourceConfigVersion, bool, error)
	LatestVersion() (ResourceConfigVersion, bool, error)

	AcquireResourceCheckingLock(
		logger lager.Logger,
	) (lock.Lock, bool, error)

	LastCheck() (LastCheck, error)
	UpdateLastCheckStartTime(int, *json.RawMessage) (bool, error)
	UpdateLastCheckEndTime(bool) (bool, error)
}

type resourceConfigScope struct {
	id             int
	resourceID     *int
	resourceConfig ResourceConfig

	conn        Conn
	lockFactory lock.LockFactory
}

func (r *resourceConfigScope) ID() int                        { return r.id }
func (r *resourceConfigScope) ResourceID() *int               { return r.resourceID }
func (r *resourceConfigScope) ResourceConfig() ResourceConfig { return r.resourceConfig }

func (r *resourceConfigScope) LastCheck() (LastCheck, error) {
	var lastCheckStartTime, lastCheckEndTime time.Time
	var lastCheckSucceeded bool
	err := psql.Select("last_check_start_time", "last_check_end_time", "last_check_succeeded").
		From("resource_config_scopes").
		Where(sq.Eq{"id": r.id}).
		RunWith(r.conn).
		QueryRow().
		Scan(&lastCheckStartTime, &lastCheckEndTime, &lastCheckSucceeded)
	if err != nil {
		return LastCheck{}, err
	}

	return LastCheck{
		StartTime: lastCheckStartTime,
		EndTime:   lastCheckEndTime,
		Succeeded: lastCheckSucceeded,
	}, nil
}

// SaveVersions stores a list of version in the db for a resource config
// Each version will also have its check order field updated and the
// Cache index for pipelines using the resource config will be bumped.
//
// In the case of a check resource from an older version, the versions
// that already exist in the DB will be re-ordered using
// incrementCheckOrder to input the correct check order
func (r *resourceConfigScope) SaveVersions(spanContext SpanContext, versions []atc.Version) error {
	return saveVersions(r.conn, r.ID(), versions, spanContext)
}

func saveVersions(conn Conn, rcsID int, versions []atc.Version, spanContext SpanContext) error {
	tx, err := conn.Begin()
	if err != nil {
		return err
	}

	defer Rollback(tx)

	var containsNewVersion bool
	for _, version := range versions {
		newVersion, err := saveResourceVersion(tx, rcsID, version, nil, spanContext)
		if err != nil {
			return err
		}

		containsNewVersion = containsNewVersion || newVersion
	}

	if containsNewVersion {
		// bump the check order of all the versions returned by the check if there
		// is at least one new version within the set of returned versions
		for _, version := range versions {
			versionJSON, err := json.Marshal(version)
			if err != nil {
				return err
			}

			err = incrementCheckOrder(tx, rcsID, string(versionJSON))
			if err != nil {
				return err
			}
		}

		err = requestScheduleForJobsUsingResourceConfigScope(tx, rcsID)
		if err != nil {
			return err
		}
	}

	err = tx.Commit()
	if err != nil {
		return err
	}

	return nil
}

func (r *resourceConfigScope) FindVersion(v atc.Version) (ResourceConfigVersion, bool, error) {
	rcv := &resourceConfigVersion{
		conn: r.conn,
	}

	versionByte, err := json.Marshal(v)
	if err != nil {
		return nil, false, err
	}

	row := resourceConfigVersionQuery.
		Where(sq.Eq{
			"v.resource_config_scope_id": r.id,
		}).
		Where(sq.Expr("v.version_md5 = md5(?)", versionByte)).
		RunWith(r.conn).
		QueryRow()

	err = scanResourceConfigVersion(rcv, row)
	if err != nil {
		if err == sql.ErrNoRows {
			return nil, false, nil
		}
		return nil, false, err
	}

	return rcv, true, nil
}

func (r *resourceConfigScope) LatestVersion() (ResourceConfigVersion, bool, error) {
	rcv := &resourceConfigVersion{
		conn: r.conn,
	}

	row := resourceConfigVersionQuery.
		Where(sq.Eq{"v.resource_config_scope_id": r.id}).
		OrderBy("v.check_order DESC").
		Limit(1).
		RunWith(r.conn).
		QueryRow()

	err := scanResourceConfigVersion(rcv, row)
	if err != nil {
		if err == sql.ErrNoRows {
			return nil, false, nil
		}
		return nil, false, err
	}

	return rcv, true, nil
}

func (r *resourceConfigScope) AcquireResourceCheckingLock(
	logger lager.Logger,
) (lock.Lock, bool, error) {
	return r.lockFactory.Acquire(
		logger,
		lock.NewResourceConfigCheckingLockID(r.resourceConfig.ID()),
	)
}

func (r *resourceConfigScope) UpdateLastCheckStartTime(buildId int, publicPlan *json.RawMessage) (bool, error) {
	tx, err := r.conn.Begin()
	if err != nil {
		return false, err
	}

	defer Rollback(tx)

	var buildIdValue interface{}
	if buildId != 0 {
		buildIdValue = buildId
	}
	updated, err := checkIfRowsUpdated(tx, `
		UPDATE resource_config_scopes
		SET last_check_start_time = now(), last_check_build_id = $1, last_check_build_plan = $2
		WHERE id = $3
	`, buildIdValue, publicPlan, r.id)
	if err != nil {
		return false, err
	}

	if !updated {
		return false, nil
	}

	err = tx.Commit()
	if err != nil {
		return false, err
	}

	return true, nil
}

func (r *resourceConfigScope) UpdateLastCheckEndTime(succeeded bool) (bool, error) {
	tx, err := r.conn.Begin()
	if err != nil {
		return false, err
	}

	defer Rollback(tx)

	updated, err := checkIfRowsUpdated(tx, `
		UPDATE resource_config_scopes
		SET last_check_end_time = now(), last_check_succeeded = $1
		WHERE id = $2
	`, succeeded, r.id)
	if err != nil {
		return false, err
	}

	if !updated {
		return false, nil
	}

	err = tx.Commit()
	if err != nil {
		return false, err
	}

	return true, nil
}

func saveResourceVersion(tx Tx, rcsID int, version atc.Version, metadata ResourceConfigMetadataFields, spanContext SpanContext) (bool, error) {
	versionJSON, err := json.Marshal(version)
	if err != nil {
		return false, err
	}

	metadataJSON, err := json.Marshal(metadata)
	if err != nil {
		return false, err
	}

	spanContextJSON, err := json.Marshal(spanContext)
	if err != nil {
		return false, err
	}

	var checkOrder int
	err = tx.QueryRow(`
		INSERT INTO resource_config_versions (resource_config_scope_id, version, version_md5, metadata, span_context)
		SELECT $1, $2, md5($3), $4, $5
		ON CONFLICT (resource_config_scope_id, version_md5)
		DO UPDATE SET metadata = COALESCE(NULLIF(excluded.metadata, 'null'::jsonb), resource_config_versions.metadata)
		RETURNING check_order
		`, rcsID, string(versionJSON), string(versionJSON), string(metadataJSON), string(spanContextJSON)).Scan(&checkOrder)
	if err != nil {
		return false, err
	}

	return checkOrder == 0, nil
}

// increment the check order if the version's check order is less than the
// current max. This will fix the case of a check from an old version causing
// the desired order to change; existing versions will be re-ordered since
// we add them in the desired order.
func incrementCheckOrder(tx Tx, rcsID int, version string) error {
	_, err := tx.Exec(`
		WITH max_checkorder AS (
			SELECT max(check_order) co
			FROM resource_config_versions
			WHERE resource_config_scope_id = $1
		)

		UPDATE resource_config_versions
		SET check_order = mc.co + 1
		FROM max_checkorder mc
		WHERE resource_config_scope_id = $1
		AND version_md5 = md5($2)
		AND check_order <= mc.co;`, rcsID, version)
	return err
}

// The SELECT query orders the jobs for updating to prevent deadlocking.
// Updating multiple rows using a SELECT subquery does not preserve the same
// order for the updates, which can lead to deadlocking.
func requestScheduleForJobsUsingResourceConfigScope(tx Tx, rcsID int) error {
	rows, err := psql.Select("DISTINCT j.job_id").
		From("job_inputs j").
		Join("resources r ON r.id = j.resource_id").
		Where(sq.Eq{
			"r.resource_config_scope_id": rcsID,
			"j.passed_job_id":            nil,
		}).
		OrderBy("j.job_id DESC").
		RunWith(tx).
		Query()
	if err != nil {
		return err
	}

	var jobIDs []int
	for rows.Next() {
		var id int
		err = rows.Scan(&id)
		if err != nil {
			return err
		}

		jobIDs = append(jobIDs, id)
	}

	for _, jID := range jobIDs {
		_, err := psql.Update("jobs").
			Set("schedule_requested", sq.Expr("now()")).
			Where(sq.Eq{
				"id": jID,
			}).
			RunWith(tx).
			Exec()
		if err != nil {
			return err
		}
	}

	return nil
}


text:
###### Easily put your screenshots into the right device frames

_frameit_ allows you to put a gorgeous device frame around your iOS and macOS screenshots just by running one simple command. Use _frameit_ to prepare perfect screenshots for the App Store, your website, QA or emails.

-------

    Features •
    Usage •
    Tips

-------

frameit is part of fastlane: The easiest way to automate beta deployments and releases for your iOS and Android apps.

# Features

## Frame screenshot

Put a gorgeous device frame around your iOS and macOS screenshots just by running one simple command. Support for:

- iPhone, iPad and Mac
- Portrait and Landscape modes
- Several device frame colors

The complete and updated list of supported devices and colors can be found [here](https://github.com/fastlane/frameit-frames/tree/gh-pages/latest)

Here is a nice gif, that shows _frameit_ in action:

![img/actions/FrameitGit.gif](/img/actions/FrameitGit.gif?raw=1)

## Advanced Features

- Put framed screenshot on colored background, define padding
- add text above or under framed screenshot
  - keyword + text
  - choose text font and color
  - multi line text
  - "intelligent" positioning of text that always looks good(ish)

## Results

![img/actions/ScreenshotsBig.png](/img/actions/ScreenshotsBig.png?raw=1)

-------

![img/actions/ScreenshotsOverview.png](/img/actions/ScreenshotsOverview.png?raw=1)

-------

![img/actions/MacExample.png](/img/actions/MacExample.png?raw=1)

The frameit 2.0 update was kindly sponsored by MindNode, seen in the screenshots above.

The first time that _frameit_ is executed the frames will be downloaded automatically. Originally the frames are coming from [Facebook frameset](http://facebook.design/devices) and they are kept on [this repo](https://github.com/fastlane/frameit-frames).

More information about this process and how to update the frames can be found [here](https://github.com/fastlane/fastlane/tree/master/frameit/frames_generator)

# Usage

## Basic Usage

Why should you have to use Photoshop, just to add a frame around your screenshots?

Just navigate to your folder of screenshots and use the following command:

```no-highlight
fastlane frameit
```

To use the silver version of the frames:

```no-highlight
fastlane frameit silver
```

To download the latest frames

```no-highlight
fastlane frameit download_frames
```

Note: When using _frameit_ without titles on top, the screenshots will have the full resolution, which means they can't be uploaded to the App Store directly. They are supposed to be used for websites, print media and emails. Check out the section below to use the screenshots for the App Store.

## Advanced Usage (optional)

### Text and Background

With _frameit_ it's possible to add a custom background and text below or above the framed screenshots in fonts and colors you define.

A working example can be found in the [fastlane examples](https://github.com/fastlane/examples/tree/master/MindNode/screenshots) project.

### `Framefile.json`

The Framefile allows to define general and screenshot specific information.
It has the following general JSON structure:

```json
{
  "device_frame_version": "latest",
  "default": {
    ...
  },
  "data": [
     ...
  ]
}
```

### General parameters

The general parameters are defined in the `default` key and can be:

| Key | Description | Default value |
|-----|-------------|---------------|
| `background` | The background that should be used for the framed screenshot. Specify the (relative) path to the image file (e.g. `*.jpg`). This parameter is mandatory. | NA |
| `keyword` | An object that contains up to 3 keys to describe the optional keyword. See [table](#keyword-and-title-parameters) below. | NA |
| `title` | An object that contains up to 3 keys to describe the mandatory title. See [table](#keyword-and-title-parameters) below. | NA |
| `stack_title` | Specifies whether _frameit_ should display the keyword above the title when both keyword and title are defined. If it is false, the title and keyword will be displayed side by side when both keyword and title are defined. | `false` |
| `title_below_image` | Specifies whether _frameit_ should place the title and optional keyword below the device frame. If it is false, it will be placed above the device frame. | `false` |
| `show_complete_frame` | Specifies whether _frameit_ should shrink the device frame so that it is completely shown in the framed screenshot. If it is false, clipping of the device frame might occur at the bottom (when `title_below_image` is `false`) or top (when `title_below_image` is `true`) of the framed screenshot. | `false` |
| `padding` | The content of the framed screenshot will be resized to match the specified `padding` around all edges. The vertical padding is also applied between the text and the top or bottom (depending on `title_below_image`) of the device frame.
 There are 3 different options of specyfying the padding:
 1. Default: An integer value that defines both horizontal and vertical padding in pixels.
 2. A string that defines (different) padding values in pixels for horizontal and vertical padding. The syntax is `"<horizontal>x<vertical>"`, e.g. `"30x60"`.
 3. A string that defines (different) padding values in percentage for horizontal and vertical padding. The syntax is `"<horizontal>%x<vertical>%"`, e.g. `"5%x10%"`.
 **Note:** The percentage is calculated from the smallest image dimension (height or width).
 A combination of option 2 and 3 is possible, e.g. `"5%x40"`. | `50` |
| `interline_spacing` | Specifies whether _frameit_ should add or subtract this many pixels between the individual lines of text. This only applies to a multi-line `title` and/or `keyword` to expand or squash together the individual lines of text. | `0` |
| `font_scale_factor` | Specifies whether _frameit_ should increase or decrease the font size of the text. | `0.1` |
| `frame` | Overrides the color of the frame to be used. (Valid values are `BLACK, `WHITE`, `GOLD` and `ROSE_GOLD`) | NA |

### Specific parameters

The screenshot specific parameters are related to the keyword and title texts.
These are defined in the `data` key. This is an array with the following keys for each screenshot:

| Key | Description |
|-----|-------------|
| `filter` | This is mandatory to link the individual configuration to the screenshot, based on part of the file name.
Example:
If a screenshot is named `iPhone 8-Brainstorming.png` you can use value `Brainstorming` for `filter`.  If there are more than one `filter` matching an entry, they will all be applied in order (which means that the last one has the highest precedence). All other keys from that array element will only be applied on this specific screenshot. |
| `keyword` | Similar use as in `default`, except that parameter `text` can be used here because it is screenshot specific. |
| `title` | Similar use as in `default`, except that parameter `text` can be used here because it is screenshot specific. |
| `frame` | Overrides the color of the frame to be used. (Valid values are `BLACK, `WHITE`, `GOLD` and `ROSE_GOLD`) | NA |

### Framefile `keyword` and `title` parameters

The `keyword` and `title` parameters are both used in `default` and `data`. They both consist of the following optional keys:

| Key | Description | Default value |
|-----|-------------|---------------|
| `color` | The font color for the text. Specify a hex/html color code. | `#000000` (black) |
| `font` | The font family for the text. Specify the (relative) path to the font file (e.g. an OpenType Font). | The default `imagemagick` font, which is system dependent. |
| `text` | The text that should be used for the `keyword` or `title`.
 Note: If you want to use localised text, use [`.strings` files](#strings-files). | NA |

### Example

```json
{
  "device_frame_version": "latest",
  "default": {
    "keyword": {
      "font": "./fonts/MyFont-Rg.otf"
    },
    "title": {
      "font": "./fonts/MyFont-Th.otf",
      "color": "#545454"
    },
    "background": "./background.jpg",
    "padding": 50,
    "show_complete_frame": false,
    "stack_title" : false,
    "title_below_image": true,
    "frame": "WHITE"
  },

  "data": [
    {
      "filter": "Brainstorming",
      "keyword": {
        "color": "#d21559"
      }
    },
    {
      "filter": "Organizing",
      "keyword": {
        "color": "#feb909"
      },
      "frame": "ROSE_GOLD"
    },
    {
      "filter": "Sharing",
      "keyword": {
        "color": "#aa4dbc"
      }
    },
    {
      "filter": "Styling",
      "keyword": {
        "color": "#31bb48"
      }
    }
  ]
}
```

You can find a more complex [configuration](https://github.com/fastlane/examples/blob/master/MindNode/screenshots/Framefile.json) to also support Chinese, Japanese and Korean languages.

The `Framefile.json` should be in the `screenshots` folder, as seen in the [example](https://github.com/fastlane/examples/tree/master/MindNode/screenshots).

### `.strings` files

To define the title and optionally the keyword, put two `.strings` files into the language folder (e.g. [en-US in the example project](https://github.com/fastlane/examples/tree/master/MindNode/screenshots/en-US))

The `keyword.strings` and `title.strings` are standard `.strings` file you already use for your iOS apps, making it easy to use your existing translation service to get localized titles.

**Notes**

- These `.strings` files **MUST** be utf-8 (UTF-8) or utf-16 encoded (UTF-16 BE with BOM). They also must begin with an empty line. If you are having trouble see [issue #1740](https://github.com/fastlane/fastlane/issues/1740)
- You **MUST** provide a background if you want titles. _frameit_ will not add the tiles if a background is not specified.

### Screenshot orientation

By default _frameit_ adds a frame to your screenshot based on an orientation you took it. For a portrait (vertical orientation) it is going to add portrait frame and for a landscape (horizontal orientation) - landscape left (= [Home button on the left side](https://developer.apple.com/documentation/uikit/uiinterfaceorientation/landscapeleft)).

One way to override the default behavior is editing the file name by adding `force_landscaperight` to the end.

### `force_orientation_block`

If the default behavior doesn't fit your needs and you don't want or can't rename your screenshots, you can customize _frameit_'s orientation behavior by setting a `force_orientation_block` parameter. The valid values are: `:landscape_left` (home button on the left side), `:landscape_right` (home button on the right side), `:portrait` (home button on the bottom), `nil` (home button on the right side).

### Examples

```ruby
# It matches the filename to the framed device orientation
frameit(
  path: "./fastlane/screenshots",
  force_orientation_block: proc do |filename|
    case filename
      when "iPad Pro (12.9-inch)-01LoginScreen"
        :landscape_right
      when "iPhone 6 Plus-01LoginScreen"
        :portrait
      # and so on
    end
  end
)
```

```ruby
# It frames the screenshots in landscape right whenever the filename contains `landscape` word
frameit(
  silver: true,
  path: "./fastlane/screenshots",
  force_orientation_block: proc do |filename|
    f = filename.downcase
    if f.include?("landscape")
      :landscape_right
    end
  end
)
```

# Mac

With _frameit_ it's possible to also frame macOS Application screenshots. You have to provide the following:

- A (relative) path to a `background` image file, which should contain both the background and the Mac.
- The `offset` information so _frameit_ knows where to position your screenshot on the `background`:
  - `offset` : A string that specifies the horizontal and vertical offset in pixels, with respect to the top left corner of the `background` image. The syntax is `"+<horizontal>+<vertical>"`, e.g. `"+200+150"`.
  - `titleHeight` : The height in pixels that should be used for the title.

## Example
```json
{
  "default": {
    "title": {
      "color": "#545454"
    },
    "background": "Mac.jpg",
    "offset": {
      "offset": "+676+479",
      "titleHeight": 320
    }
  },
  "data": [
    {
      "filter": "Brainstorming",
      "keyword": {
        "color": "#d21559"
      }
    }
  ]
}
```

Check out the [MindNode example project](https://github.com/fastlane/examples/tree/master/MindNode/screenshots).

# Tips

## Generate localized screenshots

Check out [_snapshot_](https://docs.fastlane.tools/actions/snapshot/) to automatically generate screenshots using ```UI Automation```.

## Upload screenshots

Use [_deliver_](https://docs.fastlane.tools/actions/deliver/) to upload iOS screenshots to App Store Connect, or [_supply_](https://docs.fastlane.tools/actions/supply/) to upload Android screenshots to Play Store completely automatically 🚀

## Use a clean status bar

You can use [SimulatorStatusMagic](https://github.com/shinydevelopment/SimulatorStatusMagic) to clean up the status bar.

## Gray artifacts around text

If you run into any quality issues, like having a border around the font, it usually helps to just re-install `imagemagick`. You can do so by running

```sh
brew uninstall imagemagick
brew install imagemagick
```

## Uninstall

- `sudo gem uninstall fastlane`
- `rm -rf ~/.frameit`


text:
<?php

defined('_JEXEC') or die;

JHtml::_('bootstrap.tooltip');
?>
<form action="<?php echo JRoute::_('index.php?option=com_admin&view=help'); ?>" method="post" name="adminForm" id="adminForm">

<?php echo JHtml::_('link', JHelp::createUrl('JHELP_START_HERE'), JText::_('COM_ADMIN_START_HERE'), array('target' => 'helpFrame')) ?>

<?php echo JHtml::_('link', $this->latest_version_check, JText::_('COM_ADMIN_LATEST_VERSION_CHECK'), array('target' => 'helpFrame')) ?>

<?php echo JHtml::_('link', 'http://www.gnu.org/licenses/gpl-2.0.html', JText::_('COM_ADMIN_LICENSE'), array('target' => 'helpFrame')) ?>

<?php echo JHtml::_('link', JHelp::createUrl('JHELP_GLOSSARY'), JText::_('COM_ADMIN_GLOSSARY'), array('target' => 'helpFrame')) ?>

<?php echo JText::_('COM_ADMIN_ALPHABETICAL_INDEX'); ?>

					<?php foreach ($this->toc as $k => $v): ?>

							<?php $url = JHelp::createUrl('JHELP_' . strtoupper($k)); ?>
							<?php echo JHtml::_('link', $url, $v, array('target' => 'helpFrame')); ?>

					<?php endforeach; ?>

			<iframe name="helpFrame" height="2100px" src="<?php echo $this->page; ?>" class="helpFrame table table-bordered">

	<input class="textarea" type="hidden" name="option" value="com_admin" />
</form>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace WebApplication
{
    public class SiteController : Controller
    {
        // GET: Site
        public ActionResult Index()
        {
            return View();
        }
    }
}


text:
from .card import Card
from ..squares import Square
from ..utility import Logger

class AdvanceTo(Card):
    '''
    Represents an "Advance to..." card, including checking
    whether the player passes go and collects £200.
    '''

    def __init__(self, square_name):
        '''
        The 'constructor'.
        '''
        self.destination_square_name = square_name

    def play(self, game, current_player):
        '''
        We move the player to the new square, giving them
        £200 if they pass go.
        '''
        # We need to find if the player is further round the board than
        # the destination square, so we can decide whether to give them
        # £200 for passing go...
        go_square_position = game.state.board.get_index(Square.Name.GO)
        destination_square_position = game.state.board.get_index(self.destination_square_name)
        player_position = current_player.state.square
        if (player_position > destination_square_position) and (destination_square_position != go_square_position):
            # The player has to pass Go to get to the destination...
            Logger.log("{0} gets £200 for passing Go".format(current_player.name))
            game.give_money_to_player(current_player, 200)

        # We move the player to the destination...
        current_player.state.square = destination_square_position
        game.player_has_changed_square(current_player)


text:
<?php
/*
Section: email-signup
Language: English
*/

$translations = array(
    /*
     Differences email-5.7-intro vs. email-8.0-intro:
     * Version 5.7 <-> Version 8.0
     * Port 3306 <-> Port 3307
     * Version 8.0 removes "(which is the default port for MySQL)"
     */
    'email-5.7-intro' => 'Thank you for registering your database account {$user} with db4free.net.

After confirming the link below, you have access to db4free.net\'s MySQL 5.7 database server. The host name to access the server is db4free.net and the port is 3306 (which is the default port for MySQL). You can use phpMyAdmin on our website to log in to the server.',

    'email-8.0-intro' => 'Thank you for registering your database account {$user} with db4free.net.

After confirming the link below, you have access to db4free.net\'s MySQL 8.0 database server. The host name to access the server is db4free.net and the port is 3307. You can use phpMyAdmin on our website to log in to the server.',

    'email-common' => 'Please use the following link to finish the registration process within the next 14 days. By clicking this link you confirm (again) that you understand that:

* db4free.net is a testing environment
* db4free.net is not suitable for production
* if you decide to use your db4free.net database in production despite the warnings, you do that at your own risk (very frequent backups are highly recommended)
* data loss and outages can happen at any time (any complaints about that will likely be ignored)
* the db4free.net team is not granting any warranty or liability of any kind
* the db4free.net team reserves the right to delete databases and/or accounts at any time without notice
* it is up to you to get the latest information from Twitter (https://twitter.com/db4free_net) and the db4free.net blog (https://www.mpopp.net/category/db4free/)
* db4free.net provides only a MySQL database, but no web space (there is nowhere to upload any files)

Further:

* db4free.net is a service for testing, not for hosting. Databases that store more than 200 MB data will be cleared at irregular intervals without notification
* Please remove data which you no longer need, or delete your no longer needed account (https://www.db4free.net/delete-account.php). This makes it easier to recover if a server crash occurs.

{$mailLink}

Can you help translating the db4free.net website? Please go to https://www.db4free.net/translate.php

If it was not you who has registered a database account on the db4free.net website, please ignore this email!

We hope you enjoy working with your database!

The db4free.net team
https://www.db4free.net',
);
?>


text:
<?php

error_reporting(E_ALL);
ini_set('display_errors', '1');

require("conexion_bd.php");

$id = $_POST['id_usuario'];
$nombre = $_POST['nombre'];
$apellido = $_POST['apellido'];
$email = $_POST['email'];
$direccion = $_POST['direccion'];
$telefono = $_POST['telefono'];
$piso = $_POST['piso'];

$sql=mysql_query("UPDATE docente SET nombre_docente='$nombre', apellido_docente='$apellido', email='$email', direccion='$direccion', telefono='$telefono', piso='$piso' WHERE id_docente='$id'");

mysql_close($link);

if ($sql > 0){

	header('Location: ../emergente/editar_docente_exitoso.php');
}else{
	echo "error al modificar el usuario";}

?>


text:
module Rhoconnect
  module Handler
    module Changes
      module ExecuteMethods
        # combined CUD filter (aka 'queue_updates')
        def execute_cud_handler(route_handler)
          _extract_cud_params
          _run_cud_handler(route_handler)
        end

        # individual filters
        def execute_create_handler(route_handler)
          _extract_cud_params
          _run_cud_handler(route_handler, 'create')
        end

        def execute_update_handler(route_handler)
          _extract_cud_params
          # merge specific 'update' params
          begin
            if params["update"]
              cud = params["update"]
              params.delete("update")
              params.merge!("update" => {params[:id] => cud})
            end
          rescue JSON::ParserError => jpe
            log jpe.message + jpe.backtrace.join("\n")
            throw :halt, [500, "Server error while processing client data"]
          rescue Exception => e
            log e.message + e.backtrace.join("\n")
            throw :halt, [500, "Internal server error"]
          end

          _run_cud_handler(route_handler, 'update')
        end

        def execute_delete_handler(route_handler)
          begin
            obj = current_client.get_object(:cd, params[:id])
            params.merge!("delete" => { params[:id] => obj } )
          rescue JSON::ParserError => jpe
            log jpe.message + jpe.backtrace.join("\n")
            throw :halt, [500, "Server error while processing client data"]
          rescue Exception => e
            log e.message + e.backtrace.join("\n")
            throw :halt, [500, "Internal server error"]
          end

          _run_cud_handler(route_handler, 'delete')
        end

        # encapsulate common code
        def _run_cud_handler(route_handler, operations = ['create', 'update', 'delete'])
          @handler = nil
          if operations.is_a?String
            operations = [operations]
          end
          if not current_source.is_pass_through?
            @handler = Rhoconnect::Handler::Changes::Runner.new(operations, @model, current_client, route_handler, params)
          else
            @handler = Rhoconnect::Handler::Changes::PassThroughRunner.new(operations, @model, current_client, route_handler, params)
          end
          catch_all do
            @handler.run
          end
          status 200
        end

        def _extract_cud_params
          begin
            if params["cud"]
              cud = JSON.parse(params["cud"])
              params.delete("cud")
              params.merge!(cud)
            end
          rescue JSON::ParserError => jpe
            log jpe.message + jpe.backtrace.join("\n")
            throw :halt, [500, "Server error while processing client data"]
          rescue Exception => e
            log e.message + e.backtrace.join("\n")
            throw :halt, [500, "Internal server error"]
          end
        end
      end
    end
  end
end


text:
_{restartSiteConfirm}

_{restartSiteTip}

	        <form action="#{ActionLink}" method="post" class="ajaxPostForm">
            <input id="Submit1" type="submit" value="_{restartSiteCmd}" class="btn" />
	        </form>


text:
package edu.harvard.canvas_data.cli.dump;

import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Path;
import java.util.logging.Logger;

import edu.harvard.canvas_data.cli.Command;
import edu.harvard.canvas_data.cli.ReturnStatus;
import edu.harvard.canvas_data.parser.Configuration;
import edu.harvard.canvas_data.parser.DumpManager;
import edu.harvard.data.client.DataClient;
import edu.harvard.data.client.DataConfigurationException;
import edu.harvard.data.client.canvas.api.CanvasApiClient;
import edu.harvard.data.client.canvas.api.CanvasDataDump;
import edu.harvard.data.client.canvas.api.UnexpectedApiResponseException;

public class DownloadAllNewCommand implements Command {

  private static final Logger log = Logger.getLogger("Canvas Data");

  @Override
  public ReturnStatus execute(final Configuration config, final PrintStream out)
      throws IOException, DataConfigurationException, UnexpectedApiResponseException {
    final DumpManager manager = new DumpManager(config);
    final CanvasApiClient api = new DataClient().getCanvasApiClient(config.getCanvasDataHost(),
        config.getCanvasApiKey(), config.getCanvasApiSecret());
    for (final CanvasDataDump dump : api.getDumps()) {
      if (manager.needToSaveDump(dump)) {
        final CanvasDataDump fullDump = api.getDump(dump.getDumpId());
        final Path scratchDir = manager.getScratchDumpDir(fullDump);
        final Path archiveDir = manager.getArchiveDumpDir(fullDump);
        log.info("Saving " + fullDump.getSequence());
        manager.saveDump(api, scratchDir, fullDump);
        manager.archiveDump(scratchDir, archiveDir);
      }
    }
    return ReturnStatus.OK;
  }

  @Override
  public String getDescription() {
    return "Download and archive all Canvas data dumps that are not already archived.";
  }

}


text:
@function can.compute
@parent canjs
@release 1.1
@link ../docco/compute/compute.html docco

@description Create an observable value.

@signature `can.compute( getterSetter[, context] )`

Create a compute that derives its value from [can.Map]s and other [can.computed can.compute]s.

@param {function(*+,*+)} getterSetter(newVal,oldVal) A function that gets and optionally sets the value of the compute.
When called with no parameters, _getterSetter_ should return the current value of the compute. When
called with a single parameter, _getterSetter_ should arrange things so that the next read of the compute
produces that value. This compute will automatically update its value when any [can.Map observable]
values are read via [can.Map.prototype.attr].

@param {Object} [context] The `this` to use when calling the `getterSetter` function.
@return {can.computed} A new compute.

@signature `can.compute( initialValue [, settings] )`

Creates a compute from a value and optionally specifies how to read, update, and
listen to changes in dependent values. This form of can.compute can be used to
create a compute that derives its value from any source.

@param {*} initialValue The initial value of the compute. If `settings` is
not provided, the compute simply updates its value to whatever the first argument
to the compute is.

    var age = can.compute(30);
    age() //-> 30
    age(31) //-> fires a "change" event

@param {computeSettings} [settings]

Configures all behaviors of the [can.computed compute]. The following cross
binds an input element to a compute:

    var input = document.getElementById("age")
    var value = can.compute("",{
		get: function(){
			return input.value;
		},
		set: function(newVal){
			input.value = newVal;
		},
		on: function(updated){
			input.addEventListener("change", updated, false);
		},
		off: function(updated){
			input.removeEventListener("change", updated, false);
		}
	})

@return {can.computed} The new compute.

@signature `can.compute( initialValue, setter(newVal,oldVal) )`

Create a compute that has a setter that can adjust incoming new values.

    var age = can.compute(6,function(newVal, oldVal){
      if(!isNaN(+newVal)){
        return +newVal;
      } else {
        return oldVal;
      }
    })

@param {*} initialValue

The initial value of the compute.

@param {function(*,*):*} setter(newVal,oldVal)

A function that is called when a compute is called with an argument. The function is passed
the first argumented passed to [can.computed compute] and the current value. If
`set` returns a value, it is used to compare to the current value of the compute. Otherwise,
`get` is called to get the current value of the compute and that value is used
to determine if the compute has changed values.

@return {can.computed} A new compute.

@signature `can.compute( object, propertyName [, eventName] )`

Create a compute from an object's property value. This short-cut
signature lets you create a compute on objects that have events
that be listened to with [can.bind].

    var input = document.getElementById('age')
    var age = can.compute(input,"value","change");

    var me = new can.Map({name: "Justin"});
    var name = can.compute(me,"name")

@param {Object} object An object that either has a `bind` method or
a has events dispatched on it via [can.trigger].

@param {String} propertyName The property value to read on `object`.  The
property will be read via `object.attr(propertyName)` or `object[propertyame]`.

@param {String} [eventName=propertyName] Specifies the event name to listen
to on `object` for `propertyName` updates.

@return {can.computed} A new compute.

@body

## Use

`can.compute` lets you make an observable value. Computes are similar
to [can.Map Observes], but they represent a single value rather than
a collection of values.

`can.compute` returns a [can.computed compute] function that can
be called to read and optionally update the compute's value.

It's also possible to derive a compute's value from other computes,
[can.Map]s, and [can.List]s. When the derived values
change, the compute's value will be automatically updated.

Use [can.computed.bind compute.bind] to listen for changes of the
compute's value.

## Observing a value

The simplest way to use a compute is to have it store a single value, and to set it when
that value needs to change:

    var tally = can.compute(12);
    tally(); // 12

    tally.bind("change",function(ev, newVal, oldVal){
      console.log(newVal,oldVal)
    })

    tally(13);
    tally(); // 13

Any value can be observed.  The following creates a compute
that holds an object and then changes it to an array.

    var data = can.compute({name: "Justin"})
    data([{description: "Learn Computes"}])

## Derived computes

If you use a compute that derives its
value from properties of a [can.Map] or other [can.compute]s, the compute will listen for changes in those
properties and automatically recalculate itself, emitting a _change_ event if its value
changes.

The following example shows creating a `fullName` compute
that derives its value from two properties on the `person` observe:

    var person = new can.Map({
        firstName: 'Alice',
        lastName: 'Liddell'
    });

    var fullName = can.compute(function() {
        return person.attr('firstName') + ' ' + person.attr('lastName');
    });
    fullName.bind('change', function(ev, newVal, oldVal) {
        console.log("This person's full name is now " + newVal + '.');
    });

    person.attr('firstName', 'Allison'); // The log reads:
    //-> "This person's full name is now Allison Liddell."

Notice how the definition of the compute uses `[can.Map.prototype.attr attr]`
to read the values of the properties of `person`. This is how the compute knows to listen
for changes.

## Translator computes - computes that update their derived values

Sometimes you need a compute to be able to translate one value to another. For example,
consider a widget that displays and allows you to update the progress in percent
of a task. It accepts a compute with values between 0 and 100. But,
our task observe has progress values between 0 and 1 like:

    var task = new can.Map({
      progress: 0.75
    })

Use `can.compute( getterSetter )` to create a compute that updates itself
when task's `progress` changes, but can also update progress when
the compute function is called with a value.  For example:

    var progressPercent = can.compute(function(percent){
      if(arguments.length){
        task.attr('progress', percent / 100)
      } else {
        return task.attr('progress') * 100
      }
    })

    progressPercent() // -> 75

    progressPercent(100)

    task.attr('progress') // -> 1

The following is a similar example that shows converting feet into meters and back:

@codestart
var wall = new can.Map({
    material: 'brick',
    length: 10 // in feet
});

var wallLengthInMeters = can.compute(function(lengthInM) {
    if(arguments.length) {
        wall.attr('length', lengthInM / 3.28084);
    } else {
        return wall.attr('length') * 3.28084;
    }
});

wallLengthInMeters(); // 3.048

// When you set the compute...
wallLengthInMeters(5);
wallLengthInMeters(); // 5
// ...the original Observe changes too.
wall.length;          // 16.4042
@codeend

## Events

When a compute's value is changed, it emits a _change_ event. You can listen for this change
event by using `[can.computed.bind bind]` to bind an event handler to the compute:

@codestart
var tally = can.compute(0);
tally.bind('change', function(ev, newVal, oldVal) {
    console.log('The tally is now at ' + newVal + '.');
});

tally(tally() + 5); // The log reads:
                    // 'The tally is now at 5.'
@codeend

## Using computes to build Controls

It's a piece of cake to build a `[can.Control]` off of the value of a compute. And since computes
are observable, it means that the view of that Control will update itself whenever the value
of the compute updates. Here's a simple slider that works off of a compute:

@codestart
var project = new Observe({
    name: 'A Very Important Project',
    percentDone: .35
});

SimpleSlider = can.Control.extend({ }, {
    init: function() {
        this.element.html(can.view(this.options.view, this.options));
    },
    '.handle dragend': function(el, ev) {
        var percent = this.calculateSliderPercent();
        // set the compute's value
        this.options.percentDone(percent);
    },
    '{percentDone} change': function(ev, newVal, oldVal) {
	       // react to the percentage changing some other way
        this.moveSliderTo(newVal);
    }
    // Implementing calculateSliderPercent and moveSliderTo
    // has been left as an exercise for the reader.
});

new SimpleSlider('#slider', {percentDone: project.compute('percentDone')});
@codeend

Now that's some delicious cake. More information on Controls can be found under `[can.Control]`.
There is also a full explanation of can.Map's `[can.Map.prototype.compute compute]`,
which is used in the last line of the example above.


text:
package com.microsoft.azure.management.timeseriesinsights.v2017_11_15;

import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * Properties of the EventHub event source.
 */
public class EventHubEventSourceCommonProperties extends AzureEventSourceProperties {
    /**
     * The name of the service bus that contains the event hub.
     */
    @JsonProperty(value = "serviceBusNamespace", required = true)
    private String serviceBusNamespace;

    /**
     * The name of the event hub.
     */
    @JsonProperty(value = "eventHubName", required = true)
    private String eventHubName;

    /**
     * The name of the event hub's consumer group that holds the partitions
     * from which events will be read.
     */
    @JsonProperty(value = "consumerGroupName", required = true)
    private String consumerGroupName;

    /**
     * The name of the SAS key that grants the Time Series Insights service
     * access to the event hub. The shared access policies for this key must
     * grant 'Listen' permissions to the event hub.
     */
    @JsonProperty(value = "keyName", required = true)
    private String keyName;

    /**
     * Get the name of the service bus that contains the event hub.
     *
     * @return the serviceBusNamespace value
     */
    public String serviceBusNamespace() {
        return this.serviceBusNamespace;
    }

    /**
     * Set the name of the service bus that contains the event hub.
     *
     * @param serviceBusNamespace the serviceBusNamespace value to set
     * @return the EventHubEventSourceCommonProperties object itself.
     */
    public EventHubEventSourceCommonProperties withServiceBusNamespace(String serviceBusNamespace) {
        this.serviceBusNamespace = serviceBusNamespace;
        return this;
    }

    /**
     * Get the name of the event hub.
     *
     * @return the eventHubName value
     */
    public String eventHubName() {
        return this.eventHubName;
    }

    /**
     * Set the name of the event hub.
     *
     * @param eventHubName the eventHubName value to set
     * @return the EventHubEventSourceCommonProperties object itself.
     */
    public EventHubEventSourceCommonProperties withEventHubName(String eventHubName) {
        this.eventHubName = eventHubName;
        return this;
    }

    /**
     * Get the name of the event hub's consumer group that holds the partitions from which events will be read.
     *
     * @return the consumerGroupName value
     */
    public String consumerGroupName() {
        return this.consumerGroupName;
    }

    /**
     * Set the name of the event hub's consumer group that holds the partitions from which events will be read.
     *
     * @param consumerGroupName the consumerGroupName value to set
     * @return the EventHubEventSourceCommonProperties object itself.
     */
    public EventHubEventSourceCommonProperties withConsumerGroupName(String consumerGroupName) {
        this.consumerGroupName = consumerGroupName;
        return this;
    }

    /**
     * Get the name of the SAS key that grants the Time Series Insights service access to the event hub. The shared access policies for this key must grant 'Listen' permissions to the event hub.
     *
     * @return the keyName value
     */
    public String keyName() {
        return this.keyName;
    }

    /**
     * Set the name of the SAS key that grants the Time Series Insights service access to the event hub. The shared access policies for this key must grant 'Listen' permissions to the event hub.
     *
     * @param keyName the keyName value to set
     * @return the EventHubEventSourceCommonProperties object itself.
     */
    public EventHubEventSourceCommonProperties withKeyName(String keyName) {
        this.keyName = keyName;
        return this;
    }

}


text:
package org.apache.drill.exec.resolver;

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

import org.apache.drill.common.exceptions.UserException;
import org.apache.drill.common.expression.FunctionCall;
import org.apache.drill.common.expression.LogicalExpression;
import org.apache.drill.common.types.TypeProtos;
import org.apache.drill.exec.expr.fn.DrillFuncHolder;

public class DefaultFunctionResolver implements FunctionResolver {

  private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(DefaultFunctionResolver.class);

  @Override
  public DrillFuncHolder getBestMatch(List<DrillFuncHolder> methods, FunctionCall call) {

    float bestCost = Float.POSITIVE_INFINITY, currCost = Float.POSITIVE_INFINITY;
    DrillFuncHolder bestMatch = null;
    final List<DrillFuncHolder> bestMatchAlternatives = new LinkedList<>();
    List<TypeProtos.MajorType> argumentTypes = call.args().stream()
            .map(LogicalExpression::getMajorType)
            .collect(Collectors.toList());

    for (DrillFuncHolder h : methods) {
      currCost = TypeCastRules.getCost(argumentTypes, h);

      if (currCost < bestCost) {
        bestCost = currCost;
        bestMatch = h;
        bestMatchAlternatives.clear();
      } else if (currCost == bestCost && currCost < Float.POSITIVE_INFINITY) {
        // keep log of different function implementations that have the same best cost
        bestMatchAlternatives.add(h);
      }
    }

    if (bestCost == Float.POSITIVE_INFINITY) {
      //did not find a matched func implementation, either w/ or w/o implicit casts
      //TODO: raise exception here?
      return null;
    }
    if (bestMatchAlternatives.size() > 0) {
      logger.info("Multiple functions with best cost found, query processing will be aborted.");

      // printing the possible matches
      logger.debug("Printing all the possible functions that could have matched: ");
      for (DrillFuncHolder holder : bestMatchAlternatives) {
        logger.debug(holder.toString());
      }

      throw UserException.functionError()
        .message(
          "There are %d function definitions with the same casting cost for " +
          "%s, please write explicit casts disambiguate your function call.",
          1+bestMatchAlternatives.size(),
          call
        )
        .build(logger);
    }
    return bestMatch;
  }
}


text:
#include <aws/comprehend/model/DetectEntitiesRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Comprehend::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

DetectEntitiesRequest::DetectEntitiesRequest() :
    m_textHasBeenSet(false),
    m_languageCode(LanguageCode::NOT_SET),
    m_languageCodeHasBeenSet(false),
    m_endpointArnHasBeenSet(false)
{
}

Aws::String DetectEntitiesRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_textHasBeenSet)
  {
   payload.WithString("Text", m_text);

  }

  if(m_languageCodeHasBeenSet)
  {
   payload.WithString("LanguageCode", LanguageCodeMapper::GetNameForLanguageCode(m_languageCode));
  }

  if(m_endpointArnHasBeenSet)
  {
   payload.WithString("EndpointArn", m_endpointArn);

  }

  return payload.View().WriteReadable();
}

Aws::Http::HeaderValueCollection DetectEntitiesRequest::GetRequestSpecificHeaders() const
{
  Aws::Http::HeaderValueCollection headers;
  headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "Comprehend_20171127.DetectEntities"));
  return headers;

}


text:
<?php

namespace Cmsable\Contacts;

use DateTime;
use Illuminate\Database\Eloquent\Model;

class Contact extends Model
{

    /**
    * The database table used by the model.
    *
    * @var string
    */
    protected $table = 'contacts';

    /**
    * The attributes that are mass assignable.
    *
    * @var array
    */
    protected $guarded = ['user_id', 'id'];

    public function address(){
        return $this->hasOne('Cmsable\Addresses\Address');
    }

    public function user(){
        return $this->belongsTo('App\User','user_id');
    }

    public function category()
    {
        return $this->belongsTo('Cmsable\Contacts\ContactCategory');
    }

    public function profile()
    {
        return $this->hasOne('Cmsable\Contacts\Profile');
    }

    public function getSummaryAttribute()
    {
        return $this->forename . ' ' . $this->surname;
    }

    public static function byEmail($email)
    {
        return static::where('users.email', $email)
                       ->select('contacts.*','users.email')
                       ->join('users','users.id','=','contacts.user_id');
    }

}


text:
#include "Coap.h"
#include "CoapRequest.h"
#include "CoapClient.h"
#include "Queue.h"

// SMING includes
#include <Wiring/WMath.h>
#include <SmingCore/SmingCore.h>

CoapClient::CoapClient() {

	debugf("CoapClient: ctor is called.\n");

	message_id = (unsigned short) rand();   // calculate only once

	retransmissionTimer.initializeMs(1000, TimerDelegate(&CoapClient::timerTick, this));
}

CoapClient::~CoapClient() {
	debugf("CoapClient: destructor is called.\n");
}

// Callback called by the CoapResponse class
void CoapClient::onResponse(bool successful, CoapRequest *request, CoapPDU *pdu) {
	coap_tid_t tid = request->getTransactionId();

	debugf("CoapClient: onResponse (%d, %d).\n", successful, request->getTransactionId());

	if (! successful) {
		LOG_COAP_ERROR("CoapClient: malformed CoAP packet");
		return;
	}

	/* check if this is a response to our original request */
	//	if (!check_token(&pkt)) {
	//		debugf("wrong token\n");
	//		/* drop if this was just some message, or send RST in case of notification */
	//		if (recvPDU->getType() == CoapPDU::COAP_CONFIRMABLE || recvPDU->getType() == CoapPDU::COAP_NON_CONFIRMABLE) {
	//			// TODO send connection reset
	//			// coap_send_rst(pkt);  // send RST response
	//			// or, just ignore it.
	//		}
	//		goto end;
	//	}

	if (pdu->getType() == CoapPDU::COAP_RESET) {
		debugf("got RST\n");
		// goto end;
	}

	coap_queue_t *node = coapGetNodeById(&pQueue, tid);

	if (node) {
		debugf("CoapClient: Found request for transaction id\n");

		if (node->pdu->getType() == CoapPDU::COAP_NON_CONFIRMABLE) {
			// we got a response, we are done
			debugf("CoapClient: Got response for NONCONFIRMABLE MESSAGE\n");
		} else if (node->pdu->getType() == CoapPDU::COAP_CONFIRMABLE) {
			debugf("CoapClient: Got response for CONFIRMABLE MESSAGE\n");

			if (pdu->getType() == CoapPDU::COAP_ACKNOWLEDGEMENT) {
				debugf("CoapClient: got ACK\n");
			} else {
				debugf("CoapClient: got Message but waiting for ACK\n");
			}
		}
		/* transaction done, remove the PDU from queue */

		// stop timer
		timerStop();

		if (callbacks.contains(tid)) {
				callbacks[tid](true, *pdu);
				callbacks.remove(tid);
				// remove the PDU
				debugf("CoapClient: remove node for transaction %d.\n", tid);
				// close request, TODO what about observe
				request->close();
				coapRemoveNode(&pQueue, tid);
		} else {
			debugf("got unknown message Id\n");
			// TODO RESET
		}

		// calculate time elapsed
		timerUpdate();
		timerRestart();

		if (COAP_RESPONSE_CLASS(pdu->getCode()) == 2) {
			/* There is no block option set, just read the data and we are done. */
			debugf("%d.%02d\t", (pdu->getCode() >> 5), pdu->getCode() & 0x1F);
			pdu->printHex();
		} else if (COAP_RESPONSE_CLASS(pdu->getCode()) >= 4) {
			debugf("%d.%02d\t", (pdu->getCode() >> 5), pdu->getCode() & 0x1F);
			pdu->printHex();
		}
	} else {
		debugf("CoapClient: Could not found request for transaction id\n");
		// TODO send reset
	}
}

int CoapClient::request(CoapPDU::Type conn_type, CoapPDU::Code method,
		String uri, CoapPDU::ContentFormat format, String payload /* "" */, CoapResponseDelegate callback /* nullptr */) {

	debugf("CoapClient: REQUEST (%d) (%s)\n", method, uri.c_str());
	debugf("CoapClient: CONN_TYPE (%d)\n", conn_type);
	debugf("CoapClient: FORMAT (%d)\n", format);

	if ( conn_type != CoapPDU::COAP_CONFIRMABLE && conn_type != CoapPDU::COAP_NON_CONFIRMABLE ) {
		debugf("CoapClient: wrong connection type, setting to CONFIRMABLE.\n");
		conn_type = CoapPDU::COAP_CONFIRMABLE ; // default to CONFIRMABLE
	}

	URL resource(uri);

	if (resource.Protocol.equals(DEFAULT_URL_PROTOCOL)) {
		resource.Protocol = COAP_DEFAULT_SCHEME;
	}

	if (resource.Port == 80) {
		resource.Port = COAP_DEFAULT_PORT;
	}

	if (resource.Host.length() == 0)
		return debugf("CoapClient: wrong URI format.");

	struct ip_addr resolvedIP;
	int result = dns_gethostbyname(resource.Host.c_str(), &resolvedIP, staticDnsResponse, (void*) this);

	if (result == ERR_OK)  {
		// Documentation says this will be the result if the string is already
		// an ip address in dotted decimal form or if the host is found in dns cache.
		// however I'm not sure if the dns cache is working since this never seems to
		// be called for a host lookup other than an ip address.
		// Doesn't really matter since the loockup will be fast anyways, the host
		// is most likely found in the dns cache of the next PDU the query is sent to.
		CoapPDU& pdu = builPDU(conn_type, method, resource, format, payload);

#ifdef COAP_DEBUG
		pdu.printHuman();
#endif
		// connect to server
		CoapRequest *req = new CoapRequest(resolvedIP, resource.Port, CoapRxDelegate(&CoapClient::onResponse, this));

		coap_tid_t tid = doRequest(*req, pdu);

		callbacks[tid] = callback;
	} else if (result == ERR_INPROGRESS)  {
		// TODO store request and start retry timer
		debugf("DNS IP lookup in progress.");
	} else {
		debugf("DNS lookup error occurred.");
	}

	return 0;
}

coap_tid_t CoapClient::doRequest(CoapRequest &req, CoapPDU &pdu) {

	coap_queue_t *queueNode;
	coap_tid_t tid = COAP_INVALID_TID;
	timestamp diff;
	uint32 r;

	queueNode = coapAllocNode();
	if (!queueNode) {
		debugf("CoapClient: sendPDUConfirmed, insufficient memory\n");
		return COAP_INVALID_TID;
	}

	if (pdu.getType() == CoapPDU::COAP_CONFIRMABLE) {
		debugf("CoapClient: Send PDU confirmed\n");

		/* Set timer for pdu retransmission. If this is the first element in
		 * the retransmission queue, the base time is set to the current
		 * time and the retransmission time is PDU->timeout. If there is
		 * already an entry in the transmission queue, we must check if this PDU is
		 * to be retransmitted earlier. Therefore, PDU->timeout is first
		 * normalized to the timeout and then inserted into the queue with
		 * an adjusted relative time.
		 */

		queueNode->retransmit_cnt = 0;

		r = rand();

		/* add randomized RESPONSE_TIMEOUT to determine retransmission timeout */
		queueNode->timeout = COAP_DEFAULT_RESPONSE_TIMEOUT * COAP_TICKS_PER_SECOND +
				(COAP_DEFAULT_RESPONSE_TIMEOUT >> 1) *
				((COAP_TICKS_PER_SECOND * (r & 0xFF)) >> 8);

	} else {
		debugf("CoapClient: Send PDU non-confirmed\n");
		// Queue non-confirmable PDUs in order handle failed transmissions
		queueNode->timeout = COAP_DEFAULT_RESPONSE_TIMEOUT * COAP_TICKS_PER_SECOND;
	}

	queueNode->req = &req;
	queueNode->pdu = &pdu;

#ifdef COAP_DEBUG
	debugf("CoapClient: Sending ...\n");
	pdu.printHex();
#endif

	// send packet
    queueNode->id = req.sendPDU(pdu);

	timerStop();
	timerUpdate();
	queueNode->t = queueNode->timeout;
	coapAddNode(&pQueue, queueNode);
	timerRestart();

	return queueNode->id;
}

CoapPDU& CoapClient::builPDU(CoapPDU::Type conn_type, CoapPDU::Code method, URL resource,
		CoapPDU::ContentFormat format, String payload /* "" */) {
	// construct CoAP packet
	CoapPDU *pdu = new CoapPDU();
	pdu->setVersion(1);
	pdu->setType(conn_type);
	pdu->setCode(method);
	pdu->setToken((uint8_t*)"\3\2\1\1", 4);
	pdu->setMessageID(message_id);
	pdu->setURI((char*) resource.getPathWithQuery().c_str(), resource.getPathWithQuery().length());
	pdu->setContentFormat(format);

	if (payload.length() > 0) {
		debugf("CoapClient: PDU has payload\n");
		debugf("%s\n", payload.c_str());
		pdu->setPayload((unsigned char*) payload.c_str(), payload.length());
	}

	message_id++;

	return *pdu;
};

void CoapClient::staticDnsResponse(const char *name, struct ip_addr *ip, void *arg) {
	// DNS has been resolved

	CoapClient *self = (CoapClient*) arg;

	// TODO get last request and repeat
	if (ip != NULL) {
		// We do a new request since the last one was never done.
		//self->internalRequestTime(*ip);
	}
}

/** Retransmission handling */

void CoapClient::timerRestart() {
	if (pQueue) {
		// if there is a PDU in the queue, set timeout to its ->t.
		retransmissionTimer.setIntervalMs(pQueue->t);
		retransmissionTimer.startOnce();
	}
}

void CoapClient::timerStop() {
	retransmissionTimer.stop();
}

void CoapClient::timerTick() {
	coap_queue_t *node = coapPopNext(&pQueue);

	// non-confirmable PDU could not be sent, inform callback
	if (node->pdu->getType() == CoapPDU::COAP_NON_CONFIRMABLE) {
		debugf("CoapClient: non-confirmable PDU with transaction id %d could not be sent\n", node->id);
		// call callback
		if (callbacks.contains(node->id)) {
			callbacks[node->id](false, *node->pdu);
		}
		// remove PDU
		//   coapRemoveNode(&pQueue, node->id);
		coapDeleteNode(node);
	} else {
		/* re-initialize timeout when maximum number of retransmissions are not reached yet */
		if (node->retransmit_cnt < COAP_DEFAULT_MAX_RETRANSMIT) {
			node->retransmit_cnt++;
			node->t = node->timeout << node->retransmit_cnt;

			debugf("CoapClient: retransmission #%d of transaction %d\n", node->retransmit_cnt, node->id);

			// re-transmit PDU
			node->id = node->req->sendPDU(*node->pdu);
			if (COAP_INVALID_TID == node->id) {
				debugf("CoapClient: error sending PDU\n");
				coapDeleteNode(node);
			} else {
				coapAddNode(&pQueue, node);
			}
		} else {
			debugf("CoapClient: maximum retransmissions for transaction %d reached.\n", node->id);
			/* Maximum number of retransmissions reached. Inform the callback and remove PDU */
			if (callbacks.contains(node->id)) {
				callbacks[node->id](false, *node->pdu);
			}
			coapDeleteNode(node);
		}
	}

	timerRestart();
}

void CoapClient::timerUpdate() {
	timestamp diff = 0;
	coap_queue_t *first = pQueue;
	timerElapsed(&diff); // update: basetime = now, diff = now - oldbase, means time elapsed

	if (first) {
		// diff ms time is elapsed, re-calculate the first PDU->t
		if (first->t >= diff){
			first->t -= diff;
		} else {
			first->t = 0;  // when timer enabled, time out almost immediately
		}
	}
}

void CoapClient::timerElapsed(timestamp *diff) {
	timestamp now = system_get_time() / 1000;   // coap_tick_t is in ms. also sys_timer

	if (now >= basetime) {
		*diff = now-basetime;
	} else {
		*diff = now + SYS_TIME_MAX -basetime;
	}
	basetime = now;
}

// Methods
int CoapClient::get(String uri, CoapResponseDelegate responseCallback) {
	return get(CoapPDU::COAP_NON_CONFIRMABLE, uri, responseCallback);
}

int CoapClient::get(CoapPDU::Type connType, String uri, CoapResponseDelegate responseCallback) {
	debugf("CoapClient: GET (%s)", uri.c_str());
	return this->request(connType, CoapPDU::COAP_GET, uri, CoapPDU::ContentFormat::COAP_CONTENT_FORMAT_TEXT_PLAIN, "", responseCallback);
}

int CoapClient::post(String uri, CoapResponseDelegate responseCallback) {
	return post(CoapPDU::COAP_NON_CONFIRMABLE, uri, responseCallback);
}

int CoapClient::post(CoapPDU::Type connType, String uri, CoapResponseDelegate responseCallback) {
	return post(connType, uri, "", responseCallback);
}

int CoapClient::post(CoapPDU::Type connType, String uri, String payload, CoapResponseDelegate responseCallback) {
	return post(connType, uri, CoapPDU::ContentFormat::COAP_CONTENT_FORMAT_APP_JSON, payload, responseCallback);
}

int CoapClient::post(CoapPDU::Type connType, String uri, CoapPDU::ContentFormat format, String payload, CoapResponseDelegate responseCallback) {
	debugf("CoapClient: POST (%s)", uri.c_str());
	return this->request(connType, CoapPDU::COAP_POST, uri, format, payload, responseCallback);
}

int CoapClient::put(CoapPDU::Type conn_type, String uri, CoapPDU::ContentFormat format, String payload, CoapResponseDelegate responseCallback) {
	debugf("CoapClient: PUT (%s)", uri.c_str());
	return this->request(conn_type, CoapPDU::COAP_PUT, uri, format, payload, responseCallback);
}

int CoapClient::del(CoapPDU::Type conn_type, String uri, CoapResponseDelegate responseCallback) {
	debugf("CoapClient: DELETE (%s)", uri.c_str());
	return this->request(conn_type, CoapPDU::COAP_DELETE, uri, CoapPDU::ContentFormat::COAP_CONTENT_FORMAT_TEXT_PLAIN, "", responseCallback);
}

int CoapClient::observe(CoapPDU::Type conn_type, String uri, CoapResponseDelegate responseCallback) {
	debugf("CoapClient: OBSERVE (%s)", uri.c_str());
	return this->request(conn_type, CoapPDU::COAP_GET, uri, CoapPDU::ContentFormat::COAP_CONTENT_FORMAT_TEXT_PLAIN, "", responseCallback);
}


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.9.2"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>GrPPI: FieldHelper Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

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

GrPPI
    1.0

Generic and Reusable Parallel Pattern Interface

Public Member Functions |
Public Attributes |
List of all members

FieldHelper Class Reference

#include <gmock_link_test.h>

Public Member Functions

 	FieldHelper (int a_field)

int 	field () const

 	FieldHelper (int a_field)

int 	field () const

Public Attributes

int 	field_

Constructor & Destructor Documentation

◆ FieldHelper() [1/2]

          FieldHelper::FieldHelper
          (
          int
          a_field	)

inlineexplicit

◆ FieldHelper() [2/2]

          FieldHelper::FieldHelper
          (
          int
          a_field	)

inlineexplicit

Member Function Documentation

◆ field() [1/2]

          int FieldHelper::field
          (
          	)
           const

inline

◆ field() [2/2]

          int FieldHelper::field
          (
          	)
           const

inline

Member Data Documentation

◆ field_

          int FieldHelper::field_

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

cmake-build-debug/googletest-src/googlemock/test/gmock_link_test.h

cmake-build-release/googletest-src/googlemock/test/gmock_link_test.h

<address class="footer">
Generated by  1.9.2
</address>


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=constant.CL_BUILD_PROGRAM_FAILURE.html">

Redirecting to constant.CL_BUILD_PROGRAM_FAILURE.html...


text:
namespace Google.Cloud.OsConfig.V1Alpha.Snippets
{
    // [START osconfig_v1alpha_generated_OsConfigZonalService_ListInventories_sync_flattened_resourceNames]
    using Google.Api.Gax;
    using Google.Cloud.OsConfig.V1Alpha;
    using System;

    public sealed partial class GeneratedOsConfigZonalServiceClientSnippets
    {
        /// <summary>Snippet for ListInventories</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public void ListInventoriesResourceNames()
        {
            // Create client
            OsConfigZonalServiceClient osConfigZonalServiceClient = OsConfigZonalServiceClient.Create();
            // Initialize request argument(s)
            InstanceName parent = InstanceName.FromProjectLocationInstance("[PROJECT]", "[LOCATION]", "[INSTANCE]");
            // Make the request
            PagedEnumerable<ListInventoriesResponse, Inventory> response = osConfigZonalServiceClient.ListInventories(parent);

            // Iterate over all response items, lazily performing RPCs as required
            foreach (Inventory item in response)
            {
                // Do something with each item
                Console.WriteLine(item);
            }

            // Or iterate over pages (of server-defined size), performing one RPC per page
            foreach (ListInventoriesResponse page in response.AsRawResponses())
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (Inventory item in page)
                {
                    // Do something with each item
                    Console.WriteLine(item);
                }
            }

            // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
            int pageSize = 10;
            Page<Inventory> singlePage = response.ReadPage(pageSize);
            // Do something with the page of items
            Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
            foreach (Inventory item in singlePage)
            {
                // Do something with each item
                Console.WriteLine(item);
            }
            // Store the pageToken, for when the next page is required.
            string nextPageToken = singlePage.NextPageToken;
        }
    }
    // [END osconfig_v1alpha_generated_OsConfigZonalService_ListInventories_sync_flattened_resourceNames]
}


text:
package ru.aplana.app.jaxb_builders;

import static java.lang.ThreadLocal.withInitial;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Optional;

import javax.xml.bind.JAXBContext;
import javax.xml.datatype.DatatypeFactory;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import interfaces.Builder;
import ru.aplana.app.control.call.WallType;
import ru.aplana.jaxb.JaxbContexts;
import ru.aplana.tools.XmlHelper;
import ru.aplana.model.xsd.jaxb.oki.InfoRealestateObjectType.AddressRealestateObject;
import ru.aplana.model.xsd.jaxb.oki.InfoRealestateObjectType.InfoRealestateObject;
import ru.aplana.model.xsd.jaxb.oki.SrvGetClientExtendedRateRqType.Office;
import ru.aplana.model.xsd.jaxb.srg.BodyType;
import ru.aplana.model.xsd.jaxb.srg.GeneralType;
import ru.aplana.model.xsd.jaxb.srg.HeadType;
import ru.aplana.model.xsd.jaxb.srg.MessUIDType;
import ru.aplana.model.xsd.jaxb.srg.ObjectFactory;
import ru.aplana.model.xsd.jaxb.srg.RealtyValuationRqType;

public class RealtyValuationRqBuilder implements Builder {

	private static final ThreadLocal<SimpleDateFormat> DF = withInitial(
			() -> new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"));
	private static final Logger logger = LogManager.getFormatterLogger(RealtyValuationRqBuilder.class.getName());
	private static JAXBContext jaxbCtx;
	private final String messId;
	private final String kindObj;
	private final Optional<AddressRealestateObject> address;
	private final Optional<InfoRealestateObject> info;
	private final Office office;
	private final String appNum;

	static {
		jaxbCtx = JaxbContexts.getInstance().getJAXBContext(RealtyValuationRqType.class.getPackage().getName(),
				ObjectFactory.class.getClassLoader());
	}

	public RealtyValuationRqBuilder(Builder builder) {
		this.messId = builder.messId;
		this.kindObj = builder.kindObj;
		this.address = builder.address;
		this.info = builder.info;
		this.office = builder.office;
		this.appNum = builder.appNum;
	}

	public static class Builder {
		private final String messId;
		private String kindObj;
		private Optional<AddressRealestateObject> address;
		private Optional<InfoRealestateObject> info;
		private Office office;
		private final String appNum;

		public Builder(String messId, String appNum) {
			this.messId = messId;
			this.appNum = appNum;
		}

		public Builder setKindObj(String kindObj) {
			this.kindObj = kindObj;
			return this;
		}

		public Builder setAddress(Optional<AddressRealestateObject> address) {
			this.address = address;
			return this;
		}

		public Builder setInfo(Optional<InfoRealestateObject> info) {
			this.info = info;
			return this;
		}

		public Builder setOffice(Office office) {
			this.office = office;
			return this;
		}

		public RealtyValuationRqBuilder build() {
			return new RealtyValuationRqBuilder(this);
		}
	}

	@Override
	public XmlHelper getXmlHelper() {
		return new XmlHelper(jaxbCtx);
	}

	@Override
	public String makeXml() throws Exception {

		RealtyValuationRqType rq = new RealtyValuationRqType();

		HeadType head = new HeadType();

		MessUIDType messUid = new MessUIDType();
		messUid.setMessageId(this.messId);
		messUid.setMessageDate(DatatypeFactory.newInstance().newXMLGregorianCalendar(DF.get().format(new Date())));
		messUid.setFromAbonent("TSM");

		GeneralType general = new GeneralType();
		general.setPriority(50);
		general.setRepeatCount(1);
		general.setTimeout(300);
		general.setRegionalBankID(this.office.getRegionalBankID());
		general.setBranchID(this.office.getBranchID());
		general.setAdditionalOfficeID(this.office.getAdditionalOfficeID());

		head.setMessUID(messUid);
		head.setGeneral(general);

		BodyType body = new BodyType();
		body.setApplicationNumber(this.appNum);

		this.address.ifPresent(e -> {
			body.setRegion(new BigDecimal(e.getRegion().getRegionID()));

			Optional.ofNullable(e.getCity()).ifPresent(city -> {
				body.setCity(city.getCityName());
				body.setCityType(city.getShortCityTypeName());
				body.setLocality(city.getCityName());
				body.setLocalityType(city.getShortCityTypeName());
			});

			Optional.ofNullable(e.getStreetAddress()).ifPresent(address -> {
				Optional.ofNullable(address.getStreet()).ifPresent(street -> {
					body.setStreet(street.getStreetName());
					body.setStreetType(street.getShortStreetTypeName());
				});

				Optional.ofNullable(address.getHouseNumber()).ifPresent(house -> {
					body.setHouseNumber(house);
				});
			});
		});

		body.setType(this.kindObj);

		this.info.ifPresent(e -> {
			Optional.ofNullable(e.getFloorCount()).ifPresent(stroeys -> {
				body.setStoreys(new BigDecimal(stroeys));
			});
			Optional.ofNullable(e.getWallType()).ifPresent(wall -> {
				body.setWalls(WallType.getWallTypeName(Integer.parseInt(wall)));
			});
			Optional.ofNullable(e.getRooms()).ifPresent(rooms -> {
				body.setRooms(new BigDecimal(rooms));
			});
			Optional.ofNullable(e.getTotal()).ifPresent(total -> {
				body.setTotal(total);
			});
			Optional.ofNullable(e.getLiving()).ifPresent(living -> {
				body.setLiving(living);
			});
			Optional.ofNullable(e.getKitchen()).ifPresent(kitchen -> {
				body.setKitchen(kitchen);
			});
			Optional.ofNullable(e.getFloor()).ifPresent(floor -> {
				body.setFloor(floor.toString());
			});
			Optional.ofNullable(e.getReportPrice()).ifPresent(price -> {
				body.setReportPrice(price);
			});
		});

		rq.setHead(head);
		rq.setBody(body);

		ObjectFactory of = new ObjectFactory();
		String result = getXmlHelper().marshall(of.createRealtyValuationRq(rq));

		logger.trace("RealtyValuationRqType: %s", result);

		return result;
	}

}


text:
Scrollbench
=========

Scrollbench is a browser scrolling performance test. It was originally a performance test in the Chromium project that has been put into this standalone tool. Scrollbench:

 - Runs as a bookmarklet so it can work widely (including mobile), or can be invoked from JS on a page.
 - Uses the best frame time measurement methodology available on the platform; most commonly `requestAnimationFrame` callbacks, hi-resolution timer `window.performance.now()`, and `window.scrollBy()`.
 - Still doesn't give very accurate results in many cases (see below for why).

## About

Complex DOM structure, sophisticated styling, and how the rendering engine chooses to deal with them all influence framerates during scrolling. Scrollbench tries to measure the framerate of a scroll and reports the average frame time as well as how many frames went significantly beyond that average (to give a sense of how steady the framerate is, which can be just as important as the average).

Scrollbench was originally a little piece of a performance test in the Chromium project that was ripped out to live on its own here so it could be run in other browsers and contexts.

## Methodology

### Current Best Practices

It is important to note that you shouldn't compare browsers that support different set of technologies. The benchmark is performed using the best API we can find on the platform, but a browser that supports requestAnimationFrame will have very different results compared to one that only has setTimeout.

For this reason at the end of the test you'll get an index which defines the browser "resolution".

Presently we have 3 resolutions: High, Medium and Low. You should be comparing browsers at the same resolution index only. Clicking on the Resolution value in the report you'll also get a detailed list of the technologies used to perform the benchmark.

Don't mix apples and oranges!

### Test Reliability

The more sophisticated your browser the more reliable the benchmark. On recent browsers we can rely on requestAnimationFrame which grants the test a good resolution but that's only a part of the equation. We also need a high definition timer. A good candidate in this case would be window.performance.now.

So if you have both, the test result is considered reliable.

If one feature is missing we fall back to the closest alternative, which in case of requestAnimationFrame is setTimeout (notoriously a low definition timer).

In some cases, though, a JavaScript-driven scroll is never going to emulate a user-initiated scroll very accurately. For instance, on many browsers on touch devices scrolling is done asynchronously (the user flings the page and it keeps going). For the test to be reliable on such devices we need support for triggering an asyncronous scroll from JavaScript, _and_ we need a way measure framerate from the part of the browser that's moving the page (rather than measuring with requestAnimationFrame callbacks, which might be blocked by other JavaScript while the browser's compositor or UI thread cheerfully continues to scroll the page).

Unfortunately today we lack both an asynchronous scroll API and way of measuring framerate that doesn't . This is a hard problem, because if frame rates from the perspective of JavaScript (i.e. requestAnimationFrame) and the user (i.e. what the browser is currently putting on-screen) are different... what does frame rate even mean?

So don't mix apples and oranges on the current technology being used, but also don't be surprised if the apples taste like papayas.

## Quick start

The easiest way to use Scrollbench.js is through the bookmarklet.

1. Make a new bookmark (e.g. just bookmark this site).
2. Edit the bookmarklet to have the name "scrollbench" and set its URL to this:

            javascript:!function(){function e(){window.ScrollBench&&new ScrollBench({loadConfig:!0}).start()}if(!window.ScrollBench&&!window.scrollbench_bookmarklet){window.scrollbench_bookmarklet=!0;var n=document.createElement('script');return n.src='https://raw.github.com/natduca/scrollbench.js/master/src/scrollbench.js',n.addEventListener('load',e,!1),document.getElementsByTagName('head')[0].appendChild(n),void 0}e()}();

3. There is no 3, just run the bookmarklet:
    * On desktop browsers just click it.
    * On iOS Safari open the bookmarks list and select it.
    * On Chrome for Android, start typing "scrollbench" in the omnibox and hit "scrollbench" when it shows up in the suggestions list.

#### iOS
Note that on iOS, it's a little tricky to edit the bookmarklet: first save the bookmark, then open the bookmarks panel and edit the bookmark you just added. You are now able to modify the site address. Replace the address with the bookmarklet code and voilà!

#### IE10
No bookmarklets in IE10, but you can invoke it through the F12 tools console:

1. Open developer tools with "F12" and go to "Console"
2. Execute:

    ```javascript
    document.head.innerHTML+="<script src='http://domain.com/fil.js'></script>";
    ```

3. Execute:

    ```javascript
    var sb = new ScrollBench(); sb.start();
    ```

## Interpretting Results

After running, scrollbench spits out some results in a report. Most of them are self-explanatory, but a few are difficult to understand. Here's the list:

* Time: total time the test took to run, in seconds, across all runs. Also an average time per run.
* Travel: distance scrolled in pixels. Note on infinite scroll pages (or pages that change the DOM while the test is running) this might not be the same as the height of the page.
* FPS: frames per second of the animation, as defined by the number of frames generated in JavaScript. Note this might not be the same as frames seen by the user! This value is averaged across the duration of the animation, but the longest frame is also reported (since outliers represent bad jank).
* Steadines: a rough, opiniated measurement of how steady the framerate was. This counts the number of frames that are more than 10% longer or shorter than average. The steadiness number is poor if more than 10% of the frames are more than 10% longer or shorter than average.
* Resolution: a rough measurement of the test's accuracy based on the technique used for timing (date.now vs window.performance.now) and drawing (setTimeout vs requestAnimationFrame)
* Overall: a rough measurement of how well the page did on the test. 5★ only if Steadiness is good and FPS is high. 4★ if FPS is high and Steadiness is mediocre. 3★ if FPS and Steadiness are mediocre. 2★ and 1★ if FPS and Steadiness are poor.

## Per-page configuration

Sometimes a page doesn't scroll the body, but instead scroll a container element (that has an `overflow: scroll` property set). It's hard to know which element to scroll automatically, so we keep a list of pages to handle specially in `src/config.js`

We welcome additions! To add a new one, copy an existing example -- the basic format is:

```javascript
// Site name
config.pages.push({
      url: '^https://www.example.com/',
    element: document.getElementById('containerElement')
  });
```

You can also use `scrollElementFn` instead of `element` to write a function that finds the element that scrolls. See the documentation below for more on how that works.

Feel free to send a pull request with additional pages added to the config file.

## JavaScript Documentation

Scrollbench can be used from a web page like so:

```html
<head>
...
<script src="scrollbench.js" type="text/javascript"></script>
</head>
```

You can then invoke the scrollbench from inside your code or the debug console with the following:

```javascript
var sb = new ScrollBench();
sb.start();
```

Scrollbench.js (SBJS) is a class, to use it you have to create an instace with `new`. The script initiates itself but does not perform any actual benchmark until you call the start method.

### Options

SBJS accepts one paramenter for special configuration. The parameter must be an object and the accepted values are:

1. **element**: reference to a node object. SBJS can scroll both the whole page or a DOM element. Default: document.documentElement.
1. **initViewport**: boolean. If true the viewport is set to initial scale 1.0. Default: false.
1. **iterations**: an integer representing the number of passes to perform. Minimum suggested and default: 2.
1. **loadConfig**: boolean or string. Loads per site configurations from either the default config file or an user defined file. Default: 2.
1. **onCompletion**: function. Returns the results to a custom function. Default: null
1. **scrollableElementFn**: function. Function to be executed to find the scrollable element. Default: null
1. **scrollStep**: integer value. In case of synchronous scroll, the amount of pixels to scroll per cycle. Default: 100
1. **waitForFn**: function. Holds back the benchmark execution until the passed function returns true. Default: null

#### Options: Element

SBJS scrolls the DOM element with id="scrollme":

```javascript
new ScrollBench({
    element: document.getElementById('scrollme')
}).start();
```

By default SBJS scrolls the whole page (namely: document.documentElement). There are special cases where the content is contained inside an element and scrolling the document wouldn't have any effect. In those cases you can specify the element that needs to be scrolled.

#### Options: initViewport

Sets the viewport to scale factor 1.0:

```javascript
new ScrollBench({
  initViewport: true
}).start();
```

This may be useful on mobile devices. If the website doesn't define the viewport size, the mobile browser tries to fit the page on the screen, but each screen/device will have a different scale factor. To get consistent benchmark results you can force the viewport scale factor to 1.0.

#### Options: iterations

Performs the test 5 times instead of the default 2:

```javascript
new ScrollBench({
  iterations: 5
}).start();
```

For better reliability the test is performed 2 times by default, but this value can be raised for higher resolution. The browser often needs a "warm up" period to reach the highest performance level, so the first pass has sometimes a lower performance rate.

#### Options: loadConfig

Loads the default per site config file

javascriptnew ScrollBench({
  loadConfig: true
}).start();
Any of the SBJS options can be passed on a per site basis from an user defined configuration file. By default no file is loaded, passing true SBJS loads the default config. You may alternatively pass an URL the configuration file is loaded from.

The configuration is a javascript file that sets the scrollbench_config variable. See the default config for reference.

Note that the bookmarklet loads the default config file but this is not the default SBJS behavior.

#### Options: onCompletion

Bypasses the default report and simply shows an alert box with the results:

```javascript
new ScrollBench({
  onCompletion: function (result) {
    alert(JSON.stringify(result, null, ' '))
  }
}).start();
```

The parameter returned by the function has the following keys:

* numAnimationFrames: total number of frames of the animation
* droppedFrameCount: number of frames dropped (ie: performed with low frame rate)
* totalTimeInSeconds: runtime
* resolution: test reliability based on browser specs
* timer: timer used for the test
* animation: technology used to perform the animation
* avgTimePerPass: average time needed for each pass
* framesPerSecond: frames per second the animation is performed at (estimated)
* travel: pixels travelled by the animation

A value can be followed by a !, - or + meaning respectively: bad, average, good result.

The results are shown by default in an overlaying iFrame, you may want to pass them to a custom function for further inspection. The results will be passed as first parameter to the specified fuction. The default internal report is not executed.

#### Options: scrollableElementFn

Tricky code to get the scrollable element on Gmail:

```javascript
new ScrollBench({
    scrollableElementFn: function (callback) {
        gmonkey.load('2.0',
            function (api) {
                callback(api.getScrollableElement());
            }
        );
    }
}).start();
```

In some circumstances it's not possible to foresee the element that should be scrolled. In those cases we can rely on a custom function. The element must be sent as first parameter of a callback function.

#### Options: scrollStep

Increase the number of frames by reducing the scrolling step from the default 100 to 50:

```javascript
new ScrollBench({
  scrollStep: 50
}).start();
```

The scrolling is normally performed with a 100 pixels step. Each step is a frame. You may want to increase of decrease the number of frames by altering the scrollStep.

#### Options: waitForFn

Wait for the element waitForMe to be loaded before starting the benchmark.

```javascript
new ScrollBench({
    waitForFn: function () {
        return document.getElementById('waitForMe');
    }
}).start();
```

The passed function is executed repeatedely until it doesn't returs true. When it is finally true, the benchmark begins.

## Getting Involved

Scrollbench could be way better! Here are some ways to help:

1. Test it on various sites! If you find one that doesn't work, either file an issue or better yet, add a custom handler for it in `src/config.js` and send us a pull request (see "Per-page configuration" above for more info).
2. Test it on various browsers! If you find a page that only fails in one browser, file an issue.
3. Make the code better! Pull requests welcome, or if you have ideas on how this could be improved to be more accurate and want to talk about it, file an issue.

## Updating the bookmarklet code

To update the bookmarklet code (e.g. to change where the source files are served from) you need node and uglify-js installed first. Then modify src/bookmarklet.js as you see fit, and then in the `build` direction run `node makebm.js`, which will minify src/bookmarklet.js and (theoretically) update anywhere the bookmarklet code appears with an updated copy.


text:
import React from 'react';
import PropTypes from 'prop-types';

class PieChart extends React.PureComponent {
  static propTypes = {
    data: PropTypes.arrayOf(PropTypes.shape({
      value: PropTypes.number,
      color: PropTypes.string,
    })),
    sectorStrokeColor: PropTypes.string,
    sectorStrokeWidth: PropTypes.number,
    viewBoxWidth: PropTypes.number
  };

  static defaultProps = {
    data: [],
    sectorStrokeWidth: 3,
    sectorStrokeColor: '#FFF',
    viewBoxWidth: 300,
  };

  getSectors() {
    const { data, palette, sectorStrokeWidth, sectorStrokeColor, viewBoxWidth } = this.props
    const total = Math.ceil(data.reduce((n, d) => d.value + n, 0))
    const center = viewBoxWidth / 2
    let startAngle = 0
    let endAngle = 0

    return (
      data.map((d, i) => {
        const angle = 360 * d.value / total
        const largeArc = (d.value / total) <= 0.5 ? 0 : 1

        startAngle = endAngle
        endAngle = startAngle + angle

        const x1 = Math.round(center + center * Math.cos(Math.PI * startAngle / 180))
        const y1 = Math.round(center + center * Math.sin(Math.PI * startAngle / 180))

        const x2 = Math.round(center + center * Math.cos(Math.PI * endAngle / 180))
        const y2 = Math.round(center + center * Math.sin(Math.PI * endAngle / 180))

        const dPath =
          'M' + center + ',' + center + ' ' +
          'L' + x1 + ',' + y1 + ' ' +
          'A' + center + ',' + center + ' 0 ' + largeArc + ',1 ' + x2 + ',' + y2 + ' ' +
          'z'

        return (
          <path
            key={ 'sector' + i }
            d={ dPath }
            fill={ d.color || palette[i % palette.length] }
            stroke={ sectorStrokeColor }
            strokeWidth={ sectorStrokeWidth } />
        )
      })
    )
  }

  render() {
    const { viewBoxWidth, props } = this.props
    return (
      <svg viewBox={ `0 0 ${viewBoxWidth} ${viewBoxWidth}` } { ...props }>
        { this.getSectors() }
      </svg>
  )}
}

export default PieChart;


text:
<component name="libraryTable">
  <library name="Maven: org.thymeleaf:thymeleaf-spring4:3.0.0.RELEASE">
    <CLASSES>
      <root url="jar://F:/maven_dep/repository/org/thymeleaf/thymeleaf-spring4/3.0.0.RELEASE/thymeleaf-spring4-3.0.0.RELEASE.jar!/" />
    </CLASSES>
    <JAVADOC>
      <root url="jar://F:/maven_dep/repository/org/thymeleaf/thymeleaf-spring4/3.0.0.RELEASE/thymeleaf-spring4-3.0.0.RELEASE-javadoc.jar!/" />
    </JAVADOC>
    <SOURCES>
      <root url="jar://F:/maven_dep/repository/org/thymeleaf/thymeleaf-spring4/3.0.0.RELEASE/thymeleaf-spring4-3.0.0.RELEASE-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text:
chrome.extension.onRequest.addListener(
  function(request, sender, sendResponse) {
    // Let the extension know where the script ran.
    var url = sender.tab ? sender.tab.url : 'about:blank';
    chrome.test.sendMessage('content script: ' + url);
  });


text:
import { memo, useEffect } from 'react';
/**
 * A utility for rendering a drag preview image
 */ export const DragPreviewImage = memo(function DragPreviewImage({ connect , src  }) {
    useEffect(()=>{
        if (typeof Image === 'undefined') return;
        let connected = false;
        const img = new Image();
        img.src = src;
        img.onload = ()=>{
            connect(img);
            connected = true;
        };
        return ()=>{
            if (connected) {
                connect(null);
            }
        };
    });
    return null;
});

//# sourceMappingURL=DragPreviewImage.js.map