code
stringlengths
4
1.01M
language
stringclasses
2 values
/* * Copyright 2017 Hewlett Packard Enterprise Development Company, L.P. * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. */ define([ 'underscore', 'jquery', 'find/idol/app/page/dashboard/widgets/updating-widget', 'find/idol/app/page/dashboard/update-tracker-model' ], function(_, $, UpdatingWidget, UpdateTrackerModel) { 'use strict'; const spies = jasmine.createSpyObj('spies', ['onComplete', 'onIncrement', 'onCancelled', 'doUpdate']); const TestUpdatingWidget = UpdatingWidget.extend(spies); describe('Updating Widget', function() { beforeEach(function() { jasmine.addMatchers({ toShowLoadingSpinner: function() { return { compare: function(actual) { const pass = !actual.$loadingSpinner.hasClass('hide'); return { pass: pass, message: 'Expected the view ' + (pass ? 'not ' : '') + 'to show a loading spinner' }; } } } }); this.widget = new TestUpdatingWidget({ name: 'Test Widget' }); this.widget.render(); this.updateDeferred = $.Deferred(); this.updateTrackerModel = new UpdateTrackerModel(); }); afterEach(function() { _.each(spies, function(spy) { spy.calls.reset(); }) }); describe('when the update is synchronous', function() { beforeEach(function() { this.widget.doUpdate.and.callFake(function(done) { done(); }); this.widget.update(this.updateTrackerModel); }); it('it should increment the model when the done callback is called', function() { expect(this.updateTrackerModel.get('count')).toBe(1); }); it('should call onIncrement when the count increases', function() { // count increased when the widget updated expect(this.widget.onIncrement.calls.count()).toBe(1); }); it('should call onComplete when the model is set to complete', function() { this.updateTrackerModel.set('complete', true); expect(this.widget.onComplete.calls.count()).toBe(1); }); it('should call onCancelled when the model is set to cancelled', function() { this.updateTrackerModel.set('cancelled', true); expect(this.widget.onCancelled.calls.count()).toBe(1); }); }); describe('when the update is asynchronous', function() { beforeEach(function() { // when a test resolves the deferred, call the done callback this.widget.doUpdate.and.callFake(function(done) { this.updateDeferred.done(done); }.bind(this)); }); describe('and the update is called', function() { beforeEach(function() { this.widget.update(this.updateTrackerModel); }); it('should show the loading spinner until the update completes', function() { expect(this.widget).toShowLoadingSpinner(); this.updateDeferred.resolve(); expect(this.widget).not.toShowLoadingSpinner(); }); it('should not increment the model until the update is complete', function() { expect(this.updateTrackerModel.get('count')).toBe(0); this.updateDeferred.resolve(); expect(this.updateTrackerModel.get('count')).toBe(1); }); it('should call onIncrement when the count increases', function() { this.updateTrackerModel.increment(); expect(this.widget.onIncrement.calls.count()).toBe(1); }); it('should call onComplete when the model is set to complete', function() { this.updateTrackerModel.set('complete', true); expect(this.widget.onComplete.calls.count()).toBe(1); }); it('should call onCancelled when the model is set to cancelled', function() { this.updateTrackerModel.set('cancelled', true); expect(this.widget.onCancelled.calls.count()).toBe(1); }); }); }) }); });
Java
import 'rxjs/add/operator/map'; import {Injectable} from '@angular/core'; import {Http, RequestMethod} from '@angular/http'; import {Observable} from 'rxjs/Observable'; import {Cube} from '../models/cube'; import 'rxjs/add/operator/mergeMap'; import {Algorithm} from '../models/analysis/algorithm'; import {Input, InputTypes} from '../models/analysis/input'; import {Output, OutputTypes} from '../models/analysis/output'; import {environment} from '../../environments/environment'; import {ExecutionConfiguration} from '../models/analysis/executionConfiguration'; import {Configuration} from 'jasmine-spec-reporter/built/configuration'; @Injectable() export class AlgorithmsService { private API_DAM_PATH: string = environment.DAMUrl ; constructor(private http: Http) { } getActualCompatibleAlgorithms(): Observable<Algorithm[]> { // console.log(JSON.stringify({time_series: AlgorithmsService.dummyTimeSeries().serialize(), descriptive_statistics: AlgorithmsService.dummyDescriptiveStatistics().serialize(), clustering: AlgorithmsService.dummyClustering().serialize()})); return this.http.get(`${environment.DAMUrl}/services/meta/all`) .map(res => { let algorithms = []; let response = res.json(); for (let key of Object.keys(response)){ let algorithm = new Algorithm().deserialize(response[key]); algorithms.push(algorithm); } return algorithms; }); } getActualCompatibleAlgorithm( algorithmName): Observable<Algorithm> { return this.http.get(`${environment.DAMUrl}/services/meta/${algorithmName}`) .map(res => { let response = res.json(); return new Algorithm().deserialize(response); }); } getTimeSeriesAlgorithm(): Observable<Algorithm> { let that = this; return this.getActualCompatibleAlgorithm('time_series'); } getDescriptiveStatisticsAlgorithm(): Observable<Algorithm> { return this.getActualCompatibleAlgorithm('descriptive_statistics'); } getClusteringAlgorithm(): Observable<Algorithm> { return this.getActualCompatibleAlgorithm('clustering'); } getOutlierDetectionAlgorithm(): Observable<Algorithm> { let that = this; return this.getActualCompatibleAlgorithm('outlier_detection'); /*return Observable.create(function (observer: any) { observer.next(AlgorithmsService.dummyOutlierDetection()); });*/ } getRuleMiningAlgorithm(): Observable<Algorithm> { let that = this; return this.getActualCompatibleAlgorithm('rule_mining'); /*return Observable.create(function (observer: any) { observer.next(AlgorithmsService.dummyOutlierDetection()); });*/ } getAlgorithm(name, cube: Cube): Observable<Algorithm> { switch (name) { case 'time_series': return this.getTimeSeriesAlgorithm(); case 'descriptive_statistics': return this.getDescriptiveStatisticsAlgorithm(); case 'clustering': return this.getClusteringAlgorithm(); case 'outlier_detection': return this.getOutlierDetectionAlgorithm(); case 'rule_mining': return this.getRuleMiningAlgorithm(); default: return this.http.get(`${this.API_DAM_PATH}/${name}`) .map(res => { let response = res.json(); return new Algorithm().deserialize(response); }); } } }
Java
--- title: Հիսուսը որպես ուսուցիչ date: 16/11/2020 --- Աստվածաշունչը բազմաթիվ եզրույթներ է օգտագործում Հիսուսին նկարագրելու համար։ Նա Աստծո Որդին է, Մեսիան, մարդու Որդին, Փրկիչը, Փրկագնողը, Տերը, Աստծո Գառը, և սրանք դեռ մի քանիսն են։ Սակայն այն մարդկանց համար, ովքեր Նրան շատ ավելի մոտիկից էին ճանաչում Հուդայում և Գալիլեայում Նրա՝ երեքից ավելի տևած հանրային ծառայության տարիներին, Նա ուսուցիչ էր։ Նրանք Նրան անվանում էին «Վարդապետ» կամ «Ռաբբի»։ Երկուսն էլ նույն նշանակությունն ունեն՝ «Ուսուցիչ»։ Ուստի ուսուցչի մասնագիտությունը և ուսուցման գործը պիտի որ հատկապես հարմար միջոց եղած լինեին Հիսուսի համար՝ իրականացնելու Իր հանրային ծառայությունը։ Նրա փրկագնման գործն ինչ-որ կերպ մոտ է ուսուցման գործին։ Ավելին, այն կանխագուշակվել է Ավետարանի մարգարեի կողմից։ `Կարդացե՛ք Եսայի 11.1–9 համարները։ Ի՞նչ են դրանք բացահայտում Հիսուսի ուսուցման դերի մասին։` Սուրբ Գրքի ամենացնցող մեսիական մարգարեություններից մեկը զետեղված է Եսայի մարգարեության 11-րդ գլխում։ 1–3-րդ համարները Մեսիայի գալուստը նկարագրում են կրթական եզրույթներով, ի մասնավորի՝ որպես մեկը, ով բերում է գիտելիք, խորհուրդ, իմաստություն և հանճար։ Ողջ հատվածը եզրափակվում է հետևյալ ուշագրավ խոստմամբ. «Տիրոջ գիտությունը պիտի լցնի երկիրը, ինչպես ջրերը, որոնք ծածկում են ծովը» (Եսայի 11.9): Գուցե և Սուրբ Գրքի նման դասերն են ոգեշնչել Էլեն Ուայթին կրթության մասին իր գրքում նշել, որ կրթության և փրկագնման գործերը մեկ են (տե՛ս Դաստիարակություն, էջ 30)։ Կարդացե՛ք Հովհաննես 3.1–3 համարները: Նիկոդեմոսը Հիսուսին դիմում է որպես ռաբբի, իսկ հետագայում, Հիսուսի արած նշաններից (հատկապես Նրա հրաշքները և կյանքի իմաստի ընկալումը) ելնելով՝ Հիսուսի ուսուցման պարգևը որակեց որպես Աստծուց եկող։ Հիսուսն ընդունեց, եթե ոչ Իրեն շնորհված տիտղոսը, ապա հաստատապես Իր ուսուցման պարգևի սկզբնաղբյուրի մասին միտքը, երբ պատասխանեց Նիկոդեմոսին, որ վերջինս պետք է վերստին ծնվի, որպեսզի տեսնի (և՛ հասկանա, և՛ մտնի) Աստծո արքայությունը։ Սա նշանակում է, որ ուրիշներին սովորեցնելու իշխանությունը, նույնիսկ Հիսուսի դեպքում, գալիս է Աստծուց։ Իսկապես որ ուսուցանումն Աստծո պարգևն է։ Այն հանձնարարել է Աստված, որդեգրվել Հիսուսի կողմից և ճանաչվել աստվածային հեղինակություն ունեցող նրանց կողմից, ովքեր ուսուցանվում են։ `Ի՞նչ դեր մենք ունենք Տիրոջ գիտությունն ամբողջ աշխարհում տարածվելու մասին այս մարգարեության իրականացման մեջ։`
Java
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>basic_io_object::operator=</title> <link rel="stylesheet" href="../../../../../doc/src/boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.79.1"> <link rel="home" href="../../../boost_asio.html" title="Boost.Asio"> <link rel="up" href="../basic_io_object.html" title="basic_io_object"> <link rel="prev" href="implementation_type.html" title="basic_io_object::implementation_type"> <link rel="next" href="service_type.html" title="basic_io_object::service_type"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../boost.png"></td> <td align="center"><a href="../../../../../index.html">Home</a></td> <td align="center"><a href="../../../../../libs/libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../../../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="implementation_type.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../basic_io_object.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../boost_asio.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="service_type.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="section"> <div class="titlepage"><div><div><h4 class="title"> <a name="boost_asio.reference.basic_io_object.operator_eq_"></a><a class="link" href="operator_eq_.html" title="basic_io_object::operator=">basic_io_object::operator=</a> </h4></div></div></div> <p> <a class="indexterm" name="boost_asio.indexterm.basic_io_object.operator_eq_"></a> Move-assign a <a class="link" href="../basic_io_object.html" title="basic_io_object"><code class="computeroutput">basic_io_object</code></a>. </p> <pre class="programlisting">basic_io_object &amp; operator=( basic_io_object &amp;&amp; other); </pre> <p> Performs: </p> <pre class="programlisting">get_service().move_assign(get_implementation(), other.get_service(), other.get_implementation()); </pre> <h6> <a name="boost_asio.reference.basic_io_object.operator_eq_.h0"></a> <span class="phrase"><a name="boost_asio.reference.basic_io_object.operator_eq_.remarks"></a></span><a class="link" href="operator_eq_.html#boost_asio.reference.basic_io_object.operator_eq_.remarks">Remarks</a> </h6> <p> Available only for services that support movability, </p> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright © 2003-2021 Christopher M. Kohlhoff<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>) </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="implementation_type.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../basic_io_object.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../boost_asio.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="service_type.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
Java
<?php namespace Nathanmac\Utilities\Parser\Formats; use Nathanmac\Utilities\Parser\Exceptions\ParserException; /** * XML Formatter * * @package Nathanmac\Utilities\Parser\Formats * @author Nathan Macnamara <nathan.macnamara@outlook.com> * @license https://github.com/nathanmac/Parser/blob/master/LICENSE.md MIT */ class XML implements FormatInterface { /** * Parse Payload Data * * @param string $payload * * @throws ParserException * @return array * */ public function parse($payload) { if ($payload) { try { $xml = simplexml_load_string($payload, 'SimpleXMLElement', LIBXML_NOCDATA); $ns = ['' => null] + $xml->getDocNamespaces(true); return $this->recursive_parse($xml, $ns); } catch (\Exception $ex) { throw new ParserException('Failed To Parse XML'); } } return []; } protected function recursive_parse($xml, $ns) { $xml_string = (string)$xml; if ($xml->count() == 0 and $xml_string != '') { if (count($xml->attributes()) == 0) { if (trim($xml_string) == '') { $result = null; } else { $result = $xml_string; } } else { $result = array('#text' => $xml_string); } } else { $result = null; } foreach ($ns as $nsName => $nsUri) { foreach ($xml->attributes($nsUri) as $attName => $attValue) { if (!empty($nsName)) { $attName = "{$nsName}:{$attName}"; } $result["@{$attName}"] = (string)$attValue; } foreach ($xml->children($nsUri) as $childName => $child) { if (!empty($nsName)) { $childName = "{$nsName}:{$childName}"; } $child = $this->recursive_parse($child, $ns); if (is_array($result) and array_key_exists($childName, $result)) { if (is_array($result[$childName]) and is_numeric(key($result[$childName]))) { $result[$childName][] = $child; } else { $temp = $result[$childName]; $result[$childName] = [$temp, $child]; } } else { $result[$childName] = $child; } } } return $result; } }
Java
import PropTypes from 'prop-types' import React from 'react' import { List } from 'immutable' import Modal from './warningmodal.js' import Path from 'path' const FilesList = ({ folders, folderPathToRemove, actions }) => { const addStorageLocation = () => actions.addFolderAskPathSize() const removeStorageLocation = folder => () => { actions.removeFolder(folder) actions.updateFolderToRemove() } const onResizeStorageLocationClick = folder => () => actions.resizeFolder(folder) const onRemoveStorageLocationClick = folder => () => actions.updateFolderToRemove(folder.get('path')) const hideRemoveStorageModal = () => actions.updateFolderToRemove() // sort folders by their name const sortedFolders = folders.sortBy(folder => folder.get('path')) const FileList = sortedFolders.map((folder, key) => ( <div className='property pure-g' key={key}> <div className='pure-u-3-4'> <div className='name'>{folder.get('path')}</div> </div> <div className='pure-u-1-12'> <div>{Math.floor(folder.get('free')).toString()} GB</div> </div> <div className='pure-u-1-12'> <div>{Math.floor(folder.get('size')).toString()} GB</div> </div> <div className='pure-u-1-24' onClick={onResizeStorageLocationClick(folder)} > <div> <i className='fa fa-edit button' /> </div> </div> <div className='pure-u-1-24' onClick={onRemoveStorageLocationClick(folder)} > <div> <i className='fa fa-remove button' /> </div> </div> {folderPathToRemove && folderPathToRemove === folder.get('path') ? ( <Modal title={`Remove "${Path.basename(folder.get('path'))}"?`} message='No longer use this folder for storage? You may lose collateral if you do not have enough space to fill all contracts.' actions={{ acceptModal: removeStorageLocation(folder), declineModal: hideRemoveStorageModal }} /> ) : null} </div> )) return ( <div className='files section'> <div className='property row'> <div className='title' /> <div className='controls full'> <div className='button left' id='edit' onClick={addStorageLocation}> <i className='fa fa-folder-open' /> Add Storage Folder </div> <div className='pure-u-1-12' style={{ textAlign: 'left' }}> Free </div> <div className='pure-u-1-12' style={{ textAlign: 'left' }}> Max </div> <div className='pure-u-1-12' /> </div> </div> {FileList} </div> ) } FilesList.propTypes = { folderPathToRemove: PropTypes.string, folders: PropTypes.instanceOf(List).isRequired } export default FilesList
Java
<?php return unserialize('a:2:{i:0;O:30:"Doctrine\\ORM\\Mapping\\ManyToOne":4:{s:12:"targetEntity";s:5:"Cargo";s:7:"cascade";N;s:5:"fetch";s:4:"LAZY";s:10:"inversedBy";N;}i:1;O:32:"Doctrine\\ORM\\Mapping\\JoinColumns":1:{s:5:"value";a:1:{i:0;O:31:"Doctrine\\ORM\\Mapping\\JoinColumn":7:{s:4:"name";s:8:"CARGO_PK";s:20:"referencedColumnName";s:8:"CARGO_PK";s:6:"unique";b:0;s:8:"nullable";b:0;s:8:"onDelete";N;s:16:"columnDefinition";N;s:9:"fieldName";N;}}}}');
Java
from PyQt4 import QtCore import acq4.Manager import acq4.util.imageAnalysis as imageAnalysis run = True man = acq4.Manager.getManager() cam = man.getDevice('Camera') frames = [] def collect(frame): global frames frames.append(frame) cam.sigNewFrame.connect(collect) def measure(): if len(frames) == 0: QtCore.QTimer.singleShot(100, measure) return global run if run: global frames frame = frames[-1] frames = [] img = frame.data() w,h = img.shape img = img[2*w/5:3*w/5, 2*h/5:3*h/5] w,h = img.shape fit = imageAnalysis.fitGaussian2D(img, [100, w/2., h/2., w/4., 0]) # convert sigma to full width at 1/e fit[0][3] *= 2 * 2**0.5 print "WIDTH:", fit[0][3] * frame.info()['pixelSize'][0] * 1e6, "um" print " fit:", fit else: global frames frames = [] QtCore.QTimer.singleShot(2000, measure) measure()
Java
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en_US" lang="en_US"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Qt 4.8: calculator.pro Example File (demos/declarative/calculator/calculator.pro)</title> <link rel="stylesheet" type="text/css" href="style/style.css" /> <script src="scripts/jquery.js" type="text/javascript"></script> <script src="scripts/functions.js" type="text/javascript"></script> <link rel="stylesheet" type="text/css" href="style/superfish.css" /> <link rel="stylesheet" type="text/css" href="style/narrow.css" /> <!--[if IE]> <meta name="MSSmartTagsPreventParsing" content="true"> <meta http-equiv="imagetoolbar" content="no"> <![endif]--> <!--[if lt IE 7]> <link rel="stylesheet" type="text/css" href="style/style_ie6.css"> <![endif]--> <!--[if IE 7]> <link rel="stylesheet" type="text/css" href="style/style_ie7.css"> <![endif]--> <!--[if IE 8]> <link rel="stylesheet" type="text/css" href="style/style_ie8.css"> <![endif]--> <script src="scripts/superfish.js" type="text/javascript"></script> <script src="scripts/narrow.js" type="text/javascript"></script> </head> <body class="" onload="CheckEmptyAndLoadList();"> <div class="header" id="qtdocheader"> <div class="content"> <div id="nav-logo"> <a href="index.html">Home</a></div> <a href="index.html" class="qtref"><span>Qt Reference Documentation</span></a> <div id="narrowsearch"></div> <div id="nav-topright"> <ul> <li class="nav-topright-home"><a href="http://qt.digia.com/">Qt HOME</a></li> <li class="nav-topright-dev"><a href="http://qt-project.org/">DEV</a></li> <li class="nav-topright-doc nav-topright-doc-active"><a href="http://qt-project.org/doc/"> DOC</a></li> <li class="nav-topright-blog"><a href="http://blog.qt.digia.com/">BLOG</a></li> </ul> </div> <div id="shortCut"> <ul> <li class="shortCut-topleft-inactive"><span><a href="index.html">Qt 4.8</a></span></li> <li class="shortCut-topleft-active"><a href="http://qt-project.org/doc/">ALL VERSIONS </a></li> </ul> </div> <ul class="sf-menu" id="narrowmenu"> <li><a href="#">API Lookup</a> <ul> <li><a href="classes.html">Class index</a></li> <li><a href="functions.html">Function index</a></li> <li><a href="modules.html">Modules</a></li> <li><a href="namespaces.html">Namespaces</a></li> <li><a href="qtglobal.html">Global Declarations</a></li> <li><a href="qdeclarativeelements.html">QML elements</a></li> </ul> </li> <li><a href="#">Qt Topics</a> <ul> <li><a href="qt-basic-concepts.html">Programming with Qt</a></li> <li><a href="qtquick.html">Device UIs &amp; Qt Quick</a></li> <li><a href="qt-gui-concepts.html">UI Design with Qt</a></li> <li><a href="supported-platforms.html">Supported Platforms</a></li> <li><a href="technology-apis.html">Qt and Key Technologies</a></li> <li><a href="best-practices.html">How-To's and Best Practices</a></li> </ul> </li> <li><a href="#">Examples</a> <ul> <li><a href="all-examples.html">Examples</a></li> <li><a href="tutorials.html">Tutorials</a></li> <li><a href="demos.html">Demos</a></li> <li><a href="qdeclarativeexamples.html">QML Examples</a></li> </ul> </li> </ul> </div> </div> <div class="wrapper"> <div class="hd"> <span></span> </div> <div class="bd group"> <div class="sidebar"> <div class="searchlabel"> Search index:</div> <div class="search" id="sidebarsearch"> <form id="qtdocsearch" action="" onsubmit="return false;"> <fieldset> <input type="text" name="searchstring" id="pageType" value="" /> <div id="resultdialog"> <a href="#" id="resultclose">Close</a> <p id="resultlinks" class="all"><a href="#" id="showallresults">All</a> | <a href="#" id="showapiresults">API</a> | <a href="#" id="showarticleresults">Articles</a> | <a href="#" id="showexampleresults">Examples</a></p> <p id="searchcount" class="all"><span id="resultcount"></span><span id="apicount"></span><span id="articlecount"></span><span id="examplecount"></span>&nbsp;results:</p> <ul id="resultlist" class="all"> </ul> </div> </fieldset> </form> </div> <div class="box first bottombar" id="lookup"> <h2 title="API Lookup"><span></span> API Lookup</h2> <div id="list001" class="list"> <ul id="ul001" > <li class="defaultLink"><a href="classes.html">Class index</a></li> <li class="defaultLink"><a href="functions.html">Function index</a></li> <li class="defaultLink"><a href="modules.html">Modules</a></li> <li class="defaultLink"><a href="namespaces.html">Namespaces</a></li> <li class="defaultLink"><a href="qtglobal.html">Global Declarations</a></li> <li class="defaultLink"><a href="qdeclarativeelements.html">QML elements</a></li> </ul> </div> </div> <div class="box bottombar" id="topics"> <h2 title="Qt Topics"><span></span> Qt Topics</h2> <div id="list002" class="list"> <ul id="ul002" > <li class="defaultLink"><a href="qt-basic-concepts.html">Programming with Qt</a></li> <li class="defaultLink"><a href="qtquick.html">Device UIs &amp; Qt Quick</a></li> <li class="defaultLink"><a href="qt-gui-concepts.html">UI Design with Qt</a></li> <li class="defaultLink"><a href="supported-platforms.html">Supported Platforms</a></li> <li class="defaultLink"><a href="technology-apis.html">Qt and Key Technologies</a></li> <li class="defaultLink"><a href="best-practices.html">How-To's and Best Practices</a></li> </ul> </div> </div> <div class="box" id="examples"> <h2 title="Examples"><span></span> Examples</h2> <div id="list003" class="list"> <ul id="ul003"> <li class="defaultLink"><a href="all-examples.html">Examples</a></li> <li class="defaultLink"><a href="tutorials.html">Tutorials</a></li> <li class="defaultLink"><a href="demos.html">Demos</a></li> <li class="defaultLink"><a href="qdeclarativeexamples.html">QML Examples</a></li> </ul> </div> </div> </div> <div class="wrap"> <div class="toolbar"> <div class="breadcrumb toolblock"> <ul> <li class="first"><a href="index.html">Home</a></li> <!-- Breadcrumbs go here --> </ul> </div> <div class="toolbuttons toolblock"> <ul> <li id="smallA" class="t_button">A</li> <li id="medA" class="t_button active">A</li> <li id="bigA" class="t_button">A</li> <li id="print" class="t_button"><a href="javascript:this.print();"> <span>Print</span></a></li> </ul> </div> </div> <div class="content mainContent"> <h1 class="title">calculator.pro Example File</h1> <span class="small-subtitle">demos/declarative/calculator/calculator.pro</span> <!-- $$$demos/declarative/calculator/calculator.pro-description --> <div class="descr"> <a name="details"></a> <pre class="cpp"> # Add more folders to ship with the application, here folder_01.source = qml/calculator folder_01.target = qml DEPLOYMENTFOLDERS = folder_01 # Additional import path used to resolve QML modules in Creator's code model QML_IMPORT_PATH = symbian:TARGET.UID3 = 0xE8BEAB39 # Smart Installer package's UID # This UID is from the protected range and therefore the package will # fail to install if self-signed. By default qmake uses the unprotected # range value if unprotected UID is defined for the application and # 0x2002CCCF value if protected UID is given to the application #symbian:DEPLOYMENT.installer_header = 0x2002CCCF # Allow network access on Symbian symbian:TARGET.CAPABILITY += NetworkServices # If your application uses the Qt Mobility libraries, uncomment the following # lines and add the respective components to the MOBILITY variable. # CONFIG += mobility # MOBILITY += # Speed up launching on MeeGo/Harmattan when using applauncherd daemon # CONFIG += qdeclarative-boostable # Add dependency to Symbian components # CONFIG += qt-components # The .cpp file which was generated for your project. Feel free to hack it. SOURCES += main.cpp # Please do not modify the following two lines. Required for deployment. desktopInstallPrefix=$$[QT_INSTALL_DEMOS]/declarative/calculator exists(qmlapplicationviewer/qmlapplicationviewer.pri):include(qmlapplicationviewer/qmlapplicationviewer.pri) else:include(../../helper/qmlapplicationviewer/qmlapplicationviewer.pri) qtcAddDeployment()</pre> </div> <!-- @@@demos/declarative/calculator/calculator.pro --> </div> </div> </div> <div class="ft"> <span></span> </div> </div> <div class="footer"> <p> <acronym title="Copyright">&copy;</acronym> 2013 Digia Plc and/or its subsidiaries. Documentation contributions included herein are the copyrights of their respective owners.</p> <br /> <p> The documentation provided herein is licensed under the terms of the <a href="http://www.gnu.org/licenses/fdl.html">GNU Free Documentation License version 1.3</a> as published by the Free Software Foundation.</p> <p> Documentation sources may be obtained from <a href="http://www.qt-project.org"> www.qt-project.org</a>.</p> <br /> <p> Digia, Qt and their respective logos are trademarks of Digia Plc in Finland and/or other countries worldwide. All other trademarks are property of their respective owners. <a title="Privacy Policy" href="http://en.gitorious.org/privacy_policy/">Privacy Policy</a></p> </div> <script src="scripts/functions.js" type="text/javascript"></script> </body> </html>
Java
<!doctype html> <html lang="en"> <head> <title>Code coverage report for ol/interaction/dragboxinteraction.js</title> <meta charset="utf-8" /> <link rel="stylesheet" href="../../prettify.css" /> <link rel="stylesheet" href="../../base.css" /> <meta name="viewport" content="width=device-width, initial-scale=1"> <style type='text/css'> .coverage-summary .sorter { background-image: url(../../sort-arrow-sprite.png); } </style> </head> <body> <div class='wrapper'> <div class='pad1'> <h1> <a href="../../index.html">all files</a> / <a href="index.html">ol/interaction/</a> dragboxinteraction.js </h1> <div class='clearfix'> <div class='fl pad1y space-right2'> <span class="strong">55.1% </span> <span class="quiet">Statements</span> <span class='fraction'>27/49</span> </div> <div class='fl pad1y space-right2'> <span class="strong">22.22% </span> <span class="quiet">Branches</span> <span class='fraction'>4/18</span> </div> <div class='fl pad1y space-right2'> <span class="strong">50% </span> <span class="quiet">Functions</span> <span class='fraction'>3/6</span> </div> <div class='fl pad1y space-right2'> <span class="strong">55.1% </span> <span class="quiet">Lines</span> <span class='fraction'>27/49</span> </div> </div> </div> <div class='status-line medium'></div> <pre><table class="coverage"> <tr><td class="line-count quiet">1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201</td><td class="line-coverage quiet"><span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1×</span> <span class="cline-any cline-yes">1×</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1×</span> <span class="cline-any cline-yes">1×</span> <span class="cline-any cline-yes">1×</span> <span class="cline-any cline-yes">1×</span> <span class="cline-any cline-yes">1×</span> <span class="cline-any cline-yes">1×</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1×</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1×</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1×</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1×</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1×</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">118×</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">118×</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">118×</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">118×</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">118×</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1×</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1×</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1×</span> <span class="cline-any cline-yes">1×</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1×</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1×</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1×</span> <span class="cline-any cline-yes">60×</span> <span class="cline-any cline-yes">60×</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span></td><td class="text"><pre class="prettyprint lang-js">// FIXME draw drag box goog.provide('ol.DragBoxEvent'); goog.provide('ol.interaction.DragBox'); &nbsp; goog.require('goog.events.Event'); goog.require('ol'); goog.require('ol.events.ConditionType'); goog.require('ol.events.condition'); goog.require('ol.interaction.Pointer'); goog.require('ol.render.Box'); &nbsp; &nbsp; /** * @const * @type {number} */ ol.DRAG_BOX_HYSTERESIS_PIXELS_SQUARED = ol.DRAG_BOX_HYSTERESIS_PIXELS * ol.DRAG_BOX_HYSTERESIS_PIXELS; &nbsp; &nbsp; /** * @enum {string} */ ol.DragBoxEventType = { /** * Triggered upon drag box start. * @event ol.DragBoxEvent#boxstart * @api stable */ BOXSTART: 'boxstart', /** * Triggered upon drag box end. * @event ol.DragBoxEvent#boxend * @api stable */ BOXEND: 'boxend' }; &nbsp; &nbsp; &nbsp; /** * @classdesc * Events emitted by {@link ol.interaction.DragBox} instances are instances of * this type. * * @param {string} type The event type. * @param {ol.Coordinate} coordinate The event coordinate. * @extends {goog.events.Event} * @constructor * @implements {oli.DragBoxEvent} */ ol.DragBoxEvent = <span class="fstat-no" title="function not covered" >function(type, coordinate) {</span> <span class="cstat-no" title="statement not covered" > goog.base(this, type);</span> &nbsp; /** * The coordinate of the drag event. * @const * @type {ol.Coordinate} * @api stable */ <span class="cstat-no" title="statement not covered" > this.coordinate = coordinate;</span> &nbsp; }; goog.inherits(ol.DragBoxEvent, goog.events.Event); &nbsp; &nbsp; &nbsp; /** * @classdesc * Allows the user to draw a vector box by clicking and dragging on the map, * normally combined with an {@link ol.events.condition} that limits * it to when the shift or other key is held down. This is used, for example, * for zooming to a specific area of the map * (see {@link ol.interaction.DragZoom} and * {@link ol.interaction.DragRotateAndZoom}). * * This interaction is only supported for mouse devices. * * @constructor * @extends {ol.interaction.Pointer} * @fires ol.DragBoxEvent * @param {olx.interaction.DragBoxOptions=} opt_options Options. * @api stable */ ol.interaction.DragBox = function(opt_options) { &nbsp; goog.base(this, { handleDownEvent: ol.interaction.DragBox.handleDownEvent_, handleDragEvent: ol.interaction.DragBox.handleDragEvent_, handleUpEvent: ol.interaction.DragBox.handleUpEvent_ }); &nbsp; var options = opt_options ? opt_options : <span class="branch-1 cbranch-no" title="branch not covered" >{};</span> &nbsp; /** * @type {ol.render.Box} * @private */ this.box_ = new ol.render.Box(options.className || <span class="branch-1 cbranch-no" title="branch not covered" >'ol-dragbox')</span>; &nbsp; /** * @type {ol.Pixel} * @private */ this.startPixel_ = null; &nbsp; /** * @private * @type {ol.events.ConditionType} */ this.condition_ = options.condition ? options.condition : <span class="branch-1 cbranch-no" title="branch not covered" >ol.events.condition.always;</span> &nbsp; }; goog.inherits(ol.interaction.DragBox, ol.interaction.Pointer); &nbsp; &nbsp; /** * @param {ol.MapBrowserPointerEvent} mapBrowserEvent Event. * @this {ol.interaction.DragBox} * @private */ ol.interaction.DragBox.handleDragEvent_ = <span class="fstat-no" title="function not covered" >function(mapBrowserEvent) {</span> <span class="cstat-no" title="statement not covered" > if (!ol.events.condition.mouseOnly(mapBrowserEvent)) {</span> <span class="cstat-no" title="statement not covered" > return;</span> } &nbsp; <span class="cstat-no" title="statement not covered" > this.box_.setPixels(this.startPixel_, mapBrowserEvent.pixel);</span> }; &nbsp; &nbsp; /** * Returns geometry of last drawn box. * @return {ol.geom.Polygon} Geometry. * @api stable */ ol.interaction.DragBox.prototype.getGeometry = function() { return this.box_.getGeometry(); }; &nbsp; &nbsp; /** * To be overriden by child classes. * FIXME: use constructor option instead of relying on overridding. * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. * @protected */ ol.interaction.DragBox.prototype.onBoxEnd = ol.nullFunction; &nbsp; &nbsp; /** * @param {ol.MapBrowserPointerEvent} mapBrowserEvent Event. * @return {boolean} Stop drag sequence? * @this {ol.interaction.DragBox} * @private */ ol.interaction.DragBox.handleUpEvent_ = <span class="fstat-no" title="function not covered" >function(mapBrowserEvent) {</span> <span class="cstat-no" title="statement not covered" > if (!ol.events.condition.mouseOnly(mapBrowserEvent)) {</span> <span class="cstat-no" title="statement not covered" > return true;</span> } &nbsp; <span class="cstat-no" title="statement not covered" > this.box_.setMap(null);</span> &nbsp; <span class="cstat-no" title="statement not covered" > var deltaX = mapBrowserEvent.pixel[0] - this.startPixel_[0];</span> <span class="cstat-no" title="statement not covered" > var deltaY = mapBrowserEvent.pixel[1] - this.startPixel_[1];</span> &nbsp; <span class="cstat-no" title="statement not covered" > if (deltaX * deltaX + deltaY * deltaY &gt;=</span> ol.DRAG_BOX_HYSTERESIS_PIXELS_SQUARED) { <span class="cstat-no" title="statement not covered" > this.onBoxEnd(mapBrowserEvent);</span> <span class="cstat-no" title="statement not covered" > this.dispatchEvent(new ol.DragBoxEvent(ol.DragBoxEventType.BOXEND,</span> mapBrowserEvent.coordinate)); } <span class="cstat-no" title="statement not covered" > return false;</span> }; &nbsp; &nbsp; /** * @param {ol.MapBrowserPointerEvent} mapBrowserEvent Event. * @return {boolean} Start drag sequence? * @this {ol.interaction.DragBox} * @private */ ol.interaction.DragBox.handleDownEvent_ = function(mapBrowserEvent) { <span class="missing-if-branch" title="else path not taken" >E</span>if (!ol.events.condition.mouseOnly(mapBrowserEvent)) { return false; } &nbsp; <span class="cstat-no" title="statement not covered" > var browserEvent = mapBrowserEvent.browserEvent;</span> <span class="cstat-no" title="statement not covered" > if (browserEvent.isMouseActionButton() &amp;&amp; this.condition_(mapBrowserEvent)) {</span> <span class="cstat-no" title="statement not covered" > this.startPixel_ = mapBrowserEvent.pixel;</span> <span class="cstat-no" title="statement not covered" > this.box_.setMap(mapBrowserEvent.map);</span> <span class="cstat-no" title="statement not covered" > this.box_.setPixels(this.startPixel_, this.startPixel_);</span> <span class="cstat-no" title="statement not covered" > this.dispatchEvent(new ol.DragBoxEvent(ol.DragBoxEventType.BOXSTART,</span> mapBrowserEvent.coordinate)); <span class="cstat-no" title="statement not covered" > return true;</span> } else { <span class="cstat-no" title="statement not covered" > return false;</span> } }; &nbsp;</pre></td></tr> </table></pre> <div class='push'></div><!-- for sticky footer --> </div><!-- /wrapper --> <div class='footer quiet pad2 space-top1 center small'> Code coverage generated by <a href="http://istanbul-js.org/" target="_blank">istanbul</a> at Fri Nov 06 2015 19:36:11 GMT+0100 (CET) </div> </div> <script src="../../prettify.js"></script> <script> window.onload = function () { if (typeof prettyPrint === 'function') { prettyPrint(); } }; </script> <script src="../../sorter.js"></script> </body> </html>
Java
import {browser, by, element, ExpectedConditions} from 'protractor'; import { ProjectsPage } from './projects.page'; export class BellowsProjectSettingsPage { private readonly projectsPage = new ProjectsPage(); conditionTimeout: number = 3000; settingsMenuLink = element(by.id('settings-dropdown-button')); projectSettingsLink = element(by.id('dropdown-project-settings')); // Get the projectSettings for project projectName get(projectName: string) { this.projectsPage.get(); this.projectsPage.clickOnProject(projectName); browser.wait(ExpectedConditions.visibilityOf(this.settingsMenuLink), this.conditionTimeout); this.settingsMenuLink.click(); browser.wait(ExpectedConditions.visibilityOf(this.projectSettingsLink), this.conditionTimeout); this.projectSettingsLink.click(); } noticeList = element.all(by.repeater('notice in $ctrl.notices()')); firstNoticeCloseButton = this.noticeList.first().element(by.buttonText('×')); tabDivs = element.all(by.className('tab-pane')); activePane = element(by.css('div.tab-pane.active')); /* Would like to use id locators, but the pui-tab directive that is used in the project settingsPage in scripture forge is currently making it hard to assign an id to the tab element. This should be updated, but due to time shortage, it will be left as is. - Mark W 2018-01-15 */ tabs = { project: element(by.linkText('Project Properties')), // reports: element(by.linkText('Reports')), // This feature is never tested // archive: element(by.linkText('Archive')), // This is a disabled feature remove: element(by.linkText('Delete')) }; projectTab = { name: element(by.model('project.projectName')), code: element(by.model('project.projectCode')), projectOwner: element(by.binding('project.ownerRef.username')), saveButton: element(by.id('project-properties-save-button')) }; // placeholder since we don't have Reports tests reportsTab = { }; // Archive tab currently disabled // this.archiveTab = { // archiveButton: this.activePane.element(by.buttonText('Archive this project')) // }; deleteTab = { deleteBoxText: this.activePane.element(by.id('deletebox')), deleteButton: this.activePane.element(by.id('deleteProject')) }; }
Java
#ifndef AC_GEPT3DAR_H #define AC_GEPT3DAR_H // // (C) Copyright 1993-1999, 2010 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // // DESCRIPTION: // // This file contains the definition for a dynamic array, called // AcGePoint3dArray, of objects of type "AcGePoint3d". // // "Dynamic array" means that the array can grow without bounds, // unlike declaring an array of objects of type "AcGePoint3d" in the // usual manner. For example declaring "AcGePoint3d myArray[10]" // is limited to holding only ten entries. // // In order to use the class AcGePoint3dArray, you need to understand // a couple of simple, yet key, concepts: // // 1) The logical length of the array. // - How many entries have been placed into the array, // initially always zero. // 2) The physical length of the array. // - How many entries the array will hold before it // automatically "grows" larger. // 3) The grow length of the array. // - How much the array will grow when required. // // The physical length of the array is the actual length of the // physically allocated, but perhaps not fully used, array. // As a point of clarification, the size in bytes of the array // buffer for an array called `myArray' would be: // // sizeOf(AcGePoint3d) * myArray.physicalLength(). // // The physical length of the array can be zero or any positive // integer. // // The logical length of the array (or just the "length()") reflects // how many elements of AcGePoint3d have been placed into the array // with, for example, append() or insertAt(). Many member-functions // are only valid for indices that are greater than or equal to // zero AND less than length(). For example, indexing into the // array with the operator[] is only valid for indices in this range. // // You can explicitly set the logical length() to any value and // if the physical length is not large enough the array will grow to // that length. Note that if the logical length is explicitly reset // to a larger value, then all the entries from the old length up // to the new length may contain garbage values, therefor they must be // initialized explicitly. // // The logical length is always less than or equal to the physical // length. NOTE that the array ALWAYS starts out empty, i.e., the // length() always starts at zero regardless of the initial physical // length. // // If you add an element to the array causing the logical length // to become greater than the physical length of the array then // the "grow length" determines how much additional space to // allocate, and the physical length will increase by the grow length. // // The grow length must be a positive number, that is, zero is an illegal // grow length. #include "adesk.h" #include "assert.h" #include "gepnt3d.h" #include "acarray.h" typedef AcArray<AcGePoint3d> AcGePoint3dArray; #if GE_LOCATED_NEW GE_DLLEXPIMPORT AcGe::metaTypeIndex AcGeGetMetaTypeIndex(AcGePoint3dArray* pT); #endif #endif
Java
/** * Framework APIs (global - app.*) * * Note: View APIs are in view.js (view - view.*) * * @author Tim Lauv * @created 2015.07.29 * @updated 2017.04.04 */ ;(function(app){ /** * Universal app object creation api entry point * ---------------------------------------------------- * @deprecated Use the detailed apis instead. */ app.create = function(type, config){ console.warn('DEV::Application::create() method is deprecated, use methods listed in ', app._apis, ' for alternatives'); }; /** * Detailed api entry point * ------------------------ * If you don't want to use .create() there you go: */ _.extend(app, { //----------------view------------------ //pass in [name,] options to define view (named view will be registered) //pass in name to get registered view def //pass in options, true to create anonymous view view: function(name /*or options*/, options /*or instance flag*/){ if(_.isString(name) && _.isPlainObject(options)){ return app.Core.View.register(name, options); } if(_.isPlainObject(name)){ var instance = options; options = name; var Def = app.Core.View.register(options); if(_.isBoolean(instance) && instance) return Def.create(); return Def; } return app.Core.View.get(name); }, //@deprecated--------------------- //pass in [name,] options to register (always requires a name) //pass in [name] to get (name can be of path form) context: function(name /*or options*/, options){ if(!options) { if(_.isString(name) || !name) return app.Core.Context.get(name); else options = name; } else _.extend(options, {name: name}); console.warn('DEV::Application::context() method is deprecated, use .view() instead for', options.name || options /*as an indicator of anonymous view*/); return app.Core.Context.register(options); }, //-------------------------------- //pass in name, factory to register //pass in name, options to create //pass in [name] to get (name can be of path form) widget: function(name, options /*or factory*/){ if(!options) return app.Core.Widget.get(name); if(_.isFunction(options)) //register return app.Core.Widget.register(name, options); return app.Core.Widget.create(name, options); //you can not register the definition when providing name, options. }, //pass in name, factory to register //pass in name, options to create //pass in [name] to get (name can be of path form) editor: function(name, options /*or factory*/){ if(!options) return app.Core.Editor.get(name); if(_.isFunction(options)) //register return app.Core.Editor.register(name, options); return app.Core.Editor.create(name, options); //you can not register the definition when providing name, options. }, //@deprecated--------------------- regional: function(name, options){ options = options || {}; if(_.isString(name)) _.extend(options, {name: name}); else _.extend(options, name); console.warn('DEV::Application::regional() method is deprecated, use .view() instead for', options.name || options /*as an indicator of anonymous view*/); return app.view(options, !options.name); }, //-------------------------------- //(name can be of path form) has: function(name, type){ type = type || 'View'; if(name) return app.Core[type] && app.Core[type].has(name); _.each(['Context', 'View', 'Widget', 'Editor'], function(t){ if(!type && app.Core[t].has(name)) type = t; }); return type; }, //(name can be of path form) //always return View definition. get: function(name, type, options){ if(!name) return { 'Context': app.Core.Context.get(), 'View': app.Core.View.get(), 'Widget': app.Core.Widget.get(), 'Editor': app.Core.Editor.get() }; if(_.isPlainObject(type)){ options = type; type = undefined; } var Reusable, t = type || 'View'; options = _.extend({fallback: false, override: false}, options); //try local if(!options.override) Reusable = (app.Core[t] && app.Core[t].get(name)) || (options.fallback && app.Core['View'].get(name)); //try remote, if we have app.viewSrcs set to load the View def dynamically if(!Reusable && app.config && app.config.viewSrcs){ var targetJS = _.compact([app.config.viewSrcs, t.toLowerCase()/*not view.category yet*/, app.nameToPath(name)]).join('/') + '.js'; app.inject.js( targetJS, true //sync ).done(function(){ app.debug(t, name, 'injected', 'from', app.config.viewSrcs); if(app.has(name, t) || (options.fallback && app.has(name))) Reusable = app.get(name, t, {fallback: true}); else throw new Error('DEV::Application::get() loaded definitions other than required ' + name + ' of type ' + t + ' from ' + targetJS + ', please check your view name in that file!'); }).fail(function(jqXHR, settings, e){ if(!options.fallback || (t === 'View')) throw new Error('DEV::Application::get() can NOT load definition for ' + name + ' - [' + e + ']'); else Reusable = app.get(name, 'View'); }); } return Reusable; }, //**Caveat**: spray returns the region (created on $anchor), upon returning, its 'show' event has already passed. spray: function($anchor, View /*or template or name or instance or options or svg draw(paper){} func */, options, parentCt){ var $el = $($anchor); parentCt = parentCt || app.mainView; //check if $anchor is already a region var region = $el.data('region'); var regionName = region && region._name; if(!regionName){ regionName = $el.attr('region') || _.uniqueId('anonymous-region-'); $el.attr('region', regionName); region = parentCt.addRegion(regionName, '[region="' + regionName + '"]'); region.ensureEl(parentCt); } else parentCt = region.parentCt; //see if it is an svg draw(paper){} function if(_.isFunction(View) && View.length === 1){ //svg return parentCt.show(regionName, { template: '<div svg="canvas"></div>', data: options && options.data, //only honor options.data if passed in. svg: { canvas: View }, onPaperCleared: function(paper){ paper._fit($el); }, }); }else //view return parentCt.show(regionName, View, options); //returns the sub-regional view. }, icing: function(name, flag, View, options){ if(_.isBoolean(name)){ options = View; View = flag; flag = name; name = 'default'; } var regionName = ['icing', 'region', name].join('-'); if(!app.mainView.getRegion(regionName) && !_.isBoolean(name)){ options = flag; View = name; flag = true; name = 'default'; } regionName = ['icing', 'region', name].join('-'); var ir = app.mainView.getRegion(regionName); if(flag === false){ ir.$el.hide(); ir.currentView && ir.currentView.close(); } else { ir.$el.show(); app.mainView.show(regionName, View, options); } }, coop: function(event){ var args = _.toArray(arguments); args.unshift('app:coop'); app.trigger.apply(app, args); args = args.slice(2); args.unshift('app:coop-' + event); app.trigger.apply(app, args); return app; }, pathToName: function(path){ if(!_.isString(path)) throw new Error('DEV::Application::pathToName() You must pass in a valid path string.'); if(_.contains(path, '.')) return path; return path.split('/').map(_.string.humanize).map(_.string.classify).join('.'); }, nameToPath: function(name){ if(!_.isString(name)) throw new Error('DEV::Application::nameToPath() You must pass in a Reusable view name.'); if(_.contains(name, '/')) return name; return name.split('.').map(_.string.humanize).map(_.string.slugify).join('/'); }, //----------------navigation----------- navigate: function(options, silent){ return app.trigger('app:navigate', options, silent); }, navPathArray: function(){ return _.compact(window.location.hash.replace('#navigate', '').split('/')); }, //-----------------mutex--------------- lock: function(topic){ return app.Core.Lock.lock(topic); }, unlock: function(topic){ return app.Core.Lock.unlock(topic); }, available: function(topic){ return app.Core.Lock.available(topic); }, //-----------------remote data------------ //returns jqXHR object (use promise pls) remote: function(options /*or url*/, payload, restOpt){ options = options || {}; if(options.payload || payload){ payload = options.payload || payload; return app.Core.Remote.change(options, _.extend({payload: payload}, restOpt)); } else return app.Core.Remote.get(options, restOpt); }, download: function(ticket /*or url*/, options /*{params:{...}} only*/){ return app.Util.download(ticket, options); }, upload: function(url, options){ return app.Util.upload(url, options); }, //data push //(ws channels) _websockets: {}, /** * returns a promise. * * Usage * ----- * register: app.config.defaultWebsocket or app.ws(socketPath); * receive (e): view.coop['ws-data-[channel]'] or app.onWsData = custom fn; * send (json): app.ws(socketPath) * .then(function(ws){ws.channel(...).json({...});}); default per channel data * .then(function(ws){ws.send(); or ws.json();}); anything by any contract * e.websocket = ws in .then(function(ws){}) * * Default messaging contract * -------------------------- * Nodejs /devserver: json {channel: '..:..', payload: {..data..}} through ws.channel('..:..').json({..data..}) * Python ASGI: json {stream: '...', payload: {..data..}} through ws.stream('...').json({..data..}) * * Reconnecting websockets * ----------------------- * websocket path ends with '+' will be reconnecting websocket when created. * */ ws: function(socketPath, coopEvent /*or callback or options*/){ if(!app.detect('websockets')) throw new Error('DEV::Application::ws() Websocket is not supported by your browser!'); socketPath = socketPath || app.config.defaultWebsocket || '/ws'; var reconnect = false; if(_.string.endsWith(socketPath, '+')){ socketPath = socketPath.slice(0, socketPath.length - 1); reconnect = true; } var d = $.Deferred(); if(!app._websockets[socketPath]) { app._websockets[socketPath] = new WebSocket(location.protocol.replace('http', 'ws') + '//' + location.host + socketPath); app._websockets[socketPath].path = socketPath; app._websockets[socketPath].reconnect = reconnect; //events: 'open', 'error', 'close', 'message' = e.data //apis: send(), +json(), +channel().json(), close() app._websockets[socketPath].json = function(data){ app._websockets[socketPath].send(JSON.stringify(data)); }; app._websockets[socketPath].channel = function(channel){ return { name: channel, websocket: app._websockets[socketPath], json: function(data){ app._websockets[socketPath].json({ channel: channel, stream: channel, //alias for ASGI backends payload: data }); } }; }; app._websockets[socketPath].stream = app._websockets[socketPath].channel; //alias for ASGI backends app._websockets[socketPath].onclose = function(){ var ws = app._websockets[socketPath]; delete app._websockets[socketPath]; if(ws.reconnect) app.ws(ws.path + '+'); }; app._websockets[socketPath].onopen = function(){ return d.resolve(app._websockets[socketPath]); }; //general ws data stub //server need to always send default json contract string {"channel/stream": "...", "payload": "..."} //Opt: override this through app.ws(path).then(function(ws){ws.onmessage=...}); app._websockets[socketPath].onmessage = function(e){ //opt a. override app.onWsData to active otherwise app.trigger('app:ws-data', {websocket: app._websockets[socketPath], raw: e.data}); //opt b. use global coop event 'ws-data-[channel]' in views directly (default json contract) try { var data = JSON.parse(e.data); app.coop('ws-data-' + (data.channel || data.stream), data.payload, app._websockets[socketPath].channel(data.channel || data.stream)); }catch(ex){ console.warn('DEV::Application::ws() Websocket is getting non-default {channel: ..., payload: ...} json contract strings...'); } }; //register coopEvent or callback function or callback options if(coopEvent){ //onmessage callback function if(_.isFunction(coopEvent)){ //overwrite onmessage callback function defined by framework app._websockets[socketPath].onmessage = function(e){ coopEvent(e.data, e, app._websockets[socketPath]); }; } //object may contain onmessage, onerror, since onopen and onclose is done by the framework else if(_.isPlainObject(coopEvent)){ //traverse through object to register all callback events _.each(coopEvent, function(fn, eventName){ //guard events if(_.contains(['onmessage', 'onerror'], eventName)) app._websockets[socketPath][eventName] = fn; }); } //app coop event else if(_.isString(coopEvent)){ //trigger coop event with data from sse's onmessage callback app._websockets[socketPath].onmessage = function(e){ app.coop('ws-data-' + coopEvent, e.data, e, app._websockets[socketPath]); }; } //type is not right else console.warn('DEV::Application::ws() The coopEvent or callback function or callbacks\' options you give is not right.'); } }else d.resolve(app._websockets[socketPath]); return d.promise(); }, //data polling //(through later.js) and emit data events/or invoke callback _polls: {}, poll: function(url /*or {options} for app.remote()*/, occurrence, coopEvent /*or callback or options*/) { //stop everything if (url === false){ return _.map(this._polls, function(card) { return card.cancel(); }); } var schedule; if (_.isString(occurrence) && !Number.parseInt(occurrence)) { schedule = app.later.parse.text(occurrence); if (schedule.error !== -1) throw new Error('DEV::Application::poll() occurrence string unrecognizable...'); } else if (_.isPlainObject(occurrence)) schedule = occurrence; else //number schedule = Number(occurrence); //make a key from url, or {url: ..., params/querys} var key = url; if (_.isPlainObject(key)) key = [key.url, _.reduce((_.map(key.params || key.querys, function(qV, qKey) { return [qKey, qV].join('='); })).sort(), function(qSignature, more) { return [more, qSignature].join('&'); }, '')].join('?'); //cancel polling if (occurrence === false) { if (this._polls[key]) return this._polls[key].cancel(); console.warn('DEV::Application::poll() No polling card registered yet for ' + key); return; } //cancel previous polling if (this._polls[key]) this._polls[key].cancel(); //register polling card if (!occurrence || !coopEvent) throw new Error('DEV::Application::poll() You must specify an occurrence and a coop event or callback...'); var card = { _key: key, url: url, eof: coopEvent, timerId: undefined, failed: 0, valid: true, occurrence: occurrence, //info only }; this._polls[key] = card; var call = _.isNumber(schedule) ? window.setTimeout : app.later.setTimeout; //if coopEvent is an object. register options events before calling app.remote if(_.isPlainObject(coopEvent)){ //save url var temp = url; //build url as an object for app.remote url = { url: temp }; _.each(coopEvent, function(fn, eventName){ //guard for only allowing $.ajax events if(_.contains(['beforeSend', 'error', 'dataFilter', 'success', 'complete'], eventName)) url[eventName] = fn; }); } var worker = function() { app.remote(url).done(function(data) { //callback if (_.isFunction(card.eof)) card.eof(data, card); //coop event else app.coop('poll-data-' + card.eof, data, card); }).fail(function() { card.failed++; //Warning: Hardcoded 3 attemps here! if (card.failed >= 3) card.cancel(); }).always(function() { //go schedule the next call if (card.valid) card.timerId = call(worker, schedule); }); }; //+timerType card.timerType = (call === window.setTimeout) ? 'native' : 'later.js'; //+cancel() var that = this; card.cancel = function() { this.valid = false; if (this.timerType === 'native') !_.isUndefined(this.timerId) && window.clearTimeout(this.timerId); else !_.isUndefined(this.timerId) && this.timerId.clear(); delete that._polls[this._key]; return this; }; //make the 1st call (eagerly) worker(); }, //-----------------ee/observer with built-in state-machine---------------- //use start('stateB') or trigger('stateA-->stateB') to swap between states //use ['stateA-->stateB', 'stateC<-->stateB', 'stateA<--stateC', ...] in edges to constrain state changes. ee: function(data, evtmap, edges){ //+on/once, off, +start/reset/stop/getState/getEdges; +listenTo/Once, stopListening; +trigger*; var dispatcher; data = _.extend({}, data, {cid: _.uniqueId('ee')}); evtmap = _.extend({ 'initialize': _.noop, 'finalize': _.noop, }, evtmap); edges = _.reduce(edges || {}, function(mem, val, index){ var bi = val.match('(.*)<-->(.*)'), left = val.match('(.*)<--(.*)'), right = val.match('(.*)-->(.*)'); if(bi){ mem[bi[1] + '-->' + bi[2]] = true; mem[bi[2] + '-->' + bi[1]] = true; } else if (left) mem[left[2] + '-->' + left[1]] = true; else if (right) mem[val] = true; else console.warn('DEV::Application::ee() illegal edge format: ' + val); return mem; }, {}); if(!_.size(edges)) edges = undefined; dispatcher = _.extend(data, Backbone.Events); var oldTriggerFn = dispatcher.trigger; var currentState = ''; //add a state-machine friendly .trigger method; dispatcher.trigger = function(){ var changeOfStates = arguments[0] && arguments[0].match('(.*)-->(.*)'); if(changeOfStates && changeOfStates.length){ var from = _.string.trim(changeOfStates[1]), to = _.string.trim(changeOfStates[2]); //check edge constraints if(from && to && edges && !edges[arguments[0]]){ console.warn('DEV::Application::ee() edge constraint: ' + from + '-x->' + to); return this; } //check current state if(from != currentState){ console.warn('DEV::Application::ee() current state is ' + (currentState || '\'\'') + ' not ' + from); return this; } this.trigger('leave', {to: to}); //unregister event listeners in [from] state _.each(evtmap[from], function(listener, e){ dispatcher.off(from + ':' + e); }); //register event listeners in [to] state _.each(evtmap[to], function(listener, e){ dispatcher.on(to + ':' + e, listener); }); currentState = to; this.trigger('enter', {from: from}); } else { if(evtmap[currentState] && evtmap[currentState][arguments[0]]) arguments[0] = currentState + ':' + arguments[0]; oldTriggerFn.apply(this, arguments); } return this; }; //add an internal worker swap method; dispatcher._swap = function(targetState){ targetState = targetState || ''; this.trigger(currentState + '-->' + targetState); return this; }; //add a start method; (start at any state) dispatcher.start = function(targetState){ targetState = targetState || currentState; return this._swap(targetState); }; //add a reset method; (reset to '' state) dispatcher.reset = function(){ return this._swap(); }; //add a clean-up method; dispatcher.stop = function(){ this.trigger('finalize'); this.off(); this.stopListening(); }; //add some getters; dispatcher.getState = function(){ return currentState; }; dispatcher.getEdges = function(){ return edges; }; //mount shared events _.each(evtmap, function(listener, eOrStateName){ if(!_.isFunction(listener)) return; dispatcher.on(eOrStateName, listener); }); this.trigger('initialize'); return dispatcher; }, model: function(data, flat){ if(_.isBoolean(data)){ flat = data; data = undefined; } if(flat) return new Backbone.Model(data); //Warning: Possible performance impact...(default) return new Backbone.DeepModel(data); ///////////////////////////////////////// }, collection: function(data){ if(data && !_.isArray(data)) throw new Error('DEV::Application::collection You need to specify an array to init a collection'); return new Backbone.Collection(data); }, //bridge extract from app.Util.deepObjectKeys extract: function(keypath, from){ return app.Util.deepObjectKeys.extract(keypath, from); }, //bridge pack from app.Util.deepObjectKeys pack: function(keypathObj, to){ return app.Util.deepObjectKeys.pack(keypathObj, to); }, mock: function(schema, provider/*optional*/, url/*optional*/){ return app.Util.mock(schema, provider, url); }, //----------------url params--------------------------------- param: function(key, defaultVal){ var params = app.uri(window.location.href).search(true) || {}; if(key) return params[key] || defaultVal; return params; }, //----------------raw animation (DON'T mix with jQuery fx)--------------- //(specifically, don't call $.animate() inside updateFn) //(you also can NOT control the rate the browser calls updateFn, its 60 FPS all the time...) animation: function(updateFn, condition, ctx){ var id; var stepFn = function(t){ updateFn.call(ctx);//...update...(1 tick) if(!condition || (condition && condition.call(ctx)))//...condition...(to continue) move(); }; var move = function(){ if(id === undefined) return; id = app._nextFrame(stepFn); }; var stop = function(){ app._cancelFrame(id); id = undefined; }; return { start: function(){id = -1; move();}, stop: stop }; }, _nextFrame: function(stepFn){ //return request id return window.requestAnimationFrame(stepFn); }, _cancelFrame: function(id){ return window.cancelAnimationFrame(id); }, //effects see https://daneden.github.io/animate.css/ //sample usage: 'ready' --> app.animateItems(); animateItems: function(selector /*or $items*/, effect, stagger){ var $selector = $(selector); if(_.isNumber(effect)){ stagger = effect; effect = undefined; } effect = effect || 'flipInX'; stagger = stagger || 150; var inOrOut = /In/.test(effect)? 1: (/Out/.test(effect)? -1: 0); $selector.each(function(i, el){ var $el = $(el); //////////////////different than region.show effect because of stagger delay////////////////// if(inOrOut) if(inOrOut === 1) $el.css('opacity', 0); else $el.css('opacity', 1); ////////////////////////////////////////////////////////////////////////////////////////////// _.delay(function($el){ var fxName = effect + ' animated'; $el.anyone(app.ADE, function(){ $el.removeClass(fxName); }).addClass(fxName); ///////////////reset opacity immediately, not after ADE/////////////// if(inOrOut) if(inOrOut === 1) $el.css('opacity', 1); else $el.css('opacity', 0); ////////////////////////////////////////////////////////////////////// }, i * stagger, $el); }); }, //Built-in web worker utility, bridged from app.Util.worker. worker: function(name/*web worker's name*/, coopEOrCallbackOrOpts){ return app.Util.worker(name, coopEOrCallbackOrOpts); }, //Built-in Server-Sent Event(SSE) utility, bridged from app.Util.sse sse: function(url/*sse's url*/, topics/*['...', '...']*/, coopEOrCallbackOrOpts){ return app.Util.sse(url, topics, coopEOrCallbackOrOpts); }, //----------------config.rapidEventDelay wrapped util-------------------- //**Caveat**: if using cached version, pass `this` and other upper scope vars into fn as arguments, else //these in fn will be cached forever and might no longer exist or point to the right thing when called... throttle: function(fn, ms, cacheId){ ms = ms || app.config.rapidEventDelay; fn = _.throttle(fn, ms); if(!cacheId) return fn; //cached version (so you can call right after wrapping it) this._tamedFns = this._tamedFns || {}; var key = fn + cacheId + '-throttle' + ms; if(!this._tamedFns[key]) this._tamedFns[key] = fn; return this._tamedFns[key]; }, debounce: function(fn, ms, cacheId){ ms = ms || app.config.rapidEventDelay; fn = _.debounce(fn, ms); if(!cacheId) return fn; //cached version (so you can call right after wrapping it) this._tamedFns = this._tamedFns || {}; var key = fn + cacheId + '-debounce' + ms; if(!this._tamedFns[key]) this._tamedFns[key] = fn; return this._tamedFns[key]; }, //app wide e.preventDefault() util preventDefaultE: function(e){ var $el = $(e.target); //Caveat: this clumsy bit here is due to the in-ability to check on the 'action-*' attributes on e.target... if($el.is('label') || $el.is('i') || $el.is('img') || $el.is('span') || $el.is('input') || $el.is('textarea') || $el.is('select') || ($el.is('a') && $el.attr('href'))) return; e.preventDefault(); }, //wait until all targets fires e (asynchronously) then call the callback with targets (e.g [this.show(), ...], 'ready') until: function(targets, e, callback){ targets = _.compact(targets); cb = _.after(targets.length, function(){ callback(targets); }); _.each(targets, function(t){ t.once(e, cb); }); }, //----------------markdown------------------- //options.marked, options.hljs //https://guides.github.com/features/mastering-markdown/ //our addition: // ^^^class class2 class3 ... // ... // ^^^ markdown: function(md, $anchor /*or options*/, options){ options = options || (!_.isjQueryObject($anchor) && $anchor) || {}; //render content var html = marked(md, app.debug('marked options are', _.extend(app.config.marked, (options.marked && options.marked) || options, _.isjQueryObject($anchor) && $anchor.data('marked')))), hljs = window.hljs; //highlight code (use ```language to specify type) if(hljs){ hljs.configure(app.debug('hljs options are', _.extend(app.config.hljs, options.hljs, _.isjQueryObject($anchor) && $anchor.data('hljs')))); var $html = $('<div>' + html + '</div>'); $html.find('pre code').each(function(){ hljs.highlightBlock(this); }); html = $html.html(); } if(_.isjQueryObject($anchor)) return $anchor.html(html).addClass('md-content'); return html; }, //----------------notify/overlay/popover--------------------- notify: function(title /*or options*/, msg, type /*or otherOptions*/, otherOptions){ if(_.isString(title)){ if(_.isPlainObject(type)){ otherOptions = type; type = undefined; } if(otherOptions && otherOptions.icon){ //theme awesome ({.icon, .more}) $.amaran(_.extend({ theme: 'awesome ' + (type || 'ok'), //see http://ersu.me/article/amaranjs/amaranjs-themes for types content: { title: title, message: msg, info: otherOptions.more || ' ', icon: otherOptions.icon } }, otherOptions)); } else { //custom theme $.amaran(_.extend({ content: { themeName: 'stagejs', title: title, message: msg, type: type || 'info', }, themeTemplate: app.NOTIFYTPL }, otherOptions)); } } else $.amaran(title); }, //overlay or popover prompt: function(view, anchor, placement, options){ if(_.isFunction(view)) view = new view(); else if(_.isString(view)) view = app.get(view).create(); //is popover if(_.isString(placement)){ options = options || {}; options.placement = placement; return view.popover(anchor, options); } //is overlay options = placement; return view.overlay(anchor, options); }, //----------------i18n----------------------- i18n: function(key, ns){ if(key){ //insert translations to current locale if(_.isPlainObject(key)) return I18N.insertTrans(key); //return a translation for specified key, ns/module return String(key).i18n(ns); } //otherwise, collect available strings (so far) into an i18n object. return I18N.getResourceJSON(null, false); }, //----------------debug---------------------- //bridge app.debug() debug: function(){ return app.Util.debugHelper.debug.apply(null, arguments); }, //bridge app.locate() locate: function(name /*el or $el*/){ return app.Util.debugHelper.locate(name); }, //bridge app.profile() profile: function(name /*el or $el*/){ return app.Util.debugHelper.profile(name); }, //bridge app.mark() mark: function(name /*el or $el*/){ return app.Util.debugHelper.mark(name); }, //bridge app.reload() reload: function(name, override/*optional*/){ return app.Util.debugHelper.reload(name, override); }, inject: { js: function(){ return app.Util.inject.apply(null, arguments); }, tpl: function(){ return app.Util.Tpl.remote.apply(app.Util.Tpl, arguments); }, css: function(){ return loadCSS.apply(null, arguments); } }, detect: function(feature, provider/*optional*/){ if(!provider) provider = Modernizr; return app.extract(feature, provider) || false; }, //--------3rd party lib pass-through--------- // js-cookie (former jquery-cookie) //.set(), .get(), .remove() cookie: Cookies, // store.js (localStorage) //.set(), .get(), .getAll(), .remove(), .clear() store: store.enabled && store, // validator.js (var type and val validation, e.g form editor validation) validator: validator, // moment.js (date and time) moment: moment, // URI.js (uri,query and hash in the url, e.g in app.param()) uri: URI, // later.js (schedule repeated workers, e.g in app.poll()) later: later, // faker.js (mock data generator, e.g in app.mock()) faker: faker, }); //editor rules app.editor.validator = app.editor.rule = function(name, fn){ if(!_.isString(name)) throw new Error('DEV::Validator:: You must specify a validator/rule name to use.'); return app.Core.Editor.addRule(name, fn); }; //alias app.page = app.context; app.area = app.regional; app.curtain = app.icing; /** * API summary */ app._apis = [ 'ee', 'model', 'collection', 'mock', //view registery 'view', 'widget', 'editor', 'editor.validator - @alias:editor.rule', //global action locks 'lock', 'unlock', 'available', //utils 'has', 'get', 'spray', 'coop', 'navigate', 'navPathArray', 'icing/curtain', 'i18n', 'param', 'animation', 'animateItems', 'throttle', 'debounce', 'preventDefaultE', 'until', //com 'remote', 'download', 'upload', 'ws', 'poll', 'worker', 'sse', //3rd-party lib short-cut 'extract', 'markdown', 'notify', 'prompt', //wraps 'cookie', 'store', 'moment', 'uri', 'validator', 'later', 'faker', //direct refs //supportive 'debug', 'detect', 'reload', 'locate', 'profile', 'mark', 'nameToPath', 'pathToName', 'inject.js', 'inject.tpl', 'inject.css', //@deprecated 'create - @deprecated', 'regional - @deprecated', 'context - @alias:page - @deprecated' ]; /** * Statics */ //animation done events used in Animate.css //Caveat: if you use $el.one(app.ADE) but still got 2+ callback calls, the browser is firing the default and prefixed events at the same time... //use $el.anyone() to fix the problem in using $el.one() app.ADE = 'animationend webkitAnimationEnd MSAnimationEnd oAnimationEnd transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd'; //notification template app.NOTIFYTPL = Handlebars.compile('<div class="alert alert-dismissable alert-{{type}}"><button data-dismiss="alert" class="close" type="button">×</button><strong>{{title}}</strong> {{{message}}}</div>'); })(Application);
Java
// Base64 encoder/decoder with UTF-8 support // // Copyright (c) 2011 Vitaly Puzrin // Copyright (c) 2011 Aleksey V Zapparov // // Author: Aleksey V Zapparov AKA ixti (http://www.ixti.net/) // // 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. // Based on original artworks of base64 encoder/decoder by [Mozilla][1] // [1]: http://lxr.mozilla.org/mozilla/source/extensions/xml-rpc/src/nsXmlRpcClient.js 'use strict'; /* eslint-env browser */ /* eslint-disable no-bitwise */ function noop() {} var logger = { warn: noop, error: noop }, padding = '=', chrTable = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' + '0123456789+/', binTable = [ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, 0, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1 ]; if (window.console) { logger = window.console; logger.warn = logger.warn || logger.error || logger.log || noop; logger.error = logger.error || logger.warn || logger.log || noop; } // internal helpers ////////////////////////////////////////////////////////// function utf8Encode(str) { var bytes = [], offset = 0, length, char; str = encodeURI(str); length = str.length; while (offset < length) { char = str.charAt(offset); offset += 1; if (char !== '%') { bytes.push(char.charCodeAt(0)); } else { char = str.charAt(offset) + str.charAt(offset + 1); bytes.push(parseInt(char, 16)); offset += 2; } } return bytes; } function utf8Decode(bytes) { var chars = [], offset = 0, length = bytes.length, c1, c2, c3; while (offset < length) { c1 = bytes[offset]; c2 = bytes[offset + 1]; c3 = bytes[offset + 2]; if (c1 < 128) { chars.push(String.fromCharCode(c1)); offset += 1; } else if (191 < c1 && c1 < 224) { chars.push(String.fromCharCode(((c1 & 31) << 6) | (c2 & 63))); offset += 2; } else { chars.push(String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63))); offset += 3; } } return chars.join(''); } // public api //////////////////////////////////////////////////////////////// function encode(str) { var result = '', bytes = utf8Encode(str), length = bytes.length, i; // Convert every three bytes to 4 ascii characters. for (i = 0; i < (length - 2); i += 3) { result += chrTable[bytes[i] >> 2]; result += chrTable[((bytes[i] & 0x03) << 4) + (bytes[i + 1] >> 4)]; result += chrTable[((bytes[i + 1] & 0x0f) << 2) + (bytes[i + 2] >> 6)]; result += chrTable[bytes[i + 2] & 0x3f]; } // Convert the remaining 1 or 2 bytes, pad out to 4 characters. if (length % 3) { i = length - (length % 3); result += chrTable[bytes[i] >> 2]; if ((length % 3) === 2) { result += chrTable[((bytes[i] & 0x03) << 4) + (bytes[i + 1] >> 4)]; result += chrTable[(bytes[i + 1] & 0x0f) << 2]; result += padding; } else { result += chrTable[(bytes[i] & 0x03) << 4]; result += padding + padding; } } return result; } function decode(data) { var value, code, idx = 0, bytes = [], leftbits = 0, // number of bits decoded, but yet to be appended leftdata = 0; // bits decoded, but yet to be appended // Convert one by one. for (idx = 0; idx < data.length; idx += 1) { code = data.charCodeAt(idx); value = binTable[code & 0x7F]; if (value === -1) { // Skip illegal characters and whitespace logger.warn('Illegal characters (code=' + code + ') in position ' + idx); } else { // Collect data into leftdata, update bitcount leftdata = (leftdata << 6) | value; leftbits += 6; // If we have 8 or more bits, append 8 bits to the result if (leftbits >= 8) { leftbits -= 8; // Append if not padding. if (padding !== data.charAt(idx)) { bytes.push((leftdata >> leftbits) & 0xFF); } leftdata &= (1 << leftbits) - 1; } } } // If there are any bits left, the base64 string was corrupted if (leftbits) { logger.error('Corrupted base64 string'); return null; } return utf8Decode(bytes); } exports.encode = encode; exports.decode = decode;
Java
module.exports = require("npm:acorn@2.4.0/dist/acorn");
Java
require 'rr' require 'awesome_print' %w"xiki/core/core_ext xiki/core/ol".each {|o| require o} # RSpec::Runner.configure do |config| RSpec.configure do |config| config.mock_with :rr end module Xiki def self.dir File.expand_path("#{File.dirname(__FILE__)}/..") + "/" end end def stub_menu_path_dirs xiki_dir = Xiki.dir list = ["#{xiki_dir}spec/fixtures/menu", "#{xiki_dir}menu"] stub(Xiki).menu_path_dirs {list} end # Put this here until we can put it in a better place # - Maybe so it'll be used by main xiki and conf AwesomePrint.defaults = { :indent => -2, # left-align hash keys :index => false, :multiline => true, } include Xiki # Allows all specs to use classes in the Xiki module without "Xiki::"
Java
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2017 The Bitcoin Core developers // Copyright (c) 2015-2017 The Dash developers // Copyright (c) 2015-2017 The Bitsend developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITSEND_WARNINGS_H #define BITSEND_WARNINGS_H #include <stdlib.h> #include <string> void SetMiscWarning(const std::string& strWarning); void SetfLargeWorkForkFound(bool flag); bool GetfLargeWorkForkFound(); void SetfLargeWorkInvalidChainFound(bool flag); bool GetfLargeWorkInvalidChainFound(); std::string GetWarnings(const std::string& strFor); static const bool DEFAULT_TESTSAFEMODE = false; #endif // BITSEND_WARNINGS_H
Java
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2016-2018 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Create oauthclient tables.""" import sqlalchemy as sa import sqlalchemy_utils from alembic import op from sqlalchemy.engine.reflection import Inspector # revision identifiers, used by Alembic. revision = '97bbc733896c' down_revision = '44ab9963e8cf' branch_labels = () depends_on = '9848d0149abd' def upgrade(): """Upgrade database.""" op.create_table( 'oauthclient_remoteaccount', sa.Column('id', sa.Integer(), nullable=False), sa.Column('user_id', sa.Integer(), nullable=False), sa.Column('client_id', sa.String(length=255), nullable=False), sa.Column( 'extra_data', sqlalchemy_utils.JSONType(), nullable=False), sa.ForeignKeyConstraint(['user_id'], [u'accounts_user.id'], ), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('user_id', 'client_id') ) op.create_table( 'oauthclient_useridentity', sa.Column('id', sa.String(length=255), nullable=False), sa.Column('method', sa.String(length=255), nullable=False), sa.Column('id_user', sa.Integer(), nullable=False), sa.ForeignKeyConstraint(['id_user'], [u'accounts_user.id'], ), sa.PrimaryKeyConstraint('id', 'method') ) op.create_index( 'useridentity_id_user_method', 'oauthclient_useridentity', ['id_user', 'method'], unique=True ) op.create_table( 'oauthclient_remotetoken', sa.Column('id_remote_account', sa.Integer(), nullable=False), sa.Column('token_type', sa.String(length=40), nullable=False), sa.Column( 'access_token', sqlalchemy_utils.EncryptedType(), nullable=False), sa.Column('secret', sa.Text(), nullable=False), sa.ForeignKeyConstraint( ['id_remote_account'], [u'oauthclient_remoteaccount.id'], name='fk_oauthclient_remote_token_remote_account' ), sa.PrimaryKeyConstraint('id_remote_account', 'token_type') ) def downgrade(): """Downgrade database.""" ctx = op.get_context() insp = Inspector.from_engine(ctx.connection.engine) op.drop_table('oauthclient_remotetoken') for fk in insp.get_foreign_keys('oauthclient_useridentity'): if fk['referred_table'] == 'accounts_user': op.drop_constraint( op.f(fk['name']), 'oauthclient_useridentity', type_='foreignkey' ) op.drop_index( 'useridentity_id_user_method', table_name='oauthclient_useridentity') op.drop_table('oauthclient_useridentity') op.drop_table('oauthclient_remoteaccount')
Java
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Platform; using osu.Game.Configuration; namespace osu.Game.Overlays.Settings.Sections.General { public class UpdateSettings : SettingsSubsection { protected override string Header => "Updates"; [BackgroundDependencyLoader] private void load(Storage storage, OsuConfigManager config) { Children = new Drawable[] { new SettingsEnumDropdown<ReleaseStream> { LabelText = "Release stream", Bindable = config.GetBindable<ReleaseStream>(OsuSetting.ReleaseStream), }, new SettingsButton { Text = "Open osu! folder", Action = storage.OpenInNativeExplorer, } }; } } }
Java
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.eventhubs.v2017_04_01.implementation; import java.util.List; import org.joda.time.DateTime; import com.microsoft.azure.management.eventhubs.v2017_04_01.EntityStatus; import com.microsoft.azure.management.eventhubs.v2017_04_01.CaptureDescription; import com.fasterxml.jackson.annotation.JsonProperty; import com.microsoft.rest.serializer.JsonFlatten; import com.microsoft.azure.ProxyResource; /** * Single item in List or Get Event Hub operation. */ @JsonFlatten public class EventhubInner extends ProxyResource { /** * Current number of shards on the Event Hub. */ @JsonProperty(value = "properties.partitionIds", access = JsonProperty.Access.WRITE_ONLY) private List<String> partitionIds; /** * Exact time the Event Hub was created. */ @JsonProperty(value = "properties.createdAt", access = JsonProperty.Access.WRITE_ONLY) private DateTime createdAt; /** * The exact time the message was updated. */ @JsonProperty(value = "properties.updatedAt", access = JsonProperty.Access.WRITE_ONLY) private DateTime updatedAt; /** * Number of days to retain the events for this Event Hub, value should be * 1 to 7 days. */ @JsonProperty(value = "properties.messageRetentionInDays") private Long messageRetentionInDays; /** * Number of partitions created for the Event Hub, allowed values are from * 1 to 32 partitions. */ @JsonProperty(value = "properties.partitionCount") private Long partitionCount; /** * Enumerates the possible values for the status of the Event Hub. Possible * values include: 'Active', 'Disabled', 'Restoring', 'SendDisabled', * 'ReceiveDisabled', 'Creating', 'Deleting', 'Renaming', 'Unknown'. */ @JsonProperty(value = "properties.status") private EntityStatus status; /** * Properties of capture description. */ @JsonProperty(value = "properties.captureDescription") private CaptureDescription captureDescription; /** * Get current number of shards on the Event Hub. * * @return the partitionIds value */ public List<String> partitionIds() { return this.partitionIds; } /** * Get exact time the Event Hub was created. * * @return the createdAt value */ public DateTime createdAt() { return this.createdAt; } /** * Get the exact time the message was updated. * * @return the updatedAt value */ public DateTime updatedAt() { return this.updatedAt; } /** * Get number of days to retain the events for this Event Hub, value should be 1 to 7 days. * * @return the messageRetentionInDays value */ public Long messageRetentionInDays() { return this.messageRetentionInDays; } /** * Set number of days to retain the events for this Event Hub, value should be 1 to 7 days. * * @param messageRetentionInDays the messageRetentionInDays value to set * @return the EventhubInner object itself. */ public EventhubInner withMessageRetentionInDays(Long messageRetentionInDays) { this.messageRetentionInDays = messageRetentionInDays; return this; } /** * Get number of partitions created for the Event Hub, allowed values are from 1 to 32 partitions. * * @return the partitionCount value */ public Long partitionCount() { return this.partitionCount; } /** * Set number of partitions created for the Event Hub, allowed values are from 1 to 32 partitions. * * @param partitionCount the partitionCount value to set * @return the EventhubInner object itself. */ public EventhubInner withPartitionCount(Long partitionCount) { this.partitionCount = partitionCount; return this; } /** * Get enumerates the possible values for the status of the Event Hub. Possible values include: 'Active', 'Disabled', 'Restoring', 'SendDisabled', 'ReceiveDisabled', 'Creating', 'Deleting', 'Renaming', 'Unknown'. * * @return the status value */ public EntityStatus status() { return this.status; } /** * Set enumerates the possible values for the status of the Event Hub. Possible values include: 'Active', 'Disabled', 'Restoring', 'SendDisabled', 'ReceiveDisabled', 'Creating', 'Deleting', 'Renaming', 'Unknown'. * * @param status the status value to set * @return the EventhubInner object itself. */ public EventhubInner withStatus(EntityStatus status) { this.status = status; return this; } /** * Get properties of capture description. * * @return the captureDescription value */ public CaptureDescription captureDescription() { return this.captureDescription; } /** * Set properties of capture description. * * @param captureDescription the captureDescription value to set * @return the EventhubInner object itself. */ public EventhubInner withCaptureDescription(CaptureDescription captureDescription) { this.captureDescription = captureDescription; return this; } }
Java
import actionTypes from '../../client/actions/types'; const defaultState = { data: {}, errors: 'Not Found', }; export default function domainDetailReducer(state = defaultState, action = {}) { switch (action.type) { case actionTypes.getDomainDetail: return Object.assign({}, state, { data: action.data.domain, errors: action.errors, }); default: return state; } }
Java
import {createStore, combineReducers} from 'redux'; import {todos} from '../reducers/todos'; export function configureStore() { const store = createStore(combineReducers({todos})); return store; }
Java
<!DOCTYPE html> <html> <head> <title>选项</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <link rel="stylesheet" type="text/css" href="style.css" > <script src="options.js"></script> </head> <body> <div id="options_content"> <span id="message"></span> <h4>发音</h4> <input type="checkbox" name="auto" id="auto"> <label for="auto">自动发音</label> <h4>释义</h4> <input type="checkbox" name="zh_definitions" id="zh_definitions"> <label for="zh_definitions">显示中文释义</label> <input type="checkbox" name="en_definitions" id="en_definitions"> <label for="en_definitions">显示英语释义</label> <br /> <br /> <button id="reset">重置</button> <button id="save">保存</button> <a href="popup.html" id="return">返回</a> </div> </body> </html>
Java
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #include <curl/curl.h> #include "urldata.h" #include "transfer.h" #include "url.h" #include "connect.h" #include "progress.h" #include "easyif.h" #include "share.h" #include "psl.h" #include "multiif.h" #include "sendf.h" #include "timeval.h" #include "http.h" #include "select.h" #include "warnless.h" #include "speedcheck.h" #include "conncache.h" #include "multihandle.h" #include "sigpipe.h" #include "vtls/vtls.h" #include "connect.h" #include "http_proxy.h" #include "http2.h" /* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" /* CURL_SOCKET_HASH_TABLE_SIZE should be a prime number. Increasing it from 97 to 911 takes on a 32-bit machine 4 x 804 = 3211 more bytes. Still, every CURL handle takes 45-50 K memory, therefore this 3K are not significant. */ #ifndef CURL_SOCKET_HASH_TABLE_SIZE #define CURL_SOCKET_HASH_TABLE_SIZE 911 #endif #ifndef CURL_CONNECTION_HASH_SIZE #define CURL_CONNECTION_HASH_SIZE 97 #endif #define CURL_MULTI_HANDLE 0x000bab1e #define GOOD_MULTI_HANDLE(x) \ ((x) && (x)->type == CURL_MULTI_HANDLE) static CURLMcode singlesocket(struct Curl_multi *multi, struct Curl_easy *data); static CURLMcode add_next_timeout(struct curltime now, struct Curl_multi *multi, struct Curl_easy *d); static CURLMcode multi_timeout(struct Curl_multi *multi, long *timeout_ms); static void process_pending_handles(struct Curl_multi *multi); static void detach_connnection(struct Curl_easy *data); #ifdef DEBUGBUILD static const char * const statename[]={ "INIT", "CONNECT_PEND", "CONNECT", "WAITRESOLVE", "WAITCONNECT", "WAITPROXYCONNECT", "SENDPROTOCONNECT", "PROTOCONNECT", "DO", "DOING", "DO_MORE", "DO_DONE", "PERFORM", "TOOFAST", "DONE", "COMPLETED", "MSGSENT", }; #endif /* function pointer called once when switching TO a state */ typedef void (*init_multistate_func)(struct Curl_easy *data); static void Curl_init_completed(struct Curl_easy *data) { /* this is a completed transfer */ /* Important: reset the conn pointer so that we don't point to memory that could be freed anytime */ detach_connnection(data); Curl_expire_clear(data); /* stop all timers */ } /* always use this function to change state, to make debugging easier */ static void mstate(struct Curl_easy *data, CURLMstate state #ifdef DEBUGBUILD , int lineno #endif ) { CURLMstate oldstate = data->mstate; static const init_multistate_func finit[CURLM_STATE_LAST] = { NULL, /* INIT */ NULL, /* CONNECT_PEND */ Curl_init_CONNECT, /* CONNECT */ NULL, /* WAITRESOLVE */ NULL, /* WAITCONNECT */ NULL, /* WAITPROXYCONNECT */ NULL, /* SENDPROTOCONNECT */ NULL, /* PROTOCONNECT */ Curl_connect_free, /* DO */ NULL, /* DOING */ NULL, /* DO_MORE */ NULL, /* DO_DONE */ NULL, /* PERFORM */ NULL, /* TOOFAST */ NULL, /* DONE */ Curl_init_completed, /* COMPLETED */ NULL /* MSGSENT */ }; #if defined(DEBUGBUILD) && defined(CURL_DISABLE_VERBOSE_STRINGS) (void) lineno; #endif if(oldstate == state) /* don't bother when the new state is the same as the old state */ return; data->mstate = state; #if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS) if(data->mstate >= CURLM_STATE_CONNECT_PEND && data->mstate < CURLM_STATE_COMPLETED) { long connection_id = -5000; if(data->conn) connection_id = data->conn->connection_id; infof(data, "STATE: %s => %s handle %p; line %d (connection #%ld)\n", statename[oldstate], statename[data->mstate], (void *)data, lineno, connection_id); } #endif if(state == CURLM_STATE_COMPLETED) /* changing to COMPLETED means there's one less easy handle 'alive' */ data->multi->num_alive--; /* if this state has an init-function, run it */ if(finit[state]) finit[state](data); } #ifndef DEBUGBUILD #define multistate(x,y) mstate(x,y) #else #define multistate(x,y) mstate(x,y, __LINE__) #endif /* * We add one of these structs to the sockhash for each socket */ struct Curl_sh_entry { struct curl_hash transfers; /* hash of transfers using this socket */ unsigned int action; /* what combined action READ/WRITE this socket waits for */ void *socketp; /* settable by users with curl_multi_assign() */ unsigned int users; /* number of transfers using this */ unsigned int readers; /* this many transfers want to read */ unsigned int writers; /* this many transfers want to write */ }; /* bits for 'action' having no bits means this socket is not expecting any action */ #define SH_READ 1 #define SH_WRITE 2 /* look up a given socket in the socket hash, skip invalid sockets */ static struct Curl_sh_entry *sh_getentry(struct curl_hash *sh, curl_socket_t s) { if(s != CURL_SOCKET_BAD) { /* only look for proper sockets */ return Curl_hash_pick(sh, (char *)&s, sizeof(curl_socket_t)); } return NULL; } #define TRHASH_SIZE 13 static size_t trhash(void *key, size_t key_length, size_t slots_num) { size_t keyval = (size_t)*(struct Curl_easy **)key; (void) key_length; return (keyval % slots_num); } static size_t trhash_compare(void *k1, size_t k1_len, void *k2, size_t k2_len) { (void)k1_len; (void)k2_len; return *(struct Curl_easy **)k1 == *(struct Curl_easy **)k2; } static void trhash_dtor(void *nada) { (void)nada; } /* make sure this socket is present in the hash for this handle */ static struct Curl_sh_entry *sh_addentry(struct curl_hash *sh, curl_socket_t s) { struct Curl_sh_entry *there = sh_getentry(sh, s); struct Curl_sh_entry *check; if(there) { /* it is present, return fine */ return there; } /* not present, add it */ check = calloc(1, sizeof(struct Curl_sh_entry)); if(!check) return NULL; /* major failure */ if(Curl_hash_init(&check->transfers, TRHASH_SIZE, trhash, trhash_compare, trhash_dtor)) { free(check); return NULL; } /* make/add new hash entry */ if(!Curl_hash_add(sh, (char *)&s, sizeof(curl_socket_t), check)) { free(check); return NULL; /* major failure */ } return check; /* things are good in sockhash land */ } /* delete the given socket + handle from the hash */ static void sh_delentry(struct Curl_sh_entry *entry, struct curl_hash *sh, curl_socket_t s) { Curl_hash_destroy(&entry->transfers); /* We remove the hash entry. This will end up in a call to sh_freeentry(). */ Curl_hash_delete(sh, (char *)&s, sizeof(curl_socket_t)); } /* * free a sockhash entry */ static void sh_freeentry(void *freethis) { struct Curl_sh_entry *p = (struct Curl_sh_entry *) freethis; free(p); } static size_t fd_key_compare(void *k1, size_t k1_len, void *k2, size_t k2_len) { (void) k1_len; (void) k2_len; return (*((curl_socket_t *) k1)) == (*((curl_socket_t *) k2)); } static size_t hash_fd(void *key, size_t key_length, size_t slots_num) { curl_socket_t fd = *((curl_socket_t *) key); (void) key_length; return (fd % slots_num); } /* * sh_init() creates a new socket hash and returns the handle for it. * * Quote from README.multi_socket: * * "Some tests at 7000 and 9000 connections showed that the socket hash lookup * is somewhat of a bottle neck. Its current implementation may be a bit too * limiting. It simply has a fixed-size array, and on each entry in the array * it has a linked list with entries. So the hash only checks which list to * scan through. The code I had used so for used a list with merely 7 slots * (as that is what the DNS hash uses) but with 7000 connections that would * make an average of 1000 nodes in each list to run through. I upped that to * 97 slots (I believe a prime is suitable) and noticed a significant speed * increase. I need to reconsider the hash implementation or use a rather * large default value like this. At 9000 connections I was still below 10us * per call." * */ static int sh_init(struct curl_hash *hash, int hashsize) { return Curl_hash_init(hash, hashsize, hash_fd, fd_key_compare, sh_freeentry); } /* * multi_addmsg() * * Called when a transfer is completed. Adds the given msg pointer to * the list kept in the multi handle. */ static CURLMcode multi_addmsg(struct Curl_multi *multi, struct Curl_message *msg) { Curl_llist_insert_next(&multi->msglist, multi->msglist.tail, msg, &msg->list); return CURLM_OK; } struct Curl_multi *Curl_multi_handle(int hashsize, /* socket hash */ int chashsize) /* connection hash */ { struct Curl_multi *multi = calloc(1, sizeof(struct Curl_multi)); if(!multi) return NULL; multi->type = CURL_MULTI_HANDLE; if(Curl_mk_dnscache(&multi->hostcache)) goto error; if(sh_init(&multi->sockhash, hashsize)) goto error; if(Curl_conncache_init(&multi->conn_cache, chashsize)) goto error; Curl_llist_init(&multi->msglist, NULL); Curl_llist_init(&multi->pending, NULL); multi->multiplexing = CURLPIPE_MULTIPLEX; /* -1 means it not set by user, use the default value */ multi->maxconnects = -1; return multi; error: Curl_hash_destroy(&multi->sockhash); Curl_hash_destroy(&multi->hostcache); Curl_conncache_destroy(&multi->conn_cache); Curl_llist_destroy(&multi->msglist, NULL); Curl_llist_destroy(&multi->pending, NULL); free(multi); return NULL; } struct Curl_multi *curl_multi_init(void) { return Curl_multi_handle(CURL_SOCKET_HASH_TABLE_SIZE, CURL_CONNECTION_HASH_SIZE); } CURLMcode curl_multi_add_handle(struct Curl_multi *multi, struct Curl_easy *data) { /* First, make some basic checks that the CURLM handle is a good handle */ if(!GOOD_MULTI_HANDLE(multi)) return CURLM_BAD_HANDLE; /* Verify that we got a somewhat good easy handle too */ if(!GOOD_EASY_HANDLE(data)) return CURLM_BAD_EASY_HANDLE; /* Prevent users from adding same easy handle more than once and prevent adding to more than one multi stack */ if(data->multi) return CURLM_ADDED_ALREADY; if(multi->in_callback) return CURLM_RECURSIVE_API_CALL; /* Initialize timeout list for this handle */ Curl_llist_init(&data->state.timeoutlist, NULL); /* * No failure allowed in this function beyond this point. And no * modification of easy nor multi handle allowed before this except for * potential multi's connection cache growing which won't be undone in this * function no matter what. */ if(data->set.errorbuffer) data->set.errorbuffer[0] = 0; /* set the easy handle */ multistate(data, CURLM_STATE_INIT); /* for multi interface connections, we share DNS cache automatically if the easy handle's one is currently not set. */ if(!data->dns.hostcache || (data->dns.hostcachetype == HCACHE_NONE)) { data->dns.hostcache = &multi->hostcache; data->dns.hostcachetype = HCACHE_MULTI; } /* Point to the shared or multi handle connection cache */ if(data->share && (data->share->specifier & (1<< CURL_LOCK_DATA_CONNECT))) data->state.conn_cache = &data->share->conn_cache; else data->state.conn_cache = &multi->conn_cache; #ifdef USE_LIBPSL /* Do the same for PSL. */ if(data->share && (data->share->specifier & (1 << CURL_LOCK_DATA_PSL))) data->psl = &data->share->psl; else data->psl = &multi->psl; #endif /* We add the new entry last in the list. */ data->next = NULL; /* end of the line */ if(multi->easyp) { struct Curl_easy *last = multi->easylp; last->next = data; data->prev = last; multi->easylp = data; /* the new last node */ } else { /* first node, make prev NULL! */ data->prev = NULL; multi->easylp = multi->easyp = data; /* both first and last */ } /* make the Curl_easy refer back to this multi handle */ data->multi = multi; /* Set the timeout for this handle to expire really soon so that it will be taken care of even when this handle is added in the midst of operation when only the curl_multi_socket() API is used. During that flow, only sockets that time-out or have actions will be dealt with. Since this handle has no action yet, we make sure it times out to get things to happen. */ Curl_expire(data, 0, EXPIRE_RUN_NOW); /* increase the node-counter */ multi->num_easy++; /* increase the alive-counter */ multi->num_alive++; /* A somewhat crude work-around for a little glitch in Curl_update_timer() that happens if the lastcall time is set to the same time when the handle is removed as when the next handle is added, as then the check in Curl_update_timer() that prevents calling the application multiple times with the same timer info will not trigger and then the new handle's timeout will not be notified to the app. The work-around is thus simply to clear the 'lastcall' variable to force Curl_update_timer() to always trigger a callback to the app when a new easy handle is added */ memset(&multi->timer_lastcall, 0, sizeof(multi->timer_lastcall)); /* The closure handle only ever has default timeouts set. To improve the state somewhat we clone the timeouts from each added handle so that the closure handle always has the same timeouts as the most recently added easy handle. */ data->state.conn_cache->closure_handle->set.timeout = data->set.timeout; data->state.conn_cache->closure_handle->set.server_response_timeout = data->set.server_response_timeout; data->state.conn_cache->closure_handle->set.no_signal = data->set.no_signal; Curl_update_timer(multi); return CURLM_OK; } #if 0 /* Debug-function, used like this: * * Curl_hash_print(multi->sockhash, debug_print_sock_hash); * * Enable the hash print function first by editing hash.c */ static void debug_print_sock_hash(void *p) { struct Curl_sh_entry *sh = (struct Curl_sh_entry *)p; fprintf(stderr, " [easy %p/magic %x/socket %d]", (void *)sh->data, sh->data->magic, (int)sh->socket); } #endif static CURLcode multi_done(struct Curl_easy *data, CURLcode status, /* an error if this is called after an error was detected */ bool premature) { CURLcode result; struct connectdata *conn = data->conn; unsigned int i; DEBUGF(infof(data, "multi_done\n")); if(data->state.done) /* Stop if multi_done() has already been called */ return CURLE_OK; /* Stop the resolver and free its own resources (but not dns_entry yet). */ Curl_resolver_kill(conn); /* Cleanup possible redirect junk */ Curl_safefree(data->req.newurl); Curl_safefree(data->req.location); switch(status) { case CURLE_ABORTED_BY_CALLBACK: case CURLE_READ_ERROR: case CURLE_WRITE_ERROR: /* When we're aborted due to a callback return code it basically have to be counted as premature as there is trouble ahead if we don't. We have many callbacks and protocols work differently, we could potentially do this more fine-grained in the future. */ premature = TRUE; default: break; } /* this calls the protocol-specific function pointer previously set */ if(conn->handler->done) result = conn->handler->done(conn, status, premature); else result = status; if(CURLE_ABORTED_BY_CALLBACK != result) { /* avoid this if we already aborted by callback to avoid this calling another callback */ CURLcode rc = Curl_pgrsDone(conn); if(!result && rc) result = CURLE_ABORTED_BY_CALLBACK; } process_pending_handles(data->multi); /* connection / multiplex */ detach_connnection(data); if(CONN_INUSE(conn)) { /* Stop if still used. */ DEBUGF(infof(data, "Connection still in use %zu, " "no more multi_done now!\n", conn->easyq.size)); return CURLE_OK; } data->state.done = TRUE; /* called just now! */ if(conn->dns_entry) { Curl_resolv_unlock(data, conn->dns_entry); /* done with this */ conn->dns_entry = NULL; } Curl_hostcache_prune(data); Curl_safefree(data->state.ulbuf); /* if the transfer was completed in a paused state there can be buffered data left to free */ for(i = 0; i < data->state.tempcount; i++) { free(data->state.tempwrite[i].buf); } data->state.tempcount = 0; /* if data->set.reuse_forbid is TRUE, it means the libcurl client has forced us to close this connection. This is ignored for requests taking place in a NTLM/NEGOTIATE authentication handshake if conn->bits.close is TRUE, it means that the connection should be closed in spite of all our efforts to be nice, due to protocol restrictions in our or the server's end if premature is TRUE, it means this connection was said to be DONE before the entire request operation is complete and thus we can't know in what state it is for re-using, so we're forced to close it. In a perfect world we can add code that keep track of if we really must close it here or not, but currently we have no such detail knowledge. */ if((data->set.reuse_forbid #if defined(USE_NTLM) && !(conn->http_ntlm_state == NTLMSTATE_TYPE2 || conn->proxy_ntlm_state == NTLMSTATE_TYPE2) #endif #if defined(USE_SPNEGO) && !(conn->http_negotiate_state == GSS_AUTHRECV || conn->proxy_negotiate_state == GSS_AUTHRECV) #endif ) || conn->bits.close || (premature && !(conn->handler->flags & PROTOPT_STREAM))) { CURLcode res2 = Curl_disconnect(data, conn, premature); /* If we had an error already, make sure we return that one. But if we got a new error, return that. */ if(!result && res2) result = res2; } else { char buffer[256]; /* create string before returning the connection */ msnprintf(buffer, sizeof(buffer), "Connection #%ld to host %s left intact", conn->connection_id, conn->bits.socksproxy ? conn->socks_proxy.host.dispname : conn->bits.httpproxy ? conn->http_proxy.host.dispname : conn->bits.conn_to_host ? conn->conn_to_host.dispname : conn->host.dispname); /* the connection is no longer in use by this transfer */ if(Curl_conncache_return_conn(conn)) { /* remember the most recently used connection */ data->state.lastconnect = conn; infof(data, "%s\n", buffer); } else data->state.lastconnect = NULL; } Curl_free_request_state(data); return result; } CURLMcode curl_multi_remove_handle(struct Curl_multi *multi, struct Curl_easy *data) { struct Curl_easy *easy = data; bool premature; bool easy_owns_conn; struct curl_llist_element *e; /* First, make some basic checks that the CURLM handle is a good handle */ if(!GOOD_MULTI_HANDLE(multi)) return CURLM_BAD_HANDLE; /* Verify that we got a somewhat good easy handle too */ if(!GOOD_EASY_HANDLE(data)) return CURLM_BAD_EASY_HANDLE; /* Prevent users from trying to remove same easy handle more than once */ if(!data->multi) return CURLM_OK; /* it is already removed so let's say it is fine! */ if(multi->in_callback) return CURLM_RECURSIVE_API_CALL; premature = (data->mstate < CURLM_STATE_COMPLETED) ? TRUE : FALSE; easy_owns_conn = (data->conn && (data->conn->data == easy)) ? TRUE : FALSE; /* If the 'state' is not INIT or COMPLETED, we might need to do something nice to put the easy_handle in a good known state when this returns. */ if(premature) { /* this handle is "alive" so we need to count down the total number of alive connections when this is removed */ multi->num_alive--; } if(data->conn && data->mstate > CURLM_STATE_DO && data->mstate < CURLM_STATE_COMPLETED) { /* Set connection owner so that the DONE function closes it. We can safely do this here since connection is killed. */ data->conn->data = easy; streamclose(data->conn, "Removed with partial response"); easy_owns_conn = TRUE; } /* The timer must be shut down before data->multi is set to NULL, else the timenode will remain in the splay tree after curl_easy_cleanup is called. */ Curl_expire_clear(data); if(data->conn) { /* we must call multi_done() here (if we still own the connection) so that we don't leave a half-baked one around */ if(easy_owns_conn) { /* multi_done() clears the conn->data field to lose the association between the easy handle and the connection Note that this ignores the return code simply because there's nothing really useful to do with it anyway! */ (void)multi_done(data, data->result, premature); } } if(data->connect_queue.ptr) /* the handle was in the pending list waiting for an available connection, so go ahead and remove it */ Curl_llist_remove(&multi->pending, &data->connect_queue, NULL); if(data->dns.hostcachetype == HCACHE_MULTI) { /* stop using the multi handle's DNS cache, *after* the possible multi_done() call above */ data->dns.hostcache = NULL; data->dns.hostcachetype = HCACHE_NONE; } Curl_wildcard_dtor(&data->wildcard); /* destroy the timeout list that is held in the easy handle, do this *after* multi_done() as that may actually call Curl_expire that uses this */ Curl_llist_destroy(&data->state.timeoutlist, NULL); /* as this was using a shared connection cache we clear the pointer to that since we're not part of that multi handle anymore */ data->state.conn_cache = NULL; /* change state without using multistate(), only to make singlesocket() do what we want */ data->mstate = CURLM_STATE_COMPLETED; singlesocket(multi, easy); /* to let the application know what sockets that vanish with this handle */ /* Remove the association between the connection and the handle */ if(data->conn) { data->conn->data = NULL; detach_connnection(data); } #ifdef USE_LIBPSL /* Remove the PSL association. */ if(data->psl == &multi->psl) data->psl = NULL; #endif data->multi = NULL; /* clear the association to this multi handle */ /* make sure there's no pending message in the queue sent from this easy handle */ for(e = multi->msglist.head; e; e = e->next) { struct Curl_message *msg = e->ptr; if(msg->extmsg.easy_handle == easy) { Curl_llist_remove(&multi->msglist, e, NULL); /* there can only be one from this specific handle */ break; } } /* make the previous node point to our next */ if(data->prev) data->prev->next = data->next; else multi->easyp = data->next; /* point to first node */ /* make our next point to our previous node */ if(data->next) data->next->prev = data->prev; else multi->easylp = data->prev; /* point to last node */ /* NOTE NOTE NOTE We do not touch the easy handle here! */ multi->num_easy--; /* one less to care about now */ Curl_update_timer(multi); return CURLM_OK; } /* Return TRUE if the application asked for multiplexing */ bool Curl_multiplex_wanted(const struct Curl_multi *multi) { return (multi && (multi->multiplexing)); } /* This is the only function that should clear data->conn. This will occasionally be called with the pointer already cleared. */ static void detach_connnection(struct Curl_easy *data) { struct connectdata *conn = data->conn; if(conn) Curl_llist_remove(&conn->easyq, &data->conn_queue, NULL); data->conn = NULL; } /* This is the only function that should assign data->conn */ void Curl_attach_connnection(struct Curl_easy *data, struct connectdata *conn) { DEBUGASSERT(!data->conn); DEBUGASSERT(conn); data->conn = conn; Curl_llist_insert_next(&conn->easyq, conn->easyq.tail, data, &data->conn_queue); } static int waitconnect_getsock(struct connectdata *conn, curl_socket_t *sock) { int i; int s = 0; int rc = 0; #ifdef USE_SSL if(CONNECT_FIRSTSOCKET_PROXY_SSL()) return Curl_ssl_getsock(conn, sock); #endif for(i = 0; i<2; i++) { if(conn->tempsock[i] != CURL_SOCKET_BAD) { sock[s] = conn->tempsock[i]; rc |= GETSOCK_WRITESOCK(s); #ifdef ENABLE_QUIC if(conn->transport == TRNSPRT_QUIC) /* when connecting QUIC, we want to read the socket too */ rc |= GETSOCK_READSOCK(s); #endif s++; } } return rc; } static int waitproxyconnect_getsock(struct connectdata *conn, curl_socket_t *sock) { sock[0] = conn->sock[FIRSTSOCKET]; /* when we've sent a CONNECT to a proxy, we should rather wait for the socket to become readable to be able to get the response headers */ if(conn->connect_state) return GETSOCK_READSOCK(0); return GETSOCK_WRITESOCK(0); } static int domore_getsock(struct connectdata *conn, curl_socket_t *socks) { if(conn && conn->handler->domore_getsock) return conn->handler->domore_getsock(conn, socks); return GETSOCK_BLANK; } static int doing_getsock(struct connectdata *conn, curl_socket_t *socks) { if(conn && conn->handler->doing_getsock) return conn->handler->doing_getsock(conn, socks); return GETSOCK_BLANK; } static int protocol_getsock(struct connectdata *conn, curl_socket_t *socks) { if(conn->handler->proto_getsock) return conn->handler->proto_getsock(conn, socks); /* Backup getsock logic. Since there is a live socket in use, we must wait for it or it will be removed from watching when the multi_socket API is used. */ socks[0] = conn->sock[FIRSTSOCKET]; return GETSOCK_READSOCK(0) | GETSOCK_WRITESOCK(0); } /* returns bitmapped flags for this handle and its sockets. The 'socks[]' array contains MAX_SOCKSPEREASYHANDLE entries. */ static int multi_getsock(struct Curl_easy *data, curl_socket_t *socks) { /* The no connection case can happen when this is called from curl_multi_remove_handle() => singlesocket() => multi_getsock(). */ if(!data->conn) return 0; if(data->mstate > CURLM_STATE_CONNECT && data->mstate < CURLM_STATE_COMPLETED) { /* Set up ownership correctly */ data->conn->data = data; } switch(data->mstate) { default: #if 0 /* switch back on these cases to get the compiler to check for all enums to be present */ case CURLM_STATE_TOOFAST: /* returns 0, so will not select. */ case CURLM_STATE_COMPLETED: case CURLM_STATE_MSGSENT: case CURLM_STATE_INIT: case CURLM_STATE_CONNECT: case CURLM_STATE_WAITDO: case CURLM_STATE_DONE: case CURLM_STATE_LAST: /* this will get called with CURLM_STATE_COMPLETED when a handle is removed */ #endif return 0; case CURLM_STATE_WAITRESOLVE: return Curl_resolv_getsock(data->conn, socks); case CURLM_STATE_PROTOCONNECT: case CURLM_STATE_SENDPROTOCONNECT: return protocol_getsock(data->conn, socks); case CURLM_STATE_DO: case CURLM_STATE_DOING: return doing_getsock(data->conn, socks); case CURLM_STATE_WAITPROXYCONNECT: return waitproxyconnect_getsock(data->conn, socks); case CURLM_STATE_WAITCONNECT: return waitconnect_getsock(data->conn, socks); case CURLM_STATE_DO_MORE: return domore_getsock(data->conn, socks); case CURLM_STATE_DO_DONE: /* since is set after DO is completed, we switch to waiting for the same as the *PERFORM states */ case CURLM_STATE_PERFORM: return Curl_single_getsock(data->conn, socks); } } CURLMcode curl_multi_fdset(struct Curl_multi *multi, fd_set *read_fd_set, fd_set *write_fd_set, fd_set *exc_fd_set, int *max_fd) { /* Scan through all the easy handles to get the file descriptors set. Some easy handles may not have connected to the remote host yet, and then we must make sure that is done. */ struct Curl_easy *data; int this_max_fd = -1; curl_socket_t sockbunch[MAX_SOCKSPEREASYHANDLE]; int i; (void)exc_fd_set; /* not used */ if(!GOOD_MULTI_HANDLE(multi)) return CURLM_BAD_HANDLE; if(multi->in_callback) return CURLM_RECURSIVE_API_CALL; data = multi->easyp; while(data) { int bitmap = multi_getsock(data, sockbunch); for(i = 0; i< MAX_SOCKSPEREASYHANDLE; i++) { curl_socket_t s = CURL_SOCKET_BAD; if((bitmap & GETSOCK_READSOCK(i)) && VALID_SOCK((sockbunch[i]))) { FD_SET(sockbunch[i], read_fd_set); s = sockbunch[i]; } if((bitmap & GETSOCK_WRITESOCK(i)) && VALID_SOCK((sockbunch[i]))) { FD_SET(sockbunch[i], write_fd_set); s = sockbunch[i]; } if(s == CURL_SOCKET_BAD) /* this socket is unused, break out of loop */ break; if((int)s > this_max_fd) this_max_fd = (int)s; } data = data->next; /* check next handle */ } *max_fd = this_max_fd; return CURLM_OK; } #define NUM_POLLS_ON_STACK 10 static CURLMcode Curl_multi_wait(struct Curl_multi *multi, struct curl_waitfd extra_fds[], unsigned int extra_nfds, int timeout_ms, int *ret, bool extrawait) /* when no socket, wait */ { struct Curl_easy *data; curl_socket_t sockbunch[MAX_SOCKSPEREASYHANDLE]; int bitmap; unsigned int i; unsigned int nfds = 0; unsigned int curlfds; bool ufds_malloc = FALSE; long timeout_internal; int retcode = 0; struct pollfd a_few_on_stack[NUM_POLLS_ON_STACK]; struct pollfd *ufds = &a_few_on_stack[0]; if(!GOOD_MULTI_HANDLE(multi)) return CURLM_BAD_HANDLE; if(multi->in_callback) return CURLM_RECURSIVE_API_CALL; /* Count up how many fds we have from the multi handle */ data = multi->easyp; while(data) { bitmap = multi_getsock(data, sockbunch); for(i = 0; i< MAX_SOCKSPEREASYHANDLE; i++) { curl_socket_t s = CURL_SOCKET_BAD; if(bitmap & GETSOCK_READSOCK(i)) { ++nfds; s = sockbunch[i]; } if(bitmap & GETSOCK_WRITESOCK(i)) { ++nfds; s = sockbunch[i]; } if(s == CURL_SOCKET_BAD) { break; } } data = data->next; /* check next handle */ } /* If the internally desired timeout is actually shorter than requested from the outside, then use the shorter time! But only if the internal timer is actually larger than -1! */ (void)multi_timeout(multi, &timeout_internal); if((timeout_internal >= 0) && (timeout_internal < (long)timeout_ms)) timeout_ms = (int)timeout_internal; curlfds = nfds; /* number of internal file descriptors */ nfds += extra_nfds; /* add the externally provided ones */ if(nfds > NUM_POLLS_ON_STACK) { /* 'nfds' is a 32 bit value and 'struct pollfd' is typically 8 bytes big, so at 2^29 sockets this value might wrap. When a process gets the capability to actually handle over 500 million sockets this calculation needs a integer overflow check. */ ufds = malloc(nfds * sizeof(struct pollfd)); if(!ufds) return CURLM_OUT_OF_MEMORY; ufds_malloc = TRUE; } nfds = 0; /* only do the second loop if we found descriptors in the first stage run above */ if(curlfds) { /* Add the curl handles to our pollfds first */ data = multi->easyp; while(data) { bitmap = multi_getsock(data, sockbunch); for(i = 0; i< MAX_SOCKSPEREASYHANDLE; i++) { curl_socket_t s = CURL_SOCKET_BAD; if(bitmap & GETSOCK_READSOCK(i)) { ufds[nfds].fd = sockbunch[i]; ufds[nfds].events = POLLIN; ++nfds; s = sockbunch[i]; } if(bitmap & GETSOCK_WRITESOCK(i)) { ufds[nfds].fd = sockbunch[i]; ufds[nfds].events = POLLOUT; ++nfds; s = sockbunch[i]; } if(s == CURL_SOCKET_BAD) { break; } } data = data->next; /* check next handle */ } } /* Add external file descriptions from poll-like struct curl_waitfd */ for(i = 0; i < extra_nfds; i++) { ufds[nfds].fd = extra_fds[i].fd; ufds[nfds].events = 0; if(extra_fds[i].events & CURL_WAIT_POLLIN) ufds[nfds].events |= POLLIN; if(extra_fds[i].events & CURL_WAIT_POLLPRI) ufds[nfds].events |= POLLPRI; if(extra_fds[i].events & CURL_WAIT_POLLOUT) ufds[nfds].events |= POLLOUT; ++nfds; } if(nfds) { int pollrc; /* wait... */ pollrc = Curl_poll(ufds, nfds, timeout_ms); if(pollrc > 0) { retcode = pollrc; /* copy revents results from the poll to the curl_multi_wait poll struct, the bit values of the actual underlying poll() implementation may not be the same as the ones in the public libcurl API! */ for(i = 0; i < extra_nfds; i++) { unsigned short mask = 0; unsigned r = ufds[curlfds + i].revents; if(r & POLLIN) mask |= CURL_WAIT_POLLIN; if(r & POLLOUT) mask |= CURL_WAIT_POLLOUT; if(r & POLLPRI) mask |= CURL_WAIT_POLLPRI; extra_fds[i].revents = mask; } } } if(ufds_malloc) free(ufds); if(ret) *ret = retcode; if(!extrawait || extra_fds || curlfds) /* if any socket was checked */ ; else { long sleep_ms = 0; /* Avoid busy-looping when there's nothing particular to wait for */ if(!curl_multi_timeout(multi, &sleep_ms) && sleep_ms) { if(sleep_ms > timeout_ms) sleep_ms = timeout_ms; Curl_wait_ms((int)sleep_ms); } } return CURLM_OK; } CURLMcode curl_multi_wait(struct Curl_multi *multi, struct curl_waitfd extra_fds[], unsigned int extra_nfds, int timeout_ms, int *ret) { return Curl_multi_wait(multi, extra_fds, extra_nfds, timeout_ms, ret, FALSE); } CURLMcode curl_multi_poll(struct Curl_multi *multi, struct curl_waitfd extra_fds[], unsigned int extra_nfds, int timeout_ms, int *ret) { return Curl_multi_wait(multi, extra_fds, extra_nfds, timeout_ms, ret, TRUE); } /* * multi_ischanged() is called * * Returns TRUE/FALSE whether the state is changed to trigger a CONNECT_PEND * => CONNECT action. * * Set 'clear' to TRUE to have it also clear the state variable. */ static bool multi_ischanged(struct Curl_multi *multi, bool clear) { bool retval = multi->recheckstate; if(clear) multi->recheckstate = FALSE; return retval; } CURLMcode Curl_multi_add_perform(struct Curl_multi *multi, struct Curl_easy *data, struct connectdata *conn) { CURLMcode rc; if(multi->in_callback) return CURLM_RECURSIVE_API_CALL; rc = curl_multi_add_handle(multi, data); if(!rc) { struct SingleRequest *k = &data->req; /* pass in NULL for 'conn' here since we don't want to init the connection, only this transfer */ Curl_init_do(data, NULL); /* take this handle to the perform state right away */ multistate(data, CURLM_STATE_PERFORM); Curl_attach_connnection(data, conn); k->keepon |= KEEP_RECV; /* setup to receive! */ } return rc; } /* * do_complete is called when the DO actions are complete. * * We init chunking and trailer bits to their default values here immediately * before receiving any header data for the current request. */ static void do_complete(struct connectdata *conn) { conn->data->req.chunk = FALSE; Curl_pgrsTime(conn->data, TIMER_PRETRANSFER); } static CURLcode multi_do(struct Curl_easy *data, bool *done) { CURLcode result = CURLE_OK; struct connectdata *conn = data->conn; DEBUGASSERT(conn); DEBUGASSERT(conn->handler); if(conn->handler->do_it) { /* generic protocol-specific function pointer set in curl_connect() */ result = conn->handler->do_it(conn, done); if(!result && *done) /* do_complete must be called after the protocol-specific DO function */ do_complete(conn); } return result; } /* * multi_do_more() is called during the DO_MORE multi state. It is basically a * second stage DO state which (wrongly) was introduced to support FTP's * second connection. * * 'complete' can return 0 for incomplete, 1 for done and -1 for go back to * DOING state there's more work to do! */ static CURLcode multi_do_more(struct connectdata *conn, int *complete) { CURLcode result = CURLE_OK; *complete = 0; if(conn->handler->do_more) result = conn->handler->do_more(conn, complete); if(!result && (*complete == 1)) /* do_complete must be called after the protocol-specific DO function */ do_complete(conn); return result; } /* * We are doing protocol-specific connecting and this is being called over and * over from the multi interface until the connection phase is done on * protocol layer. */ static CURLcode protocol_connecting(struct connectdata *conn, bool *done) { CURLcode result = CURLE_OK; if(conn && conn->handler->connecting) { *done = FALSE; result = conn->handler->connecting(conn, done); } else *done = TRUE; return result; } /* * We are DOING this is being called over and over from the multi interface * until the DOING phase is done on protocol layer. */ static CURLcode protocol_doing(struct connectdata *conn, bool *done) { CURLcode result = CURLE_OK; if(conn && conn->handler->doing) { *done = FALSE; result = conn->handler->doing(conn, done); } else *done = TRUE; return result; } /* * We have discovered that the TCP connection has been successful, we can now * proceed with some action. * */ static CURLcode protocol_connect(struct connectdata *conn, bool *protocol_done) { CURLcode result = CURLE_OK; DEBUGASSERT(conn); DEBUGASSERT(protocol_done); *protocol_done = FALSE; if(conn->bits.tcpconnect[FIRSTSOCKET] && conn->bits.protoconnstart) { /* We already are connected, get back. This may happen when the connect worked fine in the first call, like when we connect to a local server or proxy. Note that we don't know if the protocol is actually done. Unless this protocol doesn't have any protocol-connect callback, as then we know we're done. */ if(!conn->handler->connecting) *protocol_done = TRUE; return CURLE_OK; } if(!conn->bits.protoconnstart) { result = Curl_proxy_connect(conn, FIRSTSOCKET); if(result) return result; if(CONNECT_FIRSTSOCKET_PROXY_SSL()) /* wait for HTTPS proxy SSL initialization to complete */ return CURLE_OK; if(conn->bits.tunnel_proxy && conn->bits.httpproxy && Curl_connect_ongoing(conn)) /* when using an HTTP tunnel proxy, await complete tunnel establishment before proceeding further. Return CURLE_OK so we'll be called again */ return CURLE_OK; if(conn->handler->connect_it) { /* is there a protocol-specific connect() procedure? */ /* Call the protocol-specific connect function */ result = conn->handler->connect_it(conn, protocol_done); } else *protocol_done = TRUE; /* it has started, possibly even completed but that knowledge isn't stored in this bit! */ if(!result) conn->bits.protoconnstart = TRUE; } return result; /* pass back status */ } static CURLMcode multi_runsingle(struct Curl_multi *multi, struct curltime now, struct Curl_easy *data) { struct Curl_message *msg = NULL; bool connected; bool async; bool protocol_connected = FALSE; bool dophase_done = FALSE; bool done = FALSE; CURLMcode rc; CURLcode result = CURLE_OK; timediff_t timeout_ms; timediff_t recv_timeout_ms; timediff_t send_timeout_ms; int control; if(!GOOD_EASY_HANDLE(data)) return CURLM_BAD_EASY_HANDLE; do { /* A "stream" here is a logical stream if the protocol can handle that (HTTP/2), or the full connection for older protocols */ bool stream_error = FALSE; rc = CURLM_OK; DEBUGASSERT((data->mstate <= CURLM_STATE_CONNECT) || (data->mstate >= CURLM_STATE_DONE) || data->conn); if(!data->conn && data->mstate > CURLM_STATE_CONNECT && data->mstate < CURLM_STATE_DONE) { /* In all these states, the code will blindly access 'data->conn' so this is precaution that it isn't NULL. And it silences static analyzers. */ failf(data, "In state %d with no conn, bail out!\n", data->mstate); return CURLM_INTERNAL_ERROR; } if(multi_ischanged(multi, TRUE)) { DEBUGF(infof(data, "multi changed, check CONNECT_PEND queue!\n")); process_pending_handles(multi); /* multiplexed */ } if(data->conn && data->mstate > CURLM_STATE_CONNECT && data->mstate < CURLM_STATE_COMPLETED) { /* Make sure we set the connection's current owner */ data->conn->data = data; } if(data->conn && (data->mstate >= CURLM_STATE_CONNECT) && (data->mstate < CURLM_STATE_COMPLETED)) { /* we need to wait for the connect state as only then is the start time stored, but we must not check already completed handles */ timeout_ms = Curl_timeleft(data, &now, (data->mstate <= CURLM_STATE_DO)? TRUE:FALSE); if(timeout_ms < 0) { /* Handle timed out */ if(data->mstate == CURLM_STATE_WAITRESOLVE) failf(data, "Resolving timed out after %" CURL_FORMAT_TIMEDIFF_T " milliseconds", Curl_timediff(now, data->progress.t_startsingle)); else if(data->mstate == CURLM_STATE_WAITCONNECT) failf(data, "Connection timed out after %" CURL_FORMAT_TIMEDIFF_T " milliseconds", Curl_timediff(now, data->progress.t_startsingle)); else { struct SingleRequest *k = &data->req; if(k->size != -1) { failf(data, "Operation timed out after %" CURL_FORMAT_TIMEDIFF_T " milliseconds with %" CURL_FORMAT_CURL_OFF_T " out of %" CURL_FORMAT_CURL_OFF_T " bytes received", Curl_timediff(now, data->progress.t_startsingle), k->bytecount, k->size); } else { failf(data, "Operation timed out after %" CURL_FORMAT_TIMEDIFF_T " milliseconds with %" CURL_FORMAT_CURL_OFF_T " bytes received", Curl_timediff(now, data->progress.t_startsingle), k->bytecount); } } /* Force connection closed if the connection has indeed been used */ if(data->mstate > CURLM_STATE_DO) { streamclose(data->conn, "Disconnected with pending data"); stream_error = TRUE; } result = CURLE_OPERATION_TIMEDOUT; (void)multi_done(data, result, TRUE); /* Skip the statemachine and go directly to error handling section. */ goto statemachine_end; } } switch(data->mstate) { case CURLM_STATE_INIT: /* init this transfer. */ result = Curl_pretransfer(data); if(!result) { /* after init, go CONNECT */ multistate(data, CURLM_STATE_CONNECT); Curl_pgrsTime(data, TIMER_STARTOP); rc = CURLM_CALL_MULTI_PERFORM; } break; case CURLM_STATE_CONNECT_PEND: /* We will stay here until there is a connection available. Then we try again in the CURLM_STATE_CONNECT state. */ break; case CURLM_STATE_CONNECT: /* Connect. We want to get a connection identifier filled in. */ Curl_pgrsTime(data, TIMER_STARTSINGLE); if(data->set.timeout) Curl_expire(data, data->set.timeout, EXPIRE_TIMEOUT); if(data->set.connecttimeout) Curl_expire(data, data->set.connecttimeout, EXPIRE_CONNECTTIMEOUT); result = Curl_connect(data, &async, &protocol_connected); if(CURLE_NO_CONNECTION_AVAILABLE == result) { /* There was no connection available. We will go to the pending state and wait for an available connection. */ multistate(data, CURLM_STATE_CONNECT_PEND); /* add this handle to the list of connect-pending handles */ Curl_llist_insert_next(&multi->pending, multi->pending.tail, data, &data->connect_queue); result = CURLE_OK; break; } else if(data->state.previouslypending) { /* this transfer comes from the pending queue so try move another */ infof(data, "Transfer was pending, now try another\n"); process_pending_handles(data->multi); } if(!result) { if(async) /* We're now waiting for an asynchronous name lookup */ multistate(data, CURLM_STATE_WAITRESOLVE); else { /* after the connect has been sent off, go WAITCONNECT unless the protocol connect is already done and we can go directly to WAITDO or DO! */ rc = CURLM_CALL_MULTI_PERFORM; if(protocol_connected) multistate(data, CURLM_STATE_DO); else { #ifndef CURL_DISABLE_HTTP if(Curl_connect_ongoing(data->conn)) multistate(data, CURLM_STATE_WAITPROXYCONNECT); else #endif multistate(data, CURLM_STATE_WAITCONNECT); } } } break; case CURLM_STATE_WAITRESOLVE: /* awaiting an asynch name resolve to complete */ { struct Curl_dns_entry *dns = NULL; struct connectdata *conn = data->conn; const char *hostname; DEBUGASSERT(conn); if(conn->bits.httpproxy) hostname = conn->http_proxy.host.name; else if(conn->bits.conn_to_host) hostname = conn->conn_to_host.name; else hostname = conn->host.name; /* check if we have the name resolved by now */ dns = Curl_fetch_addr(conn, hostname, (int)conn->port); if(dns) { #ifdef CURLRES_ASYNCH conn->async.dns = dns; conn->async.done = TRUE; #endif result = CURLE_OK; infof(data, "Hostname '%s' was found in DNS cache\n", hostname); } if(!dns) result = Curl_resolv_check(data->conn, &dns); /* Update sockets here, because the socket(s) may have been closed and the application thus needs to be told, even if it is likely that the same socket(s) will again be used further down. If the name has not yet been resolved, it is likely that new sockets have been opened in an attempt to contact another resolver. */ singlesocket(multi, data); if(dns) { /* Perform the next step in the connection phase, and then move on to the WAITCONNECT state */ result = Curl_once_resolved(data->conn, &protocol_connected); if(result) /* if Curl_once_resolved() returns failure, the connection struct is already freed and gone */ data->conn = NULL; /* no more connection */ else { /* call again please so that we get the next socket setup */ rc = CURLM_CALL_MULTI_PERFORM; if(protocol_connected) multistate(data, CURLM_STATE_DO); else { #ifndef CURL_DISABLE_HTTP if(Curl_connect_ongoing(data->conn)) multistate(data, CURLM_STATE_WAITPROXYCONNECT); else #endif multistate(data, CURLM_STATE_WAITCONNECT); } } } if(result) { /* failure detected */ stream_error = TRUE; break; } } break; #ifndef CURL_DISABLE_HTTP case CURLM_STATE_WAITPROXYCONNECT: /* this is HTTP-specific, but sending CONNECT to a proxy is HTTP... */ DEBUGASSERT(data->conn); result = Curl_http_connect(data->conn, &protocol_connected); if(data->conn->bits.proxy_connect_closed) { rc = CURLM_CALL_MULTI_PERFORM; /* connect back to proxy again */ result = CURLE_OK; multi_done(data, CURLE_OK, FALSE); multistate(data, CURLM_STATE_CONNECT); } else if(!result) { if((data->conn->http_proxy.proxytype != CURLPROXY_HTTPS || data->conn->bits.proxy_ssl_connected[FIRSTSOCKET]) && Curl_connect_complete(data->conn)) { rc = CURLM_CALL_MULTI_PERFORM; /* initiate protocol connect phase */ multistate(data, CURLM_STATE_SENDPROTOCONNECT); } } else if(result) stream_error = TRUE; break; #endif case CURLM_STATE_WAITCONNECT: /* awaiting a completion of an asynch TCP connect */ DEBUGASSERT(data->conn); result = Curl_is_connected(data->conn, FIRSTSOCKET, &connected); if(connected && !result) { #ifndef CURL_DISABLE_HTTP if((data->conn->http_proxy.proxytype == CURLPROXY_HTTPS && !data->conn->bits.proxy_ssl_connected[FIRSTSOCKET]) || Curl_connect_ongoing(data->conn)) { multistate(data, CURLM_STATE_WAITPROXYCONNECT); break; } #endif rc = CURLM_CALL_MULTI_PERFORM; multistate(data, data->conn->bits.tunnel_proxy? CURLM_STATE_WAITPROXYCONNECT: CURLM_STATE_SENDPROTOCONNECT); } else if(result) { /* failure detected */ Curl_posttransfer(data); multi_done(data, result, TRUE); stream_error = TRUE; break; } break; case CURLM_STATE_SENDPROTOCONNECT: result = protocol_connect(data->conn, &protocol_connected); if(!result && !protocol_connected) /* switch to waiting state */ multistate(data, CURLM_STATE_PROTOCONNECT); else if(!result) { /* protocol connect has completed, go WAITDO or DO */ multistate(data, CURLM_STATE_DO); rc = CURLM_CALL_MULTI_PERFORM; } else if(result) { /* failure detected */ Curl_posttransfer(data); multi_done(data, result, TRUE); stream_error = TRUE; } break; case CURLM_STATE_PROTOCONNECT: /* protocol-specific connect phase */ result = protocol_connecting(data->conn, &protocol_connected); if(!result && protocol_connected) { /* after the connect has completed, go WAITDO or DO */ multistate(data, CURLM_STATE_DO); rc = CURLM_CALL_MULTI_PERFORM; } else if(result) { /* failure detected */ Curl_posttransfer(data); multi_done(data, result, TRUE); stream_error = TRUE; } break; case CURLM_STATE_DO: if(data->set.connect_only) { /* keep connection open for application to use the socket */ connkeep(data->conn, "CONNECT_ONLY"); multistate(data, CURLM_STATE_DONE); result = CURLE_OK; rc = CURLM_CALL_MULTI_PERFORM; } else { /* Perform the protocol's DO action */ result = multi_do(data, &dophase_done); /* When multi_do() returns failure, data->conn might be NULL! */ if(!result) { if(!dophase_done) { #ifndef CURL_DISABLE_FTP /* some steps needed for wildcard matching */ if(data->state.wildcardmatch) { struct WildcardData *wc = &data->wildcard; if(wc->state == CURLWC_DONE || wc->state == CURLWC_SKIP) { /* skip some states if it is important */ multi_done(data, CURLE_OK, FALSE); multistate(data, CURLM_STATE_DONE); rc = CURLM_CALL_MULTI_PERFORM; break; } } #endif /* DO was not completed in one function call, we must continue DOING... */ multistate(data, CURLM_STATE_DOING); rc = CURLM_OK; } /* after DO, go DO_DONE... or DO_MORE */ else if(data->conn->bits.do_more) { /* we're supposed to do more, but we need to sit down, relax and wait a little while first */ multistate(data, CURLM_STATE_DO_MORE); rc = CURLM_OK; } else { /* we're done with the DO, now DO_DONE */ multistate(data, CURLM_STATE_DO_DONE); rc = CURLM_CALL_MULTI_PERFORM; } } else if((CURLE_SEND_ERROR == result) && data->conn->bits.reuse) { /* * In this situation, a connection that we were trying to use * may have unexpectedly died. If possible, send the connection * back to the CONNECT phase so we can try again. */ char *newurl = NULL; followtype follow = FOLLOW_NONE; CURLcode drc; drc = Curl_retry_request(data->conn, &newurl); if(drc) { /* a failure here pretty much implies an out of memory */ result = drc; stream_error = TRUE; } Curl_posttransfer(data); drc = multi_done(data, result, FALSE); /* When set to retry the connection, we must to go back to * the CONNECT state */ if(newurl) { if(!drc || (drc == CURLE_SEND_ERROR)) { follow = FOLLOW_RETRY; drc = Curl_follow(data, newurl, follow); if(!drc) { multistate(data, CURLM_STATE_CONNECT); rc = CURLM_CALL_MULTI_PERFORM; result = CURLE_OK; } else { /* Follow failed */ result = drc; } } else { /* done didn't return OK or SEND_ERROR */ result = drc; } } else { /* Have error handler disconnect conn if we can't retry */ stream_error = TRUE; } free(newurl); } else { /* failure detected */ Curl_posttransfer(data); if(data->conn) multi_done(data, result, FALSE); stream_error = TRUE; } } break; case CURLM_STATE_DOING: /* we continue DOING until the DO phase is complete */ DEBUGASSERT(data->conn); result = protocol_doing(data->conn, &dophase_done); if(!result) { if(dophase_done) { /* after DO, go DO_DONE or DO_MORE */ multistate(data, data->conn->bits.do_more? CURLM_STATE_DO_MORE: CURLM_STATE_DO_DONE); rc = CURLM_CALL_MULTI_PERFORM; } /* dophase_done */ } else { /* failure detected */ Curl_posttransfer(data); multi_done(data, result, FALSE); stream_error = TRUE; } break; case CURLM_STATE_DO_MORE: /* * When we are connected, DO MORE and then go DO_DONE */ DEBUGASSERT(data->conn); result = multi_do_more(data->conn, &control); if(!result) { if(control) { /* if positive, advance to DO_DONE if negative, go back to DOING */ multistate(data, control == 1? CURLM_STATE_DO_DONE: CURLM_STATE_DOING); rc = CURLM_CALL_MULTI_PERFORM; } else /* stay in DO_MORE */ rc = CURLM_OK; } else { /* failure detected */ Curl_posttransfer(data); multi_done(data, result, FALSE); stream_error = TRUE; } break; case CURLM_STATE_DO_DONE: DEBUGASSERT(data->conn); if(data->conn->bits.multiplex) /* Check if we can move pending requests to send pipe */ process_pending_handles(multi); /* multiplexed */ /* Only perform the transfer if there's a good socket to work with. Having both BAD is a signal to skip immediately to DONE */ if((data->conn->sockfd != CURL_SOCKET_BAD) || (data->conn->writesockfd != CURL_SOCKET_BAD)) multistate(data, CURLM_STATE_PERFORM); else { #ifndef CURL_DISABLE_FTP if(data->state.wildcardmatch && ((data->conn->handler->flags & PROTOPT_WILDCARD) == 0)) { data->wildcard.state = CURLWC_DONE; } #endif multistate(data, CURLM_STATE_DONE); } rc = CURLM_CALL_MULTI_PERFORM; break; case CURLM_STATE_TOOFAST: /* limit-rate exceeded in either direction */ DEBUGASSERT(data->conn); /* if both rates are within spec, resume transfer */ if(Curl_pgrsUpdate(data->conn)) result = CURLE_ABORTED_BY_CALLBACK; else result = Curl_speedcheck(data, now); if(!result) { send_timeout_ms = 0; if(data->set.max_send_speed > 0) send_timeout_ms = Curl_pgrsLimitWaitTime(data->progress.uploaded, data->progress.ul_limit_size, data->set.max_send_speed, data->progress.ul_limit_start, now); recv_timeout_ms = 0; if(data->set.max_recv_speed > 0) recv_timeout_ms = Curl_pgrsLimitWaitTime(data->progress.downloaded, data->progress.dl_limit_size, data->set.max_recv_speed, data->progress.dl_limit_start, now); if(!send_timeout_ms && !recv_timeout_ms) { multistate(data, CURLM_STATE_PERFORM); Curl_ratelimit(data, now); } else if(send_timeout_ms >= recv_timeout_ms) Curl_expire(data, send_timeout_ms, EXPIRE_TOOFAST); else Curl_expire(data, recv_timeout_ms, EXPIRE_TOOFAST); } break; case CURLM_STATE_PERFORM: { char *newurl = NULL; bool retry = FALSE; bool comeback = FALSE; /* check if over send speed */ send_timeout_ms = 0; if(data->set.max_send_speed > 0) send_timeout_ms = Curl_pgrsLimitWaitTime(data->progress.uploaded, data->progress.ul_limit_size, data->set.max_send_speed, data->progress.ul_limit_start, now); /* check if over recv speed */ recv_timeout_ms = 0; if(data->set.max_recv_speed > 0) recv_timeout_ms = Curl_pgrsLimitWaitTime(data->progress.downloaded, data->progress.dl_limit_size, data->set.max_recv_speed, data->progress.dl_limit_start, now); if(send_timeout_ms || recv_timeout_ms) { Curl_ratelimit(data, now); multistate(data, CURLM_STATE_TOOFAST); if(send_timeout_ms >= recv_timeout_ms) Curl_expire(data, send_timeout_ms, EXPIRE_TOOFAST); else Curl_expire(data, recv_timeout_ms, EXPIRE_TOOFAST); break; } /* read/write data if it is ready to do so */ result = Curl_readwrite(data->conn, data, &done, &comeback); if(done || (result == CURLE_RECV_ERROR)) { /* If CURLE_RECV_ERROR happens early enough, we assume it was a race * condition and the server closed the re-used connection exactly when * we wanted to use it, so figure out if that is indeed the case. */ CURLcode ret = Curl_retry_request(data->conn, &newurl); if(!ret) retry = (newurl)?TRUE:FALSE; else if(!result) result = ret; if(retry) { /* if we are to retry, set the result to OK and consider the request as done */ result = CURLE_OK; done = TRUE; } } else if((CURLE_HTTP2_STREAM == result) && Curl_h2_http_1_1_error(data->conn)) { CURLcode ret = Curl_retry_request(data->conn, &newurl); if(!ret) { infof(data, "Downgrades to HTTP/1.1!\n"); data->set.httpversion = CURL_HTTP_VERSION_1_1; /* clear the error message bit too as we ignore the one we got */ data->state.errorbuf = FALSE; if(!newurl) /* typically for HTTP_1_1_REQUIRED error on first flight */ newurl = strdup(data->change.url); /* if we are to retry, set the result to OK and consider the request as done */ retry = TRUE; result = CURLE_OK; done = TRUE; } else result = ret; } if(result) { /* * The transfer phase returned error, we mark the connection to get * closed to prevent being re-used. This is because we can't possibly * know if the connection is in a good shape or not now. Unless it is * a protocol which uses two "channels" like FTP, as then the error * happened in the data connection. */ if(!(data->conn->handler->flags & PROTOPT_DUAL) && result != CURLE_HTTP2_STREAM) streamclose(data->conn, "Transfer returned error"); Curl_posttransfer(data); multi_done(data, result, TRUE); } else if(done) { followtype follow = FOLLOW_NONE; /* call this even if the readwrite function returned error */ Curl_posttransfer(data); /* When we follow redirects or is set to retry the connection, we must to go back to the CONNECT state */ if(data->req.newurl || retry) { if(!retry) { /* if the URL is a follow-location and not just a retried request then figure out the URL here */ free(newurl); newurl = data->req.newurl; data->req.newurl = NULL; follow = FOLLOW_REDIR; } else follow = FOLLOW_RETRY; (void)multi_done(data, CURLE_OK, FALSE); /* multi_done() might return CURLE_GOT_NOTHING */ result = Curl_follow(data, newurl, follow); if(!result) { multistate(data, CURLM_STATE_CONNECT); rc = CURLM_CALL_MULTI_PERFORM; } free(newurl); } else { /* after the transfer is done, go DONE */ /* but first check to see if we got a location info even though we're not following redirects */ if(data->req.location) { free(newurl); newurl = data->req.location; data->req.location = NULL; result = Curl_follow(data, newurl, FOLLOW_FAKE); free(newurl); if(result) { stream_error = TRUE; result = multi_done(data, result, TRUE); } } if(!result) { multistate(data, CURLM_STATE_DONE); rc = CURLM_CALL_MULTI_PERFORM; } } } else if(comeback) rc = CURLM_CALL_MULTI_PERFORM; break; } case CURLM_STATE_DONE: /* this state is highly transient, so run another loop after this */ rc = CURLM_CALL_MULTI_PERFORM; if(data->conn) { CURLcode res; if(data->conn->bits.multiplex) /* Check if we can move pending requests to connection */ process_pending_handles(multi); /* multiplexing */ /* post-transfer command */ res = multi_done(data, result, FALSE); /* allow a previously set error code take precedence */ if(!result) result = res; /* * If there are other handles on the connection, multi_done won't set * conn to NULL. In such a case, curl_multi_remove_handle() can * access free'd data, if the connection is free'd and the handle * removed before we perform the processing in CURLM_STATE_COMPLETED */ if(data->conn) detach_connnection(data); } #ifndef CURL_DISABLE_FTP if(data->state.wildcardmatch) { if(data->wildcard.state != CURLWC_DONE) { /* if a wildcard is set and we are not ending -> lets start again with CURLM_STATE_INIT */ multistate(data, CURLM_STATE_INIT); break; } } #endif /* after we have DONE what we're supposed to do, go COMPLETED, and it doesn't matter what the multi_done() returned! */ multistate(data, CURLM_STATE_COMPLETED); break; case CURLM_STATE_COMPLETED: break; case CURLM_STATE_MSGSENT: data->result = result; return CURLM_OK; /* do nothing */ default: return CURLM_INTERNAL_ERROR; } statemachine_end: if(data->mstate < CURLM_STATE_COMPLETED) { if(result) { /* * If an error was returned, and we aren't in completed state now, * then we go to completed and consider this transfer aborted. */ /* NOTE: no attempt to disconnect connections must be made in the case blocks above - cleanup happens only here */ /* Check if we can move pending requests to send pipe */ process_pending_handles(multi); /* connection */ if(data->conn) { if(stream_error) { /* Don't attempt to send data over a connection that timed out */ bool dead_connection = result == CURLE_OPERATION_TIMEDOUT; struct connectdata *conn = data->conn; /* This is where we make sure that the conn pointer is reset. We don't have to do this in every case block above where a failure is detected */ detach_connnection(data); /* disconnect properly */ Curl_disconnect(data, conn, dead_connection); } } else if(data->mstate == CURLM_STATE_CONNECT) { /* Curl_connect() failed */ (void)Curl_posttransfer(data); } multistate(data, CURLM_STATE_COMPLETED); rc = CURLM_CALL_MULTI_PERFORM; } /* if there's still a connection to use, call the progress function */ else if(data->conn && Curl_pgrsUpdate(data->conn)) { /* aborted due to progress callback return code must close the connection */ result = CURLE_ABORTED_BY_CALLBACK; streamclose(data->conn, "Aborted by callback"); /* if not yet in DONE state, go there, otherwise COMPLETED */ multistate(data, (data->mstate < CURLM_STATE_DONE)? CURLM_STATE_DONE: CURLM_STATE_COMPLETED); rc = CURLM_CALL_MULTI_PERFORM; } } if(CURLM_STATE_COMPLETED == data->mstate) { if(data->set.fmultidone) { /* signal via callback instead */ data->set.fmultidone(data, result); } else { /* now fill in the Curl_message with this info */ msg = &data->msg; msg->extmsg.msg = CURLMSG_DONE; msg->extmsg.easy_handle = data; msg->extmsg.data.result = result; rc = multi_addmsg(multi, msg); DEBUGASSERT(!data->conn); } multistate(data, CURLM_STATE_MSGSENT); } } while((rc == CURLM_CALL_MULTI_PERFORM) || multi_ischanged(multi, FALSE)); data->result = result; return rc; } CURLMcode curl_multi_perform(struct Curl_multi *multi, int *running_handles) { struct Curl_easy *data; CURLMcode returncode = CURLM_OK; struct Curl_tree *t; struct curltime now = Curl_now(); if(!GOOD_MULTI_HANDLE(multi)) return CURLM_BAD_HANDLE; if(multi->in_callback) return CURLM_RECURSIVE_API_CALL; data = multi->easyp; while(data) { CURLMcode result; SIGPIPE_VARIABLE(pipe_st); sigpipe_ignore(data, &pipe_st); result = multi_runsingle(multi, now, data); sigpipe_restore(&pipe_st); if(result) returncode = result; data = data->next; /* operate on next handle */ } /* * Simply remove all expired timers from the splay since handles are dealt * with unconditionally by this function and curl_multi_timeout() requires * that already passed/handled expire times are removed from the splay. * * It is important that the 'now' value is set at the entry of this function * and not for the current time as it may have ticked a little while since * then and then we risk this loop to remove timers that actually have not * been handled! */ do { multi->timetree = Curl_splaygetbest(now, multi->timetree, &t); if(t) /* the removed may have another timeout in queue */ (void)add_next_timeout(now, multi, t->payload); } while(t); *running_handles = multi->num_alive; if(CURLM_OK >= returncode) Curl_update_timer(multi); return returncode; } CURLMcode curl_multi_cleanup(struct Curl_multi *multi) { struct Curl_easy *data; struct Curl_easy *nextdata; if(GOOD_MULTI_HANDLE(multi)) { if(multi->in_callback) return CURLM_RECURSIVE_API_CALL; multi->type = 0; /* not good anymore */ /* Firsrt remove all remaining easy handles */ data = multi->easyp; while(data) { nextdata = data->next; if(!data->state.done && data->conn) /* if DONE was never called for this handle */ (void)multi_done(data, CURLE_OK, TRUE); if(data->dns.hostcachetype == HCACHE_MULTI) { /* clear out the usage of the shared DNS cache */ Curl_hostcache_clean(data, data->dns.hostcache); data->dns.hostcache = NULL; data->dns.hostcachetype = HCACHE_NONE; } /* Clear the pointer to the connection cache */ data->state.conn_cache = NULL; data->multi = NULL; /* clear the association */ #ifdef USE_LIBPSL if(data->psl == &multi->psl) data->psl = NULL; #endif data = nextdata; } /* Close all the connections in the connection cache */ Curl_conncache_close_all_connections(&multi->conn_cache); Curl_hash_destroy(&multi->sockhash); Curl_conncache_destroy(&multi->conn_cache); Curl_llist_destroy(&multi->msglist, NULL); Curl_llist_destroy(&multi->pending, NULL); Curl_hash_destroy(&multi->hostcache); Curl_psl_destroy(&multi->psl); free(multi); return CURLM_OK; } return CURLM_BAD_HANDLE; } /* * curl_multi_info_read() * * This function is the primary way for a multi/multi_socket application to * figure out if a transfer has ended. We MUST make this function as fast as * possible as it will be polled frequently and we MUST NOT scan any lists in * here to figure out things. We must scale fine to thousands of handles and * beyond. The current design is fully O(1). */ CURLMsg *curl_multi_info_read(struct Curl_multi *multi, int *msgs_in_queue) { struct Curl_message *msg; *msgs_in_queue = 0; /* default to none */ if(GOOD_MULTI_HANDLE(multi) && !multi->in_callback && Curl_llist_count(&multi->msglist)) { /* there is one or more messages in the list */ struct curl_llist_element *e; /* extract the head of the list to return */ e = multi->msglist.head; msg = e->ptr; /* remove the extracted entry */ Curl_llist_remove(&multi->msglist, e, NULL); *msgs_in_queue = curlx_uztosi(Curl_llist_count(&multi->msglist)); return &msg->extmsg; } return NULL; } /* * singlesocket() checks what sockets we deal with and their "action state" * and if we have a different state in any of those sockets from last time we * call the callback accordingly. */ static CURLMcode singlesocket(struct Curl_multi *multi, struct Curl_easy *data) { curl_socket_t socks[MAX_SOCKSPEREASYHANDLE]; int i; struct Curl_sh_entry *entry; curl_socket_t s; int num; unsigned int curraction; int actions[MAX_SOCKSPEREASYHANDLE]; for(i = 0; i< MAX_SOCKSPEREASYHANDLE; i++) socks[i] = CURL_SOCKET_BAD; /* Fill in the 'current' struct with the state as it is now: what sockets to supervise and for what actions */ curraction = multi_getsock(data, socks); /* We have 0 .. N sockets already and we get to know about the 0 .. M sockets we should have from now on. Detect the differences, remove no longer supervised ones and add new ones */ /* walk over the sockets we got right now */ for(i = 0; (i< MAX_SOCKSPEREASYHANDLE) && (curraction & (GETSOCK_READSOCK(i) | GETSOCK_WRITESOCK(i))); i++) { unsigned int action = CURL_POLL_NONE; unsigned int prevaction = 0; unsigned int comboaction; bool sincebefore = FALSE; s = socks[i]; /* get it from the hash */ entry = sh_getentry(&multi->sockhash, s); if(curraction & GETSOCK_READSOCK(i)) action |= CURL_POLL_IN; if(curraction & GETSOCK_WRITESOCK(i)) action |= CURL_POLL_OUT; actions[i] = action; if(entry) { /* check if new for this transfer */ int j; for(j = 0; j< data->numsocks; j++) { if(s == data->sockets[j]) { prevaction = data->actions[j]; sincebefore = TRUE; break; } } } else { /* this is a socket we didn't have before, add it to the hash! */ entry = sh_addentry(&multi->sockhash, s); if(!entry) /* fatal */ return CURLM_OUT_OF_MEMORY; } if(sincebefore && (prevaction != action)) { /* Socket was used already, but different action now */ if(prevaction & CURL_POLL_IN) entry->readers--; if(prevaction & CURL_POLL_OUT) entry->writers--; if(action & CURL_POLL_IN) entry->readers++; if(action & CURL_POLL_OUT) entry->writers++; } else if(!sincebefore) { /* a new user */ entry->users++; if(action & CURL_POLL_IN) entry->readers++; if(action & CURL_POLL_OUT) entry->writers++; /* add 'data' to the transfer hash on this socket! */ if(!Curl_hash_add(&entry->transfers, (char *)&data, /* hash key */ sizeof(struct Curl_easy *), data)) return CURLM_OUT_OF_MEMORY; } comboaction = (entry->writers? CURL_POLL_OUT : 0) | (entry->readers ? CURL_POLL_IN : 0); /* socket existed before and has the same action set as before */ if(sincebefore && (entry->action == comboaction)) /* same, continue */ continue; if(multi->socket_cb) multi->socket_cb(data, s, comboaction, multi->socket_userp, entry->socketp); entry->action = comboaction; /* store the current action state */ } num = i; /* number of sockets */ /* when we've walked over all the sockets we should have right now, we must make sure to detect sockets that are removed */ for(i = 0; i< data->numsocks; i++) { int j; bool stillused = FALSE; s = data->sockets[i]; for(j = 0; j < num; j++) { if(s == socks[j]) { /* this is still supervised */ stillused = TRUE; break; } } if(stillused) continue; entry = sh_getentry(&multi->sockhash, s); /* if this is NULL here, the socket has been closed and notified so already by Curl_multi_closed() */ if(entry) { int oldactions = data->actions[i]; /* this socket has been removed. Decrease user count */ entry->users--; if(oldactions & CURL_POLL_OUT) entry->writers--; if(oldactions & CURL_POLL_IN) entry->readers--; if(!entry->users) { if(multi->socket_cb) multi->socket_cb(data, s, CURL_POLL_REMOVE, multi->socket_userp, entry->socketp); sh_delentry(entry, &multi->sockhash, s); } else { /* still users, but remove this handle as a user of this socket */ if(Curl_hash_delete(&entry->transfers, (char *)&data, sizeof(struct Curl_easy *))) { DEBUGASSERT(NULL); } } } } /* for loop over numsocks */ memcpy(data->sockets, socks, num*sizeof(curl_socket_t)); memcpy(data->actions, actions, num*sizeof(int)); data->numsocks = num; return CURLM_OK; } void Curl_updatesocket(struct Curl_easy *data) { singlesocket(data->multi, data); } /* * Curl_multi_closed() * * Used by the connect code to tell the multi_socket code that one of the * sockets we were using is about to be closed. This function will then * remove it from the sockethash for this handle to make the multi_socket API * behave properly, especially for the case when libcurl will create another * socket again and it gets the same file descriptor number. */ void Curl_multi_closed(struct Curl_easy *data, curl_socket_t s) { if(data) { /* if there's still an easy handle associated with this connection */ struct Curl_multi *multi = data->multi; if(multi) { /* this is set if this connection is part of a handle that is added to a multi handle, and only then this is necessary */ struct Curl_sh_entry *entry = sh_getentry(&multi->sockhash, s); if(entry) { if(multi->socket_cb) multi->socket_cb(data, s, CURL_POLL_REMOVE, multi->socket_userp, entry->socketp); /* now remove it from the socket hash */ sh_delentry(entry, &multi->sockhash, s); } } } } /* * add_next_timeout() * * Each Curl_easy has a list of timeouts. The add_next_timeout() is called * when it has just been removed from the splay tree because the timeout has * expired. This function is then to advance in the list to pick the next * timeout to use (skip the already expired ones) and add this node back to * the splay tree again. * * The splay tree only has each sessionhandle as a single node and the nearest * timeout is used to sort it on. */ static CURLMcode add_next_timeout(struct curltime now, struct Curl_multi *multi, struct Curl_easy *d) { struct curltime *tv = &d->state.expiretime; struct curl_llist *list = &d->state.timeoutlist; struct curl_llist_element *e; struct time_node *node = NULL; /* move over the timeout list for this specific handle and remove all timeouts that are now passed tense and store the next pending timeout in *tv */ for(e = list->head; e;) { struct curl_llist_element *n = e->next; timediff_t diff; node = (struct time_node *)e->ptr; diff = Curl_timediff(node->time, now); if(diff <= 0) /* remove outdated entry */ Curl_llist_remove(list, e, NULL); else /* the list is sorted so get out on the first mismatch */ break; e = n; } e = list->head; if(!e) { /* clear the expire times within the handles that we remove from the splay tree */ tv->tv_sec = 0; tv->tv_usec = 0; } else { /* copy the first entry to 'tv' */ memcpy(tv, &node->time, sizeof(*tv)); /* Insert this node again into the splay. Keep the timer in the list in case we need to recompute future timers. */ multi->timetree = Curl_splayinsert(*tv, multi->timetree, &d->state.timenode); } return CURLM_OK; } static CURLMcode multi_socket(struct Curl_multi *multi, bool checkall, curl_socket_t s, int ev_bitmask, int *running_handles) { CURLMcode result = CURLM_OK; struct Curl_easy *data = NULL; struct Curl_tree *t; struct curltime now = Curl_now(); if(checkall) { /* *perform() deals with running_handles on its own */ result = curl_multi_perform(multi, running_handles); /* walk through each easy handle and do the socket state change magic and callbacks */ if(result != CURLM_BAD_HANDLE) { data = multi->easyp; while(data && !result) { result = singlesocket(multi, data); data = data->next; } } /* or should we fall-through and do the timer-based stuff? */ return result; } if(s != CURL_SOCKET_TIMEOUT) { struct Curl_sh_entry *entry = sh_getentry(&multi->sockhash, s); if(!entry) /* Unmatched socket, we can't act on it but we ignore this fact. In real-world tests it has been proved that libevent can in fact give the application actions even though the socket was just previously asked to get removed, so thus we better survive stray socket actions and just move on. */ ; else { struct curl_hash_iterator iter; struct curl_hash_element *he; /* the socket can be shared by many transfers, iterate */ Curl_hash_start_iterate(&entry->transfers, &iter); for(he = Curl_hash_next_element(&iter); he; he = Curl_hash_next_element(&iter)) { data = (struct Curl_easy *)he->ptr; DEBUGASSERT(data); DEBUGASSERT(data->magic == CURLEASY_MAGIC_NUMBER); if(data->conn && !(data->conn->handler->flags & PROTOPT_DIRLOCK)) /* set socket event bitmask if they're not locked */ data->conn->cselect_bits = ev_bitmask; Curl_expire(data, 0, EXPIRE_RUN_NOW); } /* Now we fall-through and do the timer-based stuff, since we don't want to force the user to have to deal with timeouts as long as at least one connection in fact has traffic. */ data = NULL; /* set data to NULL again to avoid calling multi_runsingle() in case there's no need to */ now = Curl_now(); /* get a newer time since the multi_runsingle() loop may have taken some time */ } } else { /* Asked to run due to time-out. Clear the 'lastcall' variable to force Curl_update_timer() to trigger a callback to the app again even if the same timeout is still the one to run after this call. That handles the case when the application asks libcurl to run the timeout prematurely. */ memset(&multi->timer_lastcall, 0, sizeof(multi->timer_lastcall)); } /* * The loop following here will go on as long as there are expire-times left * to process in the splay and 'data' will be re-assigned for every expired * handle we deal with. */ do { /* the first loop lap 'data' can be NULL */ if(data) { SIGPIPE_VARIABLE(pipe_st); sigpipe_ignore(data, &pipe_st); result = multi_runsingle(multi, now, data); sigpipe_restore(&pipe_st); if(CURLM_OK >= result) { /* get the socket(s) and check if the state has been changed since last */ result = singlesocket(multi, data); if(result) return result; } } /* Check if there's one (more) expired timer to deal with! This function extracts a matching node if there is one */ multi->timetree = Curl_splaygetbest(now, multi->timetree, &t); if(t) { data = t->payload; /* assign this for next loop */ (void)add_next_timeout(now, multi, t->payload); } } while(t); *running_handles = multi->num_alive; return result; } #undef curl_multi_setopt CURLMcode curl_multi_setopt(struct Curl_multi *multi, CURLMoption option, ...) { CURLMcode res = CURLM_OK; va_list param; if(!GOOD_MULTI_HANDLE(multi)) return CURLM_BAD_HANDLE; if(multi->in_callback) return CURLM_RECURSIVE_API_CALL; va_start(param, option); switch(option) { case CURLMOPT_SOCKETFUNCTION: multi->socket_cb = va_arg(param, curl_socket_callback); break; case CURLMOPT_SOCKETDATA: multi->socket_userp = va_arg(param, void *); break; case CURLMOPT_PUSHFUNCTION: multi->push_cb = va_arg(param, curl_push_callback); break; case CURLMOPT_PUSHDATA: multi->push_userp = va_arg(param, void *); break; case CURLMOPT_PIPELINING: multi->multiplexing = va_arg(param, long) & CURLPIPE_MULTIPLEX; break; case CURLMOPT_TIMERFUNCTION: multi->timer_cb = va_arg(param, curl_multi_timer_callback); break; case CURLMOPT_TIMERDATA: multi->timer_userp = va_arg(param, void *); break; case CURLMOPT_MAXCONNECTS: multi->maxconnects = va_arg(param, long); break; case CURLMOPT_MAX_HOST_CONNECTIONS: multi->max_host_connections = va_arg(param, long); break; case CURLMOPT_MAX_TOTAL_CONNECTIONS: multi->max_total_connections = va_arg(param, long); break; /* options formerly used for pipelining */ case CURLMOPT_MAX_PIPELINE_LENGTH: break; case CURLMOPT_CONTENT_LENGTH_PENALTY_SIZE: break; case CURLMOPT_CHUNK_LENGTH_PENALTY_SIZE: break; case CURLMOPT_PIPELINING_SITE_BL: break; case CURLMOPT_PIPELINING_SERVER_BL: break; default: res = CURLM_UNKNOWN_OPTION; break; } va_end(param); return res; } /* we define curl_multi_socket() in the public multi.h header */ #undef curl_multi_socket CURLMcode curl_multi_socket(struct Curl_multi *multi, curl_socket_t s, int *running_handles) { CURLMcode result; if(multi->in_callback) return CURLM_RECURSIVE_API_CALL; result = multi_socket(multi, FALSE, s, 0, running_handles); if(CURLM_OK >= result) Curl_update_timer(multi); return result; } CURLMcode curl_multi_socket_action(struct Curl_multi *multi, curl_socket_t s, int ev_bitmask, int *running_handles) { CURLMcode result; if(multi->in_callback) return CURLM_RECURSIVE_API_CALL; result = multi_socket(multi, FALSE, s, ev_bitmask, running_handles); if(CURLM_OK >= result) Curl_update_timer(multi); return result; } CURLMcode curl_multi_socket_all(struct Curl_multi *multi, int *running_handles) { CURLMcode result; if(multi->in_callback) return CURLM_RECURSIVE_API_CALL; result = multi_socket(multi, TRUE, CURL_SOCKET_BAD, 0, running_handles); if(CURLM_OK >= result) Curl_update_timer(multi); return result; } static CURLMcode multi_timeout(struct Curl_multi *multi, long *timeout_ms) { static struct curltime tv_zero = {0, 0}; if(multi->timetree) { /* we have a tree of expire times */ struct curltime now = Curl_now(); /* splay the lowest to the bottom */ multi->timetree = Curl_splay(tv_zero, multi->timetree); if(Curl_splaycomparekeys(multi->timetree->key, now) > 0) { /* some time left before expiration */ timediff_t diff = Curl_timediff(multi->timetree->key, now); if(diff <= 0) /* * Since we only provide millisecond resolution on the returned value * and the diff might be less than one millisecond here, we don't * return zero as that may cause short bursts of busyloops on fast * processors while the diff is still present but less than one * millisecond! instead we return 1 until the time is ripe. */ *timeout_ms = 1; else /* this should be safe even on 64 bit archs, as we don't use that overly long timeouts */ *timeout_ms = (long)diff; } else /* 0 means immediately */ *timeout_ms = 0; } else *timeout_ms = -1; return CURLM_OK; } CURLMcode curl_multi_timeout(struct Curl_multi *multi, long *timeout_ms) { /* First, make some basic checks that the CURLM handle is a good handle */ if(!GOOD_MULTI_HANDLE(multi)) return CURLM_BAD_HANDLE; if(multi->in_callback) return CURLM_RECURSIVE_API_CALL; return multi_timeout(multi, timeout_ms); } /* * Tell the application it should update its timers, if it subscribes to the * update timer callback. */ void Curl_update_timer(struct Curl_multi *multi) { long timeout_ms; if(!multi->timer_cb) return; if(multi_timeout(multi, &timeout_ms)) { return; } if(timeout_ms < 0) { static const struct curltime none = {0, 0}; if(Curl_splaycomparekeys(none, multi->timer_lastcall)) { multi->timer_lastcall = none; /* there's no timeout now but there was one previously, tell the app to disable it */ multi->timer_cb(multi, -1, multi->timer_userp); return; } return; } /* When multi_timeout() is done, multi->timetree points to the node with the * timeout we got the (relative) time-out time for. We can thus easily check * if this is the same (fixed) time as we got in a previous call and then * avoid calling the callback again. */ if(Curl_splaycomparekeys(multi->timetree->key, multi->timer_lastcall) == 0) return; multi->timer_lastcall = multi->timetree->key; multi->timer_cb(multi, timeout_ms, multi->timer_userp); } /* * multi_deltimeout() * * Remove a given timestamp from the list of timeouts. */ static void multi_deltimeout(struct Curl_easy *data, expire_id eid) { struct curl_llist_element *e; struct curl_llist *timeoutlist = &data->state.timeoutlist; /* find and remove the specific node from the list */ for(e = timeoutlist->head; e; e = e->next) { struct time_node *n = (struct time_node *)e->ptr; if(n->eid == eid) { Curl_llist_remove(timeoutlist, e, NULL); return; } } } /* * multi_addtimeout() * * Add a timestamp to the list of timeouts. Keep the list sorted so that head * of list is always the timeout nearest in time. * */ static CURLMcode multi_addtimeout(struct Curl_easy *data, struct curltime *stamp, expire_id eid) { struct curl_llist_element *e; struct time_node *node; struct curl_llist_element *prev = NULL; size_t n; struct curl_llist *timeoutlist = &data->state.timeoutlist; node = &data->state.expires[eid]; /* copy the timestamp and id */ memcpy(&node->time, stamp, sizeof(*stamp)); node->eid = eid; /* also marks it as in use */ n = Curl_llist_count(timeoutlist); if(n) { /* find the correct spot in the list */ for(e = timeoutlist->head; e; e = e->next) { struct time_node *check = (struct time_node *)e->ptr; timediff_t diff = Curl_timediff(check->time, node->time); if(diff > 0) break; prev = e; } } /* else this is the first timeout on the list */ Curl_llist_insert_next(timeoutlist, prev, node, &node->list); return CURLM_OK; } /* * Curl_expire() * * given a number of milliseconds from now to use to set the 'act before * this'-time for the transfer, to be extracted by curl_multi_timeout() * * The timeout will be added to a queue of timeouts if it defines a moment in * time that is later than the current head of queue. * * Expire replaces a former timeout using the same id if already set. */ void Curl_expire(struct Curl_easy *data, timediff_t milli, expire_id id) { struct Curl_multi *multi = data->multi; struct curltime *nowp = &data->state.expiretime; struct curltime set; /* this is only interesting while there is still an associated multi struct remaining! */ if(!multi) return; DEBUGASSERT(id < EXPIRE_LAST); set = Curl_now(); set.tv_sec += (time_t)(milli/1000); /* might be a 64 to 32 bit conversion */ set.tv_usec += (unsigned int)(milli%1000)*1000; if(set.tv_usec >= 1000000) { set.tv_sec++; set.tv_usec -= 1000000; } /* Remove any timer with the same id just in case. */ multi_deltimeout(data, id); /* Add it to the timer list. It must stay in the list until it has expired in case we need to recompute the minimum timer later. */ multi_addtimeout(data, &set, id); if(nowp->tv_sec || nowp->tv_usec) { /* This means that the struct is added as a node in the splay tree. Compare if the new time is earlier, and only remove-old/add-new if it is. */ timediff_t diff = Curl_timediff(set, *nowp); int rc; if(diff > 0) { /* The current splay tree entry is sooner than this new expiry time. We don't need to update our splay tree entry. */ return; } /* Since this is an updated time, we must remove the previous entry from the splay tree first and then re-add the new value */ rc = Curl_splayremovebyaddr(multi->timetree, &data->state.timenode, &multi->timetree); if(rc) infof(data, "Internal error removing splay node = %d\n", rc); } /* Indicate that we are in the splay tree and insert the new timer expiry value since it is our local minimum. */ *nowp = set; data->state.timenode.payload = data; multi->timetree = Curl_splayinsert(*nowp, multi->timetree, &data->state.timenode); } /* * Curl_expire_done() * * Removes the expire timer. Marks it as done. * */ void Curl_expire_done(struct Curl_easy *data, expire_id id) { /* remove the timer, if there */ multi_deltimeout(data, id); } /* * Curl_expire_clear() * * Clear ALL timeout values for this handle. */ void Curl_expire_clear(struct Curl_easy *data) { struct Curl_multi *multi = data->multi; struct curltime *nowp = &data->state.expiretime; /* this is only interesting while there is still an associated multi struct remaining! */ if(!multi) return; if(nowp->tv_sec || nowp->tv_usec) { /* Since this is an cleared time, we must remove the previous entry from the splay tree */ struct curl_llist *list = &data->state.timeoutlist; int rc; rc = Curl_splayremovebyaddr(multi->timetree, &data->state.timenode, &multi->timetree); if(rc) infof(data, "Internal error clearing splay node = %d\n", rc); /* flush the timeout list too */ while(list->size > 0) { Curl_llist_remove(list, list->tail, NULL); } #ifdef DEBUGBUILD infof(data, "Expire cleared (transfer %p)\n", data); #endif nowp->tv_sec = 0; nowp->tv_usec = 0; } } CURLMcode curl_multi_assign(struct Curl_multi *multi, curl_socket_t s, void *hashp) { struct Curl_sh_entry *there = NULL; if(multi->in_callback) return CURLM_RECURSIVE_API_CALL; there = sh_getentry(&multi->sockhash, s); if(!there) return CURLM_BAD_SOCKET; there->socketp = hashp; return CURLM_OK; } size_t Curl_multi_max_host_connections(struct Curl_multi *multi) { return multi ? multi->max_host_connections : 0; } size_t Curl_multi_max_total_connections(struct Curl_multi *multi) { return multi ? multi->max_total_connections : 0; } /* * When information about a connection has appeared, call this! */ void Curl_multiuse_state(struct connectdata *conn, int bundlestate) /* use BUNDLE_* defines */ { DEBUGASSERT(conn); DEBUGASSERT(conn->bundle); DEBUGASSERT(conn->data); DEBUGASSERT(conn->data->multi); conn->bundle->multiuse = bundlestate; process_pending_handles(conn->data->multi); } static void process_pending_handles(struct Curl_multi *multi) { struct curl_llist_element *e = multi->pending.head; if(e) { struct Curl_easy *data = e->ptr; DEBUGASSERT(data->mstate == CURLM_STATE_CONNECT_PEND); multistate(data, CURLM_STATE_CONNECT); /* Remove this node from the list */ Curl_llist_remove(&multi->pending, e, NULL); /* Make sure that the handle will be processed soonish. */ Curl_expire(data, 0, EXPIRE_RUN_NOW); /* mark this as having been in the pending queue */ data->state.previouslypending = TRUE; } } void Curl_set_in_callback(struct Curl_easy *data, bool value) { /* might get called when there is no data pointer! */ if(data) { if(data->multi_easy) data->multi_easy->in_callback = value; else if(data->multi) data->multi->in_callback = value; } } bool Curl_is_in_callback(struct Curl_easy *easy) { return ((easy->multi && easy->multi->in_callback) || (easy->multi_easy && easy->multi_easy->in_callback)); } #ifdef DEBUGBUILD void Curl_multi_dump(struct Curl_multi *multi) { struct Curl_easy *data; int i; fprintf(stderr, "* Multi status: %d handles, %d alive\n", multi->num_easy, multi->num_alive); for(data = multi->easyp; data; data = data->next) { if(data->mstate < CURLM_STATE_COMPLETED) { /* only display handles that are not completed */ fprintf(stderr, "handle %p, state %s, %d sockets\n", (void *)data, statename[data->mstate], data->numsocks); for(i = 0; i < data->numsocks; i++) { curl_socket_t s = data->sockets[i]; struct Curl_sh_entry *entry = sh_getentry(&multi->sockhash, s); fprintf(stderr, "%d ", (int)s); if(!entry) { fprintf(stderr, "INTERNAL CONFUSION\n"); continue; } fprintf(stderr, "[%s %s] ", (entry->action&CURL_POLL_IN)?"RECVING":"", (entry->action&CURL_POLL_OUT)?"SENDING":""); } if(data->numsocks) fprintf(stderr, "\n"); } } } #endif
Java
///\file /****************************************************************************** The MIT License(MIT) Embedded Template Library. https://github.com/ETLCPP/etl Copyright(c) 2014 jwellbelove 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. ******************************************************************************/ #ifndef __ETL_POOL__ #define __ETL_POOL__ #include "alignment.h" #include "array.h" #include "bitset.h" #include "ipool.h" #include <iterator> //***************************************************************************** ///\defgroup pool pool /// A fixed capacity pool. ///\ingroup containers //***************************************************************************** namespace etl { //************************************************************************* /// A templated pool implementation that uses a fixed size pool. ///\ingroup pool //************************************************************************* template <typename T, const size_t SIZE_> class pool : public ipool<T> { public: static const size_t SIZE = SIZE_; //************************************************************************* /// Constructor //************************************************************************* pool() : ipool<T>(reinterpret_cast<T*>(&buffer[0]), in_use, SIZE) { } //************************************************************************* /// Destructor //************************************************************************* ~pool() { ipool<T>::release_all(); } private: ///< The memory for the pool of objects. typename etl::aligned_storage<sizeof(T), etl::alignment_of<T>::value>::type buffer[SIZE]; ///< The set of flags that indicate which items are free in the pool. bitset<SIZE> in_use; }; } #endif
Java
// This is a manifest file that'll be compiled into including all the files listed below. // Add new JavaScript/Coffee code in separate files in this directory and they'll automatically // be included in the compiled file accessible from http://example.com/assets/application.js // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // the compiled file. // //= require jquery //= require jquery_ujs //= require_tree .
Java
/* Code generated by IfcQuery EXPRESS generator, www.ifcquery.com */ #include <sstream> #include <limits> #include "ifcpp/model/AttributeObject.h" #include "ifcpp/model/BuildingException.h" #include "ifcpp/model/BuildingGuid.h" #include "ifcpp/reader/ReaderUtil.h" #include "ifcpp/writer/WriterUtil.h" #include "ifcpp/IFC4/include/IfcGloballyUniqueId.h" #include "ifcpp/IFC4/include/IfcIdentifier.h" #include "ifcpp/IFC4/include/IfcLabel.h" #include "ifcpp/IFC4/include/IfcMember.h" #include "ifcpp/IFC4/include/IfcMemberTypeEnum.h" #include "ifcpp/IFC4/include/IfcObjectPlacement.h" #include "ifcpp/IFC4/include/IfcOwnerHistory.h" #include "ifcpp/IFC4/include/IfcProductRepresentation.h" #include "ifcpp/IFC4/include/IfcRelAggregates.h" #include "ifcpp/IFC4/include/IfcRelAssigns.h" #include "ifcpp/IFC4/include/IfcRelAssignsToProduct.h" #include "ifcpp/IFC4/include/IfcRelAssociates.h" #include "ifcpp/IFC4/include/IfcRelConnectsElements.h" #include "ifcpp/IFC4/include/IfcRelConnectsWithRealizingElements.h" #include "ifcpp/IFC4/include/IfcRelContainedInSpatialStructure.h" #include "ifcpp/IFC4/include/IfcRelCoversBldgElements.h" #include "ifcpp/IFC4/include/IfcRelDeclares.h" #include "ifcpp/IFC4/include/IfcRelDefinesByObject.h" #include "ifcpp/IFC4/include/IfcRelDefinesByProperties.h" #include "ifcpp/IFC4/include/IfcRelDefinesByType.h" #include "ifcpp/IFC4/include/IfcRelFillsElement.h" #include "ifcpp/IFC4/include/IfcRelInterferesElements.h" #include "ifcpp/IFC4/include/IfcRelNests.h" #include "ifcpp/IFC4/include/IfcRelProjectsElement.h" #include "ifcpp/IFC4/include/IfcRelReferencedInSpatialStructure.h" #include "ifcpp/IFC4/include/IfcRelSpaceBoundary.h" #include "ifcpp/IFC4/include/IfcRelVoidsElement.h" #include "ifcpp/IFC4/include/IfcText.h" // ENTITY IfcMember IfcMember::IfcMember( int id ) { m_entity_id = id; } shared_ptr<BuildingObject> IfcMember::getDeepCopy( BuildingCopyOptions& options ) { shared_ptr<IfcMember> copy_self( new IfcMember() ); if( m_GlobalId ) { if( options.create_new_IfcGloballyUniqueId ) { copy_self->m_GlobalId = make_shared<IfcGloballyUniqueId>( createBase64Uuid_wstr().data() ); } else { copy_self->m_GlobalId = dynamic_pointer_cast<IfcGloballyUniqueId>( m_GlobalId->getDeepCopy(options) ); } } if( m_OwnerHistory ) { if( options.shallow_copy_IfcOwnerHistory ) { copy_self->m_OwnerHistory = m_OwnerHistory; } else { copy_self->m_OwnerHistory = dynamic_pointer_cast<IfcOwnerHistory>( m_OwnerHistory->getDeepCopy(options) ); } } if( m_Name ) { copy_self->m_Name = dynamic_pointer_cast<IfcLabel>( m_Name->getDeepCopy(options) ); } if( m_Description ) { copy_self->m_Description = dynamic_pointer_cast<IfcText>( m_Description->getDeepCopy(options) ); } if( m_ObjectType ) { copy_self->m_ObjectType = dynamic_pointer_cast<IfcLabel>( m_ObjectType->getDeepCopy(options) ); } if( m_ObjectPlacement ) { copy_self->m_ObjectPlacement = dynamic_pointer_cast<IfcObjectPlacement>( m_ObjectPlacement->getDeepCopy(options) ); } if( m_Representation ) { copy_self->m_Representation = dynamic_pointer_cast<IfcProductRepresentation>( m_Representation->getDeepCopy(options) ); } if( m_Tag ) { copy_self->m_Tag = dynamic_pointer_cast<IfcIdentifier>( m_Tag->getDeepCopy(options) ); } if( m_PredefinedType ) { copy_self->m_PredefinedType = dynamic_pointer_cast<IfcMemberTypeEnum>( m_PredefinedType->getDeepCopy(options) ); } return copy_self; } void IfcMember::getStepLine( std::stringstream& stream ) const { stream << "#" << m_entity_id << "= IFCMEMBER" << "("; if( m_GlobalId ) { m_GlobalId->getStepParameter( stream ); } else { stream << "$"; } stream << ","; if( m_OwnerHistory ) { stream << "#" << m_OwnerHistory->m_entity_id; } else { stream << "$"; } stream << ","; if( m_Name ) { m_Name->getStepParameter( stream ); } else { stream << "$"; } stream << ","; if( m_Description ) { m_Description->getStepParameter( stream ); } else { stream << "$"; } stream << ","; if( m_ObjectType ) { m_ObjectType->getStepParameter( stream ); } else { stream << "$"; } stream << ","; if( m_ObjectPlacement ) { stream << "#" << m_ObjectPlacement->m_entity_id; } else { stream << "$"; } stream << ","; if( m_Representation ) { stream << "#" << m_Representation->m_entity_id; } else { stream << "$"; } stream << ","; if( m_Tag ) { m_Tag->getStepParameter( stream ); } else { stream << "$"; } stream << ","; if( m_PredefinedType ) { m_PredefinedType->getStepParameter( stream ); } else { stream << "$"; } stream << ");"; } void IfcMember::getStepParameter( std::stringstream& stream, bool /*is_select_type*/ ) const { stream << "#" << m_entity_id; } const std::wstring IfcMember::toString() const { return L"IfcMember"; } void IfcMember::readStepArguments( const std::vector<std::wstring>& args, const std::map<int,shared_ptr<BuildingEntity> >& map ) { const size_t num_args = args.size(); if( num_args != 9 ){ std::stringstream err; err << "Wrong parameter count for entity IfcMember, expecting 9, having " << num_args << ". Entity ID: " << m_entity_id << std::endl; throw BuildingException( err.str().c_str() ); } m_GlobalId = IfcGloballyUniqueId::createObjectFromSTEP( args[0], map ); readEntityReference( args[1], m_OwnerHistory, map ); m_Name = IfcLabel::createObjectFromSTEP( args[2], map ); m_Description = IfcText::createObjectFromSTEP( args[3], map ); m_ObjectType = IfcLabel::createObjectFromSTEP( args[4], map ); readEntityReference( args[5], m_ObjectPlacement, map ); readEntityReference( args[6], m_Representation, map ); m_Tag = IfcIdentifier::createObjectFromSTEP( args[7], map ); m_PredefinedType = IfcMemberTypeEnum::createObjectFromSTEP( args[8], map ); } void IfcMember::getAttributes( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes ) const { IfcBuildingElement::getAttributes( vec_attributes ); vec_attributes.emplace_back( std::make_pair( "PredefinedType", m_PredefinedType ) ); } void IfcMember::getAttributesInverse( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes_inverse ) const { IfcBuildingElement::getAttributesInverse( vec_attributes_inverse ); } void IfcMember::setInverseCounterparts( shared_ptr<BuildingEntity> ptr_self_entity ) { IfcBuildingElement::setInverseCounterparts( ptr_self_entity ); } void IfcMember::unlinkFromInverseCounterparts() { IfcBuildingElement::unlinkFromInverseCounterparts(); }
Java
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="apple-mobile-web-app-capable" content="no"> <meta name="viewport" content="width=1000"> <meta name="keywords" content="attrs.ui"> <meta name="author" content="joje.attrs@gmail.com"> <meta name="description" content="Examples"> <title>Style System Basic</title> <script type="text/javascript" src="../ui.debug.js"></script> <script type="text/javascript"> // define style var style = new Appbus.Style({ 'background': 'white', 'color': 'black', 'font-size': 10, '.hierachy': { 'color': 'grey', 'background': 'yellow', 'test': { 'font-size': 9 } } }); console.log('style', style); style.on('*', function(e) { console.log('[' + e.type + '] event occured'); console.log('src', e.src); console.log('values', e.values); console.log('\n\n'); }); // append style.set('..newcls', { 'background': 'lightorange', '.hierachy': { '': { 'color': 'red' } } }); // replace style.set('color', 'grey'); // remove style.remove('font-size'); // merge element style.merge('..cls', { 'display': 'box', 'background-image': 'url("http://localhost/image.png")', 'transition': 'aa', 'p': { 'color': 'blue' } }); // sub style replace style.get('..cls').set('color', 'grey'); // sub style remove style.get('..cls').remove('color'); </script> </head> <body> </body> </html>
Java
/** * Copyright 2014 Pacific Controls Software Services LLC (PCSS). All Rights Reserved. * * This software is the property of Pacific Controls Software Services LLC and its * suppliers. The intellectual and technical concepts contained herein are proprietary * to PCSS. Dissemination of this information or reproduction of this material is * strictly forbidden unless prior written permission is obtained from Pacific * Controls Software Services. * * PCSS MAKES NO REPRESENTATION OR WARRANTIES ABOUT THE SUITABILITY OF THE SOFTWARE, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF * MERCHANTANILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGMENT. PCSS SHALL * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING * OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. */ /** * Version : 1.0 * User : pcseg306 * Function : Service for Super/client Admin Notification Functions */ gxMainApp.factory("adminFunctionsService", function($http,$rootScope,gxAPIServiceWrapper){ var _notificationArray = []; var _resultPromise; var _getNotificationArray = function() { _resultPromise = gxAPIServiceWrapper.get("models/superAdmin/dummySuperAdminNotification.json"); console.log(_resultPromise); return _resultPromise; } return{ notificationArray: _notificationArray, getNotificationArray: _getNotificationArray, resultPromise : _resultPromise }; });
Java
#!/usr/bin/python # -*- coding: utf-8 -*- # thumbor imaging service # https://github.com/thumbor/thumbor/wiki # Licensed under the MIT license: # http://www.opensource.org/licenses/mit-license # Copyright (c) 2011 globo.com timehome@corp.globo.com from thumbor.loaders import http_loader from tornado.concurrent import return_future from urllib import unquote def _normalize_url(url): url = http_loader.quote_url(unquote(url)) if url.startswith('http:'): url = url.replace('http:', 'https:', 1) return url if url.startswith('https://') else 'https://%s' % url def validate(context, url): if url.startswith('http://'): return False return http_loader.validate(context, url, normalize_url_func=_normalize_url) def return_contents(response, url, callback, context): return http_loader.return_contents(response, url, callback, context) @return_future def load(context, url, callback): return http_loader.load_sync(context, url, callback, normalize_url_func=_normalize_url) def encode(string): return http_loader.encode(string)
Java
<?php class device extends CI_Controller{ public function add_device(){ $this->load->model('device_model'); $device_name = $this->input->post('device_name'); $device_id = $this->input->post('device_id'); $about_device = $this->input->post('about_device'); $key = $this->session->userdata('id'); //later stages will take users key $passcode = rand($key,$key+10000); $data = array( 'device_name' => $device_name, 'device_id' => $device_id, 'about_device' => $about_device, 'key' => $key, 'passcode' => $passcode ); $this->device_model->add_device($data); $this->session->set_userdata('passcode', $passcode); redirect('user/device'); } public function edit_device($id){ $this->load->model('device_model'); $device_name = $this->input->post('device_name'); $device_id = $this->input->post('device_id'); $about_device = $this->input->post('about_device'); $key = $this->session->userdata('id');; //later stages will take users key $data = array( 'device_name' => $device_name, 'device_id' => $device_id, 'about_device' => $about_device, 'key' => $key ); $this->device_model->edit_device($id,$data); redirect('user/device'); } public function delete_device($id){ $this->load->model('device_model'); $this->device_model->delete_device($id); redirect('user/device'); } public function add_parameters($device_id){ $parameters = $this->input->post("parameter_name[]"); $this->load->model('device_model'); foreach ($parameters as $parameter_name) { $data = [ 'parameter_name' => $parameter_name, 'device_id' => $device_id ]; $this->device_model->add_parameter($data); } redirect("user/device"); } public function update_parameter(){ $this->load->model('device_model'); $parameter_names = $this->input->post('parameter_name[]'); $parameter_ids = $this->input->post('parameter_id[]'); $count = 0; foreach ($parameter_names as $parameter_name){ $id = $parameter_ids[$count]; $data = array('parameter_name' => $parameter_name); $this->device_model->edit_parameter($id,$data); $count = $count + 1; } redirect('user/device'); } } ?>
Java
define(function(require) { var test = require('../../../test') var count = 0 require.async('./a', function(a) { test.assert(a.name === 'a', 'load CMD module file') done() }) require.async('./b.js', function() { test.assert(global.SPECS_MODULES_ASYNC === true, 'load normal script file') global.SPECS_MODULES_ASYNC = undefined done() }) require.async(['./c1', './c2'], function(c1, c2) { test.assert(c1.name === 'c1', c1.name) test.assert(c2.name === 'c2', c2.name) done() }) function done() { if (++count === 3) { test.next() } } });
Java
namespace AbpKendoDemo.Migrations { using System; using System.Data.Entity.Migrations; public partial class Upgrade_Abp_And_Module_Zero_To_0_8_1 : DbMigration { public override void Up() { CreateTable( "dbo.AbpBackgroundJobs", c => new { Id = c.Long(nullable: false, identity: true), JobType = c.String(nullable: false, maxLength: 512), JobArgs = c.String(nullable: false), TryCount = c.Short(nullable: false), NextTryTime = c.DateTime(nullable: false), LastTryTime = c.DateTime(), IsAbandoned = c.Boolean(nullable: false), Priority = c.Byte(nullable: false), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }) .PrimaryKey(t => t.Id) .Index(t => new { t.IsAbandoned, t.NextTryTime }); CreateTable( "dbo.AbpNotifications", c => new { Id = c.Guid(nullable: false), NotificationName = c.String(nullable: false, maxLength: 128), Data = c.String(), DataTypeName = c.String(maxLength: 512), EntityTypeName = c.String(maxLength: 256), EntityTypeAssemblyQualifiedName = c.String(maxLength: 512), EntityId = c.String(maxLength: 128), Severity = c.Byte(nullable: false), UserIds = c.String(), ExcludedUserIds = c.String(), TenantIds = c.String(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.AbpNotificationSubscriptions", c => new { Id = c.Guid(nullable: false), TenantId = c.Int(), UserId = c.Long(nullable: false), NotificationName = c.String(maxLength: 128), EntityTypeName = c.String(maxLength: 256), EntityTypeAssemblyQualifiedName = c.String(maxLength: 512), EntityId = c.String(maxLength: 128), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }) .PrimaryKey(t => t.Id) .Index(t => new { t.NotificationName, t.EntityTypeName, t.EntityId, t.UserId }); CreateTable( "dbo.AbpUserNotifications", c => new { Id = c.Guid(nullable: false), UserId = c.Long(nullable: false), NotificationId = c.Guid(nullable: false), State = c.Int(nullable: false), CreationTime = c.DateTime(nullable: false), }) .PrimaryKey(t => t.Id) .Index(t => new { t.UserId, t.State, t.CreationTime }); } public override void Down() { DropIndex("dbo.AbpUserNotifications", new[] { "UserId", "State", "CreationTime" }); DropIndex("dbo.AbpNotificationSubscriptions", new[] { "NotificationName", "EntityTypeName", "EntityId", "UserId" }); DropIndex("dbo.AbpBackgroundJobs", new[] { "IsAbandoned", "NextTryTime" }); DropTable("dbo.AbpUserNotifications"); DropTable("dbo.AbpNotificationSubscriptions"); DropTable("dbo.AbpNotifications"); DropTable("dbo.AbpBackgroundJobs"); } } }
Java
using System.Web; using System.Web.Optimization; namespace TwitterFeed { public class BundleConfig { public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/bootstrap.css","~/Content/site.css")); bundles.Add(new ScriptBundle("~/Scripts/js").Include("~/Scripts/jquery-2.1.1.min.js", "~/Scripts/bootstrap.min.js", "~/Scripts/knockout-3.3.0.js", "~/Scripts/sammy-0.7.5.min.js", "~/Scripts/main.js")); } } }
Java
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.advisor.v2017_04_19; import com.microsoft.azure.arm.collection.SupportsCreating; import rx.Completable; import rx.Observable; import com.microsoft.azure.management.advisor.v2017_04_19.implementation.SuppressionsInner; import com.microsoft.azure.arm.model.HasInner; /** * Type representing Suppressions. */ public interface Suppressions extends SupportsCreating<SuppressionContract.DefinitionStages.Blank>, HasInner<SuppressionsInner> { /** * Retrieves the list of snoozed or dismissed suppressions for a subscription. The snoozed or dismissed attribute of a recommendation is referred to as a suppression. * * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable for the request */ Observable<SuppressionContract> listAsync(); /** * Obtains the details of a suppression. * * @param resourceUri The fully qualified Azure Resource Manager identifier of the resource to which the recommendation applies. * @param recommendationId The recommendation ID. * @param name The name of the suppression. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable for the request */ Observable<SuppressionContract> getAsync(String resourceUri, String recommendationId, String name); /** * Enables the activation of a snoozed or dismissed recommendation. The snoozed or dismissed attribute of a recommendation is referred to as a suppression. * * @param resourceUri The fully qualified Azure Resource Manager identifier of the resource to which the recommendation applies. * @param recommendationId The recommendation ID. * @param name The name of the suppression. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable for the request */ Completable deleteAsync(String resourceUri, String recommendationId, String name); }
Java
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Static() result.template = "object/static/item/shared_armor_composite_helmet.iff" result.attribute_template_id = -1 result.stfName("obj_n","unknown_object") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
Java
const fs = require('fs'); const path = require('path'); const cleanCss = require('../../index.js'); module.exports = { name : 'basic test', this : function () { const str = fs.readFileSync(path.resolve('test/styles/basic.dirty.scss'), 'utf8'); const clean = cleanCss({ css : str }); return clean; }, isEqual : function () { return fs.readFileSync(path.resolve('test/styles/basic.clean.scss'), 'utf8'); } };
Java
<script src="/socket.io/socket.io.js"></script> <script src="bower_components/virtualjoystick.js/virtualjoystick.js"></script> <script src="../threex.cloudcontroller.js"></script> <script src="../threex.cloudcontrollerscreenupdater.js"></script> <script src="../threex.cloudcontrollervirtualjoystick.js"></script> <body style='width:100%;margin: 0px; background-color: #bbbbbb; overflow: hidden;'> <!-- <img id='remoteImage' src=''/> --> <script> window.addEventListener('load', function(event){ ////////////////////////////////////////////////////////////////////////////////// // CloudController itself // ////////////////////////////////////////////////////////////////////////////////// var cloudController = new THREEx.CloudController() cloudController.socket.on('connect', function(){ console.log('connected to server') }) cloudController.socket.on('disconnect', function(){ console.warn('disconnected from server') }) ////////////////////////////////////////////////////////////////////////////////// // screenUpdater // ////////////////////////////////////////////////////////////////////////////////// var screenUpdater = new THREEx.CloudControllerScreenUpdater(cloudController) document.body.appendChild(screenUpdater.domElement) screenUpdater.sendResolution() setTimeout(function(){ screenUpdater.sendResolution() }, 1000*0.5) ////////////////////////////////////////////////////////////////////////////////// // virtualjoystick // ////////////////////////////////////////////////////////////////////////////////// var cloudVirtualJoystick = new THREEx.CloudControllerVirtualJoystick(cloudController) setInterval(function(){ cloudVirtualJoystick.sendIfChanged() }, 1000*1/60) }) </script></body>
Java
<a href="/learning-programming.html" class="lgi">Learning Programming</a> <a href="/serverless.html" class="lgi">Serverless Architectures</a> <a href="/aws-lambda.html" class="lgi">AWS Lambda</a> <a href="/monitoring.html" class="lgi">Monitoring</a> <a href="/deployment.html" class="lgi">Deployment</a> <a href="/rollbar.html" class="lgi">Rollbar</a> <a href="https://rollbar.com" class="lgi">Rollbar homepage {% include "blog/external-link.html" %}</a> <a href="https://docs.rollbar.com/docs/python/#aws-lambda" class="lgi">Rollbar AWS Lambda docs {% include "blog/external-link.html" %}</a>
Java
<!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_112) on Sat May 13 03:02:10 PDT 2017 --> <title>ConsoleUI</title> <meta name="date" content="2017-05-13"> <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="ConsoleUI"; } } catch(err) { } //--> var methods = {"i0":10}; var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],8:["t4","Concrete Methods"]}; var altColor = "altColor"; var rowColor = "rowColor"; var tableTab = "tableTab"; var activeTableTab = "activeTableTab"; </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="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../deprecated-list.html">Deprecated</a></li> <li><a href="../index-all.html">Index</a></li> <li><a href="../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev&nbsp;Class</li> <li><a href="../ui/Environment.html" title="class in ui"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../index.html?ui/ConsoleUI.html" target="_top">Frames</a></li> <li><a href="ConsoleUI.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> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">ui</div> <h2 title="Class ConsoleUI" class="title">Class ConsoleUI</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>ui.ConsoleUI</li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>All Implemented Interfaces:</dt> <dd>java.util.Observer</dd> </dl> <hr> <br> <pre>public class <span class="typeNameLabel">ConsoleUI</span> extends java.lang.Object implements java.util.Observer</pre> <dl> <dt><span class="simpleTagLabel">Since:</span></dt> <dd>0.1 A console logger</dd> </dl> </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="memberSummary" 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><span class="memberNameLink"><a href="../ui/ConsoleUI.html#ConsoleUI--">ConsoleUI</a></span>()</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="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd">&nbsp;</span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd">&nbsp;</span></span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr id="i0" class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../ui/ConsoleUI.html#update-java.util.Observable-java.lang.Object-">update</a></span>(java.util.Observable&nbsp;o, java.lang.Object&nbsp;arg)</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>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="ConsoleUI--"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>ConsoleUI</h4> <pre>public&nbsp;ConsoleUI()</pre> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method.detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="update-java.util.Observable-java.lang.Object-"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>update</h4> <pre>public&nbsp;void&nbsp;update(java.util.Observable&nbsp;o, java.lang.Object&nbsp;arg)</pre> <dl> <dt><span class="overrideSpecifyLabel">Specified by:</span></dt> <dd><code>update</code>&nbsp;in interface&nbsp;<code>java.util.Observer</code></dd> </dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= 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="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../deprecated-list.html">Deprecated</a></li> <li><a href="../index-all.html">Index</a></li> <li><a href="../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev&nbsp;Class</li> <li><a href="../ui/Environment.html" title="class in ui"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../index.html?ui/ConsoleUI.html" target="_top">Frames</a></li> <li><a href="ConsoleUI.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> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
Java
## 快捷键 ## {% highlight json %} { "去色" : "C-S-u", "反相" : "C-i", } {% endhighlight %}
Java
#!/usr/bin/env python # # __COPYRIGHT__ # # 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. # __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" """ Test setting the $P4COMSTR variable. """ import os.path import TestSCons _python_ = TestSCons._python_ test = TestSCons.TestSCons() test.subdir('Perforce', ['Perforce', 'sub'], 'sub') sub_Perforce = os.path.join('sub', 'Perforce') sub_SConscript = os.path.join('sub', 'SConscript') sub_all = os.path.join('sub', 'all') sub_ddd_in = os.path.join('sub', 'ddd.in') sub_ddd_out = os.path.join('sub', 'ddd.out') sub_eee_in = os.path.join('sub', 'eee.in') sub_eee_out = os.path.join('sub', 'eee.out') sub_fff_in = os.path.join('sub', 'fff.in') sub_fff_out = os.path.join('sub', 'fff.out') test.write('my-p4.py', """ import shutil import sys for f in sys.argv[1:]: shutil.copy('Perforce/'+f, f) """) test.write('SConstruct', """ def cat(env, source, target): target = str(target[0]) source = map(str, source) f = open(target, "wb") for src in source: f.write(open(src, "rb").read()) f.close() env = Environment(TOOLS = ['default', 'Perforce'], BUILDERS={'Cat':Builder(action=cat)}, P4COM='%(_python_)s my-p4.py $TARGET', P4COMSTR='Checking out $TARGET from our fake Perforce') env.Cat('aaa.out', 'aaa.in') env.Cat('bbb.out', 'bbb.in') env.Cat('ccc.out', 'ccc.in') env.Cat('all', ['aaa.out', 'bbb.out', 'ccc.out']) env.SourceCode('.', env.Perforce()) SConscript('sub/SConscript', "env") """ % locals()) test.write(['Perforce', 'sub', 'SConscript'], """\ Import("env") env.Cat('ddd.out', 'ddd.in') env.Cat('eee.out', 'eee.in') env.Cat('fff.out', 'fff.in') env.Cat('all', ['ddd.out', 'eee.out', 'fff.out']) """) test.write(['Perforce', 'aaa.in'], "Perforce/aaa.in\n") test.write('bbb.in', "checked-out bbb.in\n") test.write(['Perforce', 'ccc.in'], "Perforce/ccc.in\n") test.write(['Perforce', 'sub', 'ddd.in'], "Perforce/sub/ddd.in\n") test.write(['sub', 'eee.in'], "checked-out sub/eee.in\n") test.write(['Perforce', 'sub', 'fff.in'], "Perforce/sub/fff.in\n") test.run(arguments = '.', stdout = test.wrap_stdout(read_str = """\ Checking out %(sub_SConscript)s from our fake Perforce """ % locals(), build_str = """\ Checking out aaa.in from our fake Perforce cat(["aaa.out"], ["aaa.in"]) cat(["bbb.out"], ["bbb.in"]) Checking out ccc.in from our fake Perforce cat(["ccc.out"], ["ccc.in"]) cat(["all"], ["aaa.out", "bbb.out", "ccc.out"]) Checking out %(sub_ddd_in)s from our fake Perforce cat(["%(sub_ddd_out)s"], ["%(sub_ddd_in)s"]) cat(["%(sub_eee_out)s"], ["%(sub_eee_in)s"]) Checking out %(sub_fff_in)s from our fake Perforce cat(["%(sub_fff_out)s"], ["%(sub_fff_in)s"]) cat(["%(sub_all)s"], ["%(sub_ddd_out)s", "%(sub_eee_out)s", "%(sub_fff_out)s"]) """ % locals())) test.must_match('all', "Perforce/aaa.in\nchecked-out bbb.in\nPerforce/ccc.in\n") test.must_match(['sub', 'all'], "Perforce/sub/ddd.in\nchecked-out sub/eee.in\nPerforce/sub/fff.in\n") # test.pass_test()
Java
using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.Serialization; using System; using System.Linq; using System.Collections; using System.Collections.Generic; using System.Text.RegularExpressions; namespace Fungus { /** * Visual scripting controller for the Flowchart programming language. * Flowchart objects may be edited visually using the Flowchart editor window. */ [ExecuteInEditMode] public class Flowchart : MonoBehaviour { /** * Current version used to compare with the previous version so older versions can be custom-updated from previous versions. */ public const string CURRENT_VERSION = "1.0"; /** * The name of the initial block in a new flowchart. */ public const string DEFAULT_BLOCK_NAME = "New Block"; /** * Variable to track flowchart's version and if initial set up has completed. */ [HideInInspector] public string version; /** * Scroll position of Flowchart editor window. */ [HideInInspector] public Vector2 scrollPos; /** * Scroll position of Flowchart variables window. */ [HideInInspector] public Vector2 variablesScrollPos; /** * Show the variables pane. */ [HideInInspector] public bool variablesExpanded = true; /** * Height of command block view in inspector. */ [HideInInspector] public float blockViewHeight = 400; /** * Zoom level of Flowchart editor window */ [HideInInspector] public float zoom = 1f; /** * Scrollable area for Flowchart editor window. */ [HideInInspector] public Rect scrollViewRect; /** * Currently selected block in the Flowchart editor. */ [HideInInspector] [FormerlySerializedAs("selectedSequence")] public Block selectedBlock; /** * Currently selected command in the Flowchart editor. */ [HideInInspector] public List<Command> selectedCommands = new List<Command>(); /** * The list of variables that can be accessed by the Flowchart. */ [HideInInspector] public List<Variable> variables = new List<Variable>(); [TextArea(3, 5)] [Tooltip("Description text displayed in the Flowchart editor window")] public string description = ""; /** * Slow down execution in the editor to make it easier to visualise program flow. */ [Range(0f, 5f)] [Tooltip("Adds a pause after each execution step to make it easier to visualise program flow. Editor only, has no effect in platform builds.")] public float stepPause = 0f; /** * Use command color when displaying the command list in the inspector. */ [Tooltip("Use command color when displaying the command list in the Fungus Editor window")] public bool colorCommands = true; /** * Hides the Flowchart block and command components in the inspector. * Deselect to inspect the block and command components that make up the Flowchart. */ [Tooltip("Hides the Flowchart block and command components in the inspector")] public bool hideComponents = true; /** * Saves the selected block and commands when saving the scene. * Helps avoid version control conflicts if you've only changed the active selection. */ [Tooltip("Saves the selected block and commands when saving the scene.")] public bool saveSelection = true; /** * Unique identifier for identifying this flowchart in localized string keys. */ [Tooltip("Unique identifier for this flowchart in localized string keys. If no id is specified then the name of the Flowchart object will be used.")] public string localizationId = ""; /** * Cached list of flowchart objects in the scene for fast lookup */ public static List<Flowchart> cachedFlowcharts = new List<Flowchart>(); protected static bool eventSystemPresent; /** * Returns the next id to assign to a new flowchart item. * Item ids increase monotically so they are guaranteed to * be unique within a Flowchart. */ public int NextItemId() { int maxId = -1; Block[] blocks = GetComponentsInChildren<Block>(); foreach (Block block in blocks) { maxId = Math.Max(maxId, block.itemId); } Command[] commands = GetComponentsInChildren<Command>(); foreach (Command command in commands) { maxId = Math.Max(maxId, command.itemId); } return maxId + 1; } protected virtual void OnLevelWasLoaded(int level) { // Reset the flag for checking for an event system as there may not be one in the newly loaded scene. eventSystemPresent = false; } protected virtual void Start() { CheckEventSystem(); } // There must be an Event System in the scene for Say and Menu input to work. // This method will automatically instantiate one if none exists. protected virtual void CheckEventSystem() { if (eventSystemPresent) { return; } EventSystem eventSystem = GameObject.FindObjectOfType<EventSystem>(); if (eventSystem == null) { // Auto spawn an Event System from the prefab GameObject prefab = Resources.Load<GameObject>("EventSystem"); if (prefab != null) { GameObject go = Instantiate(prefab) as GameObject; go.name = "EventSystem"; } } eventSystemPresent = true; } public virtual void OnEnable() { if (!cachedFlowcharts.Contains(this)) { cachedFlowcharts.Add(this); } CheckItemIds(); CleanupComponents(); UpdateVersion(); } public virtual void OnDisable() { cachedFlowcharts.Remove(this); } protected virtual void CheckItemIds() { // Make sure item ids are unique and monotonically increasing. // This should always be the case, but some legacy Flowcharts may have issues. List<int> usedIds = new List<int>(); Block[] blocks = GetComponentsInChildren<Block>(); foreach (Block block in blocks) { if (block.itemId == -1 || usedIds.Contains(block.itemId)) { block.itemId = NextItemId(); } usedIds.Add(block.itemId); } Command[] commands = GetComponentsInChildren<Command>(); foreach (Command command in commands) { if (command.itemId == -1 || usedIds.Contains(command.itemId)) { command.itemId = NextItemId(); } usedIds.Add(command.itemId); } } protected virtual void CleanupComponents() { // Delete any unreferenced components which shouldn't exist any more // Unreferenced components don't have any effect on the flowchart behavior, but // they waste memory so should be cleared out periodically. Block[] blocks = GetComponentsInChildren<Block>(); foreach (Variable variable in GetComponents<Variable>()) { if (!variables.Contains(variable)) { DestroyImmediate(variable); } } foreach (Command command in GetComponents<Command>()) { bool found = false; foreach (Block block in blocks) { if (block.commandList.Contains(command)) { found = true; break; } } if (!found) { DestroyImmediate(command); } } foreach (EventHandler eventHandler in GetComponents<EventHandler>()) { bool found = false; foreach (Block block in blocks) { if (block.eventHandler == eventHandler) { found = true; break; } } if (!found) { DestroyImmediate(eventHandler); } } } private void UpdateVersion() { // If versions match, then we are already using the latest. if (version == CURRENT_VERSION) return; switch (version) { // Version never set, so we are initializing on first creation or this flowchart is pre-versioning. case null: case "": Initialize(); break; } version = CURRENT_VERSION; } protected virtual void Initialize() { // If there are other flowcharts in the scene and the selected block has the default name, then this is probably a new block. // Reset the event handler of the new flowchart's default block to avoid crashes. if (selectedBlock && cachedFlowcharts.Count > 1 && selectedBlock.blockName == DEFAULT_BLOCK_NAME) { selectedBlock.eventHandler = null; } } protected virtual Block CreateBlockComponent(GameObject parent) { Block block = parent.AddComponent<Block>(); return block; } /** * Create a new block node which you can then add commands to. */ public virtual Block CreateBlock(Vector2 position) { Block b = CreateBlockComponent(gameObject); b.nodeRect.x = position.x; b.nodeRect.y = position.y; b.blockName = GetUniqueBlockKey(b.blockName, b); b.itemId = NextItemId(); return b; } /** * Returns the named Block in the flowchart, or null if not found. */ public virtual Block FindBlock(string blockName) { Block [] blocks = GetComponentsInChildren<Block>(); foreach (Block block in blocks) { if (block.blockName == blockName) { return block; } } return null; } /** * Start running another Flowchart by executing a specific child block. * The block must be in an idle state to be executed. * You can use this method in a UI event. e.g. to handle a button click. */ public virtual void ExecuteBlock(string blockName) { Block [] blocks = GetComponentsInChildren<Block>(); foreach (Block block in blocks) { if (block.blockName == blockName) { ExecuteBlock(block); } } } /** * Sends a message to this Flowchart only. * Any block with a matching MessageReceived event handler will start executing. */ public virtual void SendFungusMessage(string messageName) { MessageReceived[] eventHandlers = GetComponentsInChildren<MessageReceived>(); foreach (MessageReceived eventHandler in eventHandlers) { eventHandler.OnSendFungusMessage(messageName); } } /** * Sends a message to all Flowchart objects in the current scene. * Any block with a matching MessageReceived event handler will start executing. */ public static void BroadcastFungusMessage(string messageName) { MessageReceived[] eventHandlers = GameObject.FindObjectsOfType<MessageReceived>(); foreach (MessageReceived eventHandler in eventHandlers) { eventHandler.OnSendFungusMessage(messageName); } } /** * Start executing a specific child block in the flowchart. * The block must be in an idle state to be executed. * Returns true if the Block started execution. */ public virtual bool ExecuteBlock(Block block, Action onComplete = null) { // Block must be a component of the Flowchart game object if (block == null || block.gameObject != gameObject) { return false; } // Can't restart a running block, have to wait until it's idle again if (block.IsExecuting()) { return false; } // Execute the first command in the command list block.Execute(onComplete); return true; } /** * Returns a new variable key that is guaranteed not to clash with any existing variable in the list. */ public virtual string GetUniqueVariableKey(string originalKey, Variable ignoreVariable = null) { int suffix = 0; string baseKey = originalKey; // Only letters and digits allowed char[] arr = baseKey.Where(c => (char.IsLetterOrDigit(c) || c == '_')).ToArray(); baseKey = new string(arr); // No leading digits allowed baseKey = baseKey.TrimStart('0','1','2','3','4','5','6','7','8','9'); // No empty keys allowed if (baseKey.Length == 0) { baseKey = "Var"; } string key = baseKey; while (true) { bool collision = false; foreach(Variable variable in variables) { if (variable == null || variable == ignoreVariable || variable.key == null) { continue; } if (variable.key.Equals(key, StringComparison.CurrentCultureIgnoreCase)) { collision = true; suffix++; key = baseKey + suffix; } } if (!collision) { return key; } } } /** * Returns a new Block key that is guaranteed not to clash with any existing Block in the Flowchart. */ public virtual string GetUniqueBlockKey(string originalKey, Block ignoreBlock = null) { int suffix = 0; string baseKey = originalKey.Trim(); // No empty keys allowed if (baseKey.Length == 0) { baseKey = "New Block"; } Block[] blocks = GetComponentsInChildren<Block>(); string key = baseKey; while (true) { bool collision = false; foreach(Block block in blocks) { if (block == ignoreBlock || block.blockName == null) { continue; } if (block.blockName.Equals(key, StringComparison.CurrentCultureIgnoreCase)) { collision = true; suffix++; key = baseKey + suffix; } } if (!collision) { return key; } } } /** * Returns a new Label key that is guaranteed not to clash with any existing Label in the Block. */ public virtual string GetUniqueLabelKey(string originalKey, Label ignoreLabel) { int suffix = 0; string baseKey = originalKey.Trim(); // No empty keys allowed if (baseKey.Length == 0) { baseKey = "New Label"; } Block block = ignoreLabel.parentBlock; string key = baseKey; while (true) { bool collision = false; foreach(Command command in block.commandList) { Label label = command as Label; if (label == null || label == ignoreLabel) { continue; } if (label.key.Equals(key, StringComparison.CurrentCultureIgnoreCase)) { collision = true; suffix++; key = baseKey + suffix; } } if (!collision) { return key; } } } /** * Returns the variable with the specified key, or null if the key is not found. * You can then access the variable's value using the Value property. e.g. * BooleanVariable boolVar = flowchart.GetVariable<BooleanVariable>("MyBool"); * boolVar.Value = false; */ public T GetVariable<T>(string key) where T : Variable { foreach (Variable variable in variables) { if (variable.key == key) { return variable as T; } } return null; } /** * Gets a list of all variables with public scope in this Flowchart. */ public virtual List<Variable> GetPublicVariables() { List<Variable> publicVariables = new List<Variable>(); foreach (Variable v in variables) { if (v.scope == VariableScope.Public) { publicVariables.Add(v); } } return publicVariables; } /** * Gets the value of a boolean variable. * Returns false if the variable key does not exist. */ public virtual bool GetBooleanVariable(string key) { foreach (Variable v in variables) { if (v.key == key) { BooleanVariable variable = v as BooleanVariable; if (variable != null) { return variable.value; } } } Debug.LogWarning("Boolean variable " + key + " not found."); return false; } /** * Sets the value of a boolean variable. * The variable must already be added to the list of variables for this Flowchart. */ public virtual void SetBooleanVariable(string key, bool value) { foreach (Variable v in variables) { if (v.key == key) { BooleanVariable variable = v as BooleanVariable; if (variable != null) { variable.value = value; return; } } } Debug.LogWarning("Boolean variable " + key + " not found."); } /** * Gets the value of an integer variable. * Returns 0 if the variable key does not exist. */ public virtual int GetIntegerVariable(string key) { foreach (Variable v in variables) { if (v.key == key) { IntegerVariable variable = v as IntegerVariable; if (variable != null) { return variable.value; } } } Debug.LogWarning("Integer variable " + key + " not found."); return 0; } /** * Sets the value of an integer variable. * The variable must already be added to the list of variables for this Flowchart. */ public virtual void SetIntegerVariable(string key, int value) { foreach (Variable v in variables) { if (v.key == key) { IntegerVariable variable = v as IntegerVariable; if (variable != null) { variable.value = value; return; } } } Debug.LogWarning("Integer variable " + key + " not found."); } /** * Gets the value of a float variable. * Returns 0 if the variable key does not exist. */ public virtual float GetFloatVariable(string key) { foreach (Variable v in variables) { if (v.key == key) { FloatVariable variable = v as FloatVariable; if (variable != null) { return variable.value; } } } Debug.LogWarning("Float variable " + key + " not found."); return 0f; } /** * Sets the value of a float variable. * The variable must already be added to the list of variables for this Flowchart. */ public virtual void SetFloatVariable(string key, float value) { foreach (Variable v in variables) { if (v.key == key) { FloatVariable variable = v as FloatVariable; if (variable != null) { variable.value = value; return; } } } Debug.LogWarning("Float variable " + key + " not found."); } /** * Gets the value of a string variable. * Returns the empty string if the variable key does not exist. */ public virtual string GetStringVariable(string key) { foreach (Variable v in variables) { if (v.key == key) { StringVariable variable = v as StringVariable; if (variable != null) { return variable.value; } } } Debug.LogWarning("String variable " + key + " not found."); return ""; } /** * Sets the value of a string variable. * The variable must already be added to the list of variables for this Flowchart. */ public virtual void SetStringVariable(string key, string value) { foreach (Variable v in variables) { if (v.key == key) { StringVariable variable = v as StringVariable; if (variable != null) { variable.value = value; return; } } } Debug.LogWarning("String variable " + key + " not found."); } /** * Set the block objects to be hidden or visible depending on the hideComponents property. */ public virtual void UpdateHideFlags() { if (hideComponents) { Block[] blocks = GetComponentsInChildren<Block>(); foreach (Block block in blocks) { block.hideFlags = HideFlags.HideInInspector; if (block.gameObject != gameObject) { block.gameObject.hideFlags = HideFlags.HideInHierarchy; } } Command[] commands = GetComponentsInChildren<Command>(); foreach (Command command in commands) { command.hideFlags = HideFlags.HideInInspector; } EventHandler[] eventHandlers = GetComponentsInChildren<EventHandler>(); foreach (EventHandler eventHandler in eventHandlers) { eventHandler.hideFlags = HideFlags.HideInInspector; } } else { MonoBehaviour[] monoBehaviours = GetComponentsInChildren<MonoBehaviour>(); foreach (MonoBehaviour monoBehaviour in monoBehaviours) { if (monoBehaviour == null) { continue; } monoBehaviour.hideFlags = HideFlags.None; monoBehaviour.gameObject.hideFlags = HideFlags.None; } } } public virtual void ClearSelectedCommands() { selectedCommands.Clear(); } public virtual void AddSelectedCommand(Command command) { if (!selectedCommands.Contains(command)) { selectedCommands.Add(command); } } public virtual void Reset(bool resetCommands, bool resetVariables) { if (resetCommands) { Command[] commands = GetComponentsInChildren<Command>(); foreach (Command command in commands) { command.OnReset(); } } if (resetVariables) { foreach (Variable variable in variables) { variable.OnReset(); } } } public virtual string SubstituteVariables(string text) { string subbedText = text; // Instantiate the regular expression object. Regex r = new Regex("{\\$.*?}"); // Match the regular expression pattern against a text string. var results = r.Matches(text); foreach (Match match in results) { string key = match.Value.Substring(2, match.Value.Length - 3); // Look for any matching variables in this Flowchart first (public or private) foreach (Variable variable in variables) { if (variable.key == key) { string value = variable.ToString(); subbedText = subbedText.Replace(match.Value, value); } } // Now search all public variables in all scene Flowcharts in the scene foreach (Flowchart flowchart in cachedFlowcharts) { if (flowchart == this) { // We've already searched this flowchart continue; } foreach (Variable variable in flowchart.variables) { if (variable.scope == VariableScope.Public && variable.key == key) { string value = variable.ToString(); subbedText = subbedText.Replace(match.Value, value); } } } // Next look for matching localized string string localizedString = Localization.GetLocalizedString(key); if (localizedString != null) { subbedText = subbedText.Replace(match.Value, localizedString); } } return subbedText; } } }
Java
/// \file /// \brief SocketLayer class implementation /// /// This file is part of RakNet Copyright 2003 Kevin Jenkins. /// /// Usage of RakNet is subject to the appropriate license agreement. /// Creative Commons Licensees are subject to the /// license found at /// http://creativecommons.org/licenses/by-nc/2.5/ /// Single application licensees are subject to the license found at /// http://www.jenkinssoftware.com/SingleApplicationLicense.html /// Custom license users are subject to the terms therein. /// GPL license users are subject to the GNU General Public /// License as published by the Free /// Software Foundation; either version 2 of the License, or (at your /// option) any later version. #ifndef __SOCKET_LAYER_H #define __SOCKET_LAYER_H #include "RakMemoryOverride.h" #ifdef _XBOX360 #include "Console1Includes.h" #elif defined(_PS3) #include "Console2Includes.h" typedef int SOCKET; #elif defined(_WIN32) // IP_DONTFRAGMENT is different between winsock 1 and winsock 2. Therefore, Winsock2.h must be linked againt Ws2_32.lib // winsock.h must be linked against WSock32.lib. If these two are mixed up the flag won't work correctly #include <winsock2.h> #include <ws2tcpip.h> //#include "RakMemoryOverride.h" #else #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <unistd.h> //#include "RakMemoryOverride.h" /// Unix/Linux uses ints for sockets typedef int SOCKET; #endif //#include "ClientContextStruct.h" class RakPeer; // A platform independent implementation of Berkeley sockets, with settings used by RakNet class SocketLayer : public RakNet::RakMemoryOverride { public: /// Default Constructor SocketLayer(); /// Destructor ~SocketLayer(); // Get the singleton instance of the Socket Layer. /// \return unique instance static inline SocketLayer* Instance() { return & I; } // Connect a socket to a remote host. /// \param[in] writeSocket The local socket. /// \param[in] binaryAddress The address of the remote host. /// \param[in] port the remote port. /// \return A new socket used for communication. SOCKET Connect( SOCKET writeSocket, unsigned int binaryAddress, unsigned short port ); /// Creates a bound socket to listen for incoming connections on the specified port /// \param[in] port the port number /// \param[in] blockingSocket /// \return A new socket used for accepting clients SOCKET CreateBoundSocket( unsigned short port, bool blockingSocket, const char *forceHostAddress ); /// Returns if this specified port is in use, for UDP /// \param[in] port the port number /// \return If this port is already in use static bool IsPortInUse(unsigned short port); #if !defined(_XBOX360) const char* DomainNameToIP( const char *domainName ); #endif /// Start an asynchronous read using the specified socket. The callback will use the specified SystemAddress (associated with this socket) and call either the client or the server callback (one or /// the other should be 0) /// \note Was used for depreciated IO completion ports. bool AssociateSocketWithCompletionPortAndRead( SOCKET readSocket, unsigned int binaryAddress, unsigned short port, RakPeer* rakPeer ); /// Write \a data of length \a length to \a writeSocket /// \param[in] writeSocket The socket to write to /// \param[in] data The data to write /// \param[in] length The length of \a data void Write( const SOCKET writeSocket, const char* data, const int length ); /// Read data from a socket /// \param[in] s the socket /// \param[in] rakPeer The instance of rakPeer containing the recvFrom C callback /// \param[in] errorCode An error code if an error occured . /// \param[in] connectionSocketIndex Which of the sockets in RakPeer we are using /// \return Returns true if you successfully read data, false on error. int RecvFrom( const SOCKET s, RakPeer *rakPeer, int *errorCode, unsigned connectionSocketIndex ); #if !defined(_XBOX360) /// Retrieve all local IP address in a string format. /// \param[in] s The socket whose port we are referring to /// \param[in] ipList An array of ip address in dotted notation. void GetMyIP( char ipList[ 10 ][ 16 ] ); #endif /// Call sendto (UDP obviously) /// \param[in] s the socket /// \param[in] data The byte buffer to send /// \param[in] length The length of the \a data in bytes /// \param[in] ip The address of the remote host in dotted notation. /// \param[in] port The port number to send to. /// \return 0 on success, nonzero on failure. int SendTo( SOCKET s, const char *data, int length, const char ip[ 16 ], unsigned short port ); /// Call sendto (UDP obviously) /// It won't reach the recipient, except on a LAN /// However, this is good for opening routers / firewalls /// \param[in] s the socket /// \param[in] data The byte buffer to send /// \param[in] length The length of the \a data in bytes /// \param[in] ip The address of the remote host in dotted notation. /// \param[in] port The port number to send to. /// \param[in] ttl Max hops of datagram /// \return 0 on success, nonzero on failure. int SendToTTL( SOCKET s, const char *data, int length, const char ip[ 16 ], unsigned short port, int ttl ); /// Call sendto (UDP obviously) /// \param[in] s the socket /// \param[in] data The byte buffer to send /// \param[in] length The length of the \a data in bytes /// \param[in] binaryAddress The address of the remote host in binary format. /// \param[in] port The port number to send to. /// \return 0 on success, nonzero on failure. int SendTo( SOCKET s, const char *data, int length, unsigned int binaryAddress, unsigned short port ); /// Returns the local port, useful when passing 0 as the startup port. /// \param[in] s The socket whose port we are referring to /// \return The local port unsigned short GetLocalPort ( SOCKET s ); private: static bool socketLayerStarted; #ifdef _WIN32 static WSADATA winsockInfo; #endif static SocketLayer I; }; #endif
Java
{%= author.name %}
Java
<div class="comment-view mb-6"> {% if not comment_list %} <div class="no-comment"> <p class="text-muted small">{{ _("No comments yet. ") }} <span class="hidden login-required"> <a href="/login?redirect-to={{ pathname }}">{{ _("Login to start a new discussion") }}</a> </span> <span class="hidden start-discussion">{{ _("Start a new discussion") }}</span> </p> </div> {% endif %} {% if not is_communication %} <div class="add-comment-section mb-5"> <div class="comment-form-wrapper"> <div id="comment-form"> <form class="new-comment"> <fieldset class="new-comment-fields"> <div class="user-details row" style="margin-bottom: 15px; display:none;"> <div class="comment-by col-sm-6 pb-4"> <div class="form-label mb-1">{{ _("Your Name") }}</div> <input class="form-control comment_by" name="comment_by" type="text"> </div> <div class="col-sm-6"> <div class="form-label mb-1">{{ _("Email") }}</div> <input class="form-control comment_email" name="comment_email" type="email"> </div> </div> <div class="comment-text-area"> <div class="form-label mb-1">{{ _("Add a comment") }}</div> <textarea class="form-control" name="comment" rows=5 ></textarea> <div class="text-muted small mt-1 mb-4">{{ _("Ctrl+Enter to add comment") }}</div> </div> <button class="btn btn-sm small" id="submit-comment">{{ _("Comment") }}</button> </fieldset> </form> </div> </div> </div> {% endif %} <hr class="add-comment-hr my-5"> <div itemscope itemtype="http://schema.org/UserComments" id="comment-list"> <div class="add-comment mb-5"> <div class="timeline-dot"></div> <button class="btn btn-sm small add-comment-button">{{ _("Add a comment") }}</button> </div> <div class="comment-list"> {% for comment in comment_list %} {% include "templates/includes/comments/comment.html" %} {% endfor %} </div> </div> </div> <script> frappe.ready(function() { let guest_allowed = parseInt("{{ guest_allowed or 0}}"); let comment_count = "{{ comment_text }}"; let full_name = "" let user_id = ""; let update_timeline_line_length = function(direction, size) { if (direction == 'top') { $('.blog-container')[0].style.setProperty('--comment-timeline-top', size); } else { let comment_timeline_bottom = $('.comment-list .comment-row:last-child').height() - 10; $('.blog-container')[0].style.setProperty('--comment-timeline-bottom', comment_timeline_bottom +'px'); } } let show_comment_box = function() { $('.comment-form-wrapper').show(); update_timeline_line_length('top', '-20px'); $('.add-comment-hr').hide(); $('.add-comment').hide(); } let hide_comment_box = function() { $('.comment-form-wrapper').hide(); update_timeline_line_length('top', '8px'); update_timeline_line_length('bottom'); $('.add-comment-hr').show(); $('.add-comment').show(); } let $comment_count = $(` <div class="feedback-item"> <span class="comment-icon">${frappe.utils.icon('small-message', 'md')}</span> <span class="comment-count"></span> </div> `); $('form').keydown(function(event) { if (event.ctrlKey && event.keyCode === 13) { $(this).find('#submit-comment').trigger('click'); } }) if (!frappe.is_user_logged_in()) { $(".user-details").toggle('hide'); if (guest_allowed) { $('.start-discussion').removeClass('hidden'); } else { $(".login-required, .comment-form-wrapper").toggleClass("hidden"); $('.add-comment-button').text('{{ _("Login to comment") }}'); $('.add-comment-button').click(() => { window.location.href = '/login?redirect-to={{ pathname }}'; }); } } else { $('input.comment_by').prop("disabled", true); $('input.comment_email').prop("disabled", true); full_name = frappe.get_cookie("full_name"); user_id = frappe.get_cookie("user_id"); if(user_id != "Guest") { $("[name='comment_email']").val(user_id); $("[name='comment_by']").val(full_name); } $('.start-discussion').removeClass('hidden'); } $('.blog-feedback').append($comment_count); $('.comment-count').text(comment_count); $("#comment-form textarea").val(""); update_timeline_line_length('bottom'); let n_comments = $(".comment-row").length; n_comments ? $(".no_comment").toggle(false) : show_comment_box(); if(n_comments > 50) { $(".add-comment").toggle(false) .parent().append("<div class='text-muted'>Comments are closed.</div>") } $('.add-comment-button').click(() => { show_comment_box(); }); $("#submit-comment").click(function() { var args = { comment_by: $("[name='comment_by']").val(), comment_email: $("[name='comment_email']").val(), comment: $("[name='comment']").val(), reference_doctype: "{{ reference_doctype or doctype }}", reference_name: "{{ reference_name or name }}", comment_type: "Comment", route: "{{ pathname }}", } if(!args.comment_by || !args.comment_email || !args.comment) { frappe.msgprint('{{ _("All fields are necessary to submit the comment.") }}'); return false; } if (args.comment_email!=='Administrator' && !validate_email(args.comment_email)) { frappe.msgprint('{{ _("Please enter a valid email address.") }}'); return false; } if(!args.comment || !args.comment.trim()) { frappe.msgprint('{{ _("Please add a valid comment.") }}'); return false; } frappe.call({ btn: this, type: "POST", method: "frappe.templates.includes.comments.comments.add_comment", args: args, callback: function(r) { if(r.exc) { if(r._server_messages) frappe.msgprint(r._server_messages); } else { if (r.message) { $(r.message).prependTo(".comment-list"); comment_count = cint(comment_count) + 1; $('.comment-count').text(comment_count); } $(".no-comment").toggle(false); $("#comment-form textarea").val(""); hide_comment_box(); } } }) return false; }); }); </script>
Java
// // RHCoreDataTableViewController.h // // Copyright (C) 2013 by Christopher Meyer // http://schwiiz.org/ // // 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. #import <CoreData/CoreData.h> @import UIKit; @interface RHCoreDataTableViewController : UITableViewController<NSFetchedResultsControllerDelegate, UISearchDisplayDelegate, UISearchBarDelegate> { NSFetchedResultsController *fetchedResultsController; } @property (nonatomic, strong) NSFetchedResultsController *fetchedResultsController; @property (nonatomic, strong) UISearchDisplayController *searchController; @property (nonatomic, strong) NSString *searchString; @property (nonatomic, assign) BOOL massUpdate; @property (nonatomic, assign) BOOL enableSectionIndex; -(void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath; -(void)addSearchBarWithPlaceHolder:(NSString *)placeholder; // -(void)removeSearchBar; -(void)resetMassUpdate; -(void)refreshVisibleCells; -(UITableView *)currentTableView; @end
Java
// Copyright 2016 The Gogs Authors. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. package gitutil import ( "html/template" "testing" dmp "github.com/sergi/go-diff/diffmatchpatch" "github.com/stretchr/testify/assert" "github.com/gogs/git-module" ) func Test_diffsToHTML(t *testing.T) { tests := []struct { diffs []dmp.Diff lineType git.DiffLineType expHTML template.HTML }{ { diffs: []dmp.Diff{ {Type: dmp.DiffEqual, Text: "foo "}, {Type: dmp.DiffInsert, Text: "bar"}, {Type: dmp.DiffDelete, Text: " baz"}, {Type: dmp.DiffEqual, Text: " biz"}, }, lineType: git.DiffLineAdd, expHTML: template.HTML(`+foo <span class="added-code">bar</span> biz`), }, { diffs: []dmp.Diff{ {Type: dmp.DiffEqual, Text: "foo "}, {Type: dmp.DiffDelete, Text: "bar"}, {Type: dmp.DiffInsert, Text: " baz"}, {Type: dmp.DiffEqual, Text: " biz"}, }, lineType: git.DiffLineDelete, expHTML: template.HTML(`-foo <span class="removed-code">bar</span> biz`), }, } for _, test := range tests { t.Run("", func(t *testing.T) { assert.Equal(t, test.expHTML, diffsToHTML(test.diffs, test.lineType)) }) } }
Java
#!/bin/sh set -e echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" install_framework() { if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then local source="${BUILT_PRODUCTS_DIR}/$1" elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")" elif [ -r "$1" ]; then local source="$1" fi local destination="${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" if [ -L "${source}" ]; then echo "Symlinked..." source="$(readlink "${source}")" fi # use filter instead of exclude so missing patterns dont' throw errors echo "rsync -av --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\"" rsync -av --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}" local basename basename="$(basename -s .framework "$1")" binary="${destination}/${basename}.framework/${basename}" if ! [ -r "$binary" ]; then binary="${destination}/${basename}" fi # Strip invalid architectures so "fat" simulator / device frameworks work on device if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then strip_invalid_archs "$binary" fi # Resign the code if required by the build settings to avoid unstable apps code_sign_if_enabled "${destination}/$(basename "$1")" # Embed linked Swift runtime libraries. No longer necessary as of Xcode 7. if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then local swift_runtime_libs swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u && exit ${PIPESTATUS[0]}) for lib in $swift_runtime_libs; do echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\"" rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}" code_sign_if_enabled "${destination}/${lib}" done fi } # Signs a framework with the provided identity code_sign_if_enabled() { if [ -n "${EXPANDED_CODE_SIGN_IDENTITY}" -a "${CODE_SIGNING_REQUIRED}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then # Use the current code_sign_identitiy echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}" local code_sign_cmd="/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS} --preserve-metadata=identifier,entitlements '$1'" if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then code_sign_cmd="$code_sign_cmd &" fi echo "$code_sign_cmd" eval "$code_sign_cmd" fi } # Strip invalid architectures strip_invalid_archs() { binary="$1" # Get architectures for current file archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | rev)" stripped="" for arch in $archs; do if ! [[ "${VALID_ARCHS}" == *"$arch"* ]]; then # Strip non-valid architectures in-place lipo -remove "$arch" -output "$binary" "$binary" || exit 1 stripped="$stripped $arch" fi done if [[ "$stripped" ]]; then echo "Stripped $binary of architectures:$stripped" fi } if [[ "$CONFIGURATION" == "Debug" ]]; then install_framework "$BUILT_PRODUCTS_DIR/ReactiveObjC/ReactiveObjC.framework" fi if [[ "$CONFIGURATION" == "Release" ]]; then install_framework "$BUILT_PRODUCTS_DIR/ReactiveObjC/ReactiveObjC.framework" fi if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then wait fi
Java
<?php include 'Vehicle.php'; include 'Car.php'; $car = new Car(4, 'Red', 'Audi', 'A4', 2016); print_r($car); echo "<br>"; $car->setColor('Green'); print_r($car);
Java
--- title: لمزيد من الدرس date: 25/06/2021 --- لِمَزِيد مِنْ الدَّرس: حول التطهير الأخير للأرض من الْخَطِيَّة اقرأ من كتاب الصراع العظيم صفحة ٧١٥-٧٣٢. «وإذ تمر سنو الأبدية فستأتي بإعلانات أغنى وأمجد عن الله والمسيح. وكما تتجدّد المعرفة فكذلك ستتجدّد المحبة والوقار والسعادة وتزيد أَيْضًا. وكلما عرف الناس أشياء أكثر عن الله زاد إعجابهم بصفاته. وإذ يكشف يسوع أَمَامهم غنى الفداء والأعمال العظيمة المدهشة في الصراع الهائل مع الشيطان فإن قلوب المفتدين تختلج بتعبّد حار عميق، وبفرح مذهل للعقل يضربون على قيثاراتهم الذهبية فتتحد ربوات ربوات وألوف ألوف من الأصوات في إنشاد أغنية الحمد العظيمة. « ‹وَكُلُّ خَلِيقَةٍ مِمَّا فِي السَّمَاءِ وَعَلَى الأَرْض وَتَحْتَ الأَرْض، وَمَا عَلَى الْبَحْرِ، كُلُّ مَا فِيهَا، سَمِعْتُهَا قَائِلَةً: لِلْجَالِسِ عَلَى الْعَرْشِ وَلِلْخَرُوفِ الْبَرَكَةُ وَالْكَرَامَةُ وَالْمَجْدُ وَالسُّلْطَانُ إلى الأبدين.› (رؤيا ٥: ١٣). «لقد انتهى الصّراع العظيم. وما عاد للخطيئة أو للخطاة وجود. وقد صارت المسكونة كلها طاهرة. وفي عاطفة واحدة مِن الوفاق والفرح يشترك كل الخلائق. ومَن ذاك الذي قد خَلق الجميع تفيض الحياة والنور والبهجة في كل الأقاليم في الفضاء الذي لا حدود له. فمن أصغر ذرة إلى أعظم كوكب، مِن حي إلى جماد، بجمالها وكمالها – كلّها تشهد شهادة واحدة قائلة: الله محبة» (روح النُّبُوَّة، الصراع العظيم، صفحة ٧٣٢). **أسئلة للنقاش** `١. قال الكاتب فرانسيسكو غوزي مورينو، «إننا نرى ذواتنا في ضوء ومنظور الكون ذات النظام المتناغم، فندرك جهلنا وعجزنا النهائي، وبالتالي شعورنا بعدم الأمان. ونتيجة لذلك نخاف» [بين الإيمان العقل: الخوف الأساسي والحالة الإنسانية، (مطبعة نيويورك هاربر، ١٩٧٧، صفحة ٦]. قارن هذه العبارة مع ما درسته هذا الأسبوع من أفسس ٣: ١٧-١٩. ناقش الاختلافات بين العبارتين.` `٢. يَعِدنَا الله بالفرح كمؤمنين بالمسيح. هل الفرح هو ذاته مثل السعادة؟ وهل يتوجَّب علينا أنْ نكون دائمًا فرحين؟ وإذا لم يكن الأمر كذلك، فهل يوجد شيء ما ليس على ما يرام في اختبارنا المسيحي؟ ماذا يمكن لحياة المسيح أن تُظهِره لنا ممَّا يساعدنا على فهم الأجوبة لهذه الأسئلة؟` `٣. ناقش وتعمّق أكثر في فكرة كوننا ممتلئين «إِلَى كُلِّ مِلْءِ اللهِ» (أفسس ٣: ١٩). ماذا يعني ذلك؟ وكيف لنا أن نختبر ذلك في حياتنا؟` **مُلَخَّص الدَّرس**: ليس العَهْد مجرد أفكار لاهوتية عميقة، بل هو بالأحرى يُعَرِّف عُمق علاقتنا الخلاصية مع المسيح، وتلك العلاقة تنيلنا حصادًا وفيرًا من الفوائد العجيبة الآن، وبخاصة في وقت عودة المسيح.
Java
<script type="text/javascript"> var _d = DialogManager.get('config_dialog'); _d.setWidth(350); _d.setPosition('center'); $("select[ectype='bgcolor_selector']").change(function(){ $("input[ectype='bgcolor']").val(this.value); }); $("select[name='img_recom_id']").change(function(){ switchRecommend(this.value, 'img_cate_id'); }); $("select[name='txt_recom_id']").change(function(){ switchRecommend(this.value, 'txt_cate_id'); }); switchRecommend($("select[name='img_recom_id']").val(), 'img_cate_id'); switchRecommend($("select[name='txt_recom_id']").val(), 'txt_cate_id'); function switchRecommend(recomId, selectName) { if (recomId >= 0) { $("select[name='" + selectName + "']").hide(); } else { $("select[name='" + selectName + "']").show(); } } </script> <div class="field_item"> <label>模块名称:</label> <p><input type="text" name="module_name" value="{$options.module_name}" /></p> </div> <div class="field_item"> <label>背景色:(<span>格式:#332211</span>)</label> <p><input type="text" name="bgcolor" ectype="bgcolor" value="{$options.bgcolor}" /> <select ectype="bgcolor_selector" style="width:100px"> <option value="">请选择...</option> <option value="#bbc5d6" style="background:#bbc5d6"></option> <option value="#a7d8c8" style="background:#a7d8c8"></option> <option value="#a3c9ee" style="background:#a3c9ee"></option> <option value="#9fd9dd" style="background:#9fd9dd"></option> <option value="#b9afd4" style="background:#b9afd4"></option> <option value="#dcad7f" style="background:#dcad7f"></option> <option value="#c4d568" style="background:#c4d568"></option> <option value="#dcc972" style="background:#dcc972"></option> <option value="#e8b5e5" style="background:#e8b5e5"></option> <option value="#ecb8bc" style="background:#ecb8bc"></option> </select></p> </div> <div class="field_item"> <label>热门关键字:(<span>多个关键字之间用空格隔开</span>)</label> <p><input type="text" name="keyword_list" value="{$options.keyword_list}" /></p> </div> <div class="field_item"> <label>上传广告图片:(<span>图片尺寸:210*280,支持 gif|jpg|jpeg|png 格式</span>)</label> <p><input type="file" name="ad_image_file" /><input type="hidden" name="ad_image_url" value="{$options.ad_image_url}" /></p> <!-- {if $options.ad_image_url} --><p><img src="{$options.ad_image_url}" height="20" /></p><!-- {/if} --> </div> <div class="field_item"> <label>广告链接地址:</label> <p><input type="text" name="ad_link_url" value="{$options.ad_link_url}" /></p> </div> <div class="field_item"> <label>图片推荐类型:</label> <p><select name="img_recom_id"> <option value="0">请选择...</option> <!-- {foreach from=$recommends key=recom_id item=recom_name} --> <option value="{$recom_id}"{if $options.img_recom_id eq $recom_id} selected="selected"{/if}>{$recom_name|escape}</option> <!-- {/foreach} --> </select> <select name="img_cate_id"> <option value="0">请选择分类...</option> <!-- {html_options options=$gcategories selected=$options.img_cate_id} --> </select></p> </div> <div class="field_item"> <label>文字推荐类型:</label> <p><select name="txt_recom_id"> <option value="0">请选择...</option> <!-- {foreach from=$recommends key=recom_id item=recom_name} --> <option value="{$recom_id}"{if $options.txt_recom_id eq $recom_id} selected="selected"{/if}>{$recom_name|escape}</option> <!-- {/foreach} --> </select> <select name="txt_cate_id"> <option value="0">请选择分类...</option> <!-- {html_options options=$gcategories selected=$options.txt_cate_id} --> </select></p> </div>
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd"> <!-- NewPage --> <html lang="sv"> <head> <!-- Generated by javadoc on Fri Mar 18 12:42:22 CET 2016 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>IV1201 1.0-SNAPSHOT API</title> <script type="text/javascript"> targetPage = "" + window.location.search; if (targetPage != "" && targetPage != "undefined") targetPage = targetPage.substring(1); if (targetPage.indexOf(":") != -1 || (targetPage != "" && !validURL(targetPage))) targetPage = "undefined"; function validURL(url) { try { url = decodeURIComponent(url); } catch (error) { return false; } var pos = url.indexOf(".html"); if (pos == -1 || pos != url.length - 5) return false; var allowNumber = false; var allowSep = false; var seenDot = false; for (var i = 0; i < url.length - 5; i++) { var ch = url.charAt(i); if ('a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || ch == '$' || ch == '_' || ch.charCodeAt(0) > 127) { allowNumber = true; allowSep = true; } else if ('0' <= ch && ch <= '9' || ch == '-') { if (!allowNumber) return false; } else if (ch == '/' || ch == '.') { if (!allowSep) return false; allowNumber = false; allowSep = false; if (ch == '.') seenDot = true; if (ch == '/' && seenDot) return false; } else { return false; } } return true; } function loadFrames() { if (targetPage != "" && targetPage != "undefined") top.classFrame.location = top.targetPage; } </script> </head> <frameset cols="20%,80%" title="Documentation frame" onload="top.loadFrames()"> <frameset rows="30%,70%" title="Left frames" 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> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <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. Link to <a href="overview-summary.html">Non-frame version</a>.</p> </noframes> </frameset> </html>
Java
# meteor-intro Intro to Meteor
Java
package com.xeiam.xchange.anx.v2.account.polling; import java.io.IOException; import java.io.InputStream; import java.math.BigDecimal; import org.junit.Assert; import org.junit.Test; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.xeiam.xchange.anx.v2.dto.account.polling.ANXWalletHistoryWrapper; //import static org.fest.assertions.api.Assertions.assertThat; /** * Test ANXWalletHistory JSON parsing */ public class WalletHistoryJSONTest { @Test public void testUnmarshal() throws IOException { // Read in the JSON from the example resources InputStream is = WalletHistoryJSONTest.class.getResourceAsStream("/v2/account/example-wallethistory-response.json"); // Use Jackson to parse it ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); ANXWalletHistoryWrapper anxWalletHistoryWrapper = mapper.readValue(is, ANXWalletHistoryWrapper.class); Assert.assertTrue(anxWalletHistoryWrapper.getANXWalletHistory() != null); Assert.assertTrue(anxWalletHistoryWrapper.getANXWalletHistory().getRecords() == 104); Assert.assertTrue(anxWalletHistoryWrapper.getANXWalletHistory().getCurrentPage() == 1); Assert.assertTrue(anxWalletHistoryWrapper.getANXWalletHistory().getMaxPage() == 3); Assert.assertTrue(anxWalletHistoryWrapper.getANXWalletHistory().getMaxResults() == 50); Assert.assertTrue(anxWalletHistoryWrapper.getANXWalletHistory().getANXWalletHistoryEntries().length == 50); Assert.assertEquals("BTC bought: [tid:264f7b7f-f70c-4fc6-ba27-2bcf33b6cd51] 10.00000000 BTC at 280.65500 HKD", anxWalletHistoryWrapper.getANXWalletHistory().getANXWalletHistoryEntries()[0] .getInfo()); Assert.assertEquals(104, anxWalletHistoryWrapper.getANXWalletHistory().getANXWalletHistoryEntries()[0].getIndex()); Assert.assertEquals("1394594770000", anxWalletHistoryWrapper.getANXWalletHistory().getANXWalletHistoryEntries()[0].getDate()); Assert.assertEquals("fee", anxWalletHistoryWrapper.getANXWalletHistory().getANXWalletHistoryEntries()[0].getType()); Assert.assertEquals("BTC", anxWalletHistoryWrapper.getANXWalletHistory().getANXWalletHistoryEntries()[0].getValue().getCurrency()); // Assert.assertEquals(new BigDecimal(0), // anxWalletHistoryWrapper.getANXWalletHistory().getANXWalletHistoryEntries()[0].getValue().getValue()); Assert.assertEquals(new BigDecimal("103168.75400000"), anxWalletHistoryWrapper.getANXWalletHistory().getANXWalletHistoryEntries()[0].getBalance().getValue()); Assert.assertEquals("cc496636-4849-4acf-a390-e4091a5009c3", anxWalletHistoryWrapper.getANXWalletHistory().getANXWalletHistoryEntries()[0].getTrade().getOid()); Assert.assertEquals("264f7b7f-f70c-4fc6-ba27-2bcf33b6cd51", anxWalletHistoryWrapper.getANXWalletHistory().getANXWalletHistoryEntries()[0].getTrade().getTid()); Assert.assertEquals(new BigDecimal("10.00000000"), anxWalletHistoryWrapper.getANXWalletHistory().getANXWalletHistoryEntries()[0].getTrade().getAmount().getValue()); Assert.assertEquals("market", anxWalletHistoryWrapper.getANXWalletHistory().getANXWalletHistoryEntries()[0].getTrade().getProperties()); } }
Java
#ifdef HAVE_WINRT #define ICustomStreamSink StreamSink #ifndef __cplusplus_winrt #define __is_winrt_array(type) (type == ABI::Windows::Foundation::PropertyType::PropertyType_UInt8Array || type == ABI::Windows::Foundation::PropertyType::PropertyType_Int16Array ||\ type == ABI::Windows::Foundation::PropertyType::PropertyType_UInt16Array || type == ABI::Windows::Foundation::PropertyType::PropertyType_Int32Array ||\ type == ABI::Windows::Foundation::PropertyType::PropertyType_UInt32Array || type == ABI::Windows::Foundation::PropertyType::PropertyType_Int64Array ||\ type == ABI::Windows::Foundation::PropertyType::PropertyType_UInt64Array || type == ABI::Windows::Foundation::PropertyType::PropertyType_SingleArray ||\ type == ABI::Windows::Foundation::PropertyType::PropertyType_DoubleArray || type == ABI::Windows::Foundation::PropertyType::PropertyType_Char16Array ||\ type == ABI::Windows::Foundation::PropertyType::PropertyType_BooleanArray || type == ABI::Windows::Foundation::PropertyType::PropertyType_StringArray ||\ type == ABI::Windows::Foundation::PropertyType::PropertyType_InspectableArray || type == ABI::Windows::Foundation::PropertyType::PropertyType_DateTimeArray ||\ type == ABI::Windows::Foundation::PropertyType::PropertyType_TimeSpanArray || type == ABI::Windows::Foundation::PropertyType::PropertyType_GuidArray ||\ type == ABI::Windows::Foundation::PropertyType::PropertyType_PointArray || type == ABI::Windows::Foundation::PropertyType::PropertyType_SizeArray ||\ type == ABI::Windows::Foundation::PropertyType::PropertyType_RectArray || type == ABI::Windows::Foundation::PropertyType::PropertyType_OtherTypeArray) template<typename _Type, bool bUnknown = std::is_base_of<IUnknown, _Type>::value> struct winrt_type { }; template<typename _Type> struct winrt_type<_Type, true> { static IUnknown* create(_Type* _ObjInCtx) { return reinterpret_cast<IUnknown*>(_ObjInCtx); } static IID getuuid() { return __uuidof(_Type); } static const ABI::Windows::Foundation::PropertyType _PropType = ABI::Windows::Foundation::PropertyType::PropertyType_OtherType; }; template <typename _Type> struct winrt_type<_Type, false> { static IUnknown* create(_Type* _ObjInCtx) { Microsoft::WRL::ComPtr<IInspectable> _PObj; Microsoft::WRL::ComPtr<IActivationFactory> objFactory; HRESULT hr = Windows::Foundation::GetActivationFactory(Microsoft::WRL::Wrappers::HStringReference(RuntimeClass_Windows_Foundation_PropertyValue).Get(), objFactory.ReleaseAndGetAddressOf()); if (FAILED(hr)) return nullptr; Microsoft::WRL::ComPtr<ABI::Windows::Foundation::IPropertyValueStatics> spPropVal; if (SUCCEEDED(hr)) hr = objFactory.As(&spPropVal); if (SUCCEEDED(hr)) { hr = winrt_type<_Type>::create(spPropVal.Get(), _ObjInCtx, _PObj.GetAddressOf()); if (SUCCEEDED(hr)) return reinterpret_cast<IUnknown*>(_PObj.Detach()); } return nullptr; } static IID getuuid() { return __uuidof(ABI::Windows::Foundation::IPropertyValue); } static const ABI::Windows::Foundation::PropertyType _PropType = ABI::Windows::Foundation::PropertyType::PropertyType_OtherType; }; template<> struct winrt_type<void> { static HRESULT create(ABI::Windows::Foundation::IPropertyValueStatics* spPropVal, void* _ObjInCtx, IInspectable** ppInsp) { (void)_ObjInCtx; return spPropVal->CreateEmpty(ppInsp); } static const ABI::Windows::Foundation::PropertyType _PropType = ABI::Windows::Foundation::PropertyType::PropertyType_Empty; }; #define MAKE_TYPE(Type, Name) template<>\ struct winrt_type<Type>\ {\ static HRESULT create(ABI::Windows::Foundation::IPropertyValueStatics* spPropVal, Type* _ObjInCtx, IInspectable** ppInsp) {\ return spPropVal->Create##Name(*_ObjInCtx, ppInsp);\ }\ static const ABI::Windows::Foundation::PropertyType _PropType = ABI::Windows::Foundation::PropertyType::PropertyType_##Name;\ }; template<typename _Type> struct winrt_array_type { static IUnknown* create(_Type* _ObjInCtx, size_t N) { Microsoft::WRL::ComPtr<IInspectable> _PObj; Microsoft::WRL::ComPtr<IActivationFactory> objFactory; HRESULT hr = Windows::Foundation::GetActivationFactory(Microsoft::WRL::Wrappers::HStringReference(RuntimeClass_Windows_Foundation_PropertyValue).Get(), objFactory.ReleaseAndGetAddressOf()); if (FAILED(hr)) return nullptr; Microsoft::WRL::ComPtr<ABI::Windows::Foundation::IPropertyValueStatics> spPropVal; if (SUCCEEDED(hr)) hr = objFactory.As(&spPropVal); if (SUCCEEDED(hr)) { hr = winrt_array_type<_Type>::create(spPropVal.Get(), N, _ObjInCtx, _PObj.GetAddressOf()); if (SUCCEEDED(hr)) return reinterpret_cast<IUnknown*>(_PObj.Detach()); } return nullptr; } static const ABI::Windows::Foundation::PropertyType _PropType = ABI::Windows::Foundation::PropertyType::PropertyType_OtherTypeArray; }; template<int> struct winrt_prop_type {}; template <> struct winrt_prop_type<ABI::Windows::Foundation::PropertyType_Empty> { typedef void _Type; }; template <> struct winrt_prop_type<ABI::Windows::Foundation::PropertyType_OtherType> { typedef void _Type; }; template <> struct winrt_prop_type<ABI::Windows::Foundation::PropertyType_OtherTypeArray> { typedef void _Type; }; #define MAKE_PROP(Prop, Type) template <>\ struct winrt_prop_type<ABI::Windows::Foundation::PropertyType_##Prop> {\ typedef Type _Type;\ }; #define MAKE_ARRAY_TYPE(Type, Name) MAKE_PROP(Name, Type)\ MAKE_PROP(Name##Array, Type*)\ MAKE_TYPE(Type, Name)\ template<>\ struct winrt_array_type<Type*>\ {\ static HRESULT create(ABI::Windows::Foundation::IPropertyValueStatics* spPropVal, UINT32 __valueSize, Type** _ObjInCtx, IInspectable** ppInsp) {\ return spPropVal->Create##Name##Array(__valueSize, *_ObjInCtx, ppInsp);\ }\ static const ABI::Windows::Foundation::PropertyType _PropType = ABI::Windows::Foundation::PropertyType::PropertyType_##Name##Array;\ static std::vector<Type> PropertyValueToVector(ABI::Windows::Foundation::IPropertyValue* propValue)\ {\ UINT32 uLen = 0;\ Type* pArray = nullptr;\ propValue->Get##Name##Array(&uLen, &pArray);\ return std::vector<Type>(pArray, pArray + uLen);\ }\ }; MAKE_ARRAY_TYPE(BYTE, UInt8) MAKE_ARRAY_TYPE(INT16, Int16) MAKE_ARRAY_TYPE(UINT16, UInt16) MAKE_ARRAY_TYPE(INT32, Int32) MAKE_ARRAY_TYPE(UINT32, UInt32) MAKE_ARRAY_TYPE(INT64, Int64) MAKE_ARRAY_TYPE(UINT64, UInt64) MAKE_ARRAY_TYPE(FLOAT, Single) MAKE_ARRAY_TYPE(DOUBLE, Double) MAKE_ARRAY_TYPE(WCHAR, Char16) //MAKE_ARRAY_TYPE(boolean, Boolean) //conflict with identical type in C++ of BYTE/UInt8 MAKE_ARRAY_TYPE(HSTRING, String) MAKE_ARRAY_TYPE(IInspectable*, Inspectable) MAKE_ARRAY_TYPE(GUID, Guid) MAKE_ARRAY_TYPE(ABI::Windows::Foundation::DateTime, DateTime) MAKE_ARRAY_TYPE(ABI::Windows::Foundation::TimeSpan, TimeSpan) MAKE_ARRAY_TYPE(ABI::Windows::Foundation::Point, Point) MAKE_ARRAY_TYPE(ABI::Windows::Foundation::Size, Size) MAKE_ARRAY_TYPE(ABI::Windows::Foundation::Rect, Rect) template < typename T > struct DerefHelper { typedef T DerefType; }; template < typename T > struct DerefHelper<T*> { typedef T DerefType; }; #define __is_valid_winrt_type(_Type) (std::is_void<_Type>::value || \ std::is_same<_Type, BYTE>::value || \ std::is_same<_Type, INT16>::value || \ std::is_same<_Type, UINT16>::value || \ std::is_same<_Type, INT32>::value || \ std::is_same<_Type, UINT32>::value || \ std::is_same<_Type, INT64>::value || \ std::is_same<_Type, UINT64>::value || \ std::is_same<_Type, FLOAT>::value || \ std::is_same<_Type, DOUBLE>::value || \ std::is_same<_Type, WCHAR>::value || \ std::is_same<_Type, boolean>::value || \ std::is_same<_Type, HSTRING>::value || \ std::is_same<_Type, IInspectable *>::value || \ std::is_base_of<Microsoft::WRL::Details::RuntimeClassBase, _Type>::value || \ std::is_base_of<IInspectable, typename DerefHelper<_Type>::DerefType>::value || \ std::is_same<_Type, GUID>::value || \ std::is_same<_Type, ABI::Windows::Foundation::DateTime>::value || \ std::is_same<_Type, ABI::Windows::Foundation::TimeSpan>::value || \ std::is_same<_Type, ABI::Windows::Foundation::Point>::value || \ std::is_same<_Type, ABI::Windows::Foundation::Size>::value || \ std::is_same<_Type, ABI::Windows::Foundation::Rect>::value || \ std::is_same<_Type, BYTE*>::value || \ std::is_same<_Type, INT16*>::value || \ std::is_same<_Type, UINT16*>::value || \ std::is_same<_Type, INT32*>::value || \ std::is_same<_Type, UINT32*>::value || \ std::is_same<_Type, INT64*>::value || \ std::is_same<_Type, UINT64*>::value || \ std::is_same<_Type, FLOAT*>::value || \ std::is_same<_Type, DOUBLE*>::value || \ std::is_same<_Type, WCHAR*>::value || \ std::is_same<_Type, boolean*>::value || \ std::is_same<_Type, HSTRING*>::value || \ std::is_same<_Type, IInspectable **>::value || \ std::is_same<_Type, GUID*>::value || \ std::is_same<_Type, ABI::Windows::Foundation::DateTime*>::value || \ std::is_same<_Type, ABI::Windows::Foundation::TimeSpan*>::value || \ std::is_same<_Type, ABI::Windows::Foundation::Point*>::value || \ std::is_same<_Type, ABI::Windows::Foundation::Size*>::value || \ std::is_same<_Type, ABI::Windows::Foundation::Rect*>::value) #endif #else EXTERN_C const IID IID_ICustomStreamSink; class DECLSPEC_UUID("4F8A1939-2FD3-46DB-AE70-DB7E0DD79B73") DECLSPEC_NOVTABLE ICustomStreamSink : public IUnknown { public: virtual HRESULT Initialize() = 0; virtual HRESULT Shutdown() = 0; virtual HRESULT Start(MFTIME start) = 0; virtual HRESULT Pause() = 0; virtual HRESULT Restart() = 0; virtual HRESULT Stop() = 0; }; #endif #define MF_PROP_SAMPLEGRABBERCALLBACK L"samplegrabbercallback" #define MF_PROP_VIDTYPE L"vidtype" #define MF_PROP_VIDENCPROPS L"videncprops" #include <initguid.h> // MF_MEDIASINK_SAMPLEGRABBERCALLBACK: {26957AA7-AFF4-464c-BB8B-07BA65CE11DF} // Type: IUnknown* DEFINE_GUID(MF_MEDIASINK_SAMPLEGRABBERCALLBACK, 0x26957aa7, 0xaff4, 0x464c, 0xbb, 0x8b, 0x7, 0xba, 0x65, 0xce, 0x11, 0xdf); // {4BD133CC-EB9B-496E-8865-0813BFBC6FAA} DEFINE_GUID(MF_STREAMSINK_ID, 0x4bd133cc, 0xeb9b, 0x496e, 0x88, 0x65, 0x8, 0x13, 0xbf, 0xbc, 0x6f, 0xaa); // {C9E22A8C-6A50-4D78-9183-0834A02A3780} DEFINE_GUID(MF_STREAMSINK_MEDIASINKINTERFACE, 0xc9e22a8c, 0x6a50, 0x4d78, 0x91, 0x83, 0x8, 0x34, 0xa0, 0x2a, 0x37, 0x80); // {DABD13AB-26B7-47C2-97C1-4B04C187B838} DEFINE_GUID(MF_MEDIASINK_PREFERREDTYPE, 0xdabd13ab, 0x26b7, 0x47c2, 0x97, 0xc1, 0x4b, 0x4, 0xc1, 0x87, 0xb8, 0x38); #include <utility> #ifdef _UNICODE #define MAKE_MAP(e) std::map<e, std::wstring> #define MAKE_ENUM(e) std::pair<e, std::wstring> #define MAKE_ENUM_PAIR(e, str) std::pair<e, std::wstring>(str, L#str) #else #define MAKE_MAP(e) std::map<e, std::string> #define MAKE_ENUM(e) std::pair<e, std::string> #define MAKE_ENUM_PAIR(e, str) std::pair<e, std::string>(str, #str) #endif MAKE_ENUM(MediaEventType) MediaEventTypePairs[] = { MAKE_ENUM_PAIR(MediaEventType, MEUnknown), MAKE_ENUM_PAIR(MediaEventType, MEError), MAKE_ENUM_PAIR(MediaEventType, MEExtendedType), MAKE_ENUM_PAIR(MediaEventType, MENonFatalError), MAKE_ENUM_PAIR(MediaEventType, MEGenericV1Anchor), MAKE_ENUM_PAIR(MediaEventType, MESessionUnknown), MAKE_ENUM_PAIR(MediaEventType, MESessionTopologySet), MAKE_ENUM_PAIR(MediaEventType, MESessionTopologiesCleared), MAKE_ENUM_PAIR(MediaEventType, MESessionStarted), MAKE_ENUM_PAIR(MediaEventType, MESessionPaused), MAKE_ENUM_PAIR(MediaEventType, MESessionStopped), MAKE_ENUM_PAIR(MediaEventType, MESessionClosed), MAKE_ENUM_PAIR(MediaEventType, MESessionEnded), MAKE_ENUM_PAIR(MediaEventType, MESessionRateChanged), MAKE_ENUM_PAIR(MediaEventType, MESessionScrubSampleComplete), MAKE_ENUM_PAIR(MediaEventType, MESessionCapabilitiesChanged), MAKE_ENUM_PAIR(MediaEventType, MESessionTopologyStatus), MAKE_ENUM_PAIR(MediaEventType, MESessionNotifyPresentationTime), MAKE_ENUM_PAIR(MediaEventType, MENewPresentation), MAKE_ENUM_PAIR(MediaEventType, MELicenseAcquisitionStart), MAKE_ENUM_PAIR(MediaEventType, MELicenseAcquisitionCompleted), MAKE_ENUM_PAIR(MediaEventType, MEIndividualizationStart), MAKE_ENUM_PAIR(MediaEventType, MEIndividualizationCompleted), MAKE_ENUM_PAIR(MediaEventType, MEEnablerProgress), MAKE_ENUM_PAIR(MediaEventType, MEEnablerCompleted), MAKE_ENUM_PAIR(MediaEventType, MEPolicyError), MAKE_ENUM_PAIR(MediaEventType, MEPolicyReport), MAKE_ENUM_PAIR(MediaEventType, MEBufferingStarted), MAKE_ENUM_PAIR(MediaEventType, MEBufferingStopped), MAKE_ENUM_PAIR(MediaEventType, MEConnectStart), MAKE_ENUM_PAIR(MediaEventType, MEConnectEnd), MAKE_ENUM_PAIR(MediaEventType, MEReconnectStart), MAKE_ENUM_PAIR(MediaEventType, MEReconnectEnd), MAKE_ENUM_PAIR(MediaEventType, MERendererEvent), MAKE_ENUM_PAIR(MediaEventType, MESessionStreamSinkFormatChanged), MAKE_ENUM_PAIR(MediaEventType, MESessionV1Anchor), MAKE_ENUM_PAIR(MediaEventType, MESourceUnknown), MAKE_ENUM_PAIR(MediaEventType, MESourceStarted), MAKE_ENUM_PAIR(MediaEventType, MEStreamStarted), MAKE_ENUM_PAIR(MediaEventType, MESourceSeeked), MAKE_ENUM_PAIR(MediaEventType, MEStreamSeeked), MAKE_ENUM_PAIR(MediaEventType, MENewStream), MAKE_ENUM_PAIR(MediaEventType, MEUpdatedStream), MAKE_ENUM_PAIR(MediaEventType, MESourceStopped), MAKE_ENUM_PAIR(MediaEventType, MEStreamStopped), MAKE_ENUM_PAIR(MediaEventType, MESourcePaused), MAKE_ENUM_PAIR(MediaEventType, MEStreamPaused), MAKE_ENUM_PAIR(MediaEventType, MEEndOfPresentation), MAKE_ENUM_PAIR(MediaEventType, MEEndOfStream), MAKE_ENUM_PAIR(MediaEventType, MEMediaSample), MAKE_ENUM_PAIR(MediaEventType, MEStreamTick), MAKE_ENUM_PAIR(MediaEventType, MEStreamThinMode), MAKE_ENUM_PAIR(MediaEventType, MEStreamFormatChanged), MAKE_ENUM_PAIR(MediaEventType, MESourceRateChanged), MAKE_ENUM_PAIR(MediaEventType, MEEndOfPresentationSegment), MAKE_ENUM_PAIR(MediaEventType, MESourceCharacteristicsChanged), MAKE_ENUM_PAIR(MediaEventType, MESourceRateChangeRequested), MAKE_ENUM_PAIR(MediaEventType, MESourceMetadataChanged), MAKE_ENUM_PAIR(MediaEventType, MESequencerSourceTopologyUpdated), MAKE_ENUM_PAIR(MediaEventType, MESourceV1Anchor), MAKE_ENUM_PAIR(MediaEventType, MESinkUnknown), MAKE_ENUM_PAIR(MediaEventType, MEStreamSinkStarted), MAKE_ENUM_PAIR(MediaEventType, MEStreamSinkStopped), MAKE_ENUM_PAIR(MediaEventType, MEStreamSinkPaused), MAKE_ENUM_PAIR(MediaEventType, MEStreamSinkRateChanged), MAKE_ENUM_PAIR(MediaEventType, MEStreamSinkRequestSample), MAKE_ENUM_PAIR(MediaEventType, MEStreamSinkMarker), MAKE_ENUM_PAIR(MediaEventType, MEStreamSinkPrerolled), MAKE_ENUM_PAIR(MediaEventType, MEStreamSinkScrubSampleComplete), MAKE_ENUM_PAIR(MediaEventType, MEStreamSinkFormatChanged), MAKE_ENUM_PAIR(MediaEventType, MEStreamSinkDeviceChanged), MAKE_ENUM_PAIR(MediaEventType, MEQualityNotify), MAKE_ENUM_PAIR(MediaEventType, MESinkInvalidated), MAKE_ENUM_PAIR(MediaEventType, MEAudioSessionNameChanged), MAKE_ENUM_PAIR(MediaEventType, MEAudioSessionVolumeChanged), MAKE_ENUM_PAIR(MediaEventType, MEAudioSessionDeviceRemoved), MAKE_ENUM_PAIR(MediaEventType, MEAudioSessionServerShutdown), MAKE_ENUM_PAIR(MediaEventType, MEAudioSessionGroupingParamChanged), MAKE_ENUM_PAIR(MediaEventType, MEAudioSessionIconChanged), MAKE_ENUM_PAIR(MediaEventType, MEAudioSessionFormatChanged), MAKE_ENUM_PAIR(MediaEventType, MEAudioSessionDisconnected), MAKE_ENUM_PAIR(MediaEventType, MEAudioSessionExclusiveModeOverride), MAKE_ENUM_PAIR(MediaEventType, MESinkV1Anchor), #if (WINVER >= 0x0602) // Available since Win 8 MAKE_ENUM_PAIR(MediaEventType, MECaptureAudioSessionVolumeChanged), MAKE_ENUM_PAIR(MediaEventType, MECaptureAudioSessionDeviceRemoved), MAKE_ENUM_PAIR(MediaEventType, MECaptureAudioSessionFormatChanged), MAKE_ENUM_PAIR(MediaEventType, MECaptureAudioSessionDisconnected), MAKE_ENUM_PAIR(MediaEventType, MECaptureAudioSessionExclusiveModeOverride), MAKE_ENUM_PAIR(MediaEventType, MECaptureAudioSessionServerShutdown), MAKE_ENUM_PAIR(MediaEventType, MESinkV2Anchor), #endif MAKE_ENUM_PAIR(MediaEventType, METrustUnknown), MAKE_ENUM_PAIR(MediaEventType, MEPolicyChanged), MAKE_ENUM_PAIR(MediaEventType, MEContentProtectionMessage), MAKE_ENUM_PAIR(MediaEventType, MEPolicySet), MAKE_ENUM_PAIR(MediaEventType, METrustV1Anchor), MAKE_ENUM_PAIR(MediaEventType, MEWMDRMLicenseBackupCompleted), MAKE_ENUM_PAIR(MediaEventType, MEWMDRMLicenseBackupProgress), MAKE_ENUM_PAIR(MediaEventType, MEWMDRMLicenseRestoreCompleted), MAKE_ENUM_PAIR(MediaEventType, MEWMDRMLicenseRestoreProgress), MAKE_ENUM_PAIR(MediaEventType, MEWMDRMLicenseAcquisitionCompleted), MAKE_ENUM_PAIR(MediaEventType, MEWMDRMIndividualizationCompleted), MAKE_ENUM_PAIR(MediaEventType, MEWMDRMIndividualizationProgress), MAKE_ENUM_PAIR(MediaEventType, MEWMDRMProximityCompleted), MAKE_ENUM_PAIR(MediaEventType, MEWMDRMLicenseStoreCleaned), MAKE_ENUM_PAIR(MediaEventType, MEWMDRMRevocationDownloadCompleted), MAKE_ENUM_PAIR(MediaEventType, MEWMDRMV1Anchor), MAKE_ENUM_PAIR(MediaEventType, METransformUnknown), MAKE_ENUM_PAIR(MediaEventType, METransformNeedInput), MAKE_ENUM_PAIR(MediaEventType, METransformHaveOutput), MAKE_ENUM_PAIR(MediaEventType, METransformDrainComplete), MAKE_ENUM_PAIR(MediaEventType, METransformMarker), #if (WINVER >= 0x0602) // Available since Win 8 MAKE_ENUM_PAIR(MediaEventType, MEByteStreamCharacteristicsChanged), MAKE_ENUM_PAIR(MediaEventType, MEVideoCaptureDeviceRemoved), MAKE_ENUM_PAIR(MediaEventType, MEVideoCaptureDevicePreempted), #endif MAKE_ENUM_PAIR(MediaEventType, MEReservedMax) }; MAKE_MAP(MediaEventType) MediaEventTypeMap(MediaEventTypePairs, MediaEventTypePairs + sizeof(MediaEventTypePairs) / sizeof(MediaEventTypePairs[0])); MAKE_ENUM(MFSTREAMSINK_MARKER_TYPE) StreamSinkMarkerTypePairs[] = { MAKE_ENUM_PAIR(MFSTREAMSINK_MARKER_TYPE, MFSTREAMSINK_MARKER_DEFAULT), MAKE_ENUM_PAIR(MFSTREAMSINK_MARKER_TYPE, MFSTREAMSINK_MARKER_ENDOFSEGMENT), MAKE_ENUM_PAIR(MFSTREAMSINK_MARKER_TYPE, MFSTREAMSINK_MARKER_TICK), MAKE_ENUM_PAIR(MFSTREAMSINK_MARKER_TYPE, MFSTREAMSINK_MARKER_EVENT) }; MAKE_MAP(MFSTREAMSINK_MARKER_TYPE) StreamSinkMarkerTypeMap(StreamSinkMarkerTypePairs, StreamSinkMarkerTypePairs + sizeof(StreamSinkMarkerTypePairs) / sizeof(StreamSinkMarkerTypePairs[0])); #ifdef HAVE_WINRT #ifdef __cplusplus_winrt #define _ContextCallback Concurrency::details::_ContextCallback #define BEGIN_CALL_IN_CONTEXT(hr, var, ...) hr = S_OK;\ var._CallInContext([__VA_ARGS__]() { #define END_CALL_IN_CONTEXT(hr) if (FAILED(hr)) throw Platform::Exception::CreateException(hr);\ }); #define END_CALL_IN_CONTEXT_BASE }); #else #define _ContextCallback Concurrency_winrt::details::_ContextCallback #define BEGIN_CALL_IN_CONTEXT(hr, var, ...) hr = var._CallInContext([__VA_ARGS__]() -> HRESULT { #define END_CALL_IN_CONTEXT(hr) return hr;\ }); #define END_CALL_IN_CONTEXT_BASE return S_OK;\ }); #endif #define GET_CURRENT_CONTEXT _ContextCallback::_CaptureCurrent() #define SAVE_CURRENT_CONTEXT(var) _ContextCallback var = GET_CURRENT_CONTEXT #define COMMA , #ifdef __cplusplus_winrt #define _Object Platform::Object^ #define _ObjectObj Platform::Object^ #define _String Platform::String^ #define _StringObj Platform::String^ #define _StringReference ref new Platform::String #define _StringReferenceObj Platform::String^ #define _DeviceInformationCollection Windows::Devices::Enumeration::DeviceInformationCollection #define _MediaCapture Windows::Media::Capture::MediaCapture #define _MediaCaptureVideoPreview Windows::Media::Capture::MediaCapture #define _MediaCaptureInitializationSettings Windows::Media::Capture::MediaCaptureInitializationSettings #define _VideoDeviceController Windows::Media::Devices::VideoDeviceController #define _MediaDeviceController Windows::Media::Devices::VideoDeviceController #define _MediaEncodingProperties Windows::Media::MediaProperties::IMediaEncodingProperties #define _VideoEncodingProperties Windows::Media::MediaProperties::VideoEncodingProperties #define _MediaStreamType Windows::Media::Capture::MediaStreamType #define _AsyncInfo Windows::Foundation::IAsyncInfo #define _AsyncAction Windows::Foundation::IAsyncAction #define _AsyncOperation Windows::Foundation::IAsyncOperation #define _DeviceClass Windows::Devices::Enumeration::DeviceClass #define _IDeviceInformation Windows::Devices::Enumeration::DeviceInformation #define _DeviceInformation Windows::Devices::Enumeration::DeviceInformation #define _DeviceInformationStatics Windows::Devices::Enumeration::DeviceInformation #define _MediaEncodingProfile Windows::Media::MediaProperties::MediaEncodingProfile #define _StreamingCaptureMode Windows::Media::Capture::StreamingCaptureMode #define _PropertySet Windows::Foundation::Collections::PropertySet #define _Map Windows::Foundation::Collections::PropertySet #define _PropertyValueStatics Windows::Foundation::PropertyValue #define _VectorView Windows::Foundation::Collections::IVectorView #define _StartPreviewToCustomSinkIdAsync StartPreviewToCustomSinkAsync #define _InitializeWithSettingsAsync InitializeAsync #define _FindAllAsyncDeviceClass FindAllAsync #define _MediaExtension Windows::Media::IMediaExtension #define BEGIN_CREATE_ASYNC(type, ...) (Concurrency::create_async([__VA_ARGS__]() { #define END_CREATE_ASYNC(hr) if (FAILED(hr)) throw Platform::Exception::CreateException(hr);\ })) #define DEFINE_TASK Concurrency::task #define CREATE_TASK Concurrency::create_task #define CREATE_OR_CONTINUE_TASK(_task, rettype, func) _task = (_task == Concurrency::task<rettype>()) ? Concurrency::create_task(func) : _task.then([func](rettype) -> rettype { return func(); }); #define CREATE_OR_CONTINUE_TASK_RET(_task, rettype, func) _task = (_task == Concurrency::task<rettype>()) ? Concurrency::create_task(func) : _task.then([func](rettype) -> rettype { return func(); }); #define DEFINE_RET_VAL(x) #define DEFINE_RET_TYPE(x) #define DEFINE_RET_FORMAL(x) x #define RET_VAL(x) return x; #define RET_VAL_BASE #define MAKE_STRING(str) str #define GET_STL_STRING(str) std::wstring(str->Data()) #define GET_STL_STRING_RAW(str) std::wstring(str->Data()) #define MAKE_WRL_OBJ(x) x^ #define MAKE_WRL_REF(x) x^ #define MAKE_OBJ_REF(x) x^ #define MAKE_WRL_AGILE_REF(x) Platform::Agile<x^> #define MAKE_WRL_AGILE_OBJ(x) Platform::Agile<x^> #define MAKE_PROPERTY_BACKING(Type, PropName) property Type PropName; #define MAKE_PROPERTY(Type, PropName, PropValue) #define MAKE_PROPERTY_STRING(Type, PropName, PropValue) #define MAKE_READONLY_PROPERTY(Type, PropName, PropValue) property Type PropName\ {\ Type get() { return PropValue; }\ } #define THROW_INVALID_ARG throw ref new Platform::InvalidArgumentException(); #define RELEASE_AGILE_WRL(x) x = nullptr; #define RELEASE_WRL(x) x = nullptr; #define GET_WRL_OBJ_FROM_REF(objtype, obj, orig, hr) objtype^ obj = orig;\ hr = S_OK; #define GET_WRL_OBJ_FROM_OBJ(objtype, obj, orig, hr) objtype^ obj = safe_cast<objtype^>(orig);\ hr = S_OK; #define WRL_ENUM_GET(obj, prefix, prop) obj::##prop #define WRL_PROP_GET(obj, prop, arg, hr) arg = obj->##prop;\ hr = S_OK; #define WRL_PROP_PUT(obj, prop, arg, hr) obj->##prop = arg;\ hr = S_OK; #define WRL_METHOD_BASE(obj, method, ret, hr) ret = obj->##method();\ hr = S_OK; #define WRL_METHOD(obj, method, ret, hr, ...) ret = obj->##method(__VA_ARGS__);\ hr = S_OK; #define WRL_METHOD_NORET_BASE(obj, method, hr) obj->##method();\ hr = S_OK; #define WRL_METHOD_NORET(obj, method, hr, ...) obj->##method(__VA_ARGS__);\ hr = S_OK; #define REF_WRL_OBJ(obj) &obj #define DEREF_WRL_OBJ(obj) obj #define DEREF_AGILE_WRL_MADE_OBJ(obj) obj.Get() #define DEREF_AGILE_WRL_OBJ(obj) obj.Get() #define DEREF_AS_NATIVE_WRL_OBJ(type, obj) reinterpret_cast<type*>(obj) #define PREPARE_TRANSFER_WRL_OBJ(obj) obj #define ACTIVATE_LOCAL_OBJ_BASE(objtype) ref new objtype() #define ACTIVATE_LOCAL_OBJ(objtype, ...) ref new objtype(__VA_ARGS__) #define ACTIVATE_EVENT_HANDLER(objtype, ...) ref new objtype(__VA_ARGS__) #define ACTIVATE_OBJ(rtclass, objtype, obj, hr) MAKE_WRL_OBJ(objtype) obj = ref new objtype();\ hr = S_OK; #define ACTIVATE_STATIC_OBJ(rtclass, objtype, obj, hr) objtype obj;\ hr = S_OK; #else #define _Object IInspectable* #define _ObjectObj Microsoft::WRL::ComPtr<IInspectable> #define _String HSTRING #define _StringObj Microsoft::WRL::Wrappers::HString #define _StringReference Microsoft::WRL::Wrappers::HStringReference #define _StringReferenceObj Microsoft::WRL::Wrappers::HStringReference #define _DeviceInformationCollection ABI::Windows::Devices::Enumeration::DeviceInformationCollection #define _MediaCapture ABI::Windows::Media::Capture::IMediaCapture #define _MediaCaptureVideoPreview ABI::Windows::Media::Capture::IMediaCaptureVideoPreview #define _MediaCaptureInitializationSettings ABI::Windows::Media::Capture::IMediaCaptureInitializationSettings #define _VideoDeviceController ABI::Windows::Media::Devices::IVideoDeviceController #define _MediaDeviceController ABI::Windows::Media::Devices::IMediaDeviceController #define _MediaEncodingProperties ABI::Windows::Media::MediaProperties::IMediaEncodingProperties #define _VideoEncodingProperties ABI::Windows::Media::MediaProperties::IVideoEncodingProperties #define _MediaStreamType ABI::Windows::Media::Capture::MediaStreamType #define _AsyncInfo ABI::Windows::Foundation::IAsyncInfo #define _AsyncAction ABI::Windows::Foundation::IAsyncAction #define _AsyncOperation ABI::Windows::Foundation::IAsyncOperation #define _DeviceClass ABI::Windows::Devices::Enumeration::DeviceClass #define _IDeviceInformation ABI::Windows::Devices::Enumeration::IDeviceInformation #define _DeviceInformation ABI::Windows::Devices::Enumeration::DeviceInformation #define _DeviceInformationStatics ABI::Windows::Devices::Enumeration::IDeviceInformationStatics #define _MediaEncodingProfile ABI::Windows::Media::MediaProperties::IMediaEncodingProfile #define _StreamingCaptureMode ABI::Windows::Media::Capture::StreamingCaptureMode #define _PropertySet ABI::Windows::Foundation::Collections::IPropertySet #define _Map ABI::Windows::Foundation::Collections::IMap<HSTRING, IInspectable *> #define _PropertyValueStatics ABI::Windows::Foundation::IPropertyValueStatics #define _VectorView ABI::Windows::Foundation::Collections::IVectorView #define _StartPreviewToCustomSinkIdAsync StartPreviewToCustomSinkIdAsync #define _InitializeWithSettingsAsync InitializeWithSettingsAsync #define _FindAllAsyncDeviceClass FindAllAsyncDeviceClass #define _MediaExtension ABI::Windows::Media::IMediaExtension #define BEGIN_CREATE_ASYNC(type, ...) Concurrency_winrt::create_async<type>([__VA_ARGS__]() -> HRESULT { #define END_CREATE_ASYNC(hr) return hr;\ }) #define DEFINE_TASK Concurrency_winrt::task #define CREATE_TASK Concurrency_winrt::create_task #define CREATE_OR_CONTINUE_TASK(_task, rettype, func) _task = (_task == Concurrency_winrt::task<rettype>()) ? Concurrency_winrt::create_task<rettype>(func) : _task.then(func); #define CREATE_OR_CONTINUE_TASK_RET(_task, rettype, func) _task = (_task == Concurrency_winrt::task<rettype>()) ? Concurrency_winrt::create_task<rettype>(func) : _task.then([func](rettype, rettype* retVal) -> HRESULT { return func(retVal); }); #define DEFINE_RET_VAL(x) x* retVal #define DEFINE_RET_TYPE(x) <x> #define DEFINE_RET_FORMAL(x) HRESULT #define RET_VAL(x) *retVal = x;\ return S_OK; #define RET_VAL_BASE return S_OK; #define MAKE_STRING(str) Microsoft::WRL::Wrappers::HStringReference(L##str) #define GET_STL_STRING(str) std::wstring(str.GetRawBuffer(NULL)) #define GET_STL_STRING_RAW(str) WindowsGetStringRawBuffer(str, NULL) #define MAKE_WRL_OBJ(x) Microsoft::WRL::ComPtr<x> #define MAKE_WRL_REF(x) x* #define MAKE_OBJ_REF(x) x #define MAKE_WRL_AGILE_REF(x) x* #define MAKE_WRL_AGILE_OBJ(x) Microsoft::WRL::ComPtr<x> #define MAKE_PROPERTY_BACKING(Type, PropName) Type PropName; #define MAKE_PROPERTY(Type, PropName, PropValue) STDMETHODIMP get_##PropName(Type* pVal) { if (pVal) { *pVal = PropValue; } else { return E_INVALIDARG; } return S_OK; }\ STDMETHODIMP put_##PropName(Type Val) { PropValue = Val; return S_OK; } #define MAKE_PROPERTY_STRING(Type, PropName, PropValue) STDMETHODIMP get_##PropName(Type* pVal) { if (pVal) { return ::WindowsDuplicateString(PropValue.Get(), pVal); } else { return E_INVALIDARG; } }\ STDMETHODIMP put_##PropName(Type Val) { return PropValue.Set(Val); } #define MAKE_READONLY_PROPERTY(Type, PropName, PropValue) STDMETHODIMP get_##PropName(Type* pVal) { if (pVal) { *pVal = PropValue; } else { return E_INVALIDARG; } return S_OK; } #define THROW_INVALID_ARG RoOriginateError(E_INVALIDARG, nullptr); #define RELEASE_AGILE_WRL(x) if (x) { (x)->Release(); x = nullptr; } #define RELEASE_WRL(x) if (x) { (x)->Release(); x = nullptr; } #define GET_WRL_OBJ_FROM_REF(objtype, obj, orig, hr) Microsoft::WRL::ComPtr<objtype> obj;\ hr = orig->QueryInterface(__uuidof(objtype), &obj); #define GET_WRL_OBJ_FROM_OBJ(objtype, obj, orig, hr) Microsoft::WRL::ComPtr<objtype> obj;\ hr = orig.As(&obj); #define WRL_ENUM_GET(obj, prefix, prop) obj::prefix##_##prop #define WRL_PROP_GET(obj, prop, arg, hr) hr = obj->get_##prop(&arg); #define WRL_PROP_PUT(obj, prop, arg, hr) hr = obj->put_##prop(arg); #define WRL_METHOD_BASE(obj, method, ret, hr) hr = obj->##method(&ret); #define WRL_METHOD(obj, method, ret, hr, ...) hr = obj->##method(__VA_ARGS__, &ret); #define WRL_METHOD_NORET_BASE(obj, method, hr) hr = obj->##method(); #define REF_WRL_OBJ(obj) obj.GetAddressOf() #define DEREF_WRL_OBJ(obj) obj.Get() #define DEREF_AGILE_WRL_MADE_OBJ(obj) obj.Get() #define DEREF_AGILE_WRL_OBJ(obj) obj #define DEREF_AS_NATIVE_WRL_OBJ(type, obj) obj.Get() #define PREPARE_TRANSFER_WRL_OBJ(obj) obj.Detach() #define ACTIVATE_LOCAL_OBJ_BASE(objtype) Microsoft::WRL::Make<objtype>() #define ACTIVATE_LOCAL_OBJ(objtype, ...) Microsoft::WRL::Make<objtype>(__VA_ARGS__) #define ACTIVATE_EVENT_HANDLER(objtype, ...) Microsoft::WRL::Callback<objtype>(__VA_ARGS__).Get() #define ACTIVATE_OBJ(rtclass, objtype, obj, hr) MAKE_WRL_OBJ(objtype) obj;\ {\ Microsoft::WRL::ComPtr<IActivationFactory> objFactory;\ hr = Windows::Foundation::GetActivationFactory(Microsoft::WRL::Wrappers::HStringReference(rtclass).Get(), objFactory.ReleaseAndGetAddressOf());\ if (SUCCEEDED(hr)) {\ Microsoft::WRL::ComPtr<IInspectable> pInsp;\ hr = objFactory->ActivateInstance(pInsp.GetAddressOf());\ if (SUCCEEDED(hr)) hr = pInsp.As(&obj);\ }\ } #define ACTIVATE_STATIC_OBJ(rtclass, objtype, obj, hr) objtype obj;\ {\ Microsoft::WRL::ComPtr<IActivationFactory> objFactory;\ hr = Windows::Foundation::GetActivationFactory(Microsoft::WRL::Wrappers::HStringReference(rtclass).Get(), objFactory.ReleaseAndGetAddressOf());\ if (SUCCEEDED(hr)) {\ if (SUCCEEDED(hr)) hr = objFactory.As(&obj);\ }\ } #endif #define _ComPtr Microsoft::WRL::ComPtr #else #define _COM_SMARTPTR_DECLARE(T,var) T ## Ptr var template <class T> class ComPtr { public: ComPtr() throw() { } ComPtr(T* lp) throw() { p = lp; } ComPtr(_In_ const ComPtr<T>& lp) throw() { p = lp.p; } virtual ~ComPtr() { } T** operator&() throw() { assert(p == NULL); return p.operator&(); } T* operator->() const throw() { assert(p != NULL); return p.operator->(); } bool operator!() const throw() { return p.operator==(NULL); } bool operator==(_In_opt_ T* pT) const throw() { return p.operator==(pT); } bool operator!=(_In_opt_ T* pT) const throw() { return p.operator!=(pT); } operator bool() { return p.operator!=(NULL); } T* const* GetAddressOf() const throw() { return &p; } T** GetAddressOf() throw() { return &p; } T** ReleaseAndGetAddressOf() throw() { p.Release(); return &p; } T* Get() const throw() { return p; } // Attach to an existing interface (does not AddRef) void Attach(_In_opt_ T* p2) throw() { p.Attach(p2); } // Detach the interface (does not Release) T* Detach() throw() { return p.Detach(); } _Check_return_ HRESULT CopyTo(_Deref_out_opt_ T** ppT) throw() { assert(ppT != NULL); if (ppT == NULL) return E_POINTER; *ppT = p; if (p != NULL) p->AddRef(); return S_OK; } void Reset() { p.Release(); } // query for U interface template<typename U> HRESULT As(_Inout_ U** lp) const throw() { return p->QueryInterface(__uuidof(U), reinterpret_cast<void**>(lp)); } // query for U interface template<typename U> HRESULT As(_Out_ ComPtr<U>* lp) const throw() { return p->QueryInterface(__uuidof(U), reinterpret_cast<void**>(lp->ReleaseAndGetAddressOf())); } private: _COM_SMARTPTR_TYPEDEF(T, __uuidof(T)); _COM_SMARTPTR_DECLARE(T, p); }; #define _ComPtr ComPtr #endif template <class TBase=IMFAttributes> class CBaseAttributes : public TBase { protected: // This version of the constructor does not initialize the // attribute store. The derived class must call Initialize() in // its own constructor. CBaseAttributes() { } // This version of the constructor initializes the attribute // store, but the derived class must pass an HRESULT parameter // to the constructor. CBaseAttributes(HRESULT& hr, UINT32 cInitialSize = 0) { hr = Initialize(cInitialSize); } // The next version of the constructor uses a caller-provided // implementation of IMFAttributes. // (Sometimes you want to delegate IMFAttributes calls to some // other object that implements IMFAttributes, rather than using // MFCreateAttributes.) CBaseAttributes(HRESULT& hr, IUnknown *pUnk) { hr = Initialize(pUnk); } virtual ~CBaseAttributes() { } // Initializes the object by creating the standard Media Foundation attribute store. HRESULT Initialize(UINT32 cInitialSize = 0) { if (_spAttributes.Get() == nullptr) { return MFCreateAttributes(&_spAttributes, cInitialSize); } else { return S_OK; } } // Initializes this object from a caller-provided attribute store. // pUnk: Pointer to an object that exposes IMFAttributes. HRESULT Initialize(IUnknown *pUnk) { if (_spAttributes) { _spAttributes.Reset(); _spAttributes = nullptr; } return pUnk->QueryInterface(IID_PPV_ARGS(&_spAttributes)); } public: // IMFAttributes methods STDMETHODIMP GetItem(REFGUID guidKey, PROPVARIANT* pValue) { assert(_spAttributes); return _spAttributes->GetItem(guidKey, pValue); } STDMETHODIMP GetItemType(REFGUID guidKey, MF_ATTRIBUTE_TYPE* pType) { assert(_spAttributes); return _spAttributes->GetItemType(guidKey, pType); } STDMETHODIMP CompareItem(REFGUID guidKey, REFPROPVARIANT Value, BOOL* pbResult) { assert(_spAttributes); return _spAttributes->CompareItem(guidKey, Value, pbResult); } STDMETHODIMP Compare( IMFAttributes* pTheirs, MF_ATTRIBUTES_MATCH_TYPE MatchType, BOOL* pbResult ) { assert(_spAttributes); return _spAttributes->Compare(pTheirs, MatchType, pbResult); } STDMETHODIMP GetUINT32(REFGUID guidKey, UINT32* punValue) { assert(_spAttributes); return _spAttributes->GetUINT32(guidKey, punValue); } STDMETHODIMP GetUINT64(REFGUID guidKey, UINT64* punValue) { assert(_spAttributes); return _spAttributes->GetUINT64(guidKey, punValue); } STDMETHODIMP GetDouble(REFGUID guidKey, double* pfValue) { assert(_spAttributes); return _spAttributes->GetDouble(guidKey, pfValue); } STDMETHODIMP GetGUID(REFGUID guidKey, GUID* pguidValue) { assert(_spAttributes); return _spAttributes->GetGUID(guidKey, pguidValue); } STDMETHODIMP GetStringLength(REFGUID guidKey, UINT32* pcchLength) { assert(_spAttributes); return _spAttributes->GetStringLength(guidKey, pcchLength); } STDMETHODIMP GetString(REFGUID guidKey, LPWSTR pwszValue, UINT32 cchBufSize, UINT32* pcchLength) { assert(_spAttributes); return _spAttributes->GetString(guidKey, pwszValue, cchBufSize, pcchLength); } STDMETHODIMP GetAllocatedString(REFGUID guidKey, LPWSTR* ppwszValue, UINT32* pcchLength) { assert(_spAttributes); return _spAttributes->GetAllocatedString(guidKey, ppwszValue, pcchLength); } STDMETHODIMP GetBlobSize(REFGUID guidKey, UINT32* pcbBlobSize) { assert(_spAttributes); return _spAttributes->GetBlobSize(guidKey, pcbBlobSize); } STDMETHODIMP GetBlob(REFGUID guidKey, UINT8* pBuf, UINT32 cbBufSize, UINT32* pcbBlobSize) { assert(_spAttributes); return _spAttributes->GetBlob(guidKey, pBuf, cbBufSize, pcbBlobSize); } STDMETHODIMP GetAllocatedBlob(REFGUID guidKey, UINT8** ppBuf, UINT32* pcbSize) { assert(_spAttributes); return _spAttributes->GetAllocatedBlob(guidKey, ppBuf, pcbSize); } STDMETHODIMP GetUnknown(REFGUID guidKey, REFIID riid, LPVOID* ppv) { assert(_spAttributes); return _spAttributes->GetUnknown(guidKey, riid, ppv); } STDMETHODIMP SetItem(REFGUID guidKey, REFPROPVARIANT Value) { assert(_spAttributes); return _spAttributes->SetItem(guidKey, Value); } STDMETHODIMP DeleteItem(REFGUID guidKey) { assert(_spAttributes); return _spAttributes->DeleteItem(guidKey); } STDMETHODIMP DeleteAllItems() { assert(_spAttributes); return _spAttributes->DeleteAllItems(); } STDMETHODIMP SetUINT32(REFGUID guidKey, UINT32 unValue) { assert(_spAttributes); return _spAttributes->SetUINT32(guidKey, unValue); } STDMETHODIMP SetUINT64(REFGUID guidKey,UINT64 unValue) { assert(_spAttributes); return _spAttributes->SetUINT64(guidKey, unValue); } STDMETHODIMP SetDouble(REFGUID guidKey, double fValue) { assert(_spAttributes); return _spAttributes->SetDouble(guidKey, fValue); } STDMETHODIMP SetGUID(REFGUID guidKey, REFGUID guidValue) { assert(_spAttributes); return _spAttributes->SetGUID(guidKey, guidValue); } STDMETHODIMP SetString(REFGUID guidKey, LPCWSTR wszValue) { assert(_spAttributes); return _spAttributes->SetString(guidKey, wszValue); } STDMETHODIMP SetBlob(REFGUID guidKey, const UINT8* pBuf, UINT32 cbBufSize) { assert(_spAttributes); return _spAttributes->SetBlob(guidKey, pBuf, cbBufSize); } STDMETHODIMP SetUnknown(REFGUID guidKey, IUnknown* pUnknown) { assert(_spAttributes); return _spAttributes->SetUnknown(guidKey, pUnknown); } STDMETHODIMP LockStore() { assert(_spAttributes); return _spAttributes->LockStore(); } STDMETHODIMP UnlockStore() { assert(_spAttributes); return _spAttributes->UnlockStore(); } STDMETHODIMP GetCount(UINT32* pcItems) { assert(_spAttributes); return _spAttributes->GetCount(pcItems); } STDMETHODIMP GetItemByIndex(UINT32 unIndex, GUID* pguidKey, PROPVARIANT* pValue) { assert(_spAttributes); return _spAttributes->GetItemByIndex(unIndex, pguidKey, pValue); } STDMETHODIMP CopyAllItems(IMFAttributes* pDest) { assert(_spAttributes); return _spAttributes->CopyAllItems(pDest); } // Helper functions HRESULT SerializeToStream(DWORD dwOptions, IStream* pStm) // dwOptions: Flags from MF_ATTRIBUTE_SERIALIZE_OPTIONS { assert(_spAttributes); return MFSerializeAttributesToStream(_spAttributes.Get(), dwOptions, pStm); } HRESULT DeserializeFromStream(DWORD dwOptions, IStream* pStm) { assert(_spAttributes); return MFDeserializeAttributesFromStream(_spAttributes.Get(), dwOptions, pStm); } // SerializeToBlob: Stores the attributes in a byte array. // // ppBuf: Receives a pointer to the byte array. // pcbSize: Receives the size of the byte array. // // The caller must free the array using CoTaskMemFree. HRESULT SerializeToBlob(UINT8 **ppBuffer, UINT *pcbSize) { assert(_spAttributes); if (ppBuffer == NULL) { return E_POINTER; } if (pcbSize == NULL) { return E_POINTER; } HRESULT hr = S_OK; UINT32 cbSize = 0; BYTE *pBuffer = NULL; CHECK_HR(hr = MFGetAttributesAsBlobSize(_spAttributes.Get(), &cbSize)); pBuffer = (BYTE*)CoTaskMemAlloc(cbSize); if (pBuffer == NULL) { CHECK_HR(hr = E_OUTOFMEMORY); } CHECK_HR(hr = MFGetAttributesAsBlob(_spAttributes.Get(), pBuffer, cbSize)); *ppBuffer = pBuffer; *pcbSize = cbSize; done: if (FAILED(hr)) { *ppBuffer = NULL; *pcbSize = 0; CoTaskMemFree(pBuffer); } return hr; } HRESULT DeserializeFromBlob(const UINT8* pBuffer, UINT cbSize) { assert(_spAttributes); return MFInitAttributesFromBlob(_spAttributes.Get(), pBuffer, cbSize); } HRESULT GetRatio(REFGUID guidKey, UINT32* pnNumerator, UINT32* punDenominator) { assert(_spAttributes); return MFGetAttributeRatio(_spAttributes.Get(), guidKey, pnNumerator, punDenominator); } HRESULT SetRatio(REFGUID guidKey, UINT32 unNumerator, UINT32 unDenominator) { assert(_spAttributes); return MFSetAttributeRatio(_spAttributes.Get(), guidKey, unNumerator, unDenominator); } // Gets an attribute whose value represents the size of something (eg a video frame). HRESULT GetSize(REFGUID guidKey, UINT32* punWidth, UINT32* punHeight) { assert(_spAttributes); return MFGetAttributeSize(_spAttributes.Get(), guidKey, punWidth, punHeight); } // Sets an attribute whose value represents the size of something (eg a video frame). HRESULT SetSize(REFGUID guidKey, UINT32 unWidth, UINT32 unHeight) { assert(_spAttributes); return MFSetAttributeSize (_spAttributes.Get(), guidKey, unWidth, unHeight); } protected: _ComPtr<IMFAttributes> _spAttributes; }; class StreamSink : #ifdef HAVE_WINRT public Microsoft::WRL::RuntimeClass< Microsoft::WRL::RuntimeClassFlags< Microsoft::WRL::RuntimeClassType::ClassicCom>, IMFStreamSink, IMFMediaEventGenerator, IMFMediaTypeHandler, CBaseAttributes<> > #else public IMFStreamSink, public IMFMediaTypeHandler, public CBaseAttributes<>, public ICustomStreamSink #endif { public: // IUnknown methods #if defined(_MSC_VER) && _MSC_VER >= 1700 // '_Outptr_result_nullonfailure_' SAL is avaialable since VS 2012 STDMETHOD(QueryInterface)(REFIID riid, _Outptr_result_nullonfailure_ void **ppv) #else STDMETHOD(QueryInterface)(REFIID riid, void **ppv) #endif { if (ppv == nullptr) { return E_POINTER; } (*ppv) = nullptr; HRESULT hr = S_OK; if (riid == IID_IMarshal) { return MarshalQI(riid, ppv); } else { #ifdef HAVE_WINRT hr = RuntimeClassT::QueryInterface(riid, ppv); #else if (riid == IID_IUnknown || riid == IID_IMFStreamSink) { *ppv = static_cast<IMFStreamSink*>(this); AddRef(); } else if (riid == IID_IMFMediaEventGenerator) { *ppv = static_cast<IMFMediaEventGenerator*>(this); AddRef(); } else if (riid == IID_IMFMediaTypeHandler) { *ppv = static_cast<IMFMediaTypeHandler*>(this); AddRef(); } else if (riid == IID_IMFAttributes) { *ppv = static_cast<IMFAttributes*>(this); AddRef(); } else if (riid == IID_ICustomStreamSink) { *ppv = static_cast<ICustomStreamSink*>(this); AddRef(); } else hr = E_NOINTERFACE; #endif } return hr; } #ifdef HAVE_WINRT STDMETHOD(RuntimeClassInitialize)() { return S_OK; } #else ULONG STDMETHODCALLTYPE AddRef() { return InterlockedIncrement(&m_cRef); } ULONG STDMETHODCALLTYPE Release() { ULONG cRef = InterlockedDecrement(&m_cRef); if (cRef == 0) { delete this; } return cRef; } #endif HRESULT MarshalQI(REFIID riid, LPVOID* ppv) { HRESULT hr = S_OK; if (m_spFTM == nullptr) { EnterCriticalSection(&m_critSec); if (m_spFTM == nullptr) { hr = CoCreateFreeThreadedMarshaler((IMFStreamSink*)this, &m_spFTM); } LeaveCriticalSection(&m_critSec); } if (SUCCEEDED(hr)) { if (m_spFTM == nullptr) { hr = E_UNEXPECTED; } else { hr = m_spFTM.Get()->QueryInterface(riid, ppv); } } return hr; } enum State { State_TypeNotSet = 0, // No media type is set State_Ready, // Media type is set, Start has never been called. State_Started, State_Stopped, State_Paused, State_Count // Number of states }; StreamSink() : m_IsShutdown(false), m_StartTime(0), m_fGetStartTimeFromSample(false), m_fWaitingForFirstSample(false), m_state(State_TypeNotSet), m_pParent(nullptr), m_imageWidthInPixels(0), m_imageHeightInPixels(0) { #ifdef HAVE_WINRT m_token.value = 0; #else m_bConnected = false; #endif InitializeCriticalSectionEx(&m_critSec, 3000, 0); ZeroMemory(&m_guiCurrentSubtype, sizeof(m_guiCurrentSubtype)); CBaseAttributes::Initialize(0U); DebugPrintOut(L"StreamSink::StreamSink\n"); } virtual ~StreamSink() { DeleteCriticalSection(&m_critSec); assert(m_IsShutdown); DebugPrintOut(L"StreamSink::~StreamSink\n"); } HRESULT Initialize() { HRESULT hr; // Create the event queue helper. hr = MFCreateEventQueue(&m_spEventQueue); if (SUCCEEDED(hr)) { _ComPtr<IMFMediaSink> pMedSink; hr = CBaseAttributes<>::GetUnknown(MF_STREAMSINK_MEDIASINKINTERFACE, __uuidof(IMFMediaSink), (LPVOID*)pMedSink.GetAddressOf()); assert(pMedSink.Get() != NULL); if (SUCCEEDED(hr)) { hr = pMedSink.Get()->QueryInterface(IID_PPV_ARGS(&m_pParent)); } } return hr; } HRESULT CheckShutdown() const { if (m_IsShutdown) { return MF_E_SHUTDOWN; } else { return S_OK; } } // Called when the presentation clock starts. HRESULT Start(MFTIME start) { HRESULT hr = S_OK; EnterCriticalSection(&m_critSec); if (m_state != State_TypeNotSet) { if (start != PRESENTATION_CURRENT_POSITION) { m_StartTime = start; // Cache the start time. m_fGetStartTimeFromSample = false; } else { m_fGetStartTimeFromSample = true; } m_state = State_Started; GUID guiMajorType; m_fWaitingForFirstSample = SUCCEEDED(m_spCurrentType->GetMajorType(&guiMajorType)) && (guiMajorType == MFMediaType_Video); hr = QueueEvent(MEStreamSinkStarted, GUID_NULL, hr, NULL); if (SUCCEEDED(hr)) { hr = QueueEvent(MEStreamSinkRequestSample, GUID_NULL, hr, NULL); } } else hr = MF_E_NOT_INITIALIZED; LeaveCriticalSection(&m_critSec); return hr; } // Called when the presentation clock pauses. HRESULT Pause() { EnterCriticalSection(&m_critSec); HRESULT hr = S_OK; if (m_state != State_Stopped && m_state != State_TypeNotSet) { m_state = State_Paused; hr = QueueEvent(MEStreamSinkPaused, GUID_NULL, hr, NULL); } else if (hr == State_TypeNotSet) hr = MF_E_NOT_INITIALIZED; else hr = MF_E_INVALIDREQUEST; LeaveCriticalSection(&m_critSec); return hr; } // Called when the presentation clock restarts. HRESULT Restart() { EnterCriticalSection(&m_critSec); HRESULT hr = S_OK; if (m_state == State_Paused) { m_state = State_Started; hr = QueueEvent(MEStreamSinkStarted, GUID_NULL, hr, NULL); if (SUCCEEDED(hr)) { hr = QueueEvent(MEStreamSinkRequestSample, GUID_NULL, hr, NULL); } } else if (hr == State_TypeNotSet) hr = MF_E_NOT_INITIALIZED; else hr = MF_E_INVALIDREQUEST; LeaveCriticalSection(&m_critSec); return hr; } // Called when the presentation clock stops. HRESULT Stop() { EnterCriticalSection(&m_critSec); HRESULT hr = S_OK; if (m_state != State_TypeNotSet) { m_state = State_Stopped; hr = QueueEvent(MEStreamSinkStopped, GUID_NULL, hr, NULL); } else hr = MF_E_NOT_INITIALIZED; LeaveCriticalSection(&m_critSec); return hr; } // Shuts down the stream sink. HRESULT Shutdown() { _ComPtr<IMFSampleGrabberSinkCallback> pSampleCallback; HRESULT hr = S_OK; assert(!m_IsShutdown); hr = m_pParent->GetUnknown(MF_MEDIASINK_SAMPLEGRABBERCALLBACK, IID_IMFSampleGrabberSinkCallback, (LPVOID*)pSampleCallback.GetAddressOf()); if (SUCCEEDED(hr)) { hr = pSampleCallback->OnShutdown(); } if (m_spEventQueue) { hr = m_spEventQueue->Shutdown(); } if (m_pParent) m_pParent->Release(); m_spCurrentType.Reset(); m_IsShutdown = TRUE; return hr; } //IMFStreamSink HRESULT STDMETHODCALLTYPE GetMediaSink( /* [out] */ __RPC__deref_out_opt IMFMediaSink **ppMediaSink) { if (ppMediaSink == NULL) { return E_INVALIDARG; } EnterCriticalSection(&m_critSec); HRESULT hr = CheckShutdown(); if (SUCCEEDED(hr)) { _ComPtr<IMFMediaSink> pMedSink; hr = CBaseAttributes<>::GetUnknown(MF_STREAMSINK_MEDIASINKINTERFACE, __uuidof(IMFMediaSink), (LPVOID*)pMedSink.GetAddressOf()); if (SUCCEEDED(hr)) { *ppMediaSink = pMedSink.Detach(); } } LeaveCriticalSection(&m_critSec); DebugPrintOut(L"StreamSink::GetMediaSink: HRESULT=%i\n", hr); return hr; } HRESULT STDMETHODCALLTYPE GetIdentifier( /* [out] */ __RPC__out DWORD *pdwIdentifier) { if (pdwIdentifier == NULL) { return E_INVALIDARG; } EnterCriticalSection(&m_critSec); HRESULT hr = CheckShutdown(); if (SUCCEEDED(hr)) { hr = GetUINT32(MF_STREAMSINK_ID, (UINT32*)pdwIdentifier); } LeaveCriticalSection(&m_critSec); DebugPrintOut(L"StreamSink::GetIdentifier: HRESULT=%i\n", hr); return hr; } HRESULT STDMETHODCALLTYPE GetMediaTypeHandler( /* [out] */ __RPC__deref_out_opt IMFMediaTypeHandler **ppHandler) { if (ppHandler == NULL) { return E_INVALIDARG; } EnterCriticalSection(&m_critSec); HRESULT hr = CheckShutdown(); // This stream object acts as its own type handler, so we QI ourselves. if (SUCCEEDED(hr)) { hr = QueryInterface(IID_IMFMediaTypeHandler, (void**)ppHandler); } LeaveCriticalSection(&m_critSec); DebugPrintOut(L"StreamSink::GetMediaTypeHandler: HRESULT=%i\n", hr); return hr; } HRESULT STDMETHODCALLTYPE ProcessSample(IMFSample *pSample) { _ComPtr<IMFMediaBuffer> pInput; _ComPtr<IMFSampleGrabberSinkCallback> pSampleCallback; BYTE *pSrc = NULL; // Source buffer. // Stride if the buffer does not support IMF2DBuffer LONGLONG hnsTime = 0; LONGLONG hnsDuration = 0; DWORD cbMaxLength; DWORD cbCurrentLength = 0; GUID guidMajorType; if (pSample == NULL) { return E_INVALIDARG; } HRESULT hr = S_OK; EnterCriticalSection(&m_critSec); if (m_state != State_Started && m_state != State_Paused) { if (m_state == State_TypeNotSet) hr = MF_E_NOT_INITIALIZED; else hr = MF_E_INVALIDREQUEST; } if (SUCCEEDED(hr)) hr = CheckShutdown(); if (SUCCEEDED(hr)) { hr = pSample->ConvertToContiguousBuffer(&pInput); if (SUCCEEDED(hr)) { hr = pSample->GetSampleTime(&hnsTime); } if (SUCCEEDED(hr)) { hr = pSample->GetSampleDuration(&hnsDuration); } if (SUCCEEDED(hr)) { hr = GetMajorType(&guidMajorType); } if (SUCCEEDED(hr)) { hr = m_pParent->GetUnknown(MF_MEDIASINK_SAMPLEGRABBERCALLBACK, IID_IMFSampleGrabberSinkCallback, (LPVOID*)pSampleCallback.GetAddressOf()); } if (SUCCEEDED(hr)) { hr = pInput->Lock(&pSrc, &cbMaxLength, &cbCurrentLength); } if (SUCCEEDED(hr)) { hr = pSampleCallback->OnProcessSample(guidMajorType, 0, hnsTime, hnsDuration, pSrc, cbCurrentLength); pInput->Unlock(); } if (SUCCEEDED(hr)) { hr = QueueEvent(MEStreamSinkRequestSample, GUID_NULL, S_OK, NULL); } } LeaveCriticalSection(&m_critSec); return hr; } HRESULT STDMETHODCALLTYPE PlaceMarker( /* [in] */ MFSTREAMSINK_MARKER_TYPE eMarkerType, /* [in] */ __RPC__in const PROPVARIANT * /*pvarMarkerValue*/, /* [in] */ __RPC__in const PROPVARIANT * /*pvarContextValue*/) { eMarkerType; EnterCriticalSection(&m_critSec); HRESULT hr = S_OK; if (m_state == State_TypeNotSet) hr = MF_E_NOT_INITIALIZED; if (SUCCEEDED(hr)) hr = CheckShutdown(); if (SUCCEEDED(hr)) { //at shutdown will receive MFSTREAMSINK_MARKER_ENDOFSEGMENT hr = QueueEvent(MEStreamSinkRequestSample, GUID_NULL, S_OK, NULL); } LeaveCriticalSection(&m_critSec); DebugPrintOut(L"StreamSink::PlaceMarker: HRESULT=%i %s\n", hr, StreamSinkMarkerTypeMap.at(eMarkerType).c_str()); return hr; } HRESULT STDMETHODCALLTYPE Flush(void) { EnterCriticalSection(&m_critSec); HRESULT hr = CheckShutdown(); if (SUCCEEDED(hr)) { } LeaveCriticalSection(&m_critSec); DebugPrintOut(L"StreamSink::Flush: HRESULT=%i\n", hr); return hr; } //IMFMediaEventGenerator HRESULT STDMETHODCALLTYPE GetEvent( DWORD dwFlags, IMFMediaEvent **ppEvent) { // NOTE: // GetEvent can block indefinitely, so we don't hold the lock. // This requires some juggling with the event queue pointer. HRESULT hr = S_OK; _ComPtr<IMFMediaEventQueue> pQueue; { EnterCriticalSection(&m_critSec); // Check shutdown hr = CheckShutdown(); // Get the pointer to the event queue. if (SUCCEEDED(hr)) { pQueue = m_spEventQueue.Get(); } LeaveCriticalSection(&m_critSec); } // Now get the event. if (SUCCEEDED(hr)) { hr = pQueue->GetEvent(dwFlags, ppEvent); } MediaEventType meType = MEUnknown; if (SUCCEEDED(hr) && SUCCEEDED((*ppEvent)->GetType(&meType)) && meType == MEStreamSinkStopped) { } HRESULT hrStatus = S_OK; if (SUCCEEDED(hr)) hr = (*ppEvent)->GetStatus(&hrStatus); if (SUCCEEDED(hr)) DebugPrintOut(L"StreamSink::GetEvent: HRESULT=%i %s\n", hrStatus, MediaEventTypeMap.at(meType).c_str()); else DebugPrintOut(L"StreamSink::GetEvent: HRESULT=%i\n", hr); return hr; } HRESULT STDMETHODCALLTYPE BeginGetEvent( IMFAsyncCallback *pCallback, IUnknown *punkState) { HRESULT hr = S_OK; EnterCriticalSection(&m_critSec); hr = CheckShutdown(); if (SUCCEEDED(hr)) { hr = m_spEventQueue->BeginGetEvent(pCallback, punkState); } LeaveCriticalSection(&m_critSec); DebugPrintOut(L"StreamSink::BeginGetEvent: HRESULT=%i\n", hr); return hr; } HRESULT STDMETHODCALLTYPE EndGetEvent( IMFAsyncResult *pResult, IMFMediaEvent **ppEvent) { HRESULT hr = S_OK; EnterCriticalSection(&m_critSec); hr = CheckShutdown(); if (SUCCEEDED(hr)) { hr = m_spEventQueue->EndGetEvent(pResult, ppEvent); } MediaEventType meType = MEUnknown; if (SUCCEEDED(hr) && SUCCEEDED((*ppEvent)->GetType(&meType)) && meType == MEStreamSinkStopped) { } LeaveCriticalSection(&m_critSec); HRESULT hrStatus = S_OK; if (SUCCEEDED(hr)) hr = (*ppEvent)->GetStatus(&hrStatus); if (SUCCEEDED(hr)) DebugPrintOut(L"StreamSink::EndGetEvent: HRESULT=%i %s\n", hrStatus, MediaEventTypeMap.at(meType).c_str()); else DebugPrintOut(L"StreamSink::EndGetEvent: HRESULT=%i\n", hr); return hr; } HRESULT STDMETHODCALLTYPE QueueEvent( MediaEventType met, REFGUID guidExtendedType, HRESULT hrStatus, const PROPVARIANT *pvValue) { HRESULT hr = S_OK; EnterCriticalSection(&m_critSec); hr = CheckShutdown(); if (SUCCEEDED(hr)) { hr = m_spEventQueue->QueueEventParamVar(met, guidExtendedType, hrStatus, pvValue); } LeaveCriticalSection(&m_critSec); DebugPrintOut(L"StreamSink::QueueEvent: HRESULT=%i %s\n", hrStatus, MediaEventTypeMap.at(met).c_str()); DebugPrintOut(L"StreamSink::QueueEvent: HRESULT=%i\n", hr); return hr; } /// IMFMediaTypeHandler methods // Check if a media type is supported. STDMETHODIMP IsMediaTypeSupported( /* [in] */ IMFMediaType *pMediaType, /* [out] */ IMFMediaType **ppMediaType) { if (pMediaType == nullptr) { return E_INVALIDARG; } EnterCriticalSection(&m_critSec); GUID majorType = GUID_NULL; HRESULT hr = CheckShutdown(); if (SUCCEEDED(hr)) { hr = pMediaType->GetGUID(MF_MT_MAJOR_TYPE, &majorType); } // First make sure it's video or audio type. if (SUCCEEDED(hr)) { if (majorType != MFMediaType_Video && majorType != MFMediaType_Audio) { hr = MF_E_INVALIDTYPE; } } if (SUCCEEDED(hr) && m_spCurrentType != nullptr) { GUID guiNewSubtype; if (FAILED(pMediaType->GetGUID(MF_MT_SUBTYPE, &guiNewSubtype)) || guiNewSubtype != m_guiCurrentSubtype) { hr = MF_E_INVALIDTYPE; } } // We don't return any "close match" types. if (ppMediaType) { *ppMediaType = nullptr; } if (ppMediaType && SUCCEEDED(hr)) { _ComPtr<IMFMediaType> pType; hr = MFCreateMediaType(ppMediaType); if (SUCCEEDED(hr)) { hr = m_pParent->GetUnknown(MF_MEDIASINK_PREFERREDTYPE, __uuidof(IMFMediaType), (LPVOID*)&pType); } if (SUCCEEDED(hr)) { hr = pType->LockStore(); } bool bLocked = false; if (SUCCEEDED(hr)) { bLocked = true; UINT32 uiCount; UINT32 uiTotal; hr = pType->GetCount(&uiTotal); for (uiCount = 0; SUCCEEDED(hr) && uiCount < uiTotal; uiCount++) { GUID guid; PROPVARIANT propval; hr = pType->GetItemByIndex(uiCount, &guid, &propval); if (SUCCEEDED(hr) && (guid == MF_MT_FRAME_SIZE || guid == MF_MT_MAJOR_TYPE || guid == MF_MT_PIXEL_ASPECT_RATIO || guid == MF_MT_ALL_SAMPLES_INDEPENDENT || guid == MF_MT_INTERLACE_MODE || guid == MF_MT_SUBTYPE)) { hr = (*ppMediaType)->SetItem(guid, propval); PropVariantClear(&propval); } } } if (bLocked) { hr = pType->UnlockStore(); } } LeaveCriticalSection(&m_critSec); DebugPrintOut(L"StreamSink::IsMediaTypeSupported: HRESULT=%i\n", hr); return hr; } // Return the number of preferred media types. STDMETHODIMP GetMediaTypeCount(DWORD *pdwTypeCount) { if (pdwTypeCount == nullptr) { return E_INVALIDARG; } EnterCriticalSection(&m_critSec); HRESULT hr = CheckShutdown(); if (SUCCEEDED(hr)) { // We've got only one media type *pdwTypeCount = 1; } LeaveCriticalSection(&m_critSec); DebugPrintOut(L"StreamSink::GetMediaTypeCount: HRESULT=%i\n", hr); return hr; } // Return a preferred media type by index. STDMETHODIMP GetMediaTypeByIndex( /* [in] */ DWORD dwIndex, /* [out] */ IMFMediaType **ppType) { if (ppType == NULL) { return E_INVALIDARG; } EnterCriticalSection(&m_critSec); HRESULT hr = CheckShutdown(); if (dwIndex > 0) { hr = MF_E_NO_MORE_TYPES; } else { //return preferred type based on media capture library 6 elements preferred preview type //hr = m_spCurrentType.CopyTo(ppType); if (SUCCEEDED(hr)) { _ComPtr<IMFMediaType> pType; hr = MFCreateMediaType(ppType); if (SUCCEEDED(hr)) { hr = m_pParent->GetUnknown(MF_MEDIASINK_PREFERREDTYPE, __uuidof(IMFMediaType), (LPVOID*)&pType); } if (SUCCEEDED(hr)) { hr = pType->LockStore(); } bool bLocked = false; if (SUCCEEDED(hr)) { bLocked = true; UINT32 uiCount; UINT32 uiTotal; hr = pType->GetCount(&uiTotal); for (uiCount = 0; SUCCEEDED(hr) && uiCount < uiTotal; uiCount++) { GUID guid; PROPVARIANT propval; hr = pType->GetItemByIndex(uiCount, &guid, &propval); if (SUCCEEDED(hr) && (guid == MF_MT_FRAME_SIZE || guid == MF_MT_MAJOR_TYPE || guid == MF_MT_PIXEL_ASPECT_RATIO || guid == MF_MT_ALL_SAMPLES_INDEPENDENT || guid == MF_MT_INTERLACE_MODE || guid == MF_MT_SUBTYPE)) { hr = (*ppType)->SetItem(guid, propval); PropVariantClear(&propval); } } } if (bLocked) { hr = pType->UnlockStore(); } } } LeaveCriticalSection(&m_critSec); DebugPrintOut(L"StreamSink::GetMediaTypeByIndex: HRESULT=%i\n", hr); return hr; } // Set the current media type. STDMETHODIMP SetCurrentMediaType(IMFMediaType *pMediaType) { if (pMediaType == NULL) { return E_INVALIDARG; } EnterCriticalSection(&m_critSec); HRESULT hr = S_OK; if (m_state != State_TypeNotSet && m_state != State_Ready) hr = MF_E_INVALIDREQUEST; if (SUCCEEDED(hr)) hr = CheckShutdown(); // We don't allow format changes after streaming starts. // We set media type already if (m_state >= State_Ready) { if (SUCCEEDED(hr)) { hr = IsMediaTypeSupported(pMediaType, NULL); } } if (SUCCEEDED(hr)) { hr = MFCreateMediaType(m_spCurrentType.ReleaseAndGetAddressOf()); if (SUCCEEDED(hr)) { hr = pMediaType->CopyAllItems(m_spCurrentType.Get()); } if (SUCCEEDED(hr)) { hr = m_spCurrentType->GetGUID(MF_MT_SUBTYPE, &m_guiCurrentSubtype); } GUID guid; if (SUCCEEDED(hr)) { hr = m_spCurrentType->GetMajorType(&guid); } if (SUCCEEDED(hr) && guid == MFMediaType_Video) { hr = MFGetAttributeSize(m_spCurrentType.Get(), MF_MT_FRAME_SIZE, &m_imageWidthInPixels, &m_imageHeightInPixels); } if (SUCCEEDED(hr)) { m_state = State_Ready; } } LeaveCriticalSection(&m_critSec); DebugPrintOut(L"StreamSink::SetCurrentMediaType: HRESULT=%i\n", hr); return hr; } // Return the current media type, if any. STDMETHODIMP GetCurrentMediaType(IMFMediaType **ppMediaType) { if (ppMediaType == NULL) { return E_INVALIDARG; } EnterCriticalSection(&m_critSec); HRESULT hr = CheckShutdown(); if (SUCCEEDED(hr)) { if (m_spCurrentType == nullptr) { hr = MF_E_NOT_INITIALIZED; } } if (SUCCEEDED(hr)) { hr = m_spCurrentType.CopyTo(ppMediaType); } LeaveCriticalSection(&m_critSec); DebugPrintOut(L"StreamSink::GetCurrentMediaType: HRESULT=%i\n", hr); return hr; } // Return the major type GUID. STDMETHODIMP GetMajorType(GUID *pguidMajorType) { HRESULT hr; if (pguidMajorType == nullptr) { return E_INVALIDARG; } _ComPtr<IMFMediaType> pType; hr = m_pParent->GetUnknown(MF_MEDIASINK_PREFERREDTYPE, __uuidof(IMFMediaType), (LPVOID*)&pType); if (SUCCEEDED(hr)) { hr = pType->GetMajorType(pguidMajorType); } DebugPrintOut(L"StreamSink::GetMajorType: HRESULT=%i\n", hr); return hr; } private: #ifdef HAVE_WINRT EventRegistrationToken m_token; #else bool m_bConnected; #endif bool m_IsShutdown; // Flag to indicate if Shutdown() method was called. CRITICAL_SECTION m_critSec; #ifndef HAVE_WINRT long m_cRef; #endif IMFAttributes* m_pParent; _ComPtr<IMFMediaType> m_spCurrentType; _ComPtr<IMFMediaEventQueue> m_spEventQueue; // Event queue _ComPtr<IUnknown> m_spFTM; State m_state; bool m_fGetStartTimeFromSample; bool m_fWaitingForFirstSample; MFTIME m_StartTime; // Presentation time when the clock started. GUID m_guiCurrentSubtype; UINT32 m_imageWidthInPixels; UINT32 m_imageHeightInPixels; }; // Notes: // // The List class template implements a simple double-linked list. // It uses STL's copy semantics. // There are two versions of the Clear() method: // Clear(void) clears the list w/out cleaning up the object. // Clear(FN fn) takes a functor object that releases the objects, if they need cleanup. // The List class supports enumeration. Example of usage: // // List<T>::POSIITON pos = list.GetFrontPosition(); // while (pos != list.GetEndPosition()) // { // T item; // hr = list.GetItemPos(&item); // pos = list.Next(pos); // } // The ComPtrList class template derives from List<> and implements a list of COM pointers. template <class T> struct NoOp { void operator()(T& /*t*/) { } }; template <class T> class List { protected: // Nodes in the linked list struct Node { Node *prev; Node *next; T item; Node() : prev(nullptr), next(nullptr) { } Node(T item) : prev(nullptr), next(nullptr) { this->item = item; } T Item() const { return item; } }; public: // Object for enumerating the list. class POSITION { friend class List<T>; public: POSITION() : pNode(nullptr) { } bool operator==(const POSITION &p) const { return pNode == p.pNode; } bool operator!=(const POSITION &p) const { return pNode != p.pNode; } private: const Node *pNode; POSITION(Node *p) : pNode(p) { } }; protected: Node m_anchor; // Anchor node for the linked list. DWORD m_count; // Number of items in the list. Node* Front() const { return m_anchor.next; } Node* Back() const { return m_anchor.prev; } virtual HRESULT InsertAfter(T item, Node *pBefore) { if (pBefore == nullptr) { return E_POINTER; } Node *pNode = new Node(item); if (pNode == nullptr) { return E_OUTOFMEMORY; } Node *pAfter = pBefore->next; pBefore->next = pNode; pAfter->prev = pNode; pNode->prev = pBefore; pNode->next = pAfter; m_count++; return S_OK; } virtual HRESULT GetItem(const Node *pNode, T* ppItem) { if (pNode == nullptr || ppItem == nullptr) { return E_POINTER; } *ppItem = pNode->item; return S_OK; } // RemoveItem: // Removes a node and optionally returns the item. // ppItem can be nullptr. virtual HRESULT RemoveItem(Node *pNode, T *ppItem) { if (pNode == nullptr) { return E_POINTER; } assert(pNode != &m_anchor); // We should never try to remove the anchor node. if (pNode == &m_anchor) { return E_INVALIDARG; } T item; // The next node's previous is this node's previous. pNode->next->prev = pNode->prev; // The previous node's next is this node's next. pNode->prev->next = pNode->next; item = pNode->item; delete pNode; m_count--; if (ppItem) { *ppItem = item; } return S_OK; } public: List() { m_anchor.next = &m_anchor; m_anchor.prev = &m_anchor; m_count = 0; } virtual ~List() { Clear(); } // Insertion functions HRESULT InsertBack(T item) { return InsertAfter(item, m_anchor.prev); } HRESULT InsertFront(T item) { return InsertAfter(item, &m_anchor); } HRESULT InsertPos(POSITION pos, T item) { if (pos.pNode == nullptr) { return InsertBack(item); } return InsertAfter(item, pos.pNode->prev); } // RemoveBack: Removes the tail of the list and returns the value. // ppItem can be nullptr if you don't want the item back. (But the method does not release the item.) HRESULT RemoveBack(T *ppItem) { if (IsEmpty()) { return E_FAIL; } else { return RemoveItem(Back(), ppItem); } } // RemoveFront: Removes the head of the list and returns the value. // ppItem can be nullptr if you don't want the item back. (But the method does not release the item.) HRESULT RemoveFront(T *ppItem) { if (IsEmpty()) { return E_FAIL; } else { return RemoveItem(Front(), ppItem); } } // GetBack: Gets the tail item. HRESULT GetBack(T *ppItem) { if (IsEmpty()) { return E_FAIL; } else { return GetItem(Back(), ppItem); } } // GetFront: Gets the front item. HRESULT GetFront(T *ppItem) { if (IsEmpty()) { return E_FAIL; } else { return GetItem(Front(), ppItem); } } // GetCount: Returns the number of items in the list. DWORD GetCount() const { return m_count; } bool IsEmpty() const { return (GetCount() == 0); } // Clear: Takes a functor object whose operator() // frees the object on the list. template <class FN> void Clear(FN& clear_fn) { Node *n = m_anchor.next; // Delete the nodes while (n != &m_anchor) { clear_fn(n->item); Node *tmp = n->next; delete n; n = tmp; } // Reset the anchor to point at itself m_anchor.next = &m_anchor; m_anchor.prev = &m_anchor; m_count = 0; } // Clear: Clears the list. (Does not delete or release the list items.) virtual void Clear() { NoOp<T> clearOp; Clear<>(clearOp); } // Enumerator functions POSITION FrontPosition() { if (IsEmpty()) { return POSITION(nullptr); } else { return POSITION(Front()); } } POSITION EndPosition() const { return POSITION(); } HRESULT GetItemPos(POSITION pos, T *ppItem) { if (pos.pNode) { return GetItem(pos.pNode, ppItem); } else { return E_FAIL; } } POSITION Next(const POSITION pos) { if (pos.pNode && (pos.pNode->next != &m_anchor)) { return POSITION(pos.pNode->next); } else { return POSITION(nullptr); } } // Remove an item at a position. // The item is returns in ppItem, unless ppItem is nullptr. // NOTE: This method invalidates the POSITION object. HRESULT Remove(POSITION& pos, T *ppItem) { if (pos.pNode) { // Remove const-ness temporarily... Node *pNode = const_cast<Node*>(pos.pNode); pos = POSITION(); return RemoveItem(pNode, ppItem); } else { return E_INVALIDARG; } } }; // Typical functors for Clear method. // ComAutoRelease: Releases COM pointers. // MemDelete: Deletes pointers to new'd memory. class ComAutoRelease { public: void operator()(IUnknown *p) { if (p) { p->Release(); } } }; class MemDelete { public: void operator()(void *p) { if (p) { delete p; } } }; // ComPtrList class // Derived class that makes it safer to store COM pointers in the List<> class. // It automatically AddRef's the pointers that are inserted onto the list // (unless the insertion method fails). // // T must be a COM interface type. // example: ComPtrList<IUnknown> // // NULLABLE: If true, client can insert nullptr pointers. This means GetItem can // succeed but return a nullptr pointer. By default, the list does not allow nullptr // pointers. #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable: 4127) // constant expression #endif template <class T, bool NULLABLE = FALSE> class ComPtrList : public List<T*> { public: typedef T* Ptr; void Clear() { ComAutoRelease car; List<Ptr>::Clear(car); } ~ComPtrList() { Clear(); } protected: HRESULT InsertAfter(Ptr item, Node *pBefore) { // Do not allow nullptr item pointers unless NULLABLE is true. if (item == nullptr && !NULLABLE) { return E_POINTER; } if (item) { item->AddRef(); } HRESULT hr = List<Ptr>::InsertAfter(item, pBefore); if (FAILED(hr) && item != nullptr) { item->Release(); } return hr; } HRESULT GetItem(const Node *pNode, Ptr* ppItem) { Ptr pItem = nullptr; // The base class gives us the pointer without AddRef'ing it. // If we return the pointer to the caller, we must AddRef(). HRESULT hr = List<Ptr>::GetItem(pNode, &pItem); if (SUCCEEDED(hr)) { assert(pItem || NULLABLE); if (pItem) { *ppItem = pItem; (*ppItem)->AddRef(); } } return hr; } HRESULT RemoveItem(Node *pNode, Ptr *ppItem) { // ppItem can be nullptr, but we need to get the // item so that we can release it. // If ppItem is not nullptr, we will AddRef it on the way out. Ptr pItem = nullptr; HRESULT hr = List<Ptr>::RemoveItem(pNode, &pItem); if (SUCCEEDED(hr)) { assert(pItem || NULLABLE); if (ppItem && pItem) { *ppItem = pItem; (*ppItem)->AddRef(); } if (pItem) { pItem->Release(); pItem = nullptr; } } return hr; } }; #ifdef _MSC_VER #pragma warning(pop) #endif /* Be sure to declare webcam device capability in manifest For better media capture support, add the following snippet with correct module name to the project manifest (highgui needs DLL activation class factoryentry points): <Extensions> <Extension Category="windows.activatableClass.inProcessServer"> <InProcessServer> <Path>modulename</Path> <ActivatableClass ActivatableClassId="cv.MediaSink" ThreadingModel="both" /> </InProcessServer> </Extension> </Extensions>*/ extern const __declspec(selectany) WCHAR RuntimeClass_CV_MediaSink[] = L"cv.MediaSink"; class MediaSink : #ifdef HAVE_WINRT public Microsoft::WRL::RuntimeClass< Microsoft::WRL::RuntimeClassFlags< Microsoft::WRL::RuntimeClassType::WinRtClassicComMix >, Microsoft::WRL::Implements<ABI::Windows::Media::IMediaExtension>, IMFMediaSink, IMFClockStateSink, Microsoft::WRL::FtmBase, CBaseAttributes<>> #else public IMFMediaSink, public IMFClockStateSink, public CBaseAttributes<> #endif { #ifdef HAVE_WINRT InspectableClass(RuntimeClass_CV_MediaSink, BaseTrust) public: #else public: ULONG STDMETHODCALLTYPE AddRef() { return InterlockedIncrement(&m_cRef); } ULONG STDMETHODCALLTYPE Release() { ULONG cRef = InterlockedDecrement(&m_cRef); if (cRef == 0) { delete this; } return cRef; } #if defined(_MSC_VER) && _MSC_VER >= 1700 // '_Outptr_result_nullonfailure_' SAL is avaialable since VS 2012 STDMETHOD(QueryInterface)(REFIID riid, _Outptr_result_nullonfailure_ void **ppv) #else STDMETHOD(QueryInterface)(REFIID riid, void **ppv) #endif { if (ppv == nullptr) { return E_POINTER; } (*ppv) = nullptr; HRESULT hr = S_OK; if (riid == IID_IUnknown || riid == IID_IMFMediaSink) { (*ppv) = static_cast<IMFMediaSink*>(this); AddRef(); } else if (riid == IID_IMFClockStateSink) { (*ppv) = static_cast<IMFClockStateSink*>(this); AddRef(); } else if (riid == IID_IMFAttributes) { (*ppv) = static_cast<IMFAttributes*>(this); AddRef(); } else { hr = E_NOINTERFACE; } return hr; } #endif MediaSink() : m_IsShutdown(false), m_llStartTime(0) { CBaseAttributes<>::Initialize(0U); InitializeCriticalSectionEx(&m_critSec, 3000, 0); DebugPrintOut(L"MediaSink::MediaSink\n"); } virtual ~MediaSink() { DebugPrintOut(L"MediaSink::~MediaSink\n"); DeleteCriticalSection(&m_critSec); assert(m_IsShutdown); } HRESULT CheckShutdown() const { if (m_IsShutdown) { return MF_E_SHUTDOWN; } else { return S_OK; } } #ifdef HAVE_WINRT STDMETHODIMP SetProperties(ABI::Windows::Foundation::Collections::IPropertySet *pConfiguration) { HRESULT hr = S_OK; if (pConfiguration) { Microsoft::WRL::ComPtr<IInspectable> spInsp; Microsoft::WRL::ComPtr<ABI::Windows::Foundation::Collections::IMap<HSTRING, IInspectable *>> spSetting; Microsoft::WRL::ComPtr<ABI::Windows::Foundation::IPropertyValue> spPropVal; Microsoft::WRL::ComPtr<ABI::Windows::Media::MediaProperties::IMediaEncodingProperties> pMedEncProps; UINT32 uiType = ABI::Windows::Media::Capture::MediaStreamType_VideoPreview; hr = pConfiguration->QueryInterface(IID_PPV_ARGS(&spSetting)); if (FAILED(hr)) { hr = E_FAIL; } if (SUCCEEDED(hr)) { hr = spSetting->Lookup(Microsoft::WRL::Wrappers::HStringReference(MF_PROP_SAMPLEGRABBERCALLBACK).Get(), spInsp.ReleaseAndGetAddressOf()); if (FAILED(hr)) { hr = E_INVALIDARG; } if (SUCCEEDED(hr)) { hr = SetUnknown(MF_MEDIASINK_SAMPLEGRABBERCALLBACK, spInsp.Get()); } } if (SUCCEEDED(hr)) { hr = spSetting->Lookup(Microsoft::WRL::Wrappers::HStringReference(MF_PROP_VIDTYPE).Get(), spInsp.ReleaseAndGetAddressOf()); if (FAILED(hr)) { hr = E_INVALIDARG; } if (SUCCEEDED(hr)) { if (SUCCEEDED(hr = spInsp.As(&spPropVal))) { hr = spPropVal->GetUInt32(&uiType); } } } if (SUCCEEDED(hr)) { hr = spSetting->Lookup(Microsoft::WRL::Wrappers::HStringReference(MF_PROP_VIDENCPROPS).Get(), spInsp.ReleaseAndGetAddressOf()); if (FAILED(hr)) { hr = E_INVALIDARG; } if (SUCCEEDED(hr)) { hr = spInsp.As(&pMedEncProps); } } if (SUCCEEDED(hr)) { hr = SetMediaStreamProperties((ABI::Windows::Media::Capture::MediaStreamType)uiType, pMedEncProps.Get()); } } return hr; } static DWORD GetStreamId(ABI::Windows::Media::Capture::MediaStreamType mediaStreamType) { return 3 - mediaStreamType; } static HRESULT AddAttribute(_In_ GUID guidKey, _In_ ABI::Windows::Foundation::IPropertyValue *pValue, _In_ IMFAttributes* pAttr) { HRESULT hr = S_OK; PROPVARIANT var; ABI::Windows::Foundation::PropertyType type; hr = pValue->get_Type(&type); ZeroMemory(&var, sizeof(var)); if (SUCCEEDED(hr)) { switch (type) { case ABI::Windows::Foundation::PropertyType_UInt8Array: { UINT32 cbBlob; BYTE *pbBlog = nullptr; hr = pValue->GetUInt8Array(&cbBlob, &pbBlog); if (SUCCEEDED(hr)) { if (pbBlog == nullptr) { hr = E_INVALIDARG; } else { hr = pAttr->SetBlob(guidKey, pbBlog, cbBlob); } } CoTaskMemFree(pbBlog); } break; case ABI::Windows::Foundation::PropertyType_Double: { DOUBLE value; hr = pValue->GetDouble(&value); if (SUCCEEDED(hr)) { hr = pAttr->SetDouble(guidKey, value); } } break; case ABI::Windows::Foundation::PropertyType_Guid: { GUID value; hr = pValue->GetGuid(&value); if (SUCCEEDED(hr)) { hr = pAttr->SetGUID(guidKey, value); } } break; case ABI::Windows::Foundation::PropertyType_String: { Microsoft::WRL::Wrappers::HString value; hr = pValue->GetString(value.GetAddressOf()); if (SUCCEEDED(hr)) { UINT32 len = 0; LPCWSTR szValue = WindowsGetStringRawBuffer(value.Get(), &len); hr = pAttr->SetString(guidKey, szValue); } } break; case ABI::Windows::Foundation::PropertyType_UInt32: { UINT32 value; hr = pValue->GetUInt32(&value); if (SUCCEEDED(hr)) { pAttr->SetUINT32(guidKey, value); } } break; case ABI::Windows::Foundation::PropertyType_UInt64: { UINT64 value; hr = pValue->GetUInt64(&value); if (SUCCEEDED(hr)) { hr = pAttr->SetUINT64(guidKey, value); } } break; case ABI::Windows::Foundation::PropertyType_Inspectable: { Microsoft::WRL::ComPtr<IInspectable> value; hr = TYPE_E_TYPEMISMATCH; if (SUCCEEDED(hr)) { pAttr->SetUnknown(guidKey, value.Get()); } } break; // ignore unknown values } } return hr; } static HRESULT ConvertPropertiesToMediaType(_In_ ABI::Windows::Media::MediaProperties::IMediaEncodingProperties *pMEP, _Outptr_ IMFMediaType **ppMT) { HRESULT hr = S_OK; _ComPtr<IMFMediaType> spMT; Microsoft::WRL::ComPtr<ABI::Windows::Foundation::Collections::IMap<GUID, IInspectable*>> spMap; Microsoft::WRL::ComPtr<ABI::Windows::Foundation::Collections::IIterable<ABI::Windows::Foundation::Collections::IKeyValuePair<GUID, IInspectable*>*>> spIterable; Microsoft::WRL::ComPtr<ABI::Windows::Foundation::Collections::IIterator<ABI::Windows::Foundation::Collections::IKeyValuePair<GUID, IInspectable*>*>> spIterator; if (pMEP == nullptr || ppMT == nullptr) { return E_INVALIDARG; } *ppMT = nullptr; hr = pMEP->get_Properties(spMap.GetAddressOf()); if (SUCCEEDED(hr)) { hr = spMap.As(&spIterable); } if (SUCCEEDED(hr)) { hr = spIterable->First(&spIterator); } if (SUCCEEDED(hr)) { MFCreateMediaType(spMT.ReleaseAndGetAddressOf()); } boolean hasCurrent = false; if (SUCCEEDED(hr)) { hr = spIterator->get_HasCurrent(&hasCurrent); } while (hasCurrent) { Microsoft::WRL::ComPtr<ABI::Windows::Foundation::Collections::IKeyValuePair<GUID, IInspectable*> > spKeyValuePair; Microsoft::WRL::ComPtr<IInspectable> spValue; Microsoft::WRL::ComPtr<ABI::Windows::Foundation::IPropertyValue> spPropValue; GUID guidKey; hr = spIterator->get_Current(&spKeyValuePair); if (FAILED(hr)) { break; } hr = spKeyValuePair->get_Key(&guidKey); if (FAILED(hr)) { break; } hr = spKeyValuePair->get_Value(&spValue); if (FAILED(hr)) { break; } hr = spValue.As(&spPropValue); if (FAILED(hr)) { break; } hr = AddAttribute(guidKey, spPropValue.Get(), spMT.Get()); if (FAILED(hr)) { break; } hr = spIterator->MoveNext(&hasCurrent); if (FAILED(hr)) { break; } } if (SUCCEEDED(hr)) { Microsoft::WRL::ComPtr<IInspectable> spValue; Microsoft::WRL::ComPtr<ABI::Windows::Foundation::IPropertyValue> spPropValue; GUID guiMajorType; hr = spMap->Lookup(MF_MT_MAJOR_TYPE, spValue.GetAddressOf()); if (SUCCEEDED(hr)) { hr = spValue.As(&spPropValue); } if (SUCCEEDED(hr)) { hr = spPropValue->GetGuid(&guiMajorType); } if (SUCCEEDED(hr)) { if (guiMajorType != MFMediaType_Video && guiMajorType != MFMediaType_Audio) { hr = E_UNEXPECTED; } } } if (SUCCEEDED(hr)) { *ppMT = spMT.Detach(); } return hr; } //this should be passed through SetProperties! HRESULT SetMediaStreamProperties(ABI::Windows::Media::Capture::MediaStreamType MediaStreamType, _In_opt_ ABI::Windows::Media::MediaProperties::IMediaEncodingProperties *mediaEncodingProperties) { HRESULT hr = S_OK; _ComPtr<IMFMediaType> spMediaType; if (MediaStreamType != ABI::Windows::Media::Capture::MediaStreamType_VideoPreview && MediaStreamType != ABI::Windows::Media::Capture::MediaStreamType_VideoRecord && MediaStreamType != ABI::Windows::Media::Capture::MediaStreamType_Audio) { return E_INVALIDARG; } RemoveStreamSink(GetStreamId(MediaStreamType)); if (mediaEncodingProperties != nullptr) { _ComPtr<IMFStreamSink> spStreamSink; hr = ConvertPropertiesToMediaType(mediaEncodingProperties, &spMediaType); if (SUCCEEDED(hr)) { hr = AddStreamSink(GetStreamId(MediaStreamType), nullptr, spStreamSink.GetAddressOf()); } if (SUCCEEDED(hr)) { hr = SetUnknown(MF_MEDIASINK_PREFERREDTYPE, spMediaType.Detach()); } } return hr; } #endif //IMFMediaSink HRESULT STDMETHODCALLTYPE GetCharacteristics( /* [out] */ __RPC__out DWORD *pdwCharacteristics) { HRESULT hr; if (pdwCharacteristics == NULL) return E_INVALIDARG; EnterCriticalSection(&m_critSec); if (SUCCEEDED(hr = CheckShutdown())) { //if had an activation object for the sink, shut down would be managed and MF_STREAM_SINK_SUPPORTS_ROTATION appears to be setable to TRUE *pdwCharacteristics = MEDIASINK_FIXED_STREAMS;// | MEDIASINK_REQUIRE_REFERENCE_MEDIATYPE; } LeaveCriticalSection(&m_critSec); DebugPrintOut(L"MediaSink::GetCharacteristics: HRESULT=%i\n", hr); return hr; } HRESULT STDMETHODCALLTYPE AddStreamSink( DWORD dwStreamSinkIdentifier, IMFMediaType * /*pMediaType*/, IMFStreamSink **ppStreamSink) { _ComPtr<IMFStreamSink> spMFStream; _ComPtr<ICustomStreamSink> pStream; EnterCriticalSection(&m_critSec); HRESULT hr = CheckShutdown(); if (SUCCEEDED(hr)) { hr = GetStreamSinkById(dwStreamSinkIdentifier, &spMFStream); } if (SUCCEEDED(hr)) { hr = MF_E_STREAMSINK_EXISTS; } else { hr = S_OK; } if (SUCCEEDED(hr)) { #ifdef HAVE_WINRT pStream = Microsoft::WRL::Make<StreamSink>(); if (pStream == nullptr) { hr = E_OUTOFMEMORY; } if (SUCCEEDED(hr)) hr = pStream.As<IMFStreamSink>(&spMFStream); #else StreamSink* pSink = new StreamSink(); if (pSink) { hr = pSink->QueryInterface(IID_IMFStreamSink, (void**)spMFStream.GetAddressOf()); if (SUCCEEDED(hr)) { hr = spMFStream.As(&pStream); } if (FAILED(hr)) delete pSink; } #endif } // Initialize the stream. _ComPtr<IMFAttributes> pAttr; if (SUCCEEDED(hr)) { hr = pStream.As(&pAttr); } if (SUCCEEDED(hr)) { hr = pAttr->SetUINT32(MF_STREAMSINK_ID, dwStreamSinkIdentifier); if (SUCCEEDED(hr)) { hr = pAttr->SetUnknown(MF_STREAMSINK_MEDIASINKINTERFACE, (IMFMediaSink*)this); } } if (SUCCEEDED(hr)) { hr = pStream->Initialize(); } if (SUCCEEDED(hr)) { ComPtrList<IMFStreamSink>::POSITION pos = m_streams.FrontPosition(); ComPtrList<IMFStreamSink>::POSITION posEnd = m_streams.EndPosition(); // Insert in proper position for (; pos != posEnd; pos = m_streams.Next(pos)) { DWORD dwCurrId; _ComPtr<IMFStreamSink> spCurr; hr = m_streams.GetItemPos(pos, &spCurr); if (FAILED(hr)) { break; } hr = spCurr->GetIdentifier(&dwCurrId); if (FAILED(hr)) { break; } if (dwCurrId > dwStreamSinkIdentifier) { break; } } if (SUCCEEDED(hr)) { hr = m_streams.InsertPos(pos, spMFStream.Get()); } } if (SUCCEEDED(hr)) { *ppStreamSink = spMFStream.Detach(); } LeaveCriticalSection(&m_critSec); DebugPrintOut(L"MediaSink::AddStreamSink: HRESULT=%i\n", hr); return hr; } HRESULT STDMETHODCALLTYPE RemoveStreamSink(DWORD dwStreamSinkIdentifier) { EnterCriticalSection(&m_critSec); HRESULT hr = CheckShutdown(); ComPtrList<IMFStreamSink>::POSITION pos = m_streams.FrontPosition(); ComPtrList<IMFStreamSink>::POSITION endPos = m_streams.EndPosition(); _ComPtr<IMFStreamSink> spStream; if (SUCCEEDED(hr)) { for (; pos != endPos; pos = m_streams.Next(pos)) { hr = m_streams.GetItemPos(pos, &spStream); DWORD dwId; if (FAILED(hr)) { break; } hr = spStream->GetIdentifier(&dwId); if (FAILED(hr) || dwId == dwStreamSinkIdentifier) { break; } } if (pos == endPos) { hr = MF_E_INVALIDSTREAMNUMBER; } } if (SUCCEEDED(hr)) { hr = m_streams.Remove(pos, nullptr); _ComPtr<ICustomStreamSink> spCustomSink; #ifdef HAVE_WINRT spCustomSink = static_cast<StreamSink*>(spStream.Get()); hr = S_OK; #else hr = spStream.As(&spCustomSink); #endif if (SUCCEEDED(hr)) hr = spCustomSink->Shutdown(); } LeaveCriticalSection(&m_critSec); DebugPrintOut(L"MediaSink::RemoveStreamSink: HRESULT=%i\n", hr); return hr; } HRESULT STDMETHODCALLTYPE GetStreamSinkCount(DWORD *pStreamSinkCount) { if (pStreamSinkCount == NULL) { return E_INVALIDARG; } EnterCriticalSection(&m_critSec); HRESULT hr = CheckShutdown(); if (SUCCEEDED(hr)) { *pStreamSinkCount = m_streams.GetCount(); } LeaveCriticalSection(&m_critSec); DebugPrintOut(L"MediaSink::GetStreamSinkCount: HRESULT=%i\n", hr); return hr; } HRESULT STDMETHODCALLTYPE GetStreamSinkByIndex( DWORD dwIndex, IMFStreamSink **ppStreamSink) { if (ppStreamSink == NULL) { return E_INVALIDARG; } _ComPtr<IMFStreamSink> spStream; EnterCriticalSection(&m_critSec); DWORD cStreams = m_streams.GetCount(); if (dwIndex >= cStreams) { return MF_E_INVALIDINDEX; } HRESULT hr = CheckShutdown(); if (SUCCEEDED(hr)) { ComPtrList<IMFStreamSink>::POSITION pos = m_streams.FrontPosition(); ComPtrList<IMFStreamSink>::POSITION endPos = m_streams.EndPosition(); DWORD dwCurrent = 0; for (; pos != endPos && dwCurrent < dwIndex; pos = m_streams.Next(pos), ++dwCurrent) { // Just move to proper position } if (pos == endPos) { hr = MF_E_UNEXPECTED; } else { hr = m_streams.GetItemPos(pos, &spStream); } } if (SUCCEEDED(hr)) { *ppStreamSink = spStream.Detach(); } LeaveCriticalSection(&m_critSec); DebugPrintOut(L"MediaSink::GetStreamSinkByIndex: HRESULT=%i\n", hr); return hr; } HRESULT STDMETHODCALLTYPE GetStreamSinkById( DWORD dwStreamSinkIdentifier, IMFStreamSink **ppStreamSink) { if (ppStreamSink == NULL) { return E_INVALIDARG; } EnterCriticalSection(&m_critSec); HRESULT hr = CheckShutdown(); _ComPtr<IMFStreamSink> spResult; if (SUCCEEDED(hr)) { ComPtrList<IMFStreamSink>::POSITION pos = m_streams.FrontPosition(); ComPtrList<IMFStreamSink>::POSITION endPos = m_streams.EndPosition(); for (; pos != endPos; pos = m_streams.Next(pos)) { _ComPtr<IMFStreamSink> spStream; hr = m_streams.GetItemPos(pos, &spStream); DWORD dwId; if (FAILED(hr)) { break; } hr = spStream->GetIdentifier(&dwId); if (FAILED(hr)) { break; } else if (dwId == dwStreamSinkIdentifier) { spResult = spStream; break; } } if (pos == endPos) { hr = MF_E_INVALIDSTREAMNUMBER; } } if (SUCCEEDED(hr)) { assert(spResult); *ppStreamSink = spResult.Detach(); } LeaveCriticalSection(&m_critSec); DebugPrintOut(L"MediaSink::GetStreamSinkById: HRESULT=%i\n", hr); return hr; } HRESULT STDMETHODCALLTYPE SetPresentationClock( IMFPresentationClock *pPresentationClock) { EnterCriticalSection(&m_critSec); HRESULT hr = CheckShutdown(); // If we already have a clock, remove ourselves from that clock's // state notifications. if (SUCCEEDED(hr)) { if (m_spClock) { hr = m_spClock->RemoveClockStateSink(this); } } // Register ourselves to get state notifications from the new clock. if (SUCCEEDED(hr)) { if (pPresentationClock) { hr = pPresentationClock->AddClockStateSink(this); } } _ComPtr<IMFSampleGrabberSinkCallback> pSampleCallback; if (SUCCEEDED(hr)) { // Release the pointer to the old clock. // Store the pointer to the new clock. m_spClock = pPresentationClock; hr = GetUnknown(MF_MEDIASINK_SAMPLEGRABBERCALLBACK, IID_IMFSampleGrabberSinkCallback, (LPVOID*)pSampleCallback.GetAddressOf()); } LeaveCriticalSection(&m_critSec); if (SUCCEEDED(hr)) hr = pSampleCallback->OnSetPresentationClock(pPresentationClock); DebugPrintOut(L"MediaSink::SetPresentationClock: HRESULT=%i\n", hr); return hr; } HRESULT STDMETHODCALLTYPE GetPresentationClock( IMFPresentationClock **ppPresentationClock) { if (ppPresentationClock == NULL) { return E_INVALIDARG; } EnterCriticalSection(&m_critSec); HRESULT hr = CheckShutdown(); if (SUCCEEDED(hr)) { if (!m_spClock) { hr = MF_E_NO_CLOCK; // There is no presentation clock. } else { // Return the pointer to the caller. hr = m_spClock.CopyTo(ppPresentationClock); } } LeaveCriticalSection(&m_critSec); DebugPrintOut(L"MediaSink::GetPresentationClock: HRESULT=%i\n", hr); return hr; } HRESULT STDMETHODCALLTYPE Shutdown(void) { EnterCriticalSection(&m_critSec); HRESULT hr = CheckShutdown(); if (SUCCEEDED(hr)) { ForEach(m_streams, ShutdownFunc()); m_streams.Clear(); m_spClock.ReleaseAndGetAddressOf(); _ComPtr<IMFMediaType> pType; hr = CBaseAttributes<>::GetUnknown(MF_MEDIASINK_PREFERREDTYPE, __uuidof(IMFMediaType), (LPVOID*)pType.GetAddressOf()); if (SUCCEEDED(hr)) { hr = DeleteItem(MF_MEDIASINK_PREFERREDTYPE); } m_IsShutdown = true; } LeaveCriticalSection(&m_critSec); DebugPrintOut(L"MediaSink::Shutdown: HRESULT=%i\n", hr); return hr; } class ShutdownFunc { public: HRESULT operator()(IMFStreamSink *pStream) const { _ComPtr<ICustomStreamSink> spCustomSink; HRESULT hr; #ifdef HAVE_WINRT spCustomSink = static_cast<StreamSink*>(pStream); #else hr = pStream->QueryInterface(IID_PPV_ARGS(spCustomSink.GetAddressOf())); if (FAILED(hr)) return hr; #endif hr = spCustomSink->Shutdown(); return hr; } }; class StartFunc { public: StartFunc(LONGLONG llStartTime) : _llStartTime(llStartTime) { } HRESULT operator()(IMFStreamSink *pStream) const { _ComPtr<ICustomStreamSink> spCustomSink; HRESULT hr; #ifdef HAVE_WINRT spCustomSink = static_cast<StreamSink*>(pStream); #else hr = pStream->QueryInterface(IID_PPV_ARGS(spCustomSink.GetAddressOf())); if (FAILED(hr)) return hr; #endif hr = spCustomSink->Start(_llStartTime); return hr; } LONGLONG _llStartTime; }; class StopFunc { public: HRESULT operator()(IMFStreamSink *pStream) const { _ComPtr<ICustomStreamSink> spCustomSink; HRESULT hr; #ifdef HAVE_WINRT spCustomSink = static_cast<StreamSink*>(pStream); #else hr = pStream->QueryInterface(IID_PPV_ARGS(spCustomSink.GetAddressOf())); if (FAILED(hr)) return hr; #endif hr = spCustomSink->Stop(); return hr; } }; template <class T, class TFunc> HRESULT ForEach(ComPtrList<T> &col, TFunc fn) { ComPtrList<T>::POSITION pos = col.FrontPosition(); ComPtrList<T>::POSITION endPos = col.EndPosition(); HRESULT hr = S_OK; for (; pos != endPos; pos = col.Next(pos)) { _ComPtr<T> spStream; hr = col.GetItemPos(pos, &spStream); if (FAILED(hr)) { break; } hr = fn(spStream.Get()); } return hr; } //IMFClockStateSink HRESULT STDMETHODCALLTYPE OnClockStart( MFTIME hnsSystemTime, LONGLONG llClockStartOffset) { EnterCriticalSection(&m_critSec); HRESULT hr = CheckShutdown(); if (SUCCEEDED(hr)) { // Start each stream. m_llStartTime = llClockStartOffset; hr = ForEach(m_streams, StartFunc(llClockStartOffset)); } _ComPtr<IMFSampleGrabberSinkCallback> pSampleCallback; if (SUCCEEDED(hr)) hr = GetUnknown(MF_MEDIASINK_SAMPLEGRABBERCALLBACK, IID_IMFSampleGrabberSinkCallback, (LPVOID*)pSampleCallback.GetAddressOf()); LeaveCriticalSection(&m_critSec); if (SUCCEEDED(hr)) hr = pSampleCallback->OnClockStart(hnsSystemTime, llClockStartOffset); DebugPrintOut(L"MediaSink::OnClockStart: HRESULT=%i\n", hr); return hr; } HRESULT STDMETHODCALLTYPE OnClockStop( MFTIME hnsSystemTime) { EnterCriticalSection(&m_critSec); HRESULT hr = CheckShutdown(); if (SUCCEEDED(hr)) { // Stop each stream hr = ForEach(m_streams, StopFunc()); } _ComPtr<IMFSampleGrabberSinkCallback> pSampleCallback; if (SUCCEEDED(hr)) hr = GetUnknown(MF_MEDIASINK_SAMPLEGRABBERCALLBACK, IID_IMFSampleGrabberSinkCallback, (LPVOID*)pSampleCallback.GetAddressOf()); LeaveCriticalSection(&m_critSec); if (SUCCEEDED(hr)) hr = pSampleCallback->OnClockStop(hnsSystemTime); DebugPrintOut(L"MediaSink::OnClockStop: HRESULT=%i\n", hr); return hr; } HRESULT STDMETHODCALLTYPE OnClockPause( MFTIME hnsSystemTime) { HRESULT hr; _ComPtr<IMFSampleGrabberSinkCallback> pSampleCallback; hr = GetUnknown(MF_MEDIASINK_SAMPLEGRABBERCALLBACK, IID_IMFSampleGrabberSinkCallback, (LPVOID*)pSampleCallback.GetAddressOf()); if (SUCCEEDED(hr)) hr = pSampleCallback->OnClockPause(hnsSystemTime); DebugPrintOut(L"MediaSink::OnClockPause: HRESULT=%i\n", hr); return hr; } HRESULT STDMETHODCALLTYPE OnClockRestart( MFTIME hnsSystemTime) { HRESULT hr; _ComPtr<IMFSampleGrabberSinkCallback> pSampleCallback; hr = GetUnknown(MF_MEDIASINK_SAMPLEGRABBERCALLBACK, IID_IMFSampleGrabberSinkCallback, (LPVOID*)pSampleCallback.GetAddressOf()); if (SUCCEEDED(hr)) hr = pSampleCallback->OnClockRestart(hnsSystemTime); DebugPrintOut(L"MediaSink::OnClockRestart: HRESULT=%i\n", hr); return hr; } HRESULT STDMETHODCALLTYPE OnClockSetRate( MFTIME hnsSystemTime, float flRate) { HRESULT hr; _ComPtr<IMFSampleGrabberSinkCallback> pSampleCallback; hr = GetUnknown(MF_MEDIASINK_SAMPLEGRABBERCALLBACK, IID_IMFSampleGrabberSinkCallback, (LPVOID*)pSampleCallback.GetAddressOf()); if (SUCCEEDED(hr)) hr = pSampleCallback->OnClockSetRate(hnsSystemTime, flRate); DebugPrintOut(L"MediaSink::OnClockSetRate: HRESULT=%i\n", hr); return hr; } private: #ifndef HAVE_WINRT long m_cRef; #endif CRITICAL_SECTION m_critSec; bool m_IsShutdown; ComPtrList<IMFStreamSink> m_streams; _ComPtr<IMFPresentationClock> m_spClock; LONGLONG m_llStartTime; }; #ifdef HAVE_WINRT ActivatableClass(MediaSink); #endif
Java
#money Node.js module to perform precise common money calculations. This library is a partial javascript implementation of the [Money Pattern](http://martinfowler.com/eaaCatalog/money.html) as described by Martin Fowler in his book *Patterns of Enterprise Application Architecture*. ## Using the library ```javascript var money = require('path/to/lib/money.js'); // Show me those monies var inheritance = money.dollar(1234567.89); // Subtract taxes var TAXMAN = 0.69; var netSum = inheritance.mult(TAXMAN); console.log(netSum.toNumber()); // 851851.84 // Hand out loot to heirs. // The oldest will receive 40% of the money, the next one 30% etc. var heirs = netSum.allocate([4,3,2,1]); heirs.forEach(function(heir) { console.log(heir.toNumber()); }); // 340740.74 // 255555.56 // 170370.36 // 85185.18 var addBack = heirs[0].add(heirs[1]).add(heirs[2]).add(heirs[3]); assert.deepEqual(addBack, netSum); // undefined (wow so money much precise) ``` ## Running the tests (*nix only) 1. Clone and install [node-jscoverage](https://github.com/visionmedia/node-jscoverage) in your system 2. Enter the money repository and run `jscoverage lib/ lib-cov/` to instrument the library 3. Install [Mocha](http://mochajs.org/) as a command via npm `sudo npm install -g mocha` * a. To run the tests execute the following command: `mocha --ui tdd test/test.js` * b. To view a coverage report use the `html-cov` reporter: `mocha --ui tdd -R html-cov test/test.js > report.html` and open the HTML file with your browser of choice.
Java
angular.module('starter.controllers', []) // A simple controller that fetches a list of data from a service .controller('PetIndexCtrl', function($scope, PetService) { // "Pets" is a service returning mock data (services.js) $scope.pets = PetService.all(); }) // A simple controller that shows a tapped item's data .controller('PetDetailCtrl', function($scope, $stateParams, PetService) { // "Pets" is a service returning mock data (services.js) $scope.pet = PetService.get($stateParams.petId); }) // getting fake favor data .controller('FavorIndexCtrl', function($scope, FavorService) { $scope.favors = FavorService.all(); }) // A simple controller that shows a tapped item's data .controller('FavorDetailCtrl', function($scope, $stateParams, FavorService) { // "Pets" is a service returning mock data (services.js) $scope.favor = FavorService.get($stateParams.favorId); });
Java
<html lang="en"> <head> <title>Native - Debugging with GDB</title> <meta http-equiv="Content-Type" content="text/html"> <meta name="description" content="Debugging with GDB"> <meta name="generator" content="makeinfo 4.11"> <link title="Top" rel="start" href="index.html#Top"> <link rel="up" href="Configurations.html#Configurations" title="Configurations"> <link rel="next" href="Embedded-OS.html#Embedded-OS" title="Embedded OS"> <link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage"> <!-- Copyright (C) 1988-2014 Free Software Foundation, Inc. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with the Invariant Sections being ``Free Software'' and ``Free Software Needs Free Documentation'', with the Front-Cover Texts being ``A GNU Manual,'' and with the Back-Cover Texts as in (a) below. (a) The FSF's Back-Cover Text is: ``You are free to copy and modify this GNU Manual. Buying copies from GNU Press supports the FSF in developing GNU and promoting software freedom.'' --> <meta http-equiv="Content-Style-Type" content="text/css"> <style type="text/css"><!-- pre.display { font-family:inherit } pre.format { font-family:inherit } pre.smalldisplay { font-family:inherit; font-size:smaller } pre.smallformat { font-family:inherit; font-size:smaller } pre.smallexample { font-size:smaller } pre.smalllisp { font-size:smaller } span.sc { font-variant:small-caps } span.roman { font-family:serif; font-weight:normal; } span.sansserif { font-family:sans-serif; font-weight:normal; } --></style> </head> <body> <div class="node"> <p> <a name="Native"></a> Next:&nbsp;<a rel="next" accesskey="n" href="Embedded-OS.html#Embedded-OS">Embedded OS</a>, Up:&nbsp;<a rel="up" accesskey="u" href="Configurations.html#Configurations">Configurations</a> <hr> </div> <h3 class="section">21.1 Native</h3> <p>This section describes details specific to particular native configurations. <ul class="menu"> <li><a accesskey="1" href="HP_002dUX.html#HP_002dUX">HP-UX</a>: HP-UX <li><a accesskey="2" href="BSD-libkvm-Interface.html#BSD-libkvm-Interface">BSD libkvm Interface</a>: Debugging BSD kernel memory images <li><a accesskey="3" href="SVR4-Process-Information.html#SVR4-Process-Information">SVR4 Process Information</a>: SVR4 process information <li><a accesskey="4" href="DJGPP-Native.html#DJGPP-Native">DJGPP Native</a>: Features specific to the DJGPP port <li><a accesskey="5" href="Cygwin-Native.html#Cygwin-Native">Cygwin Native</a>: Features specific to the Cygwin port <li><a accesskey="6" href="Hurd-Native.html#Hurd-Native">Hurd Native</a>: Features specific to <span class="sc">gnu</span> Hurd <li><a accesskey="7" href="Darwin.html#Darwin">Darwin</a>: Features specific to Darwin </ul> </body></html>
Java
// // FXCachePlist.h // FancyMall // // Created by fancy on 16/1/14. // Copyright © 2016年 FancyMall. All rights reserved. // #import <Foundation/Foundation.h> @interface FXCachePlist : NSObject +(instancetype)sharedPlist; -(NSString *)needRemoveFileName; -(void)dataForDataArrayWithUrl:(NSString *)url withMark:(NSString *)mark; -(void)removeOldFileAndOldFileName; -(NSMutableArray *)readArrayFramePlist; //-(void)creatFileWithWithList; /**将数据写入到文件中去*/ //-(void)dataToPlist:(NSMutableArray *)mutArray; /**将数据进行删除*/ -(void)removeFileByLabel:(NSString *)label; @end
Java
// Copyright 2011, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * 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. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "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 COPYRIGHT // OWNER 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. var kDefaultNumberOfResampleRanges = 11; function WaveTable(name, context) { this.name = name; this.context = context; this.sampleRate = context.sampleRate; this.url = "wave-tables/" + this.name; this.waveTableSize = 4096; // hard-coded for now this.buffer = 0; this.numberOfResampleRanges = kDefaultNumberOfResampleRanges; } WaveTable.prototype.getWaveDataForPitch = function(pitchFrequency) { var nyquist = 0.5 * this.sampleRate; var lowestNumPartials = this.getNumberOfPartialsForRange(0); var lowestFundamental = nyquist / lowestNumPartials; // Find out pitch range var ratio = pitchFrequency / lowestFundamental; var pitchRange = ratio == 0.0 ? 0 : Math.floor(Math.log(ratio) / Math.LN2); if (pitchRange < 0) pitchRange = 0; // Too bad, we'll alias if pitch is greater than around 5KHz :) if (pitchRange >= this.numberOfResampleRanges) pitchRange = this.numberOfResampleRanges - 1; return this.buffers[pitchRange]; } WaveTable.prototype.getNumberOfPartialsForRange = function(j) { // goes from 1024 -> 4 @ 44.1KHz (and do same for 48KHz) // goes from 2048 -> 8 @ 96KHz var npartials = Math.pow(2, 1 + this.numberOfResampleRanges - j); if (this.getSampleRate() > 48000.0) npartials *= 2; // high sample rate allows more harmonics at given fundamental return npartials; } WaveTable.prototype.getWaveTableSize = function() { return this.waveTableSize; } WaveTable.prototype.getSampleRate = function() { return this.sampleRate; } WaveTable.prototype.getRateScale = function() { return this.getWaveTableSize() / this.getSampleRate(); } WaveTable.prototype.getNumberOfResampleRanges = function() { this.numberOfResampleRanges; } WaveTable.prototype.getName = function() { return this.name; } WaveTable.prototype.load = function(callback) { var request = new XMLHttpRequest(); request.open("GET", this.url, true); var wave = this; request.onload = function() { // Get the frequency-domain waveform data. var f = eval('(' + request.responseText + ')'); // Copy into more efficient Float32Arrays. var n = f.real.length; frequencyData = { "real": new Float32Array(n), "imag": new Float32Array(n) }; wave.frequencyData = frequencyData; for (var i = 0; i < n; ++i) { frequencyData.real[i] = f.real[i]; frequencyData.imag[i] = f.imag[i]; } wave.createBuffers(); if (callback) callback(wave); }; request.onerror = function() { alert("error loading: " + wave.url); }; request.send(); } WaveTable.prototype.print = function() { var f = this.frequencyData; var info = document.getElementById("info"); var s = ""; for (var i = 0; i < 2048; ++i) { s += "{" + f.real[i] + ", " + f.imag[i] + "}, <br>"; } info.innerHTML = s; } WaveTable.prototype.printBuffer = function(buffer) { var info = document.getElementById("info"); var s = ""; for (var i = 0; i < 4096; ++i) { s += buffer[i] + "<br>"; } info.innerHTML = s; } // WaveTable.prototype.createBuffers = function() { // var f = this.frequencyData; // // var n = 4096; // // var fft = new FFT(n, 44100); // // // Copy from loaded frequency data and scale. // for (var i = 0; i < n / 2; ++i) { // fft.real[i] = 4096 * f.real[i]; // fft.imag[i] = 4096 * f.imag[i]; // } // // // Now do inverse FFT // this.data = fft.inverse(); // var data = this.data; // // this.buffer = context.createBuffer(1, data.length, 44100); // // // Copy data to the buffer. // var p = this.buffer.getChannelData(0); // for (var i = 0; i < data.length; ++i) { // p[i] = data[i]; // } // } // Convert into time-domain wave tables. // We actually create several of them for non-aliasing playback at different playback rates. WaveTable.prototype.createBuffers = function() { // resample ranges // // let's divide up versions of our waves based on the maximum fundamental frequency we're // resampling at. Let's use fundamental frequencies based on dividing Nyquist by powers of two. // For example for 44.1KHz sample-rate we have: // // ranges // ---------------------------------- // 21Hz, 43Hz, 86Hz, 172Hz, 344Hz, 689Hz, 1378Hz, 2756Hz, 5512Hz, 11025Hz, 22050Hz <-- 44.1KHz // 23Hz, 47Hz, 94Hz, 187Hz, 375Hz, 750Hz, 1500Hz, 3000Hz, 6000Hz, 12000Hz, 24000Hz, 48000Hz <-- 96KHz // // and number of partials: // // 1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1 // 2048, 1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1 // // But it's probably OK if we skip the very highest fundamental frequencies and only // go up to 5512Hz, so we have a total of 9 resample ranges // // 0 1 2 3 4 5 6 7 8 // The FFT size needs to be at least 2048 @ 44.1KHz and 4096 @ 96KHz // // So let's try to use FFT size of 4096 all the time and pull out the harmonics we want // this.buffers = new Array(); var finalScale = 1.0; for (var j = 0; j < this.numberOfResampleRanges; ++j) { var n = this.waveTableSize; var frame = new FFT(n, this.sampleRate); // Copy from loaded frequency data and scale. var f = this.frequencyData; var scale = n; for (var i = 0; i < n / 2; ++i) { frame.real[i] = scale * f.real[i]; frame.imag[i] = scale * f.imag[i]; } var realP = frame.real; var imagP = frame.imag; // Find the starting bin where we should start clearing out // (we need to clear out the highest frequencies to band-limit the waveform) var fftSize = n; var halfSize = fftSize / 2; var npartials = this.getNumberOfPartialsForRange(j); // Now, go through and cull out the aliasing harmonics... for (var i = npartials + 1; i < halfSize; i++) { realP[i] = 0.0; imagP[i] = 0.0; } // Clear packed-nyquist if necessary if (npartials < halfSize) imagP[0] = 0.0; // Clear any DC-offset realP[0] = 0.0; // For the first resample range, find power and compute scale. if (j == 0) { var power = 0; for (var i = 1; i < halfSize; ++i) { x = realP[i]; y = imagP[i]; power += x * x + y * y; } power = Math.sqrt(power) / fftSize; finalScale = 0.5 / power; // window.console.log("power = " + power); } // Great, now do inverse FFT into our wavetable... var data = frame.inverse(); // Create mono AudioBuffer. var buffer = this.context.createBuffer(1, data.length, this.sampleRate); // Copy data to the buffer. var p = buffer.getChannelData(0); for (var i = 0; i < data.length; ++i) { p[i] = finalScale * data[i]; } this.buffers[j] = buffer; } } WaveTable.prototype.displayWaveData = function() { var data = this.data; var n = data.length; var s = ""; for (var i = 0; i < n; ++i) { s += data[i].toFixed(3) + "<br> "; } var info = document.getElementById("info"); info.innerHTML = s; }
Java
/** * Created by maomao on 2020/4/20. */ Java.perform(function() { var cn = "android.telephony.SubscriptionManager"; var target = Java.use(cn); if (target) { target.addOnSubscriptionsChangedListener.overloads[0].implementation = function(dest) { var myArray=new Array() myArray[0] = "SENSITIVE" //INTERESTED & SENSITIVE myArray[1] = cn + "." + "addOnSubscriptionsChangedListener"; myArray[2] = Java.use("android.util.Log").getStackTraceString(Java.use("java.lang.Exception").$new()).split('\n\tat'); send(myArray); return this.addOnSubscriptionsChangedListener.overloads[0].apply(this, arguments); }; // target.addOnSubscriptionsChangedListener.overloads[1].implementation = function(dest) { // var myArray=new Array() // myArray[0] = "SENSITIVE" //INTERESTED & SENSITIVE // myArray[1] = cn + "." + "addOnSubscriptionsChangedListener"; // myArray[2] = Java.use("android.util.Log").getStackTraceString(Java.use("java.lang.Exception").$new()).split('\n\tat'); // send(myArray); // return this.addOnSubscriptionsChangedListener.overloads[1].apply(this, arguments); // }; target.getActiveSubscriptionInfo.overloads[0].implementation = function(dest) { var myArray=new Array() myArray[0] = "SENSITIVE" //INTERESTED & SENSITIVE myArray[1] = cn + "." + "getActiveSubscriptionInfo"; myArray[2] = Java.use("android.util.Log").getStackTraceString(Java.use("java.lang.Exception").$new()).split('\n\tat'); send(myArray); return this.getActiveSubscriptionInfo.overloads[0].apply(this, arguments); }; // target.getActiveSubscriptionInfo.overloads[1].implementation = function(dest) { // var myArray=new Array() // myArray[0] = "SENSITIVE" //INTERESTED & SENSITIVE // myArray[1] = cn + "." + "getActiveSubscriptionInfo"; // myArray[2] = Java.use("android.util.Log").getStackTraceString(Java.use("java.lang.Exception").$new()).split('\n\tat'); // send(myArray); // return this.getActiveSubscriptionInfo.overloads[1].apply(this, arguments); // }; target.getActiveSubscriptionInfoCount.implementation = function(dest) { var myArray=new Array() myArray[0] = "SENSITIVE" //INTERESTED & SENSITIVE myArray[1] = cn + "." + "getActiveSubscriptionInfoCount"; myArray[2] = Java.use("android.util.Log").getStackTraceString(Java.use("java.lang.Exception").$new()).split('\n\tat'); send(myArray); return this.getActiveSubscriptionInfoCount.apply(this, arguments); }; target.getActiveSubscriptionInfoForSimSlotIndex.implementation = function(dest) { var myArray=new Array() myArray[0] = "SENSITIVE" //INTERESTED & SENSITIVE myArray[1] = cn + "." + "getActiveSubscriptionInfoForSimSlotIndex"; myArray[2] = Java.use("android.util.Log").getStackTraceString(Java.use("java.lang.Exception").$new()).split('\n\tat'); send(myArray); return this.getActiveSubscriptionInfoForSimSlotIndex.apply(this, arguments); }; target.getActiveSubscriptionInfoList.implementation = function(dest) { var myArray=new Array() myArray[0] = "SENSITIVE" //INTERESTED & SENSITIVE myArray[1] = cn + "." + "getActiveSubscriptionInfoList"; myArray[2] = Java.use("android.util.Log").getStackTraceString(Java.use("java.lang.Exception").$new()).split('\n\tat'); send(myArray); return this.getActiveSubscriptionInfoList.apply(this, arguments); }; } });
Java
#!/bin/bash FN="HsAgilentDesign026652.db_3.2.3.tar.gz" URLS=( "https://bioconductor.org/packages/3.11/data/annotation/src/contrib/HsAgilentDesign026652.db_3.2.3.tar.gz" "https://bioarchive.galaxyproject.org/HsAgilentDesign026652.db_3.2.3.tar.gz" "https://depot.galaxyproject.org/software/bioconductor-hsagilentdesign026652.db/bioconductor-hsagilentdesign026652.db_3.2.3_src_all.tar.gz" "https://depot.galaxyproject.org/software/bioconductor-hsagilentdesign026652.db/bioconductor-hsagilentdesign026652.db_3.2.3_src_all.tar.gz" ) MD5="dcd2c748bf9d7c002611cd5cf2ff38c0" # Use a staging area in the conda dir rather than temp dirs, both to avoid # permission issues as well as to have things downloaded in a predictable # manner. STAGING=$PREFIX/share/$PKG_NAME-$PKG_VERSION-$PKG_BUILDNUM mkdir -p $STAGING TARBALL=$STAGING/$FN SUCCESS=0 for URL in ${URLS[@]}; do curl $URL > $TARBALL [[ $? == 0 ]] || continue # Platform-specific md5sum checks. if [[ $(uname -s) == "Linux" ]]; then if md5sum -c <<<"$MD5 $TARBALL"; then SUCCESS=1 break fi else if [[ $(uname -s) == "Darwin" ]]; then if [[ $(md5 $TARBALL | cut -f4 -d " ") == "$MD5" ]]; then SUCCESS=1 break fi fi fi done if [[ $SUCCESS != 1 ]]; then echo "ERROR: post-link.sh was unable to download any of the following URLs with the md5sum $MD5:" printf '%s\n' "${URLS[@]}" exit 1 fi # Install and clean up R CMD INSTALL --library=$PREFIX/lib/R/library $TARBALL rm $TARBALL rmdir $STAGING
Java
#import <UIKit/UIKit.h> #import "OLCVideoPlayer.h" FOUNDATION_EXPORT double OLCVideoPlayerVersionNumber; FOUNDATION_EXPORT const unsigned char OLCVideoPlayerVersionString[];
Java
"use strict"; const chalk = require("chalk"); const readline = require("readline"); /** * Fill screen with blank lines, move to "0" afterwards and clear screen afterwards. * Note that it is still possible to "scroll back" afterwards. * * Function performs nothing in case the stdout is NOT a TTY. */ exports.cls = function() { if (process.stdout.isTTY) { const blank = "\n".repeat(process.stdout.rows); console.log(blank); readline.cursorTo(process.stdout, 0, 0); readline.clearScreenDown(process.stdout); } }; /** * A less soft version of `cls` above which completely clears out the screen, * without leaving the option to scroll up again. * * Function performs nothing in case the stdout is NOT a TTY. */ exports.hardCls = function() { if (process.stdout.isTTY) { process.stdout.write( process.platform === "win32" ? "\x1Bc" : "\x1B[2J\x1B[3J\x1B[H" ); } }; exports.formatFirstLineMessage = function(text) { return chalk.bgWhite.black(text); };
Java
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"/><!-- using block title in layout.dt--><!-- using block ddox.defs in ddox.layout.dt--><!-- using block ddox.title in ddox.layout.dt--> <title>Method AssetAnimation.convertVectorArray</title> <link rel="stylesheet" type="text/css" href="../../styles/ddox.css"/> <link rel="stylesheet" href="../../prettify/prettify.css" type="text/css"/> <script type="text/javascript" src="../../scripts/jquery.js">/**/</script> <script type="text/javascript" src="../../prettify/prettify.js">/**/</script> <script type="text/javascript" src="../../scripts/ddox.js">/**/</script> </head> <body onload="prettyPrint(); setupDdox();"> <nav id="main-nav"><!-- using block navigation in layout.dt--> <ul class="tree-view"> <li class=" tree-view"> <a href="#" class="package">components</a> <ul class="tree-view"> <li> <a href="../../components/animation.html" class="selected module">animation</a> </li> <li> <a href="../../components/assets.html" class=" module">assets</a> </li> <li> <a href="../../components/behavior.html" class=" module">behavior</a> </li> <li> <a href="../../components/camera.html" class=" module">camera</a> </li> <li> <a href="../../components/icomponent.html" class=" module">icomponent</a> </li> <li> <a href="../../components/lights.html" class=" module">lights</a> </li> <li> <a href="../../components/material.html" class=" module">material</a> </li> <li> <a href="../../components/mesh.html" class=" module">mesh</a> </li> <li> <a href="../../components/userinterface.html" class=" module">userinterface</a> </li> </ul> </li> <li class="collapsed tree-view"> <a href="#" class="package">core</a> <ul class="tree-view"> <li> <a href="../../core/dgame.html" class=" module">dgame</a> </li> <li> <a href="../../core/gameobject.html" class=" module">gameobject</a> </li> <li> <a href="../../core/prefabs.html" class=" module">prefabs</a> </li> <li> <a href="../../core/properties.html" class=" module">properties</a> </li> <li> <a href="../../core/reflection.html" class=" module">reflection</a> </li> <li> <a href="../../core/scene.html" class=" module">scene</a> </li> </ul> </li> <li class="collapsed tree-view"> <a href="#" class="package">graphics</a> <ul class="tree-view"> <li class="collapsed tree-view"> <a href="#" class="package">adapters</a> <ul class="tree-view"> <li> <a href="../../graphics/adapters/adapter.html" class=" module">adapter</a> </li> <li> <a href="../../graphics/adapters/linux.html" class=" module">linux</a> </li> <li> <a href="../../graphics/adapters/mac.html" class=" module">mac</a> </li> <li> <a href="../../graphics/adapters/win32.html" class=" module">win32</a> </li> </ul> </li> <li class="collapsed tree-view"> <a href="#" class="package">shaders</a> <ul class="tree-view"> <li class="collapsed tree-view"> <a href="#" class="package">glsl</a> <ul class="tree-view"> <li> <a href="../../graphics/shaders/glsl/ambientlight.html" class=" module">ambientlight</a> </li> <li> <a href="../../graphics/shaders/glsl/animatedgeometry.html" class=" module">animatedgeometry</a> </li> <li> <a href="../../graphics/shaders/glsl/directionallight.html" class=" module">directionallight</a> </li> <li> <a href="../../graphics/shaders/glsl/geometry.html" class=" module">geometry</a> </li> <li> <a href="../../graphics/shaders/glsl/pointlight.html" class=" module">pointlight</a> </li> <li> <a href="../../graphics/shaders/glsl/userinterface.html" class=" module">userinterface</a> </li> </ul> </li> <li> <a href="../../graphics/shaders/glsl.html" class=" module">glsl</a> </li> <li> <a href="../../graphics/shaders/shaders.html" class=" module">shaders</a> </li> </ul> </li> <li> <a href="../../graphics/adapters.html" class=" module">adapters</a> </li> <li> <a href="../../graphics/graphics.html" class=" module">graphics</a> </li> <li> <a href="../../graphics/shaders.html" class=" module">shaders</a> </li> </ul> </li> <li class="collapsed tree-view"> <a href="#" class="package">utility</a> <ul class="tree-view"> <li> <a href="../../utility/array.html" class=" module">array</a> </li> <li> <a href="../../utility/awesomium.html" class=" module">awesomium</a> </li> <li> <a href="../../utility/concurrency.html" class=" module">concurrency</a> </li> <li> <a href="../../utility/config.html" class=" module">config</a> </li> <li> <a href="../../utility/filepath.html" class=" module">filepath</a> </li> <li> <a href="../../utility/input.html" class=" module">input</a> </li> <li> <a href="../../utility/output.html" class=" module">output</a> </li> <li> <a href="../../utility/string.html" class=" module">string</a> </li> <li> <a href="../../utility/tasks.html" class=" module">tasks</a> </li> <li> <a href="../../utility/time.html" class=" module">time</a> </li> </ul> </li> <li> <a href="../../components.html" class=" module">components</a> </li> <li> <a href="../../core.html" class=" module">core</a> </li> <li> <a href="../../graphics.html" class=" module">graphics</a> </li> <li> <a href="../../utility.html" class=" module">utility</a> </li> </ul> <noscript> <p style="color: red">The search functionality needs JavaScript enabled</p> </noscript> <div id="symbolSearchPane" style="display: none"> <p> <input id="symbolSearch" type="text" placeholder="Search for symbols" onchange="performSymbolSearch(24);" onkeypress="this.onchange();" onpaste="this.onchange();" oninput="this.onchange();"/> </p> <ul id="symbolSearchResults" style="display: none"></ul> <script type="application/javascript" src="../../symbols.js"></script> <script type="application/javascript"> //<![CDATA[ var symbolSearchRootDir = "../../"; $('#symbolSearchPane').show(); //]]> </script> </div> </nav> <div id="main-contents"> <h1>Method AssetAnimation.convertVectorArray</h1><!-- using block body in layout.dt--><!-- Default block ddox.description in ddox.layout.dt--><!-- Default block ddox.sections in ddox.layout.dt--><!-- using block ddox.members in ddox.layout.dt--> <p> Converts a aiVectorKey[] to vec3[]. </p> <section></section> <section> <h2>Prototype</h2> <pre class="code prettyprint lang-d prototype"> shared(gl3n.linalg.Vector!(float,3)[]) convertVectorArray( &nbsp;&nbsp;const(derelict.assimp3.types.aiVectorKey*) vectors, &nbsp;&nbsp;int numKeys ) shared;</pre> </section> <section><h2>Parameters</h2> <table><col class="caption"><tr><th>Name</th><th>Description</th></tr> <tr><td id="quaternions">quaternions</td><td> aiVectorKey[] to be converted</td></tr> <tr><td id="numKeys">numKeys</td><td> Number of keys in vector array</td></tr> </table> </section> <section><h2>Returns</h2> <p>The <a href="../../components/animation/AssetAnimation.convertVectorArray.html#vectors"><code class="prettyprint lang-d">vectors</code></a> in vector[] format </p> </section> <section> <h2>Authors</h2><!-- using block ddox.authors in ddox.layout.dt--> </section> <section> <h2>Copyright</h2><!-- using block ddox.copyright in ddox.layout.dt--> </section> <section> <h2>License</h2><!-- using block ddox.license in ddox.layout.dt--> </section> </div> </body> </html>
Java
module Locomotive class SitePolicy < ApplicationPolicy class Scope < Scope def resolve if membership.account.super_admin? scope.all else membership.account.sites end end end def index? true end def show? true end def create? true end def update? super_admin? || site_staff? end def destroy? super_admin? || site_admin? end def point? super_admin? || site_admin? end def update_advanced? super_admin? || site_admin? end def show_developers_documentation? super_admin? || site_admin? end def permitted_attributes plain = [:name, :handle, :picture, :remove_picture, :seo_title, :meta_keywords, :meta_description, :timezone_name, :robots_txt] hash = { domains: [], locales: [] } unless update_advanced? plain -= [:timezone_name, :robots_txt] hash.delete(:locales) end unless point? plain -= [:handle] hash.delete(:domains) end plain << hash end end end
Java
# -*- coding: utf-8 -*- from __future__ import unicode_literals import time import string import json import config import helper import busses def log_message(msg): #log format: time type message time_str = str(time.time()) line = time_str[:time_str.find(".")] line = line.rjust(10, str(" ")) line += " " busses.status_bus["latest_messages"][msg.chat_id] = msg msg_type = helper.get_message_type(msg) if msg_type == "text" and msg.text.startswith("/"): msg_type = "command" appendix = "ERROR" if msg_type == "text": appendix = msg.text elif msg_type == "command": appendix = msg.text[1:] elif msg_type == "location": location_data = msg.location.to_dict() appendix = str(location_data["latitude"]) + "°, " + str(location_data["longitude"]) + "°" elif msg_type == "contact": appendix = str(msg.contact.user_id) + " " + msg.contact.first_name + " " + msg.contact.last_name elif msg_type == "new_user": appendix = str(msg.new_chat_member.id) + " " + str(msg.new_chat_member.first_name) + " " + str(msg.new_chat_member.last_name) elif msg_type in ["audio", "document", "game", "photo", "sticker", "video", "voice", "video_note", "unknown"]: appendix = "" msg_type = msg_type.rjust(10, str(" ")) appendix = appendix.replace("\n", "\\n").rjust(40, str(" ")) line += msg_type + " " + appendix + " " line += str(msg.chat_id) + "," + str(msg.message_id) line += "\n" with open(config.msg_log_file_path, "a") as log_file: log_file.write(line.encode("utf-8")) def complete_log(update): with open(config.complete_log_file_path, "a") as log_file: data = update.to_dict() data.update({"time": time.time()}) json_data = json.dumps(data) log_file.write(str(json_data).replace("\n", "\\n") + "\n".encode("utf-8"))
Java
<div layout="vertical"> <md-sidenav class="md-sidenav-left md-whiteframe-z2" md-component-id="left" md-is-locked-open="$mdMedia('gt-sm')"> <md-toolbar> <h1>Characters</h1> </md-toolbar> <char-list></char-list> </md-sidenav> </div>
Java
public class LeetCode0363 { public int maxSumSubmatrix(int[][] matrix, int k) { int m = matrix.length, n = matrix[0].length, ans = Integer.MIN_VALUE; long[] sum = new long[m + 1]; for (int i = 0; i < n; ++i) { long[] sumInRow = new long[m]; for (int j = i; j < n; ++j) { for (int p = 0; p < m; ++p) { sumInRow[p] += matrix[p][j]; sum[p + 1] = sum[p] + sumInRow[p]; } ans = Math.max(ans, mergeSort(sum, 0, m + 1, k)); if (ans == k) return k; } } return ans; } int mergeSort(long[] sum, int start, int end, int k) { if (end == start + 1) return Integer.MIN_VALUE; int mid = start + (end - start) / 2, cnt = 0; int ans = mergeSort(sum, start, mid, k); if (ans == k) return k; ans = Math.max(ans, mergeSort(sum, mid, end, k)); if (ans == k) return k; long[] cache = new long[end - start]; for (int i = start, j = mid, p = mid; i < mid; ++i) { while (j < end && sum[j] - sum[i] <= k){ ++j; } if (j - 1 >= mid) { ans = Math.max(ans, (int) (sum[j - 1] - sum[i])); if (ans == k){ return k; } } while (p < end && sum[p] < sum[i]){ cache[cnt++] = sum[p++]; } cache[cnt++] = sum[i]; } System.arraycopy(cache, 0, sum, start, cnt); return ans; } }
Java
<?php /* * This file is part of the PHPExifTool package. * * (c) Alchemy <support@alchemy.fr> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPExiftool\Driver\Tag\DICOM; use JMS\Serializer\Annotation\ExclusionPolicy; use PHPExiftool\Driver\AbstractTag; /** * @ExclusionPolicy("all") */ class FilmBoxContentSequence extends AbstractTag { protected $Id = '2130,0030'; protected $Name = 'FilmBoxContentSequence'; protected $FullName = 'DICOM::Main'; protected $GroupName = 'DICOM'; protected $g0 = 'DICOM'; protected $g1 = 'DICOM'; protected $g2 = 'Image'; protected $Type = '?'; protected $Writable = false; protected $Description = 'Film Box Content Sequence'; }
Java
<?php namespace Cascade\Mapper\Map; use Cascade\Mapper\Mapping\MappingInterface; class Map implements MapInterface { /** * @var MappingInterface[] */ private $mappings = []; /** * @param MappingInterface[] $mappings */ public function __construct($mappings) { foreach ($mappings as $mapping) { $this->addMapping($mapping); } } public function getMappings() { return $this->mappings; } /** * @param MappingInterface $mapping */ private function addMapping(MappingInterface $mapping) { $this->mappings[] = $mapping; } }
Java
# Cisco Spark React Audio Component _(@ciscospark/react-component-audio)_ ## WARNING We renamed this module to [@webex/react-component-audio](https://www.npmjs.com/package/@webex/react-component-audio). Please install it instead. ## License © 2016-2020 Cisco and/or its affiliates. All Rights Reserved.
Java
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import time import numpy as np import matplotlib matplotlib.use('GTKAgg') from matplotlib import pyplot as plt from koheron import connect from drivers import Spectrum from drivers import Laser host = os.getenv('HOST','192.168.1.100') client = connect(host, name='spectrum') driver = Spectrum(client) laser = Laser(client) laser.start() current = 30 # mA laser.set_current(current) # driver.reset_acquisition() wfm_size = 4096 decimation_factor = 1 index_low = 0 index_high = wfm_size / 2 signal = driver.get_decimated_data(decimation_factor, index_low, index_high) print('Signal') print(signal) mhz = 1e6 sampling_rate = 125e6 freq_min = 0 freq_max = sampling_rate / mhz / 2 # Plot parameters fig = plt.figure() ax = fig.add_subplot(111) x = np.linspace(freq_min, freq_max, (wfm_size / 2)) print('X') print(len(x)) y = 10*np.log10(signal) print('Y') print(len(y)) li, = ax.plot(x, y) fig.canvas.draw() ax.set_xlim((x[0],x[-1])) ax.set_ylim((0,200)) ax.set_xlabel('Frequency (MHz)') ax.set_ylabel('Power spectral density (dB)') while True: try: signal = driver.get_decimated_data(decimation_factor, index_low, index_high) li.set_ydata(10*np.log10(signal)) fig.canvas.draw() plt.pause(0.001) except KeyboardInterrupt: # Save last spectrum in a csv file np.savetxt("psd.csv", signal, delimiter=",") laser.stop() driver.close() break
Java
const assert = require('assert') const crypto = require('crypto') const { createRequest } = require("../util/util") describe('测试搜索是否正常', () => { it('获取到的数据的 name 应该和搜索关键词一致', done => { const keywords = "海阔天空" const type = 1 const limit = 30 const data = 's=' + keywords + '&limit=' + limit + '&type=' + type + '&offset=0' createRequest('/api/search/pc/', 'POST', data) .then(result => { console.log(JSON.parse(result).result.songs[0].mp3Url) assert(JSON.parse(result).result.songs[0].name === '海阔天空') done() }) .catch(err => { done(err) }) }) })
Java
<footer class="site-footer"> <div class="container"> <small class="pull-right">Made with <a href="http://jekyllrb.com/" target="_blank">Jekyll</a></small> </div> </footer>
Java
<!DOCTYPE html> <html> {% include head.html %} <body> {%include banner.html%} {%include middle.html%} <!-- <script src="{{ site.baseurl }}/js/index.js"></script> --> </body> <footer></footer> </html>
Java
export default function collapseDuplicateDeclarations() { return (root) => { root.walkRules((node) => { let seen = new Map() let droppable = new Set([]) node.walkDecls((decl) => { // This could happen if we have nested selectors. In that case the // parent will loop over all its declarations but also the declarations // of nested rules. With this we ensure that we are shallowly checking // declarations. if (decl.parent !== node) { return } if (seen.has(decl.prop)) { droppable.add(seen.get(decl.prop)) } seen.set(decl.prop, decl) }) for (let decl of droppable) { decl.remove() } }) } }
Java
module.exports = { "env": { "browser": true, "commonjs": true, "es6": true, "jasmine" : true }, "extends": "eslint:recommended", "parserOptions": { "sourceType": "module" }, "rules": { "no-mixed-spaces-and-tabs": [2, "smart-tabs"], "linebreak-style": [ "error", "unix" ], "quotes": [ "error", "single" ], "semi": [ "error", "always" ] } };
Java
import * as debug from 'debug'; import Resolver from '../../resolver'; import { IRemoteUser } from '../../../../models/user'; import acceptFollow from './follow'; import { IAccept, IFollow } from '../../type'; const log = debug('misskey:activitypub'); export default async (actor: IRemoteUser, activity: IAccept): Promise<void> => { const uri = activity.id || activity; log(`Accept: ${uri}`); const resolver = new Resolver(); let object; try { object = await resolver.resolve(activity.object); } catch (e) { log(`Resolution failed: ${e}`); throw e; } switch (object.type) { case 'Follow': acceptFollow(actor, object as IFollow); break; default: console.warn(`Unknown accept type: ${object.type}`); break; } };
Java
version https://git-lfs.github.com/spec/v1 oid sha256:42fcecf8fdabe110af986ac81bb56b598f5a3fa59c6d0c4cc8b80daa2dca0473 size 1121
Java
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>Function template make_managed_shared_ptr</title> <link rel="stylesheet" href="../../../../doc/src/boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.78.1"> <link rel="home" href="../../index.html" title="The Boost C++ Libraries BoostBook Documentation Subset"> <link rel="up" href="../../interprocess/acknowledgements_notes.html#header.boost.interprocess.smart_ptr.shared_ptr_hpp" title="Header &lt;boost/interprocess/smart_ptr/shared_ptr.hpp&gt;"> <link rel="prev" href="make_managed_s_idp50535792.html" title="Function template make_managed_shared_ptr"> <link rel="next" href="unique_ptr.html" title="Class template unique_ptr"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../boost.png"></td> <td align="center"><a href="../../../../index.html">Home</a></td> <td align="center"><a href="../../../../libs/libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="make_managed_s_idp50535792.html"><img src="../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../interprocess/acknowledgements_notes.html#header.boost.interprocess.smart_ptr.shared_ptr_hpp"><img src="../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="unique_ptr.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="refentry"> <a name="boost.interprocess.make_managed_s_idp50540304"></a><div class="titlepage"></div> <div class="refnamediv"> <h2><span class="refentrytitle">Function template make_managed_shared_ptr</span></h2> <p>boost::interprocess::make_managed_shared_ptr</p> </div> <h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2> <div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: &lt;<a class="link" href="../../interprocess/acknowledgements_notes.html#header.boost.interprocess.smart_ptr.shared_ptr_hpp" title="Header &lt;boost/interprocess/smart_ptr/shared_ptr.hpp&gt;">boost/interprocess/smart_ptr/shared_ptr.hpp</a>&gt; </span> <span class="keyword">template</span><span class="special">&lt;</span><span class="keyword">typename</span> T<span class="special">,</span> <span class="keyword">typename</span> ManagedMemory<span class="special">&gt;</span> <a class="link" href="managed_shared_ptr.html" title="Struct template managed_shared_ptr">managed_shared_ptr</a><span class="special">&lt;</span> <span class="identifier">T</span><span class="special">,</span> <span class="identifier">ManagedMemory</span> <span class="special">&gt;</span><span class="special">::</span><span class="identifier">type</span> <span class="identifier">make_managed_shared_ptr</span><span class="special">(</span><span class="identifier">T</span> <span class="special">*</span> constructed_object<span class="special">,</span> <span class="identifier">ManagedMemory</span> <span class="special">&amp;</span> managed_memory<span class="special">,</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">nothrow_t</span><span class="special">)</span><span class="special">;</span></pre></div> <div class="refsect1"> <a name="idp253351568"></a><h2>Description</h2> <p>Returns an instance of a shared pointer constructed with the default allocator and deleter from a pointer of type T that has been allocated in the passed managed segment. Does not throw, return null shared pointer in error. </p> </div> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 2005-2012 Ion Gaztanaga<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>) </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="make_managed_s_idp50535792.html"><img src="../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../interprocess/acknowledgements_notes.html#header.boost.interprocess.smart_ptr.shared_ptr_hpp"><img src="../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="unique_ptr.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
Java
/** \brief A timer module with only a single compare value. Can be used to replace the "bsp_timer" and "radiotimer" modules with the help of abstimer. \author Xavi Vilajosana <xvilajosana@eecs.berkeley.edu>, May 2012. \author Thomas Watteyne <watteyne@eecs.berkeley.edu>, May 2012. */ #include "sctimer.h" #include "msp430x26x.h" //=========================== defines ========================================= //=========================== variables ======================================= typedef struct { uint8_t running; uint16_t taiv; } sctimers_vars_t; sctimers_vars_t sctimers_vars; //=========================== prototypes ====================================== void sctimer_setup(); void sctimer_start(); //=========================== public ========================================== void sctimer_init() { sctimer_setup(); } void sctimer_stop() { sctimer_setup(); } void sctimer_schedule(uint16_t val) { if (sctimers_vars.running==0) { sctimers_vars.running=1; sctimer_start(); } // load when to fire TACCR1 = val; // enable interrupt TACCTL1 = CCIE; } uint16_t sctimer_getValue() { return TAR; } void sctimer_setCb(sctimer_cbt cb){ // does nothing as it is done by IAR -- look at board.c } void sctimer_clearISR() { sctimers_vars.taiv = TAIV;//read taiv to clear the flags. } //=========================== private ========================================= void sctimer_setup() { // clear local variables memset(&sctimers_vars,0,sizeof(sctimers_vars_t)); // ACLK sources from external 32kHz BCSCTL3 |= LFXT1S_0; // disable all compares TACCTL0 = 0; TACCR0 = 0; // CCR1 in compare mode (disabled for now) TACCTL1 = 0; TACCR1 = 0; // CCR2 in capture mode TACCTL2 = 0; TACCR2 = 0; // reset couter TAR = 0; } void sctimer_start() { // start counting TACTL = MC_2+TASSEL_1; // continuous mode, clocked from ACLK }
Java
$(document).ready(function(){ var Previewer = { preview: function(content, output) { $.ajax({ type: 'POST', url: "/govspeak", data: { govspeak: content.val() }, dataType: 'json' }).success(function(data){ output.html(data['govspeak']); }); } }; $("[data-preview]").each(function(){ var source_field = $($(this).data('preview-for')); var render_area = $(this); source_field.keyup(function() { Previewer.preview(source_field, render_area); }) }); $('textarea').autosize(); });
Java
__version__ = '0.8.1' __author__ = "Massimiliano Pippi & Federico Frenguelli" VERSION = __version__ # synonym
Java
/** * @author Richard Davey <rich@photonstorm.com> * @copyright 2020 Photon Storm Ltd. * @license {@link https://opensource.org/licenses/MIT|MIT License} */ /** * @namespace Phaser.Structs */ module.exports = { List: require('./List'), Map: require('./Map'), ProcessQueue: require('./ProcessQueue'), RTree: require('./RTree'), Set: require('./Set'), Size: require('./Size') };
Java
#! /usr/bin/env python """Show file statistics by extension.""" import os import sys class Stats: def __init__(self): self.stats = {} def statargs(self, args): for arg in args: if os.path.isdir(arg): self.statdir(arg) elif os.path.isfile(arg): self.statfile(arg) else: sys.stderr.write("Can't find %s\n" % file) self.addstats("<???>", "unknown", 1) def statdir(self, dir): self.addstats("<dir>", "dirs", 1) try: names = os.listdir(dir) except os.error, err: sys.stderr.write("Can't list %s: %s\n" % (file, err)) self.addstats(ext, "unlistable", 1) return names.sort() for name in names: if name.startswith(".#"): continue # Skip CVS temp files if name.endswith("~"): continue# Skip Emacs backup files full = os.path.join(dir, name) if os.path.islink(full): self.addstats("<lnk>", "links", 1) elif os.path.isdir(full): self.statdir(full) else: self.statfile(full) def statfile(self, file): head, ext = os.path.splitext(file) head, base = os.path.split(file) if ext == base: ext = "" # E.g. .cvsignore is deemed not to have an extension ext = os.path.normcase(ext) if not ext: ext = "<none>" self.addstats(ext, "files", 1) try: f = open(file, "rb") except IOError, err: sys.stderr.write("Can't open %s: %s\n" % (file, err)) self.addstats(ext, "unopenable", 1) return data = f.read() f.close() self.addstats(ext, "bytes", len(data)) if '\0' in data: self.addstats(ext, "binary", 1) return if not data: self.addstats(ext, "empty", 1) #self.addstats(ext, "chars", len(data)) lines = data.splitlines() self.addstats(ext, "lines", len(lines)) del lines words = data.split() self.addstats(ext, "words", len(words)) def addstats(self, ext, key, n): d = self.stats.setdefault(ext, {}) d[key] = d.get(key, 0) + n def report(self): exts = self.stats.keys() exts.sort() # Get the column keys columns = {} for ext in exts: columns.update(self.stats[ext]) cols = columns.keys() cols.sort() colwidth = {} colwidth["ext"] = max([len(ext) for ext in exts]) minwidth = 6 self.stats["TOTAL"] = {} for col in cols: total = 0 cw = max(minwidth, len(col)) for ext in exts: value = self.stats[ext].get(col) if value is None: w = 0 else: w = len("%d" % value) total += value cw = max(cw, w) cw = max(cw, len(str(total))) colwidth[col] = cw self.stats["TOTAL"][col] = total exts.append("TOTAL") for ext in exts: self.stats[ext]["ext"] = ext cols.insert(0, "ext") def printheader(): for col in cols: print "%*s" % (colwidth[col], col), print printheader() for ext in exts: for col in cols: value = self.stats[ext].get(col, "") print "%*s" % (colwidth[col], value), print printheader() # Another header at the bottom def main(): args = sys.argv[1:] if not args: args = [os.curdir] s = Stats() s.statargs(args) s.report() if __name__ == "__main__": main()
Java
package com.ocdsoft.bacta.swg.shared.localization; /** * Created by crush on 11/21/2015. */ public class LocalizedString { }
Java
# Contributing ## Mailing list The main communication tool in use is the Yocto Project mailing list: * <yocto@yoctoproject.org> * <https://lists.yoctoproject.org/listinfo/yocto> Feel free to ask any kind of questions but please always prepend your email subject with `[meta-raspberrypi]` as this is the global *Yocto* mailing list and not a dedicated *meta-raspberrypi* mailing list. ## Formatting patches First and foremost, all of the contributions to the layer must be compliant with the standard openembedded patch guidelines: * <http://www.openembedded.org/wiki/Commit_Patch_Message_Guidelines> In summary, your commit log messages should be formatted as follows: <layer-component>: <short log/statement of what needed to be changed> (Optional pointers to external resources, such as defect tracking) The intent of your change. (Optional: if it's not clear from above, how your change resolves the issues in the first part) Signed-off-by: Your Name <yourname@youremail.com> The `<layer-component>` is the layer component name that your changes affect. It is important that you choose it correctly. A simple guide for selecting a a good component name is the following: * For changes that affect *layer recipes*, please just use the **base names** of the affected recipes, separated by commas (`,`), as the component name. For example: use `omxplayer` instead of `omxplayer_git.bb`. If you are adding new recipe(s), just use the new recipe(s) base name(s). An example for changes to multiple recipes would be `userland,vc-graphics,wayland`. * For changes that affect the *layer documentation*, please just use `docs` as the component name. * For changes that affect *other files*, i.e. under the `conf` directory, please use the full path as the component name, e.g. `conf/layer.conf`. * For changes that affect the *layer itself* and do not fall into any of the above cases, please use `meta-raspberrypi` as the component name. A full example of a suitable commit log message is below: foobar: Adjusted the foo setting in bar When using foobar on systems with less than a gigabyte of RAM common usage patterns often result in an Out-of-memory condition causing slowdowns and unexpected application termination. Low-memory systems should continue to function without running into memory-starvation conditions with minimal cost to systems with more available memory. High-memory systems will be less able to use the full extent of the system, a dynamically tunable option may be best, long-term. The foo setting in bar was decreased from X to X-50% in order to ensure we don't exhaust all system memory with foobar threads. Signed-off-by: Joe Developer <joe.developer@example.com> A common issue during patch reviewing is commit log formatting, please review the above formatting guidelines carefully before sending your patches. ## Sending patches The preferred method to contribute to this project is to send pull requests to the GitHub mirror of the layer: * <https://github.com/agherzan/meta-raspberrypi> **In addition**, you may send patches for review to the above specified mailing list. In this case, when creating patches using `git` please make sure to use the following formatting for the message subject: git format-patch -s --subject-prefix='meta-raspberrypi][PATCH' origin Then, for sending patches to the mailing list, you may use this command: git send-email --to yocto@yoctoproject.org <generated patch> ## GitHub issues In order to manage and track the layer issues more efficiently, the GitHub issues facility is used by this project: * <https://github.com/agherzan/meta-raspberrypi/issues> If you submit patches that have a GitHub issue associated, please make sure to use standard GitHub keywords, e.g. `closes`, `resolves` or `fixes`, before the "Signed-off-by" tag to close the relevant issues automatically: foobar: Adjusted the foo setting in bar Fixes: #324 Signed-off-by: Joe Developer <joe.developer@example.com> More information on the available GitHub close keywords can be found here: * <https://help.github.com/articles/closing-issues-using-keywords>
Java
<!doctype html> <html> <head> <title>Network | Hierarchical layout</title> <style type="text/css"> body { font: 10pt sans; } #mynetwork { width: 600px; height: 600px; border: 1px solid lightgray; } </style> <script type="text/javascript" src="../../../dist/vis.js"></script> <link href="../../../dist/vis-network.min.css" rel="stylesheet" type="text/css"/> <script type="text/javascript"> var network = null; function p(data) { var container = document.getElementById('mynetwork'); var options = { layout: { hierarchical: {}, }, }; console.log("starting layout"); network = new vis.Network(container, data, options); console.log("layout complete"); } </script> </head> <body> <h2>Hierarchical Layout</h2> <div id="mynetwork"></div> <script type="text/javascript" src="./demo.jsonp"></script> </body> </html>
Java
<?php namespace WiderFunnel\OptimizelyX\Items; /** * Class Experiment * @package WiderFunnel\Items; */ class Experiment extends ItemAbstract { // }
Java
var jsbin = { 'root': '{{root}}', 'shareRoot': '{{shareRoot}}', 'runner': '{{runner}}', 'static': '{{static}}', 'version': '{{version}}', user: {{{user}}}, }; (function () { if (jsbin.user && jsbin.user.name) { $('.loggedout').hide(); var menu = $('.loggedin').show(); var html = $('#profile-template').text(); var $html = $(html.replace(/({.*?})/g, function (all, match) { var key = match.slice(1, -1).trim(); // ditch the wrappers return jsbin.user[key] || ''; })); if (jsbin.user.pro) { document.documentElement.className += ' pro'; $html.find('.gopro').remove(); } else { $html.find('.pro').remove(); } menu.append($html); } else { $('.loggedout').show(); } })();
Java
Hi, this is Mirong Kim.
Java
/*------------------------------------*\ # components.profile \*------------------------------------*/ .profile__login { position: relative; display: inline-block; z-index: 50; padding-bottom: .5rem; } .profile__login__icon { width: 2.5rem; margin-bottom: -0.7rem; } .profile__login__popup { opacity: 0; position: absolute; right: 3rem; padding: 1rem; margin-top: 1rem; border-radius: .5rem; white-space: nowrap; background: var(--color-secondary); transition: all .2s ease-in-out; } .profile__login__popup::before { content: ""; position: absolute; top: -0.5rem; right: 0.8rem; border-left: 0.625rem solid transparent; border-right: 0.625rem solid transparent; border-bottom: 0.625rem solid var(--color-secondary); transition-duration: 0.2s; transition-property: transform; } .profile__login__link { font-family: var(--ff-sans); text-decoration: none; color: white; transition: color .2s ease-in-out; } .profile__login__link:hover { color: var(--ultra-dark); } .profile__login:hover .profile__login__popup { opacity: 1; transform: translate(3rem); transition: all 0.5s cubic-bezier(0.75, -0.02, 0.2, 0.97); }
Java
using System.Text; namespace GuruComponents.Netrix.Events { /// <summary> /// SaveEventArgs provides information about the current save process. /// </summary> public class SaveEventArgs : LoadEventArgs { /// <summary> /// Constructor. It's build by Save event handler and not intendet to being called from user's code. /// </summary> /// <param name="encoding"></param> /// <param name="url"></param> public SaveEventArgs(Encoding encoding, string url) : base(encoding, url) { } /// <summary> /// Set another encoding temporarily, if used within the <see cref="IHtmlEditor.Saving">Saving</see> event. /// </summary> /// <param name="encoding"></param> public void SetEncoding(Encoding encoding) { _encoding = encoding; } } }
Java
YUI.add("yuidoc-meta", function(Y) { Y.YUIDoc = { meta: { "classes": [ "Audio" ], "modules": [ "gallery-audio" ], "allModules": [ { "displayName": "gallery-audio", "name": "gallery-audio" } ] } }; });
Java
// angular import { HttpClient } from '@angular/common/http'; import { Routes } from '@angular/router'; // libs import * as _ from 'lodash'; import { I18NRouterLoader, I18NRouterSettings } from '@ngx-i18n-router/core'; export class I18NRouterHttpLoader implements I18NRouterLoader { private _translations: any; get routes(): Routes { return _.map(this.providedSettings.routes, _.cloneDeep); } get translations(): any { return this._translations; } constructor(private readonly http: HttpClient, private readonly path: string = '/routes.json', private readonly providedSettings: I18NRouterSettings = {}) { } loadTranslations(): any { return new Promise((resolve, reject) => { this.http.get(this.path) .subscribe(res => { this._translations = res; return resolve(res); }, () => reject('Endpoint unreachable!')); }); } }
Java
'use strict'; var fs = require('fs'), util = require('util'), Duplexify = require('duplexify'), _ = require('lodash'), su = require('bindings')('serialutil.node'), fsu = require('./fsutil'), pins = require('./pins'), Dto = require('./dto'), dto = new Dto(__dirname + '/../templates/uart.dts'); var DEFAULT_OPTIONS; function onopen(uart, options) { if (uart._rxfd !== -1 && uart._txfd !== -1) { su.setRawMode(uart._rxfd); uart.baudRate(options.baudRate); uart.characterSize(options.characterSize); uart.parity(options.parity); uart.stopBits(options.stopBits); setImmediate(function () { uart.emit('open'); uart.emit('ready'); }); } } function onclose(uart) { if (uart._rxfd === -1 && uart._txfd === -1) { setImmediate(function () { uart.emit('close'); }); } } function createStreams(uart, options) { uart._rxfd = -1; uart._txfd = -1; uart._rxstream = fs.createReadStream(uart.devPath, { highWaterMark: options.highWaterMark, encoding: options.encoding }); uart._txstream = fs.createWriteStream(uart.devPath, { highWaterMark: options.highWaterMark, encoding: options.encoding, flags: 'r+' }); uart._rxstream.once('open', function (rxfd) { uart._rxfd = rxfd; onopen(uart, options); }); uart._txstream.once('open', function (txfd) { uart._txfd = txfd; onopen(uart, options); }); uart._rxstream.once('close', function () { uart._rxfd = -1; onclose(uart); }); uart._txstream.once('close', function () { uart._txfd = -1; onclose(uart); }); // TODO - test error handling uart.setReadable(uart._rxstream); uart.setWritable(uart._txstream); } function waitForUart(uart, options) { fsu.waitForFile(uart.devPath, function (err, devPath) { if (err) { return uart.emit('error', err); } createStreams(uart, options); }); } function Uart(uartDef, options) { var badPin, config; if (!(this instanceof Uart)) { return new Uart(uartDef); } options = options ? _.defaults(options, DEFAULT_OPTIONS) : DEFAULT_OPTIONS; // Consider calling Duplexify with the allowHalfOpen option set to false. // It's super-class (Duplex) will then ensure that this.end is called when // the read stream fires the 'end' event. (see: // https://github.com/joyent/node/blob/v0.10.25/lib/_stream_duplex.js) Duplexify.call(this, null, null); if (typeof uartDef === 'string') { this.uartDef = null; this.devPath = uartDef; this.name = null; waitForUart(this, options); } else { if (uartDef.txPin.uart === undefined) { badPin = new Error(uartDef.txPin + ' doesn\'t support uarts'); } else if (uartDef.rxPin.uart === undefined) { badPin = new Error(uartDef.rxPin + ' doesn\'t support uarts'); } if (badPin) { setImmediate(function () { this.emit('error', badPin); }.bind(this)); return; } this.uartDef = uartDef; this.devPath = '/dev/ttyO' + uartDef.id; this.name = 'bot_uart' + uartDef.id; config = { txHeader: this.uartDef.txPin.name.toUpperCase().replace('_', '.'), rxHeader: this.uartDef.rxPin.name.toUpperCase().replace('_', '.'), hardwareIp: 'uart' + this.uartDef.id, name: this.name, rxMuxOffset: '0x' + this.uartDef.rxPin.muxOffset.toString(16), rxMuxValue: '0x' + this.uartDef.rxPin.uart.muxValue.toString(16), txMuxOffset: '0x' + this.uartDef.txPin.muxOffset.toString(16), txMuxValue: '0x' + this.uartDef.txPin.uart.muxValue.toString(16), targetUart: 'uart' + (this.uartDef.id + 1), partNumber: this.name }; dto.install(config, function (err) { if (err) { return this.emit('error', err); } waitForUart(this, options); }.bind(this)); } } module.exports = Uart; util.inherits(Uart, Duplexify); Uart.B0 = su.B0; Uart.B50 = su.B50; Uart.B75 = su.B75; Uart.B110 = su.B110; Uart.B134 = su.B134; Uart.B150 = su.B150; Uart.B200 = su.B200; Uart.B300 = su.B300; Uart.B600 = su.B600; Uart.B1200 = su.B1200; Uart.B1800 = su.B1800; Uart.B2400 = su.B2400; Uart.B4800 = su.B4800; Uart.B9600 = su.B9600; Uart.B19200 = su.B19200; Uart.B38400 = su.B38400; Uart.B57600 = su.B57600; Uart.B115200 = su.B115200; Uart.B230400 = su.B230400; Uart.B460800 = su.B460800; Uart.B500000 = su.B500000; Uart.B576000 = su.B576000; Uart.B921600 = su.B921600; Uart.B1000000 = su.B1000000; Uart.B1152000 = su.B1152000; Uart.B1500000 = su.B1500000; Uart.B2000000 = su.B2000000; Uart.B2500000 = su.B2500000; Uart.B3000000 = su.B3000000; Uart.B3500000 = su.B3500000; Uart.B4000000 = su.B4000000; Uart.PARITY_NONE = su.PARITY_NONE; Uart.PARITY_ODD = su.PARITY_ODD; Uart.PARITY_EVEN = su.PARITY_EVEN; Uart.UART1 = { id: 1, txPin: pins.p9_24, rxPin: pins.p9_26 }; Uart.UART2 = { id: 2, txPin: pins.p9_21, rxPin: pins.p9_22 }; Uart.UART4 = { id: 4, txPin: pins.p9_13, rxPin: pins.p9_11 }; DEFAULT_OPTIONS = { baudRate: Uart.B38400, characterSize: 8, parity: Uart.PARITY_NONE, stopBits: 1, highWaterMark: 512, encoding: null }; Object.freeze(DEFAULT_OPTIONS); Uart.prototype.baudRate = function (rate) { if (rate === undefined) { return su.getBaudRate(this._rxfd); } su.setBaudRate(this._rxfd, rate); }; Uart.prototype.characterSize = function (size) { if (size === undefined) { return su.getCharacterSize(this._rxfd); } su.setCharacterSize(this._rxfd, size); }; Uart.prototype.parity = function (type) { if (type === undefined) { return su.getParity(this._rxfd); } su.setParity(this._rxfd, type); }; Uart.prototype.stopBits = function (count) { if (count === undefined) { return su.getStopBits(this._rxfd); } su.setStopBits(this._rxfd, count); }; Uart.prototype.close = function () { this.removeAllListeners('data'); // Is this a good idea? Should the user be doing this? // TODO: the following is a bit of a hack. // Here \n EOF is faked for this._rxfd inorder to close the read stream. // It's faked three times as the uart may receive a character between // \n and EOF and the stream will not be closed. Faking three times // increases the chances of it working! su.setCanonical(this._rxfd, true); su.fakeInput(this._rxfd, '\n'.charCodeAt(0)); su.fakeInput(this._rxfd, 4); // fake eof su.fakeInput(this._rxfd, '\n'.charCodeAt(0)); su.fakeInput(this._rxfd, 4); // fake eof su.fakeInput(this._rxfd, '\n'.charCodeAt(0)); su.fakeInput(this._rxfd, 4); // fake eof };
Java
package de.andreasgiemza.mangadownloader.gui.chapter; import de.andreasgiemza.mangadownloader.MangaDownloader; import de.andreasgiemza.mangadownloader.helpers.RegexHelper; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.RowFilter; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.table.TableRowSorter; /** * * @author Andreas Giemza <andreas@giemza.net> */ public class ChapterListSearchDocumentListener implements DocumentListener { private final MangaDownloader mangaDownloader; private final JTextField chapterListSearchTextField; private final TableRowSorter<ChapterTableModel> chapterTableRowSorter; @SuppressWarnings("unchecked") public ChapterListSearchDocumentListener(MangaDownloader mangaDownloader, JTextField chapterListSearchTextField, JTable chapterListTable) { this.mangaDownloader = mangaDownloader; this.chapterListSearchTextField = chapterListSearchTextField; chapterTableRowSorter = (TableRowSorter<ChapterTableModel>) chapterListTable .getRowSorter(); } @Override public void insertUpdate(DocumentEvent e) { changed(); } @Override public void removeUpdate(DocumentEvent e) { changed(); } @Override public void changedUpdate(DocumentEvent e) { changed(); } private void changed() { mangaDownloader.chapterSearchChanged(); final String searchText = chapterListSearchTextField.getText(); if (searchText.length() == 0) { chapterTableRowSorter.setRowFilter(null); } else if (searchText.length() > 0) { chapterTableRowSorter.setRowFilter(RowFilter .regexFilter(RegexHelper.build(searchText))); } } }
Java
package nxt.http; import nxt.Account; import nxt.Attachment; import nxt.Constants; import nxt.NxtException; import nxt.util.Convert; import org.json.simple.JSONStreamAware; import javax.servlet.http.HttpServletRequest; import static nxt.http.JSONResponses.INCORRECT_ASSET; import static nxt.http.JSONResponses.INCORRECT_PRICE; import static nxt.http.JSONResponses.INCORRECT_QUANTITY; import static nxt.http.JSONResponses.MISSING_ASSET; import static nxt.http.JSONResponses.MISSING_PRICE; import static nxt.http.JSONResponses.MISSING_QUANTITY; import static nxt.http.JSONResponses.NOT_ENOUGH_ASSETS; import static nxt.http.JSONResponses.UNKNOWN_ACCOUNT; public final class PlaceAskOrder extends CreateTransaction { static final PlaceAskOrder instance = new PlaceAskOrder(); private PlaceAskOrder() { super("asset", "quantity", "price"); } @Override JSONStreamAware processRequest(HttpServletRequest req) throws NxtException.ValidationException { String assetValue = req.getParameter("asset"); String quantityValue = req.getParameter("quantity"); String priceValue = req.getParameter("price"); if (assetValue == null) { return MISSING_ASSET; } else if (quantityValue == null) { return MISSING_QUANTITY; } else if (priceValue == null) { return MISSING_PRICE; } long price; try { price = Long.parseLong(priceValue); if (price <= 0 || price > Constants.MAX_BALANCE * 100L) { return INCORRECT_PRICE; } } catch (NumberFormatException e) { return INCORRECT_PRICE; } Long asset; try { asset = Convert.parseUnsignedLong(assetValue); } catch (RuntimeException e) { return INCORRECT_ASSET; } int quantity; try { quantity = Integer.parseInt(quantityValue); if (quantity <= 0 || quantity > Constants.MAX_ASSET_QUANTITY) { return INCORRECT_QUANTITY; } } catch (NumberFormatException e) { return INCORRECT_QUANTITY; } Account account = getAccount(req); if (account == null) { return UNKNOWN_ACCOUNT; } Integer assetBalance = account.getUnconfirmedAssetBalance(asset); if (assetBalance == null || quantity > assetBalance) { return NOT_ENOUGH_ASSETS; } Attachment attachment = new Attachment.ColoredCoinsAskOrderPlacement(asset, quantity, price); return createTransaction(req, account, attachment); } }
Java