repo_name
stringlengths 4
116
| path
stringlengths 3
942
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
|---|---|---|---|---|
forxer/okatea
|
Okatea/Tao/L10n/country-list/fo_FO/country.php
|
5531
|
<?php
return array(
'AD' => 'Andorra',
'AE' => 'Sameindu Emirríkini',
'AF' => 'Afganistan',
'AG' => 'Antigua og Barbuda',
'AI' => 'Anguilla',
'AL' => 'Albania',
'AM' => 'Armenia',
'AN' => 'Niðurlendsku Antilloyggjar',
'AO' => 'Angola',
'AQ' => 'Antarktis',
'AR' => 'Argentina',
'AS' => 'Amerikanska Sámoa',
'AT' => 'Eysturríki',
'AU' => 'Avstralia',
'AW' => 'Aruba',
'AX' => 'Áland',
'AZ' => 'Aserbajdsjan',
'BA' => 'Bosnia-Hersegovina',
'BB' => 'Barbados',
'BD' => 'Bangladesj',
'BE' => 'Belgia',
'BF' => 'Burkina Faso',
'BG' => 'Bulgaria',
'BH' => 'Bahrain',
'BI' => 'Burundi',
'BJ' => 'Benin',
'BL' => 'Saint Barthélemy',
'BM' => 'Bermuda',
'BN' => 'Brunei',
'BO' => 'Bolivia',
'BR' => 'Brasilia',
'BS' => 'Bahamas',
'BT' => 'Butan',
'BV' => 'Bouvetoy',
'BW' => 'Botsvana',
'BY' => 'Hvítarussland',
'BZ' => 'Belis',
'CA' => 'Kanada',
'CC' => 'Kokosoyggjar',
'CD' => 'Kongo-Kinshasa',
'CF' => 'Miðafrikalýðveldið',
'CG' => 'Kongo',
'CH' => 'Sveis',
'CI' => 'Fílabeinsstrondin',
'CK' => 'Cooksoyggjar',
'CL' => 'Kili',
'CM' => 'Kamerun',
'CN' => 'Kina',
'CO' => 'Kolombia',
'CR' => 'Kosta Rika',
'CU' => 'Kuba',
'CV' => 'Grønhøvdaoyggjarnar',
'CX' => 'Jólaoyggjin',
'CY' => 'Kýpros',
'CZ' => 'Kekkia',
'DE' => 'Týskland',
'DJ' => 'Djibouti',
'DK' => 'Danmørk',
'DM' => 'Dominika',
'DO' => 'Domingo lýðveldið',
'DZ' => 'Algeria',
'EC' => 'Ekvador',
'EE' => 'Estland',
'EG' => 'Egyptaland',
'EH' => 'Vestursahara',
'ER' => 'Eritrea',
'ES' => 'Spania',
'ET' => 'Etiopia',
'FI' => 'Finnland',
'FJ' => 'Fiji',
'FK' => 'Falklandsoyggjar',
'FM' => 'Mikronesia',
'FO' => 'Føroyar',
'FR' => 'Frakland',
'GA' => 'Gabon',
'GB' => 'Stóra Bretland',
'GD' => 'Grenada',
'GE' => 'Georgia',
'GF' => 'Fransk Gujana',
'GG' => 'Guernsey',
'GH' => 'Ghana',
'GI' => 'Gibraltar',
'GL' => 'Grønland',
'GM' => 'Gambia',
'GN' => 'Guinea',
'GP' => 'Guadeloupe',
'GQ' => 'Ekvator Guinea',
'GR' => 'Grikkaland',
'GS' => 'Suðurgeorgia',
'GT' => 'Guatemala',
'GU' => 'Guam',
'GW' => 'Guinea Bissau',
'GY' => 'Gujana',
'HK' => 'Hongkong',
'HM' => 'Heard- og McDonald-oyggjar',
'HN' => 'Honduras',
'HR' => 'Kroatia',
'HT' => 'Haiti',
'HU' => 'Ungarn',
'ID' => 'Indonesia',
'IE' => 'Írland',
'IL' => 'Ísrael',
'IM' => 'Mann',
'IN' => 'India',
'IO' => 'Bretsku Indiahavsoyggjar',
'IQ' => 'Irak',
'IR' => 'Iran',
'IS' => 'Ísland',
'IT' => 'Italia',
'JE' => 'Jersey',
'JM' => 'Jameika',
'JO' => 'Jordan',
'JP' => 'Japan',
'KE' => 'Kenja',
'KG' => 'Kirgisia',
'KH' => 'Kambodja',
'KI' => 'Kiribati',
'KM' => 'Komorooyggjarnar',
'KN' => 'Saint Kitts og Nevis',
'KP' => 'Norður-Korea',
'KR' => 'Suður-Korea',
'KW' => 'Kuvait',
'KY' => 'Caymanoyggjar',
'KZ' => 'Kasakstan',
'LA' => 'Laos',
'LB' => 'Libanon',
'LC' => 'Saint Lusia',
'LI' => 'Liktenstein',
'LK' => 'Sri Lanka',
'LR' => 'Liberia',
'LS' => 'Lesoto',
'LT' => 'Litava',
'LU' => 'Luksemborg',
'LV' => 'Lettland',
'LY' => 'Libya',
'MA' => 'Marokko',
'MC' => 'Monako',
'MD' => 'Moldova',
'ME' => 'Montenegro',
'MF' => 'Saint Martin',
'MG' => 'Madagaskar',
'MH' => 'Marshalloyggjarnar',
'MK' => 'Makedónia',
'ML' => 'Mali',
'MM' => 'Burma',
'MN' => 'Mongolia',
'MO' => 'Makao',
'MP' => 'Norðurmarianoyggjar',
'MQ' => 'Martinique',
'MR' => 'Móritania',
'MS' => 'Montserrat',
'MT' => 'Malta',
'MU' => 'Móritius',
'MV' => 'Maldivuoyggjarnar',
'MW' => 'Malavi',
'MX' => 'Meksiko',
'MY' => 'Maleisia',
'MZ' => 'Mosambik',
'NA' => 'Namibia',
'NC' => 'Ný-Kaledonia',
'NE' => 'Niger',
'NF' => 'Norfolkoy',
'NG' => 'Nigeria',
'NI' => 'Nikaragua',
'NL' => 'Niðurlond',
'NO' => 'Noreg',
'NP' => 'Nepal',
'NR' => 'Nauru',
'NU' => 'Niue',
'NZ' => 'Ný Sæland',
'OM' => 'Oman',
'PA' => 'Panama',
'PE' => 'Perú',
'PF' => 'Franska Polynesia',
'PG' => 'Papua Nýguinea',
'PH' => 'Filipsoyggjar',
'PK' => 'Pakistan',
'PL' => 'Pólland',
'PM' => 'Saint-Pierre og Miquelon',
'PN' => 'Pitcairn',
'PR' => 'Puerto Rico',
'PS' => 'Palestinskt territorium',
'PT' => 'Portugal',
'PW' => 'Palau',
'PY' => 'Paraguei',
'QA' => 'Katar',
'RE' => 'Réunion',
'RO' => 'Rumenia',
'RS' => 'Serbia',
'RU' => 'Russland',
'RW' => 'Ruanda',
'SA' => 'Saudi-Arábia',
'SB' => 'Sálomonoyggjarnar',
'SC' => 'Seyskelloyggjarnar',
'SD' => 'Sudan',
'SE' => 'Svøríki',
'SG' => 'Singapor',
'SH' => 'Saint Helena',
'SI' => 'Slovenia',
'SJ' => 'Svalbard og Jan Mayen',
'SK' => 'Slovakia',
'SL' => 'Sierra Leone',
'SM' => 'San Marino',
'SN' => 'Senegal',
'SO' => 'Somalia',
'SR' => 'Surinam',
'ST' => 'Sao Tome og Prinsipi',
'SV' => 'El Salvador',
'SY' => 'Syria',
'SZ' => 'Svasiland',
'TC' => 'Turks- og Caicosoyggjar',
'TD' => 'Kjad',
'TG' => 'Togo',
'TH' => 'Teiland',
'TJ' => 'Tadsjikistan',
'TK' => 'Tokelau',
'TL' => 'Eystur Timor',
'TM' => 'Turkmenistan',
'TN' => 'Tunesia',
'TO' => 'Tonga',
'TR' => 'Turkaland',
'TT' => 'Trinidad og Tobago',
'TV' => 'Tuvalu',
'TW' => 'Teivan',
'TZ' => 'Tansania',
'UA' => 'Ukreina',
'UG' => 'Uganda',
'US' => 'Sambandsríki Amerika',
'UY' => 'Uruguei',
'UZ' => 'Usbekistan',
'VA' => 'Vatikan',
'VC' => 'Saint Vinsent og Grenadinoyggjar',
'VE' => 'Venesuela',
'VG' => 'Stóra Bretlands Jómfrúoyggjar',
'VI' => 'Sambandsríki Amerikas Jómfrúoyggjar',
'VN' => 'Vietnam',
'VU' => 'Vanuatu',
'WF' => 'Wallis og Futuna',
'WS' => 'Sámoa',
'YE' => 'Jemen',
'YT' => 'Mayotte',
'ZA' => 'Suðurafrika',
'ZM' => 'Sambia',
'ZW' => 'Simbabvi'
);
|
mit
|
yanivefraim/theme-creator-demo-angular-2
|
app/components/font-family-component/font-family-component.ts
|
656
|
import {Component, View, FORM_DIRECTIVES, EventEmitter, NgFor} from 'angular2/angular2';
@Component({
selector: 'font-family-component',
inputs: ['fontFamily'],
outputs: ['fontFamilyChange']
})
@View({
template: `
<select class="form-control" [ng-model]="fontFamily" (input)="fontFamilyChange.next($event.target.value)">
<option *ng-for="#font of fonts">{{font}}</option>
</select>
`,
directives: [FORM_DIRECTIVES, NgFor]
})
export class FontFamilyComponent {
fontFamily: string;
fontFamilyChange = new EventEmitter();
fonts: string[];
constructor() {
this.fonts = ['Helvetica', 'Ariel', 'fantasy', 'cursive'];
}
}
|
mit
|
tgriesser/azul
|
lib/relations/belongs_to_config.js
|
6858
|
'use strict';
var _ = require('lodash');
var util = require('util');
var property = require('corazon/property');
var inflection = require('../util/inflection');
var Mixin = require('corazon/mixin');
/**
* A helper function for creating config properties that either reads from a
* cached value or calls a function to get a value to cache.
*
* @function BelongsTo~config
* @param {String} name The name of the option/property.
* @param {Function} calculate A function to calculate the default value.
* @return {Property} A config property
*/
var config = function(name, calculate) {
var attr = '$' + name;
return property(function() {
if (this[attr] === undefined) {
this[attr] = calculate.call(this);
}
return this[attr];
});
};
/**
* BelongsTo mixin for options/configuration.
*
* This mixin separates some of the logic of {@link BelongsTo} and is only
* intended to be mixed into that one class.
*/
module.exports = Mixin.create(/** @lends BelongsTo# */ {
/**
* Override of {@link BaseRelation#configure}.
*
* @protected
* @method
* @see {@link BaseRelation#configure}
*/
configure: function() {
/* jshint expr: true */
// configure each of the properties that are calculated on a delay by
// simply invoking the property once. configure the inverse first as some
// other calculations may rely on it.
this.inverse;
this.primaryKey;
this.primaryKeyAttr;
this.foreignKey;
this.foreignKeyAttr;
this.inverseRelation(); // ensure the inverse is configured
this._super();
},
/**
* Get the inverse of this relation. Access the option that was given or
* calculate the value based on the current model class name.
*
* The resulting value will be locked in after the first call to avoid any
* possible changes due to changing state outside of the relation.
*
* @private
* @type {String}
*/
inverse: config('inverse', function() {
var inverse = this._options.inverse || this._inverse();
// add the inverse if it's missing
if (inverse && !this._relatedModel[inverse + 'Relation']) {
var db = this._modelClass.db;
var attr = db.hasMany(this._modelClass, {
inverse: this._name,
primaryKey: this._options.primaryKey,
foreignKey: this._options.foreignKey,
implicit: true,
});
this._relatedModel.reopen(_.object([[inverse, attr]]));
}
return inverse;
}),
/**
* Calculate the default value of the inverse for when an option was not
* provided for this relation.
*
* Mixins installed after this one can override {@link HasMany#_inverse} if
* they need to change the default.
*
* @method
* @private
* @return {String} The default value.
*/
_inverse: function() {
var name = _.camelCase(this._modelClass.__name__);
var singularized = inflection.singularize(name);
var pluralized = inflection.pluralize(name);
var related = this._relatedModel;
var inverse;
if (related[pluralized + 'Relation']) { inverse = pluralized; }
else if (related[singularized + 'Relation']) { inverse = singularized; }
else {
// find a relation w/ an inverse that points back to this one
var match = _.find(related.relations, function(relation) {
return relation._options.inverse === this._name;
}.bind(this));
inverse = _.get(match, '_name');
}
if (!inverse) {
inverse = pluralized;
}
return inverse;
},
/**
* Get the primary key for this relation. This will access the primary key
* value specified on the inverse relation, if an inverse relation exists. If
* the inverse exists and the user also provided the `primaryKey` option when
* creating this relation, it will ensure that the given value matches the
* value from the inverse.
*
* If an inverse does not exist, this will return the value given for the
* `primaryKey` option or `pk` as a default.
*
* The resulting value will be locked in after the first call to avoid any
* possible changes due to changing state outside of the relation.
*
* @private
* @type {String}
*/
primaryKey: config('primaryKey', function() {
var primaryKey = this._options.primaryKey;
var inverseRelation = this.inverseRelation();
var inversePrimaryKey = inverseRelation && inverseRelation.primaryKey;
if (inverseRelation && primaryKey && primaryKey !== inversePrimaryKey) {
throw new Error(util.format('%s.%s primary key must equal %j ' +
'specified by %s.%s relation',
this._modelClass.__identity__.__name__, this._name,
inverseRelation.primaryKey,
inverseRelation._modelClass.__identity__.__name__,
inverseRelation._name));
}
if (inverseRelation) {
primaryKey = inverseRelation.primaryKey;
}
if (!primaryKey) { // default in case the inverse does not exist
primaryKey = 'pk';
}
return primaryKey;
}),
/**
* Get the primary key attribute value for this relation. This looks up the
* attribute value on the related class. If that value was not defied, it
* falls back to the underscored version of {@link BelongsTo#primaryKey}.
*
* @private
* @type {String}
*/
primaryKeyAttr: config('primaryKeyAttr', function() {
// since the related model may not have defined the attribute being used as
// the primary key attribute, we need a fallback here, so we snake case the
// property name.
var relatedClass = this._relatedModel.__class__;
var prototype = relatedClass.prototype;
var primaryKeyAttr = prototype[this.primaryKey + 'Attr'];
return primaryKeyAttr || _.snakeCase(this.primaryKey);
}),
/**
* Get the foreign key for this relation. Access the option that was given or
* calculate the value based on the relation name.
*
* @private
* @type {String}
*/
foreignKey: config('foreignKey', function() {
return this._options.foreignKey || _.camelCase(this._name + 'Id');
}),
/**
* Get the foreign key attribute value for this relation. This looks up the
* attribute value on the model class.
*
* @private
* @type {String}
*/
foreignKeyAttr: config('foreignKeyAttr', function() {
// we always try to find the foreign key attribute by looking at the model
// class. it's possible that it won't be there, though. belongs-to
// relationships that were created implicitly from a has-many won't add the
// attribute, so we need to fall back to snake casing the foreign key.
var modelClass = this._modelClass;
var prototype = modelClass.__class__.prototype;
var foreignKeyAttr = prototype[this.foreignKey + 'Attr'];
if (!foreignKeyAttr) {
foreignKeyAttr = _.snakeCase(this.foreignKey);
}
return foreignKeyAttr;
}),
});
|
mit
|
drhenner/elzzad
|
app/controllers/myaccount/base_controller.rb
|
149
|
class Myaccount::BaseController < ApplicationController
before_filter :require_user
protected
def ssl_required?
ssl_supported?
end
end
|
mit
|
DoSomething/rogue
|
database/migrations/2017_12_08_203149_add_indexes_to_posts.php
|
763
|
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AddIndexesToPosts extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('posts', function (Blueprint $table) {
$table->index('created_at');
$table->index(['status', 'deleted_at']);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('posts', function (Blueprint $table) {
$table->dropIndex('posts_status_deleted_at_index');
$table->dropIndex('posts_created_at_index');
});
}
}
|
mit
|
cyberdelia/dynamodb
|
types/attributes_test.go
|
1829
|
package types
import (
"reflect"
"testing"
"time"
)
type structTest struct {
Int int
IntArray []int
Float float32
FloatArray []float64
String string
StringArray []string
Blob []byte
BlobArray [][]byte
Time time.Time
}
var marshallTests = []struct {
item structTest
value AttributeValue
}{
{
structTest{
Int: 8,
IntArray: []int{8, 12},
},
AttributeValue{
"Int": {
"N": "8",
},
"IntArray": {
"NS": []string{"8", "12"},
},
},
},
{
structTest{
Float: 8.12,
FloatArray: []float64{8.12, 12.8},
},
AttributeValue{
"Float": {
"N": "8.12",
},
"FloatArray": {
"NS": []string{"8.12", "12.8"},
},
},
},
{
structTest{
String: "abc",
StringArray: []string{"a", "b"},
},
AttributeValue{
"String": {
"S": "abc",
},
"StringArray": {
"SS": []string{"a", "b"},
},
},
},
{
structTest{
Blob: []byte{'a', 'b', 'c'},
BlobArray: [][]byte{
{'a', 'b', 'c'}, {'d', 'e', 'f'},
},
},
AttributeValue{
"Blob": {
"B": "abc",
},
"BlobArray": {
"BS": []string{"abc", "def"},
},
},
},
{
structTest{
Time: time.Date(2013, 12, 12, 17, 55, 30, 0, time.UTC),
},
AttributeValue{
"Time": {
"S": "2013-12-12T17:55:30Z",
},
},
},
}
func TestMarshall(t *testing.T) {
for _, e := range marshallTests {
v, err := Marshal(e.item, false)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(v, e.value) {
t.Errorf("got %v wants %v", v, e.value)
}
}
}
func TestUnmarshall(t *testing.T) {
for _, e := range marshallTests {
var item structTest
err := Unmarshal(e.value, &item)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(item, e.item) {
t.Errorf("got %v wants %v", item, e.item)
}
}
}
|
mit
|
asudhak/One-Button-App---Android
|
lib/commons-httpclient-3.0.1/docs/xref/org/apache/commons/httpclient/HeaderGroup.html
|
19680
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" /><title>HeaderGroup xref</title>
<link type="text/css" rel="stylesheet" href="../../../../stylesheet.css" />
</head>
<body>
<div id="overview"><a href="../../../../../apidocs/org/apache/commons/httpclient/HeaderGroup.html">View Javadoc</a></div><pre>
<a name="1" href="#1">1</a> <em class="comment">/*</em>
<a name="2" href="#2">2</a> <em class="comment"> * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/HeaderGroup.java,v 1.8 2004/05/13 04:03:25 mbecke Exp $</em>
<a name="3" href="#3">3</a> <em class="comment"> * $Revision: 155418 $</em>
<a name="4" href="#4">4</a> <em class="comment"> * $Date: 2005-02-26 08:01:52 -0500 (Sat, 26 Feb 2005) $</em>
<a name="5" href="#5">5</a> <em class="comment"> *</em>
<a name="6" href="#6">6</a> <em class="comment"> * ====================================================================</em>
<a name="7" href="#7">7</a> <em class="comment"> *</em>
<a name="8" href="#8">8</a> <em class="comment"> * Copyright 2003-2004 The Apache Software Foundation</em>
<a name="9" href="#9">9</a> <em class="comment"> *</em>
<a name="10" href="#10">10</a> <em class="comment"> * Licensed under the Apache License, Version 2.0 (the "License");</em>
<a name="11" href="#11">11</a> <em class="comment"> * you may not use this file except in compliance with the License.</em>
<a name="12" href="#12">12</a> <em class="comment"> * You may obtain a copy of the License at</em>
<a name="13" href="#13">13</a> <em class="comment"> *</em>
<a name="14" href="#14">14</a> <em class="comment"> * <a href="http://www.apache.org/licenses/LICENSE-2.0" target="alexandria_uri">http://www.apache.org/licenses/LICENSE-2.0</a></em>
<a name="15" href="#15">15</a> <em class="comment"> *</em>
<a name="16" href="#16">16</a> <em class="comment"> * Unless required by applicable law or agreed to in writing, software</em>
<a name="17" href="#17">17</a> <em class="comment"> * distributed under the License is distributed on an "AS IS" BASIS,</em>
<a name="18" href="#18">18</a> <em class="comment"> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.</em>
<a name="19" href="#19">19</a> <em class="comment"> * See the License for the specific language governing permissions and</em>
<a name="20" href="#20">20</a> <em class="comment"> * limitations under the License.</em>
<a name="21" href="#21">21</a> <em class="comment"> * ====================================================================</em>
<a name="22" href="#22">22</a> <em class="comment"> *</em>
<a name="23" href="#23">23</a> <em class="comment"> * This software consists of voluntary contributions made by many</em>
<a name="24" href="#24">24</a> <em class="comment"> * individuals on behalf of the Apache Software Foundation. For more</em>
<a name="25" href="#25">25</a> <em class="comment"> * information on the Apache Software Foundation, please see</em>
<a name="26" href="#26">26</a> <em class="comment"> * <<a href="http://www.apache.org/" target="alexandria_uri">http://www.apache.org/</a>>.</em>
<a name="27" href="#27">27</a> <em class="comment"> *</em>
<a name="28" href="#28">28</a> <em class="comment"> */</em>
<a name="29" href="#29">29</a>
<a name="30" href="#30">30</a> <strong>package</strong> <a href="../../../../org/apache/commons/httpclient/package-summary.html">org.apache.commons.httpclient</a>;
<a name="31" href="#31">31</a>
<a name="32" href="#32">32</a> <strong>import</strong> java.util.ArrayList;
<a name="33" href="#33">33</a> <strong>import</strong> java.util.Iterator;
<a name="34" href="#34">34</a> <strong>import</strong> java.util.List;
<a name="35" href="#35">35</a>
<a name="36" href="#36">36</a> <em>/**<em>*</em></em>
<a name="37" href="#37">37</a> <em> * A class for combining a set of headers. This class allows for multiple</em>
<a name="38" href="#38">38</a> <em> * headers with the same name and keeps track of the order in which headers were</em>
<a name="39" href="#39">39</a> <em> * added.</em>
<a name="40" href="#40">40</a> <em> * </em>
<a name="41" href="#41">41</a> <em> * @author Michael Becke</em>
<a name="42" href="#42">42</a> <em> * </em>
<a name="43" href="#43">43</a> <em> * @since 2.0beta1</em>
<a name="44" href="#44">44</a> <em> */</em>
<a name="45" href="#45">45</a> <strong>public</strong> <strong>class</strong> <a href="../../../../org/apache/commons/httpclient/HeaderGroup.html">HeaderGroup</a> {
<a name="46" href="#46">46</a>
<a name="47" href="#47">47</a> <em>/**<em>* The list of headers for this group, in the order in which they were added */</em></em>
<a name="48" href="#48">48</a> <strong>private</strong> List headers;
<a name="49" href="#49">49</a>
<a name="50" href="#50">50</a> <em>/**<em>*</em></em>
<a name="51" href="#51">51</a> <em> * Constructor for HeaderGroup.</em>
<a name="52" href="#52">52</a> <em> */</em>
<a name="53" href="#53">53</a> <strong>public</strong> <a href="../../../../org/apache/commons/httpclient/HeaderGroup.html">HeaderGroup</a>() {
<a name="54" href="#54">54</a> <strong>this</strong>.headers = <strong>new</strong> ArrayList();
<a name="55" href="#55">55</a> }
<a name="56" href="#56">56</a>
<a name="57" href="#57">57</a> <em>/**<em>*</em></em>
<a name="58" href="#58">58</a> <em> * Removes any contained headers.</em>
<a name="59" href="#59">59</a> <em> */</em>
<a name="60" href="#60">60</a> <strong>public</strong> <strong>void</strong> clear() {
<a name="61" href="#61">61</a> headers.clear();
<a name="62" href="#62">62</a> }
<a name="63" href="#63">63</a>
<a name="64" href="#64">64</a> <em>/**<em>*</em></em>
<a name="65" href="#65">65</a> <em> * Adds the given header to the group. The order in which this header was</em>
<a name="66" href="#66">66</a> <em> * added is preserved.</em>
<a name="67" href="#67">67</a> <em> * </em>
<a name="68" href="#68">68</a> <em> * @param header the header to add</em>
<a name="69" href="#69">69</a> <em> */</em>
<a name="70" href="#70">70</a> <strong>public</strong> <strong>void</strong> addHeader(<a href="../../../../org/apache/commons/httpclient/Header.html">Header</a> header) {
<a name="71" href="#71">71</a> headers.add(header);
<a name="72" href="#72">72</a> }
<a name="73" href="#73">73</a>
<a name="74" href="#74">74</a> <em>/**<em>*</em></em>
<a name="75" href="#75">75</a> <em> * Removes the given header.</em>
<a name="76" href="#76">76</a> <em> *</em>
<a name="77" href="#77">77</a> <em> * @param header the header to remove</em>
<a name="78" href="#78">78</a> <em> */</em>
<a name="79" href="#79">79</a> <strong>public</strong> <strong>void</strong> removeHeader(<a href="../../../../org/apache/commons/httpclient/Header.html">Header</a> header) {
<a name="80" href="#80">80</a> headers.remove(header);
<a name="81" href="#81">81</a> }
<a name="82" href="#82">82</a>
<a name="83" href="#83">83</a> <em>/**<em>*</em></em>
<a name="84" href="#84">84</a> <em> * Sets all of the headers contained within this group overriding any</em>
<a name="85" href="#85">85</a> <em> * existing headers. The headers are added in the order in which they appear</em>
<a name="86" href="#86">86</a> <em> * in the array.</em>
<a name="87" href="#87">87</a> <em> * </em>
<a name="88" href="#88">88</a> <em> * @param headers the headers to set</em>
<a name="89" href="#89">89</a> <em> */</em>
<a name="90" href="#90">90</a> <strong>public</strong> <strong>void</strong> setHeaders(<a href="../../../../org/apache/commons/httpclient/Header.html">Header</a>[] headers) {
<a name="91" href="#91">91</a> clear();
<a name="92" href="#92">92</a>
<a name="93" href="#93">93</a> <strong>for</strong> (<strong>int</strong> i = 0; i < headers.length; i++) {
<a name="94" href="#94">94</a> addHeader(headers[i]);
<a name="95" href="#95">95</a> }
<a name="96" href="#96">96</a> }
<a name="97" href="#97">97</a>
<a name="98" href="#98">98</a> <em>/**<em>*</em></em>
<a name="99" href="#99">99</a> <em> * Gets a header representing all of the header values with the given name.</em>
<a name="100" href="#100">100</a> <em> * If more that one header with the given name exists the values will be</em>
<a name="101" href="#101">101</a> <em> * combined with a "," as per RFC 2616.</em>
<a name="102" href="#102">102</a> <em> * </em>
<a name="103" href="#103">103</a> <em> * <p>Header name comparison is case insensitive.</em>
<a name="104" href="#104">104</a> <em> * </em>
<a name="105" href="#105">105</a> <em> * @param name the name of the header(s) to get</em>
<a name="106" href="#106">106</a> <em> * @return a header with a condensed value or <code>null</code> if no</em>
<a name="107" href="#107">107</a> <em> * headers by the given name are present</em>
<a name="108" href="#108">108</a> <em> */</em>
<a name="109" href="#109">109</a> <strong>public</strong> <a href="../../../../org/apache/commons/httpclient/Header.html">Header</a> getCondensedHeader(String name) {
<a name="110" href="#110">110</a> <a href="../../../../org/apache/commons/httpclient/Header.html">Header</a>[] headers = getHeaders(name);
<a name="111" href="#111">111</a>
<a name="112" href="#112">112</a> <strong>if</strong> (headers.length == 0) {
<a name="113" href="#113">113</a> <strong>return</strong> <strong>null</strong>;
<a name="114" href="#114">114</a> } <strong>else</strong> <strong>if</strong> (headers.length == 1) {
<a name="115" href="#115">115</a> <strong>return</strong> <strong>new</strong> <a href="../../../../org/apache/commons/httpclient/Header.html">Header</a>(headers[0].getName(), headers[0].getValue());
<a name="116" href="#116">116</a> } <strong>else</strong> {
<a name="117" href="#117">117</a> StringBuffer valueBuffer = <strong>new</strong> StringBuffer(headers[0].getValue());
<a name="118" href="#118">118</a>
<a name="119" href="#119">119</a> <strong>for</strong> (<strong>int</strong> i = 1; i < headers.length; i++) {
<a name="120" href="#120">120</a> valueBuffer.append(<span class="string">", "</span>);
<a name="121" href="#121">121</a> valueBuffer.append(headers[i].getValue());
<a name="122" href="#122">122</a> }
<a name="123" href="#123">123</a>
<a name="124" href="#124">124</a> <strong>return</strong> <strong>new</strong> <a href="../../../../org/apache/commons/httpclient/Header.html">Header</a>(name.toLowerCase(), valueBuffer.toString());
<a name="125" href="#125">125</a> }
<a name="126" href="#126">126</a> }
<a name="127" href="#127">127</a>
<a name="128" href="#128">128</a> <em>/**<em>*</em></em>
<a name="129" href="#129">129</a> <em> * Gets all of the headers with the given name. The returned array</em>
<a name="130" href="#130">130</a> <em> * maintains the relative order in which the headers were added. </em>
<a name="131" href="#131">131</a> <em> * </em>
<a name="132" href="#132">132</a> <em> * <p>Header name comparison is case insensitive.</em>
<a name="133" href="#133">133</a> <em> * </em>
<a name="134" href="#134">134</a> <em> * @param name the name of the header(s) to get</em>
<a name="135" href="#135">135</a> <em> * </em>
<a name="136" href="#136">136</a> <em> * @return an array of length >= 0</em>
<a name="137" href="#137">137</a> <em> */</em>
<a name="138" href="#138">138</a> <strong>public</strong> <a href="../../../../org/apache/commons/httpclient/Header.html">Header</a>[] getHeaders(String name) {
<a name="139" href="#139">139</a> ArrayList headersFound = <strong>new</strong> ArrayList();
<a name="140" href="#140">140</a>
<a name="141" href="#141">141</a> <strong>for</strong> (Iterator headerIter = headers.iterator(); headerIter.hasNext();) {
<a name="142" href="#142">142</a> <a href="../../../../org/apache/commons/httpclient/Header.html">Header</a> header = (Header) headerIter.next();
<a name="143" href="#143">143</a> <strong>if</strong> (header.getName().equalsIgnoreCase(name)) {
<a name="144" href="#144">144</a> headersFound.add(header);
<a name="145" href="#145">145</a> }
<a name="146" href="#146">146</a> }
<a name="147" href="#147">147</a>
<a name="148" href="#148">148</a> <strong>return</strong> (Header[]) headersFound.toArray(<strong>new</strong> Header[headersFound.size()]);
<a name="149" href="#149">149</a> }
<a name="150" href="#150">150</a>
<a name="151" href="#151">151</a> <em>/**<em>*</em></em>
<a name="152" href="#152">152</a> <em> * Gets the first header with the given name.</em>
<a name="153" href="#153">153</a> <em> * </em>
<a name="154" href="#154">154</a> <em> * <p>Header name comparison is case insensitive.</em>
<a name="155" href="#155">155</a> <em> * </em>
<a name="156" href="#156">156</a> <em> * @param name the name of the header to get</em>
<a name="157" href="#157">157</a> <em> * @return the first header or <code>null</code></em>
<a name="158" href="#158">158</a> <em> */</em>
<a name="159" href="#159">159</a> <strong>public</strong> <a href="../../../../org/apache/commons/httpclient/Header.html">Header</a> getFirstHeader(String name) {
<a name="160" href="#160">160</a> <strong>for</strong> (Iterator headerIter = headers.iterator(); headerIter.hasNext();) {
<a name="161" href="#161">161</a> <a href="../../../../org/apache/commons/httpclient/Header.html">Header</a> header = (Header) headerIter.next();
<a name="162" href="#162">162</a> <strong>if</strong> (header.getName().equalsIgnoreCase(name)) {
<a name="163" href="#163">163</a> <strong>return</strong> header;
<a name="164" href="#164">164</a> }
<a name="165" href="#165">165</a> }
<a name="166" href="#166">166</a>
<a name="167" href="#167">167</a> <strong>return</strong> <strong>null</strong>;
<a name="168" href="#168">168</a> }
<a name="169" href="#169">169</a>
<a name="170" href="#170">170</a> <em>/**<em>*</em></em>
<a name="171" href="#171">171</a> <em> * Gets the last header with the given name.</em>
<a name="172" href="#172">172</a> <em> *</em>
<a name="173" href="#173">173</a> <em> * <p>Header name comparison is case insensitive.</em>
<a name="174" href="#174">174</a> <em> *</em>
<a name="175" href="#175">175</a> <em> * @param name the name of the header to get</em>
<a name="176" href="#176">176</a> <em> * @return the last header or <code>null</code></em>
<a name="177" href="#177">177</a> <em> */</em>
<a name="178" href="#178">178</a> <strong>public</strong> <a href="../../../../org/apache/commons/httpclient/Header.html">Header</a> getLastHeader(String name) {
<a name="179" href="#179">179</a> <em class="comment">// start at the end of the list and work backwards</em>
<a name="180" href="#180">180</a> <strong>for</strong> (<strong>int</strong> i = headers.size() - 1; i >= 0; i--) {
<a name="181" href="#181">181</a> <a href="../../../../org/apache/commons/httpclient/Header.html">Header</a> header = (Header) headers.get(i);
<a name="182" href="#182">182</a> <strong>if</strong> (header.getName().equalsIgnoreCase(name)) {
<a name="183" href="#183">183</a> <strong>return</strong> header;
<a name="184" href="#184">184</a> }
<a name="185" href="#185">185</a> }
<a name="186" href="#186">186</a>
<a name="187" href="#187">187</a> <strong>return</strong> <strong>null</strong>;
<a name="188" href="#188">188</a> }
<a name="189" href="#189">189</a>
<a name="190" href="#190">190</a> <em>/**<em>*</em></em>
<a name="191" href="#191">191</a> <em> * Gets all of the headers contained within this group.</em>
<a name="192" href="#192">192</a> <em> * </em>
<a name="193" href="#193">193</a> <em> * @return an array of length >= 0</em>
<a name="194" href="#194">194</a> <em> */</em>
<a name="195" href="#195">195</a> <strong>public</strong> <a href="../../../../org/apache/commons/httpclient/Header.html">Header</a>[] getAllHeaders() {
<a name="196" href="#196">196</a> <strong>return</strong> (Header[]) headers.toArray(<strong>new</strong> Header[headers.size()]);
<a name="197" href="#197">197</a> }
<a name="198" href="#198">198</a>
<a name="199" href="#199">199</a> <em>/**<em>*</em></em>
<a name="200" href="#200">200</a> <em> * Tests if headers with the given name are contained within this group.</em>
<a name="201" href="#201">201</a> <em> * </em>
<a name="202" href="#202">202</a> <em> * <p>Header name comparison is case insensitive.</em>
<a name="203" href="#203">203</a> <em> * </em>
<a name="204" href="#204">204</a> <em> * @param name the header name to test for</em>
<a name="205" href="#205">205</a> <em> * @return <code>true</code> if at least one header with the name is</em>
<a name="206" href="#206">206</a> <em> * contained, <code>false</code> otherwise</em>
<a name="207" href="#207">207</a> <em> */</em>
<a name="208" href="#208">208</a> <strong>public</strong> <strong>boolean</strong> containsHeader(String name) {
<a name="209" href="#209">209</a> <strong>for</strong> (Iterator headerIter = headers.iterator(); headerIter.hasNext();) {
<a name="210" href="#210">210</a> <a href="../../../../org/apache/commons/httpclient/Header.html">Header</a> header = (Header) headerIter.next();
<a name="211" href="#211">211</a> <strong>if</strong> (header.getName().equalsIgnoreCase(name)) {
<a name="212" href="#212">212</a> <strong>return</strong> <strong>true</strong>;
<a name="213" href="#213">213</a> }
<a name="214" href="#214">214</a> }
<a name="215" href="#215">215</a>
<a name="216" href="#216">216</a> <strong>return</strong> false;
<a name="217" href="#217">217</a> }
<a name="218" href="#218">218</a>
<a name="219" href="#219">219</a> <em>/**<em>*</em></em>
<a name="220" href="#220">220</a> <em> * Returns an iterator over this group of headers.</em>
<a name="221" href="#221">221</a> <em> * </em>
<a name="222" href="#222">222</a> <em> * @return iterator over this group of headers.</em>
<a name="223" href="#223">223</a> <em> * </em>
<a name="224" href="#224">224</a> <em> * @since 3.0</em>
<a name="225" href="#225">225</a> <em> */</em>
<a name="226" href="#226">226</a> <strong>public</strong> Iterator getIterator() {
<a name="227" href="#227">227</a> <strong>return</strong> <strong>this</strong>.headers.iterator();
<a name="228" href="#228">228</a> }
<a name="229" href="#229">229</a> }
</pre>
<hr/><div id="footer">This page was automatically generated by <a href="http://maven.apache.org/">Maven</a></div></body>
</html>
|
mit
|
huntervwang/bobingqing_www
|
gradle_groovydoc/org/gradle/api/plugins/quality/FindBugsXmlReport.html
|
13677
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- **************************************************************** -->
<!-- * PLEASE KEEP COMPLICATED EXPRESSIONS OUT OF THESE TEMPLATES, * -->
<!-- * i.e. only iterate & print data where possible. Thanks, Jez. * -->
<!-- **************************************************************** -->
<html>
<head>
<!-- Generated by groovydoc (2.3.9) on Mon Feb 16 06:14:52 CET 2015 -->
<title>FindBugsXmlReport (Gradle API 2.3)</title>
<meta name="date" content="2015-02-16">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href="../../../../../groovy.ico" type="image/x-icon" rel="shortcut icon">
<link href="../../../../../groovy.ico" type="image/x-icon" rel="icon">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<body class="center">
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="FindBugsXmlReport (Gradle API 2.3)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<div>
<ul class="navList">
<li><a href="../../../../../index.html?org/gradle/api/plugins/quality/FindBugsXmlReport" target="_top">Frames</a></li>
<li><a href="FindBugsXmlReport.html" target="_top">No Frames</a></li>
</ul>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
Nested Field <li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li> | Detail: </li>
Field <li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">Package: <strong>org.gradle.api.plugins.quality</strong></div>
<h2 title="[Java] Interface FindBugsXmlReport" class="title">[Java] Interface FindBugsXmlReport</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li><ul class="inheritance"></ul></li><li><ul class="inheritance"></ul></li><li><ul class="inheritance"></ul></li><li>org.gradle.api.reporting.SingleFileReport
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Superinterfaces:</dt>
<dd><a href='../../../../../org/gradle/api/reporting/ConfigurableReport.html'>ConfigurableReport</a>, <a href='../../../../../org/gradle/api/reporting/Report.html'>Report</a>, <a href='../../../../../org/gradle/api/reporting/SingleFileReport.html'>SingleFileReport</a></dd>
</dl>
<p> The single file XML report for FindBugs.
</p>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- =========== NESTED CLASS SUMMARY =========== -->
<!-- =========== ENUM CONSTANT SUMMARY =========== -->
<!-- =========== FIELD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="field_summary"><!-- --></a>
<ul class="blockList">
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Inherited fields summary table">
<caption><span>Inherited fields</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Fields inherited from class</th>
<th class="colLast" scope="col">Fields</th>
</tr>
<tr class="altColor">
<td class="colFirst"><strong><code>interface <a href='../../../../../org/gradle/api/reporting/Report.html'>Report</a></code></strong></td>
<td class="colLast"><code><a href='../../../../../org/gradle/api/reporting/Report.html#NAMER'>NAMER</a></code></td>
</tr>
</table>
</ul>
</li>
</ul>
<!-- =========== PROPERTY SUMMARY =========== -->
<!-- =========== ELEMENT SUMMARY =========== -->
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_summary"><!-- --></a>
<h3>Methods Summary</h3>
<ul class="blockList">
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Methods Summary table">
<caption><span>Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Type</th>
<th class="colLast" scope="col">Name and description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>boolean</strong></code></td>
<td class="colLast"><code><strong><a href="#isWithMessages()">isWithMessages</a></strong>()</code><br>Whether or not FindBugs should generate XML augmented with human-readable messages.
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</strong></code></td>
<td class="colLast"><code><strong><a href="#setWithMessages(boolean)">setWithMessages</a></strong>(boolean withMessages)</code><br>Whether or not FindBugs should generate XML augmented with human-readable messages.</td>
</tr>
</table>
</ul>
</li>
<li class="blockList"><a name="method_summary"><!-- --></a>
<h3>Inherited Methods Summary</h3>
<ul class="blockList">
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Inherited Methods Summary table">
<caption><span>Inherited Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Methods inherited from class</th>
<th class="colLast" scope="col">Name</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>interface <a href='../../../../../org/gradle/api/reporting/SingleFileReport.html'>SingleFileReport</a></strong></code></td>
<td class="colLast"><code><a href='../../../../../org/gradle/api/reporting/SingleFileReport.html#getOutputType()'>getOutputType</a></code></td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>interface <a href='../../../../../org/gradle/api/reporting/ConfigurableReport.html'>ConfigurableReport</a></strong></code></td>
<td class="colLast"><code><a href='../../../../../org/gradle/api/reporting/ConfigurableReport.html#setDestination(java.lang.Object)'>setDestination</a></code></td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>interface <a href='../../../../../org/gradle/api/reporting/Report.html'>Report</a></strong></code></td>
<td class="colLast"><code><a href='../../../../../org/gradle/api/reporting/Report.html#getDestination()'>getDestination</a>, <a href='../../../../../org/gradle/api/reporting/Report.html#getDisplayName()'>getDisplayName</a>, <a href='../../../../../org/gradle/api/reporting/Report.html#getName()'>getName</a>, <a href='../../../../../org/gradle/api/reporting/Report.html#getOutputType()'>getOutputType</a>, <a href='../../../../../org/gradle/api/reporting/Report.html#isEnabled()'>isEnabled</a>, <a href='../../../../../org/gradle/api/reporting/Report.html#setEnabled(boolean)'>setEnabled</a></code></td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>interface org.gradle.util.Configurable</strong></code></td>
<td class="colLast"><code>org.gradle.util.Configurable#configure(groovy.lang.Closure)</code></td>
</tr>
</table>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- =========== METHOD DETAIL =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="isWithMessages()"><!-- --></a>
<ul class="blockListLast">
<li class="blockList">
<h4>public boolean <strong>isWithMessages</strong>()</h4>
<p> Whether or not FindBugs should generate XML augmented with human-readable messages.
You should use this format if you plan to generate a report using an XSL stylesheet.
<p>
If <CODE>true</CODE>, FindBugs will augment the XML with human-readable messages.
If <CODE>false</CODE>, FindBugs will not augment the XML with human-readable messages.
<DL><DT><B>Returns:</B></DT><DD>Whether or not FindBugs should generate XML augmented with human-readable messages.</DD></DL></p>
</li>
</ul>
<a name="setWithMessages(boolean)"><!-- --></a>
<ul class="blockListLast">
<li class="blockList">
<h4>public void <strong>setWithMessages</strong>(boolean withMessages)</h4>
<p> Whether or not FindBugs should generate XML augmented with human-readable messages.
<DL><DT><B>Parameters:</B></DT><DD><code>withMessages</code> - Whether or not FindBugs should generate XML augmented with human-readable messages.</DD></DL><DL><DT><B>See Also:</B></DT><DD><a href='#isWithMessages()'>isWithMessages()</a></DD></DL></p>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<div>
<ul class="navList">
<li><a href="../../../../../index.html?org/gradle/api/plugins/quality/FindBugsXmlReport" target="_top">Frames</a></li>
<li><a href="FindBugsXmlReport.html" target="_top">No Frames</a></li>
</ul>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
Nested Field <li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li> | Detail: </li>
Field <li><a href="#method_detail">Method</a></li>
</ul>
</div>
<p>Gradle API 2.3</p>
<a name="skip-navbar_bottom">
<!-- -->
</a>
</div>
</div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
|
mit
|
selvasingh/azure-sdk-for-java
|
sdk/datamigration/mgmt-v2017_11_15_preview/src/main/java/com/microsoft/azure/management/datamigration/v2017_11_15_preview/implementation/IdParsingUtils.java
|
1762
|
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.datamigration.v2017_11_15_preview.implementation;
import java.util.Arrays;
import java.util.Iterator;
class IdParsingUtils {
public static String getValueFromIdByName(String id, String name) {
if (id == null) {
return null;
}
Iterable<String> iterable = Arrays.asList(id.split("/"));
Iterator<String> itr = iterable.iterator();
while (itr.hasNext()) {
String part = itr.next();
if (part != null && part.trim() != "") {
if (part.equalsIgnoreCase(name)) {
if (itr.hasNext()) {
return itr.next();
} else {
return null;
}
}
}
}
return null;
}
public static String getValueFromIdByPosition(String id, int pos) {
if (id == null) {
return null;
}
Iterable<String> iterable = Arrays.asList(id.split("/"));
Iterator <String> itr = iterable.iterator();
int index = 0;
while (itr.hasNext()) {
String part = itr.next();
if (part != null && part.trim() != "") {
if (index == pos) {
if (itr.hasNext()) {
return itr.next();
} else {
return null;
}
}
}
index++;
}
return null;
}
}
|
mit
|
Mozu/mozu-java
|
mozu-javaasync-core/src/main/java/com/mozu/api/contracts/productadmin/CurrencyLocalizationCollection.java
|
1459
|
/**
* This code was auto-generated by a Codezu.
*
* Changes to this file may cause incorrect behavior and will be lost if
* the code is regenerated.
*/
package com.mozu.api.contracts.productadmin;
import java.util.List;
import java.util.HashMap;
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.joda.time.DateTime;
import java.io.IOException;
import java.lang.ClassNotFoundException;
import com.mozu.api.contracts.productadmin.CurrencyLocalization;
/**
* Collection of data about currency localization formatting rules, such as decimal places and rounding strategies.
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class CurrencyLocalizationCollection implements Serializable
{
// Default Serial Version UID
private static final long serialVersionUID = 1L;
/**
* The total number of items in the list.
*/
protected Integer totalCount;
public Integer getTotalCount() {
return this.totalCount;
}
public void setTotalCount(Integer totalCount) {
this.totalCount = totalCount;
}
/**
* A list of requested items. All returned data is provided in an items array.For a failed request, the returned response may be success with an empty item array.
*/
protected List<CurrencyLocalization> items;
public List<CurrencyLocalization> getItems() {
return this.items;
}
public void setItems(List<CurrencyLocalization> items) {
this.items = items;
}
}
|
mit
|
ParticularLabs/GitVersion
|
src/GitVersionCore.Tests/BuildAgents/GitHubActionsTests.cs
|
6097
|
using System.Collections.Generic;
using System.IO;
using GitVersion;
using GitVersion.BuildAgents;
using GitVersionCore.Tests.Helpers;
using Microsoft.Extensions.DependencyInjection;
using NUnit.Framework;
using Shouldly;
using Environment = System.Environment;
namespace GitVersionCore.Tests.BuildAgents
{
[TestFixture]
public class GitHubActionsTests : TestBase
{
private IEnvironment environment;
private GitHubActions buildServer;
private string githubSetEnvironmentTempFilePath;
[SetUp]
public void SetUp()
{
var sp = ConfigureServices(services =>
{
services.AddSingleton<GitHubActions>();
});
environment = sp.GetService<IEnvironment>();
buildServer = sp.GetService<GitHubActions>();
environment.SetEnvironmentVariable(GitHubActions.EnvironmentVariableName, "true");
githubSetEnvironmentTempFilePath = Path.GetTempFileName();
environment.SetEnvironmentVariable(GitHubActions.GitHubSetEnvTempFileEnvironmentVariableName, githubSetEnvironmentTempFilePath);
}
[TearDown]
public void TearDown()
{
environment.SetEnvironmentVariable(GitHubActions.EnvironmentVariableName, null);
environment.SetEnvironmentVariable(GitHubActions.GitHubSetEnvTempFileEnvironmentVariableName, null);
if (githubSetEnvironmentTempFilePath != null && File.Exists(githubSetEnvironmentTempFilePath))
{
File.Delete(githubSetEnvironmentTempFilePath);
githubSetEnvironmentTempFilePath = null;
}
}
[Test]
public void CanApplyToCurrentContextShouldBeTrueWhenEnvironmentVariableIsSet()
{
// Act
var result = buildServer.CanApplyToCurrentContext();
// Assert
result.ShouldBeTrue();
}
[Test]
public void CanApplyToCurrentContextShouldBeFalseWhenEnvironmentVariableIsNotSet()
{
// Arrange
environment.SetEnvironmentVariable(GitHubActions.EnvironmentVariableName, "");
// Act
var result = buildServer.CanApplyToCurrentContext();
// Assert
result.ShouldBeFalse();
}
[Test]
public void GetCurrentBranchShouldHandleBranches()
{
// Arrange
environment.SetEnvironmentVariable("GITHUB_REF", "refs/heads/master");
// Act
var result = buildServer.GetCurrentBranch(false);
// Assert
result.ShouldBe("refs/heads/master");
}
[Test]
public void GetCurrentBranchShouldHandleTags()
{
// Arrange
environment.SetEnvironmentVariable("GITHUB_REF", "refs/tags/1.0.0");
// Act
var result = buildServer.GetCurrentBranch(false);
// Assert
result.ShouldBe("refs/tags/1.0.0");
}
[Test]
public void GetCurrentBranchShouldHandlePullRequests()
{
// Arrange
environment.SetEnvironmentVariable("GITHUB_REF", "refs/pull/1/merge");
// Act
var result = buildServer.GetCurrentBranch(false);
// Assert
result.ShouldBe("refs/pull/1/merge");
}
[Test]
public void GetSetParameterMessage()
{
// Assert
environment.GetEnvironmentVariable("GitVersion_Something").ShouldBeNullOrWhiteSpace();
// Act
var result = buildServer.GenerateSetParameterMessage("GitVersion_Something", "1.0.0");
// Assert
result.ShouldContain(s => true, 0);
}
[Test]
public void SkipEmptySetParameterMessage()
{
// Act
var result = buildServer.GenerateSetParameterMessage("Hello", string.Empty);
// Assert
result.ShouldBeEquivalentTo(new string[0]);
}
[Test]
public void ShouldWriteIntegration()
{
// Arrange
var vars = new TestableVersionVariables("1.0.0");
var list = new List<string>();
// Assert
environment.GetEnvironmentVariable("GitVersion_Major").ShouldBeNullOrWhiteSpace();
// Act
buildServer.WriteIntegration(s => { list.Add(s); }, vars);
// Assert
var expected = new List<string>
{
"Executing GenerateSetVersionMessage for 'GitHubActions'.",
"",
"Executing GenerateBuildLogOutput for 'GitHubActions'.",
"Writing version variables to $GITHUB_ENV file for 'GitHubActions'."
};
string.Join(Environment.NewLine, list)
.ShouldBe(string.Join(Environment.NewLine, expected));
var expectedFileContents = new List<string>
{
"GitVersion_Major=1.0.0"
};
var actualFileContents = File.ReadAllLines(githubSetEnvironmentTempFilePath);
actualFileContents.ShouldBe(expectedFileContents);
}
[Test]
public void ShouldNotWriteIntegration()
{
// Arrange
var vars = new TestableVersionVariables("1.0.0");
var list = new List<string>();
// Assert
environment.GetEnvironmentVariable("GitVersion_Major").ShouldBeNullOrWhiteSpace();
// Act
buildServer.WriteIntegration(s => { list.Add(s); }, vars, false);
list.ShouldNotContain(x => x.StartsWith("Executing GenerateSetVersionMessage for "));
}
[Test]
public void GetEmptyGenerateSetVersionMessage()
{
// Arrange
var vars = new TestableVersionVariables("1.0.0");
// Act
var message = buildServer.GenerateSetVersionMessage(vars);
// Assert
message.ShouldBeEmpty();
}
}
}
|
mit
|
OGRECave/ogre
|
RenderSystems/Vulkan/src/OgreVulkanQueue.cpp
|
40249
|
/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-present Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreVulkanQueue.h"
#include "OgreVulkanDevice.h"
#include "OgreVulkanMappings.h"
#include "OgreVulkanRenderSystem.h"
#include "OgreVulkanTextureGpu.h"
#include "OgreVulkanWindow.h"
#include "OgreException.h"
#include "OgrePixelFormat.h"
#include "OgreStringConverter.h"
#include "OgreVulkanUtils.h"
#include "OgreVulkanDescriptorPool.h"
#define TODO_findRealPresentQueue
#define TODO_we_assume_has_stencil
namespace Ogre
{
// Mask away read flags from srcAccessMask
static const uint32 c_srcValidAccessFlags =
0xFFFFFFFF ^
( VK_ACCESS_INDIRECT_COMMAND_READ_BIT | VK_ACCESS_INDEX_READ_BIT |
VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT | VK_ACCESS_UNIFORM_READ_BIT |
VK_ACCESS_INPUT_ATTACHMENT_READ_BIT | VK_ACCESS_SHADER_READ_BIT |
VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT |
VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_HOST_READ_BIT | VK_ACCESS_MEMORY_READ_BIT );
VulkanQueue::VulkanQueue() :
mDevice( 0 ),
mFamily( NumQueueFamilies ),
mFamilyIdx( 0u ),
mQueueIdx( 0u ),
mQueue( 0 ),
mCurrentCmdBuffer( 0 ),
mOwnerDevice( 0 ),
mNumFramesInFlight( 3 ),
mCurrentFrameIdx( 0 ),
mRenderSystem( 0 ),
mCurrentFence( 0 ),
mEncoderState( EncoderClosed ),
mCopyEndReadSrcBufferFlags( 0 ),
mCopyEndReadDstBufferFlags( 0 ),
mCopyEndReadDstTextureFlags( 0 ),
mCopyStartWriteSrcBufferFlags( 0 )
{
}
//-------------------------------------------------------------------------
VulkanQueue::~VulkanQueue() { destroy(); }
//-------------------------------------------------------------------------
void VulkanQueue::setQueueData( VulkanDevice *owner, QueueFamily family, uint32 familyIdx,
uint32 queueIdx )
{
mOwnerDevice = owner;
mFamily = family;
mFamilyIdx = familyIdx;
mQueueIdx = queueIdx;
}
//-------------------------------------------------------------------------
void VulkanQueue::init( VkDevice device, VkQueue queue, VulkanRenderSystem *renderSystem )
{
mDevice = device;
mQueue = queue;
mRenderSystem = renderSystem;
mPerFrameData.resize( mNumFramesInFlight );
VkCommandPoolCreateInfo cmdPoolCreateInfo = {VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO};
cmdPoolCreateInfo.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT;
cmdPoolCreateInfo.queueFamilyIndex = mFamilyIdx;
VkCommandBufferAllocateInfo allocateInfo = {VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO};
allocateInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
allocateInfo.commandBufferCount = 1u;
VkFenceCreateInfo fenceCi = {VK_STRUCTURE_TYPE_FENCE_CREATE_INFO};
fenceCi.flags = VK_FENCE_CREATE_SIGNALED_BIT;
for (auto& fd : mPerFrameData)
{
OGRE_VK_CHECK(vkCreateCommandPool(mDevice, &cmdPoolCreateInfo, 0, &fd.mCommandPool));
allocateInfo.commandPool = fd.mCommandPool;
OGRE_VK_CHECK(vkAllocateCommandBuffers( mDevice, &allocateInfo, &fd.mCommandBuffer ));
OGRE_VK_CHECK(vkCreateFence(mDevice, &fenceCi, 0, &fd.mProtectingFence));
}
newCommandBuffer();
}
void VulkanQueue::destroy()
{
if( mDevice )
{
vkDeviceWaitIdle( mDevice );
for(size_t i = 0; i < mPerFrameData.size(); ++i)
{
_waitOnFrame(i);
}
for(auto& fd : mPerFrameData)
{
vkDestroyFence( mDevice, fd.mProtectingFence, 0 );
vkDestroyCommandPool( mDevice, fd.mCommandPool, 0 );
}
mDevice = 0;
}
}
//-------------------------------------------------------------------------
void VulkanQueue::newCommandBuffer( void )
{
_waitOnFrame(mCurrentFrameIdx);
vkResetCommandPool(mDevice, mPerFrameData[mCurrentFrameIdx].mCommandPool, 0);
mCurrentCmdBuffer = mPerFrameData[mCurrentFrameIdx].mCommandBuffer;
mCurrentFence = mPerFrameData[mCurrentFrameIdx].mProtectingFence;
VkCommandBufferBeginInfo beginInfo = {VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO};
beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
vkBeginCommandBuffer( mCurrentCmdBuffer, &beginInfo );
}
//-------------------------------------------------------------------------
void VulkanQueue::endCommandBuffer( void )
{
if( mCurrentCmdBuffer )
{
endAllEncoders();
OGRE_VK_CHECK(vkEndCommandBuffer( mCurrentCmdBuffer ));
}
}
//-------------------------------------------------------------------------
void VulkanQueue::getGraphicsEncoder( void )
{
if( mEncoderState != EncoderGraphicsOpen )
{
endCopyEncoder();
endComputeEncoder();
mEncoderState = EncoderGraphicsOpen;
}
}
//-------------------------------------------------------------------------
void VulkanQueue::getComputeEncoder( void )
{
if( mEncoderState != EncoderComputeOpen )
{
endRenderEncoder();
endCopyEncoder();
mEncoderState = EncoderComputeOpen;
}
}
//-------------------------------------------------------------------------
VkPipelineStageFlags VulkanQueue::deriveStageFromBufferAccessFlags( VkAccessFlags accessFlags )
{
VkPipelineStageFlags stage = 0;
if( accessFlags & VK_ACCESS_INDIRECT_COMMAND_READ_BIT )
stage |= VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT;
if( accessFlags & ( VK_ACCESS_INDEX_READ_BIT | VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT ) )
{
stage |= VK_PIPELINE_STAGE_VERTEX_INPUT_BIT;
}
if( accessFlags &
( VK_ACCESS_UNIFORM_READ_BIT | VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT ) )
{
stage |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT |
VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT |
VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT |
VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT |
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
}
if( accessFlags & ( VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT ) )
{
stage |= VK_PIPELINE_STAGE_TRANSFER_BIT;
}
return stage;
}
//-------------------------------------------------------------------------
VkPipelineStageFlags VulkanQueue::deriveStageFromTextureAccessFlags( VkAccessFlags accessFlags )
{
VkPipelineStageFlags stage = 0;
if( accessFlags & ( VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT |
VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT ) )
{
stage |=
VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT;
}
if( accessFlags &
( VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT ) )
{
stage |= VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
}
if( accessFlags & ( VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT ) )
{
stage |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT |
VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT |
VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT |
VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT |
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
}
if( accessFlags & ( VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT ) )
{
stage |= VK_PIPELINE_STAGE_TRANSFER_BIT;
}
if( accessFlags & VK_ACCESS_INPUT_ATTACHMENT_READ_BIT )
stage |= VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
return stage;
}
//-------------------------------------------------------------------------
void VulkanQueue::insertRestoreBarrier( VulkanTextureGpu *vkTexture,
const VkImageLayout newTransferLayout )
{
const VkImageLayout oldLayout = vkTexture->mCurrLayout;
const VkImageLayout otherTransferLayout =
newTransferLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL
? VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL
: VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
const VkAccessFlags accessFlags = newTransferLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL
? VK_ACCESS_TRANSFER_READ_BIT
: VK_ACCESS_TRANSFER_WRITE_BIT;
if( oldLayout == newTransferLayout )
{
// Nothing to do. A restore barrier has already been inserted
// If the assert fails, then the texture transitioned
// to this layout without us knowing
OGRE_ASSERT_HIGH( std::find( mImageMemBarrierPtrs.begin(), mImageMemBarrierPtrs.end(),
vkTexture ) != mImageMemBarrierPtrs.end() &&
"Only this class should set VK_IMAGE_LAYOUT_TRANSFER_*_OPTIMAL" );
}
else if( oldLayout == otherTransferLayout )
{
// A restore barrier has already been inserted, but it needs modification
FastArray<TextureGpu *>::iterator itor =
std::find( mImageMemBarrierPtrs.begin(), mImageMemBarrierPtrs.end(), vkTexture );
// If the assert fails, then the texture transitioned
// to this layout without us knowing
OGRE_ASSERT_LOW( itor != mImageMemBarrierPtrs.end() &&
"Only this class should set VK_IMAGE_LAYOUT_TRANSFER_*_OPTIMAL" );
const size_t idx = ( size_t )( itor - mImageMemBarrierPtrs.begin() );
VkImageMemoryBarrier &imageMemBarrier = *( mImageMemBarriers.begin() + idx );
imageMemBarrier.srcAccessMask = accessFlags & c_srcValidAccessFlags;
imageMemBarrier.oldLayout = newTransferLayout;
}
else
{
// First time we see this texture
VkImageMemoryBarrier imageMemBarrier = vkTexture->getImageMemoryBarrier();
imageMemBarrier.srcAccessMask = accessFlags & c_srcValidAccessFlags;
imageMemBarrier.dstAccessMask = VulkanMappings::get( vkTexture );
if( newTransferLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL )
{
// We need to block subsequent stages from writing to this texture
// until we're done copying from it (but they can read)
imageMemBarrier.dstAccessMask &= (VkAccessFlags)~VK_ACCESS_SHADER_READ_BIT;
mCopyEndReadDstTextureFlags |= imageMemBarrier.dstAccessMask;
}
imageMemBarrier.oldLayout = newTransferLayout;
imageMemBarrier.newLayout = vkTexture->mNextLayout;
mImageMemBarriers.push_back( imageMemBarrier );
mImageMemBarrierPtrs.push_back( vkTexture );
}
}
//-------------------------------------------------------------------------
void VulkanQueue::prepareForUpload( const BufferPacked *buffer, TextureGpu *texture )
{
VkAccessFlags bufferAccessFlags = 0;
if( buffer )
{
BufferPackedDownloadMap::iterator it = mCopyDownloadBuffers.find( buffer );
if( it == mCopyDownloadBuffers.end() )
;//bufferAccessFlags = VulkanMappings::get( buffer->getBufferPackedType() );
else
{
if( !it->second )
{
// bufferAccessFlags = VK_ACCESS_TRANSFER_WRITE_BIT;
// We assume consecutive writes means we're writing to non-overlapping areas
// Do not wait for previous transfers.
bufferAccessFlags = 0;
}
else
bufferAccessFlags = VK_ACCESS_TRANSFER_READ_BIT;
}
mCopyDownloadBuffers[buffer] = false;
mCopyEndReadSrcBufferFlags |= VK_ACCESS_TRANSFER_WRITE_BIT;
}
OGRE_ASSERT_HIGH( !texture || dynamic_cast<VulkanTextureGpu *>( texture ) );
VulkanTextureGpu *vkTexture = static_cast<VulkanTextureGpu *>( texture );
VkAccessFlags texAccessFlags = 0;
if( texture )
{
TextureGpuDownloadMap::iterator it = mCopyDownloadTextures.find( vkTexture );
if( vkTexture->mCurrLayout == VK_IMAGE_LAYOUT_UNDEFINED )
{
// This texture must just have been created
texAccessFlags = 0;
}
else if( it == mCopyDownloadTextures.end() )
{
if( vkTexture->mCurrLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL ||
vkTexture->mCurrLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL )
{
OGRE_EXCEPT( Exception::ERR_INVALID_STATE,
"Texture " + vkTexture->getName() +
" is already in CopySrc or CopyDst layout, externally set. Perhaps "
"you need to call RenderSystem::flushTextureCopyOperations",
"VulkanQueue::prepareForUpload" );
}
texAccessFlags = VulkanMappings::get( texture );
}
else
{
if( !it->second )
{
OGRE_ASSERT_MEDIUM( vkTexture->mCurrLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL );
// texAccessFlags = VK_ACCESS_TRANSFER_WRITE_BIT;
// We assume consecutive writes means we're writing to non-overlapping areas
// Do not wait for previous transfers.
texAccessFlags = 0;
}
else
{
OGRE_ASSERT_MEDIUM( vkTexture->mCurrLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL );
texAccessFlags = VK_ACCESS_TRANSFER_READ_BIT;
}
}
// We need to block subsequent stages from accessing this texture at all
// until we're done copying into it
mCopyEndReadDstTextureFlags |= VulkanMappings::get( texture );
mCopyDownloadTextures[vkTexture] = false;
}
// One buffer barrier is enough for all buffers.
// Unless we already issued a transfer to this same buffer
const bool bNeedsBufferBarrier =
( bufferAccessFlags &&
( mCopyEndReadDstBufferFlags & bufferAccessFlags ) != bufferAccessFlags ) ||
( bufferAccessFlags & ( VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT ) );
const bool bNeedsTexTransition =
vkTexture && vkTexture->mCurrLayout != VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
mCopyEndReadDstBufferFlags |= bufferAccessFlags;
// Trigger the barrier if we actually have to wait.
// And only if we haven't issued this barrier already
if( bNeedsBufferBarrier || bNeedsTexTransition )
{
VkPipelineStageFlags srcStage = 0;
uint32 numMemBarriers = 0u;
VkMemoryBarrier memBarrier = {VK_STRUCTURE_TYPE_MEMORY_BARRIER};
if( bNeedsBufferBarrier )
{
// GPU must stop using this buffer before we can write into it
memBarrier.srcAccessMask = bufferAccessFlags & c_srcValidAccessFlags;
memBarrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
srcStage |= deriveStageFromBufferAccessFlags( bufferAccessFlags );
numMemBarriers = 1u;
}
uint32 numImageMemBarriers = 0u;
VkImageMemoryBarrier imageMemBarrier;
if( bNeedsTexTransition )
{
// GPU must stop using this texture before we can write into it
// Also we need to do a transition
imageMemBarrier = vkTexture->getImageMemoryBarrier();
imageMemBarrier.srcAccessMask = texAccessFlags & c_srcValidAccessFlags;
imageMemBarrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
imageMemBarrier.oldLayout = vkTexture->mCurrLayout;
imageMemBarrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
if( texAccessFlags == 0u )
{
if( bufferAccessFlags == 0u )
{
// Wait for nothing. We're only issuing a barrier
// because of the texture transition
srcStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
}
}
else
{
srcStage |= deriveStageFromTextureAccessFlags( texAccessFlags );
}
insertRestoreBarrier( vkTexture, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL );
vkTexture->mCurrLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
numImageMemBarriers = 1u;
}
// Wait until earlier render, compute and transfers are done so we can copy what
// they wrote (unless we're only here for a texture transition)
vkCmdPipelineBarrier( mCurrentCmdBuffer, srcStage & mOwnerDevice->mSupportedStages,
VK_PIPELINE_STAGE_TRANSFER_BIT, 0, numMemBarriers, &memBarrier, 0u, 0,
numImageMemBarriers, &imageMemBarrier );
}
}
//-------------------------------------------------------------------------
void VulkanQueue::prepareForDownload( const BufferPacked *buffer, VulkanTextureGpu *texture )
{
VkAccessFlags bufferAccessFlags = 0;
VkPipelineStageFlags srcStage = 0;
// Evaluate the stages which blocks us before we can begin our transfer
if( buffer )
{
BufferPackedDownloadMap::iterator it = mCopyDownloadBuffers.find( buffer );
if( it == mCopyDownloadBuffers.end() )
{
if( /*buffer->getBufferPackedType() == BP_TYPE_UAV*/ 0 )
{
bufferAccessFlags = VK_ACCESS_SHADER_WRITE_BIT;
srcStage |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT |
VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT |
VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT |
VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT |
VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT |
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
}
// else
//{
// If the buffer is not BT_TYPE_UAV, the GPU won't modify these buffers,
// we can start downloading right away without waiting
//}
}
else
{
if( !it->second )
{
bufferAccessFlags = VK_ACCESS_TRANSFER_WRITE_BIT;
srcStage |= VK_PIPELINE_STAGE_TRANSFER_BIT;
}
else
bufferAccessFlags = 0; // Consecutive reads don't require waiting
}
mCopyDownloadBuffers[buffer] = true;
mCopyEndReadSrcBufferFlags |= VK_ACCESS_TRANSFER_READ_BIT;
}
OGRE_ASSERT_HIGH( !texture || dynamic_cast<VulkanTextureGpu *>( texture ) );
VulkanTextureGpu *vkTexture = static_cast<VulkanTextureGpu *>( texture );
VkAccessFlags texAccessFlags = 0;
if( texture )
{
TextureGpuDownloadMap::iterator it = mCopyDownloadTextures.find( vkTexture );
if( it == mCopyDownloadTextures.end() )
{
if( vkTexture->mCurrLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL ||
vkTexture->mCurrLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL )
{
OGRE_EXCEPT( Exception::ERR_INVALID_STATE,
"Texture " + vkTexture->getName() +
" is already in CopySrc or CopyDst layout, externally set. Perhaps "
"you need to call RenderSystem::flushTextureCopyOperations",
"VulkanQueue::prepareForDownload" );
}
if( texture->isUav() )
{
texAccessFlags |= VK_ACCESS_SHADER_WRITE_BIT;
srcStage |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT |
VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT |
VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT |
VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT |
VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT |
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT;
}
if( texture->getUsage() & TU_RENDERTARGET )
{
texAccessFlags |= VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
if( !PixelUtil::isDepth( texture->getFormat() ) )
{
texAccessFlags |= VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
srcStage |= VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
}
else
{
texAccessFlags |= VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
srcStage |= VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT |
VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT;
}
}
}
else
{
if( !it->second )
{
OGRE_ASSERT_MEDIUM( vkTexture->mCurrLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL );
texAccessFlags = VK_ACCESS_TRANSFER_WRITE_BIT;
srcStage |= VK_PIPELINE_STAGE_TRANSFER_BIT;
}
else
{
OGRE_ASSERT_MEDIUM( vkTexture->mCurrLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL );
texAccessFlags = 0; // Consecutive reads don't require waiting
}
}
mCopyDownloadTextures[vkTexture] = true;
}
// One buffer barrier is enough for all buffers.
// Unless we already issued a transfer to this same buffer
const bool bNeedsBufferBarrier =
( bufferAccessFlags &&
( mCopyStartWriteSrcBufferFlags & bufferAccessFlags ) != bufferAccessFlags ) ||
( bufferAccessFlags & ( VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT ) );
mCopyStartWriteSrcBufferFlags |= bufferAccessFlags;
const bool bNeedsTexTransition =
vkTexture && vkTexture->mCurrLayout != VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
// Trigger the barrier if we actually have to wait.
// And only if we haven't issued this barrier already
if( bNeedsBufferBarrier || bNeedsTexTransition )
{
uint32 numMemBarriers = 0u;
VkMemoryBarrier memBarrier = {VK_STRUCTURE_TYPE_MEMORY_BARRIER};
if( bNeedsBufferBarrier )
{
memBarrier.srcAccessMask = bufferAccessFlags & c_srcValidAccessFlags;
memBarrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
numMemBarriers = 1u;
}
uint32 numImageMemBarriers = 0u;
VkImageMemoryBarrier imageMemBarrier;
if( bNeedsTexTransition )
{
imageMemBarrier = vkTexture->getImageMemoryBarrier();
imageMemBarrier.srcAccessMask = texAccessFlags & c_srcValidAccessFlags;
imageMemBarrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
imageMemBarrier.oldLayout = vkTexture->mCurrLayout;
imageMemBarrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
insertRestoreBarrier( vkTexture, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL );
vkTexture->mCurrLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
numImageMemBarriers = 1u;
if( !srcStage )
{
// If we're here the texture is read-only and we only
// need the barrier to perform a layout transition
srcStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
}
}
// Wait until earlier render, compute and transfers are done so we can copy what
// they wrote (unless we're only here for a texture transition)
vkCmdPipelineBarrier( mCurrentCmdBuffer, srcStage & mOwnerDevice->mSupportedStages,
VK_PIPELINE_STAGE_TRANSFER_BIT, 0, numMemBarriers, &memBarrier, 0u, 0,
numImageMemBarriers, &imageMemBarrier );
}
}
//-------------------------------------------------------------------------
void VulkanQueue::getCopyEncoder( const BufferPacked *buffer, VulkanTextureGpu *texture,
const bool bDownload )
{
OgreAssert(mEncoderState != EncoderGraphicsOpen, "interrupting RenderPass not supported");
if( mEncoderState != EncoderCopyOpen )
{
endRenderEncoder();
endComputeEncoder();
mEncoderState = EncoderCopyOpen;
// Submission guarantees the host write being complete, as per
// khronos.org/registry/vulkan/specs/1.0/html/vkspec.html#synchronization-submission-host-writes
// So no need for a barrier before the transfer
//
// The only exception is when writing from CPU to GPU when a command that uses that region
// has already been submitted via vkQueueSubmit (and you're using vkCmdWaitEvents to wait
// for the CPU to write the data and give ok to the GPU).
// Which Ogre does not do (too complex to get right).
}
if( bDownload )
prepareForDownload( buffer, texture );
else
prepareForUpload( buffer, texture );
}
//-------------------------------------------------------------------------
void VulkanQueue::getCopyEncoderV1Buffer( const bool bDownload )
{
OgreAssert(mEncoderState != EncoderGraphicsOpen, "interrupting RenderPass not supported");
if( mEncoderState != EncoderCopyOpen )
{
endRenderEncoder();
endComputeEncoder();
mEncoderState = EncoderCopyOpen;
}
if( !bDownload )
{
// V1 buffers are only used for vertex and index buffers
// We assume v1 buffers don't try to write then read (or read then write) in a row
const VkAccessFlags bufferAccessFlags =
VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT | VK_ACCESS_INDEX_READ_BIT;
if( ( mCopyEndReadDstBufferFlags & bufferAccessFlags ) != bufferAccessFlags )
{
uint32 numMemBarriers = 0u;
VkMemoryBarrier memBarrier = {VK_STRUCTURE_TYPE_MEMORY_BARRIER};
memBarrier.srcAccessMask = bufferAccessFlags & c_srcValidAccessFlags;
memBarrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
numMemBarriers = 1u;
// GPU must stop using this buffer before we can write into it
vkCmdPipelineBarrier( mCurrentCmdBuffer, VK_PIPELINE_STAGE_VERTEX_INPUT_BIT,
VK_PIPELINE_STAGE_TRANSFER_BIT, 0, numMemBarriers, &memBarrier, 0u,
0, 0u, 0 );
}
mCopyEndReadDstBufferFlags |= bufferAccessFlags;
mCopyEndReadSrcBufferFlags |= VK_ACCESS_TRANSFER_WRITE_BIT;
}
else
{
mCopyEndReadSrcBufferFlags |= VK_ACCESS_TRANSFER_READ_BIT;
}
}
//-------------------------------------------------------------------------
void VulkanQueue::endCopyEncoder( void )
{
if( mEncoderState != EncoderCopyOpen )
return;
if( mCopyEndReadDstBufferFlags || !mImageMemBarrierPtrs.empty() )
{
VkPipelineStageFlags dstStage = 0;
uint32 numMemBarriers = 0u;
VkMemoryBarrier memBarrier = {VK_STRUCTURE_TYPE_MEMORY_BARRIER};
if( mCopyEndReadDstBufferFlags )
{
memBarrier.srcAccessMask = mCopyEndReadSrcBufferFlags & c_srcValidAccessFlags;
memBarrier.dstAccessMask = mCopyEndReadDstBufferFlags;
// Evaluate the stages we can unblock when our transfers are done
dstStage |= deriveStageFromBufferAccessFlags( memBarrier.dstAccessMask );
numMemBarriers = 1u;
}
dstStage |= deriveStageFromTextureAccessFlags( mCopyEndReadDstTextureFlags );
if( dstStage == 0u )
{
// Nothing needs to wait for us. Can happen if all we're
// doing is copying from read-only textures (rare)
dstStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
#if OGRE_DEBUG_MODE
FastArray<TextureGpu *>::const_iterator itor = mImageMemBarrierPtrs.begin();
FastArray<TextureGpu *>::const_iterator endt = mImageMemBarrierPtrs.end();
while( itor != endt )
{
OgreAssert( (( *itor )->getUsage() & TU_RENDERTARGET) == 0/*&& !( *itor )->isUav()*/,
"endCopyEncoder says nothing will wait on this texture(s) but "
"we don't know if a subsequent stage will write to it" );
++itor;
}
#endif
}
// Wait until earlier render, compute and transfers are done
// Block render, compute and transfers until we're done
vkCmdPipelineBarrier( mCurrentCmdBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT,
dstStage & mOwnerDevice->mSupportedStages, 0, numMemBarriers,
&memBarrier, 0u, 0, static_cast<uint32_t>( mImageMemBarriers.size() ),
mImageMemBarriers.data() );
mImageMemBarriers.clear();
mImageMemBarrierPtrs.clear();
TextureGpuDownloadMap::const_iterator itor = mCopyDownloadTextures.begin();
TextureGpuDownloadMap::const_iterator endt = mCopyDownloadTextures.end();
while( itor != endt )
{
itor->first->mCurrLayout = itor->first->mNextLayout;
++itor;
}
}
mCopyEndReadSrcBufferFlags = 0;
mCopyEndReadDstBufferFlags = 0;
mCopyEndReadDstTextureFlags = 0;
mCopyStartWriteSrcBufferFlags = 0;
mCopyDownloadTextures.clear();
mCopyDownloadBuffers.clear();
mEncoderState = EncoderClosed;
}
//-------------------------------------------------------------------------
void VulkanQueue::endRenderEncoder( const bool endRenderPassDesc )
{
if( mEncoderState != EncoderGraphicsOpen )
return;
mRenderSystem->_notifyActiveEncoderEnded();
if( endRenderPassDesc )
mRenderSystem->endRenderPassDescriptor();
mEncoderState = EncoderClosed;
}
//-------------------------------------------------------------------------
void VulkanQueue::endComputeEncoder( void )
{
if( mEncoderState != EncoderComputeOpen )
return;
mEncoderState = EncoderClosed;
mRenderSystem->_notifyActiveComputeEnded();
}
//-------------------------------------------------------------------------
void VulkanQueue::endAllEncoders( const bool endRenderPassDesc )
{
endCopyEncoder();
endRenderEncoder( endRenderPassDesc );
endComputeEncoder();
}
//-------------------------------------------------------------------------
void VulkanQueue::notifyTextureDestroyed( VulkanTextureGpu *texture )
{
if( mEncoderState == EncoderCopyOpen )
{
bool needsToFlush = false;
TextureGpuDownloadMap::const_iterator itor = mCopyDownloadTextures.find( texture );
if( itor != mCopyDownloadTextures.end() )
needsToFlush = true;
else
{
FastArray<TextureGpu *>::const_iterator it2 =
std::find( mImageMemBarrierPtrs.begin(), mImageMemBarrierPtrs.end(), texture );
if( it2 != mImageMemBarrierPtrs.end() )
needsToFlush = true;
}
if( needsToFlush )
{
// If this asserts triggers, then the texture is probably being referenced
// by something else doing anything on the texture and was interrupted
// midway (since Ogre must ensure the texture ends in TRANSFER_SRC/DST_OPTIMAL
// if the copy encoder is holding a reference.
OGRE_ASSERT_LOW( texture->mCurrLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL ||
texture->mCurrLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL );
endCopyEncoder();
}
}
}
//-------------------------------------------------------------------------
void VulkanQueue::addWindowToWaitFor( VkSemaphore imageAcquisitionSemaph )
{
OGRE_ASSERT_MEDIUM( mFamily == Graphics );
mGpuWaitFlags.push_back( VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT );
mGpuWaitSemaphForCurrCmdBuff.push_back( imageAcquisitionSemaph );
}
//-------------------------------------------------------------------------
void VulkanQueue::queueForDeletion(VkBuffer buffer, VkDeviceMemory memory)
{
mPerFrameData[mCurrentFrameIdx].mBufferGraveyard.push_back({buffer, memory});
}
void VulkanQueue::queueForDeletion(const std::shared_ptr<VulkanDescriptorPool>& descriptorPool)
{
mPerFrameData[mCurrentFrameIdx].mDescriptorPoolGraveyard.push_back(descriptorPool);
}
void VulkanQueue::_waitOnFrame( uint8 frameIdx )
{
VkFence fence = mPerFrameData[frameIdx].mProtectingFence;
vkWaitForFences( mDevice, 1, &fence, VK_TRUE, UINT64_MAX );
// it is safe to free staging buffers now
for(auto bm : mPerFrameData[frameIdx].mBufferGraveyard)
{
vkDestroyBuffer(mDevice, bm.first, nullptr);
vkFreeMemory(mDevice, bm.second, nullptr);
}
mPerFrameData[frameIdx].mBufferGraveyard.clear();
mPerFrameData[frameIdx].mDescriptorPoolGraveyard.clear();
}
//-------------------------------------------------------------------------
bool VulkanQueue::_isFrameFinished( uint8 frameIdx )
{
VkFence fence = mPerFrameData[frameIdx].mProtectingFence;
VkResult ret = vkWaitForFences( mDevice, 1, &fence, VK_TRUE, 0u );
if( ret != VK_TIMEOUT )
{
OGRE_VK_CHECK(ret);
//recycleFences( fences );
return true;
}
return false;
}
//-------------------------------------------------------------------------
void VulkanQueue::commitAndNextCommandBuffer( SubmissionType::SubmissionType submissionType )
{
endCommandBuffer();
VkSubmitInfo submitInfo = {VK_STRUCTURE_TYPE_SUBMIT_INFO};
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &mCurrentCmdBuffer;
if( !mGpuWaitSemaphForCurrCmdBuff.empty() )
{
// We need to wait on these semaphores so that rendering can
// only happen start the swapchain is done presenting
submitInfo.waitSemaphoreCount = mGpuWaitSemaphForCurrCmdBuff.size();
submitInfo.pWaitSemaphores = mGpuWaitSemaphForCurrCmdBuff.data();
submitInfo.pWaitDstStageMask = mGpuWaitFlags.data();
}
if( submissionType >= SubmissionType::NewFrameIdx )
{
if( submissionType >= SubmissionType::EndFrameAndSwap )
{
// Get semaphores so that presentation can wait for this job to finish rendering
// (one for each window that will be swapped)
for (auto w : mWindowsPendingSwap)
{
mGpuSignalSemaphForCurrCmdBuff.push_back(w->getRenderFinishedSemaphore());
w->setImageFence(mCurrentFence);
}
}
if( !mGpuSignalSemaphForCurrCmdBuff.empty() )
{
// We need to signal these semaphores so that presentation
// can only happen after we're done rendering (presentation may not be the
// only thing waiting for us though; thus we must set this with NewFrameIdx
// and not just with EndFrameAndSwap)
submitInfo.signalSemaphoreCount = mGpuSignalSemaphForCurrCmdBuff.size();
submitInfo.pSignalSemaphores = mGpuSignalSemaphForCurrCmdBuff.data();
}
}
OGRE_VK_CHECK(vkResetFences(mDevice, 1, &mCurrentFence) );
vkQueueSubmit( mQueue, 1u, &submitInfo, mCurrentFence );
mGpuWaitSemaphForCurrCmdBuff.clear();
mCurrentCmdBuffer = VK_NULL_HANDLE;
if( submissionType >= SubmissionType::EndFrameAndSwap )
{
for (auto w : mWindowsPendingSwap)
w->_swapBuffers();
}
if( submissionType >= SubmissionType::NewFrameIdx )
{
mCurrentFrameIdx = (mCurrentFrameIdx + 1) % mPerFrameData.size();
}
newCommandBuffer();
if( submissionType >= SubmissionType::EndFrameAndSwap )
{
// acquireNextImage must be called after newCommandBuffer()
for (auto w : mWindowsPendingSwap)
w->acquireNextImage();
mWindowsPendingSwap.clear();
mGpuSignalSemaphForCurrCmdBuff.clear();
}
}
} // namespace Ogre
|
mit
|
michaelghinrichs/hello-world
|
scope-chains-closures/scopes.js
|
37
|
function foo() {
var bar = '';
};
|
mit
|
erniu/air
|
test-air.js
|
442
|
/*--
简单测试node.js端使用的air-js
-note 所有的模块以模块简称为属性名挂载在air上
*/
var air = require('air-js');
var byteLength = air.byteLength;
console.log(byteLength('中国人')); // => 6
console.log(byteLength('air')); // => 3
console.log(air.byteLength('air')); // => 3
console.log(air.clip('我是中国人', 8)); // => 我是中国…
console.log(air.thousandFloat(78934.25)); // => 78,934.25
|
mit
|
chirashijs/chirashi
|
lib/_internals/_parseAndApply.js
|
261
|
import forIn from '../core/forIn'
import forElements from '../core/forElements'
export default function _parseAndApply (parse, apply, elements, options) {
forIn(options, parse.bind(null, options))
return forElements(elements, apply.bind(null, options))
}
|
mit
|
beni55/vektor
|
sonar-scan/public/js/node_modules/jeesh/node_modules/bonzo/tests/tests.html
|
5302
|
<!DOCTYPE HTML>
<html lang="en-us">
<head>
<title>Bonzo Tests</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<link rel="stylesheet" href="../node_modules/sink-test/src/sink.css" type="text/css">
<style type="text/css">
#fixtures {
position: absolute;
top: -9999em;
width: 1000px; /*for ie<=7*/
}
#overflowed {
overflow: auto;
width: 50px;
height: 100px;
top: 10000px;
position: absolute;
}
#overflower {
height: 1000px;
width: 1000px;
}
.show-hide-css {
display: none;
}
</style>
<script src="../node_modules/sink-test/src/sink.js"></script>
<script src="../node_modules/qwery/qwery.js"></script>
<script src="../node_modules/bowser/bowser.js"></script>
<script src="../src/bonzo.js"></script>
<script type="text/javascript">
var dom = bonzo
var Q = qwery
dom.setQueryEngine(Q)
function $(s) {
return dom(Q(s))
}
dom.aug(dom, $)
</script>
<script src="ender-js.js"></script>
<script type="text/javascript">
var ender = $.noConflict()
dom.setQueryEngine = function() {}
provide('bonzo', dom)
ender._select = Q
</script>
<script src="../src/ender.js"></script>
<!-- we now have an 'ender' object to test on that has Bonzo integrated via the bridge -->
</head>
<body>
<div id="fixtures">
<div class="prepend-with-engine"></div>
<div class="prepend-with-engine"></div>
<div class="prepend-with-engine-move"></div>
<div id="class-test" class="existing-class"></div>
<div id="toggle-class" class="toggle-me"></div>
<div id="append">
<div></div>
<div></div>
</div>
<div id="prepend">
<div id="prepend-a"></div>
<div id="prepend-b"></div>
</div>
<div id="after">
<div class="after-examples"></div>
<div class="after-examples"></div>
</div>
<div id="before">
<div class="before-examples"></div>
<div class="before-examples"></div>
</div>
<div id="insert-before">
<div class="before-target"></div>
</div>
<div id="insert-after">
<div class="after-target"></div>
</div>
<div id="insert-after-last"><div class="after-last-target"></div></div>
<div id="html"></div>
<p id="html-p"></p>
<div id="html-select"></div>
<div id="html-table"></div>
<div id="text"></div>
<div id="show-hide" style="width:10px"></div>
<div id="toggle" style="width:10px"></div>
<div id="augment" style="color:orange;"></div>
<div id="empty">
<p>one</p>
<p>two</p>
<p>tre</p>
</div>
<div id="detach">
<div id="detach-a"></div>
<div id="detach-b"></div>
</div>
<div id="attrs">
<a id="twitter" href="http://twitter.com/">twitter.com</a>
<a id="hrefrel" href="/relative">relative</a>
<a id="hrefname" href="#name">name</a>
<img id="srcabs" src="http://a2.twimg.com/a/1317419607/phoenix/img/twitter_logo_right.png">
<img id="srcrel" src="/relative">
<form id="resetme">
<input type="text" value="eyo">
<input type="checkbox" checked disabled>
</form>
</div>
<div id="first-last">
<div id="first"></div>
<div id="second"></div>
<div id="last"></div>
</div>
<div id="append-to"></div>
<div id="prepend-to">
<div id="prepend-first-child"></div>
</div>
<div id="sibling-tests">
<ul>
<li>zero</li>
<li class="nextr">one</li>
<li>two</li>
<li class="nextr">three</li>
<li>four</li>
<li class="nextr">five</li>
</ul>
</div>
<div id="parent-test-wrapper">
<div id="parent-test"></div>
</div>
<div id="checkboxes-bug">
<input type="checkbox" checked="checked">
<input type="checkbox" checked="checked">
<input type="checkbox" checked="checked">
</div>
<div id="styles" style="margin-left:5px;"><div style="float: left;"></div></div>
<div id="callback-styles" data-original="15"></div>
<div id="data-test" data-foo="bar" data-hoo-haa="true" data-no-hoo-haa="false" data-int="100" data-float="111.11" data-empty="" data-whitespace=" " data-nulltastic="null"></div>
<div id="data-temp"></div>
<div id="insertiontasticSource"></div>
<div id="insertiontastic"></div>
</div>
<!-- special fixtures -->
<div id="overflowed">
<div id="overflower"></div>
</div>
<h1>Bonzo Tests</h1>
<ol id="tests"></ol>
<script src="misc-test.js"></script>
<script src="traversal-test.js"></script>
<script src="layout-test.js"></script>
<script src="dommanip-test.js"></script>
<script src="dommanip_insertions-test.js"></script>
<script src="attributes-test.js"></script>
<script src="selectorengine-test.js"></script>
<script src="emptycollection-test.js"></script>
<script src="bridge-test.js"></script>
<script>
start()
</script>
</body>
</html>
|
mit
|
bburnichon/PHPExiftool
|
lib/PHPExiftool/Driver/Tag/DICOM/SelectorSequencePointer.php
|
822
|
<?php
/*
* This file is part of the PHPExifTool package.
*
* (c) Alchemy <support@alchemy.fr>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPExiftool\Driver\Tag\DICOM;
use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;
/**
* @ExclusionPolicy("all")
*/
class SelectorSequencePointer extends AbstractTag
{
protected $Id = '0072,0052';
protected $Name = 'SelectorSequencePointer';
protected $FullName = 'DICOM::Main';
protected $GroupName = 'DICOM';
protected $g0 = 'DICOM';
protected $g1 = 'DICOM';
protected $g2 = 'Image';
protected $Type = '?';
protected $Writable = false;
protected $Description = 'Selector Sequence Pointer';
}
|
mit
|
jakobjohansson/Verbalizer
|
framework/Http/Middleware/AuthorizesRequests.php
|
304
|
<?php
namespace kiwi\Http\Middleware;
use kiwi\Http\Request;
trait AuthorizesRequests
{
/**
* Dont access without authorizing.
*
* @return void
*/
public function middleware()
{
if (!auth()->check()) {
Request::redirect('/login');
}
}
}
|
mit
|
nilportugues/php_forbidden_functions
|
src/ForbiddenFunctions/Console/Application.php
|
778
|
<?php
namespace NilPortugues\ForbiddenFunctions\Console;
use NilPortugues\ForbiddenFunctions\Command\CheckCommand;
class Application extends \Symfony\Component\Console\Application
{
/**
* Construct method
*/
public function __construct()
{
$name = <<<NAME
-------------------------------------------------
PHP Forbidden Functions Checker
-------------------------------------------------
NAME;
parent::__construct($name);
}
/**
* Initializes all the composer commands
*
* @return \Symfony\Component\Console\Command\Command[]
*/
protected function getDefaultCommands()
{
$commands = parent::getDefaultCommands();
$commands[] = new CheckCommand();
return $commands;
}
}
|
mit
|
plattformbrandenburg/ldadmin
|
src/main/java/de/piratenpartei/berlin/ldadmin/dbaccess/generated/routines/DelegationChainForClosedIssue.java
|
2840
|
/**
* This class is generated by jOOQ
*/
package de.piratenpartei.berlin.ldadmin.dbaccess.generated.routines;
/**
* This class is generated by jOOQ.
*/
@javax.annotation.Generated(value = { "http://www.jooq.org", "3.4.4" },
comments = "This class is generated by jOOQ")
@java.lang.SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class DelegationChainForClosedIssue extends org.jooq.impl.AbstractRoutine<de.piratenpartei.berlin.ldadmin.dbaccess.generated.udt.records.DelegationChainRowRecord> {
private static final long serialVersionUID = -1265014680;
/**
* The parameter <code>delegation_chain_for_closed_issue.RETURN_VALUE</code>.
*/
public static final org.jooq.Parameter<de.piratenpartei.berlin.ldadmin.dbaccess.generated.udt.records.DelegationChainRowRecord> RETURN_VALUE = createParameter("RETURN_VALUE", de.piratenpartei.berlin.ldadmin.dbaccess.generated.udt.DelegationChainRow.DELEGATION_CHAIN_ROW.getDataType());
/**
* The parameter <code>delegation_chain_for_closed_issue.member_id_p</code>.
*/
public static final org.jooq.Parameter<java.lang.Integer> MEMBER_ID_P = createParameter("member_id_p", org.jooq.impl.SQLDataType.INTEGER);
/**
* The parameter <code>delegation_chain_for_closed_issue.issue_id_p</code>.
*/
public static final org.jooq.Parameter<java.lang.Integer> ISSUE_ID_P = createParameter("issue_id_p", org.jooq.impl.SQLDataType.INTEGER);
/**
* Create a new routine call instance
*/
public DelegationChainForClosedIssue() {
super("delegation_chain_for_closed_issue", de.piratenpartei.berlin.ldadmin.dbaccess.generated.DefaultSchema.DEFAULT_SCHEMA, de.piratenpartei.berlin.ldadmin.dbaccess.generated.udt.DelegationChainRow.DELEGATION_CHAIN_ROW.getDataType());
setReturnParameter(RETURN_VALUE);
addInParameter(MEMBER_ID_P);
addInParameter(ISSUE_ID_P);
}
/**
* Set the <code>member_id_p</code> parameter IN value to the routine
*/
public void setMemberIdP(java.lang.Integer value) {
setValue(de.piratenpartei.berlin.ldadmin.dbaccess.generated.routines.DelegationChainForClosedIssue.MEMBER_ID_P, value);
}
/**
* Set the <code>member_id_p</code> parameter to the function to be used with a {@link org.jooq.Select} statement
*/
public void setMemberIdP(org.jooq.Field<java.lang.Integer> field) {
setField(MEMBER_ID_P, field);
}
/**
* Set the <code>issue_id_p</code> parameter IN value to the routine
*/
public void setIssueIdP(java.lang.Integer value) {
setValue(de.piratenpartei.berlin.ldadmin.dbaccess.generated.routines.DelegationChainForClosedIssue.ISSUE_ID_P, value);
}
/**
* Set the <code>issue_id_p</code> parameter to the function to be used with a {@link org.jooq.Select} statement
*/
public void setIssueIdP(org.jooq.Field<java.lang.Integer> field) {
setField(ISSUE_ID_P, field);
}
}
|
mit
|
moyunmo/CMTabbarView
|
Example/Pods/Target Support Files/Pods-StoryboardDemo/Pods-StoryboardDemo-acknowledgements.markdown
|
1241
|
# Acknowledgements
This application makes use of the following third party libraries:
## CMTabbarView
Copyright (c) 2017 momo605654602@gmail.com <moyunmo@hotmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
Generated by CocoaPods - https://cocoapods.org
|
mit
|
TypeW/eShopOnContainers
|
src/BuildingBlocks/EventBus/EventBusServiceBus/DefaultServiceBusPersisterConnection.cs
|
1621
|
using Microsoft.Azure.ServiceBus;
using Microsoft.Extensions.Logging;
using System;
using System.IO;
namespace Microsoft.eShopOnContainers.BuildingBlocks.EventBusServiceBus
{
public class DefaultServiceBusPersisterConnection :IServiceBusPersisterConnection
{
private readonly ILogger<DefaultServiceBusPersisterConnection> _logger;
private readonly ServiceBusConnectionStringBuilder _serviceBusConnectionStringBuilder;
private ITopicClient _topicClient;
bool _disposed;
public DefaultServiceBusPersisterConnection(ServiceBusConnectionStringBuilder serviceBusConnectionStringBuilder,
ILogger<DefaultServiceBusPersisterConnection> logger)
{
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_serviceBusConnectionStringBuilder = serviceBusConnectionStringBuilder ??
throw new ArgumentNullException(nameof(serviceBusConnectionStringBuilder));
_topicClient = new TopicClient(_serviceBusConnectionStringBuilder, RetryPolicy.Default);
}
public ServiceBusConnectionStringBuilder ServiceBusConnectionStringBuilder => _serviceBusConnectionStringBuilder;
public ITopicClient CreateModel()
{
if(_topicClient.IsClosedOrClosing)
{
_topicClient = new TopicClient(_serviceBusConnectionStringBuilder, RetryPolicy.Default);
}
return _topicClient;
}
public void Dispose()
{
if (_disposed) return;
_disposed = true;
}
}
}
|
mit
|
jumpinjackie/mapguide-ajax-viewer
|
shared/src/fusion/widget.ts
|
448
|
/// <reference path="./event.ts" />
module Fusion {
/**
* Represents a component of discrete functionality in a Fusion application
*/
export interface Widget extends EventEmittable {
}
/**
* Represents a component of discrete functionality in a Fusion application
*/
export class WidgetBase extends EventEmitter implements Widget {
constructor() {
super();
}
}
}
|
mit
|
dgreenway/til
|
git/ignore-files-specific-to-your-workflow.md
|
1193
|
# Ignore Files Specific To Your Workflow
_If you want to watch instead of read, I explore this in [Four Ways to Ignore
Files with Git](https://www.youtube.com/watch?v=ip06v7Wnfz0)._
The most common way to tell git to ignore files is to add them to a project's
`.gitignore` file. This file is kept under version control, so it is shared
with anyone who clones the project.
What about ignoring files that shouldn't necessarily be recorded in the
project's `.gitignore`?
For instance, let's say I create a `notes.md` file to write some project notes
to myself or keep track of a few todo items. This file is just for me. I don't
want it committed. Because this `notes.md` is an idiosyncrasy of my workflow, I
don't want to exclude it in the tracked `.gitignore` file.
Instead, this file is a perfect candidate for the git repository's
`.git/info/exclude` file. Git treats entries in this file the same as it does
the `.gitignore` file. This file only exists on my machine and is not under
version control.
```
# .git/info/exclude
notes.md
```
Once I've added that line, `notes.md` will no longer show up as an untracked
file when I run `git status`.
See `man gitignore` for more details.
|
mit
|
h0m3/python-mprint
|
README.md
|
959
|
# mprint

mprint stands for **M**arkup **Print**, is an easy way to use Markup Tags to format your text,
you can set colors, bold, italic. All with simple markup tags.
- Simple to use, you can just use markup tags and format your text.
- Uses ANSI Escape Sentences, its compatible with almost everything, including windows.
- Lightweight, uses less processing than alternatives like curses
- Support common formatting like italic, bold, underscore
- Support colors and bold colors
- Easy to understand documentation trought [wiki] (https://github.com/h0m3/python-mprint/wiki).
- Can nest tags, you can mix formatting and colors
- Use own Markup Engine, lighter and no additional dependencies for processing markup.
- Easy to personalize, you can easly add new color or create your own tags.
# Try it now
Go right ahead, visit our [wiki] (https://github.com/h0m3/python-mprint/wiki), clone our project and get started.
|
mit
|
delainewendling/NP_trip_planner
|
deploy/app/controllers/DeleteTripModalCtrl.js
|
1660
|
'use strict';
app.controller('DeleteTripModalCtrl', function($scope, $uibModalInstance, TripFactory, $routeParams, $window, ActivityFactory, MemberFactory){
let tripId = $routeParams.tripId;
$scope.close = () => {
$uibModalInstance.close();
};
//Not only do we want to delete the trip object connected to that user from Firebase but we also want to delete anything associated with the trip - notes, packing list, and trails that have been added.
$scope.deleteTrip = ()=>{
TripFactory.deleteTrip(tripId)
.then(()=>{
console.log("trip was deleted");
$scope.close();
$window.location.href='#/parks/explore';
return ActivityFactory.getActivities(tripId)
})
.then((activityData)=>{
console.log("activities in trip", activityData);
Object.keys(activityData).forEach((activityId)=>{
ActivityFactory.deleteActivityFromTrip(activityId);
});
return TripFactory.getUserPackingList(tripId)
})
.then((packingData)=>{
console.log("user packing list", packingData);
Object.keys(packingData).forEach((listId)=>{
TripFactory.deleteItemFromList(listId);
});
return MemberFactory.getMembersOfTrip(tripId)
})
.then((members)=>{
console.log("members", members);
Object.keys(members).forEach((memberId)=>{
MemberFactory.deleteMember(memberId);
});
return TripFactory.getInvitationsInTrip(tripId)
})
.then((invitations)=>{
console.log("invitations", invitations);
Object.keys(invitations).forEach((invitationId)=>{
TripFactory.deleteInvitation(invitationId);
});
})
};
});
|
mit
|
windracer/xmlguy
|
src/XmlElement.cs
|
1589
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace XmlGuy
{
public class XmlElement : AbstractXmlElement
{
public XmlElement(XmlElement parent = null) : base(parent)
{
Children = new List<IXmlElement>();
Attributes = new Dictionary<string, string>();
}
public IList<IXmlElement> Children { get; set; }
public IDictionary<string, string> Attributes { get; set; }
public XmlElement Up()
{
return Parent;
}
public XmlElement Add(string name, params object[] args)
{
string value = null;
Dictionary<string, string> attributes = new Dictionary<string, string>();
if (args != null)
{
foreach (var arg in args)
{
if (arg is string)
value = arg as string;
else
foreach (var prop in arg.GetType().GetProperties())
attributes.Add(prop.Name, prop.GetValue(arg, null) as string);
}
}
return Add(name, value, attributes);
}
private XmlElement Add(string name, string value, IDictionary<string, string> attributes)
{
if (Value != null)
throw new InvalidOperationException("XML Element " + Name + " has a text value: it cannot contain child elements");
var child = new XmlElement(this) { Name = name, Value = value, Attributes = attributes };
Children.Add(child);
return child;
}
public XmlElement CData(string data)
{
Children.Add(new CDataElement(this) { Value = data });
return this;
}
}
public class CDataElement : AbstractXmlElement
{
public CDataElement(XmlElement parent = null) : base(parent)
{
}
}
}
|
mit
|
andene/substance
|
model/data/PropertyIndex.js
|
2682
|
import isArray from '../../util/isArray'
import forEach from '../../util/forEach'
import TreeIndex from '../../util/TreeIndex'
import NodeIndex from './NodeIndex'
class PropertyIndex extends NodeIndex {
constructor(property) {
super()
this._property = property || 'id'
this.index = new TreeIndex()
}
/**
Get all indexed nodes for a given path.
@param {Array<String>} path
@returns A node or an object with ids and nodes as values.
*/
get(path) {
return this.index.get(path) || {}
}
/**
Collects nodes recursively.
@returns An object with ids as keys and nodes as values.
*/
getAll(path) {
return this.index.getAll(path)
}
/**
Check if a node should be indexed.
Used internally only. Override this in subclasses to achieve a custom behavior.
@private
@param {Node}
@returns {Boolean} true if the given node should be added to the index.
*/
select(node) { // eslint-disable-line
return true
}
/**
Called when a node has been created.
Override this in subclasses for customization.
@private
@param {Node} node
*/
create(node) {
var values = node[this._property]
if (!isArray(values)) {
values = [values]
}
forEach(values, function(value) {
this.index.set([value, node.id], node)
}.bind(this))
}
/**
* Called when a node has been deleted.
*
* Override this in subclasses for customization.
*
* @private
* @param {model/data/Node} node
*/
delete(node) {
var values = node[this._property]
if (!isArray(values)) {
values = [values]
}
forEach(values, function(value) {
this.index.delete([value, node.id])
}.bind(this))
}
/**
Called when a property has been updated.
Override this in subclasses for customization.
@private
@param {Node} node
*/
update(node, path, newValue, oldValue) {
if (!this.select(node) || path[1] !== this._property) return
var values = oldValue
if (!isArray(values)) {
values = [values]
}
forEach(values, function(value) {
this.index.delete([value, node.id])
}.bind(this))
values = newValue
if (!isArray(values)) {
values = [values]
}
forEach(values, function(value) {
this.index.set([value, node.id], node)
}.bind(this))
}
set(node, path, newValue, oldValue) {
this.update(node, path, newValue, oldValue)
}
_clear() {
this.index.clear()
}
_initialize(data) {
forEach(data.getNodes(), function(node) {
if (this.select(node)) {
this.create(node)
}
}.bind(this))
}
}
export default PropertyIndex
|
mit
|
rails/jquery-ujs
|
test/public/test/call-remote.js
|
6202
|
(function(){
function buildForm(attrs) {
attrs = $.extend({ action: '/echo', 'data-remote': 'true' }, attrs);
$('#qunit-fixture').append($('<form />', attrs))
.find('form').append($('<input type="text" name="user_name" value="john">'));
};
module('call-remote');
function submit(fn) {
$('form')
.on('ajax:success', fn)
.on('ajax:complete', function() { start() })
.trigger('submit');
}
asyncTest('form method is read from "method" and not from "data-method"', 1, function() {
buildForm({ method: 'post', 'data-method': 'get' });
submit(function(e, data, status, xhr) {
App.assertPostRequest(data);
});
});
asyncTest('form method is not read from "data-method" attribute in case of missing "method"', 1, function() {
buildForm({ 'data-method': 'put' });
submit(function(e, data, status, xhr) {
App.assertGetRequest(data);
});
});
asyncTest('form method is read from submit button "formmethod" if submit is triggered by that button', 1, function() {
var submitButton = $('<input type="submit" formmethod="get">')
buildForm({ method: 'post' });
$('#qunit-fixture').find('form').append(submitButton)
.on('ajax:success', function(e, data, status, xhr) {
App.assertGetRequest(data);
})
.on('ajax:complete', function() { start() });
submitButton.trigger('click');
});
asyncTest('form default method is GET', 1, function() {
buildForm();
submit(function(e, data, status, xhr) {
App.assertGetRequest(data);
});
});
asyncTest('form url is picked up from "action"', 1, function() {
buildForm({ method: 'post' });
submit(function(e, data, status, xhr) {
App.assertRequestPath(data, '/echo');
});
});
asyncTest('form url is read from "action" not "href"', 1, function() {
buildForm({ method: 'post', href: '/echo2' });
submit(function(e, data, status, xhr) {
App.assertRequestPath(data, '/echo');
});
});
asyncTest('form url is read from submit button "formaction" if submit is triggered by that button', 1, function() {
var submitButton = $('<input type="submit" formaction="/echo">')
buildForm({ method: 'post', href: '/echo2' });
$('#qunit-fixture').find('form').append(submitButton)
.on('ajax:success', function(e, data, status, xhr) {
App.assertRequestPath(data, '/echo');
})
.on('ajax:complete', function() { start() });
submitButton.trigger('click');
});
asyncTest('prefer JS, but accept any format', 1, function() {
buildForm({ method: 'post' });
submit(function(e, data, status, xhr) {
var accept = data.HTTP_ACCEPT;
ok(accept.indexOf('*/*;q=0.5, text/javascript, application/javascript') === 0, 'Accept: ' + accept);
});
});
asyncTest('accept application/json if "data-type" is json', 1, function() {
buildForm({ method: 'post', 'data-type': 'json' });
submit(function(e, data, status, xhr) {
equal(data.HTTP_ACCEPT, 'application/json, text/javascript, */*; q=0.01');
});
});
asyncTest('allow empty "data-remote" attribute', 1, function() {
var form = $('#qunit-fixture').append($('<form action="/echo" data-remote />')).find('form');
submit(function() {
ok(true, 'form with empty "data-remote" attribute is also allowed');
});
});
asyncTest('allow empty form "action"', 1, function() {
var currentLocation, ajaxLocation;
buildForm({ action: '' });
$('#qunit-fixture').find('form')
.on('ajax:beforeSend', function(e, xhr, settings) {
// Get current location (the same way jQuery does)
try {
currentLocation = location.href;
} catch(e) {
currentLocation = document.createElement( "a" );
currentLocation.href = "";
currentLocation = currentLocation.href;
}
currentLocation = currentLocation.replace(/\?$/, '');
// Actual location (strip out settings.data that jQuery serializes and appends)
// HACK: can no longer use settings.data below to see what was appended to URL, as of
// jQuery 1.6.3 (see http://bugs.jquery.com/ticket/10202 and https://github.com/jquery/jquery/pull/544)
ajaxLocation = settings.url.replace("user_name=john","").replace(/&$/, "").replace(/\?$/, "");
equal(ajaxLocation.match(/^(.*)/)[1], currentLocation, 'URL should be current page by default');
// Prevent the request from actually getting sent to the current page and
// causing an error.
return false;
})
.trigger('submit');
setTimeout(function() { start(); }, 13);
});
asyncTest('sends CSRF token in custom header', 1, function() {
buildForm({ method: 'post' });
$('#qunit-fixture').append('<meta name="csrf-token" content="cf50faa3fe97702ca1ae" />');
submit(function(e, data, status, xhr) {
equal(data.HTTP_X_CSRF_TOKEN, 'cf50faa3fe97702ca1ae', 'X-CSRF-Token header should be sent');
});
});
asyncTest('intelligently guesses crossDomain behavior when target URL has a different protocol and/or hostname', 1, function(e, xhr) {
// Don't set data-cross-domain here, just set action to be a different domain than localhost
buildForm({ action: 'http://www.alfajango.com' });
$('#qunit-fixture').append('<meta name="csrf-token" content="cf50faa3fe97702ca1ae" />');
$('#qunit-fixture').find('form')
.on('ajax:beforeSend', function(e, xhr, settings) {
equal(settings.crossDomain, true, 'crossDomain should be set to true');
// prevent request from actually getting sent off-domain
return false;
})
.trigger('submit');
setTimeout(function() { start(); }, 13);
});
asyncTest('intelligently guesses crossDomain behavior when target URL consists of only a path', 1, function(e, xhr) {
// Don't set data-cross-domain here, just set action to be a different domain than localhost
buildForm({ action: '/just/a/path' });
$('#qunit-fixture').append('<meta name="csrf-token" content="cf50faa3fe97702ca1ae" />');
$('#qunit-fixture').find('form')
.on('ajax:beforeSend', function(e, xhr, settings) {
equal(settings.crossDomain, false, 'crossDomain should be set to false');
// prevent request from actually getting sent off-domain
return false;
})
.trigger('submit');
setTimeout(function() { start(); }, 13);
});
})();
|
mit
|
shanejdonnelly/smush-in
|
smushIn.js
|
3613
|
/*
* Smush In - jQuery plugin
*
* Copyright (c) 2013 Shane Donnelly
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/mit-license.php
*
* Project home:
* http://shanejdonnelly.github.io/smush-in
* Version: 1.0
*
*/
;(function ($) {
"use strict";
/* CLASS DEFINITION
* ====================== */
var SmushIn = function ($element, options) {
this.settings = options;
this.$el = $element;
this.setup();
}
SmushIn.prototype = {
constructor: SmushIn,
setup: function(){
this.height = this.$el.height();
this.width = this.$el.width();
this.left = parseInt(this.$el.css('left'));
this.top = parseInt(this.$el.css('top'));
this.font_size = parseInt(this.$el.css('font-size'));
this.window_width = $(window).width();
this.window_height = $(window).height();
this.max_anim_speed = (this.settings.speed === 'slow') ? 130 : 75;
if(this.settings.overshot === 0){ this.settings.overshot = this.rand(10,70) }
//decide direction
if(this.settings.from_direction === 'random') {
var random_direction = (this.rand(0,20) < 10) ? 'left' : 'right';
this.horzAnim(random_direction);
}
else{
this.horzAnim(this.settings.from_direction);
}
},
horzAnim: function(from_direction){
var
base = this,
start_position = (from_direction === 'right') ? ( base.rand((base.window_width * 1.1), (base.window_width * 2)) ) : ( start_position = -1 * base.rand((base.window_width * 1.1), (base.window_width * 2)) ),
fly_to = (from_direction === 'right') ? (base.left - base.settings.overshot) : (base.left + base.settings.overshot);
//set start position
base.$el.css('left', start_position );
setTimeout(function(){
//fly in
base.$el.show().animate({'left': fly_to}, base.rand(200,500 ), function(){
//hit the 'wall'
base.$el.animate(
{
'height': (base.height * base.rand(1,2)),
'width': base.width * base.rand(.3, .7),
'margin-top': -(base.height * base.rand(.2,.4))
}, base.max_anim_speed, function(){
//bounce back
base.$el.animate(
{
'height': base.height,
'width': base.width,
'margin-top':0,
'left':base.left
}, ( base.max_anim_speed * 1.75));
});
});
}, base.rand(500,1500));
},
//returns float
rand: function(min, max){
return Math.random() * (max - min) + min;
}
}
/* PLUGIN DEFINITION
* ======================= */
$.fn.smushIn = function (custom_options) {
return this.each(function () {
var
$el = $(this),
options = $.extend({}, $.fn.smushIn.defaults, custom_options);
new SmushIn($el, options)
})
}
$.fn.smushIn.defaults = {
'overshot' : 0,
'speed' : 'slow',
'from_direction' : 'left'
}
$.fn.smushIn.Constructor = SmushIn
})(window.jQuery);
|
mit
|
DevKhater/YallaWebSite
|
app/cache/prod/assetic/config/4/423e5d4324992a3bd20ae71d066b011d.php
|
75
|
<?php
// SonataMediaBundle:Form:media_widgets.html.twig
return array (
);
|
mit
|
leekelleher/Umbraco-CMS
|
src/Umbraco.Web.UI.Client/src/views/components/media/umb-media-node-info.html
|
9872
|
<div class="umb-package-details">
<umb-load-indicator ng-if="loading === true"></umb-load-indicator>
<!-- Main Column -->
<div class="umb-package-details__main-content" ng-if="loading === false">
<!-- Links -->
<umb-box data-element="node-info-urls" class="mb4">
<umb-box-header title-key="general_links"></umb-box-header>
<umb-box-content class="block-form">
<umb-empty-state ng-if="!nodeUrl"
size="small">
<localize key="content_noMediaLink"></localize>
</umb-empty-state>
<ul ng-if="nodeUrl" class="nav nav-stacked mb0">
<li>
<a href="" ng-attr-href="{{node.extension !== 'svg' ? nodeUrl : undefined}}" ng-click="node.extension === 'svg' && openSVG()" target="_blank" rel="noopener" class="umb-outline">
<i class="icon icon-out" aria-hidden="true"></i>
<span>{{nodeFileName}}</span>
</a>
</li>
</ul>
</umb-box-content>
</umb-box>
<!-- Media Tracking (NO Items) -->
<umb-box ng-if="(hasContentReferences === false) && (hasMediaReferences === false) && (hasMemberReferences === false) && loading === false">
<umb-box-header title-key="references_tabName"></umb-box-header>
<umb-box-content>
<umb-empty-state size="small">
This Media item has no references.
</umb-empty-state>
</umb-box-content>
</umb-box>
<!-- Media Tracking (With Items) -->
<div ng-if="loading === false">
<!-- Content -->
<div ng-if="contentReferences.items.length > 0">
<h5 class="mt0" style="margin-bottom: 20px;">
<localize key="references_labelUsedByDocuments">Used in Documents</localize>
</h5>
<div class="umb-table">
<div class="umb-table-head">
<div class="umb-table-row">
<div class="umb-table-cell"></div>
<div class="umb-table-cell umb-table__name not-fixed"><localize key="general_name">Name</localize></div>
<div class="umb-table-cell"><localize key="content_alias">Alias</localize></div>
<div class="umb-table-cell umb-table-cell--nano"><localize key="general_open" style="visibility:hidden;">Open</localize></div>
</div>
</div>
<div class="umb-table-body">
<div class="umb-table-row" ng-repeat="reference in contentReferences.items">
<div class="umb-table-cell"><i class="umb-table-body__icon {{reference.icon}}"></i></div>
<div class="umb-table-cell umb-table__name"><span>{{::reference.name}}</span></div>
<div class="umb-table-cell"><span title="{{::reference.alias}}">{{::reference.alias}}</span></div>
<div class="umb-table-cell umb-table-cell--nano"><a ng-href="#/content/content/edit/{{::reference.id}}"><localize key="general_open">Open</localize></a></div>
</div>
</div>
</div>
<!-- Pagination -->
<div class="flex justify-center">
<umb-pagination ng-if="contentReferences.totalPages"
page-number="contentReferences.pageNumber"
total-pages="contentReferences.totalPages"
on-change="changeContentPageNumber(pageNumber)">
</umb-pagination>
</div>
</div>
<!-- Members -->
<div ng-if="memberReferences.items.length > 0">
<h5 class="mt0" style="margin-bottom: 20px;">
<localize key="references_labelUsedByMembers">Used in Members</localize>
</h5>
<div class="umb-table">
<div class="umb-table-head">
<div class="umb-table-row">
<div class="umb-table-cell"></div>
<div class="umb-table-cell umb-table__name not-fixed"><localize key="general_name">Name</localize></div>
<div class="umb-table-cell"><localize key="content_alias">Alias</localize></div>
<div class="umb-table-cell umb-table-cell--nano"><localize key="general_open" style="visibility:hidden;">Open</localize></div>
</div>
</div>
<div class="umb-table-body">
<div class="umb-table-row" ng-repeat="reference in memberReferences.items">
<div class="umb-table-cell"><i class="umb-table-body__icon {{reference.icon}}"></i></div>
<div class="umb-table-cell umb-table__name"><span>{{::reference.name}}</span></div>
<div class="umb-table-cell"><span title="{{::reference.alias}}">{{::reference.alias}}</span></div>
<div class="umb-table-cell umb-table-cell--nano"><a href="#/member/member/edit/{{::reference.key}}"><localize key="general_open">Open</localize></a></div>
</div>
</div>
</div>
<!-- Pagination -->
<div class="flex justify-center">
<umb-pagination ng-if="memberReferences.totalPages"
page-number="memberReferences.pageNumber"
total-pages="memberReferences.totalPages"
on-change="changeMemberPageNumber(pageNumber)">
</umb-pagination>
</div>
</div>
<!-- Media -->
<div ng-if="mediaReferences.items.length > 0">
<h5 class="mt0" style="margin-bottom: 20px;">
<localize key="references_labelUsedByMedia">Used in Media</localize>
</h5>
<div class="umb-table">
<div class="umb-table-head">
<div class="umb-table-row">
<div class="umb-table-cell"></div>
<div class="umb-table-cell umb-table__name not-fixed"><localize key="general_name">Name</localize></div>
<div class="umb-table-cell"><localize key="content_alias">Alias</localize></div>
<div class="umb-table-cell umb-table-cell--nano"><localize key="general_open" style="visibility:hidden;">Open</localize></div>
</div>
</div>
<div class="umb-table-body">
<div class="umb-table-row" ng-repeat="reference in mediaReferences.items">
<div class="umb-table-cell"><i class="umb-table-body__icon {{reference.icon}}"></i></div>
<div class="umb-table-cell umb-table__name"><span>{{::reference.name}}</span></div>
<div class="umb-table-cell"><span title="{{::reference.alias}}">{{::reference.alias}}</span></div>
<div class="umb-table-cell umb-table-cell--nano"><a href="#/media/media/edit/{{::reference.id}}"><localize key="general_open">Open</localize></a></div>
</div>
</div>
</div>
<!-- Pagination -->
<div class="flex justify-center">
<umb-pagination ng-if="mediaReferences.totalPages"
page-number="mediaReferences.pageNumber"
total-pages="mediaReferences.totalPages"
on-change="changeMediaPageNumber(pageNumber)">
</umb-pagination>
</div>
</div>
</div>
</div>
<!-- Sidebar -->
<div class="umb-package-details__sidebar" ng-if="loading === false">
<!-- General Info -->
<umb-box data-element="node-info-general">
<umb-box-header title-key="general_general"></umb-box-header>
<umb-box-content class="block-form">
<umb-control-group ng-if="node.id !== 0" data-element="node-info-create-date" label="@content_createDate">
{{node.createDateFormatted}} by {{ node.owner.name }}
</umb-control-group>
<umb-control-group ng-if="node.id !== 0" data-element="node-info-update-date" label="@content_updateDate">
{{node.updateDateFormatted}}
</umb-control-group>
<umb-control-group data-element="node-info-media-type" label="@content_mediatype">
<umb-node-preview style="max-width: 100%; margin-bottom: 0px;"
icon="node.icon"
name="node.contentTypeName"
allow-open="allowChangeMediaType"
on-open="openMediaType(mediaType)">
</umb-node-preview>
</umb-control-group>
<umb-control-group ng-if="node.id !== 0" data-element="node-info-id" label="Id">
<div>{{ node.id }}</div>
<small>{{ node.key }}</small>
</umb-control-group>
</umb-box-content>
</umb-box>
</div>
</div>
|
mit
|
yaelduckwen/lo_imaginario
|
web2/plugins/vmpayment/mercadopago/mercadopago/tmpl/mercadopago_checkout_standard.php
|
491
|
<?php
defined('_JEXEC') or die('Restricted access');
/**
* Mercado Pago plugin
*
* @author Developers Mercado Pago <modulos@mercadopago.com>
* @version 2.0.5
* @package VirtueMart
* @subpackage payment
* @link https://www.mercadopago.com
* @copyright Copyright © 2016 MercadoPago.com
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
*/
?>
<br/>
<img src="<?php echo MercadoPagoHelper::getBanner($viewData['site_id']);?>" id="mercadopago-banner-basic">
|
mit
|
g0v/laweasyread-data
|
rawdata/lawstat/version2/01468/0146894011100.html
|
6825
|
<html>
<META HTTP-EQUIV=Content-Type Content="text/html; charset=big5">
<!-- Mirrored from lis.ly.gov.tw/lghtml/lawstat/version2/01468/0146894011100.htm by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 24 Mar 2013 09:11:06 GMT -->
<head><title>ªk½s¸¹:01468 ª©¥»:094011100</title>
<link rel="stylesheet" type="text/css" href="../../version.css" >
</HEAD>
<body><left>
<table><tr><td><FONT COLOR=blue SIZE=5>¥þ¥Á°ê¨¾±Ð¨|ªk(01468)</font>
<table><tr><td> </td><td>
<table><tr><td> </td><td>
<table><tr><td> </td>
<tr><td align=left valign=top>
<a href=0146894011100.html target=law01468><nobr><font size=2>¤¤µØ¥Á°ê 94 ¦~ 1 ¤ë 11 ¤é</font></nobr></a>
</td>
<td valign=top><font size=2>¨î©w15±ø</font></td>
<tr><td align=left valign=top><nobr><font size=2>¤¤µØ¥Á°ê 94 ¦~ 2 ¤ë 2 ¤é¤½¥¬</font></nobr></td>
</table></table></table></table>
<p><table><tr><td><font color=blue size=4>¥Á°ê94¦~1¤ë11¤é</font></td>
<td><a href=http://lis.ly.gov.tw/lghtml/lawstat/reason2/0146894011100.htm target=reason><font size=2>¥ßªk²z¥Ñ</font></a></td>
<td><a href=http://lis.ly.gov.tw/lgcgi/lglawproc?0146894011100 target=proc><font size=2>¥ßªk¬ö¿ý</font></a></td>
</table>
<table><tr><td> </td><td><font color=8000ff>²Ä¤@±ø</font>
<font size=2>(¥ßªk¥Øªº)</font>
<table><tr><td> </td>
<td>
¡@¡@¬°±À°Ê¥þ¥Á°ê¨¾±Ð¨|¡A¥H¼W¶i¥þ¥Á¤§°ê¨¾ª¾ÃѤΥþ¥Á¨¾½Ã°ê®a·NÃÑ¡A°·¥þ°ê¨¾µo®i¡A½T«O°ê®a¦w¥þ¡A¯S¨î©w¥»ªk¡C<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td><font color=8000ff>²Ä¤G±ø</font>
<font size=2>(¥DºÞ¾÷Ãö)</font>
<table><tr><td> </td>
<td>
¡@¡@¥»ªk©ÒºÙ¥DºÞ¾÷Ãö¡G¦b¤¤¥¡¬°°ê¨¾³¡¡F¦bª½ÁÒ¥«¬°ª½ÁÒ¥«¬F©²¡F¦b¿¤¡]¥«¡^¬°¿¤¡]¥«¡^¬F©²¡C<br>
¡@¡@¥»ªk©Ò©w¨Æ¶µ¡A¯A¤Î¦U¥Øªº¨Æ·~¥DºÞ¾÷Ãö¾´xªÌ¡A¥Ñ¦U¥Øªº¨Æ·~¥DºÞ¾÷Ãö¿ì²z¡C<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td><font color=8000ff>²Ä¤T±ø</font>
<font size=2>(¤¤¥¡¥DºÞ¾÷Ãö¤§Â¾´x)</font>
<table><tr><td> </td>
<td>
¡@¡@¤U¦C¨Æ¶µ¡A¥Ñ¤¤¥¡¥DºÞ¾÷Ãö´x²z¡G<br>
¡@¡@¤@¡B¥þ¥Á°ê¨¾±Ð¨|ªk³W¡B¬Fµ¦¤§¬ãq¨Æ¶µ¡C<br>
¡@¡@¤G¡B¥þ¥Á°ê¨¾±Ð¨|¤§¬ã¨s¡Bµo®i¨Æ¶µ¡C<br>
¡@¡@¤T¡B¥þ¥Á°ê¨¾±Ð¨|¤u§@¤§µ¦¹º¤Î¦Ò®Ö¨Æ¶µ¡C<br>
¡@¡@¥|¡B¥þ¥Á°ê¨¾±Ð¨|¤u§@¤§¼ú§U¤ÎµûŲ¨Æ¶µ¡C<br>
¡@¡@¤¡B¥þ¥Á°ê¨¾±Ð¨|¤Hû°ö°V¤Î¦b¾°V½m¨Æ¶µ¡C<br>
¡@¡@¤»¡B¥þ°ê©Ê¥þ¥Á°ê¨¾±Ð¨|¤§«Å¾É¡B±À®i¨Æ¶µ¡C<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td><font color=8000ff>²Ä¥|±ø</font>
<font size=2>(¦a¤è¥DºÞ¾÷Ãö¤§Â¾´x)</font>
<table><tr><td> </td>
<td>
¡@¡@ª½ÁÒ¥«¡B¿¤¡]¥«¡^¥DºÞ¾÷Ãö´x²zÁҰϤU¦C¨Æ¶µ¡G<br>
¡@¡@¤@¡B¥þ¥Á°ê¨¾±Ð¨|¤u§@¤§µ¦¹º¡B¿ì²z¤Î·þ¾É¨Æ¶µ¡C<br>
¡@¡@¤G¡B©ÒÄݾǮաB¾÷Ãö¡]ºc¡^µ¥¿ì²z¥þ¥Á°ê¨¾±Ð¨|¤u§@¤§¼ú§U¤ÎµûŲ¨Æ¶µ¡C<br>
¡@¡@¤T¡B©ÒÄÝ¥þ¥Á°ê¨¾±Ð¨|¤Hû¤§¦b¾°V½m¨Æ¶µ¡C<br>
¡@¡@¥|¡B¥þ¥Á°ê¨¾±Ð¨|¤§«Å¾É¡B±À®i¨Æ¶µ¡C<br>
¡@¡@¤¡B¨ä¥L¥þ¥Á°ê¨¾±Ð¨|¦³Ãö¨Æ¶µ¡C<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td><font color=8000ff>²Ä¤±ø</font>
<font size=2>(¥þ¥Á°ê¨¾±Ð¨|¤§½d³ò)</font>
<table><tr><td> </td>
<td>
¡@¡@¥»ªk©ÒºÙ¥þ¥Á°ê¨¾±Ð¨|¡A¥H¸g±`¤è¦¡¹ê¬I¬°ì«h¡A¨ä½d³ò¥]¬A¡G<br>
¡@¡@¤@¡B¾Ç®Õ±Ð¨|¡C<br>
¡@¡@¤G¡B¬F©²¾÷Ãö¡]ºc¡^¦b¾±Ð¨|¡C<br>
¡@¡@¤T¡BªÀ·|±Ð¨|¡C<br>
¡@¡@¥|¡B°ê¨¾¤åª««OÅ@¡B«Å¾É¤Î±Ð¨|¡C<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td><font color=8000ff>²Ä¤»±ø</font>
<font size=2>(³]¸m¥þ¥Á°ê¨¾±Ð¨|¤é)</font>
<table><tr><td> </td>
<td>
¡@¡@¦æ¬F°|À³q©w¥þ¥Á°ê¨¾±Ð¨|¤é¡A¨ÃÁ|¿ì¦UºØ¬ÛÃö¬¡°Ê¡A¥H±j¤Æ¥þ¥Á°ê¨¾±Ð¨|¡C<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td><font color=8000ff>²Ä¤C±ø</font>
<font size=2>(¦U¯Å¾Ç®Õ¹ê¬Iì«h)</font>
<table><tr><td> </td>
<td>
¡@¡@¦U¯Å¾Ç®ÕÀ³±À°Ê¥þ¥Á°ê¨¾±Ð¨|¡A¨Ãµø¹ê»Ú»Ýn¡A¯Ç¤J±Ð¾Ç½Òµ{¡A¹ê¬I¦h¤¸±Ð¾Ç¬¡°Ê¡C<br>
¡@¡@«e¶µ½Òµ{¤º®e¤Î¹ê¬I¿ìªk¡A¥Ñ±Ð¨|³¡·|¦P¤¤¥¡¥DºÞ¾÷Ãö©w¤§¡C<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td><font color=8000ff>²Ä¤K±ø</font>
<font size=2>(¬F©²¾÷Ãö©ÒÄݤHû¹ê¬Iì«h)</font>
<table><tr><td> </td>
<td>
¡@¡@¬F©²¦U¾÷Ãö¡]ºc¡^À³¨Ì¾Ú¨ä¤u§@©Ê½è¡A¹ï©ÒÄݤHû©w´Á¹ê¬I¥þ¥Á°ê¨¾±Ð¨|¡C<br>
¡@¡@«e¶µ±Ð¨|¤º®e¤Î¹ê¬I¿ìªk¡A¥Ñ¦æ¬F°|¤H¨Æ¦æ¬F§½·|¦P¤½°È¤Hû«O»Ùº[°ö°V©eû·|¡B¤¤¥¡¥DºÞ¾÷Ãö©w¤§¡C<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td><font color=8000ff>²Ä¤E±ø</font>
<font size=2>(¤@¯ëªÀ·|¤j²³¹ê¬Iì«h)</font>
<table><tr><td> </td>
<td>
¡@¡@¦U¯Å¥DºÞ¾÷Ãö¤Î¥Øªº¨Æ·~¥DºÞ¾÷ÃöÀ³»s§@¥þ¥Á°ê¨¾±Ð¨|¹q¼v¤ù¡B¿ý¼v¸`¥Ø±a©Î¤å«Å¸ê®Æ¡A³z¹L¤j²³¶Ç¼½´CÅé¼½©ñ¡B¥Z¸ü¡A¿n·¥¾®»EªÀ·|¤j²³¤§¥þ¥Á°ê¨¾¦@ÃÑ¡A«Ø¥ß¥þ¥Á°ê¨¾²z©À¡C<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td><font color=8000ff>²Ä¤Q±ø</font>
<font size=2>(°Êûºt²ß¤§°t¦X)</font>
<table><tr><td> </td>
<td>
¡@¡@¦U¯Å¥DºÞ¾÷ÃöÀ³°t¦X°Êûºt²ß¡A³W¹º¿ì²z¥þ¥Á¨¾½Ã°Êûºt²ß¤§±Ð¨|¬¡°Ê©Î½Òµ{¡A¨Ã©ó°Êûºt²ß®É°t¦X¹ê¬I¥þ¥Á°ê¨¾±Ð¨|¡C<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td><font color=8000ff>²Ä¤Q¤@±ø</font>
<font size=2>(¦UÃþ°ê¨¾±Ð¨|¤åª«¤§«OÅ@)</font>
<table><tr><td> </td>
<td>
¡@¡@¦U¯Å¥DºÞ¾÷ÃöÀ³§´µ½ºÞ²z¦UÃþ¨ã¥þ¥Á°ê¨¾±Ð¨|¥\¯à¤§x¨Æ¿ò§}¡B³Õª«À]¡B¬ö©ÀÀ]¤Î¨ä¥L¤å¤Æ³õ©Ò¡A¨Ã¥[±j¨ä¹ï¨ã°ê¨¾±Ð¨|·N¸q¤åª«¤§»`¶°¡B¬ã¨s¡B¸Ñ»¡»P«OÅ@¤u§@¡C<br>
¡@¡@«e¶µ¤§¹ê¬I¿ìªk¡A¥Ñ¦æ¬F°|¤å¤Æ«Ø³]©eû·|·|¦P±Ð¨|³¡¡B¤¤¥¡¥DºÞ¾÷Ãö©w¤§¡C<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td><font color=8000ff>²Ä¤Q¤G±ø</font>
<font size=2>(°Ñ¥[¤Hûµ¹¤©¤½°²)</font>
<table><tr><td> </td>
<td>
¡@¡@¬F©²¾÷Ãö¡]ºc¡^¡B¾Ç®Õ¡B¨Æ·~³æ¦ì¤§¤Hû¡A°Ñ¥[¥þ¥Á°ê¨¾±Ð¨|ªÌ¡AÀ³µ¹¤©¤½°²¡C<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td><font color=8000ff>²Ä¤Q¤T±ø</font>
<font size=2>(¹wºâ½s¦C)</font>
<table><tr><td> </td>
<td>
¡@¡@¦U¯Å¥DºÞ¾÷Ãö¤Î¥Øªº¨Æ·~¥DºÞ¾÷ÃöÀ³½s¦C¸g¶O¡A±À¦æ¥þ¥Á°ê¨¾±Ð¨|¬ÛÃö¨Æ¶µ¡C<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td><font color=8000ff>²Ä¤Q¥|±ø</font>
<font size=2>(¼úÀy)</font>
<table><tr><td> </td>
<td>
¡@¡@¹ê¬I¥þ¥Á°ê¨¾±Ð¨|¤u§@¨ã¦³³Ç¥X°^Äm¤§¾÷Ãö¡]ºc¡^¡B¹ÎÅé©ÎÓ¤H¡AÀ³µ¹¤©¾A·í¼úÀy¡C<br>
¡@¡@«e¶µ¼úÀy¿ìªk¡A¥Ñ¤¤¥¡¥DºÞ¾÷Ãö©w¤§¡C<br>
</td>
</table>
</table>
</table>
<table><tr><td> </td><td><font color=8000ff>²Ä¤Q¤±ø</font>
<font size=2>(¬I¦æ¤é)</font>
<table><tr><td> </td>
<td>
¡@¡@¥»ªk¦Û¤½¥¬¤é¤@¦~¤º¬I¦æ¡C<br>
</td>
</table>
</table>
</table>
</left>
</body>
<!-- Mirrored from lis.ly.gov.tw/lghtml/lawstat/version2/01468/0146894011100.htm by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 24 Mar 2013 09:11:06 GMT -->
</html>
|
mit
|
NewSpring/apollos-core
|
.bin/index.js
|
5565
|
#!/usr/bin/env node
"use strict";
// XXX currently this project is written to support node 0.10.*
// when Meteor 1.4 is ready, we can rewrite in es6
var Vorpal = require("vorpal")(),
Path = require("path"),
Fs = require("fs"),
Exec = require("child_process").exec,
Spawn = require("child_process").spawn,
Rimraf = require("rimraf").sync,
Promise = require("es6-promise").Promise,
GitHub = require("github-download"),
Mkdirp = require("mkdirp")
;
var root = Path.resolve(__dirname, "../");
var built = [
".remote",
"node_modules",
"packages",
".meteor/local"
];
function installDep(src, dep){
return new Promise(function(resolve, reject){
Mkdirp(src, function(err) {
if (err) return reject(err);
GitHub(dep, src)
.on("error", function(err){}) // XXX handle error
.on("end", resolve);
});
});
}
Vorpal
.command("setup")
.description("Bootstrap an application. This may take some time...")
.option("-c, --clean", "Force rebuild of application(s)")
.option("-l, --log [level]", "Sets verbosity level.")
.action(function(args, cb) {
var app = root;
var options = args.options;
if (options.clean) {
console.log("Cleaning all dependencies...");
for (var i = 0; i < built.length; i++) {
var localPath = built[i];
Rimraf(Path.join(app, localPath));
}
}
var packageFile = require(Path.join(app, "package.json"));
var depPromises = [];
if (packageFile.apollos && packageFile.apollos.resource) {
for (var subDir in packageFile.apollos.resource) {
if (!packageFile.apollos.resource.hasOwnProperty(subDir)) continue;
var localPath = Path.join(app, subDir);
var deps = packageFile.apollos.resource[subDir];
for (var dep in deps) {
if (!deps.hasOwnProperty(dep)) continue;
console.log("installing resource: " + dep)
depPromises.push(installDep(Path.join(localPath, dep), deps[dep]));
}
}
}
// var npmPromises = [];
// npmPromises.push(
// new Promise(function(p, f){
// console.log("installing npm deps");
// var child = Spawn("npm", ["install"], {
// cwd: app, stdio: "inherit"
// });
// child.on("error", f);
// })
// );
return Promise.all(depPromises)
.then(function(){
console.log("Holtzmann should be ready to go!");
// console.log("you will need to clone it down manually");
// console.log("\n");
// console.log(" cd " + app + "/.remote/ && git clone https://github.com/NewSpring/ops-settings.git settings");
// console.log("\n");
cb();
})
.catch(function(err) {
console.error(err);
cb();
})
});
Vorpal
.command("run")
.description("Start a local server to serve the site and print its address in your console")
.option("-p, --port", "Choose a port to run the application")
.option("-v, --verbosity [level]", "Sets verbosity level.")
.option("-q, --quick", "Only runs the app, not apollos watcher as well")
.option("-n, --native", "Runs the native version of the application")
.option("--ios", "Run the native app of a given site in the iOS simulator")
.option("--android", "Run the native app of a given site in the Android simulator")
.option("--device", "Run the native app of a given site on the device of the platform")
.option("--production", "Run the application in production mode")
.option("--debug", "Run the application in debug mode")
.action(function(args, cb) {
var app = root;
var options = args.options;
var packageFile = require(Path.join(app, "package.json"));
var env = process.env;
env.METEOR_DISABLE_FS_FIBERS = 1; // https://github.com/meteor/meteor/pull/7668#issuecomment-256230102
if (options.debug) env.METEOR_PROFILE = 200;
if (options.production) env.NODE_ENV = "production";
if (!options.ios && !options.android && !options.native) env.WEB = true;
if (options.native || options.ios || options.android) env.NATIVE = true;
var configFile = Path.join(__dirname, "apollos-runtime.json");
if (!Fs.existsSync(configFile)) {
Fs.writeFileSync(configFile, JSON.stringify({ WEB: !!env.WEB }, null, 2), "utf8");
}
var apolloRuntime = require(configFile);
// removes the built files for a rebuild
if (!options.quick && !!apolloRuntime.WEB != !!env.WEB) {
Rimraf(Path.join(app, ".meteor/local"));
}
var meteorArgs = [ "--settings" ];
if (options.ios && !options.device) meteorArgs.unshift("run", "ios");
if (options.android && !options.device) meteorArgs.unshift("run", "android");
if (options.ios && options.device) meteorArgs.unshift("run", "ios-device");
if (options.android && options.device) meteorArgs.unshift("run", "android-device");
if (
packageFile.apollos && packageFile.apollos.settings &&
Fs.existsSync(Path.join(app, packageFile.apollos.settings))
) {
meteorArgs.push(packageFile.apollos.settings)
} else {
meteorArgs.push(Path.join(app, ".meteor/sample.settings.json"));
}
function run() {
var meteor = Spawn("meteor", meteorArgs, { stdio: "inherit", cwd: app, env: env });
}
Fs.writeFileSync(configFile, JSON.stringify({ WEB: !!env.WEB }, null, 2), "utf8");
if (options.production) {
console.log("Building apollos in production mode");
meteorArgs.push("--production");
}
run();
});
Vorpal
.parse(process.argv);
|
mit
|
maniero/SOpt
|
JavaScript/Algorithm/Bmi2.js
|
207
|
function calculaIMC(altura, peso) { return peso / (altura * altura); }
console.log("O seu imc é: " + calculaIMC(prompt("Sua altura? "), prompt("Seu peso? ")));
//https://pt.stackoverflow.com/q/327751/101
|
mit
|
guowilling/iOSExamples
|
ObjC/Others/AllUIFonts/AllUIFonts/AppDelegate.h
|
275
|
//
// AppDelegate.h
// iOSAllFonts
//
// Created by Willing Guo on 17/1/8.
// Copyright © 2017年 SR. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
|
mit
|
ThirteenAG/limit_adjuster_gta3vcsa
|
src/sample/sample.cpp
|
2162
|
/*
* Sample Adjuster
*
*/
#include "LimitAdjuster.h"
// Sample Simple Adjuster
class Sample1 : public SimpleAdjuster
{
public:
const char* GetLimitName() { return GetGVM().IsSA()? "FoodLimit" : nullptr; }
void ChangeLimit(int, const std::string& value) { injector::WriteMemory(0xF00D, std::stof(value)); }
// Instantiate the adjuster on the global scope
} simple_adjuster_sample;
// Sample "Complex" Adjuster
class Sample2 : public Adjuster
{
public:
// ID enum, those ids are local between each Adjuster, you shouldn't worry about conflicts with other adjusters
enum
{
CoffeeLimit,
FoodLimit,
IceLimit
};
// Get the limit table that we're going to handle
const Limit* GetLimits()
{
static Limit limits[] =
{
// You could use DEFINE_LIMIT(CoffeeLimit) instead of {...}
{ "CoffeeLimit", CoffeeLimit },
{ "FoodLimit", FoodLimit },
{ "IceLimit", IceLimit },
// You could also use FINISH_LIMITS()
{ nullptr, 0 }
};
// This Sample Adjuster can handle only San Andreas game
if(GetGVM().IsSA()) return limits;
return nullptr;
}
// Change an specific limit
void ChangeLimit(int id, const std::string& value)
{
switch(id)
{
case CoffeeLimit: // Changes the cofee limit
injector::WriteMemory(0xC0FFEE, std::stoi(value, 0, 0));
break;
case FoodLimit: // Changes the food limit
injector::WriteMemory(0xF00D, std::stof(value));
break;
case IceLimit: // Changes the ice limit
injector::WriteMemory<short>(0x1CED, std::stoi(value) % 1337);
break;
}
}
// Instantiate the adjuster on the global scope
} complex_adjuster_sample;
|
mit
|
DimensionDataCBUSydney/DimensionData.ComputeClient
|
docs/powershell/_build/html/Wait-CaasServerOperation.html
|
7069
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Wait-CaasServerOperation — CaaS PowerShell 3.1 documentation</title>
<link rel="stylesheet" href="_static/alabaster.css" type="text/css" />
<link rel="stylesheet" href="_static/pygments.css" type="text/css" />
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: './',
VERSION: '3.1',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true
};
</script>
<script type="text/javascript" src="_static/jquery.js"></script>
<script type="text/javascript" src="_static/underscore.js"></script>
<script type="text/javascript" src="_static/doctools.js"></script>
<link rel="top" title="CaaS PowerShell 3.1 documentation" href="index.html" />
<link rel="stylesheet" href="_static/custom.css" type="text/css" />
<meta name="viewport" content="width=device-width, initial-scale=0.9, maximum-scale=0.9" />
</head>
<body role="document">
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="wait-caasserveroperation">
<h1>Wait-CaasServerOperation<a class="headerlink" href="#wait-caasserveroperation" title="Permalink to this headline">¶</a></h1>
<div class="section" id="synopsis">
<h2>Synopsis<a class="headerlink" href="#synopsis" title="Permalink to this headline">¶</a></h2>
<p>Wait-CaasServerOperation -Server <ServerType> [-Connection <ComputeServiceConnection>] [<CommonParameters>]</p>
</div>
<div class="section" id="syntax">
<h2>Syntax<a class="headerlink" href="#syntax" title="Permalink to this headline">¶</a></h2>
<div class="highlight-powershell"><div class="highlight"><pre><span></span><span class="n">syntaxItem</span>
</pre></div>
</div>
<hr class="docutils" />
<p><a class="reference external" href="mailto:{%40{name=Wait-CaasServerOperation">{<span>@</span>{name=Wait-CaasServerOperation</a>; CommonParameters=True; WorkflowCommonParameters=False; parameter=System.Object[]}}</p>
</div>
<div class="section" id="description">
<h2>Description<a class="headerlink" href="#description" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="parameters">
<h2>Parameters<a class="headerlink" href="#parameters" title="Permalink to this headline">¶</a></h2>
<div class="section" id="connection-computeserviceconnection">
<h3>-Connection <ComputeServiceConnection><a class="headerlink" href="#connection-computeserviceconnection" title="Permalink to this headline">¶</a></h3>
<p>The CaaS Connection created by New-CaasConnection</p>
<div class="highlight-powershell"><div class="highlight"><pre><span></span><span class="k">Position</span><span class="p">?</span> <span class="n">Named</span>
</pre></div>
</div>
<p>Accept pipeline input? true (ByPropertyName)
Parameter set name (All)
Aliases None
Dynamic? false</p>
</div>
<div class="section" id="server-servertype">
<h3>-Server <ServerType><a class="headerlink" href="#server-servertype" title="Permalink to this headline">¶</a></h3>
<p>The server to action on</p>
<div class="highlight-powershell"><div class="highlight"><pre><span></span><span class="k">Position</span><span class="p">?</span> <span class="n">Named</span>
</pre></div>
</div>
<p>Accept pipeline input? true (ByValue)
Parameter set name (All)
Aliases None
Dynamic? false</p>
</div>
</div>
<div class="section" id="inputs">
<h2>INPUTS<a class="headerlink" href="#inputs" title="Permalink to this headline">¶</a></h2>
<p>DD.CBU.Compute.Api.Contracts.Network20.ServerType
DD.CBU.Compute.Powershell.ComputeServiceConnection</p>
</div>
<div class="section" id="outputs">
<h2>OUTPUTS<a class="headerlink" href="#outputs" title="Permalink to this headline">¶</a></h2>
<p>DD.CBU.Compute.Api.Contracts.Network20.ServerType</p>
</div>
<div class="section" id="notes">
<h2>NOTES<a class="headerlink" href="#notes" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="examples">
<h2>EXAMPLES<a class="headerlink" href="#examples" title="Permalink to this headline">¶</a></h2>
</div>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
<div class="sphinxsidebarwrapper">
<h3><a href="index.html">Table Of Contents</a></h3>
<ul>
<li><a class="reference internal" href="#">Wait-CaasServerOperation</a><ul>
<li><a class="reference internal" href="#synopsis">Synopsis</a></li>
<li><a class="reference internal" href="#syntax">Syntax</a></li>
<li><a class="reference internal" href="#description">Description</a></li>
<li><a class="reference internal" href="#parameters">Parameters</a><ul>
<li><a class="reference internal" href="#connection-computeserviceconnection">-Connection <ComputeServiceConnection></a></li>
<li><a class="reference internal" href="#server-servertype">-Server <ServerType></a></li>
</ul>
</li>
<li><a class="reference internal" href="#inputs">INPUTS</a></li>
<li><a class="reference internal" href="#outputs">OUTPUTS</a></li>
<li><a class="reference internal" href="#notes">NOTES</a></li>
<li><a class="reference internal" href="#examples">EXAMPLES</a></li>
</ul>
</li>
</ul>
<div class="relations">
<h3>Related Topics</h3>
<ul>
<li><a href="index.html">Documentation overview</a><ul>
</ul></li>
</ul>
</div>
<div role="note" aria-label="source link">
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="_sources/Wait-CaasServerOperation.txt"
rel="nofollow">Show Source</a></li>
</ul>
</div>
<div id="searchbox" style="display: none" role="search">
<h3>Quick search</h3>
<form class="search" action="search.html" method="get">
<input type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
<p class="searchtip" style="font-size: 90%">
Enter search terms or a module, class or function name.
</p>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="footer">
©2016, Dimension Data.
|
Powered by <a href="http://sphinx-doc.org/">Sphinx 1.3.1</a>
& <a href="https://github.com/bitprophet/alabaster">Alabaster 0.7.8</a>
|
<a href="_sources/Wait-CaasServerOperation.txt"
rel="nofollow">Page source</a>
</div>
</body>
</html>
|
mit
|
jujudellago/yc2016
|
web/app/plugins/js_composer/include/classes/vendors/plugins/class-vc-vendor-woocommerce.php
|
55910
|
<?php
if ( ! defined( 'ABSPATH' ) ) {
die( '-1' );
}
/**
* Class Vc_Vendor_Woocommerce
*
* @since 4.4
* @todo move to separate file and dir.
*/
class Vc_Vendor_Woocommerce {
protected static $product_fields_list = false;
protected static $order_fields_list = false;
/**
* @since 4.4
*/
public function load() {
if ( class_exists( 'WooCommerce' ) ) {
add_action( 'vc_after_mapping', array(
$this,
'mapShortcodes',
) );
add_action( 'vc_backend_editor_render', array(
$this,
'enqueueJsBackend',
) );
add_action( 'vc_frontend_editor_render', array(
$this,
'enqueueJsFrontend',
) );
add_filter( 'vc_grid_item_shortcodes', array(
$this,
'mapGridItemShortcodes',
) );
add_action( 'vc_vendor_yoastseo_filter_results', array(
$this,
'yoastSeoCompatibility',
) );
add_filter( 'woocommerce_product_tabs', array(
$this,
'addContentTabPageEditable',
) );
add_filter( 'woocommerce_shop_manager_editable_roles', array(
$this,
'addShopManagerRoleToEditable',
) );
}
}
/**
* @param $rules
* @return array
*/
public function addShopManagerRoleToEditable( $rules ) {
$rules[] = 'shop_manager';
return array_unique( $rules );
}
/**
* @param $tabs
* @return mixed
*/
public function addContentTabPageEditable( $tabs ) {
if ( vc_is_page_editable() ) {
// Description tab - shows product content
$tabs['description'] = array(
'title' => esc_html__( 'Description', 'woocommerce' ),
'priority' => 10,
'callback' => 'woocommerce_product_description_tab',
);
}
return $tabs;
}
/**
* @since 4.4
*/
public function enqueueJsBackend() {
wp_enqueue_script( 'vc_vendor_woocommerce_backend', vc_asset_url( 'js/vendors/woocommerce.js' ), array( 'vc-backend-min-js' ), '1.0', true );
}
/**
* @since 4.4
*/
public function enqueueJsFrontend() {
wp_enqueue_script( 'vc_vendor_woocommerce_frontend', vc_asset_url( 'js/vendors/woocommerce.js' ), array( 'vc-frontend-editor-min-js' ), '1.0', true );
}
/**
* Add settings for shortcodes
*
* @param $tag
*
* @return array
* @since 4.9
*
*/
public function addShortcodeSettings( $tag ) {
$args = array(
'type' => 'post',
'child_of' => 0,
'parent' => '',
'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => false,
'hierarchical' => 1,
'exclude' => '',
'include' => '',
'number' => '',
'taxonomy' => 'product_cat',
'pad_counts' => false,
);
$order_by_values = array(
'',
esc_html__( 'Date', 'js_composer' ) => 'date',
esc_html__( 'ID', 'js_composer' ) => 'ID',
esc_html__( 'Author', 'js_composer' ) => 'author',
esc_html__( 'Title', 'js_composer' ) => 'title',
esc_html__( 'Modified', 'js_composer' ) => 'modified',
esc_html__( 'Random', 'js_composer' ) => 'rand',
esc_html__( 'Comment count', 'js_composer' ) => 'comment_count',
esc_html__( 'Menu order', 'js_composer' ) => 'menu_order',
esc_html__( 'Menu order & title', 'js_composer' ) => 'menu_order title',
esc_html__( 'Include', 'js_composer' ) => 'include',
);
$order_way_values = array(
'',
esc_html__( 'Descending', 'js_composer' ) => 'DESC',
esc_html__( 'Ascending', 'js_composer' ) => 'ASC',
);
$settings = array();
switch ( $tag ) {
case 'woocommerce_cart':
$settings = array(
'name' => esc_html__( 'Cart', 'js_composer' ),
'base' => 'woocommerce_cart',
'icon' => 'icon-wpb-woocommerce',
'category' => esc_html__( 'WooCommerce', 'js_composer' ),
'description' => esc_html__( 'Displays the cart contents', 'js_composer' ),
'show_settings_on_create' => false,
'php_class_name' => 'Vc_WooCommerce_NotEditable',
);
break;
case 'woocommerce_checkout':
/**
* @shortcode woocommerce_checkout
* @description Used on the checkout page, the checkout shortcode displays the checkout process.
* @no_params
* @not_editable
*/ $settings = array(
'name' => esc_html__( 'Checkout', 'js_composer' ),
'base' => 'woocommerce_checkout',
'icon' => 'icon-wpb-woocommerce',
'category' => esc_html__( 'WooCommerce', 'js_composer' ),
'description' => esc_html__( 'Displays the checkout', 'js_composer' ),
'show_settings_on_create' => false,
'php_class_name' => 'Vc_WooCommerce_NotEditable',
);
break;
case 'woocommerce_order_tracking':
/**
* @shortcode woocommerce_order_tracking
* @description Lets a user see the status of an order by entering their order details.
* @no_params
* @not_editable
*/ $settings = array(
'name' => esc_html__( 'Order Tracking Form', 'js_composer' ),
'base' => 'woocommerce_order_tracking',
'icon' => 'icon-wpb-woocommerce',
'category' => esc_html__( 'WooCommerce', 'js_composer' ),
'description' => esc_html__( 'Lets a user see the status of an order', 'js_composer' ),
'show_settings_on_create' => false,
'php_class_name' => 'Vc_WooCommerce_NotEditable',
);
break;
case 'woocommerce_my_account':
/**
* @shortcode woocommerce_my_account
* @description Shows the ‘my account’ section where the customer can view past orders and update their information.
* You can specify the number or order to show, it’s set by default to 15 (use -1 to display all orders.)
*
* @param order_count integer
* Current user argument is automatically set using get_user_by( ‘id’, get_current_user_id() ).
*/ $settings = array(
'name' => esc_html__( 'My Account', 'js_composer' ),
'base' => 'woocommerce_my_account',
'icon' => 'icon-wpb-woocommerce',
'category' => esc_html__( 'WooCommerce', 'js_composer' ),
'description' => esc_html__( 'Shows the "my account" section', 'js_composer' ),
'params' => array(
array(
'type' => 'textfield',
'heading' => esc_html__( 'Order count', 'js_composer' ),
'value' => 15,
'save_always' => true,
'param_name' => 'order_count',
'description' => esc_html__( 'You can specify the number or order to show, it\'s set by default to 15 (use -1 to display all orders.)', 'js_composer' ),
),
),
);
break;
case 'recent_products':
/**
* @shortcode recent_products
* @description Lists recent products – useful on the homepage. The ‘per_page’ shortcode determines how many products
* to show on the page and the columns attribute controls how many columns wide the products should be before wrapping.
* To learn more about the default ‘orderby’ parameters please reference the WordPress Codex: http://codex.wordpress.org/Class_Reference/WP_Query
*
* @param per_page integer
* @param columns integer
* @param orderby array
* @param order array
*/ $settings = array(
'name' => esc_html__( 'Recent products', 'js_composer' ),
'base' => 'recent_products',
'icon' => 'icon-wpb-woocommerce',
'category' => esc_html__( 'WooCommerce', 'js_composer' ),
'description' => esc_html__( 'Lists recent products', 'js_composer' ),
'params' => array(
array(
'type' => 'textfield',
'heading' => esc_html__( 'Per page', 'js_composer' ),
'value' => 12,
'save_always' => true,
'param_name' => 'per_page',
'description' => esc_html__( 'The "per_page" shortcode determines how many products to show on the page', 'js_composer' ),
),
array(
'type' => 'textfield',
'heading' => esc_html__( 'Columns', 'js_composer' ),
'value' => 4,
'param_name' => 'columns',
'save_always' => true,
'description' => esc_html__( 'The columns attribute controls how many columns wide the products should be before wrapping.', 'js_composer' ),
),
array(
'type' => 'dropdown',
'heading' => esc_html__( 'Order by', 'js_composer' ),
'param_name' => 'orderby',
'value' => $order_by_values,
'std' => 'date',
// default WC value for recent_products
'save_always' => true,
'description' => sprintf( esc_html__( 'Select how to sort retrieved products. More at %s.', 'js_composer' ), '<a href="https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters" target="_blank">WordPress codex page</a>' ),
),
array(
'type' => 'dropdown',
'heading' => esc_html__( 'Sort order', 'js_composer' ),
'param_name' => 'order',
'value' => $order_way_values,
'std' => 'DESC',
// default WC value
'save_always' => true,
'description' => sprintf( esc_html__( 'Designates the ascending or descending order. More at %s.', 'js_composer' ), '<a href="https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters" target="_blank">WordPress codex page</a>' ),
),
),
);
break;
case 'featured_products':
/**
* @shortcode featured_products
* @description Works exactly the same as recent products but displays products which have been set as “featured”.
*
* @param per_page integer
* @param columns integer
* @param orderby array
* @param order array
*/ $settings = array(
'name' => esc_html__( 'Featured products', 'js_composer' ),
'base' => 'featured_products',
'icon' => 'icon-wpb-woocommerce',
'category' => esc_html__( 'WooCommerce', 'js_composer' ),
'description' => esc_html__( 'Display products set as "featured"', 'js_composer' ),
'params' => array(
array(
'type' => 'textfield',
'heading' => esc_html__( 'Per page', 'js_composer' ),
'value' => 12,
'param_name' => 'per_page',
'save_always' => true,
'description' => esc_html__( 'The "per_page" shortcode determines how many products to show on the page', 'js_composer' ),
),
array(
'type' => 'textfield',
'heading' => esc_html__( 'Columns', 'js_composer' ),
'value' => 4,
'param_name' => 'columns',
'save_always' => true,
'description' => esc_html__( 'The columns attribute controls how many columns wide the products should be before wrapping.', 'js_composer' ),
),
array(
'type' => 'dropdown',
'heading' => esc_html__( 'Order by', 'js_composer' ),
'param_name' => 'orderby',
'value' => $order_by_values,
'std' => 'date',
// default WC value
'save_always' => true,
'description' => sprintf( esc_html__( 'Select how to sort retrieved products. More at %s.', 'js_composer' ), '<a href="https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters" target="_blank">WordPress codex page</a>' ),
),
array(
'type' => 'dropdown',
'heading' => esc_html__( 'Sort order', 'js_composer' ),
'param_name' => 'order',
'value' => $order_way_values,
'std' => 'DESC',
// default WC value
'save_always' => true,
'description' => sprintf( esc_html__( 'Designates the ascending or descending order. More at %s.', 'js_composer' ), '<a href="s://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters" target="_blank">WordPress codex page</a>' ),
),
),
);
break;
case 'product':
/**
* @shortcode product
* @description Show a single product by ID or SKU.
*
* @param id integer
* @param sku string
* If the product isn’t showing, make sure it isn’t set to Hidden in the Catalog Visibility.
* To find the Product ID, go to the Product > Edit screen and look in the URL for the postid= .
*/ $settings = array(
'name' => esc_html__( 'Product', 'js_composer' ),
'base' => 'product',
'icon' => 'icon-wpb-woocommerce',
'category' => esc_html__( 'WooCommerce', 'js_composer' ),
'description' => esc_html__( 'Show a single product by ID or SKU', 'js_composer' ),
'params' => array(
array(
'type' => 'autocomplete',
'heading' => esc_html__( 'Select identificator', 'js_composer' ),
'param_name' => 'id',
'description' => esc_html__( 'Input product ID or product SKU or product title to see suggestions', 'js_composer' ),
),
array(
'type' => 'hidden',
// This will not show on render, but will be used when defining value for autocomplete
'param_name' => 'sku',
),
),
);
break;
case 'products':
$settings = array(
'name' => esc_html__( 'Products', 'js_composer' ),
'base' => 'products',
'icon' => 'icon-wpb-woocommerce',
'category' => esc_html__( 'WooCommerce', 'js_composer' ),
'description' => esc_html__( 'Show multiple products by ID or SKU.', 'js_composer' ),
'params' => array(
array(
'type' => 'textfield',
'heading' => esc_html__( 'Columns', 'js_composer' ),
'value' => 4,
'param_name' => 'columns',
'save_always' => true,
),
array(
'type' => 'dropdown',
'heading' => esc_html__( 'Order by', 'js_composer' ),
'param_name' => 'orderby',
'value' => $order_by_values,
'std' => 'title',
// Default WC value
'save_always' => true,
'description' => sprintf( esc_html__( 'Select how to sort retrieved products. More at %s. Default by Title', 'js_composer' ), '<a href="https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters" target="_blank">WordPress codex page</a>' ),
),
array(
'type' => 'dropdown',
'heading' => esc_html__( 'Sort order', 'js_composer' ),
'param_name' => 'order',
'value' => $order_way_values,
'std' => 'ASC',
// default WC value
'save_always' => true,
'description' => sprintf( esc_html__( 'Designates the ascending or descending order. More at %s. Default by ASC', 'js_composer' ), '<a href="https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters" target="_blank">WordPress codex page</a>' ),
),
array(
'type' => 'autocomplete',
'heading' => esc_html__( 'Products', 'js_composer' ),
'param_name' => 'ids',
'settings' => array(
'multiple' => true,
'sortable' => true,
'unique_values' => true,
// In UI show results except selected. NB! You should manually check values in backend
),
'save_always' => true,
'description' => esc_html__( 'Enter List of Products', 'js_composer' ),
),
array(
'type' => 'hidden',
'param_name' => 'skus',
),
),
);
break;
case 'add_to_cart':
/**
* @shortcode add_to_cart
* @description Show the price and add to cart button of a single product by ID (or SKU).
*
* @param id integer
* @param sku string
* @param style string
* If the product isn’t showing, make sure it isn’t set to Hidden in the Catalog Visibility.
*/ $settings = array(
'name' => esc_html__( 'Add to cart', 'js_composer' ),
'base' => 'add_to_cart',
'icon' => 'icon-wpb-woocommerce',
'category' => esc_html__( 'WooCommerce', 'js_composer' ),
'description' => esc_html__( 'Show multiple products by ID or SKU', 'js_composer' ),
'params' => array(
array(
'type' => 'autocomplete',
'heading' => esc_html__( 'Select identificator', 'js_composer' ),
'param_name' => 'id',
'description' => esc_html__( 'Input product ID or product SKU or product title to see suggestions', 'js_composer' ),
),
array(
'type' => 'hidden',
'param_name' => 'sku',
),
array(
'type' => 'textfield',
'heading' => esc_html__( 'Wrapper inline style', 'js_composer' ),
'param_name' => 'style',
),
),
);
break;
case 'add_to_cart_url':
/**
* @shortcode add_to_cart_url
* @description Print the URL on the add to cart button of a single product by ID.
*
* @param id integer
* @param sku string
*/ $settings = array(
'name' => esc_html__( 'Add to cart URL', 'js_composer' ),
'base' => 'add_to_cart_url',
'icon' => 'icon-wpb-woocommerce',
'category' => esc_html__( 'WooCommerce', 'js_composer' ),
'description' => esc_html__( 'Show URL on the add to cart button', 'js_composer' ),
'params' => array(
array(
'type' => 'autocomplete',
'heading' => esc_html__( 'Select identificator', 'js_composer' ),
'param_name' => 'id',
'description' => esc_html__( 'Input product ID or product SKU or product title to see suggestions', 'js_composer' ),
),
array(
'type' => 'hidden',
'param_name' => 'sku',
),
),
);
break;
case 'product_page':
/**
* @shortcode product_page
* @description Show a full single product page by ID or SKU.
*
* @param id integer
* @param sku string
*/ $settings = array(
'name' => esc_html__( 'Product page', 'js_composer' ),
'base' => 'product_page',
'icon' => 'icon-wpb-woocommerce',
'category' => esc_html__( 'WooCommerce', 'js_composer' ),
'description' => esc_html__( 'Show single product by ID or SKU', 'js_composer' ),
'params' => array(
array(
'type' => 'autocomplete',
'heading' => esc_html__( 'Select identificator', 'js_composer' ),
'param_name' => 'id',
'description' => esc_html__( 'Input product ID or product SKU or product title to see suggestions', 'js_composer' ),
),
array(
'type' => 'hidden',
'param_name' => 'sku',
),
),
);
break;
case 'product_category':
/**
* @shortcode product_category
* @description Show multiple products in a category by slug.
*
* @param per_page integer
* @param columns integer
* @param orderby array
* @param order array
* @param category string
* Go to: WooCommerce > Products > Categories to find the slug column.
*/ // All this move to product
$categories = get_categories( $args );
$product_categories_dropdown = array();
$this->getCategoryChildsFull( 0, $categories, 0, $product_categories_dropdown );
$settings = array(
'name' => esc_html__( 'Product category', 'js_composer' ),
'base' => 'product_category',
'icon' => 'icon-wpb-woocommerce',
'category' => esc_html__( 'WooCommerce', 'js_composer' ),
'description' => esc_html__( 'Show multiple products in a category', 'js_composer' ),
'params' => array(
array(
'type' => 'textfield',
'heading' => esc_html__( 'Per page', 'js_composer' ),
'value' => 12,
'save_always' => true,
'param_name' => 'per_page',
'description' => esc_html__( 'How much items per page to show', 'js_composer' ),
),
array(
'type' => 'textfield',
'heading' => esc_html__( 'Columns', 'js_composer' ),
'value' => 4,
'save_always' => true,
'param_name' => 'columns',
'description' => esc_html__( 'How much columns grid', 'js_composer' ),
),
array(
'type' => 'dropdown',
'heading' => esc_html__( 'Order by', 'js_composer' ),
'param_name' => 'orderby',
'value' => $order_by_values,
'std' => 'menu_order title',
// Default WC value
'save_always' => true,
'description' => sprintf( esc_html__( 'Select how to sort retrieved products. More at %s.', 'js_composer' ), '<a href="s://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters" target="_blank">WordPress codex page</a>' ),
),
array(
'type' => 'dropdown',
'heading' => esc_html__( 'Sort order', 'js_composer' ),
'param_name' => 'order',
'value' => $order_way_values,
'std' => 'ASC',
// default WC value
'save_always' => true,
'description' => sprintf( esc_html__( 'Designates the ascending or descending order. More at %s.', 'js_composer' ), '<a href="https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters" target="_blank">WordPress codex page</a>' ),
),
array(
'type' => 'dropdown',
'heading' => esc_html__( 'Category', 'js_composer' ),
'value' => $product_categories_dropdown,
'param_name' => 'category',
'save_always' => true,
'description' => esc_html__( 'Product category list', 'js_composer' ),
),
),
);
break;
case 'product_categories':
$settings = array(
'name' => esc_html__( 'Product categories', 'js_composer' ),
'base' => 'product_categories',
'icon' => 'icon-wpb-woocommerce',
'category' => esc_html__( 'WooCommerce', 'js_composer' ),
'description' => esc_html__( 'Display product categories loop', 'js_composer' ),
'params' => array(
array(
'type' => 'textfield',
'heading' => esc_html__( 'Number', 'js_composer' ),
'param_name' => 'number',
'description' => esc_html__( 'The `number` field is used to display the number of products.', 'js_composer' ),
),
array(
'type' => 'dropdown',
'heading' => esc_html__( 'Order by', 'js_composer' ),
'param_name' => 'orderby',
'value' => $order_by_values,
'std' => 'name',
// default WC value
'save_always' => true,
'description' => sprintf( esc_html__( 'Select how to sort retrieved products. More at %s.', 'js_composer' ), '<a href="https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters" target="_blank">WordPress codex page</a>' ),
),
array(
'type' => 'dropdown',
'heading' => esc_html__( 'Sort order', 'js_composer' ),
'param_name' => 'order',
'value' => $order_way_values,
'std' => 'ASC',
// default WC value
'save_always' => true,
'description' => sprintf( esc_html__( 'Designates the ascending or descending order. More at %s.', 'js_composer' ), '<a href="https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters" target="_blank">WordPress codex page</a>' ),
),
array(
'type' => 'textfield',
'heading' => esc_html__( 'Columns', 'js_composer' ),
'value' => 4,
'param_name' => 'columns',
'save_always' => true,
'description' => esc_html__( 'How much columns grid', 'js_composer' ),
),
array(
'type' => 'textfield',
'heading' => esc_html__( 'Number', 'js_composer' ),
'param_name' => 'hide_empty',
'description' => esc_html__( 'Hide empty', 'js_composer' ),
),
array(
'type' => 'autocomplete',
'heading' => esc_html__( 'Categories', 'js_composer' ),
'param_name' => 'ids',
'settings' => array(
'multiple' => true,
'sortable' => true,
),
'save_always' => true,
'description' => esc_html__( 'List of product categories', 'js_composer' ),
),
),
);
break;
case 'sale_products':
/**
* @shortcode sale_products
* @description List all products on sale.
*
* @param per_page integer
* @param columns integer
* @param orderby array
* @param order array
*/ $settings = array(
'name' => esc_html__( 'Sale products', 'js_composer' ),
'base' => 'sale_products',
'icon' => 'icon-wpb-woocommerce',
'category' => esc_html__( 'WooCommerce', 'js_composer' ),
'description' => esc_html__( 'List all products on sale', 'js_composer' ),
'params' => array(
array(
'type' => 'textfield',
'heading' => esc_html__( 'Per page', 'js_composer' ),
'value' => 12,
'save_always' => true,
'param_name' => 'per_page',
'description' => esc_html__( 'How much items per page to show', 'js_composer' ),
),
array(
'type' => 'textfield',
'heading' => esc_html__( 'Columns', 'js_composer' ),
'value' => 4,
'save_always' => true,
'param_name' => 'columns',
'description' => esc_html__( 'How much columns grid', 'js_composer' ),
),
array(
'type' => 'dropdown',
'heading' => esc_html__( 'Order by', 'js_composer' ),
'param_name' => 'orderby',
'value' => $order_by_values,
'std' => 'title',
// default WC value
'save_always' => true,
'description' => sprintf( esc_html__( 'Select how to sort retrieved products. More at %s.', 'js_composer' ), '<a href="https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters" target="_blank">WordPress codex page</a>' ),
),
array(
'type' => 'dropdown',
'heading' => esc_html__( 'Sort order', 'js_composer' ),
'param_name' => 'order',
'value' => $order_way_values,
'std' => 'ASC',
// default WC value
'save_always' => true,
'description' => sprintf( esc_html__( 'Designates the ascending or descending order. More at %s.', 'js_composer' ), '<a href="https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters" target="_blank">WordPress codex page</a>' ),
),
),
);
break;
case 'best_selling_products':
/**
* @shortcode best_selling_products
* @description List best selling products on sale.
*
* @param per_page integer
* @param columns integer
*/ $settings = array(
'name' => esc_html__( 'Best Selling Products', 'js_composer' ),
'base' => 'best_selling_products',
'icon' => 'icon-wpb-woocommerce',
'category' => esc_html__( 'WooCommerce', 'js_composer' ),
'description' => esc_html__( 'List best selling products on sale', 'js_composer' ),
'params' => array(
array(
'type' => 'textfield',
'heading' => esc_html__( 'Per page', 'js_composer' ),
'value' => 12,
'param_name' => 'per_page',
'save_always' => true,
'description' => esc_html__( 'How much items per page to show', 'js_composer' ),
),
array(
'type' => 'textfield',
'heading' => esc_html__( 'Columns', 'js_composer' ),
'value' => 4,
'param_name' => 'columns',
'save_always' => true,
'description' => esc_html__( 'How much columns grid', 'js_composer' ),
),
),
);
break;
case 'top_rated_products':
/**
* @shortcode top_rated_products
* @description List top rated products on sale.
*
* @param per_page integer
* @param columns integer
* @param orderby array
* @param order array
*/ $settings = array(
'name' => esc_html__( 'Top Rated Products', 'js_composer' ),
'base' => 'top_rated_products',
'icon' => 'icon-wpb-woocommerce',
'category' => esc_html__( 'WooCommerce', 'js_composer' ),
'description' => esc_html__( 'List all products on sale', 'js_composer' ),
'params' => array(
array(
'type' => 'textfield',
'heading' => esc_html__( 'Per page', 'js_composer' ),
'value' => 12,
'param_name' => 'per_page',
'save_always' => true,
'description' => esc_html__( 'How much items per page to show', 'js_composer' ),
),
array(
'type' => 'textfield',
'heading' => esc_html__( 'Columns', 'js_composer' ),
'value' => 4,
'param_name' => 'columns',
'save_always' => true,
'description' => esc_html__( 'How much columns grid', 'js_composer' ),
),
array(
'type' => 'dropdown',
'heading' => esc_html__( 'Order by', 'js_composer' ),
'param_name' => 'orderby',
'value' => $order_by_values,
'std' => 'title',
// default WC value
'save_always' => true,
'description' => sprintf( esc_html__( 'Select how to sort retrieved products. More at %s.', 'js_composer' ), '<a href="https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters" target="_blank">WordPress codex page</a>' ),
),
array(
'type' => 'dropdown',
'heading' => esc_html__( 'Sort order', 'js_composer' ),
'param_name' => 'order',
'value' => $order_way_values,
'std' => 'ASC',
// Default WP Value
'save_always' => true,
'description' => sprintf( esc_html__( 'Designates the ascending or descending order. More at %s.', 'js_composer' ), '<a href="https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters" target="_blank">WordPress codex page</a>' ),
),
),
);
break;
case 'product_attribute':
/**
* @shortcode product_attribute
* @description List products with an attribute shortcode.
*
* @param per_page integer
* @param columns integer
* @param orderby array
* @param order array
* @param attribute string
* @param filter string
*/ $attributes_tax = wc_get_attribute_taxonomies();
$attributes = array();
foreach ( $attributes_tax as $attribute ) {
$attributes[ $attribute->attribute_label ] = $attribute->attribute_name;
}
$settings = array(
'name' => esc_html__( 'Product Attribute', 'js_composer' ),
'base' => 'product_attribute',
'icon' => 'icon-wpb-woocommerce',
'category' => esc_html__( 'WooCommerce', 'js_composer' ),
'description' => esc_html__( 'List products with an attribute shortcode', 'js_composer' ),
'params' => array(
array(
'type' => 'textfield',
'heading' => esc_html__( 'Per page', 'js_composer' ),
'value' => 12,
'param_name' => 'per_page',
'save_always' => true,
'description' => esc_html__( 'How much items per page to show', 'js_composer' ),
),
array(
'type' => 'textfield',
'heading' => esc_html__( 'Columns', 'js_composer' ),
'value' => 4,
'param_name' => 'columns',
'save_always' => true,
'description' => esc_html__( 'How much columns grid', 'js_composer' ),
),
array(
'type' => 'dropdown',
'heading' => esc_html__( 'Order by', 'js_composer' ),
'param_name' => 'orderby',
'value' => $order_by_values,
'std' => 'title',
// default WC value
'save_always' => true,
'description' => sprintf( esc_html__( 'Select how to sort retrieved products. More at %s.', 'js_composer' ), '<a href="https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters" target="_blank">WordPress codex page</a>' ),
),
array(
'type' => 'dropdown',
'heading' => esc_html__( 'Sort order', 'js_composer' ),
'param_name' => 'order',
'value' => $order_way_values,
'std' => 'ASC',
// Default WC value
'save_always' => true,
'description' => sprintf( esc_html__( 'Designates the ascending or descending order. More at %s.', 'js_composer' ), '<a href="https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters" target="_blank">WordPress codex page</a>' ),
),
array(
'type' => 'dropdown',
'heading' => esc_html__( 'Attribute', 'js_composer' ),
'param_name' => 'attribute',
'value' => $attributes,
'save_always' => true,
'description' => esc_html__( 'List of product taxonomy attribute', 'js_composer' ),
),
array(
'type' => 'checkbox',
'heading' => esc_html__( 'Filter', 'js_composer' ),
'param_name' => 'filter',
'value' => array( 'empty' => 'empty' ),
'save_always' => true,
'description' => esc_html__( 'Taxonomy values', 'js_composer' ),
'dependency' => array(
'callback' => 'vcWoocommerceProductAttributeFilterDependencyCallback',
),
),
),
);
break;
case 'related_products':
/**
* @shortcode related_products
* @description List related products.
*
* @param per_page integer
* @param columns integer
* @param orderby array
* @param order array
*/ /* we need to detect post type to show this shortcode */ global $post, $typenow, $current_screen;
$post_type = '';
if ( $post && $post->post_type ) {
//we have a post so we can just get the post type from that
$post_type = $post->post_type;
} elseif ( $typenow ) {
//check the global $typenow - set in admin.php
$post_type = $typenow;
} elseif ( $current_screen && $current_screen->post_type ) {
//check the global $current_screen object - set in sceen.php
$post_type = $current_screen->post_type;
} elseif ( isset( $_REQUEST['post_type'] ) ) {
//lastly check the post_type querystring
$post_type = sanitize_key( $_REQUEST['post_type'] );
//we do not know the post type!
}
$settings = array(
'name' => esc_html__( 'Related Products', 'js_composer' ),
'base' => 'related_products',
'icon' => 'icon-wpb-woocommerce',
'content_element' => 'product' === $post_type,
// disable showing if not product type
'category' => esc_html__( 'WooCommerce', 'js_composer' ),
'description' => esc_html__( 'List related products', 'js_composer' ),
'params' => array(
array(
'type' => 'textfield',
'heading' => esc_html__( 'Per page', 'js_composer' ),
'value' => 12,
'save_always' => true,
'param_name' => 'per_page',
'description' => esc_html__( 'Please note: the "per_page" shortcode argument will determine how many products are shown on a page. This will not add pagination to the shortcode. ', 'js_composer' ),
),
array(
'type' => 'textfield',
'heading' => esc_html__( 'Columns', 'js_composer' ),
'value' => 4,
'save_always' => true,
'param_name' => 'columns',
'description' => esc_html__( 'How much columns grid', 'js_composer' ),
),
array(
'type' => 'dropdown',
'heading' => esc_html__( 'Order by', 'js_composer' ),
'param_name' => 'orderby',
'value' => $order_by_values,
'std' => 'rand',
// default WC value
'save_always' => true,
'description' => sprintf( esc_html__( 'Select how to sort retrieved products. More at %s.', 'js_composer' ), '<a href="https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters" target="_blank">WordPress codex page</a>' ),
),
array(
'type' => 'dropdown',
'heading' => esc_html__( 'Sort order', 'js_composer' ),
'param_name' => 'order',
'value' => $order_way_values,
'std' => 'DESC',
// Default WC value
'save_always' => true,
'description' => sprintf( esc_html__( 'Designates the ascending or descending order. More at %s.', 'js_composer' ), '<a href="https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters" target="_blank">WordPress codex page</a>' ),
),
),
);
break;
}
return $settings;
}
/**
* Add woocommerce shortcodes and hooks/filters for it.
* @since 4.4
*/
public function mapShortcodes() {
add_action( 'wp_ajax_vc_woocommerce_get_attribute_terms', array(
$this,
'getAttributeTermsAjax',
) );
$tags = array(
'woocommerce_cart',
'woocommerce_checkout',
'woocommerce_order_tracking',
'woocommerce_my_account',
'recent_products',
'featured_products',
'product',
'products',
'add_to_cart',
'add_to_cart_url',
'product_page',
'product_category',
'product_categories',
'sale_products',
'best_selling_products',
'top_rated_products',
'product_attribute',
'related_products',
);
while ( $tag = current( $tags ) ) {
vc_lean_map( $tag, array(
$this,
'addShortcodeSettings',
) );
next( $tags );
}
//Filters For autocomplete param:
//For suggestion: vc_autocomplete_[shortcode_name]_[param_name]_callback
add_filter( 'vc_autocomplete_product_id_callback', array(
$this,
'productIdAutocompleteSuggester',
), 10, 1 ); // Get suggestion(find). Must return an array
add_filter( 'vc_autocomplete_product_id_render', array(
$this,
'productIdAutocompleteRender',
), 10, 1 ); // Render exact product. Must return an array (label,value)
//For param: ID default value filter
add_filter( 'vc_form_fields_render_field_product_id_param_value', array(
$this,
'productIdDefaultValue',
), 10, 4 ); // Defines default value for param if not provided. Takes from other param value.
//Filters For autocomplete param:
//For suggestion: vc_autocomplete_[shortcode_name]_[param_name]_callback
add_filter( 'vc_autocomplete_products_ids_callback', array(
$this,
'productIdAutocompleteSuggester',
), 10, 1 ); // Get suggestion(find). Must return an array
add_filter( 'vc_autocomplete_products_ids_render', array(
$this,
'productIdAutocompleteRender',
), 10, 1 ); // Render exact product. Must return an array (label,value)
//For param: ID default value filter
add_filter( 'vc_form_fields_render_field_products_ids_param_value', array(
$this,
'productsIdsDefaultValue',
), 10, 4 ); // Defines default value for param if not provided. Takes from other param value.
//Filters For autocomplete param: Exactly Same as "product" shortcode
//For suggestion: vc_autocomplete_[shortcode_name]_[param_name]_callback
add_filter( 'vc_autocomplete_add_to_cart_id_callback', array(
$this,
'productIdAutocompleteSuggester',
), 10, 1 ); // Get suggestion(find). Must return an array
add_filter( 'vc_autocomplete_add_to_cart_id_render', array(
$this,
'productIdAutocompleteRender',
), 10, 1 ); // Render exact product. Must return an array (label,value)
//For param: ID default value filter
add_filter( 'vc_form_fields_render_field_add_to_cart_id_param_value', array(
$this,
'productIdDefaultValue',
), 10, 4 ); // Defines default value for param if not provided. Takes from other param value.
//Filters For autocomplete param: Exactly Same as "product" shortcode
//For suggestion: vc_autocomplete_[shortcode_name]_[param_name]_callback
add_filter( 'vc_autocomplete_add_to_cart_url_id_callback', array(
$this,
'productIdAutocompleteSuggester',
), 10, 1 ); // Get suggestion(find). Must return an array
add_filter( 'vc_autocomplete_add_to_cart_url_id_render', array(
$this,
'productIdAutocompleteRender',
), 10, 1 ); // Render exact product. Must return an array (label,value)
//For param: ID default value filter
add_filter( 'vc_form_fields_render_field_add_to_cart_url_id_param_value', array(
$this,
'productIdDefaultValue',
), 10, 4 ); // Defines default value for param if not provided. Takes from other param value.
//Filters For autocomplete param: Exactly Same as "product" shortcode
//For suggestion: vc_autocomplete_[shortcode_name]_[param_name]_callback
add_filter( 'vc_autocomplete_product_page_id_callback', array(
$this,
'productIdAutocompleteSuggester',
), 10, 1 ); // Get suggestion(find). Must return an array
add_filter( 'vc_autocomplete_product_page_id_render', array(
$this,
'productIdAutocompleteRender',
), 10, 1 ); // Render exact product. Must return an array (label,value)
//For param: ID default value filter
add_filter( 'vc_form_fields_render_field_product_page_id_param_value', array(
$this,
'productIdDefaultValue',
), 10, 4 ); // Defines default value for param if not provided. Takes from other param value.
//Filters For autocomplete param:
//For suggestion: vc_autocomplete_[shortcode_name]_[param_name]_callback
add_filter( 'vc_autocomplete_product_category_category_callback', array(
$this,
'productCategoryCategoryAutocompleteSuggesterBySlug',
), 10, 1 ); // Get suggestion(find). Must return an array
add_filter( 'vc_autocomplete_product_category_category_render', array(
$this,
'productCategoryCategoryRenderBySlugExact',
), 10, 1 ); // Render exact category by Slug. Must return an array (label,value)
//Filters For autocomplete param:
//For suggestion: vc_autocomplete_[shortcode_name]_[param_name]_callback
add_filter( 'vc_autocomplete_product_categories_ids_callback', array(
$this,
'productCategoryCategoryAutocompleteSuggester',
), 10, 1 ); // Get suggestion(find). Must return an array
add_filter( 'vc_autocomplete_product_categories_ids_render', array(
$this,
'productCategoryCategoryRenderByIdExact',
), 10, 1 ); // Render exact category by id. Must return an array (label,value)
//For param: "filter" param value
//vc_form_fields_render_field_{shortcode_name}_{param_name}_param
add_filter( 'vc_form_fields_render_field_product_attribute_filter_param', array(
$this,
'productAttributeFilterParamValue',
), 10, 4 ); // Defines default value for param if not provided. Takes from other param value.
}
/**
* @param array $shortcodes
* @return array|mixed
*/
/**
* @param array $shortcodes
* @return array|mixed
*/
public function mapGridItemShortcodes( array $shortcodes ) {
require_once vc_path_dir( 'VENDORS_DIR', 'plugins/woocommerce/class-vc-gitem-woocommerce-shortcode.php' );
require_once vc_path_dir( 'VENDORS_DIR', 'plugins/woocommerce/grid-item-attributes.php' );
$wc_shortcodes = include vc_path_dir( 'VENDORS_DIR', 'plugins/woocommerce/grid-item-shortcodes.php' );
return $shortcodes + $wc_shortcodes;
}
/**
* Defines default value for param if not provided. Takes from other param value.
* @param array $param_settings
* @param $current_value
* @param $map_settings
* @param $atts
*
* @return array
* @since 4.4
*
*/
public function productAttributeFilterParamValue( $param_settings, $current_value, $map_settings, $atts ) {
if ( isset( $atts['attribute'] ) ) {
$value = $this->getAttributeTerms( $atts['attribute'] );
if ( is_array( $value ) && ! empty( $value ) ) {
$param_settings['value'] = $value;
}
}
return $param_settings;
}
/**
* Get attribute terms hooks from ajax request
* @since 4.4
*/
public function getAttributeTermsAjax() {
vc_user_access()->checkAdminNonce()->validateDie()->wpAny( 'edit_posts', 'edit_pages' )->validateDie();
$attribute = vc_post_param( 'attribute' );
$values = $this->getAttributeTerms( $attribute );
$param = array(
'param_name' => 'filter',
'type' => 'checkbox',
);
$param_line = '';
foreach ( $values as $label => $v ) {
$param_line .= ' <label class="vc_checkbox-label"><input id="' . $param['param_name'] . '-' . $v . '" value="' . $v . '" class="wpb_vc_param_value ' . $param['param_name'] . ' ' . $param['type'] . '" type="checkbox" name="' . $param['param_name'] . '"' . '> ' . $label . '</label>';
}
die( wp_json_encode( $param_line ) );
}
/**
* Get attribute terms suggester
* @param $attribute
*
* @return array
* @since 4.4
*
*/
public function getAttributeTerms( $attribute ) {
$terms = get_terms( 'pa_' . $attribute ); // return array. take slug
$data = array();
if ( ! empty( $terms ) && empty( $terms->errors ) ) {
foreach ( $terms as $term ) {
$data[ $term->name ] = $term->slug;
}
}
return $data;
}
/**
* Get lists of categories.
* @param $parent_id
* @param array $array
* @param $level
* @param array $dropdown - passed by reference
* @return array
* @since 4.5.3
*
*/
protected function getCategoryChildsFull( $parent_id, $array, $level, &$dropdown ) {
$keys = array_keys( $array );
$i = 0;
while ( $i < count( $array ) ) {
$key = $keys[ $i ];
$item = $array[ $key ];
$i ++;
if ( $item->category_parent == $parent_id ) {
$name = str_repeat( '- ', $level ) . $item->name;
$value = $item->slug;
$dropdown[] = array(
'label' => $name . '(' . $item->term_id . ')',
'value' => $value,
);
unset( $array[ $key ] );
$array = $this->getCategoryChildsFull( $item->term_id, $array, $level + 1, $dropdown );
$keys = array_keys( $array );
$i = 0;
}
}
return $array;
}
/**
* Replace single product sku to id.
* @param $current_value
* @param $param_settings
* @param $map_settings
* @param $atts
*
* @return bool|string
* @since 4.4
*
*/
public function productIdDefaultValue( $current_value, $param_settings, $map_settings, $atts ) {
$value = trim( $current_value );
if ( strlen( trim( $current_value ) ) === 0 && isset( $atts['sku'] ) && strlen( $atts['sku'] ) > 0 ) {
$value = $this->productIdDefaultValueFromSkuToId( $atts['sku'] );
}
return $value;
}
/**
* Replaces product skus to id's.
* @param $current_value
* @param $param_settings
* @param $map_settings
* @param $atts
*
* @return string
* @since 4.4
*
*/
public function productsIdsDefaultValue( $current_value, $param_settings, $map_settings, $atts ) {
$value = trim( $current_value );
if ( strlen( trim( $value ) ) === 0 && isset( $atts['skus'] ) && strlen( $atts['skus'] ) > 0 ) {
$data = array();
$skus = $atts['skus'];
$skus_array = explode( ',', $skus );
foreach ( $skus_array as $sku ) {
$id = $this->productIdDefaultValueFromSkuToId( trim( $sku ) );
if ( is_numeric( $id ) ) {
$data[] = $id;
}
}
if ( ! empty( $data ) ) {
$values = explode( ',', $value );
$values = array_merge( $values, $data );
$value = implode( ',', $values );
}
}
return $value;
}
/**
* Suggester for autocomplete by id/name/title/sku
* @param $query
*
* @return array - id's from products with title/sku.
* @since 4.4
*
*/
public function productIdAutocompleteSuggester( $query ) {
global $wpdb;
$product_id = (int) $query;
$post_meta_infos = $wpdb->get_results( $wpdb->prepare( "SELECT a.ID AS id, a.post_title AS title, b.meta_value AS sku
FROM {$wpdb->posts} AS a
LEFT JOIN ( SELECT meta_value, post_id FROM {$wpdb->postmeta} WHERE `meta_key` = '_sku' ) AS b ON b.post_id = a.ID
WHERE a.post_type = 'product' AND ( a.ID = '%d' OR b.meta_value LIKE '%%%s%%' OR a.post_title LIKE '%%%s%%' )", $product_id > 0 ? $product_id : - 1, stripslashes( $query ), stripslashes( $query ) ), ARRAY_A );
$results = array();
if ( is_array( $post_meta_infos ) && ! empty( $post_meta_infos ) ) {
foreach ( $post_meta_infos as $value ) {
$data = array();
$data['value'] = $value['id'];
$data['label'] = esc_html__( 'Id', 'js_composer' ) . ': ' . $value['id'] . ( ( strlen( $value['title'] ) > 0 ) ? ' - ' . esc_html__( 'Title', 'js_composer' ) . ': ' . $value['title'] : '' ) . ( ( strlen( $value['sku'] ) > 0 ) ? ' - ' . esc_html__( 'Sku', 'js_composer' ) . ': ' . $value['sku'] : '' );
$results[] = $data;
}
}
return $results;
}
/**
* Find product by id
* @param $query
*
* @return bool|array
* @since 4.4
*
*/
public function productIdAutocompleteRender( $query ) {
$query = trim( $query['value'] ); // get value from requested
if ( ! empty( $query ) ) {
// get product
$product_object = wc_get_product( (int) $query );
if ( is_object( $product_object ) ) {
$product_sku = $product_object->get_sku();
$product_title = $product_object->get_title();
$product_id = $product_object->get_id();
$product_sku_display = '';
if ( ! empty( $product_sku ) ) {
$product_sku_display = ' - ' . esc_html__( 'Sku', 'js_composer' ) . ': ' . $product_sku;
}
$product_title_display = '';
if ( ! empty( $product_title ) ) {
$product_title_display = ' - ' . esc_html__( 'Title', 'js_composer' ) . ': ' . $product_title;
}
$product_id_display = esc_html__( 'Id', 'js_composer' ) . ': ' . $product_id;
$data = array();
$data['value'] = $product_id;
$data['label'] = $product_id_display . $product_title_display . $product_sku_display;
return ! empty( $data ) ? $data : false;
}
return false;
}
return false;
}
/**
* Return ID of product by provided SKU of product.
* @param $query
*
* @return bool
* @since 4.4
*
*/
public function productIdDefaultValueFromSkuToId( $query ) {
$result = $this->productIdAutocompleteSuggesterExactSku( $query );
return isset( $result['value'] ) ? $result['value'] : false;
}
/**
* Find product by SKU
* @param $query
*
* @return bool|array
* @since 4.4
*
*/
public function productIdAutocompleteSuggesterExactSku( $query ) {
global $wpdb;
$query = trim( $query );
$product_id = $wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key='_sku' AND meta_value='%s' LIMIT 1", stripslashes( $query ) ) );
$product_data = get_post( $product_id );
if ( 'product' !== $product_data->post_type ) {
return '';
}
$product_object = wc_get_product( $product_data );
if ( is_object( $product_object ) ) {
$product_sku = $product_object->get_sku();
$product_title = $product_object->get_title();
$product_id = $product_object->get_id();
$product_sku_display = '';
if ( ! empty( $product_sku ) ) {
$product_sku_display = ' - ' . esc_html__( 'Sku', 'js_composer' ) . ': ' . $product_sku;
}
$product_title_display = '';
if ( ! empty( $product_title ) ) {
$product_title_display = ' - ' . esc_html__( 'Title', 'js_composer' ) . ': ' . $product_title;
}
$product_id_display = esc_html__( 'Id', 'js_composer' ) . ': ' . $product_id;
$data = array();
$data['value'] = $product_id;
$data['label'] = $product_id_display . $product_title_display . $product_sku_display;
return ! empty( $data ) ? $data : false;
}
return false;
}
/**
* Autocomplete suggester to search product category by name/slug or id.
* @param $query
* @param bool $slug - determines what output is needed
* default false - return id of product category
* true - return slug of product category
*
* @return array
* @since 4.4
*
*/
public function productCategoryCategoryAutocompleteSuggester( $query, $slug = false ) {
global $wpdb;
$cat_id = (int) $query;
$query = trim( $query );
$post_meta_infos = $wpdb->get_results( $wpdb->prepare( "SELECT a.term_id AS id, b.name as name, b.slug AS slug
FROM {$wpdb->term_taxonomy} AS a
INNER JOIN {$wpdb->terms} AS b ON b.term_id = a.term_id
WHERE a.taxonomy = 'product_cat' AND (a.term_id = '%d' OR b.slug LIKE '%%%s%%' OR b.name LIKE '%%%s%%' )", $cat_id > 0 ? $cat_id : - 1, stripslashes( $query ), stripslashes( $query ) ), ARRAY_A );
$result = array();
if ( is_array( $post_meta_infos ) && ! empty( $post_meta_infos ) ) {
foreach ( $post_meta_infos as $value ) {
$data = array();
$data['value'] = $slug ? $value['slug'] : $value['id'];
$data['label'] = esc_html__( 'Id', 'js_composer' ) . ': ' . $value['id'] . ( ( strlen( $value['name'] ) > 0 ) ? ' - ' . esc_html__( 'Name', 'js_composer' ) . ': ' . $value['name'] : '' ) . ( ( strlen( $value['slug'] ) > 0 ) ? ' - ' . esc_html__( 'Slug', 'js_composer' ) . ': ' . $value['slug'] : '' );
$result[] = $data;
}
}
return $result;
}
/**
* Search product category by id
* @param $query
*
* @return bool|array
* @since 4.4
*
*/
public function productCategoryCategoryRenderByIdExact( $query ) {
$query = $query['value'];
$cat_id = (int) $query;
$term = get_term( $cat_id, 'product_cat' );
return $this->productCategoryTermOutput( $term );
}
/**
* Suggester for autocomplete to find product category by id/name/slug but return found product category SLUG
* @param $query
*
* @return array - slug of products categories.
* @since 4.4
*
*/
public function productCategoryCategoryAutocompleteSuggesterBySlug( $query ) {
$result = $this->productCategoryCategoryAutocompleteSuggester( $query, true );
return $result;
}
/**
* Search product category by slug.
* @param $query
*
* @return bool|array
* @since 4.4
*
*/
public function productCategoryCategoryRenderBySlugExact( $query ) {
$query = $query['value'];
$query = trim( $query );
$term = get_term_by( 'slug', $query, 'product_cat' );
return $this->productCategoryTermOutput( $term );
}
/**
* Return product category value|label array
*
* @param $term
*
* @return array|bool
* @since 4.4
*/
protected function productCategoryTermOutput( $term ) {
$term_slug = $term->slug;
$term_title = $term->name;
$term_id = $term->term_id;
$term_slug_display = '';
if ( ! empty( $term_slug ) ) {
$term_slug_display = ' - ' . esc_html__( 'Sku', 'js_composer' ) . ': ' . $term_slug;
}
$term_title_display = '';
if ( ! empty( $term_title ) ) {
$term_title_display = ' - ' . esc_html__( 'Title', 'js_composer' ) . ': ' . $term_title;
}
$term_id_display = esc_html__( 'Id', 'js_composer' ) . ': ' . $term_id;
$data = array();
$data['value'] = $term_id;
$data['label'] = $term_id_display . $term_title_display . $term_slug_display;
return ! empty( $data ) ? $data : false;
}
/**
* @return array
*/
/**
* @return array
*/
public static function getProductsFieldsList() {
return array(
esc_html__( 'SKU', 'js_composer' ) => 'sku',
esc_html__( 'ID', 'js_composer' ) => 'id',
esc_html__( 'Price', 'js_composer' ) => 'price',
esc_html__( 'Regular Price', 'js_composer' ) => 'regular_price',
esc_html__( 'Sale Price', 'js_composer' ) => 'sale_price',
esc_html__( 'Price html', 'js_composer' ) => 'price_html',
esc_html__( 'Reviews count', 'js_composer' ) => 'reviews_count',
esc_html__( 'Short description', 'js_composer' ) => 'short_description',
esc_html__( 'Dimensions', 'js_composer' ) => 'dimensions',
esc_html__( 'Rating count', 'js_composer' ) => 'rating_count',
esc_html__( 'Weight', 'js_composer' ) => 'weight',
esc_html__( 'Is on sale', 'js_composer' ) => 'on_sale',
esc_html__( 'Custom field', 'js_composer' ) => '_custom_',
);
}
/**
* @param $key
* @return string
*/
/**
* @param $key
* @return string
*/
public static function getProductFieldLabel( $key ) {
if ( false === self::$product_fields_list ) {
self::$product_fields_list = array_flip( self::getProductsFieldsList() );
}
return isset( self::$product_fields_list[ $key ] ) ? self::$product_fields_list[ $key ] : '';
}
/**
* @return array
*/
/**
* @return array
*/
public static function getOrderFieldsList() {
return array(
esc_html__( 'ID', 'js_composer' ) => 'id',
esc_html__( 'Order number', 'js_composer' ) => 'order_number',
esc_html__( 'Currency', 'js_composer' ) => 'order_currency',
esc_html__( 'Total', 'js_composer' ) => 'total',
esc_html__( 'Status', 'js_composer' ) => 'status',
esc_html__( 'Payment method', 'js_composer' ) => 'payment_method',
esc_html__( 'Billing address city', 'js_composer' ) => 'billing_address_city',
esc_html__( 'Billing address country', 'js_composer' ) => 'billing_address_country',
esc_html__( 'Shipping address city', 'js_composer' ) => 'shipping_address_city',
esc_html__( 'Shipping address country', 'js_composer' ) => 'shipping_address_country',
esc_html__( 'Customer Note', 'js_composer' ) => 'customer_note',
esc_html__( 'Customer API', 'js_composer' ) => 'customer_api',
esc_html__( 'Custom field', 'js_composer' ) => '_custom_',
);
}
/**
* @param $key
* @return string
*/
/**
* @param $key
* @return string
*/
public static function getOrderFieldLabel( $key ) {
if ( false === self::$order_fields_list ) {
self::$order_fields_list = array_flip( self::getOrderFieldsList() );
}
return isset( self::$order_fields_list[ $key ] ) ? self::$order_fields_list[ $key ] : '';
}
public function yoastSeoCompatibility() {
if ( function_exists( 'WC' ) ) {
// WC()->frontend_includes();
include_once( WC()->plugin_path() . '/includes/wc-template-functions.php' );
// include_once WC()->plugin_path() . '';
}
}
}
/**
* Removes EDIT button in backend and frontend editor
* Class Vc_WooCommerce_NotEditable
* @since 4.4
*/
class Vc_WooCommerce_NotEditable extends WPBakeryShortCode {
/**
* @since 4.4
* @var array
*/
protected $controls_list = array(
'clone',
'delete',
);
}
|
mit
|
rkq/cxxexp
|
third-party/src/boost_1_56_0/doc/html/boost/posix_time/operator-__idp106693728.html
|
4591
|
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Function operator-=</title>
<link rel="stylesheet" href="../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1">
<link rel="home" href="../../index.html" title="The Boost C++ Libraries BoostBook Documentation Subset">
<link rel="up" href="../../date_time/doxy.html#header.boost.date_time.posix_time.date_duration_operators_hpp" title="Header <boost/date_time/posix_time/date_duration_operators.hpp>">
<link rel="prev" href="operator-_idp106690336.html" title="Function operator-">
<link rel="next" href="operator__idp106696960.html" title="Function operator+">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../boost.png"></td>
<td align="center"><a href="../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="operator-_idp106690336.html"><img src="../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../date_time/doxy.html#header.boost.date_time.posix_time.date_duration_operators_hpp"><img src="../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="operator__idp106696960.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="refentry">
<a name="boost.posix_time.operator-=_idp106693728"></a><div class="titlepage"></div>
<div class="refnamediv">
<h2><span class="refentrytitle">Function operator-=</span></h2>
<p>boost::posix_time::operator-=</p>
</div>
<h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2>
<div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: <<a class="link" href="../../date_time/doxy.html#header.boost.date_time.posix_time.date_duration_operators_hpp" title="Header <boost/date_time/posix_time/date_duration_operators.hpp>">boost/date_time/posix_time/date_duration_operators.hpp</a>>
</span>
<a class="link" href="ptime.html" title="Class ptime">ptime</a> <span class="keyword">operator</span><span class="special">-=</span><span class="special">(</span><a class="link" href="ptime.html" title="Class ptime">ptime</a> <span class="special">&</span> t<span class="special">,</span> <span class="keyword">const</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">gregorian</span><span class="special">::</span><span class="identifier">months</span> <span class="special">&</span> m<span class="special">)</span><span class="special">;</span></pre></div>
<div class="refsect1">
<a name="idp208022320"></a><h2>Description</h2>
<p>Subtracts a months object from a ptime. Result will be same day-of-month as ptime unless original day was the last day of month. see date_time::months_duration for more details </p>
</div>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2001-2005 CrystalClear Software, Inc<p>Subject to the Boost Software License, Version 1.0. (See accompanying file
<code class="filename">LICENSE_1_0.txt</code> or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="operator-_idp106690336.html"><img src="../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../date_time/doxy.html#header.boost.date_time.posix_time.date_duration_operators_hpp"><img src="../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="operator__idp106696960.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
|
mit
|
ccwang002/2014-ggplot2-intro
|
DRAFT.md
|
48
|
## Specs
- Max 25 mins, recommended 15-20 mins
|
mit
|
LazyTarget/ProcHelper
|
src/Remotus.Base/Observables/DelegateObserver.cs
|
1134
|
using System;
using System.Threading;
namespace Remotus.Base.Observables
{
public sealed class DelegateObserver<T> : IObserver<T>, IDisposable
{
private readonly Action _onCompleted;
private readonly Action<Exception> _onError;
private readonly Action<T> _onNext;
private int _isStopped;
public DelegateObserver(Action<T> onNext, Action<Exception> onError = null, Action onCompleted = null)
{
_onNext = onNext;
_onError = onError;
_onCompleted = onCompleted;
}
public void OnNext(T value)
{
if (_isStopped == 0)
_onNext?.Invoke(value);
}
public void OnError(Exception error)
{
if (Interlocked.Exchange(ref _isStopped, 1) == 0)
_onError?.Invoke(error);
}
public void OnCompleted()
{
if (Interlocked.Exchange(ref _isStopped, 1) == 0)
_onCompleted?.Invoke();
}
public void Dispose()
{
Interlocked.Exchange(ref _isStopped, 1);
}
}
}
|
mit
|
ericholscher/pinax
|
pinax/apps/topics/urls.py
|
399
|
from django.conf.urls.defaults import *
urlpatterns = patterns('',
url(r'^$', 'topics.views.topics', name="topic_list"),
url(r'^(?P<topic_id>\d+)/edit/$', 'topics.views.topic', kwargs={"edit": True}, name="topic_edit"),
url(r'^(?P<topic_id>\d+)/delete/$', 'topics.views.topic_delete', name="topic_delete"),
url(r'^(?P<topic_id>\d+)/$', 'topics.views.topic', name="topic_detail"),
)
|
mit
|
abock/roslyn
|
src/VisualStudio/Core/Def/Implementation/TaskList/ExternalErrorDiagnosticUpdateSource.cs
|
31502
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.ComponentModel.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.CodeAnalysis.Shared.Options;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.SolutionCrawler;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.TaskList
{
internal sealed class ExternalErrorDiagnosticUpdateSource : IDiagnosticUpdateSource
{
private readonly Workspace _workspace;
private readonly IDiagnosticAnalyzerService _diagnosticService;
private readonly IGlobalOperationNotificationService _notificationService;
private readonly SimpleTaskQueue _taskQueue;
private readonly IAsynchronousOperationListener _listener;
private readonly object _gate = new object();
private InProgressState _stateDoNotAccessDirectly = null;
private ImmutableArray<DiagnosticData> _lastBuiltResult = ImmutableArray<DiagnosticData>.Empty;
public ExternalErrorDiagnosticUpdateSource(
VisualStudioWorkspace workspace,
IDiagnosticAnalyzerService diagnosticService,
IDiagnosticUpdateSourceRegistrationService registrationService,
IAsynchronousOperationListenerProvider listenerProvider)
: this(workspace, diagnosticService, listenerProvider.GetListener(FeatureAttribute.ErrorList))
{
registrationService.Register(this);
}
/// <summary>
/// internal for testing
/// </summary>
internal ExternalErrorDiagnosticUpdateSource(
Workspace workspace,
IDiagnosticAnalyzerService diagnosticService,
IAsynchronousOperationListener listener)
{
// use queue to serialize work. no lock needed
_taskQueue = new SimpleTaskQueue(TaskScheduler.Default);
_listener = listener;
_workspace = workspace;
_workspace.WorkspaceChanged += OnWorkspaceChanged;
_diagnosticService = diagnosticService;
_notificationService = _workspace.Services.GetService<IGlobalOperationNotificationService>();
}
public event EventHandler<BuildProgress> BuildProgressChanged;
public event EventHandler<DiagnosticsUpdatedArgs> DiagnosticsUpdated;
public event EventHandler DiagnosticsCleared { add { } remove { } }
public bool IsInProgress => BuildInprogressState != null;
public ImmutableArray<DiagnosticData> GetBuildErrors()
{
return _lastBuiltResult;
}
public bool IsSupportedDiagnosticId(ProjectId projectId, string id)
{
return BuildInprogressState?.IsSupportedDiagnosticId(projectId, id) ?? false;
}
public void ClearErrors(ProjectId projectId)
{
// capture state if it exists
var state = BuildInprogressState;
var asyncToken = _listener.BeginAsyncOperation("ClearErrors");
_taskQueue.ScheduleTask(() =>
{
// this will get called if the project is actually built by "build" command.
// we track what project has been built, so that later we can clear any stale live errors
// if build give us no errors for this project
state?.Built(projectId);
ClearProjectErrors(state?.Solution ?? _workspace.CurrentSolution, projectId);
}).CompletesAsyncOperation(asyncToken);
}
private void OnWorkspaceChanged(object sender, WorkspaceChangeEventArgs e)
{
switch (e.Kind)
{
case WorkspaceChangeKind.SolutionAdded:
case WorkspaceChangeKind.SolutionRemoved:
case WorkspaceChangeKind.SolutionCleared:
case WorkspaceChangeKind.SolutionReloaded:
{
var asyncToken = _listener.BeginAsyncOperation("OnSolutionChanged");
_taskQueue.ScheduleTask(() => e.OldSolution.ProjectIds.Do(p => ClearProjectErrors(e.OldSolution, p))).CompletesAsyncOperation(asyncToken);
break;
}
case WorkspaceChangeKind.ProjectRemoved:
case WorkspaceChangeKind.ProjectReloaded:
{
var asyncToken = _listener.BeginAsyncOperation("OnProjectChanged");
_taskQueue.ScheduleTask(() => ClearProjectErrors(e.OldSolution, e.ProjectId)).CompletesAsyncOperation(asyncToken);
break;
}
case WorkspaceChangeKind.DocumentRemoved:
case WorkspaceChangeKind.DocumentReloaded:
{
var asyncToken = _listener.BeginAsyncOperation("OnDocumentRemoved");
_taskQueue.ScheduleTask(() => ClearDocumentErrors(e.OldSolution, e.ProjectId, e.DocumentId)).CompletesAsyncOperation(asyncToken);
break;
}
case WorkspaceChangeKind.ProjectAdded:
case WorkspaceChangeKind.DocumentAdded:
case WorkspaceChangeKind.DocumentChanged:
case WorkspaceChangeKind.ProjectChanged:
case WorkspaceChangeKind.SolutionChanged:
case WorkspaceChangeKind.AdditionalDocumentAdded:
case WorkspaceChangeKind.AdditionalDocumentRemoved:
case WorkspaceChangeKind.AdditionalDocumentReloaded:
case WorkspaceChangeKind.AdditionalDocumentChanged:
case WorkspaceChangeKind.AnalyzerConfigDocumentAdded:
case WorkspaceChangeKind.AnalyzerConfigDocumentRemoved:
case WorkspaceChangeKind.AnalyzerConfigDocumentChanged:
case WorkspaceChangeKind.AnalyzerConfigDocumentReloaded:
break;
default:
Contract.Fail("Unknown workspace events");
break;
}
}
internal void OnSolutionBuildStarted()
{
// build just started, create the state and fire build in progress event.
// build just started, create the state and fire build in progress event.
_ = GetOrCreateInProgressState();
}
internal void OnSolutionBuildCompleted()
{
// building is done. reset the state
// and get local copy of in-progress state
var inProgressState = ClearInProgressState();
// enqueue build/live sync in the queue.
var asyncToken = _listener.BeginAsyncOperation("OnSolutionBuild");
_taskQueue.ScheduleTask(async () =>
{
// nothing to do
if (inProgressState == null)
{
return;
}
// explicitly start solution crawler if it didn't start yet. since solution crawler is lazy,
// user might have built solution before workspace fires its first event yet (which is when solution crawler is initialized)
// here we give initializeLazily: false so that solution crawler is fully initialized when we do de-dup live and build errors,
// otherwise, we will think none of error we have here belong to live errors since diagnostic service is not initialized yet.
var registrationService = (SolutionCrawlerRegistrationService)_workspace.Services.GetService<ISolutionCrawlerRegistrationService>();
registrationService.EnsureRegistration(_workspace, initializeLazily: false);
_lastBuiltResult = inProgressState.GetBuildDiagnostics();
// we are about to update live analyzer data using one from build.
// pause live analyzer
using var operation = _notificationService.Start("BuildDone");
if (_diagnosticService is DiagnosticAnalyzerService diagnosticService)
{
await CleanupAllLiveErrorsAsync(diagnosticService, inProgressState.GetProjectsWithoutErrors()).ConfigureAwait(false);
await SyncBuildErrorsAndReportAsync(diagnosticService, inProgressState).ConfigureAwait(false);
}
inProgressState.Done();
}).CompletesAsyncOperation(asyncToken);
}
private Task CleanupAllLiveErrorsAsync(DiagnosticAnalyzerService diagnosticService, IEnumerable<ProjectId> projects)
{
var map = projects.ToImmutableDictionary(p => p, _ => ImmutableArray<DiagnosticData>.Empty);
return diagnosticService.SynchronizeWithBuildAsync(_workspace, map);
}
private async Task SyncBuildErrorsAndReportAsync(DiagnosticAnalyzerService diagnosticService, InProgressState inProgressState)
{
var solution = inProgressState.Solution;
var map = await inProgressState.GetLiveDiagnosticsPerProjectAsync().ConfigureAwait(false);
// make those errors live errors
await diagnosticService.SynchronizeWithBuildAsync(_workspace, map).ConfigureAwait(false);
// raise events for ones left-out
var buildErrors = GetBuildErrors().Except(map.Values.SelectMany(v => v)).GroupBy(k => k.DocumentId);
foreach (var group in buildErrors)
{
if (group.Key == null)
{
foreach (var projectGroup in group.GroupBy(g => g.ProjectId))
{
Contract.ThrowIfNull(projectGroup.Key);
ReportBuildErrors(projectGroup.Key, solution, projectGroup.ToImmutableArray());
}
continue;
}
ReportBuildErrors(group.Key, solution, group.ToImmutableArray());
}
}
private void ReportBuildErrors<T>(T item, Solution solution, ImmutableArray<DiagnosticData> buildErrors)
{
if (item is ProjectId projectId)
{
RaiseDiagnosticsCreated(projectId, solution, projectId, null, buildErrors);
return;
}
// must be not null
var documentId = item as DocumentId;
RaiseDiagnosticsCreated(documentId, solution, documentId.ProjectId, documentId, buildErrors);
}
private void ClearProjectErrors(Solution solution, ProjectId projectId)
{
// remove all project errors
RaiseDiagnosticsRemoved(projectId, solution, projectId, documentId: null);
var project = solution.GetProject(projectId);
if (project == null)
{
return;
}
// remove all document errors
foreach (var documentId in project.DocumentIds)
{
ClearDocumentErrors(solution, projectId, documentId);
}
}
private void ClearDocumentErrors(Solution solution, ProjectId projectId, DocumentId documentId)
{
RaiseDiagnosticsRemoved(documentId, solution, projectId, documentId);
}
public void AddNewErrors(ProjectId projectId, DiagnosticData diagnostic)
{
// capture state that will be processed in background thread.
var state = GetOrCreateInProgressState();
var asyncToken = _listener.BeginAsyncOperation("Project New Errors");
_taskQueue.ScheduleTask(() =>
{
state.AddError(projectId, diagnostic);
}).CompletesAsyncOperation(asyncToken);
}
public void AddNewErrors(DocumentId documentId, DiagnosticData diagnostic)
{
// capture state that will be processed in background thread.
var state = GetOrCreateInProgressState();
var asyncToken = _listener.BeginAsyncOperation("Document New Errors");
_taskQueue.ScheduleTask(() =>
{
state.AddError(documentId, diagnostic);
}).CompletesAsyncOperation(asyncToken);
}
public void AddNewErrors(
ProjectId projectId, HashSet<DiagnosticData> projectErrors, Dictionary<DocumentId, HashSet<DiagnosticData>> documentErrorMap)
{
// capture state that will be processed in background thread
var state = GetOrCreateInProgressState();
var asyncToken = _listener.BeginAsyncOperation("Project New Errors");
_taskQueue.ScheduleTask(() =>
{
foreach (var kv in documentErrorMap)
{
state.AddErrors(kv.Key, kv.Value);
}
state.AddErrors(projectId, projectErrors);
}).CompletesAsyncOperation(asyncToken);
}
private InProgressState BuildInprogressState
{
get
{
lock (_gate)
{
return _stateDoNotAccessDirectly;
}
}
}
private InProgressState ClearInProgressState()
{
lock (_gate)
{
var state = _stateDoNotAccessDirectly;
_stateDoNotAccessDirectly = null;
return state;
}
}
private InProgressState GetOrCreateInProgressState()
{
lock (_gate)
{
if (_stateDoNotAccessDirectly == null)
{
// here, we take current snapshot of solution when the state is first created. and through out this code, we use this snapshot.
// since we have no idea what actual snapshot of solution the out of proc build has picked up, it doesn't remove the race we can have
// between build and diagnostic service, but this at least make us to consistent inside of our code.
_stateDoNotAccessDirectly = new InProgressState(this, _workspace.CurrentSolution);
}
return _stateDoNotAccessDirectly;
}
}
private void RaiseDiagnosticsCreated(object id, Solution solution, ProjectId projectId, DocumentId documentId, ImmutableArray<DiagnosticData> items)
{
DiagnosticsUpdated?.Invoke(this, DiagnosticsUpdatedArgs.DiagnosticsCreated(
CreateArgumentKey(id), _workspace, solution, projectId, documentId, items));
}
private void RaiseDiagnosticsRemoved(object id, Solution solution, ProjectId projectId, DocumentId documentId)
{
DiagnosticsUpdated?.Invoke(this, DiagnosticsUpdatedArgs.DiagnosticsRemoved(
CreateArgumentKey(id), _workspace, solution, projectId, documentId));
}
private static ArgumentKey CreateArgumentKey(object id) => new ArgumentKey(id);
private void RaiseBuildProgressChanged(BuildProgress progress)
{
BuildProgressChanged?.Invoke(this, progress);
}
#region not supported
public bool SupportGetDiagnostics { get { return false; } }
public ImmutableArray<DiagnosticData> GetDiagnostics(
Workspace workspace, ProjectId projectId, DocumentId documentId, object id, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default)
{
return ImmutableArray<DiagnosticData>.Empty;
}
#endregion
internal enum BuildProgress
{
Started,
Updated,
Done
}
private sealed class InProgressState
{
private int _incrementDoNotAccessDirectly = 0;
private readonly ExternalErrorDiagnosticUpdateSource _owner;
private readonly HashSet<ProjectId> _projectsBuilt = new HashSet<ProjectId>();
private readonly HashSet<ProjectId> _projectsWithErrors = new HashSet<ProjectId>();
private readonly Dictionary<ProjectId, ImmutableHashSet<string>> _allDiagnosticIdMap = new Dictionary<ProjectId, ImmutableHashSet<string>>();
private readonly Dictionary<ProjectId, ImmutableHashSet<string>> _liveDiagnosticIdMap = new Dictionary<ProjectId, ImmutableHashSet<string>>();
private readonly Dictionary<ProjectId, Dictionary<DiagnosticData, int>> _projectMap = new Dictionary<ProjectId, Dictionary<DiagnosticData, int>>();
private readonly Dictionary<DocumentId, Dictionary<DiagnosticData, int>> _documentMap = new Dictionary<DocumentId, Dictionary<DiagnosticData, int>>();
public InProgressState(ExternalErrorDiagnosticUpdateSource owner, Solution solution)
{
_owner = owner;
Solution = solution;
// let people know build has started
_owner.RaiseBuildProgressChanged(BuildProgress.Started);
}
public Solution Solution { get; }
public void Done()
{
_owner.RaiseBuildProgressChanged(BuildProgress.Done);
}
public bool IsSupportedDiagnosticId(ProjectId projectId, string id)
{
lock (_allDiagnosticIdMap)
{
if (_allDiagnosticIdMap.TryGetValue(projectId, out var ids))
{
return ids.Contains(id);
}
var project = Solution.GetProject(projectId);
if (project == null)
{
// projectId no longer exist, return false;
_allDiagnosticIdMap.Add(projectId, ImmutableHashSet<string>.Empty);
return false;
}
// set ids set
var builder = ImmutableHashSet.CreateBuilder<string>();
var descriptorMap = _owner._diagnosticService.AnalyzerInfoCache.GetDiagnosticDescriptorsPerReference(project);
builder.UnionWith(descriptorMap.Values.SelectMany(v => v.Select(d => d.Id)));
var set = builder.ToImmutable();
_allDiagnosticIdMap.Add(projectId, set);
return set.Contains(id);
}
}
public ImmutableArray<DiagnosticData> GetBuildDiagnostics()
{
// return errors in the order that is reported
return ImmutableArray.CreateRange(
_projectMap.Values.SelectMany(d => d).Concat(_documentMap.Values.SelectMany(d => d)).OrderBy(kv => kv.Value).Select(kv => kv.Key));
}
public void Built(ProjectId projectId)
{
_projectsBuilt.Add(projectId);
}
public IEnumerable<ProjectId> GetProjectsWithErrors()
{
// filter out project that is no longer exist in IDE
// this can happen if user started a "build" and then remove a project from IDE
// before build finishes
return _projectsWithErrors.Where(p => Solution.GetProject(p) != null);
}
public IEnumerable<ProjectId> GetProjectsWithoutErrors()
{
return GetProjectsBuilt().Except(GetProjectsWithErrors());
IEnumerable<ProjectId> GetProjectsBuilt()
{
// filter out project that is no longer exist in IDE
// this can happen if user started a "build" and then remove a project from IDE
// before build finishes
return Solution.ProjectIds.Where(p => _projectsBuilt.Contains(p));
}
}
public async Task<ImmutableDictionary<ProjectId, ImmutableArray<DiagnosticData>>> GetLiveDiagnosticsPerProjectAsync()
{
var builder = ImmutableDictionary.CreateBuilder<ProjectId, ImmutableArray<DiagnosticData>>();
foreach (var projectId in GetProjectsWithErrors())
{
var project = Solution.GetProject(projectId);
var compilation = project.SupportsCompilation ?
await project.GetCompilationAsync(CancellationToken.None).ConfigureAwait(false) : null;
var diagnostics = ImmutableArray.CreateRange(
_projectMap.Where(kv => kv.Key == projectId).SelectMany(kv => kv.Value).Concat(
_documentMap.Where(kv => kv.Key.ProjectId == projectId).SelectMany(kv => kv.Value))
.Select(kv => kv.Key).Where(d => IsLive(project, compilation, d)));
builder.Add(projectId, diagnostics);
}
return builder.ToImmutable();
}
public void AddErrors(DocumentId key, HashSet<DiagnosticData> diagnostics)
{
AddErrors(_documentMap, key, diagnostics);
}
public void AddErrors(ProjectId key, HashSet<DiagnosticData> diagnostics)
{
AddErrors(_projectMap, key, diagnostics);
}
public void AddError(DocumentId key, DiagnosticData diagnostic)
{
AddError(_documentMap, key, diagnostic);
}
public void AddError(ProjectId key, DiagnosticData diagnostic)
{
AddError(_projectMap, key, diagnostic);
}
private bool IsLive(Project project, Compilation compilation, DiagnosticData diagnosticData)
{
// REVIEW: current design is that we special case compiler analyzer case and we accept only document level
// diagnostic as live. otherwise, we let them be build errors. we changed compiler analyzer accordingly as well
// so that it doesn't report project level diagnostic as live errors.
if (_owner._diagnosticService.AnalyzerInfoCache.IsCompilerDiagnostic(project.Language, diagnosticData) &&
!IsDocumentLevelDiagnostic(diagnosticData))
{
// compiler error but project level error
return false;
}
if (SupportedLiveDiagnosticId(project, compilation, diagnosticData.Id))
{
return true;
}
return false;
static bool IsDocumentLevelDiagnostic(DiagnosticData diagnoaticData)
{
if (diagnoaticData.DocumentId != null)
{
return true;
}
// due to mapped file such as
//
// A.cs having
// #line 2 RandomeFile.txt
// ErrorHere
// #line default
//
// we can't simply say it is not document level diagnostic since
// file path is not part of solution. build output will just tell us
// mapped span not original span, so any code like above will not
// part of solution.
//
// but also we can't simply say it is a document level error because it has file path
// since project level error can have a file path pointing to a file such as dll
// , pdb, embedded files and etc.
//
// unfortunately, there is no 100% correct way to do this.
// so we will use a heuristic that will most likely work for most of common cases.
return !string.IsNullOrEmpty(diagnoaticData.DataLocation.OriginalFilePath) &&
(diagnoaticData.DataLocation.OriginalStartLine > 0 ||
diagnoaticData.DataLocation.OriginalStartColumn > 0);
}
}
private bool SupportedLiveDiagnosticId(Project project, Compilation compilation, string id)
{
var projectId = project.Id;
lock (_liveDiagnosticIdMap)
{
if (_liveDiagnosticIdMap.TryGetValue(projectId, out var ids))
{
return ids.Contains(id);
}
var fullSolutionAnalysis = SolutionCrawlerOptions.GetBackgroundAnalysisScope(project) == BackgroundAnalysisScope.FullSolution;
if (!project.SupportsCompilation || fullSolutionAnalysis)
{
return IsSupportedDiagnosticId(project.Id, id);
}
// set ids set
var builder = ImmutableHashSet.CreateBuilder<string>();
var diagnosticService = _owner._diagnosticService;
var infoCache = diagnosticService.AnalyzerInfoCache;
foreach (var analyzersPerReference in infoCache.CreateDiagnosticAnalyzersPerReference(project))
{
foreach (var analyzer in analyzersPerReference.Value)
{
if (diagnosticService.IsCompilationEndAnalyzer(analyzer, project, compilation))
{
continue;
}
var diagnosticIds = infoCache.GetDiagnosticDescriptors(analyzer).Select(d => d.Id);
builder.UnionWith(diagnosticIds);
}
}
var set = builder.ToImmutable();
_liveDiagnosticIdMap.Add(projectId, set);
return set.Contains(id);
}
}
private void AddErrors<T>(Dictionary<T, Dictionary<DiagnosticData, int>> map, T key, HashSet<DiagnosticData> diagnostics)
{
var errors = GetErrorSet(map, key);
foreach (var diagnostic in diagnostics)
{
AddError(errors, diagnostic, key);
}
}
private void AddError<T>(Dictionary<T, Dictionary<DiagnosticData, int>> map, T key, DiagnosticData diagnostic)
{
var errors = GetErrorSet(map, key);
AddError(errors, diagnostic, key);
}
private void AddError<T>(Dictionary<DiagnosticData, int> errors, DiagnosticData diagnostic, T key)
{
RecordProjectContainsErrors();
// add only new errors
if (!errors.TryGetValue(diagnostic, out _))
{
Logger.Log(FunctionId.ExternalErrorDiagnosticUpdateSource_AddError, d => d.ToString(), diagnostic);
errors.Add(diagnostic, GetNextIncrement());
}
int GetNextIncrement()
{
return _incrementDoNotAccessDirectly++;
}
void RecordProjectContainsErrors()
{
var projectId = (key is DocumentId documentId) ? documentId.ProjectId : (ProjectId)(object)key;
if (!_projectsWithErrors.Add(projectId))
{
return;
}
// this will make build only error list to be updated per project rather than per solution.
// basically this will make errors up to last project to show up in error list
_owner._lastBuiltResult = GetBuildDiagnostics();
_owner.RaiseBuildProgressChanged(BuildProgress.Updated);
}
}
private Dictionary<DiagnosticData, int> GetErrorSet<T>(Dictionary<T, Dictionary<DiagnosticData, int>> map, T key)
{
return map.GetOrAdd(key, _ => new Dictionary<DiagnosticData, int>(DiagnosticDataComparer.Instance));
}
}
private sealed class ArgumentKey : BuildToolId.Base<object>
{
public ArgumentKey(object key) : base(key)
{
}
public override string BuildTool
{
get { return PredefinedBuildTools.Build; }
}
public override bool Equals(object obj)
=> obj is ArgumentKey &&
base.Equals(obj);
public override int GetHashCode()
{
return base.GetHashCode();
}
}
private sealed class DiagnosticDataComparer : IEqualityComparer<DiagnosticData>
{
public static readonly DiagnosticDataComparer Instance = new DiagnosticDataComparer();
public bool Equals(DiagnosticData item1, DiagnosticData item2)
{
if ((item1.DocumentId == null) != (item2.DocumentId == null) ||
item1.Id != item2.Id ||
item1.ProjectId != item2.ProjectId ||
item1.Severity != item2.Severity ||
item1.Message != item2.Message ||
(item1.DataLocation?.MappedStartLine ?? 0) != (item2.DataLocation?.MappedStartLine ?? 0) ||
(item1.DataLocation?.MappedStartColumn ?? 0) != (item2.DataLocation?.MappedStartColumn ?? 0) ||
(item1.DataLocation?.OriginalStartLine ?? 0) != (item2.DataLocation?.OriginalStartLine ?? 0) ||
(item1.DataLocation?.OriginalStartColumn ?? 0) != (item2.DataLocation?.OriginalStartColumn ?? 0))
{
return false;
}
return (item1.DocumentId != null) ?
item1.DocumentId == item2.DocumentId :
item1.DataLocation?.OriginalFilePath == item2.DataLocation?.OriginalFilePath;
}
public int GetHashCode(DiagnosticData obj)
{
var result =
Hash.Combine(obj.Id,
Hash.Combine(obj.Message,
Hash.Combine(obj.ProjectId,
Hash.Combine(obj.DataLocation?.MappedStartLine ?? 0,
Hash.Combine(obj.DataLocation?.MappedStartColumn ?? 0,
Hash.Combine(obj.DataLocation?.OriginalStartLine ?? 0,
Hash.Combine(obj.DataLocation?.OriginalStartColumn ?? 0, (int)obj.Severity)))))));
return obj.DocumentId != null ?
Hash.Combine(obj.DocumentId, result) :
Hash.Combine(obj.DataLocation?.OriginalFilePath?.GetHashCode() ?? 0, result);
}
}
}
}
|
mit
|
vinzBad/checklost
|
main.go
|
965
|
package main
import (
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"html/template"
"log"
"net/http"
"os"
)
const (
addr = "127.0.0.1:8090"
)
var (
indexTemplate = template.Must(template.ParseFiles("index.html"))
tasks = []Task{
Task{1, "Learn golang", true},
Task{2, "Write webapp", true},
Task{3, "???", false},
Task{4, "Profit! $$$", false},
}
)
type Index struct {
Tasks []Task
Addr string
}
type Task struct {
Id uint64
Name string
Done bool
}
func index(w http.ResponseWriter, r *http.Request) {
indexTemplate.Execute(w, Index{tasks, addr})
}
func main() {
r := mux.NewRouter()
r.HandleFunc("/", index)
r.HandleFunc("/ws", serveWs)
static := http.StripPrefix("/static/", http.FileServer(http.Dir("./static/")))
r.PathPrefix("/static/").Handler(static)
go h.run()
logger := handlers.LoggingHandler(os.Stdout, r)
log.Println("Starting server on", addr)
log.Fatal(http.ListenAndServe(addr, logger))
}
|
mit
|
etewiah/property-web-builder
|
app/controllers/pwb/omniauth_controller.rb
|
520
|
module Pwb
class OmniauthController < ApplicationController
# https://github.com/plataformatec/devise/wiki/How-To:-OmniAuth-inside-localized-scope
def localized
# Just save the current locale in the session and redirect to the unscoped path as before
session[:omniauth_login_locale] = I18n.locale
# user_facebook_omniauth_authorize_path
# redirect_to user_omniauth_authorize_path(params[:provider])
redirect_to omniauth_authorize_path("user", params[:provider])
end
end
end
|
mit
|
alterway/component-workflow
|
src/Exception/MoreThanOneOpenTransitionException.php
|
264
|
<?php
namespace Alterway\Component\Workflow\Exception;
class MoreThanOneOpenTransitionException extends \LogicException
{
public function __construct()
{
return parent::__construct('More than one open transition with current context');
}
}
|
mit
|
YawLife/LIFE
|
html/ui/js/ats.js
|
6337
|
/**
* JS initialization and core functions for API test servlet
*
* @depends {3rdparty/jquery.js}
* @depends {3rdparty/bootstrap.js}
* @depends {3rdparty/highlight.pack.js}
*/
var ATS = (function(ATS, $, undefined) {
ATS.apiCalls = [];
ATS.selectedApiCalls = [];
ATS.init = function() {
hljs.initHighlightingOnLoad();
ATS.selectedApiCalls = ATS.setSelectedApiCalls();
ATS.selectedApiCallsChange();
$('#search').keyup(function(e) {
if (e.keyCode == 13) {
ATS.performSearch($(this).val());
}
});
$(".collapse-link").click(function(event) {
event.preventDefault();
});
$('#navi-show-open').click(function(e) {
$('.api-call-All').each(function() {
if($(this).find('.panel-collapse.in').length != 0) {
$(this).show();
} else {
$(this).hide();
}
});
$('#navi-show-all').css('font-weight', 'normal');
$(this).css('font-weight', 'bold');
e.preventDefault();
});
$('#navi-show-all').click(function(e) {
$('.api-call-All').show();
$('#navi-show-open').css('font-weight', 'normal');
$(this).css('font-weight', 'bold');
e.preventDefault();
});
$('.api-call-sel-ALL').change(function() {
if($(this).is(":checked")) {
ATS.addToSelected($(this));
} else {
ATS.removeFromSelected($(this));
}
});
$('#navi-select-all-d-add-btn').click(function(e) {
$.each($('.api-call-sel-ALL:visible:not(:checked)'), function(key, value) {
ATS.addToSelected($(value));
});
e.preventDefault();
});
$('#navi-select-all-d-replace-btn').click(function(e) {
ATS.selectedApiCalls = [];
$.each($('.api-call-sel-ALL:visible'), function(key, value) {
ATS.addToSelected($(value));
});
e.preventDefault();
});
$('#navi-deselect-all-d-btn').click(function(e) {
$.each($('.api-call-sel-ALL:visible'), function(key, value) {
ATS.removeFromSelected($(value));
});
e.preventDefault();
});
$('#navi-deselect-all-btn').click(function(e) {
ATS.selectedApiCalls = [];
$('.api-call-sel-ALL').prop('checked', false);
ATS.selectedApiCallsChange();
e.preventDefault();
});
}
ATS.performSearch = function(searchStr) {
if (searchStr == '') {
$('.api-call-All').show();
} else {
$('.api-call-All').hide();
$('.topic-link').css('font-weight', 'normal');
for(var i=0; i<ATS.apiCalls.length; i++) {
var apiCall = ATS.apiCalls[i];
if (new RegExp(searchStr.toLowerCase()).test(apiCall.toLowerCase())) {
$('#api-call-' + apiCall).show();
}
}
}
}
ATS.submitForm = function(form) {
var url = '/life';
var params = {};
for (i = 0; i < form.elements.length; i++) {
if (form.elements[i].type != 'button' && form.elements[i].value && form.elements[i].value != 'submit') {
var key = form.elements[i].name;
var value = form.elements[i].value;
if(key in params) {
var index = params[key].length;
params[key][index] = value;
} else {
params[key] = [value];
}
}
}
$.ajax({
url: url,
type: 'POST',
data: params,
traditional: true // "true" needed for duplicate params
})
.done(function(result) {
var resultStr = JSON.stringify(JSON.parse(result), null, 4);
var code_elem = form.getElementsByClassName("result")[0];
code_elem.textContent = resultStr;
hljs.highlightBlock(code_elem);
})
.error(function() {
alert('API not available, check if Life Server is running!');
});
if ($(form).has('.uri-link').length > 0) {
var uri = '/life?' + jQuery.param(params, true);
var html = '<a href="' + uri + '" target="_blank" style="font-size:12px;font-weight:normal;">Open GET URL</a>';
form.getElementsByClassName("uri-link")[0].innerHTML = html;
}
return false;
}
ATS.selectedApiCallsChange = function() {
var newUrl = '/test?requestTypes=' + encodeURIComponent(ATS.selectedApiCalls.join('_'));
$('#navi-selected').attr('href', newUrl);
$('#navi-selected').text('SELECTED (' + ATS.selectedApiCalls.length + ')');
ATS.setCookie('selected_api_calls', ATS.selectedApiCalls.join('_'), 30);
}
ATS.setSelectedApiCalls = function() {
var calls = [];
var getParam = ATS.getUrlParameter('requestTypes');
var cookieParam = ATS.getCookie('selected_api_calls');
if (getParam != undefined && getParam != '') {
calls=getParam.split('_');
} else if (cookieParam != undefined && cookieParam != ''){
calls=cookieParam.split('_');
}
for (var i=0; i<calls.length; i++) {
$('#api-call-sel-' + calls[i]).prop('checked', true);
}
return calls;
}
ATS.addToSelected = function(elem) {
var type=elem.attr('id').substr(13);
elem.prop('checked', true);
if($.inArray(type, ATS.selectedApiCalls) == -1) {
ATS.selectedApiCalls.push(type);
ATS.selectedApiCallsChange();
}
}
ATS.removeFromSelected = function(elem) {
var type=elem.attr('id').substr(13);
elem.prop('checked', false);
var index = ATS.selectedApiCalls.indexOf(type);
if (index > -1) {
ATS.selectedApiCalls.splice(index, 1);
ATS.selectedApiCallsChange();
}
}
return ATS;
}(ATS || {}, jQuery));
$(document).ready(function() {
ATS.init();
});
|
mit
|
yimingkuan/PhoneGapPluginDemo
|
www/file-filetransfer.html
|
2284
|
<!DOCTYPE html>
<html>
<head>
<title>file.fileTransfer</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script>
function getTitle() {
document.getElementById("ct").innerHTML = "DEMO: " + document.title;
}
</script>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for device API libraries to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// device APIs are available
//
function onDeviceReady() {
// Retrieve image file location from specified source
navigator.camera.getPicture(
uploadPhoto,
function(message) { alert('get picture failed'); },
{
quality : 50,
destinationType : navigator.camera.DestinationType.FILE_URI,
sourceType : navigator.camera.PictureSourceType.PHOTOLIBRARY
}
);
}
function uploadPhoto(imageURI) {
var options = new FileUploadOptions();
options.fileKey="file";
options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
var params = {};
params.value1 = "test";
params.value2 = "param";
options.params = params;
var ft = new FileTransfer();
ft.upload(imageURI, encodeURI("http://localhost/upload.php"), win, fail, options);
}
function win(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
}
function fail(error) {
alert("An error has occurred: Code = " + error.code);
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
}
</script>
</head>
<body onload="getTitle();">
<ul id="nav">
<li><a href="index.html">← Back</a></li>
<li><a href="#" id="ct" onclick="location.reload();"></a></li>
</ul>
<h1>Example</h1>
<p>Upload File</p>
</body>
</html>
|
mit
|
manonsys/MVC
|
libs/Jena/javadoc-core/org/apache/jena/graph/class-use/FrontsTriple.html
|
6573
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_66-internal) on Tue Dec 08 09:26:31 GMT 2015 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Interface org.apache.jena.graph.FrontsTriple (Apache Jena)</title>
<meta name="date" content="2015-12-08">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Interface org.apache.jena.graph.FrontsTriple (Apache Jena)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../org/apache/jena/graph/FrontsTriple.html" title="interface in org.apache.jena.graph">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/jena/graph/class-use/FrontsTriple.html" target="_top">Frames</a></li>
<li><a href="FrontsTriple.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Interface org.apache.jena.graph.FrontsTriple" class="title">Uses of Interface<br>org.apache.jena.graph.FrontsTriple</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../org/apache/jena/graph/FrontsTriple.html" title="interface in org.apache.jena.graph">FrontsTriple</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#org.apache.jena.rdf.model">org.apache.jena.rdf.model</a></td>
<td class="colLast">
<div class="block">A package for creating and manipulating RDF graphs.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="org.apache.jena.rdf.model">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../org/apache/jena/graph/FrontsTriple.html" title="interface in org.apache.jena.graph">FrontsTriple</a> in <a href="../../../../../org/apache/jena/rdf/model/package-summary.html">org.apache.jena.rdf.model</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing subinterfaces, and an explanation">
<caption><span>Subinterfaces of <a href="../../../../../org/apache/jena/graph/FrontsTriple.html" title="interface in org.apache.jena.graph">FrontsTriple</a> in <a href="../../../../../org/apache/jena/rdf/model/package-summary.html">org.apache.jena.rdf.model</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Interface and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>interface </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/apache/jena/rdf/model/Statement.html" title="interface in org.apache.jena.rdf.model">Statement</a></span></code>
<div class="block">An RDF Statement.</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../org/apache/jena/graph/FrontsTriple.html" title="interface in org.apache.jena.graph">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/jena/graph/class-use/FrontsTriple.html" target="_top">Frames</a></li>
<li><a href="FrontsTriple.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Licenced under the Apache License, Version 2.0</small></p>
</body>
</html>
|
mit
|
yahehe/Nancy.Swagger
|
samples/Nancy.Swagger.Autofac.Demo/AutofacBootstrapper.cs
|
1351
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices.ComTypes;
using System.Threading.Tasks;
using Autofac;
using Nancy.Bootstrapper;
using Nancy.Bootstrappers.Autofac;
using Nancy.Swagger.Annotations;
using Nancy.Swagger.Autofac.Demo.Modules;
using Nancy.Swagger.Services;
using Swagger.ObjectModel;
namespace Nancy.Swagger.Autofac.Demo
{
public class AutofacBootstrapper : AutofacNancyBootstrapper
{
public AutofacBootstrapper() : base()
{
}
protected override void ConfigureApplicationContainer(ILifetimeScope container)
{
SwaggerMetadataProvider.SetInfo("Nancy Swagger w/ AutoFac Example", "v0", "Our awesome service", new Contact()
{
EmailAddress = "exampleEmail@example.com"
});
SwaggerAnnotationsConfig.ShowOnlyAnnotatedRoutes = true;
this.ApplicationPipelines.AfterRequest.AddItemToEndOfPipeline(x => x.Response.Headers.Add("Access-Control-Allow-Origin", "*"));
this.ApplicationPipelines.AfterRequest.AddItemToEndOfPipeline(x => x.Response.Headers.Add("Access-Control-Allow-Headers", "*"));
this.ApplicationPipelines.AfterRequest.AddItemToEndOfPipeline(x => x.Response.Headers.Add("Access-Control-Allow-Methods", "*"));
}
}
}
|
mit
|
mandino/nu
|
wp-content/plugins/advanced-access-manager/Application/Core/Subject.php
|
7033
|
<?php
/**
* ======================================================================
* LICENSE: This file is subject to the terms and conditions defined in *
* file 'license.txt', which is part of this source code package. *
* ======================================================================
*/
/**
* Abstract subject
*
* @package AAM
* @author Vasyl Martyniuk <vasyl@vasyltech.com>
*/
abstract class AAM_Core_Subject {
/**
* Subject ID
*
* Whether it is User ID or Role ID
*
* @var string|int
*
* @access private
*/
private $_id;
/**
* WordPres Subject
*
* It can be WP_User or WP_Role, based on what class has been used
*
* @var WP_Role|WP_User
*
* @access private
*/
private $_subject;
/**
* List of Objects to be access controlled for current subject
*
* All access control objects like Admin Menu, Metaboxes, Posts etc
*
* @var array
*
* @access private
*/
private $_objects = array();
/**
* Constructor
*
* @param string|int $id
*
* @return void
*
* @access public
*/
public function __construct($id = '') {
//set subject
$this->setId($id);
//retrieve and set subject itself
$this->setSubject($this->retrieveSubject());
}
/**
* Trigger Subject native methods
*
* @param string $name
* @param array $args
*
* @return mixed
*
* @access public
*/
public function __call($name, $args) {
$subject = $this->getSubject();
//make sure that method is callable
if (method_exists($subject, $name)) {
$response = call_user_func_array(array($subject, $name), $args);
} else {
$response = null;
}
return $response;
}
/**
* Get Subject's native properties
*
* @param string $name
*
* @return mixed
*
* @access public
*/
public function __get($name) {
$subject = $this->getSubject();
return (!empty($subject->$name) ? $subject->$name : null);
}
/**
* Set Subject's native properties
*
* @param string $name
*
* @return mixed
*
* @access public
*/
public function __set($name, $value) {
$subject = $this->getSubject();
if ($subject) {
$subject->$name = $value;
}
}
/**
* Set Subject ID
*
* @param string|int
*
* @return void
*
* @access public
*/
public function setId($id) {
$this->_id = $id;
}
/**
* Get Subject ID
*
* @return string|int
*
* @access public
*/
public function getId() {
return $this->_id;
}
/**
* Get subject name
*
* @return string
*
* @access public
*/
public function getName() {
return '';
}
/**
*
* @return int
*/
public function getMaxLevel() {
return 0;
}
/**
* Get Subject
*
* @return WP_Role|WP_User
*
* @access public
*/
public function getSubject() {
return $this->_subject;
}
/**
* Set Subject
*
* @param WP_Role|WP_User $subject
*
* @return void
*
* @access public
*/
public function setSubject($subject) {
$this->_subject = $subject;
}
/**
* Get Individual Object
*
* @param string $type
* @param mixed $id
*
* @return AAM_Core_Object
*
* @access public
*/
public function getObject($type, $id = 'none', $param = null) {
$object = null;
//performance optimization
$id = (is_scalar($id) ? $id : 'none'); //prevent from any surprises
//check if there is an object with specified ID
if (!isset($this->_objects[$type][$id])) {
$classname = 'AAM_Core_Object_' . ucfirst($type);
if (class_exists($classname)) {
$object = new $classname($this, (is_null($param) ? $id : $param));
}
$object = apply_filters('aam-object-filter', $object, $type, $id, $this);
if (is_a($object, 'AAM_Core_Object')) {
$this->_objects[$type][$id] = $object;
}
} else {
$object = $this->_objects[$type][$id];
}
return $object;
}
/**
* Check if subject has capability
*
* @param string $capability
*
* @return boolean
*
* @access public
*/
public function hasCapability($capability) {
$subject = $this->getSubject();
return ($subject ? $subject->has_cap($capability) : false);
}
/**
* Save option
*
* @param string $param
* @param mixed $value
* @param string $object
* @param mixed $objectId
*
* @return boolean
*
* @access public
*/
public function save($param, $value, $object, $objectId = 0) {
return $this->getObject($object, $objectId)->save($param, $value);
}
/**
* Reset object
*
* @param string $object
*
* @return boolean
*
* @access public
*/
public function resetObject($object) {
return $this->deleteOption($object);
}
/**
* Delete option
*
* @param string $object
* @param mixed $id
*
* @return boolean
*
* @access public
*/
public function deleteOption($object, $id = 0) {
return AAM_Core_API::deleteOption($this->getOptionName($object, $id));
}
/**
* Retrieve list of subject's capabilities
*
* @return array
*
* @access public
*/
public function getCapabilities() {
return array();
}
/**
* Retrieve subject based on used class
*
* @return void
*
* @access protected
*/
protected function retrieveSubject() {
return null;
}
/**
*
*/
abstract public function getOptionName($object, $id);
/**
* Read object from parent subject
*
* @param string $object
* @param mixed $id
*
* @return mixed
*
* @access public
*/
public function inheritFromParent($object, $id = '', $param = null){
if ($subject = $this->getParent()){
$option = $subject->getObject($object, $id, $param)->getOption();
} else {
$option = null;
}
return $option;
}
/**
* Retrieve parent subject
*
* If there is no parent subject, return null
*
* @return AAM_Core_Subject|null
*
* @access public
*/
public function getParent() {
return null;
}
}
|
mit
|
marszczybrew/Diorite
|
DioriteCore/src/main/java/org/diorite/impl/connection/packets/play/server/PacketPlayServerResourcePackSend.java
|
2319
|
package org.diorite.impl.connection.packets.play.server;
import java.io.IOException;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.diorite.impl.connection.EnumProtocol;
import org.diorite.impl.connection.EnumProtocolDirection;
import org.diorite.impl.connection.packets.PacketClass;
import org.diorite.impl.connection.packets.PacketDataSerializer;
import org.diorite.impl.connection.packets.play.PacketPlayServerListener;
import org.diorite.impl.connection.packets.play.client.PacketPlayClientResourcePackStatus;
@PacketClass(id = 0x48, protocol = EnumProtocol.PLAY, direction = EnumProtocolDirection.CLIENTBOUND, size = 180)
public class PacketPlayServerResourcePackSend extends PacketPlayServer
{
private String url; // ~130 bytes
private String hash; // ~41 bytes
public PacketPlayServerResourcePackSend()
{
}
public PacketPlayServerResourcePackSend(final String url, final String hash)
{
if (hash.length() > PacketPlayClientResourcePackStatus.MAX_HASH_SIZE)
{
throw new IllegalArgumentException("Hash is too long (max 40, was " + hash.length() + ")");
}
this.url = url;
this.hash = hash;
}
public String getUrl()
{
return this.url;
}
public void setUrl(final String url)
{
this.url = url;
}
public String getHash()
{
return this.hash;
}
public void setHash(final String hash)
{
this.hash = hash;
}
@Override
public void readPacket(final PacketDataSerializer data) throws IOException
{
this.url = data.readText(Short.MAX_VALUE);
this.hash = data.readText(PacketPlayClientResourcePackStatus.MAX_HASH_SIZE);
}
@Override
public void writeFields(final PacketDataSerializer data) throws IOException
{
data.writeText(this.url);
data.writeText(this.hash);
}
@Override
public void handle(final PacketPlayServerListener listener)
{
listener.handle(this);
}
@Override
public String toString()
{
return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE).appendSuper(super.toString()).append("url", this.url).append("hash", this.hash).toString();
}
}
|
mit
|
michael-munoz/MooMooPlanet
|
Project455/Assets/Scripts/ShapeInfo.cs
|
145
|
using UnityEngine;
using System.Collections;
public class ShapeInfo
{
public int Column { get; set; }
public int Row { get; set; }
}
|
mit
|
sbt/sbt-assembly
|
src/sbt-test/shading/unmanagedjars/src/main/scala/toshade/ShadeClass.scala
|
33
|
package toshade
class ShadeClass
|
mit
|
selvasingh/azure-sdk-for-java
|
sdk/resourcemanager/azure-resourcemanager-trafficmanager/src/main/java/com/azure/resourcemanager/trafficmanager/implementation/TrafficManagerNestedProfileEndpointImpl.java
|
1325
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.resourcemanager.trafficmanager.implementation;
import com.azure.core.management.Region;
import com.azure.resourcemanager.resources.fluentcore.utils.ResourceManagerUtils;
import com.azure.resourcemanager.trafficmanager.fluent.EndpointsClient;
import com.azure.resourcemanager.trafficmanager.fluent.models.EndpointInner;
import com.azure.resourcemanager.trafficmanager.models.TrafficManagerNestedProfileEndpoint;
/** Implementation for {@link TrafficManagerNestedProfileEndpoint}. */
class TrafficManagerNestedProfileEndpointImpl extends TrafficManagerEndpointImpl
implements TrafficManagerNestedProfileEndpoint {
TrafficManagerNestedProfileEndpointImpl(
String name, TrafficManagerProfileImpl parent, EndpointInner inner, EndpointsClient client) {
super(name, parent, inner, client);
}
@Override
public String nestedProfileId() {
return innerModel().targetResourceId();
}
@Override
public long minimumChildEndpointCount() {
return ResourceManagerUtils.toPrimitiveLong(innerModel().minChildEndpoints());
}
@Override
public Region sourceTrafficLocation() {
return Region.fromName((innerModel().endpointLocation()));
}
}
|
mit
|
evgenypoyarkov/bodybuilder
|
lib/aggregations/terms-aggregation.js
|
1036
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _assign = require('lodash/assign');
var _assign2 = _interopRequireDefault(_assign);
exports.default = termsAggregation;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
/**
* Construct a Terms aggregation.
*
* @param {String} field Field name to aggregate over.
* @param {String} name Aggregation name. Defaults to agg_terms_<field>.
* @param {Object} opts Additional options to include in the aggregation.
* @return {Object} Terms aggregation.
*/
function termsAggregation(field, name, opts) {
name = name || 'agg_terms_' + field;
return _defineProperty({}, name, {
terms: function () {
return (0, _assign2.default)({ field: field }, opts);
}()
});
}
|
mit
|
braz/mojito-helloworld
|
node_modules/mojito/node_modules/yui/selector/selector.js
|
93
|
YUI.add('selector', function (Y, NAME) {
}, '3.10.3', {"requires": ["selector-native"]});
|
mit
|
AlejandroCano/framework
|
Signum.Test/LinqProvider/JoinGroupTest.cs
|
6007
|
using System.Linq;
using Xunit;
using Signum.Engine;
using Signum.Entities;
using Signum.Utilities;
using Signum.Test.Environment;
namespace Signum.Test.LinqProvider
{
/// <summary>
/// Summary description for LinqProvider
/// </summary>
public class JoinGroupTest
{
public JoinGroupTest()
{
MusicStarter.StartAndLoad();
Connector.CurrentLogger = new DebugTextWriter();
}
[Fact]
public void Join()
{
var songsAlbum = (from a in Database.Query<AlbumEntity>()
join b in Database.Query<AlbumEntity>().SelectMany(a => a.Songs) on a.Name equals b.Name
select new { a.Name, Label = a.Label.Name }).ToList();
}
[Fact]
public void JoinEntity()
{
var songsAlbum = (from a in Database.Query<ArtistEntity>()
join b in Database.Query<AlbumEntity>() on a equals b.Author
select new { Artist = a.Name, Album = b.Name }).ToList();
}
[Fact]
public void JoinEntityTwice()
{
var algums = (from a1 in Database.Query<AlbumEntity>()
join a2 in Database.Query<AlbumEntity>() on a1.Label equals a2.Label
join a3 in Database.Query<AlbumEntity>() on a2.Label equals a3.Label
select new { Name1 = a1.Name, Name2 = a2.Name, Name3 = a3.Name }).ToList();
}
[Fact]
public void JoinerExpansions()
{
var labels = Database.Query<AlbumEntity>().Join(
Database.Query<AlbumEntity>(),
a => a.Year, a => a.Year,
(a1, a2) => a1.Label.Name + " " + a2.Label.Name).ToList();
}
[Fact]
public void LeftOuterJoinEntity()
{
var songsAlbum = (from a in Database.Query<ArtistEntity>().DefaultIfEmpty()
join b in Database.Query<AlbumEntity>() on a equals b.Author
select new { Artist = a.Name, Album = b.Name }).ToList();
}
[Fact]
public void LeftOuterJoinEntityNotNull()
{
var songsAlbum = (from a in Database.Query<ArtistEntity>().DefaultIfEmpty()
join b in Database.Query<AlbumEntity>() on a equals b.Author
select new { Artist = a.Name, Album = b.Name, HasArtist = a != null }).ToList();
}
[Fact]
public void RightOuterJoinEntity()
{
var songsAlbum = (from a in Database.Query<ArtistEntity>()
join b in Database.Query<AlbumEntity>().DefaultIfEmpty() on a equals b.Author
select new { Artist = a.Name, Album = b.Name }).ToList();
}
[Fact]
public void RightOuterJoinEntityNotNull()
{
var songsAlbum = (from a in Database.Query<ArtistEntity>()
join b in Database.Query<AlbumEntity>().DefaultIfEmpty() on a equals b.Author
select new { Artist = a.Name, Album = b.Name, HasArtist = b != null }).ToList();
}
[Fact]
public void FullOuterJoinEntity()
{
var songsAlbum = (from a in Database.Query<ArtistEntity>().DefaultIfEmpty()
join b in Database.Query<AlbumEntity>().DefaultIfEmpty() on a equals b.Author
select new { Artist = a.Name, Album = b.Name }).ToList();
}
[Fact]
public void FullOuterJoinEntityNotNull()
{
var songsAlbum = (from a in Database.Query<ArtistEntity>().DefaultIfEmpty()
join b in Database.Query<AlbumEntity>().DefaultIfEmpty() on a equals b.Author
select new { Artist = a.Name, Album = b.Name, HasArtist = a != null, HasAlbum = b != null }).ToList();
}
[Fact]
public void JoinGroup()
{
var songsAlbum = (from a in Database.Query<ArtistEntity>()
join b in Database.Query<AlbumEntity>() on a equals b.Author into g
select new { a.Name, Albums = (int?)g.Count() }).ToList();
}
[Fact]
public void LeftOuterJoinGroup()
{
var songsAlbum = (from a in Database.Query<ArtistEntity>()
join b in Database.Query<AlbumEntity>().DefaultIfEmpty() on a equals b.Author into g
select new { a.Name, Albums = (int?)g.Count() }).ToList();
}
[TableName("#MyView")]
class MyTempView : IView
{
[ViewPrimaryKey]
public Lite<ArtistEntity> Artist { get; set; }
}
[Fact]
public void LeftOuterMyView()
{
using (Transaction tr = new Transaction())
{
Administrator.CreateTemporaryTable<MyTempView>();
Database.Query<ArtistEntity>().Where(a => a.Name.StartsWith("M")).UnsafeInsertView(a => new MyTempView { Artist = a.ToLite() });
var artists = (from a in Database.Query<ArtistEntity>()
join b in Database.View<MyTempView>() on a.ToLite() equals b.Artist into g
select a.ToLite()).ToList();
Assert.True(artists.All(a => a.ToString()!.StartsWith("M")));
var list1 = Database.View<MyTempView>().ToList();
var list2 = Database.Query<ArtistEntity>().Where(a => a.Name.StartsWith("M")).ToList();
Assert.Equal(list1.Count, list2.Count);
tr.Commit();
}
}
}
}
|
mit
|
Estevo-Aleixo/grimoire
|
_posts/2014-08-24-thunderous-smite.markdown
|
598
|
---
layout: post
title: "Thunderous Smite"
date: 2014-08-24
tags: [paladin, level1, evocation]
---
**1st-level evocation**
**Casting Time**: 1 bonus action
**Range**: Self
**Components**: V
**Duration**: Concentration, up to 1 minute
The first time you hit with a melee weapon attack during this spell's duration, your weapon rings with thunder that is audible within 300 feet of you, and the attack deals an extra 2d6 thunder damage to the target. Additionally, if the target is a creature, it must succeed on a Strength saving throw or be pushed 10 feet away from you and knocked prone.
|
mit
|
KamevoTeam/Kamevo
|
kamevo_src/user.php
|
962
|
<?php
session_start();
require('php/userProfile.class.php'); //load userProfileclass
?>
<!DOCTYPE html>
<html>
<head>
<?php
require("head_userpage.php"); //load special header only for this page
?>
</head>
<body>
<?php
if(isset($_SESSION['ID'])){ //load the appropriate menu
require("menu_co.php");
}else{
require("menu_pasco_general.php");
}
?>
<div class="site-pusher">
<div class="content">
<?php
if(!isset($errorProfile)){
require("disp_user_profile.php"); //load banner, pseudo and avatar of the current user
require("disp_info_user.php"); //load info box for the user
?>
<div class="fade"></div>
<div class=blockallz>
<?php
$userPage->printPosts('profile'); //show all posts of the user (userProfile.class.php)
}else{
include('disp_userNotExist.php'); //if we can't find user
}
?>
</div>
<?php require("js/animation_user.php") ?>
<script src="js/explore.js"></script>
</body>
</html>
|
mit
|
dushka-dragoeva/TelerikSeson2016
|
Software Technologies/Data Base/01. XML-Basics/01. XmlLanguage.md
|
605
|
##XML Language
**XML** is an extesible markup languageor describing structured data using text with tags and attributes.
It is worldwild standart supported by W3C. XML stores data in plain text format.
The data is stored together with the meta-data about it.
**XML** is used to describe other languages (formats) for data representation.
It defines rules for encoding documents in a specific text-based format.
**XML** is not only machine-readable, but it is also human-readable.
Provides a way to store and transmit information, to describe and identify information accurately and unambiguously.
|
mit
|
solag/Sofia
|
app/cache/prod/annotations/b2a8b2d443b35df2d93d6ecfc343a901b065def5$id.cache.php
|
386
|
<?php return unserialize('a:3:{i:0;O:27:"Doctrine\\ORM\\Mapping\\Column":9:{s:4:"name";s:7:"DBMS_ID";s:4:"type";s:7:"integer";s:6:"length";N;s:9:"precision";i:0;s:5:"scale";i:0;s:6:"unique";b:0;s:8:"nullable";b:0;s:7:"options";a:0:{}s:16:"columnDefinition";N;}i:1;O:23:"Doctrine\\ORM\\Mapping\\Id":0:{}i:2;O:35:"Doctrine\\ORM\\Mapping\\GeneratedValue":1:{s:8:"strategy";s:4:"AUTO";}}');
|
mit
|
newset/theme
|
backend/normal/Fusion/maps.html
|
46120
|
<!DOCTYPE html>
<html>
<head>
<!-- Meta, title, CSS, favicons, etc. -->
<meta charset="utf-8">
<title>Fusion - A Responsive HTML5 Admin UI Template Theme</title>
<meta name="keywords" content="HTML5 Bootstrap 3 Admin Template UI Theme" />
<meta name="description" content="Fusion - A Responsive HTML5 Admin UI Template Theme">
<meta name="author" content="AdminDesigns">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Font CSS (Via CDN) -->
<link rel='stylesheet' type='text/css' href='http://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700,800'>
<!-- Bootstrap CSS -->
<link rel="stylesheet" type="text/css" href="vendor/bootstrap/css/bootstrap.min.css">
<!-- Theme CSS -->
<link rel="stylesheet" type="text/css" href="css/vendor.css">
<link rel="stylesheet" type="text/css" href="css/theme.css">
<link rel="stylesheet" type="text/css" href="css/utility.css">
<link rel="stylesheet" type="text/css" href="css/custom.css">
<!-- Favicon -->
<link rel="shortcut icon" href="img/favicon.ico">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
<![endif]-->
</head>
<body class="maps-page">
<script> var boxtest = localStorage.getItem('boxed'); if (boxtest === 'true') {document.body.className+=' boxed-layout';} </script>
<!-- Start: Theme Preview Pane -->
<div id="skin-toolbox">
<div class="skin-toolbox-toggle"> <i class="fa fa-wrench"></i> </div>
<div class="skin-toolbox-panel">
<form id="skin-toolbox-form">
<h4 class="pl5">Theme Options</h4>
<div class="form-group">
<div class="cBox cBox-inline">
<input type="checkbox" id="ajax-option" checked/>
<label for="ajax-option">Ajax Loading</label>
</div>
</div>
<h4 class="pl5 mt20">Stylesss Options</h4>
<div class="form-group">
<div class="cBox cBox-inline">
<input type="checkbox" id="header-option" checked/>
<label for="header-option">Fixed Header</label>
</div>
</div>
<div class="form-group">
<div class="cBox cBox-inline">
<input type="checkbox" id="sidebar-option"/>
<label for="sidebar-option">Fixed Sidebar</label>
</div>
</div>
<div class="form-group">
<div class="cBox cBox-inline">
<input type="checkbox" id="breadcrumb-hidden"/>
<label for="breadcrumb-hidden">Hide Breadcrumbs</label>
</div>
</div>
<div class="form-group">
<div class="cBox cBox-inline">
<input type="checkbox" id="usermenu-hidden"/>
<label for="usermenu-hidden">Hide Usermenu</label>
</div>
</div>
<h4 class="pl5 mt20">Layout Options</h4>
<div class="form-group">
<label class="radio-inline">
<input type="radio" name="optionsRadios" id="fullwidth-option" checked>
Fullwidth </label>
</div>
<div class="form-group mb20">
<label class="radio-inline">
<input type="radio" name="optionsRadios" id="boxed-option">
Boxed Layouts </label>
</div>
<h4 class="pl5 mt20">Header Colors</h4>
<div class="form-group mb10">
<div class="toggle-color-wrap">
<div class="toggle-color-swap bg-purple3" data-swap="bg-purple3"></div>
<div class="toggle-color-swap bg-purple2" data-swap="bg-purple2"></div>
<div class="toggle-color-swap bg-blue4-alt" data-swap="bg-blue4-alt"></div>
<div class="toggle-color-swap bg-blue5-alt" data-swap="bg-blue5-alt"></div>
<div class="toggle-color-swap bg-blue6-alt" data-swap="bg-blue6-alt"></div>
<div class="toggle-color-swap bg-red2" data-swap="bg-red2"></div>
<div class="toggle-color-swap bg-orange2" data-swap="bg-orange2"></div>
<div class="toggle-color-swap bg-brown-alt" data-swap="bg-brown-alt"></div>
<div class="toggle-color-swap bg-dark3" data-swap="bg-dark3"></div>
<div class="toggle-color-swap bg-white" data-swap="bg-white"></div>
<div class="clearfix"></div>
</div>
</div>
<div class="form-group"> <a href="customizer.html" id="customizer-link" class="btn btn-gradient btn-block">CUSTOMIZER</a> </div>
</form>
</div>
</div>
<!-- End: Theme Preview Pane -->
<!-- Start: Header -->
<header class="navbar navbar-fixed-top">
<div class="navbar-branding"> <span id="toggle_sidemenu_l" class="glyphicons glyphicons-show_lines"></span> <a class="navbar-brand" href="dashboard.html"><img src="img/logos/header-logo.png"></a> </div>
<div class="navbar-left">
<div class="navbar-divider"></div>
<div id="settings_menu"> <span class="glyphicons glyphicons-settings dropdown-toggle cursor" data-toggle="dropdown"></span>
<ul class="dropdown-menu" role="menu">
<li><a href="javascript:void(0);"><span class="glyphicons glyphicons-bell text-purple mr15"></span>Users</a></li>
<li><a href="javascript:void(0);"><span class="glyphicons glyphicons-notes text-blue mr15"></span>Servers</a></li>
<li><a href="javascript:void(0);"><span class="glyphicons glyphicons-facebook text-orange mr15"></span>Crons</a></li>
</ul>
</div>
<div id="language_menu"> <a class="dropdown-toggle" data-toggle="dropdown" href="#"> <span class="flag-xs flag-us"></span> <span class="small va-m">US</span> <i class="fa fa-angle-down"></i> </a>
<ul class="dropdown-menu" role="menu">
<li><a href="javascript:void(0);"><span class="flag-xs flag-in"></span> Hindu</a></li>
<li><a href="javascript:void(0);"><span class="flag-xs flag-tr"></span> Turkish</a></li>
<li><a href="javascript:void(0);"><span class="flag-xs flag-es"></span> Spanish</a></li>
</ul>
</div>
</div>
<div class="navbar-right">
<div class="navbar-search">
<input type="text" id="HeaderSearch" placeholder="Search..." value="Search...">
</div>
<div class="navbar-menus">
<div class="btn-group" id="alert_menu">
<button type="button" class="dropdown-toggle" data-toggle="dropdown"><span class="glyphicons glyphicons-bell"></span> <b>3</b> </button>
<ul class="dropdown-menu media-list" role="menu">
<li class="dropdown-header">Recent Messages<span class="pull-right glyphicons glyphicons-bell"></span></li>
<li class="p15 pb10">
<ul class="list-unstyled">
<li><span class="glyphicons glyphicons-bell text-orange2 fs16 mr15"></span><b>CEO</b> lunch meeting Tuesday</li>
<li class="pt10"><span class="glyphicons glyphicons-facebook text-blue2 fs16 mr15"></span>Facebook likes are at <b>4,100</b></li>
<li class="pt10"><span class="glyphicons glyphicons-paperclip text-teal2 fs16 mr15"></span>Mark <b>uploaded</b> 3 new Docs</li>
<li class="pt10"><span class="glyphicons glyphicons-gift text-purple2 fs16 mr15"></span>It's <b>Marks</b> 34th Birthday</li>
<li class="pt10"><span class="glyphicons glyphicons-cup text-red2 fs16 mr15"></span>Best new employee awarded to <b>Jessica</b></li>
</ul>
</li>
</ul>
</div>
<div class="btn-group" id="comment_menu">
<button type="button" class="dropdown-toggle" data-toggle="dropdown"><span class="glyphicons glyphicons-display"></span> <b>7</b> </button>
<div class="dropdown-menu" role="menu">
<ul class="nav nav-tabs tabs-border-bottom" role="tablist">
<li class="active"><a href="#header_tab1" role="tab" data-toggle="tab">Messages</a></li>
<li><a href="#header_tab2" role="tab" data-toggle="tab">Tickets</a></li>
<li><a href="#header_tab3" role="tab" data-toggle="tab">Todo List</a></li>
</ul>
<!-- Tab panes -->
<div class="tab-content pn border-none dropdown-persist">
<div class="tab-pane active" id="header_tab1">
<div class="dropdown-submenu dropdown-persist">
<div class="row">
<div class="col-xs-8">
<input class="dropdownSearch" type="text" placeholder="Search...">
</div>
<div class="col-xs-4">
<div class="cBox cBox-inline ml20">
<input type="checkbox" id="headercBox1" name="check" value="None"/>
<label for="headercBox1">Delete</label>
</div>
</div>
</div>
</div>
<div class="p15">
<div class="media border-none"> <a class="pull-left" href="#"> <img class="media-object thumbnail thumbnail-sm rounded" src="img/avatars/2.jpg" alt="..."> </a>
<div class="media-body">
<h5 class="media-heading mbn">Simon Rivers <small class="text-light5"> - 3 hours ago</small></h5>
<p class="text-muted"> Hey Louis, I was wondering if</p>
</div>
</div>
<div class="media mt10 border-none"> <a class="pull-left" href="#"> <img class="media-object thumbnail thumbnail-sm rounded border-online" src="img/avatars/6.jpg" alt="..."> </a>
<div class="media-body">
<h5 class="media-heading mbn">Tracy Rope <small class="text-light5"> - 8 hours ago</small></h5>
<p class="text-muted"> Bam baby get at, I was</p>
</div>
</div>
<div class="media mt10 border-none"> <a class="pull-left" href="#"> <img class="media-object thumbnail thumbnail-sm rounded border-online" src="img/avatars/8.jpg" alt="..."> </a>
<div class="media-body">
<h5 class="media-heading mbn">Courtney Dash <small class="text-light5"> - 3 days ago</small></h5>
<p class="text-muted"> I was wonde awesome brief </p>
</div>
</div>
<div class="media mt10 border-none"> <a class="pull-left" href="#"> <img class="media-object thumbnail thumbnail-sm rounded border-light5" src="img/avatars/2.jpg" alt="..."> </a>
<div class="media-body">
<h5 class="media-heading mbn">Simon Rivers <small class="text-light5"> - 3 hours ago</small></h5>
<p class="text-muted mbn"> Hey Louis, I was wondering </p>
</div>
</div>
</div>
</div>
<div class="tab-pane" id="header_tab2">
<div class="dropdown-submenu dropdown-persist">
<div class="cBox cBox-inline cBox-orange ml15 p1">
<input type="checkbox" id="headercBox2" name="check" value="None"/>
<label for="headercBox2">Closed</label>
</div>
<div class="cBox cBox-inline cBox-purple">
<input type="checkbox" id="headercBox3" name="check" value="None"/>
<label for="headercBox3">Low</label>
</div>
<div class="cBox cBox-inline cBox-blue">
<input type="checkbox" id="headercBox4" name="check" value="None"/>
<label for="headercBox4">Med</label>
</div>
<div class="cBox cBox-inline cBox-red2 cBox-gradient">
<input type="checkbox" id="headercBox5" name="check" value="None" checked/>
<label for="headercBox5">Urgent</label>
</div>
</div>
<div class="sortable mt10 mb10">
<div class="todo-item table-layout p8">
<div class="todo-handle va-m">
<div class="v-handle"></div>
</div>
<div class="todo-body va-m"><b class="text-muted">[Ticket #1]</b> - Validation Errors <small class="text-blue2"> [read more..]</small></div>
</div>
<div class="todo-item table-layout p8">
<div class="todo-handle va-m">
<div class="v-handle"></div>
</div>
<div class="todo-body va-m"><b class="text-muted">[Ticket #2]</b> - User Profile Debug<small class="text-blue2"> [read more..]</small></div>
</div>
<div class="todo-item table-layout p8">
<div class="todo-handle va-m">
<div class="v-handle"></div>
</div>
<div class="todo-body va-m"><b class="text-muted">[Ticket #3]</b> - User hacked <small class="text-blue2"> [read more..]</small></div>
</div>
<div class="todo-item table-layout p8">
<div class="todo-handle va-m">
<div class="v-handle"></div>
</div>
<div class="todo-body va-m"><b class="text-muted">[Ticket #4]</b> - Mailbox Debug <small class="text-blue2"> [read more..]</small></div>
</div>
<div class="todo-item table-layout p8">
<div class="todo-handle va-m">
<div class="v-handle"></div>
</div>
<div class="todo-body va-m"><b class="text-muted">[Ticket #5]</b> - User Profile Debug<small class="text-blue2"> [read more..]</small></div>
</div>
<div class="todo-item table-layout p8">
<div class="todo-handle va-m">
<div class="v-handle"></div>
</div>
<div class="todo-body va-m"><b class="text-muted">[Ticket #6]</b> - User Profile Debug<small class="text-blue2"> [read more..]</small></div>
</div>
<div class="todo-item table-layout p8">
<div class="todo-handle va-m">
<div class="v-handle"></div>
</div>
<div class="todo-body va-m"><b class="text-muted">[Ticket #7]</b> - User Profile Debug<small class="text-blue2"> [read more..]</small></div>
</div>
</div>
</div>
<div class="tab-pane" id="header_tab3">
<div class="dropdown-submenu dropdown-persist">
<div class="row">
<div class="col-xs-12">
<input class="dropdownSearch" type="text" placeholder="Create New Item...">
</div>
</div>
</div>
<div class="ticket-item table-layout">
<div class="ticket-handle va-m">
<div class="cBox ml10">
<input type="checkbox" id="headercBox7" name="check" value="None"/>
<label for="headercBox7"></label>
</div>
</div>
<div class="ticket-body p10 va-m"><b class="text-muted">[#2]</b> - IE8 Profile Drag Errors <span class="label label-sm bg-grey2 ml10">Javascript</span></div>
</div>
<div class="ticket-item table-layout">
<div class="ticket-handle va-m">
<div class="cBox ml10">
<input type="checkbox" id="headercBox6" name="check" value="None"/>
<label for="headercBox6"></label>
</div>
</div>
<div class="ticket-body p10 va-m"><b class="text-muted">[#1]</b> - Validation Errors on USCM testing facitiliy <small class="text-red2">- Urgent</small></div>
</div>
<div class="ticket-item table-layout">
<div class="ticket-handle va-m">
<div class="cBox ml10">
<input type="checkbox" id="headercBox9" name="check" value="None"/>
<label for="headercBox9"></label>
</div>
</div>
<div class="ticket-body p10 va-m"><b class="text-muted">[#4]</b> - CSS Problems with Tables <span class="label label-sm bg-orange2 ml10">CSS</span></div>
</div>
<div class="ticket-item table-layout">
<div class="ticket-handle va-m">
<div class="cBox ml10">
<input type="checkbox" id="headercBox10" name="check" value="None"/>
<label for="headercBox10"></label>
</div>
</div>
<div class="ticket-body p10 va-m"><b class="text-muted">[#5]</b> - PHP Form validation errors occuring on email page<span class="label label-sm bg-purple2 ml10">PHP</span></div>
</div>
<div class="ticket-item table-layout">
<div class="ticket-handle va-m">
<div class="cBox ml10">
<input type="checkbox" id="headercBox8" name="check" value="None"/>
<label for="headercBox8"></label>
</div>
</div>
<div class="ticket-body p10 pb15 va-m"><b class="text-muted">[#3]</b> - Mailbox Validation Errors on Firefox</div>
</div>
</div>
</div>
</div>
</div>
<div class="btn-group" id="toggle_sidemenu_r">
<button type="button"> <span class="glyphicons glyphicons-parents"></span> </button>
</div>
</div>
</div>
</header>
<!-- End: Header -->
<!-- Start: Main -->
<div id="main">
<!-- Start: Sidebar -->
<aside id="sidebar_left">
<div class="user-info">
<div class="media"> <a class="pull-left" href="#">
<div class="media-object border border-purple br64 bw2 p2"> <img class="br64" src="img/avatars/5.jpg" alt="..."> </div>
</a>
<div class="mobile-link"> <span class="glyphicons glyphicons-show_big_thumbnails"></span> </div>
<div class="media-body">
<h5 class="media-heading mt5 mbn fw700 cursor">John.Smith<span class="caret ml5"></span></h5>
<div class="media-links fs11"><a href="#">Menu</a><i class="fa fa-circle text-muted fs3 p8 va-m"></i><a href="screen-lock.html">Sign Out</a></div>
</div>
</div>
</div>
<div class="user-divider"></div>
<div class="user-menu">
<div class="row text-center mb15">
<div class="col-xs-4"> <a href="dashboard.html"> <span class="glyphicons glyphicons-home fs22 text-blue2"></span>
<h5 class="fs11">Home</h5>
</a> </div>
<div class="col-xs-4"> <a href="messages.html"> <span class="glyphicons glyphicons-inbox fs22 text-orange2"></span>
<h5 class="fs11">Inbox</h5>
</a> </div>
<div class="col-xs-4"> <a href="tables.html"> <span class="glyphicons glyphicons-bell fs22 text-purple2"></span>
<h5 class="fs11">Data</h5>
</a> </div>
</div>
<div class="row text-center">
<div class="col-xs-4 text-center"> <a href="timeline.html"> <span class="glyphicons glyphicons-imac fs22 text-grey3"></span>
<h5 class="fs11">Views</h5>
</a> </div>
<div class="col-xs-4"> <a href="profile.html"> <span class="glyphicons glyphicons-settings fs22 text-green2"></span>
<h5 class="fs11">Settings</h5>
</a> </div>
<div class="col-xs-4"> <a href="gallery.html"> <span class="glyphicons glyphicons-restart fs22 text-light6"></span>
<h5 class="fs11">Images</h5>
</a> </div>
</div>
</div>
<div class="sidebar-menu">
<ul class="nav sidebar-nav">
<li> <a href="customizer.html" class="ajax-disable"><span class="glyphicons glyphicons-eyedropper"></span> <span class="sidebar-title">Customizer</span> <span class="sidebar-title-tray"> <span class="label label-xs bg-purple2">New</span> </span> </a> </li>
<li> <a href="messages.html" class="ajax-disable"><span class="glyphicons glyphicons-inbox"></span><span class="sidebar-title">Messages</span></a> </li>
<li> <a href="dashboard.html"><span class="glyphicons glyphicons-home"></span><span class="sidebar-title">Dashboard</span></a> </li>
<li> <a class="accordion-toggle" href="#resources"><span class="glyphicons glyphicons-settings"></span><span class="sidebar-title">Resources</span><span class="caret"></span></a>
<ul id="resources" class="nav sub-nav">
<li><a href="dashboard.html"><span class="glyphicons glyphicons-magic"></span>Dashboard </a></li>
<li><a class="ajax-disable" href="../documentation/index.html"><span class="glyphicons glyphicons-book"></span> Documentation </a></li>
<li><a class="ajax-disable" href="login.html"><span class="glyphicons glyphicons-power"></span> Login Page</a></li>
<li><a class="ajax-disable" href="screen-lock.html"><span class="glyphicons glyphicons-lock"></span> Screen Lock</a></li>
<li><a class="ajax-disable" href="coming-soon.html"><span class="glyphicons glyphicons-road"></span> Coming Soon</a></li>
<li><a class="ajax-disable" href="404-page.html"><span class="glyphicons glyphicons-circle_remove"></span> 404 Page</a></li>
<li><a class="ajax-disable" href="500-page.html"><span class="glyphicons glyphicons-circle_exclamation_mark"></span> 500 Page</a></li>
</ul>
</li>
<li> <a class="accordion-toggle" href="#sideOne"><span class="glyphicons glyphicons-adjust_alt"></span><span class="sidebar-title">UI Elements</span><span class="caret"></span></a>
<ul id="sideOne" class="nav sub-nav">
<li><a href="portlets.html"><span class="glyphicons glyphicons-sort"></span> Portlets</a></li>
<li><a href="elements.html"><span class="glyphicons glyphicons-paperclip"></span> Elements</a></li>
<li><a class="ajax-disable" href="charts.html"><span class="glyphicons glyphicons-stats"></span> Charts</a></li>
<li><a href="tabs.html"><span class="glyphicons glyphicons-adjust"></span> Tabs</a></li>
<li><a href="buttons.html"><span class="glyphicons glyphicons-macbook"></span> Buttons</a></li>
<li><a href="typography.html"><span class="glyphicons glyphicons-font"></span> Typography</a></li>
<li><a href="grid.html"><span class="glyphicons glyphicons-show_big_thumbnails"></span> Grid</a></li>
</ul>
</li>
<li> <a class="accordion-toggle" href="#sideTwo"><span class="glyphicons glyphicons-vcard"></span><span class="sidebar-title">Form Elements</span><span class="caret"></span></a>
<ul id="sideTwo" class="nav sub-nav">
<li><a href="forms.html"><span class="glyphicons glyphicons-link"></span> Form Elements</a></li>
<li><a href="editors.html"><span class="glyphicons glyphicons-pencil"></span> Editors</a></li>
<li><a href="editable.html"><span class="glyphicons glyphicons-edit"></span> Inline Editing</a></li>
<li><a href="xedit.html"><span class="glyphicons glyphicons-check"></span> X-editable</a></li>
<li><a href="tables.html"><span class="glyphicons glyphicons-table"></span> Tables</a></li>
<li><a href="treeview.html"><span class="glyphicons glyphicons-tree_conifer"></span> Treeview</a></li>
</ul>
</li>
<li class="active"> <a class="accordion-toggle menu-open" href="#sideSix"><span class="glyphicons glyphicons-globe"></span><span class="sidebar-title">Maps</span><span class="caret"></span></a>
<ul id="sideSix" class="nav sub-nav">
<li class="active"><a href="maps.html"><span class="glyphicons glyphicons-global"></span> GMaps</a></li>
<li><a href="map-full.html"><span class="glyphicons glyphicons-globe_af"></span> Window Map</a></li>
<li><a href="maps-vector.html"><span class="glyphicons glyphicons-vector_path_circle"></span> Vector Maps</a></li>
</ul>
</li>
<li> <a class="accordion-toggle" href="#sideSeven"><span class="glyphicons glyphicons-book_open"></span><span class="sidebar-title">Pages</span><span class="caret"></span></a>
<ul id="sideSeven" class="nav sub-nav">
<li><a href="profile.html"><span class="glyphicons glyphicons glyphicons-user"></span> Profile</a></li>
<li><a href="timeline.html"><span class="glyphicons glyphicons-film"></span> Timeline</a></li>
<li><a href="gallery.html"><span class="glyphicons glyphicons-picture"></span> Gallery</a></li>
<li><a href="invoice.html"><span class="glyphicons glyphicons glyphicons-print"></span> Printable Invoice</a></li>
<li><a href="calendar.html"><span class="glyphicons glyphicons-calendar"></span> Calendar</a></li>
<li><a href="faq.html"><span class="glyphicons glyphicons-edit"></span> Faq Page</a></li>
<li><a href="blank.html"><span class="glyphicons glyphicons-unchecked"></span> Blank Page</a></li>
</ul>
</li>
<li> <a class="accordion-toggle" href="#sideFive"><span class="glyphicons glyphicons-magic"></span><span class="sidebar-title">Extras</span><span class="caret"></span></a>
<ul id="sideFive" class="nav sub-nav">
<li><a href="icons.html"><span class="glyphicons glyphicons-flash"></span> Icons</a></li>
<li><a href="animations.html"><span class="glyphicons glyphicons-fire"></span> Animations</a></li>
<li><a href="sliders.html"><span class="glyphicons glyphicons-retweet"></span> Sliders</a></li>
<li><a href="image-tools.html"><span class="glyphicons glyphicons-camera"></span> Image Tools</a></li>
<li><a href="sketchpad.html"><span class="glyphicons glyphicons-vector_path_square"></span> Sketchpad</a></li>
</ul>
</li>
<li> <a class="accordion-toggle" href="#sideEight"><span class="glyphicons glyphicons-more_items"></span><span class="sidebar-title">Multi Level Nav</span><span class="caret"></span></a>
<ul id="sideEight" class="nav sub-nav">
<li><a href="javascript:void(0);" class="ajax-disable"><span class="glyphicons glyphicons-ok_2"></span> Item #1</a></li>
<li><a href="javascript:void(0);" class="ajax-disable"><span class="glyphicons glyphicons-ok_2"></span> Item #2</a></li>
<li><a class="accordion-toggle" href="#sideEight-sub"><span class="glyphicons glyphicons-show_lines"></span>2nd Level Nav<span class="caret"></span></a>
<ul id="sideEight-sub" class="nav sub-nav">
<li><a href="javascript:void(0);" class="ajax-disable"><span class="glyphicons glyphicons-ok_2"></span> Item #1</a></li>
<li><a href="javascript:void(0);" class="ajax-disable"><span class="glyphicons glyphicons-ok_2"></span> Item #2</a></li>
<li><a class="accordion-toggle" href="#sideEight-sub-2"><span class="glyphicons glyphicons-show_lines"></span>3rd Level Nav<span class="caret"></span></a>
<ul id="sideEight-sub-2" class="nav sub-nav">
<li><a href="javascript:void(0);" class="ajax-disable"><span class="glyphicons glyphicons-ok_2"></span> Item #1</a></li>
<li><a href="javascript:void(0);" class="ajax-disable"><span class="glyphicons glyphicons-ok_2"></span> Item #2</a></li>
<li><a class="accordion-toggle" href="#sideEight-sub-2"><span class="glyphicons glyphicons-show_lines"></span>4th Level Nav<span class="caret"></span></a>
<ul id="sideEight-sub-3" class="nav sub-nav">
<li><a href="javascript:void(0);" class="ajax-disable"><span class="glyphicons glyphicons-ok_2"></span> Item #1</a></li>
<li><a href="javascript:void(0);" class="ajax-disable"><span class="glyphicons glyphicons-ok_2"></span> Item #2</a></li>
<li><a href="javascript:void(0);" class="ajax-disable"><span class="glyphicons glyphicons-ok_2"></span> Item #3</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</aside>
<!-- End: Sidebar -->
<!-- Start: Content -->
<section id="content_wrapper">
<div id="topbar">
<div class="topbar-left">
<ol class="breadcrumb">
<li class="crumb-active"><a href="maps.html">Maps</a></li>
<li class="crumb-icon"><a href="dashboard.html"><span class="glyphicon glyphicon-home"></span></a></li>
<li class="crumb-link"><a href="index.html">Home</a></li>
<li class="crumb-trail">Maps</li>
</ol>
</div>
</div>
<div id="content">
<div class="row">
<div class="col-md-12">
<div class="panel">
<div class="panel-body">
<div id="panorama" class="map"></div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="row">
<div class="col-md-12">
<div class="panel">
<div class="panel-heading"> <span class="panel-title"> <span class="glyphicon glyphicon-map-marker"></span> Searchable Map </span> </div>
<div class="panel-menu">
<div class="form-group">
<form method="post" id="geocoding_form">
<div class="col-xs-9 prn">
<input type="text" class="form-control" id="address" name="address" placeholder="Enter an Address...">
</div>
<div class="col-xs-3">
<input type="submit" class="btn btn-default btn-gradient btn-block" value="Search">
</div>
</form>
</div>
<div class="clearfix"></div>
</div>
<div class="panel-body">
<div id="map1" class="map"></div>
</div>
</div>
</div>
<div class="col-md-12">
<div class="panel">
<div class="panel-heading"> <span class="panel-title"> <span class="glyphicon glyphicon-map-marker"></span> Standard Map </span> </div>
<div class="panel-body">
<div id="map_canvas1" class="map"></div>
</div>
</div>
</div>
<div class="col-md-12">
<div class="panel">
<div class="panel-heading"> <span class="panel-title"> <span class="glyphicon glyphicon-map-marker"></span> Map with List Filter </span> </div>
<div class="panel-body">
<div id="map_canvas4" class="map"></div>
<div id="radio" class="map-gradient map-rounded map-shadow" style="border: 1px solid #AAA; margin:5px;padding:10px 10px 5px 10px;"></div>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-6">
<div class="row">
<div class="col-md-12">
<div class="panel">
<div class="panel-heading"> <span class="panel-title"> <span class="glyphicon glyphicon-map-marker"></span> Map with Clickable Locations </span> </div>
<div class="panel-menu">
<button type="button" class="btn btn-default btn-gradient" data-gmapping='{"id":"m_1","latlng":{"lat":27.6648274,"lng":-81.51575350000002},"tags":"drupal"}' data-title="Florida DrupalCamp - Feb 11 2012"> <span class="glyphicons glyphicons-google_maps pr5"></span> 1 </button>
<button type="button" class="btn btn-default btn-gradient" data-gmapping='{"id":"m_2","latlng":{"lat":1.352083,"lng":103.81983600000001},"tags":"drupal"}' data-title="DrupalCamp Singapore - Mar 03 2012"> <span class="glyphicons glyphicons-google_maps pr5"></span> 2 </button>
<button type="button" class="btn btn-default btn-gradient" data-gmapping='{"id":"m_3","latlng":{"lat":39.7391536,"lng":-104.9847034},"tags":"drupal"}' data-title="DrupalCon 2012 Denver - Mar 20 2012"> <span class="glyphicons glyphicons-google_maps pr5"></span> 3 </button>
<button type="button" class="btn btn-default btn-gradient" data-gmapping='{"id":"m_4","latlng":{"lat":36.1658899,"lng":-86.7844432},"tags":"drupal"}' data-title="DrupalCamp Nashville - Apr 28 2012"> <span class="glyphicons glyphicons-google_maps pr5"></span> 4 </button>
<button type="button" class="btn btn-default btn-gradient" data-gmapping='{"id":"m_5","latlng":{"lat":55.6760968,"lng":12.568337100000008},"tags":"drupal"}' data-title="Camp Copenhagen 5.0 - May 11 2012"> <span class="glyphicons glyphicons-google_maps pr5"></span> 5 </button>
</div>
<div class="panel-body">
<div id="map_canvas2" class="map rounded"></div>
</div>
</div>
</div>
<div class="col-md-12">
<div class="panel">
<div class="panel-heading"> <span class="panel-title"> <span class="glyphicon glyphicon-map-marker"></span> Map with Inner Pagination </span> </div>
<div class="panel-body">
<div id="map_canvas3" class="map"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<!-- End: Content -->
<!-- Start: Right Sidebar -->
<aside id="sidebar_right">
<div class="sidebar-right-header">
<div class="pull-right posr"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> <i class="fa fa-circle text-orange2 fs8"></i> <span class="caret text-muted"></span> </a>
<ul class="dropdown-menu dropdown-sm" role="menu">
<li class="menu-arrow">
<div class="menu-arrow-up"></div>
</li>
<li><a href="javascript:void(0);"><i class="fa fa-circle text-green2 pr5"></i> Online</a></li>
<li><a href="javascript:void(0);"><i class="fa fa-circle text-red2 pr5"></i> Busy</a></li>
<li class="divider"></li>
<li><a href="javascript:void(0);"><i class="fa fa-circle text-orange2 pr5"></i> Away</a></li>
</ul>
</div>
<div class="media mtn"> <a class="pull-left mt5" href="#"> <img class="thumbnail thumbnail-sm rounded" src="img/avatars/2.jpg" alt="..."> </a>
<div class="media-body">
<h5 class="small mt5 mbn text-cloud"><b>Current Status:</b></h5>
<h5 class="small text-white"><b>"Away: Lunch meeting"</b></h5>
</div>
</div>
</div>
<div class="sidebar_right_content p25">
<div class="sidebar_right_menu row text-center">
<div class="col-xs-4 pln"> <a href="calendar.html"> <span class="glyphicons glyphicons-imac fs22 text-grey2"></span>
<h5 class="fs11 text-white">Calendar</h5>
</a> </div>
<div class="col-xs-4"> <a href="profile.html"> <span class="glyphicons glyphicons-settings fs22 text-green"></span>
<h5 class="fs11 text-white">Settings</h5>
</a> </div>
<div class="col-xs-4 prn"> <a href="messages.html"> <span class="glyphicons glyphicons-inbox fs22 text-orange"></span>
<h5 class="fs11 text-white">Inbox</h5>
</a> </div>
</div>
<hr class="mb25 mtn border-dark3"/>
<h5 class="text-muted fs13 mb25">Notes</h5>
<h5 class="text-white mbn">9:30 AM - Ford Pitch</h5>
<p class="text-light6 fs12 fw600 mb15">Client expects a working draft</p>
<h5 class="text-white mbn">12:15 AM - Lunch Meeting</h5>
<p class="text-light6 fs12 fw600 mb15">To discuss Ford Pitch outcome</p>
<h5 class="text-white mbn">2:30 AM - Computer Repair</h5>
<p class="text-light6 fs12 fw600 mb15">Coming to replace failing HD </p>
<h5 class="text-white mbn">4:15 AM - First Yoga Class</h5>
<p class="text-light6 fs12 fw600">Ask about your free classes</p>
<hr class="mb25 mt25 border-dark3"/>
<h5 class="text-muted fs13 pull-left mr20">Users</h5>
<div class="btn-group pull-left">
<button type="button" class="btn btn-gradient btn-xs bg-blue7-alt dropdown-toggle fs11 fw600" data-toggle="dropdown"><i class="fa fa-circle text-green2 fs8 pr5"></i> Online <span class="caret caret-sm ml5"></span> </button>
<ul class="dropdown-menu dropdown-sm" role="menu">
<li class="menu-arrow">
<div class="menu-arrow-up"></div>
</li>
<li><a href="javascript:void(0);"><i class="fa fa-circle text-green2 pr5"></i> Online</a></li>
<li><a href="javascript:void(0);"><i class="fa fa-circle text-red2 pr5"></i> Busy</a></li>
<li class="divider"></li>
<li><a href="javascript:void(0);"><i class="fa fa-circle text-orange2 pr5"></i> Away</a></li>
</ul>
</div>
<div class="clearfix"></div>
<div class="media mt30 border-none"> <a class="pull-left" href="#"> <img class="media-object thumbnail thumbnail-sm rounded" src="img/avatars/4.jpg" alt="..."> </a>
<div class="media-body">
<h5 class="media-heading text-white mbn">Simon Rivers</h5>
<p class="text-muted fs12"> What's up, buddy</p>
</div>
</div>
<div class="media border-none"> <a class="pull-left" href="#"> <img class="media-object thumbnail thumbnail-sm rounded" src="img/avatars/5.jpg" alt="..."> </a>
<div class="media-body">
<h5 class="media-heading text-white mbn">Eric Ulrich</h5>
<p class="text-muted fs12"> Client Problem pg.14</p>
</div>
</div>
<div class="media border-none"> <a class="pull-left" href="#"> <img class="media-object thumbnail thumbnail-sm rounded" src="img/avatars/6.jpg" alt="..."> </a>
<div class="media-body">
<h5 class="media-heading text-white mbn">Hershel Sandin</h5>
<p class="text-muted fs12"> Looking for an intern?</p>
</div>
</div>
<div class="media border-none"> <a class="pull-left" href="#"> <img class="media-object thumbnail thumbnail-sm rounded" src="img/avatars/7.jpg" alt="..."> </a>
<div class="media-body">
<h5 class="media-heading text-white mbn">Jacob Hill</h5>
<p class="text-muted fs12"> Lunch meeting tomorrow.</p>
</div>
</div>
<div class="media border-none"> <a class="pull-left" href="#"> <img class="media-object thumbnail thumbnail-sm rounded" src="img/avatars/3.jpg" alt="..."> </a>
<div class="media-body">
<h5 class="media-heading text-white mbn">Dante Harper</h5>
<p class="text-muted fs12"> I have a new twitter!</p>
</div>
</div>
</div>
</aside>
<!-- End: Right Sidebar -->
</div>
<!-- End: Main -->
<!-- Google Map API -->
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
<!-- jQuery -->
<script type="text/javascript" src="vendor/jquery/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="vendor/jquery/jquery_ui/jquery-ui.min.js"></script> <!-- Bootstrap -->
<script type="text/javascript" src="vendor/bootstrap/js/bootstrap.min.js"></script>
<!-- Page Plugins -->
<script type="text/javascript" src="vendor/plugins/map/gmaps.min.js"></script>
<script type="text/javascript" src="vendor/plugins/gmap/jquery.ui.map.min.js"></script>
<script type="text/javascript" src="vendor/plugins/gmap/ui/jquery.ui.map.services.js"></script>
<script type="text/javascript" src="vendor/plugins/gmap/ui/jquery.ui.map.extensions.js"></script>
<script type="text/javascript" src="vendor/plugins/gmap/ui/jquery.ui.map.microformat.js"></script>
<!-- Theme Javascript -->
<script type="text/javascript" src="js/utility/spin.min.js"></script>
<script type="text/javascript" src="js/utility/underscore-min.js"></script>
<script type="text/javascript" src="js/main.js"></script>
<script type="text/javascript" src="js/ajax.js"></script>
<script type="text/javascript" src="js/custom.js"></script>
<script type="text/javascript">
jQuery(document).ready(function () {
"use strict";
// Init Theme Core
Core.init();
// Enable Ajax Loading
Ajax.init();
// Streetview for panorama map
var panorama = GMaps.createPanorama({
el: '#panorama',
lat : 51.693249,
lng : -0.419630,
pov: {
heading: 194,
pitch: 8
}
});
// Initilize Gmap1 - basic
if ($('#map_canvas1').length) {
$('#map_canvas1').gmap({'center': '57.7973333,12.0502107', 'zoom': 10, 'disableDefaultUI':true, 'callback': function() {
var self = this;
self.addMarker({'position': this.get('map').getCenter() }).click(function() {
self.openInfoWindow({ 'content': 'Hello World!' }, this);
});
}});
}
// Initilize Gmap2 - clickable movements
$(function() {
$('#map_canvas2').gmap({'disableDefaultUI':true, 'callback': function() {
var self = this;
$("[data-gmapping]").each(function(i,el) {
var data = $(el).data('gmapping');
var title = $(el).data('title');
self.addMarker({'id': data.id, 'tags':data.tags, 'position': new google.maps.LatLng(data.latlng.lat, data.latlng.lng), 'bounds':true }, function(map,marker) {
$(el).click(function() {
$(marker).triggerEvent('click');
});
}).click(function() {
self.openInfoWindow({ 'content': title}, this);
});
});
}});
});
// Initilize Gmap3 - scrollable toolbar
$(function() {
var markers = [
{'position': '59.32893000000001,18.064910000000054', 'title': 'Stockholm, Sweden' },
{'position': '35.6894875,139.69170639999993', 'title': 'Tokyo, Japan' },
{'position': '13.7234186, 100.47623190000002', 'title': 'Bangkok, Thailand' },
{'position': '51.508129,-0.12800500000003012', 'title': 'London, Great Britain' },
{'position': '40.7143528,-74.0059731', 'title': 'New York, USA' },
{'position': '48.856614,2.3522219000000177', 'title': 'Paris, France' },
{'position': '34.0522342,-118.2436849', 'title': 'Los Angeles, USA' },
{'position': '55.75,37.616666699999996', 'title': 'Moskva, Ryssia' }
];
$('#map_canvas3').gmap({'zoom': 5, 'disableDefaultUI':true, 'callback': function() {
var self = this;
$.each(markers, function(i, marker) {
self.addMarker(marker).click(function() {
self.openInfoWindow({'content': this.title}, this);
});
});
}}).gmap('pagination', 'title');
});
// Initilize Gmap4 - sortable control panel
$(function() {
String.prototype.format = function() { var a = this; for ( var k in arguments ) { a = a.replace("{" + k + "}", arguments[k]); } return a; };
$('#map_canvas4').gmap({'disableDefaultUI':true}).bind('init', function(evt, map) {
//$('#map_canvas').gmap('addControl', 'tags-control', google.maps.ControlPosition.TOP_LEFT);
$('#map_canvas4').gmap('addControl', 'radio', google.maps.ControlPosition.TOP_LEFT);
var southWest = map.getBounds().getSouthWest();
var northEast = map.getBounds().getNorthEast();
var lngSpan = northEast.lng() - southWest.lng();
var latSpan = northEast.lat() - southWest.lat();
var images = ['img/map_icons/map-icon-1.png', 'img/map_icons/map-icon-2.png', 'img/map_icons/map-icon-3.png', 'img/map_icons/map-icon-4.png', 'img/map_icons/map-icon-5.png', 'img/map_icons/map-icon-6.png'];
var tags = ['jQuery', 'Google maps', 'Plugin', 'SEO', 'Java', 'PHP', 'C#', 'Ruby', 'JavaScript', 'HTML'];
//$('#tags').append('<option value="all">All</option>');
$.each(tags, function(i, tag) {
//$('#tags').append(('<option value="{0}">{1}</option>').format(tag, tag));
$('#radio').append(('<div class="cBox mt5 mb5"><input type="checkbox" id="'+tag+'" value="{0}"/><label for="'+tag+'">{1}</label></div>').format(tag, tag));
});
for (var i = 0; i < 100; i++ ) {
var temp = [];
for (var j = 0; j < Math.random()*5; j++ ) {
temp.push(tags[Math.floor(Math.random()*10)]);
}
$('#map_canvas4').gmap('addMarker', { 'icon': images[(Math.floor(Math.random()*7))], 'tags':temp, 'bound':true, 'position': new google.maps.LatLng(southWest.lat() + latSpan * Math.random(), southWest.lng() + lngSpan * Math.random()) } ).click(function() {
var visibleInViewport = ( $('#map_canvas4').gmap('inViewport', $(this)[0]) ) ? 'I\'m visible in the viewport.' : 'I\'m sad and hidden.';
$('#map_canvas4').gmap('openInfoWindow', { 'content': $(this)[0].tags + '<br/>' +visibleInViewport }, this);
});
}
$('input:checkbox').click(function() {
$('#map_canvas4').gmap('closeInfoWindow');
$('#map_canvas4').gmap('set', 'bounds', null);
var filters = [];
$('input:checkbox:checked').each(function(i, checkbox) {
filters.push($(checkbox).val());
});
if ( filters.length > 0 ) {
$('#map_canvas4').gmap('find', 'markers', { 'property': 'tags', 'value': filters, 'operator': 'OR' }, function(marker, found) {
if (found) {
$('#map_canvas4').gmap('addBounds', marker.position);
}
marker.setVisible(found);
});
} else {
$.each($('#map_canvas4').gmap('get', 'markers'), function(i, marker) {
$('#map_canvas4').gmap('addBounds', marker.position);
marker.setVisible(true);
});
}
});
});
});
// Init Searchable map using gmaps plugin
var map = new GMaps({
div: '#map1',
lat: -12.043333,
lng: -77.028333,
});
//add search bar to map
$('#geocoding_form').submit(function(e){
e.preventDefault();
GMaps.geocode({
address: $('#address').val().trim(),
callback: function(results, status){
if(status=='OK'){
var latlng = results[0].geometry.location;
map.setCenter(latlng.lat(), latlng.lng());
map.addMarker({
lat: latlng.lat(),
lng: latlng.lng()
});
}
}
});
});
});
</script>
</body>
</html>
|
mit
|
bburnichon/PHPExiftool
|
lib/PHPExiftool/Driver/Tag/Pentax/InternalSerialNumber.php
|
862
|
<?php
/*
* This file is part of the PHPExifTool package.
*
* (c) Alchemy <support@alchemy.fr>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPExiftool\Driver\Tag\Pentax;
use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;
/**
* @ExclusionPolicy("all")
*/
class InternalSerialNumber extends AbstractTag
{
protected $Id = 4;
protected $Name = 'InternalSerialNumber';
protected $FullName = 'Pentax::CameraInfo';
protected $GroupName = 'Pentax';
protected $g0 = 'MakerNotes';
protected $g1 = 'Pentax';
protected $g2 = 'Camera';
protected $Type = 'int32u';
protected $Writable = true;
protected $Description = 'Internal Serial Number';
protected $flag_Permanent = true;
}
|
mit
|
stuartleeks/nether
|
rundev.ps1
|
2347
|
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
function CheckDependencies()
{
$missing = @()
if((Get-Command "node" -ErrorAction SilentlyContinue) -eq $null)
{
$missing += "Node.js is not installed"
}
if((Get-Command "npm" -ErrorAction SilentlyContinue) -eq $null)
{
$missing += "NPM is not installed"
}
if($missing.Length -gt 0)
{
Write-Error "missing dependencides: $missing"
exit
}
if((Get-Command "bower" -ErrorAction SilentlyContinue) -eq $null)
{
Write-Host "installing bower..."
npm install -g bower
}
if((Get-Command "gulp" -ErrorAction SilentlyContinue) -eq $null)
{
Write-Host "installing gulp..."
npm install -g gulp
}
}
function PrepareWebEnvironment
{
npm install
bower install
gulp npmtolib
}
# Set environment variables for development and testing:
$env:ASPNETCORE_ENVIRONMENT="Development" # Set ASP.NET Core environment to Development to enable dev logging, and other dev-only services
${env:Identity:IdentityServer:RequireHttps} = "false"
# The following settings configure the Identity clients for integration tests
# They are also in the launchSettings.json for Nether.Web for the VS experience
${env:Identity:Clients:clientcreds-test:Name} = "Test Client for client credentials flow"
${env:Identity:Clients:clientcreds-test:AllowedGrantTypes} = "client_credentials"
${env:Identity:Clients:clientcreds-test:ClientSecrets} = "devsecret"
${env:Identity:Clients:clientcreds-test:AllowedScopes} = "openid, profile, nether-all"
${env:Identity:Clients:resourceowner-test:AllowedGrantTypes} = "password"
${env:Identity:Clients:resourceowner-test:ClientSecrets} = "devsecret"
${env:Identity:Clients:resourceowner-test:AllowedScopes} = "nether-all"
${env:Identity:Clients:customgrant-test:AllowedGrantTypes} = "fb-usertoken"
${env:Identity:Clients:customgrant-test:ClientSecrets} = "devsecret"
${env:Identity:Clients:customgrant-test:AllowedScopes} = "nether-all"
Push-Location
cd src/Nether.Web
try{
CheckDependencies
PrepareWebEnvironment
dotnet watch run
}
finally{
Pop-Location
}
|
mit
|
canton7/Stylet
|
Stylet/StyletIoC/Internal/Creators/CreatorBase.cs
|
2037
|
using StyletIoC.Creation;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
namespace StyletIoC.Internal.Creators
{
/// <summary>
/// Base class for all ICreators (which want to use it). Provides convenience
/// </summary>
internal abstract class CreatorBase : ICreator
{
public virtual RuntimeTypeHandle TypeHandle { get; protected set; }
protected IRegistrationContext ParentContext { get; set; }
protected CreatorBase(IRegistrationContext parentContext)
{
this.ParentContext = parentContext;
}
// Common utility method
protected Expression CompleteExpressionFromCreator(Expression creator, ParameterExpression registrationContext)
{
var type = Type.GetTypeFromHandle(this.TypeHandle);
var instanceVar = Expression.Variable(type, "instance");
var assignment = Expression.Assign(instanceVar, creator);
var buildUpExpression = this.ParentContext.GetBuilderUpper(type).GetExpression(instanceVar, registrationContext);
// We always start with:
// var instance = new Class(.....)
// instance.Property1 = new ....
// instance.Property2 = new ....
var blockItems = new List<Expression>() { assignment, buildUpExpression };
// If it implements IInjectionAware, follow that up with:
// instance.ParametersInjected()
if (typeof(IInjectionAware).IsAssignableFrom(type))
blockItems.Add(Expression.Call(instanceVar, typeof(IInjectionAware).GetMethod("ParametersInjected")));
// Final appearance of instanceVar, as this sets the return value of the block
blockItems.Add(instanceVar);
var completeExpression = Expression.Block(new[] { instanceVar }, blockItems);
return completeExpression;
}
public abstract Expression GetInstanceExpression(ParameterExpression registrationContext);
}
}
|
mit
|
Olog/olog.github.com
|
2.2.4-SNAPSHOT/modules/olog-service/xref/edu/msu/nscl/olog/Logbooks.html
|
12532
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Logbooks xref</title>
<link type="text/css" rel="stylesheet" href="../../../../stylesheet.css" />
</head>
<body>
<div id="overview"><a href="../../../../../apidocs/edu/msu/nscl/olog/Logbooks.html">View Javadoc</a></div><pre>
<a class="jxr_linenumber" name="1" href="#1">1</a> <em class="jxr_comment">/*</em>
<a class="jxr_linenumber" name="2" href="#2">2</a> <em class="jxr_comment"> * Copyright (c) 2010 Brookhaven National Laboratory</em>
<a class="jxr_linenumber" name="3" href="#3">3</a> <em class="jxr_comment"> * Copyright (c) 2010 Helmholtz-Zentrum Berlin fuer Materialien und Energie GmbH</em>
<a class="jxr_linenumber" name="4" href="#4">4</a> <em class="jxr_comment"> * Subject to license terms and conditions.</em>
<a class="jxr_linenumber" name="5" href="#5">5</a> <em class="jxr_comment"> */</em>
<a class="jxr_linenumber" name="6" href="#6">6</a> <strong class="jxr_keyword">package</strong> edu.msu.nscl.olog;
<a class="jxr_linenumber" name="7" href="#7">7</a>
<a class="jxr_linenumber" name="8" href="#8">8</a> <strong class="jxr_keyword">import</strong> java.util.ArrayList;
<a class="jxr_linenumber" name="9" href="#9">9</a> <strong class="jxr_keyword">import</strong> java.util.Collection;
<a class="jxr_linenumber" name="10" href="#10">10</a> <strong class="jxr_keyword">import</strong> java.util.Set;
<a class="jxr_linenumber" name="11" href="#11">11</a> <strong class="jxr_keyword">import</strong> javax.xml.bind.annotation.XmlRootElement;
<a class="jxr_linenumber" name="12" href="#12">12</a> <strong class="jxr_keyword">import</strong> javax.xml.bind.annotation.XmlElement;
<a class="jxr_linenumber" name="13" href="#13">13</a>
<a class="jxr_linenumber" name="14" href="#14">14</a> <em class="jxr_javadoccomment">/**</em>
<a class="jxr_linenumber" name="15" href="#15">15</a> <em class="jxr_javadoccomment"> * Logbooks (collection) object that can be represented as XML/JSON in payload</em>
<a class="jxr_linenumber" name="16" href="#16">16</a> <em class="jxr_javadoccomment"> * data.</em>
<a class="jxr_linenumber" name="17" href="#17">17</a> <em class="jxr_javadoccomment"> *</em>
<a class="jxr_linenumber" name="18" href="#18">18</a> <em class="jxr_javadoccomment"> * @author Eric Berryman taken from Ralph Lange <Ralph.Lange@bessy.de></em>
<a class="jxr_linenumber" name="19" href="#19">19</a> <em class="jxr_javadoccomment"> */</em>
<a class="jxr_linenumber" name="20" href="#20">20</a> @XmlRootElement(name = <span class="jxr_string">"logbooks"</span>)
<a class="jxr_linenumber" name="21" href="#21">21</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">class</strong> <a href="../../../../edu/msu/nscl/olog/Logbooks.html">Logbooks</a> {
<a class="jxr_linenumber" name="22" href="#22">22</a>
<a class="jxr_linenumber" name="23" href="#23">23</a> <strong class="jxr_keyword">private</strong> Collection<Logbook> logbooks = <strong class="jxr_keyword">new</strong> ArrayList<Logbook>();
<a class="jxr_linenumber" name="24" href="#24">24</a>
<a class="jxr_linenumber" name="25" href="#25">25</a> <em class="jxr_javadoccomment">/**</em>
<a class="jxr_linenumber" name="26" href="#26">26</a> <em class="jxr_javadoccomment"> * Creates a new instance of Logbooks.</em>
<a class="jxr_linenumber" name="27" href="#27">27</a> <em class="jxr_javadoccomment"> */</em>
<a class="jxr_linenumber" name="28" href="#28">28</a> <strong class="jxr_keyword">public</strong> <a href="../../../../edu/msu/nscl/olog/Logbooks.html">Logbooks</a>() {
<a class="jxr_linenumber" name="29" href="#29">29</a> }
<a class="jxr_linenumber" name="30" href="#30">30</a>
<a class="jxr_linenumber" name="31" href="#31">31</a> <em class="jxr_javadoccomment">/**</em>
<a class="jxr_linenumber" name="32" href="#32">32</a> <em class="jxr_javadoccomment"> * Creates a new instance of Logbooks with one initial logbook.</em>
<a class="jxr_linenumber" name="33" href="#33">33</a> <em class="jxr_javadoccomment"> *</em>
<a class="jxr_linenumber" name="34" href="#34">34</a> <em class="jxr_javadoccomment"> * @param logbook initial element</em>
<a class="jxr_linenumber" name="35" href="#35">35</a> <em class="jxr_javadoccomment"> */</em>
<a class="jxr_linenumber" name="36" href="#36">36</a> <strong class="jxr_keyword">public</strong> <a href="../../../../edu/msu/nscl/olog/Logbooks.html">Logbooks</a>(<a href="../../../../edu/msu/nscl/olog/Logbook.html">Logbook</a> logbook) {
<a class="jxr_linenumber" name="37" href="#37">37</a> logbooks.add(logbook);
<a class="jxr_linenumber" name="38" href="#38">38</a> }
<a class="jxr_linenumber" name="39" href="#39">39</a>
<a class="jxr_linenumber" name="40" href="#40">40</a> <em class="jxr_javadoccomment">/**</em>
<a class="jxr_linenumber" name="41" href="#41">41</a> <em class="jxr_javadoccomment"> * Returns a collection of Logbook.</em>
<a class="jxr_linenumber" name="42" href="#42">42</a> <em class="jxr_javadoccomment"> *</em>
<a class="jxr_linenumber" name="43" href="#43">43</a> <em class="jxr_javadoccomment"> * @return logbooks a collection of Logbook</em>
<a class="jxr_linenumber" name="44" href="#44">44</a> <em class="jxr_javadoccomment"> */</em>
<a class="jxr_linenumber" name="45" href="#45">45</a> @XmlElement(name = <span class="jxr_string">"logbook"</span>)
<a class="jxr_linenumber" name="46" href="#46">46</a> <strong class="jxr_keyword">public</strong> Collection<Logbook> getLogbooks() {
<a class="jxr_linenumber" name="47" href="#47">47</a> <strong class="jxr_keyword">return</strong> logbooks;
<a class="jxr_linenumber" name="48" href="#48">48</a> }
<a class="jxr_linenumber" name="49" href="#49">49</a>
<a class="jxr_linenumber" name="50" href="#50">50</a> <em class="jxr_javadoccomment">/**</em>
<a class="jxr_linenumber" name="51" href="#51">51</a> <em class="jxr_javadoccomment"> * Sets the collection of logbooks.</em>
<a class="jxr_linenumber" name="52" href="#52">52</a> <em class="jxr_javadoccomment"> *</em>
<a class="jxr_linenumber" name="53" href="#53">53</a> <em class="jxr_javadoccomment"> * @param items new logbook collection</em>
<a class="jxr_linenumber" name="54" href="#54">54</a> <em class="jxr_javadoccomment"> */</em>
<a class="jxr_linenumber" name="55" href="#55">55</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">void</strong> setLogbooks(Collection<Logbook> items) {
<a class="jxr_linenumber" name="56" href="#56">56</a> <strong class="jxr_keyword">this</strong>.logbooks = items;
<a class="jxr_linenumber" name="57" href="#57">57</a> }
<a class="jxr_linenumber" name="58" href="#58">58</a>
<a class="jxr_linenumber" name="59" href="#59">59</a> <em class="jxr_javadoccomment">/**</em>
<a class="jxr_linenumber" name="60" href="#60">60</a> <em class="jxr_javadoccomment"> * Adds a logbook to the logbook collection.</em>
<a class="jxr_linenumber" name="61" href="#61">61</a> <em class="jxr_javadoccomment"> *</em>
<a class="jxr_linenumber" name="62" href="#62">62</a> <em class="jxr_javadoccomment"> * @param item the Logbook to add</em>
<a class="jxr_linenumber" name="63" href="#63">63</a> <em class="jxr_javadoccomment"> */</em>
<a class="jxr_linenumber" name="64" href="#64">64</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">void</strong> addLogbook(<a href="../../../../edu/msu/nscl/olog/Logbook.html">Logbook</a> item) {
<a class="jxr_linenumber" name="65" href="#65">65</a> <strong class="jxr_keyword">this</strong>.logbooks.add(item);
<a class="jxr_linenumber" name="66" href="#66">66</a> }
<a class="jxr_linenumber" name="67" href="#67">67</a>
<a class="jxr_linenumber" name="68" href="#68">68</a> <em class="jxr_javadoccomment">/**</em>
<a class="jxr_linenumber" name="69" href="#69">69</a> <em class="jxr_javadoccomment"> * Creates a compact string representation for the log.</em>
<a class="jxr_linenumber" name="70" href="#70">70</a> <em class="jxr_javadoccomment"> *</em>
<a class="jxr_linenumber" name="71" href="#71">71</a> <em class="jxr_javadoccomment"> * @param data XmlLog to create the string representation for</em>
<a class="jxr_linenumber" name="72" href="#72">72</a> <em class="jxr_javadoccomment"> * @return string representation</em>
<a class="jxr_linenumber" name="73" href="#73">73</a> <em class="jxr_javadoccomment"> */</em>
<a class="jxr_linenumber" name="74" href="#74">74</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">static</strong> String toLogger(<a href="../../../../edu/msu/nscl/olog/Logbooks.html">Logbooks</a> data) {
<a class="jxr_linenumber" name="75" href="#75">75</a> <strong class="jxr_keyword">if</strong> (data.getLogbooks().size() == 0) {
<a class="jxr_linenumber" name="76" href="#76">76</a> <strong class="jxr_keyword">return</strong> <span class="jxr_string">"[None]"</span>;
<a class="jxr_linenumber" name="77" href="#77">77</a> } <strong class="jxr_keyword">else</strong> {
<a class="jxr_linenumber" name="78" href="#78">78</a> StringBuilder s = <strong class="jxr_keyword">new</strong> StringBuilder();
<a class="jxr_linenumber" name="79" href="#79">79</a> s.append(<span class="jxr_string">"["</span>);
<a class="jxr_linenumber" name="80" href="#80">80</a> <strong class="jxr_keyword">for</strong> (Logbook p : data.getLogbooks()) {
<a class="jxr_linenumber" name="81" href="#81">81</a> s.append(Logbook.toLogger(p) + <span class="jxr_string">","</span>);
<a class="jxr_linenumber" name="82" href="#82">82</a> }
<a class="jxr_linenumber" name="83" href="#83">83</a> s.delete(s.length() - 1, s.length());
<a class="jxr_linenumber" name="84" href="#84">84</a> s.append(<span class="jxr_string">"]"</span>);
<a class="jxr_linenumber" name="85" href="#85">85</a> <strong class="jxr_keyword">return</strong> s.toString();
<a class="jxr_linenumber" name="86" href="#86">86</a> }
<a class="jxr_linenumber" name="87" href="#87">87</a> }
<a class="jxr_linenumber" name="88" href="#88">88</a>
<a class="jxr_linenumber" name="89" href="#89">89</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">static</strong> String toLogger(Set<Logbook> data) {
<a class="jxr_linenumber" name="90" href="#90">90</a> <strong class="jxr_keyword">if</strong> (data.size() == 0) {
<a class="jxr_linenumber" name="91" href="#91">91</a> <strong class="jxr_keyword">return</strong> <span class="jxr_string">"[None]"</span>;
<a class="jxr_linenumber" name="92" href="#92">92</a> } <strong class="jxr_keyword">else</strong> {
<a class="jxr_linenumber" name="93" href="#93">93</a> StringBuilder s = <strong class="jxr_keyword">new</strong> StringBuilder();
<a class="jxr_linenumber" name="94" href="#94">94</a> s.append(<span class="jxr_string">"["</span>);
<a class="jxr_linenumber" name="95" href="#95">95</a> <strong class="jxr_keyword">for</strong> (Logbook p : data) {
<a class="jxr_linenumber" name="96" href="#96">96</a> s.append(Logbook.toLogger(p) + <span class="jxr_string">","</span>);
<a class="jxr_linenumber" name="97" href="#97">97</a> }
<a class="jxr_linenumber" name="98" href="#98">98</a> s.delete(s.length() - 1, s.length());
<a class="jxr_linenumber" name="99" href="#99">99</a> s.append(<span class="jxr_string">"]"</span>);
<a class="jxr_linenumber" name="100" href="#100">100</a> <strong class="jxr_keyword">return</strong> s.toString();
<a class="jxr_linenumber" name="101" href="#101">101</a> }
<a class="jxr_linenumber" name="102" href="#102">102</a> }
<a class="jxr_linenumber" name="103" href="#103">103</a> }
</pre>
<hr/><div id="footer">This page was automatically generated by <a href="http://maven.apache.org/">Maven</a></div></body>
</html>
|
mit
|
OlivierCoue/invow
|
src/app/tc-shared/tc-sortable.directive.ts
|
2177
|
import { Directive, ElementRef, EventEmitter, Output, Input, OnInit } from '@angular/core';
import { TcCollectionService } from '../tc-collection/tc-collection.service';
import { TcCollection } from '../tc-collection/tc-collection.class';
declare var $: any;
@Directive({ selector: '[tc-sortable]' })
export class TcSortableDirective {
@Input('ignoreItem') ignoreItem = 0;
@Input('list') list: any[];
@Input('ghostClass') ghostClass: string;
@Output() itemMoved = new EventEmitter();
private element: HTMLElement;
constructor(public el: ElementRef, private collectionService: TcCollectionService) {
}
ngOnInit() {
this.element = this.el.nativeElement;
var elCopy = this.element;
let newIndex;
let oldIndex;
$(this.element).sortable({
placeholder: this.ghostClass,
helper: function(x, y){ y.addClass('card-moving'); return y },
handle: '.card-collection--drag-handle',
cancel: '.cancel-sort',
tolerance: "pointer",
items: "> :not(.not-sortable-item)",
scroll: false,
start: (event, ui) => {
$(this).attr('data-previndex', ui.item.index());
},
update: (event, ui) => {
newIndex = ui.item.index()-this.ignoreItem;
oldIndex = $(this).attr('data-previndex')-this.ignoreItem;
$(this).removeAttr('data-previndex');
},
stop: (event, ui) => {
ui.item.removeClass('card-moving');
let tmpItem = this.list[oldIndex];
if(!tmpItem)
return;
tmpItem.position = newIndex;
tmpItem.updatePosition = true;
this.itemMoved.emit({
value: {modifiedItem: tmpItem}
})
tmpItem.updatePosition = false;
this.list.splice(oldIndex,1);
this.list.splice(newIndex, 0, tmpItem);
for(let i in this.list){
this.list[i].position = i;
}
}
})
}
}
|
mit
|
demisto/content
|
Packs/CVE_2021_44228/ReleaseNotes/1_0_1.md
|
79
|
#### Playbooks
##### CVE-2021-44228 - Log4j RCE
- Added Sigma and Yara rules.
|
mit
|
PS-Group/cg_course_examples
|
chapter_4/lesson_19/main.cpp
|
620
|
#include "stdafx.h"
#include "WindowClient.h"
#include <SDL2/SDL.h>
int main(int, char *[])
{
try
{
CWindow window(ContextProfile::RobustOpenGL_3_2, ContextMode::Normal);
// window.ShowFullscreen("Demo #19 (Particle Systems)");
window.Show("Demo #19 (Particle Systems)", {800, 600});
CWindowClient client(window);
window.DoMainLoop();
}
catch (const std::exception &ex)
{
const char *title = "Fatal Error";
const char *message = ex.what();
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, title, message, nullptr);
}
return 0;
}
|
mit
|
georghinkel/ttc2017smartGrids
|
solutions/eMoflon/rgse.ttc17.metamodels.src/src/gluemodel/COSEM/COSEMObjects/impl/PushScheduleImpl.java
|
844
|
/**
*/
package gluemodel.COSEM.COSEMObjects.impl;
import gluemodel.COSEM.COSEMObjects.COSEMObjectsPackage;
import gluemodel.COSEM.COSEMObjects.PushSchedule;
import gluemodel.COSEM.InterfaceClasses.impl.SingleactionscheduleImpl;
import org.eclipse.emf.ecore.EClass;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Push Schedule</b></em>'.
* <!-- end-user-doc -->
*
* @generated
*/
public class PushScheduleImpl extends SingleactionscheduleImpl implements PushSchedule {
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected PushScheduleImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return COSEMObjectsPackage.eINSTANCE.getPushSchedule();
}
} //PushScheduleImpl
|
mit
|
floooh/oryol
|
code/Modules/LocalFS/private/dummy/dummyFSWrapper.cc
|
1707
|
//------------------------------------------------------------------------------
// dummyFSWrapper.cc
//------------------------------------------------------------------------------
#include "Pre.h"
#include "dummyFSWrapper.h"
namespace Oryol {
namespace _priv {
//------------------------------------------------------------------------------
dummyFSWrapper::handle
dummyFSWrapper::openRead(const char* path) {
return invalidHandle;
}
//------------------------------------------------------------------------------
dummyFSWrapper::handle
dummyFSWrapper::openWrite(const char* path) {
return invalidHandle;
}
//------------------------------------------------------------------------------
int
dummyFSWrapper::write(handle f, const void* ptr, int numBytes) {
return 0;
}
//------------------------------------------------------------------------------
int
dummyFSWrapper::read(handle f, void* ptr, int numBytes) {
return 0;
}
//------------------------------------------------------------------------------
bool
dummyFSWrapper::seek(handle f, int offset) {
return true;
}
//------------------------------------------------------------------------------
int
dummyFSWrapper::size(handle f) {
return 0;
}
//------------------------------------------------------------------------------
void
dummyFSWrapper::close(handle f) {
// empty
}
//------------------------------------------------------------------------------
String
dummyFSWrapper::getExecutableDir() {
return String();
}
//------------------------------------------------------------------------------
String
dummyFSWrapper::getCwd() {
return String();
}
} // namespace _priv
} // namespace Oryol
|
mit
|
amirbawab/CPP-LAB
|
design-patterns/factory-method/SolidFrame.h
|
165
|
#ifndef FACTORY_METHOD_SOLIDFRAME_H
#define FACTORY_METHOD_SOLIDFRAME_H
#include "Frame.h"
class SolidFrame : public Frame {
public:
void print();
};
#endif
|
mit
|
mixxmac/jekyll
|
lib/jekyll/version.rb
|
48
|
module Jekyll
VERSION = '3.0.0.pre.beta6'
end
|
mit
|
ilendl2/wagtail-cookiecutter-foundation
|
{{cookiecutter.project_slug}}/gallery/models.py
|
4587
|
import logging
from django.conf import settings
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.db import models
from django.utils.translation import ugettext_lazy as _
from wagtail.admin.edit_handlers import FieldPanel, MultiFieldPanel
from wagtail.core.fields import RichTextField
from wagtail.core.models import Page
from wagtail.images.models import Image
from wagtail.images.edit_handlers import ImageChooserPanel
class PhotoGalleryIndexPage(Page):
intro = RichTextField(blank=True)
feed_image = models.ForeignKey(
Image,
help_text="An optional image to represent the page",
null=True,
blank=True,
on_delete=models.SET_NULL,
related_name='+'
)
indexed_fields = ('intro')
@property
def galleries(self):
galleries = GalleryIndex.objects.live().descendant_of(self)
galleries = galleries.order_by('-first_published_at')
return galleries
def get_context(self, request):
galleries = self.galleries
page = request.GET.get('page')
paginator = Paginator(galleries, 16)
try:
galleries = paginator.page(page)
except PageNotAnInteger:
galleries = paginator.page(1)
except EmptyPage:
galleries = paginator.page(paginator.num_pages)
context = super(PhotoGalleryIndexPage, self).get_context(request)
context['galleries'] = galleries
return context
class Meta:
verbose_name = _('Photo Gallery Index')
PhotoGalleryIndexPage.content_panels = [
FieldPanel('title', classname="full title"),
FieldPanel('intro', classname="full"),
]
PhotoGalleryIndexPage.promote_panels = [
MultiFieldPanel(Page.promote_panels, "Common page configuration"),
ImageChooserPanel('feed_image'),
]
IMAGE_ORDER_TYPES = (
(1, 'Image title'),
(2, 'Newest image first'),
)
class GalleryIndex(Page):
intro = RichTextField(
blank=True,
verbose_name=_('Intro text'),
help_text=_('Optional text to go with the intro text.')
)
collection = models.ForeignKey(
'wagtailcore.Collection',
verbose_name=_('Collection'),
null=True,
blank=False,
on_delete=models.SET_NULL,
related_name='+',
help_text=_('Show images in this collection in the gallery view.')
)
images_per_page = models.IntegerField(
default=20,
verbose_name=_('Images per page'),
help_text=_('How many images there should be on one page.')
)
order_images_by = models.IntegerField(choices=IMAGE_ORDER_TYPES, default=1)
feed_image = models.ForeignKey(
Image,
help_text="An optional image to represent the page",
null=True,
blank=True,
on_delete=models.SET_NULL,
related_name='+'
)
content_panels = Page.content_panels + [
FieldPanel('intro', classname='full title'),
FieldPanel('collection'),
FieldPanel('images_per_page', classname='full title'),
FieldPanel('order_images_by'),
]
promote_panels = [
MultiFieldPanel(Page.promote_panels, "Common page configuration"),
ImageChooserPanel('feed_image'),
]
@property
def images(self):
return get_gallery_images(self.collection.name, self)
def get_context(self, request):
images = self.images
page = request.GET.get('page')
paginator = Paginator(images, self.images_per_page)
try:
images = paginator.page(page)
except PageNotAnInteger:
images = paginator.page(1)
except EmptyPage:
images = paginator.page(paginator.num_pages)
context = super(GalleryIndex, self).get_context(request)
context['gallery_images'] = images
return context
class Meta:
verbose_name = _('Photo Gallery')
verbose_name_plural = _('Photo Galleries')
template = getattr(settings, 'GALLERY_TEMPLATE', 'gallery/gallery_index.html')
def get_gallery_images(collection, page=None, tags=None):
images = None
try:
images = Image.objects.filter(collection__name=collection)
if page:
if page.order_images_by == 0:
images = images.order_by('title')
elif page.order_images_by == 1:
images = images.order_by('-created_at')
except Exception as e:
logging.exception(e)
if images and tags:
images = images.filter(tags__name__in=tags).distinct()
return images
|
mit
|
enotio/Tempest
|
docs/html/class_tempest_1_1_layout-members.html
|
10961
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.12"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Tempest: Member List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtreedata.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<script type="text/javascript">
$(document).ready(initResizable);
</script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { init_search(); });
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
<link href="style.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectlogo"><img alt="Logo" src="icon.png"/></td>
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">Tempest
</div>
</td>
<td> <div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.12 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
</div><!-- top -->
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
<div id="nav-sync" class="sync"></div>
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){initNavTree('class_tempest_1_1_layout.html','');});
</script>
<div id="doc-content">
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div class="header">
<div class="headertitle">
<div class="title">Tempest::Layout Member List</div> </div>
</div><!--header-->
<div class="contents">
<p>This is the complete list of members for <a class="el" href="class_tempest_1_1_layout.html">Tempest::Layout</a>, including all inherited members.</p>
<table class="directory">
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>add</b>(Widget *w, size_t pos) (defined in <a class="el" href="class_tempest_1_1_layout.html">Tempest::Layout</a>)</td><td class="entry"><a class="el" href="class_tempest_1_1_layout.html">Tempest::Layout</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>add</b>(Widget *widget) (defined in <a class="el" href="class_tempest_1_1_layout.html">Tempest::Layout</a>)</td><td class="entry"><a class="el" href="class_tempest_1_1_layout.html">Tempest::Layout</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>applyLayout</b>() (defined in <a class="el" href="class_tempest_1_1_layout.html">Tempest::Layout</a>)</td><td class="entry"><a class="el" href="class_tempest_1_1_layout.html">Tempest::Layout</a></td><td class="entry"><span class="mlabel">inline</span><span class="mlabel">virtual</span></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>del</b>(Widget *widget) (defined in <a class="el" href="class_tempest_1_1_layout.html">Tempest::Layout</a>)</td><td class="entry"><a class="el" href="class_tempest_1_1_layout.html">Tempest::Layout</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>Layout</b>() (defined in <a class="el" href="class_tempest_1_1_layout.html">Tempest::Layout</a>)</td><td class="entry"><a class="el" href="class_tempest_1_1_layout.html">Tempest::Layout</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>margin</b>() const (defined in <a class="el" href="class_tempest_1_1_layout.html">Tempest::Layout</a>)</td><td class="entry"><a class="el" href="class_tempest_1_1_layout.html">Tempest::Layout</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>owner</b>() (defined in <a class="el" href="class_tempest_1_1_layout.html">Tempest::Layout</a>)</td><td class="entry"><a class="el" href="class_tempest_1_1_layout.html">Tempest::Layout</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>owner</b>() const (defined in <a class="el" href="class_tempest_1_1_layout.html">Tempest::Layout</a>)</td><td class="entry"><a class="el" href="class_tempest_1_1_layout.html">Tempest::Layout</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>placeIn</b>(Widget *wx, int x, int y, int w, int h) (defined in <a class="el" href="class_tempest_1_1_layout.html">Tempest::Layout</a>)</td><td class="entry"><a class="el" href="class_tempest_1_1_layout.html">Tempest::Layout</a></td><td class="entry"><span class="mlabel">static</span></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>placeIn</b>(Widget *wx, const Rect &r) (defined in <a class="el" href="class_tempest_1_1_layout.html">Tempest::Layout</a>)</td><td class="entry"><a class="el" href="class_tempest_1_1_layout.html">Tempest::Layout</a></td><td class="entry"><span class="mlabel">static</span></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>removeAll</b>() (defined in <a class="el" href="class_tempest_1_1_layout.html">Tempest::Layout</a>)</td><td class="entry"><a class="el" href="class_tempest_1_1_layout.html">Tempest::Layout</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>setMargin</b>(const Margin &m) (defined in <a class="el" href="class_tempest_1_1_layout.html">Tempest::Layout</a>)</td><td class="entry"><a class="el" href="class_tempest_1_1_layout.html">Tempest::Layout</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>setMargin</b>(int l, int r, int t, int b) (defined in <a class="el" href="class_tempest_1_1_layout.html">Tempest::Layout</a>)</td><td class="entry"><a class="el" href="class_tempest_1_1_layout.html">Tempest::Layout</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>setSpacing</b>(int s) (defined in <a class="el" href="class_tempest_1_1_layout.html">Tempest::Layout</a>)</td><td class="entry"><a class="el" href="class_tempest_1_1_layout.html">Tempest::Layout</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>sizeHint</b>(const Widget *wx) (defined in <a class="el" href="class_tempest_1_1_layout.html">Tempest::Layout</a>)</td><td class="entry"><a class="el" href="class_tempest_1_1_layout.html">Tempest::Layout</a></td><td class="entry"><span class="mlabel">protected</span><span class="mlabel">static</span></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>spacing</b>() const (defined in <a class="el" href="class_tempest_1_1_layout.html">Tempest::Layout</a>)</td><td class="entry"><a class="el" href="class_tempest_1_1_layout.html">Tempest::Layout</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>summarySpacings</b>() (defined in <a class="el" href="class_tempest_1_1_layout.html">Tempest::Layout</a>)</td><td class="entry"><a class="el" href="class_tempest_1_1_layout.html">Tempest::Layout</a></td><td class="entry"><span class="mlabel">protected</span></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>take</b>(Widget *widget) (defined in <a class="el" href="class_tempest_1_1_layout.html">Tempest::Layout</a>)</td><td class="entry"><a class="el" href="class_tempest_1_1_layout.html">Tempest::Layout</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>visibleCount</b>() const (defined in <a class="el" href="class_tempest_1_1_layout.html">Tempest::Layout</a>)</td><td class="entry"><a class="el" href="class_tempest_1_1_layout.html">Tempest::Layout</a></td><td class="entry"><span class="mlabel">protected</span></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>Widget</b> (defined in <a class="el" href="class_tempest_1_1_layout.html">Tempest::Layout</a>)</td><td class="entry"><a class="el" href="class_tempest_1_1_layout.html">Tempest::Layout</a></td><td class="entry"><span class="mlabel">friend</span></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>widgets</b>() (defined in <a class="el" href="class_tempest_1_1_layout.html">Tempest::Layout</a>)</td><td class="entry"><a class="el" href="class_tempest_1_1_layout.html">Tempest::Layout</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>~Layout</b>() (defined in <a class="el" href="class_tempest_1_1_layout.html">Tempest::Layout</a>)</td><td class="entry"><a class="el" href="class_tempest_1_1_layout.html">Tempest::Layout</a></td><td class="entry"><span class="mlabel">virtual</span></td></tr>
</table></div><!-- contents -->
</div><!-- doc-content -->
<!-- start footer part -->
<div id="nav-path" class="navpath"><!-- id is needed for treeview function! -->
<ul>
<li class="footer">Generated by
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.12 </li>
</ul>
</div>
</body>
</html>
|
mit
|
mojmir-svoboda/BlackBoxTT
|
3rd_party/asio/src/examples/cpp03/porthopper/client.cpp
|
6839
|
//
// client.cpp
// ~~~~~~~~~~
//
// Copyright (c) 2003-2015 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#include <asio.hpp>
#include <boost/lambda/lambda.hpp>
#include <boost/lambda/bind.hpp>
#include <boost/lambda/if.hpp>
#include <boost/shared_ptr.hpp>
#include <algorithm>
#include <cstdlib>
#include <exception>
#include <iostream>
#include <string>
#include "protocol.hpp"
using namespace boost;
using asio::ip::tcp;
using asio::ip::udp;
int main(int argc, char* argv[])
{
try
{
if (argc != 3)
{
std::cerr << "Usage: client <host> <port>\n";
return 1;
}
using namespace std; // For atoi.
std::string host_name = argv[1];
std::string port = argv[2];
asio::io_context io_context;
// Determine the location of the server.
tcp::resolver resolver(io_context);
tcp::endpoint remote_endpoint = *resolver.resolve(host_name, port).begin();
// Establish the control connection to the server.
tcp::socket control_socket(io_context);
control_socket.connect(remote_endpoint);
// Create a datagram socket to receive data from the server.
boost::shared_ptr<udp::socket> data_socket(
new udp::socket(io_context, udp::endpoint(udp::v4(), 0)));
// Determine what port we will receive data on.
udp::endpoint data_endpoint = data_socket->local_endpoint();
// Ask the server to start sending us data.
control_request start = control_request::start(data_endpoint.port());
asio::write(control_socket, start.to_buffers());
unsigned long last_frame_number = 0;
for (;;)
{
// Receive 50 messages on the current data socket.
for (int i = 0; i < 50; ++i)
{
// Receive a frame from the server.
frame f;
data_socket->receive(f.to_buffers(), 0);
if (f.number() > last_frame_number)
{
last_frame_number = f.number();
std::cout << "\n" << f.payload();
}
}
// Time to switch to a new socket. To ensure seamless handover we will
// continue to receive packets using the old socket until data arrives on
// the new one.
std::cout << " Starting renegotiation";
// Create the new data socket.
boost::shared_ptr<udp::socket> new_data_socket(
new udp::socket(io_context, udp::endpoint(udp::v4(), 0)));
// Determine the new port we will use to receive data.
udp::endpoint new_data_endpoint = new_data_socket->local_endpoint();
// Ask the server to switch over to the new port.
control_request change = control_request::change(
data_endpoint.port(), new_data_endpoint.port());
asio::error_code control_result;
asio::async_write(control_socket, change.to_buffers(),
(
lambda::var(control_result) = lambda::_1
));
// Try to receive a frame from the server on the new data socket. If we
// successfully receive a frame on this new data socket we can consider
// the renegotation complete. In that case we will close the old data
// socket, which will cause any outstanding receive operation on it to be
// cancelled.
frame f1;
asio::error_code new_data_socket_result;
new_data_socket->async_receive(f1.to_buffers(),
(
// Note: lambda::_1 is the first argument to the callback handler,
// which in this case is the error code for the operation.
lambda::var(new_data_socket_result) = lambda::_1,
lambda::if_(!lambda::_1)
[
// We have successfully received a frame on the new data socket,
// so we can close the old data socket. This will cancel any
// outstanding receive operation on the old data socket.
lambda::var(data_socket) = boost::shared_ptr<udp::socket>()
]
));
// This loop will continue until we have successfully completed the
// renegotiation (i.e. received a frame on the new data socket), or some
// unrecoverable error occurs.
bool done = false;
while (!done)
{
// Even though we're performing a renegotation, we want to continue
// receiving data as smoothly as possible. Therefore we will continue to
// try to receive a frame from the server on the old data socket. If we
// receive a frame on this socket we will interrupt the io_context,
// print the frame, and resume waiting for the other operations to
// complete.
frame f2;
done = true; // Let's be optimistic.
if (data_socket) // Might have been closed by new_data_socket's handler.
{
data_socket->async_receive(f2.to_buffers(), 0,
(
lambda::if_(!lambda::_1)
[
// We have successfully received a frame on the old data
// socket. Stop the io_context so that we can print it.
lambda::bind(&asio::io_context::stop, &io_context),
lambda::var(done) = false
]
));
}
// Run the operations in parallel. This will block until all operations
// have finished, or until the io_context is interrupted. (No threads!)
io_context.restart();
io_context.run();
// If the io_context.run() was interrupted then we have received a frame
// on the old data socket. We need to keep waiting for the renegotation
// operations to complete.
if (!done)
{
if (f2.number() > last_frame_number)
{
last_frame_number = f2.number();
std::cout << "\n" << f2.payload();
}
}
}
// Since the loop has finished, we have either successfully completed
// the renegotation, or an error has occurred. First we'll check for
// errors.
if (control_result)
throw asio::system_error(control_result);
if (new_data_socket_result)
throw asio::system_error(new_data_socket_result);
// If we get here it means we have successfully started receiving data on
// the new data socket. This new data socket will be used from now on
// (until the next time we renegotiate).
std::cout << " Renegotiation complete";
data_socket = new_data_socket;
data_endpoint = new_data_endpoint;
if (f1.number() > last_frame_number)
{
last_frame_number = f1.number();
std::cout << "\n" << f1.payload();
}
}
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << std::endl;
}
return 0;
}
|
mit
|
darul75/nsjoy.github.io2
|
packages/articles/public/routes/articles.js
|
1768
|
'use strict';
//Setting up route
angular.module('mean.articles').config(['$stateProvider', 'markedProvider',
function($stateProvider, markedProvider) {
markedProvider.setOptions({
gfm: true,
tables: true,
breaks: true,
highlight: function (code) {
/* jshint ignore:start */
return hljs.highlightAuto(code).value;
/* jshint ignore:end */
}
});
// Check if the user is connected
var checkLoggedin = function($q, $timeout, $http, $location) {
// Initialize a new promise
var deferred = $q.defer();
// Make an AJAX call to check if the user is logged in
$http.get('/loggedin').success(function(user) {
// Authenticated
if (user !== '0') $timeout(deferred.resolve);
// Not Authenticated
else {
$timeout(deferred.reject);
$location.url('/login');
}
});
return deferred.promise;
};
// states for my app
$stateProvider
.state('all articles', {
url: '/articles',
templateUrl: 'articles/views/list.html',
//resolve: {
// loggedin: checkLoggedin
//}
})
.state('create article', {
url: '/articles/create',
templateUrl: 'articles/views/create.html',
resolve: {
loggedin: checkLoggedin
}
})
.state('edit article', {
url: '/articles/:articleId/edit',
templateUrl: 'articles/views/edit.html',
resolve: {
loggedin: checkLoggedin
}
})
.state('article by id', {
url: '/articles/:articleId',
templateUrl: 'articles/views/view.html',
//resolve: {
// loggedin: checkLoggedin
//}
});
}
]);
|
mit
|
EngineDreamer/DreamEngine
|
Engine/script/runtimelibrary/MeshRenderComponent_register.cs
|
2409
|
/****************************************************************************
Copyright (c) 2011-2013,WebJet Business Division,CYOU
http://www.genesis-3d.com.cn
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
using System;
using System.Runtime.CompilerServices;
using ScriptRuntime;
namespace ScriptRuntime
{
/// <summary>
/// 网格渲染组件类
/// </summary>
public partial class MeshRenderComponent : RenderComponent
{
// - internal call declare
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern private static void ICall_MeshRenderComponent_SetMeshID(MeshRenderComponent self, String sMeshId, int priority);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern private static void ICall_MeshRenderComponent_SetDrawDepth(MeshRenderComponent self, bool bDraw);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern private static int ICall_MeshRenderComponent_GetTriangleCount(MeshRenderComponent self);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern private static int ICall_MeshRenderComponent_GetVertexCount(MeshRenderComponent self);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern private static string ICall_MeshRenderComponent_GetMeshID(MeshRenderComponent self);
}
}
|
mit
|
misuqian/ExcelTool
|
eclipse/poi-3.12/docs/apidocs/org/apache/poi/hslf/model/textproperties/AlignmentTextProp.html
|
14938
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<title>AlignmentTextProp (POI API Documentation)</title>
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="AlignmentTextProp (POI API Documentation)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/AlignmentTextProp.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev Class</li>
<li><a href="../../../../../../org/apache/poi/hslf/model/textproperties/BitMaskTextProp.html" title="class in org.apache.poi.hslf.model.textproperties"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/apache/poi/hslf/model/textproperties/AlignmentTextProp.html" target="_top">Frames</a></li>
<li><a href="AlignmentTextProp.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#field_summary">Field</a> | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#methods_inherited_from_class_org.apache.poi.hslf.model.textproperties.TextProp">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field_detail">Field</a> | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li>Method</li>
</ul>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">org.apache.poi.hslf.model.textproperties</div>
<h2 title="Class AlignmentTextProp" class="title">Class AlignmentTextProp</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li><a href="../../../../../../org/apache/poi/hslf/model/textproperties/TextProp.html" title="class in org.apache.poi.hslf.model.textproperties">org.apache.poi.hslf.model.textproperties.TextProp</a></li>
<li>
<ul class="inheritance">
<li>org.apache.poi.hslf.model.textproperties.AlignmentTextProp</li>
</ul>
</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Implemented Interfaces:</dt>
<dd>java.lang.Cloneable</dd>
</dl>
<hr>
<br>
<pre>public class <span class="strong">AlignmentTextProp</span>
extends <a href="../../../../../../org/apache/poi/hslf/model/textproperties/TextProp.html" title="class in org.apache.poi.hslf.model.textproperties">TextProp</a></pre>
<div class="block">Definition for the alignment text property.</div>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- =========== FIELD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="field_summary">
<!-- -->
</a>
<h3>Field Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation">
<caption><span>Fields</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Field and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><code><strong><a href="../../../../../../org/apache/poi/hslf/model/textproperties/AlignmentTextProp.html#CENTER">CENTER</a></strong></code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><code><strong><a href="../../../../../../org/apache/poi/hslf/model/textproperties/AlignmentTextProp.html#JUSTIFY">JUSTIFY</a></strong></code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><code><strong><a href="../../../../../../org/apache/poi/hslf/model/textproperties/AlignmentTextProp.html#JUSTIFYLOW">JUSTIFYLOW</a></strong></code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><code><strong><a href="../../../../../../org/apache/poi/hslf/model/textproperties/AlignmentTextProp.html#LEFT">LEFT</a></strong></code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><code><strong><a href="../../../../../../org/apache/poi/hslf/model/textproperties/AlignmentTextProp.html#RIGHT">RIGHT</a></strong></code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><code><strong><a href="../../../../../../org/apache/poi/hslf/model/textproperties/AlignmentTextProp.html#THAIDISTRIBUTED">THAIDISTRIBUTED</a></strong></code> </td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="fields_inherited_from_class_org.apache.poi.hslf.model.textproperties.TextProp">
<!-- -->
</a>
<h3>Fields inherited from class org.apache.poi.hslf.model.textproperties.<a href="../../../../../../org/apache/poi/hslf/model/textproperties/TextProp.html" title="class in org.apache.poi.hslf.model.textproperties">TextProp</a></h3>
<code><a href="../../../../../../org/apache/poi/hslf/model/textproperties/TextProp.html#dataValue">dataValue</a>, <a href="../../../../../../org/apache/poi/hslf/model/textproperties/TextProp.html#maskInHeader">maskInHeader</a>, <a href="../../../../../../org/apache/poi/hslf/model/textproperties/TextProp.html#propName">propName</a>, <a href="../../../../../../org/apache/poi/hslf/model/textproperties/TextProp.html#sizeOfDataBlock">sizeOfDataBlock</a></code></li>
</ul>
</li>
</ul>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><strong><a href="../../../../../../org/apache/poi/hslf/model/textproperties/AlignmentTextProp.html#AlignmentTextProp()">AlignmentTextProp</a></strong>()</code> </td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_org.apache.poi.hslf.model.textproperties.TextProp">
<!-- -->
</a>
<h3>Methods inherited from class org.apache.poi.hslf.model.textproperties.<a href="../../../../../../org/apache/poi/hslf/model/textproperties/TextProp.html" title="class in org.apache.poi.hslf.model.textproperties">TextProp</a></h3>
<code><a href="../../../../../../org/apache/poi/hslf/model/textproperties/TextProp.html#clone()">clone</a>, <a href="../../../../../../org/apache/poi/hslf/model/textproperties/TextProp.html#getMask()">getMask</a>, <a href="../../../../../../org/apache/poi/hslf/model/textproperties/TextProp.html#getName()">getName</a>, <a href="../../../../../../org/apache/poi/hslf/model/textproperties/TextProp.html#getSize()">getSize</a>, <a href="../../../../../../org/apache/poi/hslf/model/textproperties/TextProp.html#getValue()">getValue</a>, <a href="../../../../../../org/apache/poi/hslf/model/textproperties/TextProp.html#getWriteMask()">getWriteMask</a>, <a href="../../../../../../org/apache/poi/hslf/model/textproperties/TextProp.html#setValue(int)">setValue</a></code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ FIELD DETAIL =========== -->
<ul class="blockList">
<li class="blockList"><a name="field_detail">
<!-- -->
</a>
<h3>Field Detail</h3>
<a name="LEFT">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>LEFT</h4>
<pre>public static final int LEFT</pre>
<dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../../constant-values.html#org.apache.poi.hslf.model.textproperties.AlignmentTextProp.LEFT">Constant Field Values</a></dd></dl>
</li>
</ul>
<a name="CENTER">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>CENTER</h4>
<pre>public static final int CENTER</pre>
<dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../../constant-values.html#org.apache.poi.hslf.model.textproperties.AlignmentTextProp.CENTER">Constant Field Values</a></dd></dl>
</li>
</ul>
<a name="RIGHT">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>RIGHT</h4>
<pre>public static final int RIGHT</pre>
<dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../../constant-values.html#org.apache.poi.hslf.model.textproperties.AlignmentTextProp.RIGHT">Constant Field Values</a></dd></dl>
</li>
</ul>
<a name="JUSTIFY">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>JUSTIFY</h4>
<pre>public static final int JUSTIFY</pre>
<dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../../constant-values.html#org.apache.poi.hslf.model.textproperties.AlignmentTextProp.JUSTIFY">Constant Field Values</a></dd></dl>
</li>
</ul>
<a name="THAIDISTRIBUTED">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>THAIDISTRIBUTED</h4>
<pre>public static final int THAIDISTRIBUTED</pre>
<dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../../constant-values.html#org.apache.poi.hslf.model.textproperties.AlignmentTextProp.THAIDISTRIBUTED">Constant Field Values</a></dd></dl>
</li>
</ul>
<a name="JUSTIFYLOW">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>JUSTIFYLOW</h4>
<pre>public static final int JUSTIFYLOW</pre>
<dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../../constant-values.html#org.apache.poi.hslf.model.textproperties.AlignmentTextProp.JUSTIFYLOW">Constant Field Values</a></dd></dl>
</li>
</ul>
</li>
</ul>
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="AlignmentTextProp()">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>AlignmentTextProp</h4>
<pre>public AlignmentTextProp()</pre>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/AlignmentTextProp.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev Class</li>
<li><a href="../../../../../../org/apache/poi/hslf/model/textproperties/BitMaskTextProp.html" title="class in org.apache.poi.hslf.model.textproperties"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/apache/poi/hslf/model/textproperties/AlignmentTextProp.html" target="_top">Frames</a></li>
<li><a href="AlignmentTextProp.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#field_summary">Field</a> | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#methods_inherited_from_class_org.apache.poi.hslf.model.textproperties.TextProp">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field_detail">Field</a> | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li>Method</li>
</ul>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>
<i>Copyright 2015 The Apache Software Foundation or
its licensors, as applicable.</i>
</small></p>
</body>
</html>
|
mit
|
rmorrin/sample-code-csharp
|
PaypalExpressCheckout/PriorAuthorizationCapture.cs
|
3051
|
using System;
using System.Text;
using System.Threading.Tasks;
using System.Collections.Generic;
using AuthorizeNet.Api.Controllers;
using AuthorizeNet.Api.Contracts.V1;
using AuthorizeNet.Api.Controllers.Bases;
namespace net.authorize.sample
{
class PayPalPriorAuthorizationCapture
{
public static void Run(String ApiLoginID, String ApiTransactionKey, string TransactionID)
{
Console.WriteLine("PayPal Prior Authorization Transaction");
ApiOperationBase<ANetApiRequest, ANetApiResponse>.RunEnvironment = AuthorizeNet.Environment.SANDBOX;
// define the merchant information (authentication / transaction id)
ApiOperationBase<ANetApiRequest, ANetApiResponse>.MerchantAuthentication = new merchantAuthenticationType()
{
name = ApiLoginID,
ItemElementName = ItemChoiceType.transactionKey,
Item = ApiTransactionKey
};
var payPalType = new payPalType
{
cancelUrl = "http://www.merchanteCommerceSite.com/Success/TC25262",
successUrl = "http://www.merchanteCommerceSite.com/Success/TC25262", // the url where the user will be returned to
};
//standard api call to retrieve response
var paymentType = new paymentType { Item = payPalType };
var transactionRequest = new transactionRequestType
{
transactionType = transactionTypeEnum.priorAuthCaptureTransaction.ToString(), // capture a prior authorization
payment = paymentType,
amount = 19.45m,
refTransId = TransactionID // the TransID value that was returned from the first AuthOnlyTransaction call
};
var request = new createTransactionRequest { transactionRequest = transactionRequest };
// instantiate the contoller that will call the service
var controller = new createTransactionController(request);
controller.Execute();
// get the response from the service (errors contained if any)
var response = controller.GetApiResponse();
//validate
if (response.messages.resultCode == messageTypeEnum.Ok)
{
if (response.transactionResponse != null)
{
Console.WriteLine("Success, Auth Code : " + response.transactionResponse.authCode);
}
}
else
{
Console.WriteLine("Error: " + response.messages.message[0].code + " " + response.messages.message[0].text);
if (response.transactionResponse != null)
{
Console.WriteLine("Transaction Error : " + response.transactionResponse.errors[0].errorCode + " " + response.transactionResponse.errors[0].errorText);
}
}
}
}
}
|
mit
|
jaredjbarnes/WoodlandCreatures
|
packages/WebLib.2.0.0.724/content/lib/weblib/lib/BASE/LG/core/dataModel/core/PeopleGroupToPermission.js
|
545
|
BASE.require(["Object"], function () {
BASE.namespace("LG.core.dataModel.core");
LG.core.dataModel.core.PeopleGroupToPermission = (function (Super) {
var PeopleGroupToPermission = function () {
var self = this;
if (!(self instanceof arguments.callee)) {
return new PeopleGroupToPermission();
}
Super.call(self);
return self;
};
BASE.extend(PeopleGroupToPermission, Super);
return PeopleGroupToPermission;
}(Object));
});
|
mit
|
lucidphp/mux
|
tests/RouteTest.php
|
4374
|
<?php
/*
* This File is part of the Lucid\Mux package
*
* (c) iwyg <mail@thomas-appel.com>
*
* For full copyright and license information, please refer to the LICENSE file
* that was distributed with this package.
*/
namespace Lucid\Mux\Tests;
use Lucid\Mux\Route;
/**
* @class RouteTest
*
* @package Lucid\Mux
* @version $Id$
* @author iwyg <mail@thomas-appel.com>
*/
class RouteTest extends \PHPUnit_Framework_TestCase
{
/** @test */
public function itShouldBeInstantiable()
{
$this->assertInstanceOf('Lucid\Mux\RouteInterface', $this->newRoute());
}
/** @test */
public function itShouldGetPattern()
{
$route = new Route($pattern = '/user/{id}', 'action');
$this->assertSame($pattern, $route->getPattern());
}
/** @test */
public function itShouldBeSerializable()
{
$route = new Route(
$pattern = '/user/{id}',
$handler = 'action',
$methods = ['DELETE'],
$host = 'example.com',
$defaults = ['id' => 12],
$constraints = ['id' => '\d+'],
$schemes = ['https']
);
$newRoute = unserialize(serialize($route));
$this->assertSame($pattern, $newRoute->getPattern());
$this->assertSame($handler, $newRoute->getHandler());
$this->assertSame($methods, $newRoute->getMethods());
$this->assertSame($host, $newRoute->getHost());
$this->assertSame($defaults, $newRoute->getDefaults());
$this->assertSame($constraints, $newRoute->getConstraints());
$this->assertSame($schemes, $newRoute->getSchemes());
}
/** @test */
public function itShouldThrowIfSerializedAndAnderIsClosure()
{
$route = new Route('/', function () {
});
try {
serialize($route);
} catch (\LogicException $e) {
$this->assertEquals('Cannot serialize handler.', $e->getMessage());
}
}
/** @test */
public function itShouldGetMethods()
{
$route = new Route('/', 'action', ['POST']);
$this->assertTrue($route->hasMethod('post'));
$route = new Route('/', 'action', $methods = ['get', 'head']);
$this->assertTrue($route->hasMethod('get'));
$this->assertTrue($route->hasMethod('head'));
$this->assertSame(['GET', 'HEAD'], $route->getMethods());
}
/** @test */
public function itShouldGetSchemes()
{
$route = new Route('/', 'action');
$this->assertTrue($route->hasScheme('http'));
$this->assertTrue($route->hasScheme('https'));
$route = new Route('/', 'action', null, null, null, null, ['https']);
$this->assertFalse($route->hasScheme('http'));
$this->assertTrue($route->hasScheme('HTTPS'));
$route = new Route('/', 'action', null, null, null, null, null, ['HTTP', 'https']);
$this->assertSame(['http', 'https'], $route->getSchemes());
}
/** @test */
public function itShouldGetHost()
{
$route = new Route('/', 'action');
$this->assertNull($route->getHost());
$route = new Route('/', 'action', null, $host = 'example.com');
$this->assertSame($host, $route->getHost());
}
/** @test */
public function itShouldGetDefaults()
{
$route = new Route('/', 'action', null, null, $def = ['foo' => 'bar']);
$this->assertSame($def, $route->getDefaults());
$this->assertSame('bar', $route->getDefault('foo'));
}
/** @test */
public function itShouldGetConstraints()
{
$route = new Route('/', 'action', null, null, null, $const = ['foo' => 'bar']);
$this->assertSame($const, $route->getConstraints());
$this->assertSame('bar', $route->getConstraint('foo'));
}
/** @test */
public function itShouldCallParser()
{
$route = $this->getMock(Route::class, ['getParserFunc'], ['/', 'action']);
$route->method('getParserFunc')->willReturnCallback(function () {
return function () {
return 'RouteContext';
};
});
$this->assertSame('RouteContext', $route->getContext());
}
private function newRoute($path = '/', $handler = 'action')
{
return new Route($path, $handler);
}
}
|
mit
|
samwisehawkins/wrftools
|
util/split_time_dimension.py
|
1878
|
"""Splits the time dimension into an reftime and a leadtime
so that multiple files can be concatenated more easily"""
import sys
from netCDF4 import Dataset, num2date, date2num
for f in sys.argv[1:]:
dataset = Dataset(f, 'a')
# rename record dimension to reftime
dataset.renameDimension('record', 'reftime')
# rename time dimension to leadtime
dataset.renameDimension('time', 'leadtime')
dataset.renameVariable('time', 'leadtime')
time = dataset.variables['leadtime']
reftime = dataset.createVariable('reftime', 'f8', ('reftime',))
reftime.units = time.units
reftime.calendar = time.calendar
reftime[0] = time[0]
reftime.standard_name = "forecast_reference_time"
reftime.long_name = "Time of model initialization"
dt = num2date(time[:], units=time.units, calendar=time.calendar)
lt = date2num(dt, units="hours since %s" % dt[0], calendar=time.calendar)
# use the existing time variable to hold lead time information
time.units = "hours"
time.standard_name = "forecast_period"
time.long_name = "hours since forecast_reference_time"
time[:] = lt
del(time.calendar)
dataset.renameVariable('location', 'old_location')
dataset.renameVariable('lat', 'old_lat')
dataset.renameVariable('lon', 'old_lon')
dataset.renameVariable('height', 'old_height')
loc = dataset.createVariable('location', 'S1', ('location','loc_str_length'))
lat = dataset.createVariable('lat', 'f8', ('location',))
lon = dataset.createVariable('lon', 'f8', ('location',))
hgt = dataset.createVariable('height','i4',('height',))
loc[:] = dataset.variables['old_location'][0]
lat[:] = dataset.variables['old_lat'][0]
lon[:] = dataset.variables['old_lon'][0]
hgt[:] = dataset.variables['old_height'][0]
dataset.close()
|
mit
|
VirtualClub/vclub
|
browserExtensions/chromeExtension/content-script.js
|
658
|
/* global chrome */
const VERSION = 1;
const handlers = {
'vclub:screenShare:requestSourceId': () => {
chrome.runtime.sendMessage({ type: 'vclub:requestSourceId' }, (response) => {
window.postMessage({
type: 'vclub:screenShare:response',
response,
}, '*');
});
},
'vclub:ping': () => {
window.postMessage({
type: 'vclub:extension:loaded',
version: VERSION,
}, '*');
},
};
window.addEventListener('message', (event) => {
if (event.source !== window) return;
const handler = handlers[event.data.type];
if (handler) {
handler(event.data, event);
}
});
handlers['vclub:ping']();
|
mit
|
v-iam/azure-sdk-for-python
|
azure-mgmt-devtestlabs/azure/mgmt/devtestlabs/models/target_cost_properties.py
|
2286
|
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.serialization import Model
class TargetCostProperties(Model):
"""Properties of a cost target.
:param status: Target cost status. Possible values include: 'Enabled',
'Disabled'
:type status: str or :class:`TargetCostStatus
<azure.mgmt.devtestlabs.models.TargetCostStatus>`
:param target: Lab target cost
:type target: int
:param cost_thresholds: Cost thresholds.
:type cost_thresholds: list of :class:`CostThresholdProperties
<azure.mgmt.devtestlabs.models.CostThresholdProperties>`
:param cycle_start_date_time: Reporting cycle start date.
:type cycle_start_date_time: datetime
:param cycle_end_date_time: Reporting cycle end date.
:type cycle_end_date_time: datetime
:param cycle_type: Reporting cycle type. Possible values include:
'CalendarMonth', 'Custom'
:type cycle_type: str or :class:`ReportingCycleType
<azure.mgmt.devtestlabs.models.ReportingCycleType>`
"""
_attribute_map = {
'status': {'key': 'status', 'type': 'str'},
'target': {'key': 'target', 'type': 'int'},
'cost_thresholds': {'key': 'costThresholds', 'type': '[CostThresholdProperties]'},
'cycle_start_date_time': {'key': 'cycleStartDateTime', 'type': 'iso-8601'},
'cycle_end_date_time': {'key': 'cycleEndDateTime', 'type': 'iso-8601'},
'cycle_type': {'key': 'cycleType', 'type': 'str'},
}
def __init__(self, status=None, target=None, cost_thresholds=None, cycle_start_date_time=None, cycle_end_date_time=None, cycle_type=None):
self.status = status
self.target = target
self.cost_thresholds = cost_thresholds
self.cycle_start_date_time = cycle_start_date_time
self.cycle_end_date_time = cycle_end_date_time
self.cycle_type = cycle_type
|
mit
|
miguelgrinberg/Flask-HTTPAuth
|
tests/test_basic_hashed_password.py
|
2215
|
import unittest
import base64
from hashlib import md5 as basic_md5
from flask import Flask
from flask_httpauth import HTTPBasicAuth
def md5(s):
if isinstance(s, str):
s = s.encode('utf-8')
return basic_md5(s)
class HTTPAuthTestCase(unittest.TestCase):
def setUp(self):
app = Flask(__name__)
app.config['SECRET_KEY'] = 'my secret'
basic_custom_auth = HTTPBasicAuth()
@basic_custom_auth.get_password
def get_basic_custom_auth_get_password(username):
if username == 'john':
return md5('hello').hexdigest()
elif username == 'susan':
return md5('bye').hexdigest()
else:
return None
@basic_custom_auth.hash_password
def basic_custom_auth_hash_password(password):
return md5(password).hexdigest()
@app.route('/')
def index():
return 'index'
@app.route('/basic-custom')
@basic_custom_auth.login_required
def basic_custom_auth_route():
return 'basic_custom_auth:' + basic_custom_auth.username()
self.app = app
self.basic_custom_auth = basic_custom_auth
self.client = app.test_client()
def test_basic_auth_login_valid_with_hash1(self):
creds = base64.b64encode(b'john:hello').decode('utf-8')
response = self.client.get(
'/basic-custom', headers={'Authorization': 'Basic ' + creds})
self.assertEqual(response.data.decode('utf-8'),
'basic_custom_auth:john')
def test_basic_custom_auth_login_valid(self):
creds = base64.b64encode(b'john:hello').decode('utf-8')
response = self.client.get(
'/basic-custom', headers={'Authorization': 'Basic ' + creds})
self.assertEqual(response.data, b'basic_custom_auth:john')
def test_basic_custom_auth_login_invalid(self):
creds = base64.b64encode(b'john:bye').decode('utf-8')
response = self.client.get(
'/basic-custom', headers={"Authorization": "Basic " + creds})
self.assertEqual(response.status_code, 401)
self.assertTrue("WWW-Authenticate" in response.headers)
|
mit
|
andysylvester/TSW_WebAudioPrimer
|
ex06/index06.html
|
3114
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Starter Template for Bootstrap</title>
<!-- Bootstrap core CSS -->
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
<script src="tsw.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- Custom styles for this template -->
<link href="starter-template.css" rel="stylesheet">
<link href="slider.css" rel="stylesheet">
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Project name</a>
</div>
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#about">About</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
<div class="container">
<div class="starter-template">
<p>Press Play to hear how the pitch sounds. <button onclick="turn_on();">Play</button></p>
<p>Press Stop to turn it off. <button onclick="turn_off();">Stop</button></p>
<p>Start Chord <button onclick="playChord();">Start Chord</button></p>
<p>Stop Chord <button onclick="stopChord();">Stop Chord</button></p>
<p>Test function <button onclick="playScale();">Scale Test</button></p>
<center><p><input class="slider-width200" id="slider" type="range" min="0" max="1000" value="600" onchange="changePitch(this.value)"></p></center>
<form>
<input type="radio" name="oscType" value="sine" onclick="getOscType(this.value);" checked>Sine
<input type="radio" name="oscType" value="square" onclick="getOscType(this.value);">Square
<input type="radio" name="oscType" value="triangle" onclick="getOscType(this.value);">Triangle
<input type="radio" name="oscType" value="sawtooth" onclick="getOscType(this.value);">Sawtooth
</form>
</div>
<div id="keyboard"></div>
<script src="qwerty-hancock.js"></script>
<script src="pitch06.js"></script>
</div><!-- /.container -->
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
</body>
</html>
|
mit
|
mrdoob/three.js
|
docs/api/en/textures/CubeTexture.html
|
1733
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<base href="../../../" />
<script src="page.js"></script>
<link type="text/css" rel="stylesheet" href="page.css" />
</head>
<body>
[page:Texture] →
<h1>[name]</h1>
<p class="desc">Creates a cube texture made up of six images.</p>
<h2>Code Example</h2>
<code>
const loader = new THREE.CubeTextureLoader();
loader.setPath( 'textures/cube/pisa/' );
const textureCube = loader.load( [
'px.png', 'nx.png',
'py.png', 'ny.png',
'pz.png', 'nz.png'
] );
const material = new THREE.MeshBasicMaterial( { color: 0xffffff, envMap: textureCube } );
</code>
<h2>Constructor</h2>
<h3>[name]( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy )</h3>
<p>
CubeTexture is almost equivalent in functionality and usage to [page:Texture]. The only differences are that the
images are an array of 6 images as opposed to a single image, and the mapping options are
[page:Textures THREE.CubeReflectionMapping] (default) or [page:Textures THREE.CubeRefractionMapping]
</p>
<h2>Properties</h2>
<p>
See the base [page:Texture Texture] class for common properties.
</p>
<h3>[property:Boolean flipY]</h3>
<p>
If set to *true*, the texture is flipped along the vertical axis when uploaded to the GPU. Default is *false*.
</p>
<h3>[property:Boolean isCubeTexture]</h3>
<p>
Read-only flag to check if a given object is of type [name].
</p>
<h2>Methods</h2>
<p>
See the base [page:Texture Texture] class for common methods.
</p>
<h2>Source</h2>
<p>
[link:https://github.com/mrdoob/three.js/blob/master/src/[path].js src/[path].js]
</p>
</body>
</html>
|
mit
|
GlobalcachingEU/GAPP
|
GAPPSF/UIControls/UpDownCtrls/TimeCtrl.xaml.cs
|
35541
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using System.Windows.Markup;
using System.Windows.Controls.Primitives;
namespace GAPPSF.UIControls
{
/// <summary>
/// Interaction logic for TimeCtrl.xaml
/// </summary>
[ContentProperty("Children")]
public partial class TimeCtrl : UserControl, IFrameTxtBoxCtrl
{
private static readonly DependencyProperty ValueProperty =
DependencyProperty.Register("Value", typeof(DateTime), typeof(TimeCtrl), new PropertyMetadata(DateTime.Now, ValueChangedCallback));
private static readonly DependencyProperty TimePatternProperty =
DependencyProperty.Register("TimePattern", typeof(string), typeof(TimeCtrl), new PropertyMetadata(SystemDateInfo.LongTimePattern));
private static readonly DependencyProperty TextAlignmentProperty =
DependencyProperty.Register("TextAlignment", typeof(TextAlignment), typeof(TimeCtrl), new PropertyMetadata(TextAlignment.Left, TextAlignmentChangedCallback));
public static readonly DependencyProperty UseValidTimesProperty =
DependencyProperty.Register("UseValidTimes", typeof(bool), typeof(TimeCtrl), new PropertyMetadata(false, UseValidTimesChangedCallback));
public static readonly DependencyProperty ValidTimesNameProperty =
DependencyProperty.Register("ValidTimesName", typeof(string), typeof(TimeCtrl), new PropertyMetadata(LanguageStrings.ValidTimes));
public static readonly DependencyProperty NoValidTimesStringProperty =
DependencyProperty.Register("NoValidTimesString", typeof(string), typeof(TimeCtrl), new PropertyMetadata(LanguageStrings.None));
private static readonly DependencyProperty InvalidTimeTextBrushProperty =
DependencyProperty.Register("InvalidTimeTextBrush", typeof(Brush), typeof(TimeCtrl), new PropertyMetadata(Brushes.Red));
public static readonly DependencyProperty IsValidTimeProperty =
DependencyProperty.Register("IsValidTime", typeof(bool), typeof(TimeCtrl), new PropertyMetadata(true, IsValidTimeChangedCallback));
private static void ValueChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
TimeCtrl tc = d as TimeCtrl;
if (tc != null && e.NewValue is DateTime)
{
foreach (UIElement ele in tc.TimeCtrls.Children)
{
var ctrl = ele as FrameworkElement;
HMSType hmsType = ctrl.get_HMSType();
if (hmsType != HMSType.unknown)
{
var tb = ctrl as TextBox;
if (tb != null)
tb.set_HMSText((DateTime)e.NewValue);
}
}
tc.SetIsValidTime();
}
}
private static void TextAlignmentChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
TimeCtrl tc = d as TimeCtrl;
if (tc != null && e.NewValue is TextAlignment)
{
tc.TextBoxCtrl.TextAlignment = (TextAlignment)e.NewValue;
tc.ReloadTimeCtrlsGrid();
}
}
private static void IsValidTimeChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
TimeCtrl tc = d as TimeCtrl;
if (tc != null && e.NewValue is bool)
{
foreach (FrameworkElement fe in tc.TimeCtrls.Children)
{
if (fe is TextBox)
((TextBox)fe).Foreground = tc.TextBrush;
else if (fe is TextBlock)
((TextBlock)fe).Foreground = tc.TextBrush;
}
}
}
private static void UseValidTimesChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
TimeCtrl tc = d as TimeCtrl;
if (tc != null && e.NewValue is bool)
tc.SetIsValidTime();
}
static TimeCtrl()
{
Coercer.Initialize<TimeCtrl>();
}
public TimeCtrl()
{
Children = new ObservableCollection<ValidTimeItem>();
InitializeComponent();
this.Children.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(Children_CollectionChanged);
}
public DateTime Value
{
get { return (DateTime)GetValue(ValueProperty); }
set { SetValue(ValueProperty, value); }
}
public string TimePattern
{
get { return (string)GetValue(TimePatternProperty); }
set { SetValue(TimePatternProperty, value); }
}
public TextAlignment TextAlignment
{
get { return (TextAlignment)GetValue(TextAlignmentProperty); }
set { SetValue(TextAlignmentProperty, value); }
}
public bool UseValidTimes
{
get { return (bool)GetValue(UseValidTimesProperty); }
set { SetValue(UseValidTimesProperty, value); }
}
public string ValidTimesName
{
get { return (string)GetValue(ValidTimesNameProperty); }
set { SetValue(ValidTimesNameProperty, value); }
}
public string NoValidTimesString
{
get { return (string)GetValue(NoValidTimesStringProperty); }
set { SetValue(NoValidTimesStringProperty, value); }
}
public Brush InvalidTimeTextBrush
{
get { return (Brush)GetValue(InvalidTimeTextBrushProperty); }
set { SetValue(InvalidTimeTextBrushProperty, value); }
}
public bool IsValidTime
{
get { return (bool)GetValue(IsValidTimeProperty); }
private set { SetValue(IsValidTimeProperty, value); }
}
public ObservableCollection<ValidTimeItem> Children
{
get; private set;
}
private Brush TextBrush
{
get
{
return IsEnabled ? (IsValidTime ? Foreground : InvalidTimeTextBrush) : SystemColors.GrayTextBrush;
}
}
private void SetIsValidTime()
{
if (!UseValidTimes)
IsValidTime = true;
else
{
IsValidTime = false;
foreach (ValidTimeItem vti in Children)
{
if (Value >= vti.BeginTime && Value <= vti.EndTime)
{
IsValidTime = true;
break;
}
}
}
}
private void Children_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
SetIsValidTime();
}
TextBox IFrameTxtBoxCtrl.TextBox
{
get { return TextBoxCtrl; }
}
private bool MouseClicked = false;
private void AddGridCtrl(FrameworkElement ctrl)
{
var cd = new ColumnDefinition();
cd.Width = new GridLength(1, GridUnitType.Auto);
TimeCtrls.ColumnDefinitions.Add(cd);
TimeCtrls.Children.Add(ctrl);
Grid.SetColumn(ctrl, TimeCtrls.ColumnDefinitions.Count - 1);
}
private void AddHMSCtrlContextMenuItems(TextBox tb, params ICommand[] Commands)
{
foreach (ICommand Command in Commands)
{
MenuItem mi = new MenuItem();
mi.Command = Command;
tb.ContextMenu.Items.Add(mi);
}
}
private bool CmdBindCutPasteExecuteHandler(object sender, bool Execute, bool Cut)
{
var tb = sender as TextBox;
bool CanExecute = false;
string ClipTxt = "";
if (tb != null)
{
int CurPos = tb.SelectionStart, CurrentValue = 0, SelLength = tb.SelectionLength;
if (Cut)
ClipTxt = tb.Text.Substring(CurPos, tb.SelectionLength);
string Txt = tb.Text.Remove(CurPos, tb.SelectionLength);
if (!Cut) // If paste
ClipTxt = (string)System.Windows.Clipboard.GetData("Text");
CanExecute = (!Cut && string.IsNullOrEmpty(ClipTxt)) ? false : (tb.IsAM_PM() ?
(ClipTxt == SystemDateInfo.AMDesignator || ClipTxt == SystemDateInfo.PMDesignator)
: ValidateInput(tb, (Cut)? Txt : Txt.Insert(CurPos, ClipTxt), out CurrentValue));
if (Execute)
{
Value = tb.IsAM_PM() ? Value.Reset_AM_PM_Time(ClipTxt == SystemDateInfo.AMDesignator)
: Value.ResetTime(CurrentValue, tb.get_HMSType());
tb.SelectionStart = CurPos + SelLength;
if (Cut)
System.Windows.Clipboard.SetData("Text", ClipTxt);
}
}
return CanExecute;
}
private void CmdBindCutExecuted(object sender, ExecutedRoutedEventArgs e)
{
CmdBindCutPasteExecuteHandler(sender, true, true);
e.Handled = true;
}
void CmdBindCutCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
var tb = sender as TextBox;
e.CanExecute = (tb != null) && tb.SelectionLength > 0 && !tb.IsAM_PM();
}
private void CmdBindPasteExecuted(object sender, ExecutedRoutedEventArgs e)
{
CmdBindCutPasteExecuteHandler(sender, true, false);
e.Handled = true;
}
void CmdBindPasteCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = CmdBindCutPasteExecuteHandler(sender, false, false);
e.Handled = true;
}
private void CmdBindCopyTimeExecuted(object sender, ExecutedRoutedEventArgs e)
{
string strClipTime = "";
foreach (FrameworkElement fe in TimeCtrls.Children)
{
if (fe is TextBox)
strClipTime += ((TextBox)fe).Text;
else if (fe is TextBlock)
strClipTime += ((TextBlock)fe).Text;
}
System.Windows.Clipboard.SetData("Text", strClipTime);
e.Handled = true;
}
private void CmdBindPasteTimeExecuted(object sender, ExecutedRoutedEventArgs e)
{
int Hour, Minute, Second;
if (TimeCtrlExtensions.IsValidTime((string)System.Windows.Clipboard.GetData("Text"), TimePattern, out Hour, out Minute, out Second))
Value = new DateTime(Value.Year, Value.Month, Value.Day, Hour, Minute, Second, Value.Millisecond, Value.Kind);
}
void CmdBindPasteTimeCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
int Hour, Minute, Second;
e.CanExecute = TimeCtrlExtensions.IsValidTime((string)System.Windows.Clipboard.GetData("Text"), TimePattern, out Hour, out Minute, out Second);
}
private void AddValidTimeString(string str, bool Highlighted = false)
{
var rd = new RowDefinition();
ValidTimesGrid.RowDefinitions.Add(rd);
TextBlock tb = new TextBlock();
tb.Text = str;
if (Highlighted)
tb.FontWeight = FontWeights.Bold;
tb.HorizontalAlignment = HorizontalAlignment.Center;
tb.Background = Background;
tb.Foreground = Foreground;
tb.Margin = new Thickness(0.0);
ValidTimesGrid.Children.Add(tb);
Grid.SetRow(tb, ValidTimesGrid.RowDefinitions.Count - 1); ;
ValidTimesGrid.Height += tb.Height;
}
private string GetFormatedStr(TimeEntry te)
{
string strFormat = "";
string strAMPM = (te.Hour >= 12) ? SystemDateInfo.PMDesignator : SystemDateInfo.AMDesignator;
char AMPMShort = (te.Hour >= 12) ? SystemDateInfo.PMDesignator[TimeCtrlExtensions.Get_t_Idx()] :
SystemDateInfo.AMDesignator[TimeCtrlExtensions.Get_t_Idx()];
foreach (FrameworkElement fe in TimeCtrls.Children)
strFormat += fe.get_TextFormat();
return string.Format(strFormat, te.Hour, te.Hour.Get12Hour(), te.Minute, te.Second, strAMPM, AMPMShort);
}
private void CmdBindShowValidTimesExecuted(object sender, ExecutedRoutedEventArgs e)
{
if (ValidTimesGrid.Background == null)
ValidTimesGrid.Background = Brushes.White;
ValidTimesGrid.Children.Clear();
ValidTimesGrid.ColumnDefinitions.Clear();
ValidTimesGrid.RowDefinitions.Clear();
var cd = new ColumnDefinition();
ValidTimesGrid.ColumnDefinitions.Add(cd);
ValidTimesGrid.Height = 0;
AddValidTimeString(" " + ValidTimesName + " ", true);
string str;
foreach (ValidTimeItem vti in Children)
{
str = " " + LanguageStrings.From + " " + GetFormatedStr(vti.BeginTime) + " " + LanguageStrings.To
+ " " + GetFormatedStr(vti.EndTime) + " ";
AddValidTimeString(str);
}
if (Children.Count == 0)
AddValidTimeString(" " + NoValidTimesString + " ");
ValidTimesPopup.IsOpen = true;
}
private void AddHMSCtrlContextMenu(TextBox tb)
{
ContextMenu cmSource = new ContextMenu();
tb.ContextMenu = cmSource;
cmSource.PlacementTarget = tb; // Very important line: without this, context menu won't work if cursor not over a TextBox (but will otherwise!)
AddHMSCtrlContextMenuItems(tb, ApplicationCommands.Cut, ApplicationCommands.Copy, ApplicationCommands.Paste,
TimeCtrlCustomCommands.CopyTime, TimeCtrlCustomCommands.PasteTime);
if (UseValidTimes)
{
TimeCtrlCustomCommands.ShowValidTimes.Text = ValidTimesName;
AddHMSCtrlContextMenuItems(tb, TimeCtrlCustomCommands.ShowValidTimes);
}
CommandBinding CmdBindCut = new CommandBinding(ApplicationCommands.Cut, CmdBindCutExecuted, CmdBindCutCanExecute);
tb.CommandBindings.Add(CmdBindCut);
CommandBinding CmdBindPaste = new CommandBinding(ApplicationCommands.Paste, CmdBindPasteExecuted, CmdBindPasteCanExecute);
tb.CommandBindings.Add(CmdBindPaste);
CommandBinding CmdBindCopyTime = new CommandBinding(TimeCtrlCustomCommands.CopyTime, CmdBindCopyTimeExecuted);
tb.CommandBindings.Add(CmdBindCopyTime);
CommandBinding CmdBindPasteTime = new CommandBinding(TimeCtrlCustomCommands.PasteTime, CmdBindPasteTimeExecuted, CmdBindPasteTimeCanExecute);
tb.CommandBindings.Add(CmdBindPasteTime);
CommandBinding CmdBindShowValidTimes = new CommandBinding(TimeCtrlCustomCommands.ShowValidTimes, CmdBindShowValidTimesExecuted);
tb.CommandBindings.Add(CmdBindShowValidTimes);
}
private void AddHMSCtrl(HMSType hmsType)
{
TextBox tb = new TextBox();
tb.set_HMSType(hmsType);
tb.set_HMSText(Value);
tb.Height = ActualHeight;
tb.Margin = new Thickness(0.0);
tb.BorderThickness = new Thickness();
tb.Background = Background;
tb.Foreground = TextBrush;
tb.IsEnabled = IsEnabled;
if (hmsType == HMSType.t || hmsType == HMSType.tt)
{
tb.Focusable = true;
tb.AllowDrop = false;
tb.IsReadOnly = true;
tb.IsUndoEnabled = false;
tb.GotKeyboardFocus += new KeyboardFocusChangedEventHandler(tb_tt_GotKeyboardFocus);
tb.PreviewMouseLeftButtonDown += new MouseButtonEventHandler(tb_tt_PreviewMouseLeftButtonDown);
tb.PreviewKeyDown += new KeyEventHandler(tb_tt_PreviewKeyDown);
tb.PreviewTextInput += new TextCompositionEventHandler(tb_tt_PreviewTextInput);
}
else
{
tb.PreviewTextInput += new TextCompositionEventHandler(tb_PreviewTextInput);
tb.PreviewLostKeyboardFocus += new KeyboardFocusChangedEventHandler(tb_PreviewLostKeyboardFocus);
tb.GotKeyboardFocus += new KeyboardFocusChangedEventHandler(tb_GotKeyboardFocus);
tb.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(tb_LostKeyboardFocus);
tb.PreviewKeyDown += new KeyEventHandler(tb_PreviewKeyDown);
tb.PreviewMouseLeftButtonDown += new MouseButtonEventHandler(tb_PreviewMouseLeftButtonDown);
tb.PreviewMouseRightButtonDown += new MouseButtonEventHandler(tb_PreviewMouseRightButtonDown);
tb.PreviewQueryContinueDrag += new QueryContinueDragEventHandler(tb_PreviewQueryContinueDrag);
tb.PreviewDragEnter += new DragEventHandler(tb_PreviewDrag);
tb.PreviewDragOver += new DragEventHandler(tb_PreviewDrag);
}
AddHMSCtrlContextMenu(tb);
tb.PreviewMouseWheel += new MouseWheelEventHandler(tb_PreviewMouseWheel);
AddGridCtrl(tb);
}
private void AddString(string str)
{
TextBlock tb = new TextBlock();
tb.Text = str;
tb.Background = Brushes.Transparent;
tb.Foreground = TextBrush;
tb.Margin = new Thickness(0.0);
tb.Height = Height;
AddGridCtrl(tb);
}
void tb_PreviewMouseWheel(object sender, MouseWheelEventArgs e)
{
// MouseWheel does not work very well. The mouse cursor has to be over the item for it to work.
// CodePlex sample does same, which is why I am leaving implementation as such.
var tb = sender as TextBox;
if (tb != null)
{
if (e.Delta > 0)
ManipulateValue(tb, IncrementValue);
else
ManipulateValue(tb, DecrementValue);
// Following is illegal: !!!!! (would replace 4 lines above)
// ManipulateValue(tb, (e.Delta > 0) ? IncrementValue : DecrementValue);
tb.Focus();
e.Handled = true;
}
}
void tb_tt_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
var tb = sender as TextBox;
if (tb != null)
tb.SelectAll();
}
void tb_tt_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
var tb = sender as TextBox;
if (tb != null)
{
tb.Focus();
e.Handled = true;
}
}
void AM_PM_Handle(TextBox tb)
{
bool IsAm;
if (tb.get_HMSType() == HMSType.tt)
IsAm = (tb.Text == SystemDateInfo.AMDesignator);
else // tb.get_HMSType() == HMSType.t
IsAm = (tb.Text == SystemDateInfo.AMDesignator[TimeCtrlExtensions.Get_t_Idx()].ToString());
Value = Value.Reset_AM_PM_Time(IsAm);
tb.SelectAll();
}
void AM_PM_Change(TextBox tb)
{
if (tb.get_HMSType() == HMSType.tt)
tb.Text = (tb.Text == SystemDateInfo.AMDesignator) ? SystemDateInfo.PMDesignator : SystemDateInfo.AMDesignator;
else // tb.get_HMSType() == HMSType.t
{
int Idx = TimeCtrlExtensions.Get_t_Idx();
tb.Text = (tb.Text == SystemDateInfo.AMDesignator[Idx].ToString()) ?
SystemDateInfo.PMDesignator[Idx].ToString() : SystemDateInfo.AMDesignator[Idx].ToString();
}
AM_PM_Handle(tb);
}
void tb_tt_PreviewKeyDown(object sender, KeyEventArgs e)
{
var tb = sender as TextBox;
if (tb == null)
return;
if (e.Key == Key.Up || e.Key == Key.Down)
{
AM_PM_Change(tb);
e.Handled = true;
}
}
bool AM_PM_HandleInput(TextBox tb, string InputTxt, string AM_PM_Designator, int Idx)
{
if (string.Compare(InputTxt, AM_PM_Designator[Idx].ToString(), true) == 0)
{
if (tb.get_HMSType() == HMSType.tt)
tb.Text = AM_PM_Designator;
else // tb.get_HMSType() == HMSType.t
tb.Text = AM_PM_Designator[Idx].ToString();
AM_PM_Handle(tb);
return true;
}
return false;
}
void tb_tt_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
TextBox tb = sender as TextBox;
if (tb != null)
{
int Idx = TimeCtrlExtensions.Get_t_Idx();
if (!AM_PM_HandleInput(tb, e.Text, SystemDateInfo.AMDesignator, Idx))
e.Handled = AM_PM_HandleInput(tb, e.Text, SystemDateInfo.PMDesignator, Idx);
else
e.Handled = true;
}
}
void tb_LostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
var tb = sender as TextBox;
if (tb != null && tb.Text == "")
tb.set_HMSText(Value);
}
void tb_PreviewDrag(object sender, DragEventArgs e)
{
e.Effects = DragDropEffects.None;
e.Handled = true;
}
void tb_PreviewQueryContinueDrag(object sender, QueryContinueDragEventArgs e)
{
e.Action = DragAction.Cancel;
e.Handled = true;
}
void tb_PreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
MouseClicked = true;
}
void tb_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
MouseClicked = true;
}
private delegate void ValueManipulator(TextBox tb, int NewValue);
private int AdjustHalfDayHour(TextBox tb, int CurrentValue)
{
if (tb.IsHalfDayHour())
{
if (CurrentValue == 12)
{
if (Value.Hour < 12)
CurrentValue = 0;
}
else if (Value.Hour >= 12)
CurrentValue += 12;
}
return CurrentValue;
}
private void IncrementValue(TextBox tb, int NewValue)
{
NewValue = (NewValue < tb.get_Max() - 1) ? NewValue + 1 : tb.get_Min();
NewValue = AdjustHalfDayHour(tb, NewValue);
Value = Value.ResetTime(NewValue, tb.get_HMSType());
}
private void DecrementValue(TextBox tb, int NewValue)
{
NewValue = (NewValue > tb.get_Min()) ? NewValue - 1 : tb.get_Max() - 1;
NewValue = AdjustHalfDayHour(tb, NewValue);
Value = Value.ResetTime(NewValue, tb.get_HMSType());
}
private void ManipulateValue(TextBox tb, ValueManipulator ValMan)
{
if (tb.get_HMSType() == HMSType.t || tb.get_HMSType() == HMSType.tt)
{
AM_PM_Change(tb);
return;
}
int NewValue;
if (int.TryParse(tb.Text, out NewValue))
ValMan(tb, NewValue);
tb.Focus();
tb.SelectAll();
}
void tb_PreviewKeyDown(object sender, KeyEventArgs e)
{
var tb = sender as TextBox;
if (tb == null)
return;
if (e.Key == Key.Up)
{
ManipulateValue(tb, IncrementValue);
e.Handled = true;
}
else if (e.Key == Key.Down)
{
ManipulateValue(tb, DecrementValue);
e.Handled = true;
}
else if (e.Key == Key.Delete || e.Key == Key.Back)
{
int CurPos = tb.SelectionStart;
string Txt = tb.Text;
e.Handled = true;
if (tb.SelectionLength > 0)
Txt = Txt.Remove(CurPos, tb.SelectionLength);
else if (e.Key == Key.Delete && CurPos < Txt.Length)
{
Txt = Txt.Remove(CurPos, 1);
if (tb.IsAlways2CharInt())
CurPos++;
}
else if (e.Key == Key.Back && CurPos > 0)
{
Txt = Txt.Remove(CurPos - 1, 1);
if (!tb.IsAlways2CharInt()) --CurPos;
}
else
e.Handled = false;
if (e.Handled)
{
int CurrentValue;
if (ValidateInput(tb, Txt, out CurrentValue))
{
Value = Value.ResetTime(CurrentValue, tb.get_HMSType());
tb.SelectionStart = CurPos;
}
else if (Txt == "" || (Txt == "0" && tb.get_HMSType() == HMSType.hhour))
{
tb.SelectionStart = 0;
tb.Text = "";
}
else
e.Handled = false;
}
}
else if (e.Key == Key.Space) // Want to prevent entering spaces. Amazingly, tb_PreviewTextInput not called, even though
// tb_PreviewTextInput IS called when enter return key (and e.Text = '\r') ??!!!
e.Handled = true;
}
void tb_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
var tb = sender as TextBox;
if (tb != null && MouseClicked == false) // We do not want to select all when user has clicked on TextBox.
// Without the MouseClicked parameter, everything is selected/deselected immediately, which looks ugly.
// I agree having this parameter is not the most pretty programming style, but know no better way.
tb.SelectAll();
MouseClicked = false;
}
void tb_PreviewLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
var tb = sender as TextBox;
if (tb != null && e.NewFocus == tb.ContextMenu)
{
tb.Focus();
tb.ContextMenu.DataContext = tb;
e.Handled = true;
}
}
/// <param name="shortHMS">An HMS tag corresponding to 'H', 'h', 'm', 's', 't' </param>
/// <param name="longHMS">An HMS tag corresponding to 'HH', 'hh', 'mm', 'ss', 'tt'</param>
private int LoadTimeTag(string TimePattern, int Idx, HMSType shortHMS, HMSType longHMS)
{
if (Idx < TimePattern.Length - 1 && TimePattern[Idx + 1] == TimePattern[Idx])
{
AddHMSCtrl(longHMS);
Idx++;
}
else
AddHMSCtrl(shortHMS);
return Idx;
}
private int LoadTimeSeparator(string TimePattern, int Idx)
{
// Assume the separator is something like ':' or '.'. Not considering case when want to use a character normally used
// to indicate a time tag.
int StartIdx = Idx;
while (Idx < TimePattern.Length - 1 && TimePattern[Idx + 1] != 'H'
&& TimePattern[Idx + 1] != 'h'
&& TimePattern[Idx + 1] != 'm'
&& TimePattern[Idx + 1] != 's'
&& TimePattern[Idx + 1] != 't')
Idx++;
AddString(TimePattern.Substring(StartIdx, Idx - StartIdx + 1));
return Idx;
}
private void LoadTimePattern(string TimePattern)
{
for (int Idx = 0; Idx < TimePattern.Length; Idx++)
{
switch (TimePattern[Idx])
{
case 'H':
Idx = LoadTimeTag(TimePattern, Idx, HMSType.Hour, HMSType.HHour);
break;
case 'h':
Idx = LoadTimeTag(TimePattern, Idx, HMSType.hour, HMSType.hhour);
break;
case 'm':
Idx = LoadTimeTag(TimePattern, Idx, HMSType.minute, HMSType.mminute);
break;
case 's':
Idx = LoadTimeTag(TimePattern, Idx, HMSType.second, HMSType.ssecond);
break;
case 't':
Idx = LoadTimeTag(TimePattern, Idx, HMSType.t, HMSType.tt);
break;
default:
Idx = LoadTimeSeparator(TimePattern, Idx);
break;
}
}
}
private void ReloadTimeCtrlsGrid()
{
TimeCtrls.Children.Clear();
TimeCtrls.ColumnDefinitions.Clear();
TimeCtrls.RowDefinitions.Clear();
TimeCtrls.RowDefinitions.Add(new RowDefinition());
if (TextAlignment == TextAlignment.Right || TextAlignment == TextAlignment.Center)
TimeCtrls.ColumnDefinitions.Add(new ColumnDefinition());
LoadTimePattern(TimePattern);
if (TextAlignment == TextAlignment.Left || TextAlignment == TextAlignment.Center)
TimeCtrls.ColumnDefinitions.Add(new ColumnDefinition());
}
private void Root_Loaded(object sender, RoutedEventArgs e)
{
ReloadTimeCtrlsGrid();
}
private TextBox GetNextTextBox(int Idx)
{
while (++Idx < TimeCtrls.Children.Count && !(TimeCtrls.Children[Idx] is TextBox)) ;
return (Idx < TimeCtrls.Children.Count) ? (TextBox)TimeCtrls.Children[Idx] : null;
}
void tb_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
TextBox tb = sender as TextBox;
if (tb != null)
{
int CurrentValue;
int CurPos = tb.SelectionStart, SelLen = tb.SelectionLength;
string Txt = tb.Text.Remove(CurPos, SelLen);
if (Keyboard.GetKeyStates(Key.Insert) == KeyStates.Toggled && CurPos < Txt.Length)
Txt = Txt.Remove(CurPos, 1);
Txt = Txt.Insert(CurPos, e.Text);
// Don't do anything for entries like "003" "012" or "05" (not '0' prefixed) when entry is a '0' only
if (!(e.Text == "0" && ((Txt.Length == 3 && Txt[0] == '0' && CurPos == 0) || (!tb.IsAlways2CharInt() && Txt.Length == 2 && Txt[0] == '0')))
&& ValidateInput(tb, Txt, out CurrentValue))
{
CurrentValue = AdjustHalfDayHour(tb, CurrentValue);
Value = Value.ResetTime(CurrentValue, tb.get_HMSType());
tb.SelectionStart = (tb.Text.Length == 1 ||
(CurPos == 0 && SelLen < 2 && Txt.Length >= 2) ||
(Txt.Length == 3 && Txt[0] == '0' && CurPos == 1 && SelLen == 0)) ? 1 : 2;
}
else if (tb.IsHalfDayHour() && (Txt == "0" || Txt == "00"))
tb.Text = "";
}
e.Handled = true;
}
private bool ValidateInput(TextBox tb, string Txt, out int CurrentValue)
{
if (int.TryParse(Txt, out CurrentValue))
return (CurrentValue < tb.get_Max() && CurrentValue >= tb.get_Min());
return false;
}
private TextBox SetFocusToClosestTextBox()
{
Point pt;
TextBox tbClosest = null;
double MinDist = 0;
foreach (UIElement ele in TimeCtrls.Children)
{
var tb = ele as TextBox;
if (tb != null)
{
pt = Mouse.GetPosition(tb);
if (tbClosest == null || Math.Abs(pt.X) < MinDist)
{
tbClosest = tb;
MinDist = Math.Abs(pt.X);
}
}
}
if (tbClosest != null)
{
tbClosest.Focus();
tbClosest.CaptureMouse();
}
return tbClosest;
}
private void Root_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
MouseClicked = true;
SetFocusToClosestTextBox();
}
private void Root_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
MouseClicked = true;
TextBox tb = SetFocusToClosestTextBox();
if (tb != null)
{
tb.ContextMenu.IsOpen = true;
e.Handled = true;
}
}
private void CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = false;
e.Handled = true;
}
private TextBox GetTextBoxToFocusOn()
{
var tb = FocusManager.GetFocusedElement(this) as TextBox;
if (tb == null)
tb = GetNextTextBox(-1);
return tb;
}
private void UpDown_UpClick(object sender, RoutedEventArgs e)
{
var tb = GetTextBoxToFocusOn();
if (tb != null) ManipulateValue(tb, IncrementValue);
}
private void UpDown_DownClick(object sender, RoutedEventArgs e)
{
var tb = GetTextBoxToFocusOn();
if (tb != null) ManipulateValue(tb, DecrementValue);
}
private void Root_IsEnabledChanged(object sender, DependencyPropertyChangedEventArgs e)
{
foreach (FrameworkElement fe in TimeCtrls.Children)
{
if (fe is TextBox)
{
((TextBox)fe).IsEnabled = (bool)e.NewValue;
((TextBox)fe).Foreground = TextBrush;
}
else if (fe is TextBlock)
((TextBlock)fe).Foreground = TextBrush;
}
}
}
}
|
mit
|
rsredsq/AtomicGameEngine
|
Source/Atomic/UI/SystemUI/Sprite.h
|
4555
|
//
// Copyright (c) 2008-2015 the Urho3D project.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#pragma once
#include "../../Math/Matrix3x4.h"
#include "UIElement.h"
namespace Atomic
{
namespace SystemUI
{
/// %UI element which allows sub-pixel positioning and size, as well as rotation. Only other Sprites should be added as child elements.
class ATOMIC_API Sprite : public UIElement
{
OBJECT(Sprite);
public:
/// Construct.
Sprite(Context* context);
/// Destruct.
virtual ~Sprite();
/// Register object factory.
static void RegisterObject(Context* context);
/// Return whether is visible and inside a scissor rectangle and should be rendered.
virtual bool IsWithinScissor(const IntRect& currentScissor);
/// Update and return screen position.
virtual const IntVector2& GetScreenPosition() const;
/// Return UI rendering batches.
virtual void GetBatches(PODVector<SystemUIBatch>& batches, PODVector<float>& vertexData, const IntRect& currentScissor);
/// React to position change.
virtual void OnPositionSet();
/// Set floating point position.
void SetPosition(const Vector2& position);
/// Set floating point position.
void SetPosition(float x, float y);
/// Set hotspot for positioning and rotation.
void SetHotSpot(const IntVector2& hotSpot);
/// Set hotspot for positioning and rotation.
void SetHotSpot(int x, int y);
/// Set scale. Scale also affects child sprites.
void SetScale(const Vector2& scale);
/// Set scale. Scale also affects child sprites.
void SetScale(float x, float y);
/// Set uniform scale. Scale also affects child sprites.
void SetScale(float scale);
/// Set rotation angle.
void SetRotation(float angle);
/// Set texture.
void SetTexture(Texture* texture);
/// Set part of texture to use as the image.
void SetImageRect(const IntRect& rect);
/// Use whole texture as the image.
void SetFullImageRect();
/// Set blend mode.
void SetBlendMode(BlendMode mode);
/// Return floating point position.
const Vector2& GetPosition() const { return floatPosition_; }
/// Return hotspot.
const IntVector2& GetHotSpot() const { return hotSpot_; }
/// Return scale.
const Vector2& GetScale() const { return scale_; }
/// Return rotation angle.
float GetRotation() const { return rotation_; }
/// Return texture.
Texture* GetTexture() const { return texture_; }
/// Return image rectangle.
const IntRect& GetImageRect() const { return imageRect_; }
/// Return blend mode.
BlendMode GetBlendMode() const { return blendMode_; }
/// Set texture attribute.
void SetTextureAttr(const ResourceRef& value);
/// Return texture attribute.
ResourceRef GetTextureAttr() const;
/// Update and return rendering transform, also used to transform child sprites.
const Matrix3x4& GetTransform() const;
protected:
/// Floating point position.
Vector2 floatPosition_;
/// Hotspot for positioning and rotation.
IntVector2 hotSpot_;
/// Scale.
Vector2 scale_;
/// Rotation angle.
float rotation_;
/// Texture.
SharedPtr<Texture> texture_;
/// Image rectangle.
IntRect imageRect_;
/// Blend mode flag.
BlendMode blendMode_;
/// Transform matrix.
mutable Matrix3x4 transform_;
};
}
}
|
mit
|
dmullins78/easybatch-framework
|
easybatch-integration/easybatch-apache-commons-csv/src/test/java/org/easybatch/integration/apache/common/csv/ApacheCommonCsvRecordReaderTest.java
|
3254
|
/*
* The MIT License
*
* Copyright (c) 2015, Mahmoud Ben Hassine (mahmoud@benhassine.fr)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.easybatch.integration.apache.common.csv;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.easybatch.core.api.Record;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.io.StringReader;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Test class for {@link ApacheCommonCsvRecordReader}.
*
* @author Mahmoud Ben Hassine (mahmoud@benhassine.fr)
*/
public class ApacheCommonCsvRecordReaderTest {
private ApacheCommonCsvRecordReader recordReader;
@Before
public void setUp() throws Exception {
StringReader stringReader = new StringReader("foo,bar,15,true");
CSVFormat csvFormat = CSVFormat.DEFAULT.withHeader("firstName", "lastName", "age", "married");
CSVParser parser = new CSVParser(stringReader, csvFormat);
recordReader = new ApacheCommonCsvRecordReader(parser);
recordReader.open();
}
@Test
public void testHasNextRecord() throws Exception {
Assert.assertTrue(recordReader.hasNextRecord());
}
@Test
public void testReadNextRecord() throws Exception {
recordReader.hasNextRecord();
Record record = recordReader.readNextRecord();
assertThat(record).isNotNull().isInstanceOf(ApacheCommonCsvRecord.class);
ApacheCommonCsvRecord apacheCommonCsvRecord = (ApacheCommonCsvRecord) record;
assertThat(apacheCommonCsvRecord.getHeader()).isNotNull();
assertThat(apacheCommonCsvRecord.getHeader().getNumber()).isEqualTo(1);
CSVRecord csvRecord = apacheCommonCsvRecord.getPayload();
assertThat(csvRecord.get("firstName")).isEqualTo("foo");
assertThat(csvRecord.get("lastName")).isEqualTo("bar");
assertThat(csvRecord.get("age")).isEqualTo("15");
assertThat(csvRecord.get("married")).isEqualTo("true");
}
@After
public void tearDown() throws Exception {
recordReader.close();
}
}
|
mit
|
PyORBIT-Collaboration/py-orbit
|
py/orbit/time_dep/time_dep.py
|
4174
|
"""
Module. Includes classes for all time dependent lattice.
"""
import sys
import os
import math
from orbit.teapot import TEAPOT_Lattice
from orbit.parsers.mad_parser import MAD_Parser, MAD_LattLine
from orbit.lattice import AccNode, AccActionsContainer
from orbit.time_dep import waveform
class TIME_DEP_Lattice(TEAPOT_Lattice):
"""
The subclass of the TEAPOT_Lattice.
TIME_DEP_Lattice has the ability to set time dependent parameters to the Lattice.
Multi-turn track also available.
"""
def __init__(self, name = "no name"):
TEAPOT_Lattice.__init__(self,name)
self.__latticeDict = {}
self.__TDNodeDict = {}
self.__turns = 1
def setLatticeOrder(self):
"""
Sets the time dependent lattice names to the lattice.
"""
accNodes = self.getNodes()
elemInLine = {}
for i in range(len(accNodes)):
elem = accNodes[i]
elemname = elem.getName()
if(elemInLine.has_key(elemname)):
elemInLine[elemname] += 1
else: elemInLine[elemname] = 1
node = self.getNodes()[i]
node.setParam("TPName",node.getName()+"_"+str(elemInLine[elemname]))
#node.setParam("sequence",i+1)
#print "debug node",node.getName(),node.getParamsDict()
def setTimeDepNode(self, TPName, waveform):
"""
Sets the waveform function to the TP node before track.
"""
flag = 0
for node in self.getNodes():
if (TPName == node.getParam("TPName")):
flag = 1
node.setParam("waveform",waveform)
self.__TDNodeDict[TPName] = node
if not flag:
print "The",TPName,"is not found."
sys.exit(1)
def setTimeDepStrength(self, time):
"""
Set strength to the TP node while running.
"""
NodeDict = self.__TDNodeDict
for i in NodeDict.keys():
node = NodeDict[i]
waveform = node.getParam("waveform")
waveform.calc(time)
waveformType = waveform.getType()
if waveformType == "kicker waveform":
if node.getType() == "kick teapot":
self.setParam(node,"kx",waveform.getKx())
self.setParam(node,"ky",waveform.getKy())
else: print "No kicker waveform added. Please check node type."
elif waveformType == "magnet waveform":
strength = waveform.getStrength()
if node.getType() == "multipole teapot":
self.setParam(node,"kls",strength)
elif node.getType() == "quad teapot":
self.setParam(node,"kls",strength)
self.setParam(node,"kq",strength)
elif node.getType() == "solenoid teapot":
self.setParam(node,"B",strength)
else: print "No magnet waveform added. Please check node type."
def setParam(self, node, Kparam, strength):
if node.hasParam(Kparam):
paramval = node.getParam(Kparam)
if Kparam == "kls":
newparamval = []
for i in range(len(paramval)):
newparamval.append(paramval[i]*strength)
paramval = newparamval
else:paramval = paramval*strength
node.setParam(Kparam,paramval)
def trackBunchTurns(self, bunch):
"""
It tracks the bunch through the lattice with multi-turn.
"""
turns = self.__turns
#start
for i in range(turns-1):
self.trackBunch(bunch)
syncPart = bunch.getSyncParticle()
time = syncPart.time()
self.setTimeDepStrength(time)
print "debug trackBunchTurns time",time,"in",i,"turn"
#getsublattice
#sublattice.trackBunch(bunch)
def setTurns(self, turns, startPosition = 0, endPosition = -1):
"""
Sets the turns and start end position before track.
"""
startNode = StartNode("start node")
endNode = EndNode("end node")
self.addNode(startNode, startPosition)
self.addNode(endNode, endPosition)
self.__turns = turns
#print self.getNodes()
class StartNode(AccNode):
def __init__(self, name = "no name"):
AccNode.__init__(self,name)
self.setType("start node")
def track(self, paramsDict):
bunch = paramsDict["bunch"]
#bunch.getSyncParticle().time(0.)
class EndNode(AccNode):
def __init__(self, name = "no name"):
AccNode.__init__(self,name)
self.setType("end node")
def track(self, paramsDict):
pass
|
mit
|
sjsinju/coreclr
|
src/mscorlib/src/System/Text/EncoderBestFitFallback.cs
|
8893
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
// This is used internally to create best fit behavior as per the original windows best fit behavior.
//
using System;
using System.Globalization;
using System.Text;
using System.Threading;
using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.Text
{
[Serializable]
internal class InternalEncoderBestFitFallback : EncoderFallback
{
// Our variables
internal Encoding encoding = null;
internal char[] arrayBestFit = null;
internal InternalEncoderBestFitFallback(Encoding encoding)
{
// Need to load our replacement characters table.
this.encoding = encoding;
this.bIsMicrosoftBestFitFallback = true;
}
public override EncoderFallbackBuffer CreateFallbackBuffer()
{
return new InternalEncoderBestFitFallbackBuffer(this);
}
// Maximum number of characters that this instance of this fallback could return
public override int MaxCharCount
{
get
{
return 1;
}
}
public override bool Equals(Object value)
{
InternalEncoderBestFitFallback that = value as InternalEncoderBestFitFallback;
if (that != null)
{
return (this.encoding.CodePage == that.encoding.CodePage);
}
return (false);
}
public override int GetHashCode()
{
return this.encoding.CodePage;
}
}
internal sealed class InternalEncoderBestFitFallbackBuffer : EncoderFallbackBuffer
{
// Our variables
private char cBestFit = '\0';
private InternalEncoderBestFitFallback oFallback;
private int iCount = -1;
private int iSize;
// Private object for locking instead of locking on a public type for SQL reliability work.
private static Object s_InternalSyncObject;
private static Object InternalSyncObject
{
get
{
if (s_InternalSyncObject == null)
{
Object o = new Object();
Interlocked.CompareExchange<Object>(ref s_InternalSyncObject, o, null);
}
return s_InternalSyncObject;
}
}
// Constructor
public InternalEncoderBestFitFallbackBuffer(InternalEncoderBestFitFallback fallback)
{
oFallback = fallback;
if (oFallback.arrayBestFit == null)
{
// Lock so we don't confuse ourselves.
lock (InternalSyncObject)
{
// Double check before we do it again.
if (oFallback.arrayBestFit == null)
oFallback.arrayBestFit = fallback.encoding.GetBestFitUnicodeToBytesData();
}
}
}
// Fallback methods
public override bool Fallback(char charUnknown, int index)
{
// If we had a buffer already we're being recursive, throw, it's probably at the suspect
// character in our array.
// Shouldn't be able to get here for all of our code pages, table would have to be messed up.
Debug.Assert(iCount < 1, "[InternalEncoderBestFitFallbackBuffer.Fallback(non surrogate)] Fallback char " + ((int)cBestFit).ToString("X4", CultureInfo.InvariantCulture) + " caused recursive fallback");
iCount = iSize = 1;
cBestFit = TryBestFit(charUnknown);
if (cBestFit == '\0')
cBestFit = '?';
return true;
}
public override bool Fallback(char charUnknownHigh, char charUnknownLow, int index)
{
// Double check input surrogate pair
if (!Char.IsHighSurrogate(charUnknownHigh))
throw new ArgumentOutOfRangeException(nameof(charUnknownHigh),
Environment.GetResourceString("ArgumentOutOfRange_Range",
0xD800, 0xDBFF));
if (!Char.IsLowSurrogate(charUnknownLow))
throw new ArgumentOutOfRangeException(nameof(charUnknownLow),
Environment.GetResourceString("ArgumentOutOfRange_Range",
0xDC00, 0xDFFF));
Contract.EndContractBlock();
// If we had a buffer already we're being recursive, throw, it's probably at the suspect
// character in our array. 0 is processing last character, < 0 is not falling back
// Shouldn't be able to get here, table would have to be messed up.
Debug.Assert(iCount < 1, "[InternalEncoderBestFitFallbackBuffer.Fallback(surrogate)] Fallback char " + ((int)cBestFit).ToString("X4", CultureInfo.InvariantCulture) + " caused recursive fallback");
// Go ahead and get our fallback, surrogates don't have best fit
cBestFit = '?';
iCount = iSize = 2;
return true;
}
// Default version is overridden in EncoderReplacementFallback.cs
public override char GetNextChar()
{
// We want it to get < 0 because == 0 means that the current/last character is a fallback
// and we need to detect recursion. We could have a flag but we already have this counter.
iCount--;
// Do we have anything left? 0 is now last fallback char, negative is nothing left
if (iCount < 0)
return '\0';
// Need to get it out of the buffer.
// Make sure it didn't wrap from the fast count-- path
if (iCount == int.MaxValue)
{
iCount = -1;
return '\0';
}
// Return the best fit character
return cBestFit;
}
public override bool MovePrevious()
{
// Exception fallback doesn't have anywhere to back up to.
if (iCount >= 0)
iCount++;
// Return true if we could do it.
return (iCount >= 0 && iCount <= iSize);
}
// How many characters left to output?
public override int Remaining
{
get
{
return (iCount > 0) ? iCount : 0;
}
}
// Clear the buffer
public override unsafe void Reset()
{
iCount = -1;
charStart = null;
bFallingBack = false;
}
// private helper methods
private char TryBestFit(char cUnknown)
{
// Need to figure out our best fit character, low is beginning of array, high is 1 AFTER end of array
int lowBound = 0;
int highBound = oFallback.arrayBestFit.Length;
int index;
// Binary search the array
int iDiff;
while ((iDiff = (highBound - lowBound)) > 6)
{
// Look in the middle, which is complicated by the fact that we have 2 #s for each pair,
// so we don't want index to be odd because we want to be on word boundaries.
// Also note that index can never == highBound (because diff is rounded down)
index = ((iDiff / 2) + lowBound) & 0xFFFE;
char cTest = oFallback.arrayBestFit[index];
if (cTest == cUnknown)
{
// We found it
Debug.Assert(index + 1 < oFallback.arrayBestFit.Length,
"[InternalEncoderBestFitFallbackBuffer.TryBestFit]Expected replacement character at end of array");
return oFallback.arrayBestFit[index + 1];
}
else if (cTest < cUnknown)
{
// We weren't high enough
lowBound = index;
}
else
{
// We weren't low enough
highBound = index;
}
}
for (index = lowBound; index < highBound; index += 2)
{
if (oFallback.arrayBestFit[index] == cUnknown)
{
// We found it
Debug.Assert(index + 1 < oFallback.arrayBestFit.Length,
"[InternalEncoderBestFitFallbackBuffer.TryBestFit]Expected replacement character at end of array");
return oFallback.arrayBestFit[index + 1];
}
}
// Char wasn't in our table
return '\0';
}
}
}
|
mit
|
JuliaPackageMirrors/Stochy.jl
|
src/cps.jl
|
8446
|
using Base.Meta
export @cps
const compops = [symbol("=="), :>, :<, :>=, :<=]
Atom = Union(Number, Bool, Symbol, String, QuoteNode)
function cps(expr, cont)
strippedexpr = striplineinfo(expr)
cpsexpr = tc(strippedexpr, cont)
# Trampolining function definitions prevent them from been added
# to the calling scope.
if isfuncdef(strippedexpr)
cpsexpr
else
:(Stochy.trampoline(Stochy.Thunk(() -> $cpsexpr)))
end
end
# This assumes line numbers have been stripped.
function isfuncdef(expr::Expr)
expr.head == :function ||
expr.head == :block && !isempty(expr.args) && isfuncdef(expr.args[1])
end
isfuncdef(expr) = false
macro cps(expr)
cpsexpr = cps(expr, :identity)
debug() && println(striplineinfo(cpsexpr))
esc(cpsexpr)
end
# Distinguish thunks from functions returns by the transformed code.
immutable Thunk
f::Function
function Thunk(f)
new(f)
end
end
function trampoline(t::Thunk)
thunkcount = 0
while isa(t, Thunk)
t = t.f()
if debug()
#println(t.f.code)
thunkcount += 1
end
end
debug() && println("trampolined thunks: ", thunkcount)
t
end
# Convenience function used to kick-off trampolining in enum() &
# pmcmc().
trampoline(f::Function) = trampoline(Thunk(f))
# CPS transform based on:
# http://matt.might.net/articles/cps-conversion/
# Essentials of Programming Languages (3rd Ed.) [Friedman & Wand]
# | CPS | EoPL | Might's Scheme CPS | |
# | tc | cps-of-exp | T-c | |
# | tk(::Function, expr) | cps-of-exp/ctx | T-k | Ex. 6.30, p225. |
# | tk(::Function, exprs) | cps-of-exps | T*-k | |
# | m | cps-of-simple-exp | M | |
function tc(expr, cont)
if isatomic(expr)
:(Stochy.Thunk(() -> $cont($(m(expr)))))
elseif expr.head == :block && length(expr.args) == 1
tc(expr.args[1], cont)
elseif expr.head == :block && length(expr.args) > 1
tk(expr.args[1]) do _
# Build block this way rather than with quoting so line
# number expressions aren't added, preventing recursion
# from ever bottoming out.
tc(Expr(:block, expr.args[2:end]...), cont)
end
elseif expr.head == :local
@assert expr.args[1].head == symbol("=")
@assert length(expr.args) == 1
val = expr.args[1].args[2]
tk(e -> :($cont($e)), val)
# elseif expr.head == :let
# @assert all([arg.head == symbol("=") for arg in expr.args[2:end]])
# body = expr.args[1]
# vars = [arg.args[1]::Symbol for arg in expr.args[2:end]]
# exprs = [arg.args[2] for arg in expr.args[2:end]]
# tk(exprs) do e...
# :(let $(map((var, val) -> :($(var)=$(val)), vars, e)...); $(tc(body, cont)) end)
# end
elseif expr.head == :if
@assert length(expr.args) == 3
tk(expr.args[1]) do test
:($test ? $(tc(expr.args[2], cont)) : $(tc(expr.args[3], cont)))
end
elseif expr.head == :function
f = expr.args[1].args[1]
args = expr.args[1].args[2:end]
body = expr.args[2]
v = gensym()
:($cont(function $f($v, $(args...)); $(tc(body, v)); end))
elseif expr.head == :||
# Convert to if statement.
@assert length(expr.args) == 2
lhs, rhs = expr.args
tc(:($lhs ? true : ($rhs ? true : false)), cont)
elseif expr.head == :&&
@assert length(expr.args) == 2
lhs, rhs = expr.args
tc(:($lhs ? ($rhs ? true : false) : false), cont)
elseif isprimop(expr)
f = expr.args[1]
tk(expr.args[2:end]) do e...
:($cont($f($(e...))))
end
elseif expr.head == :call
tk(expr.args) do f, e...
:($f($cont, $(e...)))
end
elseif expr.head == :.
@assert isa(expr.args[2], QuoteNode) || isa(expr.args[2], Expr)
@assert length(expr.args) == 2
# The dot syntax turns in to two different Exprs depending on
# whether you use the macro or :(<expr>). Handle both.
if isa(expr.args[2], Expr)
@assert expr.args[2].head == :quote
@assert length(expr.args[2].args) == 1
sym = expr.args[2].args[1]
else
@assert isa(expr.args[2].value, Symbol)
sym = expr.args[2].value
end
tk(expr.args[1]) do e
:($cont($(e).$(sym)))
end
elseif expr.head == :comparison && expr.args[2] in compops
@assert length(expr.args) == 3
tk([expr.args[1], expr.args[3]]) do x, y
compexpr = Expr(expr.head, x, expr.args[2], y)
:($cont($compexpr))
end
elseif expr.head == :vcat
tk(expr.args) do e...
:($cont([$(e...)]))
end
elseif expr.head == :ref
@assert length(expr.args) == 2
tk(expr.args) do x, y
:($cont($x[$y]))
end
else
error("$(expr.head) expression not recognized")
end
end
function tk(k::Function, expr::Union(Expr, Atom))
if isatomic(expr)
k(m(expr))
elseif expr.head == :local && isexpr(expr.args[1].args[2], :call)
# This is an optimization.
# When the result of a function call is bound to a local
# variable, bind the variable by using its name as the
# continuation's argument.
# e.g. local a = f(x); <expr> => f(x, (a) -> <expr>)
#
# This optimization is contained wholly within this elseif.
v = expr.args[1].args[1]
callexpr = expr.args[1].args[2]
tc(callexpr, :($v -> $(k(v))))
elseif expr.head == :local
v = expr.args[1].args[1]
tc(expr, :($v -> $(k(v))))
elseif expr.head == :...
v = gensym()
vsplat = Expr(:..., v)
tc(expr.args[1], :($v -> $(k(vsplat))))
else
v = gensym()
tc(expr, :($v -> Stochy.Thunk(() -> $(k(v)))))
end
end
function tk(k::Function, exprs::Array)
if isempty(exprs)
k(()...)
else
tk(first(exprs)) do e
tk(exprs[2:end]) do es...
k(e, es...)
end
end
end
end
function m(expr::Expr)
@assert isatomic(expr)
if expr.head == :->
k = symbol("##k00")
args = procargs(expr.args[1])
# This type annotation is required to fix a failing test
# caused by this issue:
# https://github.com/JuliaLang/julia/issues/9770
body = expr.args[2]::Expr
:(($k, $(args...)) -> $(tc(body, k)))
elseif expr.head == :quote
expr
else
error("unreachable")
end
end
m(expr::Atom) = expr
procargs(exp::Expr) = exp.args
procargs(exp) = [exp]
isatomic(exp::Atom) = true
isatomic(exp::Expr) = exp.head == :-> || exp.head == :quote
isatomic(exp) = false
isprimop(exp::Expr) = exp.head == :call && exp.args[1] in primitives
isline(exp::Expr) = exp.head == :line
isline(exp::LineNumberNode) = true
isline(exp) = false
not(pred) = x -> !(pred(x))
split(pos::Int, a::Array) = (a[1:pos-1],a[pos:end])
striplineinfo(exp::Expr) = Expr(exp.head, map(striplineinfo, filter(not(isline), exp.args))...)
striplineinfo(exp) = exp
function desugar(expr::Expr)
if expr.head == :block
# Expand local expressions of n variables into n local
# expressions each introducing a single variable.
newargs = map(expandlocals, expr.args) |> flatten
Expr(:block, map(desugar, newargs)...)
elseif expr.head == :local && length(expr.args) > 1
# Add a top-level local expression to a block and recurse to
# expand if required.
desugar(Expr(:block, expr))
elseif expr.head == :call && expr.args[1] == :~
# Re-write calls to ~.
Expr(:call, :sample, map(desugar, expr.args[2:end])...)
else
Expr(expr.head, map(desugar, expr.args)...)
end
end
desugar(expr::Atom) = expr
desugar(expr::LineNumberNode) = expr
flatten(a) = vcat(a...)
function expandlocals(expr::Expr)
if expr.head == :local
map(arg->:(local $(arg.args[1])=$(arg.args[2])), expr.args)
else
expr
end
end
expandlocals(expr::Atom) = expr
expandlocals(expr::LineNumberNode) = expr
|
mit
|
nodejitsu/service-select
|
index.js
|
3961
|
'use strict';
var Pagelet = require('pagelet')
, async = require('async')
, path = require('path');
Pagelet.extend({
view: 'view.ejs',
css: 'css.styl',
js: 'client.js',
//
// Allow FORM submits to be streaming.
//
streaming: true,
//
// Force a name.
//
name: 'service-select',
//
// What data needs to be synced with the front-end.
//
query: ['services'],
pagelets: {
target: Pagelet.extend({
view: 'target.ejs',
streaming: true
}).on(module)
},
//
// External dependencies that should be included on the page using a regular
// script tag. This dependency is needed for the `package.js` client file.
//
dependencies: [
path.join(__dirname, '/selectize.default.css'),
'//code.jquery.com/jquery-2.1.0.min.js',
path.join(__dirname, '/selectize.js')
],
/**
* Respond to POST requests.
*
* @param {Object} fields The input fields.
* @param {Object} files Optional uploaded files.
* @param {Function} next Completion callback.
* @api public
*/
post: function post(fields, files, next) {
if ('delete' in fields) {
this.remove(fields, next);
} else if ('add' in fields) {
this.add(fields, next);
} else {
next(new Error('Invalid form data'));
}
},
/**
* Called when a new service has to be added.
*
* @param {Object} data The data to add.
* @param {FUnction} next Continuation function.
* @api public
*/
add: function add(data, next) {
throw new Error([
'You, as a developer need to implement the `.add` method of the service',
'select pagelet. If you dont know how to do this, see the documenation',
'about Pagelet.extend({});'
].join(' '));
},
/**
* A service has been removed from the UI.
*
* @param {Object} data The data containing the info about the service
*/
remove: function remove(data, next) {
throw new Error([
'You, as a developer need to implement the `.remove` method of the service',
'select pagelet. If you dont know how to do this, see the documenation',
'about Pagelet.extend({});'
].join(' '));
},
/**
* The available services that should be listed in the UI.
*
* @param {Function} next Continuation callback
* @api public
*/
services: function services(next) {
throw new Error([
'You, as a developer need to implement the `.services` method of the service',
'select pagelet. If you dont know how to do this, see the documenation',
'about Pagelet.extend({});'
].join(' '));
},
/**
* List of added services that should be displayed in the UI.
*
* @param {Fucntion} next Continuation callback.
* @api public
*/
added: function added(next) {
throw new Error([
'You, as a developer need to implement the `.added` method of the service',
'select pagelet. If you dont know how to do this, see the documenation',
'about Pagelet.extend({});'
].join(' '));
},
/**
* Render the HTML things.
*
* @param {Function} done Continuation callback.
* @api public
*/
get: function get(done) {
var pagelet = this;
async.parallel({
services: this.services.bind(this),
added: this.added.bind(this)
}, function completed(err, data) {
if (err) return done(err);
data.services = data.services || [];
data.added = data.added || [];
['services', 'added'].forEach(function transform(key) {
if (Array.isArray(data[key])) return;
data[key] = Object.keys(data[key]).map(function map(name) {
var thing = data[key][name];
thing.name = thing.name || name;
return thing;
});
});
data.description = pagelet.description;
data.name = pagelet.name.replace('-', ' ');
data.name = data.name.slice(0, 1).toUpperCase() + data.name.slice(1);
done(err, data);
});
}
}).on(module);
|
mit
|
toajs/toajs.com
|
public/src/views/docs/guide.html
|
47151
|
<h1>Toa</h1>
<p>简洁而强大的 web 框架。</p>
<h2>Thanks to <a href="https://github.com/koajs/koa">Koa</a> and it’s authors</h2>
<h2 id="doc-summary">Summary</h2>
<ul>
<li><a href="#toa">Toa 简介</a></li>
<li><a href="#application">Application 应用</a></li>
<li><a href="#context">Context 对象</a></li>
<li><a href="#request">Request 对象</a></li>
<li><a href="#response">Response 对象</a></li>
</ul>
<h2>Toa 简介</h2>
<p><strong>Toa</strong> 修改自 <strong>Koa</strong>,基本架构原理与 <strong>Koa</strong> 相似,<code>context</code>、<code>request</code>、<code>response</code> 三大基础对象几乎一样。</p>
<p><strong>Toa</strong> 是基于 <a href="https://github.com/thunks/thunks">thunks</a> 组合业务逻辑,来实现异步流程控制和异常处理。<code>thunks</code> 是一个比 <code>co</code> 更强大的异步流程控制工具,支持所有形式的异步控制,包括 callback,promise,generator,async/await 等。</p>
<p><strong>Toa</strong> 支持 <code>Node.js v0.12</code> 以上,但在高版本中将有更好的体验和性能,如 <code>>=v4</code> 的版本支持 generator 函数,<code>>=v7</code> 的版本支持 async/await 函数,这些特性支持<strong>用同步逻辑编写非阻塞的异步程序</strong>。</p>
<p><strong>Toa</strong> 与 <strong>Koa</strong> 学习成本和编程体验是一致的,两者之间几乎是无缝切换。但 <strong>Toa</strong> 去掉了 <strong>Koa</strong> 的 <code>级联(Cascading)</code> 逻辑,强化中间件,尽量削弱第三方组件访问应用的能力,使得编写大型应用的结构逻辑更简洁明了,也更安全。</p>
<h3>安装 Toa</h3>
<pre><code class="language-sh">npm install toa
</code></pre>
<h2 id="doc-application">Application</h2>
<p>一个 Toa Application(以下简称 <strong>app</strong>)由一系列 <strong>中间件</strong> 组成。<strong>中间件</strong> 是指通过 <code>app.use</code> 加载的同步函数、thunk 函数、generator 函数或 async/await 函数。</p>
<p>对于 web server 的一次访问请求,app 会按照顺序先运行中间件,然后再运行业务逻辑中 <code>context.after(hook)</code> 动态添加的 hooks,最后运行内置的 <code>respond</code> 函数,将请求结果自动响应的客户端。由于 Toa 没有 <code>级联(Cascading)</code>,这些中间件或模块的运行不会有任何交叉,它们总是先运行完一个,再运行下一个。</p>
<p>Toa 只有一个极简的内核,提供快捷的 HTTP 操作和异步流程控制能力。具体的业务功能逻辑则由中间件和模块组合实现。用户则可根据自己的业务需求,以最轻量级的方式组合自己的应用。</p>
<p>让我们来看看 Toa 极其简单的 Hello World 应用程序:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> Toa = <span class="hljs-built_in">require</span>(<span class="hljs-string">'toa'</span>)
<span class="hljs-keyword">const</span> app = <span class="hljs-keyword">new</span> Toa()
app.use(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
<span class="hljs-keyword">this</span>.body = <span class="hljs-string">'Hello World!\n-- toa'</span>
})
app.listen(<span class="hljs-number">3000</span>)
</code></pre>
<h3>Class: Toa()</h3>
<h3>Class: Toa(server)</h3>
<h3>Class: Toa(options)</h3>
<h3>Class: Toa(onerror)</h3>
<h3>Class: Toa(server, options)</h3>
<ul>
<li><code>server</code>: {Object}, http server 或 https server 实例。</li>
<li><code>options</code>: {Object} 类似 <code>thunks</code> 的 options,对于 server 的每一个 <strong>client request</strong>,toa app 均会用 <code>thunks</code> 生成一个的 <code>thunk</code>,挂载到 <code>context.thunk</code>,该 <code>thunk</code> 的作用域对该 <strong>client request</strong> 的整个生命周期生效。
<ul>
<li><code>options.onerror</code>: {Function} 其 <code>this</code> 为 <strong>client request</strong> 的 <code>context</code> 对象。当 <strong>client request</strong> 处理流程出现异常时,会抛出到 <code>onerror</code>,原有处理流程会终止,<code>onerror</code> 运行完毕后再进入 toa 内置的异常处理流程,最后 <code>respond</code> 客户端。如果 <code>onerror</code> 返回 <code>true</code>,则会忽略该异常,异常不会进入内置异常处理流程,然后直接 <code>respond</code> 客户端。</li>
</ul></li>
</ul>
<pre><code class="language-js"><span class="hljs-comment">// with full arguments</span>
<span class="hljs-keyword">const</span> app = <span class="hljs-keyword">new</span> Toa(server, {
<span class="hljs-attr">onerror</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">error</span>) </span>{}
})
</code></pre>
<h4>app.keys = ['key1’, ‘key2’]</h4>
<p>设置 cookie 签名密钥,参考 <a href="https://github.com/expressjs/keygrip">Keygrip</a>。<br>
注意,签名密钥只在配置项 <code>signed</code> 参数为真时才会生效:</p>
<pre><code class="language-js"><span class="hljs-keyword">this</span>.cookies.set(<span class="hljs-string">'name'</span>, <span class="hljs-string">'test'</span>, {<span class="hljs-attr">signed</span>: <span class="hljs-literal">true</span>})
</code></pre>
<h4>app.config = config</h4>
<p>config 会被 <code>context.config</code> 继承,但 <code>context.config</code> 不会修改 <code>app.config</code>。</p>
<pre><code class="language-js">app.config = config
</code></pre>
<p>app.config 默认值:</p>
<pre><code class="language-js">{
<span class="hljs-attr">proxy</span>: <span class="hljs-literal">false</span>, <span class="hljs-comment">// 决定了哪些 `proxy header` 参数会被加到信任列表中</span>
env: process.env.NODE_ENV || <span class="hljs-string">'development'</span>, <span class="hljs-comment">// node 执行环境</span>
subdomainOffset: <span class="hljs-number">2</span>,
<span class="hljs-attr">poweredBy</span>: <span class="hljs-string">'Toa'</span>
}
</code></pre>
<h4>app.use(function () {})</h4>
<h4>app.use(function (callback) {})</h4>
<h4>app.use(function * () {})</h4>
<h4>app.use(async function () {})</h4>
<p>加载中间件,返回 <code>app</code>,<code>fn</code> 必须是 <code>thunk</code> 函数或 <code>generator</code> 函数,函数中的 <code>this</code> 值为 <code>context</code>。</p>
<pre><code class="language-js">app.use(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">callback</span>) </span>{
<span class="hljs-comment">// task</span>
<span class="hljs-comment">// this === context</span>
callback(err, result)
})
</code></pre>
<pre><code class="language-js">app.use(<span class="hljs-function"><span class="hljs-keyword">function</span> * (<span class="hljs-params"></span>) </span>{
<span class="hljs-comment">// task</span>
<span class="hljs-comment">// this === context</span>
<span class="hljs-keyword">yield</span> result
})
</code></pre>
<h4>app.onerror = function (error) {}</h4>
<p>设置 <code>onerror</code> 函数,当 app 捕捉到程序运行期间的错误时,会先使用 <code>options.onerror</code>(若提供)处理,再使用内置的 <code>onResError</code> 函数处理响应给客户端,最后抛出给 <code>app.onerror</code> 处理,应用通常可以在这里判断错误类型,根据情况将错误写入日志系统。</p>
<pre><code class="language-js"><span class="hljs-comment">// default</span>
app.onerror = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">err</span>) </span>{
<span class="hljs-comment">// ignore null and response error</span>
<span class="hljs-keyword">if</span> (err == <span class="hljs-literal">null</span> || (err.status && err.status < <span class="hljs-number">500</span>)) <span class="hljs-keyword">return</span>
<span class="hljs-keyword">if</span> (!util.isError(err)) err = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'non-error thrown: '</span> + err)
<span class="hljs-comment">// catch system error</span>
<span class="hljs-keyword">let</span> msg = err.stack || err.toString()
<span class="hljs-built_in">console</span>.error(msg.replace(<span class="hljs-regexp">/^/gm</span>, <span class="hljs-string">' '</span>))
}
</code></pre>
<h4>app.toListener()</h4>
<p>返回 app request listener。</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'http'</span>)
<span class="hljs-keyword">const</span> toa = <span class="hljs-built_in">require</span>(<span class="hljs-string">'toa'</span>)
<span class="hljs-keyword">const</span> app = toa()
<span class="hljs-keyword">const</span> server = http.createServer(app.toListener())
server.listen(<span class="hljs-number">3000</span>)
</code></pre>
<p>等效于:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> toa = <span class="hljs-built_in">require</span>(<span class="hljs-string">'toa'</span>)
<span class="hljs-keyword">const</span> app = toa()
app.listen(<span class="hljs-number">3000</span>)
</code></pre>
<h4>app.listen(port, [hostname], [backlog], [callback])</h4>
<h4>app.listen(path, [callback])</h4>
<h4>app.listen(handle, [callback])</h4>
<p>返回 <code>server</code>,用法与 <code>httpServer.listen</code> 一致。</p>
<pre><code class="language-js"><span class="hljs-comment">// 与 httpServer.listen 一致</span>
app.listen(<span class="hljs-number">3000</span>)
</code></pre>
<hr>
<h2 id="doc-context">Context</h2>
<p>Similar to <a href="https://github.com/koajs/koa/blob/master/docs/api/context.md">Koa’s Context</a></p>
<h3>Difference from Koa</h3>
<ul>
<li>remove <code>ctx.app</code></li>
<li>add <code>ctx.thunk</code> method, it is thunk function that bound a scope with <code>onerror</code>.</li>
<li>add <code>ctx.end</code> method, use to stopping request process and respond immediately.</li>
<li>add <code>ctx.after</code> method, use to add hooks that run after middlewares and before respond.</li>
<li>add <code>ctx.catchStream</code> method, used to catch stream’s error or clean stream when some error.</li>
<li>add <code>ctx.ended</code> property, indicates that the response ended.</li>
<li>add <code>ctx.finished</code> property, indicates that the response finished successfully.</li>
<li>add <code>ctx.closed</code> property, indicates that the response closed unexpectedly.</li>
<li>context is a <code>EventEmitter</code> instance</li>
</ul>
<p><code>Context</code> object encapsulates node’s <code>request</code> and <code>response</code> objects into a single object which provides many helpful methods for writing web applications and APIs. These operations are used so frequently in HTTP server development that they are added at this level instead of a higher level framework, which would force middleware to re-implement this common functionality.</p>
<p>A <code>Context</code> is created <em>per</em> request, and is referenced in middleware as the receiver, or the <code>this</code> identifier, as shown in the following snippet:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> app = Toa(<span class="hljs-function"><span class="hljs-keyword">function</span> * (<span class="hljs-params"></span>) </span>{
<span class="hljs-keyword">this</span> <span class="hljs-comment">// is the Context</span>
<span class="hljs-keyword">this</span>.request <span class="hljs-comment">// is a toa Request</span>
<span class="hljs-keyword">this</span>.response <span class="hljs-comment">// is a toa Response</span>
})
app.use(<span class="hljs-function"><span class="hljs-keyword">function</span> * (<span class="hljs-params"></span>) </span>{
<span class="hljs-keyword">this</span> <span class="hljs-comment">// is the Context</span>
<span class="hljs-keyword">this</span>.request <span class="hljs-comment">// is a toa Request</span>
<span class="hljs-keyword">this</span>.response <span class="hljs-comment">// is a toa Response</span>
})
</code></pre>
<p>Many of the context’s accessors and methods simply delegate to their <code>ctx.request</code> or <code>ctx.response</code> equivalents for convenience, and are otherwise identical. For example <code>ctx.type</code> and <code>ctx.length</code> delegate to the <code>response</code> object, and <code>ctx.path</code> and <code>ctx.method</code> delegate to the <code>request</code>.</p>
<h3>Events</h3>
<h4>‘close’</h4>
<p>Emitted after a HTTP request closed, indicates that the socket has been closed, and <code>context.closed</code> will be <code>true</code>.</p>
<h4>‘end’</h4>
<p>Emitted after respond() was called, indicates that body was sent. and <code>context.ended</code> will be <code>true</code></p>
<h4>‘finish’</h4>
<p>Emitted after a HTTP response finished. and <code>context.finished</code> will be <code>true</code>.</p>
<h4>‘error’</h4>
<p>A context always listen <code>'error'</code> event by <code>ctx.onerror</code>. <code>ctx.onerror</code> is a <strong>immutable</strong> error handle. So you can use <code>ctx.emit('error', error)</code> to deal with your exception or error.</p>
<h3>API</h3>
<p><code>Context</code> specific methods and accessors.</p>
<h4>ctx.thunk([thunkable])</h4>
<p>A thunk function that bound a scope.</p>
<ul>
<li><code>thunkable</code> thunkable value, see: <a href="https://github.com/thunks/thunks">https://github.com/thunks/thunks</a></li>
</ul>
<h4>ctx.end([message])</h4>
<p>Use to stopping request process and respond immediately. <strong>It should not run in <code>try catch</code> block, otherwise <code>onstop</code> will not be trigger</strong>.</p>
<ul>
<li><code>message</code> String, see: <a href="https://github.com/thunks/thunks">https://github.com/thunks/thunks</a></li>
</ul>
<h4>ctx.after(function () {})</h4>
<h4>ctx.after(function (callback) {})</h4>
<h4>ctx.after(function * () {})</h4>
<h4>ctx.after(async function () {})</h4>
<p>Add hooks dynamicly. Hooks will be executed in LIFO order after middlewares, but before <code>respond</code>.</p>
<h4>ctx.req</h4>
<p>Node’s <code>request</code> object.</p>
<h4>ctx.res</h4>
<p>Node’s <code>response</code> object.</p>
<p>Bypassing Toa’s response handling is <strong>not supported</strong>. Avoid using the following node properties:</p>
<ul>
<li><code>res.statusCode</code></li>
<li><code>res.writeHead()</code></li>
<li><code>res.write()</code></li>
<li><code>res.end()</code></li>
</ul>
<h4>ctx.request</h4>
<p>A Toa <code>Request</code> object.</p>
<h4>ctx.response</h4>
<p>A Toa <code>Response</code> object.</p>
<h4>ctx.state</h4>
<p>The recommended namespace for passing information through middleware and to your frontend views.</p>
<pre><code class="language-js"><span class="hljs-keyword">this</span>.state.user = <span class="hljs-keyword">yield</span> User.find(id)
</code></pre>
<h4>ctx.cookies.get(name, [options])</h4>
<p>Get cookie <code>name</code> with <code>options</code>:</p>
<ul>
<li><code>signed</code> the cookie requested should be signed</li>
</ul>
<p>Toa uses the <a href="https://github.com/jed/cookies">cookies</a> module where options are simply passed.</p>
<h4>ctx.cookies.set(name, value, [options])</h4>
<p>Set cookie <code>name</code> to <code>value</code> with <code>options</code>:</p>
<ul>
<li><code>signed</code> sign the cookie value</li>
<li><code>expires</code> a <code>Date</code> for cookie expiration</li>
<li><code>path</code> cookie path, <code>/'</code> by default</li>
<li><code>domain</code> cookie domain</li>
<li><code>secure</code> secure cookie</li>
<li><code>httpOnly</code> server-accessible cookie, <strong>true</strong> by default</li>
</ul>
<p>Toa uses the <a href="https://github.com/jed/cookies">cookies</a> module where options are simply passed.</p>
<h4>ctx.throw([msg], [status], [properties])</h4>
<p>Helper method to throw an error with a <code>.status</code> property defaulting to <code>500</code> that will allow Toa to respond appropriately. The following combinations are allowed:</p>
<pre><code class="language-js"><span class="hljs-keyword">this</span>.throw(<span class="hljs-number">403</span>)
<span class="hljs-keyword">this</span>.throw(<span class="hljs-string">'name required'</span>, <span class="hljs-number">400</span>)
<span class="hljs-keyword">this</span>.throw(<span class="hljs-number">400</span>, <span class="hljs-string">'name required'</span>)
<span class="hljs-keyword">this</span>.throw(<span class="hljs-string">'something exploded'</span>)
</code></pre>
<p>For example <code>this.throw('name required', 400)</code> is equivalent to:</p>
<pre><code class="language-js"><span class="hljs-keyword">let</span> err = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'name required'</span>)
err.status = <span class="hljs-number">400</span>
<span class="hljs-keyword">throw</span> err
</code></pre>
<p>Note that these are user-level errors and are flagged with <code>err.expose</code> meaning the messages are appropriate for client responses, which is typically not the case for error messages since you do not want to leak failure details.</p>
<p>You may optionally pass a <code>properties</code> object which is merged into the error as-is, useful for decorating machine-friendly errors which are reported to the requester upstream.</p>
<pre><code class="language-js"><span class="hljs-keyword">this</span>.throw(<span class="hljs-number">401</span>, <span class="hljs-string">'access_denied'</span>, {<span class="hljs-attr">user</span>: user})
<span class="hljs-keyword">this</span>.throw(<span class="hljs-string">'access_denied'</span>, {<span class="hljs-attr">user</span>: user})
</code></pre>
<p>Toa uses <a href="https://github.com/jshttp/http-errors">http-errors</a> to create errors.</p>
<h4>ctx.createError([status], [msg], [properties])</h4>
<p>Similar to <code>ctx.throw</code>, create a error object, but don’t throw.</p>
<h4>ctx.assert(value, [status], [msg], [properties])</h4>
<p>Helper method to throw an error similar to <code>.throw()</code> when <code>!value</code>. Similar to node’s <a href="http://nodejs.org/api/assert.html">assert()</a> method.</p>
<pre><code class="language-js"><span class="hljs-keyword">this</span>.assert(<span class="hljs-keyword">this</span>.state.user, <span class="hljs-number">401</span>, <span class="hljs-string">'User not found. Please login!'</span>)
</code></pre>
<p>Toa uses <a href="https://github.com/jshttp/http-assert">http-assert</a> for assertions.</p>
<h4>ctx.respond</h4>
<p>To bypass Toa’s built-in response handling, you may explicitly set <code>this.respond = false</code>. Use this if you want to write to the raw <code>res</code> object instead of letting Toa handle the response for you.</p>
<p>Note that using this is <strong>not</strong> supported by Toa. This may break intended functionality of Toa middleware and Toa itself. Using this property is considered a hack and is only a convenience to those wishing to use traditional <code>fn(req, res)</code> functions and middleware within Toa.</p>
<h4>ctx.catchStream(stream)</h4>
<p>Catch a <code>stream</code>'s error, if ‘error’ event emit from the stream, the error will be throw to Thunk’s <code>onerror</code> and response it.</p>
<h3>Request aliases</h3>
<p>The following accessors and alias <a href="request.md">Request</a> equivalents:</p>
<ul>
<li><code>ctx.header</code></li>
<li><code>ctx.headers</code></li>
<li><code>ctx.method</code></li>
<li><code>ctx.method=</code></li>
<li><code>ctx.url</code></li>
<li><code>ctx.url=</code></li>
<li><code>ctx.origin</code></li>
<li><code>ctx.originalUrl</code></li>
<li><code>ctx.href</code></li>
<li><code>ctx.path</code></li>
<li><code>ctx.path=</code></li>
<li><code>ctx.query</code></li>
<li><code>ctx.query=</code></li>
<li><code>ctx.querystring</code></li>
<li><code>ctx.querystring=</code></li>
<li><code>ctx.host</code></li>
<li><code>ctx.hostname</code></li>
<li><code>ctx.fresh</code></li>
<li><code>ctx.stale</code></li>
<li><code>ctx.socket</code></li>
<li><code>ctx.protocol</code></li>
<li><code>ctx.secure</code></li>
<li><code>ctx.ip</code></li>
<li><code>ctx.ips</code></li>
<li><code>ctx.idempotent</code></li>
<li><code>ctx.subdomains</code></li>
<li><code>ctx.is()</code></li>
<li><code>ctx.accepts()</code></li>
<li><code>ctx.acceptsEncodings()</code></li>
<li><code>ctx.acceptsCharsets()</code></li>
<li><code>ctx.acceptsLanguages()</code></li>
<li><code>ctx.get()</code></li>
<li><code>ctx.search()</code></li>
</ul>
<h3>Response aliases</h3>
<p>The following accessors and alias <a href="response.md">Response</a> equivalents:</p>
<ul>
<li><code>ctx.body</code></li>
<li><code>ctx.body=</code></li>
<li><code>ctx.status</code></li>
<li><code>ctx.status=</code></li>
<li><code>ctx.message</code></li>
<li><code>ctx.message=</code></li>
<li><code>ctx.length=</code></li>
<li><code>ctx.length</code></li>
<li><code>ctx.type=</code></li>
<li><code>ctx.type</code></li>
<li><code>ctx.headerSent</code></li>
<li><code>ctx.redirect()</code></li>
<li><code>ctx.attachment()</code></li>
<li><code>ctx.set()</code></li>
<li><code>ctx.append()</code></li>
<li><code>ctx.remove()</code></li>
<li><code>ctx.vary()</code></li>
<li><code>ctx.lastModified=</code></li>
<li><code>ctx.etag=</code></li>
</ul>
<hr>
<h2 id="doc-request">Request</h2>
<p>The same as <a href="https://github.com/koajs/koa/blob/master/docs/api/request.md">Koa’s Request</a></p>
<p><code>Request</code> object is an abstraction on top of node’s vanilla request object, providing additional functionality that is useful for every day HTTP server development.</p>
<h3>API</h3>
<h4>request.header</h4>
<p>Request header object.</p>
<h4>request.headers</h4>
<p>Request header object. Alias as <code>request.header</code>.</p>
<h4>request.method</h4>
<p>Request method.</p>
<h4>request.method=</h4>
<p>Set request method, useful for implementing middleware such as <code>methodOverride()</code>.</p>
<h4>request.length</h4>
<p>Return request Content-Length as a number when present, or <code>undefined</code>.</p>
<h4>request.url</h4>
<p>Get request URL.</p>
<h4>request.url=</h4>
<p>Set request URL, useful for url rewrites.</p>
<h4>request.origin</h4>
<p>Get origin of URL.</p>
<h4>request.originalUrl</h4>
<p>Get request original URL.</p>
<h4>request.href</h4>
<p>Get full request URL, include <code>protocol</code>, <code>host</code> and <code>url</code>.</p>
<pre><code class="language-js"><span class="hljs-keyword">this</span>.request.href
<span class="hljs-comment">// => http://example.com/foo/bar?q=1</span>
</code></pre>
<h4>request.path</h4>
<p>Get request pathname.</p>
<h4>request.path=</h4>
<p>Set request pathname and retain query-string when present.</p>
<h4>request.querystring</h4>
<p>Get raw query string void of <code>?</code>.</p>
<h4>request.querystring=</h4>
<p>Set raw query string.</p>
<h4>request.search</h4>
<p>Get raw query string with the <code>?</code>.</p>
<h4>request.search=</h4>
<p>Set raw query string.</p>
<h4>request.host</h4>
<p>Get host (hostname:port) when present. Supports <code>X-Forwarded-Host</code> when <code>app.proxy</code> is <strong>true</strong>, otherwise <code>Host</code> is used.</p>
<h4>request.hostname</h4>
<p>Get hostname when present. Supports <code>X-Forwarded-Host</code> when <code>app.proxy</code> is <strong>true</strong>, otherwise <code>Host</code> is used.</p>
<h4>request.type</h4>
<p>Get request <code>Content-Type</code> void of parameters such as "charset".</p>
<pre><code class="language-js"><span class="hljs-keyword">let</span> ct = <span class="hljs-keyword">this</span>.request.type
<span class="hljs-comment">// => "image/png"</span>
</code></pre>
<h4>request.charset</h4>
<p>Get request charset when present, or <code>undefined</code>:</p>
<pre><code class="language-js"><span class="hljs-keyword">this</span>.request.charset
<span class="hljs-comment">// => "utf-8"</span>
</code></pre>
<h4>request.query</h4>
<p>Get parsed query-string, returning an empty object when no query-string is present. Note that this getter does <em>not</em> support nested parsing.</p>
<p>For example "color=blue&size=small":</p>
<pre><code class="language-js">{
<span class="hljs-attr">color</span>: <span class="hljs-string">'blue'</span>,
<span class="hljs-attr">size</span>: <span class="hljs-string">'small'</span>
}
</code></pre>
<h4>request.query=</h4>
<p>Set query-string to the given object. Note that this setter does <em>not</em> support nested objects.</p>
<pre><code class="language-js"><span class="hljs-keyword">this</span>.query = {<span class="hljs-attr">next</span>: <span class="hljs-string">'/login'</span>}
</code></pre>
<h4>request.fresh</h4>
<p>Check if a request cache is "fresh", aka the contents have not changed. This method is for cache negotiation between <code>If-None-Match</code> / <code>ETag</code>, and <code>If-Modified-Since</code> and <code>Last-Modified</code>. It should be referenced after setting one or more of these response headers.</p>
<pre><code class="language-js"><span class="hljs-keyword">this</span>.status = <span class="hljs-number">200</span>
<span class="hljs-keyword">this</span>.set(<span class="hljs-string">'ETag'</span>, <span class="hljs-string">'123'</span>)
<span class="hljs-comment">// cache is ok</span>
<span class="hljs-keyword">if</span> (<span class="hljs-keyword">this</span>.fresh) {
<span class="hljs-keyword">this</span>.status = <span class="hljs-number">304</span>
<span class="hljs-keyword">return</span>
}
<span class="hljs-comment">// cache is stale</span>
<span class="hljs-comment">// fetch new data</span>
<span class="hljs-keyword">this</span>.body = <span class="hljs-keyword">yield</span> db.find(<span class="hljs-string">'something'</span>)
</code></pre>
<h4>request.stale</h4>
<p>Inverse of <code>request.fresh</code>.</p>
<h4>request.protocol</h4>
<p>Return request protocol, “https” or "http". Supports <code>X-Forwarded-Proto</code> when <code>app.proxy</code> is <strong>true</strong>.</p>
<h4>request.secure</h4>
<p>Shorthand for <code>this.protocol == "https"</code> to check if a request was issued via TLS.</p>
<h4>request.ip</h4>
<p>Request remote address. Supports <code>X-Forwarded-For</code> when <code>app.proxy</code> is <strong>true</strong>.</p>
<h4>request.ips</h4>
<p>When <code>X-Forwarded-For</code> is present and <code>app.proxy</code> is enabled an array of these ips is returned, ordered from upstream -> downstream. When disabled an empty array is returned.</p>
<h4>request.subdomains</h4>
<p>Return subdomains as an array.</p>
<p>Subdomains are the dot-separated parts of the host before the main domain of the app. By default, the domain of the app is assumed to be the last two parts of the host. This can be changed by setting <code>app.subdomainOffset</code>.</p>
<p>For example, if the domain is "tobi.ferrets.example.com":</p>
<p>If <code>app.subdomainOffset</code> is not set, this.subdomains is <code>["ferrets", "tobi"]</code>.<br>
If <code>app.subdomainOffset</code> is 3, this.subdomains is <code>["tobi"]</code>.</p>
<h4>request.is(types...)</h4>
<p>Check if the incoming request contains the “Content-Type” header field, and it contains any of the give mime <code>type</code>s. If there is no request body, <code>null</code> is returned. If there is no content type, or the match fails <code>false</code> is returned. Otherwise, it returns the matching content-type.</p>
<pre><code class="language-js"><span class="hljs-comment">// With Content-Type: text/html; charset=utf-8</span>
<span class="hljs-keyword">this</span>.is(<span class="hljs-string">'html'</span>) <span class="hljs-comment">// => 'html'</span>
<span class="hljs-keyword">this</span>.is(<span class="hljs-string">'text/html'</span>) <span class="hljs-comment">// => 'text/html'</span>
<span class="hljs-keyword">this</span>.is(<span class="hljs-string">'text/*'</span>, <span class="hljs-string">'text/html'</span>) <span class="hljs-comment">// => 'text/html'</span>
<span class="hljs-comment">// When Content-Type is application/json</span>
<span class="hljs-keyword">this</span>.is(<span class="hljs-string">'json'</span>, <span class="hljs-string">'urlencoded'</span>) <span class="hljs-comment">// => 'json'</span>
<span class="hljs-keyword">this</span>.is(<span class="hljs-string">'application/json'</span>) <span class="hljs-comment">// => 'application/json'</span>
<span class="hljs-keyword">this</span>.is(<span class="hljs-string">'html'</span>, <span class="hljs-string">'application/*'</span>) <span class="hljs-comment">// => 'application/json'</span>
<span class="hljs-keyword">this</span>.is(<span class="hljs-string">'html'</span>) <span class="hljs-comment">// => false</span>
</code></pre>
<p>For example if you want to ensure that only images are sent to a given route:</p>
<pre><code class="language-js"><span class="hljs-keyword">if</span> (<span class="hljs-keyword">this</span>.is(<span class="hljs-string">'image/*'</span>)) {
<span class="hljs-comment">// process</span>
} <span class="hljs-keyword">else</span> {
<span class="hljs-keyword">this</span>.throw(<span class="hljs-number">415</span>, <span class="hljs-string">'images only!'</span>)
}
</code></pre>
<h4>Content Negotiation</h4>
<p><code>Request</code> object includes helpful content negotiation utilities powered by <a href="http://github.com/expressjs/accepts">accepts</a> and <a href="https://github.com/federomero/negotiator">negotiator</a>. These utilities are:</p>
<ul>
<li><code>request.accepts(types)</code></li>
<li><code>request.acceptsEncodings(types)</code></li>
<li><code>request.acceptsCharsets(charsets)</code></li>
<li><code>request.acceptsLanguages(langs)</code></li>
</ul>
<p>If no types are supplied, <strong>all</strong> acceptable types are returned.</p>
<p>If multiple types are supplied, the best match will be returned. If no matches are found, a <code>false</code> is returned, and you should send a <code>406 "Not Acceptable"</code> response to the client.</p>
<p>In the case of missing accept headers where any type is acceptable, the first type will be returned. Thus, the order of types you supply is important.</p>
<h4>request.accepts(types)</h4>
<p>Check if the given <code>type(s)</code> is acceptable, returning the best match when true, otherwise <code>false</code>. The <code>type</code> value may be one or more mime type string such as "application/json", the extension name such as "json", or an array <code>["json", "html", "text/plain"]</code>.</p>
<pre><code class="language-js"><span class="hljs-comment">// Accept: text/html</span>
<span class="hljs-keyword">this</span>.accepts(<span class="hljs-string">'html'</span>)
<span class="hljs-comment">// => "html"</span>
<span class="hljs-comment">// Accept: text/*, application/json</span>
<span class="hljs-keyword">this</span>.accepts(<span class="hljs-string">'html'</span>)
<span class="hljs-comment">// => "html"</span>
<span class="hljs-keyword">this</span>.accepts(<span class="hljs-string">'text/html'</span>)
<span class="hljs-comment">// => "text/html"</span>
<span class="hljs-keyword">this</span>.accepts(<span class="hljs-string">'json'</span>, <span class="hljs-string">'text'</span>)
<span class="hljs-comment">// => "json"</span>
<span class="hljs-keyword">this</span>.accepts(<span class="hljs-string">'application/json'</span>)
<span class="hljs-comment">// => "application/json"</span>
<span class="hljs-comment">// Accept: text/*, application/json</span>
<span class="hljs-keyword">this</span>.accepts(<span class="hljs-string">'image/png'</span>)
<span class="hljs-keyword">this</span>.accepts(<span class="hljs-string">'png'</span>)
<span class="hljs-comment">// => false</span>
<span class="hljs-comment">// Accept: text/*;q=.5, application/json</span>
<span class="hljs-keyword">this</span>.accepts([<span class="hljs-string">'html'</span>, <span class="hljs-string">'json'</span>])
<span class="hljs-keyword">this</span>.accepts(<span class="hljs-string">'html'</span>, <span class="hljs-string">'json'</span>)
<span class="hljs-comment">// => "json"</span>
<span class="hljs-comment">// No Accept header</span>
<span class="hljs-keyword">this</span>.accepts(<span class="hljs-string">'html'</span>, <span class="hljs-string">'json'</span>)
<span class="hljs-comment">// => "html"</span>
<span class="hljs-keyword">this</span>.accepts(<span class="hljs-string">'json'</span>, <span class="hljs-string">'html'</span>)
<span class="hljs-comment">// => "json"</span>
</code></pre>
<p>You may call <code>this.accepts()</code> as many times as you like, or use a switch:</p>
<pre><code class="language-js"><span class="hljs-keyword">switch</span> (<span class="hljs-keyword">this</span>.accepts(<span class="hljs-string">'json'</span>, <span class="hljs-string">'html'</span>, <span class="hljs-string">'text'</span>)) {
<span class="hljs-keyword">case</span> <span class="hljs-string">'json'</span>: <span class="hljs-keyword">break</span>
<span class="hljs-keyword">case</span> <span class="hljs-string">'html'</span>: <span class="hljs-keyword">break</span>
<span class="hljs-keyword">case</span> <span class="hljs-string">'text'</span>: <span class="hljs-keyword">break</span>
<span class="hljs-keyword">default</span>: <span class="hljs-keyword">this</span>.throw(<span class="hljs-number">406</span>, <span class="hljs-string">'json, html, or text only'</span>)
}
</code></pre>
<h4>request.acceptsEncodings(encodings)</h4>
<p>Check if <code>encodings</code> are acceptable, returning the best match when true, otherwise <code>false</code>. Note that you should include <code>identity</code> as one of the encodings!</p>
<pre><code class="language-js"><span class="hljs-comment">// Accept-Encoding: gzip</span>
<span class="hljs-keyword">this</span>.acceptsEncodings(<span class="hljs-string">'gzip'</span>, <span class="hljs-string">'deflate'</span>, <span class="hljs-string">'identity'</span>)
<span class="hljs-comment">// => "gzip"</span>
<span class="hljs-keyword">this</span>.acceptsEncodings([<span class="hljs-string">'gzip'</span>, <span class="hljs-string">'deflate'</span>, <span class="hljs-string">'identity'</span>])
<span class="hljs-comment">// => "gzip"</span>
</code></pre>
<p>When no arguments are given all accepted encodings are returned as an array:</p>
<pre><code class="language-js"><span class="hljs-comment">// Accept-Encoding: gzip, deflate</span>
<span class="hljs-keyword">this</span>.acceptsEncodings()
<span class="hljs-comment">// => ["gzip", "deflate", "identity"]</span>
</code></pre>
<p>Note that the <code>identity</code> encoding (which means no encoding) could be unacceptable if the client explicitly sends <code>identity;q=0</code>. Although this is an edge case, you should still handle the case where this method returns <code>false</code>.</p>
<h4>request.acceptsCharsets(charsets)</h4>
<p>Check if <code>charsets</code> are acceptable, returning the best match when true, otherwise <code>false</code>.</p>
<pre><code class="language-js"><span class="hljs-comment">// Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5</span>
<span class="hljs-keyword">this</span>.acceptsCharsets(<span class="hljs-string">'utf-8'</span>, <span class="hljs-string">'utf-7'</span>)
<span class="hljs-comment">// => "utf-8"</span>
<span class="hljs-keyword">this</span>.acceptsCharsets([<span class="hljs-string">'utf-7'</span>, <span class="hljs-string">'utf-8'</span>])
<span class="hljs-comment">// => "utf-8"</span>
</code></pre>
<p>When no arguments are given all accepted charsets are returned as an array:</p>
<pre><code class="language-js"><span class="hljs-comment">// Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5</span>
<span class="hljs-keyword">this</span>.acceptsCharsets()
<span class="hljs-comment">// => ["utf-8", "utf-7", "iso-8859-1"]</span>
</code></pre>
<h4>request.acceptsLanguages(langs)</h4>
<p>Check if <code>langs</code> are acceptable, returning the best match when true, otherwise <code>false</code>.</p>
<pre><code class="language-js"><span class="hljs-comment">// Accept-Language: en;q=0.8, es, pt</span>
<span class="hljs-keyword">this</span>.acceptsLanguages(<span class="hljs-string">'es'</span>, <span class="hljs-string">'en'</span>)
<span class="hljs-comment">// => "es"</span>
<span class="hljs-keyword">this</span>.acceptsLanguages([<span class="hljs-string">'en'</span>, <span class="hljs-string">'es'</span>])
<span class="hljs-comment">// => "es"</span>
</code></pre>
<p>When no arguments are given all accepted languages are returned as an array:</p>
<pre><code class="language-js"><span class="hljs-comment">// Accept-Language: en;q=0.8, es, pt</span>
<span class="hljs-keyword">this</span>.acceptsLanguages()
<span class="hljs-comment">// => ["es", "pt", "en"]</span>
</code></pre>
<h4>request.idempotent</h4>
<p>Check if the request is idempotent.</p>
<h4>request.socket</h4>
<p>Return the request socket.</p>
<h4>request.get(field)</h4>
<p>Return request header.</p>
<hr>
<h2 id="doc-response">Response</h2>
<p>The same as <a href="https://github.com/koajs/koa/blob/master/docs/api/response.md">Koa’s Response</a></p>
<p><code>Response</code> object is an abstraction on top of node’s vanilla response object, providing additional functionality that is useful for every day HTTP server development.</p>
<h3>API</h3>
<h4>response.header</h4>
<p>Response header object.</p>
<h4>response.headers</h4>
<p>Response header object. Alias as <code>response.header</code>.</p>
<h4>response.socket</h4>
<p>Request socket.</p>
<h4>response.status</h4>
<p>Get response status. By default, <code>response.status</code> is not set unlike node’s <code>res.statusCode</code> which defaults to <code>200</code>.</p>
<h4>response.status=</h4>
<p>Set response status via numeric code:</p>
<ul>
<li>100 “continue”</li>
<li>101 “switching protocols”</li>
<li>102 “processing”</li>
<li>200 “ok”</li>
<li>201 “created”</li>
<li>202 “accepted”</li>
<li>203 “non-authoritative information”</li>
<li>204 “no content”</li>
<li>205 “reset content”</li>
<li>206 “partial content”</li>
<li>207 “multi-status”</li>
<li>300 “multiple choices”</li>
<li>301 “moved permanently”</li>
<li>302 “moved temporarily”</li>
<li>303 “see other”</li>
<li>304 “not modified”</li>
<li>305 “use proxy”</li>
<li>307 “temporary redirect”</li>
<li>400 “bad request”</li>
<li>401 “unauthorized”</li>
<li>402 “payment required”</li>
<li>403 “forbidden”</li>
<li>404 “not found”</li>
<li>405 “method not allowed”</li>
<li>406 “not acceptable”</li>
<li>407 “proxy authentication required”</li>
<li>408 “request time-out”</li>
<li>409 “conflict”</li>
<li>410 “gone”</li>
<li>411 “length required”</li>
<li>412 “precondition failed”</li>
<li>413 “request entity too large”</li>
<li>414 “request-uri too large”</li>
<li>415 “unsupported media type”</li>
<li>416 “requested range not satisfiable”</li>
<li>417 “expectation failed”</li>
<li>418 “i’m a teapot”</li>
<li>422 “unprocessable entity”</li>
<li>423 “locked”</li>
<li>424 “failed dependency”</li>
<li>425 “unordered collection”</li>
<li>426 “upgrade required”</li>
<li>428 “precondition required”</li>
<li>429 “too many requests”</li>
<li>431 “request header fields too large”</li>
<li>500 “internal server error”</li>
<li>501 “not implemented”</li>
<li>502 “bad gateway”</li>
<li>503 “service unavailable”</li>
<li>504 “gateway time-out”</li>
<li>505 “http version not supported”</li>
<li>506 “variant also negotiates”</li>
<li>507 “insufficient storage”</li>
<li>509 “bandwidth limit exceeded”</li>
<li>510 “not extended”</li>
<li>511 “network authentication required”</li>
</ul>
<p><strong>NOTE</strong>: don’t worry too much about memorizing these strings,<br>
if you have a typo an error will be thrown, displaying this list<br>
so you can make a correction.</p>
<h4>response.message</h4>
<p>Get response status message. By default, <code>response.message</code> is associated with <code>response.status</code>.</p>
<h4>response.message=</h4>
<p>Set response status message to the given value.</p>
<h4>response.length=</h4>
<p>Set response Content-Length to the given value.</p>
<h4>response.length</h4>
<p>Return response Content-Length as a number when present, or deduce from <code>this.body</code> when possible, or <code>undefined</code>.</p>
<h4>response.body</h4>
<p>Get response body.</p>
<h4>response.body=</h4>
<p>Set response body to one of the following:</p>
<ul>
<li><code>string</code> written</li>
<li><code>Buffer</code> written</li>
<li><code>Stream</code> piped</li>
<li><code>Object</code> json-stringified</li>
<li><code>null</code> no content response</li>
</ul>
<p>If <code>response.status</code> has not been set, Toa will automatically set the status to <code>200</code> or <code>204</code>.</p>
<h5>String</h5>
<p>The Content-Type is defaulted to text/html or text/plain, both with a default charset of utf-8. The Content-Length field is also set.</p>
<h5>Buffer</h5>
<p>The Content-Type is defaulted to application/octet-stream, and Content-Length is also set.</p>
<h5>Stream</h5>
<p>The Content-Type is defaulted to application/octet-stream.</p>
<h5>Object</h5>
<p>The Content-Type is defaulted to application/json.</p>
<h4>response.get(field)</h4>
<p>Get a response header field value with case-insensitive <code>field</code>.</p>
<pre><code class="language-js"><span class="hljs-keyword">let</span> etag = <span class="hljs-keyword">this</span>.get(<span class="hljs-string">'etag'</span>)
</code></pre>
<h4>response.set(field, value)</h4>
<p>Set response header <code>field</code> to <code>value</code>:</p>
<pre><code class="language-js"><span class="hljs-keyword">this</span>.set(<span class="hljs-string">'Cache-Control'</span>, <span class="hljs-string">'no-cache'</span>)
</code></pre>
<h4>response.append(field, value)</h4>
<p>Append additional header <code>field</code> with value <code>val</code>.</p>
<pre><code class="language-js"><span class="hljs-keyword">this</span>.append(<span class="hljs-string">'Link'</span>, <span class="hljs-string">'<http://127.0.0.1/>'</span>)
</code></pre>
<h4>response.set(fields)</h4>
<p>Set several response header <code>fields</code> with an object:</p>
<pre><code class="language-js"><span class="hljs-keyword">this</span>.set({
<span class="hljs-string">'ETag'</span>: <span class="hljs-string">'1234'</span>,
<span class="hljs-string">'Last-Modified'</span>: date
})
</code></pre>
<h4>response.remove(field)</h4>
<p>Remove header <code>field</code>.</p>
<h4>response.type</h4>
<p>Get response <code>Content-Type</code> void of parameters such as "charset".</p>
<pre><code class="language-js"><span class="hljs-keyword">let</span> ct = <span class="hljs-keyword">this</span>.type
<span class="hljs-comment">// => "image/png"</span>
</code></pre>
<h4>response.type=</h4>
<p>Set response <code>Content-Type</code> via mime string or file extension.</p>
<pre><code class="language-js"><span class="hljs-keyword">this</span>.type = <span class="hljs-string">'text/plain; charset=utf-8'</span>
<span class="hljs-keyword">this</span>.type = <span class="hljs-string">'image/png'</span>
<span class="hljs-keyword">this</span>.type = <span class="hljs-string">'.png'</span>
<span class="hljs-keyword">this</span>.type = <span class="hljs-string">'png'</span>
</code></pre>
<p>Note: when appropriate a <code>charset</code> is selected for you, for example <code>response.type = 'html'</code> will default to "utf-8", however when explicitly defined in full as <code>response.type = 'text/html'</code> no charset is assigned.</p>
<h4>response.is(types...)</h4>
<p>Very similar to <code>this.request.is()</code>. Check whether the response type is one of the supplied types. This is particularly useful for creating middleware that manipulate responses.</p>
<h4>response.redirect(url, [alt])</h4>
<p>Perform a [302] redirect to <code>url</code>.</p>
<p>The string “back” is special-cased to provide Referrer support, when Referrer is not present <code>alt</code> or “/” is used.</p>
<pre><code class="language-js"><span class="hljs-keyword">this</span>.redirect(<span class="hljs-string">'back'</span>)
<span class="hljs-keyword">this</span>.redirect(<span class="hljs-string">'back'</span>, <span class="hljs-string">'/index.html'</span>)
<span class="hljs-keyword">this</span>.redirect(<span class="hljs-string">'/login'</span>)
<span class="hljs-keyword">this</span>.redirect(<span class="hljs-string">'http://google.com'</span>)
</code></pre>
<p>To alter the default status of <code>302</code>, simply assign the status before or after this call. To alter the body, assign it after this call:</p>
<pre><code class="language-js"><span class="hljs-keyword">this</span>.status = <span class="hljs-number">301</span>
<span class="hljs-keyword">this</span>.redirect(<span class="hljs-string">'/cart'</span>)
<span class="hljs-keyword">this</span>.body = <span class="hljs-string">'Redirecting to shopping cart'</span>
</code></pre>
<h4>response.attachment([filename])</h4>
<p>Set <code>Content-Disposition</code> to “attachment” to signal the client to prompt for download. Optionally specify the <code>filename</code> of the download.</p>
<h4>response.headerSent</h4>
<p>Check if a response header has already been sent. Useful for seeing if the client may be notified on error.</p>
<h4>response.lastModified</h4>
<p>Return the <code>Last-Modified</code> header as a <code>Date</code>, if it exists.</p>
<h4>response.lastModified=</h4>
<p>Set the <code>Last-Modified</code> header as an appropriate UTC string. You can either set it as a <code>Date</code> or date string.</p>
<pre><code class="language-js"><span class="hljs-keyword">this</span>.response.lastModified = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>()
</code></pre>
<h4>response.etag=</h4>
<p>Set the ETag of a response including the wrapped <code>"</code>s. Note that there is no corresponding <code>response.etag</code> getter.</p>
<pre><code class="language-js"><span class="hljs-keyword">this</span>.response.etag = crypto.createHash(<span class="hljs-string">'md5'</span>).update(<span class="hljs-keyword">this</span>.body).digest(<span class="hljs-string">'hex'</span>)
</code></pre>
<h4>response.vary(field)</h4>
<p>Vary on <code>field</code>.</p>
<hr>
|
mit
|
BrighterCommand/Brighter
|
tests/Paramore.Brighter.Core.Tests/CommandProcessors/TestDoubles/MyPostLoggingHandlerAsyncAttribute.cs
|
1576
|
#region Licence
/* The MIT License (MIT)
Copyright © 2015 Ian Cooper <ian_hammond_cooper@yahoo.co.uk>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the “Software”), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#endregion
using System;
namespace Paramore.Brighter.Core.Tests.CommandProcessors.TestDoubles
{
class MyPostLoggingHandlerAsyncAttribute : RequestHandlerAttribute
{
public MyPostLoggingHandlerAsyncAttribute(int step, HandlerTiming timing)
: base(step, timing)
{
}
public override Type GetHandlerType()
{
return typeof(MyLoggingHandlerAsync<>);
}
}
}
|
mit
|