text
stringlengths
3
1.05M
sap.ui.define([ "sap/base/util/merge" ], function ( merge ) { "use strict"; /** * ConnectorFeaturesMerger class for Connector implementations (write). * * @namespace sap.ui.fl.write._internal.StorageFeaturesMerger * @since 1.70 * @version ${version} * @private * @ui5-restricted sap.ui.fl.write._internal.Storage */ var DEFAULT_FEATURES = { isKeyUser: false, isKeyUserTranslationEnabled: false, isVariantSharingEnabled: false, isPublicFlVariantEnabled: false, isVariantPersonalizationEnabled: true, isContextSharingEnabled: true, isContextSharingEnabledForComp: true, isAtoAvailable: false, isAtoEnabled: false, versioning: {}, isProductiveSystem: true, isPublicLayerAvailable: false, isLocalResetEnabled: false, isZeroDowntimeUpgradeRunning: false, system: "", client: "" }; function _getVersioningFromResponse(oResponse) { var oVersioning = {}; var bVersioningEnabled = !!oResponse.features.isVersioningEnabled; oResponse.layers.forEach(function(sLayer) { oVersioning[sLayer] = bVersioningEnabled; }); return oVersioning; } return { /** * Merges the results from all involved connectors otherwise take default value; * The information if a draft is enabled for a given layer on write is determined by * each connector individually; since getConnectorsForLayer allows no more than 1 connector * for any given layer a merging is not necessary. * * @param {object[]} aResponses - All responses provided by the different connectors * @returns {object} Merged result */ mergeResults: function(aResponses) { var oResult = DEFAULT_FEATURES; aResponses.forEach(function (oResponse) { Object.keys(oResponse.features).forEach(function (sKey) { if (sKey !== "isVersioningEnabled") { oResult[sKey] = oResponse.features[sKey]; } }); oResult.versioning = merge(oResult.versioning, _getVersioningFromResponse(oResponse)); if (oResponse.isContextSharingEnabled !== undefined && oResponse.isContextSharingEnabledForComp === undefined) { oResult.isContextSharingEnabled = oResponse.isContextSharingEnabled; oResult.isContextSharingEnabledForComp = oResponse.isContextSharingEnabled; } }); return oResult; } }; });
<?php require('../config/dbconnect.php'); $sql = "SELECT `plugin_lthc_scores`.clientid as clientid, client_name as 'Client Name', team_assignment as 'Team Assignment', `Client Specialist`, ROUND(AVG(antivirus),1) AS Antivirus, ROUND(AVG(DISK),1) AS Disk, ROUND(AVG(intrusion),1) AS Intrusion, ROUND(AVG(usability),1) AS Usability, ROUND(AVG(services),1) AS Services, ROUND(AVG(updates),1) AS Updates, ROUND(AVG(`event_log`),1) AS Events, ROUND((COALESCE(antivirus,0) + COALESCE(DISK,0) + COALESCE(intrusion,0) + COALESCE(usability,0) + COALESCE(services,0) + COALESCE(updates,0) + COALESCE(event_log,0)) / (COALESCE(antivirus/antivirus,0) + COALESCE(DISK/DISK,0) + COALESCE(intrusion/intrusion,0) + COALESCE(usability/usability,0) + COALESCE(services/services,0) + COALESCE(updates/updates,0) + COALESCE(event_log/event_log,0)),1) AS 'Overall Score' FROM plugin_lthc_scores JOIN v_extradataclients USING(clientid) WHERE `v_extradataclients`.`Name` NOT LIKE '~%' GROUP BY client_name"; $list_spec = "SELECT distinct `Client Specialist` as 'specialist' FROM v_extradataclients WHERE `Client Specialist` != 'None' order by specialist asc"; $listTeamSql = "select distinct `Team_Assignment` as 'team' from plugin_lthc_scores where `Team_Assignment` != '' and `Team_Assignment` != 'None'"; ?> <script src="js/jquery.dataTables.columnFilter.js" type="text/javascript"></script> <script type="text/javascript" language="javascript" class="init"> $(document).ready(function() { $('#hcAllScores').DataTable( { scrollCollapse: true, scrollY: "400px", responsive: true, lengthChange: false, bPaginate: false, searching: true, jQueryUI: true, /*ordering: false,*/ "aaSorting": [], buttons: true }); var tEX = $('#hcAllScores').DataTable(); tEX.buttons().container().insertBefore('#hcAllScores_filter'); }); $('#hcAllScores').dataTable().columnFilter({ aoColumns:[ null, { type: "select", values: [<?php foreach($pdo->query($list_spec) as $listSpec) {echo "'".$listSpec['specialist']."',"; }; ?>] }, {sSelector: "#teamFilter", type: "select", values: [<?php foreach($pdo->query($listTeamSql) as $listTeam) {echo "'".$listTeam['team']."',"; }; ?>] }, null, null, null, null, null, null, null, ]} ); </script> <table id="hcAllScores" class="compact display" cellspacing="0" width="100%"> <thead> <tr> <th>Client Name</th> <th>Specialist</th> <th>Team</th> <th><img src="images/icons/medal_gold_1.png" height="16" width="16"> Overall</th> <th><img src="images/icons/shield.png" height="16" width="16"> AV</th> <th><img src="images/icons/drive_magnify.png" height="16" width="16"> DSK</th> <th><img src="images/icons/status_busy.png" height="16" width="16"> INT</th> <th><img src="images/icons/chart_curve.png" height="16" width="16"> USB</th> <th><img src="images/icons/cog.png" height="16" width="16"> SRV</th> <th><img src="images/icons/package.png" height="16" width="16"> UPD</th> <th><img src="images/icons/chart_bar_error.png" height="16" width="16"> EVT</th> </tr> </thead> <tfoot> <tr> <th>Client Name</th> <th>Specialist</th> <th>Team</th> <th>Overall</th> <th>AV</th> <th>DSK</th> <th>INT</th> <th>USB</th> <th>SRV</th> <th>UPD</th> <th>EVT</th> </tr> </tfoot> <tbody> <?php foreach($pdo->query($sql) as $row) { echo "<tr> <td><a href='clients.php?clientid=".$row['clientid']."'>".$row['Client Name']."</td> <td style='text-align:left;'>".$row['Client Specialist']."</td> <td style='text-align:left;'>".$row['Team Assignment']."</td> <td style='text-align:center;'>".$row['Overall Score']."</td> <td style='text-align:center;'>".$row['Antivirus']."</td> <td style='text-align:center;'>".$row['Disk']."</td> <td style='text-align:center;'>".$row['Intrusion']."</td> <td style='text-align:center;'>".$row['Usability']."</td> <td style='text-align:center;'>".$row['Services']."</td> <td style='text-align:center;'>".$row['Updates']."</td> <td style='text-align:center;'>".$row['Events']."</td> </tr>"; }; ?> </tbody> </table>
package org.apache.curator.framework.schema; import com.google.common.base.Objects; import com.google.common.collect.ImmutableList; import org.apache.zookeeper.data.ACL; import java.util.Arrays; import java.util.List; /** * Thrown by the various <code>validation</code> methods in a Schema */ public class SchemaViolation extends RuntimeException { private final Schema schema; private final String violation; private final ViolatorData violatorData; /** * Data about the calling API that violated the schema */ public static class ViolatorData { private final String path; private final byte[] data; private final List<ACL> acl; public ViolatorData(String path, byte[] data, List<ACL> acl) { this.path = path; this.data = (data != null) ? Arrays.copyOf(data, data.length) : null; this.acl = (acl != null) ? ImmutableList.copyOf(acl) : null; } /** * The path used in the API or <code>null</code> * * @return path or null */ public String getPath() { return path; } /** * The data used in the API or <code>null</code> * * @return data or null */ public byte[] getData() { return data; } /** * The ACLs used in the API or <code>null</code> * * @return ACLs or null */ public List<ACL> getAcl() { return acl; } @Override public String toString() { String dataString = (data != null) ? new String(data) : ""; return "ViolatorData{" + "path='" + path + '\'' + ", data=" + dataString + ", acl=" + acl + '}'; } } /** * @param violation the violation * @deprecated use {@link #SchemaViolation(Schema, ViolatorData, String)} instance */ public SchemaViolation(String violation) { super(String.format("Schema violation: %s", violation)); this.schema = null; this.violation = violation; this.violatorData = new ViolatorData(null, null, null); } /** * @param schema the schema * @param violation the violation * @deprecated use {@link #SchemaViolation(Schema, ViolatorData, String)} instance */ public SchemaViolation(Schema schema, String violation) { super(String.format("Schema violation: %s for schema: %s", violation, schema)); this.schema = schema; this.violation = violation; this.violatorData = new ViolatorData(null, null, null); } /** * @param schema the schema * @param violatorData data about the caller who violated the schema * @param violation the violation */ public SchemaViolation(Schema schema, ViolatorData violatorData, String violation) { super(toString(schema, violation, violatorData)); this.schema = schema; this.violation = violation; this.violatorData = violatorData; } public Schema getSchema() { return schema; } public String getViolation() { return violation; } public ViolatorData getViolatorData() { return violatorData; } @Override public String toString() { return toString(schema, violation, violatorData) + super.toString(); } private static String toString(Schema schema, String violation, ViolatorData violatorData) { return Objects.firstNonNull(violation, "") + " " + schema + " " + violatorData; } }
@interface STPBankAccount () @property (nonatomic, readwrite) NSString *bankAccountId; @property (nonatomic, readwrite) NSString *last4; @property (nonatomic, readwrite) NSString *bankName; @property (nonatomic, readwrite) NSString *fingerprint; @property (nonatomic, readwrite) NSString *currency; @property (nonatomic, readwrite) BOOL validated; @property (nonatomic, readwrite) BOOL disabled; @end @implementation STPBankAccount #pragma mark - Getters - (NSString *)last4 { if (_last4) { return _last4; } else if (self.accountNumber && self.accountNumber.length >= 4) { return [self.accountNumber substringFromIndex:(self.accountNumber.length - 4)]; } else { return nil; } } #pragma mark - Equality - (BOOL)isEqual:(STPBankAccount *)bankAccount { return [self isEqualToBankAccount:bankAccount]; } - (NSUInteger)hash { return [self.fingerprint hash]; } - (BOOL)isEqualToBankAccount:(STPBankAccount *)bankAccount { if (self == bankAccount) { return YES; } if (!bankAccount || ![bankAccount isKindOfClass:self.class]) { return NO; } return [self.accountNumber ?: @"" isEqualToString:bankAccount.accountNumber ?: @""] && [self.routingNumber ?: @"" isEqualToString:bankAccount.routingNumber ?: @""] && [self.country ?: @"" isEqualToString:bankAccount.country ?: @""] && [self.last4 ?: @"" isEqualToString:bankAccount.last4 ?: @""] && [self.bankName ?: @"" isEqualToString:bankAccount.bankName ?: @""] && [self.currency ?: @"" isEqualToString:bankAccount.currency ?: @""]; } @end @implementation STPBankAccount (PrivateMethods) - (instancetype)initWithAttributeDictionary:(NSDictionary *)attributeDictionary { self = [self init]; if (self) { // sanitize NSNull NSMutableDictionary *dictionary = [NSMutableDictionary dictionary]; [attributeDictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, __unused BOOL *stop) { if (obj != [NSNull null]) { dictionary[key] = obj; } }]; _bankAccountId = dictionary[@"id"]; _last4 = dictionary[@"last4"]; _bankName = dictionary[@"bank_name"]; _country = dictionary[@"country"]; _fingerprint = dictionary[@"fingerprint"]; _currency = dictionary[@"currency"]; _validated = [dictionary[@"validated"] boolValue]; _disabled = [dictionary[@"disabled"] boolValue]; } return self; } @end
package org.springframework.boot.test.autoconfigure.json; import java.io.IOException; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.ObjectCodec; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.SerializerProvider; import org.springframework.boot.jackson.JsonComponent; import org.springframework.boot.jackson.JsonObjectDeserializer; import org.springframework.boot.jackson.JsonObjectSerializer; /** * Example {@link JsonComponent} for use with {@link JsonTest @JsonTest} tests. * * @author Phillip Webb */ @JsonComponent public class ExampleJsonComponent { public static class Serializer extends JsonObjectSerializer<ExampleCustomObject> { @Override protected void serializeObject(ExampleCustomObject value, JsonGenerator jgen, SerializerProvider provider) throws IOException { jgen.writeStringField("value", value.toString()); } } public static class Deserializer extends JsonObjectDeserializer<ExampleCustomObject> { @Override protected ExampleCustomObject deserializeObject(JsonParser jsonParser, DeserializationContext context, ObjectCodec codec, JsonNode tree) throws IOException { return new ExampleCustomObject( nullSafeValue(tree.get("value"), String.class)); } } }
package de.mprengemann.intellij.plugin.androidicons.util; public final class TextUtils { private TextUtils() { } public static boolean isEmpty(final CharSequence s) { return s == null || s.length() == 0; } public static boolean isBlank(final CharSequence s) { if (s == null) { return true; } for (int i = 0; i < s.length(); i++) { if (Character.isWhitespace(s.charAt(i))) { continue; } return false; } return true; } }
package com.hrLDA.readdocs; import java.io.File; import java.util.List; import java.util.Vector; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import com.hrLDA.mysql.MySqlDB; import com.hrLDA.util.FileUtil; import edu.stanford.nlp.ie.AbstractSequenceClassifier; import edu.stanford.nlp.ie.crf.CRFClassifier; import edu.stanford.nlp.ling.CoreLabel; public class ConvertDocs{ private AbstractSequenceClassifier<CoreLabel> classifier; private String serializedClassifierPath = "classifiers"+File.separator+ "english.muc.7class.distsim.crf.ser.gz"; private MySqlDB mySqlDB; private String fileExtension; private int numOfThreads; public ConvertDocs (String databaseName, String username, String password, String fileTableName, String relationTableName, String fileExtension, int numOfThreads){ this.mySqlDB= new MySqlDB(databaseName,username,password,fileTableName, relationTableName); this.mySqlDB.createTable(); this.mySqlDB.createRelationTable(); this.fileExtension = fileExtension; this.numOfThreads =numOfThreads; }// end of ConvertDocs (...) /** * concert documents with different extensions to .txt format files * @param corpusDir * @throws Exception */ public void Convert(String corpusDir)throws Exception{ String tempfolderPathString=".."+File.separator+"temp"+File.separator; // invoke function from com.xiaofeng.FileUtil FileUtil.createTempFolder(tempfolderPathString); System.out.println("tempfolderPathString is "+tempfolderPathString); boolean moveOn = FileUtil.checkClassifierFile(); if (!moveOn) System.exit(2); // record total number of qualified documents int totalCounts =0; ///////////////////////////////////////////////////////////////////// try{ classifier = CRFClassifier.getClassifier(this.serializedClassifierPath); FileList fileList = new FileList(fileExtension); FileReaderRunnable[] runnables = new FileReaderRunnable[numOfThreads]; if (numOfThreads > 1) { fileList.getFileList(corpusDir); Vector<String> complexResult = fileList.getComplexFileVector(); int thread =0; if (complexResult.size() >0){ runnables[0] = new FileReaderRunnable( complexResult, tempfolderPathString, mySqlDB, classifier, 0); thread++; } Vector<String> result = fileList.getSimpleFileVector(); //divide result vector into different threads if (result.size() >0){ numOfThreads =2;// set to the fixed number because of NER does not allow multi-thread accesses int docsPerThread = result.size() / (numOfThreads-1); int offset = 0; for (; thread < numOfThreads; thread++) { // some docs may be missing at the end due to integer division if (thread == numOfThreads - 1) { docsPerThread = result.size() - offset; } List <String> subResultList = result.subList(offset, offset + docsPerThread); runnables[thread] = new FileReaderRunnable( subResultList, tempfolderPathString, mySqlDB, classifier, thread); offset += docsPerThread; }// end of for (; thread < numOfThreads; thread++) }else numOfThreads = 1; }else { Vector<String> result = fileList.getList(corpusDir); runnables[0] = new FileReaderRunnable( result, tempfolderPathString, mySqlDB,classifier, 0); } ExecutorService executor = Executors.newFixedThreadPool(numOfThreads); for (int thread = 0; thread < numOfThreads; thread++) { System.out.println("submitting thread " + thread); executor.submit(runnables[thread]); } try { Thread.sleep(20); } catch (InterruptedException e) { } boolean finished = false; while (! finished) { try { Thread.sleep(50); } catch (InterruptedException e) { } finished = true; // Are all the threads done? for (int thread = 0; thread < numOfThreads; thread++) { // System.out.println("thread " + thread + " done? " + runnables[thread].getIsFinished()); finished = finished && runnables[thread].getIsFinished(); } } executor.shutdown(); for (int thread = 0; thread < numOfThreads; thread++) { totalCounts += runnables[thread].getCounter(); } executor.awaitTermination(1, TimeUnit.SECONDS); System.out.println("All tasks are finished!"); System.out.println("Converting "+totalCounts+" Files in total!"); }catch(Exception e){ System.out.println("Strip failed."); System.err.println(e.getMessage()); } ///////////////////////////////////////////////////////////////////// }// end of Convert public static void main(String[] args)throws Exception{ long startTime = System.currentTimeMillis(); ConvertDocs convertDocs = new ConvertDocs("test", "root", "mysql", "tempTxtFiles", "tempSemiconductor", "txt,ppt,pptx,pdf,doc,docx", 2); convertDocs.Convert("/Users/xiaofengzhu/Documents/eclipseWorkspace/temp3"); long endTime = System.currentTimeMillis(); long totalTime = (endTime - startTime); System.out.println(totalTime); System.out.println( String.format("%d min, %d sec", TimeUnit.MILLISECONDS.toMinutes(totalTime), TimeUnit.MILLISECONDS.toSeconds(totalTime) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(totalTime)) ) ); // end of testing running time }// end of main }
[![Build Status](https://travis-ci.org/yargs/yargs-parser.png)](https://travis-ci.org/yargs/yargs-parser) [![Coverage Status](https://coveralls.io/repos/yargs/yargs-parser/badge.svg?branch=)](https://coveralls.io/r/yargs/yargs-parser?branch=master) [![NPM version](https://img.shields.io/npm/v/yargs-parser.svg)](https://www.npmjs.com/package/yargs-parser) [![Windows Tests](https://img.shields.io/appveyor/ci/bcoe/yargs-parser/master.svg?label=Windows%20Tests)](https://ci.appveyor.com/project/yargs/yargs-parser) [![Standard Version](https://img.shields.io/badge/release-standard%20version-brightgreen.svg)](https://github.com/conventional-changelog/standard-version) The mighty option parser used by [yargs](https://github.com/yargs/yargs). visit the [yargs website](http://yargs.js.org/) for more examples, and thorough usage instructions. <img width="250" src="yargs-logo.png"> ## Example ```sh npm i yargs-parser --save ``` ```js var argv = require('yargs-parser')(process.argv.slice(2)) console.log(argv) ``` ```sh node example.js --foo=33 --bar hello { _: [], foo: 33, bar: 'hello' } ``` _or parse a string!_ ```js var argv = require('./')('--foo=99 --bar=33') console.log(argv) ``` ```sh { _: [], foo: 99, bar: 33 } ``` Convert an array of mixed types before passing to `yargs-parser`: ```js var parse = require('yargs-parser') parse(['-f', 11, '--zoom', 55].join(' ')) // <-- array to string parse(['-f', 11, '--zoom', 55].map(String)) // <-- array of strings ``` ## API ### require('yargs-parser')(args, opts={}) Parses command line arguments returning a simple mapping of keys and values. **expects:** * `args`: a string or array of strings representing the options to parse. * `opts`: provide a set of hints indicating how `args` should be parsed: * `opts.alias`: an object representing the set of aliases for a key: `{alias: {foo: ['f']}}`. * `opts.array`: indicate that keys should be parsed as an array: `{array: ['foo', 'bar']}`. * `opts.boolean`: arguments should be parsed as booleans: `{boolean: ['x', 'y']}`. * `opts.config`: indicate a key that represents a path to a configuration file (this file will be loaded and parsed). * `opts.coerce`: provide a custom synchronous function that returns a coerced value from the argument provided (or throws an error), e.g. `{coerce: {foo: function (arg) {return modifiedArg}}}`. * `opts.count`: indicate a key that should be used as a counter, e.g., `-vvv` = `{v: 3}`. * `opts.default`: provide default values for keys: `{default: {x: 33, y: 'hello world!'}}`. * `opts.envPrefix`: environment variables (`process.env`) with the prefix provided should be parsed. * `opts.narg`: specify that a key requires `n` arguments: `{narg: {x: 2}}`. * `opts.normalize`: `path.normalize()` will be applied to values set to this key. * `opts.string`: keys should be treated as strings (even if they resemble a number `-x 33`). * `opts.configuration`: provide configuration options to the yargs-parser (see: [configuration](#configuration)). * `opts.number`: keys should be treated as numbers. **returns:** * `obj`: an object representing the parsed value of `args` * `key/value`: key value pairs for each argument and their aliases. * `_`: an array representing the positional arguments. ### require('yargs-parser').detailed(args, opts={}) Parses a command line string, returning detailed information required by the yargs engine. **expects:** * `args`: a string or array of strings representing options to parse. * `opts`: provide a set of hints indicating how `args`, inputs are identical to `require('yargs-parser')(args, opts={})`. **returns:** * `argv`: an object representing the parsed value of `args` * `key/value`: key value pairs for each argument and their aliases. * `_`: an array representing the positional arguments. * `error`: populated with an error object if an exception occurred during parsing. * `aliases`: the inferred list of aliases built by combining lists in `opts.alias`. * `newAliases`: any new aliases added via camel-case expansion. * `configuration`: the configuration loaded from the `yargs` stanza in package.json. <a name="configuration"></a> ### Configuration The yargs-parser applies several automated transformations on the keys provided in `args`. These features can be turned on and off using the `configuration` field of `opts`. ```js var parsed = parser(['--no-dice'], { configuration: { 'boolean-negation': false } }) ``` ### short option groups * default: `true`. * key: `short-option-groups`. Should a group of short-options be treated as boolean flags? ```sh node example.js -abc { _: [], a: true, b: true, c: true } ``` _if disabled:_ ```sh node example.js -abc { _: [], abc: true } ``` ### camel-case expansion * default: `true`. * key: `camel-case-expansion`. Should hyphenated arguments be expanded into camel-case aliases? ```sh node example.js --foo-bar { _: [], 'foo-bar': true, fooBar: true } ``` _if disabled:_ ```sh node example.js --foo-bar { _: [], 'foo-bar': true } ``` ### dot-notation * default: `true` * key: `dot-notation` Should keys that contain `.` be treated as objects? ```sh node example.js --foo.bar { _: [], foo: { bar: true } } ``` _if disabled:_ ```sh node example.js --foo.bar { _: [], "foo.bar": true } ``` ### parse numbers * default: `true` * key: 'parse-numbers' Should keys that look like numbers be treated as such? ```sh node example.js --foo=99.3 { _: [], foo: 99.3 } ``` _if disabled:_ ```sh node example.js --foo=99.3 { _: [], foo: "99.3" } ``` ### boolean negation * default: `true` * key: 'boolean-negation' Should variables prefixed with `--no` be treated as negations? ```sh node example.js --no-foo { _: [], foo: false } ``` _if disabled:_ ```sh node example.js --no-foo { _: [], "no-foo": true } ``` ## Special Thanks The yargs project evolves from optimist and minimist. It owes its existence to a lot of James Halliday's hard work. Thanks [substack](https://github.com/substack) **beep** **boop** \o/ ## License ISC
package org.elasticsearch.action.support; import org.elasticsearch.threadpool.ThreadPool; /** * */ public class PlainListenableActionFuture<T> extends AbstractListenableActionFuture<T, T> { public PlainListenableActionFuture(boolean listenerThreaded, ThreadPool threadPool) { super(listenerThreaded, threadPool); } @Override protected T convert(T response) { return response; } }
<!-- Create tabs with an icon and label, using the tabs-positive style. Each tab's child <ion-nav-view> directive will have its own navigation history that also transitions its views in and out. --> <ion-tabs class="tabs-icon-top tabs-color-active-calm"> <!-- events-board Tab --> <ion-tab title="Events" icon-off="ion-person-stalker" icon-on="ion-person-stalker" href="#/tab/events"> <ion-nav-view name="tab-events"></ion-nav-view> </ion-tab> <!-- Chats Tab --> <ion-tab title="Chats" icon-off="ion-ios-chatboxes-outline" icon-on="ion-ios-chatboxes" href="#/tab/chats"> <ion-nav-view name="tab-chats"></ion-nav-view> </ion-tab> <!-- Account Tab --> <ion-tab title="Account" icon-off="ion-ios-gear-outline" icon-on="ion-ios-gear" href="#/tab/account"> <ion-nav-view name="tab-account"></ion-nav-view> </ion-tab> </ion-tabs>
<?php /* Safe sample input : use fopen to read /tmp/tainted.txt and put the first line in $tainted sanitize : use of floatval construction : concatenation */ /*Copyright 2015 Bertrand STIVALET Permission is hereby granted, without written agreement or royalty fee, to use, copy, modify, and distribute this software and its documentation for any purpose, provided that the above copyright notice and the following three paragraphs appear in all copies of this software. IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.*/ $handle = @fopen("/tmp/tainted.txt", "r"); if ($handle) { if(($tainted = fgets($handle, 4096)) == false) { $tainted = ""; } fclose($handle); } else { $tainted = ""; } $tainted = floatval($tainted); $query = "SELECT Trim(a.FirstName) & ' ' & Trim(a.LastName) AS employee_name, a.city, a.street & (' ' +a.housenum) AS address FROM Employees AS a WHERE a.supervisor=". $tainted . ""; $conn = mysql_connect('localhost', 'mysql_user', 'mysql_password'); // Connection to the database (address, user, password) mysql_select_db('dbname') ; echo "query : ". $query ."<br /><br />" ; $res = mysql_query($query); //execution while($data =mysql_fetch_array($res)){ print_r($data) ; echo "<br />" ; } mysql_close($conn); ?>
package clientcmd import ( "fmt" "io" "io/ioutil" "os" "path" "path/filepath" goruntime "runtime" "strings" "github.com/golang/glog" "github.com/imdario/mergo" "k8s.io/kubernetes/pkg/api/unversioned" clientcmdapi "k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api" clientcmdlatest "k8s.io/kubernetes/pkg/client/unversioned/clientcmd/api/latest" "k8s.io/kubernetes/pkg/runtime" utilerrors "k8s.io/kubernetes/pkg/util/errors" "k8s.io/kubernetes/pkg/util/homedir" ) const ( RecommendedConfigPathFlag = "kubeconfig" RecommendedConfigPathEnvVar = "KUBECONFIG" RecommendedHomeDir = ".kube" RecommendedFileName = "config" RecommendedSchemaName = "schema" ) var RecommendedHomeFile = path.Join(homedir.HomeDir(), RecommendedHomeDir, RecommendedFileName) var RecommendedSchemaFile = path.Join(homedir.HomeDir(), RecommendedHomeDir, RecommendedSchemaName) // currentMigrationRules returns a map that holds the history of recommended home directories used in previous versions. // Any future changes to RecommendedHomeFile and related are expected to add a migration rule here, in order to make // sure existing config files are migrated to their new locations properly. func currentMigrationRules() map[string]string { oldRecommendedHomeFile := path.Join(os.Getenv("HOME"), "/.kube/.kubeconfig") oldRecommendedWindowsHomeFile := path.Join(os.Getenv("HOME"), RecommendedHomeDir, RecommendedFileName) migrationRules := map[string]string{} migrationRules[RecommendedHomeFile] = oldRecommendedHomeFile if goruntime.GOOS == "windows" { migrationRules[RecommendedHomeFile] = oldRecommendedWindowsHomeFile } return migrationRules } // ClientConfigLoadingRules is an ExplicitPath and string slice of specific locations that are used for merging together a Config // Callers can put the chain together however they want, but we'd recommend: // EnvVarPathFiles if set (a list of files if set) OR the HomeDirectoryPath // ExplicitPath is special, because if a user specifically requests a certain file be used and error is reported if thie file is not present type ClientConfigLoadingRules struct { ExplicitPath string Precedence []string // MigrationRules is a map of destination files to source files. If a destination file is not present, then the source file is checked. // If the source file is present, then it is copied to the destination file BEFORE any further loading happens. MigrationRules map[string]string // DoNotResolvePaths indicates whether or not to resolve paths with respect to the originating files. This is phrased as a negative so // that a default object that doesn't set this will usually get the behavior it wants. DoNotResolvePaths bool } // NewDefaultClientConfigLoadingRules returns a ClientConfigLoadingRules object with default fields filled in. You are not required to // use this constructor func NewDefaultClientConfigLoadingRules() *ClientConfigLoadingRules { chain := []string{} envVarFiles := os.Getenv(RecommendedConfigPathEnvVar) if len(envVarFiles) != 0 { chain = append(chain, filepath.SplitList(envVarFiles)...) } else { chain = append(chain, RecommendedHomeFile) } return &ClientConfigLoadingRules{ Precedence: chain, MigrationRules: currentMigrationRules(), } } // Load starts by running the MigrationRules and then // takes the loading rules and returns a Config object based on following rules. // if the ExplicitPath, return the unmerged explicit file // Otherwise, return a merged config based on the Precedence slice // A missing ExplicitPath file produces an error. Empty filenames or other missing files are ignored. // Read errors or files with non-deserializable content produce errors. // The first file to set a particular map key wins and map key's value is never changed. // BUT, if you set a struct value that is NOT contained inside of map, the value WILL be changed. // This results in some odd looking logic to merge in one direction, merge in the other, and then merge the two. // It also means that if two files specify a "red-user", only values from the first file's red-user are used. Even // non-conflicting entries from the second file's "red-user" are discarded. // Relative paths inside of the .kubeconfig files are resolved against the .kubeconfig file's parent folder // and only absolute file paths are returned. func (rules *ClientConfigLoadingRules) Load() (*clientcmdapi.Config, error) { if err := rules.Migrate(); err != nil { return nil, err } errlist := []error{} kubeConfigFiles := []string{} // Make sure a file we were explicitly told to use exists if len(rules.ExplicitPath) > 0 { if _, err := os.Stat(rules.ExplicitPath); os.IsNotExist(err) { return nil, err } kubeConfigFiles = append(kubeConfigFiles, rules.ExplicitPath) } else { kubeConfigFiles = append(kubeConfigFiles, rules.Precedence...) } kubeconfigs := []*clientcmdapi.Config{} // read and cache the config files so that we only look at them once for _, filename := range kubeConfigFiles { if len(filename) == 0 { // no work to do continue } config, err := LoadFromFile(filename) if os.IsNotExist(err) { // skip missing files continue } if err != nil { errlist = append(errlist, fmt.Errorf("Error loading config file \"%s\": %v", filename, err)) continue } kubeconfigs = append(kubeconfigs, config) } // first merge all of our maps mapConfig := clientcmdapi.NewConfig() for _, kubeconfig := range kubeconfigs { mergo.Merge(mapConfig, kubeconfig) } // merge all of the struct values in the reverse order so that priority is given correctly // errors are not added to the list the second time nonMapConfig := clientcmdapi.NewConfig() for i := len(kubeconfigs) - 1; i >= 0; i-- { kubeconfig := kubeconfigs[i] mergo.Merge(nonMapConfig, kubeconfig) } // since values are overwritten, but maps values are not, we can merge the non-map config on top of the map config and // get the values we expect. config := clientcmdapi.NewConfig() mergo.Merge(config, mapConfig) mergo.Merge(config, nonMapConfig) if rules.ResolvePaths() { if err := ResolveLocalPaths(config); err != nil { errlist = append(errlist, err) } } return config, utilerrors.NewAggregate(errlist) } // Migrate uses the MigrationRules map. If a destination file is not present, then the source file is checked. // If the source file is present, then it is copied to the destination file BEFORE any further loading happens. func (rules *ClientConfigLoadingRules) Migrate() error { if rules.MigrationRules == nil { return nil } for destination, source := range rules.MigrationRules { if _, err := os.Stat(destination); err == nil { // if the destination already exists, do nothing continue } else if !os.IsNotExist(err) { // if we had an error other than non-existence, fail return err } if sourceInfo, err := os.Stat(source); err != nil { if os.IsNotExist(err) { // if the source file doesn't exist, there's no work to do. continue } // if we had an error other than non-existence, fail return err } else if sourceInfo.IsDir() { return fmt.Errorf("cannot migrate %v to %v because it is a directory", source, destination) } in, err := os.Open(source) if err != nil { return err } defer in.Close() out, err := os.Create(destination) if err != nil { return err } defer out.Close() if _, err = io.Copy(out, in); err != nil { return err } } return nil } // GetLoadingPrecedence implements ConfigAccess func (rules *ClientConfigLoadingRules) GetLoadingPrecedence() []string { return rules.Precedence } // GetStartingConfig implements ConfigAccess func (rules *ClientConfigLoadingRules) GetStartingConfig() (*clientcmdapi.Config, error) { clientConfig := NewNonInteractiveDeferredLoadingClientConfig(rules, &ConfigOverrides{}) rawConfig, err := clientConfig.RawConfig() if os.IsNotExist(err) { return clientcmdapi.NewConfig(), nil } if err != nil { return nil, err } return &rawConfig, nil } // GetDefaultFilename implements ConfigAccess func (rules *ClientConfigLoadingRules) GetDefaultFilename() string { // Explicit file if we have one. if rules.IsExplicitFile() { return rules.GetExplicitFile() } // Otherwise, first existing file from precedence. for _, filename := range rules.GetLoadingPrecedence() { if _, err := os.Stat(filename); err == nil { return filename } } // If none exists, use the first from precedence. if len(rules.Precedence) > 0 { return rules.Precedence[0] } return "" } // IsExplicitFile implements ConfigAccess func (rules *ClientConfigLoadingRules) IsExplicitFile() bool { return len(rules.ExplicitPath) > 0 } // GetExplicitFile implements ConfigAccess func (rules *ClientConfigLoadingRules) GetExplicitFile() string { return rules.ExplicitPath } // LoadFromFile takes a filename and deserializes the contents into Config object func LoadFromFile(filename string) (*clientcmdapi.Config, error) { kubeconfigBytes, err := ioutil.ReadFile(filename) if err != nil { return nil, err } config, err := Load(kubeconfigBytes) if err != nil { return nil, err } glog.V(6).Infoln("Config loaded from file", filename) // set LocationOfOrigin on every Cluster, User, and Context for key, obj := range config.AuthInfos { obj.LocationOfOrigin = filename config.AuthInfos[key] = obj } for key, obj := range config.Clusters { obj.LocationOfOrigin = filename config.Clusters[key] = obj } for key, obj := range config.Contexts { obj.LocationOfOrigin = filename config.Contexts[key] = obj } if config.AuthInfos == nil { config.AuthInfos = map[string]*clientcmdapi.AuthInfo{} } if config.Clusters == nil { config.Clusters = map[string]*clientcmdapi.Cluster{} } if config.Contexts == nil { config.Contexts = map[string]*clientcmdapi.Context{} } return config, nil } // Load takes a byte slice and deserializes the contents into Config object. // Encapsulates deserialization without assuming the source is a file. func Load(data []byte) (*clientcmdapi.Config, error) { config := clientcmdapi.NewConfig() // if there's no data in a file, return the default object instead of failing (DecodeInto reject empty input) if len(data) == 0 { return config, nil } decoded, _, err := clientcmdlatest.Codec.Decode(data, &unversioned.GroupVersionKind{Version: clientcmdlatest.Version, Kind: "Config"}, config) if err != nil { return nil, err } return decoded.(*clientcmdapi.Config), nil } // WriteToFile serializes the config to yaml and writes it out to a file. If not present, it creates the file with the mode 0600. If it is present // it stomps the contents func WriteToFile(config clientcmdapi.Config, filename string) error { content, err := Write(config) if err != nil { return err } dir := filepath.Dir(filename) if _, err := os.Stat(dir); os.IsNotExist(err) { if err = os.MkdirAll(dir, 0755); err != nil { return err } } if err := ioutil.WriteFile(filename, content, 0600); err != nil { return err } return nil } // Write serializes the config to yaml. // Encapsulates serialization without assuming the destination is a file. func Write(config clientcmdapi.Config) ([]byte, error) { return runtime.Encode(clientcmdlatest.Codec, &config) } func (rules ClientConfigLoadingRules) ResolvePaths() bool { return !rules.DoNotResolvePaths } // ResolveLocalPaths resolves all relative paths in the config object with respect to the stanza's LocationOfOrigin // this cannot be done directly inside of LoadFromFile because doing so there would make it impossible to load a file without // modification of its contents. func ResolveLocalPaths(config *clientcmdapi.Config) error { for _, cluster := range config.Clusters { if len(cluster.LocationOfOrigin) == 0 { continue } base, err := filepath.Abs(filepath.Dir(cluster.LocationOfOrigin)) if err != nil { return fmt.Errorf("Could not determine the absolute path of config file %s: %v", cluster.LocationOfOrigin, err) } if err := ResolvePaths(GetClusterFileReferences(cluster), base); err != nil { return err } } for _, authInfo := range config.AuthInfos { if len(authInfo.LocationOfOrigin) == 0 { continue } base, err := filepath.Abs(filepath.Dir(authInfo.LocationOfOrigin)) if err != nil { return fmt.Errorf("Could not determine the absolute path of config file %s: %v", authInfo.LocationOfOrigin, err) } if err := ResolvePaths(GetAuthInfoFileReferences(authInfo), base); err != nil { return err } } return nil } // RelativizeClusterLocalPaths first absolutizes the paths by calling ResolveLocalPaths. This assumes that any NEW path is already // absolute, but any existing path will be resolved relative to LocationOfOrigin func RelativizeClusterLocalPaths(cluster *clientcmdapi.Cluster) error { if len(cluster.LocationOfOrigin) == 0 { return fmt.Errorf("no location of origin for %s", cluster.Server) } base, err := filepath.Abs(filepath.Dir(cluster.LocationOfOrigin)) if err != nil { return fmt.Errorf("could not determine the absolute path of config file %s: %v", cluster.LocationOfOrigin, err) } if err := ResolvePaths(GetClusterFileReferences(cluster), base); err != nil { return err } if err := RelativizePathWithNoBacksteps(GetClusterFileReferences(cluster), base); err != nil { return err } return nil } // RelativizeAuthInfoLocalPaths first absolutizes the paths by calling ResolveLocalPaths. This assumes that any NEW path is already // absolute, but any existing path will be resolved relative to LocationOfOrigin func RelativizeAuthInfoLocalPaths(authInfo *clientcmdapi.AuthInfo) error { if len(authInfo.LocationOfOrigin) == 0 { return fmt.Errorf("no location of origin for %v", authInfo) } base, err := filepath.Abs(filepath.Dir(authInfo.LocationOfOrigin)) if err != nil { return fmt.Errorf("could not determine the absolute path of config file %s: %v", authInfo.LocationOfOrigin, err) } if err := ResolvePaths(GetAuthInfoFileReferences(authInfo), base); err != nil { return err } if err := RelativizePathWithNoBacksteps(GetAuthInfoFileReferences(authInfo), base); err != nil { return err } return nil } func RelativizeConfigPaths(config *clientcmdapi.Config, base string) error { return RelativizePathWithNoBacksteps(GetConfigFileReferences(config), base) } func ResolveConfigPaths(config *clientcmdapi.Config, base string) error { return ResolvePaths(GetConfigFileReferences(config), base) } func GetConfigFileReferences(config *clientcmdapi.Config) []*string { refs := []*string{} for _, cluster := range config.Clusters { refs = append(refs, GetClusterFileReferences(cluster)...) } for _, authInfo := range config.AuthInfos { refs = append(refs, GetAuthInfoFileReferences(authInfo)...) } return refs } func GetClusterFileReferences(cluster *clientcmdapi.Cluster) []*string { return []*string{&cluster.CertificateAuthority} } func GetAuthInfoFileReferences(authInfo *clientcmdapi.AuthInfo) []*string { return []*string{&authInfo.ClientCertificate, &authInfo.ClientKey} } // ResolvePaths updates the given refs to be absolute paths, relative to the given base directory func ResolvePaths(refs []*string, base string) error { for _, ref := range refs { // Don't resolve empty paths if len(*ref) > 0 { // Don't resolve absolute paths if !filepath.IsAbs(*ref) { *ref = filepath.Join(base, *ref) } } } return nil } // RelativizePathWithNoBacksteps updates the given refs to be relative paths, relative to the given base directory as long as they do not require backsteps. // Any path requiring a backstep is left as-is as long it is absolute. Any non-absolute path that can't be relativized produces an error func RelativizePathWithNoBacksteps(refs []*string, base string) error { for _, ref := range refs { // Don't relativize empty paths if len(*ref) > 0 { rel, err := MakeRelative(*ref, base) if err != nil { return err } // if we have a backstep, don't mess with the path if strings.HasPrefix(rel, "../") { if filepath.IsAbs(*ref) { continue } return fmt.Errorf("%v requires backsteps and is not absolute", *ref) } *ref = rel } } return nil } func MakeRelative(path, base string) (string, error) { if len(path) > 0 { rel, err := filepath.Rel(base, path) if err != nil { return path, err } return rel, nil } return path, nil }
require "cases/helper" class PostgresqlRenameTableTest < ActiveRecord::TestCase def setup @connection = ActiveRecord::Base.connection @connection.create_table :before_rename, force: true end def teardown @connection.execute 'DROP TABLE IF EXISTS "before_rename"' @connection.execute 'DROP TABLE IF EXISTS "after_rename"' end test "renaming a table also renames the primary key index" do # sanity check assert_equal 1, num_indices_named("before_rename_pkey") assert_equal 0, num_indices_named("after_rename_pkey") @connection.rename_table :before_rename, :after_rename assert_equal 0, num_indices_named("before_rename_pkey") assert_equal 1, num_indices_named("after_rename_pkey") end private def num_indices_named(name) @connection.execute(<<-SQL).values.length SELECT 1 FROM "pg_index" JOIN "pg_class" ON "pg_index"."indexrelid" = "pg_class"."oid" WHERE "pg_class"."relname" = '#{name}' SQL end end
package org.apache.camel.maven; import java.util.Iterator; import javax.xml.namespace.NamespaceContext; /** * Default namespace for xsd schema. */ public class CamelSpringNamespace implements NamespaceContext { @Override public String getNamespaceURI(String prefix) { if (prefix == null) { throw new IllegalArgumentException("The prefix cannot be null."); } if (Constants.XML_SCHEMA_NAMESPACE_PREFIX.equals(prefix)) { return Constants.XML_SCHEMA_NAMESPACE_URI; } return null; } @Override public String getPrefix(String namespaceURI) { throw new UnsupportedOperationException("Operation not supported"); } @Override public Iterator getPrefixes(String namespaceURI) { throw new UnsupportedOperationException("Operation not supported"); } }
from __future__ import unicode_literals import os from django.db import migrations from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor from django.db.migrations.state import StateApps from zerver.lib.upload import attachment_url_re, attachment_url_to_path_id def check_and_create_attachments(apps, schema_editor): # type: (StateApps, DatabaseSchemaEditor) -> None STREAM = 2 Message = apps.get_model('zerver', 'Message') Attachment = apps.get_model('zerver', 'Attachment') Stream = apps.get_model('zerver', 'Stream') for message in Message.objects.filter(has_attachment=True, attachment=None): attachment_url_list = attachment_url_re.findall(message.content) for url in attachment_url_list: path_id = attachment_url_to_path_id(url) user_profile = message.sender is_message_realm_public = False if message.recipient.type == STREAM: stream = Stream.objects.get(id=message.recipient.type_id) is_message_realm_public = not stream.invite_only and not stream.realm.is_zephyr_mirror_realm if path_id is not None: attachment = Attachment.objects.create( file_name=os.path.basename(path_id), path_id=path_id, owner=user_profile, realm=user_profile.realm, is_realm_public=is_message_realm_public) attachment.messages.add(message) class Migration(migrations.Migration): dependencies = [ ('zerver', '0040_realm_authentication_methods'), ] operations = [ migrations.RunPython(check_and_create_attachments) ]
package io.netty.buffer; import io.netty.util.ByteProcessor; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.channels.GatheringByteChannel; import java.nio.channels.ScatteringByteChannel; import java.nio.charset.Charset; /** * Wrapper which swap the {@link ByteOrder} of a {@link ByteBuf}. */ public class SwappedByteBuf extends ByteBuf { private final ByteBuf buf; private final ByteOrder order; public SwappedByteBuf(ByteBuf buf) { if (buf == null) { throw new NullPointerException("buf"); } this.buf = buf; if (buf.order() == ByteOrder.BIG_ENDIAN) { order = ByteOrder.LITTLE_ENDIAN; } else { order = ByteOrder.BIG_ENDIAN; } } @Override public ByteOrder order() { return order; } @Override public ByteBuf order(ByteOrder endianness) { if (endianness == null) { throw new NullPointerException("endianness"); } if (endianness == order) { return this; } return buf; } @Override public ByteBuf unwrap() { return buf.unwrap(); } @Override public ByteBufAllocator alloc() { return buf.alloc(); } @Override public int capacity() { return buf.capacity(); } @Override public ByteBuf capacity(int newCapacity) { buf.capacity(newCapacity); return this; } @Override public int maxCapacity() { return buf.maxCapacity(); } @Override public boolean isDirect() { return buf.isDirect(); } @Override public int readerIndex() { return buf.readerIndex(); } @Override public ByteBuf readerIndex(int readerIndex) { buf.readerIndex(readerIndex); return this; } @Override public int writerIndex() { return buf.writerIndex(); } @Override public ByteBuf writerIndex(int writerIndex) { buf.writerIndex(writerIndex); return this; } @Override public ByteBuf setIndex(int readerIndex, int writerIndex) { buf.setIndex(readerIndex, writerIndex); return this; } @Override public int readableBytes() { return buf.readableBytes(); } @Override public int writableBytes() { return buf.writableBytes(); } @Override public int maxWritableBytes() { return buf.maxWritableBytes(); } @Override public boolean isReadable() { return buf.isReadable(); } @Override public boolean isReadable(int size) { return buf.isReadable(size); } @Override public boolean isWritable() { return buf.isWritable(); } @Override public boolean isWritable(int size) { return buf.isWritable(size); } @Override public ByteBuf clear() { buf.clear(); return this; } @Override public ByteBuf markReaderIndex() { buf.markReaderIndex(); return this; } @Override public ByteBuf resetReaderIndex() { buf.resetReaderIndex(); return this; } @Override public ByteBuf markWriterIndex() { buf.markWriterIndex(); return this; } @Override public ByteBuf resetWriterIndex() { buf.resetWriterIndex(); return this; } @Override public ByteBuf discardReadBytes() { buf.discardReadBytes(); return this; } @Override public ByteBuf discardSomeReadBytes() { buf.discardSomeReadBytes(); return this; } @Override public ByteBuf ensureWritable(int writableBytes) { buf.ensureWritable(writableBytes); return this; } @Override public int ensureWritable(int minWritableBytes, boolean force) { return buf.ensureWritable(minWritableBytes, force); } @Override public boolean getBoolean(int index) { return buf.getBoolean(index); } @Override public byte getByte(int index) { return buf.getByte(index); } @Override public short getUnsignedByte(int index) { return buf.getUnsignedByte(index); } @Override public short getShort(int index) { return ByteBufUtil.swapShort(buf.getShort(index)); } @Override public int getUnsignedShort(int index) { return getShort(index) & 0xFFFF; } @Override public int getMedium(int index) { return ByteBufUtil.swapMedium(buf.getMedium(index)); } @Override public int getUnsignedMedium(int index) { return getMedium(index) & 0xFFFFFF; } @Override public int getInt(int index) { return ByteBufUtil.swapInt(buf.getInt(index)); } @Override public long getUnsignedInt(int index) { return getInt(index) & 0xFFFFFFFFL; } @Override public long getLong(int index) { return ByteBufUtil.swapLong(buf.getLong(index)); } @Override public char getChar(int index) { return (char) getShort(index); } @Override public float getFloat(int index) { return Float.intBitsToFloat(getInt(index)); } @Override public double getDouble(int index) { return Double.longBitsToDouble(getLong(index)); } @Override public ByteBuf getBytes(int index, ByteBuf dst) { buf.getBytes(index, dst); return this; } @Override public ByteBuf getBytes(int index, ByteBuf dst, int length) { buf.getBytes(index, dst, length); return this; } @Override public ByteBuf getBytes(int index, ByteBuf dst, int dstIndex, int length) { buf.getBytes(index, dst, dstIndex, length); return this; } @Override public ByteBuf getBytes(int index, byte[] dst) { buf.getBytes(index, dst); return this; } @Override public ByteBuf getBytes(int index, byte[] dst, int dstIndex, int length) { buf.getBytes(index, dst, dstIndex, length); return this; } @Override public ByteBuf getBytes(int index, ByteBuffer dst) { buf.getBytes(index, dst); return this; } @Override public ByteBuf getBytes(int index, OutputStream out, int length) throws IOException { buf.getBytes(index, out, length); return this; } @Override public int getBytes(int index, GatheringByteChannel out, int length) throws IOException { return buf.getBytes(index, out, length); } @Override public ByteBuf setBoolean(int index, boolean value) { buf.setBoolean(index, value); return this; } @Override public ByteBuf setByte(int index, int value) { buf.setByte(index, value); return this; } @Override public ByteBuf setShort(int index, int value) { buf.setShort(index, ByteBufUtil.swapShort((short) value)); return this; } @Override public ByteBuf setMedium(int index, int value) { buf.setMedium(index, ByteBufUtil.swapMedium(value)); return this; } @Override public ByteBuf setInt(int index, int value) { buf.setInt(index, ByteBufUtil.swapInt(value)); return this; } @Override public ByteBuf setLong(int index, long value) { buf.setLong(index, ByteBufUtil.swapLong(value)); return this; } @Override public ByteBuf setChar(int index, int value) { setShort(index, value); return this; } @Override public ByteBuf setFloat(int index, float value) { setInt(index, Float.floatToRawIntBits(value)); return this; } @Override public ByteBuf setDouble(int index, double value) { setLong(index, Double.doubleToRawLongBits(value)); return this; } @Override public ByteBuf setBytes(int index, ByteBuf src) { buf.setBytes(index, src); return this; } @Override public ByteBuf setBytes(int index, ByteBuf src, int length) { buf.setBytes(index, src, length); return this; } @Override public ByteBuf setBytes(int index, ByteBuf src, int srcIndex, int length) { buf.setBytes(index, src, srcIndex, length); return this; } @Override public ByteBuf setBytes(int index, byte[] src) { buf.setBytes(index, src); return this; } @Override public ByteBuf setBytes(int index, byte[] src, int srcIndex, int length) { buf.setBytes(index, src, srcIndex, length); return this; } @Override public ByteBuf setBytes(int index, ByteBuffer src) { buf.setBytes(index, src); return this; } @Override public int setBytes(int index, InputStream in, int length) throws IOException { return buf.setBytes(index, in, length); } @Override public int setBytes(int index, ScatteringByteChannel in, int length) throws IOException { return buf.setBytes(index, in, length); } @Override public ByteBuf setZero(int index, int length) { buf.setZero(index, length); return this; } @Override public boolean readBoolean() { return buf.readBoolean(); } @Override public byte readByte() { return buf.readByte(); } @Override public short readUnsignedByte() { return buf.readUnsignedByte(); } @Override public short readShort() { return ByteBufUtil.swapShort(buf.readShort()); } @Override public int readUnsignedShort() { return readShort() & 0xFFFF; } @Override public int readMedium() { return ByteBufUtil.swapMedium(buf.readMedium()); } @Override public int readUnsignedMedium() { return readMedium() & 0xFFFFFF; } @Override public int readInt() { return ByteBufUtil.swapInt(buf.readInt()); } @Override public long readUnsignedInt() { return readInt() & 0xFFFFFFFFL; } @Override public long readLong() { return ByteBufUtil.swapLong(buf.readLong()); } @Override public char readChar() { return (char) readShort(); } @Override public float readFloat() { return Float.intBitsToFloat(readInt()); } @Override public double readDouble() { return Double.longBitsToDouble(readLong()); } @Override public ByteBuf readBytes(int length) { return buf.readBytes(length).order(order()); } @Override public ByteBuf readSlice(int length) { return buf.readSlice(length).order(order); } @Override public ByteBuf readBytes(ByteBuf dst) { buf.readBytes(dst); return this; } @Override public ByteBuf readBytes(ByteBuf dst, int length) { buf.readBytes(dst, length); return this; } @Override public ByteBuf readBytes(ByteBuf dst, int dstIndex, int length) { buf.readBytes(dst, dstIndex, length); return this; } @Override public ByteBuf readBytes(byte[] dst) { buf.readBytes(dst); return this; } @Override public ByteBuf readBytes(byte[] dst, int dstIndex, int length) { buf.readBytes(dst, dstIndex, length); return this; } @Override public ByteBuf readBytes(ByteBuffer dst) { buf.readBytes(dst); return this; } @Override public ByteBuf readBytes(OutputStream out, int length) throws IOException { buf.readBytes(out, length); return this; } @Override public int readBytes(GatheringByteChannel out, int length) throws IOException { return buf.readBytes(out, length); } @Override public ByteBuf skipBytes(int length) { buf.skipBytes(length); return this; } @Override public ByteBuf writeBoolean(boolean value) { buf.writeBoolean(value); return this; } @Override public ByteBuf writeByte(int value) { buf.writeByte(value); return this; } @Override public ByteBuf writeShort(int value) { buf.writeShort(ByteBufUtil.swapShort((short) value)); return this; } @Override public ByteBuf writeMedium(int value) { buf.writeMedium(ByteBufUtil.swapMedium(value)); return this; } @Override public ByteBuf writeInt(int value) { buf.writeInt(ByteBufUtil.swapInt(value)); return this; } @Override public ByteBuf writeLong(long value) { buf.writeLong(ByteBufUtil.swapLong(value)); return this; } @Override public ByteBuf writeChar(int value) { writeShort(value); return this; } @Override public ByteBuf writeFloat(float value) { writeInt(Float.floatToRawIntBits(value)); return this; } @Override public ByteBuf writeDouble(double value) { writeLong(Double.doubleToRawLongBits(value)); return this; } @Override public ByteBuf writeBytes(ByteBuf src) { buf.writeBytes(src); return this; } @Override public ByteBuf writeBytes(ByteBuf src, int length) { buf.writeBytes(src, length); return this; } @Override public ByteBuf writeBytes(ByteBuf src, int srcIndex, int length) { buf.writeBytes(src, srcIndex, length); return this; } @Override public ByteBuf writeBytes(byte[] src) { buf.writeBytes(src); return this; } @Override public ByteBuf writeBytes(byte[] src, int srcIndex, int length) { buf.writeBytes(src, srcIndex, length); return this; } @Override public ByteBuf writeBytes(ByteBuffer src) { buf.writeBytes(src); return this; } @Override public int writeBytes(InputStream in, int length) throws IOException { return buf.writeBytes(in, length); } @Override public int writeBytes(ScatteringByteChannel in, int length) throws IOException { return buf.writeBytes(in, length); } @Override public ByteBuf writeZero(int length) { buf.writeZero(length); return this; } @Override public int indexOf(int fromIndex, int toIndex, byte value) { return buf.indexOf(fromIndex, toIndex, value); } @Override public int bytesBefore(byte value) { return buf.bytesBefore(value); } @Override public int bytesBefore(int length, byte value) { return buf.bytesBefore(length, value); } @Override public int bytesBefore(int index, int length, byte value) { return buf.bytesBefore(index, length, value); } @Override public int forEachByte(ByteProcessor processor) { return buf.forEachByte(processor); } @Override public int forEachByte(int index, int length, ByteProcessor processor) { return buf.forEachByte(index, length, processor); } @Override public int forEachByteDesc(ByteProcessor processor) { return buf.forEachByteDesc(processor); } @Override public int forEachByteDesc(int index, int length, ByteProcessor processor) { return buf.forEachByteDesc(index, length, processor); } @Override public ByteBuf copy() { return buf.copy().order(order); } @Override public ByteBuf copy(int index, int length) { return buf.copy(index, length).order(order); } @Override public ByteBuf slice() { return buf.slice().order(order); } @Override public ByteBuf slice(int index, int length) { return buf.slice(index, length).order(order); } @Override public ByteBuf duplicate() { return buf.duplicate().order(order); } @Override public int nioBufferCount() { return buf.nioBufferCount(); } @Override public ByteBuffer nioBuffer() { return buf.nioBuffer().order(order); } @Override public ByteBuffer nioBuffer(int index, int length) { return buf.nioBuffer(index, length).order(order); } @Override public ByteBuffer internalNioBuffer(int index, int length) { return nioBuffer(index, length); } @Override public ByteBuffer[] nioBuffers() { ByteBuffer[] nioBuffers = buf.nioBuffers(); for (int i = 0; i < nioBuffers.length; i++) { nioBuffers[i] = nioBuffers[i].order(order); } return nioBuffers; } @Override public ByteBuffer[] nioBuffers(int index, int length) { ByteBuffer[] nioBuffers = buf.nioBuffers(index, length); for (int i = 0; i < nioBuffers.length; i++) { nioBuffers[i] = nioBuffers[i].order(order); } return nioBuffers; } @Override public boolean hasArray() { return buf.hasArray(); } @Override public byte[] array() { return buf.array(); } @Override public int arrayOffset() { return buf.arrayOffset(); } @Override public boolean hasMemoryAddress() { return buf.hasMemoryAddress(); } @Override public long memoryAddress() { return buf.memoryAddress(); } @Override public String toString(Charset charset) { return buf.toString(charset); } @Override public String toString(int index, int length, Charset charset) { return buf.toString(index, length, charset); } @Override public int refCnt() { return buf.refCnt(); } @Override public ByteBuf retain() { buf.retain(); return this; } @Override public ByteBuf retain(int increment) { buf.retain(increment); return this; } @Override public ByteBuf touch() { buf.touch(); return this; } @Override public ByteBuf touch(Object hint) { buf.touch(hint); return this; } @Override public boolean release() { return buf.release(); } @Override public boolean release(int decrement) { return buf.release(decrement); } @Override public int hashCode() { return buf.hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof ByteBuf) { return ByteBufUtil.equals(this, (ByteBuf) obj); } return false; } @Override public int compareTo(ByteBuf buffer) { return ByteBufUtil.compare(this, buffer); } @Override public String toString() { return "Swapped(" + buf + ')'; } }
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chromeos/dbus/blocking_method_caller.h" #include "base/bind.h" #include "base/location.h" #include "base/threading/thread_restrictions.h" #include "dbus/bus.h" #include "dbus/object_proxy.h" namespace chromeos { namespace { // This function is a part of CallMethodAndBlock implementation. void CallMethodAndBlockInternal( scoped_ptr<dbus::Response>* response, base::ScopedClosureRunner* signaler, dbus::ObjectProxy* proxy, dbus::MethodCall* method_call) { *response = proxy->CallMethodAndBlock( method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT); } } // namespace BlockingMethodCaller::BlockingMethodCaller(dbus::Bus* bus, dbus::ObjectProxy* proxy) : bus_(bus), proxy_(proxy), on_blocking_method_call_(false /* manual_reset */, false /* initially_signaled */) { } BlockingMethodCaller::~BlockingMethodCaller() { } scoped_ptr<dbus::Response> BlockingMethodCaller::CallMethodAndBlock( dbus::MethodCall* method_call) { // on_blocking_method_call_->Signal() will be called when |signaler| is // destroyed. base::Closure signal_task( base::Bind(&base::WaitableEvent::Signal, base::Unretained(&on_blocking_method_call_))); base::ScopedClosureRunner* signaler = new base::ScopedClosureRunner(signal_task); scoped_ptr<dbus::Response> response; bus_->PostTaskToDBusThread( FROM_HERE, base::Bind(&CallMethodAndBlockInternal, &response, base::Owned(signaler), base::Unretained(proxy_), method_call)); // http://crbug.com/125360 base::ThreadRestrictions::ScopedAllowWait allow_wait; on_blocking_method_call_.Wait(); return response.Pass(); } } // namespace chromeos
package net.community.chest.net; public interface NetConnectionEmbedder<C extends NetConnection> { /** * @return currently embedded connection - may be null if none set or * the embedder has been closed (e.g., some I/O stream reader/writer) */ C getConnection (); void setConnection (C conn); }
function t = figurefun(func, A, varargin) % figurefun(FUN, A, 'param1', val1, ...) % Simulate user interactions with figures such as inputdlg, msgbox, etc. by % evaluating FUN for graphic objects found with A. % % Inputs: % FUN - cell array of functions to call (default is empty, callback of props object) % A - cell array of type, value pairs in order to find figure and % object (such as a button) as used with findobj. Alternatively, A can be a % string (default is {'type','figure'}). % options - timer options to be used as pairs of parameter name and value % (defualts are 'tag', mfilename, 'ExecutionMode', 'fixedSpacing', % 'TimerFcn', @(x,y)wait_fig(x, A, FUN), 'TasksToExecute', 10000). % see timer for more information % % Outputs: % t - timer object for stopping/deleting timer if necessary % % Example 1: set inputdlg text to "test" and simulate OK press % figurefun(@(x,y)set(y,'string','test'),{'string',''}); % figurefun('set(h,''UserData'',''OK''); uiresume(h);',{'string','OK'}); % txt = inputdlg % % txt = % % 'test' % % Example 2: take control of a questdlg to rename title, question, button, % and answer returned when button is pressed % figurefun(@(x,y)set(x,'name','Title'),{'type','figure'}); % figurefun({@(x,y)set(y,'string','Button'),@(x,y)setappdata(y,'QuestDlgReturnName','Answer')},... % {'style','pushbutton','string','bla'}); % figurefun(@(x,y)set(y,'string','Text'),{'string','bla'}); % txt = questdlg('bla','bla','bla','bla') % % txt = % % Answer % % Example 3: Close inputdlg (using gcf) after 3 second delay % figurefun('uiresume(h);', 'gcf', 'StartDelay', 3); % txt = inputdlg % % txt = % % {} % % Note: If FUN is a function handle, the inputs should be the figure and % object returned from props (i.e., @(x,y) x is figure and y is object). % If FUN is a string, h or hh can be included to be evaluated. Also, if a % figure requires more time before the function should be evaluated, set % 'StartDelay' to some number greater than 0. % % Created by Justin Theiss % init vars if ~exist('func','var') || isempty(func), func = []; end; if ~exist('A','var') || isempty(A), A = {'type','figure'}; end; if ~isempty(func) && ~iscell(func), func = {func}; end; % setup timer t = timer('tag',mfilename); set(t,'ExecutionMode','fixedSpacing'); set(t,'TimerFcn',@(x,y)wait_fig(x, A, func)); set(t,'TasksToExecute',10000); if ~isempty(varargin), set(t,varargin{:}); end; start(t); % wait function function wait_fig(t, props, func) % get h and hh [h, hh] = find_fig(props); % h and hh are found if ~isempty(h) && ~isempty(hh), % evaluate function try eval_fig(h, hh, func); catch err disp(err.message); end; % stop timer stop_timer(t); end end function [h, hh] = find_fig(props) % set showhiddenhandles on shh = get(0,'ShowHiddenHandles'); set(0,'ShowHiddenHandles','on'); % init h and hh h = []; hh = []; if ischar(props), % evaluate eg 'gcbf' hh = eval(props); h = hh(strcmp(get(hh,'type'),'figure')); else % use findobj if ~iscell(props), props = {props}; end; hh = findobj(props{:}); if ~isempty(hh), % get parent of hh h = hh(1); while ~strcmp(get(h,'type'),'figure'), h = get(h,'Parent'); if h==0, break; end; end end end % reset showhiddenhandles set(0,'ShowHiddenHandles',shh); end function eval_fig(h, hh, func) % for each function for x = 1:numel(func), % if no function, get callback if isempty(func{x}), % if function handle, evaluate if isa(hh,'function_handle'), hh(h,[]); elseif ischar(hh), eval(hh); end % get callback function callbackBtn = get(hh,'Callback'); if ischar(callbackBtn), % set gcbf to h callbackBtn = strrep(callbackBtn,'gcbf','h'); eval(callbackBtn); elseif iscell(callbackBtn), % evaluate cell callback callbackBtn{1}(hh,[],callbackBtn{2:end}); else % evaluate callback function callbackBtn(hh,[]); end elseif isa(func{x},'function_handle'), % evaluate function with h feval(func{x}, h, hh); else % evaluate function eval(func{x}); end end end function stop_timer(t) % if not a timer, return if ~isa(t,'timer'), return; end; % if running, stop if strcmp(get(t,'Running'),'on'), stop(t); end; % delete timer delete(t); end end
<server> <featureManager> <feature>servlet-3.1</feature> </featureManager> <httpEndpoint id="defaultHttpEndpoint" host="*" httpPort="9080"> <tcpOptions soReuseAddr="true"/> </httpEndpoint> <application name="JavaHelloWorldApp" context-root="/JavaHelloWorldApp" location="${appLocation}" type="war"/> </server>
ChromeSyncShellMainDelegate::ChromeSyncShellMainDelegate() { } ChromeSyncShellMainDelegate::~ChromeSyncShellMainDelegate() { } int ChromeSyncShellMainDelegate::RunProcess( const std::string& process_type, const content::MainFunctionParams& main_function_params) { if (process_type.empty()) { FakeServerHelperAndroid::Register(base::android::AttachCurrentThread()); } return ChromeMainDelegateAndroid::RunProcess( process_type, main_function_params); }
<?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) FuseSource, Inc. http://fusesource.com Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <component> <dependencySets> <dependencySet> <outputDirectory>/lib</outputDirectory> <outputFileNameMapping>mq-version.jar</outputFileNameMapping> <fileMode>0644</fileMode> <includes> <include>org.jboss.amq:org.jboss.amq.karaf.branding</include> </includes> <useTransitiveDependencies>false</useTransitiveDependencies> </dependencySet> <dependencySet> <outputDirectory>/lib</outputDirectory> <outputFileNameMapping>patch-client.jar</outputFileNameMapping> <fileMode>0644</fileMode> <includes> <include>io.fabric8.patch:patch-client</include> </includes> <useTransitiveDependencies>false</useTransitiveDependencies> </dependencySet> <dependencySet> <outputDirectory>/extras</outputDirectory> <outputFileNameMapping>mq-client.jar</outputFileNameMapping> <fileMode>0644</fileMode> <includes> <include>org.jboss.amq:mq-client</include> </includes> <useTransitiveDependencies>false</useTransitiveDependencies> </dependencySet> <dependencySet> <outputDirectory>/lib/ext</outputDirectory> <outputFileNameMapping>bcprov-jdk15on.jar</outputFileNameMapping> <fileMode>0644</fileMode> <includes> <include>org.bouncycastle:bcprov-jdk15on</include> </includes> <useTransitiveDependencies>false</useTransitiveDependencies> </dependencySet> </dependencySets> <fileSets> <!-- Add licenses to the assembly --> <fileSet> <directory>target/shared/licenses</directory> <outputDirectory>/licenses/</outputDirectory> <lineEnding>unix</lineEnding> <fileMode>0644</fileMode> <directoryMode>0755</directoryMode> </fileSet> <!-- Add shared scripts --> <fileSet> <directory>target/shared/bin</directory> <outputDirectory>/bin/</outputDirectory> <lineEnding>unix</lineEnding> <fileMode>0755</fileMode> <directoryMode>0755</directoryMode> </fileSet> <!-- System repo --> <fileSet> <directory>target/features-repo</directory> <outputDirectory>/system/</outputDirectory> </fileSet> </fileSets> <files> <file> <source>${basedir}/target/META-INF/NOTICE</source> <outputDirectory>/</outputDirectory> <destName>mq_notices.txt</destName> <fileMode>0644</fileMode> <lineEnding>unix</lineEnding> </file> <file> <source>${basedir}/target/META-INF/DEPENDENCIES</source> <outputDirectory>/</outputDirectory> <destName>mq_dependencies.txt</destName> <fileMode>0644</fileMode> <lineEnding>unix</lineEnding> </file> <file> <source>${basedir}/target/dependencies/unix/apache-activemq-${activemq-version}-bin.zip</source> <outputDirectory>extras</outputDirectory> <fileMode>0644</fileMode> </file> </files> </component>
Aurora Configuration Templating =============================== The `.aurora` file format is just Python. However, `Job`, `Task`, `Process`, and other classes are defined by a templating library called *Pystachio*, a powerful tool for configuration specification and reuse. [Aurora Configuration Reference](configuration.md) has a full reference of all Aurora/Thermos defined Pystachio objects. When writing your `.aurora` file, you may use any Pystachio datatypes, as well as any objects shown in the *Aurora+Thermos Configuration Reference* without `import` statements - the Aurora config loader injects them automatically. Other than that the `.aurora` format works like any other Python script. Templating 1: Binding in Pystachio ---------------------------------- Pystachio uses the visually distinctive {{}} to indicate template variables. These are often called "mustache variables" after the similarly appearing variables in the Mustache templating system and because the curly braces resemble mustaches. If you are familiar with the Mustache system, templates in Pystachio have significant differences. They have no nesting, joining, or inheritance semantics. On the other hand, when evaluated, templates are evaluated iteratively, so this affords some level of indirection. Let's start with the simplest template; text with one variable, in this case `name`; Hello {{name}} If we evaluate this as is, we'd get back: Hello If a template variable doesn't have a value, when evaluated it's replaced with nothing. If we add a binding to give it a value: { "name" : "Tom" } We'd get back: Hello Tom Every Pystachio object has an associated `.bind` method that can bind values to {{}} variables. Bindings are not immediately evaluated. Instead, they are evaluated only when the interpolated value of the object is necessary, e.g. for performing equality or serializing a message over the wire. Objects with and without mustache templated variables behave differently: >>> Float(1.5) Float(1.5) >>> Float('{{x}}.5') Float({{x}}.5) >>> Float('{{x}}.5').bind(x = 1) Float(1.5) >>> Float('{{x}}.5').bind(x = 1) == Float(1.5) True >>> contextual_object = String('{{metavar{{number}}}}').bind( ... metavar1 = "first", metavar2 = "second") >>> contextual_object String({{metavar{{number}}}}) >>> contextual_object.bind(number = 1) String(first) >>> contextual_object.bind(number = 2) String(second) You usually bind simple key to value pairs, but you can also bind three other objects: lists, dictionaries, and structurals. These will be described in detail later. ### Structurals in Pystachio / Aurora Most Aurora/Thermos users don't ever (knowingly) interact with `String`, `Float`, or `Integer` Pystashio objects directly. Instead they interact with derived structural (`Struct`) objects that are collections of fundamental and structural objects. The structural object components are called *attributes*. Aurora's most used structural objects are `Job`, `Task`, and `Process`: class Process(Struct): cmdline = Required(String) name = Required(String) max_failures = Default(Integer, 1) daemon = Default(Boolean, False) ephemeral = Default(Boolean, False) min_duration = Default(Integer, 5) final = Default(Boolean, False) Construct default objects by following the object's type with (). If you want an attribute to have a value different from its default, include the attribute name and value inside the parentheses. >>> Process() Process(daemon=False, max_failures=1, ephemeral=False, min_duration=5, final=False) Attribute values can be template variables, which then receive specific values when creating the object. >>> Process(cmdline = 'echo {{message}}') Process(daemon=False, max_failures=1, ephemeral=False, min_duration=5, cmdline=echo {{message}}, final=False) >>> Process(cmdline = 'echo {{message}}').bind(message = 'hello world') Process(daemon=False, max_failures=1, ephemeral=False, min_duration=5, cmdline=echo hello world, final=False) A powerful binding property is that all of an object's children inherit its bindings: >>> List(Process)([ ... Process(name = '{{prefix}}_one'), ... Process(name = '{{prefix}}_two') ... ]).bind(prefix = 'hello') ProcessList( Process(daemon=False, name=hello_one, max_failures=1, ephemeral=False, min_duration=5, final=False), Process(daemon=False, name=hello_two, max_failures=1, ephemeral=False, min_duration=5, final=False) ) Remember that an Aurora Job contains Tasks which contain Processes. A Job level binding is inherited by its Tasks and all their Processes. Similarly a Task level binding is available to that Task and its Processes but is *not* visible at the Job level (inheritance is a one-way street.) #### Mustaches Within Structurals When you define a `Struct` schema, one powerful, but confusing, feature is that all of that structure's attributes are Mustache variables within the enclosing scope *once they have been populated*. For example, when `Process` is defined above, all its attributes such as {{`name`}}, {{`cmdline`}}, {{`max_failures`}} etc., are all immediately defined as Mustache variables, implicitly bound into the `Process`, and inherit all child objects once they are defined. Thus, you can do the following: >>> Process(name = "installer", cmdline = "echo {{name}} is running") Process(daemon=False, name=installer, max_failures=1, ephemeral=False, min_duration=5, cmdline=echo installer is running, final=False) WARNING: This binding only takes place in one direction. For example, the following does NOT work and does not set the `Process` `name` attribute's value. >>> Process().bind(name = "installer") Process(daemon=False, max_failures=1, ephemeral=False, min_duration=5, final=False) The following is also not possible and results in an infinite loop that attempts to resolve `Process.name`. >>> Process(name = '{{name}}').bind(name = 'installer') Do not confuse Structural attributes with bound Mustache variables. Attributes are implicitly converted to Mustache variables but not vice versa. ### Templating 2: Structurals Are Factories #### A Second Way of Templating A second templating method is both as powerful as the aforementioned and often confused with it. This method is due to automatic conversion of Struct attributes to Mustache variables as described above. Suppose you create a Process object: >>> p = Process(name = "process_one", cmdline = "echo hello world") >>> p Process(daemon=False, name=process_one, max_failures=1, ephemeral=False, min_duration=5, cmdline=echo hello world, final=False) This `Process` object, "`p`", can be used wherever a `Process` object is needed. It can also be reused by changing the value(s) of its attribute(s). Here we change its `name` attribute from `process_one` to `process_two`. >>> p(name = "process_two") Process(daemon=False, name=process_two, max_failures=1, ephemeral=False, min_duration=5, cmdline=echo hello world, final=False) Template creation is a common use for this technique: >>> Daemon = Process(daemon = True) >>> logrotate = Daemon(name = 'logrotate', cmdline = './logrotate conf/logrotate.conf') >>> mysql = Daemon(name = 'mysql', cmdline = 'bin/mysqld --safe-mode') ### Advanced Binding As described above, `.bind()` binds simple strings or numbers to Mustache variables. In addition to Structural types formed by combining atomic types, Pystachio has two container types; `List` and `Map` which can also be bound via `.bind()`. #### Bind Syntax The `bind()` function can take Python dictionaries or `kwargs` interchangeably (when "`kwargs`" is in a function definition, `kwargs` receives a Python dictionary containing all keyword arguments after the formal parameter list). >>> String('{{foo}}').bind(foo = 'bar') == String('{{foo}}').bind({'foo': 'bar'}) True Bindings done "closer" to the object in question take precedence: >>> p = Process(name = '{{context}}_process') >>> t = Task().bind(context = 'global') >>> t(processes = [p, p.bind(context = 'local')]) Task(processes=ProcessList( Process(daemon=False, name=global_process, max_failures=1, ephemeral=False, final=False, min_duration=5), Process(daemon=False, name=local_process, max_failures=1, ephemeral=False, final=False, min_duration=5) )) #### Binding Complex Objects ##### Lists >>> fibonacci = List(Integer)([1, 1, 2, 3, 5, 8, 13]) >>> String('{{fib[4]}}').bind(fib = fibonacci) String(5) ##### Maps >>> first_names = Map(String, String)({'Kent': 'Clark', 'Wayne': 'Bruce', 'Prince': 'Diana'}) >>> String('{{first[Kent]}}').bind(first = first_names) String(Clark) ##### Structurals >>> String('{{p.cmdline}}').bind(p = Process(cmdline = "echo hello world")) String(echo hello world) ### Structural Binding Use structural templates when binding more than two or three individual values at the Job or Task level. For fewer than two or three, standard key to string binding is sufficient. Structural binding is a very powerful pattern and is most useful in Aurora/Thermos for doing Structural configuration. For example, you can define a job profile. The following profile uses `HDFS`, the Hadoop Distributed File System, to designate a file's location. `HDFS` does not come with Aurora, so you'll need to either install it separately or change the way the dataset is designated. class Profile(Struct): version = Required(String) environment = Required(String) dataset = Default(String, hdfs://home/aurora/data/{{environment}}') PRODUCTION = Profile(version = 'live', environment = 'prod') DEVEL = Profile(version = 'latest', environment = 'devel', dataset = 'hdfs://home/aurora/data/test') TEST = Profile(version = 'latest', environment = 'test') JOB_TEMPLATE = Job( name = 'application', role = 'myteam', cluster = 'cluster1', environment = '{{profile.environment}}', task = SequentialTask( name = 'task', resources = Resources(cpu = 2, ram = 4*GB, disk = 8*GB), processes = [ Process(name = 'main', cmdline = 'java -jar application.jar -hdfsPath {{profile.dataset}}') ] ) ) jobs = [ JOB_TEMPLATE(instances = 100).bind(profile = PRODUCTION), JOB_TEMPLATE.bind(profile = DEVEL), JOB_TEMPLATE.bind(profile = TEST), ] In this case, a custom structural "Profile" is created to self-document the configuration to some degree. This also allows some schema "type-checking", and for default self-substitution, e.g. in `Profile.dataset` above. So rather than a `.bind()` with a half-dozen substituted variables, you can bind a single object that has sensible defaults stored in a single place.
<!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_151) on Wed May 02 00:35:09 MST 2018 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>org.wildfly.swarm.microprofile.faulttolerance.detect Class Hierarchy (BOM: * : All 2018.5.0 API)</title> <meta name="date" content="2018-05-02"> <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="org.wildfly.swarm.microprofile.faulttolerance.detect Class Hierarchy (BOM: * : All 2018.5.0 API)"; } } 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>Class</li> <li>Use</li> <li class="navBarCell1Rev">Tree</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 class="aboutLanguage">WildFly Swarm API, 2018.5.0</div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../../org/wildfly/swarm/microprofile/faulttolerance/deployment/config/package-tree.html">Prev</a></li> <li><a href="../../../../../../org/wildfly/swarm/microprofile/health/package-tree.html">Next</a></li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/wildfly/swarm/microprofile/faulttolerance/detect/package-tree.html" target="_top">Frames</a></li> <li><a href="package-tree.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;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"> <h1 class="title">Hierarchy For Package org.wildfly.swarm.microprofile.faulttolerance.detect</h1> <span class="packageHierarchyLabel">Package Hierarchies:</span> <ul class="horizontal"> <li><a href="../../../../../../overview-tree.html">All Packages</a></li> </ul> </div> <div class="contentContainer"> <h2 title="Class Hierarchy">Class Hierarchy</h2> <ul> <li type="circle">java.lang.<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang"><span class="typeNameLink">Object</span></a> <ul> <li type="circle">PackageFractionDetector <ul> <li type="circle">org.wildfly.swarm.microprofile.faulttolerance.detect.<a href="../../../../../../org/wildfly/swarm/microprofile/faulttolerance/detect/FTPackageDetector.html" title="class in org.wildfly.swarm.microprofile.faulttolerance.detect"><span class="typeNameLink">FTPackageDetector</span></a></li> </ul> </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>Class</li> <li>Use</li> <li class="navBarCell1Rev">Tree</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 class="aboutLanguage">WildFly Swarm API, 2018.5.0</div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../../org/wildfly/swarm/microprofile/faulttolerance/deployment/config/package-tree.html">Prev</a></li> <li><a href="../../../../../../org/wildfly/swarm/microprofile/health/package-tree.html">Next</a></li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/wildfly/swarm/microprofile/faulttolerance/detect/package-tree.html" target="_top">Frames</a></li> <li><a href="package-tree.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;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>Copyright &#169; 2018 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p> </body> </html>
from openstack.tests.unit import base from openstack.network.v2 import listener IDENTIFIER = 'IDENTIFIER' EXAMPLE = { 'admin_state_up': True, 'connection_limit': '2', 'default_pool_id': '3', 'description': '4', 'id': IDENTIFIER, 'loadbalancers': [{'id': '6'}], 'loadbalancer_id': '6', 'name': '7', 'project_id': '8', 'protocol': '9', 'protocol_port': '10', 'default_tls_container_ref': '11', 'sni_container_refs': [], } class TestListener(base.TestCase): def test_basic(self): sot = listener.Listener() self.assertEqual('listener', sot.resource_key) self.assertEqual('listeners', sot.resources_key) self.assertEqual('/lbaas/listeners', sot.base_path) self.assertTrue(sot.allow_create) self.assertTrue(sot.allow_fetch) self.assertTrue(sot.allow_commit) self.assertTrue(sot.allow_delete) self.assertTrue(sot.allow_list) def test_make_it(self): sot = listener.Listener(**EXAMPLE) self.assertTrue(sot.is_admin_state_up) self.assertEqual(EXAMPLE['connection_limit'], sot.connection_limit) self.assertEqual(EXAMPLE['default_pool_id'], sot.default_pool_id) self.assertEqual(EXAMPLE['description'], sot.description) self.assertEqual(EXAMPLE['id'], sot.id) self.assertEqual(EXAMPLE['loadbalancers'], sot.load_balancer_ids) self.assertEqual(EXAMPLE['loadbalancer_id'], sot.load_balancer_id) self.assertEqual(EXAMPLE['name'], sot.name) self.assertEqual(EXAMPLE['project_id'], sot.project_id) self.assertEqual(EXAMPLE['protocol'], sot.protocol) self.assertEqual(EXAMPLE['protocol_port'], sot.protocol_port) self.assertEqual(EXAMPLE['default_tls_container_ref'], sot.default_tls_container_ref) self.assertEqual(EXAMPLE['sni_container_refs'], sot.sni_container_refs)
+ Initial release. ## 0.1.1 + change validate strategy from read validator map to read payload map. ## 0.1.2 + change lodash.clone to lodash.clonedeep ## 0.1.3 + pass action.payload in validator func ## 0.1.4 + check all validators not all params ## 0.1.5 + allow validators undefined ## 0.2.0 + no longer support promise, instead support thunk + custom `paramKey` is supported + `options.key` changed to `options.validatorKey` ## 0.2.1 + skip this middleware when `disableValidator: true` in `meta` ## 0.2.2 + ignore non-enumerable properties on validators ## 0.2.3 + add dynamic error message support
Please see the official documentation at https://material.angular.io/components/component/grid-list
using System; using System.Web.Http.Description; namespace Swashbuckle.Swagger.Annotations { public class ApplySwaggerOperationFilterAttributes : IOperationFilter { public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription) { var attributes = apiDescription.GetControllerAndActionAttributes<SwaggerOperationFilterAttribute>(); foreach (var attribute in attributes) { var filter = (IOperationFilter)Activator.CreateInstance(attribute.FilterType); filter.Apply(operation, schemaRegistry, apiDescription); } } } }
//%LICENSE//////////////////////////////////////////////////////////////// // // Licensed to The Open Group (TOG) under one or more contributor license // agreements. Refer to the OpenPegasusNOTICE.txt file distributed with // this work for additional information regarding copyright ownership. // Each contributor licenses this file to you under the OpenPegasus Open // Source License; you may not use this file except in compliance with the // License. // // 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. // ////////////////////////////////////////////////////////////////////////// // //%///////////////////////////////////////////////////////////////////////// UNIX_ExtentInDiskGroup::UNIX_ExtentInDiskGroup(void) { } UNIX_ExtentInDiskGroup::~UNIX_ExtentInDiskGroup(void) { } Boolean UNIX_ExtentInDiskGroup::getCollection(CIMProperty &p) const { p = CIMProperty(PROPERTY_COLLECTION, getCollection()); return true; } CIMInstance UNIX_ExtentInDiskGroup::getCollection() const { return CIMInstance(CIMName("CIM_ManagedElement")); } Boolean UNIX_ExtentInDiskGroup::getMember(CIMProperty &p) const { p = CIMProperty(PROPERTY_MEMBER, getMember()); return true; } CIMInstance UNIX_ExtentInDiskGroup::getMember() const { return CIMInstance(CIMName("CIM_ManagedElement")); } Boolean UNIX_ExtentInDiskGroup::initialize() { return false; } Boolean UNIX_ExtentInDiskGroup::load(int &pIndex) { return false; } Boolean UNIX_ExtentInDiskGroup::finalize() { return false; } Boolean UNIX_ExtentInDiskGroup::find(Array<CIMKeyBinding> &kbArray) { CIMKeyBinding kb; String collectionKey; String memberKey; for(Uint32 i = 0; i < kbArray.size(); i++) { kb = kbArray[i]; CIMName keyName = kb.getName(); if (keyName.equal(PROPERTY_COLLECTION)) collectionKey = kb.getValue(); else if (keyName.equal(PROPERTY_MEMBER)) memberKey = kb.getValue(); } /* EXecute find with extracted keys */ return false; }
var assert = require('assert'); var esprima = require('esprima'); var babelJscs = require('babel-jscs'); var JsFile = require('../../lib/js-file'); var sinon = require('sinon'); var fs = require('fs'); var assign = require('lodash.assign'); describe('js-file', function() { function createJsFile(sources, options) { var params = { filename: 'example.js', source: sources, esprima: esprima }; return new JsFile(assign(params, options)); } function createBabelJsFile(sources) { return new JsFile({ filename: 'example.js', source: sources, esprima: babelJscs, es6: true }); } describe('constructor', function() { it('empty file should have one token EOF', function() { var file = new JsFile({filename: 'example.js', source: '', esprima: esprima}); assert(Array.isArray(file.getTokens())); assert.equal(file.getTokens().length, 1); assert.equal(file.getTokens()[0].type, 'EOF'); }); it('should accept broken JS file', function() { var file = new JsFile({ filename: 'example.js', source: '/1', esprima: esprima }); assert(Array.isArray(file.getTokens())); assert.equal(file.getTokens().length, 1); assert.equal(file.getTokens()[0].type, 'EOF'); }); // Testing esprima token fix // https://code.google.com/p/esprima/issues/detail?id=481 describe('Keywords -> Identifier fixing', function() { it('should affect object keys tokens', function() { var str = '({' + 'break: true, export: true, return: true, case: true, for: true, switch: true, comment: true,' + 'function: true, this: true, continue: true, if: true, typeof: true, default: true, import: true,' + 'var: true, delete: true, in: true, void: true, do: true, label: true, while: true, else: true,' + 'new: true, with: true, catch: true, try: true, finally: true, \'\': true, null: true, 0: true' + '})'; createJsFile(str).getTokens().forEach(function(token) { assert(token.type !== 'Keyword'); }); }); it('should affect member access tokens', function() { var str = 'o.break(); o.export(); o.return(); o.case(); o.for(); o.switch(); o.comment();' + 'o.function(); o.this(); o.continue(); o.if(); o.typeof(); o.default(); o.import();' + 'o.var(); o.delete(); o.in(); o.void(); o.do(); o.label(); o.while(); o.else();' + 'o.new(); o.with(); o.catch(); o.try(); o.finally();'; createJsFile(str).getTokens().forEach(function(token) { assert(token.type !== 'Keyword'); }); }); it('should not affect valid nested constructions', function() { createJsFile('if (true) { if (false); }').getTokens().forEach(function(token) { if (token.value === 'if') { assert(token.type === 'Keyword'); } }); }); }); it('should handle parse errors', function() { var file = new JsFile({ filename: 'input', source: '\n2++;', esprima: esprima, esprimaOptions: {tolerant: false} }); assert.equal(file.getParseErrors().length, 1); var parseError = file.getParseErrors()[0]; assert.equal(parseError.description, 'Invalid left-hand side in assignment'); assert.equal(parseError.lineNumber, 2); assert.equal(parseError.column, 2); }); it('should ignore lines containing only <include> tag', function() { var file = createJsFile('<include src="file.js">\n' + ' <include src="file.js">\n' + '< include src="file.js" >\n' + '<include\n' + ' src="file.js">\n' + 'var a = 5;\n'); var comments = file._tree.comments; var gritTags = comments.filter(function(comment) { return comment.type === 'GritTag'; }); assert.equal(4, comments.length); assert.equal(4, gritTags.length); }); it('should ignore lines containing only <if> tag', function() { var file = createJsFile('<if expr="false">\n' + ' <if expr="false">\n' + '< if expr="false" >\n' + 'var a = 5;\n' + '</if>\n' + '<if\n' + ' expr="false">\n' + 'var b = 7;\n' + '</ if>'); var comments = file._tree.comments; var gritTags = comments.filter(function(comment) { return comment.type === 'GritTag'; }); assert.equal(6, comments.length); assert.equal(6, gritTags.length); }); }); describe('isEnabledRule', function() { it('should always return true when no control comments are used', function() { var file = createJsFile(['var x = "1";', 'x++;', 'x--;'].join('\n')); assert(file.isEnabledRule('validateQuoteMarks', 1)); assert(file.isEnabledRule('validateQuoteMarks', 2)); assert(file.isEnabledRule('validateQuoteMarks', 3)); }); it('should always return false when jscs is disabled', function() { var file = createJsFile(['// jscs: disable', 'var x = "1";', 'x++;', 'x--;'].join('\n')); assert(!file.isEnabledRule('validateQuoteMarks', 2)); assert(!file.isEnabledRule('validateQuoteMarks', 3)); assert(!file.isEnabledRule('validateQuoteMarks', 4)); }); it('should return true when jscs is reenabled', function() { var file = createJsFile([ '// jscs: disable', 'var x = "1";', '// jscs: enable', 'x++;', 'x--;' ].join('\n')); assert(!file.isEnabledRule('validateQuoteMarks', 2)); assert(file.isEnabledRule('validateQuoteMarks', 4)); assert(file.isEnabledRule('validateQuoteMarks', 5)); }); it('should ignore other comments', function() { var file = createJsFile([ '// jscs: disable', 'var x = "1";', '// jscs: enable', 'x++;', '// hello world', 'x--;' ].join('\n')); assert(!file.isEnabledRule('validateQuoteMarks', 2)); assert(file.isEnabledRule('validateQuoteMarks', 4)); assert(file.isEnabledRule('validateQuoteMarks', 6)); }); it('should accept block comments', function() { var file = createJsFile([ '/* jscs: disable */', 'var x = "1";', '/* jscs: enable */', 'x++;', 'x--;' ].join('\n')); assert(!file.isEnabledRule('validateQuoteMarks', 2)); assert(file.isEnabledRule('validateQuoteMarks', 4)); assert(file.isEnabledRule('validateQuoteMarks', 5)); }); it('should only enable the specified rule', function() { var file = createJsFile([ '// jscs: disable', 'var x = "1";', '// jscs: enable validateQuoteMarks', 'x++;', '// jscs: enable', 'x--;' ].join('\n')); assert(!file.isEnabledRule('validateQuoteMarks', 2)); assert(file.isEnabledRule('validateQuoteMarks', 4)); assert(file.isEnabledRule('newRule', 7)); }); it('should ignore leading and final comma', function() { var file = createJsFile([ '// jscs: disable', 'var x = "1";', '// jscs: enable ,validateQuoteMarks,', 'x++;' ].join('\n')); assert(!file.isEnabledRule('validateQuoteMarks', 2)); assert(file.isEnabledRule('validateQuoteMarks', 4)); }); it('should only disable the specified rule', function() { var file = createJsFile([ '// jscs: disable validateQuoteMarks', 'var x = "1";', '// jscs: enable newRule', 'x++;', '// jscs: enable', 'x--;' ].join('\n')); assert(!file.isEnabledRule('validateQuoteMarks', 2)); assert(!file.isEnabledRule('validateQuoteMarks', 4)); assert(file.isEnabledRule('validateQuoteMarks', 7)); }); it('should trim whitespace from the rule name', function() { var file = createJsFile([ '// jscs: disable validateQuoteMarks', 'var x = "1";' ].join('\n')); assert(!file.isEnabledRule('validateQuoteMarks', 2)); assert(!file.isEnabledRule('validateQuoteMarks ', 2)); assert(!file.isEnabledRule(' validateQuoteMarks', 2)); assert(!file.isEnabledRule(' validateQuoteMarks ', 2)); }); describe('single line trailing comment', function() { it('should ignore a single line', function() { var file = createJsFile([ 'var x = "1";', 'var y = "1"; // jscs: ignore validateQuoteMarks', 'var z = "1";' ].join('\n')); assert(file.isEnabledRule('validateQuoteMarks', 1)); assert(!file.isEnabledRule('validateQuoteMarks', 2)); assert(file.isEnabledRule('validateQuoteMarks', 3)); }); it('should work with no space before jscs:ignore', function() { var file = createJsFile([ 'var x = "1";', 'var y = "1"; //jscs: ignore validateQuoteMarks', 'var z = "1";' ].join('\n')); assert(file.isEnabledRule('validateQuoteMarks', 1)); assert(!file.isEnabledRule('validateQuoteMarks', 2)); assert(file.isEnabledRule('validateQuoteMarks', 3)); }); it('should work without a space before `jscs`', function() { var file = createJsFile([ 'var x = "1";', 'var y = "1"; //jscs: ignore validateQuoteMarks', 'var z = "1";' ].join('\n')); assert(file.isEnabledRule('validateQuoteMarks', 1)); assert(!file.isEnabledRule('validateQuoteMarks', 2)); assert(file.isEnabledRule('validateQuoteMarks', 3)); }); it('should not re-enable rules', function() { var file = createJsFile([ 'var a = "1";', '// jscs: disable validateQuoteMarks', 'var b = "1"; // jscs: ignore validateQuoteMarks', 'var c = "1";' ].join('\n')); assert(file.isEnabledRule('validateQuoteMarks', 1)); assert(!file.isEnabledRule('validateQuoteMarks', 2)); assert(!file.isEnabledRule('validateQuoteMarks', 3)); assert(!file.isEnabledRule('validateQuoteMarks', 4)); }); it('should also work with multiple rules', function() { var file = createJsFile([ '// jscs: disable validateQuoteMarks', 'var a = "1"; // jscs: ignore validateQuoteMarks, anotherRule', 'var b = "1";' ].join('\n')); assert(!file.isEnabledRule('validateQuoteMarks', 1)); assert(!file.isEnabledRule('validateQuoteMarks', 2)); assert(!file.isEnabledRule('validateQuoteMarks', 3)); assert(file.isEnabledRule('anotherRule', 1)); assert(!file.isEnabledRule('anotherRule', 2)); assert(file.isEnabledRule('anotherRule', 3)); }); it('should be able to ignore all rules', function() { var file = createJsFile([ 'var a = "1"; // jscs: ignore', 'var b = "1";' ].join('\n')); assert(!file.isEnabledRule('validateQuoteMarks', 1)); assert(file.isEnabledRule('validateQuoteMarks', 2)); }); }); }); describe('iterateNodesByType', function() { it('should handle ES6 export keyword', function() { var spy = sinon.spy(); createBabelJsFile('export function foo() { var a = "b"; };') .iterateNodesByType('VariableDeclaration', spy); assert(spy.calledOnce); }); }); describe('iterateTokenByValue', function() { it('should find token by value', function() { createJsFile('if (true);').iterateTokenByValue(')', function(token, index, tokens) { assert(token.value === ')'); assert(index === 3); assert(Array.isArray(tokens)); }); }); it('should find tokens by value', function() { createJsFile('if (true);').iterateTokenByValue([')', '('], function(token, index, tokens) { assert(token.value === ')' || token.value === '('); assert(index === 3 || index === 1); assert(Array.isArray(tokens)); }); }); it('should not find string value', function() { var spy = sinon.spy(); createJsFile('"("').iterateTokenByValue('(', spy); assert(!spy.calledOnce); }); it('should not take only own propeties', function() { var spy = sinon.spy(); createJsFile('test.toString').iterateTokenByValue('(', spy); assert(!spy.calledOnce); }); it('should not have duplicate tokens in es6 export default statements', function() { var spy = sinon.spy(); createBabelJsFile('export default function() {}').iterateTokenByValue('(', spy); assert(spy.calledOnce); }); it('should not have duplicate tokens in es6 export default statements', function() { var spy = sinon.spy(); createBabelJsFile('export default function init() {\n' + ' window.addEventListener(\'fb-flo-reload\', function(ev) {\n' + ' });\n' + '}').iterateTokenByValue('(', spy); assert(spy.calledThrice); }); }); describe('getNodeByRange', function() { it('should get node by range for function declaration', function() { assert.equal(createJsFile('function foo(a,b) {}').getNodeByRange(16).type, 'FunctionDeclaration'); }); it('should get node by range for identifier', function() { assert.equal(createJsFile('foo(a,b)').getNodeByRange(0).type, 'Identifier'); }); it('should get node by range for function expression', function() { assert.equal(createJsFile('foo(a,b)').getNodeByRange(7).type, 'CallExpression'); }); it('should get node by range for "if" statement', function() { assert.equal(createJsFile('if(true){foo(a,b)}').getNodeByRange(0).type, 'IfStatement'); }); it('should get node by range for identifier inside "if" statement', function() { assert.equal(createJsFile('if(true){foo(a,b)}').getNodeByRange(9).type, 'Identifier'); }); it('should get node by range for function expression inside "if" statement', function() { assert.equal(createJsFile('if(true){foo(a,b)}').getNodeByRange(16).type, 'CallExpression'); }); it('should get node by range for function expression with additional parentheses', function() { assert.equal(createJsFile('foo(1,(2))').getNodeByRange(9).type, 'CallExpression'); }); it('should return empty object', function() { assert.equal(createJsFile('foo(1,2)').getNodeByRange(20).type, undefined); }); it('should not throw on regexp', function() { var file = createJsFile('/^/'); try { file.getNodeByRange(1); assert(true); } catch (e) { assert(false); } }); }); describe('findNextToken', function() { var file; beforeEach(function() { file = createJsFile('switch(varName){case"yes":a++;break;}'); }); it('should find the first next token when only the type is specified', function() { var switchToken = file.getTokens()[0]; assert.equal(switchToken.type, 'Keyword'); assert.equal(switchToken.value, 'switch'); var nextToken = file.findNextToken(switchToken, 'Identifier'); assert.equal(nextToken.type, 'Identifier'); assert.equal(nextToken.value, 'varName'); nextToken = file.findNextToken(switchToken, 'Keyword'); assert.equal(nextToken.type, 'Keyword'); assert.equal(nextToken.value, 'case'); nextToken = file.findNextToken(switchToken, 'Punctuator'); assert.equal(nextToken.type, 'Punctuator'); assert.equal(nextToken.value, '('); }); it('should find the first next token when both type and value are specified', function() { var switchToken = file.getTokens()[0]; assert.equal(switchToken.type, 'Keyword'); assert.equal(switchToken.value, 'switch'); var nextToken = file.findNextToken(switchToken, 'Identifier', 'varName'); assert.equal(nextToken.type, 'Identifier'); assert.equal(nextToken.value, 'varName'); nextToken = file.findNextToken(switchToken, 'Keyword', 'case'); assert.equal(nextToken.type, 'Keyword'); assert.equal(nextToken.value, 'case'); nextToken = file.findNextToken(switchToken, 'Punctuator', '('); assert.equal(nextToken.type, 'Punctuator'); assert.equal(nextToken.value, '('); }); it('should find the correct next token when both type and value are specified', function() { var switchToken = file.getTokens()[0]; assert.equal(switchToken.type, 'Keyword'); assert.equal(switchToken.value, 'switch'); var nextToken = file.findNextToken(switchToken, 'Keyword', 'break'); assert.equal(nextToken.type, 'Keyword'); assert.equal(nextToken.value, 'break'); nextToken = file.findNextToken(switchToken, 'Punctuator', '{'); assert.equal(nextToken.type, 'Punctuator'); assert.equal(nextToken.value, '{'); nextToken = file.findNextToken(switchToken, 'Punctuator', ':'); assert.equal(nextToken.type, 'Punctuator'); assert.equal(nextToken.value, ':'); nextToken = file.findNextToken(switchToken, 'Punctuator', '}'); assert.equal(nextToken.type, 'Punctuator'); assert.equal(nextToken.value, '}'); }); it('should not find any token if it does not exist', function() { var switchToken = file.getTokens()[0]; assert.equal(switchToken.type, 'Keyword'); assert.equal(switchToken.value, 'switch'); var nextToken = file.findNextToken(switchToken, 'Keyword', 'if'); assert.equal(nextToken, undefined); nextToken = file.findNextToken(switchToken, 'Numeric'); assert.equal(nextToken, undefined); nextToken = file.findNextToken(switchToken, 'Boolean'); assert.equal(nextToken, undefined); nextToken = file.findNextToken(switchToken, 'Null'); assert.equal(nextToken, undefined); }); }); describe('findPrevToken', function() { var file; var tokens; beforeEach(function() { file = createJsFile('switch(varName){case"yes":a++;break;}'); tokens = file.getTokens(); }); it('should find the first previous token when only the type is specified', function() { var lastToken = tokens[tokens.length - 1]; assert.equal(lastToken.type, 'EOF'); var previousToken = file.findPrevToken(lastToken, 'Punctuator'); var firstPunctuator = previousToken; assert.equal(previousToken.type, 'Punctuator'); assert.equal(previousToken.value, '}'); previousToken = file.findPrevToken(lastToken, 'Identifier'); assert.equal(previousToken.type, 'Identifier'); assert.equal(previousToken.value, 'a'); previousToken = file.findPrevToken(lastToken, 'Keyword'); assert.equal(previousToken.type, 'Keyword'); assert.equal(previousToken.value, 'break'); previousToken = file.findPrevToken(firstPunctuator, 'Punctuator'); assert.equal(previousToken.type, 'Punctuator'); assert.equal(previousToken.value, ';'); }); it('should find the first previous token when both type and value are specified', function() { var lastToken = tokens[tokens.length - 2]; assert.equal(lastToken.type, 'Punctuator'); assert.equal(lastToken.value, '}'); var previousToken = file.findPrevToken(lastToken, 'Identifier', 'a'); assert.equal(previousToken.type, 'Identifier'); assert.equal(previousToken.value, 'a'); previousToken = file.findPrevToken(lastToken, 'Keyword', 'break'); assert.equal(previousToken.type, 'Keyword'); assert.equal(previousToken.value, 'break'); previousToken = file.findPrevToken(lastToken, 'Punctuator', ';'); assert.equal(previousToken.type, 'Punctuator'); assert.equal(previousToken.value, ';'); }); it('should find the correct previous token when both type and value are specified', function() { var lastToken = tokens[tokens.length - 2]; assert.equal(lastToken.type, 'Punctuator'); assert.equal(lastToken.value, '}'); var previousToken = file.findPrevToken(lastToken, 'Keyword', 'case'); assert.equal(previousToken.type, 'Keyword'); assert.equal(previousToken.value, 'case'); previousToken = file.findPrevToken(lastToken, 'Punctuator', '{'); assert.equal(previousToken.type, 'Punctuator'); assert.equal(previousToken.value, '{'); previousToken = file.findPrevToken(lastToken, 'Punctuator', ':'); assert.equal(previousToken.type, 'Punctuator'); assert.equal(previousToken.value, ':'); previousToken = file.findPrevToken(lastToken, 'Punctuator', '('); assert.equal(previousToken.type, 'Punctuator'); assert.equal(previousToken.value, '('); }); it('should not find any token if it does not exist', function() { var lastToken = tokens[tokens.length - 2]; assert.equal(lastToken.type, 'Punctuator'); assert.equal(lastToken.value, '}'); var previousToken = file.findPrevToken(lastToken, 'Keyword', 'if'); assert.equal(previousToken, undefined); previousToken = file.findPrevToken(lastToken, 'Numeric'); assert.equal(previousToken, undefined); previousToken = file.findPrevToken(lastToken, 'Boolean'); assert.equal(previousToken, undefined); previousToken = file.findPrevToken(lastToken, 'Null'); assert.equal(previousToken, undefined); }); it('should find prev token', function() { file = createJsFile('if (true);'); var trueToken = file.getTokens()[2]; assert.equal(trueToken.type, 'Boolean'); assert.equal(trueToken.value, 'true'); var ifToken = file.findPrevToken(trueToken, 'Keyword'); assert.equal(ifToken.type, 'Keyword'); assert.equal(ifToken.value, 'if'); ifToken = file.findPrevToken(trueToken, 'Keyword', 'if'); assert.equal(ifToken.type, 'Keyword'); assert.equal(ifToken.value, 'if'); }); }); describe('findNextOperatorToken', function() { it('should should return next punctuator', function() { var file = createJsFile('x = y;'); var token = file.findNextOperatorToken(file.getTokens()[0], '='); assert.equal(token.type, 'Punctuator'); assert.equal(token.value, '='); assert.equal(token.range[0], 2); }); it('should should return next operator-keyword', function() { var file = createJsFile('x instanceof y;'); var token = file.findNextOperatorToken(file.getTokens()[0], 'instanceof'); assert.equal(token.type, 'Keyword'); assert.equal(token.value, 'instanceof'); assert.equal(token.range[0], 2); }); it('should should return undefined for non-found token', function() { var file = createJsFile('x = y;'); var token = file.findNextOperatorToken(file.getTokens()[0], '-'); assert(token === undefined); }); }); describe('findPrevOperatorToken', function() { it('should should return next punctuator', function() { var file = createJsFile('x = y;'); var token = file.findPrevOperatorToken(file.getTokens()[2], '='); assert.equal(token.type, 'Punctuator'); assert.equal(token.value, '='); assert.equal(token.range[0], 2); }); it('should should return next operator-keyword', function() { var file = createJsFile('x instanceof y;'); var token = file.findPrevOperatorToken(file.getTokens()[2], 'instanceof'); assert.equal(token.type, 'Keyword'); assert.equal(token.value, 'instanceof'); assert.equal(token.range[0], 2); }); it('should should return undefined for non-found token', function() { var file = createJsFile('x = y;'); var token = file.findPrevOperatorToken(file.getTokens()[2], '-'); assert(token === undefined); }); }); describe('getTokenByRangeStart', function() { it('should return token for specified start position', function() { var file = createJsFile('if (true) { x++; }'); var ifToken = file.getTokenByRangeStart(0); assert.equal(ifToken.type, 'Keyword'); assert.equal(ifToken.value, 'if'); var incToken = file.getTokenByRangeStart(12); assert.equal(incToken.type, 'Identifier'); assert.equal(incToken.value, 'x'); }); it('should return undefined if token was not found', function() { var file = createJsFile('if (true) { x++; }'); var token = file.getTokenByRangeStart(1); assert(token === undefined); }); }); describe('getTokenByRangeEnd', function() { it('should return token for specified end position', function() { var file = createJsFile('if (true) { x++; }'); var ifToken = file.getTokenByRangeEnd(2); assert.equal(ifToken.type, 'Keyword'); assert.equal(ifToken.value, 'if'); var incToken = file.getTokenByRangeEnd(13); assert.equal(incToken.type, 'Identifier'); assert.equal(incToken.value, 'x'); }); it('should return undefined if token was not found', function() { var file = createJsFile('if (true) { x++; }'); var token = file.getTokenByRangeEnd(3); assert(token === undefined); }); }); describe('getFirstNodeToken', function() { it('should return token for specified node', function() { var file = createJsFile('if (true) { while (true) x++; }'); var ifToken = file.getFirstNodeToken(file.getNodesByType('IfStatement')[0]); assert.equal(ifToken.type, 'Keyword'); assert.equal(ifToken.value, 'if'); var incToken = file.getFirstNodeToken(file.getNodesByType('UpdateExpression')[0]); assert.equal(incToken.type, 'Identifier'); assert.equal(incToken.value, 'x'); }); }); describe('getLastNodeToken', function() { it('should return token for specified node', function() { var file = createJsFile('if (true) { while (true) x++; }'); var ifToken = file.getLastNodeToken(file.getNodesByType('IfStatement')[0]); assert.equal(ifToken.type, 'Punctuator'); assert.equal(ifToken.value, '}'); var incToken = file.getLastNodeToken(file.getNodesByType('UpdateExpression')[0]); assert.equal(incToken.type, 'Punctuator'); assert.equal(incToken.value, '++'); }); }); describe('getFirstToken', function() { it('should return token for specified file', function() { var file = createJsFile('if (true) { while (true) x++; }'); var ifToken = file.getFirstToken(); assert.equal(ifToken.type, 'Keyword'); assert.equal(ifToken.value, 'if'); }); }); describe('getLastToken', function() { it('should return token for specified file', function() { var file = createJsFile('if (true) { while (true) x++; }'); var EOFToken = file.getLastToken(); assert.equal(EOFToken.type, 'EOF'); }); }); describe('getNodesByFirstToken', function() { describe('invalid arguments', function() { var file; beforeEach(function() { file = createJsFile('x++;y++;'); }); it('should return empty array if the argument is invalid', function() { var nodes = file.getNodesByFirstToken(); assert.equal(nodes.length, 0); }); it('should return empty array if the argument.range is invalid', function() { var nodes = file.getNodesByFirstToken({}); assert.equal(nodes.length, 0); }); it('should return empty array if the argument.range[0] is invalid', function() { var nodes = file.getNodesByFirstToken({ range: {} }); assert.equal(nodes.length, 0); }); }); describe('empty progam', function() { var file; beforeEach(function() { file = createJsFile(''); }); it('should return 1 node of type Program when provided the first token', function() { var token = file.getFirstToken(); var nodes = file.getNodesByFirstToken(token); assert.equal(nodes.length, 1); assert.equal(nodes[0].type, 'Program'); }); }); describe('normal progam', function() { var file; beforeEach(function() { file = createJsFile('var x;\ndo {\n\tx++;\n} while (x < 10);'); }); it('should return nodes when supplied with a token that is the start of a node', function() { var token = file.getFirstToken(); var nodes = file.getNodesByFirstToken(token); assert.equal(nodes.length, 2); assert.equal(nodes[0].type, 'Program'); assert.equal(nodes[1].type, 'VariableDeclaration'); }); it('should return an empty array when supplied with a token that is not the start of a node', function() { var token = file.getFirstToken(); var nextToken = file.findNextToken(token, 'Keyword', 'while'); var nodes = file.getNodesByFirstToken(nextToken); assert.equal(nodes.length, 0); }); }); }); describe('getNodesByType', function() { it('should return nodes using specified type', function() { var nodes = createJsFile('x++;y++;').getNodesByType('Identifier'); assert.equal(nodes.length, 2); assert.equal(nodes[0].type, 'Identifier'); assert.equal(nodes[0].name, 'x'); assert.equal(nodes[1].type, 'Identifier'); assert.equal(nodes[1].name, 'y'); }); it('should return empty array for non-existing type', function() { var nodes = createJsFile('x++;y++;').getNodesByType('Literal'); assert.equal(nodes.length, 0); }); it('should accept array as an argument', function() { var nodes = createJsFile('x += 1;').getNodesByType(['Identifier', 'Literal']); assert.equal(nodes.length, 2); assert.equal(nodes[0].type, 'Identifier'); assert.equal(nodes[0].name, 'x'); assert.equal(nodes[1].type, 'Literal'); assert.equal(nodes[1].value, 1); }); it('should return empty array for non-existing type array', function() { var nodes = createJsFile('x++;y++;').getNodesByType(['Literal', 'BinaryExpression']); assert.equal(nodes.length, 0); }); }); describe('getFirstLineToken', function() { it('should return first line token', function() { var file = createJsFile('x += 1;\ny += 4;'); var xToken = file.getFirstTokenOnLine(1); assert.equal(xToken.type, 'Identifier'); assert.equal(xToken.value, 'x'); var yToken = file.getFirstTokenOnLine(2); assert.equal(yToken.type, 'Identifier'); assert.equal(yToken.value, 'y'); }); it('should return first line token if token is indented', function() { var file = createJsFile('\t\tx += 1;\n\t\ty += 4;'); var xToken = file.getFirstTokenOnLine(1); assert.equal(xToken.type, 'Identifier'); assert.equal(xToken.value, 'x'); var yToken = file.getFirstTokenOnLine(2); assert.equal(yToken.type, 'Identifier'); assert.equal(yToken.value, 'y'); }); it('should return undefined if no token was found', function() { var file = createJsFile('\t\tx += 1;\n\n'); var yToken = file.getFirstTokenOnLine(2); assert.equal(yToken, undefined); }); it('should return undefined if only comment was found', function() { var file = createJsFile('\t\tx += 1;\n/*123*/\n'); var yToken = file.getFirstTokenOnLine(2); assert.equal(yToken, undefined); }); it('should return first line token ignoring comments', function() { var file = createJsFile('\t/* 123 */\tx += 1;\n\t/* 321 */\ty += 4;'); var xToken = file.getFirstTokenOnLine(1); assert.equal(xToken.type, 'Identifier'); assert.equal(xToken.value, 'x'); var yToken = file.getFirstTokenOnLine(2); assert.equal(yToken.type, 'Identifier'); assert.equal(yToken.value, 'y'); }); it('should return first line token including comments', function() { var file = createJsFile('\t/*123*/\tx += 1;\n\t/*321*/\ty += 4;'); var commentToken1 = file.getFirstTokenOnLine(1, {includeComments: true}); assert(commentToken1.isComment); assert.equal(commentToken1.type, 'Block'); assert.equal(commentToken1.value, '123'); var commentToken2 = file.getFirstTokenOnLine(2, {includeComments: true}); assert(commentToken2.isComment); assert.equal(commentToken2.type, 'Block'); assert.equal(commentToken2.value, '321'); }); it('should return undefined if no token was found including comments', function() { var file = createJsFile('\t\tx += 1;\n\n'); var yToken = file.getFirstTokenOnLine(2, {includeComments: true}); assert.equal(yToken, undefined); }); }); describe('getLastLineToken', function() { it('should return last line token', function() { var file = createJsFile('x = 1;\nif (x) {}\n'); var xToken = file.getLastTokenOnLine(1); assert.equal(xToken.type, 'Punctuator'); assert.equal(xToken.value, ';'); var ifToken = file.getLastTokenOnLine(2); assert.equal(ifToken.type, 'Punctuator'); assert.equal(ifToken.value, '}'); }); it('should return undefined if no token was found', function() { var file = createJsFile('\nx = 1;'); var noToken = file.getLastTokenOnLine(1); assert.equal(noToken, undefined); }); it('should return undefined if only comment was found', function() { var file = createJsFile('\t\tx += 1;\n/*123*/\n'); var noToken = file.getLastTokenOnLine(2); assert.equal(noToken, undefined); }); it('should return last line token ignoring comments', function() { var file = createJsFile('x = 1; /* 321 */\n'); var xToken = file.getLastTokenOnLine(1); assert.equal(xToken.type, 'Punctuator'); assert.equal(xToken.value, ';'); }); it('should return last line token including comments', function() { var file = createJsFile('x = 1; /*123*/\n'); var commentToken = file.getLastTokenOnLine(1, {includeComments: true}); assert(commentToken.isComment); assert.equal(commentToken.type, 'Block'); assert.equal(commentToken.value, '123'); }); it('should return undefined if no token was found including comments', function() { var file = createJsFile('\nx = 1;'); var noToken = file.getLastTokenOnLine(1, {includeComments: true}); assert.equal(noToken, undefined); }); }); describe('iterate', function() { it('should iterate all nodes in the document', function() { var file = createJsFile('x++;'); var spy = sinon.spy(); file.iterate(spy); assert.equal(spy.callCount, 4); assert.equal(spy.getCall(0).args[0].type, 'Program'); assert.equal(spy.getCall(1).args[0].type, 'ExpressionStatement'); assert.equal(spy.getCall(2).args[0].type, 'UpdateExpression'); assert.equal(spy.getCall(3).args[0].type, 'Identifier'); }); it('should iterate nested nodes', function() { var file = createJsFile('x = (5 + 4) && (3 + 1);'); var spy = sinon.spy(); file.iterate(spy, file.getNodesByType('LogicalExpression')[0].left); assert.equal(spy.callCount, 3); assert.equal(spy.getCall(0).args[0].type, 'BinaryExpression'); assert.equal(spy.getCall(1).args[0].type, 'Literal'); assert.equal(spy.getCall(1).args[0].value, 5); assert.equal(spy.getCall(2).args[0].type, 'Literal'); assert.equal(spy.getCall(2).args[0].value, 4); }); }); describe('iterateNodesByType', function() { it('should apply callback using specified type', function() { var spy = sinon.spy(); createJsFile('x++;y++;').iterateNodesByType('Identifier', spy); assert.equal(spy.callCount, 2); assert.equal(spy.getCall(0).args[0].type, 'Identifier'); assert.equal(spy.getCall(0).args[0].name, 'x'); assert.equal(spy.getCall(1).args[0].type, 'Identifier'); assert.equal(spy.getCall(1).args[0].name, 'y'); }); it('should not apply callback for non-existing type', function() { var spy = sinon.spy(); createJsFile('x++;y++;').iterateNodesByType('Literal', spy); assert(!spy.called); }); it('should accept array as an argument', function() { var spy = sinon.spy(); createJsFile('x += 1;').iterateNodesByType(['Identifier', 'Literal'], spy); assert.equal(spy.callCount, 2); assert.equal(spy.getCall(0).args[0].type, 'Identifier'); assert.equal(spy.getCall(0).args[0].name, 'x'); assert.equal(spy.getCall(1).args[0].type, 'Literal'); assert.equal(spy.getCall(1).args[0].value, 1); }); it('should not apply callback for non-existing type array', function() { var spy = sinon.spy(); createJsFile('x++;y++;').iterateNodesByType(['Literal', 'BinaryExpression'], spy); assert(!spy.called); }); }); describe('iterateTokensByType', function() { it('should apply callback using specified type', function() { var spy = sinon.spy(); createJsFile('x++;y++;').iterateTokensByType('Identifier', spy); assert.equal(spy.callCount, 2); assert.equal(spy.getCall(0).args[0].type, 'Identifier'); assert.equal(spy.getCall(0).args[0].value, 'x'); assert.equal(spy.getCall(1).args[0].type, 'Identifier'); assert.equal(spy.getCall(1).args[0].value, 'y'); }); it('should not apply callback for non-existing type', function() { var spy = sinon.spy(); createJsFile('x++;y++;').iterateTokensByType('Boolean', spy); assert(!spy.called); }); it('should apply callback for line comments', function() { var spy = sinon.spy(); createJsFile('//foo').iterateTokensByType('Line', spy); assert(spy.calledOnce); }); it('should apply callback for block comments', function() { var spy = sinon.spy(); createJsFile('/*foo*/').iterateTokensByType('Block', spy); assert(spy.calledOnce); }); it('should accept array as an argument', function() { var spy = sinon.spy(); createJsFile('x += 1;').iterateTokensByType(['Identifier', 'Numeric'], spy); assert.equal(spy.callCount, 2); assert.equal(spy.getCall(0).args[0].type, 'Identifier'); assert.equal(spy.getCall(0).args[0].value, 'x'); assert.equal(spy.getCall(1).args[0].type, 'Numeric'); assert.equal(spy.getCall(1).args[0].value, '1'); }); it('should not apply callback for non-existing type array', function() { var spy = sinon.spy(); createJsFile('x++;y++;').iterateTokensByType(['Boolean', 'Numeric'], spy); assert(!spy.called); }); }); describe('getTree', function() { it('should return empty token tree for non-existing esprima-tree', function() { var file = new JsFile({filename: 'example.js', source: 'Hello\nWorld', esprima: esprima}); assert.equal(typeof file.getTree(), 'object'); assert(file.getTree() !== null); }); }); describe('getSource', function() { it('should return specified source code', function() { var sources = 'var x = 1;\nvar y = 2;'; var file = createJsFile(sources); assert.equal(file.getSource(), sources); }); }); describe('getTokens', function() { it('should return EOF for empty string', function() { var tokens = createJsFile('').getTokens(); assert.equal(tokens.length, 1); assert.equal(tokens[0].type, 'EOF'); }); it('should end with EOF', function() { var tokens = createJsFile('if(true) {\nvar a = 2;\n}').getTokens(); assert.equal(tokens[tokens.length - 1].type, 'EOF'); }); it('should include comments', function() { var tokens = createJsFile('/* foo */').getTokens(); assert.equal(tokens[0].type, 'Block'); }); }); describe('getDialect', function() { var sources = 'var x = 1;\nvar y = 2;'; it('should return es5 with no options specified', function() { var file = createJsFile(sources); assert.equal(file.getDialect(), 'es5'); }); it('should return es6 when es6 is specified as true', function() { var file = createJsFile(sources, {es6: true}); assert.equal(file.getDialect(), 'es6'); }); it('should return es5 when es6 is specified as false', function() { var file = createJsFile(sources, {es6: false}); assert.equal(file.getDialect(), 'es5'); }); it('should return es3 when es3 is specified as true', function() { var file = createJsFile(sources, {es3: true}); assert.equal(file.getDialect(), 'es3'); }); it('should return es5 when es3 is specified as false', function() { var file = createJsFile(sources, {es3: false}); assert.equal(file.getDialect(), 'es5'); }); it('should return es6 when es3 and es6 are both specified as true', function() { var file = createJsFile(sources, {es3: true, es6: true}); assert.equal(file.getDialect(), 'es6'); }); }); describe('getLines', function() { it('should return specified source code lines', function() { var sources = ['var x = 1;', 'var y = 2;']; var file = createJsFile(sources.join('\n')); assert.equal(file.getLines().length, 2); assert.equal(file.getLines()[0], sources[0]); assert.equal(file.getLines()[1], sources[1]); }); it('should accept all line endings', function() { var lineEndings = ['\r\n', '\r', '\n']; lineEndings.forEach(function(lineEnding) { var sources = ['var x = 1;', 'var y = 2;']; var file = createJsFile(sources.join(lineEnding)); assert.equal(file.getLines().length, 2); assert.equal(file.getLines()[0], sources[0]); assert.equal(file.getLines()[1], sources[1]); }); }); }); describe('getLinesWithCommentsRemoved', function() { it('should strip line comments', function() { var source = 'a++; //comment\n//comment'; var file = createJsFile(source); var lines = file.getLinesWithCommentsRemoved(); assert.equal(lines.length, 2); assert.equal(lines[0], 'a++; '); assert.equal(lines[1], ''); }); it('should strip single-line block comments', function() { var source = 'a++;/*comment*/b++;\n/*comment*/'; var file = createJsFile(source); var lines = file.getLinesWithCommentsRemoved(); assert.equal(lines.length, 2); assert.equal(lines[0], 'a++;b++;'); assert.equal(lines[1], ''); }); it('should strip multi-line block comments', function() { var source = 'a++;/*comment\nmore comment\nmore comment*/'; var file = createJsFile(source); var lines = file.getLinesWithCommentsRemoved(); assert.equal(lines.length, 3); assert.equal(lines[0], 'a++;'); assert.equal(lines[1], ''); assert.equal(lines[2], ''); }); it('should strip an multi-line block comments with trailing tokens', function() { var source = 'a++;/*comment\nmore comment\nmore comment*/b++;'; var file = createJsFile(source); var lines = file.getLinesWithCommentsRemoved(); assert.equal(lines.length, 3); assert.equal(lines[0], 'a++;'); assert.equal(lines[1], ''); assert.equal(lines[2], 'b++;'); }); it('should preserve comment order', function() { var source = '//comment1\n//comment2'; var file = createJsFile(source); file.getLinesWithCommentsRemoved(); assert.equal(file.getComments()[0].value, 'comment1'); assert.equal(file.getComments()[1].value, 'comment2'); }); }); describe('getFilename', function() { it('should return given filename', function() { var file = new JsFile({ filename: 'example.js', source: 'Hello\nWorld', esprima: esprima }); assert.equal(file.getFilename(), 'example.js'); }); }); describe('render', function() { var relativeDirPath = '../data/render'; var absDirPath = __dirname + '/' + relativeDirPath; fs.readdirSync(absDirPath).forEach(function(filename) { it('file ' + relativeDirPath + '/' + filename + ' should be rendered correctly', function() { var source = fs.readFileSync(absDirPath + '/' + filename, 'utf8'); var file = createBabelJsFile(source); assert.equal(file.render(), source); }); }); }); describe('getLineBreaks', function() { it('should return \\n', function() { var file = new JsFile({filename: 'example.js', source: 'Hello\nWorld', esprima: esprima}); assert.deepEqual(file.getLineBreaks(), ['\n']); }); it('should return empty array for single line file', function() { var file = new JsFile({filename: 'example.js', source: 'Hello', esprima: esprima}); assert.deepEqual(file.getLineBreaks(), []); }); it('should return \\r', function() { var file = new JsFile({filename: 'example.js', source: 'Hello\rWorld', esprima: esprima}); assert.deepEqual(file.getLineBreaks(), ['\r']); }); it('should return \\r\\n', function() { var file = new JsFile({filename: 'example.js', source: 'Hello\r\nWorld', esprima: esprima}); assert.deepEqual(file.getLineBreaks(), ['\r\n']); }); }); describe('getLineBreakStyle', function() { it('should return \\n', function() { var file = new JsFile({filename: 'example.js', source: 'Hello\nWorld', esprima: esprima}); assert.equal(file.getLineBreakStyle(), '\n'); }); it('should return \\r', function() { var file = new JsFile({filename: 'example.js', source: 'Hello\rWorld', esprima: esprima}); assert.equal(file.getLineBreakStyle(), '\r'); }); it('should return \\r\\n', function() { var file = new JsFile({filename: 'example.js', source: 'Hello\r\nWorld', esprima: esprima}); assert.equal(file.getLineBreakStyle(), '\r\n'); }); it('should return \\n for single line file', function() { var file = new JsFile({filename: 'example.js', source: 'Hello', esprima: esprima}); assert.equal(file.getLineBreakStyle(), '\n'); }); it('should return first line break for mixed file', function() { var file = new JsFile({filename: 'example.js', source: 'Hello\nWorld\r\n!', esprima: esprima}); assert.equal(file.getLineBreakStyle(), file.getLineBreaks()[0]); }); }); describe('getNextToken', function() { it('should return next token', function() { var file = createJsFile('x++'); var xToken = file.getTokens()[0]; assert.equal(xToken.type, 'Identifier'); assert.equal(xToken.value, 'x'); var nextToken = file.getNextToken(xToken); assert.equal(nextToken.type, 'Punctuator'); assert.equal(nextToken.value, '++'); }); it('should return EOF token', function() { var file = createJsFile('x'); var xToken = file.getTokens()[0]; assert.equal(xToken.type, 'Identifier'); assert.equal(xToken.value, 'x'); var nextToken = file.getNextToken(xToken); assert.equal(nextToken.type, 'EOF'); assert.equal(nextToken.value, ''); }); it('should return undefined for out-of-range token', function() { var file = createJsFile('x'); var xToken = file.getTokens()[0]; var nextToken = file.getNextToken(file.getNextToken(xToken)); assert.equal(nextToken, undefined); }); it('should ignore comments', function() { var file = createJsFile('x /*123*/'); var xToken = file.getTokens()[0]; var nextToken = file.getNextToken(xToken, {includeComments: false}); assert.equal(nextToken.type, 'EOF'); assert.equal(nextToken.value, ''); }); it('should return next comment', function() { var file = createJsFile('x /*123*/'); var xToken = file.getTokens()[0]; var nextToken = file.getNextToken(xToken, {includeComments: true}); assert.equal(nextToken.type, 'Block'); }); it('should return EOF next to comment', function() { var file = createJsFile('x /*123*/'); var xToken = file.getComments()[0]; var nextToken = file.getNextToken(xToken, {includeComments: true}); assert.equal(nextToken.type, 'EOF'); }); }); describe('getPrevToken', function() { it('should return previous token', function() { var file = createJsFile('++x'); var xToken = file.getTokens()[1]; assert.equal(xToken.type, 'Identifier'); assert.equal(xToken.value, 'x'); var nextToken = file.getPrevToken(xToken); assert.equal(nextToken.type, 'Punctuator'); assert.equal(nextToken.value, '++'); }); it('should return undefined for out-of-range token', function() { var file = createJsFile('x'); var xToken = file.getTokens()[0]; assert.equal(xToken.type, 'Identifier'); assert.equal(xToken.value, 'x'); var nextToken = file.getPrevToken(xToken); assert.equal(nextToken, undefined); }); it('should ignore comments', function() { var file = createJsFile('/*123*/ x'); var xToken = file.getTokens()[1]; var nextToken = file.getPrevToken(xToken, {includeComments: false}); assert.equal(nextToken, undefined); }); it('should return previous comment', function() { var file = createJsFile('/*123*/ x'); var xToken = file.getTokens()[1]; var nextToken = file.getPrevToken(xToken, {includeComments: true}); assert.equal(nextToken.type, 'Block'); }); it('should return undefined next to comment', function() { var file = createJsFile('/*123*/ x'); var xToken = file.getComments()[0]; var nextToken = file.getPrevToken(xToken, {includeComments: true}); assert.equal(nextToken, undefined); }); }); describe('iterateTokensByTypeAndValue', function() { it('should match specified type', function() { var file = createJsFile('var x = 1 + 1; /*1*/ //1'); var spy = sinon.spy(); file.iterateTokensByTypeAndValue('Numeric', '1', spy); assert.equal(spy.callCount, 2); assert.equal(spy.getCall(0).args[0].type, 'Numeric'); assert.equal(spy.getCall(0).args[0].value, '1'); assert.equal(spy.getCall(1).args[0].type, 'Numeric'); assert.equal(spy.getCall(1).args[0].value, '1'); }); it('should accept value list', function() { var file = createJsFile('var x = 1 + 2 + "2"; /*1*/ //2'); var spy = sinon.spy(); file.iterateTokensByTypeAndValue('Numeric', ['1', '2'], spy); assert.equal(spy.callCount, 2); assert.equal(spy.getCall(0).args[0].type, 'Numeric'); assert.equal(spy.getCall(0).args[0].value, '1'); assert.equal(spy.getCall(1).args[0].type, 'Numeric'); assert.equal(spy.getCall(1).args[0].value, '2'); }); }); });
<?xml version="1.0" encoding="utf-8"?> <!-- Reviewed: no --> <sect1 id="zend.ldap.api" xmlns:xi="http://www.w3.org/2001/XInclude"> <title>API overview</title> <sect2 id="zend.ldap.api.configuration"> <title>Configuration / options</title> <para> The <classname>Zend_Ldap</classname> component accepts an array of options either supplied to the constructor or through the <methodname>setOptions()</methodname> method. The permitted options are as follows: </para> <table id="zend.ldap.api.configuration.table"> <title>Zend_Ldap Options</title> <tgroup cols="2"> <thead> <row> <entry>Name</entry> <entry>Description</entry> </row> </thead> <tbody> <row> <entry><property>host</property></entry> <entry> The default hostname of <acronym>LDAP</acronym> server if not supplied to <methodname>connect()</methodname> (also may be used when trying to canonicalize usernames in <methodname>bind()</methodname>). </entry> </row> <row> <entry><property>port</property></entry> <entry> Default port of <acronym>LDAP</acronym> server if not supplied to <methodname>connect()</methodname>. </entry> </row> <row> <entry><property>useStartTls</property></entry> <entry> Whether or not the <acronym>LDAP</acronym> client should use <acronym>TLS</acronym> (aka <acronym>SSLv2</acronym>) encrypted transport. A value of <constant>TRUE</constant> is strongly favored in production environments to prevent passwords from be transmitted in clear text. The default value is <constant>FALSE</constant>, as servers frequently require that a certificate be installed separately after installation. The <emphasis>useSsl</emphasis> and <emphasis>useStartTls</emphasis> options are mutually exclusive. The <emphasis>useStartTls</emphasis> option should be favored over <emphasis>useSsl</emphasis> but not all servers support this newer mechanism. </entry> </row> <row> <entry><property>useSsl</property></entry> <entry> Whether or not the <acronym>LDAP</acronym> client should use <acronym>SSL</acronym> encrypted transport. The <emphasis>useSsl</emphasis> and <emphasis>useStartTls</emphasis> options are mutually exclusive. </entry> </row> <row> <entry><property>username</property></entry> <entry> The default credentials username. Some servers require that this be in DN form. This must be given in DN form if the <acronym>LDAP</acronym> server requires a DN to bind and binding should be possible with simple usernames. </entry> </row> <row> <entry><property>password</property></entry> <entry> The default credentials password (used only with username above). </entry> </row> <row> <entry><property>bindRequiresDn</property></entry> <entry> If <constant>TRUE</constant>, this instructs <classname>Zend_Ldap</classname> to retrieve the DN for the account used to bind if the username is not already in DN form. The default value is <constant>FALSE</constant>. </entry> </row> <row> <entry><property>baseDn</property></entry> <entry> The default base DN used for searching (e.g., for accounts). This option is required for most account related operations and should indicate the DN under which accounts are located. </entry> </row> <row> <entry><property>accountCanonicalForm</property></entry> <entry> A small integer indicating the form to which account names should be canonicalized. See the <link linkend="zend.ldap.introduction.theory-of-operations.account-name-canonicalization"><emphasis>Account Name Canonicalization</emphasis></link> section below. </entry> </row> <row> <entry><property>accountDomainName</property></entry> <entry> The <acronym>FQDN</acronym> domain for which the target <acronym>LDAP</acronym> server is an authority (e.g., example.com). </entry> </row> <row> <entry><property>accountDomainNameShort</property></entry> <entry> The 'short' domain for which the target <acronym>LDAP</acronym> server is an authority. This is usually used to specify the NetBIOS domain name for Windows networks but may also be used by non-AD servers. </entry> </row> <row> <entry><property>accountFilterFormat</property></entry> <entry> The <acronym>LDAP</acronym> search filter used to search for accounts. This string is a <ulink url="http://php.net/sprintf"><methodname>sprintf()</methodname></ulink> style expression that must contain one '<emphasis>%s</emphasis>' to accommodate the username. The default value is '<emphasis>(&amp;(objectClass=user)(sAMAccountName=%s))</emphasis>' unless <emphasis>bindRequiresDn</emphasis> is set to <constant>TRUE</constant>, in which case the default is '<emphasis>(&amp;(objectClass=posixAccount)(uid=%s))</emphasis>'. Users of custom schemas may need to change this option. </entry> </row> <row> <entry><property>allowEmptyPassword</property></entry> <entry> Some <acronym>LDAP</acronym> servers can be configured to accept an empty string password as an anonymous bind. This behavior is almost always undesirable. For this reason, empty passwords are explicitly disallowed. Set this value to <constant>TRUE</constant> to allow an empty string password to be submitted during the bind. </entry> </row> <row> <entry><property>optReferrals</property></entry> <entry> If set to <constant>TRUE</constant>, this option indicates to the <acronym>LDAP</acronym> client that referrals should be followed. The default value is <constant>FALSE</constant>. </entry> </row> <row> <entry><property>tryUsernameSplit</property></entry> <entry> If set to <constant>FALSE</constant>, this option indicates that the given username should not be split at the first <emphasis>@</emphasis> or <emphasis>\</emphasis> character to separate the username from the domain during the binding-procedure. This allows the user to use usernames that contain an <emphasis>@</emphasis> or <emphasis>\</emphasis> character that do not inherit some domain-information, e.g. using email-addresses for binding. The default value is <constant>TRUE</constant>. </entry> </row> </tbody> </tgroup> </table> </sect2> <sect2 id="zend.ldap.api.reference"> <title>API Reference</title> <note> <para>Method names in <emphasis>italics</emphasis> are static methods.</para> </note> <xi:include href="Zend_Ldap-API-Ldap.xml" /> <xi:include href="Zend_Ldap-API-Ldap-Attribute.xml" /> <xi:include href="Zend_Ldap-API-Ldap-Dn.xml" /> <xi:include href="Zend_Ldap-API-Ldap-Filter.xml" /> <xi:include href="Zend_Ldap-API-Ldap-Node.xml" /> <xi:include href="Zend_Ldap-API-Ldap-Node-RootDse.xml" /> <xi:include href="Zend_Ldap-API-Ldap-Node-Schema.xml" /> <xi:include href="Zend_Ldap-API-Ldap-Ldif-Encoder.xml" /> </sect2> </sect1>
class Foo {} class Params<X extends Foo,Y> {} class Main extends Params<Foo, <caret>
**************************************************************** Version 1.0 -- First Release ********************************************************************* ********************** Documentation Of The Extension ************************** The Yii-Image-Zoomer is a extension which consists of two type of image zoom.They are: 1) Single Image Zoom: This type of zoom is used when you want to apply zoom effect on single image. 2) Multi-image Zoom: This type of zoom is used when you want to apply zoom effect on Multiple images . Yii-Image Zoomer uses Featured Image Zoomer v2.1 script from http://www.dynamicdrive.com/dynamicindex4/featuredzoomer.htm ##Requirements Yii 1.1x Tested on the following Yii Versions: Version : 1.1.13,1.1.12,1.1.11,1.1.10,1.1.9,1.1.8 and 1.1.7 ##Setup 1) Extract the downloaded file and put the extracted extension files into _[protected/extensions]_ folder of your Yii application. Rename the folder from "YiiImageZoomer-master" to "YiiImageZoomer". 2) Copy the "spinner.gif" image which comes with this extension into _[/images]_ .This image is used by script .The folder or directory "images" is created by default when you create a new yii application, it is located at "yourapplicationwebroot/images" For Example: Let's say your application name is "Music_Cart" , than the images folder is located at -[Music_Cart/images]. Directory Structure will be like : - - Music_Cart/ - - - images/ --- spinner.gif 3) To use YII-IMAGE-ZOOMER in a page, include the following code in the page: ** For Single Image Zoom Include the following code: ** <?php $this->widget('ext.YiiImageZoomer.YiiImageZoomer',array( 'multiple_zoom'=>false, 'imagefolder'=>'images', 'single_image'=>array( 'image'=>'millasmall.jpg', 'image_large'=>'hayden.jpg', 'image_alt'=>'Hayden', 'image_desc'=>'Hayden' ), 'cursorshade'=>true, 'cursorshadecolor'=>'#fff', 'cursorshadeopacity'=>0.5, 'cursorshadeborder'=>'2px solid red', 'imagevertcenter'=>true, 'magvertcenter'=>true, 'magnifierpos'=>'right', 'magnifiersize'=>array(200,200), 'width'=>200, 'height'=>300, 'zoomrange'=>array(3,10), 'initzoomablefade'=>true, 'zoomablefade'=>true, 'speed'=>300, 'zIndex'=>4, )); ?> ** For Multi-Image Zoom Include the following code: ** <?php $this->widget('ext.YiiImageZoomer.YiiImageZoomer',array( 'multiple_zoom'=>true, 'imagefolder'=>'images', 'images'=>array( array( 'image'=>'haydensmall.jpg', 'image_large'=>'hayden.jpg', 'image_thumb'=>'hayden_tmb.jpg', 'image_alt'=>'Hayden', 'image_desc'=>'Hayden'), array( 'image'=>'millasmall.jpg', 'image_large'=>'milla.jpg', 'image_thumb'=>'milla_tmb.jpg', 'image_alt'=>'Milla', 'image_desc'=>'MIlla'), array( 'image'=>'millasmall.jpg', 'image_large'=>'milla.jpg', 'image_thumb'=>'milla_tmb.jpg', 'image_alt'=>'Milla', 'image_desc'=>'MIlla'), ), 'cursorshade'=>true, 'cursorshadecolor'=>'#fff', 'cursorshadeopacity'=>0.5, 'cursorshadeborder'=>'2px solid red', 'imagevertcenter'=>true, 'magvertcenter'=>true, 'width'=>200, 'height'=>300, 'magnifierpos'=>'left', 'magnifiersize'=>array(200,200), 'zoomrange'=>array(3,10), 'initzoomablefade'=>true, 'zoomablefade'=>true, 'speed'=>300, 'zIndex'=>4, )); ?> ** About Variuos Parameters that you can customize according to your needs: ** 1) Common Parameters between Single Image Zoom and Multi-image Zoom multiple_zoom= @var boolean - used to enable or disable Multi-Image zoom when set to 'true' will enable MultiImage zoom when set to 'false' will disable MultiImage Zoom which means user wants to use single image zoom @default: none imagefolder= @var string - used to specify the images folder path @default : "/images"(By Default it will point to the "images" folder of your yii application ) Example: It can consists value like "themes/images" which means that the images are inside the "themes/images" folder. Note: Make Sure the images folder should not reside inside the protected directory if this is the case, the Yii-Image-Zoomer will not be able to access the images.So whatever location your images are located just provide the complete path to the folder in which images are located keeping in mind that folder should not reside in protected directory cursorshade= @var boolean - used to enable or disable cursorshade when set to 'true' will enable cursorshade when set to 'false' will disable cursorshade @default: false cursorshadecolor= @var string - used to specify the cursor shade colour @default : "#fff" (white color) cursorshadeopacity= @var decimal - used to specify the cursor shade opacity minimum value = 0.1 which is almost transparent. maximum value=1 which is fully opaque (as if no opacity is applied). @default : 0.1 (almost transparent) cursorshadeborder= @var string - used to specify the cursor shade border @default: '1px solid black' Example: You can set to something like '2px solid red' this will set the border of cursorshade to '2px solid red'. imagevertcenter= @var boolean - use this option if you want the image to be vertically centered within it's container when set to 'true', the image will centers vertically within its container when set to 'false' the image will not centers vertically within its container @default: false magvertcenter= @var boolean - use this option if you want the magnified area to be vertically centered in relation to the zoomable image when set to 'true',the magnified area centers vertically in relation to the zoomable image when set to 'false' the magnified area will not centers vertically in relation to the zoomable image @default: false magnifierpos= @var string - used to set the position of the magnifying area relative to the original image. when set to "right" ,the position of the magnifying area will be set to right when set to "left", the position of the magnifying area will be set to left Note: If there's not enough room for it in the window in the desired direction, it will automatically shift to the other direction. @default: 'right' magnifiersize= @var array - used to set the magnifying area's dimensions in pixels @default: Default is [200, 200] , or 200px wide by 200px tall Example: $magnifiersize=array(300,300) will set the magnifying area's dimensions to 300px wide by 300px tall width= @var int - this option lets you set the width of the zoomable image @default: undefined (script determines width of the zoomable image) height= @var int - this option lets you set the height of the zoomable image @default: undefined (script determines height of the zoomable image) initzoomablefade= @var boolean - whether or not the zoomable image should fade in automatically when the page loads if set to 'true', the zoomable image will fade when the page loads if set to 'false', the zoomable image will not fade when the page loads Note: See also zoomablefade option. If zoomablefade is set to false, this will also be false. If you are using multi-zoom, if zoomablefade is true and this option is set to false, only the first zoomable image will not fade in and rest of the images when loaded will fade in. @default: true zoomablefade= @var boolean - Sets whether or not the zoomable image within a Image Zoomer should fade in as the page loads and, if this is a multi-zoom, when the user switches between zoomable images using the thumbnail links. @default: true speed= @var int - sets the duration of fade in for zoomable images (in milliseconds) when zoomablefade is set to true @default: 600 zIndex= @var int $zIndex-In most cases the script will determine the optimal z-index to use here, so this property should only be used if there are z-index stacking problems. If there are, use it to set the z-index for created elements. It should be at least as high as the highest z-index of the zoomable (midsized) image and, if any its positioned parents @default: script determines the optimal z-index value to use . zoomrange= @var array $zoomrange- used to set the zoom level of the magnified image relative to the original image. The value should be in the form [x, y], where x and y are integers that define the lower(minimum value:3) and upper bounds(maximum value:10) of the zoom level. @default: Default is [3,10] 2) Specific Parameters of single image zoom: All the parameters are same but only one parameter is different in single image zoom as compare to multi-image zoom .It is listed below: single_image= @var array - this is where you specify the image for single image zoom @default: empty array * This parameter is an array which further containes Sub-Parameters,they are listed below * 'image'= It specifies the specifies name of zoomable image (Example: 'hayden.jpg') 'image_large'= It specifies the name of the magnified image. This should be a larger, higher resolution version of the original image (Example:hayden_large.jpg). 'image_alt'= It specifies the image alt text 'image_desc'= It specifies the image decription to be displayed Example : 'single_image'=>array( 'image'=>'millasmall.jpg', 'image'=>'hayden', 'image_large'=>'hayden.jpg', 'image_alt'=>'Hayden', 'image_desc'=>'Hayden' ) 2) Specific Parameters of Multi-image zoom: All the parameters are same but only one parameter is different in Multi-Image zoom as compare to single image zoom .It is listed below: images= @var array - this is where you specify the image for single image zoom @default: empty array * This parameter is an two-dimentional array which further containes Sub-Parameters,they are listed below * 'image'= It specifies the specifies name of zoomable image (Example: 'hayden.jpg') 'image_large'= It specifies the name of the magnified image. This should be a larger, higher resolution version of the original image (Example:hayden_large.jpg). 'image_thumb'= It specifies the name of the thumb image (Example: hayden_thumb.jpg) This should be a smaller, lower resolution version of the original image (Example:hayden_thumb.jpg). 'image_alt'= It specifies the image alt text 'image_desc'= It specifies the image decription to be displayed. Example: 'images'=>array( array( 'image'=>'haydensmall.jpg', 'image_large'=>'hayden.jpg', 'image_thumb'=>'hayden_tmb.jpg', 'image_alt'=>'Hayden', 'image_desc'=>'Hayden'), array( 'image'=>'millasmall.jpg', 'image_large'=>'milla.jpg', 'image_thumb'=>'milla_tmb.jpg', 'image_alt'=>'Milla', 'image_desc'=>'MIlla'), array( 'image'=>'millasmall.jpg', 'image_large'=>'milla.jpg', 'image_thumb'=>'milla_tmb.jpg', 'image_alt'=>'Milla', 'image_desc'=>'MIlla'), ), *********************************** Documentation Of Extension Ends Here*******************************************
package creational.abstractfactory; import creational.factory.Car; import creational.factory.CarType; public class MercedesFactory extends CarFactory { @Override public Car getCar(CarType carType) { switch (carType) { case ESTATE: return new MercedesEstateCar(); case SPORT: return new MercedesSportsCar(); case COMPACT: return new MercedesCompactCar(); default: return null; } } }
'use strict'; var assert = require('assert'); var https = require('https'); var http = require('http'); var tls = require('tls'); var net = require('net'); var util = require('util'); var selectHose = require('select-hose'); var transport = require('spdy-transport'); var debug = require('debug')('spdy:server'); var EventEmitter = require('events').EventEmitter; var spdy = require('../spdy'); var proto = {}; function instantiate(base) { function Server(options, handler) { this._init(base, options, handler); } util.inherits(Server, base); Server.create = function create(options, handler) { return new Server(options, handler); }; Object.keys(proto).forEach(function(key) { Server.prototype[key] = proto[key]; }); return Server; } proto._init = function _init(base, options, handler) { var state = {}; this._spdyState = state; state.options = options.spdy || {}; var protocols = state.options.protocols || [ 'h2', 'spdy/3.1', 'spdy/3', 'spdy/2', 'http/1.1', 'http/1.0' ]; var actualOptions = util._extend({ NPNProtocols: protocols, // Future-proof ALPNProtocols: protocols }, options); state.secure = this instanceof tls.Server; if (state.secure) base.call(this, actualOptions); else base.call(this); // Support HEADERS+FIN this.httpAllowHalfOpen = true; var event = state.secure ? 'secureConnection' : 'connection'; state.listeners = this.listeners(event).slice(); assert(state.listeners.length > 0, 'Server does not have default listeners'); this.removeAllListeners(event); if (state.options.plain) this.on(event, this._onPlainConnection); else this.on(event, this._onConnection); if (handler) this.on('request', handler); debug('server init secure=%d', state.secure); }; proto._onConnection = function _onConnection(socket) { var state = this._spdyState; var protocol; if (state.secure) protocol = socket.npnProtocol || socket.alpnProtocol; this._handleConnection(socket, protocol); }; proto._handleConnection = function _handleConnection(socket, protocol) { var state = this._spdyState; if (!protocol) protocol = state.options.protocol; debug('incoming socket protocol=%j', protocol); // No way we can do anything with the socket if (!protocol || protocol === 'http/1.1' || protocol === 'http/1.0') { debug('to default handler it goes'); return this._invokeDefault(socket); } socket.setNoDelay(true); var connection = transport.connection.create(socket, util._extend({ protocol: /spdy/.test(protocol) ? 'spdy' : 'http2', isServer: true }, state.options.connection || {})); // Set version when we are certain if (protocol === 'http2') connection.start(4); else if (protocol === 'spdy/3.1') connection.start(3.1); else if (protocol === 'spdy/3') connection.start(3); else if (protocol === 'spdy/2') connection.start(2); connection.on('error', function() { socket.destroy(); }); var self = this; connection.on('stream', function(stream) { self._onStream(stream); }); }; // HTTP2 preface var PREFACE = 'PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n'; var PREFACE_BUFFER = new Buffer(PREFACE); function hoseFilter(data, callback) { if (data.length < 1) return callback(null, null); // SPDY! if (data[0] === 0x80) return callback(null, 'spdy'); var avail = Math.min(data.length, PREFACE_BUFFER.length); for (var i = 0; i < avail; i++) if (data[i] !== PREFACE_BUFFER[i]) return callback(null, 'http/1.1'); // Not enough bytes to be sure about HTTP2 if (avail !== PREFACE_BUFFER.length) return callback(null, null); return callback(null, 'h2'); } proto._onPlainConnection = function _onPlainConnection(socket) { var hose = selectHose.create(socket, {}, hoseFilter); var self = this; hose.on('select', function(protocol, socket) { self._handleConnection(socket, protocol); }); hose.on('error', function(err) { debug('hose error %j', err.message); socket.destroy(); }); }; proto._invokeDefault = function _invokeDefault(socket) { var state = this._spdyState; for (var i = 0; i < state.listeners.length; i++) state.listeners[i].call(this, socket); }; proto._onStream = function _onStream(stream) { var state = this._spdyState; var handle = spdy.handle.create(this._spdyState.options, stream); var socketOptions = { handle: handle, allowHalfOpen: true }; var socket; if (state.secure) socket = new spdy.Socket(stream.connection.socket, socketOptions); else socket = new net.Socket(socketOptions); handle.assignSocket(socket); // For v0.8 socket.readable = true; socket.writable = true; this._invokeDefault(socket); // Add lazy `checkContinue` listener, otherwise `res.writeContinue` will be // called before the response object was patched by us. if (stream.headers.expect !== undefined && /100-continue/i.test(stream.headers.expect) && EventEmitter.listenerCount(this, 'checkContinue') === 0) { this.once('checkContinue', function(req, res) { res.writeContinue(); this.emit('request', req, res); }); } handle.emitRequest(); }; proto.emit = function emit(event, req, res) { if (event !== 'request' && event !== 'checkContinue') return EventEmitter.prototype.emit.apply(this, arguments); if (!(req.socket._handle instanceof spdy.handle)) { debug('not spdy req/res'); req.isSpdy = false; req.spdyVersion = 1; res.isSpdy = false; res.spdyVersion = 1; return EventEmitter.prototype.emit.apply(this, arguments); } var handle = req.connection._handle; req.isSpdy = true; req.spdyVersion = handle.getStream().connection.getVersion(); res.isSpdy = true; res.spdyVersion = req.spdyVersion; req.spdyStream = handle.getStream(); debug('override req/res'); res.writeHead = spdy.response.writeHead; res.end = spdy.response.end; res.push = spdy.response.push; res.writeContinue = spdy.response.writeContinue; res.spdyStream = handle.getStream(); res._req = req; handle.assignRequest(req); handle.assignResponse(res); return EventEmitter.prototype.emit.apply(this, arguments); }; exports.Server = instantiate(https.Server); exports.PlainServer = instantiate(http.Server); exports.create = function create(base, options, handler) { if (typeof base === 'object') { handler = options; options = base; base = null; } if (base) return instantiate(base).create(options, handler); if (options.spdy && options.spdy.plain) return exports.PlainServer.create(options, handler); else return exports.Server.create(options, handler); };
#ifndef WebMediaDevicesRequest_h #define WebMediaDevicesRequest_h #include "WebSecurityOrigin.h" #include "public/platform/WebCommon.h" #include "public/platform/WebPrivatePtr.h" #include "public/platform/WebString.h" namespace blink { class MediaDevicesRequest; class WebDocument; class WebMediaDeviceInfo; template <typename T> class WebVector; class WebMediaDevicesRequest { public: WebMediaDevicesRequest() { } WebMediaDevicesRequest(const WebMediaDevicesRequest& request) { assign(request); } ~WebMediaDevicesRequest() { reset(); } WebMediaDevicesRequest& operator=(const WebMediaDevicesRequest& other) { assign(other); return *this; } BLINK_EXPORT void reset(); bool isNull() const { return m_private.isNull(); } BLINK_EXPORT bool equals(const WebMediaDevicesRequest&) const; BLINK_EXPORT void assign(const WebMediaDevicesRequest&); BLINK_EXPORT WebSecurityOrigin securityOrigin() const; BLINK_EXPORT WebDocument ownerDocument() const; BLINK_EXPORT void requestSucceeded(WebVector<WebMediaDeviceInfo>); #if BLINK_IMPLEMENTATION WebMediaDevicesRequest(MediaDevicesRequest*); operator MediaDevicesRequest*() const; #endif private: WebPrivatePtr<MediaDevicesRequest> m_private; }; inline bool operator==(const WebMediaDevicesRequest& a, const WebMediaDevicesRequest& b) { return a.equals(b); } } // namespace blink #endif // WebMediaDevicesRequest_h
package org.apache.camel.language; import java.io.File; import org.apache.camel.ContextTestSupport; import org.apache.camel.Exchange; import org.apache.camel.builder.RouteBuilder; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; /** * */ public class XPathFromFileExceptionTest extends ContextTestSupport { @Override @BeforeEach public void setUp() throws Exception { deleteDirectory("target/data/xpath"); super.setUp(); } @Test public void testXPathFromFileExceptionOk() throws Exception { getMockEndpoint("mock:result").expectedMessageCount(1); getMockEndpoint("mock:error").expectedMessageCount(0); template.sendBodyAndHeader("file:target/data/xpath", "<hello>world!</hello>", Exchange.FILE_NAME, "hello.xml"); assertMockEndpointsSatisfied(); oneExchangeDone.matchesWaitTime(); File file = new File("target/data/xpath/hello.xml"); assertFalse(file.exists(), "File should not exists " + file); file = new File("target/data/xpath/ok/hello.xml"); assertTrue(file.exists(), "File should exists " + file); } @Test public void testXPathFromFileExceptionFail() throws Exception { getMockEndpoint("mock:result").expectedMessageCount(0); getMockEndpoint("mock:error").expectedMessageCount(1); // the last tag is not ended properly template.sendBodyAndHeader("file:target/data/xpath", "<hello>world!</hello", Exchange.FILE_NAME, "hello2.xml"); assertMockEndpointsSatisfied(); oneExchangeDone.matchesWaitTime(); File file = new File("target/data/xpath/hello2.xml"); assertFalse(file.exists(), "File should not exists " + file); file = new File("target/data/xpath/error/hello2.xml"); assertTrue(file.exists(), "File should exists " + file); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { from("file:target/data/xpath?initialDelay=0&delay=10&moveFailed=error&move=ok").onException(Exception.class) .to("mock:error").end().choice().when().xpath("/hello") .to("mock:result").end(); } }; } }
This repository contains a simple implementation of a SSH proxy daemon used to securely tunnel TCP connections in forward and reverse proxy mode. This tool provides equivalent functionality to using the `ssh` command's `-L` and `-R` flags. Consider using [github.com/dsnet/udptunnel](https://github.com/dsnet/udptunnel) if running behind a NAT that drops long-running TCP connections, but allows UDP traffic to reliably pass through. ## Usage ## Build the daemon: ```go get -u github.com/dsnet/sshtunnel``` Create a configuration file: ```javascript { "KeyFiles": ["/path/to/key.priv"], "KnownHostFiles": ["/path/to/known_hosts"], "Tunnels": [{ // Forward tunnel (locally binded socket proxies to remote target). "Tunnel": "bind_address:port -> dial_address:port", "Server": "user@host", }, { // Reverse tunnel (remotely binded socket proxies to local target). "Tunnel": "dial_address:port <- bind_address:port", "Server": "user@host", }], } ``` The above configuration is equivalent to running the following: ```bash ssh $USER@$HOST -i /path/to/key.priv -L $BIND_ADDRESS:$BIND_PORT:$DIAL_ADDRESS:$DIAL_PORT ssh $USER@$HOST -i /path/to/key.priv -R $BIND_ADDRESS:$BIND_PORT:$DIAL_ADDRESS:$DIAL_PORT ``` Start the daemon (assuming `$GOPATH/bin` is in your `$PATH`): ```sshtunnel /path/to/config.json```
package com.google.devtools.intellij.protoeditor.lang.psi; import com.google.common.primitives.UnsignedLong; import com.intellij.psi.PsiElement; import org.jetbrains.annotations.Nullable; /** A number value: either an integer or floating point number, "inf" or "nan". Can be negative. */ public interface ProtoNumberValue extends ProtoLiteral { /** Represents the number's format in proto source. */ enum SourceType { INTEGER, FLOAT, INF, NAN } /** Represents the radix used to specify an integer. */ enum IntegerFormat { OCT, DEC, HEX } /** Returns the child containing the number, without the optional negation. */ PsiElement getNumberElement(); /** Returns the {@link SourceType format} that this number was defined as in proto source. */ @Nullable SourceType getSourceType(); /** Returns the {@link IntegerFormat radix} that this integer was defined as in proto source. */ @Nullable default IntegerFormat getIntegerFormat() { if (getSourceType() == SourceType.INTEGER) { PsiElement numberElement = getNumberElement(); if (numberElement == null) { return null; } String numberText = numberElement.getText(); int radix = ProtoNumberValueUtil.getRadix(numberText); switch (radix) { case 8: return IntegerFormat.OCT; case 10: return IntegerFormat.DEC; case 16: return IntegerFormat.HEX; default: return null; } } return null; } /** * Returns <code>true</code> if the number was defined as a negative value. For large unsigned * 64-bit values, the actual value of the returned UnsignedLong will be negative since Java does * not support unsigned values natively. * * @return whether the value was defined as a negative number. */ boolean isNegative(); @Override @Nullable default Object getValue() { return getNumber(); } /** * Returns the value as a Long, or <code>null</code> if either SourceType is not INTEGER or the * value is larger than the bounds of a signed 64-bit integer. */ @Nullable default Long getLongValue() { PsiElement numberElement = getNumberElement(); if (numberElement == null) { return null; } if (getSourceType() == SourceType.INTEGER) { String numberText = numberElement.getText(); String negativePrefix = isNegative() ? "-" : ""; int radix = ProtoNumberValueUtil.getRadix(numberText); numberText = ProtoNumberValueUtil.trimRadixPrefix(numberText, radix); try { return Long.parseLong(negativePrefix + numberText, radix); } catch (NumberFormatException e) { return null; } } return null; } /** * Returns the value as an UnsignedLong, or <code>null</code> if SourceType is not INTEGER, the * value was defined as a negative, or the value is larger than the bounds of an unsigned 64-bit * integer. */ @Nullable default UnsignedLong getUnsignedLongValue() { if (isNegative()) { return null; } return getUnsignedLongComponent(); } /** * Returns the integer component as an UnsignedLong, ignoring an optional negation sign. Returns * <code>null</code> if SourceType is not INTEGER or the value is larger than the bounds of an * unsigned 64-bit integer. */ @Nullable default UnsignedLong getUnsignedLongComponent() { PsiElement numberElement = getNumberElement(); if (numberElement == null) { return null; } if (getSourceType() == SourceType.INTEGER) { String numberText = numberElement.getText(); int radix = ProtoNumberValueUtil.getRadix(numberText); numberText = ProtoNumberValueUtil.trimRadixPrefix(numberText, radix); try { return UnsignedLong.valueOf(numberText, radix); } catch (NumberFormatException e) { return null; } } return null; } /** * Returns the value as a Double, or <code>null</code> if the SourceType is not FLOAT, INF, or * NAN, or the value is larger than the bounds of a Double. */ @Nullable default Double getDoubleValue() { SourceType sourceType = getSourceType(); if (sourceType == null) { return null; } switch (sourceType) { case FLOAT: PsiElement numberElement = getNumberElement(); if (numberElement == null) { return null; } String numberText = numberElement.getText(); String negativePrefix = isNegative() ? "-" : ""; try { return Double.parseDouble(negativePrefix + numberText); } catch (NumberFormatException e) { return null; } case INF: return isNegative() ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY; case NAN: return Double.NaN; default: break; } return null; } /** * Returns a {@link Number} representation of the value. This will be a {@link Double} if the * value is a floating point number, a {@link Long} if the value is an integer within the range of * a 64-bit signed integer, or a {@link UnsignedLong} if the value is a non-negative integer * greater than the maximum value of a signed 64-bit integer. If the number cannot be represented * by any of Double, Long or UnsignedLong, <code>null</code> is returned. */ @Nullable default Number getNumber() { SourceType sourceType = getSourceType(); if (sourceType != null) { switch (getSourceType()) { case FLOAT: case INF: case NAN: return getDoubleValue(); case INTEGER: Long longValue = getLongValue(); return longValue != null ? longValue : getUnsignedLongValue(); } } return null; } /** Returns <code>true</code> if this value represents a valid double. */ default boolean isValidDouble() { return getDoubleValue() != null; } /** Returns <code>true</code> if this value represents a valid int32. */ default boolean isValidInt32() { Long value = getLongValue(); return value != null && value >= Integer.MIN_VALUE && value <= Integer.MAX_VALUE; } /** Returns <code>true</code> if this value represents a valid uint32. */ default boolean isValidUint32() { if (isNegative()) { return false; } Long value = getLongValue(); return value != null && value >= 0 && value <= 0xFFFFFFFFL; } /** Returns <code>true</code> if this value represents a valid 64-bit signed integer. */ default boolean isValidInt64() { return getLongValue() != null; } /** Returns <code>true</code> if this value represents a valid 64-bit unsigned integer. */ default boolean isValidUint64() { return getUnsignedLongValue() != null; } /** * Returns <code>true</code> if this value represents a valid 65-bit signed integer. * * <p>Proto allows default values for float and double types to be set to -0xFFFFFFFFFFFFFFFF, a * value which is not a valid unsigned 64-bit int. The acceptance of the sign bit effectively * makes the value a signed 65-bit integer. */ default boolean isValidInt65() { return getUnsignedLongComponent() != null; } }
package com.sino.scaffold.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import com.baomidou.mybatisplus.plugins.Page; import com.sino.scaffold.biz.UserService; /** * @author kerbores * */ @Controller @RequestMapping("beetl") public class BeetlController { @Autowired UserService userService; @GetMapping("/") public String index(Model model) { model.addAttribute("test", "Hello Beetl"); model.addAttribute("users", userService.selectPage(new Page<>(0, Integer.MAX_VALUE)).getRecords()); return "index.btl"; } }
/** * This package contains the annotations and support classes you need as a user of lombok, for * all features which aren't (yet) supported as a first class feature. Features that involve the * annotations and support classes in this package may change or may be removed entirely in future versions, * and bugs may not be solved as expediently. For the status and likely future of any feature, refer * to the official feature documentation. * * @see lombok * @see <a href="https://projectlombok.org/features/experimental/all">Lombok features (experimental)</a> */ package lombok.experimental;
import asyncore import unittest import select import os import socket import sys import time import warnings import errno from test import support from test.support import TESTFN, run_unittest, unlink from io import BytesIO from io import StringIO try: import threading except ImportError: threading = None HOST = support.HOST class dummysocket: def __init__(self): self.closed = False def close(self): self.closed = True def fileno(self): return 42 class dummychannel: def __init__(self): self.socket = dummysocket() def close(self): self.socket.close() class exitingdummy: def __init__(self): pass def handle_read_event(self): raise asyncore.ExitNow() handle_write_event = handle_read_event handle_close = handle_read_event handle_expt_event = handle_read_event class crashingdummy: def __init__(self): self.error_handled = False def handle_read_event(self): raise Exception() handle_write_event = handle_read_event handle_close = handle_read_event handle_expt_event = handle_read_event def handle_error(self): self.error_handled = True # used when testing senders; just collects what it gets until newline is sent def capture_server(evt, buf, serv): try: serv.listen(5) conn, addr = serv.accept() except socket.timeout: pass else: n = 200 while n > 0: r, w, e = select.select([conn], [], []) if r: data = conn.recv(10) # keep everything except for the newline terminator buf.write(data.replace(b'\n', b'')) if b'\n' in data: break n -= 1 time.sleep(0.01) conn.close() finally: serv.close() evt.set() class HelperFunctionTests(unittest.TestCase): def test_readwriteexc(self): # Check exception handling behavior of read, write and _exception # check that ExitNow exceptions in the object handler method # bubbles all the way up through asyncore read/write/_exception calls tr1 = exitingdummy() self.assertRaises(asyncore.ExitNow, asyncore.read, tr1) self.assertRaises(asyncore.ExitNow, asyncore.write, tr1) self.assertRaises(asyncore.ExitNow, asyncore._exception, tr1) # check that an exception other than ExitNow in the object handler # method causes the handle_error method to get called tr2 = crashingdummy() asyncore.read(tr2) self.assertEqual(tr2.error_handled, True) tr2 = crashingdummy() asyncore.write(tr2) self.assertEqual(tr2.error_handled, True) tr2 = crashingdummy() asyncore._exception(tr2) self.assertEqual(tr2.error_handled, True) # asyncore.readwrite uses constants in the select module that # are not present in Windows systems (see this thread: # http://mail.python.org/pipermail/python-list/2001-October/109973.html) # These constants should be present as long as poll is available @unittest.skipUnless(hasattr(select, 'poll'), 'select.poll required') def test_readwrite(self): # Check that correct methods are called by readwrite() attributes = ('read', 'expt', 'write', 'closed', 'error_handled') expected = ( (select.POLLIN, 'read'), (select.POLLPRI, 'expt'), (select.POLLOUT, 'write'), (select.POLLERR, 'closed'), (select.POLLHUP, 'closed'), (select.POLLNVAL, 'closed'), ) class testobj: def __init__(self): self.read = False self.write = False self.closed = False self.expt = False self.error_handled = False def handle_read_event(self): self.read = True def handle_write_event(self): self.write = True def handle_close(self): self.closed = True def handle_expt_event(self): self.expt = True def handle_error(self): self.error_handled = True for flag, expectedattr in expected: tobj = testobj() self.assertEqual(getattr(tobj, expectedattr), False) asyncore.readwrite(tobj, flag) # Only the attribute modified by the routine we expect to be # called should be True. for attr in attributes: self.assertEqual(getattr(tobj, attr), attr==expectedattr) # check that ExitNow exceptions in the object handler method # bubbles all the way up through asyncore readwrite call tr1 = exitingdummy() self.assertRaises(asyncore.ExitNow, asyncore.readwrite, tr1, flag) # check that an exception other than ExitNow in the object handler # method causes the handle_error method to get called tr2 = crashingdummy() self.assertEqual(tr2.error_handled, False) asyncore.readwrite(tr2, flag) self.assertEqual(tr2.error_handled, True) def test_closeall(self): self.closeall_check(False) def test_closeall_default(self): self.closeall_check(True) def closeall_check(self, usedefault): # Check that close_all() closes everything in a given map l = [] testmap = {} for i in range(10): c = dummychannel() l.append(c) self.assertEqual(c.socket.closed, False) testmap[i] = c if usedefault: socketmap = asyncore.socket_map try: asyncore.socket_map = testmap asyncore.close_all() finally: testmap, asyncore.socket_map = asyncore.socket_map, socketmap else: asyncore.close_all(testmap) self.assertEqual(len(testmap), 0) for c in l: self.assertEqual(c.socket.closed, True) def test_compact_traceback(self): try: raise Exception("I don't like spam!") except: real_t, real_v, real_tb = sys.exc_info() r = asyncore.compact_traceback() else: self.fail("Expected exception") (f, function, line), t, v, info = r self.assertEqual(os.path.split(f)[-1], 'test_asyncore.py') self.assertEqual(function, 'test_compact_traceback') self.assertEqual(t, real_t) self.assertEqual(v, real_v) self.assertEqual(info, '[%s|%s|%s]' % (f, function, line)) class DispatcherTests(unittest.TestCase): def setUp(self): pass def tearDown(self): asyncore.close_all() def test_basic(self): d = asyncore.dispatcher() self.assertEqual(d.readable(), True) self.assertEqual(d.writable(), True) def test_repr(self): d = asyncore.dispatcher() self.assertEqual(repr(d), '<asyncore.dispatcher at %#x>' % id(d)) def test_log(self): d = asyncore.dispatcher() # capture output of dispatcher.log() (to stderr) fp = StringIO() stderr = sys.stderr l1 = "Lovely spam! Wonderful spam!" l2 = "I don't like spam!" try: sys.stderr = fp d.log(l1) d.log(l2) finally: sys.stderr = stderr lines = fp.getvalue().splitlines() self.assertEqual(lines, ['log: %s' % l1, 'log: %s' % l2]) def test_log_info(self): d = asyncore.dispatcher() # capture output of dispatcher.log_info() (to stdout via print) fp = StringIO() stdout = sys.stdout l1 = "Have you got anything without spam?" l2 = "Why can't she have egg bacon spam and sausage?" l3 = "THAT'S got spam in it!" try: sys.stdout = fp d.log_info(l1, 'EGGS') d.log_info(l2) d.log_info(l3, 'SPAM') finally: sys.stdout = stdout lines = fp.getvalue().splitlines() expected = ['EGGS: %s' % l1, 'info: %s' % l2, 'SPAM: %s' % l3] self.assertEqual(lines, expected) def test_unhandled(self): d = asyncore.dispatcher() d.ignore_log_types = () # capture output of dispatcher.log_info() (to stdout via print) fp = StringIO() stdout = sys.stdout try: sys.stdout = fp d.handle_expt() d.handle_read() d.handle_write() d.handle_connect() finally: sys.stdout = stdout lines = fp.getvalue().splitlines() expected = ['warning: unhandled incoming priority event', 'warning: unhandled read event', 'warning: unhandled write event', 'warning: unhandled connect event'] self.assertEqual(lines, expected) def test_issue_8594(self): # XXX - this test is supposed to be removed in next major Python # version d = asyncore.dispatcher(socket.socket()) # make sure the error message no longer refers to the socket # object but the dispatcher instance instead self.assertRaisesRegex(AttributeError, 'dispatcher instance', getattr, d, 'foo') # cheap inheritance with the underlying socket is supposed # to still work but a DeprecationWarning is expected with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") family = d.family self.assertEqual(family, socket.AF_INET) self.assertEqual(len(w), 1) self.assertTrue(issubclass(w[0].category, DeprecationWarning)) def test_strerror(self): # refers to bug #8573 err = asyncore._strerror(errno.EPERM) if hasattr(os, 'strerror'): self.assertEqual(err, os.strerror(errno.EPERM)) err = asyncore._strerror(-1) self.assertTrue(err != "") class dispatcherwithsend_noread(asyncore.dispatcher_with_send): def readable(self): return False def handle_connect(self): pass class DispatcherWithSendTests(unittest.TestCase): usepoll = False def setUp(self): pass def tearDown(self): asyncore.close_all() @unittest.skipUnless(threading, 'Threading required for this test.') @support.reap_threads def test_send(self): evt = threading.Event() sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(3) port = support.bind_port(sock) cap = BytesIO() args = (evt, cap, sock) t = threading.Thread(target=capture_server, args=args) t.start() try: # wait a little longer for the server to initialize (it sometimes # refuses connections on slow machines without this wait) time.sleep(0.2) data = b"Suppose there isn't a 16-ton weight?" d = dispatcherwithsend_noread() d.create_socket(socket.AF_INET, socket.SOCK_STREAM) d.connect((HOST, port)) # give time for socket to connect time.sleep(0.1) d.send(data) d.send(data) d.send(b'\n') n = 1000 while d.out_buffer and n > 0: asyncore.poll() n -= 1 evt.wait() self.assertEqual(cap.getvalue(), data*2) finally: t.join() class DispatcherWithSendTests_UsePoll(DispatcherWithSendTests): usepoll = True @unittest.skipUnless(hasattr(asyncore, 'file_wrapper'), 'asyncore.file_wrapper required') class FileWrapperTest(unittest.TestCase): def setUp(self): self.d = b"It's not dead, it's sleeping!" with open(TESTFN, 'wb') as file: file.write(self.d) def tearDown(self): unlink(TESTFN) def test_recv(self): fd = os.open(TESTFN, os.O_RDONLY) w = asyncore.file_wrapper(fd) os.close(fd) self.assertNotEqual(w.fd, fd) self.assertNotEqual(w.fileno(), fd) self.assertEqual(w.recv(13), b"It's not dead") self.assertEqual(w.read(6), b", it's") w.close() self.assertRaises(OSError, w.read, 1) def test_send(self): d1 = b"Come again?" d2 = b"I want to buy some cheese." fd = os.open(TESTFN, os.O_WRONLY | os.O_APPEND) w = asyncore.file_wrapper(fd) os.close(fd) w.write(d1) w.send(d2) w.close() with open(TESTFN, 'rb') as file: self.assertEqual(file.read(), self.d + d1 + d2) @unittest.skipUnless(hasattr(asyncore, 'file_dispatcher'), 'asyncore.file_dispatcher required') def test_dispatcher(self): fd = os.open(TESTFN, os.O_RDONLY) data = [] class FileDispatcher(asyncore.file_dispatcher): def handle_read(self): data.append(self.recv(29)) s = FileDispatcher(fd) os.close(fd) asyncore.loop(timeout=0.01, use_poll=True, count=2) self.assertEqual(b"".join(data), self.d) class BaseTestHandler(asyncore.dispatcher): def __init__(self, sock=None): asyncore.dispatcher.__init__(self, sock) self.flag = False def handle_accept(self): raise Exception("handle_accept not supposed to be called") def handle_accepted(self): raise Exception("handle_accepted not supposed to be called") def handle_connect(self): raise Exception("handle_connect not supposed to be called") def handle_expt(self): raise Exception("handle_expt not supposed to be called") def handle_close(self): raise Exception("handle_close not supposed to be called") def handle_error(self): raise class TCPServer(asyncore.dispatcher): """A server which listens on an address and dispatches the connection to a handler. """ def __init__(self, handler=BaseTestHandler, host=HOST, port=0): asyncore.dispatcher.__init__(self) self.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.set_reuse_addr() self.bind((host, port)) self.listen(5) self.handler = handler @property def address(self): return self.socket.getsockname()[:2] def handle_accepted(self, sock, addr): self.handler(sock) def handle_error(self): raise class BaseClient(BaseTestHandler): def __init__(self, address): BaseTestHandler.__init__(self) self.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.connect(address) def handle_connect(self): pass class BaseTestAPI(unittest.TestCase): def tearDown(self): asyncore.close_all() def loop_waiting_for_flag(self, instance, timeout=5): timeout = float(timeout) / 100 count = 100 while asyncore.socket_map and count > 0: asyncore.loop(timeout=0.01, count=1, use_poll=self.use_poll) if instance.flag: return count -= 1 time.sleep(timeout) self.fail("flag not set") def test_handle_connect(self): # make sure handle_connect is called on connect() class TestClient(BaseClient): def handle_connect(self): self.flag = True server = TCPServer() client = TestClient(server.address) self.loop_waiting_for_flag(client) def test_handle_accept(self): # make sure handle_accept() is called when a client connects class TestListener(BaseTestHandler): def __init__(self): BaseTestHandler.__init__(self) self.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.bind((HOST, 0)) self.listen(5) self.address = self.socket.getsockname()[:2] def handle_accept(self): self.flag = True server = TestListener() client = BaseClient(server.address) self.loop_waiting_for_flag(server) def test_handle_accepted(self): # make sure handle_accepted() is called when a client connects class TestListener(BaseTestHandler): def __init__(self): BaseTestHandler.__init__(self) self.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.bind((HOST, 0)) self.listen(5) self.address = self.socket.getsockname()[:2] def handle_accept(self): asyncore.dispatcher.handle_accept(self) def handle_accepted(self, sock, addr): sock.close() self.flag = True server = TestListener() client = BaseClient(server.address) self.loop_waiting_for_flag(server) def test_handle_read(self): # make sure handle_read is called on data received class TestClient(BaseClient): def handle_read(self): self.flag = True class TestHandler(BaseTestHandler): def __init__(self, conn): BaseTestHandler.__init__(self, conn) self.send(b'x' * 1024) server = TCPServer(TestHandler) client = TestClient(server.address) self.loop_waiting_for_flag(client) def test_handle_write(self): # make sure handle_write is called class TestClient(BaseClient): def handle_write(self): self.flag = True server = TCPServer() client = TestClient(server.address) self.loop_waiting_for_flag(client) def test_handle_close(self): # make sure handle_close is called when the other end closes # the connection class TestClient(BaseClient): def handle_read(self): # in order to make handle_close be called we are supposed # to make at least one recv() call self.recv(1024) def handle_close(self): self.flag = True self.close() class TestHandler(BaseTestHandler): def __init__(self, conn): BaseTestHandler.__init__(self, conn) self.close() server = TCPServer(TestHandler) client = TestClient(server.address) self.loop_waiting_for_flag(client) @unittest.skipIf(sys.platform.startswith("sunos"), "OOB support is broken on Solaris") def test_handle_expt(self): # Make sure handle_expt is called on OOB data received. # Note: this might fail on some platforms as OOB data is # tenuously supported and rarely used. class TestClient(BaseClient): def handle_expt(self): self.flag = True class TestHandler(BaseTestHandler): def __init__(self, conn): BaseTestHandler.__init__(self, conn) self.socket.send(bytes(chr(244), 'latin-1'), socket.MSG_OOB) server = TCPServer(TestHandler) client = TestClient(server.address) self.loop_waiting_for_flag(client) def test_handle_error(self): class TestClient(BaseClient): def handle_write(self): 1.0 / 0 def handle_error(self): self.flag = True try: raise except ZeroDivisionError: pass else: raise Exception("exception not raised") server = TCPServer() client = TestClient(server.address) self.loop_waiting_for_flag(client) def test_connection_attributes(self): server = TCPServer() client = BaseClient(server.address) # we start disconnected self.assertFalse(server.connected) self.assertTrue(server.accepting) # this can't be taken for granted across all platforms #self.assertFalse(client.connected) self.assertFalse(client.accepting) # execute some loops so that client connects to server asyncore.loop(timeout=0.01, use_poll=self.use_poll, count=100) self.assertFalse(server.connected) self.assertTrue(server.accepting) self.assertTrue(client.connected) self.assertFalse(client.accepting) # disconnect the client client.close() self.assertFalse(server.connected) self.assertTrue(server.accepting) self.assertFalse(client.connected) self.assertFalse(client.accepting) # stop serving server.close() self.assertFalse(server.connected) self.assertFalse(server.accepting) def test_create_socket(self): s = asyncore.dispatcher() s.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.assertEqual(s.socket.family, socket.AF_INET) SOCK_NONBLOCK = getattr(socket, 'SOCK_NONBLOCK', 0) self.assertEqual(s.socket.type, socket.SOCK_STREAM | SOCK_NONBLOCK) def test_bind(self): s1 = asyncore.dispatcher() s1.create_socket(socket.AF_INET, socket.SOCK_STREAM) s1.bind((HOST, 0)) s1.listen(5) port = s1.socket.getsockname()[1] s2 = asyncore.dispatcher() s2.create_socket(socket.AF_INET, socket.SOCK_STREAM) # EADDRINUSE indicates the socket was correctly bound self.assertRaises(socket.error, s2.bind, (HOST, port)) def test_set_reuse_addr(self): sock = socket.socket() try: sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) except socket.error: unittest.skip("SO_REUSEADDR not supported on this platform") else: # if SO_REUSEADDR succeeded for sock we expect asyncore # to do the same s = asyncore.dispatcher(socket.socket()) self.assertFalse(s.socket.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)) s.socket.close() s.create_socket(socket.AF_INET, socket.SOCK_STREAM) s.set_reuse_addr() self.assertTrue(s.socket.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)) finally: sock.close() class TestAPI_UseSelect(BaseTestAPI): use_poll = False @unittest.skipUnless(hasattr(select, 'poll'), 'select.poll required') class TestAPI_UsePoll(BaseTestAPI): use_poll = True def test_main(): tests = [HelperFunctionTests, DispatcherTests, DispatcherWithSendTests, DispatcherWithSendTests_UsePoll, TestAPI_UseSelect, TestAPI_UsePoll, FileWrapperTest] run_unittest(*tests) if __name__ == "__main__": test_main()
local Class = require "lib.hump.Class" local InputComponent = require "component.input.InputComponent" local Signals = require "constants.Signals" local EntityTypes = require "constants.EntityTypes" local Constants = require "constants.Constants" local BulletInputComponent = Class{} BulletInputComponent:include(InputComponent) function BulletInputComponent:init() self._bullet = true InputComponent.init(self) end function BulletInputComponent:conception() self._velNormDenominator = self.owner.movement:getTerminalVelocity() * 2 InputComponent.conception(self) end function BulletInputComponent:update(dt) -- Slight movement in the owner's direction, normalized to be a number between 0 and 1, (but really way less than 1, at 1 it will move diagonally when owner is moving at max speed orthogonally to the shoot direction) local xVel, yVel = self.owner.movement:getVelocity() xVel = xVel / self._velNormDenominator yVel = yVel / self._velNormDenominator if love.keyboard.isDown("left") then if self._bullet then local x, y = self.owner.body:center() Signal.emit(Signals.ADD_ENTITY, EntityCreator.create(EntityTypes.BULLET, x - Constants.TILE_SIZE, y, -1, yVel)) self:_bulletCooldown() end end if love.keyboard.isDown("up") then if self._bullet then local x, y = self.owner.body:center() Signal.emit(Signals.ADD_ENTITY, EntityCreator.create(EntityTypes.BULLET, x, y - Constants.TILE_SIZE, xVel, -1)) self:_bulletCooldown() end end if love.keyboard.isDown("right") then if self._bullet then local x, y = self.owner.body:center() Signal.emit(Signals.ADD_ENTITY, EntityCreator.create(EntityTypes.BULLET, x + Constants.TILE_SIZE, y, 1, yVel)) self:_bulletCooldown() end end if love.keyboard.isDown("down") then if self._bullet then local x, y = self.owner.body:center() Signal.emit(Signals.ADD_ENTITY, EntityCreator.create(EntityTypes.BULLET, x, y + Constants.TILE_SIZE, xVel, 1)) self:_bulletCooldown() end end InputComponent.update(self, dt) end function BulletInputComponent:_bulletCooldown() self._bullet = false if Constants.BULLET_COOLDOWN > 0 then game.timer:after(Constants.BULLET_COOLDOWN, function() self._bullet = true end) end end return BulletInputComponent
package org.mini2Dx.ui.element; import org.mini2Dx.core.graphics.TextureRegion; import org.mini2Dx.core.serialization.annotation.ConstructorArg; import org.mini2Dx.core.serialization.annotation.Field; import org.mini2Dx.ui.render.ImageButtonRenderNode; import org.mini2Dx.ui.render.ParentRenderNode; import com.badlogic.gdx.assets.AssetManager; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.TextureAtlas; /** * Implementation of {@link Button} that only contains an image */ public class ImageButton extends Button { private ImageButtonRenderNode renderNode; private TextureRegion textureRegion; @Field(optional=true) private String texturePath; @Field(optional = true) private String atlas; @Field(optional=true) private boolean responsive = false; /** * Constructor. Generates a unique ID for this {@link ImageButton} */ public ImageButton() { super(); } /** * Constructor * @param id The unique ID for this {@link ImageButton} */ public ImageButton(@ConstructorArg(clazz=String.class, name = "id") String id) { super(id); } /** * Returns the current {@link TextureRegion} for this {@link ImageButton} * * @param assetManager * The game's {@link AssetManager} * @return Null if no {@link TextureRegion} has been set */ public TextureRegion getTextureRegion(AssetManager assetManager) { if (atlas != null) { if (texturePath != null) { TextureAtlas textureAtlas = assetManager.get(atlas, TextureAtlas.class); textureRegion = new TextureRegion(textureAtlas.findRegion(texturePath)); texturePath = null; } } else if (texturePath != null) { textureRegion = new TextureRegion(assetManager.get(texturePath, Texture.class)); texturePath = null; } return textureRegion; } /** * Sets the current {@link TextureRegion} used by this {@link ImageButton} * * @param textureRegion * The {@link TextureRegion} to use */ public void setTextureRegion(TextureRegion textureRegion) { this.textureRegion = textureRegion; if(renderNode == null) { return; } renderNode.setDirty(true); } /** * Sets the current {@link Texture} used by this {@link ImageButton} * * @param texture * The {@link Texture} to use */ public void setTexture(Texture texture) { setTextureRegion(new TextureRegion(texture)); } /** * Sets the current texture path. This will set the current * {@link TextureRegion} by loading it via the {@link AssetManager} * * @param texturePath * The path to the texture */ public void setTexturePath(String texturePath) { this.texturePath = texturePath; if(renderNode == null) { return; } renderNode.setDirty(true); } /** * Returns the atlas (if any) to look up the texture in * @return Null by default */ public String getAtlas() { return atlas; } /** * Sets the atlas to look up the texture in * @param atlas Null if the texture should not be looked up via an atlas */ public void setAtlas(String atlas) { this.atlas = atlas; if (renderNode == null) { return; } renderNode.setDirty(true); } /** * Returns if the image should scale to the size of the {@link ImageButton} * @return False by default */ public boolean isResponsive() { return responsive; } /** * Sets if the image should scale to the size of the {@link ImageButton} * @param responsive */ public void setResponsive(boolean responsive) { this.responsive = responsive; if(renderNode == null) { return; } renderNode.setDirty(true); } @Override public void attach(ParentRenderNode<?, ?> parentRenderNode) { if(renderNode != null) { return; } renderNode = new ImageButtonRenderNode(parentRenderNode, this); parentRenderNode.addChild(renderNode); } @Override public void detach(ParentRenderNode<?, ?> parentRenderNode) { if(renderNode == null) { return; } parentRenderNode.removeChild(renderNode); renderNode = null; } @Override public void setVisibility(Visibility visibility) { if(this.visibility == visibility) { return; } this.visibility = visibility; if(renderNode == null) { return; } renderNode.setDirty(true); } @Override public void setStyleId(String styleId) { if(styleId == null) { return; } if(this.styleId.equals(styleId)) { return; } this.styleId = styleId; if(renderNode == null) { return; } renderNode.setDirty(true); } @Override public void syncWithRenderNode() { while(!effects.isEmpty()) { renderNode.applyEffect(effects.poll()); } } @Override public void setZIndex(int zIndex) { this.zIndex = zIndex; if(renderNode == null) { return; } renderNode.setDirty(true); } @Override public void setLayout(String layout) { if(layout == null) { return; } this.layout = layout; if(renderNode == null) { return; } renderNode.setDirty(true); } }
package org.kie.server.api.model.definition; import java.util.HashMap; import java.util.Map; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlRootElement; @XmlAccessorType(XmlAccessType.FIELD) @XmlRootElement(name = "process-task-inputs") public class TaskInputsDefinition { @XmlElementWrapper(name="inputs") private Map<String, String> taskInputs; public TaskInputsDefinition() { this(new HashMap<String, String>()); } public TaskInputsDefinition(Map<String, String> taskInputs) { this.taskInputs = taskInputs; } public Map<String, String> getTaskInputs() { return taskInputs; } public void setTaskInputs(Map<String, String> taskInputs) { this.taskInputs = taskInputs; } @Override public String toString() { return "TaskInputsDefinition{" + "taskInputs=" + taskInputs + '}'; } }
var baseFlatten = require('../internal/baseFlatten'); /** * Recursively flattens a nested array. * * @static * @memberOf _ * @category Array * @param {Array} array The array to recursively flatten. * @returns {Array} Returns the new flattened array. * @example * * _.flattenDeep([1, [2, 3, [4]]]); * // => [1, 2, 3, 4]; */ function flattenDeep(array) { var length = array ? array.length : 0; return length ? baseFlatten(array, true) : []; } module.exports = flattenDeep;
<?php namespace Symfony\Component\Translation\Dumper; use Symfony\Component\Translation\MessageCatalogue; /** * PhpFileDumper generates PHP files from a message catalogue. * * @author Michel Salib <michelsalib@hotmail.com> */ class PhpFileDumper extends FileDumper { /** * {@inheritdoc} */ public function formatCatalogue(MessageCatalogue $messages, string $domain, array $options = []) { return "<?php\n\nreturn ".var_export($messages->all($domain), true).";\n"; } /** * {@inheritdoc} */ protected function getExtension() { return 'php'; } }
"use strict"; var keyMirror = require('keyMirror'); /** * When a component's children are updated, a series of update configuration * objects are created in order to batch and serialize the required changes. * * Enumerates all the possible types of update configurations. * * @internal */ var ReactMultiChildUpdateTypes = keyMirror({ INSERT_MARKUP: null, MOVE_EXISTING: null, REMOVE_NODE: null, TEXT_CONTENT: null }); module.exports = ReactMultiChildUpdateTypes;
package com.mossle.bridge.userrepo; import java.io.IOException; import javax.annotation.Resource; import com.mossle.api.userrepo.UserRepoCache; import com.mossle.api.userrepo.UserRepoDTO; import com.mossle.core.mapper.JsonMapper; import com.mossle.ext.message.Subscribable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class UserRepoSubscriber implements Subscribable<String> { private static Logger logger = LoggerFactory .getLogger(UserRepoSubscriber.class); private JsonMapper jsonMapper = new JsonMapper(); private UserRepoCache userRepoCache; private String destinationName = "topic.userrepo.update"; public void handleMessage(String message) { try { UserRepoDTO userRepoDto = jsonMapper.fromJson(message, UserRepoDTO.class); if (userRepoDto.getName() == null) { userRepoCache.removeUserRepo(userRepoDto); logger.info("remove userRepoDto : {}", message); } else { userRepoCache.updateUserRepo(userRepoDto); logger.info("update userRepoDto : {}", message); } } catch (IOException ex) { logger.error(ex.getMessage(), ex); } } public boolean isTopic() { return true; } public String getName() { return destinationName; } @Resource public void setUserRepoCache(UserRepoCache userRepoCache) { this.userRepoCache = userRepoCache; } public void setDestinationName(String destinationName) { this.destinationName = destinationName; } }
///////////////////////////////////////////////////////////////////////////////// // // // AliFemtoPairCutRadialDistance - a pair cut which checks // // for some pair qualities that attempt to identify slit/doubly // // reconstructed tracks and also selects pairs based on their separation // // at the entrance to the TPC // // // ///////////////////////////////////////////////////////////////////////////////// /******************************************************************************** * * Authors: Johanna Gramling, University of Heidelberg, jgramlin@cern.ch * Malgorzata Janik, Warsaw University of Technology, majanik@cern.ch * Lukasz Graczykowski, Warsaw University of Technology, lgraczyk@cern.ch * ********************************************************************************/ #ifndef ALIFEMTOPAIRCUTRADIALDISTANCE_H #define ALIFEMTOPAIRCUTRADIALDISTANCE_H // do I need these lines ? //#ifndef StMaker_H //#include "StMaker.h" //#endif #include "AliFemtoPairCut.h" #include "AliFemtoShareQualityPairCut.h" #include "AliFemtoPairCutAntiGamma.h" #include "AliAODInputHandler.h" #include "AliAnalysisManager.h" class AliFemtoPairCutRadialDistance : public AliFemtoPairCutAntiGamma { public: AliFemtoPairCutRadialDistance(); AliFemtoPairCutRadialDistance(const AliFemtoPairCutRadialDistance& c); virtual ~AliFemtoPairCutRadialDistance(); AliFemtoPairCutRadialDistance& operator=(const AliFemtoPairCutRadialDistance& c); virtual bool Pass(const AliFemtoPair* pair); virtual AliFemtoString Report(); virtual TList *ListSettings(); virtual AliFemtoPairCut* Clone(); void SetPhiStarDifferenceMinimum(double dtpc); void SetEtaDifferenceMinimum(double etpc); void SetMinimumRadius(double minrad); void SetMaximumRadius(double maxrad); void SetMagneticFieldSign(int magsign); void SetPhiStarMin(Bool_t); protected: Double_t fDPhiStarMin; // Minimum allowed pair separation //at the specified radius //Double_t fRadius; // Radius at which the separation is calculated Double_t fEtaMin; // Minimum allowed pair separation in eta Double_t fMinRad; Double_t fMaxRad; Int_t fMagSign; Bool_t fPhistarmin; #ifdef __ROOT__ ClassDef(AliFemtoPairCutRadialDistance, 0) #endif }; inline AliFemtoPairCut* AliFemtoPairCutRadialDistance::Clone() { AliFemtoPairCutRadialDistance* c = new AliFemtoPairCutRadialDistance(*this); return c;} #endif
using blink::WebString; using blink::WebURLResponse; namespace content { // Inputs & expected output for GetReasonsForUncacheability. struct GRFUTestCase { WebURLResponse::HTTPVersion version; int status_code; const char* headers; uint32 expected_reasons; }; // Create a new WebURLResponse object. static WebURLResponse CreateResponse(const GRFUTestCase& test) { WebURLResponse response; response.initialize(); response.setHTTPVersion(test.version); response.setHTTPStatusCode(test.status_code); std::vector<std::string> lines; Tokenize(test.headers, "\n", &lines); for (size_t i = 0; i < lines.size(); ++i) { size_t colon = lines[i].find(": "); response.addHTTPHeaderField( WebString::fromUTF8(lines[i].substr(0, colon)), WebString::fromUTF8(lines[i].substr(colon + 2))); } return response; } TEST(CacheUtilTest, GetReasonsForUncacheability) { enum { kNoReasons = 0 }; const GRFUTestCase tests[] = { { WebURLResponse::HTTP_1_1, 206, "ETag: 'fooblort'", kNoReasons }, { WebURLResponse::HTTP_1_1, 206, "", kNoStrongValidatorOnPartialResponse }, { WebURLResponse::HTTP_1_0, 206, "", kPre11PartialResponse | kNoStrongValidatorOnPartialResponse }, { WebURLResponse::HTTP_1_1, 200, "cache-control: max-Age=42", kShortMaxAge }, { WebURLResponse::HTTP_1_1, 200, "cache-control: max-Age=4200", kNoReasons }, { WebURLResponse::HTTP_1_1, 200, "Date: Tue, 22 May 2012 23:46:08 GMT\n" "Expires: Tue, 22 May 2012 23:56:08 GMT", kExpiresTooSoon }, { WebURLResponse::HTTP_1_1, 200, "cache-control: must-revalidate", kHasMustRevalidate }, { WebURLResponse::HTTP_1_1, 200, "cache-control: no-cache", kNoCache }, { WebURLResponse::HTTP_1_1, 200, "cache-control: no-store", kNoStore }, { WebURLResponse::HTTP_1_1, 200, "cache-control: no-cache\ncache-control: no-store", kNoCache | kNoStore }, }; for (size_t i = 0; i < arraysize(tests); ++i) { SCOPED_TRACE(base::StringPrintf("case: %" PRIuS ", version: %d, code: %d, headers: %s", i, tests[i].version, tests[i].status_code, tests[i].headers)); EXPECT_EQ(GetReasonsForUncacheability(CreateResponse(tests[i])), tests[i].expected_reasons); } } } // namespace content
<!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 (version 1.7.0_45) on Tue Mar 18 13:16:09 EDT 2014 --> <title>TextFont</title> <meta name="date" content="2014-03-18"> <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="TextFont"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">com.inverseinnovations.MALSignatureDesigner</div> <h2 title="Class TextFont" class="title">Class TextFont</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>com.inverseinnovations.MALSignatureDesigner.TextFont</li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <hr> <br> <pre>public class <span class="strong">TextFont</span> extends java.lang.Object</pre> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ======== 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">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><strong><a href="../../../com/inverseinnovations/MALSignatureDesigner/TextFont.html#TextFont()">TextFont</a></strong>()</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colOne"><code><strong><a href="../../../com/inverseinnovations/MALSignatureDesigner/TextFont.html#TextFont(java.lang.String, int)">TextFont</a></strong>(java.lang.String&nbsp;fontName, int&nbsp;size)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colOne"><code><strong><a href="../../../com/inverseinnovations/MALSignatureDesigner/TextFont.html#TextFont(java.lang.String, int, java.lang.String)">TextFont</a></strong>(java.lang.String&nbsp;fontName, int&nbsp;size, java.lang.String&nbsp;rgbColor)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colOne"><code><strong><a href="../../../com/inverseinnovations/MALSignatureDesigner/TextFont.html#TextFont(java.lang.String, java.lang.String, int, java.lang.String)">TextFont</a></strong>(java.lang.String&nbsp;fontName, java.lang.String&nbsp;style, int&nbsp;size, java.lang.String&nbsp;rgbColor)</code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method_summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span>Methods</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>java.awt.Color</code></td> <td class="colLast"><code><strong><a href="../../../com/inverseinnovations/MALSignatureDesigner/TextFont.html#getColor()">getColor</a></strong>()</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>java.awt.Font</code></td> <td class="colLast"><code><strong><a href="../../../com/inverseinnovations/MALSignatureDesigner/TextFont.html#getFont()">getFont</a></strong>()</code>&nbsp;</td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>equals, 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"> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="TextFont()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>TextFont</h4> <pre>public&nbsp;TextFont()</pre> </li> </ul> <a name="TextFont(java.lang.String, int)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>TextFont</h4> <pre>public&nbsp;TextFont(java.lang.String&nbsp;fontName, int&nbsp;size)</pre> </li> </ul> <a name="TextFont(java.lang.String, int, java.lang.String)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>TextFont</h4> <pre>public&nbsp;TextFont(java.lang.String&nbsp;fontName, int&nbsp;size, java.lang.String&nbsp;rgbColor)</pre> </li> </ul> <a name="TextFont(java.lang.String, java.lang.String, int, java.lang.String)"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>TextFont</h4> <pre>public&nbsp;TextFont(java.lang.String&nbsp;fontName, java.lang.String&nbsp;style, int&nbsp;size, java.lang.String&nbsp;rgbColor)</pre> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>fontName</code> - </dd><dd><code>style</code> - </dd><dd><code>size</code> - </dd><dd><code>rgbColor</code> - </dd></dl> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method_detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="getFont()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getFont</h4> <pre>public&nbsp;java.awt.Font&nbsp;getFont()</pre> </li> </ul> <a name="getColor()"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>getColor</h4> <pre>public&nbsp;java.awt.Color&nbsp;getColor()</pre> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> </body> </html>
<?php namespace ZendTest\Form\View\Helper\Captcha; use Zend\Captcha\Figlet as FigletCaptcha; use Zend\Form\Element\Captcha as CaptchaElement; use Zend\Form\View\Helper\Captcha\Figlet as FigletCaptchaHelper; use ZendTest\Form\View\Helper\CommonTestCase; class FigletTest extends CommonTestCase { public function setUp() { $this->helper = new FigletCaptchaHelper(); $this->captcha = new FigletCaptcha(array( 'sessionClass' => 'ZendTest\Captcha\TestAsset\SessionContainer', )); parent::setUp(); } public function getElement() { $element = new CaptchaElement('foo'); $element->setCaptcha($this->captcha); return $element; } public function testMissingCaptchaAttributeThrowsDomainException() { $element = new CaptchaElement('foo'); $this->setExpectedException('Zend\Form\Exception\DomainException'); $this->helper->render($element); } public function testRendersHiddenInputForId() { $element = $this->getElement(); $markup = $this->helper->render($element); $this->assertRegExp('#(name="' . $element->getName() . '\&\#x5B\;id\&\#x5D\;").*?(type="hidden")#', $markup); $this->assertRegExp('#(name="' . $element->getName() . '\&\#x5B\;id\&\#x5D\;").*?(value="' . $this->captcha->getId() . '")#', $markup); } public function testRendersTextInputForInput() { $element = $this->getElement(); $markup = $this->helper->render($element); $this->assertRegExp('#(name="' . $element->getName() . '\&\#x5B\;input\&\#x5D\;").*?(type="text")#', $markup); } public function testRendersFigletPriorToInputByDefault() { $element = $this->getElement(); $markup = $this->helper->render($element); $this->assertContains('<pre>' . $this->captcha->getFiglet()->render($this->captcha->getWord()) . '</pre>' . $this->helper->getSeparator() . '<input', $markup); } public function testCanRenderFigletFollowingInput() { $this->helper->setCaptchaPosition('prepend'); $element = $this->getElement(); $markup = $this->helper->render($element); $this->assertContains('><pre>', $markup); } }
'use strict'; var FontFace = require('./FontFace'); var clamp = require('./clamp'); var measureText = require('./measureText'); /** * Draw an image into a <canvas>. This operation requires that the image * already be loaded. * * @param {CanvasContext} ctx * @param {Image} image The source image (from ImageCache.get()) * @param {Number} x The x-coordinate to begin drawing * @param {Number} y The y-coordinate to begin drawing * @param {Number} width The desired width * @param {Number} height The desired height * @param {Object} options Available options are: * {Number} originalWidth * {Number} originalHeight * {Object} focusPoint {x,y} * {String} backgroundColor */ function drawImage (ctx, image, x, y, width, height, options) { options = options || {}; if (options.backgroundColor) { ctx.save(); ctx.fillStyle = options.backgroundColor; ctx.fillRect(x, y, width, height); ctx.restore(); } var dx = 0; var dy = 0; var dw = 0; var dh = 0; var sx = 0; var sy = 0; var sw = 0; var sh = 0; var scale; var scaledSize; var actualSize; var focusPoint = options.focusPoint; actualSize = { width: image.getWidth(), height: image.getHeight() }; scale = Math.max( width / actualSize.width, height / actualSize.height ) || 1; scale = parseFloat(scale.toFixed(4), 10); scaledSize = { width: actualSize.width * scale, height: actualSize.height * scale }; if (focusPoint) { // Since image hints are relative to image "original" dimensions (original != actual), // use the original size for focal point cropping. if (options.originalHeight) { focusPoint.x *= (actualSize.height / options.originalHeight); focusPoint.y *= (actualSize.height / options.originalHeight); } } else { // Default focal point to [0.5, 0.5] focusPoint = { x: actualSize.width * 0.5, y: actualSize.height * 0.5 }; } // Clip the image to rectangle (sx, sy, sw, sh). sx = Math.round(clamp(width * 0.5 - focusPoint.x * scale, width - scaledSize.width, 0)) * (-1 / scale); sy = Math.round(clamp(height * 0.5 - focusPoint.y * scale, height - scaledSize.height, 0)) * (-1 / scale); sw = Math.round(actualSize.width - (sx * 2)); sh = Math.round(actualSize.height - (sy * 2)); // Scale the image to dimensions (dw, dh). dw = Math.round(width); dh = Math.round(height); // Draw the image on the canvas at coordinates (dx, dy). dx = Math.round(x); dy = Math.round(y); ctx.drawImage(image.getRawImage(), sx, sy, sw, sh, dx, dy, dw, dh); } /** * @param {CanvasContext} ctx * @param {String} text The text string to render * @param {Number} x The x-coordinate to begin drawing * @param {Number} y The y-coordinate to begin drawing * @param {Number} width The maximum allowed width * @param {Number} height The maximum allowed height * @param {FontFace} fontFace The FontFace to to use * @param {Object} options Available options are: * {Number} fontSize * {Number} lineHeight * {String} textAlign * {String} color * {String} backgroundColor */ function drawText (ctx, text, x, y, width, height, fontFace, options) { var textMetrics; var currX = x; var currY = y; var currText; var options = options || {}; options.fontSize = options.fontSize || 16; options.lineHeight = options.lineHeight || 18; options.textAlign = options.textAlign || 'left'; options.backgroundColor = options.backgroundColor || 'transparent'; options.color = options.color || '#000'; textMetrics = measureText( text, width, fontFace, options.fontSize, options.lineHeight ); ctx.save(); // Draw the background if (options.backgroundColor !== 'transparent') { ctx.fillStyle = options.backgroundColor; ctx.fillRect(0, 0, width, height); } ctx.fillStyle = options.color; ctx.font = fontFace.attributes.style + ' ' + fontFace.attributes.weight + ' ' + options.fontSize + 'px ' + fontFace.family; textMetrics.lines.forEach(function (line, index) { currText = line.text; currY = (index === 0) ? y + options.fontSize : (y + options.fontSize + options.lineHeight * index); // Account for text-align: left|right|center switch (options.textAlign) { case 'center': currX = x + (width / 2) - (line.width / 2); break; case 'right': currX = x + width - line.width; break; default: currX = x; } if ((index < textMetrics.lines.length - 1) && ((options.fontSize + options.lineHeight * (index + 1)) > height)) { currText = currText.replace(/\,?\s?\w+$/, '…'); } if (currY <= (height + y)) { ctx.fillText(currText, currX, currY); } }); ctx.restore(); } /** * Draw a linear gradient * * @param {CanvasContext} ctx * @param {Number} x1 gradient start-x coordinate * @param {Number} y1 gradient start-y coordinate * @param {Number} x2 gradient end-x coordinate * @param {Number} y2 gradient end-y coordinate * @param {Array} colorStops Array of {(String)color, (Number)position} values * @param {Number} x x-coordinate to begin fill * @param {Number} y y-coordinate to begin fill * @param {Number} width how wide to fill * @param {Number} height how tall to fill */ function drawGradient(ctx, x1, y1, x2, y2, colorStops, x, y, width, height) { var grad; ctx.save(); grad = ctx.createLinearGradient(x1, y1, x2, y2); colorStops.forEach(function (colorStop) { grad.addColorStop(colorStop.position, colorStop.color); }); ctx.fillStyle = grad; ctx.fillRect(x, y, width, height); ctx.restore(); } module.exports = { drawImage: drawImage, drawText: drawText, drawGradient: drawGradient, };
<?xml version="1.0" encoding="UTF-8"?> <project version="4"> <component name="ChangeListManager"> <list default="true" id="480beb4e-c9a8-4860-b1b3-0f68b1d02530" name="Default" comment=""> <change type="MODIFICATION" beforePath="$PROJECT_DIR$/css/scrolling-nav.css" afterPath="$PROJECT_DIR$/css/scrolling-nav.css" /> </list> <ignored path="accentureFinData.iws" /> <ignored path=".idea/workspace.xml" /> <option name="EXCLUDED_CONVERTED_TO_IGNORED" value="true" /> <option name="TRACKING_ENABLED" value="true" /> <option name="SHOW_DIALOG" value="false" /> <option name="HIGHLIGHT_CONFLICTS" value="true" /> <option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" /> <option name="LAST_RESOLUTION" value="IGNORE" /> </component> <component name="ChangesViewManager" flattened_view="true" show_ignored="false" /> <component name="CreatePatchCommitExecutor"> <option name="PATCH_PATH" value="" /> </component> <component name="ExecutionTargetManager" SELECTED_TARGET="default_target" /> <component name="FavoritesManager"> <favorites_list name="accentureFinData" /> </component> <component name="FileEditorManager"> <leaf> <file leaf-file-name="index.html" pinned="false" current-in-tab="true"> <entry file="file://$PROJECT_DIR$/index.html"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.62693685"> <caret line="253" column="31" selection-start-line="253" selection-start-column="31" selection-end-line="253" selection-end-column="31" /> <folding /> </state> </provider> </entry> </file> <file leaf-file-name="package.json" pinned="false" current-in-tab="false"> <entry file="file://$PROJECT_DIR$/package.json"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="-0.0"> <caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" /> <folding /> </state> </provider> </entry> </file> <file leaf-file-name="scrolling-nav.css" pinned="false" current-in-tab="false"> <entry file="file://$PROJECT_DIR$/css/scrolling-nav.css"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="39" column="24" selection-start-line="39" selection-start-column="24" selection-end-line="39" selection-end-column="24" /> <folding /> </state> </provider> </entry> </file> <file leaf-file-name="charts.js" pinned="false" current-in-tab="false"> <entry file="file://$PROJECT_DIR$/js/charts.js"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="452" column="23" selection-start-line="452" selection-start-column="16" selection-end-line="452" selection-end-column="23" /> <folding /> </state> </provider> </entry> </file> </leaf> </component> <component name="Git.Settings"> <option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" /> </component> <component name="IdeDocumentHistory"> <option name="CHANGED_PATHS"> <list> <option value="$PROJECT_DIR$/README.md" /> <option value="$PROJECT_DIR$/data/acnIndex.csv" /> <option value="$PROJECT_DIR$/line.html" /> <option value="$PROJECT_DIR$/js/treemap.js" /> <option value="$PROJECT_DIR$/data/bars.csv" /> <option value="$PROJECT_DIR$/data/bar.csv" /> <option value="$PROJECT_DIR$/js/bars.js" /> <option value="$PROJECT_DIR$/data/world50.json" /> <option value="$PROJECT_DIR$/js/line.js" /> <option value="$PROJECT_DIR$/data/world.json" /> <option value="$PROJECT_DIR$/data/world50_simple.json" /> <option value="$PROJECT_DIR$/data/acnISOcountries.csv" /> <option value="$PROJECT_DIR$/js/countries.js" /> <option value="$PROJECT_DIR$/data/world10.json" /> <option value="$PROJECT_DIR$/data/world_simple.json" /> <option value="$PROJECT_DIR$/js/charts.js" /> <option value="$PROJECT_DIR$/index.html" /> <option value="$PROJECT_DIR$/css/scrolling-nav.css" /> </list> </option> </component> <component name="JsBuildToolGruntFileManager" detection-done="true" /> <component name="JsGulpfileManager"> <detection-done>true</detection-done> </component> <component name="NamedScopeManager"> <order /> </component> <component name="ProjectFrameBounds"> <option name="x" value="62" /> <option name="y" value="63" /> <option name="width" value="1542" /> <option name="height" value="983" /> </component> <component name="ProjectLevelVcsManager" settingsEditedManually="false"> <OptionsSetting value="true" id="Add" /> <OptionsSetting value="true" id="Remove" /> <OptionsSetting value="true" id="Checkout" /> <OptionsSetting value="true" id="Update" /> <OptionsSetting value="true" id="Status" /> <OptionsSetting value="true" id="Edit" /> <ConfirmationsSetting value="0" id="Add" /> <ConfirmationsSetting value="0" id="Remove" /> </component> <component name="ProjectView"> <navigator currentView="ProjectPane" proportions="" version="1"> <flattenPackages /> <showMembers /> <showModules /> <showLibraryContents /> <hideEmptyPackages /> <abbreviatePackageNames /> <autoscrollToSource /> <autoscrollFromSource /> <sortByType /> </navigator> <panes> <pane id="ProjectPane"> <subPane> <PATH> <PATH_ELEMENT> <option name="myItemId" value="accentureFinData" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" /> </PATH_ELEMENT> </PATH> <PATH> <PATH_ELEMENT> <option name="myItemId" value="accentureFinData" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" /> </PATH_ELEMENT> <PATH_ELEMENT> <option name="myItemId" value="accentureFinData" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" /> </PATH_ELEMENT> </PATH> <PATH> <PATH_ELEMENT> <option name="myItemId" value="accentureFinData" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" /> </PATH_ELEMENT> <PATH_ELEMENT> <option name="myItemId" value="accentureFinData" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" /> </PATH_ELEMENT> <PATH_ELEMENT> <option name="myItemId" value="js" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" /> </PATH_ELEMENT> </PATH> <PATH> <PATH_ELEMENT> <option name="myItemId" value="accentureFinData" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" /> </PATH_ELEMENT> <PATH_ELEMENT> <option name="myItemId" value="accentureFinData" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" /> </PATH_ELEMENT> <PATH_ELEMENT> <option name="myItemId" value="fonts" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" /> </PATH_ELEMENT> </PATH> <PATH> <PATH_ELEMENT> <option name="myItemId" value="accentureFinData" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" /> </PATH_ELEMENT> <PATH_ELEMENT> <option name="myItemId" value="accentureFinData" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" /> </PATH_ELEMENT> <PATH_ELEMENT> <option name="myItemId" value="data" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" /> </PATH_ELEMENT> </PATH> <PATH> <PATH_ELEMENT> <option name="myItemId" value="accentureFinData" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" /> </PATH_ELEMENT> <PATH_ELEMENT> <option name="myItemId" value="accentureFinData" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" /> </PATH_ELEMENT> <PATH_ELEMENT> <option name="myItemId" value="css" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" /> </PATH_ELEMENT> </PATH> </subPane> </pane> <pane id="Scratches" /> <pane id="Scope" /> </panes> </component> <component name="PropertiesComponent"> <property name="settings.editor.selected.configurable" value="File.Encoding" /> <property name="settings.editor.splitter.proportion" value="0.2" /> <property name="HbShouldOpenHtmlAsHb" value="" /> <property name="last_opened_file_path" value="$PROJECT_DIR$" /> <property name="WebServerToolWindowFactoryState" value="false" /> <property name="FullScreen" value="false" /> </component> <component name="RecentsManager"> <key name="CopyFile.RECENT_KEYS"> <recent name="$PROJECT_DIR$/data" /> </key> <key name="MoveFile.RECENT_KEYS"> <recent name="$PROJECT_DIR$" /> </key> </component> <component name="RunManager"> <configuration default="true" type="DartCommandLineRunConfigurationType" factoryName="Dart Command Line Application"> <method /> </configuration> <configuration default="true" type="DartUnitRunConfigurationType" factoryName="DartUnit"> <method /> </configuration> <configuration default="true" type="JavaScriptTestRunnerKarma" factoryName="Karma" config-file=""> <envs /> <method /> </configuration> <configuration default="true" type="JavascriptDebugType" factoryName="JavaScript Debug"> <method /> </configuration> <configuration default="true" type="JsTestDriver-test-runner" factoryName="JsTestDriver"> <setting name="configLocationType" value="CONFIG_FILE" /> <setting name="settingsFile" value="" /> <setting name="serverType" value="INTERNAL" /> <setting name="preferredDebugBrowser" value="Chrome" /> <method /> </configuration> <configuration default="true" type="NodeJSConfigurationType" factoryName="Node.js" working-dir=""> <method /> </configuration> <configuration default="true" type="cucumber.js" factoryName="Cucumber.js"> <option name="cucumberJsArguments" value="" /> <option name="executablePath" /> <option name="filePath" /> <method /> </configuration> <configuration default="true" type="js.build_tools.gulp" factoryName="Gulp.js"> <node-options /> <gulpfile /> <tasks /> <arguments /> <pass-parent-envs>true</pass-parent-envs> <envs /> <method /> </configuration> </component> <component name="ShelveChangesManager" show_recycled="false" /> <component name="SvnConfiguration"> <configuration /> </component> <component name="TaskManager"> <task active="true" id="Default" summary="Default task"> <changelist id="480beb4e-c9a8-4860-b1b3-0f68b1d02530" name="Default" comment="" /> <created>1453836310365</created> <option name="number" value="Default" /> <updated>1453836310365</updated> </task> <servers /> </component> <component name="TodoView"> <todo-panel id="selected-file"> <is-autoscroll-to-source value="true" /> </todo-panel> <todo-panel id="all"> <are-packages-shown value="true" /> <is-autoscroll-to-source value="true" /> </todo-panel> </component> <component name="ToolWindowManager"> <frame x="62" y="63" width="1542" height="983" extended-state="0" /> <editor active="true" /> <layout> <window_info id="Terminal" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" content_ui="tabs" /> <window_info id="TODO" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.32996634" sideWeight="0.5" order="6" side_tool="false" content_ui="tabs" /> <window_info id="Structure" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.24983564" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" /> <window_info id="Application Servers" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="10" side_tool="false" content_ui="tabs" /> <window_info id="Project" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" weight="0.24983564" sideWeight="0.49607182" order="0" side_tool="false" content_ui="combo" /> <window_info id="Favorites" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.24983564" sideWeight="0.5039282" order="2" side_tool="true" content_ui="tabs" /> <window_info id="Event Log" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.32996634" sideWeight="0.5" order="8" side_tool="true" content_ui="tabs" /> <window_info id="Version Control" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="9" side_tool="false" content_ui="tabs" /> <window_info id="Cvs" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="4" side_tool="false" content_ui="tabs" /> <window_info id="Message" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" /> <window_info id="Ant Build" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" /> <window_info id="Find" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" /> <window_info id="Debug" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.4" sideWeight="0.5" order="3" side_tool="false" content_ui="tabs" /> <window_info id="Commander" active="false" anchor="right" auto_hide="false" internal_type="SLIDING" type="SLIDING" visible="false" weight="0.4" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" /> <window_info id="Hierarchy" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="2" side_tool="false" content_ui="combo" /> <window_info id="Inspection" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.4" sideWeight="0.5" order="5" side_tool="false" content_ui="tabs" /> <window_info id="Run" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="2" side_tool="false" content_ui="tabs" /> </layout> <layout-to-restore> <window_info id="Cvs" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="4" side_tool="false" content_ui="tabs" /> <window_info id="Terminal" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" content_ui="tabs" /> <window_info id="Message" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" /> <window_info id="Ant Build" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" /> <window_info id="Find" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" /> <window_info id="Debug" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.4" sideWeight="0.5" order="3" side_tool="false" content_ui="tabs" /> <window_info id="Favorites" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.24983564" sideWeight="0.5039282" order="2" side_tool="true" content_ui="tabs" /> <window_info id="Event Log" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="8" side_tool="true" content_ui="tabs" /> <window_info id="Version Control" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="9" side_tool="false" content_ui="tabs" /> <window_info id="TODO" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.32996634" sideWeight="0.5" order="6" side_tool="false" content_ui="tabs" /> <window_info id="Structure" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.24983564" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" /> <window_info id="Commander" active="false" anchor="right" auto_hide="false" internal_type="SLIDING" type="SLIDING" visible="false" weight="0.4" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" /> <window_info id="Application Servers" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="10" side_tool="false" content_ui="tabs" /> <window_info id="Project" active="true" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" weight="0.24983564" sideWeight="0.49607182" order="0" side_tool="false" content_ui="combo" /> <window_info id="Run" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="2" side_tool="false" content_ui="tabs" /> <window_info id="Hierarchy" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="2" side_tool="false" content_ui="combo" /> <window_info id="Inspection" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.4" sideWeight="0.5" order="5" side_tool="false" content_ui="tabs" /> </layout-to-restore> </component> <component name="Vcs.Log.UiProperties"> <option name="RECENTLY_FILTERED_USER_GROUPS"> <collection /> </option> <option name="RECENTLY_FILTERED_BRANCH_GROUPS"> <collection /> </option> </component> <component name="VcsContentAnnotationSettings"> <option name="myLimit" value="2678400000" /> </component> <component name="XDebuggerManager"> <breakpoint-manager /> <watches-manager /> </component> <component name="editorHistoryManager"> <entry file="file://$PROJECT_DIR$/index.html"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="104" column="49" selection-start-line="104" selection-start-column="49" selection-end-line="104" selection-end-column="49" /> <folding /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/package.json"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" /> <folding /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/css/scrolling-nav.css"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" /> <folding /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/js/charts.js"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="452" column="23" selection-start-line="452" selection-start-column="16" selection-end-line="452" selection-end-column="23" /> <folding /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/js/treemap.js"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" /> <folding /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/index.html"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="159" column="38" selection-start-line="159" selection-start-column="4" selection-end-line="159" selection-end-column="38" /> <folding /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/js/line.js"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="16" column="43" selection-start-line="16" selection-start-column="43" selection-end-line="16" selection-end-column="43" /> <folding /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/line.html"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="149" column="8" selection-start-line="149" selection-start-column="8" selection-end-line="149" selection-end-column="8" /> <folding /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/data/acnIndex.csv"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="7" column="16" selection-start-line="7" selection-start-column="16" selection-end-line="7" selection-end-column="16" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/css/scrolling-nav.css"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="50" column="23" selection-start-line="50" selection-start-column="23" selection-end-line="50" selection-end-column="23" /> <folding /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/js/jquery.js"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="-1.5930787"> <caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" /> <folding> <element signature="n#!!doc" expanded="false" /> </folding> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/js/scrolling-nav.js"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" /> <folding /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/css/bootstrap.css"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="2.611244"> <caret line="1580" column="11" selection-start-line="1580" selection-start-column="5" selection-end-line="1580" selection-end-column="11" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/README.md"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.08971292"> <caret line="5" column="0" selection-start-line="5" selection-start-column="0" selection-end-line="5" selection-end-column="0" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/data/world.json"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.9630542"> <caret line="0" column="212618" selection-start-line="0" selection-start-column="212618" selection-end-line="0" selection-end-column="212618" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/line.html"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="-19.375"> <caret line="87" column="3" selection-start-line="76" selection-start-column="0" selection-end-line="87" selection-end-column="3" /> <folding /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/js/countries.js"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.31490386"> <caret line="71" column="49" selection-start-line="71" selection-start-column="49" selection-end-line="71" selection-end-column="49" /> <folding /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/data/acnISOcountries.csv"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.13904983"> <caret line="8" column="9" selection-start-line="8" selection-start-column="9" selection-end-line="8" selection-end-column="9" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/data/acnIndex.csv"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.1216686"> <caret line="7" column="16" selection-start-line="7" selection-start-column="16" selection-end-line="7" selection-end-column="16" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/js/line.js"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.2526072"> <caret line="76" column="23" selection-start-line="76" selection-start-column="23" selection-end-line="76" selection-end-column="23" /> <folding /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/js/bars.js"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.17942584"> <caret line="15" column="37" selection-start-line="12" selection-start-column="0" selection-end-line="15" selection-end-column="37" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/js/treemap.js"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.39976826"> <caret line="116" column="37" selection-start-line="110" selection-start-column="5" selection-end-line="116" selection-end-column="37" /> <folding /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/../scoil/squares.js"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="72" column="7" selection-start-line="66" selection-start-column="4" selection-end-line="72" selection-end-column="7" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/data/world10.json"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/data/world_simple.json"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="72.461266"> <caret line="0" column="612997" selection-start-line="0" selection-start-column="612997" selection-end-line="0" selection-end-column="612997" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/data/world50_simple.json"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="-0.7520858"> <caret line="0" column="43205" selection-start-line="0" selection-start-column="43198" selection-end-line="0" selection-end-column="43205" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/data/world10_simple.json"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="177.79167"> <caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/data/bar.csv"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.017381229"> <caret line="1" column="0" selection-start-line="1" selection-start-column="0" selection-end-line="1" selection-end-column="0" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/data/countries.json"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/../bankline/bankline.js"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/js/charts.js"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="452" column="23" selection-start-line="452" selection-start-column="16" selection-end-line="452" selection-end-column="23" /> <folding /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/package.json"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" /> <folding /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/css/scrolling-nav.css"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="39" column="24" selection-start-line="39" selection-start-column="24" selection-end-line="39" selection-end-column="24" /> <folding /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/index.html"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.62693685"> <caret line="253" column="31" selection-start-line="253" selection-start-column="31" selection-end-line="253" selection-end-column="31" /> <folding /> </state> </provider> </entry> </component> </project>
using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace Slp.Evi.Storage.Sparql.Algebra.Expressions { /// <summary> /// Representation of OR expression /// </summary> /// <seealso cref="Slp.Evi.Storage.Sparql.Algebra.ISparqlCondition" /> public class DisjunctionExpression : ISparqlCondition { /// <summary> /// Gets the operands. /// </summary> /// <value>The operands.</value> public ISparqlCondition[] Operands { get; } /// <summary> /// Initializes a new instance of the <see cref="DisjunctionExpression"/> class. /// </summary> /// <param name="operands">The operands.</param> public DisjunctionExpression(IEnumerable<ISparqlCondition> operands) { Operands = operands.ToArray(); NeededVariables = Operands.SelectMany(x => x.NeededVariables).Distinct().ToArray(); } /// <summary> /// Accepts the specified visitor. /// </summary> /// <param name="visitor">The visitor.</param> /// <param name="data">The data.</param> /// <returns>The returned value from visitor.</returns> [DebuggerStepThrough] public object Accept(ISparqlExpressionVisitor visitor, object data) { return visitor.Visit(this, data); } /// <summary> /// Gets the needed variables to evaluate the expression. /// </summary> public IEnumerable<string> NeededVariables { get; } } }
'use strict'; module.exports = function(app) { var users = require('../../app/controllers/users.server.controller'); var doctors = require('../../app/controllers/doctors.server.controller'); // Doctors Routes app.route('/doctors') .get(doctors.list) .post(users.requiresLogin, doctors.create); app.route('/doctorsvisiting') .get(doctors.listVisiting) app.route('/doctors/:doctorId') .get(doctors.read) .put(users.requiresLogin, doctors.hasAuthorization, doctors.update) .delete(users.requiresLogin, doctors.hasAuthorization, doctors.delete); // Finish by binding the Doctor middleware app.param('doctorId', doctors.doctorByID); };
<?php namespace yii\widgets; use Yii; use yii\base\InvalidConfigException; use yii\base\Widget; use yii\helpers\ArrayHelper; use yii\helpers\Html; /** * BaseListView is a base class for widgets displaying data from data provider * such as ListView and GridView. * * It provides features like sorting, paging and also filtering the data. * * @author Qiang Xue <qiang.xue@gmail.com> * @since 2.0 */ abstract class BaseListView extends Widget { /** * @var array the HTML attributes for the container tag of the list view. * The "tag" element specifies the tag name of the container element and defaults to "div". * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered. */ public $options = []; /** * @var \yii\data\DataProviderInterface the data provider for the view. This property is required. */ public $dataProvider; /** * @var array the configuration for the pager widget. By default, [[LinkPager]] will be * used to render the pager. You can use a different widget class by configuring the "class" element. * Note that the widget must support the `pagination` property which will be populated with the * [[\yii\data\BaseDataProvider::pagination|pagination]] value of the [[dataProvider]]. */ public $pager = []; /** * @var array the configuration for the sorter widget. By default, [[LinkSorter]] will be * used to render the sorter. You can use a different widget class by configuring the "class" element. * Note that the widget must support the `sort` property which will be populated with the * [[\yii\data\BaseDataProvider::sort|sort]] value of the [[dataProvider]]. */ public $sorter = []; /** * @var string the HTML content to be displayed as the summary of the list view. * If you do not want to show the summary, you may set it with an empty string. * * The following tokens will be replaced with the corresponding values: * * - `{begin}`: the starting row number (1-based) currently being displayed * - `{end}`: the ending row number (1-based) currently being displayed * - `{count}`: the number of rows currently being displayed * - `{totalCount}`: the total number of rows available * - `{page}`: the page number (1-based) current being displayed * - `{pageCount}`: the number of pages available */ public $summary; /** * @var array the HTML attributes for the summary of the list view. * The "tag" element specifies the tag name of the summary element and defaults to "div". * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered. */ public $summaryOptions = ['class' => 'summary']; /** * @var boolean whether to show the list view if [[dataProvider]] returns no data. */ public $showOnEmpty = false; /** * @var string the HTML content to be displayed when [[dataProvider]] does not have any data. */ public $emptyText; /** * @var array the HTML attributes for the emptyText of the list view. * The "tag" element specifies the tag name of the emptyText element and defaults to "div". * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered. */ public $emptyTextOptions = ['class' => 'empty']; /** * @var string the layout that determines how different sections of the list view should be organized. * The following tokens will be replaced with the corresponding section contents: * * - `{summary}`: the summary section. See [[renderSummary()]]. * - `{items}`: the list items. See [[renderItems()]]. * - `{sorter}`: the sorter. See [[renderSorter()]]. * - `{pager}`: the pager. See [[renderPager()]]. */ public $layout = "{summary}\n{items}\n{pager}"; /** * Renders the data models. * @return string the rendering result. */ abstract public function renderItems(); /** * Initializes the view. */ public function init() { if ($this->dataProvider === null) { throw new InvalidConfigException('The "dataProvider" property must be set.'); } if ($this->emptyText === null) { $this->emptyText = Yii::t('yii', 'No results found.'); } if (!isset($this->options['id'])) { $this->options['id'] = $this->getId(); } } /** * Runs the widget. */ public function run() { if ($this->showOnEmpty || $this->dataProvider->getCount() > 0) { $content = preg_replace_callback("/{\\w+}/", function ($matches) { $content = $this->renderSection($matches[0]); return $content === false ? $matches[0] : $content; }, $this->layout); } else { $content = $this->renderEmpty(); } $options = $this->options; $tag = ArrayHelper::remove($options, 'tag', 'div'); echo Html::tag($tag, $content, $options); } /** * Renders a section of the specified name. * If the named section is not supported, false will be returned. * @param string $name the section name, e.g., `{summary}`, `{items}`. * @return string|boolean the rendering result of the section, or false if the named section is not supported. */ public function renderSection($name) { switch ($name) { case '{summary}': return $this->renderSummary(); case '{items}': return $this->renderItems(); case '{pager}': return $this->renderPager(); case '{sorter}': return $this->renderSorter(); default: return false; } } /** * Renders the HTML content indicating that the list view has no data. * @return string the rendering result * @see emptyText */ public function renderEmpty() { $options = $this->emptyTextOptions; $tag = ArrayHelper::remove($options, 'tag', 'div'); return Html::tag($tag, ($this->emptyText === null ? Yii::t('yii', 'No results found.') : $this->emptyText), $options); } /** * Renders the summary text. */ public function renderSummary() { $count = $this->dataProvider->getCount(); if ($count <= 0) { return ''; } $summaryOptions = $this->summaryOptions; $tag = ArrayHelper::remove($summaryOptions, 'tag', 'div'); if (($pagination = $this->dataProvider->getPagination()) !== false) { $totalCount = $this->dataProvider->getTotalCount(); $begin = $pagination->getPage() * $pagination->pageSize + 1; $end = $begin + $count - 1; if ($begin > $end) { $begin = $end; } $page = $pagination->getPage() + 1; $pageCount = $pagination->pageCount; if (($summaryContent = $this->summary) === null) { return Html::tag($tag, Yii::t('yii', 'Showing <b>{begin, number}-{end, number}</b> of <b>{totalCount, number}</b> {totalCount, plural, one{item} other{items}}.', [ 'begin' => $begin, 'end' => $end, 'count' => $count, 'totalCount' => $totalCount, 'page' => $page, 'pageCount' => $pageCount, ]), $summaryOptions); } } else { $begin = $page = $pageCount = 1; $end = $totalCount = $count; if (($summaryContent = $this->summary) === null) { return Html::tag($tag, Yii::t('yii', 'Total <b>{count, number}</b> {count, plural, one{item} other{items}}.', [ 'begin' => $begin, 'end' => $end, 'count' => $count, 'totalCount' => $totalCount, 'page' => $page, 'pageCount' => $pageCount, ]), $summaryOptions); } } return Yii::$app->getI18n()->format($summaryContent, [ 'begin' => $begin, 'end' => $end, 'count' => $count, 'totalCount' => $totalCount, 'page' => $page, 'pageCount' => $pageCount, ], Yii::$app->language); } /** * Renders the pager. * @return string the rendering result */ public function renderPager() { $pagination = $this->dataProvider->getPagination(); if ($pagination === false || $this->dataProvider->getCount() <= 0) { return ''; } /* @var $class LinkPager */ $pager = $this->pager; $class = ArrayHelper::remove($pager, 'class', LinkPager::className()); $pager['pagination'] = $pagination; $pager['view'] = $this->getView(); return $class::widget($pager); } /** * Renders the sorter. * @return string the rendering result */ public function renderSorter() { $sort = $this->dataProvider->getSort(); if ($sort === false || empty($sort->attributes) || $this->dataProvider->getCount() <= 0) { return ''; } /* @var $class LinkSorter */ $sorter = $this->sorter; $class = ArrayHelper::remove($sorter, 'class', LinkSorter::className()); $sorter['sort'] = $sort; $sorter['view'] = $this->getView(); return $class::widget($sorter); } }
package cz.petrkubes.ioweyou.Activities; import android.app.ActivityOptions; import android.app.job.JobInfo; import android.app.job.JobScheduler; import android.content.ComponentName; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.CoordinatorLayout; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.design.widget.TabLayout; import android.support.v4.view.ViewPager; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ProgressBar; import android.widget.Toast; import com.facebook.FacebookSdk; import com.facebook.login.LoginManager; import cz.petrkubes.ioweyou.Adapters.FragmentsAdapter; import cz.petrkubes.ioweyou.Api.Api; import cz.petrkubes.ioweyou.Api.SimpleCallback; import cz.petrkubes.ioweyou.Database.DatabaseHandler; import cz.petrkubes.ioweyou.Pojos.ApiParams; import cz.petrkubes.ioweyou.Pojos.User; import cz.petrkubes.ioweyou.R; import cz.petrkubes.ioweyou.Services.UpdateAllService; /** * Main activity includes all fragments and a viewPager, which displays the fragments * * @author Petr Kubes */ public class MainActivity extends AppCompatActivity { public static final int ADD_DEBT_REQUEST = 0; public static final String MY_DEBT = "myDebt"; // Widgets private FloatingActionButton btnAddDebt; private DatabaseHandler db; private FragmentsAdapter pageAdapter; private ViewPager viewPager; private TabLayout tabLayout; private ProgressBar toolbarProgressBar; private Toolbar toolbar; private CoordinatorLayout coordinatorLayout; private User user; private Api api; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Library only for testing purposes //Stetho.initializeWithDefaults(this); setContentView(R.layout.activity_main); // Setup actionbar toolbar = (Toolbar) findViewById(R.id.my_toolbar); setSupportActionBar(toolbar); toolbarProgressBar = (ProgressBar) findViewById(R.id.toolbar_progress_bar); toolbarProgressBar.setVisibility(View.GONE); // Parent view for snackbar coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinatorLayout); // Setup views and buttons btnAddDebt = (FloatingActionButton) findViewById(R.id.btn_add_debt); tabLayout = (TabLayout) findViewById(R.id.tabs); // Setup tabs pageAdapter = new FragmentsAdapter(getSupportFragmentManager(), getApplicationContext()); viewPager = (ViewPager) findViewById(R.id.pager); viewPager.setAdapter(pageAdapter); viewPager.setOffscreenPageLimit(4); tabLayout.setupWithViewPager(viewPager); pageAdapter.notifyDataSetChanged(); // Setup database db = new DatabaseHandler(getApplicationContext()); // Setup api client for synchronization api = new Api(this); user = db.getUser(); // Start a new activity in which user adds debts when user click the plus button btnAddDebt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(getApplicationContext(), DebtActivity.class); // put extra boolean to the intent, so that DebtActivity knows which radio button to check boolean myDebt = true; if (viewPager.getCurrentItem() == 1) { myDebt = false; } intent.putExtra(MY_DEBT, myDebt); // Make transition only on newer android version if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) { ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(MainActivity.this, btnAddDebt, getString(R.string.transition_button)); startActivityForResult(intent, ADD_DEBT_REQUEST, options.toBundle()); } else { startActivityForResult(intent, ADD_DEBT_REQUEST); } } }); // Start a background job startBackgroundJob(); } @Override protected void onResume() { super.onResume(); pageAdapter.notifyDataSetChanged(); if (user == null) { logOut(); } } /** * Syncs debts after user adds/updates a debt */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == ADD_DEBT_REQUEST && resultCode == RESULT_OK) { updateDebtsAndActions(); } } /** * Handles toolbar actions */ @Override public boolean onOptionsItemSelected(final MenuItem item) { switch (item.getItemId()) { case R.id.action_logout: logOut(); return true; case R.id.action_refresh: // Refresh everything if (user != null) { updateAll(); } else { // This should not happen during normal app usage. Used for testing. Toast.makeText(getApplicationContext(), "User is not logged in", Toast.LENGTH_SHORT).show(); } return true; default: return super.onOptionsItemSelected(item); } } /** * Inflates actionbar */ @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu, menu); return true; } /** * This is kind of a hacky solution. Toolbar progressbar cannot be updated before the menu is created, so I can't update debts onStart or onCreate of the Actrivity */ @Override public boolean onPrepareOptionsMenu(Menu menu) { // Updates debts and actions when the user launches the app // This is necessary, because JobScheduler job can be turned off by Android system updateDebtsAndActions(); return super.onPrepareOptionsMenu(menu); } /** * Show an alertDialog on pressing a back button */ @Override public void onBackPressed() { AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this); dialogBuilder.setMessage(getString(R.string.are_you_sure_you_want_to_exit)); dialogBuilder.setPositiveButton(getString(R.string.yes), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { finish(); } }); dialogBuilder.setNegativeButton(getString(R.string.no), null); dialogBuilder.show(); } /** * Calls Api download method to update debts and actions and processes callback */ public void updateDebtsAndActions() { pageAdapter.notifyDataSetChanged(); toggleLoading(); ApiParams params = new ApiParams(); params.callback = new SimpleCallback() { @Override public void onSuccess(int apiMethodCode) { toggleLoading(); pageAdapter.notifyDataSetChanged(); Snackbar.make(coordinatorLayout, getString(R.string.changes_synced), Snackbar.LENGTH_SHORT).show(); } @Override public void onFailure(String message) { toggleLoading(); Snackbar.make(coordinatorLayout, message, Snackbar.LENGTH_LONG).show(); } }; api.download(Api.API_UPDATE_DEBTS_AND_ACTIONS, params); } /** * Calls Api download method to update everything and processes callback */ public void updateAll() { toggleLoading(); ApiParams params = new ApiParams(); params.callback = new SimpleCallback() { @Override public void onSuccess(int apiMethodCode) { toggleLoading(); pageAdapter.notifyDataSetChanged(); Snackbar.make(coordinatorLayout, getString(R.string.changes_synced), Snackbar.LENGTH_SHORT).show(); } @Override public void onFailure(String message) { toggleLoading(); Snackbar.make(coordinatorLayout, message, Snackbar.LENGTH_LONG).show(); } }; api.download(Api.API_UPDATE_ALL, params); } /** * Logs user out of facebook, truncates database and launches Login activity */ public void logOut() { // Logout from facebook if (!FacebookSdk.isInitialized()) { FacebookSdk.sdkInitialize(getApplicationContext()); } LoginManager.getInstance().logOut(); // TODO empty api key on server // Cancel all background jobs JobScheduler jobScheduler = (JobScheduler) getApplication().getSystemService(Context.JOB_SCHEDULER_SERVICE); jobScheduler.cancelAll(); // Truncate db db.truncate(); Intent intent = new Intent(getApplicationContext(), LoginActivity.class); startActivity(intent); } /** * Toggles loading in the toolbar */ private void toggleLoading() { final MenuItem item = toolbar.getMenu().getItem(0); if (item.isVisible()) { item.setVisible(false); toolbarProgressBar.setVisibility(View.VISIBLE); } else { item.setVisible(true); toolbarProgressBar.setVisibility(View.GONE); } } /** * Starts a JobScheduler, which launches UpdateAllService to update the database every few hours * First checks if job doesn't already exist, if yes, does not create any new jobs */ public void startBackgroundJob() { JobScheduler jobScheduler = (JobScheduler) getApplication().getSystemService(Context.JOB_SCHEDULER_SERVICE); if (jobScheduler.getAllPendingJobs().size() < 1) { ComponentName mServiceComponent = new ComponentName(this, UpdateAllService.class); JobInfo jobInfo = new JobInfo.Builder(0, mServiceComponent) .setPeriodic(4 * 60 * 60 * 1000) // 4 hours .setRequiresCharging(false) .setPersisted(true) .build(); jobScheduler.cancelAll(); jobScheduler.schedule(jobInfo); } } }
namespace { const char kExtensionId[] = "ddchlicdkolnonkihahngkmmmjnjlkkf"; // Skip a few events from the beginning. static const size_t kSkipEvents = 3; enum TestFlags { kUseGpu = 1 << 0, // Only execute test if --enable-gpu was given // on the command line. This is required for // tests that run on GPU. kDisableVsync = 1 << 1, // Do not limit framerate to vertical refresh. // when on GPU, nor to 60hz when not on GPU. kSmallWindow = 1 << 2, // 1 = 800x600, 0 = 2000x1000 k24fps = 1 << 3, // use 24 fps video k30fps = 1 << 4, // use 30 fps video k60fps = 1 << 5, // use 60 fps video kProxyWifi = 1 << 6, // Run UDP through UDPProxy wifi profile kProxyBad = 1 << 7, // Run UDP through UDPProxy bad profile kSlowClock = 1 << 8, // Receiver clock is 10 seconds slow kFastClock = 1 << 9, // Receiver clock is 10 seconds fast }; class SkewedTickClock : public base::DefaultTickClock { public: explicit SkewedTickClock(const base::TimeDelta& delta) : delta_(delta) { } base::TimeTicks NowTicks() override { return DefaultTickClock::NowTicks() + delta_; } private: base::TimeDelta delta_; }; class SkewedCastEnvironment : public media::cast::StandaloneCastEnvironment { public: explicit SkewedCastEnvironment(const base::TimeDelta& delta) : StandaloneCastEnvironment() { clock_.reset(new SkewedTickClock(delta)); } protected: ~SkewedCastEnvironment() override {} }; // We log one of these for each call to OnAudioFrame/OnVideoFrame. struct TimeData { TimeData(uint16_t frame_no_, base::TimeTicks render_time_) : frame_no(frame_no_), render_time(render_time_) {} // The unit here is video frames, for audio data there can be duplicates. // This was decoded from the actual audio/video data. uint16_t frame_no; // This is when we should play this data, according to the sender. base::TimeTicks render_time; }; // TODO(hubbe): Move to media/cast to use for offline log analysis. class MeanAndError { public: MeanAndError() {} explicit MeanAndError(const std::vector<double>& values) { double sum = 0.0; double sqr_sum = 0.0; num_values = values.size(); if (num_values) { for (size_t i = 0; i < num_values; i++) { sum += values[i]; sqr_sum += values[i] * values[i]; } mean = sum / num_values; std_dev = sqrt(std::max(0.0, num_values * sqr_sum - sum * sum)) / num_values; } } std::string AsString() const { return base::StringPrintf("%f,%f", mean, std_dev); } void Print(const std::string& measurement, const std::string& modifier, const std::string& trace, const std::string& unit) { if (num_values >= 20) { perf_test::PrintResultMeanAndError(measurement, modifier, trace, AsString(), unit, true); } else { LOG(ERROR) << "Not enough events for " << measurement << modifier << " " << trace; } } size_t num_values; double mean; double std_dev; }; // This function checks how smooth the data in |data| is. // It computes the average error of deltas and the average delta. // If data[x] == x * A + B, then this function returns zero. // The unit is milliseconds. static MeanAndError AnalyzeJitter(const std::vector<TimeData>& data) { CHECK_GT(data.size(), 1UL); VLOG(0) << "Jitter analyzis on " << data.size() << " values."; std::vector<double> deltas; double sum = 0.0; for (size_t i = 1; i < data.size(); i++) { double delta = (data[i].render_time - data[i - 1].render_time).InMillisecondsF(); deltas.push_back(delta); sum += delta; } double mean = sum / deltas.size(); for (size_t i = 0; i < deltas.size(); i++) { deltas[i] = fabs(mean - deltas[i]); } return MeanAndError(deltas); } // An in-process Cast receiver that examines the audio/video frames being // received and logs some data about each received audio/video frame. class TestPatternReceiver : public media::cast::InProcessReceiver { public: explicit TestPatternReceiver( const scoped_refptr<media::cast::CastEnvironment>& cast_environment, const net::IPEndPoint& local_end_point) : InProcessReceiver(cast_environment, local_end_point, net::IPEndPoint(), media::cast::GetDefaultAudioReceiverConfig(), media::cast::GetDefaultVideoReceiverConfig()) { } typedef std::map<uint16_t, base::TimeTicks> TimeMap; // Build a map from frame ID (as encoded in the audio and video data) // to the rtp timestamp for that frame. Note that there will be multiple // audio frames which all have the same frame ID. When that happens we // want the minimum rtp timestamp, because that audio frame is supposed // to play at the same time that the corresponding image is presented. void MapFrameTimes(const std::vector<TimeData>& events, TimeMap* map) { for (size_t i = kSkipEvents; i < events.size(); i++) { base::TimeTicks& frame_tick = (*map)[events[i].frame_no]; if (frame_tick.is_null()) { frame_tick = events[i].render_time; } else { frame_tick = std::min(events[i].render_time, frame_tick); } } } void Analyze(const std::string& name, const std::string& modifier) { // First, find the minimum rtp timestamp for each audio and video frame. // Note that the data encoded in the audio stream contains video frame // numbers. So in a 30-fps video stream, there will be 1/30s of "1", then // 1/30s of "2", etc. TimeMap audio_frame_times, video_frame_times; MapFrameTimes(audio_events_, &audio_frame_times); MapFrameTimes(video_events_, &video_frame_times); std::vector<double> deltas; for (TimeMap::const_iterator i = audio_frame_times.begin(); i != audio_frame_times.end(); ++i) { TimeMap::const_iterator j = video_frame_times.find(i->first); if (j != video_frame_times.end()) { deltas.push_back((i->second - j->second).InMillisecondsF()); } } // Close to zero is better. (can be negative) MeanAndError(deltas).Print(name, modifier, "av_sync", "ms"); // lower is better. AnalyzeJitter(audio_events_).Print(name, modifier, "audio_jitter", "ms"); // lower is better. AnalyzeJitter(video_events_).Print(name, modifier, "video_jitter", "ms"); } private: // Invoked by InProcessReceiver for each received audio frame. void OnAudioFrame(std::unique_ptr<media::AudioBus> audio_frame, const base::TimeTicks& playout_time, bool is_continuous) override { CHECK(cast_env()->CurrentlyOn(media::cast::CastEnvironment::MAIN)); if (audio_frame->frames() <= 0) { NOTREACHED() << "OnAudioFrame called with no samples?!?"; return; } // Note: This is the number of the video frame that this audio belongs to. uint16_t frame_no; if (media::cast::DecodeTimestamp(audio_frame->channel(0), audio_frame->frames(), &frame_no)) { audio_events_.push_back(TimeData(frame_no, playout_time)); } else { VLOG(0) << "Failed to decode audio timestamp!"; } } void OnVideoFrame(const scoped_refptr<media::VideoFrame>& video_frame, const base::TimeTicks& render_time, bool is_continuous) override { CHECK(cast_env()->CurrentlyOn(media::cast::CastEnvironment::MAIN)); TRACE_EVENT_INSTANT1( "mirroring", "TestPatternReceiver::OnVideoFrame", TRACE_EVENT_SCOPE_THREAD, "render_time", render_time.ToInternalValue()); uint16_t frame_no; if (media::cast::test::DecodeBarcode(video_frame, &frame_no)) { video_events_.push_back(TimeData(frame_no, render_time)); } else { VLOG(0) << "Failed to decode barcode!"; } } std::vector<TimeData> audio_events_; std::vector<TimeData> video_events_; DISALLOW_COPY_AND_ASSIGN(TestPatternReceiver); }; class CastV2PerformanceTest : public ExtensionApiTest, public testing::WithParamInterface<int> { public: CastV2PerformanceTest() {} bool HasFlag(TestFlags flag) const { return (GetParam() & flag) == flag; } bool IsGpuAvailable() const { return base::CommandLine::ForCurrentProcess()->HasSwitch("enable-gpu"); } std::string GetSuffixForTestFlags() { std::string suffix; if (HasFlag(kUseGpu)) suffix += "_gpu"; if (HasFlag(kDisableVsync)) suffix += "_novsync"; if (HasFlag(kSmallWindow)) suffix += "_small"; if (HasFlag(k24fps)) suffix += "_24fps"; if (HasFlag(k30fps)) suffix += "_30fps"; if (HasFlag(k60fps)) suffix += "_60fps"; if (HasFlag(kProxyWifi)) suffix += "_wifi"; if (HasFlag(kProxyBad)) suffix += "_bad"; if (HasFlag(kSlowClock)) suffix += "_slow"; if (HasFlag(kFastClock)) suffix += "_fast"; return suffix; } int getfps() { if (HasFlag(k24fps)) return 24; if (HasFlag(k30fps)) return 30; if (HasFlag(k60fps)) return 60; NOTREACHED(); return 0; } net::IPEndPoint GetFreeLocalPort() { // Determine a unused UDP port for the in-process receiver to listen on. // Method: Bind a UDP socket on port 0, and then check which port the // operating system assigned to it. std::unique_ptr<net::UDPServerSocket> receive_socket( new net::UDPServerSocket(NULL, net::NetLog::Source())); receive_socket->AllowAddressReuse(); CHECK_EQ(net::OK, receive_socket->Listen( net::IPEndPoint(net::IPAddress::IPv4Localhost(), 0))); net::IPEndPoint endpoint; CHECK_EQ(net::OK, receive_socket->GetLocalAddress(&endpoint)); return endpoint; } void SetUp() override { EnablePixelOutput(); ExtensionApiTest::SetUp(); } void SetUpCommandLine(base::CommandLine* command_line) override { // Some of the tests may launch http requests through JSON or AJAX // which causes a security error (cross domain request) when the page // is loaded from the local file system ( file:// ). The following switch // fixes that error. command_line->AppendSwitch(switches::kAllowFileAccessFromFiles); if (HasFlag(kSmallWindow)) { command_line->AppendSwitchASCII(switches::kWindowSize, "800,600"); } else { command_line->AppendSwitchASCII(switches::kWindowSize, "2000,1500"); } if (!HasFlag(kUseGpu)) command_line->AppendSwitch(switches::kDisableGpu); if (HasFlag(kDisableVsync)) command_line->AppendSwitch(switches::kDisableGpuVsync); command_line->AppendSwitchASCII( extensions::switches::kWhitelistedExtensionID, kExtensionId); ExtensionApiTest::SetUpCommandLine(command_line); } void GetTraceEvents(trace_analyzer::TraceAnalyzer* analyzer, const std::string& event_name, trace_analyzer::TraceEventVector* events) { trace_analyzer::Query query = trace_analyzer::Query::EventNameIs(event_name) && (trace_analyzer::Query::EventPhaseIs(TRACE_EVENT_PHASE_BEGIN) || trace_analyzer::Query::EventPhaseIs(TRACE_EVENT_PHASE_ASYNC_BEGIN) || trace_analyzer::Query::EventPhaseIs(TRACE_EVENT_PHASE_FLOW_BEGIN) || trace_analyzer::Query::EventPhaseIs(TRACE_EVENT_PHASE_INSTANT) || trace_analyzer::Query::EventPhaseIs(TRACE_EVENT_PHASE_COMPLETE)); analyzer->FindEvents(query, events); } // The key contains the name of the argument and the argument. typedef std::pair<std::string, double> EventMapKey; typedef std::map<EventMapKey, const trace_analyzer::TraceEvent*> EventMap; // Make events findable by their arguments, for instance, if an // event has a "timestamp": 238724 argument, the map will contain // pair<"timestamp", 238724> -> &event. All arguments are indexed. void IndexEvents(trace_analyzer::TraceAnalyzer* analyzer, const std::string& event_name, EventMap* event_map) { trace_analyzer::TraceEventVector events; GetTraceEvents(analyzer, event_name, &events); for (size_t i = 0; i < events.size(); i++) { std::map<std::string, double>::const_iterator j; for (j = events[i]->arg_numbers.begin(); j != events[i]->arg_numbers.end(); ++j) { (*event_map)[*j] = events[i]; } } } // Look up an event in |event_map|. The return event will have the same // value for the argument |key_name| as |prev_event|. Note that if // the |key_name| is "time_delta", then we allow some fuzzy logic since // the time deltas are truncated to milliseconds in the code. const trace_analyzer::TraceEvent* FindNextEvent( const EventMap& event_map, std::vector<const trace_analyzer::TraceEvent*> prev_events, std::string key_name) { EventMapKey key; for (size_t i = prev_events.size(); i;) { --i; std::map<std::string, double>::const_iterator j = prev_events[i]->arg_numbers.find(key_name); if (j != prev_events[i]->arg_numbers.end()) { key = *j; break; } } EventMap::const_iterator i = event_map.lower_bound(key); if (i == event_map.end()) return NULL; if (i->first.second == key.second) return i->second; if (key_name != "time_delta") return NULL; if (fabs(i->first.second - key.second) < 1000) return i->second; if (i == event_map.begin()) return NULL; i--; if (fabs(i->first.second - key.second) < 1000) return i->second; return NULL; } // Given a vector of vector of data, extract the difference between // two columns (|col_a| and |col_b|) and output the result as a // performance metric. void OutputMeasurement(const std::string& test_name, const std::vector<std::vector<double> > data, const std::string& measurement_name, int col_a, int col_b) { std::vector<double> tmp; for (size_t i = 0; i < data.size(); i++) { tmp.push_back((data[i][col_b] - data[i][col_a]) / 1000.0); } return MeanAndError(tmp).Print(test_name, GetSuffixForTestFlags(), measurement_name, "ms"); } // Analyzing latency is hard, because there is no unifying identifier for // frames throughout the code. At first, we have a capture timestamp, which // gets converted to a time delta, then back to a timestamp. Once it enters // the cast library it gets converted to an rtp_timestamp, and when it leaves // the cast library, all we have is the render_time. // // To be able to follow the frame throughout all this, we insert TRACE // calls that tracks each conversion as it happens. Then we extract all // these events and link them together. void AnalyzeLatency(const std::string& test_name, trace_analyzer::TraceAnalyzer* analyzer) { EventMap onbuffer, sink, inserted, encoded, transmitted, decoded, done; IndexEvents(analyzer, "OnBufferReceived", &onbuffer); IndexEvents(analyzer, "MediaStreamVideoSink::OnVideoFrame", &sink); IndexEvents(analyzer, "InsertRawVideoFrame", &inserted); IndexEvents(analyzer, "VideoFrameEncoded", &encoded); IndexEvents(analyzer, "PullEncodedVideoFrame", &transmitted); IndexEvents(analyzer, "FrameDecoded", &decoded); IndexEvents(analyzer, "TestPatternReceiver::OnVideoFrame", &done); std::vector<std::pair<EventMap*, std::string> > event_maps; event_maps.push_back(std::make_pair(&onbuffer, "timestamp")); event_maps.push_back(std::make_pair(&sink, "time_delta")); event_maps.push_back(std::make_pair(&inserted, "timestamp")); event_maps.push_back(std::make_pair(&encoded, "rtp_timestamp")); event_maps.push_back(std::make_pair(&transmitted, "rtp_timestamp")); event_maps.push_back(std::make_pair(&decoded, "rtp_timestamp")); event_maps.push_back(std::make_pair(&done, "render_time")); trace_analyzer::TraceEventVector capture_events; GetTraceEvents(analyzer, "Capture" , &capture_events); EXPECT_GT(capture_events.size(), 0UL); std::vector<std::vector<double> > traced_frames; for (size_t i = kSkipEvents; i < capture_events.size(); i++) { std::vector<double> times; const trace_analyzer::TraceEvent *event = capture_events[i]; times.push_back(event->timestamp); // begin capture event = event->other_event; if (!event) { continue; } times.push_back(event->timestamp); // end capture (with timestamp) std::vector<const trace_analyzer::TraceEvent*> prev_events; prev_events.push_back(event); for (size_t j = 0; j < event_maps.size(); j++) { event = FindNextEvent(*event_maps[j].first, prev_events, event_maps[j].second); if (!event) { break; } prev_events.push_back(event); times.push_back(event->timestamp); } if (event) { // Successfully traced frame from beginning to end traced_frames.push_back(times); } } // 0 = capture begin // 1 = capture end // 2 = onbuffer // 3 = sink // 4 = inserted // 5 = encoded // 6 = transmitted // 7 = decoded // 8 = done // Lower is better for all of these. OutputMeasurement(test_name, traced_frames, "total_latency", 0, 8); OutputMeasurement(test_name, traced_frames, "capture_duration", 0, 1); OutputMeasurement(test_name, traced_frames, "send_to_renderer", 1, 3); OutputMeasurement(test_name, traced_frames, "encode", 3, 5); OutputMeasurement(test_name, traced_frames, "transmit", 5, 6); OutputMeasurement(test_name, traced_frames, "decode", 6, 7); OutputMeasurement(test_name, traced_frames, "cast_latency", 3, 8); } MeanAndError AnalyzeTraceDistance(trace_analyzer::TraceAnalyzer* analyzer, const std::string& event_name) { trace_analyzer::TraceEventVector events; GetTraceEvents(analyzer, event_name, &events); std::vector<double> deltas; for (size_t i = kSkipEvents + 1; i < events.size(); ++i) { double delta_micros = events[i]->timestamp - events[i - 1]->timestamp; deltas.push_back(delta_micros / 1000.0); } return MeanAndError(deltas); } void RunTest(const std::string& test_name) { if (HasFlag(kUseGpu) && !IsGpuAvailable()) { LOG(WARNING) << "Test skipped: requires gpu. Pass --enable-gpu on the command " "line if use of GPU is desired."; return; } ASSERT_EQ(1, (HasFlag(k24fps) ? 1 : 0) + (HasFlag(k30fps) ? 1 : 0) + (HasFlag(k60fps) ? 1 : 0)); net::IPEndPoint receiver_end_point = GetFreeLocalPort(); // Start the in-process receiver that examines audio/video for the expected // test patterns. base::TimeDelta delta = base::TimeDelta::FromSeconds(0); if (HasFlag(kFastClock)) { delta = base::TimeDelta::FromSeconds(10); } if (HasFlag(kSlowClock)) { delta = base::TimeDelta::FromSeconds(-10); } scoped_refptr<media::cast::StandaloneCastEnvironment> cast_environment( new SkewedCastEnvironment(delta)); TestPatternReceiver* const receiver = new TestPatternReceiver(cast_environment, receiver_end_point); receiver->Start(); std::unique_ptr<media::cast::test::UDPProxy> udp_proxy; if (HasFlag(kProxyWifi) || HasFlag(kProxyBad)) { net::IPEndPoint proxy_end_point = GetFreeLocalPort(); if (HasFlag(kProxyWifi)) { udp_proxy = media::cast::test::UDPProxy::Create( proxy_end_point, receiver_end_point, media::cast::test::WifiNetwork(), media::cast::test::WifiNetwork(), NULL); } else if (HasFlag(kProxyBad)) { udp_proxy = media::cast::test::UDPProxy::Create( proxy_end_point, receiver_end_point, media::cast::test::BadNetwork(), media::cast::test::BadNetwork(), NULL); } receiver_end_point = proxy_end_point; } std::string json_events; ASSERT_TRUE(tracing::BeginTracing( "test_fps,mirroring,gpu.capture,cast_perf_test")); const std::string page_url = base::StringPrintf( "performance%d.html?port=%d", getfps(), receiver_end_point.port()); ASSERT_TRUE(RunExtensionSubtest("cast_streaming", page_url)) << message_; ASSERT_TRUE(tracing::EndTracing(&json_events)); receiver->Stop(); // Stop all threads, removes the need for synchronization when analyzing // the data. cast_environment->Shutdown(); std::unique_ptr<trace_analyzer::TraceAnalyzer> analyzer; analyzer.reset(trace_analyzer::TraceAnalyzer::Create(json_events)); analyzer->AssociateAsyncBeginEndEvents(); MeanAndError frame_data = AnalyzeTraceDistance( analyzer.get(), "OnSwapCompositorFrame"); EXPECT_GT(frame_data.num_values, 0UL); // Lower is better. frame_data.Print(test_name, GetSuffixForTestFlags(), "time_between_frames", "ms"); // This prints out the average time between capture events. // As the capture frame rate is capped at 30fps, this score // cannot get any better than (lower) 33.33 ms. MeanAndError capture_data = AnalyzeTraceDistance(analyzer.get(), "Capture"); // Lower is better. capture_data.Print(test_name, GetSuffixForTestFlags(), "time_between_captures", "ms"); receiver->Analyze(test_name, GetSuffixForTestFlags()); AnalyzeLatency(test_name, analyzer.get()); } }; } // namespace IN_PROC_BROWSER_TEST_P(CastV2PerformanceTest, Performance) { RunTest("CastV2Performance"); } // Note: First argument is optional and intentionally left blank. // (it's a prefix for the generated test cases) INSTANTIATE_TEST_CASE_P( , CastV2PerformanceTest, testing::Values( kUseGpu | k24fps, kUseGpu | k30fps, kUseGpu | k60fps, kUseGpu | k24fps | kDisableVsync, kUseGpu | k30fps | kProxyWifi, kUseGpu | k30fps | kProxyBad, kUseGpu | k30fps | kSlowClock, kUseGpu | k30fps | kFastClock));
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.CodeGeneration Imports Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration Friend Class ParameterGenerator Public Shared Function GenerateParameterList(parameterDefinitions As ImmutableArray(Of IParameterSymbol), options As CodeGenerationOptions) As ParameterListSyntax Return GenerateParameterList(DirectCast(parameterDefinitions, IList(Of IParameterSymbol)), options) End Function Public Shared Function GenerateParameterList(parameterDefinitions As IEnumerable(Of IParameterSymbol), options As CodeGenerationOptions) As ParameterListSyntax Dim result = New List(Of ParameterSyntax)() Dim seenOptional = False For Each p In parameterDefinitions Dim generated = GenerateParameter(p, seenOptional, options) result.Add(generated) seenOptional = seenOptional OrElse generated.Default IsNot Nothing Next Return SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList(result)) End Function Friend Shared Function GenerateParameter(parameter As IParameterSymbol, seenOptional As Boolean, options As CodeGenerationOptions) As ParameterSyntax Dim reusableSyntax = GetReuseableSyntaxNodeForSymbol(Of ParameterSyntax)(parameter, options) If reusableSyntax IsNot Nothing Then Return reusableSyntax End If ' TODO(cyrusn): Should we provide some way to disable this special case? ' If the type is actually an array, then we place the array specifier on the identifier, ' not on the type syntax. If parameter.Type.IsArrayType() Then Dim arrayType = DirectCast(parameter.Type, IArrayTypeSymbol) Dim elementType = arrayType.ElementType If Not elementType.IsArrayType() AndAlso elementType.OriginalDefinition.SpecialType <> SpecialType.System_Nullable_T Then Dim arguments = Enumerable.Repeat(Of ArgumentSyntax)(SyntaxFactory.OmittedArgument(), arrayType.Rank) Dim argumentList = SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(arguments)) Return SyntaxFactory.Parameter( AttributeGenerator.GenerateAttributeBlocks(parameter.GetAttributes(), options), GenerateModifiers(parameter, seenOptional), parameter.Name.ToModifiedIdentifier.WithArrayBounds(argumentList), SyntaxFactory.SimpleAsClause(type:=elementType.GenerateTypeSyntax()), GenerateEqualsValue(parameter, seenOptional)) End If End If Dim asClause = If(parameter.Type Is Nothing, Nothing, SyntaxFactory.SimpleAsClause(type:=parameter.Type.GenerateTypeSyntax())) Return SyntaxFactory.Parameter( AttributeGenerator.GenerateAttributeBlocks(parameter.GetAttributes(), options), GenerateModifiers(parameter, seenOptional), parameter.Name.ToModifiedIdentifier(), asClause, GenerateEqualsValue(parameter, seenOptional)) End Function Private Shared Function GenerateModifiers(parameter As IParameterSymbol, seenOptional As Boolean) As SyntaxTokenList If parameter.IsParams Then Return SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.ParamArrayKeyword)) End If Dim modifiers = SyntaxFactory.TokenList() If parameter.IsRefOrOut() Then modifiers = modifiers.Add(SyntaxFactory.Token(SyntaxKind.ByRefKeyword)) End If If parameter.IsOptional OrElse seenOptional Then modifiers = modifiers.Add(SyntaxFactory.Token(SyntaxKind.OptionalKeyword)) End If Return modifiers End Function Private Shared Function GenerateEqualsValue(parameter As IParameterSymbol, seenOptional As Boolean) As EqualsValueSyntax If parameter.HasExplicitDefaultValue OrElse parameter.IsOptional OrElse seenOptional Then Return SyntaxFactory.EqualsValue( ExpressionGenerator.GenerateExpression( parameter.Type, If(parameter.HasExplicitDefaultValue, parameter.ExplicitDefaultValue, Nothing), canUseFieldReference:=True)) End If Return Nothing End Function End Class End Namespace
from azure.identity import DefaultAzureCredential from azure.mgmt.apimanagement import ApiManagementClient """ # PREREQUISITES pip install azure-identity pip install azure-mgmt-apimanagement # USAGE python api_management_create_api_operation_policy.py Before run the sample, please set the values of the client ID, tenant ID and client secret of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET. For more info about how to get the value, please see: https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal """ def main(): client = ApiManagementClient( credential=DefaultAzureCredential(), subscription_id="subid", ) response = client.api_operation_policy.create_or_update( resource_group_name="rg1", service_name="apimService1", api_id="5600b57e7e8880006a040001", operation_id="5600b57e7e8880006a080001", policy_id="policy", parameters={ "properties": { "format": "xml", "value": "<policies> <inbound /> <backend> <forward-request /> </backend> <outbound /></policies>", } }, ) print(response) # x-ms-original-file: specification/apimanagement/resource-manager/Microsoft.ApiManagement/stable/2021-08-01/examples/ApiManagementCreateApiOperationPolicy.json if __name__ == "__main__": main()
namespace content { class LocalTimeDelta; class LocalTimeTicks; class RemoteTimeDelta; class RemoteTimeTicks; // On Windows, TimeTicks are not consistent between processes. Often, the values // on one process have a static offset relative to another. Occasionally, these // offsets shift while running. // // To combat this, any TimeTicks values sent from the remote process to the // local process must be tweaked in order to appear monotonic. // // In order to properly tweak ticks, we need 4 reference points: // // - |local_lower_bound|: A known point, recorded on the local process, that // occurs before any remote values that will be // converted. // - |remote_lower_bound|: The equivalent point on the remote process. This // should be recorded immediately after // |local_lower_bound|. // - |local_upper_bound|: A known point, recorded on the local process, that // occurs after any remote values that will be // converted. // - |remote_upper_bound|: The equivalent point on the remote process. This // should be recorded immediately before // |local_upper_bound|. // // Once these bounds are determined, values within the remote process's range // can be converted to the local process's range. The values are converted as // follows: // // 1. If the remote's range exceeds the local's range, it is scaled to fit. // Any values converted will have the same scale factor applied. // // 2. The remote's range is shifted so that it is centered within the // local's range. Any values converted will be shifted the same amount. class CONTENT_EXPORT InterProcessTimeTicksConverter { public: InterProcessTimeTicksConverter(const LocalTimeTicks& local_lower_bound, const LocalTimeTicks& local_upper_bound, const RemoteTimeTicks& remote_lower_bound, const RemoteTimeTicks& remote_upper_bound); // Returns the value within the local's bounds that correlates to // |remote_ms|. LocalTimeTicks ToLocalTimeTicks(const RemoteTimeTicks& remote_ms) const; // Returns the equivalent delta after applying remote-to-local scaling to // |remote_delta|. LocalTimeDelta ToLocalTimeDelta(const RemoteTimeDelta& remote_delta) const; // Returns true iff the TimeTicks are converted by adding a constant, without // scaling. This is the case whenever the remote timespan is smaller than the // local timespan, which should be the majority of cases due to IPC overhead. bool IsSkewAdditiveForMetrics() const; // Returns the (remote time) - (local time) difference estimated by the // converter. This is the constant that is subtracted from remote TimeTicks to // get local TimeTicks when no scaling is applied. base::TimeDelta GetSkewForMetrics() const; private: int64 Convert(int64 value) const; // The local time which |remote_lower_bound_| is mapped to. int64 local_base_time_; int64 numerator_; int64 denominator_; int64 remote_lower_bound_; int64 remote_upper_bound_; }; class CONTENT_EXPORT LocalTimeDelta { public: int ToInt32() const { return value_; } private: friend class InterProcessTimeTicksConverter; friend class LocalTimeTicks; LocalTimeDelta(int value) : value_(value) {} int value_; }; class CONTENT_EXPORT LocalTimeTicks { public: static LocalTimeTicks FromTimeTicks(const base::TimeTicks& value) { return LocalTimeTicks(value.ToInternalValue()); } base::TimeTicks ToTimeTicks() { return base::TimeTicks::FromInternalValue(value_); } LocalTimeTicks operator+(const LocalTimeDelta& delta) { return LocalTimeTicks(value_ + delta.value_); } private: friend class InterProcessTimeTicksConverter; LocalTimeTicks(int64 value) : value_(value) {} int64 value_; }; class CONTENT_EXPORT RemoteTimeDelta { public: static RemoteTimeDelta FromRawDelta(int delta) { return RemoteTimeDelta(delta); } private: friend class InterProcessTimeTicksConverter; friend class RemoteTimeTicks; RemoteTimeDelta(int value) : value_(value) {} int value_; }; class CONTENT_EXPORT RemoteTimeTicks { public: static RemoteTimeTicks FromTimeTicks(const base::TimeTicks& ticks) { return RemoteTimeTicks(ticks.ToInternalValue()); } RemoteTimeDelta operator-(const RemoteTimeTicks& rhs) const { return RemoteTimeDelta(value_ - rhs.value_); } private: friend class InterProcessTimeTicksConverter; RemoteTimeTicks(int64 value) : value_(value) {} int64 value_; }; } // namespace content #endif // CONTENT_COMMON_INTER_PROCESS_TIME_TICKS_CONVERTER_H_
/* * File: CrashFault.cpp * Author: rmartins * * Created on February 8, 2011, 3:16 PM */ #include "CrashFault.h" CrashFault::CrashFault(int level,ACE_Time_Value& startTime): Fault(Fault::CRASH_FAULT,level,startTime) { } CrashFault::CrashFault(const CrashFault& orig): Fault(orig) { } CrashFault::~CrashFault() { }
 CKEDITOR.plugins.setLang( 'smiley', 'de-ch', { options: 'Smiley-Optionen', title: 'Smiley auswählen', toolbar: 'Smiley' } );
class Tab; namespace gfx { class Point; } namespace ui { class ListSelectionModel; class LocatedEvent; class MouseEvent; } namespace views { class View; } // Controller for tabs. class TabController { public: virtual const ui::ListSelectionModel& GetSelectionModel() = 0; // Returns true if multiple selection is supported. virtual bool SupportsMultipleSelection() = 0; // Selects the tab. virtual void SelectTab(Tab* tab) = 0; // Extends the selection from the anchor to |tab|. virtual void ExtendSelectionTo(Tab* tab) = 0; // Toggles whether |tab| is selected. virtual void ToggleSelected(Tab* tab) = 0; // Adds the selection from the anchor to |tab|. virtual void AddSelectionFromAnchorTo(Tab* tab) = 0; // Closes the tab. virtual void CloseTab(Tab* tab, CloseTabSource source) = 0; // Toggles whether tab-wide audio muting is active. virtual void ToggleTabAudioMute(Tab* tab) = 0; // Shows a context menu for the tab at the specified point in screen coords. virtual void ShowContextMenuForTab(Tab* tab, const gfx::Point& p, ui::MenuSourceType source_type) = 0; // Returns true if |tab| is the active tab. The active tab is the one whose // content is shown in the browser. virtual bool IsActiveTab(const Tab* tab) const = 0; // Returns true if the specified Tab is selected. virtual bool IsTabSelected(const Tab* tab) const = 0; // Returns true if the specified Tab is pinned. virtual bool IsTabPinned(const Tab* tab) const = 0; // Potentially starts a drag for the specified Tab. virtual void MaybeStartDrag( Tab* tab, const ui::LocatedEvent& event, const ui::ListSelectionModel& original_selection) = 0; // Continues dragging a Tab. virtual void ContinueDrag(views::View* view, const ui::LocatedEvent& event) = 0; // Ends dragging a Tab. Returns whether the tab has been destroyed. virtual bool EndDrag(EndDragReason reason) = 0; // Returns the tab that contains the specified coordinates, in terms of |tab|, // or NULL if there is no tab that contains the specified point. virtual Tab* GetTabAt(Tab* tab, const gfx::Point& tab_in_tab_coordinates) = 0; // Invoked when a mouse event occurs on |source|. virtual void OnMouseEventInTab(views::View* source, const ui::MouseEvent& event) = 0; // Returns true if |tab| needs to be painted. If false is returned the tab is // not painted. If true is returned the tab should be painted and |clip| is // set to the clip (if |clip| is empty means no clip). virtual bool ShouldPaintTab(const Tab* tab, gfx::Rect* clip) = 0; // Returns true if tabs painted in the rectangular light-bar style. virtual bool IsImmersiveStyle() const = 0; // Adds private information to the tab's accessibility state. virtual void UpdateTabAccessibilityState(const Tab* tab, ui::AXViewState* state) = 0; protected: virtual ~TabController() {} }; #endif // CHROME_BROWSER_UI_VIEWS_TABS_TAB_CONTROLLER_H_
package com.intellij.openapi.vcs.changes; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Computable; import com.intellij.openapi.vcs.AbstractVcs; import com.intellij.openapi.vcs.FilePath; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.vcsUtil.VcsUtil; import java.util.*; /** * @author max */ public class VirtualFileHolder implements FileHolder { private final Set<VirtualFile> myFiles = new HashSet<VirtualFile>(); private final Project myProject; private final HolderType myType; private int myNumDirs; public VirtualFileHolder(Project project, final HolderType type) { myProject = project; myType = type; } public HolderType getType() { return myType; } @Override public void notifyVcsStarted(AbstractVcs vcs) { } public void cleanAll() { myFiles.clear(); myNumDirs = 0; } // returns number of removed directories static int cleanScope(final Project project, final Collection<VirtualFile> files, final VcsModifiableDirtyScope scope) { return ApplicationManager.getApplication().runReadAction(new Computable<Integer>() { public Integer compute() { int result = 0; // to avoid deadlocks caused by incorrect lock ordering, need to lock on this after taking read action if (project.isDisposed() || files.isEmpty()) return 0; if (scope.getRecursivelyDirtyDirectories().size() == 0) { final Set<FilePath> dirtyFiles = scope.getDirtyFiles(); boolean cleanDroppedFiles = false; for(FilePath dirtyFile: dirtyFiles) { VirtualFile f = dirtyFile.getVirtualFile(); if (f != null) { if (files.remove(f)) { if (f.isDirectory()) ++ result; } } else { cleanDroppedFiles = true; } } if (cleanDroppedFiles) { for (Iterator<VirtualFile> iterator = files.iterator(); iterator.hasNext();) { final VirtualFile file = iterator.next(); if (fileDropped(file)) { iterator.remove(); scope.addDirtyFile(VcsUtil.getFilePath(file)); if (file.isDirectory()) ++ result; } } } } else { for (Iterator<VirtualFile> iterator = files.iterator(); iterator.hasNext();) { final VirtualFile file = iterator.next(); final boolean fileDropped = fileDropped(file); if (fileDropped) { scope.addDirtyFile(VcsUtil.getFilePath(file)); } if (fileDropped || scope.belongsTo(VcsUtil.getFilePath(file))) { iterator.remove(); if (file.isDirectory()) ++ result; } } } return result; } }); } public void cleanAndAdjustScope(final VcsModifiableDirtyScope scope) { myNumDirs -= cleanScope(myProject, myFiles, scope); } private static boolean fileDropped(final VirtualFile file) { return ! file.isValid(); } public void addFile(VirtualFile file) { if (myFiles.add(file)) { if (file.isDirectory()) { ++myNumDirs; } } } public void removeFile(VirtualFile file) { if (myFiles.remove(file)) { if (file.isDirectory()) { -- myNumDirs; } } } // todo track number of copies made public List<VirtualFile> getFiles() { return new ArrayList<VirtualFile>(myFiles); } public VirtualFileHolder copy() { final VirtualFileHolder copyHolder = new VirtualFileHolder(myProject, myType); copyHolder.myFiles.addAll(myFiles); copyHolder.myNumDirs = myNumDirs; return copyHolder; } public boolean containsFile(final VirtualFile file) { return myFiles.contains(file); } public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final VirtualFileHolder that = (VirtualFileHolder)o; if (!myFiles.equals(that.myFiles)) return false; return true; } public int hashCode() { return myFiles.hashCode(); } public int getSize() { return myFiles.size(); } public int getNumDirs() { assert myNumDirs >= 0; return myNumDirs; } }
from django.core.management import call_command from django.test import override_settings from .test_base import MigrationTestBase class Tests(MigrationTestBase): """ Deprecated model fields should still be usable in historic migrations. """ @override_settings(MIGRATION_MODULES={"migrations": "migrations.deprecated_field_migrations"}) def test_migrate(self): # Make sure no tables are created self.assertTableNotExists("migrations_ipaddressfield") # Run migration call_command("migrate", verbosity=0) # Make sure the right tables exist self.assertTableExists("migrations_ipaddressfield") # Unmigrate everything call_command("migrate", "migrations", "zero", verbosity=0) # Make sure it's all gone self.assertTableNotExists("migrations_ipaddressfield")
import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams, MenuController } from 'ionic-angular'; import { AngularFireDatabaseModule, AngularFireDatabase, FirebaseListObservable } from 'angularfire2/database'; import { AngularFireAuthModule, AngularFireAuth } from 'angularfire2/auth'; import * as firebase from 'firebase/app'; import { Api } from '../../providers/api'; import { Observable } from 'rxjs/Observable'; import { TutorialPage } from "../tutorial/tutorial"; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/toPromise'; //@IonicPage() @Component({ selector: 'page-logout', templateUrl: 'logout.html' }) export class LogoutPage { constructor(public navCtrl: NavController, public navParams: NavParams, public api : Api, public menuCtrl: MenuController) { } doLogout(){ var result:any = this.api.doLogOut(); let res = Observable.fromPromise(result); res.subscribe(res => { if (res instanceof Error){ } else { this.navCtrl.push(TutorialPage); } }) } ionViewDidLoad() { this.menuCtrl.close(); } }
<?xml version="1.0" encoding="UTF-8"?> <project version="4"> <component name="ProjectInspectionProfilesVisibleTreeState"> <entry key="Project Default"> <profile-state> <expanded-state> <State> <id /> </State> </expanded-state> <selected-state> <State> <id>CSS</id> </State> </selected-state> </profile-state> </entry> </component> <component name="ProjectLevelVcsManager" settingsEditedManually="false"> <OptionsSetting value="true" id="Add" /> <OptionsSetting value="true" id="Remove" /> <OptionsSetting value="true" id="Checkout" /> <OptionsSetting value="true" id="Update" /> <OptionsSetting value="true" id="Status" /> <OptionsSetting value="true" id="Edit" /> <OptionsSetting value="true" id="添加" /> <OptionsSetting value="true" id="移除" /> <OptionsSetting value="true" id="签出" /> <OptionsSetting value="true" id="更新" /> <OptionsSetting value="true" id="状态" /> <OptionsSetting value="true" id="编辑" /> <ConfirmationsSetting value="0" id="添加" /> <ConfirmationsSetting value="0" id="移除" /> </component> </project>
<?xml version="1.0" encoding="utf-8"?> <android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" style="@style/CardViewStyle" android:layout_width="match_parent" android:layout_height="wrap_content"> <com.etiennelawlor.quickreturn.views.CustomFontTextView android:id="@+id/country_tv" android:layout_width="match_parent" android:layout_height="100dp" android:gravity="center_vertical" android:textSize="16sp" android:padding="16dp" android:minHeight="?android:attr/listPreferredItemHeight" app:textFont="Roboto_Bold" android:background="?android:attr/selectableItemBackground" android:clickable="true" /> </android.support.v7.widget.CardView>
/** * Module dependencies. */ var Node = require('./node'); /** * Initialize a `Code` node with the given code `val`. * Code may also be optionally buffered and escaped. * * @param {String} val * @param {Boolean} buffer * @param {Boolean} escape * @api public */ var Code = module.exports = function Code(val, buffer, escape) { this.val = val; this.buffer = buffer; this.escape = escape; if (val.match(/^ *else/)) this.debug = false; }; /** * Inherit from `Node`. */ Code.prototype.__proto__ = Node.prototype;
using System; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Azure; using Azure.Core; using Azure.Core.Pipeline; using Azure.ResourceManager.DataFactory.Models; namespace Azure.ResourceManager.DataFactory { internal partial class PipelineRunsRestOperations { private readonly TelemetryDetails _userAgent; private readonly HttpPipeline _pipeline; private readonly Uri _endpoint; private readonly string _apiVersion; /// <summary> Initializes a new instance of PipelineRunsRestOperations. </summary> /// <param name="pipeline"> The HTTP pipeline for sending and receiving REST requests and responses. </param> /// <param name="applicationId"> The application id to use for user agent. </param> /// <param name="endpoint"> server parameter. </param> /// <param name="apiVersion"> Api Version. </param> /// <exception cref="ArgumentNullException"> <paramref name="pipeline"/> or <paramref name="apiVersion"/> is null. </exception> public PipelineRunsRestOperations(HttpPipeline pipeline, string applicationId, Uri endpoint = null, string apiVersion = default) { _pipeline = pipeline ?? throw new ArgumentNullException(nameof(pipeline)); _endpoint = endpoint ?? new Uri("https://management.azure.com"); _apiVersion = apiVersion ?? "2018-06-01"; _userAgent = new TelemetryDetails(GetType().Assembly, applicationId); } internal HttpMessage CreateQueryByFactoryRequest(string subscriptionId, string resourceGroupName, string factoryName, RunFilterContent content) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Post; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.DataFactory/factories/", false); uri.AppendPath(factoryName, true); uri.AppendPath("/queryPipelineRuns", false); uri.AppendQuery("api-version", _apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); request.Headers.Add("Content-Type", "application/json"); var content0 = new Utf8JsonRequestContent(); content0.JsonWriter.WriteObjectValue(content); request.Content = content0; _userAgent.Apply(message); return message; } /// <summary> Query pipeline runs in the factory based on input filter conditions. </summary> /// <param name="subscriptionId"> The subscription identifier. </param> /// <param name="resourceGroupName"> The resource group name. </param> /// <param name="factoryName"> The factory name. </param> /// <param name="content"> Parameters to filter the pipeline run. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="factoryName"/> or <paramref name="content"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="factoryName"/> is an empty string, and was expected to be non-empty. </exception> public async Task<Response<FactoryPipelineRunsQueryResult>> QueryByFactoryAsync(string subscriptionId, string resourceGroupName, string factoryName, RunFilterContent content, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(factoryName, nameof(factoryName)); Argument.AssertNotNull(content, nameof(content)); using var message = CreateQueryByFactoryRequest(subscriptionId, resourceGroupName, factoryName, content); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { FactoryPipelineRunsQueryResult value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = FactoryPipelineRunsQueryResult.DeserializeFactoryPipelineRunsQueryResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw new RequestFailedException(message.Response); } } /// <summary> Query pipeline runs in the factory based on input filter conditions. </summary> /// <param name="subscriptionId"> The subscription identifier. </param> /// <param name="resourceGroupName"> The resource group name. </param> /// <param name="factoryName"> The factory name. </param> /// <param name="content"> Parameters to filter the pipeline run. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="factoryName"/> or <paramref name="content"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="factoryName"/> is an empty string, and was expected to be non-empty. </exception> public Response<FactoryPipelineRunsQueryResult> QueryByFactory(string subscriptionId, string resourceGroupName, string factoryName, RunFilterContent content, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(factoryName, nameof(factoryName)); Argument.AssertNotNull(content, nameof(content)); using var message = CreateQueryByFactoryRequest(subscriptionId, resourceGroupName, factoryName, content); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { FactoryPipelineRunsQueryResult value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = FactoryPipelineRunsQueryResult.DeserializeFactoryPipelineRunsQueryResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw new RequestFailedException(message.Response); } } internal HttpMessage CreateGetRequest(string subscriptionId, string resourceGroupName, string factoryName, string runId) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.DataFactory/factories/", false); uri.AppendPath(factoryName, true); uri.AppendPath("/pipelineruns/", false); uri.AppendPath(runId, true); uri.AppendQuery("api-version", _apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); _userAgent.Apply(message); return message; } /// <summary> Get a pipeline run by its run ID. </summary> /// <param name="subscriptionId"> The subscription identifier. </param> /// <param name="resourceGroupName"> The resource group name. </param> /// <param name="factoryName"> The factory name. </param> /// <param name="runId"> The pipeline run identifier. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="factoryName"/> or <paramref name="runId"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="factoryName"/> or <paramref name="runId"/> is an empty string, and was expected to be non-empty. </exception> public async Task<Response<FactoryPipelineRunInfo>> GetAsync(string subscriptionId, string resourceGroupName, string factoryName, string runId, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(factoryName, nameof(factoryName)); Argument.AssertNotNullOrEmpty(runId, nameof(runId)); using var message = CreateGetRequest(subscriptionId, resourceGroupName, factoryName, runId); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { FactoryPipelineRunInfo value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = FactoryPipelineRunInfo.DeserializeFactoryPipelineRunInfo(document.RootElement); return Response.FromValue(value, message.Response); } default: throw new RequestFailedException(message.Response); } } /// <summary> Get a pipeline run by its run ID. </summary> /// <param name="subscriptionId"> The subscription identifier. </param> /// <param name="resourceGroupName"> The resource group name. </param> /// <param name="factoryName"> The factory name. </param> /// <param name="runId"> The pipeline run identifier. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="factoryName"/> or <paramref name="runId"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="factoryName"/> or <paramref name="runId"/> is an empty string, and was expected to be non-empty. </exception> public Response<FactoryPipelineRunInfo> Get(string subscriptionId, string resourceGroupName, string factoryName, string runId, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(factoryName, nameof(factoryName)); Argument.AssertNotNullOrEmpty(runId, nameof(runId)); using var message = CreateGetRequest(subscriptionId, resourceGroupName, factoryName, runId); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { FactoryPipelineRunInfo value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = FactoryPipelineRunInfo.DeserializeFactoryPipelineRunInfo(document.RootElement); return Response.FromValue(value, message.Response); } default: throw new RequestFailedException(message.Response); } } internal HttpMessage CreateCancelRequest(string subscriptionId, string resourceGroupName, string factoryName, string runId, bool? isRecursive) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Post; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.DataFactory/factories/", false); uri.AppendPath(factoryName, true); uri.AppendPath("/pipelineruns/", false); uri.AppendPath(runId, true); uri.AppendPath("/cancel", false); if (isRecursive != null) { uri.AppendQuery("isRecursive", isRecursive.Value, true); } uri.AppendQuery("api-version", _apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); _userAgent.Apply(message); return message; } /// <summary> Cancel a pipeline run by its run ID. </summary> /// <param name="subscriptionId"> The subscription identifier. </param> /// <param name="resourceGroupName"> The resource group name. </param> /// <param name="factoryName"> The factory name. </param> /// <param name="runId"> The pipeline run identifier. </param> /// <param name="isRecursive"> If true, cancel all the Child pipelines that are triggered by the current pipeline. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="factoryName"/> or <paramref name="runId"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="factoryName"/> or <paramref name="runId"/> is an empty string, and was expected to be non-empty. </exception> public async Task<Response> CancelAsync(string subscriptionId, string resourceGroupName, string factoryName, string runId, bool? isRecursive = null, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(factoryName, nameof(factoryName)); Argument.AssertNotNullOrEmpty(runId, nameof(runId)); using var message = CreateCancelRequest(subscriptionId, resourceGroupName, factoryName, runId, isRecursive); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: return message.Response; default: throw new RequestFailedException(message.Response); } } /// <summary> Cancel a pipeline run by its run ID. </summary> /// <param name="subscriptionId"> The subscription identifier. </param> /// <param name="resourceGroupName"> The resource group name. </param> /// <param name="factoryName"> The factory name. </param> /// <param name="runId"> The pipeline run identifier. </param> /// <param name="isRecursive"> If true, cancel all the Child pipelines that are triggered by the current pipeline. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="factoryName"/> or <paramref name="runId"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="factoryName"/> or <paramref name="runId"/> is an empty string, and was expected to be non-empty. </exception> public Response Cancel(string subscriptionId, string resourceGroupName, string factoryName, string runId, bool? isRecursive = null, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(factoryName, nameof(factoryName)); Argument.AssertNotNullOrEmpty(runId, nameof(runId)); using var message = CreateCancelRequest(subscriptionId, resourceGroupName, factoryName, runId, isRecursive); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: return message.Response; default: throw new RequestFailedException(message.Response); } } } }
package com.google.common.primitives; import com.google.common.collect.ImmutableSet; import com.google.common.testing.NullPointerTester; import junit.framework.TestCase; import java.util.Set; /** * Unit test for {@link Primitives}. * * @author Kevin Bourrillion */ public class PrimitivesTest extends TestCase { public void testIsWrapperType() { assertTrue(Primitives.isWrapperType(Void.class)); assertFalse(Primitives.isWrapperType(void.class)); } public void testWrap() { assertSame(Integer.class, Primitives.wrap(int.class)); assertSame(Integer.class, Primitives.wrap(Integer.class)); assertSame(String.class, Primitives.wrap(String.class)); } public void testUnwrap() { assertSame(int.class, Primitives.unwrap(Integer.class)); assertSame(int.class, Primitives.unwrap(int.class)); assertSame(String.class, Primitives.unwrap(String.class)); } public void testAllPrimitiveTypes() { Set<Class<?>> primitives = Primitives.allPrimitiveTypes(); assertEquals( ImmutableSet.<Object>of( boolean.class, byte.class, char.class, double.class, float.class, int.class, long.class, short.class, void.class), primitives); try { primitives.remove(boolean.class); fail(); } catch (UnsupportedOperationException expected) { } } public void testAllWrapperTypes() { Set<Class<?>> wrappers = Primitives.allWrapperTypes(); assertEquals( ImmutableSet.<Object>of( Boolean.class, Byte.class, Character.class, Double.class, Float.class, Integer.class, Long.class, Short.class, Void.class), wrappers); try { wrappers.remove(Boolean.class); fail(); } catch (UnsupportedOperationException expected) { } } public void testNullPointerExceptions() throws Exception { NullPointerTester tester = new NullPointerTester(); tester.testAllPublicStaticMethods(Primitives.class); } }
var jwt = require("jwt-simple"); // var Promise = require('bluebird'); var Models = require('../db/models.js'); var Collections = require('../db/collections.js'); var User = Models.User; var List = Models.List; var Lists = Collections.Lists; var secret = "MYWITTYSECRET"; module.exports = { // Gets the user by the id passed in API call // and sends it to the next method getUserById: function(req, res, next, userId){ User.forge({id: userId}) .fetch() .then(function (user){ if(!user){ throw new Error('user not found'); } req.user = user; next(); }) .catch(function (error){ console.log(error); }) }, // Adds the list to database according to user addList: function(req, res) { var name = req.body.name; List.forge({ name: name, user_id: req.user.id }) .save() .then(function (list) { if (!list) { throw new Error('Error creating list'); } res.sendStatus(201); }) .catch(function (error) { console.log(error); }); }, // Fetches the user's lists getLists: function(req, res){ Lists.query("where", "user_id", "=", req.user.id) .fetch() .then(function (lists){ if(!lists){ throw new Error('user does not have any lists'); } res.json(lists); }) .catch(function (error){ console.log(error); }); }, // Adds the user to the database and sends back a token. signup: function(req, res){ var username = req.body.username; var password = req.body.password; User.forge({ username: username }) .fetch() .then(function (user){ if (!user){ return User.forge({ username: username }) .save(); } else { throw new Error('User already exists.'); } }) .then(function (newUser){ return newUser.hashPassword(password); }) .then(function (user){ if (!user){ throw new Error('User creation failed.'); } res.json({ token: jwt.encode(user, secret), userId: user.id }); }) .catch(function (error){ console.log(error); }); }, // Checks that the user is in the database and sends back a token signin: function(req, res){ var username = req.body.username; var password = req.body.password; var foundUser; User.forge({ username: username }) .fetch() .then(function (user){ if(!user){ throw new Error('User does not exist. Go sign up.'); } foundUser = user; return user.comparePassword(password); }) .then(function (passwordMatch){ if(!passwordMatch){ throw new Error('Incorrect password.'); } res.json({ token: jwt.encode(foundUser, secret), userId: foundUser.id }) }) .catch(function (error){ console.log(error); }); } }
import React from 'react'; import { Link } from 'react-router'; import APPCONFIG from 'constants/Config'; import Converter from 'utils/converter' import QueueAnim from 'rc-queue-anim'; import PrefecturesChart from './PrefecturesChart'; import AquisitionChart from './AquisitionChart'; import StatBoxes from './StatBoxes'; import EngagementStats from './EngagementStats'; import BenchmarkChart from './BenchmarkChart'; const SelectionChart = (props) => ( <div className="row"> <div className="col-xl-10"> <div className="box box-default"> <div className="box-header">{props.title}</div> <div className="box-body"> <PrefecturesChart stats={props.stats} /> </div> </div> </div> </div> ); const TimeStats = (props) => ( <div className="box box-default"> <div className="box-body"> <div className="row"> <div className="col-xl-8"> <div className="box box-transparent"> <div className="box-header">{props.title}</div> <div className="box-body"> <div className="row text-center metrics"> <div className="col-xs-6 col-md-3 metric-box"> <span className="metric">{props.stats.getIn([props.type,'day']) || 0}</span> <span className="metric-info">Hari Ini</span> </div> <div className="col-xs-6 col-md-3 metric-box"> <span className="metric">{props.stats.getIn([props.type,'week']) || 0}</span> <span className="metric-info">Pekan Ini</span> </div> <div className="col-xs-6 col-md-3 metric-box"> <span className="metric">{props.stats.getIn([props.type,'month']) || 0}</span> <span className="metric-info">Bulan Ini</span> </div> <div className="col-xs-6 col-md-3 metric-box"> <span className="metric">{props.stats.getIn([props.type,'year']) || 0}</span> <span className="metric-info">Tahun Ini</span> </div> </div> </div> </div> </div> </div> </div> </div> ); export class DataGraph extends React.Component { constructor() { super(); this.state = { brand: APPCONFIG.brand }; } componentWillMount() { console.log('componentWillMount', this.state, this.props) if ( !this.props.token ) { console.log('should change location'); setTimeout(() => { this.props.router.push('/admin/') // XXX hardwired. See XXX }, 10) } this.dashboardForms = ['LaporDiri'] try { switch(this.props.fungsi) { case 'admin': this.dashboardForms = ['LaporDiri', 'PermohonanPaspor', 'LaporanKemajuanStudi', 'LaporanKelulusan', 'LaporanKepulangan', 'PemilikBarangPindahan'] break case 'keuangan': this.dashboardForms = ['LaporanKepulangan', 'PemilikBarangPindahan'] break case 'dikbud': this.dashboardForms = ['LaporDiri', 'LaporanKemajuanStudi', 'LaporanKelulusan' ] break case 'imigrasi': this.dashboardForms = ['LaporDiri', 'PermohonanPaspor', 'LaporanKepulangan'] break default: this.dashboardForms = ['LaporDiri', 'LaporanKepulangan'] } } catch(e) {} this.dashboardForms.forEach((v) => this.props.getSelectionStats(v, 'almtJpProv', 'prefecture')) // this.props.getSelectionStats('LaporDiri', 'almtJpProv', 'prefecture') } componentWillReceiveProps(nextProps) { if (!nextProps.apiLoading && this.props.apiLoading) { console.log('componentWillReceiveProps', nextProps, this.props) // if (nextProps.token && !this.props.token) { // setTimeout(() => { // this.props.router.push('/app') // }, 10) // } if (nextProps.apiError && nextProps.apiErrorData) { // console.log('error', nextProps.apiErrorData) switch (nextProps.apiErrorData.code) { case 'no token': break default: this.setState({message:'Maaf, ada masalah dengan sistem.'}) } } } } // <div key="1"><SelectionChart title="Lapor Diri per Provinsi" stats={this.props.selectionStats.get('LaporDiri')} /></div> // <div key="2"><SelectionChart title="Permohonan Paspor per Provinsi" /></div> render() { return ( <div className="container-fluid no-breadcrumbs with-maxwidth chapter"> <article className="article"> <h2 className="article-title">Data Grafik</h2> <QueueAnim type="bottom" className="ui-animate"> {this.dashboardForms.map((v,idx) => (<SelectionChart key={idx} title={Converter.camelCasetoTitle(v)} stats={this.props.selectionStats.get(v)} />))} </QueueAnim> </article> </div> ); } } export default DataGraph
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.prestosql.parquet.dictionary; import io.prestosql.parquet.DictionaryPage; import parquet.io.api.Binary; import java.io.IOException; import static com.google.common.base.MoreObjects.toStringHelper; import static com.google.common.base.Preconditions.checkArgument; import static parquet.bytes.BytesUtils.readIntLittleEndian; public class BinaryDictionary extends Dictionary { private final Binary[] content; public BinaryDictionary(DictionaryPage dictionaryPage) throws IOException { this(dictionaryPage, null); } public BinaryDictionary(DictionaryPage dictionaryPage, Integer length) throws IOException { super(dictionaryPage.getEncoding()); byte[] dictionaryBytes = dictionaryPage.getSlice().getBytes(); content = new Binary[dictionaryPage.getDictionarySize()]; int offset = 0; if (length == null) { for (int i = 0; i < content.length; i++) { int len = readIntLittleEndian(dictionaryBytes, offset); offset += 4; content[i] = Binary.fromByteArray(dictionaryBytes, offset, len); offset += len; } } else { checkArgument(length > 0, "Invalid byte array length: %s", length); for (int i = 0; i < content.length; i++) { content[i] = Binary.fromByteArray(dictionaryBytes, offset, length); offset += length; } } } @Override public Binary decodeToBinary(int id) { return content[id]; } @Override public String toString() { return toStringHelper(this) .add("content", content) .toString(); } }
/* * Created by IntelliJ IDEA. * User: dsl * Date: 09.07.2002 * Time: 15:41:29 * To change template for new class use * Code Style | Class Templates options (Tools | IDE Options). */ package com.intellij.refactoring.classMembers; import com.intellij.psi.PsiElement; import java.util.Collection; public class MemberInfoChange<T extends PsiElement, U extends MemberInfoBase<T>> { private final Collection<U> myChangedMembers; public MemberInfoChange(Collection<U> changedMembers) { myChangedMembers = changedMembers; } public Collection<U> getChangedMembers() { return myChangedMembers; } }
#import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN /*! An object that can run a given block. */ @interface BFExecutor : NSObject /*! Returns a default executor, which runs continuations immediately until the call stack gets too deep, then dispatches to a new GCD queue. */ + (instancetype)defaultExecutor; /*! Returns an executor that runs continuations on the thread where the previous task was completed. */ + (instancetype)immediateExecutor; /*! Returns an executor that runs continuations on the main thread. */ + (instancetype)mainThreadExecutor; /*! Returns a new executor that uses the given block to execute continuations. @param block The block to use. */ + (instancetype)executorWithBlock:(void(^)(void(^block)()))block; /*! Returns a new executor that runs continuations on the given queue. @param queue The instance of `dispatch_queue_t` to dispatch all continuations onto. */ + (instancetype)executorWithDispatchQueue:(dispatch_queue_t)queue; /*! Returns a new executor that runs continuations on the given queue. @param queue The instance of `NSOperationQueue` to run all continuations on. */ + (instancetype)executorWithOperationQueue:(NSOperationQueue *)queue; /*! Runs the given block using this executor's particular strategy. @param block The block to execute. */ - (void)execute:(void(^)())block; @end NS_ASSUME_NONNULL_END
package com.alibaba.dubbo.examples.generic.impl; import com.alibaba.dubbo.examples.generic.api.IUserService; /** * @author chao.liuc * */ public class UserServiceImpl implements IUserService { public User get(Params params) { return new User(1, "charles"); } }
/* ### * IP: GHIDRA * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ghidra.app.plugin.match; import java.util.*; import ghidra.program.model.address.Address; import ghidra.program.model.address.AddressSetView; import ghidra.program.model.listing.*; import ghidra.util.exception.CancelledException; import ghidra.util.task.TaskMonitor; /** * This class does the work of matching subroutines. Every subroutine * in the current program is hashed and the start address is put into a * table. There are often identical subroutines which may have the same hash * value. Then the subroutines in the other program are hashed as well. All unique * match pairs are returned as matches. The next step would be to use call graph * information or address order to get additional matches. */ public class MatchFunctions { private MatchFunctions() { // non-instantiable } // Finds one-to-many matches in functions from addressSet A and Address Set B public static List<MatchedFunctions> matchFunctions(Program aProgram, AddressSetView setA, Program bProgram, AddressSetView setB, int minimumFunctionSize, boolean includeOneToOne, boolean includeNonOneToOne, FunctionHasher hasher, TaskMonitor monitor) throws CancelledException { Map<Long, Match> functionHashes = new HashMap<>(); List<MatchedFunctions> functionMatches = new ArrayList<MatchedFunctions>(); FunctionIterator aProgfIter = aProgram.getFunctionManager().getFunctions(setA, true); FunctionIterator bProgfIter = bProgram.getFunctionManager().getFunctions(setB, true); monitor.setIndeterminate(false); monitor.initialize(2 * (aProgram.getFunctionManager().getFunctionCount() + bProgram.getFunctionManager().getFunctionCount())); monitor.setMessage("Hashing functions in " + aProgram.getName()); // Hash functions in program A while (!monitor.isCancelled() && aProgfIter.hasNext()) { monitor.incrementProgress(1); Function func = aProgfIter.next(); if (!func.isThunk() && func.getBody().getNumAddresses() >= minimumFunctionSize) { hashFunction(monitor, functionHashes, func, hasher, true); } } monitor.setMessage("Hashing functions in " + bProgram.getName()); // Hash functions in Program B while (!monitor.isCancelled() && bProgfIter.hasNext()) { monitor.incrementProgress(1); Function func = bProgfIter.next(); if (!func.isThunk() && func.getBody().getNumAddresses() >= minimumFunctionSize) { hashFunction(monitor, functionHashes, func, hasher, false); } } //Find the remaining hash matches ---> unique code match left and THERE is no symbol that matches //in the other program. final long progress = monitor.getProgress(); monitor.setMaximum(progress + functionHashes.size()); monitor.setProgress(progress); monitor.setMessage("Finding function matches"); for (Match match : functionHashes.values()) { monitor.incrementProgress(1); if (monitor.isCancelled()) { break; } ArrayList<Address> aProgAddrs = match.aAddresses; ArrayList<Address> bProgAddrs = match.bAddresses; if ((includeOneToOne && aProgAddrs.size() == 1 && bProgAddrs.size() == 1) || (includeNonOneToOne && !(aProgAddrs.size() == 1 && bProgAddrs.size() == 1))) { for (Address aAddr : aProgAddrs) { for (Address bAddr : bProgAddrs) { MatchedFunctions functionMatch = new MatchedFunctions(aProgram, bProgram, aAddr, bAddr, aProgAddrs.size(), bProgAddrs.size(), "Code Only Match"); functionMatches.add(functionMatch); } } } } return functionMatches; } public static List<MatchedFunctions> matchOneFunction(Program aProgram, Address aEntryPoint, Program bProgram, FunctionHasher hasher, TaskMonitor monitor) throws CancelledException { return matchOneFunction(aProgram, aEntryPoint, bProgram, null, hasher, monitor); } // Finds all matches in program B to the function in Program A public static List<MatchedFunctions> matchOneFunction(Program aProgram, Address aEntryPoint, Program bProgram, AddressSetView bAddressSet, FunctionHasher hasher, TaskMonitor monitor) throws CancelledException { Map<Long, Match> functionHashes = new HashMap<>(); List<MatchedFunctions> functionMatches = new ArrayList<MatchedFunctions>(); Function aFunc = aProgram.getFunctionManager().getFunctionContaining(aEntryPoint); FunctionIterator bProgfIter = bAddressSet == null ? bProgram.getFunctionManager().getFunctions(true) : bProgram.getFunctionManager().getFunctions(bAddressSet, true); // Hash the one function in program A hashFunction(monitor, functionHashes, aFunc, hasher, true); // Hash functions in Program B while (!monitor.isCancelled() && bProgfIter.hasNext()) { Function func = bProgfIter.next(); hashFunction(monitor, functionHashes, func, hasher, false); } //Find the remaining hash matches ---> unique code match left and THERE is no symbol that matches //in the other program. List<Long> keys = new ArrayList<>(functionHashes.keySet()); for (long key : keys) { if (monitor.isCancelled()) { break; } Match match = functionHashes.get(key); ArrayList<Address> aProgAddrs = match.aAddresses; ArrayList<Address> bProgAddrs = match.bAddresses; // Want all possible matches from destination program if ((aProgAddrs.size() == 1) && (bProgAddrs.size() >= 1)) { for (int m = 0; m < bProgAddrs.size(); m++) { MatchedFunctions functionMatch = new MatchedFunctions(aProgram, bProgram, aProgAddrs.get(0), bProgAddrs.get(m), aProgAddrs.size(), bProgAddrs.size(), "Code Only Match"); functionMatches.add(functionMatch); } functionHashes.remove(key); } } return functionMatches; } private static void hashFunction(TaskMonitor monitor, Map<Long, Match> functionHashes, Function function, FunctionHasher hasher, boolean isProgA) throws CancelledException { long hash = hasher.hash(function, monitor); Match subMatch = functionHashes.get(hash); if (subMatch == null) { subMatch = new Match(); functionHashes.put(hash, subMatch); } subMatch.add(function.getEntryPoint(), isProgA); } private static class Match { final ArrayList<Address> aAddresses = new ArrayList<Address>(); final ArrayList<Address> bAddresses = new ArrayList<Address>(); public void add(Address address, boolean isProgA) { if (isProgA) { aAddresses.add(address); } else { bAddresses.add(address); } } } public static class MatchedFunctions { private final Program aProg; private final Program bProg; private final Address aAddr; private final Address bAddr; private final int aMatchNum; private final int bMatchNum; MatchedFunctions(Program aProg, Program bProg, Address aAddr, Address bAddr, int aMatchNum, int bMatchNum, String reason) { this.aProg = aProg; this.bProg = bProg; this.aAddr = aAddr; this.bAddr = bAddr; this.aMatchNum = aMatchNum; this.bMatchNum = bMatchNum; } public Program getAProgram() { return aProg; } public Program getBProgram() { return bProg; } public Address getAFunctionAddress() { return aAddr; } public Address getBFunctionAddress() { return bAddr; } public int getAMatchNum() { return aMatchNum; } public int getBMatchNum() { return bMatchNum; } } }
set -e set -o pipefail handle_signal() { PID=$! echo "Received signal. PID is ${PID}" kill -s SIGHUP $PID } trap "handle_signal" SIGINT SIGTERM SIGHUP echo "Starting sonarr..." exec mono --debug /opt/sonarr/NzbDrone.exe --no-browser -data=/config & wait echo "Stopping sonarr..."
using System; using System.IO; using System.Collections.Generic; using System.ComponentModel; using System.Reflection; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Web; using System.Web.UI; using System.Web.Mvc; using System.Web.Caching; using System.Web.Routing; using System.ComponentModel.DataAnnotations; namespace Library { // FOR PROPERTIES #region Email Attribute [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public class EmailAttribute : RegularExpressionAttribute { public EmailAttribute() : base(@"([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})") { } } #endregion #region Json Attribute [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public class JsonAttribute : ValidationAttribute { public override bool IsValid(object value) { var str = value as string; if (string.IsNullOrEmpty(str)) return true; return str.IsJson(); } } #endregion #region Number Attribute [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public class NumberAttribute : ValidationAttribute { public bool IsDecimal { get; set; } public NumberAttribute(bool isDecimal = false) : base("The number is not valid.") { IsDecimal = isDecimal; } public override bool IsValid(object value) { if (value == null) return true; var val = value.ToString(); if (val.IsEmpty()) return true; return IsDecimal ? val.To<decimal>() > 0M : val.To<int>() > 0; } } #endregion #region Checked Attribute [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public class CheckedAttribute : ValidationAttribute { public CheckedAttribute() : base("You must agree.") { } public override bool IsValid(object value) { if (value == null) return true; var val = value.ToString(); if (val.IsEmpty()) return true; return val == "1" || val.ToLower() == "true"; } } #endregion // FOR ACTIONS #region Xhr Attribute [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] public class XhrAttribute : ActionFilterAttribute { public bool HostValid { get; set; } public int HttpStatus { get; set; } public XhrAttribute() { HostValid = true; } public XhrAttribute(bool hostValid) { HostValid = hostValid; } public XhrAttribute(bool hostValid, int httpStatus) { HostValid = hostValid; HttpStatus = httpStatus; } public override void OnActionExecuting(ActionExecutingContext filterContext) { if (HttpStatus == 0) HttpStatus = 406; if (!filterContext.HttpContext.Request.IsAjaxRequest()) filterContext.Result = new HttpStatusCodeResult(HttpStatus); if (HostValid) { var referrer = filterContext.HttpContext.Request.UrlReferrer; if (referrer == null || referrer.Host != filterContext.HttpContext.Request.Url.Host) filterContext.Result = new HttpStatusCodeResult(HttpStatus); } base.OnActionExecuting(filterContext); } } #endregion #region Header Attribute [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] public class HeaderAttribute : ActionFilterAttribute { public string Name { get; set; } public string Value { get; set; } public int HttpStatus { get; set; } public HeaderAttribute() { } public HeaderAttribute(string name, string value) { Name = name; Value = value; } public HeaderAttribute(string name, string value, int httpStatus) { Name = name; Value = value; HttpStatus = httpStatus; } public override void OnActionExecuting(ActionExecutingContext filterContext) { if (HttpStatus == 0) HttpStatus = 403; var value = filterContext.HttpContext.Request.Headers[Name]; if (value != Value) filterContext.Result = new HttpStatusCodeResult(HttpStatus); base.OnActionExecuting(filterContext); } } #endregion #region Referer Attribute [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] public class RefererAttribute : ActionFilterAttribute { [DefaultValue(404)] public int HttpStatus { get; set; } public override void OnActionExecuting(ActionExecutingContext filterContext) { var referrer = filterContext.HttpContext.Request.UrlReferrer; if (referrer == null || referrer.Host != filterContext.HttpContext.Request.Url.Host) filterContext.Result = new HttpStatusCodeResult(HttpStatus); base.OnActionExecuting(filterContext); } } #endregion #region UnLogged Attribute [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] public class UnLoggedAttribute : ActionFilterAttribute { private Authorization authorization = Authorization.Unlogged; public override void OnActionExecuting(ActionExecutingContext filterContext) { if (Configuration.OnAuthorization == null) return; authorization = Configuration.OnAuthorization(filterContext.HttpContext, string.Empty, string.Empty); if (authorization != Authorization.Unlogged) { filterContext.Result = Configuration.OnAuthorizationError(filterContext.RequestContext.HttpContext.Request, authorization); return; } base.OnActionExecuting(filterContext); } } #endregion #region Logged Attribute [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] public class LoggedAttribute : AuthorizeAttribute { private Authorization authorization = Authorization.Unlogged; public string ErrorMessage { get; set; } protected override bool AuthorizeCore(HttpContextBase httpContext) { if (Configuration.OnAuthorization == null) return false; authorization = Configuration.OnAuthorization(httpContext, Roles, Users); return authorization == Authorization.Logged; } private void CacheValidateHandler(HttpContext context, object data, ref HttpValidationStatus validationStatus) { validationStatus = OnCacheAuthorization(new HttpContextWrapper(context)); } protected override HttpValidationStatus OnCacheAuthorization(HttpContextBase httpContext) { return AuthorizeCore(httpContext) ? HttpValidationStatus.Valid : HttpValidationStatus.Invalid; } public override void OnAuthorization(AuthorizationContext filterContext) { if (!AuthorizeCore(filterContext.HttpContext)) { filterContext.Result = Configuration.OnAuthorizationError(filterContext.RequestContext.HttpContext.Request, authorization); return; } HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache; cachePolicy.SetProxyMaxAge(new TimeSpan(0)); cachePolicy.AddValidationCallback(CacheValidateHandler, null); } } #endregion #region User Attribute [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] public class UserAttribute : AuthorizeAttribute { private Authorization authorization = Authorization.Unlogged; public string ErrorMessage { get; set; } protected override bool AuthorizeCore(HttpContextBase httpContext) { if (Configuration.OnAuthorization == null) return false; authorization = Configuration.OnAuthorization(httpContext, Roles, Users); return authorization == Authorization.Logged; } private void CacheValidateHandler(HttpContext context, object data, ref HttpValidationStatus validationStatus) { validationStatus = OnCacheAuthorization(new HttpContextWrapper(context)); } protected override HttpValidationStatus OnCacheAuthorization(HttpContextBase httpContext) { return AuthorizeCore(httpContext) ? HttpValidationStatus.Valid : HttpValidationStatus.Invalid; } public override void OnAuthorization(AuthorizationContext filterContext) { if (!AuthorizeCore(filterContext.HttpContext)) { filterContext.Result = Configuration.OnAuthorizationError(filterContext.RequestContext.HttpContext.Request, authorization); return; } HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache; cachePolicy.SetProxyMaxAge(new TimeSpan(0)); cachePolicy.AddValidationCallback(CacheValidateHandler, null); } } #endregion #region UnLogged Attribute [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] public class AnonymAttribute : ActionFilterAttribute { private Authorization authorization = Authorization.Unlogged; public override void OnActionExecuting(ActionExecutingContext filterContext) { if (Configuration.OnAuthorization == null) return; authorization = Configuration.OnAuthorization(filterContext.HttpContext, string.Empty, string.Empty); if (authorization != Authorization.Unlogged) { filterContext.Result = Configuration.OnAuthorizationError(filterContext.RequestContext.HttpContext.Request, authorization); return; } base.OnActionExecuting(filterContext); } } #endregion #region Proxy Attribute [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] public class ProxyAttribute : ActionFilterAttribute { public int HttpStatus { get; set; } public string Key { get; set; } public string Method { get; set; } public ProxyAttribute() { HttpStatus = 403; } public ProxyAttribute(string key, string method = "POST", int httpStatus = 434) { Key = "Library." + key.Hash("sha256"); Method = "POST"; HttpStatus = httpStatus; } public override void OnActionExecuting(ActionExecutingContext filterContext) { var request = filterContext.HttpContext.Request; if (request.HttpMethod != Method || request.Headers["X-Proxy"] != Key) filterContext.Result = new HttpStatusCodeResult(HttpStatus); base.OnActionExecuting(filterContext); } } #endregion #region Form Attribute [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] public class FormAttribute : ActionFilterAttribute { public bool HostValid { get; set; } public bool Json { get; set; } public int HttpStatus { get; set; } public string Parameter { get; set; } public Type ParameterType { get; set; } public FormAttribute() { HostValid = true; HttpStatus = 403; Json = true; } public FormAttribute(Type type, string parameter = "model", bool hostValid = true, int httpStatus = 401, bool json = true) { ParameterType = type; Parameter = parameter; HostValid = hostValid; HttpStatus = httpStatus; Json = json; } public FormAttribute(bool hostValid = true, int httpStatus = 401, bool json = true) { HostValid = hostValid; HttpStatus = httpStatus; Json = json; } public override void OnActionExecuting(ActionExecutingContext filterContext) { var request = filterContext.HttpContext.Request; if (!request.IsAjaxRequest()) { filterContext.Result = new HttpStatusCodeResult(HttpStatus); base.OnActionExecuting(filterContext); return; } if (HostValid) { var referrer = filterContext.HttpContext.Request.UrlReferrer; if (referrer == null || referrer.Host != filterContext.HttpContext.Request.Url.Host) { filterContext.Result = new HttpStatusCodeResult(HttpStatus); base.OnActionExecuting(filterContext); return; } } if (Json) { if (request.ContentType.StartsWith("application/json", StringComparison.InvariantCultureIgnoreCase) == false) { filterContext.Result = new HttpStatusCodeResult(HttpStatus); base.OnActionExecuting(filterContext); return; } if (!string.IsNullOrEmpty(Parameter)) { string inputContent; using (var sr = new StreamReader(filterContext.HttpContext.Request.InputStream)) inputContent = sr.ReadToEnd(); var value = Configuration.JsonProvider.DeserializeObject(inputContent, ParameterType); filterContext.ActionParameters[Parameter] = value; } } base.OnActionExecuting(filterContext); } } #endregion // FOR CONTROLLERS #region Analylitcs public class AnalyticsAttribute : ActionFilterAttribute, IActionFilter { public bool AllowXhr { get; set; } public AnalyticsAttribute(bool allowXhr = false) { AllowXhr = allowXhr; } void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext) { Configuration.Analytics.Request(filterContext.HttpContext, AllowXhr); OnActionExecuting(filterContext); } } #endregion #region Stopwatch public class StopwatchAttribute : ActionFilterAttribute, IResultFilter { private DateTime start; public override void OnActionExecuting(ActionExecutingContext filterContext) { if (Configuration.AllowStopwatch) start = DateTime.Now; base.OnActionExecuting(filterContext); } void IResultFilter.OnResultExecuted(ResultExecutedContext filterContext) { if (Configuration.AllowStopwatch) Configuration.InvokeStopwatch(filterContext.Controller.GetType().Name, DateTime.Now - start, filterContext.RequestContext.HttpContext.Request); base.OnResultExecuted(filterContext); } } #endregion }
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <!-- ~ Copyright 2022 Thoughtworks, Inc. ~ ~ Licensed under the Apache License, Version 2.0 (the "License"); ~ you may not use this file except in compliance with the License. ~ You may obtain a copy of the License at ~ ~ http://www.apache.org/licenses/LICENSE-2.0 ~ ~ Unless required by applicable law or agreed to in writing, software ~ distributed under the License is distributed on an "AS IS" BASIS, ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ~ See the License for the specific language governing permissions and ~ limitations under the License. --> <databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.8.xsd"> <changeSet author="gocd(generated)" id="105"> <createView fullDefinition="false" remarks="" viewName="_BUILDS">SELECT B.ID, B.NAME, B.STATE, B.RESULT, B.AGENTUUID, B.SCHEDULEDDATE, B.STAGEID, B.IGNORED, B.RUNONALLAGENTS, B.ORIGINALJOBID, B.RERUN, B.RUNMULTIPLEINSTANCE, P.ID AS PIPELINEID, P.NAME AS PIPELINENAME, P.LABEL AS PIPELINELABEL, P.COUNTER AS PIPELINECOUNTER, S.NAME AS STAGENAME, S.COUNTER AS STAGECOUNTER, S.FETCHMATERIALS, S.CLEANWORKINGDIR, S.RERUNOFCOUNTER FROM BUILDS B INNER JOIN STAGES S ON S.ID = B.STAGEID INNER JOIN PIPELINES P ON P.ID = S.PIPELINEID </createView> </changeSet> <changeSet author="gocd(generated)" id="106"> <createView fullDefinition="false" remarks="" viewName="_STAGES">SELECT S.ID, S.NAME, S.APPROVEDBY, S.PIPELINEID, S.CREATEDTIME, S.ORDERID, S.RESULT, S.APPROVALTYPE, S.COUNTER, S.COMPLETEDBYTRANSITIONID, S.STATE, S.LATESTRUN, S.FETCHMATERIALS, S.CLEANWORKINGDIR, S.RERUNOFCOUNTER, S.ARTIFACTSDELETED, S.CONFIGVERSION, S.LASTTRANSITIONEDTIME, P.NAME AS PIPELINENAME, P.BUILDCAUSETYPE, P.BUILDCAUSEBY, P.LABEL AS PIPELINELABEL, P.BUILDCAUSEMESSAGE, P.COUNTER AS PIPELINECOUNTER, PS.LOCKED, P.NATURALORDER FROM STAGES S INNER JOIN PIPELINES P ON P.ID = S.PIPELINEID LEFT OUTER JOIN PIPELINESTATES PS ON PS.LOCKEDBYPIPELINEID = S.PIPELINEID </createView> </changeSet> </databaseChangeLog>
if exist setup64.exe (del setup64.exe) msbuild /target:Bootstrapper setup64.proj rename setup.exe setup64.exe iexpress /N Installer64.sed
<?php namespace JMS\Serializer\Tests\Fixtures; use JMS\Serializer\Annotation\Type; class CircularReferenceChild { /** @Type("string") */ private $name; /** @Type("JMS\Serializer\Tests\Fixtures\CircularReferenceParent") */ private $parent; public function __construct($name, CircularReferenceParent $parent) { $this->name = $name; $this->parent = $parent; } public function getName() { return $this->name; } public function getParent() { return $this->parent; } public function setParent(CircularReferenceParent $parent) { $this->parent = $parent; } }
#include "tensorflow/compiler/xla/service/gpu/cudnn_convolution_rewriter.h" #include "tensorflow/compiler/xla/service/gpu/ir_emission_utils.h" #include "tensorflow/compiler/xla/service/hlo_computation.h" #include "tensorflow/compiler/xla/service/hlo_instruction.h" #include "tensorflow/compiler/xla/service/hlo_matchers.h" #include "tensorflow/compiler/xla/service/hlo_module.h" #include "tensorflow/compiler/xla/service/hlo_opcode.h" #include "tensorflow/compiler/xla/service/shape_inference.h" #include "tensorflow/compiler/xla/test.h" #include "tensorflow/compiler/xla/test_helpers.h" #include "tensorflow/compiler/xla/tests/hlo_test_base.h" #include "tensorflow/core/platform/test.h" namespace xla { namespace gpu { namespace { namespace op = xla::testing::opcode_matchers; class CudnnConvolutionRewriterTest : public HloTestBase { public: CudnnConvolutionRewriterTest() { for (int i = 0; i < 2; ++i) { WindowDimension* window_dim = default_conv_window_.add_dimensions(); window_dim->set_size(1); window_dim->set_stride(1); window_dim->set_padding_low(0); window_dim->set_padding_high(0); window_dim->set_window_dilation(1); window_dim->set_base_dilation(1); } // TF data shapes are by default in the NHWC order, and filter shape is by // default in HWIO order. For backward filter convolution, we need to swap // the batch and feature dimension in the activations, and treat the batch // dimension in gradients as the input feature dimension in the filter. // // TODO(jingyue): Add more tests on NCHW input order, which TF also // supports. tf_default_dnums_for_backward_filter_.set_input_batch_dimension(3); tf_default_dnums_for_backward_filter_.set_input_feature_dimension(0); tf_default_dnums_for_backward_filter_.add_input_spatial_dimensions(1); tf_default_dnums_for_backward_filter_.add_input_spatial_dimensions(2); tf_default_dnums_for_backward_filter_.set_kernel_input_feature_dimension(0); tf_default_dnums_for_backward_filter_.set_kernel_output_feature_dimension( 3); tf_default_dnums_for_backward_filter_.add_kernel_spatial_dimensions(1); tf_default_dnums_for_backward_filter_.add_kernel_spatial_dimensions(2); tf_default_dnums_for_backward_filter_.add_output_spatial_dimensions(0); tf_default_dnums_for_backward_filter_.add_output_spatial_dimensions(1); tf_default_dnums_for_backward_filter_.set_output_batch_dimension(2); tf_default_dnums_for_backward_filter_.set_output_feature_dimension(3); tf_default_dnums_for_backward_input_.set_input_batch_dimension(0); tf_default_dnums_for_backward_input_.set_output_batch_dimension(0); tf_default_dnums_for_backward_input_.set_input_feature_dimension(3); tf_default_dnums_for_backward_input_.set_output_feature_dimension(3); tf_default_dnums_for_backward_input_.add_input_spatial_dimensions(1); tf_default_dnums_for_backward_input_.add_output_spatial_dimensions(1); tf_default_dnums_for_backward_input_.add_input_spatial_dimensions(2); tf_default_dnums_for_backward_input_.add_output_spatial_dimensions(2); tf_default_dnums_for_backward_input_.set_kernel_input_feature_dimension(3); tf_default_dnums_for_backward_input_.set_kernel_output_feature_dimension(2); tf_default_dnums_for_backward_input_.add_kernel_spatial_dimensions(0); tf_default_dnums_for_backward_input_.add_kernel_spatial_dimensions(1); } protected: bool RunPass(HloModule* module) { return CudnnConvolutionRewriter().Run(module).ValueOrDie(); } // A convolution window with stride 1 and zero padding. The size fields are // not set. Window default_conv_window_; ConvolutionDimensionNumbers tf_default_dnums_for_backward_filter_; ConvolutionDimensionNumbers tf_default_dnums_for_backward_input_; }; TEST_F(CudnnConvolutionRewriterTest, BackwardFilterConvolve) { HloComputation::Builder builder(TestName()); HloInstruction* activations = builder.AddInstruction(HloInstruction::CreateParameter( 0, ShapeUtil::MakeShape(F32, {1, 1, 3, 1}), "activations")); HloInstruction* gradients = builder.AddInstruction(HloInstruction::CreateParameter( 1, ShapeUtil::MakeShape(F32, {1, 1, 2, 1}), "gradients")); Window conv_window = default_conv_window_; conv_window.mutable_dimensions(1)->set_size(2); conv_window.mutable_dimensions(1)->set_window_dilation(2); builder.AddInstruction(HloInstruction::CreateConvolve( ShapeInference::InferConvolveShape(activations->shape(), gradients->shape(), conv_window, tf_default_dnums_for_backward_filter_) .ConsumeValueOrDie(), activations, gradients, conv_window, tf_default_dnums_for_backward_filter_)); auto module = CreateNewModule(); HloComputation* entry_computation = module->AddEntryComputation(builder.Build()); EXPECT_TRUE(RunPass(module.get())); EXPECT_THAT(entry_computation->root_instruction(), op::GetTupleElement( op::CustomCall(kCudnnConvBackwardFilterCallTarget), 0)); } TEST_F(CudnnConvolutionRewriterTest, BackwardFilterConvolveEquivalentToForwardConvolution) { HloComputation::Builder builder(TestName()); HloInstruction* activations = builder.AddInstruction(HloInstruction::CreateParameter( 0, ShapeUtil::MakeShape(F32, {1, 1, 3, 1}), "activations")); HloInstruction* gradients = builder.AddInstruction(HloInstruction::CreateParameter( 1, ShapeUtil::MakeShape(F32, {1, 1, 3, 1}), "gradients")); Window conv_window = default_conv_window_; conv_window.mutable_dimensions(1)->set_size(3); builder.AddInstruction(HloInstruction::CreateConvolve( ShapeInference::InferConvolveShape(activations->shape(), gradients->shape(), conv_window, tf_default_dnums_for_backward_filter_) .ConsumeValueOrDie(), activations, gradients, conv_window, tf_default_dnums_for_backward_filter_)); auto module = CreateNewModule(); HloComputation* entry_computation = module->AddEntryComputation(builder.Build()); EXPECT_TRUE(RunPass(module.get())); EXPECT_THAT(entry_computation->root_instruction(), op::GetTupleElement( op::CustomCall(kCudnnConvBackwardFilterCallTarget), 0)); } // Extracted from block35 training. TEST_F(CudnnConvolutionRewriterTest, BackwardFilterConvolveWithPaddedActivations) { auto builder = HloComputation::Builder(TestName()); HloInstruction* activations = builder.AddInstruction(HloInstruction::CreateParameter( 0, ShapeUtil::MakeShape(F32, {20, 35, 35, 32}), "activations")); HloInstruction* gradients = builder.AddInstruction(HloInstruction::CreateParameter( 1, ShapeUtil::MakeShape(F32, {20, 35, 35, 32}), "gradients")); Window conv_window = default_conv_window_; for (int i = 0; i < 2; ++i) { conv_window.mutable_dimensions(i)->set_size(35); conv_window.mutable_dimensions(i)->set_padding_low(1); conv_window.mutable_dimensions(i)->set_padding_high(1); } builder.AddInstruction(HloInstruction::CreateConvolve( ShapeUtil::MakeShape(F32, {32, 3, 3, 32}), activations, gradients, conv_window, tf_default_dnums_for_backward_filter_)); auto module = CreateNewModule(); HloComputation* entry_computation = module->AddEntryComputation(builder.Build()); EXPECT_TRUE(RunPass(module.get())); EXPECT_THAT(entry_computation->root_instruction(), op::GetTupleElement( op::CustomCall(kCudnnConvBackwardFilterCallTarget), 0)); } // Extracted from inception v3 training. TEST_F(CudnnConvolutionRewriterTest, BackwardFilterConvolveWithPaddedGradients) { auto builder = HloComputation::Builder(TestName()); HloInstruction* activations = builder.AddInstruction(HloInstruction::CreateParameter( 0, ShapeUtil::MakeShape(F32, {20, 10, 10, 192}), "activations")); HloInstruction* gradients = builder.AddInstruction(HloInstruction::CreateParameter( 1, ShapeUtil::MakeShape(F32, {20, 4, 4, 320}), "gradients")); Window conv_window = default_conv_window_; for (int i = 0; i < 2; ++i) { conv_window.mutable_dimensions(i)->set_size(4); conv_window.mutable_dimensions(i)->set_padding_high(-1); conv_window.mutable_dimensions(i)->set_window_dilation(2); } builder.AddInstruction(HloInstruction::CreateConvolve( ShapeUtil::MakeShape(F32, {320, 3, 3, 192}), activations, gradients, conv_window, tf_default_dnums_for_backward_filter_)); auto module = CreateNewModule(); HloComputation* entry_computation = module->AddEntryComputation(builder.Build()); EXPECT_TRUE(RunPass(module.get())); EXPECT_THAT(entry_computation->root_instruction(), op::GetTupleElement( op::CustomCall(kCudnnConvBackwardFilterCallTarget), 0)); } TEST_F(CudnnConvolutionRewriterTest, BackwardFilterConvolveWithUnevenPadding) { auto builder = HloComputation::Builder(TestName()); HloInstruction* activations = builder.AddInstruction(HloInstruction::CreateParameter( 0, ShapeUtil::MakeShape(F32, {20, 35, 35, 32}), "activations")); HloInstruction* gradients = builder.AddInstruction(HloInstruction::CreateParameter( 1, ShapeUtil::MakeShape(F32, {20, 35, 35, 32}), "gradients")); Window conv_window = default_conv_window_; for (int i = 0; i < 2; ++i) { conv_window.mutable_dimensions(i)->set_size(35); // Uneven padding: padding_low=0, padding_high=1 conv_window.mutable_dimensions(i)->set_padding_high(1); } builder.AddInstruction(HloInstruction::CreateConvolve( ShapeUtil::MakeShape(F32, {32, 2, 2, 32}), activations, gradients, conv_window, tf_default_dnums_for_backward_filter_)); auto module = CreateNewModule(); HloComputation* entry_computation = module->AddEntryComputation(builder.Build()); EXPECT_TRUE(RunPass(module.get())); EXPECT_THAT(entry_computation->root_instruction(), op::GetTupleElement( op::CustomCall(kCudnnConvBackwardFilterCallTarget), 0)); } TEST_F(CudnnConvolutionRewriterTest, BackwardInputConvolveEvenPadding) { auto builder = HloComputation::Builder(TestName()); HloInstruction* output = builder.AddInstruction(HloInstruction::CreateParameter( 0, ShapeUtil::MakeShape(F32, {4, 5, 16, 16}), "output")); HloInstruction* kernel = builder.AddInstruction(HloInstruction::CreateParameter( 1, ShapeUtil::MakeShape(F32, {5, 3, 7, 7}), "kernel")); HloInstruction* reverse_kernel = builder.AddInstruction( HloInstruction::CreateReverse(kernel->shape(), kernel, {2, 3})); Window conv_window = default_conv_window_; for (int i = 0; i < 2; ++i) { conv_window.mutable_dimensions(i)->set_size(7); conv_window.mutable_dimensions(i)->set_padding_low(3); conv_window.mutable_dimensions(i)->set_padding_high(3); } ConvolutionDimensionNumbers conv_dnums; conv_dnums.set_input_batch_dimension(0); conv_dnums.set_output_batch_dimension(0); conv_dnums.set_input_feature_dimension(1); conv_dnums.set_output_feature_dimension(1); conv_dnums.add_input_spatial_dimensions(2); conv_dnums.add_output_spatial_dimensions(2); conv_dnums.add_input_spatial_dimensions(3); conv_dnums.add_output_spatial_dimensions(3); conv_dnums.set_kernel_input_feature_dimension(0); conv_dnums.set_kernel_output_feature_dimension(1); conv_dnums.add_kernel_spatial_dimensions(2); conv_dnums.add_kernel_spatial_dimensions(3); HloInstruction* conv = builder.AddInstruction(HloInstruction::CreateConvolve( ShapeUtil::MakeShape(F32, {4, 3, 16, 16}), /*lhs=*/output, /*rhs=*/reverse_kernel, conv_window, conv_dnums)); // Verify the convolution's shape is consistent with ShapeInference. CHECK(ShapeUtil::Compatible( conv->shape(), ShapeInference::InferConvolveShape( output->shape(), reverse_kernel->shape(), conv_window, conv_dnums) .ValueOrDie())); auto module = CreateNewModule(); HloComputation* entry_computation = module->AddEntryComputation(builder.Build()); EXPECT_TRUE(RunPass(module.get())); ASSERT_THAT(entry_computation->root_instruction(), op::GetTupleElement( op::CustomCall(kCudnnConvBackwardInputCallTarget), 0)); const HloInstruction* custom_call = entry_computation->root_instruction()->operand(0); for (int i = 0; i < 2; ++i) { const WindowDimension& window_dim = custom_call->window().dimensions(i); // Low padding of the backward input convolution // = kernel_size - 1 - low padding on gradients. EXPECT_EQ(3, window_dim.padding_low()); EXPECT_EQ(3, window_dim.padding_high()); EXPECT_EQ(1, window_dim.stride()); } } // Convolve([abc], [x], base_dilation=2) // = Convolve([abc], Reverse([x]), base_dilation=2) // = BackwardInputConvolve([abc], [x], stride=2) TEST_F(CudnnConvolutionRewriterTest, BackwardInputConvolve1x1Filter) { auto builder = HloComputation::Builder(TestName()); // NHWC dimension order. HloInstruction* output = builder.AddInstruction(HloInstruction::CreateParameter( 0, ShapeUtil::MakeShape(F32, {1, 1, 3, 1}), "output")); // HWOI dimension order. HloInstruction* kernel = builder.AddInstruction(HloInstruction::CreateParameter( 1, ShapeUtil::MakeShape(F32, {1, 1, 1, 1}), "kernel")); Window conv_window = default_conv_window_; conv_window.mutable_dimensions(1)->set_base_dilation(2); builder.AddInstruction(HloInstruction::CreateConvolve( ShapeInference::InferConvolveShape(output->shape(), kernel->shape(), conv_window, tf_default_dnums_for_backward_input_) .ConsumeValueOrDie(), /*lhs=*/output, /*rhs=*/kernel, conv_window, tf_default_dnums_for_backward_input_)); auto module = CreateNewModule(); HloComputation* entry_computation = module->AddEntryComputation(builder.Build()); EXPECT_TRUE(RunPass(module.get())); EXPECT_THAT(entry_computation->root_instruction(), op::GetTupleElement( op::CustomCall(kCudnnConvBackwardInputCallTarget), 0)); } // BackwardInputConvolve([abc], [x], stride=1) is equivalent to // ForwardConvolve([abc], [x], stride=1). No need to fold it into backward input // convolution. TEST_F(CudnnConvolutionRewriterTest, BackwardInputConvolve1x1FilterEquivalentToForwardConvolve) { auto builder = HloComputation::Builder(TestName()); // NHWC dimension order. HloInstruction* output = builder.AddInstruction(HloInstruction::CreateParameter( 0, ShapeUtil::MakeShape(F32, {1, 1, 3, 1}), "output")); // HWOI dimension order. HloInstruction* kernel = builder.AddInstruction(HloInstruction::CreateParameter( 1, ShapeUtil::MakeShape(F32, {1, 1, 1, 1}), "kernel")); builder.AddInstruction(HloInstruction::CreateConvolve( ShapeInference::InferConvolveShape(output->shape(), kernel->shape(), default_conv_window_, tf_default_dnums_for_backward_input_) .ConsumeValueOrDie(), /*lhs=*/output, /*rhs=*/kernel, default_conv_window_, tf_default_dnums_for_backward_input_)); auto module = CreateNewModule(); HloComputation* entry_computation = module->AddEntryComputation(builder.Build()); EXPECT_TRUE(RunPass(module.get())); EXPECT_THAT( entry_computation->root_instruction(), op::GetTupleElement(op::CustomCall(kCudnnConvForwardCallTarget), 0)); } // Extracted from Inception V3 training. // // filter(HWIO) // 3x3x192x320 // | // v // gradients(NHWC) reverse // 20x4x4x320 3x3x192x320 // \ / // \ / // conv (NHWC) with padding (low=2,high=3,interior=1) // 20x10x10x192 // // Gradients are padded unevenly. TEST_F(CudnnConvolutionRewriterTest, BackwardInputConvolveUnevenPaddingOnGradients) { auto builder = HloComputation::Builder(TestName()); HloInstruction* output = builder.AddInstruction(HloInstruction::CreateParameter( 0, ShapeUtil::MakeShape(F32, {20, 4, 4, 320}), "output")); HloInstruction* kernel = builder.AddInstruction(HloInstruction::CreateParameter( 1, ShapeUtil::MakeShape(F32, {3, 3, 192, 320}), "kernel")); HloInstruction* reverse_kernel = builder.AddInstruction( HloInstruction::CreateReverse(kernel->shape(), kernel, {0, 1})); Window conv_window = default_conv_window_; for (int i = 0; i < 2; ++i) { conv_window.mutable_dimensions(i)->set_size(3); conv_window.mutable_dimensions(i)->set_padding_low(2); conv_window.mutable_dimensions(i)->set_padding_high(3); // Interior padding = 1. conv_window.mutable_dimensions(i)->set_base_dilation(2); } HloInstruction* conv = builder.AddInstruction(HloInstruction::CreateConvolve( ShapeUtil::MakeShape(F32, {20, 10, 10, 192}), output, reverse_kernel, conv_window, tf_default_dnums_for_backward_input_)); // Verify the convolution's shape is consistent with ShapeInference. CHECK(ShapeUtil::Compatible( conv->shape(), ShapeInference::InferConvolveShape( output->shape(), reverse_kernel->shape(), conv_window, tf_default_dnums_for_backward_input_) .ValueOrDie())); auto module = CreateNewModule(); HloComputation* entry_computation = module->AddEntryComputation(builder.Build()); EXPECT_TRUE(RunPass(module.get())); ASSERT_THAT(entry_computation->root_instruction(), op::GetTupleElement( op::CustomCall(kCudnnConvBackwardInputCallTarget), 0)); const HloInstruction* custom_call = entry_computation->root_instruction()->operand(0); for (int i = 0; i < 2; ++i) { const WindowDimension& window_dim = custom_call->window().dimensions(i); EXPECT_EQ(0, window_dim.padding_low()); EXPECT_EQ(0, window_dim.padding_high()); EXPECT_EQ(2, window_dim.stride()); } } // Similar to BackwardInputConvolveUnevenPadding, but the low padding of the // gradients exceeds kernel_size - 1. Therefore, this pattern cannot be fused. TEST_F(CudnnConvolutionRewriterTest, BackwardInputConvolveLowPaddingTooLarge) { auto builder = HloComputation::Builder(TestName()); HloInstruction* output = builder.AddInstruction(HloInstruction::CreateParameter( 0, ShapeUtil::MakeShape(F32, {20, 4, 4, 320}), "output")); HloInstruction* kernel = builder.AddInstruction(HloInstruction::CreateParameter( 1, ShapeUtil::MakeShape(F32, {3, 3, 192, 320}), "kernel")); HloInstruction* reverse_kernel = builder.AddInstruction( HloInstruction::CreateReverse(kernel->shape(), kernel, {0, 1})); Window conv_window = default_conv_window_; for (int i = 0; i < 2; ++i) { conv_window.mutable_dimensions(i)->set_size(3); conv_window.mutable_dimensions(i)->set_padding_low(3); conv_window.mutable_dimensions(i)->set_padding_high(2); conv_window.mutable_dimensions(i)->set_base_dilation(2); } HloInstruction* conv = builder.AddInstruction(HloInstruction::CreateConvolve( ShapeUtil::MakeShape(F32, {20, 10, 10, 192}), output, reverse_kernel, conv_window, tf_default_dnums_for_backward_input_)); // Verify the convolution's shape is consistent with ShapeInference. CHECK(ShapeUtil::Compatible( conv->shape(), ShapeInference::InferConvolveShape( output->shape(), reverse_kernel->shape(), conv_window, tf_default_dnums_for_backward_input_) .ValueOrDie())); auto module = CreateNewModule(); HloComputation* entry_computation = module->AddEntryComputation(builder.Build()); EXPECT_TRUE(RunPass(module.get())); EXPECT_THAT( entry_computation->root_instruction(), op::GetTupleElement(op::CustomCall(kCudnnConvForwardCallTarget), 0)); } // Extracted from //learning/brain/google/xla/benchmarks/resnet.py // // For simplicity, we focus on the column dimension and ignore other dimensions. // We use [?] to represent the shape instead of the content. // // Suppose operator FC does // [4] = conv([14], [3], stride=2, padding_high=1) // Padding::kSame // // BC = BackwardInput(FC) does: // [14] = conv([7], reverse([3]), // padding_low=2, padding_high=1, base_dilation=2) // // We should fuse BC even though padding on activations is uneven, because // PadInsertion will canonicalize the fusion HLO. TEST_F(CudnnConvolutionRewriterTest, BackwardInputConvolveUnevenPaddingOnActivations) { auto builder = HloComputation::Builder(TestName()); // The gradients are in NCHW layout. HloInstruction* output = builder.AddInstruction(HloInstruction::CreateParameter( 0, ShapeUtil::MakeShape(F32, {1, 1, 7, 1}), "output")); // The kernel is in HWIO layout. HloInstruction* kernel = builder.AddInstruction(HloInstruction::CreateParameter( 1, ShapeUtil::MakeShape(F32, {1, 3, 1, 1}), "kernel")); HloInstruction* reverse_kernel = builder.AddInstruction( HloInstruction::CreateReverse(kernel->shape(), kernel, {0, 1})); Window conv_window = default_conv_window_; WindowDimension* forward_conv_col_dim = conv_window.mutable_dimensions(1); forward_conv_col_dim->set_size(3); forward_conv_col_dim->set_padding_low(2); forward_conv_col_dim->set_padding_high(1); forward_conv_col_dim->set_base_dilation(2); HloInstruction* conv = builder.AddInstruction(HloInstruction::CreateConvolve( ShapeUtil::MakeShape(F32, {1, 1, 14, 1}), output, reverse_kernel, conv_window, tf_default_dnums_for_backward_input_)); // Verify the convolution's shape is consistent with ShapeInference. CHECK(ShapeUtil::Compatible( conv->shape(), ShapeInference::InferConvolveShape( output->shape(), reverse_kernel->shape(), conv_window, tf_default_dnums_for_backward_input_) .ValueOrDie())); auto module = CreateNewModule(); const HloComputation* entry_computation = module->AddEntryComputation(builder.Build()); EXPECT_TRUE(RunPass(module.get())); ASSERT_THAT(entry_computation->root_instruction(), op::GetTupleElement( op::CustomCall(kCudnnConvBackwardInputCallTarget), 0)); const WindowDimension& backward_conv_col_dim = entry_computation->root_instruction()->operand(0)->window().dimensions(1); EXPECT_EQ(0, backward_conv_col_dim.padding_low()); EXPECT_EQ(1, backward_conv_col_dim.padding_high()); } // For simplicity, we focus on the column dimension and ignore other dimensions. // We use [?] to represent the shape instead of the content. // // Suppose operator FC does // [3] = conv([4], [2], padding_low=1, padding_high=-1) // // BC = BackwardInput(FC) does: // [4] = conv([3], reverse([2]), padding_high=2) // // We currently don't fuse BC because PadInsertion doesn't support negative // padding on the gradients of backward convolution (b/32744257). TEST_F(CudnnConvolutionRewriterTest, BackwardInputConvolveNegativePaddingHighOnActivations) { auto builder = HloComputation::Builder(TestName()); // The gradients are in NCHW layout. HloInstruction* output = builder.AddInstruction(HloInstruction::CreateParameter( 0, ShapeUtil::MakeShape(F32, {1, 1, 3, 1}), "output")); // The kernel is in HWIO layout. HloInstruction* kernel = builder.AddInstruction(HloInstruction::CreateParameter( 1, ShapeUtil::MakeShape(F32, {1, 2, 1, 1}), "kernel")); HloInstruction* reverse_kernel = builder.AddInstruction( HloInstruction::CreateReverse(kernel->shape(), kernel, {0, 1})); Window conv_window = default_conv_window_; WindowDimension* forward_conv_col_dim = conv_window.mutable_dimensions(1); forward_conv_col_dim->set_size(2); forward_conv_col_dim->set_padding_high(2); HloInstruction* conv = builder.AddInstruction(HloInstruction::CreateConvolve( ShapeUtil::MakeShape(F32, {1, 1, 4, 1}), output, reverse_kernel, conv_window, tf_default_dnums_for_backward_input_)); // Verify the convolution's shape is consistent with ShapeInference. CHECK(ShapeUtil::Compatible( conv->shape(), ShapeInference::InferConvolveShape( output->shape(), reverse_kernel->shape(), conv_window, tf_default_dnums_for_backward_input_) .ValueOrDie())); auto module = CreateNewModule(); HloComputation* entry_computation = module->AddEntryComputation(builder.Build()); EXPECT_TRUE(RunPass(module.get())); EXPECT_THAT( entry_computation->root_instruction(), op::GetTupleElement(op::CustomCall(kCudnnConvForwardCallTarget), 0)); } } // anonymous namespace } // namespace gpu } // namespace xla
package org.elasticsearch.client.ml; import org.elasticsearch.client.core.PageParams; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.test.AbstractXContentTestCase; import java.io.IOException; public class GetCategoriesRequestTests extends AbstractXContentTestCase<GetCategoriesRequest> { @Override protected GetCategoriesRequest createTestInstance() { GetCategoriesRequest request = new GetCategoriesRequest(randomAlphaOfLengthBetween(1, 20)); if (randomBoolean()) { request.setCategoryId(randomNonNegativeLong()); } else { int from = randomInt(10000); int size = randomInt(10000); request.setPageParams(new PageParams(from, size)); } if (randomBoolean()) { request.setPartitionFieldValue(randomAlphaOfLength(10)); } return request; } @Override protected GetCategoriesRequest doParseInstance(XContentParser parser) throws IOException { return GetCategoriesRequest.PARSER.apply(parser, null); } @Override protected boolean supportsUnknownFields() { return false; } }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc on Sat Sep 26 12:35:56 CDT 2009--> <TITLE> Java Email Server Client API </TITLE> <SCRIPT type="text/javascript"> targetPage = "" + window.location.search; if (targetPage != "" && targetPage != "undefined") targetPage = targetPage.substring(1); if (targetPage.indexOf(":") != -1) targetPage = "undefined"; function loadFrames() { if (targetPage != "" && targetPage != "undefined") top.classFrame.location = top.targetPage; } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <FRAMESET cols="20%,80%" title="" onLoad="top.loadFrames()"> <FRAMESET rows="30%,70%" title="" onLoad="top.loadFrames()"> <FRAME src="overview-frame.html" name="packageListFrame" title="All Packages"> <FRAME src="allclasses-frame.html" name="packageFrame" title="All classes and interfaces (except non-static nested types)"> </FRAMESET> <FRAME src="overview-summary.html" name="classFrame" title="Package, class and interface descriptions" scrolling="yes"> <NOFRAMES> <H2> Frame Alert</H2> <P> This document is designed to be viewed using the frames feature. If you see this message, you are using a non-frame-capable web client. <BR> Link to<A HREF="overview-summary.html">Non-frame version.</A> </NOFRAMES> </FRAMESET> </HTML>
define(function (require) { var foo = require('../foo'); return { name: 'ALPHA' + foo.name }; });
// // LoadMoreResultsCell.h // MakeAMealOfIt // // Created by James Valaitis on 18/06/2013. // Copyright (c) 2013 &Beyond. All rights reserved. // #pragma mark - Result Management Cell Public Interface @interface ResultManagementCell : UICollectionViewCell {} /** * Publicly allows the setting of the instruction label text. * * @param text The text for the instruction label to present. */ - (void)setInstructionLabelText:(NSString *)text; /** * Starts the activity indicator of this view spinning. */ - (void)startLoading; /** * Stop the activity indicator view spinning. */ - (void)stopLoading; @end
#include "lib/sensors.h" #include "dev/button-sensor.h" #include "mc1322x.h" #include <signal.h> const struct sensors_sensor button_sensor; static struct timer debouncetimer; static int status(int type); void kbi4_isr(void) { if(timer_expired(&debouncetimer)) { timer_set(&debouncetimer, CLOCK_SECOND / 4); sensors_changed(&button_sensor); } clear_kbi_evnt(4); } static int value(int type) { return GPIO->DATA.GPIO_26 || !timer_expired(&debouncetimer); } static int configure(int type, int c) { switch (type) { case SENSORS_ACTIVE: if (c) { if(!status(SENSORS_ACTIVE)) { timer_set(&debouncetimer, 0); enable_irq_kbi(4); kbi_edge(4); enable_ext_wu(4); } } else { disable_irq_kbi(4); } return 1; } return 0; } static int status(int type) { switch (type) { case SENSORS_ACTIVE: case SENSORS_READY: return bit_is_set(*CRM_WU_CNTL, 20); /* check if kbi4 irq is enabled */ } return 0; } SENSORS_SENSOR(button_sensor, BUTTON_SENSOR, value, configure, status);
/* (c) 2014 LinkedIn Corp. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use * this file except in compliance with the License. You may obtain a copy of the * License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. */ package com.linkedin.cubert.functions; import static com.linkedin.cubert.utils.JsonUtils.getText; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.pig.backend.executionengine.ExecException; import org.apache.pig.data.Tuple; import org.codehaus.jackson.JsonNode; import org.codehaus.jackson.node.ArrayNode; import com.linkedin.cubert.block.Block; import com.linkedin.cubert.block.BlockSchema; import com.linkedin.cubert.block.ColumnType; import com.linkedin.cubert.block.DataType; import com.linkedin.cubert.functions.builtin.FunctionFactory; import com.linkedin.cubert.operator.PreconditionException; import com.linkedin.cubert.operator.PreconditionExceptionType; import com.linkedin.cubert.utils.JsonUtils; /** * Parses, constructs and executes the function tree. * <p> * This class can maintain multiple function trees (added via the {@code addFunctionTree} * method). This method parses the JSON specification and builds a runtime representation * of the function tree. This method may throw a {@code PreconditionException} if any * inconsistency is found in the JSON. * <p> * The output type for each function tree can be retrieved using the {@code getType} * method. * <p> * The function tree can be evaluation using the {@code evalTree} method. Before calling * this method, the input tuple must be assigned to the tree using the {@code attachTuple} * method. * * @author Maneesh Varshney * */ public class FunctionTree { private final Block block; private final BlockSchema inputSchema; private final InputProjection[] inputProjections; private final List<FunctionTreeNode> functionTrees = new ArrayList<FunctionTreeNode>(); private DataType[] outputTypes; /** * Create a new object using the input Block. This constructor is called when creating * the FunctionTree at runtime. * * @param block */ public FunctionTree(Block block) { this.block = block; this.inputSchema = block.getProperties().getSchema(); inputProjections = new InputProjection[inputSchema.getNumColumns()]; } /** * Create a new object using the schema of the input block. This constructor is called * when creating the FunctionTree at compile time (since the 'Block' object is not * available at compile time). * * @param schema */ public FunctionTree(BlockSchema schema) { this.block = null; this.inputSchema = schema; inputProjections = new InputProjection[inputSchema.getNumColumns()]; } /** * Adds a new function tree. * * @param json * JSON representation of the function tree. * @throws PreconditionException */ public void addFunctionTree(JsonNode json) throws PreconditionException { FunctionTreeNode root = createTreeNode(json); functionTrees.add(root); outputTypes = new DataType[functionTrees.size()]; for (int i = 0; i < outputTypes.length; i++) outputTypes[i] = functionTrees.get(i).getType().getType(); } /** * Get the type of the root function for the specified function tree. * * @param treeIndex * @return */ public ColumnType getType(int treeIndex) { return functionTrees.get(treeIndex).getType(); } /** * Attaches an input tuple to the tree before calling the {@code evalTree} method. * * @param tuple * @throws ExecException */ public void attachTuple(Tuple tuple) throws ExecException { for (int i = 0; i < inputProjections.length; i++) { if (inputProjections[i] != null) inputProjections[i].setValue(tuple.get(i)); } } /** * Evaluates the specified function tree. * * @param treeIndex * the index of the tree to evaluate. * @return * @throws IOException */ public Object evalTree(int treeIndex) throws IOException { FunctionTreeNode root = functionTrees.get(treeIndex); Object val = root.eval(); if (val == null) return null; // if val is numeric, the actual value may be of narrower type. // upcast it to the proper wider type switch (outputTypes[treeIndex]) { case INT: return ((Number) val).intValue(); case LONG: return ((Number) val).longValue(); case FLOAT: return ((Number) val).floatValue(); case DOUBLE: return ((Number) val).doubleValue(); default: return val; } } /** * Recursive method to parse and construct the function tree. * * @param json * @return * @throws PreconditionException */ private FunctionTreeNode createTreeNode(JsonNode json) throws PreconditionException { String function = getText(json, "function"); ArrayNode args = (ArrayNode) json.get("arguments"); if (function.equals("INPUT_PROJECTION")) { Object selector = JsonUtils.decodeConstant(args.get(0), null); int index = getSelectorIndex(inputSchema, selector); if (inputProjections[index] == null) inputProjections[index] = new InputProjection(index); Function func = inputProjections[index]; return new FunctionTreeNode(func, null, func.outputSchema(inputSchema)); } else if (function.equals("PROJECTION")) { Object selector = JsonUtils.decodeConstant(args.get(1), null); FunctionTreeNode parent = createTreeNode(args.get(0)); int index = getSelectorIndex(parent.getType().getColumnSchema(), selector); Function func = new Projection(index); return new FunctionTreeNode(func, new LazyTuple(parent), func.outputSchema(parent.getType() .getColumnSchema())); } else if (function.equals("MAP_PROJECTION")) { String key = args.get(1).getTextValue(); FunctionTreeNode mapNode = createTreeNode(args.get(0)); Function func = new MapProjection(key); return new FunctionTreeNode(func, new LazyTuple(mapNode), func.outputSchema(mapNode.getType() .getColumnSchema())); } else if (function.equals("CONSTANT")) { String type = (args.size() > 1) ? args.get(1).getTextValue() : null; Object constant = JsonUtils.decodeConstant(args.get(0), type); Function func = new Constant(constant); return new FunctionTreeNode(func, null, func.outputSchema(null)); } else { Function func = FunctionFactory.get(function, json.get("constructorArgs")); if (block != null) func.setBlock(block); FunctionTreeNode[] children = new FunctionTreeNode[args.size()]; ColumnType[] columnTypes = new ColumnType[args.size()]; for (int i = 0; i < args.size(); i++) { children[i] = createTreeNode(args.get(i)); columnTypes[i] = children[i].getType(); } return new FunctionTreeNode(func, new LazyTuple(children), func.outputSchema(new BlockSchema(columnTypes))); } } public static int getSelectorIndex(BlockSchema schema, Object selector) throws PreconditionException { int index = -1; if (selector instanceof Integer) { index = (Integer) selector; if (index < 0 || index >= schema.getNumColumns()) { throw new PreconditionException(PreconditionExceptionType.COLUMN_NOT_PRESENT, "Column at index " + index + " is not present in input: " + schema); } } else { String colName = (String) selector; if (!schema.hasIndex(colName)) throw new PreconditionException(PreconditionExceptionType.COLUMN_NOT_PRESENT, "Column " + colName + " is not present in input: " + schema); index = schema.getIndex(colName); } return index; } }
[HTML5 Boilerplate homepage](https://html5boilerplate.com) | [Documentation table of contents](TOC.md) # The CSS HTML5 Boilerplate's CSS includes: * [Normalize.css](#normalizecss) * [Useful defaults](#useful-defaults) * [Common helpers](#common-helpers) * [Placeholder media queries](#media-queries) * [Print styles](#print-styles) This starting CSS does not rely on the presence of [conditional class names](https://www.paulirish.com/2008/conditional-stylesheets-vs-css-hacks-answer-neither/), [conditional style sheets](https://css-tricks.com/how-to-create-an-ie-only-stylesheet/), or [Modernizr](http://modernizr.com/), and it is ready to use no matter what your development preferences happen to be. ## Normalize.css In order to make browsers render all elements more consistently and in line with modern standards, we include [Normalize.css](https://necolas.github.io/normalize.css/) — a modern, HTML5-ready alternative to CSS resets. As opposed to CSS resets, Normalize.css: * targets only the styles that need normalizing * preserves useful browser defaults rather than erasing them * corrects bugs and common browser inconsistencies * improves usability with subtle improvements * doesn't clutter the debugging tools * has better documentation For more information about Normalize.css, please refer to its [project page](https://necolas.github.com/normalize.css/), as well as this [blog post](http://nicolasgallagher.com/about-normalize-css/). ## Useful defaults Several base styles are included that build upon `Normalize.css`. These styles: * provide basic typography settings that improve text readability * protect against unwanted `text-shadow` during text highlighting * tweak the default alignment of some elements (e.g.: `img`, `video`, `fieldset`, `textarea`) * style the prompt that is displayed to users using an outdated browser You are free and even encouraged to modify or add to these base styles as your project requires. ## Common helpers Along with the base styles, we also provide some commonly used helper classes. #### `.hidden` The `hidden` class can be added to any element that you want to hide visually and from screen readers. It could be an element that will be populated and displayed later, or an element you will hide with JavaScript. #### `.visuallyhidden` The `visuallyhidden` class can be added to any element that you want to hide visually, while still have its content accessible to screen readers. See also: * [CSS in Action: Invisible Content Just for Screen Reader Users](http://www.webaim.org/techniques/css/invisiblecontent/) * [Hiding content for accessibility](http://snook.ca/archives/html_and_css/hiding-content-for-accessibility) * [HTML5 Boilerplate - Issue #194](https://github.com/h5bp/html5-boilerplate/issues/194/). #### `.invisible` The `invisible` class can be added to any element that you want to hide visually and from screen readers, but without affecting the layout. As opposed to the `hidden` class that effectively removes the element from the layout, the `invisible` class will simply make the element invisible while keeping it in the flow and not affecting the positioning of the surrounding content. __N.B.__ Try to stay away from, and don't use the classes specified above for [keyword stuffing](https://en.wikipedia.org/wiki/Keyword_stuffing) as you will harm your site's ranking! #### `.clearfix` The `clearfix` class can be added to any element to ensure that it always fully contains its floated children. Over the years there have been many variants of the clearfix hack, but currently, we use the [micro clearfix](http://nicolasgallagher.com/micro-clearfix-hack/). ## Media Queries HTML5 Boilerplate makes it easy for you to get started with a [_mobile first_](http://www.lukew.com/presos/preso.asp?26) and [_responsive web design_](http://www.alistapart.com/articles/responsive-web-design/) approach to development. But it's worth remembering that there are [no silver bullets](http://blog.cloudfour.com/css-media-query-for-mobile-is-fools-gold/). We include placeholder media queries to help you build up your mobile styles for wider viewports and high-resolution displays. It's recommended that you adapt these media queries based on the content of your site rather than mirroring the fixed dimensions of specific devices. If you do not want to take the _mobile first_ approach, you can simply edit or remove these placeholder media queries. One possibility would be to work from wide viewports down, and use `max-width` media queries instead (e.g.: `@media only screen and (max-width: 480px)`). For more features that can help you in your mobile web development, take a look into our [Mobile Boilerplate](https://github.com/h5bp/mobile-boilerplate). ## Print styles Lastly, we provide some useful print styles that will optimize the printing process, as well as make the printed pages easier to read. At printing time, these styles will: * strip all background colors, change the font color to black, and remove the `text-shadow` — done in order to [help save printer ink and speed up the printing process](http://www.sanbeiji.com/archives/953) * underline and expand links to include the URL — done in order to allow users to know where to refer to<br> (exceptions to this are: the links that are [fragment identifiers](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#attr-href), or use the [`javascript:` pseudo protocol](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void#JavaScript_URIs)) * expand abbreviations to include the full description — done in order to allow users to know what the abbreviations stands for * provide instructions on how browsers should break the content into pages and on [orphans/widows](https://en.wikipedia.org/wiki/Widows_and_orphans), namely, we instruct [supporting browsers](https://en.wikipedia.org/wiki/Comparison_of_layout_engines_%28Cascading_Style_Sheets%29#Grammar_and_rules) that they should: * ensure the table header (`<thead>`) is [printed on each page spanned by the table](http://css-discuss.incutio.com/wiki/Printing_Tables) * prevent block quotations, preformatted text, images and table rows from being split onto two different pages * ensure that headings never appear on a different page than the text they are associated with * ensure that [orphans and widows](https://en.wikipedia.org/wiki/Widows_and_orphans) do [not appear on printed pages](https://css-tricks.com/almanac/properties/o/orphans/) The print styles are included along with the other `css` to [avoid the additional HTTP request](http://www.phpied.com/delay-loading-your-print-css/). Also, they should always be included last, so that the other styles can be overwritten.
(function($) { var LINE_ELM_ID_FORMAT = 'line_{0}'; var RECT_ELM_ID_FORMAT = 'rect_{0}'; var VERT_LINE_ELM_ID_FORMAT = 'vert_line_{0}'; var X_LABEL_ELM_ID_FORMAT = 'x_label_{0}'; var TOOLTIP_TIME_FORMAT = '{0}-{1}'; var TOOLTIP_OPEN_CLOSE_FORMAT = 'Open/Close= {0}/{1}'; var TOOLTIP_HIGH_LOW_FORMAT = 'High/Low= {0}/{1}'; var TOOLTIP_WIDTH = 150; var TOOLTIP_HEIGHT = 50; var PATH_LINE_FORMAT = 'L {0} {1} '; var SEQUENCE_START_INDEX = 1; var REFRESH_SIZE = 2; var X_LABEL_HEIGHT = 32; var Y_LABEL_WIDTH = 70; var TOOLTIP_MARGIN = { TOP: 10, LEFT: 10 }; var SERIES_PREFIX = '_series'; var COLORS = ['red', 'blue', 'green', 'yellow', 'orange', 'purple']; // TODO: デフォルトカラー決める var CHART_TYPES = ['line', 'ohlc', 'bar', 'stacked_line', 'stacked_bar']; var STACKED_CHART_TYPES = ['stacked_line', 'stacked_bar']; // 変数のインポート var h5format = h5.u.str.format; var requestAnimationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame || function(func) { window.setTimeout(func, 15); }; var graphicRenderer = h5.ui.components.chart.GraphicRenderer; var chartDataModelManager = h5.core.data.createManager('ChartDataManager'); /** * chartの設定に関するデータアイテム */ var chartSettingsSchema = { rangeMin: { type: 'number' }, rangeMax: { type: 'number' }, /** * y軸の最小値 */ minVal: { type: 'number', defaultValue: Infinity }, /** * y軸の最大値 */ maxVal: { type: 'number', defaultValue: -Infinity }, /** * candleの中心のx軸方向の間隔 */ dx: { depend: { on: ['dispDataSize', 'width'], calc: function() { return this.get('width') / this.get('dispDataSize'); } } }, dispDataSize: { type: 'integer' }, vertLineNum: { type: 'integer' }, horizLineNum: { type: 'integer' }, keepDataSize: { type: 'integer' }, movedNum: { type: 'integer', defaultValue: 0 }, /** * 描画領域の高さ */ height: { type: 'number' }, /** * 描画領域の幅 */ width: { type: 'number' }, translateX: { defalutValue: 0 }, timeInterval: { type: 'integer' }, /** * 補助線の色 */ additionalLineColor: { type: 'string' } }; /** * ローソク表示用データを保持するモ * * @name chartModel */ var candleStickSchema = { id: { id: true, type: 'integer' }, rectX: { type: 'number', depend: { on: ['rectWidth', 'lineX'], calc: function() { return this.get('lineX') - this.get('rectWidth') / 2; } } }, rectY: { type: 'number', constraint: { notNull: true } }, rectWidth: { type: 'number', constraint: { notNull: true } }, rectHeight: { type: 'number', constraint: { notNull: true } }, fill: { type: 'string' }, lineX: { type: 'number', constraint: { notNull: true } }, lineY1: { type: 'number', constraint: { notNull: true } }, lineY2: { type: 'number', constraint: { notNull: true } }, time: { type: 'string' } }; var lineSchema = { id: { id: true, type: 'integer' }, fromX: { type: 'number', constraint: { notNull: true } }, toX: { type: 'number', constraint: { notNull: true } }, fromY: { type: 'number', constraint: { notNull: true } }, toY: { type: 'number', constraint: { notNull: true } } }; /** * グループ内でのY座標の位置を計算します * * @param val * @returns {Number} */ function calcYPos(val, rangeMin, rangeMax, height) { return -(val * 1000 - rangeMin * 1000) / (rangeMax * 1000 - rangeMin * 1000) * height + height; } /** * 2つの値からグループ内でのY座標の位置の差を計算します * * @param val1 * @param val2 * @returns {Number} */ function calcYDiff(val1, val2, rangeMin, rangeMax, height) { return Math.abs(val1 * 1000 - val2 * 1000) / (rangeMax * 1000 - rangeMin * 1000) * height; } function sortById(items) { var ret = []; for (var i = 0, iLen = items.length; i < iLen; i++) { var item = items[i]; var id = item.get('id'); var inserted = false; for (var j = 0, jLen = ret.length; j < jLen; j++) { if (id < ret[j].get('id')) { ret.splice(j, 0, item); inserted = true; break; } } if (!inserted) { ret.push(item); } } return ret; } var dataSourceCounter = 0; function DataSource(name, seriesSetting, number) { this.name = name; this.seriesSetting = seriesSetting; this.number = number; this.sequence = h5.core.data.createSequence(SEQUENCE_START_INDEX); this.xLabelArray = null; } DataSource.prototype = { getData: function(series) { var that = this; this._getData(series).done(function(data) { that.convertToModel(series.type, data, series.propNames); }); }, /** * チャート 行 * * @memberOf * @returns Promiseオブジェクト */ _getData: function(series) { var dfd = $.Deferred(); if (series.data == null) { // 初期表示データの取得 h5.ajax({ type: 'GET', dataType: 'text', url: series.url }).done(function(data) { dfd.resolve(); }); } else { var len = series.data.length; var keepDataSize = this.manager.chartSetting.get('keepDataSize'); var _data = keepDataSize == null ? series.data : series.data.slice(len - keepDataSize); if (this.manager.chartSetting.get('dispDataSize') == null) { this.manager.chartSetting.set('dispDataSize', _data.length); } dfd.resolve(_data); } return dfd.promise(); }, convertToModel: function(type, data, propNames) { var modelBaseName = 'dataModel'; this._type = type.toLowerCase(); var schema; // var schema = rateDataSchema; switch (this._type) { case 'ohlc': this.propNames = propNames || {}; this.highProp = this.propNames.high || 'high'; this.lowProp = this.propNames.low || 'low'; this.xProp = this.propNames.time || 'time'; schema = this._createSchema(data[0]); break; case 'stacked_line': case 'line': this.propNames = propNames || { x: 'x', y: 'y' }; // this.highProp = this.propNames.y || 'y'; // this.lowProp = this.propNames.y || 'y'; this.xProp = this.propNames.x || 'x'; this.highProp = 'y'; this.lowProp = 'y'; // this.xProp = 'x'; schema = this._createSchema(data[0]); break; default: modelBaseName = ''; schema = ''; break; } var modelName = modelBaseName + '_' + this.name + '_' + dataSourceCounter; dataSourceCounter++; if (this.dataModel != null) { chartDataModelManager.dropModel(this.dataMode.name); } this.dataModel = chartDataModelManager.createModel({ name: modelName, schema: schema }); this._calcDataItem(data, propNames); }, getDataObj: function(id) { var item = this.dataModel.get(id); if (!item) { return null; } var obj = item.get(); delete obj.id; for ( var name in obj) { if (this.propNames[name]) { obj[this.propNames[name]] = obj[name]; delete obj[name]; } } return obj; }, createItem: function(data, chartSetting) { // if (chartSetting.get('keepDataSize') != null) { // this.dataModel.remove(this.sequence.current() - chartSetting.get('keepDataSize')); // } return this._calcDataItem([data], this.propNames)[0]; }, _createSchema: function(data) { var schema = {}; for ( var name in data) { if (data.hasOwnProperty(name)) { var propName = name; for ( var key in this.propNames) { if (this.propNames[key] === name) { // propName = key; schema[key] = null; } } schema[propName] = null; } } schema.id = { id: true, type: 'integer' }; return schema; }, _calcDataItem: function(data, prop) { var arr = []; var chartSetting = this.manager.chartSetting; var dispDataSize = chartSetting.get('dispDataSize'); var minVal = Infinity; var maxVal = -Infinity; for (var i = 0, len = data.length; i < len; i++) { var obj = this._toData(data[i], prop); arr.push(obj); if (len - dispDataSize <= i) { minVal = Math.min(minVal, this._getStackedVal(obj, this.lowProp)); maxVal = Math.max(maxVal, this._getStackedVal(obj, this.highProp)); } } if (!this.seriesSetting.axis || !this.seriesSetting.axis.yaixs || this.seriesSetting.axis.yaxis.autoScale !== false) { chartSetting.set({ minVal: Math.min(minVal, chartSetting.get('minVal')), maxVal: Math.max(maxVal, chartSetting.get('maxVal')) }); } return this.dataModel.create(arr); }, _getStackedVal: function(obj, propName) { if ($.inArray(this._type, STACKED_CHART_TYPES) === -1) { return obj[propName]; } return obj[propName] + this.manager.getStackedData(obj.id, propName, this.number)[propName]; }, _toData: function(data, prop) { // switch (this._type) { // case 'line': // return { // id: this.sequence.next(), // x: data[prop.x], // y: data[prop.y] // }; // case 'candlestick': var ret = { id: this.sequence.next() }; if (!prop) { return $.extend(ret, data); } for ( var name in data) { var propName = name; ret[propName] = data[name]; for ( var key in prop) { if (prop[key] === name) { propName = key; ret[key] = data[name]; break; } } } return ret; // return $.extend({}, data, { // id: this.sequence.next() // }); // } }, getStackedData: function(item) { return this.manager.getStackedData(item.get('id'), this.propNames.y, this.number); }, getMaxAndMinVals: function(rightEndId, dispDataSize) { var maxVal = -Infinity; var minVal = Infinity; var current = rightEndId || this.sequence.current(); var item = null; // 表示対象の中で、最大・最小を求める for (var i = current - dispDataSize + 1; i <= current; i++) { item = this.dataModel.get(i); if (item === null) { continue; } var high = item.get(this.highProp); var low = item.get(this.lowProp); if (high > maxVal) { maxVal = high; } if (low < minVal) { minVal = low; } } return { maxVal: maxVal, minVal: minVal }; }, getXVal: function(idOrItem) { if (idOrItem == null) { return null; } var item; if (typeof (idOrItem.getModel) === 'function' && idOrItem.getModel() === this.dataModel) { item = idOrItem; } else { item = this.dataModel.get(idOrItem); } return item.get(this.xProp); }, checkRange: function(addedItem, removedItem, dispDataSize, rightEndId) { if (this.seriesSetting.axis && this.seriesSetting.axis.yaixs && this.seriesSetting.axis.yaxis.autoScale === false) { return; } this.manager.checkRange(addedItem.get(this.highProp), addedItem.get(this.lowProp), removedItem.get(this.highProp), removedItem.get(this.lowProp), rightEndId, dispDataSize); } }; /** * @class * @name dataSourceManager */ function DataSourceManager(chartSetting) { this._count = 0; this._map = {}; this.chartSetting = chartSetting; } DataSourceManager.prototype = { checkRange: function(adderdMax, addedMin, removedMax, removedMin, rightEndId) { if (this._isUpdateRange(adderdMax, addedMin, removedMax, removedMin)) { this.setRange(rightEndId); } }, setRange: function(rightEndId) { this.chartSetting.set(this.getMaxAndMinVals(rightEndId, this.chartSetting .get('dispDataSize'))); }, _isUpdateRange: function(adderdMax, addedMin, removedMax, removedMin) { var maxVal = this.chartSetting.get('maxVal'); var minVal = this.chartSetting.get('minVal'); return adderdMax > maxVal || addedMin < minVal || removedMax === maxVal || removedMin === minVal; }, getAllDataSources: function() { return this._map; }, getStackedData: function(id, yProp, number) { var stackedVal = 0; for ( var name in this._map) { var dataSource = this._map[name]; if (dataSource.number < number) { stackedVal += dataSource.dataModel.get(id).get(yProp); } } var ret = {}; ret.id = id; ret[yProp] = stackedVal; return ret; }, createDataSource: function(seriesSetting) { var name = seriesSetting.name; this._map[name] = new DataSource(name, seriesSetting, this._count); this._map[name].manager = this; this._count++; return this._map[name]; }, removeDataSource: function(name) { delete this._map[name]; }, getDataSource: function(name) { return this._map[name]; }, getMaxAndMinVals: function(rightEndId, dispDataSize) { var dataSources = this._map; var maxAndMinVals = { maxVal: -Infinity, minVal: Infinity }; for ( var name in dataSources) { var vals = dataSources[name].getMaxAndMinVals(rightEndId, dispDataSize); maxAndMinVals = { maxVal: Math.max(vals.maxVal, maxAndMinVals.maxVal), minVal: Math.min(vals.minVal, maxAndMinVals.minVal) }; } return maxAndMinVals; } }; // チャートレンダラ―の定義 var rendererNum = 0; function getDefaultTooltip(data) { var time = h5format(TOOLTIP_TIME_FORMAT, data.openTime, data.closeTime); var open_close = h5format(TOOLTIP_OPEN_CLOSE_FORMAT, data.open, data.close); var high_low = h5format(TOOLTIP_HIGH_LOW_FORMAT, data.high, data.low); return time + '<br>' + open_close + '<br>' + high_low; } function createChartRenderer(rootElement, dataSource, chartSetting, seriesSetting, schema, prototype) { function ChartRendererBase(rootElement, dataSource, chartSetting, seriesSetting, schema) { this.dataSource = dataSource; this.name = dataSource.name; this.chartSetting = chartSetting; this.rootElement = rootElement; this.seriesSetting = seriesSetting; this.isReadyToAdd = false; if (!graphicRenderer.isSvg) { this.COORDSIZE = this.chartSetting.get('width') + ' ' + this.chartSetting.get('height'); } this.chartModel = chartDataModelManager.createModel({ name: 'chartModel_' + rendererNum + '_' + this.name, schema: schema }); rendererNum++; var that = this; this.chartModel.addEventListener('itemsChange', function(ev) { that._chartModelChangeListener.apply(that, [ev]); }); this.leftEndCandleStickId = Infinity; } ChartRendererBase.prototype = { addData: function(data) { // this.seriesSetting.data.push(data); var dataSource = this.dataSource; // データを1つ分受け取って、チャートを更新する var item = dataSource.createItem(data, this.chartSetting); this.updateChart(item); dataSource.dataModel.remove(item.get('id') - this.chartSetting.get('keepDataSize')); }, updateChart: function(addedItem, removedItemId, isRightEndRemove) { // ローソク情報を計算する var chartItem = this.createItem(addedItem); this.getXLabelArray(); // チャートのローソクを更新する var dispDataSize = this.chartSetting.get('dispDataSize'); if (removedItemId == null) { // 表示範囲の左端のIDを取得 removedItemId = addedItem.get('id') - dispDataSize - this.chartSetting.get('movedNum'); isRightEndRemove = false; } this.removeChartElm(removedItemId); var removedItem = this.dataSource.dataModel.get(removedItemId); var rightEndId = isRightEndRemove ? removedItemId - 1 : addedItem.get('id'); this.dataSource.checkRange(addedItem, removedItem, dispDataSize, rightEndId); this._appendChart([chartItem]); }, updateYVal: function() { chartDataModelManager.beginUpdate(); for ( var id in this.chartModel.items) { var intId = parseInt(id); // 描画範囲のローソクは座標情報を計算する var item = this.dataSource.dataModel.get(intId); var chartItem = this.chartModel.get(intId); if (chartItem != null) { chartItem.set(this.toData(item)); } } chartDataModelManager.endUpdate(); }, removeChartElm: function(id) { var $root = $(this.rootElement); this.chartModel.remove(id); $(this.rootElement).trigger('removeTooltip', id); // TODO: ID体系、DOM構成見直し. ローソクには同じクラス名あてたほうがよいかも。 $root.find('#' + h5format(LINE_ELM_ID_FORMAT, id)).remove(); $root.find('#' + h5format(RECT_ELM_ID_FORMAT, id)).remove(); $root.find('#' + h5format(VERT_LINE_ELM_ID_FORMAT, id)).remove(); $root.find('#' + h5format(X_LABEL_ELM_ID_FORMAT, id)).remove(); }, getTargetId: function(context, type) { if (graphicRenderer.isSvg && type !== 'line') { return context.event.target.id.split('_')[1]; } var ev = context.event; var t = ev.currentTarget; var top = t.offsetTop || t.clientTop; var left = t.offsetLeft || t.clientLeft; if (graphicRenderer.isSvg && !h5.env.ua.isIE) { top -= 10; left -= this.chartSetting.get('translateX') + Y_LABEL_WIDTH / 2; } var oy = ev.offsetY; var ox = ev.offsetX; var items = this.chartModel.toArray(); for (var i = items.length - 1; 0 <= i; i--) { var r = this.getRectPos(items[i]); if (r.sx - left <= ox && ox <= r.ex - left && r.sy - top - 1 <= oy && oy <= r.ey - top + 1) { return items[i].get('id'); } } }, showToolTip: function(tooltipId, $tooltip) { if (this.seriesSetting.mouseover && this.seriesSetting.mouseover.tooltip === false) { return; } var dataItem = this.dataSource.dataModel.get(tooltipId); var chartItem = this.chartModel.get(tooltipId); if (chartItem == null) { return; } $tooltip.empty(); var coord = this._getCentralPos(chartItem); if (coord.x + TOOLTIP_WIDTH + TOOLTIP_MARGIN.LEFT > -this.chartSetting .get('translateX') + this.chartSetting.get('width')) { coord.x -= (TOOLTIP_WIDTH + TOOLTIP_MARGIN.LEFT); } else { coord.x += TOOLTIP_MARGIN.LEFT; } if (coord.y + TOOLTIP_HEIGHT + TOOLTIP_MARGIN.TOP > this.chartSetting.get('height')) { coord.y -= (TOOLTIP_HEIGHT + TOOLTIP_MARGIN.TOP); } else { coord.y += TOOLTIP_MARGIN.TOP; } var showTooltip = this.seriesSetting.mouseover.tooltip.content || getDefaultTooltip; var content = showTooltip(dataItem.get()); var rect = graphicRenderer.createRectElm(coord.x, coord.y, TOOLTIP_WIDTH, TOOLTIP_HEIGHT, '#eee', {}); $tooltip.append(rect); graphicRenderer.appendTextElm(content, coord.x, coord.y + 20, '#000', { 'font-size': 11 }, graphicRenderer.isSvg ? $tooltip : $(rect)); // VMLの場合はTEXT要素をRECT要素にappendする this._appendHighLight(chartItem, $tooltip); this.showAdditionalLine(tooltipId, $tooltip); }, showAdditionalLine: function(tooltipId, $tooltip) { var chartItem = this.chartModel.get(tooltipId); var pos = this._getCentralPos(chartItem); var startX = Math.abs(this.chartSetting.get('translateX')); var lineColor = this.chartSetting.get('additionalLineColor'); // Y軸に補助線を引く $tooltip.prepend(graphicRenderer.createLineElm(startX, pos.y, startX + (this.chartSetting.get('width') * 2), pos.y, lineColor, null)); // X軸に補助線を引く $tooltip.prepend(graphicRenderer.createLineElm(pos.x, 0, pos.x, this.chartSetting .get('height'), lineColor, null)); }, getXLabelArray: function() { var vertLineNum = this.chartSetting.get('vertLineNum'); if (vertLineNum === 0) { return; } if (this.xLabelArray == null) { this.xLabelArray = h5.core.data.createObservableArray(); } var rightItemId = this.dataSource.sequence.current() - 1; var dispSizeNum = this.chartSetting.get('dispDataSize'); var itemInterval = (dispSizeNum - 1) / vertLineNum; var id = rightItemId - dispSizeNum + 1; for (var i = 0; i <= vertLineNum; i++) { var item = this.dataSource.getDataObj(id); this.xLabelArray.set(i, { value: item[this.dataSource.xProp], item: item }); id += itemInterval; } return this.xLabelArray; }, _rectPath: function(rect) { var left = parseInt(rect.left); var top = parseInt(rect.top); var right = parseInt(rect.left + rect.width); var bottom = parseInt(rect.top + rect.height); return h5format('m {0} {1} l {2} {3} {4} {5} {6} {7} {8} {9} e', left, top, right, top, right, bottom, left, bottom, left, top); } }; $.extend(ChartRendererBase.prototype, prototype); return new ChartRendererBase(rootElement, dataSource, chartSetting, seriesSetting, schema); } // ローソクチャートのレンダラ― function createCandleStickChartRenderer(rootElement, dataSource, chartSetting, seriesSetting) { return createChartRenderer( rootElement, dataSource, chartSetting, seriesSetting, candleStickSchema, { _getCentralPos: function(chartItem) { return { x: chartItem.get('rectX') + (chartItem.get('rectWidth') / 2), y: chartItem.get('rectY') + (chartItem.get('rectHeight') / 2) }; }, /** * ーソク を生成する * * @memberOf candleStickRenderer */ createCandleStickDataItems: function() { this.chartModel.removeAll(); var candleStickData = []; var current = this.dataSource.sequence.current(); for ( var id in this.dataSource.dataModel.items) { if (id >= current - this.chartSetting.get('dispDataSize')) { // 描画範囲のローソクは座標情報を計算する var dataItem = this.dataSource.dataModel.items[id]; candleStickData.push(this.toData(dataItem)); } } this.chartModel.create(candleStickData); }, createItem: function(dataItem) { return this.chartModel.create(this.toData(dataItem)); }, /** * * ロ ータを取得す * * @memberOf candleStickRenderer * @param {object} chart チャート情報 * @returns {object} ローソクの座標情報 */ toData: function(chartDataItem) { var id = chartDataItem.get('id'); var open = chartDataItem.get('open'); var close = chartDataItem.get('close'); var time = chartDataItem.get(this.dataSource.xProp); return $.extend(this._calcCandleYValues(chartDataItem), { id: id, rectWidth: this.chartSetting.get('dx') * 0.8, fill: open > close ? 'blue' : open === close ? 'black' : 'red', lineX: id * this.chartSetting.get('dx') + this.chartSetting.get('width'), time: time }); }, _calcCandleYValues: function(chartDataItem) { var open = chartDataItem.get('open'); var close = chartDataItem.get('close'); var min = this.chartSetting.get('rangeMin'); var max = this.chartSetting.get('rangeMax'); var height = this.chartSetting.get('height'); return { rectY: calcYPos(Math.max(open, close), min, max, height), rectHeight: open !== close ? calcYDiff(open, close, min, max, height) : 1, lineY1: calcYPos(chartDataItem.get('low'), min, max, height), lineY2: calcYPos(chartDataItem.get('high'), min, max, height) }; }, draw: function() { $(this.rootElement).empty(); this.createCandleStickDataItems(); if (graphicRenderer.isSvg) { this._showSVGCandleSticks(); // ローソクを描画 } else { this._showVMLCandleSticks(); // ローソクを描画 } }, _showSVGCandleSticks: function() { var candleSticks = this.chartModel.toArray(); for (var i = 0, len = candleSticks.length; i < len; i++) { this.appendCandleStick(candleSticks[i], this.rootElement); } }, _appendChart: function(items) { if (graphicRenderer.isSvg) { this.appendCandleStick(items[0], this.rootElement); } else { this.updateCandleStick(); } }, appendCandleStick: function(candleStickItem, parent) { var $parent = $(parent); this._appendCandleStick(candleStickItem, $parent, '#000', { id: h5format(LINE_ELM_ID_FORMAT, candleStickItem.get('id')), 'class': 'candleStickChart chartElm' }, candleStickItem.get('fill'), { id: h5format(RECT_ELM_ID_FORMAT, candleStickItem.get('id')), 'class': 'candleStickChart chartElm' }); }, _appendHighLight: function(candleStickItem, $tooltip) { if (graphicRenderer.isSvg) { this._appendCandleStick(candleStickItem, $tooltip, 'yellow', { 'class': 'highlight_candle', 'stroke-width': '1px' }, candleStickItem.get('fill'), { 'class': 'highlight_candle', stroke: 'yellow', 'stroke-width': '2px' }); } else { // ハイライト var highlightShape = graphicRenderer.createShapeElm({ coordsize: this.COORDSIZE, path: this._rectPath(this._dataToRect(candleStickItem)), 'class': 'candleStickChart' }); graphicRenderer.css(highlightShape, { zoom: '1', width: this.chartSetting.get('width'), height: this.chartSetting.get('height') }); // 塗りつぶし graphicRenderer.fill(highlightShape, { color: candleStickItem.get('fill') }); // 枠線 graphicRenderer.stroke(highlightShape, { color: 'yellow', weight: 2, on: true }); $tooltip[0].appendChild(highlightShape); } }, _appendCandleStick: function(candleStickItem, $parent, lineColor, lineProp, rectColor, rectProp) { graphicRenderer.appendLineElm(candleStickItem.get('lineX'), candleStickItem .get('lineY1'), candleStickItem.get('lineX'), candleStickItem .get('lineY2'), lineColor, lineProp, $parent); graphicRenderer.appendRectElm(candleStickItem.get('rectX'), candleStickItem .get('rectY'), candleStickItem.get('rectWidth'), candleStickItem .get('rectHeight'), rectColor, rectProp, $parent); }, _chartModelChangeListener: function(ev) { var $root = $(this.rootElement); // 表示範囲が広がった時に、左端のidを探す for (var i = 0, len = ev.created.length; i < len; i++) { if (ev.created[i].get('id') < this.leftEndCandleStickId) { this.leftEndCandleStickId = ev.created[i].get('id'); } } // 座標情報が変更されたときに、表示に反映する for (var i = 0, len = ev.changed.length; i < len; i++) { var changed = ev.changed[i]; if (changed.props.rectY == null && changed.props.rectHeight == null && changed.props.lineY1 == null && changed.props.lineY2 == null) { return; } var item = changed.target; var $line = $root.find('#' + h5format(LINE_ELM_ID_FORMAT, item.get('id'))); $line.attr({ y1: item.get('lineY1'), y2: item.get('lineY2') }); var $rect = $root.find('#' + h5format(RECT_ELM_ID_FORMAT, item.get('id'))); $rect.attr({ y: item.get('rectY'), height: item.get('rectHeight') }); } }, // VML用 _showVMLCandleSticks: function() { this.updateCandleStick(); }, updateCandleStick: function(newCandleStick, removeId) { var data = this._getShapePaths(); this._updateHighLowShape(data); this._updateOpenCloseShape(data); }, _getShapePaths: function() { var lines = []; var rects = {}; // fillの種類ごとに配列を持つ(1shapeにつき1色しか持てないため) var cdata = {}; for ( var id in this.chartModel.items) { var data = this.chartModel.get(id); var lineSubpath = this._linePath(data); // path (m始まり, e終わり)を指定 lines.push(lineSubpath); var rectType = this._getRectType(data); if (!rects[rectType]) { rects[rectType] = []; cdata[rectType] = []; } var pos = this._dataToRect(data); // left, top, width, height, fillを指定 var rectSubpath = this._rectPath(pos); // rect表示のpathを取得 rects[rectType].push(rectSubpath); cdata[rectType].push(pos); } return { lines: lines, rects: rects, data: cdata }; }, _updateHighLowShape: function(shapePaths) { var highlowLineShape = $(this.rootElement).find( '.candleStickChart.chartElm')[0]; if (highlowLineShape == null) { highlowLineShape = graphicRenderer.createShapeElm({ 'class': 'candleStickChart chartElm', coordsize: this.COORDSIZE }); graphicRenderer.css(highlowLineShape, { zoom: '1', width: this.chartSetting.get('width'), height: this.chartSetting.get('height') }); graphicRenderer.stroke(highlowLineShape, { on: true, weight: 1 }); this.rootElement.appendChild(highlowLineShape); } highlowLineShape.path = shapePaths.lines.join(','); }, _updateOpenCloseShape: function(shapePaths) { var rects = shapePaths.rects; // fillの種類ごとに開始・終了値の四角形を描画 for (rectPaths in rects) { if (!rects.hasOwnProperty(rectPaths)) { continue; } var rectShape = $(this.rootElement).find( '.candleStickChart.' + rectPaths)[0]; if (rectShape == null) { var rectShape = graphicRenderer.createShapeElm({ coordsize: this.COORDSIZE, 'class': 'candleStickChart chartElm ' + rectPaths }); graphicRenderer.css(rectShape, { zoom: '1', width: this.chartSetting.get('width'), height: this.chartSetting.get('height') }); graphicRenderer.fill(rectShape, { color: rectPaths }); graphicRenderer.stroke(rectShape, { opacity: 0.01, on: true }); this.rootElement.appendChild(rectShape); } rectShape.path = rects[rectPaths].join(' '); } }, _getRectType: function(data) { return data.get('fill'); }, _dataToRect: function(data) { return { id: data.get('id'), left: data.get('rectX'), top: data.get('rectY'), width: data.get('rectWidth'), height: data.get('rectHeight'), fill: data.get('fill') }; }, _linePath: function(line) { var x = parseInt(line.get('lineX')); var y1 = parseInt(line.get('lineY1')); var y2 = parseInt(line.get('lineY2')); return h5format('m {0} {1} l {0} {2} e', x, y1, y2); }, getRectPos: function(item) { return { sx: parseInt(item.get('rectX')), sy: parseInt(item.get('rectY')), ex: parseInt(item.get('rectX') + item.get('rectWidth')), ey: parseInt(item.get('rectY') + item.get('rectHeight')) }; } }); } /** * ラインチャートレンダラ―を生成する。 * * @private * @returns LineChartRenderer */ function createLineChartRenderer(rootElement, dataSource, chartSetting, seriesSetting) { return createChartRenderer(rootElement, dataSource, chartSetting, seriesSetting, lineSchema, { _getCentralPos: function(chartItem) { return { x: chartItem.get('toX'), y: chartItem.get('toY') }; }, getLeftEndItemId: function() { return this.leftEndCandleStickId; }, draw: function(preRendererChartModel) { $(this.rootElement).empty(); this.$path = null; this.createLineDataItems(preRendererChartModel); var count = 0; var animateNum = this.seriesSetting.animateNum; if (preRendererChartModel == null || animateNum < 1) { animateNum = 1; } var that = this; function doAnimation() { that.appendLines(that.chartModel.toArray(), preRendererChartModel, count / animateNum); count++; if (count < animateNum) { requestAnimationFrame(doAnimation); } else { // 描画完了時にイベントをあげる $(that.rootElement).trigger('finishDrawing'); } } requestAnimationFrame(doAnimation); }, _appendChart: function(elms) { // this.appendLines(elms); this.appendLines(); }, _calcY: function(item, prop, preRendererChartModel, rate) { if (!preRendererChartModel || rate === 1) { return item.get(prop); } return (1 - rate) * preRendererChartModel.get(item.get('id')).get(prop) + rate * item.get(prop); }, appendLines: function(lines, preRendererChartModel, rate) { graphicRenderer.isSvg ? this._appendLinesForSvg(lines, preRendererChartModel, rate) : this._appendLinesForVml(); }, _appendLinesForSvg: function(lines, preRendererChartModel, rate) { var $root = $(this.rootElement); var chartItems = sortById(lines || this.chartModel.toArray()); var item0 = chartItems[0]; var d = 'M' + item0.get('fromX') + ' ' + this._calcY(item0, 'fromY', preRendererChartModel, rate) + ' '; var len = chartItems.length; for (var i = 0; i < len; i++) { d += h5format(PATH_LINE_FORMAT, chartItems[i].get('toX'), this._calcY( chartItems[i], 'toY', preRendererChartModel, rate)); } var fill = this._getFill(); if (fill != null) { d += h5format(PATH_LINE_FORMAT, chartItems[len - 1].get('toX'), this.chartSetting.get('height')) + h5format(PATH_LINE_FORMAT, item0.get('fromX'), this.chartSetting.get('height')) + ' Z'; } if (this.$path != null) { this.$path.attr('d', d); } else { var attrs = { stroke: this.seriesSetting.color || '#000', 'class': 'LineChart chartElm', 'stroke-width': this.seriesSetting['stroke-width'], fill: fill || 'none' }; var $path = $(graphicRenderer.createPathElm(d, attrs)); // iOS7対応 window.scrollTo(window.scrollX, window.scrollY); $root.append($path); this.$path = $path; } }, // TODO: きっとSVG版と統合できるはず(svg/vmlレイヤーで吸収できるはず) _appendLinesForVml: function() { var $root = $(this.rootElement); $root.empty(); var lineData = this.chartModel.toArray(); var lineShape = graphicRenderer.createShapeElm(); graphicRenderer.css(lineShape, { width: this.chartSetting.get('width'), height: this.chartSetting.get('height'), position: 'absolute' }); var fill = this._getFill(); // if (!fill) { // fill = { // color: '#000' // }; // } graphicRenderer.fill(lineShape, fill); graphicRenderer.stroke(lineShape, { on: true, fill: fill.color }); lineShape.className = 'LineChart chartElm'; lineShape.coordsize = this.COORDSIZE; var lineShapePath = ''; var len = lineData.length; for (var i = 0; i < len; i++) { if (i === 0) { var x1 = parseInt(lineData[i].get('fromX')); var y1 = parseInt(lineData[i].get('fromY')); lineShapePath += h5format('m {0},{1} l{0}, {1}', x1, y1); } var x2 = parseInt(lineData[i].get('toX')); var y2 = parseInt(lineData[i].get('toY')); lineShapePath += h5format(',{0},{1}', x2, y2); } if (fill) { var firstX = parseInt(lineData[0].get('fromX')); var lastX = parseInt(lineData[len - 1].get('toX')); var height = this.chartSetting.get('height'); lineShapePath += h5format(',{0},{1}', lastX, height); lineShapePath += h5format(',{0},{1}', firstX, height); lineShapePath += h5format(',{0},{1}', firstX, parseInt(lineData[0] .get('fromY'))); } lineShape.path = lineShapePath + 'e'; $root[0].appendChild(lineShape); }, _getFill: function() { var color = this.seriesSetting.fillColor; if (!color) { return null; } if (typeof color === 'object') { // グラデーションの定義オブジェクト return graphicRenderer.gradient(color.id, color, $(this.rootElement)); } if (typeof color === 'string') { return color; } // TODO: エラー return null; }, createItem: function(dataItem) { return this.chartModel.create(this.toData(dataItem)); }, createLineDataItems: function(preRendererChartModel) { this.chartModel.removeAll(); var lineData = []; var current = this.dataSource.sequence.current() - chartSetting.get('movedNum'); var dispDataSize = this.chartSetting.get('dispDataSize'); for ( var id in this.dataSource.dataModel.items) { var intId = parseInt(id); if (intId < current - dispDataSize || intId >= current) { continue; } // 描画範囲のローソクは座標情報を計算する var item = this.dataSource.dataModel.get(intId); lineData.push(this.toData(item)); } this.chartModel.create(lineData); }, // TODO: xの位置がデータに依存しない toData: function(currentItem) { var id = currentItem.get('id'); var pre = this.dataSource.dataModel.get(id - 1); if (pre == null) { // preがnullのときは、データとしても端であり、このときはただの点を表示する pre = currentItem; } var min = this.chartSetting.get('rangeMin'); var max = this.chartSetting.get('rangeMax'); var height = this.chartSetting.get('height'); var yProp = this.dataSource.propNames.y; //var yProp = 'y'; var fromY = pre.get(yProp); var toY = currentItem.get(yProp); if ($.inArray(this.seriesSetting.type, STACKED_CHART_TYPES) !== -1) { fromY += this.dataSource.getStackedData(pre)[yProp]; toY += this.dataSource.getStackedData(currentItem)[yProp]; } return { id: id, fromX: (id - 1) * this.chartSetting.get('dx') + this.chartSetting.get('width'), toX: id * this.chartSetting.get('dx') + this.chartSetting.get('width'), fromY: calcYPos(fromY, min, max, height), toY: calcYPos(toY, min, max, height) }; }, getXCoord: function(idOrItem) { if (idOrItem == null) { return null; } var item; if (typeof (idOrItem.getModel) === 'function' && idOrItem.getModel() === this.chartModel) { item = idOrItem; } else { item = this.chartModel.get(idOrItem); } return item.get('toX'); }, getXVal: function(idOrItem) { return this.dataSource.getXVal(idOrItem); }, _chartModelChangeListener: function(ev) { // 表示範囲が広がった時に、左端のidを探す for (var i = 0, len = ev.created.length; i < len; i++) { if (ev.created[i].get('id') < this.leftEndCandleStickId) { this.leftEndCandleStickId = ev.created[i].get('id'); } } // // 座標情報が変更されたときに、表示に反映する if (ev.changed.length > 0) { this.appendLines(); } // var $root = $(this.rootElement); // for ( var i = 0, len = ev.changed.length; i < len; i++) { // var changed = ev.changed[i]; // if (changed.props.fromY == null && changed.props.toY == null) { // return; // } // // var item = changed.target; // var $line = $root.find('#' // + h5format(LINE_ELM_ID_FORMAT, item.get('id'))); // $line.attr({ // y1: item.get('fromY'), // y2: item.get('toY') // }); // } }, getRectPos: function(item) { var sx = 0; var sy = 0; var ex = 0; var ey = 0; if (item.get('fromX') < item.get('toX')) { sx = item.get('fromX'); ex = item.get('toX'); } else { sx = item.get('toX'); ex = item.get('fromX'); } if (item.get('fromY') < item.get('toY')) { sy = item.get('fromY'); ey = item.get('toY'); } else { sy = item.get('toY'); ey = item.get('fromY'); } return { sx: sx, sy: sy, ex: ex, ey: ey }; }, _dataToRect: function(data) { return { id: data.get('id'), left: parseInt(data.get('fromX')), top: parseInt(data.get('fromY')), width: parseInt(data.get('toX') - data.get('fromX')), height: parseInt(data.get('toY') - data.get('fromY')) }; }, _appendHighLight: function() { } }); } function AxisRenderer(axesElm, chartSetting, axesSettings) { this.rootElement = axesElm; this.$horizLines = null; this.$vertLines = null; this.chartSetting = chartSetting; this.setAxesSetting(axesSettings); var that = this; function scaling(min, max) { var range; if (that.autoScale) { range = that.autoScale(min, max); } else { range = that.defaultAutoScale(min, max); } chartSetting.set(range); } scaling(chartSetting.get('minVal'), chartSetting.get('maxVal')); chartSetting.addEventListener('change', function(ev) { if (ev.props.minVal != null || ev.props.maxVal != null) { var minVal = ev.target.get('minVal'); var maxVal = ev.target.get('maxVal'); if (minVal === Infinity || maxVal === -Infinity) { return; } scaling(minVal, maxVal); } if (ev.props.rangeMin != null || ev.props.rangeMax != null) { // rangeが変更されたので、水平方向の補助線を引き直す that._drawHorizLines(); } }); } AxisRenderer.prototype = { defaultAutoScale: function(min, max) { return { rangeMin: min, rangeMax: max }; }, showAxisLabels: function(xLabelArray) { if (xLabelArray == null) { return; } this.$vertLines.children('.xLabel').remove(); if (this.xLabelArray !== xLabelArray) { this.xLabelArray = xLabelArray; var that = this; this.xLabelArray.addEventListener('changeBefore', function(ev) { var $xLabelTexts = that.$vertLines.children('.xLabel'); if ($xLabelTexts.length === 0) { return; } var value = ev.args[1].value; var index = ev.args[0]; var orgValue = this.get(index).value; if (ev.method !== 'set' || value === orgValue) { return; } var label = that._getXLabel(ev.args[1], index); graphicRenderer.text(label, $xLabelTexts.eq(index)); }); } var dx = this.chartSetting.get('dx'); var xInterval = (this.chartSetting.get('width') - dx) / this.chartSetting.get('vertLineNum'); var x = dx * 0.5; if (!graphicRenderer.isSvg) { x -= 10; } for (i = 0, len = this.xLabelArray.length; i < len; i++) { var label = this._getXLabel(this.xLabelArray.get(i), i); var height = this.chartSetting.get('height'); var textY = graphicRenderer.isSvg ? height + 11 : height + 5; graphicRenderer.appendTextElm(label, x, textY, null, { 'class': 'xLabel', 'text-anchor': 'middle' }, this.$vertLines); x += xInterval; } }, _getXLabel: function(xLabelObj, index) { return this._xLabelFormatter(xLabelObj.value, xLabelObj.item, index); }, drawGridLines: function() { this._drawHorizLines(); // 水平方向の補助線を引く this._drawVertLines(); }, // _appendVertLine: function(dataItem, chartItem, id, renderer) { // var $vertLines = this.$vertLines; // // if ((id + 1) % (this.chartSetting.get('dispDataSize') / // this.chartSetting.get('vertLineNum')) === 0) { // // TODO: idでなく時間によって線を表示するように変更する // var x = renderer.getXCoord(chartItem); // var text = renderer.getXVal(dataItem); // // graphicRenderer.appendLineElm(x, 0, x, this.chartSetting.get('height'), '#CCC', { // id: h5format(VERT_LINE_ELM_ID_FORMAT, id) // }, $vertLines); // // graphicRenderer.appendTextElm(text, x, this.chartSetting.get('height') + 10, null, { // 'text-anchor': 'middle', // 'font-size': 9, // id: h5format(X_LABEL_ELM_ID_FORMAT, id) // }, $vertLines); // } // /** * チャートの横の補助線を引く * * @memberOf AxisRenderer */ _drawHorizLines: function() { if (this.$horizLines == null) { this.$horizLines = $(graphicRenderer.createGroupElm({ id: 'horiz_lines' })); $(this.rootElement).prepend(this.$horizLines); } else { this.$horizLines.empty(); } // 指定した数だけ分割して、横のメモリを引く var horizLineNum = this.chartSetting.get('horizLineNum'); var rangeMax = this.chartSetting.get('rangeMax'); var rangeMin = this.chartSetting.get('rangeMin'); var width = this.chartSetting.get('width'); var yInterval = (rangeMax - rangeMin) / horizLineNum; for (var i = 0; i <= horizLineNum; i++) { var val = yInterval * i + rangeMin; var y = calcYPos(val, rangeMin, rangeMax, this.chartSetting.get('height')); // 目盛を付ける var textY = graphicRenderer.isSvg ? y + 2 : y - 7; graphicRenderer.appendTextElm(this._yLabelFormatter(val, i), -30, textY, null, { 'class': 'added', 'font-size': this._axesSettings.yaxis.fontSize }, this.$horizLines); if (val === rangeMin || val === rangeMax) { continue; } graphicRenderer.appendLineElm(0, y, width, y, '#ccc', { 'class': 'added' }, this.$horizLines); } }, /** * チャートの縦の補助線を引く * * @memberOf AxisRenderer */ _drawVertLines: function(renderer) { if (this.$vertLines == null) { this.$vertLines = $(graphicRenderer.createGroupElm({ id: 'vert_lines' })); } else { this.$vertLines.empty(); } var vertLineNum = this.chartSetting.get('vertLineNum'); if (vertLineNum === 0) { return; } if (renderer == null) { $(this.rootElement).prepend(this.$vertLines); var dx = this.chartSetting.get('dx'); var height = this.chartSetting.get('height'); var width = this.chartSetting.get('width') - dx; // 両脇にdx/2ずつ余白を取る var xInterval = width / vertLineNum; var x = dx * 0.5; for (var i = 0; i <= vertLineNum; i++) { graphicRenderer.appendLineElm(x, 0, x, height, '#CCC', null, this.$vertLines); x += xInterval; } return; } // rendererが指定されているとき // this.$movingGroups.append(this.$vertLines); // for ( var id in renderer.chartModel.items) { // var dataItem = renderer.dataSource.dataModel.get(id); // var chartItem = renderer.chartModel.get(id); // this._appendVertLine(dataItem, chartItem, parseInt(id), renderer); // } }, setAxesSetting: function(axesSettings) { this._axesSettings = axesSettings; this.chartSetting.set({ vertLineNum: !axesSettings.xaxis.off ? axesSettings.xaxis.lineNum + 1 : 0, horizLineNum: axesSettings.yaxis.lineNum }); this.autoScale = axesSettings.yaxis.autoScale || this.defaultAutoScale; this._xLabelFormatter = axesSettings.xaxis.formatter || this._xLabelDefaultFormatter; this._yLabelFormatter = axesSettings.yaxis.formatter || this._yLabelDefaultFormatter; }, _xLabelDefaultFormatter: function(value, data, index) { return value.toString(); }, _yLabelDefaultFormatter: function(value, index) { return value.toString(); } }; var chartSequense = 0; /** * 描画を行うコントローラ * * @class * @memberOf h5.ui.components.chart * @name ChartController */ chartController = { __name: 'h5.ui.components.chart.ChartController', chartSetting: null, _renderers: {}, _rendererQueue: [], axisRenderer: null, dataSourceManager: null, chartId: null, $chart: null, $movingGroups: null, isInitDraw: false, isFirstDraw: true, tooltip: {}, _addedCount: 0, __ready: function() { this.chartId = '__h5_chart' + chartSequense; chartSequense++; this.chartSetting = h5.core.data.createObservableItem(chartSettingsSchema); this.dataSourceManager = new DataSourceManager(this.chartSetting); this.chartSetting .addEventListener('change', this.own(this._chartSettingChangeListener)); }, _chartSettingChangeListener: function(ev) { if (this.isInitDraw) { return; } if (ev.props.translateX != null) { graphicRenderer.setTranslate(this.$seriesGroup, ev.props.translateX.newValue, 0); graphicRenderer.setTranslate(this.$tooltip, ev.props.translateX.newValue, 0); } if (ev.props.width != null || ev.props.height != null) { this._appendBorder(this.chartSetting.get('width'), this.chartSetting.get('height')); } if (ev.props.rangeMin || ev.props.rangeMax) { for ( var name in this._renderers) { this._renderers[name].updateYVal(); if (this.tooltip.id != null) { this.tooltip.renderer.showToolTip(this.tooltip.id, this.$tooltip); } } } }, /** * * チャートの初期表示を行う * * @memberOf h5.ui.components.chart.ChartController */ _initChart: function(firstChartRenderer) { this._appendBorder(); this._initAxis(firstChartRenderer); var rightId = firstChartRenderer.dataSource.sequence.current() - 1; var paddingRight = this.settings.chartSetting.paddingRight; if (paddingRight == null) { paddingRight = 0; } // TODO: translateXの計算は共通化すべき this.chartSetting.set('translateX', -this.chartSetting.get('dx') * (rightId + paddingRight - this.chartSetting.get('movedNum'))); }, _initAxis: function(firstChartRenderer) { if (this.axisRenderer == null) { var axesElm = graphicRenderer.createGroupElm({ id: 'axes' }); this.$stickingGroups.append(axesElm); this.axisRenderer = new AxisRenderer(axesElm, this.chartSetting, this.settings.axes); } else { this.axisRenderer.setAxesSetting(this.settings.axes); } this.axisRenderer.drawGridLines(); var xLabelArray = firstChartRenderer.getXLabelArray(); this.axisRenderer.showAxisLabels(xLabelArray); }, _appendBorder: function() { this.$borderGroup.empty(); var w = this.chartSetting.get('width'); var h = this.chartSetting.get('height'); graphicRenderer.appendLineElm(0, h, w, h, '#000', { id: 'xline' }, this.$borderGroup); graphicRenderer.appendLineElm(0, 0, 0, h, '#000', { id: 'yline' }, this.$borderGroup); graphicRenderer.appendLineElm(0, 0, w, 0, '#000', { id: 'x2line' }, this.$borderGroup); graphicRenderer.appendLineElm(w, 0, w, h, '#000', { id: 'y2line' }, this.$borderGroup); }, /** * @memberOf h5.ui.components.chart.ChartController */ _appendChartElement: function(props) { var w = props.width; var h = props.height; var xStart = Y_LABEL_WIDTH / 2; var yStart = 10; var $graphicRootElm = this.$find('#' + this.chartId); if ($graphicRootElm != null && $graphicRootElm.length !== 0) { $graphicRootElm.empty(); $graphicRootElm.attr('width', w + Y_LABEL_WIDTH); $graphicRootElm.attr('height', h + X_LABEL_HEIGHT); } else { $graphicRootElm = $(graphicRenderer.createGraphicRootElm({ width: w + Y_LABEL_WIDTH, height: h + X_LABEL_HEIGHT, id: this.chartId })); $(this.rootElement).append($graphicRootElm); } this.$chart = $(graphicRenderer.createGroupElm({ id: 'h5_chart', transform: 'translate(' + xStart + ', ' + yStart + ')' })); $graphicRootElm.append(this.$chart); this.$stickingGroups = $(graphicRenderer.createGroupElm({ id: 'stickingGroups', 'class': 'vml_absolute' })); this.$chart.append(this.$stickingGroups); this.$borderGroup = $(graphicRenderer.createGroupElm({ id: 'borderGroup' })); this.$stickingGroups.append(this.$borderGroup); this.$movingGroups = $(graphicRenderer.createGroupElm({ id: 'movingGroup', 'class': 'vml_absolute' })); // クリッピング if (graphicRenderer.isSvg) { var clipRect = graphicRenderer.createRectElm(0, 0, this.chartSetting.get('width'), this.chartSetting.get('height')); graphicRenderer.clip(this.$movingGroups, clipRect, 'moving_area_clip', $graphicRootElm); } else { this.$movingGroups.css('clip', 'rect(0px ' + this.chartSetting.get('width') + 'px ' + this.chartSetting.get('height') + 'px 0px)'); } this.$chart.append(this.$movingGroups); this.$tooltip = $(graphicRenderer.createGroupElm({ id: 'tooltip', 'font-family': 'Verdana' })); this.$movingGroups.append(this.$tooltip); }, draw: function(settings) { this.isInitDraw = true; // チャートのパラメータの設定 if (settings != null) { this.settings = settings; var minVal = +Infinity; var maxVal = -Infinity; var range = settings.seriesDefault.range; if (range) { if (range.minVal != null) { minVal = range.minVal; } if (range.maxVal != null) { maxVal = range.maxVal; } } // TODO: 定義し直し(ばらす?) this.chartSetting.set({ width: settings.chartSetting.width - Y_LABEL_WIDTH, height: settings.chartSetting.height - X_LABEL_HEIGHT, dispDataSize: settings.seriesDefault.dispDataSize, keepDataSize: settings.seriesDefault.keepDataSize, timeInterval: settings.timeInterval || 1, minVal: minVal, maxVal: maxVal, additionalLineColor: 'yellow' }); } if (this.isFirstDraw) { this._appendChartElement(this.chartSetting.get()); } this.$tooltip.empty(); // TODO: データ生成はイベントをあげるようにして、ここは同期的な書き方にしたほうがよいかもしれない this._createChartRenderes(this.settings).done(this.own(function() { this.isInitDraw = false; this._initChart(this._renderers[this.settings.series[0].name]); // チャート表示の初期化 this._drawChart();// チャート情報の計算 this.isFirstDraw = false; })); }, _createChartRenderes: function(settings) { if (this.$seriesGroup == null) { this.$seriesGroup = $(graphicRenderer.createGroupElm({ id: 'series_group' })); this.$movingGroups.prepend(this.$seriesGroup); } else { this.$seriesGroup.empty(); } // this._renderers = {}; return this._addSeriesWithAsync(settings.series); }, _createChartRenderer: function(g, dataSource, seriesOption) { var name = seriesOption.name; switch (seriesOption.type.toLowerCase()) { case 'ohlc': this._renderers[name] = createCandleStickChartRenderer(g, dataSource, this.chartSetting, seriesOption); break; case 'stacked_line': case 'line': this._renderers[name] = createLineChartRenderer(g, dataSource, this.chartSetting, seriesOption); break; default: break; } return this._renderers[name]; }, _getPreRenderer: function(currentRenderer) { var name = currentRenderer.name; var series = this.settings.series; for (var i = 0, len = series.length; i < len; i++) { if (name === series[i].name) { return this._renderers[series[i - 1].name]; } } return null; }, _drawByRenderer: function(renderer) { var preRenderer = this._getPreRenderer(renderer); var preChartModel = preRenderer.chartModel; renderer.draw(preChartModel); }, getSettings: function() { return this.settings; }, setChartSetting: function(chartSetting) { var w = chartSetting.width ? chartSetting.width - Y_LABEL_WIDTH : this.chartSetting .get('width'); var h = chartSetting.height ? chartSetting.height - X_LABEL_HEIGHT : this.chartSetting .get('height'); this.chartSetting.set({ width: w, height: h }); var firstRenderer = this._renderers[this.settings.series[0].name]; this._initChart(firstRenderer); // チャート表示の初期化 this._drawChart();// チャート情報の計算 }, _addSeriesWithAsync: function(series) { var promises = []; for (var i = 0, len = series.length; i < len; i++) { var seriesSettings = $.extend({}, this.settings.seriesDefault, series[i]); var g = graphicRenderer.createGroupElm({ id: SERIES_PREFIX + series[i].name }); if ($.inArray(series[i].type, STACKED_CHART_TYPES) === -1) { this.$seriesGroup.append(g); } else { this.$seriesGroup.prepend(g); } // this.$seriesGroup.prepend(g); var dataSource = this.dataSourceManager.createDataSource(seriesSettings); this._createChartRenderer(g, dataSource, seriesSettings); promises.push(dataSource.getData(seriesSettings, this.chartSetting .get('dispDataSize'), this.chartSetting.get('keepDataSize'))); } return $.when.apply($, promises); }, addSeries: function(series) { var thisSeries = this.settings.series; this._addSeriesWithAsync(series).done(this.own(function() { for (var i = 0, len = series.length; i < len; i++) { thisSeries.push(series[i]); var renderer = this._renderers[series[i].name]; if (this._rendererQueue.length === 0) { // 描画中のものがなければ描画を開始する。 this._drawByRenderer(renderer); } this._rendererQueue.push(renderer); } })); }, removeSeries: function(names) { var array = $.isArray(names) ? names : [names]; var seriesSettings = []; for (var i = 0, len = array.length; i < len; i++) { $(this._renderers[array[i]].rootElement).remove(); this.dataSourceManager.removeDataSource(array[i]); delete this._renderers[array[i]]; for (var j = 0, jLen = this.settings.series.length; j < jLen; j++) { if (this.settings.series[j].name === array[i]) { seriesSettings.push(this.settings.series.splice(j, 1)[0]); break; } } } // 再描画 this._drawChart(); return $.isArray(names) ? seriesSettings : seriesSettings[0]; }, _drawChart: function() { for ( var name in this._renderers) { this._renderers[name].draw(); } // this._startUpdate(settings); }, _startUpdate: function(settings) { if (this.interval != null) { clearInterval(this.interval); } if (settings.url != null) { this.interval = setInterval(this.own(function() { this._updateChart(settings); }), 1); } }, _updateChart: function(settings) { var that = this; this.chartLogic.getData(settings.url, true).done(function(data) { that.addData('', data); }); }, addData: function(data, commonData) { // if (this._addedCount >= REFRESH_SIZE) { // this.draw(); // メモリリーク回避のため、再描画する // this._addedCount = 0; // } var individualSeries = []; for (var i = 0, len = data.length; i < len; i++) { var name = data[i].name; individualSeries.push(name); // var series = this.settings.series; // for (var j=0, len=series.length; j<len; j++) { // if(series[j].name === name) { // series[j].data.push(data[i].data); // series[j].data.pop(); // break; // } // } this._renderers[name].addData(data[i].data); } var renderers = this._renderers; for ( var name in renderers) { if ($.inArray(name, individualSeries) !== -1) { continue; } renderers[name].addData(commonData); } // チャートを左にスライドする var translateX = this.chartSetting.get('translateX'); this.chartSetting.set('translateX', translateX - this.chartSetting.get('dx')); this._addedCount++; }, go: function(num) { var movedNum = this.chartSetting.get('movedNum'); var move = Math.min(movedNum, num); for ( var name in this._renderers) { var dataSource = this._renderers[name].dataSource; var rightEndId = dataSource.sequence.current() - movedNum; var leftEndId = rightEndId - this.chartSetting.get('dispDataSize'); for (var i = 0; i < move; i++) { var item = dataSource.dataModel.get(rightEndId + i); this._renderers[name].updateChart(item, leftEndId, false); } } var translateX = this.chartSetting.get('translateX'); this.chartSetting.set('translateX', translateX - this.chartSetting.get('dx') * move); this.chartSetting.set('movedNum', movedNum - move); return move; }, back: function(num) { var movedNum = this.chartSetting.get('movedNum'); for ( var name in this._renderers) { var dataSource = this._renderers[name].dataSource; var rightEndId = dataSource.sequence.current() - movedNum - 1; var leftEndId = rightEndId - this.chartSetting.get('dispDataSize'); for (var i = 0; i < num; i++) { var item = dataSource.dataModel.get(leftEndId - i); this._renderers[name].updateChart(item, rightEndId, true); } } var translateX = this.chartSetting.get('translateX'); this.chartSetting.set('translateX', translateX + this.chartSetting.get('dx') * num); this.chartSetting.set('movedNum', movedNum + num); return movedNum; }, setSeriesDefault: function(obj) { if (obj.dispDataSize == null && obj.keepDataSize) { return; } for ( var name in obj) { this.chartSetting.set(name, obj[name]); } if (this.chartSetting.get('keepDataSize') < this.chartSetting.get('dispDataSize')) { this.chartSetting.set('dispDataSize', this.chartSetting.get('keepDataSize')); } this.leftEndCandleStickId = Infinity; var firstRenderer = this._renderers[this.settings.series[0].name]; this.dataSourceManager.setRange(firstRenderer.dataSource.sequence.current()); this._initChart(firstRenderer); // チャート表示の初期化 this._drawChart();// チャート情報の計算 }, '#series_group finishDrawing': function() { this._rendererQueue.shift(); var renderer = this._rendererQueue[0]; if (renderer != null) { this._drawByRenderer(renderer); } }, '.chartElm mousemove': function(context, $el) { var seriesName = $el.parent().attr('id').slice(SERIES_PREFIX.length); var renderer = this._renderers[seriesName]; var type = renderer.seriesSetting.type; var tooltipId = renderer.getTargetId(context, type); if (tooltipId == null) { return; } this.tooltip.id = tooltipId; this.tooltip.renderer = renderer; renderer.showToolTip(tooltipId, this.$tooltip); }, '#movingGroup removeTooltip': function(context) { if (context.evArg == this.tooltip.id) { this.$tooltip.empty(); this.tooltip.id = null; this.tooltip.renderer = null; } }, '{rootElement} click': function() { this.$tooltip.empty(); } }; h5.core.expose(chartController); })(jQuery);
package cucumber.runtime.java.guice.integration; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; import javax.inject.Inject; import javax.inject.Provider; import java.util.ArrayList; import java.util.List; import static cucumber.runtime.java.guice.matcher.ElementsAreAllUniqueMatcher.elementsAreAllUnique; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.assertThat; public class UnScopedSteps { private static final List<UnScopedObject> OBJECTS = new ArrayList<UnScopedObject>(3); private final Provider<UnScopedObject> unScopedObjectProvider; @Inject public UnScopedSteps(Provider<UnScopedObject> unScopedObjectProvider) { this.unScopedObjectProvider = unScopedObjectProvider; } @Given("^an un-scoped instance has been provided in this scenario$") public void an_un_scoped_instance_has_been_provided_in_this_scenario() throws Throwable { OBJECTS.clear(); provide(); } @When("^another un-scoped instance is provided$") public void another_un_scoped_instance_is_provided() throws Throwable { provide(); } @Then("^all three provided instances are unique instances$") public void all_three_provided_instances_are_unique_instances() throws Throwable { assertThat("Expected test scenario to provide three objects.", OBJECTS.size(), equalTo(3)); assertThat(OBJECTS, elementsAreAllUnique()); } private void provide() { UnScopedObject unScopedObject = unScopedObjectProvider.get(); assertThat(unScopedObject, notNullValue()); OBJECTS.add(unScopedObject); } }
/* crypto/buffer/buffer.h */ /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) * All rights reserved. * * This package is an SSL implementation written * by Eric Young (eay@cryptsoft.com). * The implementation was written so as to conform with Netscapes SSL. * * This library is free for commercial and non-commercial use as long as * the following conditions are aheared to. The following conditions * apply to all code found in this distribution, be it the RC4, RSA, * lhash, DES, etc., code; not just the SSL code. The SSL documentation * included with this distribution is covered by the same copyright terms * except that the holder is Tim Hudson (tjh@cryptsoft.com). * * Copyright remains Eric Young's, and as such any Copyright notices in * the code are not to be removed. * If this package is used in a product, Eric Young should be given attribution * as the author of the parts of the library used. * This can be in the form of a textual message at program startup or * in documentation (online or textual) provided with the package. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * "This product includes cryptographic software written by * Eric Young (eay@cryptsoft.com)" * The word 'cryptographic' can be left out if the rouines from the library * being used are not cryptographic related :-). * 4. If you include any Windows specific code (or a derivative thereof) from * the apps directory (application code) you must include an acknowledgement: * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" * * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * The licence and distribution terms for any publically available version or * derivative of this code cannot be changed. i.e. this code cannot simply be * copied and put under another distribution licence * [including the GNU Public Licence.] */ #ifndef HEADER_BUFFER_H #define HEADER_BUFFER_H #include <openssl/ossl_typ.h> #ifdef __cplusplus extern "C" { #endif #include <stddef.h> #if !defined(NO_SYS_TYPES_H) #include <sys/types.h> #endif /* Already declared in ossl_typ.h */ /* typedef struct buf_mem_st BUF_MEM; */ struct buf_mem_st { size_t length; /* current number of bytes */ char *data; size_t max; /* size of buffer */ }; BUF_MEM *BUF_MEM_new(void); void BUF_MEM_free(BUF_MEM *a); int BUF_MEM_grow(BUF_MEM *str, size_t len); int BUF_MEM_grow_clean(BUF_MEM *str, size_t len); char * BUF_strdup(const char *str); char * BUF_strndup(const char *str, size_t siz); void * BUF_memdup(const void *data, size_t siz); void BUF_reverse(unsigned char *out, unsigned char *in, size_t siz); /* safe string functions */ size_t BUF_strlcpy(char *dst,const char *src,size_t siz); size_t BUF_strlcat(char *dst,const char *src,size_t siz); /* BEGIN ERROR CODES */ /* The following lines are auto generated by the script mkerr.pl. Any changes * made after this point may be overwritten when the script is next run. */ void ERR_load_BUF_strings(void); /* Error codes for the BUF functions. */ /* Function codes. */ #define BUF_F_BUF_MEMDUP 103 #define BUF_F_BUF_MEM_GROW 100 #define BUF_F_BUF_MEM_GROW_CLEAN 105 #define BUF_F_BUF_MEM_NEW 101 #define BUF_F_BUF_STRDUP 102 #define BUF_F_BUF_STRNDUP 104 /* Reason codes. */ #ifdef __cplusplus } #endif #endif
using System; using Newtonsoft.Json; using System.IO; namespace TrueCraft.Core { public class UserSettings { public static UserSettings Local { get; set; } public static string SettingsPath { get { return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".truecraft", "settings.json"); } } public bool AutoLogin { get; set; } public string Username { get; set; } public string Password { get; set; } public string LastIP { get; set; } public string SelectedTexturePack { get; set; } public FavoriteServer[] FavoriteServers { get; set; } public bool IsFullscreen { get; set; } public WindowResolution WindowResolution { get; set; } public UserSettings() { AutoLogin = false; Username = ""; Password = ""; LastIP = ""; SelectedTexturePack = TexturePack.Default.Name; FavoriteServers = new FavoriteServer[0]; IsFullscreen = false; WindowResolution = new WindowResolution() { Width = 1280, Height = 720 }; } public void Load() { if (File.Exists(SettingsPath)) JsonConvert.PopulateObject(File.ReadAllText(SettingsPath), this); } public void Save() { Directory.CreateDirectory(Path.GetDirectoryName(SettingsPath)); File.WriteAllText(SettingsPath, JsonConvert.SerializeObject(this, Formatting.Indented)); } } public class FavoriteServer { public string Name { get; set; } public string Address { get; set; } } public class WindowResolution { public static readonly WindowResolution[] Defaults = new WindowResolution[] { // (from Wikipedia/other) WindowResolution.FromString("800 x 600"), // SVGA WindowResolution.FromString("960 x 640"), // DVGA WindowResolution.FromString("1024 x 600"), // WSVGA WindowResolution.FromString("1024 x 768"), // XGA WindowResolution.FromString("1280 x 1024"), // SXGA WindowResolution.FromString("1600 x 1200"), // UXGA WindowResolution.FromString("1920 x 1080"), // big WindowResolution.FromString("1920 x 1200"), // really big WindowResolution.FromString("4096 x 2160"), // huge }; public static WindowResolution FromString(string str) { var tmp = str.Split('x'); return new WindowResolution() { Width = int.Parse(tmp[0].Trim()), Height = int.Parse(tmp[1].Trim()) }; } public int Width { get; set; } public int Height { get; set; } public override string ToString() { return string.Format("{0} x {1}", Width, Height); } } }
package org.wso2.carbon.identity.samples.oauth; public class AuthenticationToken { private String userId; private String tenantId; private String signature; // TenantId:=0&UserId:=1&Signature:=QHGYNr0phJclgJnNUhc+RodHqCk= public AuthenticationToken(String token) { if (token != null) { String[] tokens = token.split("&"); if (tokens != null && tokens.length > 2) { for (int i = 0; i < tokens.length; i++) { if (tokens[i] != null) { String[] intTokens = tokens[i].split(":="); if (intTokens.length>1){ if ("TenantId".equals(intTokens[0])){ this.tenantId=intTokens[1]; } if ("UserId".equals(intTokens[0])){ this.userId=intTokens[1]; } if ("Signature".equals(intTokens[0])){ this.signature=intTokens[1]; } } } } } } } public String getUserId() { return userId; } public String getTenantId() { return tenantId; } public String getSignature() { return signature; } }
// Copyright (c) 2017 Brian Barto // // This program is free software; you can redistribute it and/or modify it // under the terms of the MIT License. See LICENSE for more details. /* * MODULE DESCRIPTION * * The mainsocket module stores and provides access to the main socket * file descriptor, as an integer value. For the client, this is the * socket used to communicate with the server. For the server, this is * the socket used to listen for new connections. */ /* * Static Variables */ static int mainsocket; /* * Initialize the mainsocket static variable to NULL (zero). */ void mainsocket_init(void) { mainsocket = 0; } /* * Store the integer value for the main socket file descriptor. */ void mainsocket_set(int n) { mainsocket = n; } /* * Return the integer value for the main socket file descriptor. */ int mainsocket_get(void) { return mainsocket; }