code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/json/json_string_value_serializer.h" #include "base/prefs/pref_service.h" #include "chrome/browser/net/predictor.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/common/pref_names.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "content/public/test/test_utils.h" #include "net/base/net_errors.h" #include "net/dns/host_resolver_proc.h" #include "net/dns/mock_host_resolver.h" #include "testing/gmock/include/gmock/gmock.h" using content::BrowserThread; using testing::HasSubstr; namespace { const char kChromiumHostname[] = "chromium.org"; const char kInvalidLongHostname[] = "illegally-long-hostname-over-255-" "characters-should-not-send-an-ipc-message-to-the-browser-" "0000000000000000000000000000000000000000000000000000000000000000000000000" "0000000000000000000000000000000000000000000000000000000000000000000000000" "000000000000000000000000000000000000000000000000000000.org"; // Records a history of all hostnames for which resolving has been requested, // and immediately fails the resolution requests themselves. class HostResolutionRequestRecorder : public net::HostResolverProc { public: HostResolutionRequestRecorder() : HostResolverProc(NULL), is_waiting_for_hostname_(false) { } int Resolve(const std::string& host, net::AddressFamily address_family, net::HostResolverFlags host_resolver_flags, net::AddressList* addrlist, int* os_error) override { BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&HostResolutionRequestRecorder::AddToHistory, base::Unretained(this), host)); return net::ERR_NAME_NOT_RESOLVED; } int RequestedHostnameCount() const { return requested_hostnames_.size(); } bool HasHostBeenRequested(const std::string& hostname) const { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); return std::find(requested_hostnames_.begin(), requested_hostnames_.end(), hostname) != requested_hostnames_.end(); } void WaitUntilHostHasBeenRequested(const std::string& hostname) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); DCHECK(!is_waiting_for_hostname_); if (HasHostBeenRequested(hostname)) return; waiting_for_hostname_ = hostname; is_waiting_for_hostname_ = true; content::RunMessageLoop(); } private: ~HostResolutionRequestRecorder() override {} void AddToHistory(const std::string& hostname) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); requested_hostnames_.push_back(hostname); if (is_waiting_for_hostname_ && waiting_for_hostname_ == hostname) { is_waiting_for_hostname_ = false; waiting_for_hostname_.clear(); base::MessageLoop::current()->Quit(); } } // The hostname which WaitUntilHostHasBeenRequested is currently waiting for // to be requested. std::string waiting_for_hostname_; // Whether WaitUntilHostHasBeenRequested is waiting for a hostname to be // requested and thus is running a nested message loop. bool is_waiting_for_hostname_; // A list of hostnames for which resolution has already been requested. Only // to be accessed from the UI thread. std::vector<std::string> requested_hostnames_; DISALLOW_COPY_AND_ASSIGN(HostResolutionRequestRecorder); }; } // namespace namespace chrome_browser_net { class PredictorBrowserTest : public InProcessBrowserTest { public: PredictorBrowserTest() : startup_url_("http://host1:1"), referring_url_("http://host2:1"), target_url_("http://host3:1"), host_resolution_request_recorder_(new HostResolutionRequestRecorder) { } protected: void SetUpInProcessBrowserTestFixture() override { scoped_host_resolver_proc_.reset(new net::ScopedDefaultHostResolverProc( host_resolution_request_recorder_.get())); InProcessBrowserTest::SetUpInProcessBrowserTestFixture(); } void TearDownInProcessBrowserTestFixture() override { InProcessBrowserTest::TearDownInProcessBrowserTestFixture(); scoped_host_resolver_proc_.reset(); } void LearnAboutInitialNavigation(const GURL& url) { Predictor* predictor = browser()->profile()->GetNetworkPredictor(); BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind(&Predictor::LearnAboutInitialNavigation, base::Unretained(predictor), url)); content::RunAllPendingInMessageLoop(BrowserThread::IO); } void LearnFromNavigation(const GURL& referring_url, const GURL& target_url) { Predictor* predictor = browser()->profile()->GetNetworkPredictor(); BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind(&Predictor::LearnFromNavigation, base::Unretained(predictor), referring_url, target_url)); content::RunAllPendingInMessageLoop(BrowserThread::IO); } void PrepareFrameSubresources(const GURL& url) { Predictor* predictor = browser()->profile()->GetNetworkPredictor(); predictor->PredictFrameSubresources(url, GURL()); } void GetListFromPrefsAsString(const char* list_path, std::string* value_as_string) const { PrefService* prefs = browser()->profile()->GetPrefs(); const base::ListValue* list_value = prefs->GetList(list_path); JSONStringValueSerializer serializer(value_as_string); serializer.Serialize(*list_value); } bool HasHostBeenRequested(const std::string& hostname) const { return host_resolution_request_recorder_->HasHostBeenRequested(hostname); } void WaitUntilHostHasBeenRequested(const std::string& hostname) { host_resolution_request_recorder_->WaitUntilHostHasBeenRequested(hostname); } int RequestedHostnameCount() const { return host_resolution_request_recorder_->RequestedHostnameCount(); } const GURL startup_url_; const GURL referring_url_; const GURL target_url_; private: scoped_refptr<HostResolutionRequestRecorder> host_resolution_request_recorder_; scoped_ptr<net::ScopedDefaultHostResolverProc> scoped_host_resolver_proc_; }; IN_PROC_BROWSER_TEST_F(PredictorBrowserTest, PRE_ShutdownStartupCycle) { // Prepare state that will be serialized on this shut-down and read on next // start-up. LearnAboutInitialNavigation(startup_url_); LearnFromNavigation(referring_url_, target_url_); } IN_PROC_BROWSER_TEST_F(PredictorBrowserTest, ShutdownStartupCycle) { // Make sure that the Preferences file is actually wiped of all DNS prefetch // related data after start-up. std::string cleared_startup_list; std::string cleared_referral_list; GetListFromPrefsAsString(prefs::kDnsPrefetchingStartupList, &cleared_startup_list); GetListFromPrefsAsString(prefs::kDnsPrefetchingHostReferralList, &cleared_referral_list); EXPECT_THAT(cleared_startup_list, Not(HasSubstr(startup_url_.host()))); EXPECT_THAT(cleared_referral_list, Not(HasSubstr(referring_url_.host()))); EXPECT_THAT(cleared_referral_list, Not(HasSubstr(target_url_.host()))); // But also make sure this data has been first loaded into the Predictor, by // inspecting that the Predictor starts making the expected hostname requests. PrepareFrameSubresources(referring_url_); WaitUntilHostHasBeenRequested(startup_url_.host()); WaitUntilHostHasBeenRequested(target_url_.host()); } IN_PROC_BROWSER_TEST_F(PredictorBrowserTest, DnsPrefetch) { ASSERT_TRUE(test_server()->Start()); int hostnames_requested_before_load = RequestedHostnameCount(); ui_test_utils::NavigateToURL( browser(), GURL(test_server()->GetURL("files/predictor/dns_prefetch.html"))); WaitUntilHostHasBeenRequested(kChromiumHostname); ASSERT_FALSE(HasHostBeenRequested(kInvalidLongHostname)); ASSERT_EQ(hostnames_requested_before_load + 1, RequestedHostnameCount()); } } // namespace chrome_browser_net
CTSRD-SOAAP/chromium-42.0.2311.135
chrome/browser/net/predictor_browsertest.cc
C++
bsd-3-clause
8,500
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.10"/> <title>HE_Mesh: src/hemesh_creators/wblut/hemesh/HEC_FromBinaryHemeshFile.java File Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="navtree.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="resize.js"></script> <script type="text/javascript" src="navtreedata.js"></script> <script type="text/javascript" src="navtree.js"></script> <script type="text/javascript"> $(document).ready(initResizable); $(window).load(resizeHeight); </script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { init_search(); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">HE_Mesh &#160;<span id="projectnumber">6.0.1</span> </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.10 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="namespaces.html"><span>Packages</span></a></li> <li><a href="annotated.html"><span>Classes</span></a></li> <li class="current"><a href="files.html"><span>Files</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="files.html"><span>File&#160;List</span></a></li> </ul> </div> </div><!-- top --> <div id="side-nav" class="ui-resizable side-nav-resizable"> <div id="nav-tree"> <div id="nav-tree-contents"> <div id="nav-sync" class="sync"></div> </div> </div> <div id="splitbar" style="-moz-user-select:none;" class="ui-resizable-handle"> </div> </div> <script type="text/javascript"> $(document).ready(function(){initNavTree('_h_e_c___from_binary_hemesh_file_8java.html','');}); </script> <div id="doc-content"> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div class="header"> <div class="summary"> <a href="#nested-classes">Classes</a> &#124; <a href="#namespaces">Packages</a> </div> <div class="headertitle"> <div class="title">HEC_FromBinaryHemeshFile.java File Reference</div> </div> </div><!--header--> <div class="contents"> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="nested-classes"></a> Classes</h2></td></tr> <tr class="memitem:"><td class="memItemLeft" align="right" valign="top">class &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classwblut_1_1hemesh_1_1_h_e_c___from_binary_hemesh_file.html">wblut.hemesh.HEC_FromBinaryHemeshFile</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> </table><table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="namespaces"></a> Packages</h2></td></tr> <tr class="memitem:namespacewblut_1_1hemesh"><td class="memItemLeft" align="right" valign="top">package &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespacewblut_1_1hemesh.html">wblut.hemesh</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> </div><!-- contents --> </div><!-- doc-content --> <!-- start footer part --> <div id="nav-path" class="navpath"><!-- id is needed for treeview function! --> <ul> <li class="navelem"><a class="el" href="dir_abb63ba6bdd980ee47e7becce32622d5.html">src</a></li><li class="navelem"><a class="el" href="dir_3234cf545203c34888e65d329c00e564.html">hemesh_creators</a></li><li class="navelem"><a class="el" href="dir_fb23ba32b52a6d79ecd96ff96bd3ac99.html">wblut</a></li><li class="navelem"><a class="el" href="dir_c470a09591d0942eb985807eee15f118.html">hemesh</a></li><li class="navelem"><a class="el" href="_h_e_c___from_binary_hemesh_file_8java.html">HEC_FromBinaryHemeshFile.java</a></li> <li class="footer">Generated on Tue Dec 19 2017 21:20:11 for HE_Mesh by <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.10 </li> </ul> </div> </body> </html>
DweebsUnited/CodeMonkey
resources/hemesh/ref/html/_h_e_c___from_binary_hemesh_file_8java.html
HTML
bsd-3-clause
6,261
--- title: BackgroundFetch sourceCodeUrl: 'https://github.com/expo/expo/tree/sdk-37/packages/expo-background-fetch' --- import PlatformsSection from '~/components/plugins/PlatformsSection'; **`expo-background-fetch`** provides an API to perform [background fetch](https://developer.apple.com/documentation/uikit/core_app/managing_your_app_s_life_cycle/preparing_your_app_to_run_in_the_background/updating_your_app_with_background_app_refresh) tasks, allowing you to run specific code periodically in the background to update your app. This module uses [TaskManager](task-manager.md) Native API under the hood. <PlatformsSection android emulator ios simulator /> ## Known issues BackgroundFetch only works when the app is backgrounded, not if the app was terminated or upon device reboot. [Here is the relevant Github issue](https://github.com/expo/expo/issues/3582) ## Installation For [managed](../../../introduction/managed-vs-bare.md#managed-workflow) apps, you'll need to run `expo install expo-background-fetch`. To use it in [bare](../../../introduction/managed-vs-bare.md#bare-workflow) React Native app, follow its [installation instructions](https://github.com/expo/expo/tree/master/packages/expo-background-fetch); ## Configuration In order to use `BackgroundFetch` API in standalone, detached and bare apps on iOS, your app has to include background mode in the `Info.plist` file. See [background tasks configuration guide](task-manager.md#configuration-for-standalone-apps) for more details. ## API ```js import * as BackgroundFetch from 'expo-background-fetch'; ``` ## Methods ### `BackgroundFetch.getStatusAsync()` Gets a status of background fetch. #### Returns Returns a promise resolving to one of these values: - `BackgroundFetch.Status.Restricted` — Background updates are unavailable and the user cannot enable them again. This status can occur when, for example, parental controls are in effect for the current user. - `BackgroundFetch.Status.Denied` - The user explicitly disabled background behavior for this app or for the whole system. - `BackgroundFetch.Status.Available` - Background updates are available for the app. ### `BackgroundFetch.registerTaskAsync(taskName, options)` Registers background fetch task with given name. Registered tasks are saved in persistent storage and restored once the app is initialized. #### Arguments - **taskName (_string_)** -- Name of the task to register. The task needs to be defined first - see [TaskManager.defineTask](task-manager.md#taskmanagerdefinetasktaskname-task) for more details. - **options (_object_)** -- An object of options: - **minimumInterval (_number_)** -- Inexact interval in seconds between subsequent repeats of the background fetch alarm. The final interval may differ from the specified one to minimize wakeups and battery usage. On Android it defaults to **15 minutes**. On iOS it calls [BackgroundFetch.setMinimumIntervalAsync](#backgroundfetchsetminimumintervalasyncminimuminterval) behind the scenes and the default value is the smallest fetch interval supported by the system (**10-15 minutes**). - **stopOnTerminate (_boolean_)** -- Whether to stop receiving background fetch events after user terminates the app. Defaults to `true`. (**Android only**) - **startOnBoot (_boolean_)** -- Whether to restart background fetch events when the device has finished booting. Defaults to `false`. (**Android only**) #### Returns Returns a promise that resolves once the task is registered and rejects in case of any errors. #### Task parameters Background fetch task receives no data, but your task should return a value that best describes the results of your background fetch work. - `BackgroundFetch.Result.NoData` - There was no new data to download. - `BackgroundFetch.Result.NewData` - New data was successfully downloaded. - `BackgroundFetch.Result.Failed` - An attempt to download data was made but that attempt failed. This return value is to let iOS know what the result of your background fetch was, so the platform can better schedule future background fetches. Also, your app has up to 30 seconds to perform the task, otherwise your app will be terminated and future background fetches may be delayed. ```javascript import * as BackgroundFetch from 'expo-background-fetch'; import * as TaskManager from 'expo-task-manager'; TaskManager.defineTask(YOUR_TASK_NAME, () => { try { const receivedNewData = // do your background fetch here return receivedNewData ? BackgroundFetch.Result.NewData : BackgroundFetch.Result.NoData; } catch (error) { return BackgroundFetch.Result.Failed; } }); ``` ### `BackgroundFetch.unregisterTaskAsync(taskName)` Unregisters background fetch task, so the application will no longer be executing this task. #### Arguments - **taskName (_string_)** -- Name of the task to unregister. #### Returns A promise resolving when the task is fully unregistered. ### `BackgroundFetch.setMinimumIntervalAsync(minimumInterval)` Sets the minimum number of seconds that must elapse before another background fetch can be initiated. This value is advisory only and does not indicate the exact amount of time expected between fetch operations. _This method doesn't take any effect on Android._ _It is a global value which means that it can overwrite settings from another application opened through Expo client._ #### Arguments - **minimumInterval (_number_)** -- Number of seconds that must elapse before another background fetch can be called. #### Returns A promise resolving once the minimum interval is set.
exponent/exponent
docs/pages/versions/v37.0.0/sdk/background-fetch.md
Markdown
bsd-3-clause
5,596
""" Concat routines. """ from collections import abc from typing import ( TYPE_CHECKING, Iterable, List, Mapping, Optional, Type, Union, cast, overload, ) import numpy as np from pandas._typing import FrameOrSeriesUnion, Label from pandas.util._decorators import cache_readonly from pandas.core.dtypes.concat import concat_compat from pandas.core.dtypes.generic import ABCDataFrame, ABCSeries from pandas.core.dtypes.missing import isna from pandas.core.arrays.categorical import ( factorize_from_iterable, factorize_from_iterables, ) import pandas.core.common as com from pandas.core.indexes.api import ( Index, MultiIndex, all_indexes_same, ensure_index, get_objs_combined_axis, get_unanimous_names, ) import pandas.core.indexes.base as ibase from pandas.core.internals import concatenate_block_managers if TYPE_CHECKING: from pandas import DataFrame, Series from pandas.core.generic import NDFrame # --------------------------------------------------------------------- # Concatenate DataFrame objects @overload def concat( objs: Union[Iterable["DataFrame"], Mapping[Label, "DataFrame"]], axis=0, join: str = "outer", ignore_index: bool = False, keys=None, levels=None, names=None, verify_integrity: bool = False, sort: bool = False, copy: bool = True, ) -> "DataFrame": ... @overload def concat( objs: Union[Iterable["NDFrame"], Mapping[Label, "NDFrame"]], axis=0, join: str = "outer", ignore_index: bool = False, keys=None, levels=None, names=None, verify_integrity: bool = False, sort: bool = False, copy: bool = True, ) -> FrameOrSeriesUnion: ... def concat( objs: Union[Iterable["NDFrame"], Mapping[Label, "NDFrame"]], axis=0, join="outer", ignore_index: bool = False, keys=None, levels=None, names=None, verify_integrity: bool = False, sort: bool = False, copy: bool = True, ) -> FrameOrSeriesUnion: """ Concatenate pandas objects along a particular axis with optional set logic along the other axes. Can also add a layer of hierarchical indexing on the concatenation axis, which may be useful if the labels are the same (or overlapping) on the passed axis number. Parameters ---------- objs : a sequence or mapping of Series or DataFrame objects If a mapping is passed, the sorted keys will be used as the `keys` argument, unless it is passed, in which case the values will be selected (see below). Any None objects will be dropped silently unless they are all None in which case a ValueError will be raised. axis : {0/'index', 1/'columns'}, default 0 The axis to concatenate along. join : {'inner', 'outer'}, default 'outer' How to handle indexes on other axis (or axes). ignore_index : bool, default False If True, do not use the index values along the concatenation axis. The resulting axis will be labeled 0, ..., n - 1. This is useful if you are concatenating objects where the concatenation axis does not have meaningful indexing information. Note the index values on the other axes are still respected in the join. keys : sequence, default None If multiple levels passed, should contain tuples. Construct hierarchical index using the passed keys as the outermost level. levels : list of sequences, default None Specific levels (unique values) to use for constructing a MultiIndex. Otherwise they will be inferred from the keys. names : list, default None Names for the levels in the resulting hierarchical index. verify_integrity : bool, default False Check whether the new concatenated axis contains duplicates. This can be very expensive relative to the actual data concatenation. sort : bool, default False Sort non-concatenation axis if it is not already aligned when `join` is 'outer'. This has no effect when ``join='inner'``, which already preserves the order of the non-concatenation axis. .. versionchanged:: 1.0.0 Changed to not sort by default. copy : bool, default True If False, do not copy data unnecessarily. Returns ------- object, type of objs When concatenating all ``Series`` along the index (axis=0), a ``Series`` is returned. When ``objs`` contains at least one ``DataFrame``, a ``DataFrame`` is returned. When concatenating along the columns (axis=1), a ``DataFrame`` is returned. See Also -------- Series.append : Concatenate Series. DataFrame.append : Concatenate DataFrames. DataFrame.join : Join DataFrames using indexes. DataFrame.merge : Merge DataFrames by indexes or columns. Notes ----- The keys, levels, and names arguments are all optional. A walkthrough of how this method fits in with other tools for combining pandas objects can be found `here <https://pandas.pydata.org/pandas-docs/stable/user_guide/merging.html>`__. Examples -------- Combine two ``Series``. >>> s1 = pd.Series(['a', 'b']) >>> s2 = pd.Series(['c', 'd']) >>> pd.concat([s1, s2]) 0 a 1 b 0 c 1 d dtype: object Clear the existing index and reset it in the result by setting the ``ignore_index`` option to ``True``. >>> pd.concat([s1, s2], ignore_index=True) 0 a 1 b 2 c 3 d dtype: object Add a hierarchical index at the outermost level of the data with the ``keys`` option. >>> pd.concat([s1, s2], keys=['s1', 's2']) s1 0 a 1 b s2 0 c 1 d dtype: object Label the index keys you create with the ``names`` option. >>> pd.concat([s1, s2], keys=['s1', 's2'], ... names=['Series name', 'Row ID']) Series name Row ID s1 0 a 1 b s2 0 c 1 d dtype: object Combine two ``DataFrame`` objects with identical columns. >>> df1 = pd.DataFrame([['a', 1], ['b', 2]], ... columns=['letter', 'number']) >>> df1 letter number 0 a 1 1 b 2 >>> df2 = pd.DataFrame([['c', 3], ['d', 4]], ... columns=['letter', 'number']) >>> df2 letter number 0 c 3 1 d 4 >>> pd.concat([df1, df2]) letter number 0 a 1 1 b 2 0 c 3 1 d 4 Combine ``DataFrame`` objects with overlapping columns and return everything. Columns outside the intersection will be filled with ``NaN`` values. >>> df3 = pd.DataFrame([['c', 3, 'cat'], ['d', 4, 'dog']], ... columns=['letter', 'number', 'animal']) >>> df3 letter number animal 0 c 3 cat 1 d 4 dog >>> pd.concat([df1, df3], sort=False) letter number animal 0 a 1 NaN 1 b 2 NaN 0 c 3 cat 1 d 4 dog Combine ``DataFrame`` objects with overlapping columns and return only those that are shared by passing ``inner`` to the ``join`` keyword argument. >>> pd.concat([df1, df3], join="inner") letter number 0 a 1 1 b 2 0 c 3 1 d 4 Combine ``DataFrame`` objects horizontally along the x axis by passing in ``axis=1``. >>> df4 = pd.DataFrame([['bird', 'polly'], ['monkey', 'george']], ... columns=['animal', 'name']) >>> pd.concat([df1, df4], axis=1) letter number animal name 0 a 1 bird polly 1 b 2 monkey george Prevent the result from including duplicate index values with the ``verify_integrity`` option. >>> df5 = pd.DataFrame([1], index=['a']) >>> df5 0 a 1 >>> df6 = pd.DataFrame([2], index=['a']) >>> df6 0 a 2 >>> pd.concat([df5, df6], verify_integrity=True) Traceback (most recent call last): ... ValueError: Indexes have overlapping values: ['a'] """ op = _Concatenator( objs, axis=axis, ignore_index=ignore_index, join=join, keys=keys, levels=levels, names=names, verify_integrity=verify_integrity, copy=copy, sort=sort, ) return op.get_result() class _Concatenator: """ Orchestrates a concatenation operation for BlockManagers """ def __init__( self, objs: Union[Iterable["NDFrame"], Mapping[Label, "NDFrame"]], axis=0, join: str = "outer", keys=None, levels=None, names=None, ignore_index: bool = False, verify_integrity: bool = False, copy: bool = True, sort=False, ): if isinstance(objs, (ABCSeries, ABCDataFrame, str)): raise TypeError( "first argument must be an iterable of pandas " f'objects, you passed an object of type "{type(objs).__name__}"' ) if join == "outer": self.intersect = False elif join == "inner": self.intersect = True else: # pragma: no cover raise ValueError( "Only can inner (intersect) or outer (union) join the other axis" ) if isinstance(objs, abc.Mapping): if keys is None: keys = list(objs.keys()) objs = [objs[k] for k in keys] else: objs = list(objs) if len(objs) == 0: raise ValueError("No objects to concatenate") if keys is None: objs = list(com.not_none(*objs)) else: # #1649 clean_keys = [] clean_objs = [] for k, v in zip(keys, objs): if v is None: continue clean_keys.append(k) clean_objs.append(v) objs = clean_objs name = getattr(keys, "name", None) keys = Index(clean_keys, name=name) if len(objs) == 0: raise ValueError("All objects passed were None") # figure out what our result ndim is going to be ndims = set() for obj in objs: if not isinstance(obj, (ABCSeries, ABCDataFrame)): msg = ( f"cannot concatenate object of type '{type(obj)}'; " "only Series and DataFrame objs are valid" ) raise TypeError(msg) ndims.add(obj.ndim) # get the sample # want the highest ndim that we have, and must be non-empty # unless all objs are empty sample: Optional["NDFrame"] = None if len(ndims) > 1: max_ndim = max(ndims) for obj in objs: if obj.ndim == max_ndim and np.sum(obj.shape): sample = obj break else: # filter out the empties if we have not multi-index possibilities # note to keep empty Series as it affect to result columns / name non_empties = [ obj for obj in objs if sum(obj.shape) > 0 or isinstance(obj, ABCSeries) ] if len(non_empties) and ( keys is None and names is None and levels is None and not self.intersect ): objs = non_empties sample = objs[0] if sample is None: sample = objs[0] self.objs = objs # Standardize axis parameter to int if isinstance(sample, ABCSeries): axis = sample._constructor_expanddim._get_axis_number(axis) else: axis = sample._get_axis_number(axis) # Need to flip BlockManager axis in the DataFrame special case self._is_frame = isinstance(sample, ABCDataFrame) if self._is_frame: axis = sample._get_block_manager_axis(axis) self._is_series = isinstance(sample, ABCSeries) if not 0 <= axis <= sample.ndim: raise AssertionError( f"axis must be between 0 and {sample.ndim}, input was {axis}" ) # if we have mixed ndims, then convert to highest ndim # creating column numbers as needed if len(ndims) > 1: current_column = 0 max_ndim = sample.ndim self.objs, objs = [], self.objs for obj in objs: ndim = obj.ndim if ndim == max_ndim: pass elif ndim != max_ndim - 1: raise ValueError( "cannot concatenate unaligned mixed " "dimensional NDFrame objects" ) else: name = getattr(obj, "name", None) if ignore_index or name is None: name = current_column current_column += 1 # doing a row-wise concatenation so need everything # to line up if self._is_frame and axis == 1: name = 0 # mypy needs to know sample is not an NDFrame sample = cast("FrameOrSeriesUnion", sample) obj = sample._constructor({name: obj}) self.objs.append(obj) # note: this is the BlockManager axis (since DataFrame is transposed) self.bm_axis = axis self.axis = 1 - self.bm_axis if self._is_frame else 0 self.keys = keys self.names = names or getattr(keys, "names", None) self.levels = levels self.sort = sort self.ignore_index = ignore_index self.verify_integrity = verify_integrity self.copy = copy self.new_axes = self._get_new_axes() def get_result(self): cons: Type[FrameOrSeriesUnion] sample: FrameOrSeriesUnion # series only if self._is_series: sample = cast("Series", self.objs[0]) # stack blocks if self.bm_axis == 0: name = com.consensus_name_attr(self.objs) cons = sample._constructor arrs = [ser._values for ser in self.objs] res = concat_compat(arrs, axis=0) result = cons(res, index=self.new_axes[0], name=name, dtype=res.dtype) return result.__finalize__(self, method="concat") # combine as columns in a frame else: data = dict(zip(range(len(self.objs)), self.objs)) # GH28330 Preserves subclassed objects through concat cons = sample._constructor_expanddim index, columns = self.new_axes df = cons(data, index=index) df.columns = columns return df.__finalize__(self, method="concat") # combine block managers else: sample = cast("DataFrame", self.objs[0]) mgrs_indexers = [] for obj in self.objs: indexers = {} for ax, new_labels in enumerate(self.new_axes): # ::-1 to convert BlockManager ax to DataFrame ax if ax == self.bm_axis: # Suppress reindexing on concat axis continue # 1-ax to convert BlockManager axis to DataFrame axis obj_labels = obj.axes[1 - ax] if not new_labels.equals(obj_labels): indexers[ax] = obj_labels.get_indexer(new_labels) mgrs_indexers.append((obj._mgr, indexers)) new_data = concatenate_block_managers( mgrs_indexers, self.new_axes, concat_axis=self.bm_axis, copy=self.copy ) if not self.copy: new_data._consolidate_inplace() cons = sample._constructor return cons(new_data).__finalize__(self, method="concat") def _get_result_dim(self) -> int: if self._is_series and self.bm_axis == 1: return 2 else: return self.objs[0].ndim def _get_new_axes(self) -> List[Index]: ndim = self._get_result_dim() return [ self._get_concat_axis if i == self.bm_axis else self._get_comb_axis(i) for i in range(ndim) ] def _get_comb_axis(self, i: int) -> Index: data_axis = self.objs[0]._get_block_manager_axis(i) return get_objs_combined_axis( self.objs, axis=data_axis, intersect=self.intersect, sort=self.sort, copy=self.copy, ) @cache_readonly def _get_concat_axis(self) -> Index: """ Return index to be used along concatenation axis. """ if self._is_series: if self.bm_axis == 0: indexes = [x.index for x in self.objs] elif self.ignore_index: idx = ibase.default_index(len(self.objs)) return idx elif self.keys is None: names: List[Label] = [None] * len(self.objs) num = 0 has_names = False for i, x in enumerate(self.objs): if not isinstance(x, ABCSeries): raise TypeError( f"Cannot concatenate type 'Series' with " f"object of type '{type(x).__name__}'" ) if x.name is not None: names[i] = x.name has_names = True else: names[i] = num num += 1 if has_names: return Index(names) else: return ibase.default_index(len(self.objs)) else: return ensure_index(self.keys).set_names(self.names) else: indexes = [x.axes[self.axis] for x in self.objs] if self.ignore_index: idx = ibase.default_index(sum(len(i) for i in indexes)) return idx if self.keys is None: concat_axis = _concat_indexes(indexes) else: concat_axis = _make_concat_multiindex( indexes, self.keys, self.levels, self.names ) self._maybe_check_integrity(concat_axis) return concat_axis def _maybe_check_integrity(self, concat_index: Index): if self.verify_integrity: if not concat_index.is_unique: overlap = concat_index[concat_index.duplicated()].unique() raise ValueError(f"Indexes have overlapping values: {overlap}") def _concat_indexes(indexes) -> Index: return indexes[0].append(indexes[1:]) def _make_concat_multiindex(indexes, keys, levels=None, names=None) -> MultiIndex: if (levels is None and isinstance(keys[0], tuple)) or ( levels is not None and len(levels) > 1 ): zipped = list(zip(*keys)) if names is None: names = [None] * len(zipped) if levels is None: _, levels = factorize_from_iterables(zipped) else: levels = [ensure_index(x) for x in levels] else: zipped = [keys] if names is None: names = [None] if levels is None: levels = [ensure_index(keys)] else: levels = [ensure_index(x) for x in levels] if not all_indexes_same(indexes): codes_list = [] # things are potentially different sizes, so compute the exact codes # for each level and pass those to MultiIndex.from_arrays for hlevel, level in zip(zipped, levels): to_concat = [] for key, index in zip(hlevel, indexes): # Find matching codes, include matching nan values as equal. mask = (isna(level) & isna(key)) | (level == key) if not mask.any(): raise ValueError(f"Key {key} not in level {level}") i = np.nonzero(mask)[0][0] to_concat.append(np.repeat(i, len(index))) codes_list.append(np.concatenate(to_concat)) concat_index = _concat_indexes(indexes) # these go at the end if isinstance(concat_index, MultiIndex): levels.extend(concat_index.levels) codes_list.extend(concat_index.codes) else: codes, categories = factorize_from_iterable(concat_index) levels.append(categories) codes_list.append(codes) if len(names) == len(levels): names = list(names) else: # make sure that all of the passed indices have the same nlevels if not len({idx.nlevels for idx in indexes}) == 1: raise AssertionError( "Cannot concat indices that do not have the same number of levels" ) # also copies names = list(names) + list(get_unanimous_names(*indexes)) return MultiIndex( levels=levels, codes=codes_list, names=names, verify_integrity=False ) new_index = indexes[0] n = len(new_index) kpieces = len(indexes) # also copies new_names = list(names) new_levels = list(levels) # construct codes new_codes = [] # do something a bit more speedy for hlevel, level in zip(zipped, levels): hlevel = ensure_index(hlevel) mapped = level.get_indexer(hlevel) mask = mapped == -1 if mask.any(): raise ValueError(f"Values not found in passed level: {hlevel[mask]!s}") new_codes.append(np.repeat(mapped, n)) if isinstance(new_index, MultiIndex): new_levels.extend(new_index.levels) new_codes.extend([np.tile(lab, kpieces) for lab in new_index.codes]) else: new_levels.append(new_index) new_codes.append(np.tile(np.arange(n), kpieces)) if len(new_names) < len(new_levels): new_names.extend(new_index.names) return MultiIndex( levels=new_levels, codes=new_codes, names=new_names, verify_integrity=False )
jreback/pandas
pandas/core/reshape/concat.py
Python
bsd-3-clause
22,709
/* ///////////////////////////////////////////////////////////////////////// * File: examples/cpp/misc/example.cpp.misc.strings/implicit_link.cpp * * Purpose: Implicit link file for the example.cpp.misc.strings project. * * Created: 21st October 2008 * Updated: 21st September 2015 * * Status: Wizard-generated * * License: (Licensed under the Synesis Software Open License) * * Copyright (c) 2008-2015, Synesis Software Pty Ltd. * All rights reserved. * * www: http://www.synesis.com.au/software * * ////////////////////////////////////////////////////////////////////// */ /* Pantheios header files */ #include <pantheios/implicit_link/core.h> #include <pantheios/implicit_link/fe.simple.h> #include <pantheios/implicit_link/be.console.h> /* UNIXem header files */ #include <platformstl/platformstl.h> #if defined(PLATFORMSTL_OS_IS_UNIX) && \ defined(_WIN32) # include <unixem/implicit_link.h> #endif /* _WIN32 || _WIN64 */ /* ///////////////////////////// end of file //////////////////////////// */
synesissoftware/Pantheios
examples/cpp/misc/example.cpp.misc.strings/implicit_link.cpp
C++
bsd-3-clause
1,102
// Copyright 2005, 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. // // Authors: [email protected] (Zhanyong Wan) // // Low-level types and utilities for porting Google Test to various // platforms. All macros ending with _ and symbols defined in an // internal namespace are subject to change without notice. Code // outside Google Test MUST NOT USE THEM DIRECTLY. Macros that don't // end with _ are part of Google Test's public API and can be used by // code outside Google Test. // // This file is fundamental to Google Test. All other Google Test source // files are expected to #include this. Therefore, it cannot #include // any other Google Test header. #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_ // Environment-describing macros // ----------------------------- // // Google Test can be used in many different environments. Macros in // this section tell Google Test what kind of environment it is being // used in, such that Google Test can provide environment-specific // features and implementations. // // Google Test tries to automatically detect the properties of its // environment, so users usually don't need to worry about these // macros. However, the automatic detection is not perfect. // Sometimes it's necessary for a user to define some of the following // macros in the build script to override Google Test's decisions. // // If the user doesn't define a macro in the list, Google Test will // provide a default definition. After this header is #included, all // macros in this list will be defined to either 1 or 0. // // Notes to maintainers: // - Each macro here is a user-tweakable knob; do not grow the list // lightly. // - Use #if to key off these macros. Don't use #ifdef or "#if // defined(...)", which will not work as these macros are ALWAYS // defined. // // GTEST_HAS_CLONE - Define it to 1/0 to indicate that clone(2) // is/isn't available. // GTEST_HAS_EXCEPTIONS - Define it to 1/0 to indicate that exceptions // are enabled. // GTEST_HAS_GLOBAL_STRING - Define it to 1/0 to indicate that ::string // is/isn't available (some systems define // ::string, which is different to std::string). // GTEST_HAS_GLOBAL_WSTRING - Define it to 1/0 to indicate that ::string // is/isn't available (some systems define // ::wstring, which is different to std::wstring). // GTEST_HAS_POSIX_RE - Define it to 1/0 to indicate that POSIX regular // expressions are/aren't available. // GTEST_HAS_PTHREAD - Define it to 1/0 to indicate that <pthread.h> // is/isn't available. // GTEST_HAS_RTTI - Define it to 1/0 to indicate that RTTI is/isn't // enabled. // GTEST_HAS_STD_WSTRING - Define it to 1/0 to indicate that // std::wstring does/doesn't work (Google Test can // be used where std::wstring is unavailable). // GTEST_HAS_TR1_TUPLE - Define it to 1/0 to indicate tr1::tuple // is/isn't available. // GTEST_HAS_SEH - Define it to 1/0 to indicate whether the // compiler supports Microsoft's "Structured // Exception Handling". // GTEST_HAS_STREAM_REDIRECTION // - Define it to 1/0 to indicate whether the // platform supports I/O stream redirection using // dup() and dup2(). // GTEST_USE_OWN_TR1_TUPLE - Define it to 1/0 to indicate whether Google // Test's own tr1 tuple implementation should be // used. Unused when the user sets // GTEST_HAS_TR1_TUPLE to 0. // GTEST_LANG_CXX11 - Define it to 1/0 to indicate that Google Test // is building in C++11/C++98 mode. // GTEST_LINKED_AS_SHARED_LIBRARY // - Define to 1 when compiling tests that use // Google Test as a shared library (known as // DLL on Windows). // GTEST_CREATE_SHARED_LIBRARY // - Define to 1 when compiling Google Test itself // as a shared library. // Platform-indicating macros // -------------------------- // // Macros indicating the platform on which Google Test is being used // (a macro is defined to 1 if compiled on the given platform; // otherwise UNDEFINED -- it's never defined to 0.). Google Test // defines these macros automatically. Code outside Google Test MUST // NOT define them. // // GTEST_OS_AIX - IBM AIX // GTEST_OS_CYGWIN - Cygwin // GTEST_OS_FREEBSD - FreeBSD // GTEST_OS_HPUX - HP-UX // GTEST_OS_LINUX - Linux // GTEST_OS_LINUX_ANDROID - Google Android // GTEST_OS_MAC - Mac OS X // GTEST_OS_IOS - iOS // GTEST_OS_NACL - Google Native Client (NaCl) // GTEST_OS_OPENBSD - OpenBSD // GTEST_OS_QNX - QNX // GTEST_OS_SOLARIS - Sun Solaris // GTEST_OS_SYMBIAN - Symbian // GTEST_OS_WINDOWS - Windows (Desktop, MinGW, or Mobile) // GTEST_OS_WINDOWS_DESKTOP - Windows Desktop // GTEST_OS_WINDOWS_MINGW - MinGW // GTEST_OS_WINDOWS_MOBILE - Windows Mobile // GTEST_OS_WINDOWS_PHONE - Windows Phone // GTEST_OS_WINDOWS_RT - Windows Store App/WinRT // GTEST_OS_ZOS - z/OS // // Among the platforms, Cygwin, Linux, Max OS X, and Windows have the // most stable support. Since core members of the Google Test project // don't have access to other platforms, support for them may be less // stable. If you notice any problems on your platform, please notify // [email protected] (patches for fixing them are // even more welcome!). // // It is possible that none of the GTEST_OS_* macros are defined. // Feature-indicating macros // ------------------------- // // Macros indicating which Google Test features are available (a macro // is defined to 1 if the corresponding feature is supported; // otherwise UNDEFINED -- it's never defined to 0.). Google Test // defines these macros automatically. Code outside Google Test MUST // NOT define them. // // These macros are public so that portable tests can be written. // Such tests typically surround code using a feature with an #if // which controls that code. For example: // // #if GTEST_HAS_DEATH_TEST // EXPECT_DEATH(DoSomethingDeadly()); // #endif // // GTEST_HAS_COMBINE - the Combine() function (for value-parameterized // tests) // GTEST_HAS_DEATH_TEST - death tests // GTEST_HAS_PARAM_TEST - value-parameterized tests // GTEST_HAS_TYPED_TEST - typed tests // GTEST_HAS_TYPED_TEST_P - type-parameterized tests // GTEST_IS_THREADSAFE - Google Test is thread-safe. // GTEST_USES_POSIX_RE - enhanced POSIX regex is used. Do not confuse with // GTEST_HAS_POSIX_RE (see above) which users can // define themselves. // GTEST_USES_SIMPLE_RE - our own simple regex is used; // the above two are mutually exclusive. // GTEST_CAN_COMPARE_NULL - accepts untyped NULL in EXPECT_EQ(). // Misc public macros // ------------------ // // GTEST_FLAG(flag_name) - references the variable corresponding to // the given Google Test flag. // Internal utilities // ------------------ // // The following macros and utilities are for Google Test's INTERNAL // use only. Code outside Google Test MUST NOT USE THEM DIRECTLY. // // Macros for basic C++ coding: // GTEST_AMBIGUOUS_ELSE_BLOCKER_ - for disabling a gcc warning. // GTEST_ATTRIBUTE_UNUSED_ - declares that a class' instances or a // variable don't have to be used. // GTEST_DISALLOW_ASSIGN_ - disables operator=. // GTEST_DISALLOW_COPY_AND_ASSIGN_ - disables copy ctor and operator=. // GTEST_MUST_USE_RESULT_ - declares that a function's result must be used. // GTEST_INTENTIONAL_CONST_COND_PUSH_ - start code section where MSVC C4127 is // suppressed (constant conditional). // GTEST_INTENTIONAL_CONST_COND_POP_ - finish code section where MSVC C4127 // is suppressed. // // C++11 feature wrappers: // // testing::internal::move - portability wrapper for std::move. // // Synchronization: // Mutex, MutexLock, ThreadLocal, GetThreadCount() // - synchronization primitives. // // Template meta programming: // is_pointer - as in TR1; needed on Symbian and IBM XL C/C++ only. // IteratorTraits - partial implementation of std::iterator_traits, which // is not available in libCstd when compiled with Sun C++. // // Smart pointers: // scoped_ptr - as in TR2. // // Regular expressions: // RE - a simple regular expression class using the POSIX // Extended Regular Expression syntax on UNIX-like // platforms, or a reduced regular exception syntax on // other platforms, including Windows. // // Logging: // GTEST_LOG_() - logs messages at the specified severity level. // LogToStderr() - directs all log messages to stderr. // FlushInfoLog() - flushes informational log messages. // // Stdout and stderr capturing: // CaptureStdout() - starts capturing stdout. // GetCapturedStdout() - stops capturing stdout and returns the captured // string. // CaptureStderr() - starts capturing stderr. // GetCapturedStderr() - stops capturing stderr and returns the captured // string. // // Integer types: // TypeWithSize - maps an integer to a int type. // Int32, UInt32, Int64, UInt64, TimeInMillis // - integers of known sizes. // BiggestInt - the biggest signed integer type. // // Command-line utilities: // GTEST_DECLARE_*() - declares a flag. // GTEST_DEFINE_*() - defines a flag. // GetInjectableArgvs() - returns the command line as a vector of strings. // // Environment variable utilities: // GetEnv() - gets the value of an environment variable. // BoolFromGTestEnv() - parses a bool environment variable. // Int32FromGTestEnv() - parses an Int32 environment variable. // StringFromGTestEnv() - parses a string environment variable. #include <ctype.h> // for isspace, etc #include <stddef.h> // for ptrdiff_t #include <stdlib.h> #include <stdio.h> #include <string.h> #ifndef _WIN32_WCE # include <sys/types.h> # include <sys/stat.h> #endif // !_WIN32_WCE #if defined __APPLE__ # include <AvailabilityMacros.h> # include <TargetConditionals.h> #endif #include <algorithm> // NOLINT #include <iostream> // NOLINT #include <sstream> // NOLINT #include <string> // NOLINT #include <utility> #include <vector> // NOLINT #include "gtest/internal/gtest-port-arch.h" #include "gtest/internal/custom/gtest-port.h" #if !defined(GTEST_DEV_EMAIL_) # define GTEST_DEV_EMAIL_ "googletestframework@@googlegroups.com" # define GTEST_FLAG_PREFIX_ "gtest_" # define GTEST_FLAG_PREFIX_DASH_ "gtest-" # define GTEST_FLAG_PREFIX_UPPER_ "GTEST_" # define GTEST_NAME_ "Google Test" # define GTEST_PROJECT_URL_ "http://code.google.com/p/googletest/" #endif // !defined(GTEST_DEV_EMAIL_) #if !defined(GTEST_INIT_GOOGLE_TEST_NAME_) # define GTEST_INIT_GOOGLE_TEST_NAME_ "testing::InitGoogleTest" #endif // !defined(GTEST_INIT_GOOGLE_TEST_NAME_) // Determines the version of gcc that is used to compile this. #ifdef __GNUC__ // 40302 means version 4.3.2. # define GTEST_GCC_VER_ \ (__GNUC__*10000 + __GNUC_MINOR__*100 + __GNUC_PATCHLEVEL__) #endif // __GNUC__ // Macros for disabling Microsoft Visual C++ warnings. // // GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800 4385) // /* code that triggers warnings C4800 and C4385 */ // GTEST_DISABLE_MSC_WARNINGS_POP_() #if _MSC_VER >= 1500 # define GTEST_DISABLE_MSC_WARNINGS_PUSH_(warnings) \ __pragma(warning(push)) \ __pragma(warning(disable: warnings)) # define GTEST_DISABLE_MSC_WARNINGS_POP_() \ __pragma(warning(pop)) #else // Older versions of MSVC don't have __pragma. # define GTEST_DISABLE_MSC_WARNINGS_PUSH_(warnings) # define GTEST_DISABLE_MSC_WARNINGS_POP_() #endif #ifndef GTEST_LANG_CXX11 // gcc and clang define __GXX_EXPERIMENTAL_CXX0X__ when // -std={c,gnu}++{0x,11} is passed. The C++11 standard specifies a // value for __cplusplus, and recent versions of clang, gcc, and // probably other compilers set that too in C++11 mode. # if __GXX_EXPERIMENTAL_CXX0X__ || __cplusplus >= 201103L // Compiling in at least C++11 mode. # define GTEST_LANG_CXX11 1 # else # define GTEST_LANG_CXX11 0 # endif #endif // Distinct from C++11 language support, some environments don't provide // proper C++11 library support. Notably, it's possible to build in // C++11 mode when targeting Mac OS X 10.6, which has an old libstdc++ // with no C++11 support. // // libstdc++ has sufficient C++11 support as of GCC 4.6.0, __GLIBCXX__ // 20110325, but maintenance releases in the 4.4 and 4.5 series followed // this date, so check for those versions by their date stamps. // https://gcc.gnu.org/onlinedocs/libstdc++/manual/abi.html#abi.versioning #if GTEST_LANG_CXX11 && \ (!defined(__GLIBCXX__) || ( \ __GLIBCXX__ >= 20110325ul && /* GCC >= 4.6.0 */ \ /* Blacklist of patch releases of older branches: */ \ __GLIBCXX__ != 20110416ul && /* GCC 4.4.6 */ \ __GLIBCXX__ != 20120313ul && /* GCC 4.4.7 */ \ __GLIBCXX__ != 20110428ul && /* GCC 4.5.3 */ \ __GLIBCXX__ != 20120702ul)) /* GCC 4.5.4 */ # define GTEST_STDLIB_CXX11 1 #endif // Only use C++11 library features if the library provides them. #if GTEST_STDLIB_CXX11 # define GTEST_HAS_STD_BEGIN_AND_END_ 1 # define GTEST_HAS_STD_FORWARD_LIST_ 1 # define GTEST_HAS_STD_FUNCTION_ 1 # define GTEST_HAS_STD_INITIALIZER_LIST_ 1 # define GTEST_HAS_STD_MOVE_ 1 # define GTEST_HAS_STD_UNIQUE_PTR_ 1 # define GTEST_HAS_STD_SHARED_PTR_ 1 #endif // C++11 specifies that <tuple> provides std::tuple. // Some platforms still might not have it, however. #if GTEST_LANG_CXX11 # define GTEST_HAS_STD_TUPLE_ 1 # if defined(__clang__) // Inspired by http://clang.llvm.org/docs/LanguageExtensions.html#__has_include # if defined(__has_include) && !__has_include(<tuple>) # undef GTEST_HAS_STD_TUPLE_ # endif # elif defined(_MSC_VER) // Inspired by boost/config/stdlib/dinkumware.hpp # if defined(_CPPLIB_VER) && _CPPLIB_VER < 520 # undef GTEST_HAS_STD_TUPLE_ # endif # elif defined(__GLIBCXX__) // Inspired by boost/config/stdlib/libstdcpp3.hpp, // http://gcc.gnu.org/gcc-4.2/changes.html and // http://gcc.gnu.org/onlinedocs/libstdc++/manual/bk01pt01ch01.html#manual.intro.status.standard.200x # if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 2) # undef GTEST_HAS_STD_TUPLE_ # endif # endif #endif // Brings in definitions for functions used in the testing::internal::posix // namespace (read, write, close, chdir, isatty, stat). We do not currently // use them on Windows Mobile. #if GTEST_OS_WINDOWS # if !GTEST_OS_WINDOWS_MOBILE # include <direct.h> # include <io.h> # endif // In order to avoid having to include <windows.h>, use forward declaration // assuming CRITICAL_SECTION is a typedef of _RTL_CRITICAL_SECTION. // This assumption is verified by // WindowsTypesTest.CRITICAL_SECTIONIs_RTL_CRITICAL_SECTION. //#define _RTL_CRITICAL_SECTION int struct _RTL_CRITICAL_SECTION; #else // This assumes that non-Windows OSes provide unistd.h. For OSes where this // is not the case, we need to include headers that provide the functions // mentioned above. # include <unistd.h> # include <strings.h> #endif // GTEST_OS_WINDOWS #if GTEST_OS_LINUX_ANDROID // Used to define __ANDROID_API__ matching the target NDK API level. # include <android/api-level.h> // NOLINT #endif // Defines this to true iff Google Test can use POSIX regular expressions. #ifndef GTEST_HAS_POSIX_RE # if GTEST_OS_LINUX_ANDROID // On Android, <regex.h> is only available starting with Gingerbread. # define GTEST_HAS_POSIX_RE (__ANDROID_API__ >= 9) # else # define GTEST_HAS_POSIX_RE (!GTEST_OS_WINDOWS) # endif #endif #if GTEST_USES_PCRE // The appropriate headers have already been included. #elif GTEST_HAS_POSIX_RE // On some platforms, <regex.h> needs someone to define size_t, and // won't compile otherwise. We can #include it here as we already // included <stdlib.h>, which is guaranteed to define size_t through // <stddef.h>. # include <regex.h> // NOLINT # define GTEST_USES_POSIX_RE 1 #elif GTEST_OS_WINDOWS // <regex.h> is not available on Windows. Use our own simple regex // implementation instead. # define GTEST_USES_SIMPLE_RE 1 #else // <regex.h> may not be available on this platform. Use our own // simple regex implementation instead. # define GTEST_USES_SIMPLE_RE 1 #endif // GTEST_USES_PCRE #ifndef GTEST_HAS_EXCEPTIONS // The user didn't tell us whether exceptions are enabled, so we need // to figure it out. # if defined(_MSC_VER) || defined(__BORLANDC__) // MSVC's and C++Builder's implementations of the STL use the _HAS_EXCEPTIONS // macro to enable exceptions, so we'll do the same. // Assumes that exceptions are enabled by default. # ifndef _HAS_EXCEPTIONS # define _HAS_EXCEPTIONS 1 # endif // _HAS_EXCEPTIONS # define GTEST_HAS_EXCEPTIONS _HAS_EXCEPTIONS # elif defined(__clang__) // clang defines __EXCEPTIONS iff exceptions are enabled before clang 220714, // but iff cleanups are enabled after that. In Obj-C++ files, there can be // cleanups for ObjC exceptions which also need cleanups, even if C++ exceptions // are disabled. clang has __has_feature(cxx_exceptions) which checks for C++ // exceptions starting at clang r206352, but which checked for cleanups prior to // that. To reliably check for C++ exception availability with clang, check for // __EXCEPTIONS && __has_feature(cxx_exceptions). # define GTEST_HAS_EXCEPTIONS (__EXCEPTIONS && __has_feature(cxx_exceptions)) # elif defined(__GNUC__) && __EXCEPTIONS // gcc defines __EXCEPTIONS to 1 iff exceptions are enabled. # define GTEST_HAS_EXCEPTIONS 1 # elif defined(__SUNPRO_CC) // Sun Pro CC supports exceptions. However, there is no compile-time way of // detecting whether they are enabled or not. Therefore, we assume that // they are enabled unless the user tells us otherwise. # define GTEST_HAS_EXCEPTIONS 1 # elif defined(__IBMCPP__) && __EXCEPTIONS // xlC defines __EXCEPTIONS to 1 iff exceptions are enabled. # define GTEST_HAS_EXCEPTIONS 1 # elif defined(__HP_aCC) // Exception handling is in effect by default in HP aCC compiler. It has to // be turned of by +noeh compiler option if desired. # define GTEST_HAS_EXCEPTIONS 1 # else // For other compilers, we assume exceptions are disabled to be // conservative. # define GTEST_HAS_EXCEPTIONS 0 # endif // defined(_MSC_VER) || defined(__BORLANDC__) #endif // GTEST_HAS_EXCEPTIONS #if !defined(GTEST_HAS_STD_STRING) // Even though we don't use this macro any longer, we keep it in case // some clients still depend on it. # define GTEST_HAS_STD_STRING 1 #elif !GTEST_HAS_STD_STRING // The user told us that ::std::string isn't available. # error "Google Test cannot be used where ::std::string isn't available." #endif // !defined(GTEST_HAS_STD_STRING) #ifndef GTEST_HAS_GLOBAL_STRING // The user didn't tell us whether ::string is available, so we need // to figure it out. # define GTEST_HAS_GLOBAL_STRING 0 #endif // GTEST_HAS_GLOBAL_STRING #ifndef GTEST_HAS_STD_WSTRING // The user didn't tell us whether ::std::wstring is available, so we need // to figure it out. // TODO([email protected]): uses autoconf to detect whether ::std::wstring // is available. // Cygwin 1.7 and below doesn't support ::std::wstring. // Solaris' libc++ doesn't support it either. Android has // no support for it at least as recent as Froyo (2.2). # define GTEST_HAS_STD_WSTRING \ (!(GTEST_OS_LINUX_ANDROID || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS)) #endif // GTEST_HAS_STD_WSTRING #ifndef GTEST_HAS_GLOBAL_WSTRING // The user didn't tell us whether ::wstring is available, so we need // to figure it out. # define GTEST_HAS_GLOBAL_WSTRING \ (GTEST_HAS_STD_WSTRING && GTEST_HAS_GLOBAL_STRING) #endif // GTEST_HAS_GLOBAL_WSTRING // Determines whether RTTI is available. #ifndef GTEST_HAS_RTTI // The user didn't tell us whether RTTI is enabled, so we need to // figure it out. # ifdef _MSC_VER # ifdef _CPPRTTI // MSVC defines this macro iff RTTI is enabled. # define GTEST_HAS_RTTI 1 # else # define GTEST_HAS_RTTI 0 # endif // Starting with version 4.3.2, gcc defines __GXX_RTTI iff RTTI is enabled. # elif defined(__GNUC__) && (GTEST_GCC_VER_ >= 40302) # ifdef __GXX_RTTI // When building against STLport with the Android NDK and with // -frtti -fno-exceptions, the build fails at link time with undefined // references to __cxa_bad_typeid. Note sure if STL or toolchain bug, // so disable RTTI when detected. # if GTEST_OS_LINUX_ANDROID && defined(_STLPORT_MAJOR) && \ !defined(__EXCEPTIONS) # define GTEST_HAS_RTTI 0 # else # define GTEST_HAS_RTTI 1 # endif // GTEST_OS_LINUX_ANDROID && __STLPORT_MAJOR && !__EXCEPTIONS # else # define GTEST_HAS_RTTI 0 # endif // __GXX_RTTI // Clang defines __GXX_RTTI starting with version 3.0, but its manual recommends // using has_feature instead. has_feature(cxx_rtti) is supported since 2.7, the // first version with C++ support. # elif defined(__clang__) # define GTEST_HAS_RTTI __has_feature(cxx_rtti) // Starting with version 9.0 IBM Visual Age defines __RTTI_ALL__ to 1 if // both the typeid and dynamic_cast features are present. # elif defined(__IBMCPP__) && (__IBMCPP__ >= 900) # ifdef __RTTI_ALL__ # define GTEST_HAS_RTTI 1 # else # define GTEST_HAS_RTTI 0 # endif # else // For all other compilers, we assume RTTI is enabled. # define GTEST_HAS_RTTI 1 # endif // _MSC_VER #endif // GTEST_HAS_RTTI // It's this header's responsibility to #include <typeinfo> when RTTI // is enabled. #if GTEST_HAS_RTTI # include <typeinfo> #endif // Determines whether Google Test can use the pthreads library. #ifndef GTEST_HAS_PTHREAD // The user didn't tell us explicitly, so we make reasonable assumptions about // which platforms have pthreads support. // // To disable threading support in Google Test, add -DGTEST_HAS_PTHREAD=0 // to your compiler flags. # define GTEST_HAS_PTHREAD (GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_HPUX \ || GTEST_OS_QNX || GTEST_OS_FREEBSD || GTEST_OS_NACL) #endif // GTEST_HAS_PTHREAD #if GTEST_HAS_PTHREAD // gtest-port.h guarantees to #include <pthread.h> when GTEST_HAS_PTHREAD is // true. # include <pthread.h> // NOLINT // For timespec and nanosleep, used below. # include <time.h> // NOLINT #endif // Determines if hash_map/hash_set are available. // Only used for testing against those containers. #if !defined(GTEST_HAS_HASH_MAP_) # if _MSC_VER # define GTEST_HAS_HASH_MAP_ 1 // Indicates that hash_map is available. # define GTEST_HAS_HASH_SET_ 1 // Indicates that hash_set is available. # endif // _MSC_VER #endif // !defined(GTEST_HAS_HASH_MAP_) // Determines whether Google Test can use tr1/tuple. You can define // this macro to 0 to prevent Google Test from using tuple (any // feature depending on tuple with be disabled in this mode). #ifndef GTEST_HAS_TR1_TUPLE # if GTEST_OS_LINUX_ANDROID && defined(_STLPORT_MAJOR) // STLport, provided with the Android NDK, has neither <tr1/tuple> or <tuple>. # define GTEST_HAS_TR1_TUPLE 0 # else // The user didn't tell us not to do it, so we assume it's OK. # define GTEST_HAS_TR1_TUPLE 1 # endif #endif // GTEST_HAS_TR1_TUPLE // Determines whether Google Test's own tr1 tuple implementation // should be used. #ifndef GTEST_USE_OWN_TR1_TUPLE // The user didn't tell us, so we need to figure it out. // We use our own TR1 tuple if we aren't sure the user has an // implementation of it already. At this time, libstdc++ 4.0.0+ and // MSVC 2010 are the only mainstream standard libraries that come // with a TR1 tuple implementation. NVIDIA's CUDA NVCC compiler // pretends to be GCC by defining __GNUC__ and friends, but cannot // compile GCC's tuple implementation. MSVC 2008 (9.0) provides TR1 // tuple in a 323 MB Feature Pack download, which we cannot assume the // user has. QNX's QCC compiler is a modified GCC but it doesn't // support TR1 tuple. libc++ only provides std::tuple, in C++11 mode, // and it can be used with some compilers that define __GNUC__. # if (defined(__GNUC__) && !defined(__CUDACC__) && (GTEST_GCC_VER_ >= 40000) \ && !GTEST_OS_QNX && !defined(_LIBCPP_VERSION)) || _MSC_VER >= 1600 # define GTEST_ENV_HAS_TR1_TUPLE_ 1 # endif // C++11 specifies that <tuple> provides std::tuple. Use that if gtest is used // in C++11 mode and libstdc++ isn't very old (binaries targeting OS X 10.6 // can build with clang but need to use gcc4.2's libstdc++). # if GTEST_LANG_CXX11 && (!defined(__GLIBCXX__) || __GLIBCXX__ > 20110325) # define GTEST_ENV_HAS_STD_TUPLE_ 1 # endif # if GTEST_ENV_HAS_TR1_TUPLE_ || GTEST_ENV_HAS_STD_TUPLE_ # define GTEST_USE_OWN_TR1_TUPLE 0 # else # define GTEST_USE_OWN_TR1_TUPLE 1 # endif #endif // GTEST_USE_OWN_TR1_TUPLE // To avoid conditional compilation everywhere, we make it // gtest-port.h's responsibility to #include the header implementing // tuple. #if GTEST_HAS_STD_TUPLE_ # include <tuple> // IWYU pragma: export # define GTEST_TUPLE_NAMESPACE_ ::std #endif // GTEST_HAS_STD_TUPLE_ // We include tr1::tuple even if std::tuple is available to define printers for // them. #if GTEST_HAS_TR1_TUPLE # ifndef GTEST_TUPLE_NAMESPACE_ # define GTEST_TUPLE_NAMESPACE_ ::std::tr1 # endif // GTEST_TUPLE_NAMESPACE_ # if GTEST_USE_OWN_TR1_TUPLE # include "gtest/internal/gtest-tuple.h" // IWYU pragma: export // NOLINT # elif GTEST_ENV_HAS_STD_TUPLE_ # include <tuple> // C++11 puts its tuple into the ::std namespace rather than // ::std::tr1. gtest expects tuple to live in ::std::tr1, so put it there. // This causes undefined behavior, but supported compilers react in // the way we intend. namespace std { namespace tr1 { using ::std::get; using ::std::make_tuple; using ::std::tuple; using ::std::tuple_element; using ::std::tuple_size; } } # elif GTEST_OS_SYMBIAN // On Symbian, BOOST_HAS_TR1_TUPLE causes Boost's TR1 tuple library to // use STLport's tuple implementation, which unfortunately doesn't // work as the copy of STLport distributed with Symbian is incomplete. // By making sure BOOST_HAS_TR1_TUPLE is undefined, we force Boost to // use its own tuple implementation. # ifdef BOOST_HAS_TR1_TUPLE # undef BOOST_HAS_TR1_TUPLE # endif // BOOST_HAS_TR1_TUPLE // This prevents <boost/tr1/detail/config.hpp>, which defines // BOOST_HAS_TR1_TUPLE, from being #included by Boost's <tuple>. # define BOOST_TR1_DETAIL_CONFIG_HPP_INCLUDED # include <tuple> // IWYU pragma: export // NOLINT # elif defined(__GNUC__) && (GTEST_GCC_VER_ >= 40000) // GCC 4.0+ implements tr1/tuple in the <tr1/tuple> header. This does // not conform to the TR1 spec, which requires the header to be <tuple>. # if !GTEST_HAS_RTTI && GTEST_GCC_VER_ < 40302 // Until version 4.3.2, gcc has a bug that causes <tr1/functional>, // which is #included by <tr1/tuple>, to not compile when RTTI is // disabled. _TR1_FUNCTIONAL is the header guard for // <tr1/functional>. Hence the following #define is a hack to prevent // <tr1/functional> from being included. # define _TR1_FUNCTIONAL 1 # include <tr1/tuple> # undef _TR1_FUNCTIONAL // Allows the user to #include // <tr1/functional> if he chooses to. # else # include <tr1/tuple> // NOLINT # endif // !GTEST_HAS_RTTI && GTEST_GCC_VER_ < 40302 # else // If the compiler is not GCC 4.0+, we assume the user is using a // spec-conforming TR1 implementation. # include <tuple> // IWYU pragma: export // NOLINT # endif // GTEST_USE_OWN_TR1_TUPLE #endif // GTEST_HAS_TR1_TUPLE // Determines whether clone(2) is supported. // Usually it will only be available on Linux, excluding // Linux on the Itanium architecture. // Also see http://linux.die.net/man/2/clone. #ifndef GTEST_HAS_CLONE // The user didn't tell us, so we need to figure it out. # if GTEST_OS_LINUX && !defined(__ia64__) # if GTEST_OS_LINUX_ANDROID // On Android, clone() is only available on ARM starting with Gingerbread. # if defined(__arm__) && __ANDROID_API__ >= 9 # define GTEST_HAS_CLONE 1 # else # define GTEST_HAS_CLONE 0 # endif # else # define GTEST_HAS_CLONE 1 # endif # else # define GTEST_HAS_CLONE 0 # endif // GTEST_OS_LINUX && !defined(__ia64__) #endif // GTEST_HAS_CLONE // Determines whether to support stream redirection. This is used to test // output correctness and to implement death tests. #ifndef GTEST_HAS_STREAM_REDIRECTION // By default, we assume that stream redirection is supported on all // platforms except known mobile ones. # if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || \ GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT # define GTEST_HAS_STREAM_REDIRECTION 0 # else # define GTEST_HAS_STREAM_REDIRECTION 1 # endif // !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_SYMBIAN #endif // GTEST_HAS_STREAM_REDIRECTION // Determines whether to support death tests. // Google Test does not support death tests for VC 7.1 and earlier as // abort() in a VC 7.1 application compiled as GUI in debug config // pops up a dialog window that cannot be suppressed programmatically. #if (GTEST_OS_LINUX || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS || \ (GTEST_OS_MAC && !GTEST_OS_IOS) || \ (GTEST_OS_WINDOWS_DESKTOP && _MSC_VER >= 1400) || \ GTEST_OS_WINDOWS_MINGW || GTEST_OS_AIX || GTEST_OS_HPUX || \ GTEST_OS_OPENBSD || GTEST_OS_QNX || GTEST_OS_FREEBSD) # define GTEST_HAS_DEATH_TEST 1 #endif // We don't support MSVC 7.1 with exceptions disabled now. Therefore // all the compilers we care about are adequate for supporting // value-parameterized tests. #define GTEST_HAS_PARAM_TEST 1 // Determines whether to support type-driven tests. // Typed tests need <typeinfo> and variadic macros, which GCC, VC++ 8.0, // Sun Pro CC, IBM Visual Age, and HP aCC support. #if defined(__GNUC__) || (_MSC_VER >= 1400) || defined(__SUNPRO_CC) || \ defined(__IBMCPP__) || defined(__HP_aCC) # define GTEST_HAS_TYPED_TEST 1 # define GTEST_HAS_TYPED_TEST_P 1 #endif // Determines whether to support Combine(). This only makes sense when // value-parameterized tests are enabled. The implementation doesn't // work on Sun Studio since it doesn't understand templated conversion // operators. #if GTEST_HAS_PARAM_TEST && GTEST_HAS_TR1_TUPLE && !defined(__SUNPRO_CC) # define GTEST_HAS_COMBINE 1 #endif // Determines whether the system compiler uses UTF-16 for encoding wide strings. #define GTEST_WIDE_STRING_USES_UTF16_ \ (GTEST_OS_WINDOWS || GTEST_OS_CYGWIN || GTEST_OS_SYMBIAN || GTEST_OS_AIX) // Determines whether test results can be streamed to a socket. #if GTEST_OS_LINUX # define GTEST_CAN_STREAM_RESULTS_ 1 #endif // Defines some utility macros. // The GNU compiler emits a warning if nested "if" statements are followed by // an "else" statement and braces are not used to explicitly disambiguate the // "else" binding. This leads to problems with code like: // // if (gate) // ASSERT_*(condition) << "Some message"; // // The "switch (0) case 0:" idiom is used to suppress this. #ifdef __INTEL_COMPILER # define GTEST_AMBIGUOUS_ELSE_BLOCKER_ #else # define GTEST_AMBIGUOUS_ELSE_BLOCKER_ switch (0) case 0: default: // NOLINT #endif // Use this annotation at the end of a struct/class definition to // prevent the compiler from optimizing away instances that are never // used. This is useful when all interesting logic happens inside the // c'tor and / or d'tor. Example: // // struct Foo { // Foo() { ... } // } GTEST_ATTRIBUTE_UNUSED_; // // Also use it after a variable or parameter declaration to tell the // compiler the variable/parameter does not have to be used. #if defined(__GNUC__) && !defined(COMPILER_ICC) # define GTEST_ATTRIBUTE_UNUSED_ __attribute__ ((unused)) #elif defined(__clang__) # if __has_attribute(unused) # define GTEST_ATTRIBUTE_UNUSED_ __attribute__ ((unused)) # endif #endif #ifndef GTEST_ATTRIBUTE_UNUSED_ # define GTEST_ATTRIBUTE_UNUSED_ #endif // A macro to disallow operator= // This should be used in the private: declarations for a class. #define GTEST_DISALLOW_ASSIGN_(type)\ void operator=(type const &) // A macro to disallow copy constructor and operator= // This should be used in the private: declarations for a class. #define GTEST_DISALLOW_COPY_AND_ASSIGN_(type)\ type(type const &);\ GTEST_DISALLOW_ASSIGN_(type) // Tell the compiler to warn about unused return values for functions declared // with this macro. The macro should be used on function declarations // following the argument list: // // Sprocket* AllocateSprocket() GTEST_MUST_USE_RESULT_; #if defined(__GNUC__) && (GTEST_GCC_VER_ >= 30400) && !defined(COMPILER_ICC) # define GTEST_MUST_USE_RESULT_ __attribute__ ((warn_unused_result)) #else # define GTEST_MUST_USE_RESULT_ #endif // __GNUC__ && (GTEST_GCC_VER_ >= 30400) && !COMPILER_ICC // MS C++ compiler emits warning when a conditional expression is compile time // constant. In some contexts this warning is false positive and needs to be // suppressed. Use the following two macros in such cases: // // GTEST_INTENTIONAL_CONST_COND_PUSH_() // while (true) { // GTEST_INTENTIONAL_CONST_COND_POP_() // } # define GTEST_INTENTIONAL_CONST_COND_PUSH_() \ GTEST_DISABLE_MSC_WARNINGS_PUSH_(4127) # define GTEST_INTENTIONAL_CONST_COND_POP_() \ GTEST_DISABLE_MSC_WARNINGS_POP_() // Determine whether the compiler supports Microsoft's Structured Exception // Handling. This is supported by several Windows compilers but generally // does not exist on any other system. #ifndef GTEST_HAS_SEH // The user didn't tell us, so we need to figure it out. # if defined(_MSC_VER) || defined(__BORLANDC__) // These two compilers are known to support SEH. # define GTEST_HAS_SEH 1 # else // Assume no SEH. # define GTEST_HAS_SEH 0 # endif #define GTEST_IS_THREADSAFE \ (GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ \ || (GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT) \ || GTEST_HAS_PTHREAD) #endif // GTEST_HAS_SEH #ifdef _MSC_VER # if GTEST_LINKED_AS_SHARED_LIBRARY # define GTEST_API_ __declspec(dllimport) # elif GTEST_CREATE_SHARED_LIBRARY # define GTEST_API_ __declspec(dllexport) # endif #endif // _MSC_VER #ifndef GTEST_API_ # define GTEST_API_ #endif #ifdef __GNUC__ // Ask the compiler to never inline a given function. # define GTEST_NO_INLINE_ __attribute__((noinline)) #else # define GTEST_NO_INLINE_ #endif // _LIBCPP_VERSION is defined by the libc++ library from the LLVM project. #if defined(__GLIBCXX__) || defined(_LIBCPP_VERSION) # define GTEST_HAS_CXXABI_H_ 1 #else # define GTEST_HAS_CXXABI_H_ 0 #endif // A function level attribute to disable checking for use of uninitialized // memory when built with MemorySanitizer. #if defined(__clang__) # if __has_feature(memory_sanitizer) # define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ \ __attribute__((no_sanitize_memory)) # else # define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ # endif // __has_feature(memory_sanitizer) #else # define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ #endif // __clang__ // A function level attribute to disable AddressSanitizer instrumentation. #if defined(__clang__) # if __has_feature(address_sanitizer) # define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ \ __attribute__((no_sanitize_address)) # else # define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ # endif // __has_feature(address_sanitizer) #else # define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ #endif // __clang__ // A function level attribute to disable ThreadSanitizer instrumentation. #if defined(__clang__) # if __has_feature(thread_sanitizer) # define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ \ __attribute__((no_sanitize_thread)) # else # define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ # endif // __has_feature(thread_sanitizer) #else # define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ #endif // __clang__ namespace testing { class Message; #if defined(GTEST_TUPLE_NAMESPACE_) // Import tuple and friends into the ::testing namespace. // It is part of our interface, having them in ::testing allows us to change // their types as needed. using GTEST_TUPLE_NAMESPACE_::get; using GTEST_TUPLE_NAMESPACE_::make_tuple; using GTEST_TUPLE_NAMESPACE_::tuple; using GTEST_TUPLE_NAMESPACE_::tuple_size; using GTEST_TUPLE_NAMESPACE_::tuple_element; #endif // defined(GTEST_TUPLE_NAMESPACE_) namespace internal { // A secret type that Google Test users don't know about. It has no // definition on purpose. Therefore it's impossible to create a // Secret object, which is what we want. class Secret; // The GTEST_COMPILE_ASSERT_ macro can be used to verify that a compile time // expression is true. For example, you could use it to verify the // size of a static array: // // GTEST_COMPILE_ASSERT_(GTEST_ARRAY_SIZE_(names) == NUM_NAMES, // names_incorrect_size); // // or to make sure a struct is smaller than a certain size: // // GTEST_COMPILE_ASSERT_(sizeof(foo) < 128, foo_too_large); // // The second argument to the macro is the name of the variable. If // the expression is false, most compilers will issue a warning/error // containing the name of the variable. #if GTEST_LANG_CXX11 # define GTEST_COMPILE_ASSERT_(expr, msg) static_assert(expr, #msg) #else // !GTEST_LANG_CXX11 template <bool> struct CompileAssert { }; # define GTEST_COMPILE_ASSERT_(expr, msg) \ typedef ::testing::internal::CompileAssert<(static_cast<bool>(expr))> \ msg[static_cast<bool>(expr) ? 1 : -1] GTEST_ATTRIBUTE_UNUSED_ #endif // !GTEST_LANG_CXX11 // Implementation details of GTEST_COMPILE_ASSERT_: // // (In C++11, we simply use static_assert instead of the following) // // - GTEST_COMPILE_ASSERT_ works by defining an array type that has -1 // elements (and thus is invalid) when the expression is false. // // - The simpler definition // // #define GTEST_COMPILE_ASSERT_(expr, msg) typedef char msg[(expr) ? 1 : -1] // // does not work, as gcc supports variable-length arrays whose sizes // are determined at run-time (this is gcc's extension and not part // of the C++ standard). As a result, gcc fails to reject the // following code with the simple definition: // // int foo; // GTEST_COMPILE_ASSERT_(foo, msg); // not supposed to compile as foo is // // not a compile-time constant. // // - By using the type CompileAssert<(bool(expr))>, we ensures that // expr is a compile-time constant. (Template arguments must be // determined at compile-time.) // // - The outter parentheses in CompileAssert<(bool(expr))> are necessary // to work around a bug in gcc 3.4.4 and 4.0.1. If we had written // // CompileAssert<bool(expr)> // // instead, these compilers will refuse to compile // // GTEST_COMPILE_ASSERT_(5 > 0, some_message); // // (They seem to think the ">" in "5 > 0" marks the end of the // template argument list.) // // - The array size is (bool(expr) ? 1 : -1), instead of simply // // ((expr) ? 1 : -1). // // This is to avoid running into a bug in MS VC 7.1, which // causes ((0.0) ? 1 : -1) to incorrectly evaluate to 1. // StaticAssertTypeEqHelper is used by StaticAssertTypeEq defined in gtest.h. // // This template is declared, but intentionally undefined. template <typename T1, typename T2> struct StaticAssertTypeEqHelper; template <typename T> struct StaticAssertTypeEqHelper<T, T> { enum { value = true }; }; // Evaluates to the number of elements in 'array'. #define GTEST_ARRAY_SIZE_(array) (sizeof(array) / sizeof(array[0])) #if GTEST_HAS_GLOBAL_STRING typedef ::string string; #else typedef ::std::string string; #endif // GTEST_HAS_GLOBAL_STRING #if GTEST_HAS_GLOBAL_WSTRING typedef ::wstring wstring; #elif GTEST_HAS_STD_WSTRING typedef ::std::wstring wstring; #endif // GTEST_HAS_GLOBAL_WSTRING // A helper for suppressing warnings on constant condition. It just // returns 'condition'. GTEST_API_ bool IsTrue(bool condition); // Defines scoped_ptr. // This implementation of scoped_ptr is PARTIAL - it only contains // enough stuff to satisfy Google Test's need. template <typename T> class scoped_ptr { public: typedef T element_type; explicit scoped_ptr(T* p = NULL) : ptr_(p) {} ~scoped_ptr() { reset(); } T& operator*() const { return *ptr_; } T* operator->() const { return ptr_; } T* get() const { return ptr_; } T* release() { T* const ptr = ptr_; ptr_ = NULL; return ptr; } void reset(T* p = NULL) { if (p != ptr_) { if (IsTrue(sizeof(T) > 0)) { // Makes sure T is a complete type. delete ptr_; } ptr_ = p; } } friend void swap(scoped_ptr& a, scoped_ptr& b) { using std::swap; swap(a.ptr_, b.ptr_); } private: T* ptr_; GTEST_DISALLOW_COPY_AND_ASSIGN_(scoped_ptr); }; // Defines RE. // A simple C++ wrapper for <regex.h>. It uses the POSIX Extended // Regular Expression syntax. class GTEST_API_ RE { public: // A copy constructor is required by the Standard to initialize object // references from r-values. RE(const RE& other) { Init(other.pattern()); } // Constructs an RE from a string. RE(const ::std::string& regex) { Init(regex.c_str()); } // NOLINT #if GTEST_HAS_GLOBAL_STRING RE(const ::string& regex) { Init(regex.c_str()); } // NOLINT #endif // GTEST_HAS_GLOBAL_STRING RE(const char* regex) { Init(regex); } // NOLINT ~RE(); // Returns the string representation of the regex. const char* pattern() const { return pattern_; } // FullMatch(str, re) returns true iff regular expression re matches // the entire str. // PartialMatch(str, re) returns true iff regular expression re // matches a substring of str (including str itself). // // TODO([email protected]): make FullMatch() and PartialMatch() work // when str contains NUL characters. static bool FullMatch(const ::std::string& str, const RE& re) { return FullMatch(str.c_str(), re); } static bool PartialMatch(const ::std::string& str, const RE& re) { return PartialMatch(str.c_str(), re); } #if GTEST_HAS_GLOBAL_STRING static bool FullMatch(const ::string& str, const RE& re) { return FullMatch(str.c_str(), re); } static bool PartialMatch(const ::string& str, const RE& re) { return PartialMatch(str.c_str(), re); } #endif // GTEST_HAS_GLOBAL_STRING static bool FullMatch(const char* str, const RE& re); static bool PartialMatch(const char* str, const RE& re); private: void Init(const char* regex); // We use a const char* instead of an std::string, as Google Test used to be // used where std::string is not available. TODO([email protected]): change to // std::string. const char* pattern_; bool is_valid_; #if GTEST_USES_POSIX_RE regex_t full_regex_; // For FullMatch(). regex_t partial_regex_; // For PartialMatch(). #else // GTEST_USES_SIMPLE_RE const char* full_pattern_; // For FullMatch(); #endif GTEST_DISALLOW_ASSIGN_(RE); }; // Formats a source file path and a line number as they would appear // in an error message from the compiler used to compile this code. GTEST_API_ ::std::string FormatFileLocation(const char* file, int line); // Formats a file location for compiler-independent XML output. // Although this function is not platform dependent, we put it next to // FormatFileLocation in order to contrast the two functions. GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(const char* file, int line); // Defines logging utilities: // GTEST_LOG_(severity) - logs messages at the specified severity level. The // message itself is streamed into the macro. // LogToStderr() - directs all log messages to stderr. // FlushInfoLog() - flushes informational log messages. enum GTestLogSeverity { GTEST_INFO, GTEST_WARNING, GTEST_ERROR, GTEST_FATAL }; // Formats log entry severity, provides a stream object for streaming the // log message, and terminates the message with a newline when going out of // scope. class GTEST_API_ GTestLog { public: GTestLog(GTestLogSeverity severity, const char* file, int line); // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program. ~GTestLog(); ::std::ostream& GetStream() { return ::std::cerr; } private: const GTestLogSeverity severity_; GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestLog); }; #if !defined(GTEST_LOG_) # define GTEST_LOG_(severity) \ ::testing::internal::GTestLog(::testing::internal::GTEST_##severity, \ __FILE__, __LINE__).GetStream() inline void LogToStderr() {} inline void FlushInfoLog() { fflush(NULL); } #endif // !defined(GTEST_LOG_) #if !defined(GTEST_CHECK_) // INTERNAL IMPLEMENTATION - DO NOT USE. // // GTEST_CHECK_ is an all-mode assert. It aborts the program if the condition // is not satisfied. // Synopsys: // GTEST_CHECK_(boolean_condition); // or // GTEST_CHECK_(boolean_condition) << "Additional message"; // // This checks the condition and if the condition is not satisfied // it prints message about the condition violation, including the // condition itself, plus additional message streamed into it, if any, // and then it aborts the program. It aborts the program irrespective of // whether it is built in the debug mode or not. # define GTEST_CHECK_(condition) \ GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ if (::testing::internal::IsTrue(condition)) \ ; \ else \ GTEST_LOG_(FATAL) << "Condition " #condition " failed. " #endif // !defined(GTEST_CHECK_) // An all-mode assert to verify that the given POSIX-style function // call returns 0 (indicating success). Known limitation: this // doesn't expand to a balanced 'if' statement, so enclose the macro // in {} if you need to use it as the only statement in an 'if' // branch. #define GTEST_CHECK_POSIX_SUCCESS_(posix_call) \ if (const int gtest_error = (posix_call)) \ GTEST_LOG_(FATAL) << #posix_call << "failed with error " \ << gtest_error #if GTEST_HAS_STD_MOVE_ using std::move; #else // GTEST_HAS_STD_MOVE_ template <typename T> const T& move(const T& t) { return t; } #endif // GTEST_HAS_STD_MOVE_ // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // Use ImplicitCast_ as a safe version of static_cast for upcasting in // the type hierarchy (e.g. casting a Foo* to a SuperclassOfFoo* or a // const Foo*). When you use ImplicitCast_, the compiler checks that // the cast is safe. Such explicit ImplicitCast_s are necessary in // surprisingly many situations where C++ demands an exact type match // instead of an argument type convertable to a target type. // // The syntax for using ImplicitCast_ is the same as for static_cast: // // ImplicitCast_<ToType>(expr) // // ImplicitCast_ would have been part of the C++ standard library, // but the proposal was submitted too late. It will probably make // its way into the language in the future. // // This relatively ugly name is intentional. It prevents clashes with // similar functions users may have (e.g., implicit_cast). The internal // namespace alone is not enough because the function can be found by ADL. template<typename To> inline To ImplicitCast_(To x) { return x; } // When you upcast (that is, cast a pointer from type Foo to type // SuperclassOfFoo), it's fine to use ImplicitCast_<>, since upcasts // always succeed. When you downcast (that is, cast a pointer from // type Foo to type SubclassOfFoo), static_cast<> isn't safe, because // how do you know the pointer is really of type SubclassOfFoo? It // could be a bare Foo, or of type DifferentSubclassOfFoo. Thus, // when you downcast, you should use this macro. In debug mode, we // use dynamic_cast<> to double-check the downcast is legal (we die // if it's not). In normal mode, we do the efficient static_cast<> // instead. Thus, it's important to test in debug mode to make sure // the cast is legal! // This is the only place in the code we should use dynamic_cast<>. // In particular, you SHOULDN'T be using dynamic_cast<> in order to // do RTTI (eg code like this: // if (dynamic_cast<Subclass1>(foo)) HandleASubclass1Object(foo); // if (dynamic_cast<Subclass2>(foo)) HandleASubclass2Object(foo); // You should design the code some other way not to need this. // // This relatively ugly name is intentional. It prevents clashes with // similar functions users may have (e.g., down_cast). The internal // namespace alone is not enough because the function can be found by ADL. template<typename To, typename From> // use like this: DownCast_<T*>(foo); inline To DownCast_(From* f) { // so we only accept pointers // Ensures that To is a sub-type of From *. This test is here only // for compile-time type checking, and has no overhead in an // optimized build at run-time, as it will be optimized away // completely. GTEST_INTENTIONAL_CONST_COND_PUSH_() if (false) { GTEST_INTENTIONAL_CONST_COND_POP_() const To to = NULL; ::testing::internal::ImplicitCast_<From*>(to); } #if GTEST_HAS_RTTI // RTTI: debug mode only! GTEST_CHECK_(f == NULL || dynamic_cast<To>(f) != NULL); #endif return static_cast<To>(f); } // Downcasts the pointer of type Base to Derived. // Derived must be a subclass of Base. The parameter MUST // point to a class of type Derived, not any subclass of it. // When RTTI is available, the function performs a runtime // check to enforce this. template <class Derived, class Base> Derived* CheckedDowncastToActualType(Base* base) { #if GTEST_HAS_RTTI GTEST_CHECK_(typeid(*base) == typeid(Derived)); #endif #if GTEST_HAS_DOWNCAST_ return ::down_cast<Derived*>(base); #elif GTEST_HAS_RTTI return dynamic_cast<Derived*>(base); // NOLINT #else return static_cast<Derived*>(base); // Poor man's downcast. #endif } #if GTEST_HAS_STREAM_REDIRECTION // Defines the stderr capturer: // CaptureStdout - starts capturing stdout. // GetCapturedStdout - stops capturing stdout and returns the captured string. // CaptureStderr - starts capturing stderr. // GetCapturedStderr - stops capturing stderr and returns the captured string. // GTEST_API_ void CaptureStdout(); GTEST_API_ std::string GetCapturedStdout(); GTEST_API_ void CaptureStderr(); GTEST_API_ std::string GetCapturedStderr(); #endif // GTEST_HAS_STREAM_REDIRECTION // Returns a path to temporary directory. GTEST_API_ std::string TempDir(); // Returns the size (in bytes) of a file. GTEST_API_ size_t GetFileSize(FILE* file); // Reads the entire content of a file as a string. GTEST_API_ std::string ReadEntireFile(FILE* file); // All command line arguments. GTEST_API_ const ::std::vector<testing::internal::string>& GetArgvs(); #if GTEST_HAS_DEATH_TEST const ::std::vector<testing::internal::string>& GetInjectableArgvs(); void SetInjectableArgvs(const ::std::vector<testing::internal::string>* new_argvs); #endif // GTEST_HAS_DEATH_TEST // Defines synchronization primitives. #if GTEST_IS_THREADSAFE # if GTEST_HAS_PTHREAD // Sleeps for (roughly) n milliseconds. This function is only for testing // Google Test's own constructs. Don't use it in user tests, either // directly or indirectly. inline void SleepMilliseconds(int n) { const timespec time = { 0, // 0 seconds. n * 1000L * 1000L, // And n ms. }; nanosleep(&time, NULL); } # endif // GTEST_HAS_PTHREAD # if GTEST_HAS_NOTIFICATION_ // Notification has already been imported into the namespace. // Nothing to do here. # elif GTEST_HAS_PTHREAD // Allows a controller thread to pause execution of newly created // threads until notified. Instances of this class must be created // and destroyed in the controller thread. // // This class is only for testing Google Test's own constructs. Do not // use it in user tests, either directly or indirectly. class Notification { public: Notification() : notified_(false) { GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_init(&mutex_, NULL)); } ~Notification() { pthread_mutex_destroy(&mutex_); } // Notifies all threads created with this notification to start. Must // be called from the controller thread. void Notify() { pthread_mutex_lock(&mutex_); notified_ = true; pthread_mutex_unlock(&mutex_); } // Blocks until the controller thread notifies. Must be called from a test // thread. void WaitForNotification() { for (;;) { pthread_mutex_lock(&mutex_); const bool notified = notified_; pthread_mutex_unlock(&mutex_); if (notified) break; SleepMilliseconds(10); } } private: pthread_mutex_t mutex_; bool notified_; GTEST_DISALLOW_COPY_AND_ASSIGN_(Notification); }; # elif GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT GTEST_API_ void SleepMilliseconds(int n); // Provides leak-safe Windows kernel handle ownership. // Used in death tests and in threading support. class GTEST_API_ AutoHandle { public: // Assume that Win32 HANDLE type is equivalent to void*. Doing so allows us to // avoid including <windows.h> in this header file. Including <windows.h> is // undesirable because it defines a lot of symbols and macros that tend to // conflict with client code. This assumption is verified by // WindowsTypesTest.HANDLEIsVoidStar. typedef void* Handle; AutoHandle(); explicit AutoHandle(Handle handle); ~AutoHandle(); Handle Get() const; void Reset(); void Reset(Handle handle); private: // Returns true iff the handle is a valid handle object that can be closed. bool IsCloseable() const; Handle handle_; GTEST_DISALLOW_COPY_AND_ASSIGN_(AutoHandle); }; // Allows a controller thread to pause execution of newly created // threads until notified. Instances of this class must be created // and destroyed in the controller thread. // // This class is only for testing Google Test's own constructs. Do not // use it in user tests, either directly or indirectly. class GTEST_API_ Notification { public: Notification(); void Notify(); void WaitForNotification(); private: AutoHandle event_; GTEST_DISALLOW_COPY_AND_ASSIGN_(Notification); }; # endif // GTEST_HAS_NOTIFICATION_ // On MinGW, we can have both GTEST_OS_WINDOWS and GTEST_HAS_PTHREAD // defined, but we don't want to use MinGW's pthreads implementation, which // has conformance problems with some versions of the POSIX standard. # if GTEST_HAS_PTHREAD && !GTEST_OS_WINDOWS_MINGW // As a C-function, ThreadFuncWithCLinkage cannot be templated itself. // Consequently, it cannot select a correct instantiation of ThreadWithParam // in order to call its Run(). Introducing ThreadWithParamBase as a // non-templated base class for ThreadWithParam allows us to bypass this // problem. class ThreadWithParamBase { public: virtual ~ThreadWithParamBase() {} virtual void Run() = 0; }; // pthread_create() accepts a pointer to a function type with the C linkage. // According to the Standard (7.5/1), function types with different linkages // are different even if they are otherwise identical. Some compilers (for // example, SunStudio) treat them as different types. Since class methods // cannot be defined with C-linkage we need to define a free C-function to // pass into pthread_create(). extern "C" inline void* ThreadFuncWithCLinkage(void* thread) { static_cast<ThreadWithParamBase*>(thread)->Run(); return NULL; } // Helper class for testing Google Test's multi-threading constructs. // To use it, write: // // void ThreadFunc(int param) { /* Do things with param */ } // Notification thread_can_start; // ... // // The thread_can_start parameter is optional; you can supply NULL. // ThreadWithParam<int> thread(&ThreadFunc, 5, &thread_can_start); // thread_can_start.Notify(); // // These classes are only for testing Google Test's own constructs. Do // not use them in user tests, either directly or indirectly. template <typename T> class ThreadWithParam : public ThreadWithParamBase { public: typedef void UserThreadFunc(T); ThreadWithParam(UserThreadFunc* func, T param, Notification* thread_can_start) : func_(func), param_(param), thread_can_start_(thread_can_start), finished_(false) { ThreadWithParamBase* const base = this; // The thread can be created only after all fields except thread_ // have been initialized. GTEST_CHECK_POSIX_SUCCESS_( pthread_create(&thread_, 0, &ThreadFuncWithCLinkage, base)); } ~ThreadWithParam() { Join(); } void Join() { if (!finished_) { GTEST_CHECK_POSIX_SUCCESS_(pthread_join(thread_, 0)); finished_ = true; } } virtual void Run() { if (thread_can_start_ != NULL) thread_can_start_->WaitForNotification(); func_(param_); } private: UserThreadFunc* const func_; // User-supplied thread function. const T param_; // User-supplied parameter to the thread function. // When non-NULL, used to block execution until the controller thread // notifies. Notification* const thread_can_start_; bool finished_; // true iff we know that the thread function has finished. pthread_t thread_; // The native thread object. GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParam); }; # endif // !GTEST_OS_WINDOWS && GTEST_HAS_PTHREAD || // GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ # if GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ // Mutex and ThreadLocal have already been imported into the namespace. // Nothing to do here. # elif GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT // Mutex implements mutex on Windows platforms. It is used in conjunction // with class MutexLock: // // Mutex mutex; // ... // MutexLock lock(&mutex); // Acquires the mutex and releases it at the // // end of the current scope. // // A static Mutex *must* be defined or declared using one of the following // macros: // GTEST_DEFINE_STATIC_MUTEX_(g_some_mutex); // GTEST_DECLARE_STATIC_MUTEX_(g_some_mutex); // // (A non-static Mutex is defined/declared in the usual way). class GTEST_API_ Mutex { public: enum MutexType { kStatic = 0, kDynamic = 1 }; // We rely on kStaticMutex being 0 as it is to what the linker initializes // type_ in static mutexes. critical_section_ will be initialized lazily // in ThreadSafeLazyInit(). enum StaticConstructorSelector { kStaticMutex = 0 }; // This constructor intentionally does nothing. It relies on type_ being // statically initialized to 0 (effectively setting it to kStatic) and on // ThreadSafeLazyInit() to lazily initialize the rest of the members. explicit Mutex(StaticConstructorSelector /*dummy*/) {} Mutex(); ~Mutex(); void Lock(); void Unlock(); // Does nothing if the current thread holds the mutex. Otherwise, crashes // with high probability. void AssertHeld(); private: // Initializes owner_thread_id_ and critical_section_ in static mutexes. void ThreadSafeLazyInit(); // Per http://blogs.msdn.com/b/oldnewthing/archive/2004/02/23/78395.aspx, // we assume that 0 is an invalid value for thread IDs. unsigned int owner_thread_id_; // For static mutexes, we rely on these members being initialized to zeros // by the linker. MutexType type_; long critical_section_init_phase_; // NOLINT _RTL_CRITICAL_SECTION* critical_section_; GTEST_DISALLOW_COPY_AND_ASSIGN_(Mutex); }; # define GTEST_DECLARE_STATIC_MUTEX_(mutex) \ extern ::testing::internal::Mutex mutex # define GTEST_DEFINE_STATIC_MUTEX_(mutex) \ ::testing::internal::Mutex mutex(::testing::internal::Mutex::kStaticMutex) // We cannot name this class MutexLock because the ctor declaration would // conflict with a macro named MutexLock, which is defined on some // platforms. That macro is used as a defensive measure to prevent against // inadvertent misuses of MutexLock like "MutexLock(&mu)" rather than // "MutexLock l(&mu)". Hence the typedef trick below. class GTestMutexLock { public: explicit GTestMutexLock(Mutex* mutex) : mutex_(mutex) { mutex_->Lock(); } ~GTestMutexLock() { mutex_->Unlock(); } private: Mutex* const mutex_; GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestMutexLock); }; typedef GTestMutexLock MutexLock; // Base class for ValueHolder<T>. Allows a caller to hold and delete a value // without knowing its type. class ThreadLocalValueHolderBase { public: virtual ~ThreadLocalValueHolderBase() {} }; // Provides a way for a thread to send notifications to a ThreadLocal // regardless of its parameter type. class ThreadLocalBase { public: // Creates a new ValueHolder<T> object holding a default value passed to // this ThreadLocal<T>'s constructor and returns it. It is the caller's // responsibility not to call this when the ThreadLocal<T> instance already // has a value on the current thread. virtual ThreadLocalValueHolderBase* NewValueForCurrentThread() const = 0; protected: ThreadLocalBase() {} virtual ~ThreadLocalBase() {} private: GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocalBase); }; // Maps a thread to a set of ThreadLocals that have values instantiated on that // thread and notifies them when the thread exits. A ThreadLocal instance is // expected to persist until all threads it has values on have terminated. class GTEST_API_ ThreadLocalRegistry { public: // Registers thread_local_instance as having value on the current thread. // Returns a value that can be used to identify the thread from other threads. static ThreadLocalValueHolderBase* GetValueOnCurrentThread( const ThreadLocalBase* thread_local_instance); // Invoked when a ThreadLocal instance is destroyed. static void OnThreadLocalDestroyed( const ThreadLocalBase* thread_local_instance); }; class GTEST_API_ ThreadWithParamBase { public: void Join(); protected: class Runnable { public: virtual ~Runnable() {} virtual void Run() = 0; }; ThreadWithParamBase(Runnable *runnable, Notification* thread_can_start); virtual ~ThreadWithParamBase(); private: AutoHandle thread_; }; // Helper class for testing Google Test's multi-threading constructs. template <typename T> class ThreadWithParam : public ThreadWithParamBase { public: typedef void UserThreadFunc(T); ThreadWithParam(UserThreadFunc* func, T param, Notification* thread_can_start) : ThreadWithParamBase(new RunnableImpl(func, param), thread_can_start) { } virtual ~ThreadWithParam() {} private: class RunnableImpl : public Runnable { public: RunnableImpl(UserThreadFunc* func, T param) : func_(func), param_(param) { } virtual ~RunnableImpl() {} virtual void Run() { func_(param_); } private: UserThreadFunc* const func_; const T param_; GTEST_DISALLOW_COPY_AND_ASSIGN_(RunnableImpl); }; GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParam); }; // Implements thread-local storage on Windows systems. // // // Thread 1 // ThreadLocal<int> tl(100); // 100 is the default value for each thread. // // // Thread 2 // tl.set(150); // Changes the value for thread 2 only. // EXPECT_EQ(150, tl.get()); // // // Thread 1 // EXPECT_EQ(100, tl.get()); // In thread 1, tl has the original value. // tl.set(200); // EXPECT_EQ(200, tl.get()); // // The template type argument T must have a public copy constructor. // In addition, the default ThreadLocal constructor requires T to have // a public default constructor. // // The users of a TheadLocal instance have to make sure that all but one // threads (including the main one) using that instance have exited before // destroying it. Otherwise, the per-thread objects managed for them by the // ThreadLocal instance are not guaranteed to be destroyed on all platforms. // // Google Test only uses global ThreadLocal objects. That means they // will die after main() has returned. Therefore, no per-thread // object managed by Google Test will be leaked as long as all threads // using Google Test have exited when main() returns. template <typename T> class ThreadLocal : public ThreadLocalBase { public: ThreadLocal() : default_factory_(new DefaultValueHolderFactory()) {} explicit ThreadLocal(const T& value) : default_factory_(new InstanceValueHolderFactory(value)) {} ~ThreadLocal() { ThreadLocalRegistry::OnThreadLocalDestroyed(this); } T* pointer() { return GetOrCreateValue(); } const T* pointer() const { return GetOrCreateValue(); } const T& get() const { return *pointer(); } void set(const T& value) { *pointer() = value; } private: // Holds a value of T. Can be deleted via its base class without the caller // knowing the type of T. class ValueHolder : public ThreadLocalValueHolderBase { public: ValueHolder() : value_() {} explicit ValueHolder(const T& value) : value_(value) {} T* pointer() { return &value_; } private: T value_; GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolder); }; T* GetOrCreateValue() const { return static_cast<ValueHolder*>( ThreadLocalRegistry::GetValueOnCurrentThread(this))->pointer(); } virtual ThreadLocalValueHolderBase* NewValueForCurrentThread() const { return default_factory_->MakeNewHolder(); } class ValueHolderFactory { public: ValueHolderFactory() {} virtual ~ValueHolderFactory() {} virtual ValueHolder* MakeNewHolder() const = 0; private: GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolderFactory); }; class DefaultValueHolderFactory : public ValueHolderFactory { public: DefaultValueHolderFactory() {} virtual ValueHolder* MakeNewHolder() const { return new ValueHolder(); } private: GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultValueHolderFactory); }; class InstanceValueHolderFactory : public ValueHolderFactory { public: explicit InstanceValueHolderFactory(const T& value) : value_(value) {} virtual ValueHolder* MakeNewHolder() const { return new ValueHolder(value_); } private: const T value_; // The value for each thread. GTEST_DISALLOW_COPY_AND_ASSIGN_(InstanceValueHolderFactory); }; scoped_ptr<ValueHolderFactory> default_factory_; GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocal); }; # elif GTEST_HAS_PTHREAD // MutexBase and Mutex implement mutex on pthreads-based platforms. class MutexBase { public: // Acquires this mutex. void Lock() { GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_lock(&mutex_)); owner_ = pthread_self(); has_owner_ = true; } // Releases this mutex. void Unlock() { // Since the lock is being released the owner_ field should no longer be // considered valid. We don't protect writing to has_owner_ here, as it's // the caller's responsibility to ensure that the current thread holds the // mutex when this is called. has_owner_ = false; GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_unlock(&mutex_)); } // Does nothing if the current thread holds the mutex. Otherwise, crashes // with high probability. void AssertHeld() const { GTEST_CHECK_(has_owner_ && pthread_equal(owner_, pthread_self())) << "The current thread is not holding the mutex @" << this; } // A static mutex may be used before main() is entered. It may even // be used before the dynamic initialization stage. Therefore we // must be able to initialize a static mutex object at link time. // This means MutexBase has to be a POD and its member variables // have to be public. public: pthread_mutex_t mutex_; // The underlying pthread mutex. // has_owner_ indicates whether the owner_ field below contains a valid thread // ID and is therefore safe to inspect (e.g., to use in pthread_equal()). All // accesses to the owner_ field should be protected by a check of this field. // An alternative might be to memset() owner_ to all zeros, but there's no // guarantee that a zero'd pthread_t is necessarily invalid or even different // from pthread_self(). bool has_owner_; pthread_t owner_; // The thread holding the mutex. }; // Forward-declares a static mutex. # define GTEST_DECLARE_STATIC_MUTEX_(mutex) \ extern ::testing::internal::MutexBase mutex // Defines and statically (i.e. at link time) initializes a static mutex. // The initialization list here does not explicitly initialize each field, // instead relying on default initialization for the unspecified fields. In // particular, the owner_ field (a pthread_t) is not explicitly initialized. // This allows initialization to work whether pthread_t is a scalar or struct. // The flag -Wmissing-field-initializers must not be specified for this to work. # define GTEST_DEFINE_STATIC_MUTEX_(mutex) \ ::testing::internal::MutexBase mutex = { PTHREAD_MUTEX_INITIALIZER, false } // The Mutex class can only be used for mutexes created at runtime. It // shares its API with MutexBase otherwise. class Mutex : public MutexBase { public: Mutex() { GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_init(&mutex_, NULL)); has_owner_ = false; } ~Mutex() { GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_destroy(&mutex_)); } private: GTEST_DISALLOW_COPY_AND_ASSIGN_(Mutex); }; // We cannot name this class MutexLock because the ctor declaration would // conflict with a macro named MutexLock, which is defined on some // platforms. That macro is used as a defensive measure to prevent against // inadvertent misuses of MutexLock like "MutexLock(&mu)" rather than // "MutexLock l(&mu)". Hence the typedef trick below. class GTestMutexLock { public: explicit GTestMutexLock(MutexBase* mutex) : mutex_(mutex) { mutex_->Lock(); } ~GTestMutexLock() { mutex_->Unlock(); } private: MutexBase* const mutex_; GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestMutexLock); }; typedef GTestMutexLock MutexLock; // Helpers for ThreadLocal. // pthread_key_create() requires DeleteThreadLocalValue() to have // C-linkage. Therefore it cannot be templatized to access // ThreadLocal<T>. Hence the need for class // ThreadLocalValueHolderBase. class ThreadLocalValueHolderBase { public: virtual ~ThreadLocalValueHolderBase() {} }; // Called by pthread to delete thread-local data stored by // pthread_setspecific(). extern "C" inline void DeleteThreadLocalValue(void* value_holder) { delete static_cast<ThreadLocalValueHolderBase*>(value_holder); } // Implements thread-local storage on pthreads-based systems. template <typename T> class ThreadLocal { public: ThreadLocal() : key_(CreateKey()), default_factory_(new DefaultValueHolderFactory()) {} explicit ThreadLocal(const T& value) : key_(CreateKey()), default_factory_(new InstanceValueHolderFactory(value)) {} ~ThreadLocal() { // Destroys the managed object for the current thread, if any. DeleteThreadLocalValue(pthread_getspecific(key_)); // Releases resources associated with the key. This will *not* // delete managed objects for other threads. GTEST_CHECK_POSIX_SUCCESS_(pthread_key_delete(key_)); } T* pointer() { return GetOrCreateValue(); } const T* pointer() const { return GetOrCreateValue(); } const T& get() const { return *pointer(); } void set(const T& value) { *pointer() = value; } private: // Holds a value of type T. class ValueHolder : public ThreadLocalValueHolderBase { public: ValueHolder() : value_() {} explicit ValueHolder(const T& value) : value_(value) {} T* pointer() { return &value_; } private: T value_; GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolder); }; static pthread_key_t CreateKey() { pthread_key_t key; // When a thread exits, DeleteThreadLocalValue() will be called on // the object managed for that thread. GTEST_CHECK_POSIX_SUCCESS_( pthread_key_create(&key, &DeleteThreadLocalValue)); return key; } T* GetOrCreateValue() const { ThreadLocalValueHolderBase* const holder = static_cast<ThreadLocalValueHolderBase*>(pthread_getspecific(key_)); if (holder != NULL) { return CheckedDowncastToActualType<ValueHolder>(holder)->pointer(); } ValueHolder* const new_holder = default_factory_->MakeNewHolder(); ThreadLocalValueHolderBase* const holder_base = new_holder; GTEST_CHECK_POSIX_SUCCESS_(pthread_setspecific(key_, holder_base)); return new_holder->pointer(); } class ValueHolderFactory { public: ValueHolderFactory() {} virtual ~ValueHolderFactory() {} virtual ValueHolder* MakeNewHolder() const = 0; private: GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolderFactory); }; class DefaultValueHolderFactory : public ValueHolderFactory { public: DefaultValueHolderFactory() {} virtual ValueHolder* MakeNewHolder() const { return new ValueHolder(); } private: GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultValueHolderFactory); }; class InstanceValueHolderFactory : public ValueHolderFactory { public: explicit InstanceValueHolderFactory(const T& value) : value_(value) {} virtual ValueHolder* MakeNewHolder() const { return new ValueHolder(value_); } private: const T value_; // The value for each thread. GTEST_DISALLOW_COPY_AND_ASSIGN_(InstanceValueHolderFactory); }; // A key pthreads uses for looking up per-thread values. const pthread_key_t key_; scoped_ptr<ValueHolderFactory> default_factory_; GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocal); }; # endif // GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ #else // GTEST_IS_THREADSAFE // A dummy implementation of synchronization primitives (mutex, lock, // and thread-local variable). Necessary for compiling Google Test where // mutex is not supported - using Google Test in multiple threads is not // supported on such platforms. class Mutex { public: Mutex() {} void Lock() {} void Unlock() {} void AssertHeld() const {} }; # define GTEST_DECLARE_STATIC_MUTEX_(mutex) \ extern ::testing::internal::Mutex mutex # define GTEST_DEFINE_STATIC_MUTEX_(mutex) ::testing::internal::Mutex mutex // We cannot name this class MutexLock because the ctor declaration would // conflict with a macro named MutexLock, which is defined on some // platforms. That macro is used as a defensive measure to prevent against // inadvertent misuses of MutexLock like "MutexLock(&mu)" rather than // "MutexLock l(&mu)". Hence the typedef trick below. class GTestMutexLock { public: explicit GTestMutexLock(Mutex*) {} // NOLINT }; typedef GTestMutexLock MutexLock; template <typename T> class ThreadLocal { public: ThreadLocal() : value_() {} explicit ThreadLocal(const T& value) : value_(value) {} T* pointer() { return &value_; } const T* pointer() const { return &value_; } const T& get() const { return value_; } void set(const T& value) { value_ = value; } private: T value_; }; #endif // GTEST_IS_THREADSAFE // Returns the number of threads running in the process, or 0 to indicate that // we cannot detect it. GTEST_API_ size_t GetThreadCount(); // Passing non-POD classes through ellipsis (...) crashes the ARM // compiler and generates a warning in Sun Studio. The Nokia Symbian // and the IBM XL C/C++ compiler try to instantiate a copy constructor // for objects passed through ellipsis (...), failing for uncopyable // objects. We define this to ensure that only POD is passed through // ellipsis on these systems. #if defined(__SYMBIAN32__) || defined(__IBMCPP__) || defined(__SUNPRO_CC) // We lose support for NULL detection where the compiler doesn't like // passing non-POD classes through ellipsis (...). # define GTEST_ELLIPSIS_NEEDS_POD_ 1 #else # define GTEST_CAN_COMPARE_NULL 1 #endif // The Nokia Symbian and IBM XL C/C++ compilers cannot decide between // const T& and const T* in a function template. These compilers // _can_ decide between class template specializations for T and T*, // so a tr1::type_traits-like is_pointer works. #if defined(__SYMBIAN32__) || defined(__IBMCPP__) # define GTEST_NEEDS_IS_POINTER_ 1 #endif template <bool bool_value> struct bool_constant { typedef bool_constant<bool_value> type; static const bool value = bool_value; }; template <bool bool_value> const bool bool_constant<bool_value>::value; typedef bool_constant<false> false_type; typedef bool_constant<true> true_type; template <typename T> struct is_pointer : public false_type {}; template <typename T> struct is_pointer<T*> : public true_type {}; template <typename Iterator> struct IteratorTraits { typedef typename Iterator::value_type value_type; }; template <typename T> struct IteratorTraits<T*> { typedef T value_type; }; template <typename T> struct IteratorTraits<const T*> { typedef T value_type; }; #if GTEST_OS_WINDOWS # define GTEST_PATH_SEP_ "\\" # define GTEST_HAS_ALT_PATH_SEP_ 1 // The biggest signed integer type the compiler supports. typedef __int64 BiggestInt; #else # define GTEST_PATH_SEP_ "/" # define GTEST_HAS_ALT_PATH_SEP_ 0 typedef long long BiggestInt; // NOLINT #endif // GTEST_OS_WINDOWS // Utilities for char. // isspace(int ch) and friends accept an unsigned char or EOF. char // may be signed, depending on the compiler (or compiler flags). // Therefore we need to cast a char to unsigned char before calling // isspace(), etc. inline bool IsAlpha(char ch) { return isalpha(static_cast<unsigned char>(ch)) != 0; } inline bool IsAlNum(char ch) { return isalnum(static_cast<unsigned char>(ch)) != 0; } inline bool IsDigit(char ch) { return isdigit(static_cast<unsigned char>(ch)) != 0; } inline bool IsLower(char ch) { return islower(static_cast<unsigned char>(ch)) != 0; } inline bool IsSpace(char ch) { return isspace(static_cast<unsigned char>(ch)) != 0; } inline bool IsUpper(char ch) { return isupper(static_cast<unsigned char>(ch)) != 0; } inline bool IsXDigit(char ch) { return isxdigit(static_cast<unsigned char>(ch)) != 0; } inline bool IsXDigit(wchar_t ch) { const unsigned char low_byte = static_cast<unsigned char>(ch); return ch == low_byte && isxdigit(low_byte) != 0; } inline char ToLower(char ch) { return static_cast<char>(tolower(static_cast<unsigned char>(ch))); } inline char ToUpper(char ch) { return static_cast<char>(toupper(static_cast<unsigned char>(ch))); } inline std::string StripTrailingSpaces(std::string str) { std::string::iterator it = str.end(); while (it != str.begin() && IsSpace(*--it)) it = str.erase(it); return str; } // The testing::internal::posix namespace holds wrappers for common // POSIX functions. These wrappers hide the differences between // Windows/MSVC and POSIX systems. Since some compilers define these // standard functions as macros, the wrapper cannot have the same name // as the wrapped function. namespace posix { // Functions with a different name on Windows. #if GTEST_OS_WINDOWS typedef struct _stat StatStruct; # ifdef __BORLANDC__ inline int IsATTY(int fd) { return isatty(fd); } inline int StrCaseCmp(const char* s1, const char* s2) { return stricmp(s1, s2); } inline char* StrDup(const char* src) { return strdup(src); } # else // !__BORLANDC__ # if GTEST_OS_WINDOWS_MOBILE inline int IsATTY(int /* fd */) { return 0; } # else inline int IsATTY(int fd) { return _isatty(fd); } # endif // GTEST_OS_WINDOWS_MOBILE inline int StrCaseCmp(const char* s1, const char* s2) { return _stricmp(s1, s2); } inline char* StrDup(const char* src) { return _strdup(src); } # endif // __BORLANDC__ # if GTEST_OS_WINDOWS_MOBILE inline int FileNo(FILE* file) { return reinterpret_cast<int>(_fileno(file)); } // Stat(), RmDir(), and IsDir() are not needed on Windows CE at this // time and thus not defined there. # else inline int FileNo(FILE* file) { return _fileno(file); } inline int Stat(const char* path, StatStruct* buf) { return _stat(path, buf); } inline int RmDir(const char* dir) { return _rmdir(dir); } inline bool IsDir(const StatStruct& st) { return (_S_IFDIR & st.st_mode) != 0; } # endif // GTEST_OS_WINDOWS_MOBILE #else typedef struct stat StatStruct; inline int FileNo(FILE* file) { return fileno(file); } inline int IsATTY(int fd) { return isatty(fd); } inline int Stat(const char* path, StatStruct* buf) { return stat(path, buf); } inline int StrCaseCmp(const char* s1, const char* s2) { return strcasecmp(s1, s2); } inline char* StrDup(const char* src) { return strdup(src); } inline int RmDir(const char* dir) { return rmdir(dir); } inline bool IsDir(const StatStruct& st) { return S_ISDIR(st.st_mode); } #endif // GTEST_OS_WINDOWS // Functions deprecated by MSVC 8.0. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996 /* deprecated function */) inline const char* StrNCpy(char* dest, const char* src, size_t n) { return strncpy(dest, src, n); } // ChDir(), FReopen(), FDOpen(), Read(), Write(), Close(), and // StrError() aren't needed on Windows CE at this time and thus not // defined there. #if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT inline int ChDir(const char* dir) { return chdir(dir); } #endif inline FILE* FOpen(const char* path, const char* mode) { return fopen(path, mode); } #if !GTEST_OS_WINDOWS_MOBILE inline FILE *FReopen(const char* path, const char* mode, FILE* stream) { return freopen(path, mode, stream); } inline FILE* FDOpen(int fd, const char* mode) { return fdopen(fd, mode); } #endif inline int FClose(FILE* fp) { return fclose(fp); } #if !GTEST_OS_WINDOWS_MOBILE inline int Read(int fd, void* buf, unsigned int count) { return static_cast<int>(read(fd, buf, count)); } inline int Write(int fd, const void* buf, unsigned int count) { return static_cast<int>(write(fd, buf, count)); } inline int Close(int fd) { return close(fd); } inline const char* StrError(int errnum) { return strerror(errnum); } #endif inline const char* GetEnv(const char* name) { #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE | GTEST_OS_WINDOWS_RT // We are on Windows CE, which has no environment variables. static_cast<void>(name); // To prevent 'unused argument' warning. return NULL; #elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9) // Environment variables which we programmatically clear will be set to the // empty string rather than unset (NULL). Handle that case. const char* const env = getenv(name); return (env != NULL && env[0] != '\0') ? env : NULL; #else return getenv(name); #endif } GTEST_DISABLE_MSC_WARNINGS_POP_() #if GTEST_OS_WINDOWS_MOBILE // Windows CE has no C library. The abort() function is used in // several places in Google Test. This implementation provides a reasonable // imitation of standard behaviour. void Abort(); #else inline void Abort() { abort(); } #endif // GTEST_OS_WINDOWS_MOBILE } // namespace posix // MSVC "deprecates" snprintf and issues warnings wherever it is used. In // order to avoid these warnings, we need to use _snprintf or _snprintf_s on // MSVC-based platforms. We map the GTEST_SNPRINTF_ macro to the appropriate // function in order to achieve that. We use macro definition here because // snprintf is a variadic function. #if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE // MSVC 2005 and above support variadic macros. # define GTEST_SNPRINTF_(buffer, size, format, ...) \ _snprintf_s(buffer, size, size, format, __VA_ARGS__) #elif defined(_MSC_VER) // Windows CE does not define _snprintf_s and MSVC prior to 2005 doesn't // complain about _snprintf. # define GTEST_SNPRINTF_ _snprintf #else # define GTEST_SNPRINTF_ snprintf #endif // The maximum number a BiggestInt can represent. This definition // works no matter BiggestInt is represented in one's complement or // two's complement. // // We cannot rely on numeric_limits in STL, as __int64 and long long // are not part of standard C++ and numeric_limits doesn't need to be // defined for them. const BiggestInt kMaxBiggestInt = ~(static_cast<BiggestInt>(1) << (8*sizeof(BiggestInt) - 1)); // This template class serves as a compile-time function from size to // type. It maps a size in bytes to a primitive type with that // size. e.g. // // TypeWithSize<4>::UInt // // is typedef-ed to be unsigned int (unsigned integer made up of 4 // bytes). // // Such functionality should belong to STL, but I cannot find it // there. // // Google Test uses this class in the implementation of floating-point // comparison. // // For now it only handles UInt (unsigned int) as that's all Google Test // needs. Other types can be easily added in the future if need // arises. template <size_t size> class TypeWithSize { public: // This prevents the user from using TypeWithSize<N> with incorrect // values of N. typedef void UInt; }; // The specialization for size 4. template <> class TypeWithSize<4> { public: // unsigned int has size 4 in both gcc and MSVC. // // As base/basictypes.h doesn't compile on Windows, we cannot use // uint32, uint64, and etc here. typedef int Int; typedef unsigned int UInt; }; // The specialization for size 8. template <> class TypeWithSize<8> { public: #if GTEST_OS_WINDOWS typedef __int64 Int; typedef unsigned __int64 UInt; #else typedef long long Int; // NOLINT typedef unsigned long long UInt; // NOLINT #endif // GTEST_OS_WINDOWS }; // Integer types of known sizes. typedef TypeWithSize<4>::Int Int32; typedef TypeWithSize<4>::UInt UInt32; typedef TypeWithSize<8>::Int Int64; typedef TypeWithSize<8>::UInt UInt64; typedef TypeWithSize<8>::Int TimeInMillis; // Represents time in milliseconds. // Utilities for command line flags and environment variables. // Macro for referencing flags. #if !defined(GTEST_FLAG) # define GTEST_FLAG(name) FLAGS_gtest_##name #endif // !defined(GTEST_FLAG) #if !defined(GTEST_USE_OWN_FLAGFILE_FLAG_) # define GTEST_USE_OWN_FLAGFILE_FLAG_ 1 #endif // !defined(GTEST_USE_OWN_FLAGFILE_FLAG_) #if !defined(GTEST_DECLARE_bool_) # define GTEST_FLAG_SAVER_ ::testing::internal::GTestFlagSaver // Macros for declaring flags. # define GTEST_DECLARE_bool_(name) GTEST_API_ extern bool GTEST_FLAG(name) # define GTEST_DECLARE_int32_(name) \ GTEST_API_ extern ::testing::internal::Int32 GTEST_FLAG(name) #define GTEST_DECLARE_string_(name) \ GTEST_API_ extern ::std::string GTEST_FLAG(name) // Macros for defining flags. #define GTEST_DEFINE_bool_(name, default_val, doc) \ GTEST_API_ bool GTEST_FLAG(name) = (default_val) #define GTEST_DEFINE_int32_(name, default_val, doc) \ GTEST_API_ ::testing::internal::Int32 GTEST_FLAG(name) = (default_val) #define GTEST_DEFINE_string_(name, default_val, doc) \ GTEST_API_ ::std::string GTEST_FLAG(name) = (default_val) #endif // !defined(GTEST_DECLARE_bool_) // Thread annotations #if !defined(GTEST_EXCLUSIVE_LOCK_REQUIRED_) # define GTEST_EXCLUSIVE_LOCK_REQUIRED_(locks) # define GTEST_LOCK_EXCLUDED_(locks) #endif // !defined(GTEST_EXCLUSIVE_LOCK_REQUIRED_) // Parses 'str' for a 32-bit signed integer. If successful, writes the result // to *value and returns true; otherwise leaves *value unchanged and returns // false. // TODO(chandlerc): Find a better way to refactor flag and environment parsing // out of both gtest-port.cc and gtest.cc to avoid exporting this utility // function. bool ParseInt32(const Message& src_text, const char* str, Int32* value); // Parses a bool/Int32/string from the environment variable // corresponding to the given Google Test flag. bool BoolFromGTestEnv(const char* flag, bool default_val); GTEST_API_ Int32 Int32FromGTestEnv(const char* flag, Int32 default_val); const char* StringFromGTestEnv(const char* flag, const char* default_val); } // namespace internal } // namespace testing #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_
Abce/googletest
include/gtest/internal/gtest-port.h
C
bsd-3-clause
90,042
<?php /** * Contains classes for constructing an xml sitemap * * @author Nate Levesque <[email protected]> * @copyright Nate Levesque 2013 * * Language: PHP * Filename: core_sitemap.php * */ /** * Include classes and functions from core_web */ include_once NWEB_ROOT.'/lib/core_web.php'; include NWEB_ROOT.'/Content/Generators/Sitemap/HtmlSitemap.php'; include NWEB_ROOT.'/Content/Generators/Sitemap/XmlSitemap.php';
thenaterhood/thenaterweb
Naterweb/lib/core_sitemap.php
PHP
bsd-3-clause
442
var classIoss_1_1StorageInitializer = [ [ "StorageInitializer", "classIoss_1_1StorageInitializer.html#aef4b840a666fb10d76e989963fce76a7", null ] ];
nschloe/seacas
docs/ioss_html/classIoss_1_1StorageInitializer.js
JavaScript
bsd-3-clause
151
package edu.ucdenver.ccp.datasource.fileparsers.ncbi.gene; /* * #%L * Colorado Computational Pharmacology's common module * %% * Copyright (C) 2012 - 2015 Regents of the University of Colorado * %% * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the Regents of the University of Colorado 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 HOLDER 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. * #L% */ import lombok.Data; import org.apache.log4j.Logger; import edu.ucdenver.ccp.common.file.reader.Line; import edu.ucdenver.ccp.datasource.fileparsers.License; import edu.ucdenver.ccp.datasource.fileparsers.Record; import edu.ucdenver.ccp.datasource.fileparsers.RecordField; import edu.ucdenver.ccp.datasource.fileparsers.SingleLineFileRecord; import edu.ucdenver.ccp.datasource.identifiers.DataSource; import edu.ucdenver.ccp.datasource.identifiers.ncbi.gene.EntrezGeneID; import edu.ucdenver.ccp.datasource.identifiers.ncbi.gene.GiNumberID; import edu.ucdenver.ccp.datasource.identifiers.ncbi.refseq.RefSeqID; import edu.ucdenver.ccp.datasource.identifiers.ncbi.taxonomy.NcbiTaxonomyID; /** * This class represents data contained in the EntrezGene gene2accession file. * * @author Bill Baumgartner * */ @Record(dataSource = DataSource.EG, comment = "", license = License.NCBI, citation = "The NCBI handbook [Internet]. Bethesda (MD): National Library of Medicine (US), National Center for Biotechnology Information; 2002 Oct. Chapter 19 Gene: A Directory of Genes. Available from http://www.ncbi.nlm.nih.gov/books/NBK21091", label = "gene2refseq record") @Data public class EntrezGene2RefseqFileData extends SingleLineFileRecord { public static final String RECORD_NAME_PREFIX = "ENTREZ_GENE2ACCESSION_RECORD_"; /* * #Format: tax_id GeneID status RNA_nucleotide_accession.version RNA_nucleotide_gi * protein_accession.version protein_gi genomic_nucleotide_accession.version * genomic_nucleotide_gi start_position_on_the_genomic_accession * end_position_on_the_genomic_accession orientation assembly (tab is used as a separator, pound * sign - start of a comment) */ @RecordField(comment = "the unique identifier provided by NCBI Taxonomy for the species or strain/isolate") private final NcbiTaxonomyID taxonID; @RecordField(comment = "the unique identifier for a gene") private final EntrezGeneID geneID; @RecordField(comment = "status of the RefSeq. values are: INFERRED, MODEL, NA, PREDICTED, PROVISIONAL, REVIEWED, SUPPRESSED, VALIDATED") private final String status; @RecordField(comment = "may be null (-) for some genomes") private final RefSeqID RNA_nucleotide_accession_dot_version; @RecordField(comment = "the gi for an RNA nucleotide accession, '-' if not applicable") private final GiNumberID RNA_nucleotide_gi; @RecordField(comment = "will be null (-) for RNA-coding genes") private final RefSeqID protein_accession_dot_version; @RecordField(comment = "the gi for a protein accession, '-' if not applicable") private final GiNumberID protein_gi; @RecordField(comment = "may be null (-) if a RefSeq was provided after the genomic accession was submitted") private final RefSeqID genomic_nucleotide_accession_dot_version; @RecordField(comment = "the gi for a genomic nucleotide accession, '-' if not applicable") private final GiNumberID genomic_nucleotide_gi; @RecordField(comment = "position of the gene feature on the genomic accession, '-' if not applicable position 0-based. NOTE: this file does not report the position of each exon for positions on RefSeq contigs and chromosomes, use the seq_gene.md file in the desired build directory. For example, for human at the time this was written: /am/ftp-genomes/H_sapiens/maps/mapview/BUILD.35.1 WARNING: positions in these files are one-based, not 0-based NOTE: if genes are merged after an annotation is released, there may be more than one location reported on a genomic sequence per GeneID, each resulting from the annotation before the merge.") private final Integer start_position_on_the_genomic_accession; @RecordField(comment = "position of the gene feature on the genomic accession, '-' if not applicable position 0-based NOTE: this file does not report the position of each exon for positions on RefSeq contigs and chromosomes, use the seq_gene.md file in the desired build directory. For example, for human at the time this was written: /am/ftp-genomes/H_sapiens/maps/mapview/BUILD.35.1 WARNING: positions in these files are one-based, not 0-based NOTE: if genes are merged after an annotation is released, there may be more than one location reported on a genomic sequence per GeneID, each resulting from the annotation before the merge.") private final Integer end_position_on_the_genomic_accession; @RecordField(comment = "orientation of the gene feature on the genomic accession, '?' if not applicable") private final char orientation; @RecordField(comment = "the name of the assembly '-' if not applicable") private final String assembly; @RecordField private final RefSeqID mature_peptide_accession_dot_version; @RecordField private final GiNumberID mature_peptide_gi; @RecordField private final String symbol; public EntrezGene2RefseqFileData(NcbiTaxonomyID taxonID, EntrezGeneID geneID, String status, RefSeqID rNANucleotideAccessionDotVersion, GiNumberID rNANucleotideGi, RefSeqID proteinAccessionDotVersion, GiNumberID proteinGi, RefSeqID genomicNucleotideAccessionDotVersion, GiNumberID genomicNucleotideGi, Integer startPositionOnTheGenomicAccession, Integer endPositionOnTheGenomicAccession, char orientation, String assembly, RefSeqID mature_peptide_accession_dot_version, GiNumberID mature_peptide_gi, String symbol, long byteOffset, long lineNumber) { super(byteOffset, lineNumber); this.taxonID = taxonID; this.geneID = geneID; this.status = status; RNA_nucleotide_accession_dot_version = rNANucleotideAccessionDotVersion; RNA_nucleotide_gi = rNANucleotideGi; protein_accession_dot_version = proteinAccessionDotVersion; protein_gi = proteinGi; genomic_nucleotide_accession_dot_version = genomicNucleotideAccessionDotVersion; genomic_nucleotide_gi = genomicNucleotideGi; start_position_on_the_genomic_accession = startPositionOnTheGenomicAccession; end_position_on_the_genomic_accession = endPositionOnTheGenomicAccession; this.orientation = orientation; this.assembly = assembly; this.mature_peptide_accession_dot_version = mature_peptide_accession_dot_version; this.mature_peptide_gi = mature_peptide_gi; this.symbol = symbol; } /** * Parse a line from the EntrezGene gene2accession file * * @param line * @return */ public static EntrezGene2RefseqFileData parseGene2AccessionLine(Line line) { if (!line.getText().startsWith("#")) { String[] toks = line.getText().split("\\t", -1); Logger logger = Logger.getLogger(EntrezGene2RefseqFileData.class); if (toks.length != 16) { logger.error("Unexpected number of tokens (" + toks.length + ") on line:" + line.getText().replaceAll("\\t", " [TAB] ")); return null; } NcbiTaxonomyID taxonID = new NcbiTaxonomyID(toks[0]); EntrezGeneID geneID = new EntrezGeneID(toks[1]); String status = toks[2]; if (status.equals("-")) { status = null; } RefSeqID RNA_nucleotide_accession_dot_version = null; if (!toks[3].equals("-") && status != null) { RNA_nucleotide_accession_dot_version = new RefSeqID(toks[3]); } String intStr = toks[4]; GiNumberID RNA_nucleotide_gi = null; if (!intStr.equals("-")) { RNA_nucleotide_gi = new GiNumberID(intStr); } RefSeqID protein_accession_dot_version = null; if (!toks[5].equals("-") && status != null) { protein_accession_dot_version = new RefSeqID(toks[5]); } intStr = toks[6]; GiNumberID protein_gi = null; if (!intStr.equals("-")) { protein_gi = new GiNumberID(intStr); } RefSeqID genomic_nucleotide_accession_dot_version = null; if (!toks[7].equals("-") && status != null) { genomic_nucleotide_accession_dot_version = new RefSeqID(toks[7]); } intStr = toks[8]; GiNumberID genomic_nucleotide_gi = null; if (!intStr.equals("-")) { genomic_nucleotide_gi = new GiNumberID(intStr); } intStr = toks[9]; Integer start_position_on_the_genomic_accession; if (intStr.equals("-")) { start_position_on_the_genomic_accession = null; } else { start_position_on_the_genomic_accession = new Integer(intStr); } intStr = toks[10]; Integer end_position_on_the_genomic_accession; if (intStr.equals("-")) { end_position_on_the_genomic_accession = null; } else { end_position_on_the_genomic_accession = new Integer(intStr); } if (toks[11].trim().length() > 1) { logger.error("Expected a single character for the orientation on line: " + line); return null; } char orientation = toks[11].trim().charAt(0); String assembly = toks[12]; if (assembly.equals("-")) { assembly = null; } RefSeqID mature_peptide_accession_dot_version = null; if (!toks[13].equals("-") && status != null) { mature_peptide_accession_dot_version = new RefSeqID(toks[13]); } intStr = toks[14]; GiNumberID mature_peptide_gi = null; if (!intStr.equals("-")) { mature_peptide_gi = new GiNumberID(intStr); } String symbol = null; if (!toks[15].equals("-")) { symbol = toks[15]; } return new EntrezGene2RefseqFileData(taxonID, geneID, status, RNA_nucleotide_accession_dot_version, RNA_nucleotide_gi, protein_accession_dot_version, protein_gi, genomic_nucleotide_accession_dot_version, genomic_nucleotide_gi, start_position_on_the_genomic_accession, end_position_on_the_genomic_accession, orientation, assembly, mature_peptide_accession_dot_version, mature_peptide_gi, symbol, line.getByteOffset(), line.getLineNumber()); } return null; } }
bill-baumgartner/datasource
datasource-fileparsers/src/main/java/edu/ucdenver/ccp/datasource/fileparsers/ncbi/gene/EntrezGene2RefseqFileData.java
Java
bsd-3-clause
11,245
# -*- coding: utf-8 -*- """ Splash can send outgoing network requests through an HTTP proxy server. This modules provides classes ("proxy factories") which define which proxies to use for a given request. QNetworkManager calls a proxy factory for each outgoing request. Not to be confused with Splash Proxy mode when Splash itself works as an HTTP proxy (see :mod:`splash.proxy_server`). """ from __future__ import absolute_import import re import os import ConfigParser from PyQt4.QtNetwork import QNetworkProxy from splash.render_options import BadOption from splash.qtutils import create_proxy, validate_proxy_type class _BlackWhiteSplashProxyFactory(object): """ Proxy factory that enables non-default proxy list when requested URL is matched by one of whitelist patterns while not being matched by one of the blacklist patterns. """ def __init__(self, blacklist=None, whitelist=None, proxy_list=None): self.blacklist = blacklist or [] self.whitelist = whitelist or [] self.proxy_list = proxy_list or [] def queryProxy(self, query=None, *args, **kwargs): protocol = unicode(query.protocolTag()) url = unicode(query.url().toString()) if self.shouldUseProxyList(protocol, url): return self._customProxyList() return self._defaultProxyList() def shouldUseProxyList(self, protocol, url): if not self.proxy_list: return False if protocol not in ('http', 'https'): # don't try to proxy unknown protocols return False if any(re.match(p, url) for p in self.blacklist): return False if any(re.match(p, url) for p in self.whitelist): return True return not bool(self.whitelist) def _defaultProxyList(self): return [QNetworkProxy(QNetworkProxy.DefaultProxy)] def _customProxyList(self): return [ create_proxy(host, port, username, password, type) for host, port, username, password,type in self.proxy_list ] class ProfilesSplashProxyFactory(_BlackWhiteSplashProxyFactory): """ This proxy factory reads BlackWhiteQNetworkProxyFactory parameters from ini file; name of the profile can be set per-request using GET parameter. Example config file for 'mywebsite' proxy profile:: ; /etc/splash/proxy-profiles/mywebsite.ini [proxy] host=proxy.crawlera.com port=8010 username=username password=password type=HTTP [rules] whitelist= .*mywebsite\.com.* blacklist= .*\.js.* .*\.css.* .*\.png If there is ``default.ini`` proxy profile in profiles folder it will be used when no profile is specified in GET parameter. If GET parameter is 'none' or empty ('') no proxy will be used even if ``default.ini`` is present. """ NO_PROXY_PROFILE_MSG = 'Proxy profile does not exist' def __init__(self, proxy_profiles_path, profile_name): self.proxy_profiles_path = proxy_profiles_path blacklist, whitelist, proxy_list = self._getFilterParams(profile_name) super(ProfilesSplashProxyFactory, self).__init__(blacklist, whitelist, proxy_list) def _getFilterParams(self, profile_name=None): """ Return (blacklist, whitelist, proxy_list) tuple loaded from profile ``profile_name``. """ if profile_name is None: profile_name = 'default' ini_path = self._getIniPath(profile_name) if not os.path.isfile(ini_path): profile_name = 'none' if profile_name == 'none': return [], [], [] ini_path = self._getIniPath(profile_name) return self._parseIni(ini_path) def _getIniPath(self, profile_name): proxy_profiles_path = os.path.abspath(self.proxy_profiles_path) filename = profile_name + '.ini' ini_path = os.path.abspath(os.path.join(proxy_profiles_path, filename)) if not ini_path.startswith(proxy_profiles_path + os.path.sep): # security check fails raise BadOption(self.NO_PROXY_PROFILE_MSG) else: return ini_path def _parseIni(self, ini_path): parser = ConfigParser.ConfigParser(allow_no_value=True) if not parser.read(ini_path): raise BadOption(self.NO_PROXY_PROFILE_MSG) blacklist = _get_lines(parser, 'rules', 'blacklist', []) whitelist = _get_lines(parser, 'rules', 'whitelist', []) try: proxy = dict(parser.items('proxy')) except ConfigParser.NoSectionError: raise BadOption("Invalid proxy profile: no [proxy] section found") try: host = proxy['host'] except KeyError: raise BadOption("Invalid proxy profile: [proxy] host is not found") try: port = int(proxy['port']) except KeyError: raise BadOption("Invalid proxy profile: [proxy] port is not found") except ValueError: raise BadOption("Invalid proxy profile: [proxy] port is incorrect") if 'type' in proxy: validate_proxy_type(proxy['type']) proxy_list = [(host, port, proxy.get('username'), proxy.get('password'), proxy.get('type'))] return blacklist, whitelist, proxy_list def _get_lines(config_parser, section, option, default): try: lines = config_parser.get(section, option).splitlines() return [line for line in lines if line] except (ConfigParser.NoOptionError, ConfigParser.NoSectionError): return default
kod3r/splash
splash/proxy.py
Python
bsd-3-clause
5,738
<?php use yii\helpers\Url; $this->title = $kit->info->name; ?> <!-- PAGE --> <section id="page" class="page page__kit"> <div class="page__inner"> <!-- breadcrumbs --> <div class="breadcrumbs is-slideInLeft is-animated"> <ol class="breadcrumbs__list"> <li class="breadcrumbs__item" itemscope="" itemtype="http://data-vocabulary.org/Breadcrumb"> <a href="<?= Url::to(['/']) ?>" class="breadcrumbs__link" itemprop="url"> <span itemprop="title"><?= Yii::t('app','main') ?></span> </a> </li> <li class="breadcrumbs__item" itemscope="" itemtype="http://data-vocabulary.org/Breadcrumb"> <a href="<?= Url::to(['/services']) ?>" class="breadcrumbs__link" itemprop="url"> <span itemprop="title"><?= Yii::t('app','services') ?></span> </a> </li> <li class="breadcrumbs__item" itemscope="" itemtype="http://data-vocabulary.org/Breadcrumb"> <a href="<?= Url::to(['/equipment']) ?>" class="breadcrumbs__link" itemprop="url"> <span itemprop="title"><?= Yii::t('app','equipment_and_furniture') ?></span> </a> </li> <li class="breadcrumbs__item" itemscope="" itemtype="http://data-vocabulary.org/Breadcrumb"> <a href="<?= Url::to(["/equipment/{$category->alias}"]) ?>" class="breadcrumbs__link" itemprop="url"> <span itemprop="title"><?= $category->info->name ?></span> </a> </li> <li class="breadcrumbs__item"> <?= $kit->info->name ?> </li> </ol> </div> <!-- /breadcrumbs --> <h1 class="page__title title"> <div class="title__inner is-slideInUp is-animated"> <div class="title__text"> <?= $kit->info->name ?> <div class="title__underline is-slideInLeft is-animated"></div> </div> </div> </h1> <div class="page__content"> <article class="g-block"> <div class="g-block__header"> <?php if (Yii::$app->page->getSubBlockInfo('sub_title1','name')) : ?> <div class="g-block__title title is-slideInUp is-animated"> <div class="title__text"> <?= Yii::$app->page->getSubBlockInfo('sub_title1','name') ?> <div class="title__underline is-slideInLeft is-animated"></div> </div> </div> <?php endif; ?> <?php if (Yii::$app->page->getSubBlockInfo('sub_title2','name')) : ?> <div class="g-block__title g-block__title--right title is-slideInUp is-animated"> <div class="title__text"> <?= Yii::$app->page->getSubBlockInfo('sub_title2','name') ?> <div class="title__underline is-slideInLeft is-animated"></div> </div> </div> <?php endif; ?> </div> <div class="g-block__content g-block__content--alt"> <div class="g-grid is-fadeIn is-animated"> <div class="g-col--two-third"> <img src="<?= $kit->thumbPath ?>" alt="<?= $kit->info->name ?>"> </div> <div class="g-col--one-third"> <nav class="b-list b-list--square"> <h4 class="b-list__title"><?= Yii::t('app','kit_consist') ?>:</h4> <ul class="b-list__list"> <?php foreach ($kit->products as $kitProduct) : ?> <li class="b-list__item"> <a href="<?= $kitProduct->equipmentUrl ?>" class="b-list__link"><?= $kitProduct->info->name ?></a> </li> <?php endforeach; ?> </ul> <p class="b-list__text g-text--color-alt"><?= Yii::t('app','no_analogs') ?></p> </nav> </div> </div> </div> </article> <div class="action-block"> <div class="action-block__item action-block__item--centered is-fadeInLeft is-animated"> <a href="" class="btn btn--colored" data-modal="test-drive"><?= Yii::t('app','to_order_test-drive') ?></a> </div> </div> <?php if (Yii::$app->page->getPage('id')) : ?> <?= Yii::$app->page->getPageInfo('text') ?> <?php endif; ?> <?= \app\helpers\ContentHelper::seoText(Yii::$app->page->seoText) ?> </div> </div> <div class="layer layer-1"> <div class="page__block page__block-1 is-modifiedFadeInLeft is-animated"></div> </div> <div class="layer layer-2"> <div class="page__block page__block-2 is-modifiedFadeInRight is-animated"></div> </div> <div class="layer layer-3"> <div class="page__block page__block-3 is-modifiedFadeInLeft is-animated"></div> </div> <div class="layer layer-4"> <div class="page__block page__block-4 is-modifiedFadeInRight is-animated"></div> </div> <div class="layer layer-5"> <div class="page__block page__block-5 is-modifiedFadeInRight is-animated"></div> </div> </section> <!-- /PAGE --> <?php $this->beginContent('@app/views/layouts/layout-parts/modal-test-drive.php'); $this->endContent(); ?>
illyaAvdeuk/bella-v
old/views/equipment/kit.php
PHP
bsd-3-clause
7,560
// -*- C++ -*- //============================================================================= /** * @file Name_Handler.h * * @author Prashant Jain * @author Gerhard Lenzer * @author and Douglas C. Schmidt */ //============================================================================= #ifndef ACE_NAME_HANDLER_H #define ACE_NAME_HANDLER_H #include "ace/Acceptor.h" #if !defined (ACE_LACKS_PRAGMA_ONCE) # pragma once #endif /* ACE_LACKS_PRAGMA_ONCE */ #include "ace/SOCK_Acceptor.h" #include "ace/SString.h" #include "ace/Svc_Handler.h" #include "ace/Naming_Context.h" #include "ace/Name_Request_Reply.h" #include "ace/Null_Mutex.h" #include "ace/svc_export.h" #if defined ACE_HAS_EXPLICIT_TEMPLATE_INSTANTIATION_EXPORT template class ACE_Svc_Export ACE_Svc_Handler<ACE_SOCK_STREAM, ACE_NULL_SYNCH>; #endif /* ACE_HAS_EXPLICIT_TEMPLATE_INSTANTIATION_EXPORT */ /** * @class ACE_Name_Handler * * @brief Product object created by <ACE_Name_Acceptor>. An * <ACE_Name_Handler> exchanges messages with a <ACE_Name_Proxy> * object on the client-side. * * This class is the main workhorse of the <ACE_Name_Server>. It * handles client requests to bind, rebind, resolve, and unbind * names. It also schedules and handles timeouts that are used to * support "timed waits." Clients used timed waits to bound the * amount of time they block trying to get a name. */ class ACE_Svc_Export ACE_Name_Handler : public ACE_Svc_Handler<ACE_SOCK_STREAM, ACE_NULL_SYNCH> { public: /// Pointer to a member function of ACE_Name_Handler returning int typedef int (ACE_Name_Handler::*OPERATION) (void); /// Pointer to a member function of ACE_Naming_Context returning int typedef int (ACE_Naming_Context::*LIST_OP) (ACE_PWSTRING_SET &, const ACE_NS_WString &); /// Pointer to a member function of ACE_Name_Handler returning ACE_Name_Request typedef ACE_Name_Request (ACE_Name_Handler::*REQUEST) (ACE_NS_WString *); // = Initialization and termination. /// Default constructor. ACE_Name_Handler (ACE_Thread_Manager * = 0); /// Activate this instance of the <ACE_Name_Handler> (called by the /// <ACE_Strategy_Acceptor>). virtual int open (void * = 0); protected: // = Helper routines for the operations exported to clients. /// Give up waiting (e.g., when a timeout occurs or a client shuts /// down unexpectedly). virtual int abandon (void); // = Low level routines for framing requests, dispatching // operations, and returning replies. /// Receive, frame, and decode the client's request. virtual int recv_request (void); /// Dispatch the appropriate operation to handle the client's /// request. virtual int dispatch (void); /// Create and send a reply to the client. virtual int send_reply (ACE_INT32 status, ACE_UINT32 errnum = 0); /// Special kind of reply virtual int send_request (ACE_Name_Request &); // = Demultiplexing hooks. /// Return the underlying <ACE_HANDLE>. virtual ACE_HANDLE get_handle (void) const; /// Callback method invoked by the <ACE_Reactor> when client events /// arrive. virtual int handle_input (ACE_HANDLE); // = Timer hook. /// Enable clients to limit the amount of time they wait for a name. virtual int handle_timeout (const ACE_Time_Value &tv, const void *arg); /// Ensure dynamic allocation... ~ACE_Name_Handler (void); private: /// Table of pointers to member functions OPERATION op_table_[ACE_Name_Request::MAX_ENUM]; struct LIST_ENTRY { LIST_OP operation_; // A member function pointer that performs the appropriate // operation (e.g., LIST_NAMES, LIST_VALUES, or LIST_TYPES). REQUEST request_factory_; // A member function pointer that serves as a factory to create a // request that is passed back to the client. const char *description_; // Name of the operation we're dispatching (used for debugging). }; /// This is the table of pointers to functions that we use to /// simplify the handling of list requests. LIST_ENTRY list_table_[ACE_Name_Request::MAX_LIST]; /// Cache request from the client. ACE_Name_Request name_request_; /// Special kind of reply for resolve and listnames. ACE_Name_Request name_request_back_; /// Cache reply to the client. ACE_Name_Reply name_reply_; /// Address of client we are connected with. ACE_INET_Addr addr_; /// Naming Context ACE_Naming_Context *naming_context_; ACE_Naming_Context *naming_context (void); /// Handle binds. int bind (void); /// Handle rebinds. int rebind (void); /// Handle binds and rebinds. int shared_bind (int rebind); /// Handle find requests. int resolve (void); /// Handle unbind requests. int unbind (void); /// Handle LIST_NAMES, LIST_VALUES, and LIST_TYPES requests. int lists (void); /// Handle LIST_NAME_ENTRIES, LIST_VALUE_ENTRIES, and /// LIST_TYPE_ENTRIES requests. int lists_entries (void); /// Create a name request. ACE_Name_Request name_request (ACE_NS_WString *one_name); /// Create a value request. ACE_Name_Request value_request (ACE_NS_WString *one_name); /// Create a type request. ACE_Name_Request type_request (ACE_NS_WString *one_name); }; /** * @class ACE_Name_Acceptor * * @brief This class contains the service-specific methods that can't * easily be factored into the <ACE_Strategy_Acceptor>. */ class ACE_Name_Acceptor : public ACE_Strategy_Acceptor<ACE_Name_Handler, ACE_SOCK_ACCEPTOR> { public: /// Dynamic linking hook. virtual int init (int argc, ACE_TCHAR *argv[]); /// Parse svc.conf arguments. int parse_args (int argc, ACE_TCHAR *argv[]); /// Naming context for acceptor /for the listening port/ ACE_Naming_Context *naming_context (void); private: /// The scheduling strategy is designed for Reactive services. ACE_Schedule_All_Reactive_Strategy<ACE_Name_Handler> scheduling_strategy_; /// The Naming Context ACE_Naming_Context naming_context_; }; ACE_SVC_FACTORY_DECLARE (ACE_Name_Acceptor) #endif /* ACE_NAME_HANDLER_H */
wfnex/openbras
src/ace/ACE_wrappers/netsvcs/lib/Name_Handler.h
C
bsd-3-clause
6,065
/** ****************************************************************************** * @file stm32l0xx_hal_cortex.c * @author MCD Application Team * @version V1.4.0 * @date 16-October-2015 * @brief CORTEX HAL module driver. * This file provides firmware functions to manage the following * functionalities of the CORTEX: * + Initialization and de-initialization functions * + Peripheral Control functions * @verbatim ============================================================================== ##### How to use this driver ##### ============================================================================== [..] *** How to configure Interrupts using CORTEX HAL driver *** =========================================================== [..] This section provide functions allowing to configure the NVIC interrupts (IRQ). The Cortex-M0+ exceptions are managed by CMSIS functions. (#) Enable and Configure the priority of the selected IRQ Channels. The priority can be 0..3. -@- Lower priority values gives higher priority. -@- Priority Order: (#@) Lowest priority. (#@) Lowest hardware priority (IRQn position). (#) Configure the priority of the selected IRQ Channels using HAL_NVIC_SetPriority() (#) Enable the selected IRQ Channels using HAL_NVIC_EnableIRQ() [..] *** How to configure Systick using CORTEX HAL driver *** ======================================================== [..] Setup SysTick Timer for time base (+) The HAL_SYSTICK_Config()function calls the SysTick_Config() function which is a CMSIS function that: (++) Configures the SysTick Reload register with value passed as function parameter. (++) Configures the SysTick IRQ priority to the lowest value (0x03). (++) Resets the SysTick Counter register. (++) Configures the SysTick Counter clock source to be Core Clock Source (HCLK). (++) Enables the SysTick Interrupt. (++) Starts the SysTick Counter. (+) You can change the SysTick Clock source to be HCLK_Div8 by calling the macro __HAL_CORTEX_SYSTICKCLK_CONFIG(SYSTICK_CLKSOURCE_HCLK_DIV8) just after the HAL_SYSTICK_Config() function call. The __HAL_CORTEX_SYSTICKCLK_CONFIG() macro is defined inside the stm32l0xx_hal_cortex.h file. (+) You can change the SysTick IRQ priority by calling the HAL_NVIC_SetPriority(SysTick_IRQn,...) function just after the HAL_SYSTICK_Config() function call. The HAL_NVIC_SetPriority() call the NVIC_SetPriority() function which is a CMSIS function. (+) To adjust the SysTick time base, use the following formula: Reload Value = SysTick Counter Clock (Hz) x Desired Time base (s) (++) Reload Value is the parameter to be passed for HAL_SYSTICK_Config() function (++) Reload Value should not exceed 0xFFFFFF @endverbatim ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT(c) 2015 STMicroelectronics</center></h2> * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics 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 HOLDER 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. * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "stm32l0xx_hal.h" /** @addtogroup STM32L0xx_HAL_Driver * @{ */ #ifdef HAL_CORTEX_MODULE_ENABLED /** @addtogroup CORTEX * @brief CORTEX HAL module driver * @{ */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /* Private macros ------------------------------------------------------------*/ /* Private functions ---------------------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ /** @addtogroup CORTEX_Exported_Functions * @{ */ /** @addtogroup CORTEX_Exported_Functions_Group1 Initialization and de-initialization functions * @brief Initialization and Configuration functions * @verbatim ============================================================================== ##### Initialization and de-initialization functions ##### ============================================================================== [..] This section provides the CORTEX HAL driver functions allowing to configure Interrupts Systick functionalities @endverbatim * @{ */ /** * @brief Sets the priority of an interrupt. * @param IRQn: External interrupt number . * This parameter can be an enumerator of IRQn_Type enumeration * (For the complete STM32 Devices IRQ Channels list, please refer to stm32l0xx.h file) * @param PreemptPriority: The pre-emption priority for the IRQn channel. * This parameter can be a value between 0 and 3. * A lower priority value indicates a higher priority * @param SubPriority: The subpriority level for the IRQ channel. * with stm32l0xx devices, this parameter is a dummy value and it is ignored, because * no subpriority supported in Cortex M0+ based products. * @retval None */ void HAL_NVIC_SetPriority(IRQn_Type IRQn, uint32_t PreemptPriority, uint32_t SubPriority) { /* Check the parameters */ assert_param(IS_NVIC_PREEMPTION_PRIORITY(PreemptPriority)); NVIC_SetPriority(IRQn,PreemptPriority); } /** * @brief Enables a device specific interrupt in the NVIC interrupt controller. * @note To configure interrupts priority correctly, the NVIC_PriorityGroupConfig() * function should be called before. * @param IRQn External interrupt number . * This parameter can be an enumerator of IRQn_Type enumeration * (For the complete STM32 Devices IRQ Channels list, please refer to stm32l0xx.h file) * @retval None */ void HAL_NVIC_EnableIRQ(IRQn_Type IRQn) { /* Check the parameters */ assert_param(IS_NVIC_DEVICE_IRQ(IRQn)); /* Enable interrupt */ NVIC_EnableIRQ(IRQn); } /** * @brief Disables a device specific interrupt in the NVIC interrupt controller. * @param IRQn External interrupt number . * This parameter can be an enumerator of IRQn_Type enumeration * (For the complete STM32 Devices IRQ Channels list, please refer to stm32l0xx.h file) * @retval None */ void HAL_NVIC_DisableIRQ(IRQn_Type IRQn) { /* Check the parameters */ assert_param(IS_NVIC_DEVICE_IRQ(IRQn)); /* Disable interrupt */ NVIC_DisableIRQ(IRQn); } /** * @brief Initiates a system reset request to reset the MCU. * @retval None */ void HAL_NVIC_SystemReset(void) { /* System Reset */ NVIC_SystemReset(); } /** * @brief Initializes the System Timer and its interrupt, and starts the System Tick Timer. * Counter is in free running mode to generate periodic interrupts. * @param TicksNumb: Specifies the ticks Number of ticks between two interrupts. * @retval status: - 0 Function succeeded. * - 1 Function failed. */ uint32_t HAL_SYSTICK_Config(uint32_t TicksNumb) { return SysTick_Config(TicksNumb); } /** * @} */ /** @addtogroup CORTEX_Exported_Functions_Group2 Peripheral Control functions * @brief Cortex control functions * @verbatim ============================================================================== ##### Peripheral Control functions ##### ============================================================================== [..] This subsection provides a set of functions allowing to control the CORTEX (NVIC, SYSTICK) functionalities. @endverbatim * @{ */ /** * @brief Gets the priority of an interrupt. * @param IRQn: External interrupt number. * This parameter can be an enumerator of IRQn_Type enumeration * (For the complete STM32 Devices IRQ Channels list, please refer to the appropriate CMSIS device file (stm32l0xxxx.h)) * @retval None */ uint32_t HAL_NVIC_GetPriority(IRQn_Type IRQn) { /* Get priority for Cortex-M system or device specific interrupts */ return NVIC_GetPriority(IRQn); } /** * @brief Sets Pending bit of an external interrupt. * @param IRQn: External interrupt number * This parameter can be an enumerator of IRQn_Type enumeration * (For the complete STM32 Devices IRQ Channels list, please refer to stm32l0xx.h file) * @retval None */ void HAL_NVIC_SetPendingIRQ(IRQn_Type IRQn) { /* Set interrupt pending */ NVIC_SetPendingIRQ(IRQn); } /** * @brief Gets Pending Interrupt (reads the pending register in the NVIC * and returns the pending bit for the specified interrupt). * @param IRQn: External interrupt number . * This parameter can be an enumerator of IRQn_Type enumeration * (For the complete STM32 Devices IRQ Channels list, please refer to stm32l0xx.h file) * @retval status: - 0 Interrupt status is not pending. * - 1 Interrupt status is pending. */ uint32_t HAL_NVIC_GetPendingIRQ(IRQn_Type IRQn) { /* Return 1 if pending else 0 */ return NVIC_GetPendingIRQ(IRQn); } /** * @brief Clears the pending bit of an external interrupt. * @param IRQn: External interrupt number . * This parameter can be an enumerator of IRQn_Type enumeration * (For the complete STM32 Devices IRQ Channels list, please refer to stm32l0xx.h file) * @retval None */ void HAL_NVIC_ClearPendingIRQ(IRQn_Type IRQn) { /* Clear pending interrupt */ NVIC_ClearPendingIRQ(IRQn); } /** * @brief Configures the SysTick clock source. * @param CLKSource: specifies the SysTick clock source. * This parameter can be one of the following values: * @arg SYSTICK_CLKSOURCE_HCLK_DIV8: AHB clock divided by 8 selected as SysTick clock source. * @arg SYSTICK_CLKSOURCE_HCLK: AHB clock selected as SysTick clock source. * @retval None */ void HAL_SYSTICK_CLKSourceConfig(uint32_t CLKSource) { /* Check the parameters */ assert_param(IS_SYSTICK_CLK_SOURCE(CLKSource)); if (CLKSource == SYSTICK_CLKSOURCE_HCLK) { SysTick->CTRL |= SYSTICK_CLKSOURCE_HCLK; } else { SysTick->CTRL &= ~SYSTICK_CLKSOURCE_HCLK; } } /** * @brief This function handles SYSTICK interrupt request. * @retval None */ void HAL_SYSTICK_IRQHandler(void) { HAL_SYSTICK_Callback(); } /** * @brief SYSTICK callback. * @retval None */ __weak void HAL_SYSTICK_Callback(void) { /* NOTE : This function Should not be modified, when the callback is needed, the HAL_SYSTICK_Callback could be implemented in the user file */ } #if (__MPU_PRESENT == 1) /** * @brief Initialize and configure the Region and the memory to be protected. * @param MPU_Init: Pointer to a MPU_Region_InitTypeDef structure that contains * the initialization and configuration information. * @retval None */ void HAL_MPU_ConfigRegion(MPU_Region_InitTypeDef *MPU_Init) { /* Check the parameters */ assert_param(IS_MPU_REGION_NUMBER(MPU_Init->Number)); assert_param(IS_MPU_REGION_ENABLE(MPU_Init->Enable)); /* Set the Region number */ MPU->RNR = MPU_Init->Number; if ((MPU_Init->Enable) == MPU_REGION_ENABLE) { /* Check the parameters */ assert_param(IS_MPU_INSTRUCTION_ACCESS(MPU_Init->DisableExec)); assert_param(IS_MPU_REGION_PERMISSION_ATTRIBUTE(MPU_Init->AccessPermission)); assert_param(IS_MPU_ACCESS_SHAREABLE(MPU_Init->IsShareable)); assert_param(IS_MPU_ACCESS_CACHEABLE(MPU_Init->IsCacheable)); assert_param(IS_MPU_ACCESS_BUFFERABLE(MPU_Init->IsBufferable)); assert_param(IS_MPU_SUB_REGION_DISABLE(MPU_Init->SubRegionDisable)); assert_param(IS_MPU_REGION_SIZE(MPU_Init->Size)); /* Set the base adsress and set the 4 LSB to 0 */ MPU->RBAR = (MPU_Init->BaseAddress) & 0xfffffff0; /* Fill the field RASR */ MPU->RASR = ((uint32_t)MPU_Init->DisableExec << MPU_RASR_XN_Pos) | ((uint32_t)MPU_Init->AccessPermission << MPU_RASR_AP_Pos) | ((uint32_t)MPU_Init->IsShareable << MPU_RASR_S_Pos) | ((uint32_t)MPU_Init->IsCacheable << MPU_RASR_C_Pos) | ((uint32_t)MPU_Init->IsBufferable << MPU_RASR_B_Pos) | ((uint32_t)MPU_Init->SubRegionDisable << MPU_RASR_SRD_Pos) | ((uint32_t)MPU_Init->Size << MPU_RASR_SIZE_Pos) | ((uint32_t)MPU_Init->Enable << MPU_RASR_ENABLE_Pos); } else { MPU->RBAR = 0x00; MPU->RASR = 0x00; } } #endif /* __MPU_PRESENT */ /** * @} */ /** * @} */ /** * @} */ #endif /* HAL_CORTEX_MODULE_ENABLED */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
seanelaval/LoRaMac-node
src/boards/mcu/stm32/STM32L0xx_HAL_Driver/Src/stm32l0xx_hal_cortex.c
C
bsd-3-clause
14,701
# Unit test for CmakeFedoraScript INCLUDE(test/testCommon.cmake) INCLUDE(ManageMessage) FUNCTION(CMAKE_FEDORA_SCRIPT_CONFIGURE_FILE_TEST expected inputFile outputFile) MESSAGE("CMAKE_FEDORA_SCRIPT_CONFIGURE_FILE: ${expected}") EXECUTE_PROCESS(COMMAND cmake -Dcmd=configure_file "-DinputFile=${inputFile}" "-DoutputFile=${outputFile}" ${ARGN} -P Modules/CmakeFedoraScript.cmake ) FILE(READ ${outputFile} v) STRING(STRIP "${v}" v) TEST_STR_MATCH(v "${expected}") ENDFUNCTION(CMAKE_FEDORA_SCRIPT_CONFIGURE_FILE_TEST expected cmd names) CMAKE_FEDORA_SCRIPT_CONFIGURE_FILE_TEST("Name: cmake-fedora cmake-fedora" ${CTEST_SCRIPT_DIRECTORY}/configure-file-project.txt ${CMAKE_FEDORA_TMP_DIR}/configure-file-project.txt -DPROJECT_NAME=cmake-fedora ) CMAKE_FEDORA_SCRIPT_CONFIGURE_FILE_TEST("Name: cmake-fedora \${PROJECT_NAME}" ${CTEST_SCRIPT_DIRECTORY}/configure-file-project.txt ${CMAKE_FEDORA_TMP_DIR}/configure-file-project.txt -Dat_only=1 -DPROJECT_NAME=cmake-fedora ) FUNCTION(CMAKE_FEDORA_SCRIPT_FIND_TEST expected cmd names) MESSAGE("CMAKE_FEDORA_SCRIPT_FIND: ${cmd}_${names}") EXECUTE_PROCESS(COMMAND cmake -Dcmd=${cmd} "-Dnames=${names}" ${ARGN} -P Modules/CmakeFedoraScript.cmake OUTPUT_VARIABLE v OUTPUT_STRIP_TRAILING_WHITESPACE ) TEST_STR_MATCH(v "${expected}") ENDFUNCTION(CMAKE_FEDORA_SCRIPT_FIND_TEST expected cmd names) CMAKE_FEDORA_SCRIPT_FIND_TEST("/usr/bin/cmake" "find_program" "cmake") CMAKE_FEDORA_SCRIPT_FIND_TEST("" "find_program" "not exist" "-Dverbose_level=${M_OFF}" ) CMAKE_FEDORA_SCRIPT_FIND_TEST("/etc/passwd" "find_file" "passwd" "-Dpaths=/etc" "-Dno_default_path=1" ) CMAKE_FEDORA_SCRIPT_FIND_TEST("" "find_file" "not exist" "-Dverbose_level=${M_OFF}" "-Dno_default_path=1" ) FUNCTION(CMAKE_FEDORA_SCRIPT_MANAGE_FILE_CACHE_TEST expected cacheFile run) MESSAGE("CMAKE_FEDORA_SCRIPT_MANAGE_FILE_CACHE: ${cacheFile}") SET(_cacheDir "/tmp") FILE(REMOVE "${_cacheDir}/${cacheFile}") EXECUTE_PROCESS(COMMAND cmake -Dcmd=manage_file_cache "-Dcache_file=${cacheFile}" "-Drun=${run}" -Dcache_dir=/tmp ${ARGN} -P Modules/CmakeFedoraScript.cmake OUTPUT_VARIABLE v OUTPUT_STRIP_TRAILING_WHITESPACE ) TEST_STR_MATCH(v "${expected}") ENDFUNCTION(CMAKE_FEDORA_SCRIPT_MANAGE_FILE_CACHE_TEST expected cachefile run) CMAKE_FEDORA_SCRIPT_MANAGE_FILE_CACHE_TEST("Hi" "Hi" "echo 'Hi'") CMAKE_FEDORA_SCRIPT_MANAGE_FILE_CACHE_TEST("Hello" "Hello" "echo 'Hi' | sed -e \"s/Hi/Hello/\"") FUNCTION(CMAKE_FEDORA_SCRIPT_GET_VARIBLE_TEST expected var) MESSAGE("CMAKE_FEDORA_SCRIPT_GET_VARIBLE_TEST: ${var}") EXECUTE_PROCESS(COMMAND cmake -Dcmd=get_variable "-Dvar=${var}" -P Modules/CmakeFedoraScript.cmake OUTPUT_VARIABLE v OUTPUT_STRIP_TRAILING_WHITESPACE ) TEST_STR_MATCH(v "${expected}") ENDFUNCTION(CMAKE_FEDORA_SCRIPT_GET_VARIBLE_TEST expected var) CMAKE_FEDORA_SCRIPT_GET_VARIBLE_TEST("$ENV{HOME}/.cache/cmake-fedora/" "LOCAL_CACHE_DIR")
czchen/debian-cmake-fedora
test/testCmakeFedoraScript.cmake
CMake
bsd-3-clause
3,019
<?xml version="1.0" encoding="ascii"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>lxml.etree.XSLTError</title> <link rel="stylesheet" href="epydoc.css" type="text/css" /> <script type="text/javascript" src="epydoc.js"></script> </head> <body bgcolor="white" text="black" link="blue" vlink="#204080" alink="#204080"> <!-- ==================== NAVIGATION BAR ==================== --> <table class="navbar" border="0" width="100%" cellpadding="0" bgcolor="#a0c0ff" cellspacing="0"> <tr valign="middle"> <!-- Home link --> <th>&nbsp;&nbsp;&nbsp;<a href="lxml-module.html">Home</a>&nbsp;&nbsp;&nbsp;</th> <!-- Tree link --> <th>&nbsp;&nbsp;&nbsp;<a href="module-tree.html">Trees</a>&nbsp;&nbsp;&nbsp;</th> <!-- Index link --> <th>&nbsp;&nbsp;&nbsp;<a href="identifier-index.html">Indices</a>&nbsp;&nbsp;&nbsp;</th> <!-- Help link --> <th>&nbsp;&nbsp;&nbsp;<a href="help.html">Help</a>&nbsp;&nbsp;&nbsp;</th> <!-- Project homepage --> <th class="navbar" align="right" width="100%"> <table border="0" cellpadding="0" cellspacing="0"> <tr><th class="navbar" align="center" ><a class="navbar" target="_top" href="http://codespeak.net/lxml/">lxml API</a></th> </tr></table></th> </tr> </table> <table width="100%" cellpadding="0" cellspacing="0"> <tr valign="top"> <td width="100%"> <span class="breadcrumbs"> <a href="lxml-module.html">Package&nbsp;lxml</a> :: <a href="lxml.etree-module.html">Module&nbsp;etree</a> :: Class&nbsp;XSLTError </span> </td> <td> <table cellpadding="0" cellspacing="0"> <!-- hide/show private --> <tr><td align="right"><span class="options">[<a href="javascript:void(0);" class="privatelink" onclick="toggle_private();">hide&nbsp;private</a>]</span></td></tr> <tr><td align="right"><span class="options" >[<a href="frames.html" target="_top">frames</a >]&nbsp;|&nbsp;<a href="lxml.etree.XSLTError-class.html" target="_top">no&nbsp;frames</a>]</span></td></tr> </table> </td> </tr> </table> <!-- ==================== CLASS DESCRIPTION ==================== --> <h1 class="epydoc">Class XSLTError</h1><p class="nomargin-top"></p> <pre class="base-tree"> object --+ | exceptions.BaseException --+ | exceptions.Exception --+ | <a href="lxml.etree.Error-class.html">Error</a> --+ | <a href="lxml.etree.LxmlError-class.html">LxmlError</a> --+ | <strong class="uidshort">XSLTError</strong> </pre> <dl><dt>Known Subclasses:</dt> <dd> <ul class="subclass-list"> <li><a href="lxml.etree.XSLTApplyError-class.html">XSLTApplyError</a></li><li>, <a href="lxml.etree.XSLTExtensionError-class.html">XSLTExtensionError</a></li><li>, <a href="lxml.etree.XSLTParseError-class.html">XSLTParseError</a></li><li>, <a href="lxml.etree.XSLTSaveError-class.html">XSLTSaveError</a></li> </ul> </dd></dl> <hr /> Base class of all XSLT errors. <!-- ==================== INSTANCE METHODS ==================== --> <a name="section-InstanceMethods"></a> <table class="summary" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr bgcolor="#70b0f0" class="table-header"> <td colspan="2" class="table-header"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr valign="top"> <td align="left"><span class="table-header">Instance Methods</span></td> <td align="right" valign="top" ><span class="options">[<a href="#section-InstanceMethods" class="privatelink" onclick="toggle_private();" >hide private</a>]</span></td> </tr> </table> </td> </tr> <tr> <td colspan="2" class="summary"> <p class="indent-wrapped-lines"><b>Inherited from <code><a href="lxml.etree.LxmlError-class.html">LxmlError</a></code></b>: <code><a href="lxml.etree.LxmlError-class.html#__init__">__init__</a></code> </p> <p class="indent-wrapped-lines"><b>Inherited from <code>exceptions.Exception</code></b>: <code>__new__</code> </p> <p class="indent-wrapped-lines"><b>Inherited from <code>exceptions.BaseException</code></b>: <code>__delattr__</code>, <code>__getattribute__</code>, <code>__getitem__</code>, <code>__getslice__</code>, <code>__reduce__</code>, <code>__repr__</code>, <code>__setattr__</code>, <code>__setstate__</code>, <code>__str__</code>, <code>__unicode__</code> </p> <p class="indent-wrapped-lines"><b>Inherited from <code>object</code></b>: <code>__format__</code>, <code>__hash__</code>, <code>__reduce_ex__</code>, <code>__sizeof__</code>, <code>__subclasshook__</code> </p> </td> </tr> </table> <!-- ==================== PROPERTIES ==================== --> <a name="section-Properties"></a> <table class="summary" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr bgcolor="#70b0f0" class="table-header"> <td colspan="2" class="table-header"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr valign="top"> <td align="left"><span class="table-header">Properties</span></td> <td align="right" valign="top" ><span class="options">[<a href="#section-Properties" class="privatelink" onclick="toggle_private();" >hide private</a>]</span></td> </tr> </table> </td> </tr> <tr> <td colspan="2" class="summary"> <p class="indent-wrapped-lines"><b>Inherited from <code>exceptions.BaseException</code></b>: <code>args</code>, <code>message</code> </p> <p class="indent-wrapped-lines"><b>Inherited from <code>object</code></b>: <code>__class__</code> </p> </td> </tr> </table> <!-- ==================== NAVIGATION BAR ==================== --> <table class="navbar" border="0" width="100%" cellpadding="0" bgcolor="#a0c0ff" cellspacing="0"> <tr valign="middle"> <!-- Home link --> <th>&nbsp;&nbsp;&nbsp;<a href="lxml-module.html">Home</a>&nbsp;&nbsp;&nbsp;</th> <!-- Tree link --> <th>&nbsp;&nbsp;&nbsp;<a href="module-tree.html">Trees</a>&nbsp;&nbsp;&nbsp;</th> <!-- Index link --> <th>&nbsp;&nbsp;&nbsp;<a href="identifier-index.html">Indices</a>&nbsp;&nbsp;&nbsp;</th> <!-- Help link --> <th>&nbsp;&nbsp;&nbsp;<a href="help.html">Help</a>&nbsp;&nbsp;&nbsp;</th> <!-- Project homepage --> <th class="navbar" align="right" width="100%"> <table border="0" cellpadding="0" cellspacing="0"> <tr><th class="navbar" align="center" ><a class="navbar" target="_top" href="http://codespeak.net/lxml/">lxml API</a></th> </tr></table></th> </tr> </table> <table border="0" cellpadding="0" cellspacing="0" width="100%%"> <tr> <td align="left" class="footer"> Generated by Epydoc 3.0.1 on Sun Feb 6 20:25:13 2011 </td> <td align="right" class="footer"> <a target="mainFrame" href="http://epydoc.sourceforge.net" >http://epydoc.sourceforge.net</a> </td> </tr> </table> <script type="text/javascript"> <!-- // Private objects are initially displayed (because if // javascript is turned off then we want them to be // visible); but by default, we want to hide them. So hide // them unless we have a cookie that says to show them. checkCookie(); // --> </script> </body> </html>
rajendrakrp/GeoMicroFormat
build/lxml/doc/html/api/lxml.etree.XSLTError-class.html
HTML
bsd-3-clause
8,027
""" Where the sausage is made. This Redis listener passes job announcements off to :py:func:`crawl_job_url` in this module for crawling. """ from twisted.python import log from twisted.internet.defer import inlineCallbacks, returnValue from twisted.web.client import readBody from crawler.lib.data_store import record_images_for_url from crawler.webapi_service.lib.job_queue import enqueue_crawling_job from crawler.lib.tx_http import visit_url, get_response_headers from crawler.conf import MAX_CRAWL_DEPTH from crawler.crawler_worker.lib.response_parser import parse_response @inlineCallbacks def crawl_job_url(delegator_svc, job_id, url, depth): """ Crawl a URL for images. Record any images that we found under the job's record in our job store (Redis). If we encounter valid <a href> tags, fire off additional crawling announcements for the worker pool to tear into together, rather than trying to do it all here. :param str job_id: The crawling job's UUID4 string. :param str url: The URL to crawl. :param int depth: The depth of this crawling job. If it's 0, this is the top-level crawl in the job. """ # Abstraction over Twisted's HTTP client. We'll follow redirs, validate # SSL certificates, and try to work for most cases. response = yield visit_url(url, follow_redirs=True) if response.code != 200: log.err("URL %s failed with non-200 HTTP code: %d" % (url, response.code)) returnValue(None) headers = get_response_headers(response) # If this were a production environment, we'd probably want to try to # figure out chunked response body parsing. We could end up with some # huge body sizes as-is. body = yield readBody(response) # Look through the response's body for possible images and other links. image_urls, links_to_crawl = parse_response(url, headers, body) yield record_images_for_url(job_id, url, image_urls) # Rather than try to follow the links in the current invocation, hand # these off so the work may be distributed across the pool. if links_to_crawl and depth < MAX_CRAWL_DEPTH: enqueue_crawling_job(delegator_svc, job_id, links_to_crawl, depth=depth + 1)
gtaylor/dockerized-image-crawler
crawler/crawler_worker/lib/job_crawler.py
Python
bsd-3-clause
2,222
/** * Copyright (c) 2010, Anchor Intelligence. 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 Anchor Intelligence 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. * */ package com.fraudwall.util; public class RangeTest extends AbstractAnchorTest { public void testExpandReturns() { assertListEquals(Range.expand("foo"), "foo"); assertListEquals(Range.expand("bar"), "bar"); assertListEquals(Range.expand("foo1-2"), "foo1", "foo2"); assertListEquals(Range.expand("tart:9000-9002"), "tart:9000", "tart:9001", "tart:9002"); } }
mjradwin/fraudwall-util
test/com/fraudwall/util/RangeTest.java
Java
bsd-3-clause
1,963
RSpec.feature "Translations", :js do stub_authorization! given(:language) { Spree.t(:'i18n.this_file_language', locale: 'pt-BR') } given!(:store) { create(:store) } background do create(:store) reset_spree_preferences SpreeI18n::Config.available_locales = [:en, :'pt-BR'] SpreeI18n::Config.supported_locales = [:en, :'pt-BR'] end context "products" do given(:product) { create(:product) } context "fills in translations fields" do scenario "saves translated attributes properly" do visit spree.admin_product_path(product) click_on "Translations" within("#attr_fields .name.en") { fill_in_name "Pearl Jam" } within("#attr_fields .name.pt-BR") { fill_in_name "Geleia de perola" } click_on "Update" visit spree.admin_product_path(product, locale: 'pt-BR') expect(page).to have_text_like 'Geleia de perola' end end context "product properties" do given!(:product_property) { create(:product_property, value: "red") } scenario "saves translated attributes properly" do visit spree.admin_product_product_properties_path(product_property.product) within_row(1) { click_icon :translate } within("#attr_fields .value.pt-BR") { fill_in_name "vermelho" } click_on "Update" visit spree.admin_product_product_properties_path(product_property.product, locale: 'pt-BR') expect(page).to have_selector("input[value=vermelho]") end end context "option types" do given!(:option_type) { create(:option_value).option_type } scenario "saves translated attributes properly" do visit spree.admin_option_types_path within_row(1) { click_icon :translate } within("#attr_fields .name.en") { fill_in_name "shirt sizes" } within("#attr_list") { click_on "Presentation" } within("#attr_fields .presentation.en") { fill_in_name "size" } within("#attr_fields .presentation.pt-BR") { fill_in_name "tamanho" } click_on "Update" visit spree.admin_option_types_path(locale: 'pt-BR') expect(page).to have_text_like 'tamanho' end # Regression test for issue #354 scenario "successfully creates an option type and go to its edit page" do visit spree.admin_option_types_path click_link "New Option Type" fill_in "Name", with: "Shirt Size" fill_in "Presentation", with: "Sizes" click_button "Create" expect(page).to have_text_like 'has been successfully created' expect(page).to have_text_like 'Option Values' end end context "option values" do given!(:option_type) { create(:option_value).option_type } scenario "saves translated attributes properly" do visit spree.admin_option_types_path within_row(1) { click_icon :translate } within("#attr_fields .name.en") { fill_in_name "big" } within("#attr_list") { click_on "Presentation" } within("#attr_fields .presentation.en") { fill_in_name "big" } within("#attr_fields .presentation.pt-BR") { fill_in_name "grande" } click_on "Update" visit spree.admin_option_types_path(locale: 'pt-BR') expect(page).to have_text_like 'grande' end end context "properties" do given!(:property) { create(:property) } scenario "saves translated attributes properly" do visit spree.admin_properties_path within_row(1) { click_icon :translate } within("#attr_fields .name.pt-BR") { fill_in_name "Modelo" } within("#attr_list") { click_on "Presentation" } within("#attr_fields .presentation.en") { fill_in_name "Model" } within("#attr_fields .presentation.pt-BR") { fill_in_name "Modelo" } click_on "Update" visit spree.admin_properties_path(locale: 'pt-BR') expect(page).to have_text_like 'Modelo' end end end context "promotions" do given!(:promotion) { create(:promotion) } scenario "saves translated attributes properly" do visit spree.admin_promotions_path within_row(1) { click_icon :translate } within("#attr_fields .name.en") { fill_in_name "All free" } within("#attr_fields .name.pt-BR") { fill_in_name "Salve salve" } click_on "Update" visit spree.admin_promotions_path(locale: 'pt-BR') expect(page).to have_text_like 'Salve salve' end it "render edit route properly" do visit spree.admin_promotions_path within_row(1) { click_icon :translate } click_on 'Cancel' expect(page).to have_css('.content-header') end end context "taxonomies" do given!(:taxonomy) { create(:taxonomy) } scenario "saves translated attributes properly" do visit spree.admin_taxonomies_path within_row(1) { click_icon :translate } within("#attr_fields .name.en") { fill_in_name "Guitars" } within("#attr_fields .name.pt-BR") { fill_in_name "Guitarras" } click_on "Update" visit spree.admin_taxonomies_path(locale: 'pt-BR') expect(page).to have_text_like 'Guitarras' end end context 'taxons' do given!(:taxonomy) { create(:taxonomy) } given!(:taxon) { create(:taxon, taxonomy: taxonomy, parent_id: taxonomy.root.id) } scenario "saves translated attributes properly" do visit spree.admin_translations_path('taxons', taxon.id) within("#attr_fields .name.en") { fill_in_name "Acoustic" } within("#attr_fields .name.pt-BR") { fill_in_name "Acusticas" } click_on "Update" visit spree.admin_translations_path('taxons', taxon.id) # ensure we're not duplicating translated records on database expect { click_on "Update" }.not_to change { taxon.translations.count } # ensure taxon is in root or it will not be visible expect(taxonomy.root.children.count).to be(1) visit spree.admin_translations_path('taxons', taxon.id, locale: 'pt-BR') expect(page).to have_selector("input[value=Acusticas]") end end context "store" do scenario 'saves translated attributes properly' do visit spree.edit_admin_general_settings_path click_link Spree.t(:configurations) click_link "Store Translations" within("#attr_fields .name.pt-BR") { fill_in_name "nome store" } click_on "Update" visit spree.admin_translations_path('stores', store) expect(page).to have_selector("input[value='nome store']") end end context "localization settings" do given(:language) { Spree.t(:'i18n.this_file_language', locale: 'de') } given(:french) { Spree.t(:'i18n.this_file_language', locale: 'fr') } background do create(:store) SpreeI18n::Config.available_locales = [:en, :'pt-BR', :de] visit spree.edit_admin_general_settings_path end scenario "adds german to supported locales and pick it on front end" do targetted_select2_search(language, from: '#s2id_supported_locales_') click_on 'Update' expect(SpreeI18n::Config.supported_locales).to include(:de) end scenario "adds spanish to available locales" do targetted_select2_search(french, from: '#s2id_available_locales_') click_on 'Update' expect(SpreeI18n::Config.available_locales).to include(:fr) end end context "permalink routing" do given(:language) { Spree.t(:'i18n.this_file_language', locale: 'de') } given(:product) { create(:product) } scenario "finds the right product with permalink in a not active language" do SpreeI18n::Config.available_locales = [:en, :de] SpreeI18n::Config.supported_locales = [:en, :de] visit spree.admin_product_path(product) click_on "Translations" click_on "Slug" within("#attr_fields .slug.en") { fill_in_name "en_link" } within("#attr_fields .slug.de") { fill_in_name "de_link" } click_on "Update" visit spree.product_path 'en_link' expect(page).to have_text_like 'Product' visit spree.product_path 'de_link' expect(page).to have_text_like 'Product' end end private def fill_in_name(value) fill_in first("input[type='text']")["name"], with: value end end
samuelsteiner/spree_i18n
spec/features/admin/translations_spec.rb
Ruby
bsd-3-clause
8,275
package com.catclutch.pixelesque; /* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import android.os.Bundle; import android.app.Dialog; import android.content.Context; import android.graphics.*; import android.view.MotionEvent; import android.view.View; public class ColorPickerDialog extends Dialog { public interface OnColorChangedListener { void colorChanged(int color); } private OnColorChangedListener mListener; private int mInitialColor; private static class ColorPickerView extends View { private Paint mPaint; private Paint mCenterPaint; private final int[] mColors; private OnColorChangedListener mListener; ColorPickerView(Context c, OnColorChangedListener l, int color) { super(c); mListener = l; mColors = new int[] { 0xFFFF0000, 0xFFFF00FF, 0xFF0000FF, 0xFF00FFFF, 0xFF00FF00, 0xFFFFFF00, 0xFFFF0000 }; Shader s = new SweepGradient(0, 0, mColors, null); mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mPaint.setShader(s); mPaint.setStyle(Paint.Style.STROKE); mPaint.setStrokeWidth(32); mCenterPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mCenterPaint.setColor(color); mCenterPaint.setStrokeWidth(5); } private boolean mTrackingCenter; private boolean mHighlightCenter; @Override protected void onDraw(Canvas canvas) { float r = CENTER_X - mPaint.getStrokeWidth()*0.5f; canvas.translate(CENTER_X, CENTER_X); canvas.drawOval(new RectF(-r, -r, r, r), mPaint); canvas.drawCircle(0, 0, CENTER_RADIUS, mCenterPaint); if (mTrackingCenter) { int c = mCenterPaint.getColor(); mCenterPaint.setStyle(Paint.Style.STROKE); if (mHighlightCenter) { mCenterPaint.setAlpha(0xFF); } else { mCenterPaint.setAlpha(0x80); } canvas.drawCircle(0, 0, CENTER_RADIUS + mCenterPaint.getStrokeWidth(), mCenterPaint); mCenterPaint.setStyle(Paint.Style.FILL); mCenterPaint.setColor(c); } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { setMeasuredDimension(CENTER_X*2, CENTER_Y*2); } private static final int CENTER_X = 100; private static final int CENTER_Y = 100; private static final int CENTER_RADIUS = 32; private int floatToByte(float x) { int n = java.lang.Math.round(x); return n; } private int pinToByte(int n) { if (n < 0) { n = 0; } else if (n > 255) { n = 255; } return n; } private int ave(int s, int d, float p) { return s + java.lang.Math.round(p * (d - s)); } private int interpColor(int colors[], float unit) { if (unit <= 0) { return colors[0]; } if (unit >= 1) { return colors[colors.length - 1]; } float p = unit * (colors.length - 1); int i = (int)p; p -= i; // now p is just the fractional part [0...1) and i is the index int c0 = colors[i]; int c1 = colors[i+1]; int a = ave(Color.alpha(c0), Color.alpha(c1), p); int r = ave(Color.red(c0), Color.red(c1), p); int g = ave(Color.green(c0), Color.green(c1), p); int b = ave(Color.blue(c0), Color.blue(c1), p); return Color.argb(a, r, g, b); } private int rotateColor(int color, float rad) { float deg = rad * 180 / 3.1415927f; int r = Color.red(color); int g = Color.green(color); int b = Color.blue(color); ColorMatrix cm = new ColorMatrix(); ColorMatrix tmp = new ColorMatrix(); cm.setRGB2YUV(); tmp.setRotate(0, deg); cm.postConcat(tmp); tmp.setYUV2RGB(); cm.postConcat(tmp); final float[] a = cm.getArray(); int ir = floatToByte(a[0] * r + a[1] * g + a[2] * b); int ig = floatToByte(a[5] * r + a[6] * g + a[7] * b); int ib = floatToByte(a[10] * r + a[11] * g + a[12] * b); return Color.argb(Color.alpha(color), pinToByte(ir), pinToByte(ig), pinToByte(ib)); } private static final float PI = 3.1415926f; @Override public boolean onTouchEvent(MotionEvent event) { float x = event.getX() - CENTER_X; float y = event.getY() - CENTER_Y; boolean inCenter = java.lang.Math.sqrt(x*x + y*y) <= CENTER_RADIUS; switch (event.getAction()) { case MotionEvent.ACTION_DOWN: mTrackingCenter = inCenter; if (inCenter) { mHighlightCenter = true; invalidate(); break; } case MotionEvent.ACTION_MOVE: if (mTrackingCenter) { if (mHighlightCenter != inCenter) { mHighlightCenter = inCenter; invalidate(); } } else { float angle = (float)java.lang.Math.atan2(y, x); // need to turn angle [-PI ... PI] into unit [0....1] float unit = angle/(2*PI); if (unit < 0) { unit += 1; } mCenterPaint.setColor(interpColor(mColors, unit)); invalidate(); } break; case MotionEvent.ACTION_UP: if (mTrackingCenter) { if (inCenter) { mListener.colorChanged(mCenterPaint.getColor()); } mTrackingCenter = false; // so we draw w/o halo invalidate(); } break; } return true; } } public ColorPickerDialog(Context context, OnColorChangedListener listener, int initialColor) { super(context); mListener = listener; mInitialColor = initialColor; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); OnColorChangedListener l = new OnColorChangedListener() { public void colorChanged(int color) { mListener.colorChanged(color); dismiss(); } }; setContentView(new ColorPickerView(getContext(), l, mInitialColor)); setTitle("Pick a Color"); } }
alinke/CATClutchPixelEditor
src/com/catclutch/pixelesque/ColorPickerDialog.java
Java
bsd-3-clause
7,884
/* Copyright (c) 2014 The Chromium OS Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ /* Twinkie dongle configuration */ #include "adc.h" #include "adc_chip.h" #include "common.h" #include "console.h" #include "gpio.h" #include "hooks.h" #include "i2c.h" #include "ina231.h" #include "registers.h" #include "task.h" #include "util.h" void cc2_event(enum gpio_signal signal) { ccprintf("INA!\n"); } void vbus_event(enum gpio_signal signal) { ccprintf("INA!\n"); } #include "gpio_list.h" /* Initialize board. */ void board_config_pre_init(void) { /* enable SYSCFG clock */ STM32_RCC_APB2ENR |= 1 << 0; /* Remap USART DMA to match the USART driver */ STM32_SYSCFG_CFGR1 |= (1 << 9) | (1 << 10);/* Remap USART1 RX/TX DMA */ /* 40 MHz pin speed on UART PA9/PA10 */ STM32_GPIO_OSPEEDR(GPIO_A) |= 0x003C0000; /* 40 MHz pin speed on TX clock out PB9 */ STM32_GPIO_OSPEEDR(GPIO_B) |= 0x000C0000; } static void board_init(void) { /* Enable interrupts for INAs. */ gpio_enable_interrupt(GPIO_CC2_ALERT_L); gpio_enable_interrupt(GPIO_VBUS_ALERT_L); /* Calibrate INA0 (VBUS) with 1mA/LSB scale */ ina231_init(0, 0x8000, INA231_CALIB_1MA(15 /*mOhm*/)); /* Disable INA1 (VCONN2) to avoid leaking current */ ina231_init(1, 0, INA231_CALIB_1MA(15 /*mOhm*/)); } DECLARE_HOOK(HOOK_INIT, board_init, HOOK_PRIO_DEFAULT); /* Pins with alternate functions */ const struct gpio_alt_func gpio_alt_funcs[] = { {GPIO_A, 0x0020, 0, MODULE_USB_PD},/* SPI1: SCK(PA5) */ {GPIO_B, 0x0200, 2, MODULE_USB_PD},/* TIM17_CH1: PB9 */ {GPIO_A, 0x0600, 1, MODULE_UART, GPIO_PULL_UP}, /* USART1: PA9/PA10 */ {GPIO_B, 0x00C0, 1, MODULE_I2C}, /* I2C1 MASTER:PB6/7 */ }; const int gpio_alt_funcs_count = ARRAY_SIZE(gpio_alt_funcs); /* ADC channels */ const struct adc_t adc_channels[] = { /* USB PD CC lines sensing. Converted to mV (3300mV/4096). */ [ADC_CH_CC1_PD] = {"CC1_PD", 3300, 4096, 0, STM32_AIN(1)}, [ADC_CH_CC2_PD] = {"CC2_PD", 3300, 4096, 0, STM32_AIN(3)}, }; BUILD_ASSERT(ARRAY_SIZE(adc_channels) == ADC_CH_COUNT); /* I2C ports */ const struct i2c_port_t i2c_ports[] = { {"master", I2C_PORT_MASTER, 100, GPIO_I2C_SCL, GPIO_I2C_SDA}, }; const unsigned int i2c_ports_used = ARRAY_SIZE(i2c_ports);
alterapraxisptyltd/chromium-ec
board/twinkie/board.c
C
bsd-3-clause
2,292
package org.opencraft.server.model.impl; /* * OpenCraft License * * Copyright (c) 2009 Graham Edgecombe, Søren Enevoldsen and Brett Russell. * 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 the OpenCraft 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 HOLDER 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. */ import org.opencraft.server.model.BlockBehaviour; import org.opencraft.server.model.BlockConstants; import org.opencraft.server.model.BlockManager; import org.opencraft.server.model.Level; /** * A block behaviour that applies gravity to a block. Lets a block fall to the * lowest possible unoccupied square (z-axis). * @author Graham Edgecombe * @author Brett Russell */ public class GravityBehaviour implements BlockBehaviour { @Override public void handlePassive(Level level, int x, int y, int z, int type) { if (z == 0 || BlockManager.getBlockManager().getBlock(level.getBlock(x, y, z - 1)).isSolid()) return; for (int i = z - 1; i >= 0; i--) { // find the first solid block below our gravity-affected block, or // the bottom of the map if none if (i == 0 || BlockManager.getBlockManager().getBlock(level.getBlock(x, y, i)).isSolid()) { // drop it on top of that block level.setBlock(x, y, z, BlockConstants.AIR); level.setBlock(x, y, i + (i == 0 && !BlockManager.getBlockManager().getBlock(level.getBlock(x, y, i)).isSolid() ? 0 : 1), type); return; } } } @Override public void handleDestroy(Level level, int x, int y, int z, int type) { } @Override public void handleScheduledBehaviour(Level level, int x, int y, int z, int type) { } }
grahamedgecombe/opencraft
src/org/opencraft/server/model/impl/GravityBehaviour.java
Java
bsd-3-clause
3,034
# Copyright (c) 2010, Trevor Bekolay # 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 the IRCL 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 HOLDER 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. import Codegen, Gui, Io app = Gui.BehaviourApp(redirect=1, filename="ErrorLog.txt") app.MainLoop()
tbekolay/behaviour-tool
BehaviourTool.py
Python
bsd-3-clause
1,649
<?php /** * CException class file. * * @author Qiang Xue <[email protected]> * @link http://www.yiiframework.com/ * @copyright Copyright &copy; 2008-2010 Yii Software LLC * @license http://www.yiiframework.com/license/ */ /** * CException represents a generic exception for all purposes. * * @author Qiang Xue <[email protected]> * @version $Id: CException.php 1678 2010-01-07 21:02:00Z qiang.xue $ * @package system.base * @since 1.0 */ class CException extends Exception { }
hukumonline/yii
framework/base/CException.php
PHP
bsd-3-clause
497
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. {-# LANGUAGE OverloadedStrings #-} module Duckling.Time.ES.Corpus ( corpus , latentCorpus ) where import Data.String import Prelude import Duckling.Locale import Duckling.Resolve import Duckling.Time.Corpus import Duckling.TimeGrain.Types hiding (add) import Duckling.Testing.Types hiding (examples) context :: Context context = testContext {locale = makeLocale ES Nothing} latentCorpus :: Corpus latentCorpus = (context, testOptions {withLatent = True}, xs) where xs = concat [ examples (datetime (2013, 2, 12, 13, 0, 0) Hour) [ "una hora" ] ] corpus :: Corpus corpus = (context, testOptions, allExamples) allExamples :: [Example] allExamples = concat [ examples (datetime (2013, 2, 12, 4, 30, 0) Second) [ "ahora" , "ya" , "ahorita" , "cuanto antes" ] , examples (datetime (2013, 2, 12, 0, 0, 0) Day) [ "hoy" , "en este momento" ] , examples (datetime (2013, 2, 11, 0, 0, 0) Day) [ "ayer" ] , examples (datetime (2013, 2, 10, 0, 0, 0) Day) [ "anteayer" , "antier" ] {-- This is intentional The purpose is to steer the classifier towards "tomorrow" rule instead of "morning" rule. --} , examples (datetime (2013, 2, 13, 0, 0, 0) Day) [ "mañana" , "manana" , "mañana" , "manana" , "mañana" , "manana" , "manana" , "mañana" , "manana" , "mañana" , "manana" , "manana" , "mañana" , "manana" , "mañana" , "manana" , "manana" , "mañana" , "manana" , "mañana" , "manana" , "manana" , "mañana" , "manana" , "mañana" , "manana" , "manana" , "mañana" , "manana" , "mañana" , "manana" , "manana" , "mañana" , "manana" , "mañana" , "manana" , "manana" , "mañana" , "manana" , "mañana" , "manana" , "manana" , "mañana" , "manana" , "mañana" , "manana" , "manana" , "mañana" , "manana" , "mañana" , "manana" ] , examples (datetime (2013, 2, 14, 0, 0, 0) Day) [ "pasado mañana" ] , examples (datetime (2013, 2, 18, 0, 0, 0) Day) [ "lunes" , "lu" , "lun." , "este lunes" ] , examples (datetime (2013, 2, 22, 0, 0, 0) Day) [ "el próximo viernes" , "proximo viernes" ] , examples (datetime (2013, 2, 18, 0, 0, 0) Day) [ "lunes, 18 de febrero" ] , examples (datetime (2013, 2, 19, 0, 0, 0) Day) [ "martes" , "ma" , "ma." ] , examples (datetime (2013, 2, 13, 0, 0, 0) Day) [ "miercoles" , "miércoles" , "mx" , "mié." ] , examples (datetime (2013, 2, 14, 0, 0, 0) Day) [ "jueves" ] , examples (datetime (2013, 2, 15, 0, 0, 0) Day) [ "viernes" ] , examples (datetime (2013, 2, 16, 0, 0, 0) Day) [ "sabado" ] , examples (datetime (2013, 2, 17, 0, 0, 0) Day) [ "domingo" ] , examples (datetime (2013, 5, 5, 0, 0, 0) Day) [ "el 5 de mayo" , "el cinco de mayo" ] , examples (datetime (2013, 5, 5, 0, 0, 0) Day) [ "el cinco de mayo de 2013" , "mayo 5 del 2013" , "5-5-2013" ] , examples (datetime (2013, 7, 4, 0, 0, 0) Day) [ "el 4 de julio" , "el 4/7" ] , examples (datetime (2013, 3, 3, 0, 0, 0) Day) [ "el 3 de marzo" , "3 de marzo" , "3 marzo" , "marzo 3" , "el 3-3" ] , examples (datetime (2013, 4, 5, 0, 0, 0) Day) [ "el 5 de abril" , "5 de abril" , "5 abril" , "abril 5" ] , examples (datetime (2013, 3, 1, 0, 0, 0) Day) [ "el 1 de marzo" , "1 de marzo" , "el primero de marzo" , "el uno de marzo" , "primero de marzo" , "uno de marzo" ] , examples (datetime (2013, 3, 1, 0, 0, 0) Day) [ "1-3-2013" , "1.3.2013" , "1/3/2013" ] , examples (datetime (2013, 2, 16, 0, 0, 0) Day) [ "el 16" , "16 de febrero" ] , examples (datetime (2013, 2, 17, 0, 0, 0) Day) [ "el 17" , "17 de febrero" , "17-2" , "el 17/2" ] , examples (datetime (2013, 2, 20, 0, 0, 0) Day) [ "el 20" , "20 de febrero" , "20/2" ] , examples (datetime (1974, 10, 31, 0, 0, 0) Day) [ "31/10/1974" , "31/10/74" ] , examples (datetime (2013, 2, 19, 0, 0, 0) Day) [ "el martes que viene" ] , examples (datetime (2013, 2, 20, 0, 0, 0) Day) [ "miércoles que viene" , "el miércoles de la semana que viene" , "miercoles de la próxima semana" ] , examples (datetime (2013, 2, 11, 0, 0, 0) Day) [ "el lunes de esta semana" ] , examples (datetime (2013, 2, 12, 0, 0, 0) Day) [ "martes de esta semana" ] , examples (datetime (2013, 2, 13, 0, 0, 0) Day) [ "el miércoles de esta semana" ] , examples (datetime (2013, 2, 11, 0, 0, 0) Week) [ "esta semana" ] , examples (datetime (2013, 2, 4, 0, 0, 0) Week) [ "la semana pasada" ] , examples (datetime (2013, 2, 18, 0, 0, 0) Week) [ "la semana que viene" , "la proxima semana" , "semana que viene" , "proxima semana" , "proximas semana" , "próxima semana" , "siguiente semana" ] , examples (datetime (2013, 1, 1, 0, 0, 0) Month) [ "el pasado mes" ] , examples (datetime (2013, 3, 0, 0, 0, 0) Month) [ "el mes que viene" , "el proximo mes" ] , examples (datetime (2012, 0, 0, 0, 0, 0) Year) [ "el año pasado" ] , examples (datetime (2013, 0, 0, 0, 0, 0) Year) [ "este ano" ] , examples (datetime (2014, 0, 0, 0, 0, 0) Year) [ "el año que viene" , "el proximo ano" ] , examples (datetime (2013, 2, 10, 0, 0, 0) Day) [ "el domingo pasado" , "el domingo de la semana pasada" ] , examples (datetime (2013, 2, 5, 0, 0, 0) Day) [ "el martes pasado" ] , examples (datetime (2013, 2, 12, 15, 0, 0) Hour) [ "a las tres de la tarde" , "a las tres" , "a las 3 pm" , "a las 15 horas" ] , examples (datetime (2013, 2, 12, 20, 0, 0) Hour) [ "a las ocho de la tarde" ] , examples (datetime (2013, 2, 12, 15, 0, 0) Minute) [ "15:00" , "15.00" ] , examples (datetime (2013, 2, 13, 0, 0, 0) Hour) [ "medianoche" ] , examples (datetime (2013, 2, 12, 12, 0, 0) Hour) [ "mediodía" , "las doce" , "medio dia" , "medio día" ] , examples (datetime (2013, 2, 12, 12, 15, 0) Minute) [ "las doce y cuarto" ] , examples (datetime (2013, 2, 12, 11, 55, 0) Minute) [ "las doce menos cinco" ] , examples (datetime (2013, 2, 12, 12, 30, 0) Minute) [ "las doce y media" ] , examples (datetime (2013, 2, 13, 3, 0, 0) Hour) [ "las tres de la manana" , "las tres en la manana" ] , examples (datetime (2013, 2, 12, 15, 15, 0) Minute) [ "a las tres y quince" , "a las 3 y cuarto" , "a las tres y cuarto de la tarde" , "a las tres y cuarto en la tarde" , "15:15" , "15.15" ] , examples (datetime (2013, 2, 12, 15, 30, 0) Minute) [ "a las tres y media" , "a las 3 y treinta" , "a las tres y media de la tarde" , "a las 3 y treinta del mediodía" , "15:30" , "15.30" ] , examples (datetime (2013, 2, 12, 11, 45, 0) Minute) [ "las doce menos cuarto" , "11:45" , "las once y cuarenta y cinco" , "hoy a las doce menos cuarto" , "hoy a las once y cuarenta y cinco" ] , examples (datetime (2013, 2, 12, 5, 15, 0) Minute) [ "5 y cuarto" ] , examples (datetime (2013, 2, 12, 6, 0, 0) Hour) [ "6 de la mañana" ] , examples (datetime (2013, 2, 13, 11, 0, 0) Hour) [ "miércoles a las once de la mañana" ] , examples (datetime (2013, 2, 13, 11, 0, 0) Hour) [ "mañana a las once" , "mañana a 11" ] , examples (datetime (2014, 9, 12, 0, 0, 0) Day) [ "viernes, el 12 de septiembre de 2014" ] , examples (datetime (2013, 2, 12, 4, 30, 1) Second) [ "en un segundo" ] , examples (datetime (2013, 2, 12, 4, 31, 0) Second) [ "en un minuto" , "en 1 min" ] , examples (datetime (2013, 2, 12, 4, 32, 0) Second) [ "en 2 minutos" , "en dos minutos" ] , examples (datetime (2013, 2, 12, 5, 30, 0) Second) [ "en 60 minutos" ] , examples (datetime (2013, 2, 12, 5, 30, 0) Minute) [ "en una hora" ] , examples (datetime (2013, 2, 12, 2, 30, 0) Minute) [ "hace dos horas" ] , examples (datetime (2013, 2, 13, 4, 30, 0) Minute) [ "en 24 horas" , "en veinticuatro horas" ] , examples (datetime (2013, 2, 13, 4, 0, 0) Hour) [ "en un dia" ] , examples (datetime (2013, 2, 19, 4, 0, 0) Hour) [ "en 7 dias" ] , examples (datetime (2013, 2, 19, 0, 0, 0) Day) [ "en una semana" ] , examples (datetime (2013, 1, 22, 0, 0, 0) Day) [ "hace tres semanas" ] , examples (datetime (2013, 4, 12, 0, 0, 0) Day) [ "en dos meses" ] , examples (datetime (2012, 11, 12, 0, 0, 0) Day) [ "hace tres meses" ] , examples (datetime (2014, 2, 0, 0, 0, 0) Month) [ "en un ano" , "en 1 año" ] , examples (datetime (2011, 2, 0, 0, 0, 0) Month) [ "hace dos años" ] , examples (datetimeInterval ((2013, 6, 21, 0, 0, 0), (2013, 9, 24, 0, 0, 0)) Day) [ "este verano" ] , examples (datetimeInterval ((2012, 12, 21, 0, 0, 0), (2013, 3, 21, 0, 0, 0)) Day) [ "este invierno" ] , examples (datetime (2013, 12, 25, 0, 0, 0) Day) [ "Navidad" , "la Navidad" ] , examples (datetime (2013, 12, 31, 0, 0, 0) Day) [ "Nochevieja" ] , examples (datetime (2014, 1, 1, 0, 0, 0) Day) [ "ano nuevo" , "año nuevo" ] , examples (datetime (2013, 2, 12, 21, 0, 0) Hour) [ "nueve de la noche" ] , examples (datetimeInterval ((2013, 2, 12, 18, 0, 0), (2013, 2, 13, 0, 0, 0)) Hour) [ "esta noche" ] , examples (datetimeInterval ((2013, 2, 13, 18, 0, 0), (2013, 2, 14, 0, 0, 0)) Hour) [ "mañana por la noche" ] , examples (datetimeInterval ((2013, 2, 11, 18, 0, 0), (2013, 2, 12, 0, 0, 0)) Hour) [ "ayer por la noche" ] , examples (datetimeInterval ((2013, 2, 15, 18, 0, 0), (2013, 2, 18, 0, 0, 0)) Hour) [ "este weekend" , "este fin de semana" ] , examples (datetimeInterval ((2013, 2, 18, 4, 0, 0), (2013, 2, 18, 12, 0, 0)) Hour) [ "lunes por la mañana" ] , examples (datetimeInterval ((2013, 2, 15, 4, 0, 0), (2013, 2, 15, 12, 0, 0)) Hour) [ "el 15 de febrero por la mañana" ] , examples (datetime (2013, 2, 12, 20, 0, 0) Hour) [ "a las 8 de la tarde" ] , examples (datetimeInterval ((2013, 2, 12, 4, 29, 58), (2013, 2, 12, 4, 30, 0)) Second) [ "pasados 2 segundos" ] , examples (datetimeInterval ((2013, 2, 12, 4, 30, 1), (2013, 2, 12, 4, 30, 4)) Second) [ "proximos 3 segundos" ] , examples (datetimeInterval ((2013, 2, 12, 4, 28, 0), (2013, 2, 12, 4, 30, 0)) Minute) [ "pasados 2 minutos" ] , examples (datetimeInterval ((2013, 2, 12, 4, 31, 0), (2013, 2, 12, 4, 34, 0)) Minute) [ "proximos 3 minutos" ] , examples (datetimeInterval ((2013, 2, 12, 5, 0, 0), (2013, 2, 12, 8, 0, 0)) Hour) [ "proximas 3 horas" ] , examples (datetimeInterval ((2013, 2, 10, 0, 0, 0), (2013, 2, 12, 0, 0, 0)) Day) [ "pasados 2 dias" ] , examples (datetimeInterval ((2013, 2, 13, 0, 0, 0), (2013, 2, 16, 0, 0, 0)) Day) [ "proximos 3 dias" ] , examples (datetimeInterval ((2013, 1, 28, 0, 0, 0), (2013, 2, 11, 0, 0, 0)) Week) [ "pasadas dos semanas" ] , examples (datetimeInterval ((2013, 2, 18, 0, 0, 0), (2013, 3, 11, 0, 0, 0)) Week) [ "3 proximas semanas" , "3 semanas que vienen" ] , examples (datetimeInterval ((2012, 12, 0, 0, 0, 0), (2013, 2, 0, 0, 0, 0)) Month) [ "pasados 2 meses" , "dos pasados meses" ] , examples (datetimeInterval ((2013, 3, 0, 0, 0, 0), (2013, 6, 0, 0, 0, 0)) Month) [ "3 próximos meses" , "proximos tres meses" , "tres meses que vienen" ] , examples (datetimeInterval ((2011, 0, 0, 0, 0, 0), (2013, 0, 0, 0, 0, 0)) Year) [ "pasados 2 anos" , "dos pasados años" ] , examples (datetimeInterval ((2014, 0, 0, 0, 0, 0), (2017, 0, 0, 0, 0, 0)) Year) [ "3 próximos años" , "proximo tres años" , "3 años que vienen" ] , examples (datetimeInterval ((2013, 7, 13, 0, 0, 0), (2013, 7, 16, 0, 0, 0)) Day) [ "13 a 15 de julio" , "13 - 15 de julio de 2013" ] , examples (datetimeInterval ((2013, 2, 12, 9, 30, 0), (2013, 2, 12, 11, 0, 0)) Minute) [ "9:30 - 11:00" ] , examples (datetimeInterval ((2013, 12, 21, 0, 0, 0), (2014, 1, 7, 0, 0, 0)) Day) [ "21 de Dic. a 6 de Ene" ] , examples (datetimeInterval ((2013, 2, 12, 4, 30, 0), (2013, 2, 12, 7, 30, 0)) Second) [ "dentro de tres horas" ] , examples (datetime (2013, 2, 12, 16, 0, 0) Hour) [ "a las cuatro de la tarde" ] , examples (datetime (2013, 2, 12, 13, 0, 0) Minute) [ "a las cuatro CET" ] , examples (datetime (2013, 8, 15, 0, 0, 0) Day) [ "jue 15" ] , examples (datetimeHoliday (2013, 12, 18, 0, 0, 0) Day "Día Mundial de la Lengua Árabe") [ "dia mundial de la lengua arabe" , "día mundial de la lengua árabe" ] , examples (datetimeHoliday (2013, 3, 1, 0, 0, 0) Day "Día de la Cero Discriminación") [ "dia de la cero discriminacion" , "día de la cero discriminación" ] , examples (datetimeHoliday (2019, 7, 6, 0, 0, 0) Day "Día Internacional de las Cooperativas") [ "día internacional de las cooperativas del 2019" ] , examples (datetimeHoliday (2013, 11, 17, 0, 0, 0) Day "Día de la Prematuridad Mundial") [ "día de la prematuridad mundial" , "día mundial del prematuro" , "día mundial del niño prematuro" ] , examples (datetimeHoliday (2013, 4, 1, 0, 0, 0) Day "Día de los Inocentes de Abril") [ "día de los inocentes" , "día de los inocentes de abril" , "día de las bromas de abril" , "día de las bromas" ] , examples (datetime (2013, 3, 9, 0, 0, 0) Day) [ "día nueve" ] , examples (datetime (2013, 2, 15, 0, 0, 0) Day) [ "día quince" ] , examples (datetime (2013, 3, 11, 0, 0, 0) Day) [ "día once" ] , examples (datetime (2013, 2, 12, 18, 2, 0) Minute) [ "las seis cero dos pm" , "las seis zero dos pm" , "para las seis cero dos pm" , "para las seis zero dos pm" , "a las seis cero dos pm" , "a las seis zero dos pm" , "al las seis cero dos pm" , "al las seis zero dos pm" , "para las 6 0 2 pm" , "a las 6 0 2 pm" , "al las 6 0 2 pm" , "seis cero dos pm" ] , examples (datetime (2013, 2, 12, 18, 2, 0) Minute) [ "seis dos de la tarde" ] , examples (datetime (1990, 0, 0, 0, 0, 0) Year) [ "mil novecientos noventa" ] , examples (datetime (1990, 5, 4, 0, 0, 0) Day) [ "cuatro de mayo de mil novecientos noventa" ] ]
facebookincubator/duckling
Duckling/Time/ES/Corpus.hs
Haskell
bsd-3-clause
18,771
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package model import ( "time" "google.golang.org/appengine/datastore" ) // AuthReplicationState contains state used to control Primary to Replica replication. type AuthReplicationState struct { // PrimaryID represents a GAE application ID of Primary. PrimaryID string // PrimaryURL represents a root URL of Primary, i.e. https://<host> PrimaryURL string // AuthDBRev represents a revision of AuthDB. AuthDBRev int64 // ModifiedTimestamp represents a time when AuthDBRev was created (by Primary clock). ModifiedTimestamp time.Time } // AuthGlobalConfig is a root entity for auth models. type AuthGlobalConfig struct { // Key represents the entity's datastore.Key. Key *datastore.Key // OAuthClientID represents OAuth2 client id. OAuthClientID string // OAuthClientSecret represents OAuth2 client secret. OAuthClientSecret string // OAuthAdditionalClientIDs is client IDs allowed to access the services. OAuthAdditionalClientIDs []string } func (a AuthGlobalConfig) key() *datastore.Key { return a.Key } // AuthGroup is a group of identities. type AuthGroup struct { // Key represents the entity's datastore.Key. Key *datastore.Key // Members represents a list of members that are explicitly in this group. Members []string // Globs is a list of identity-glob expressions. // e.g. user:*@example.com Globs []string // Nested is a list of nested group names. Nested []string // Description is a human readable description. Description string // CreatedTimestamp represents when the group was created. CreatedTimestamp time.Time // CreatedBy represents who created the group. CreatedBy string // ModifiedTimestamp represents when the group was modified. ModifiedTimestamp time.Time // ModifiedBy represents who modified the group. ModifiedBy string } func (a AuthGroup) key() *datastore.Key { return a.Key } // AuthIPWhitelist is a named set of whitelisted IPv4 and IPv6 subnets. type AuthIPWhitelist struct { // Key represents the entity's datastore.Key. Key *datastore.Key // Subnets is the list of subnets. Subnets []string // Description is a human readable description. Description string // CreatedTimestamp represents when the list was created. CreatedTimestamp time.Time // CreatedTimestamp represents who created the list. CreatedBy string // ModifiedTimestamp represents when the list was modified. ModifiedTimestamp time.Time // ModifiedTimestamp represents who modified the list. ModifiedBy string } func (a AuthIPWhitelist) key() *datastore.Key { return a.Key } // Assignment is a internal data structure used in AuthIPWhitelistAssignments. type Assignment struct { // Identity is a name to limit by IP whitelist. Identity string // IPWhitelist is a name of IP whitelist to use. IPWhitelist string // Comment represents the reason why the assignment was created. Comment string // CreatedTimestamp represents when the assignment was created. CreatedTimestamp time.Time // CreatedTimestamp represents who created the assignment. CreatedBy string } // AuthIPWhitelistAssignments is a singleton entity with "identity -> AUthIPWhitelist to use" mapping. type AuthIPWhitelistAssignments struct { // Key represents the entity's datastore.Key. Key *datastore.Key // Assignments holds all the assignments. Assignments []Assignment } func (a AuthIPWhitelistAssignments) key() *datastore.Key { return a.Key }
shishkander/luci-go
server/common/auth/model/model.go
GO
bsd-3-clause
3,565
<?php namespace common\models; use Yii; use yii\base\Model; /** * Login form */ class LoginForm extends Model { public $username; public $password; public $rememberMe = true; // public $role; private $_user; /** * @inheritdoc */ public function rules() { return [ // username and password are both required [['username', 'password'], 'required'], // rememberMe must be a boolean value ['rememberMe', 'boolean'], // password is validated by validatePassword() ['password', 'validatePassword'], ]; } /** * Validates the password. * This method serves as the inline validation for password. * * @param string $attribute the attribute currently being validated * @param array $params the additional name-value pairs given in the rule */ public function validatePassword($attribute, $params) { if (!$this->hasErrors()) { $user = $this->getUser(); if (!$user || !$user->validatePassword($this->password)) { $this->addError($attribute, 'Incorrect username or password.'); } } } /** * Logs in a user using the provided username and password. * * @return boolean whether the user is logged in successfully */ public function login() { if ($this->validate()) { return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0); } else { return false; } // $user = User::findByUsername($this->username); // $user->role = $this->$role; // return $user->save() ? $user : null; } /** * Finds user by [[username]] * * @return User|null */ protected function getUser() { if ($this->_user === null) { $this->_user = User::findByUsername($this->username); } return $this->_user; } }
YohanesDoank/sistem_rumah_sakit
common/models/LoginForm.php
PHP
bsd-3-clause
2,026
#pragma once #include "Net/private/CUDPNetObject.hpp" namespace NNet { class CUDPClient : public CUDPNetObject { public: CUDPClient( const NNet::CNetConnectionConfig& connectionConfig, const NNet::CNetCryptionConfig& cryptionConfig, pWorker worker); virtual void start() override; virtual void sendImplementation(const QByteArray& str) override; }; }
ymuv/CameraAlerts
Net/clients/CUDPClient.hpp
C++
bsd-3-clause
402
// Copyright Contributors to the Open Shading Language project. // SPDX-License-Identifier: BSD-3-Clause // https://github.com/AcademySoftwareFoundation/OpenShadingLanguage #ifndef __OSL_XMACRO_OPNAME # error must define __OSL_XMACRO_OPNAME to name of unary operation before including this header #endif #ifndef __OSL_XMACRO_OPERATOR # error must define __OSL_XMACRO_OPERATOR to operator to be tested before including this header #endif #ifndef __OSL_XMACRO_IN_TRANSFORM # define __OSL_XMACRO_IN_TRANSFORM(...) __VA_ARGS__ #endif #ifdef __OSL_XMACRO_CONSTANT_IN # define __OSL_XMACRO_IN_TRANSFORM_X(...) __OSL_XMACRO_IN_TRANSFORM(0.5) # define __OSL_XMACRO_IN_TRANSFORM_Y(...) __OSL_XMACRO_IN_TRANSFORM(0.75) # define __OSL_XMACRO_IN_TRANSFORM_Z(...) __OSL_XMACRO_IN_TRANSFORM(0.25) #elif defined(__OSL_XMACRO_UNIFORM_IN) # define __OSL_XMACRO_IN_TRANSFORM_X(...) __OSL_XMACRO_IN_TRANSFORM(1.0/(2*raytype("camera"))) # define __OSL_XMACRO_IN_TRANSFORM_Y(...) __OSL_XMACRO_IN_TRANSFORM(1.0/(3*raytype("camera"))) # define __OSL_XMACRO_IN_TRANSFORM_Z(...) __OSL_XMACRO_IN_TRANSFORM(1.0/(4*raytype("camera"))) #else # define __OSL_XMACRO_IN_TRANSFORM_X(...) __OSL_XMACRO_IN_TRANSFORM(__VA_ARGS__) # define __OSL_XMACRO_IN_TRANSFORM_Y(...) __OSL_XMACRO_IN_TRANSFORM(__VA_ARGS__) # define __OSL_XMACRO_IN_TRANSFORM_Z(...) __OSL_XMACRO_IN_TRANSFORM(__VA_ARGS__) #endif #ifndef __OSL_XMACRO_IN_TRANSFORM2 # define __OSL_XMACRO_IN_TRANSFORM2(...) __VA_ARGS__ #endif #ifdef __OSL_XMACRO_CONSTANT_IN2 # define __OSL_XMACRO_IN_TRANSFORM_X2(...) __OSL_XMACRO_IN_TRANSFORM2(0.75) # define __OSL_XMACRO_IN_TRANSFORM_Y2(...) __OSL_XMACRO_IN_TRANSFORM2(0.95) # define __OSL_XMACRO_IN_TRANSFORM_Z2(...) __OSL_XMACRO_IN_TRANSFORM2(0.45) #elif defined(__OSL_XMACRO_UNIFORM_IN2) # define __OSL_XMACRO_IN_TRANSFORM_X2(...) __OSL_XMACRO_IN_TRANSFORM2(1.5/(2*raytype("camera"))) # define __OSL_XMACRO_IN_TRANSFORM_Y2(...) __OSL_XMACRO_IN_TRANSFORM2(1.5/(3*raytype("camera"))) # define __OSL_XMACRO_IN_TRANSFORM_Z2(...) __OSL_XMACRO_IN_TRANSFORM2(1.5/(4*raytype("camera"))) #else # define __OSL_XMACRO_IN_TRANSFORM_X2(...) __OSL_XMACRO_IN_TRANSFORM2(__VA_ARGS__) # define __OSL_XMACRO_IN_TRANSFORM_Y2(...) __OSL_XMACRO_IN_TRANSFORM2(__VA_ARGS__) # define __OSL_XMACRO_IN_TRANSFORM_Z2(...) __OSL_XMACRO_IN_TRANSFORM2(__VA_ARGS__) #endif #ifndef __OSL_XMACRO_STRIPE_TRANSFORM # define __OSL_XMACRO_STRIPE_TRANSFORM(...) (__VA_ARGS__)*0.5 #endif #ifndef __OSL_XMACRO_STRIPE_TRANSFORM2 # define __OSL_XMACRO_STRIPE_TRANSFORM2(...) (__VA_ARGS__)*2 #endif #ifndef __OSL_XMACRO_OUT_TRANSFORM # define __OSL_XMACRO_OUT_TRANSFORM(...) __VA_ARGS__ #endif #define __OSL_CONCAT_INDIRECT(A, B) A##B #define __OSL_CONCAT(A, B) __OSL_CONCAT_INDIRECT(A, B) shader __OSL_CONCAT(test_, __OSL_XMACRO_OPNAME)( int numStripes = 0, int derivX = 0, int derivY = 0, float derivShift = 0, float derivScale = 1, output int out_int = 1, output float out_float = 1, output color out_color = 1, output point out_point = 1, output vector out_vector = 1, output normal out_normal = 1) { float x_comp = __OSL_XMACRO_IN_TRANSFORM_X(P[0]); float y_comp = __OSL_XMACRO_IN_TRANSFORM_Y(P[1]); float z_comp = __OSL_XMACRO_IN_TRANSFORM_Z(P[2]); float x_comp2 = __OSL_XMACRO_IN_TRANSFORM_X2(max(0,1 - P[1])); float y_comp2 = __OSL_XMACRO_IN_TRANSFORM_Y2(max(0,1 - P[0])); float z_comp2 = __OSL_XMACRO_IN_TRANSFORM_Z2(max(0,1 - P[2])/2); float float_in = (x_comp + y_comp) * 0.5; color color_in = color(x_comp, y_comp, z_comp); point point_in = point(x_comp, y_comp, z_comp); vector vector_in = vector(x_comp, y_comp, z_comp); normal normal_in = normal(x_comp, y_comp, z_comp); float float_in2 = (x_comp2 + y_comp2) * 0.5; color color_in2 = color(x_comp2, y_comp2, z_comp2); point point_in2 = point(x_comp2, y_comp2, z_comp2); vector vector_in2 = vector(x_comp2, y_comp2, z_comp2); normal normal_in2 = normal(x_comp2, y_comp2, z_comp2); // Exercise the operator unmasked float float_val = float_in __OSL_XMACRO_OPERATOR float_in2; color color_val = color_in __OSL_XMACRO_OPERATOR color_in2; point point_val = point_in __OSL_XMACRO_OPERATOR point_in2; vector vector_val = vector_in __OSL_XMACRO_OPERATOR vector_in2; normal normal_val = normal_in __OSL_XMACRO_OPERATOR normal_in2; // Exercise the op masked if ((numStripes != 0) && (int(P[0]*P[0]*P[1]*2*numStripes)%2 == 0)) { float_val = __OSL_XMACRO_STRIPE_TRANSFORM(float_in) __OSL_XMACRO_OPERATOR __OSL_XMACRO_STRIPE_TRANSFORM2(float_in2); color_val = __OSL_XMACRO_STRIPE_TRANSFORM(color_in) __OSL_XMACRO_OPERATOR __OSL_XMACRO_STRIPE_TRANSFORM2(color_in2); point_val = __OSL_XMACRO_STRIPE_TRANSFORM(point_in) __OSL_XMACRO_OPERATOR __OSL_XMACRO_STRIPE_TRANSFORM2(point_in2); vector_val = __OSL_XMACRO_STRIPE_TRANSFORM(vector_in) __OSL_XMACRO_OPERATOR __OSL_XMACRO_STRIPE_TRANSFORM2(vector_in2); normal_val = __OSL_XMACRO_STRIPE_TRANSFORM(normal_in) __OSL_XMACRO_OPERATOR __OSL_XMACRO_STRIPE_TRANSFORM2(normal_in2); } if (derivX) { float_val = Dx(float_val); color_val = Dx(color_val); point_val = Dx(point_val); vector_val = Dx(vector_val); normal_val = Dx(normal_val); } if (derivY) { float_val = Dy(float_val); color_val = Dy(color_val); point_val = Dy(point_val); vector_val = Dy(vector_val); normal_val = Dy(normal_val); } if (derivX || derivY) { if (derivScale != 1) { float_val *= derivScale; color_val *= derivScale; point_val *= derivScale; vector_val *= derivScale; normal_val *= derivScale; } if (derivShift != 0) { float_val += derivShift; color_val += derivShift; point_val += derivShift; vector_val += derivShift; normal_val += derivShift; } } out_float = __OSL_XMACRO_OUT_TRANSFORM(float_val); out_color = __OSL_XMACRO_OUT_TRANSFORM(color_val); out_point = __OSL_XMACRO_OUT_TRANSFORM(point_val); out_vector = __OSL_XMACRO_OUT_TRANSFORM(vector_val); out_normal = __OSL_XMACRO_OUT_TRANSFORM(normal_val); }
lgritz/OpenShadingLanguage
testsuite/common/shaders/test_operator_xmacro.h
C
bsd-3-clause
6,379
/* * Copyright (c) 2008, Damian Carrillo * 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 the copyright holder's organization 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. */ package co.cdev.agave.web; import java.util.HashMap; import org.jmock.Expectations; import org.junit.Before; import org.junit.Test; import co.cdev.agave.sample.WorkflowForm; import co.cdev.agave.sample.WorkflowHandler; import co.cdev.agave.web.AgaveFilter; /** * @author <a href="mailto:[email protected]">Damian Carrillo</a> */ public class WorkflowFunctionalTest extends AbstractFunctionalTest { @Before public void setup() throws Exception { super.setup(); context.checking(new Expectations() {{ allowing(request).getContentType(); will(returnValue("application/x-www-form-urlencoded")); }}); } @Test public void testInitialize() throws Exception { AgaveFilter filter = createSilentAgaveFilter(); emulateServletContainer(new HashMap<String, String[]>()); context.checking(new Expectations() {{ allowing(request).getServletPath(); will(returnValue("/wizard/step1/")); allowing(request).getMethod(); will(returnValue("GET")); one(session).setAttribute("wizard-handler", new WorkflowHandler()); one(session).setAttribute("wizard-form", new WorkflowForm()); }}); filter.init(filterConfig); filter.doFilter(request, response, filterChain); } @Test public void testResume() throws Exception { AgaveFilter filter = createSilentAgaveFilter(); final WorkflowHandler handler = new WorkflowHandler(); final WorkflowForm form = new WorkflowForm(); emulateServletContainer(new HashMap<String, String[]>()); context.checking(new Expectations() {{ allowing(request).getServletPath(); will(returnValue("/wizard/step2/")); allowing(request).getMethod(); will(returnValue("GET")); one(session).getAttribute("wizard-handler"); will(returnValue(handler)); one(session).getAttribute("wizard-form"); will(returnValue(form)); }}); filter.init(filterConfig); filter.doFilter(request, response, filterChain); } @Test public void testCompletion() throws Exception { AgaveFilter filter = createSilentAgaveFilter(); final WorkflowHandler handler = new WorkflowHandler(); final WorkflowForm form = new WorkflowForm(); emulateServletContainer(new HashMap<String, String[]>()); context.checking(new Expectations() {{ allowing(request).getServletPath(); will(returnValue("/wizard/step3/")); allowing(request).getMethod(); will(returnValue("GET")); one(session).getAttribute("wizard-handler"); will(returnValue(handler)); one(session).getAttribute("wizard-form"); will(returnValue(form)); one(session).removeAttribute("wizard-handler"); one(session).removeAttribute("wizard-form"); }}); filter.init(filterConfig); filter.doFilter(request, response, filterChain); } }
damiancarrillo/agave-framework
agave-web-framework/src/test/java/co/cdev/agave/web/WorkflowFunctionalTest.java
Java
bsd-3-clause
4,687
// Generated, do not edit by hand package org.whitehole.binary.pe; import org.whitehole.infra.io.LargeByteBuffer; import org.whitehole.infra.types.LittleEndianReader; import org.whitehole.infra.types.UInt32; import org.whitehole.infra.types.UInt8; public class OptionalHeaderStandardFields { public static OptionalHeaderStandardFields read(LargeByteBuffer buffer, long offset) { return read(buffer, offset, new OptionalHeaderStandardFields()); } public static OptionalHeaderStandardFields read(LargeByteBuffer buffer, long offset, OptionalHeaderStandardFields x) { x.setMagic(MagicNumber.read(buffer, offset)); x.setMajorLinkerVersion(LittleEndianReader.readUInt8(buffer, offset + 2)); x.setMinorLinkerVersion(LittleEndianReader.readUInt8(buffer, offset + 3)); x.setSizeOfCode(LittleEndianReader.readUInt32(buffer, offset + 4)); x.setSizeOfInitializedData(LittleEndianReader.readUInt32(buffer, offset + 8)); x.setSizeOfUninitializedData(LittleEndianReader.readUInt32(buffer, offset + 12)); x.setAddressOfEntryPoint(LittleEndianReader.readUInt32(buffer, offset + 16)); x.setBaseOfCode(LittleEndianReader.readUInt32(buffer, offset + 20)); return x; } public MagicNumber getMagic() { return _magic; } public OptionalHeaderStandardFields setMagic(MagicNumber x) { _magic = x; return this; } public UInt8 getMajorLinkerVersion() { return _majorLinkerVersion; } public OptionalHeaderStandardFields setMajorLinkerVersion(UInt8 x) { _majorLinkerVersion = x; return this; } public UInt8 getMinorLinkerVersion() { return _minorLinkerVersion; } public OptionalHeaderStandardFields setMinorLinkerVersion(UInt8 x) { _minorLinkerVersion = x; return this; } public UInt32 getSizeOfCode() { return _sizeOfCode; } public OptionalHeaderStandardFields setSizeOfCode(UInt32 x) { _sizeOfCode = x; return this; } public UInt32 getSizeOfInitializedData() { return _sizeOfInitializedData; } public OptionalHeaderStandardFields setSizeOfInitializedData(UInt32 x) { _sizeOfInitializedData = x; return this; } public UInt32 getSizeOfUninitializedData() { return _sizeOfUninitializedData; } public OptionalHeaderStandardFields setSizeOfUninitializedData(UInt32 x) { _sizeOfUninitializedData = x; return this; } public UInt32 getAddressOfEntryPoint() { return _addressOfEntryPoint; } public OptionalHeaderStandardFields setAddressOfEntryPoint(UInt32 x) { _addressOfEntryPoint = x; return this; } public UInt32 getBaseOfCode() { return _baseOfCode; } public OptionalHeaderStandardFields setBaseOfCode(UInt32 x) { _baseOfCode = x; return this; } public static final int byteSize = 22 + MagicNumber.byteSize; private MagicNumber _magic; private UInt8 _majorLinkerVersion; private UInt8 _minorLinkerVersion; private UInt32 _sizeOfCode; private UInt32 _sizeOfInitializedData; private UInt32 _sizeOfUninitializedData; private UInt32 _addressOfEntryPoint; private UInt32 _baseOfCode; }
BenoitPerrot/whitehole-lib
src/main/java/org/whitehole/binary/pe/OptionalHeaderStandardFields.java
Java
bsd-3-clause
2,984
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html lang="en"> <head> <meta name="generator" content="AWStats 7.1 (build 1.983) from config file awstats.r.oblax.ru.conf (http://www.awstats.org)"> <meta name="robots" content="noindex,nofollow"> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta http-equiv="description" content="Awstats - Advanced Web Statistics for r.oblax.ru (2016-06) - lasthosts"> <title>Statistics for r.oblax.ru (2016-06) - lasthosts</title> <style type="text/css"> body { font: 11px verdana, arial, helvetica, sans-serif; background-color: #FFFFFF; margin-top: 0; margin-bottom: 0; } .aws_bodyl { } .aws_border { border-collapse: collapse; background-color: #CCCCDD; padding: 1px 1px 1px 1px; margin-top: 0px; margin-bottom: 0px; } .aws_title { font: 13px verdana, arial, helvetica, sans-serif; font-weight: bold; background-color: #CCCCDD; text-align: center; margin-top: 0; margin-bottom: 0; padding: 1px 1px 1px 1px; color: #000000; } .aws_blank { font: 13px verdana, arial, helvetica, sans-serif; background-color: #FFFFFF; text-align: center; margin-bottom: 0; padding: 1px 1px 1px 1px; } .aws_data { background-color: #FFFFFF; border-top-width: 1px; border-left-width: 0px; border-right-width: 0px; border-bottom-width: 0px; } .aws_formfield { font: 13px verdana, arial, helvetica; } .aws_button { font-family: arial,verdana,helvetica, sans-serif; font-size: 12px; border: 1px solid #ccd7e0; background-image : url(/awstatsicons/other/button.gif); } th { border-color: #ECECEC; border-left-width: 0px; border-right-width: 1px; border-top-width: 0px; border-bottom-width: 1px; padding: 1px 2px 1px 1px; font: 11px verdana, arial, helvetica, sans-serif; text-align:center; color: #000000; } th.aws { border-color: #ECECEC; border-left-width: 0px; border-right-width: 1px; border-top-width: 0px; border-bottom-width: 1px; padding: 1px 2px 1px 1px; font-size: 13px; font-weight: bold; } td { border-color: #ECECEC; border-left-width: 0px; border-right-width: 1px; border-top-width: 0px; border-bottom-width: 1px; font: 11px verdana, arial, helvetica, sans-serif; text-align:center; color: #000000; } td.aws { border-color: #ECECEC; border-left-width: 0px; border-right-width: 1px; border-top-width: 0px; border-bottom-width: 1px; font: 11px verdana, arial, helvetica, sans-serif; text-align:left; color: #000000; padding: 0px;} td.awsm { border-left-width: 0px; border-right-width: 0px; border-top-width: 0px; border-bottom-width: 0px; font: 11px verdana, arial, helvetica, sans-serif; text-align:left; color: #000000; padding: 0px; } b { font-weight: bold; } a { font: 11px verdana, arial, helvetica, sans-serif; } a:link { color: #0011BB; text-decoration: none; } a:visited { color: #0011BB; text-decoration: none; } a:hover { color: #605040; text-decoration: underline; } .currentday { font-weight: bold; } </style> </head> <body style="margin-top: 0px"> <a name="top"></a> <a name="menu">&nbsp;</a> <form name="FormDateFilter" action="/cgi-bin/awstats.pl?config=r.oblax.ru&amp;output=lasthosts" style="padding: 0px 0px 0px 0px; margin-top: 0"> <table class="aws_border" border="0" cellpadding="2" cellspacing="0" width="100%"> <tr><td> <table class="aws_data sortable" border="0" cellpadding="1" cellspacing="0" width="100%"> <tr><td class="aws" valign="middle"><b>Statistics for:</b>&nbsp;</td><td class="aws" valign="middle"><span style="font-size: 14px;">r.oblax.ru</span></td><td align="right" rowspan="3"><a href="http://awstats.sourceforge.net" target="awstatshome"><img src="/awstatsicons/other/awstats_logo6.png" border="0" /></a></td></tr> <tr valign="middle"><td class="aws" valign="middle" width="150"><b>Last Update:</b>&nbsp;</td><td class="aws" valign="middle"><span style="font-size: 12px;">30 Jul 2016 - 00:01</span></td></tr> <tr><td class="aws" valign="middle"><b>Reported period:</b></td><td class="aws" valign="middle"><span style="font-size: 14px;">Month Jun 2016</span></td></tr> </table> </td></tr></table> </form><br /> <table> <tr><td class="aws"><a href="javascript:parent.window.close();">Close window</a></td></tr> </table> <a name="hosts">&nbsp;</a><br /> <table class="aws_border sortable" border="0" cellpadding="2" cellspacing="0" width="100%"> <tr><td class="aws_title" width="70%">Last visit </td><td class="aws_blank">&nbsp;</td></tr> <tr><td colspan="2"> <table class="aws_data" border="1" cellpadding="2" cellspacing="0" width="100%"> <tr bgcolor="#ECECEC"><th>Total : 0 Known, 0 Unknown (unresolved ip) - 0 Unique visitors</th><th bgcolor="#4477DD" width="80">Pages</th><th bgcolor="#66DDEE" width="80">Hits</th><th class="datasize" bgcolor="#2EA495" width="80">Bandwidth</th><th width="120">Last visit</th></tr> </table></td></tr></table><br /> <br /><br /> <span dir="ltr" style="font: 11px verdana, arial, helvetica; color: #000000;"><b>Advanced Web Statistics 7.1 (build 1.983)</b> - <a href="http://www.awstats.org" target="awstatshome">Created by awstats</a></span><br /> <br /> </body> </html>
oblaxru/Nokia2700-
web/webstat/awstats.r.oblax.ru.lasthosts.062016.html
HTML
bsd-3-clause
5,082
namespace Platinum.Resolver { public partial class ResolverDefinition { internal IUrlResolver ResolverInstance { get; set; } } } /* eof */
filipetoscano/Platinum
src/Platinum.Core/Resolver/Configuration-Partial.cs
C#
bsd-3-clause
202
/*- * Copyright (c) 2005 Robert N. M. Watson * Copyright (c) 2012 Jilles Tjoelker * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD$ */ #include <sys/types.h> #include <sys/event.h> #include <sys/filio.h> #include <sys/stat.h> #include <sys/time.h> #include <err.h> #include <errno.h> #include <fcntl.h> #include <limits.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> /* * Regression test for piddling details of fifos. */ /* * All activity occurs within a temporary directory created early in the * test. */ static char temp_dir[PATH_MAX]; static void __unused atexit_temp_dir(void) { rmdir(temp_dir); } static void makefifo(const char *fifoname, const char *testname) { if (mkfifo(fifoname, 0700) < 0) err(-1, "%s: makefifo: mkfifo: %s", testname, fifoname); } static void cleanfifo(const char *fifoname, int fd1, int fd2) { if (fd1 != -1) close(fd1); if (fd2 != -1) close(fd2); (void)unlink(fifoname); } static int openfifo(const char *fifoname, int *reader_fdp, int *writer_fdp) { int error, fd1, fd2; fd1 = open(fifoname, O_RDONLY | O_NONBLOCK); if (fd1 < 0) return (-1); fd2 = open(fifoname, O_WRONLY | O_NONBLOCK); if (fd2 < 0) { error = errno; close(fd1); errno = error; return (-1); } *reader_fdp = fd1; *writer_fdp = fd2; return (0); } /* * POSIX does not allow lseek(2) on fifos, so we expect ESPIPE as a result. */ static void test_lseek(void) { int reader_fd, writer_fd; makefifo("testfifo", __func__); if (openfifo("testfifo", &reader_fd, &writer_fd) < 0) { warn("%s: openfifo", __func__); cleanfifo("testfifo", -1, -1); exit(-1); } if (lseek(reader_fd, 1, SEEK_CUR) >= 0) { warnx("%s: lseek succeeded instead of returning ESPIPE", __func__); cleanfifo("testfifo", reader_fd, writer_fd); exit(-1); } if (errno != ESPIPE) { warn("%s: lseek returned instead of ESPIPE", __func__); cleanfifo("testfifo", reader_fd, writer_fd); exit(-1); } cleanfifo("testfifo", reader_fd, writer_fd); } /* * truncate(2) on FIFO should silently return success. */ static void test_truncate(void) { makefifo("testfifo", __func__); if (truncate("testfifo", 1024) != 0) { warn("%s: truncate", __func__); cleanfifo("testfifo", -1, -1); exit(-1); } cleanfifo("testfifo", -1, -1); } static int test_ioctl_setclearflag(int fd, int flag, const char *testname, const char *fdname, const char *flagname) { int i; i = 1; if (ioctl(fd, flag, &i) < 0) { warn("%s:%s: ioctl(%s, %s, 1)", testname, __func__, fdname, flagname); cleanfifo("testfifo", -1, -1); exit(-1); } i = 0; if (ioctl(fd, flag, &i) < 0) { warn("%s:%s: ioctl(%s, %s, 0)", testname, __func__, fdname, flagname); cleanfifo("testfifo", -1, -1); exit(-1); } return (0); } /* * Test that various ioctls can be issued against the file descriptor. We * don't currently test the semantics of these changes here. */ static void test_ioctl(void) { int reader_fd, writer_fd; makefifo("testfifo", __func__); if (openfifo("testfifo", &reader_fd, &writer_fd) < 0) { warn("%s: openfifo", __func__); cleanfifo("testfifo", -1, -1); exit(-1); } /* * Set and remove the non-blocking I/O flag. */ if (test_ioctl_setclearflag(reader_fd, FIONBIO, __func__, "reader_fd", "FIONBIO") < 0) { cleanfifo("testfifo", reader_fd, writer_fd); exit(-1); } if (test_ioctl_setclearflag(writer_fd, FIONBIO, __func__, "writer_fd", "FIONBIO") < 0) { cleanfifo("testfifo", reader_fd, writer_fd); exit(-1); } /* * Set and remove the async I/O flag. */ if (test_ioctl_setclearflag(reader_fd, FIOASYNC, __func__, "reader_fd", "FIOASYNC") < 0) { cleanfifo("testfifo", reader_fd, writer_fd); exit(-1); } if (test_ioctl_setclearflag(writer_fd, FIOASYNC, __func__, "writer_fd", "FIONASYNC") < 0) { cleanfifo("testfifo", reader_fd, writer_fd); exit(-1); } cleanfifo("testfifo", reader_fd, writer_fd); } /* * fchmod(2)/fchown(2) on FIFO should work. */ static void test_chmodchown(void) { struct stat sb; int reader_fd, writer_fd; uid_t u; gid_t g; makefifo("testfifo", __func__); if (openfifo("testfifo", &reader_fd, &writer_fd) < 0) { warn("%s: openfifo", __func__); cleanfifo("testfifo", -1, -1); exit(-1); } if (fchmod(reader_fd, 0666) != 0) { warn("%s: fchmod", __func__); cleanfifo("testfifo", reader_fd, writer_fd); exit(-1); } if (stat("testfifo", &sb) != 0) { warn("%s: stat", __func__); cleanfifo("testfifo", reader_fd, writer_fd); exit(-1); } if ((sb.st_mode & 0777) != 0666) { warnx("%s: stat chmod result", __func__); cleanfifo("testfifo", reader_fd, writer_fd); exit(-1); } if (fstat(writer_fd, &sb) != 0) { warn("%s: fstat", __func__); cleanfifo("testfifo", reader_fd, writer_fd); exit(-1); } if ((sb.st_mode & 0777) != 0666) { warnx("%s: fstat chmod result", __func__); cleanfifo("testfifo", reader_fd, writer_fd); exit(-1); } if (fchown(reader_fd, -1, -1) != 0) { warn("%s: fchown 1", __func__); cleanfifo("testfifo", reader_fd, writer_fd); exit(-1); } u = geteuid(); if (u == 0) u = 1; g = getegid(); if (fchown(reader_fd, u, g) != 0) { warn("%s: fchown 2", __func__); cleanfifo("testfifo", reader_fd, writer_fd); exit(-1); } if (stat("testfifo", &sb) != 0) { warn("%s: stat", __func__); cleanfifo("testfifo", reader_fd, writer_fd); exit(-1); } if (sb.st_uid != u || sb.st_gid != g) { warnx("%s: stat chown result", __func__); cleanfifo("testfifo", reader_fd, writer_fd); exit(-1); } if (fstat(writer_fd, &sb) != 0) { warn("%s: fstat", __func__); cleanfifo("testfifo", reader_fd, writer_fd); exit(-1); } if (sb.st_uid != u || sb.st_gid != g) { warnx("%s: fstat chown result", __func__); cleanfifo("testfifo", reader_fd, writer_fd); exit(-1); } cleanfifo("testfifo", -1, -1); } int main(void) { strcpy(temp_dir, "fifo_misc.XXXXXXXXXXX"); if (mkdtemp(temp_dir) == NULL) err(-1, "mkdtemp"); atexit(atexit_temp_dir); if (chdir(temp_dir) < 0) err(-1, "chdir %s", temp_dir); test_lseek(); test_truncate(); test_ioctl(); test_chmodchown(); return (0); }
jrobhoward/SCADAbase
tests/sys/fifo/fifo_misc.c
C
bsd-3-clause
7,439
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.http import Http404 from django.shortcuts import get_object_or_404 from django.urls import reverse from django.utils.translation import ugettext_lazy as _ from django.views.generic.dates import (DateDetailView, DayArchiveView, MonthArchiveView, YearArchiveView) from django.views.generic.detail import DetailView from django.views.generic.list import ListView from parler.views import TranslatableSlugMixin, ViewUrlMixin from blogit import settings as bs from blogit.models import Category, Post, Tag class ToolbarMixin(object): def get(self, request, *args, **kwargs): response = super(ToolbarMixin, self).get(request, *args, **kwargs) if hasattr(self, 'object') and hasattr(request, 'toolbar'): request.toolbar.set_object(self.object) menu = request.toolbar.get_menu('blogit-current-menu') if menu: self.update_menu(menu, self.object) return response def update_menu(self, menu, obj): pass class PostListMixin(object): model = Post template_name = 'blogit/post_list.html' paginate_by = bs.POSTS_PER_PAGE def __init__(self, *args, **kwargs): super(PostListMixin, self).__init__(*args, **kwargs) self.filters = {} def get_queryset(self): return self.model.objects.published(self.request, **self.filters) # Category views. class CategoryListView(ListView): model = Category template_name = 'blogit/category_list.html' def get_queryset(self): return self.model.objects.filter(active=True) class CategoryDetailView(ToolbarMixin, ViewUrlMixin, PostListMixin, ListView): template_name = 'blogit/category_detail.html' def get_context_data(self, **kwargs): kwargs.update({'category': self.get_category_object()}) return super(CategoryDetailView, self).get_context_data(**kwargs) def get(self, request, *args, **kwargs): try: ids = self.get_category_object().get_descendants(include_self=True).values_list('id', flat=True) self.filters['category_id__in'] = ids except Category.DoesNotExist: raise Http404 return super(CategoryDetailView, self).get(request, *args, **kwargs) def get_category_object(self): if not hasattr(self, '_category_object'): path = self.kwargs['path'] slug = path.split('/').pop() queryset = Category.objects.translated(slug=slug) category = get_object_or_404(queryset, active=True) if category.get_path() != path: raise Http404 setattr(self, '_category_object', category) return getattr(self, '_category_object') def update_menu(self, menu, obj): pk = self.get_category_object().id menu.add_break() url = reverse('admin:blogit_category_change', args=[pk]) menu.add_modal_item(_('Edit Category'), url=url) url = reverse('admin:blogit_category_delete', args=[pk]) menu.add_modal_item(_('Delete Category'), url=url) def get_view_url(self): """ Return object view url. Used in `get_translated_url` templatetag from parler. """ return self.get_category_object().get_absolute_url() # Tag views. class TagListView(ListView): model = Tag template_name = 'blogit/tag_list.html' def get_queryset(self): return self.model.objects.filter(active=True) class TagDetailView(ToolbarMixin, PostListMixin, ListView): template_name = 'blogit/tag_detail.html' def get_context_data(self, **kwargs): kwargs.update({'tag': self.object}) return super(TagDetailView, self).get_context_data(**kwargs) def get(self, request, *args, **kwargs): try: self.object = Tag.objects.translated(slug=kwargs.get('slug')).get(active=True) self.filters['tags__in'] = [self.object] except Tag.DoesNotExist: raise Http404 return super(TagDetailView, self).get(request, *args, **kwargs) def update_menu(self, menu, obj): menu.add_break() url = reverse('admin:blogit_tag_change', args=[self.object.pk]) menu.add_modal_item(_('Edit Tag'), url=url) url = reverse('admin:blogit_tag_delete', args=[self.object.pk]) menu.add_modal_item(_('Delete Tag'), url=url) class PostDateMixin(object): date_field = 'date_published' year_format = '%Y' month_format = '%m' day_format = '%d' make_object_list = True allow_future = True class ArchiveListMixin(PostDateMixin, PostListMixin): template_name = 'blogit/post_archive.html' class PostYearArchiveView(ArchiveListMixin, YearArchiveView): pass class PostMonthArchiveView(ArchiveListMixin, MonthArchiveView): pass class PostDayArchiveView(ArchiveListMixin, DayArchiveView): pass class PostListView(PostListMixin, ListView): pass class PostDetailMixin(ToolbarMixin): model = Post template_name = 'blogit/post_detail.html' def get_queryset(self): return Post.objects.published(self.request) def update_menu(self, menu, obj): menu.add_break() url = reverse('admin:blogit_post_change', args=[self.object.pk]) menu.add_modal_item(_('Edit Post'), url=url) url = reverse('admin:blogit_post_delete', args=[self.object.pk]) menu.add_modal_item(_('Delete Post'), url=url) class PostDetailView(PostDetailMixin, TranslatableSlugMixin, DetailView): pass class PostDateDetailView(PostDateMixin, PostDetailMixin, DateDetailView): pass
dinoperovic/djangocms-blogit
blogit/views.py
Python
bsd-3-clause
5,701
""" Tests related to deprecation warnings. Also a convenient place to document how deprecations should eventually be turned into errors. """ import datetime import operator import warnings import pytest import tempfile import re import numpy as np from numpy.testing import ( assert_raises, assert_warns, assert_, assert_array_equal ) from numpy.core._multiarray_tests import fromstring_null_term_c_api try: import pytz _has_pytz = True except ImportError: _has_pytz = False class _DeprecationTestCase: # Just as warning: warnings uses re.match, so the start of this message # must match. message = '' warning_cls = DeprecationWarning def setup(self): self.warn_ctx = warnings.catch_warnings(record=True) self.log = self.warn_ctx.__enter__() # Do *not* ignore other DeprecationWarnings. Ignoring warnings # can give very confusing results because of # https://bugs.python.org/issue4180 and it is probably simplest to # try to keep the tests cleanly giving only the right warning type. # (While checking them set to "error" those are ignored anyway) # We still have them show up, because otherwise they would be raised warnings.filterwarnings("always", category=self.warning_cls) warnings.filterwarnings("always", message=self.message, category=self.warning_cls) def teardown(self): self.warn_ctx.__exit__() def assert_deprecated(self, function, num=1, ignore_others=False, function_fails=False, exceptions=np._NoValue, args=(), kwargs={}): """Test if DeprecationWarnings are given and raised. This first checks if the function when called gives `num` DeprecationWarnings, after that it tries to raise these DeprecationWarnings and compares them with `exceptions`. The exceptions can be different for cases where this code path is simply not anticipated and the exception is replaced. Parameters ---------- function : callable The function to test num : int Number of DeprecationWarnings to expect. This should normally be 1. ignore_others : bool Whether warnings of the wrong type should be ignored (note that the message is not checked) function_fails : bool If the function would normally fail, setting this will check for warnings inside a try/except block. exceptions : Exception or tuple of Exceptions Exception to expect when turning the warnings into an error. The default checks for DeprecationWarnings. If exceptions is empty the function is expected to run successfully. args : tuple Arguments for `function` kwargs : dict Keyword arguments for `function` """ # reset the log self.log[:] = [] if exceptions is np._NoValue: exceptions = (self.warning_cls,) try: function(*args, **kwargs) except (Exception if function_fails else tuple()): pass # just in case, clear the registry num_found = 0 for warning in self.log: if warning.category is self.warning_cls: num_found += 1 elif not ignore_others: raise AssertionError( "expected %s but got: %s" % (self.warning_cls.__name__, warning.category)) if num is not None and num_found != num: msg = "%i warnings found but %i expected." % (len(self.log), num) lst = [str(w) for w in self.log] raise AssertionError("\n".join([msg] + lst)) with warnings.catch_warnings(): warnings.filterwarnings("error", message=self.message, category=self.warning_cls) try: function(*args, **kwargs) if exceptions != tuple(): raise AssertionError( "No error raised during function call") except exceptions: if exceptions == tuple(): raise AssertionError( "Error raised during function call") def assert_not_deprecated(self, function, args=(), kwargs={}): """Test that warnings are not raised. This is just a shorthand for: self.assert_deprecated(function, num=0, ignore_others=True, exceptions=tuple(), args=args, kwargs=kwargs) """ self.assert_deprecated(function, num=0, ignore_others=True, exceptions=tuple(), args=args, kwargs=kwargs) class _VisibleDeprecationTestCase(_DeprecationTestCase): warning_cls = np.VisibleDeprecationWarning class TestNonTupleNDIndexDeprecation: def test_basic(self): a = np.zeros((5, 5)) with warnings.catch_warnings(): warnings.filterwarnings('always') assert_warns(FutureWarning, a.__getitem__, [[0, 1], [0, 1]]) assert_warns(FutureWarning, a.__getitem__, [slice(None)]) warnings.filterwarnings('error') assert_raises(FutureWarning, a.__getitem__, [[0, 1], [0, 1]]) assert_raises(FutureWarning, a.__getitem__, [slice(None)]) # a a[[0, 1]] always was advanced indexing, so no error/warning a[[0, 1]] class TestComparisonDeprecations(_DeprecationTestCase): """This tests the deprecation, for non-element-wise comparison logic. This used to mean that when an error occurred during element-wise comparison (i.e. broadcasting) NotImplemented was returned, but also in the comparison itself, False was given instead of the error. Also test FutureWarning for the None comparison. """ message = "elementwise.* comparison failed; .*" def test_normal_types(self): for op in (operator.eq, operator.ne): # Broadcasting errors: self.assert_deprecated(op, args=(np.zeros(3), [])) a = np.zeros(3, dtype='i,i') # (warning is issued a couple of times here) self.assert_deprecated(op, args=(a, a[:-1]), num=None) # ragged array comparison returns True/False a = np.array([1, np.array([1,2,3])], dtype=object) b = np.array([1, np.array([1,2,3])], dtype=object) self.assert_deprecated(op, args=(a, b), num=None) def test_string(self): # For two string arrays, strings always raised the broadcasting error: a = np.array(['a', 'b']) b = np.array(['a', 'b', 'c']) assert_raises(ValueError, lambda x, y: x == y, a, b) # The empty list is not cast to string, and this used to pass due # to dtype mismatch; now (2018-06-21) it correctly leads to a # FutureWarning. assert_warns(FutureWarning, lambda: a == []) def test_void_dtype_equality_failures(self): class NotArray: def __array__(self): raise TypeError # Needed so Python 3 does not raise DeprecationWarning twice. def __ne__(self, other): return NotImplemented self.assert_deprecated(lambda: np.arange(2) == NotArray()) self.assert_deprecated(lambda: np.arange(2) != NotArray()) struct1 = np.zeros(2, dtype="i4,i4") struct2 = np.zeros(2, dtype="i4,i4,i4") assert_warns(FutureWarning, lambda: struct1 == 1) assert_warns(FutureWarning, lambda: struct1 == struct2) assert_warns(FutureWarning, lambda: struct1 != 1) assert_warns(FutureWarning, lambda: struct1 != struct2) def test_array_richcompare_legacy_weirdness(self): # It doesn't really work to use assert_deprecated here, b/c part of # the point of assert_deprecated is to check that when warnings are # set to "error" mode then the error is propagated -- which is good! # But here we are testing a bunch of code that is deprecated *because* # it has the habit of swallowing up errors and converting them into # different warnings. So assert_warns will have to be sufficient. assert_warns(FutureWarning, lambda: np.arange(2) == "a") assert_warns(FutureWarning, lambda: np.arange(2) != "a") # No warning for scalar comparisons with warnings.catch_warnings(): warnings.filterwarnings("error") assert_(not (np.array(0) == "a")) assert_(np.array(0) != "a") assert_(not (np.int16(0) == "a")) assert_(np.int16(0) != "a") for arg1 in [np.asarray(0), np.int16(0)]: struct = np.zeros(2, dtype="i4,i4") for arg2 in [struct, "a"]: for f in [operator.lt, operator.le, operator.gt, operator.ge]: with warnings.catch_warnings() as l: warnings.filterwarnings("always") assert_raises(TypeError, f, arg1, arg2) assert_(not l) class TestDatetime64Timezone(_DeprecationTestCase): """Parsing of datetime64 with timezones deprecated in 1.11.0, because datetime64 is now timezone naive rather than UTC only. It will be quite a while before we can remove this, because, at the very least, a lot of existing code uses the 'Z' modifier to avoid conversion from local time to UTC, even if otherwise it handles time in a timezone naive fashion. """ def test_string(self): self.assert_deprecated(np.datetime64, args=('2000-01-01T00+01',)) self.assert_deprecated(np.datetime64, args=('2000-01-01T00Z',)) @pytest.mark.skipif(not _has_pytz, reason="The pytz module is not available.") def test_datetime(self): tz = pytz.timezone('US/Eastern') dt = datetime.datetime(2000, 1, 1, 0, 0, tzinfo=tz) self.assert_deprecated(np.datetime64, args=(dt,)) class TestNonCContiguousViewDeprecation(_DeprecationTestCase): """View of non-C-contiguous arrays deprecated in 1.11.0. The deprecation will not be raised for arrays that are both C and F contiguous, as C contiguous is dominant. There are more such arrays with relaxed stride checking than without so the deprecation is not as visible with relaxed stride checking in force. """ def test_fortran_contiguous(self): self.assert_deprecated(np.ones((2,2)).T.view, args=(complex,)) self.assert_deprecated(np.ones((2,2)).T.view, args=(np.int8,)) class TestArrayDataAttributeAssignmentDeprecation(_DeprecationTestCase): """Assigning the 'data' attribute of an ndarray is unsafe as pointed out in gh-7093. Eventually, such assignment should NOT be allowed, but in the interests of maintaining backwards compatibility, only a Deprecation- Warning will be raised instead for the time being to give developers time to refactor relevant code. """ def test_data_attr_assignment(self): a = np.arange(10) b = np.linspace(0, 1, 10) self.message = ("Assigning the 'data' attribute is an " "inherently unsafe operation and will " "be removed in the future.") self.assert_deprecated(a.__setattr__, args=('data', b.data)) class TestBinaryReprInsufficientWidthParameterForRepresentation(_DeprecationTestCase): """ If a 'width' parameter is passed into ``binary_repr`` that is insufficient to represent the number in base 2 (positive) or 2's complement (negative) form, the function used to silently ignore the parameter and return a representation using the minimal number of bits needed for the form in question. Such behavior is now considered unsafe from a user perspective and will raise an error in the future. """ def test_insufficient_width_positive(self): args = (10,) kwargs = {'width': 2} self.message = ("Insufficient bit width provided. This behavior " "will raise an error in the future.") self.assert_deprecated(np.binary_repr, args=args, kwargs=kwargs) def test_insufficient_width_negative(self): args = (-5,) kwargs = {'width': 2} self.message = ("Insufficient bit width provided. This behavior " "will raise an error in the future.") self.assert_deprecated(np.binary_repr, args=args, kwargs=kwargs) class TestNumericStyleTypecodes(_DeprecationTestCase): """ Deprecate the old numeric-style dtypes, which are especially confusing for complex types, e.g. Complex32 -> complex64. When the deprecation cycle is complete, the check for the strings should be removed from PyArray_DescrConverter in descriptor.c, and the deprecated keys should not be added as capitalized aliases in _add_aliases in numerictypes.py. """ def test_all_dtypes(self): deprecated_types = [ 'Bool', 'Complex32', 'Complex64', 'Float16', 'Float32', 'Float64', 'Int8', 'Int16', 'Int32', 'Int64', 'Object0', 'Timedelta64', 'UInt8', 'UInt16', 'UInt32', 'UInt64', 'Void0' ] for dt in deprecated_types: self.assert_deprecated(np.dtype, exceptions=(TypeError,), args=(dt,)) class TestTestDeprecated: def test_assert_deprecated(self): test_case_instance = _DeprecationTestCase() test_case_instance.setup() assert_raises(AssertionError, test_case_instance.assert_deprecated, lambda: None) def foo(): warnings.warn("foo", category=DeprecationWarning, stacklevel=2) test_case_instance.assert_deprecated(foo) test_case_instance.teardown() class TestNonNumericConjugate(_DeprecationTestCase): """ Deprecate no-op behavior of ndarray.conjugate on non-numeric dtypes, which conflicts with the error behavior of np.conjugate. """ def test_conjugate(self): for a in np.array(5), np.array(5j): self.assert_not_deprecated(a.conjugate) for a in (np.array('s'), np.array('2016', 'M'), np.array((1, 2), [('a', int), ('b', int)])): self.assert_deprecated(a.conjugate) class TestNPY_CHAR(_DeprecationTestCase): # 2017-05-03, 1.13.0 def test_npy_char_deprecation(self): from numpy.core._multiarray_tests import npy_char_deprecation self.assert_deprecated(npy_char_deprecation) assert_(npy_char_deprecation() == 'S1') class TestPyArray_AS1D(_DeprecationTestCase): def test_npy_pyarrayas1d_deprecation(self): from numpy.core._multiarray_tests import npy_pyarrayas1d_deprecation assert_raises(NotImplementedError, npy_pyarrayas1d_deprecation) class TestPyArray_AS2D(_DeprecationTestCase): def test_npy_pyarrayas2d_deprecation(self): from numpy.core._multiarray_tests import npy_pyarrayas2d_deprecation assert_raises(NotImplementedError, npy_pyarrayas2d_deprecation) class Test_UPDATEIFCOPY(_DeprecationTestCase): """ v1.14 deprecates creating an array with the UPDATEIFCOPY flag, use WRITEBACKIFCOPY instead """ def test_npy_updateifcopy_deprecation(self): from numpy.core._multiarray_tests import npy_updateifcopy_deprecation arr = np.arange(9).reshape(3, 3) v = arr.T self.assert_deprecated(npy_updateifcopy_deprecation, args=(v,)) class TestDatetimeEvent(_DeprecationTestCase): # 2017-08-11, 1.14.0 def test_3_tuple(self): for cls in (np.datetime64, np.timedelta64): # two valid uses - (unit, num) and (unit, num, den, None) self.assert_not_deprecated(cls, args=(1, ('ms', 2))) self.assert_not_deprecated(cls, args=(1, ('ms', 2, 1, None))) # trying to use the event argument, removed in 1.7.0, is deprecated # it used to be a uint8 self.assert_deprecated(cls, args=(1, ('ms', 2, 'event'))) self.assert_deprecated(cls, args=(1, ('ms', 2, 63))) self.assert_deprecated(cls, args=(1, ('ms', 2, 1, 'event'))) self.assert_deprecated(cls, args=(1, ('ms', 2, 1, 63))) class TestTruthTestingEmptyArrays(_DeprecationTestCase): # 2017-09-25, 1.14.0 message = '.*truth value of an empty array is ambiguous.*' def test_1d(self): self.assert_deprecated(bool, args=(np.array([]),)) def test_2d(self): self.assert_deprecated(bool, args=(np.zeros((1, 0)),)) self.assert_deprecated(bool, args=(np.zeros((0, 1)),)) self.assert_deprecated(bool, args=(np.zeros((0, 0)),)) class TestBincount(_DeprecationTestCase): # 2017-06-01, 1.14.0 def test_bincount_minlength(self): self.assert_deprecated(lambda: np.bincount([1, 2, 3], minlength=None)) class TestAlen(_DeprecationTestCase): # 2019-08-02, 1.18.0 def test_alen(self): self.assert_deprecated(lambda: np.alen(np.array([1, 2, 3]))) class TestGeneratorSum(_DeprecationTestCase): # 2018-02-25, 1.15.0 def test_generator_sum(self): self.assert_deprecated(np.sum, args=((i for i in range(5)),)) class TestSctypeNA(_VisibleDeprecationTestCase): # 2018-06-24, 1.16 def test_sctypeNA(self): self.assert_deprecated(lambda: np.sctypeNA['?']) self.assert_deprecated(lambda: np.typeNA['?']) self.assert_deprecated(lambda: np.typeNA.get('?')) class TestPositiveOnNonNumerical(_DeprecationTestCase): # 2018-06-28, 1.16.0 def test_positive_on_non_number(self): self.assert_deprecated(operator.pos, args=(np.array('foo'),)) class TestFromstring(_DeprecationTestCase): # 2017-10-19, 1.14 def test_fromstring(self): self.assert_deprecated(np.fromstring, args=('\x00'*80,)) class TestFromStringAndFileInvalidData(_DeprecationTestCase): # 2019-06-08, 1.17.0 # Tests should be moved to real tests when deprecation is done. message = "string or file could not be read to its end" @pytest.mark.parametrize("invalid_str", [",invalid_data", "invalid_sep"]) def test_deprecate_unparsable_data_file(self, invalid_str): x = np.array([1.51, 2, 3.51, 4], dtype=float) with tempfile.TemporaryFile(mode="w") as f: x.tofile(f, sep=',', format='%.2f') f.write(invalid_str) f.seek(0) self.assert_deprecated(lambda: np.fromfile(f, sep=",")) f.seek(0) self.assert_deprecated(lambda: np.fromfile(f, sep=",", count=5)) # Should not raise: with warnings.catch_warnings(): warnings.simplefilter("error", DeprecationWarning) f.seek(0) res = np.fromfile(f, sep=",", count=4) assert_array_equal(res, x) @pytest.mark.parametrize("invalid_str", [",invalid_data", "invalid_sep"]) def test_deprecate_unparsable_string(self, invalid_str): x = np.array([1.51, 2, 3.51, 4], dtype=float) x_str = "1.51,2,3.51,4{}".format(invalid_str) self.assert_deprecated(lambda: np.fromstring(x_str, sep=",")) self.assert_deprecated(lambda: np.fromstring(x_str, sep=",", count=5)) # The C-level API can use not fixed size, but 0 terminated strings, # so test that as well: bytestr = x_str.encode("ascii") self.assert_deprecated(lambda: fromstring_null_term_c_api(bytestr)) with assert_warns(DeprecationWarning): # this is slightly strange, in that fromstring leaves data # potentially uninitialized (would be good to error when all is # read, but count is larger then actual data maybe). res = np.fromstring(x_str, sep=",", count=5) assert_array_equal(res[:-1], x) with warnings.catch_warnings(): warnings.simplefilter("error", DeprecationWarning) # Should not raise: res = np.fromstring(x_str, sep=",", count=4) assert_array_equal(res, x) class Test_GetSet_NumericOps(_DeprecationTestCase): # 2018-09-20, 1.16.0 def test_get_numeric_ops(self): from numpy.core._multiarray_tests import getset_numericops self.assert_deprecated(getset_numericops, num=2) # empty kwargs prevents any state actually changing which would break # other tests. self.assert_deprecated(np.set_numeric_ops, kwargs={}) assert_raises(ValueError, np.set_numeric_ops, add='abc') class TestShape1Fields(_DeprecationTestCase): warning_cls = FutureWarning # 2019-05-20, 1.17.0 def test_shape_1_fields(self): self.assert_deprecated(np.dtype, args=([('a', int, 1)],)) class TestNonZero(_DeprecationTestCase): # 2019-05-26, 1.17.0 def test_zerod(self): self.assert_deprecated(lambda: np.nonzero(np.array(0))) self.assert_deprecated(lambda: np.nonzero(np.array(1))) def test_deprecate_ragged_arrays(): # 2019-11-29 1.19.0 # # NEP 34 deprecated automatic object dtype when creating ragged # arrays. Also see the "ragged" tests in `test_multiarray` # # emits a VisibleDeprecationWarning arg = [1, [2, 3]] with assert_warns(np.VisibleDeprecationWarning): np.array(arg) class TestToString(_DeprecationTestCase): # 2020-03-06 1.19.0 message = re.escape("tostring() is deprecated. Use tobytes() instead.") def test_tostring(self): arr = np.array(list(b"test\xFF"), dtype=np.uint8) self.assert_deprecated(arr.tostring) def test_tostring_matches_tobytes(self): arr = np.array(list(b"test\xFF"), dtype=np.uint8) b = arr.tobytes() with assert_warns(DeprecationWarning): s = arr.tostring() assert s == b class TestDTypeCoercion(_DeprecationTestCase): # 2020-02-06 1.19.0 message = "Converting .* to a dtype .*is deprecated" deprecated_types = [ # The builtin scalar super types: np.generic, np.flexible, np.number, np.inexact, np.floating, np.complexfloating, np.integer, np.unsignedinteger, np.signedinteger, # character is a deprecated S1 special case: np.character, ] def test_dtype_coercion(self): for scalar_type in self.deprecated_types: self.assert_deprecated(np.dtype, args=(scalar_type,)) def test_array_construction(self): for scalar_type in self.deprecated_types: self.assert_deprecated(np.array, args=([], scalar_type,)) def test_not_deprecated(self): # All specific types are not deprecated: for group in np.sctypes.values(): for scalar_type in group: self.assert_not_deprecated(np.dtype, args=(scalar_type,)) for scalar_type in [type, dict, list, tuple]: # Typical python types are coerced to object currently: self.assert_not_deprecated(np.dtype, args=(scalar_type,)) class BuiltInRoundComplexDType(_DeprecationTestCase): # 2020-03-31 1.19.0 deprecated_types = [np.csingle, np.cdouble, np.clongdouble] not_deprecated_types = [ np.int8, np.int16, np.int32, np.int64, np.uint8, np.uint16, np.uint32, np.uint64, np.float16, np.float32, np.float64, ] def test_deprecated(self): for scalar_type in self.deprecated_types: scalar = scalar_type(0) self.assert_deprecated(round, args=(scalar,)) self.assert_deprecated(round, args=(scalar, 0)) self.assert_deprecated(round, args=(scalar,), kwargs={'ndigits': 0}) def test_not_deprecated(self): for scalar_type in self.not_deprecated_types: scalar = scalar_type(0) self.assert_not_deprecated(round, args=(scalar,)) self.assert_not_deprecated(round, args=(scalar, 0)) self.assert_not_deprecated(round, args=(scalar,), kwargs={'ndigits': 0}) class TestIncorrectAdvancedIndexWithEmptyResult(_DeprecationTestCase): # 2020-05-27, NumPy 1.20.0 message = "Out of bound index found. This was previously ignored.*" @pytest.mark.parametrize("index", [([3, 0],), ([0, 0], [3, 0])]) def test_empty_subspace(self, index): # Test for both a single and two/multiple advanced indices. These # This will raise an IndexError in the future. arr = np.ones((2, 2, 0)) self.assert_deprecated(arr.__getitem__, args=(index,)) self.assert_deprecated(arr.__setitem__, args=(index, 0.)) # for this array, the subspace is only empty after applying the slice arr2 = np.ones((2, 2, 1)) index2 = (slice(0, 0),) + index self.assert_deprecated(arr2.__getitem__, args=(index2,)) self.assert_deprecated(arr2.__setitem__, args=(index2, 0.)) def test_empty_index_broadcast_not_deprecated(self): arr = np.ones((2, 2, 2)) index = ([[3], [2]], []) # broadcast to an empty result. self.assert_not_deprecated(arr.__getitem__, args=(index,)) self.assert_not_deprecated(arr.__setitem__, args=(index, np.empty((2, 0, 2))))
abalkin/numpy
numpy/core/tests/test_deprecations.py
Python
bsd-3-clause
25,399
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title>statsmodels.genmod.qif.QIF.endog_names &#8212; statsmodels v0.10.2 documentation</title> <link rel="stylesheet" href="../_static/nature.css" type="text/css" /> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" /> <link rel="stylesheet" type="text/css" href="../_static/graphviz.css" /> <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script> <script type="text/javascript" src="../_static/jquery.js"></script> <script type="text/javascript" src="../_static/underscore.js"></script> <script type="text/javascript" src="../_static/doctools.js"></script> <script type="text/javascript" src="../_static/language_data.js"></script> <script async="async" type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/latest.js?config=TeX-AMS-MML_HTMLorMML"></script> <link rel="shortcut icon" href="../_static/statsmodels_hybi_favico.ico"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="stylesheet" href="../_static/examples.css" type="text/css" /> <link rel="stylesheet" href="../_static/facebox.css" type="text/css" /> <script type="text/javascript" src="../_static/scripts.js"> </script> <script type="text/javascript" src="../_static/facebox.js"> </script> <script type="text/javascript"> $.facebox.settings.closeImage = "../_static/closelabel.png" $.facebox.settings.loadingImage = "../_static/loading.gif" </script> <script> $(document).ready(function() { $.getJSON("../../versions.json", function(versions) { var dropdown = document.createElement("div"); dropdown.className = "dropdown"; var button = document.createElement("button"); button.className = "dropbtn"; button.innerHTML = "Other Versions"; var content = document.createElement("div"); content.className = "dropdown-content"; dropdown.appendChild(button); dropdown.appendChild(content); $(".header").prepend(dropdown); for (var i = 0; i < versions.length; i++) { if (versions[i].substring(0, 1) == "v") { versions[i] = [versions[i], versions[i].substring(1)]; } else { versions[i] = [versions[i], versions[i]]; }; }; for (var i = 0; i < versions.length; i++) { var a = document.createElement("a"); a.innerHTML = versions[i][1]; a.href = "../../" + versions[i][0] + "/index.html"; a.title = versions[i][1]; $(".dropdown-content").append(a); }; }); }); </script> </head><body> <div class="headerwrap"> <div class = "header"> <a href = "../index.html"> <img src="../_static/statsmodels_hybi_banner.png" alt="Logo" style="padding-left: 15px"/></a> </div> </div> <div class="related" role="navigation" aria-label="related navigation"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li><a href ="../install.html">Install</a></li> &nbsp;|&nbsp; <li><a href="https://groups.google.com/forum/?hl=en#!forum/pystatsmodels">Support</a></li> &nbsp;|&nbsp; <li><a href="https://github.com/statsmodels/statsmodels/issues">Bugs</a></li> &nbsp;|&nbsp; <li><a href="../dev/index.html">Develop</a></li> &nbsp;|&nbsp; <li><a href="../examples/index.html">Examples</a></li> &nbsp;|&nbsp; <li><a href="../faq.html">FAQ</a></li> &nbsp;|&nbsp; </ul> </div> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <div class="section" id="statsmodels-genmod-qif-qif-endog-names"> <h1>statsmodels.genmod.qif.QIF.endog_names<a class="headerlink" href="#statsmodels-genmod-qif-qif-endog-names" title="Permalink to this headline">¶</a></h1> <dl class="method"> <dt id="statsmodels.genmod.qif.QIF.endog_names"> <em class="property">property </em><code class="sig-prename descclassname">QIF.</code><code class="sig-name descname">endog_names</code><a class="headerlink" href="#statsmodels.genmod.qif.QIF.endog_names" title="Permalink to this definition">¶</a></dt> <dd><p>Names of endogenous variables</p> </dd></dl> </div> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="main navigation"> <div class="sphinxsidebarwrapper"> <div role="note" aria-label="source link"> <h3>This Page</h3> <ul class="this-page-menu"> <li><a href="../_sources/generated/statsmodels.genmod.qif.QIF.endog_names.rst.txt" rel="nofollow">Show Source</a></li> </ul> </div> <div id="searchbox" style="display: none" role="search"> <h3 id="searchlabel">Quick search</h3> <div class="searchformwrapper"> <form class="search" action="../search.html" method="get"> <input type="text" name="q" aria-labelledby="searchlabel" /> <input type="submit" value="Go" /> </form> </div> </div> <script type="text/javascript">$('#searchbox').show(0);</script> </div> </div> <div class="clearer"></div> </div> <div class="footer" role="contentinfo"> &#169; Copyright 2009-2018, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers. Created using <a href="http://sphinx-doc.org/">Sphinx</a> 2.2.1. </div> </body> </html>
statsmodels/statsmodels.github.io
v0.10.2/generated/statsmodels.genmod.qif.QIF.endog_names.html
HTML
bsd-3-clause
5,811
/** * @createTime 2014-12-18 * @author louis.tru <[email protected]> * @copyright © 2011 louis.tru, http://mooogame.com * @version 1.0 */ include('tesla/web/service/HttpService.js'); include('tesla/web/service/Conversation.js'); include('teide/Settings.js'); include('teide/touch/Console.js'); include('teide/touch/ScriptService.js'); var Settings = teide.Settings; var fs = tesla.node.fsx; function get_icon(name){ var mat = name.match(/\.([^\.]+)$/); if(mat){ return mat[1].replace(/\+/g, 'p').toLowerCase(); } return ''; } /** * 是否要排除文件 */ function is_exclude_file(name){ name = name.toLowerCase(); // 使用微信SDK后会有这个文件 if (name.indexOf('tencent_wxo_analysis') != -1) { return true; } var exclude_files = { /* 使用ShareSDK后会有这个文件 */ 'tcsdkconfig.plus': true, /* * apple ios 外部打开的文件会自动创建这个文件夹, * 且这个文件夹还没有权限删除,所以不需要显示它 */ 'inbox': true, }; // console.log('is_exclude_file', name); exclude_files[Settings.SETTINGS_FILE_NAME.toLowerCase()] = true; if(name in exclude_files){ return true; } // if(/\.map\/entity$/.test(name) || /\.map\/conf.keys/.test(name)){ if(/\.map(\/|$)/.test(name)){ return true; } return false; } // 支持的所有后缀 var support_find_suffix = 'abap|asciidoc|c9search_results|search|Cakefile|coffee|cf|cfm|cs|css|dart|diff|patch|dot|\ glsl|frag|vert|vp|fp|go|groovy|hx|haml|htm|html|xhtml|c|cc|cpp|cxx|h|hh|hpp|clj|jade|java|\ jsp|js|json|conf|jsx|te|teh|latex|tex|ltx|bib|less|lisp|scm|rkt|liquid|lua|lp|lucene|\ GNUmakefile|makefile|Makefile|OCamlMakefile|make|mk|keys|script|log|module|map|\ md|markdown|m|mm|ml|mli|pl|pm|pgsql|php|phtml|ps1|py|gyp|gypi|r|Rd|Rhtml|ru|gemspec|rake|rb|\ scad|scala|scss|sass|sh|bash|bat|sql|styl|stylus|svg|tcl|tex|txt|textile|typescript|ts|str|\ xml|rdf|rss|wsdl|xslt|atom|mathml|mml|xul|xbl|vx|xq|yaml'.toLowerCase().split('|'); /** * 是否可以搜索的文件 */ function is_find(path){ var suffix = path.match(/[^\.\/]+$/)[0].toLowerCase(); return support_find_suffix.indexOf(suffix) != -1; } var console_log_file = 'console.log'; function getReadOnly(filename){ if(filename == console_log_file){ return true; } return false; } // 是否可运行 function is_run(filename){ var service = teide.touch.ScriptService.share(); return service.is_can_run(filename); } /* * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) * because the buffer-to-string conversion in `fs.readFileSync()` * translates it to FEFF, the UTF-16 BOM. */ function stripBOM(buff) { //0xFEFF //0xFFFE var c = buff[0];//.charCodeAt(0); if (c === 0xFEFF || c == 0xFFFE) { return buff.slice(1); } return buff; } // 查找文本中换行的数量与最后上个换行符号的位置 function find_wrap(text){ var count = 0; var index = -1; while(true){ var i = text.indexOf('\n', index + 1); if(i == -1){ break; } count++; index = i; } return { count: count, lastIndex: index }; } /** * 搜索文件 * @private */ function find_file(self, path, name, data, cb, end_cb){ // 是否要跳过文件,从指定位置开始 if(data.result.index < data.index){ data.result.index++; return cb(); // 跳过 } data.result.index++; // 增加一个索引 if(!is_find(name)){ // 不支持的文件格式 return cb(); } fs.readFile(self.documentsPath + path + name, function(err, buff){ if(err){ return cb(err); } // TODO find string var results = []; var code = stripBOM(buff).toString('utf-8'); // var cur_row = 0; // 当前行数 var prev_index = 0; // 上一个匹配的位置 var match = data.regexp.exec(code); function match_code(){ if(current_find_id != data.current_find_id){ // 是否还在查询中 return end_cb(); } var index = -1; var match_count = 0; while(match){ if(index == match.index){ // 如果一直相等就会死循环了 // return end_cb('The query expression error'); return end_cb($t('查询表达式格式错误')); } index = match.index; match_count++; if(match_count > 100){ // 歇会,这里主要是不想出现死循环,把线程阻塞 return match_code.delay2(10); } var wrap = find_wrap(code.substring(prev_index, index)); var last_wrap_index = prev_index + wrap.lastIndex; // 最后一个换行符位置 cur_row += wrap.count; // 加上经过的换行 var length = match[0].length; var start = index - last_wrap_index - 1; //列开始位置 var html_0_len = Math.min(start, 30); // 最多显示30个字符 var html_2_len = code.substr(index + length, 30).indexOf('\n'); results.push({ row: cur_row, start: start, length: length, html: [ code.substr(index - html_0_len, html_0_len).trimLeft(), code.substr(index, length), // 匹配的文本 code.substr(index + length, html_2_len == -1 ? 30 : html_2_len).trimRight() ] }); prev_index = index; match = data.regexp.exec(code); // 继续匹配 } if(results.length){ // 如果有结果返回这个文件 data.result.data.push({ icon: get_icon(name), text: name, path: path.substr(0, path.length - 1), results: results, count: results.length, expand: data.expand_class }); data.result.count++; } cb(); } match_code(); }); } /** * 当前是否正在查询 * 为性能考虑一次只能进行一次查询 * @private */ var current_find_id = 0; /** * 搜索目录 * @private */ function find_dir(self, path, data, cb, end_cb){ if(current_find_id != data.current_find_id){ // 是否还在查询中 return end_cb(); } var ls = null; var documentsPath = self.documentsPath; function callback(err){ if(err){ return end_cb(err); } if(data.result.count > 49){ // 匹配的文件达到50个停止搜索 data.result.is_end = false; // 标记为没有结束 return end_cb(); } if(!ls.length){ return cb(); } var name = ls.shift(); // 忽略影藏文件,与app设置文件 if(is_exclude_file(name) || name.slice(0, 1) == '.'){ return callback(); } fs.stat(documentsPath + path + name, function(err, stat){ if(err){ return end_cb(err); } if(stat.isFile()){ find_file(self, path, name, data, callback, end_cb); } else{ find_dir(self, path + name + '/', data, callback, end_cb); } }); } // 读取目录 fs.readdir(documentsPath + path, function(err, list){ if(err){ return end_cb(err); } ls = list; callback(); }); } //set util function setHeader(self) { var res = self.response; res.setHeader('Server', 'Tesla framework, Touch Code'); res.setHeader('Date', new Date().toUTCString()); var expires = self.server.expires; if(expires){ res.setHeader('Expires', new Date().add(6e4 * expires).toUTCString()); res.setHeader('Cache-Control', 'public, max-age=' + (expires * 60)); } } /** * @param {String} */ function uploadFile(self, path, cb) { if (self.request.method != 'POST') { return cb(); } var files = self.data.file; // 上传的文件列表 if(!files.length){ // 没有上传文件 return cb(); } var index = path.indexOf('?'); if(index != -1){ path = path.substring(0, index); } var documentsPath = self.documentsPath; var relative_dir = path ? path.replace(/\/?$/, '/') : ''; var dir = documentsPath + relative_dir; var output = []; function h() { if(!files.length){ // 通知连接的所有客户端 // 获取所socket连接 var convs = tesla.web.service.Conversation.all(); for(var token in convs){ var services = convs[token].services; // 获取绑定的服务 for(var name in services){ if(name == 'teide.touch.FileActionService'){ // 通知服务上传了文件 services[name].onupload_file_notice(relative_dir, output); } } } return cb(); } var file = files.shift(); var filename = file.filename; if(!filename){ return h(); } fs.exists(file.path, function(exists){ if(!exists){ return h(); } teide.touch.Console.share().log('Upload', './' + filename); output.push(filename); fs.rename(file.path, dir + filename, h.cb(cb)); }); } h(); } function readDocumentDirectory(self, path){ var res = self.response; var req = self.request; //读取目录 if (path && !path.match(/\/$/)){ //目录不正确,重定向 return self.redirect(self.cleanurl.replace(/\/?$/, '/')); } fs.ls(self.documentsPath + path, function(err, files) { if (err){ return self.returnStatus(404); } teide.touch.Console.share().log('Readdir', './' + path); var html = '<!DOCTYPE html><html><head><title>Index of {0}</title>'.format(path) + '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' + '<style type="text/css">*{font-family:Courier New}div,span{line-height:20px;' + 'height:20px;}span{display:block;float:right;width:220px}</style>' + '</head><body bgcolor="white">' + '<h1>Touch Code documents</h1>'+ '<h4>Index of {0}</h4><hr/><pre><div><a href="{1}">../</a></div>' .format(path, path ? '../' : 'javascript:'); var ls0 = []; var ls1 = []; for (var i = 0, stat; (stat = files[i]); i++) { var name = stat.name; if(is_exclude_file(path + name)){ continue; } var link = name; var size = (stat.size / 1024).toFixed(2) + ' KB'; var isdir = stat.dir; if (isdir) { link += '/'; size = '-'; } else{ if(/\.script$/i.test(name)){ continue; // 禁止访问 } } var s = '<div><a href="{0}">{0}</a><span>{2}</span><span>{1}</span></div>' .format(link, stat.ctime.toString('yyyy-MM-dd hh:mm:ss'), size); isdir ? ls0.push(s) : ls1.push(s); } html += ls0.join('') + ls1.join('') + '</pre>'; var from = [ '<form enctype="multipart/form-data" method="post">', '<input type="file" name="file" multiple="" />', '<input type="submit" value="upload" />', '</form>', ]; html += from.join('\n'); html += '<hr/></body></html>'; setHeader(self); var type = self.server.getMIME('html'); res.writeHead(200, { 'Content-Type': type }); res.end(html); }); } /** * @class teide.touch.APIService * @extends tesla.web.service.HttpService */ Class('teide.touch.APIService', tesla.web.service.HttpService, { /** * 文档根路径 */ documentsPath: '', /** * @constructor */ APIService: function(){ this.documentsPath = teide.touch.TouchServer.share().getDocumentsPath(); }, //overlay auth: function(cb, action) { //console.log('auth', action); if(this.form){ // 默认为不允许上传文件,这里设置为可以 this.form.isUpload = (action == 'readDocuments'); } cb(true); }, /** * 获取本机系统网络信息 */ networkInterfaces: function(cb){ var ifaces = te.node.os.networkInterfaces(); var data = { ifaces: ifaces, port: this.server.port }; cb(null, data); }, /** * read file as text * @param {String} filename * @param {Function} cb */ readFileAsText: function(filename, cb) { var self = this; var root = this.documentsPath; var path = root + filename; fs.stat(path, function(stat){ if (stat.size > self.server.maxFileSize) {// File size exceeds the limit return cb($t('文件大小超过限制')); } fs.readFile(path, function(buff) { var value = Settings.get(root).getFileProperty(filename); cb(null, { code: buff + '', breakpoints: value.breakpoints, folds: value.folds, readonly: getReadOnly(filename), is_run: is_run(filename), }); }.cb(cb)); }.cb(cb)); }, // 读取偏好设置 get_preferences: function(cb){ cb(null, Settings.get(this.documentsPath).get_preferences()); }, // 保存偏好设置 set_preferences: function(preferences, cb){ Settings.get(this.documentsPath).set_preferences(preferences) cb(); }, /** * 返回html */ touch: function(){ this.return_site_file('teide/touch/html/touch.htm'); }, /** * 返回html */ touch_debug: function(cb){ this.return_site_file('teide/touch/html/touch_debug.htm'); }, /** * read file * @param {String} filename * @param {Function} cb */ readFile: function(filename, cb){ // var self = this; var name = filename.replace(/\?.*$/, ''); // fs.readFile(this.documentsPath + name, function(err, data){ // if(err){ // return self.returnStatus(404, err.message); // } // self.returnData(self.server.getMIME(name), data); // }); this.setHeaders = function(res, status){ res.removeHeader('Expires'); // 删除默认的过期头 res.removeHeader('Cache-Control'); res.removeHeader('Last-Modified'); // console.log(filename, status); return status; }; this.returnFile(this.documentsPath + name); }, /** * 读取文档 */ readDocuments: function(path, cb){ var name = path; var index = name.indexOf('?'); var self = this; if(index != -1){ name = path.substring(0, index); } if(is_exclude_file(name) || /\.script$/i.test(name)){ return this.returnStatus(403); // 禁止访问 } fs.stat(this.documentsPath + name, function(err, stat){ if(!err && stat.isDirectory()){ uploadFile(self, path, function(err){ if(err){ return self.returnStatus(500, err.message); // 错误 } readDocumentDirectory(self, path); }); } else{ if(/\.script$/i.test(name)){ this.returnStatus(403); // 禁止访问 } else{ teide.touch.Console.share().log('Readfile', './' + name); self.returnFile(self.documentsPath + name); } } }); }, /** * 停止搜索 */ stopFind: function(){ current_find_id = 0; // 停止查询 }, /** * 查询文件 */ find: function(param, cb){ if(current_find_id){ return cb($t('请先结束当前查询才能开始新的查询')); } current_find_id = tesla.guid(); var self = this; var key = param.key; var options = param.options; var path = param.path; var data = { result: { data: [], // 这种文件内部查询非常耗时,没有办法知道有多少个文件匹配成功 // 只能一次查询部分结果,再次查询时以上次结束的位置开始. total: 0, count: 0, // 一次最多返回50个文件的搜索结果? index: 0, // 当前查询到的文件位置 is_end: true // 是否查询结束,告诉客户端不需要发起后续查询 }, index: param.index || 0, // 从指定的文件位置开始 current_find_id: current_find_id, // 当前查询的标识 enable_hide_file: options.enable_hide_file, // 是否查询隐藏的文件 expand_class: options.expand_all_results ? 'expand' : '', // 是否要展开结果 // 查询表达式 regexp: new RegExp( options.enable_regexp ? key : // 使用正则 key.replace(/([\\\[\]\(\)\{\}\.\$\&\*\+\-\^\?\|\<\>\=])/g, '\\$1'), // 使用普通文本匹配 options.ignoring_case ? 'img' : 'mg') }; // this.conversation.onclose.on(function(){ // 监控连接是否关闭 // current_find_id = 0; // }); this.response.on('close', function(){ // 监控连接是否关闭 current_find_id = 0; }); function callback(err){ current_find_id = 0; cb(err, data.result); } fs.stat(this.documentsPath + path, function(stat){ if(stat.isFile()){ var ls = path.split('/'); var name = ls.pop(); find_file(self, ls.length ? ls.join('/') + '/' : '', name, data, callback, callback); } else{ find_dir(self, path ? path.replace(/\/?$/, '/') : '', data, callback, callback); } }.cb(callback)); } }, { /** * 支持的后缀 */ support_find_suffix: support_find_suffix, /** * 是否要排除文件 */ is_exclude_file: is_exclude_file, });
louis-tru/touch_code
server/teide/touch/APIService.js
JavaScript
bsd-3-clause
17,781
// Copyright 2018-present 650 Industries. All rights reserved. #ifdef __cplusplus #import <jsi/jsi.h> #import <ReactCommon/RCTTurboModule.h> #import <ExpoModulesCore/EXNativeModulesProxy.h> using namespace facebook; using namespace react; namespace expo { using PromiseInvocationBlock = void (^)(RCTPromiseResolveBlock resolveWrapper, RCTPromiseRejectBlock rejectWrapper); void callPromiseSetupWithBlock(jsi::Runtime &runtime, std::shared_ptr<CallInvoker> jsInvoker, std::shared_ptr<Promise> promise, PromiseInvocationBlock setupBlock); class JSI_EXPORT ExpoModulesProxySpec : public TurboModule { public: ExpoModulesProxySpec(std::shared_ptr<CallInvoker> callInvoker, EXNativeModulesProxy *nativeModulesProxy); EXNativeModulesProxy *nativeModulesProxy; }; } // namespace expo #endif
exponentjs/exponent
packages/expo-modules-core/ios/JSI/ExpoModulesProxySpec.h
C
bsd-3-clause
799
#ifndef __KERN_UNIT_X86_64_TYPES_H__ #define __KERN_UNIT_X86_64_TYPES_H__ #include <stdint.h> #include <kern/unit/x86/types.h> typedef uintptr_t pml4e_t; typedef uintptr_t pdpe_t; #endif /* __KERN_UNIT_X86_64_TYPES_H__ */
vendu/OS-Zero
kern/unit/x86-64/types.h
C
bsd-3-clause
226
Zend Framework 1 for Composer ============================= This package is a part of the Zend Framework 1. Each component was separated and put into its own composer package. Some modifications were made for improved [Composer](http://getcomposer.org/) integration. This package can also be found at [Packagist](http://packagist.org/packages/zf1). ## Why? **Size!** Zend Framework is very large and contains a huge amount of files (over 72000 files in the main repository!). If you're only using a part of the framework, using the separated packages will greatly reduce the amount of files. This will make setup faster and easier on your disks. **Autoloading!** Explicit `require_once` calls in the source code has been commented out to rely on composer autoloading, this reduces the number of included files to a minimum. **Migration!** Zend Framework 2 has been around for a while now, and migrating all your projects takes a lot of time. Using these packages makes it easier to migrate each component separately. Also, some packages doesn't exist in zf2 (such as the zend-search-lucene), now you can continue using that package without requiring the entire framework. If you're using major parts of the framework, I would recommend checking out the [zendframework1 package](https://github.com/bombayworks/zendframework1), which contains the entire framework optimized for composer usage. ## How to use Add `"zf1/zend-dom": "~1.12"` to the require section of your composer.json, include the composer autoloader and you're good to go. ## Broken dependencies? Dependencies have been set automatically based on the [requirements from the zend framework manual](http://framework.zend.com/manual/1.12/en/requirements.introduction.html), if you find any broken dependencies please submit an issue.
zf1/zend-dom
README.md
Markdown
bsd-3-clause
1,825
/* $OpenBSD: event.h,v 1.3 2001/03/01 20:54:35 provos Exp $ */ /*- * Copyright (c) 1999,2000,2001 Jonathan Lemon <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD: src/sys/sys/event.h,v 1.11 2001/02/24 01:41:31 jlemon Exp $ */ #ifndef _SYS_EVENT_H_ #define _SYS_EVENT_H_ #define EVFILT_READ (-1) #define EVFILT_WRITE (-2) #define EVFILT_AIO (-3) /* attached to aio requests */ #define EVFILT_VNODE (-4) /* attached to vnodes */ #define EVFILT_PROC (-5) /* attached to struct proc */ #define EVFILT_SIGNAL (-6) /* attached to struct proc */ #define EVFILT_SYSCOUNT 6 #define EV_SET(kevp, a, b, c, d, e, f) do { \ (kevp)->ident = (a); \ (kevp)->filter = (b); \ (kevp)->flags = (c); \ (kevp)->fflags = (d); \ (kevp)->data = (e); \ (kevp)->udata = (f); \ } while(0) struct kevent { u_int ident; /* identifier for this event */ short filter; /* filter for event */ u_short flags; u_int fflags; int data; void *udata; /* opaque user data identifier */ }; /* actions */ #define EV_ADD 0x0001 /* add event to kq (implies enable) */ #define EV_DELETE 0x0002 /* delete event from kq */ #define EV_ENABLE 0x0004 /* enable event */ #define EV_DISABLE 0x0008 /* disable event (not reported) */ /* flags */ #define EV_ONESHOT 0x0010 /* only report one occurrence */ #define EV_CLEAR 0x0020 /* clear event state after reporting */ #define EV_SYSFLAGS 0xF000 /* reserved by system */ #define EV_FLAG1 0x2000 /* filter-specific flag */ /* returned values */ #define EV_EOF 0x8000 /* EOF detected */ #define EV_ERROR 0x4000 /* error, data contains errno */ /* * data/hint flags for EVFILT_{READ|WRITE}, shared with userspace */ #define NOTE_LOWAT 0x0001 /* low water mark */ /* * data/hint flags for EVFILT_VNODE, shared with userspace */ #define NOTE_DELETE 0x0001 /* vnode was removed */ #define NOTE_WRITE 0x0002 /* data contents changed */ #define NOTE_EXTEND 0x0004 /* size increased */ #define NOTE_ATTRIB 0x0008 /* attributes changed */ #define NOTE_LINK 0x0010 /* link count changed */ #define NOTE_RENAME 0x0020 /* vnode was renamed */ #define NOTE_REVOKE 0x0040 /* vnode access was revoked */ /* * data/hint flags for EVFILT_PROC, shared with userspace */ #define NOTE_EXIT 0x80000000 /* process exited */ #define NOTE_FORK 0x40000000 /* process forked */ #define NOTE_EXEC 0x20000000 /* process exec'd */ #define NOTE_PCTRLMASK 0xf0000000 /* mask for hint bits */ #define NOTE_PDATAMASK 0x000fffff /* mask for pid */ /* additional flags for EVFILT_PROC */ #define NOTE_TRACK 0x00000001 /* follow across forks */ #define NOTE_TRACKERR 0x00000002 /* could not track child */ #define NOTE_CHILD 0x00000004 /* am a child process */ /* * This is currently visible to userland to work around broken * programs which pull in <sys/proc.h> or <sys/select.h>. */ #include <sys/queue.h> struct knote; SLIST_HEAD(klist, knote); #ifdef _KERNEL #define KNOTE(list, hint) if ((list) != NULL) knote(list, hint) /* * Flag indicating hint is a signal. Used by EVFILT_SIGNAL, and also * shared by EVFILT_PROC (all knotes attached to p->p_klist) */ #define NOTE_SIGNAL 0x08000000 struct filterops { int f_isfd; /* true if ident == filedescriptor */ int (*f_attach) __P((struct knote *kn)); void (*f_detach) __P((struct knote *kn)); int (*f_event) __P((struct knote *kn, long hint)); }; struct knote { SLIST_ENTRY(knote) kn_link; /* for fd */ SLIST_ENTRY(knote) kn_selnext; /* for struct selinfo */ TAILQ_ENTRY(knote) kn_tqe; struct kqueue *kn_kq; /* which queue we are on */ struct kevent kn_kevent; int kn_status; int kn_sfflags; /* saved filter flags */ int kn_sdata; /* saved data field */ union { struct file *p_fp; /* file data pointer */ struct proc *p_proc; /* proc pointer */ } kn_ptr; struct filterops *kn_fop; caddr_t kn_hook; #define KN_ACTIVE 0x01 /* event has been triggered */ #define KN_QUEUED 0x02 /* event is on queue */ #define KN_DISABLED 0x04 /* event is disabled */ #define KN_DETACHED 0x08 /* knote is detached */ #define kn_id kn_kevent.ident #define kn_filter kn_kevent.filter #define kn_flags kn_kevent.flags #define kn_fflags kn_kevent.fflags #define kn_data kn_kevent.data #define kn_fp kn_ptr.p_fp }; struct proc; extern void knote(struct klist *list, long hint); extern void knote_remove(struct proc *p, struct klist *list); extern void knote_fdclose(struct proc *p, int fd); extern int kqueue_register(struct kqueue *kq, struct kevent *kev, struct proc *p); #else /* !_KERNEL */ #include <sys/cdefs.h> struct timespec; __BEGIN_DECLS int kqueue __P((void)); int kevent __P((int kq, const struct kevent *changelist, int nchanges, struct kevent *eventlist, int nevents, const struct timespec *timeout)); __END_DECLS #endif /* !_KERNEL */ #endif /* !_SYS_EVENT_H_ */
MarginC/kame
openbsd/sys/sys/event.h
C
bsd-3-clause
6,149
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>Content Slider - Jssor Slider, Slideshow with Javascript Source Code</title> </head> <body style="padding: 0; margin: 0; font-family: Arial, Verdana; background-color: #fff;"> <!-- use jssor.slider.min.js instead for release --> <!-- jssor.slider.min.js = (jssor.core.js + jssor.utils.js + jssor.slider.js) --> <script type="text/javascript" src="../js/jssor.core.js"></script> <script type="text/javascript" src="../js/jssor.utils.js"></script> <script type="text/javascript" src="../js/jssor.slider.js"></script> <script> jssor_slider1_starter = function (containerId) { var options = { $AutoPlay: true, //[Optional] Whether to auto play, to enable slideshow, this option must be set to true, default value is false $AutoPlayInterval: 4000, //[Optional] Interval (in milliseconds) to go for next slide since the previous stopped if the slider is auto playing, default value is 3000 $PauseOnHover: 3, //[Optional] Whether to pause when mouse over if a slider is auto playing, 0 no pause, 1 pause for desktop, 2 pause for touch device, 3 pause for desktop and touch device, default value is 3 $ArrowKeyNavigation: true, //[Optional] Allows keyboard (arrow key) navigation or not, default value is false $SlideDuration: 800, //[Optional] Specifies default duration (swipe) for slide in milliseconds, default value is 500 $MinDragOffsetToSlide: 20, //[Optional] Minimum drag offset to trigger slide , default value is 20 //$SlideWidth: 600, //[Optional] Width of every slide in pixels, default value is width of 'slides' container //$SlideHeight: 300, //[Optional] Height of every slide in pixels, default value is height of 'slides' container $SlideSpacing: 0, //[Optional] Space between each slide in pixels, default value is 0 $DisplayPieces: 1, //[Optional] Number of pieces to display (the slideshow would be disabled if the value is set to greater than 1), the default value is 1 $ParkingPosition: 0, //[Optional] The offset position to park slide (this options applys only when slideshow disabled), default value is 0. $UISearchMode: 1, //[Optional] The way (0 parellel, 1 recursive, default value is 1) to search UI components (slides container, loading screen, navigator container, arrow navigator container, thumbnail navigator container etc). $PlayOrientation: 1, //[Optional] Orientation to play slide (for auto play, navigation), 1 horizental, 2 vertical, default value is 1 $DragOrientation: 1, //[Optional] Orientation to drag slide, 0 no drag, 1 horizental, 2 vertical, 3 either, default value is 1 (Note that the $DragOrientation should be the same as $PlayOrientation when $DisplayPieces is greater than 1, or parking position is not 0) $ArrowNavigatorOptions: { //[Optional] Options to specify and enable arrow navigator or not $Class: $JssorArrowNavigator$, //[Requried] Class to create arrow navigator instance $ChanceToShow: 1, //[Required] 0 Never, 1 Mouse Over, 2 Always $AutoCenter: 2, //[Optional] Auto center arrows in parent container, 0 No, 1 Horizontal, 2 Vertical, 3 Both, default value is 0 $Steps: 1 //[Optional] Steps to go for each navigation request, default value is 1 }, $ThumbnailNavigatorOptions: { $Class: $JssorThumbnailNavigator$, //[Required] Class to create thumbnail navigator instance $ChanceToShow: 2, //[Required] 0 Never, 1 Mouse Over, 2 Always $ActionMode: 1, //[Optional] 0 None, 1 act by click, 2 act by mouse hover, 3 both, default value is 1 $AutoCenter: 0, //[Optional] Auto center thumbnail items in the thumbnail navigator container, 0 None, 1 Horizontal, 2 Vertical, 3 Both, default value is 3 $Lanes: 1, //[Optional] Specify lanes to arrange thumbnails, default value is 1 $SpacingX: 3, //[Optional] Horizontal space between each thumbnail in pixel, default value is 0 $SpacingY: 3, //[Optional] Vertical space between each thumbnail in pixel, default value is 0 $DisplayPieces: 9, //[Optional] Number of pieces to display, default value is 1 $ParkingPosition: 260, //[Optional] The offset position to park thumbnail $Orientation: 1, //[Optional] Orientation to arrange thumbnails, 1 horizental, 2 vertical, default value is 1 $DisableDrag: false //[Optional] Disable drag or not, default value is false } }; var jssor_slider1 = new $JssorSlider$(containerId, options); //responsive code begin //you can remove responsive code if you don't want the slider scales while window resizes function ScaleSlider() { var bodyWidth = document.body.clientWidth; if (bodyWidth) jssor_slider1.$SetScaleWidth(Math.min(bodyWidth, 980)); else $JssorUtils$.$Delay(ScaleSlider, 30); } ScaleSlider(); $JssorUtils$.$AddEvent(window, "load", ScaleSlider); if (!navigator.userAgent.match(/(iPhone|iPod|iPad|BlackBerry|IEMobile)/)) { $JssorUtils$.$OnWindowResize(window, ScaleSlider); } //responsive code end }; </script> <div style="position: relative; width: 100%; background-color: #003399; overflow: hidden;"> <div style="position: relative; left: 50%; width: 5000px; text-align: center; margin-left: -2500px;"> <!-- Jssor Slider Begin --> <div id="slider1_container" style="position: relative; margin: 0 auto; top: 0px; left: 0px; width: 980px; height: 400px; background: url(../img/major/main_bg.jpg) top center no-repeat;"> <!-- Loading Screen --> <div u="loading" style="position: absolute; top: 0px; left: 0px;"> <div style="filter: alpha(opacity=70); opacity: 0.7; position: absolute; display: block; top: 0px; left: 0px; width: 100%; height: 100%;"> </div> <div style="position: absolute; display: block; background: url(../img/loading.gif) no-repeat center center; top: 0px; left: 0px; width: 100%; height: 100%;"> </div> </div> <!-- Slides Container --> <div u="slides" style="cursor: move; position: absolute; left: 0px; top: 0px; width: 980px; height: 400px; overflow: hidden;"> <div> <div style="position: absolute; width: 480px; height: 300px; top: 10px; left: 10px; text-align: left; line-height: 1.8em; font-size: 12px;"> <br /> <span style="display: block; line-height: 1em; text-transform: uppercase; font-size: 52px; color: #FFFFFF;">results driven</span> <br /> <br /> <span style="display: block; line-height: 1.1em; font-size: 2.5em; color: #FFFFFF;"> iT Solutions & Services </span> <br /> <span style="display: block; line-height: 1.1em; font-size: 1.5em; color: #FFFFFF;"> Our professional services help you address the ever evolving business and technological challenges.</span> <br /> <br /> <a href="http://www.jssor.com"> <img src="../img/major/find-out-more-bt.png" border="0" alt="auction slider" width="215" height="50" /></a> </div> <img src="../img/major/s2.png" style="position: absolute; top: 23px; left: 480px; width: 500px; height: 300px;" /> <img u="thumb" src="../img/major/s2t.jpg" /> </div> <div> <div style="position: absolute; width: 480px; height: 300px; top: 10px; left: 10px; text-align: left; line-height: 1.8em; font-size: 12px;"> <span style="display: block; line-height: 1em; text-transform: uppercase; font-size: 52px; color: #FFFFFF;">web design & development</span> <br /> <br /> <span style="display: block; line-height: 1.1em; font-size: 2.5em; color: #FFFFFF;"> Visually Compelling & Functional </span> <br /> <br /> <a href="http://www.jssor.com"> <img src="../img/major/find-out-more-bt.png" border="0" alt="ebay slideshow" width="215" height="50" /></a> </div> <img src="../img/major/s3.png" style="position: absolute; top: 23px; left: 480px; width: 500px; height: 300px;" /> <img u="thumb" src="../img/major/s3t.jpg" /> </div> <div> <div style="position: absolute; width: 480px; height: 300px; top: 10px; left: 10px; text-align: left; line-height: 1.8em; font-size: 12px;"> <span style="display: block; line-height: 1em; text-transform: uppercase; font-size: 52px; color: #FFFFFF;">Online marketing</span> <br /> <span style="display: block; line-height: 1.1em; font-size: 2.5em; color: #FFFFFF;"> We enhance your brand, your website traffic and your bottom line online. </span> <br /> <br /> <a href="http://www.jssor.com"> <img src="../img/major/find-out-more-bt.png" border="0" alt="listing slider" width="215" height="50" /></a> </div> <img src="../img/major/s4.png" style="position: absolute; top: 23px; left: 480px; width: 500px; height: 300px;" /> <img u="thumb" src="../img/major/s4t.jpg" /> </div> <div> <div style="position: absolute; width: 480px; height: 300px; top: 10px; left: 10px; text-align: left; line-height: 1.8em; font-size: 12px;"> <br /> <span style="display: block; line-height: 1em; text-transform: uppercase; font-size: 52px; color: #FFFFFF;">web hosting</span> <br /> <br /> <span style="display: block; line-height: 1.1em; font-size: 2.5em; color: #FFFFFF;"> we offer the web's best hosting plans for every site. </span> <br /> <br /> <a href="http://www.jssor.com"> <img src="../img/major/find-out-more-bt.png" border="0" alt="ebay store slider" width="215" height="50" /></a> </div> <img src="../img/major/s5.png" style="position: absolute; top: 23px; left: 480px; width: 500px; height: 300px;" /> <img u="thumb" src="../img/major/s5t.jpg" /> </div> <div> <div style="position: absolute; width: 480px; height: 300px; top: 10px; left: 10px; text-align: left; line-height: 1.8em; font-size: 12px;"> <span style="display: block; line-height: 1em; text-transform: uppercase; font-size: 52px; color: #FFFFFF;">domain name registration</span> <br /> <span style="display: block; line-height: 1.1em; font-size: 2.5em; color: #FFFFFF;"> Secure your online identity and register your domain now. </span> <br /> <br /> <a href="http://www.jssor.com"> <img src="../img/major/find-out-more-bt.png" border="0" alt="listing template slider" width="215" height="50" /></a> </div> <img src="../img/major/s6.png" style="position: absolute; top: 23px; left: 480px; width: 500px; height: 300px;" /> <img u="thumb" src="../img/major/s6t.jpg" /> </div> <div> <div style="position: absolute; width: 480px; height: 300px; top: 10px; left: 10px; text-align: left; line-height: 1.8em; font-size: 12px;"> <br /> <span style="display: block; line-height: 1em; text-transform: uppercase; font-size: 52px; color: #FFFFFF;">video production</span> <br /> <span style="display: block; line-height: 1.1em; font-size: 2.5em; color: #FFFFFF;"> Make a greater impact on your clients through interactive Video Production. </span> <br /> <br /> <a href="http://www.jssor.com"> <img src="../img/major/find-out-more-bt.png" border="0" alt="auction template slider" width="215" height="50" /></a> </div> <img src="../img/major/s7.png" style="position: absolute; top: 23px; left: 480px; width: 500px; height: 300px;" /> <img u="thumb" src="../img/major/s7t.jpg" /> </div> <div> <div style="position: absolute; width: 480px; height: 300px; top: 10px; left: 10px; text-align: left; line-height: 1.8em; font-size: 12px;"> <span style="display: block; line-height: 1em; text-transform: uppercase; font-size: 52px; color: #FFFFFF;">mobile applications</span> <br /> <span style="display: block; line-height: 1.1em; font-size: 2.5em; color: #FFFFFF;"> Stay connected to your customers on the go with a MajorMedia custom mobile app. <br /> <br /> <a href="http://www.jssor.com"> <img src="../img/major/find-out-more-bt.png" border="0" alt="ebay slider" width="215" height="50" /></a> </div> <img src="../img/major/s8.png" style="position: absolute; top: 23px; left: 480px; width: 500px; height: 300px;" /> <img u="thumb" src="../img/major/s8t.jpg" /> </div> </div> <!-- Arrow Navigator Skin Begin --> <style> /* jssor slider arrow navigator skin 07 css */ /* .jssora07l (normal) .jssora07r (normal) .jssora07l:hover (normal mouseover) .jssora07r:hover (normal mouseover) .jssora07ldn (mousedown) .jssora07rdn (mousedown) */ .jssora07l, .jssora07r, .jssora07ldn, .jssora07rdn { position: absolute; cursor: pointer; display: block; background: url(../img/a07.png) no-repeat; overflow: hidden; } .jssora07l { background-position: -5px -35px; } .jssora07r { background-position: -65px -35px; } .jssora07l:hover { background-position: -125px -35px; } .jssora07r:hover { background-position: -185px -35px; } .jssora07ldn { background-position: -245px -35px; } .jssora07rdn { background-position: -305px -35px; } </style> <!-- Arrow Left --> <span u="arrowleft" class="jssora07l" style="width: 50px; height: 50px; top: 123px; left: 8px;"></span> <!-- Arrow Right --> <span u="arrowright" class="jssora07r" style="width: 50px; height: 50px; top: 123px; right: 8px"></span> <!-- Arrow Navigator Skin End --> <!-- ThumbnailNavigator Skin Begin --> <div u="thumbnavigator" class="jssort04" style="position: absolute; width: 600px; height: 60px; right: 0px; bottom: 0px;"> <!-- Thumbnail Item Skin Begin --> <style> /* jssor slider thumbnail navigator skin 04 css */ /* .jssort04 .p (normal) .jssort04 .p:hover (normal mouseover) .jssort04 .pav (active) .jssort04 .pav:hover (active mouseover) .jssort04 .pdn (mousedown) */ .jssort04 .w, .jssort04 .pav:hover .w { position: absolute; width: 60px; height: 30px; border: #0099FF 1px solid; } * html .jssort04 .w { width: /**/ 62px; height: /**/ 32px; } .jssort04 .pdn .w, .jssort04 .pav .w { border-style: solid; } .jssort04 .c { width: 62px; height: 32px; filter: alpha(opacity=45); opacity: .45; transition: opacity .6s; -moz-transition: opacity .6s; -webkit-transition: opacity .6s; -o-transition: opacity .6s; } .jssort04 .p:hover .c, .jssort04 .pav .c { filter: alpha(opacity=0); opacity: 0; } .jssort04 .p:hover .c { transition: none; -moz-transition: none; -webkit-transition: none; -o-transition: none; } </style> <div u="slides" style="bottom: 25px; right: 30px;"> <div u="prototype" class="p" style="position: absolute; width: 62px; height: 32px; top: 0; left: 0;"> <div class="w"> <thumbnailtemplate style="width: 100%; height: 100%; border: none; position: absolute; top: 0; left: 0;"></thumbnailtemplate> </div> <div class="c" style="position: absolute; background-color: #000; top: 0; left: 0"> </div> </div> </div> <!-- Thumbnail Item Skin End --> </div> <!-- ThumbnailNavigator Skin End --> <a style="display: none" href="http://www.jssor.com">jQuery Slider</a> </div> <!-- Trigger --> <script> jssor_slider1_starter('slider1_container'); </script> <!-- Jssor Slider End --> </div> </div> </body> </html>
alainbindele/openrate-it
public/js/jssor/themes-no-jquery/content-slider.source.html
HTML
bsd-3-clause
22,746
/** * Created by brodriguez on 04/11/16. */ $(document).ready(function() { $("div#productos").on('change',".cantidad", function(event){ event.preventDefault(); event.stopImmediatePropagation(); var $entrada = $(this); var valor = $entrada.val(); var pos = $entrada.attr("name"); pos = pos.replace("traslado-lote-collection[collection][",""); pos = pos.replace("][cantidad]",""); var nombdisponible = "traslado-lote-collection[collection]["+pos+"][disponible]"; var $campodisponible = $("[name=\'"+nombdisponible+"\']"); var disponible = $campodisponible.val(); if ( Number(disponible) < Number(valor) ){ alert("La cantidad a Tralasdar ("+valor+") debe ser menor o igual a la cantidad Disponible ("+disponible+") para el Producto Seleccionado"); $entrada.val(""); } else{ var nombre = "traslado-lote-collection[collection]["+pos+"][actualizado]"; var $actualizar = $("[name=\'"+nombre+"\']"); $actualizar.attr("value","actualizado"); } return false; }); $("#categoria").on('change', function(event){ event.preventDefault(); event.stopImmediatePropagation(); var $select = $(this); var categoria = $select.val(); var marca = $("#marca").val(); //alert ("Categoria: "+categoria+" Marca: "+marca); $.post("traslado-productos/filtro", { categoria: categoria, marca: marca }, function(data){ if(data.response == true) { // alert("Estoy en JSON"); $("#productos > fieldset > fieldset").remove(); //$("#productos").append("<fieldset><legend>Productos Disponibles</legend></fieldset>"); for ( i=0;i<data.productos.length;i++) { $("#productos > fieldset > legend").after( "<fieldset>" + "<input type=\"hidden\" value=\"\" name=\"traslado-lote-collection[collection]["+i+"][idalmacenmayor]\">" + "<input type=\"hidden\" value=\"\" name=\"traslado-lote-collection[collection]["+i+"][idalmacendetal]\">" + "<input type=\"text\" value=\""+data.productos[i].nombmarca+"\" disabled=\"disabled\" readonly=\"readonly\" size=\"20\" name=\"traslado-lote-collection[collection]["+i+"][nombmarca]\">" + "<input type=\"text\" value=\""+data.productos[i].nombcategoria+"\" disabled=\"disabled\" readonly=\"readonly\" size=\"20\" name=\"traslado-lote-collection[collection]["+i+"][nombcategoria]\">" + "<input type=\"hidden\" value=\""+data.productos[i].idproducto+"\" name=\"traslado-lote-collection[collection]["+i+"][idproducto]\">" + "<input class=\"actualizado\" type=\"hidden\" value=\"\" name=\"traslado-lote-collection[collection]["+i+"][actualizado]\">" + "<input type=\"text\" value=\""+data.productos[i].nombproducto+"\" disabled=\"disabled\" readonly=\"readonly\" maxlength=\"45\" size=\"45\" name=\"traslado-lote-collection[collection]["+i+"][nombproducto]\">" + "<input class=\"disponible\" type=\"text\" value=\""+data.productos[i].disponible+"\" disabled=\"disabled\" readonly=\"readonly\" maxlength=\"10\" size=\"5\" name=\"traslado-lote-collection[collection]["+i+"][disponible]\">" + "<label><span>Cantidad</span>" + "<input class=\"cantidad\" type=\"text\" value=\"\" size=\"20\" name=\"traslado-lote-collection[collection]["+i+"][cantidad]\">" + "</label>" + "<input type=\"text\" value=\""+data.productos[i].unidmed+"\" disabled=\"disabled\" readonly=\"readonly\" maxlength=\"10\" size=\"4\" name=\"traslado-lote-collection[collection]["+i+"][unidmed]\">" + "</fieldset>" ); } } else{ // print error message alert("Error en JSON"); console.log('could not remove '); } }, 'json'); return false; }); $("#marca").on('change', function(event){ event.preventDefault(); event.stopImmediatePropagation(); var $select = $(this); var marca = $select.val(); var categoria = $("#categoria").val(); // alert (valor); $.post("traslado-productos/filtro", { categoria: categoria, marca: marca }, function(data){ if(data.response == true) { // alert("Estoy en JSON"); $("#productos > fieldset > fieldset").remove(); //$("#productos").append("<fieldset><legend>Productos Disponibles</legend></fieldset>"); for ( i=0;i<data.productos.length;i++) { $("#productos > fieldset > legend").after( "<fieldset>" + "<input type=\"hidden\" value=\"\" name=\"traslado-lote-collection[collection]["+i+"][idalmacenmayor]\">" + "<input type=\"hidden\" value=\"\" name=\"traslado-lote-collection[collection]["+i+"][idalmacendetal]\">" + "<input type=\"text\" value=\""+data.productos[i].nombmarca+"\" disabled=\"disabled\" readonly=\"readonly\" size=\"20\" name=\"traslado-lote-collection[collection]["+i+"][nombmarca]\">" + "<input type=\"text\" value=\""+data.productos[i].nombcategoria+"\" disabled=\"disabled\" readonly=\"readonly\" size=\"20\" name=\"traslado-lote-collection[collection]["+i+"][nombcategoria]\">" + "<input type=\"hidden\" value=\""+data.productos[i].idproducto+"\" name=\"traslado-lote-collection[collection]["+i+"][idproducto]\">" + "<input class=\"actualizado\" type=\"hidden\" value=\"\" name=\"traslado-lote-collection[collection]["+i+"][actualizado]\">" + "<input type=\"text\" value=\""+data.productos[i].nombproducto+"\" disabled=\"disabled\" readonly=\"readonly\" maxlength=\"45\" size=\"45\" name=\"traslado-lote-collection[collection]["+i+"][nombproducto]\">" + "<input class=\"disponible\" type=\"text\" value=\""+data.productos[i].disponible+"\" disabled=\"disabled\" readonly=\"readonly\" maxlength=\"10\" size=\"5\" name=\"traslado-lote-collection[collection]["+i+"][disponible]\">" + "<label><span>Cantidad</span>" + "<input class=\"cantidad\" type=\"text\" value=\"\" size=\"20\" name=\"traslado-lote-collection[collection]["+i+"][cantidad]\">" + "</label>" + "<input type=\"text\" value=\""+data.productos[i].unidmed+"\" disabled=\"disabled\" readonly=\"readonly\" maxlength=\"10\" size=\"4\" name=\"traslado-lote-collection[collection]["+i+"][unidmed]\">" + "</fieldset>" ); } } else{ // print error message alert("Error en JSON"); console.log('could not remove '); } }, 'json'); return false; }); });
bexandy/ares-app
public/js/modules/almacen/traslado-lote.js
JavaScript
bsd-3-clause
7,619
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_SCHEDULER_RENDERER_RENDERER_SCHEDULER_IMPL_H_ #define COMPONENTS_SCHEDULER_RENDERER_RENDERER_SCHEDULER_IMPL_H_ #include "base/atomicops.h" #include "base/synchronization/lock.h" #include "components/scheduler/base/pollable_thread_safe_flag.h" #include "components/scheduler/child/idle_helper.h" #include "components/scheduler/child/scheduler_helper.h" #include "components/scheduler/renderer/deadline_task_runner.h" #include "components/scheduler/renderer/idle_time_estimator.h" #include "components/scheduler/renderer/render_widget_signals.h" #include "components/scheduler/renderer/renderer_scheduler.h" #include "components/scheduler/renderer/task_cost_estimator.h" #include "components/scheduler/renderer/throttling_helper.h" #include "components/scheduler/renderer/user_model.h" #include "components/scheduler/scheduler_export.h" namespace base { namespace trace_event { class ConvertableToTraceFormat; } } namespace scheduler { class RenderWidgetSchedulingState; class ThrottlingHelper; class SCHEDULER_EXPORT RendererSchedulerImpl : public RendererScheduler, public IdleHelper::Delegate, public SchedulerHelper::Observer, public RenderWidgetSignals::Observer { public: RendererSchedulerImpl(scoped_refptr<SchedulerTqmDelegate> main_task_runner); ~RendererSchedulerImpl() override; // RendererScheduler implementation: scoped_ptr<blink::WebThread> CreateMainThread() override; scoped_refptr<TaskQueue> DefaultTaskRunner() override; scoped_refptr<SingleThreadIdleTaskRunner> IdleTaskRunner() override; scoped_refptr<base::SingleThreadTaskRunner> CompositorTaskRunner() override; scoped_refptr<base::SingleThreadTaskRunner> LoadingTaskRunner() override; scoped_refptr<TaskQueue> TimerTaskRunner() override; scoped_refptr<TaskQueue> NewLoadingTaskRunner(const char* name) override; scoped_refptr<TaskQueue> NewTimerTaskRunner(const char* name) override; scoped_ptr<RenderWidgetSchedulingState> NewRenderWidgetSchedulingState() override; void WillBeginFrame(const cc::BeginFrameArgs& args) override; void BeginFrameNotExpectedSoon() override; void DidCommitFrameToCompositor() override; void DidHandleInputEventOnCompositorThread( const blink::WebInputEvent& web_input_event, InputEventState event_state) override; void DidHandleInputEventOnMainThread( const blink::WebInputEvent& web_input_event) override; void DidAnimateForInputOnCompositorThread() override; void OnRendererBackgrounded() override; void OnRendererForegrounded() override; void AddPendingNavigation() override; void RemovePendingNavigation() override; void OnNavigationStarted() override; bool IsHighPriorityWorkAnticipated() override; bool ShouldYieldForHighPriorityWork() override; bool CanExceedIdleDeadlineIfRequired() const override; void AddTaskObserver(base::MessageLoop::TaskObserver* task_observer) override; void RemoveTaskObserver( base::MessageLoop::TaskObserver* task_observer) override; void Shutdown() override; void SuspendTimerQueue() override; void ResumeTimerQueue() override; void SetTimerQueueSuspensionWhenBackgroundedEnabled(bool enabled) override; double CurrentTimeSeconds() const override; double MonotonicallyIncreasingTimeSeconds() const override; // RenderWidgetSignals::Observer implementation: void SetAllRenderWidgetsHidden(bool hidden) override; void SetHasVisibleRenderWidgetWithTouchHandler( bool has_visible_render_widget_with_touch_handler) override; // TaskQueueManager::Observer implementation: void OnUnregisterTaskQueue(const scoped_refptr<TaskQueue>& queue) override; // Returns a task runner where tasks run at the highest possible priority. scoped_refptr<TaskQueue> ControlTaskRunner(); void RegisterTimeDomain(TimeDomain* time_domain); void UnregisterTimeDomain(TimeDomain* time_domain); // Test helpers. SchedulerHelper* GetSchedulerHelperForTesting(); TaskCostEstimator* GetLoadingTaskCostEstimatorForTesting(); TaskCostEstimator* GetTimerTaskCostEstimatorForTesting(); IdleTimeEstimator* GetIdleTimeEstimatorForTesting(); base::TimeTicks CurrentIdleTaskDeadlineForTesting() const; base::TickClock* tick_clock() const; RealTimeDomain* real_time_domain() const { return helper_.real_time_domain(); } ThrottlingHelper* throttling_helper() { return &throttling_helper_; } private: friend class RendererSchedulerImplTest; friend class RendererSchedulerImplForTest; friend class RenderWidgetSchedulingState; struct Policy { Policy(); TaskQueue::QueuePriority compositor_queue_priority; TaskQueue::QueuePriority loading_queue_priority; TaskQueue::QueuePriority timer_queue_priority; TaskQueue::QueuePriority default_queue_priority; bool operator==(const Policy& other) const { return compositor_queue_priority == other.compositor_queue_priority && loading_queue_priority == other.loading_queue_priority && timer_queue_priority == other.timer_queue_priority && default_queue_priority == other.default_queue_priority; } }; class PollableNeedsUpdateFlag { public: PollableNeedsUpdateFlag(base::Lock* write_lock); ~PollableNeedsUpdateFlag(); // Set the flag. May only be called if |write_lock| is held. void SetWhileLocked(bool value); // Returns true iff the flag is set to true. bool IsSet() const; private: base::subtle::Atomic32 flag_; base::Lock* write_lock_; // Not owned. DISALLOW_COPY_AND_ASSIGN(PollableNeedsUpdateFlag); }; // IdleHelper::Delegate implementation: bool CanEnterLongIdlePeriod( base::TimeTicks now, base::TimeDelta* next_long_idle_period_delay_out) override; void IsNotQuiescent() override {} void OnIdlePeriodStarted() override; void OnIdlePeriodEnded() override; void EndIdlePeriod(); // Returns the serialized scheduler state for tracing. scoped_refptr<base::trace_event::ConvertableToTraceFormat> AsValue( base::TimeTicks optional_now) const; scoped_refptr<base::trace_event::ConvertableToTraceFormat> AsValueLocked( base::TimeTicks optional_now) const; static bool ShouldPrioritizeInputEvent( const blink::WebInputEvent& web_input_event); // The amount of time which idle periods can continue being scheduled when the // renderer has been hidden, before going to sleep for good. static const int kEndIdleWhenHiddenDelayMillis = 10000; // The amount of time for which loading tasks will be prioritized over // other tasks during the initial page load. static const int kRailsInitialLoadingPrioritizationMillis = 1000; // The amount of time in milliseconds we have to respond to user input as // defined by RAILS. static const int kRailsResponseTimeMillis = 50; // For the purposes of deciding whether or not it's safe to turn timers and // loading tasks on only in idle periods, we regard the system as being as // being "idle period" starved if there hasn't been an idle period in the last // 10 seconds. This was chosen to be long enough to cover most anticipated // user gestures. static const int kIdlePeriodStarvationThresholdMillis = 10000; // The amount of time to wait before suspending shared timers after the // renderer has been backgrounded. This is used only if background suspension // of shared timers is enabled. static const int kSuspendTimersWhenBackgroundedDelayMillis = 5 * 60 * 1000; // The time we should stay in a priority-escalated mode after a call to // DidAnimateForInputOnCompositorThread(). static const int kFlingEscalationLimitMillis = 100; // Schedules an immediate PolicyUpdate, if there isn't one already pending and // sets |policy_may_need_update_|. Note |any_thread_lock_| must be // locked. void EnsureUrgentPolicyUpdatePostedOnMainThread( const tracked_objects::Location& from_here); // Update the policy if a new signal has arrived. Must be called from the main // thread. void MaybeUpdatePolicy(); // Locks |any_thread_lock_| and updates the scheduler policy. May early // out if the policy is unchanged. Must be called from the main thread. void UpdatePolicy(); // Like UpdatePolicy, except it doesn't early out. void ForceUpdatePolicy(); enum class UpdateType { MAY_EARLY_OUT_IF_POLICY_UNCHANGED, FORCE_UPDATE, }; // The implelemtation of UpdatePolicy & ForceUpdatePolicy. It is allowed to // early out if |update_type| is MAY_EARLY_OUT_IF_POLICY_UNCHANGED. virtual void UpdatePolicyLocked(UpdateType update_type); // Helper for computing the use case. |expected_usecase_duration| will be // filled with the amount of time after which the use case should be updated // again. If the duration is zero, a new use case update should not be // scheduled. Must be called with |any_thread_lock_| held. Can be called from // any thread. UseCase ComputeCurrentUseCase( base::TimeTicks now, base::TimeDelta* expected_use_case_duration) const; // Works out if a gesture appears to be in progress based on the current // input signals. Can be called from any thread. bool InputSignalsSuggestGestureInProgress(base::TimeTicks now) const; // An input event of some sort happened, the policy may need updating. void UpdateForInputEventOnCompositorThread(blink::WebInputEvent::Type type, InputEventState input_event_state); // Returns true if there has been at least one idle period in the last // |kIdlePeriodStarvationThresholdMillis|. bool HadAnIdlePeriodRecently(base::TimeTicks now) const; // Helpers for safely suspending/resuming the timer queue after a // background/foreground signal. void SuspendTimerQueueWhenBackgrounded(); void ResumeTimerQueueWhenForegrounded(); // The task cost estimators and the UserModel need to be reset upon page // nagigation. This function does that. Must be called from the main thread. void ResetForNavigationLocked(); SchedulerHelper helper_; IdleHelper idle_helper_; ThrottlingHelper throttling_helper_; RenderWidgetSignals render_widget_scheduler_signals_; const scoped_refptr<TaskQueue> control_task_runner_; const scoped_refptr<TaskQueue> compositor_task_runner_; std::set<scoped_refptr<TaskQueue>> loading_task_runners_; std::set<scoped_refptr<TaskQueue>> timer_task_runners_; scoped_refptr<TaskQueue> default_loading_task_runner_; scoped_refptr<TaskQueue> default_timer_task_runner_; base::Closure update_policy_closure_; DeadlineTaskRunner delayed_update_policy_runner_; CancelableClosureHolder end_renderer_hidden_idle_period_closure_; CancelableClosureHolder suspend_timers_when_backgrounded_closure_; // We have decided to improve thread safety at the cost of some boilerplate // (the accessors) for the following data members. struct MainThreadOnly { MainThreadOnly(const scoped_refptr<TaskQueue>& compositor_task_runner, base::TickClock* time_source); ~MainThreadOnly(); TaskCostEstimator loading_task_cost_estimator; TaskCostEstimator timer_task_cost_estimator; IdleTimeEstimator idle_time_estimator; UseCase current_use_case; Policy current_policy; base::TimeTicks current_policy_expiration_time; base::TimeTicks estimated_next_frame_begin; base::TimeDelta compositor_frame_interval; base::TimeDelta expected_idle_duration; int timer_queue_suspend_count; // TIMER_TASK_QUEUE suspended if non-zero. int navigation_task_expected_count; bool renderer_hidden; bool renderer_backgrounded; bool timer_queue_suspension_when_backgrounded_enabled; bool timer_queue_suspended_when_backgrounded; bool was_shutdown; bool loading_tasks_seem_expensive; bool timer_tasks_seem_expensive; bool touchstart_expected_soon; bool have_seen_a_begin_main_frame; bool has_visible_render_widget_with_touch_handler; }; struct AnyThread { AnyThread(); ~AnyThread(); base::TimeTicks last_idle_period_end_time; base::TimeTicks rails_loading_priority_deadline; base::TimeTicks fling_compositor_escalation_deadline; UserModel user_model; bool awaiting_touch_start_response; bool in_idle_period; bool begin_main_frame_on_critical_path; bool last_gesture_was_compositor_driven; }; struct CompositorThreadOnly { CompositorThreadOnly(); ~CompositorThreadOnly(); blink::WebInputEvent::Type last_input_type; scoped_ptr<base::ThreadChecker> compositor_thread_checker; void CheckOnValidThread() { #if DCHECK_IS_ON() // We don't actually care which thread this called from, just so long as // its consistent. if (!compositor_thread_checker) compositor_thread_checker.reset(new base::ThreadChecker()); DCHECK(compositor_thread_checker->CalledOnValidThread()); #endif } }; // Don't access main_thread_only_, instead use MainThreadOnly(). MainThreadOnly main_thread_only_; MainThreadOnly& MainThreadOnly() { helper_.CheckOnValidThread(); return main_thread_only_; } const struct MainThreadOnly& MainThreadOnly() const { helper_.CheckOnValidThread(); return main_thread_only_; } mutable base::Lock any_thread_lock_; // Don't access any_thread_, instead use AnyThread(). AnyThread any_thread_; AnyThread& AnyThread() { any_thread_lock_.AssertAcquired(); return any_thread_; } const struct AnyThread& AnyThread() const { any_thread_lock_.AssertAcquired(); return any_thread_; } // Don't access compositor_thread_only_, instead use CompositorThreadOnly(). CompositorThreadOnly compositor_thread_only_; CompositorThreadOnly& CompositorThreadOnly() { compositor_thread_only_.CheckOnValidThread(); return compositor_thread_only_; } PollableThreadSafeFlag policy_may_need_update_; base::WeakPtrFactory<RendererSchedulerImpl> weak_factory_; DISALLOW_COPY_AND_ASSIGN(RendererSchedulerImpl); }; } // namespace scheduler #endif // COMPONENTS_SCHEDULER_RENDERER_RENDERER_SCHEDULER_IMPL_H_
Workday/OpenFrame
components/scheduler/renderer/renderer_scheduler_impl.h
C
bsd-3-clause
14,276
"""Most of these tests come from the examples in Bronstein's book.""" from diofant import Matrix, Poly, Rational, symbols from diofant.abc import n, t, x from diofant.integrals.prde import (constant_system, is_deriv_k, is_log_deriv_k_t_radical, is_log_deriv_k_t_radical_in_field, limited_integrate, limited_integrate_reduce, parametric_log_deriv_heu, prde_linear_constraints, prde_no_cancel_b_large, prde_no_cancel_b_small, prde_normal_denom, prde_spde, prde_special_denom) from diofant.integrals.risch import DifferentialExtension __all__ = () t0, t1, t2, t3 = symbols('t:4') def test_prde_normal_denom(): DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1 + t**2, t)]}) fa = Poly(1, t) fd = Poly(x, t) G = [(Poly(t, t), Poly(1 + t**2, t)), (Poly(1, t), Poly(x + x*t**2, t))] assert prde_normal_denom(fa, fd, G, DE) == \ (Poly(x, t), (Poly(1, t), Poly(1, t)), [(Poly(x*t, t), Poly(t**2 + 1, t)), (Poly(1, t), Poly(t**2 + 1, t))], Poly(1, t)) G = [(Poly(t, t), Poly(t**2 + 2*t + 1, t)), (Poly(x*t, t), Poly(t**2 + 2*t + 1, t)), (Poly(x*t**2, t), Poly(t**2 + 2*t + 1, t))] DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t, t)]}) assert prde_normal_denom(Poly(x, t), Poly(1, t), G, DE) == \ (Poly(t + 1, t), (Poly((-1 + x)*t + x, t), Poly(1, t)), [(Poly(t, t), Poly(1, t)), (Poly(x*t, t), Poly(1, t)), (Poly(x*t**2, t), Poly(1, t))], Poly(t + 1, t)) def test_prde_special_denom(): a = Poly(t + 1, t) ba = Poly(t**2, t) bd = Poly(1, t) G = [(Poly(t, t), Poly(1, t)), (Poly(t**2, t), Poly(1, t)), (Poly(t**3, t), Poly(1, t))] DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t, t)]}) assert prde_special_denom(a, ba, bd, G, DE) == \ (Poly(t + 1, t), Poly(t**2, t), [(Poly(t, t), Poly(1, t)), (Poly(t**2, t), Poly(1, t)), (Poly(t**3, t), Poly(1, t))], Poly(1, t)) G = [(Poly(t, t), Poly(1, t)), (Poly(1, t), Poly(t, t))] assert prde_special_denom(Poly(1, t), Poly(t**2, t), Poly(1, t), G, DE) == \ (Poly(1, t), Poly(t**2 - 1, t), [(Poly(t**2, t), Poly(1, t)), (Poly(1, t), Poly(1, t))], Poly(t, t)) DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(-2*x*t0, t0)]}) DE.decrement_level() G = [(Poly(t, t), Poly(t**2, t)), (Poly(2*t, t), Poly(t, t))] assert prde_special_denom(Poly(5*x*t + 1, t), Poly(t**2 + 2*x**3*t, t), Poly(t**3 + 2, t), G, DE) == \ (Poly(5*x*t + 1, t), Poly(0, t), [(Poly(t, t), Poly(t**2, t)), (Poly(2*t, t), Poly(t, t))], Poly(1, x)) DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly((t**2 + 1)*2*x, t)]}) G = [(Poly(t + x, t), Poly(t*x, t)), (Poly(2*t, t), Poly(x**2, x))] assert prde_special_denom(Poly(5*x*t + 1, t), Poly(t**2 + 2*x**3*t, t), Poly(t**3, t), G, DE) == \ (Poly(5*x*t + 1, t), Poly(0, t), [(Poly(t + x, t), Poly(x*t, t)), (Poly(2*t, t, x), Poly(x**2, t, x))], Poly(1, t)) assert prde_special_denom(Poly(t + 1, t), Poly(t**2, t), Poly(t**3, t), G, DE) == \ (Poly(t + 1, t), Poly(0, t), [(Poly(t + x, t), Poly(x*t, t)), (Poly(2*t, t, x), Poly(x**2, t, x))], Poly(1, t)) def test_prde_linear_constraints(): DE = DifferentialExtension(extension={'D': [Poly(1, x)]}) G = [(Poly(2*x**3 + 3*x + 1, x), Poly(x**2 - 1, x)), (Poly(1, x), Poly(x - 1, x)), (Poly(1, x), Poly(x + 1, x))] assert prde_linear_constraints(Poly(1, x), Poly(0, x), G, DE) == \ ((Poly(2*x, x), Poly(0, x), Poly(0, x)), Matrix([[1, 1, -1], [5, 1, 1]])) G = [(Poly(t, t), Poly(1, t)), (Poly(t**2, t), Poly(1, t)), (Poly(t**3, t), Poly(1, t))] DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t, t)]}) assert prde_linear_constraints(Poly(t + 1, t), Poly(t**2, t), G, DE) == \ ((Poly(t, t), Poly(t**2, t), Poly(t**3, t)), Matrix()) G = [(Poly(2*x, t), Poly(t, t)), (Poly(-x, t), Poly(t, t))] DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t)]}) assert prde_linear_constraints(Poly(1, t), Poly(0, t), G, DE) == \ ((Poly(0, t), Poly(0, t)), Matrix([[2*x, -x]])) def test_constant_system(): A = Matrix([[-(x + 3)/(x - 1), (x + 1)/(x - 1), 1], [-x - 3, x + 1, x - 1], [2*(x + 3)/(x - 1), 0, 0]]) u = Matrix([(x + 1)/(x - 1), x + 1, 0]) DE = DifferentialExtension(extension={'D': [Poly(1, x)]}) assert constant_system(A, u, DE) == \ (Matrix([[1, 0, 0], [0, 1, 0], [0, 0, 0], [0, 0, 1]]), Matrix([0, 1, 0, 0])) def test_prde_spde(): D = [Poly(x, t), Poly(-x*t, t)] DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t)]}) # TODO: when bound_degree() can handle this, test degree bound from that too assert prde_spde(Poly(t, t), Poly(-1/x, t), D, n, DE) == \ (Poly(t, t), Poly(0, t), [Poly(2*x, t), Poly(-x, t)], [Poly(-x**2, t), Poly(0, t)], n - 1) def test_prde_no_cancel(): # b large DE = DifferentialExtension(extension={'D': [Poly(1, x)]}) assert prde_no_cancel_b_large(Poly(1, x), [Poly(x**2), Poly(1, x)], 2, DE) == \ ([Poly(x**2 - 2*x + 2), Poly(1, x)], Matrix([[1, 0, -1, 0], [0, 1, 0, -1]])) assert prde_no_cancel_b_large(Poly(1, x), [Poly(x**3), Poly(1, x)], 3, DE) == \ ([Poly(x**3 - 3*x**2 + 6*x - 6), Poly(1, x)], Matrix([[1, 0, -1, 0], [0, 1, 0, -1]])) assert prde_no_cancel_b_large(Poly(x), [Poly(x**2), Poly(1, x)], 1, DE) == \ ([Poly(x), Poly(0, x)], Matrix([[1, -1, 0, 0], [1, 0, -1, 0], [0, 1, 0, -1]])) # b small # XXX: Is there a better example of a monomial with D.degree() > 2? DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t**3 + 1)]}) # My original q was t**4 + t + 1, but this solution implies q == t**4 # (c1 = 4), with some of the ci for the original q equal to 0. G = [Poly(t**6), Poly(x*t**5, t), Poly(t**3, t), Poly(x*t**2, t), Poly(1 + x, t)] assert prde_no_cancel_b_small(Poly(x*t, t), G, 4, DE) == \ ([Poly(t**4/4 - x/12*t**3 + x**2/24*t**2 + (-Rational(11, 12) - x**3/24)*t + x/24, t), Poly(x/3*t**3 - x**2/6*t**2 + (-Rational(1, 3) + x**3/6)*t - x/6, t), Poly(t, t), Poly(0, t), Poly(0, t)], Matrix([[1, 0, -1, 0, 0, 0, 0, 0, 0, 0], [0, 1, -Rational(1, 4), 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, -1, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, -1, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, -1, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0, -1, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, -1]])) # TODO: Add test for deg(b) <= 0 with b small def test_limited_integrate_reduce(): DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t)]}) assert limited_integrate_reduce(Poly(x, t), Poly(t**2, t), [(Poly(x, t), Poly(t, t))], DE) == \ (Poly(t, t), Poly(-1/x, t), Poly(t, t), 1, (Poly(x, t), Poly(1, t)), [(Poly(-x*t, t), Poly(1, t))]) def test_limited_integrate(): DE = DifferentialExtension(extension={'D': [Poly(1, x)]}) G = [(Poly(x, x), Poly(x + 1, x))] assert limited_integrate(Poly(-(1 + x + 5*x**2 - 3*x**3), x), Poly(1 - x - x**2 + x**3, x), G, DE) == \ ((Poly(x**2 - x + 2, x), Poly(x - 1, x)), [2]) G = [(Poly(1, x), Poly(x, x))] assert limited_integrate(Poly(5*x**2, x), Poly(3, x), G, DE) == \ ((Poly(5*x**3/9, x), Poly(1, x)), [0]) def test_is_log_deriv_k_t_radical(): DE = DifferentialExtension(extension={'D': [Poly(1, x)], 'E_K': [], 'L_K': [], 'E_args': [], 'L_args': []}) assert is_log_deriv_k_t_radical(Poly(2*x, x), Poly(1, x), DE) is None DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(2*t1, t1), Poly(1/x, t2)], 'L_K': [2], 'E_K': [1], 'L_args': [x], 'E_args': [2*x]}) assert is_log_deriv_k_t_radical(Poly(x + t2/2, t2), Poly(1, t2), DE) == \ ([(t1, 1), (x, 1)], t1*x, 2, 0) # TODO: Add more tests DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t0, t0), Poly(1/x, t)], 'L_K': [2], 'E_K': [1], 'L_args': [x], 'E_args': [x]}) assert is_log_deriv_k_t_radical(Poly(x + t/2 + 3, t), Poly(1, t), DE) == \ ([(t0, 2), (x, 1)], x*t0**2, 2, 3) def test_is_deriv_k(): DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t1), Poly(1/(x + 1), t2)], 'L_K': [1, 2], 'E_K': [], 'L_args': [x, x + 1], 'E_args': []}) assert is_deriv_k(Poly(2*x**2 + 2*x, t2), Poly(1, t2), DE) == \ ([(t1, 1), (t2, 1)], t1 + t2, 2) DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t1), Poly(t2, t2)], 'L_K': [1], 'E_K': [2], 'L_args': [x], 'E_args': [x]}) assert is_deriv_k(Poly(x**2*t2**3, t2), Poly(1, t2), DE) == \ ([(x, 3), (t1, 2)], 2*t1 + 3*x, 1) # TODO: Add more tests, including ones with exponentials DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(2/x, t1)], 'L_K': [1], 'E_K': [], 'L_args': [x**2], 'E_args': []}) assert is_deriv_k(Poly(x, t1), Poly(1, t1), DE) == \ ([(t1, Rational(1, 2))], t1/2, 1) DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(2/(1 + x), t0)], 'L_K': [1], 'E_K': [], 'L_args': [x**2 + 2*x + 1], 'E_args': []}) assert is_deriv_k(Poly(1 + x, t0), Poly(1, t0), DE) == \ ([(t0, Rational(1, 2))], t0/2, 1) # issue sympy/sympy#10798 DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(-1/x, t)], 'L_K': [1], 'E_K': [], 'L_args': [1/x], 'E_args': []}) assert is_deriv_k(Poly(1, t), Poly(x, t), DE) == ([(t, 1)], t, 1) def test_is_log_deriv_k_t_radical_in_field(): # NOTE: any potential constant factor in the second element of the result # doesn't matter, because it cancels in Da/a. DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t)]}) assert is_log_deriv_k_t_radical_in_field(Poly(5*t + 1, t), Poly(2*t*x, t), DE) == \ (2, t*x**5) assert is_log_deriv_k_t_radical_in_field(Poly(2 + 3*t, t), Poly(5*x*t, t), DE) == \ (5, x**3*t**2) DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(-t/x**2, t)]}) assert is_log_deriv_k_t_radical_in_field(Poly(-(1 + 2*t), t), Poly(2*x**2 + 2*x**2*t, t), DE) == \ (2, t + t**2) assert is_log_deriv_k_t_radical_in_field(Poly(-1, t), Poly(x**2, t), DE) == \ (1, t) assert is_log_deriv_k_t_radical_in_field(Poly(1, t), Poly(2*x**2, t), DE) == \ (2, 1/t) def test_parametric_log_deriv(): DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t)]}) assert parametric_log_deriv_heu(Poly(5*t**2 + t - 6, t), Poly(2*x*t**2, t), Poly(-1, t), Poly(x*t**2, t), DE) == \ (2, 6, t*x**5)
diofant/diofant
diofant/tests/integrals/test_prde.py
Python
bsd-3-clause
12,707
({ init: function (component, event, helper) { let pageRef = component.get("v.pageReference"); const recordId = pageRef.state.c__recordId; component.set("v.recordId", recordId); }, refresh: function (component, event, helper) { $A.get("e.force:refreshView").fire(); }, })
SalesforceFoundation/Cumulus
src/aura/ERR_RecordLog/ERR_RecordLogHelper.js
JavaScript
bsd-3-clause
326
<?php namespace Facturation\Model; use Zend\Db\TableGateway\TableGateway; use Zend\Db\Sql\Sql; class AdmissionTable { protected $tableGateway; public function __construct(TableGateway $tableGateway) { $this->tableGateway = $tableGateway; } public function getPatientsAdmis() { $today = new \DateTime ( 'now' ); $date = $today->format ( 'Y-m-d' ); $adapter = $this->tableGateway->getAdapter (); $sql = new Sql ( $adapter ); $select = $sql->select (); $select->from ( array ( 'p' => 'patient' ) ); $select->columns ( array () ); $select->join(array('pers' => 'personne'), 'pers.ID_PERSONNE = p.ID_PERSONNE', array( 'Nom' => 'NOM', 'Prenom' => 'PRENOM', 'Datenaissance' => 'DATE_NAISSANCE', 'Sexe' => 'SEXE', 'Adresse' => 'ADRESSE', 'Nationalite' => 'NATIONALITE_ACTUELLE', 'Id' => 'ID_PERSONNE' )); $select->join ( array ( 'a' => 'admission' ), 'p.ID_PERSONNE = a.id_patient', array ( 'Id_admission' => 'id_admission' ) ); $select->join ( array ( 's' => 'service' ), 's.ID_SERVICE = a.id_service', array ( 'Id_Service' => 'ID_SERVICE', 'Nomservice' => 'NOM' ) ); $select->where ( array ( 'a.date_cons' => $date ) ); $select->order ( 'id_admission ASC' ); $stat = $sql->prepareStatementForSqlObject ( $select ); $result = $stat->execute (); return $result; } public function nbAdmission() { $today = new \DateTime ( 'now' ); $date = $today->format ( 'Y-m-d' ); $adapter = $this->tableGateway->getAdapter (); $sql = new Sql ( $adapter ); $select = $sql->select ( 'admission' ); $select->columns ( array ( 'id_admission' ) ); $select->where ( array ( 'date_cons' => $date ) ); $stat = $sql->prepareStatementForSqlObject ( $select ); $nb = $stat->execute ()->count (); return $nb; } public function addAdmission($donnees){ $this->tableGateway->insert($donnees); } public function deleteAdmissionPatient($id){ $this->tableGateway->delete(array('id_admission'=> $id)); } public function getPatientAdmis($id){ $id = ( int ) $id; $rowset = $this->tableGateway->select ( array ( 'id_admission' => $id ) ); $row = $rowset->current (); if (! $row) { throw new \Exception ( "Could not find row $id" ); } return $row; } }
alhassimdiallo/simens-2015
module/Facturation/src/Facturation/Model/AdmissionTable.php
PHP
bsd-3-clause
2,295
require File.expand_path('../boot', __FILE__) require 'rails/all' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(:default, Rails.env) module Kabuofx class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. # config.time_zone = 'Central Time (US & Canada)' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de I18n.enforce_available_locales = false config.time_zone = "Tokyo" config.i18n.default_locale = :ja config.autoload_paths += Dir["#{config.root}/app/models/**"] end end
tmurakam/kabuofx
config/application.rb
Ruby
bsd-3-clause
1,161
/* * Copyright (c) 2016, Ford Motor Company * 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 the Ford Motor Company 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 HOLDER 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. */ #include <stdint.h> #include <string> #include "application_manager/commands/mobile/delete_command_request.h" #include "gtest/gtest.h" #include "utils/shared_ptr.h" #include "smart_objects/smart_object.h" #include "application_manager/smart_object_keys.h" #include "application_manager/test/include/application_manager/commands/command_request_test.h" #include "application_manager/mock_application_manager.h" #include "application_manager/mock_application.h" #include "application_manager/mock_message_helper.h" #include "application_manager/mock_hmi_interface.h" #include "application_manager/event_engine/event.h" namespace test { namespace components { namespace commands_test { namespace mobile_commands_test { namespace delete_command_request { using ::testing::_; using ::testing::Mock; using ::testing::Return; using ::testing::ReturnRef; namespace am = ::application_manager; using am::commands::DeleteCommandRequest; using am::commands::MessageSharedPtr; using am::event_engine::Event; using am::MockMessageHelper; typedef SharedPtr<DeleteCommandRequest> DeleteCommandPtr; namespace { const int32_t kCommandId = 1; const uint32_t kAppId = 1u; const uint32_t kCmdId = 1u; const uint32_t kConnectionKey = 2u; } // namespace class DeleteCommandRequestTest : public CommandRequestTest<CommandsTestMocks::kIsNice> { public: DeleteCommandRequestTest() : mock_message_helper_(*MockMessageHelper::message_helper_mock()) , mock_app_(CreateMockApp()) {} MessageSharedPtr CreateFullParamsUISO() { MessageSharedPtr msg = CreateMessage(smart_objects::SmartType_Map); (*msg)[am::strings::params][am::strings::connection_key] = kConnectionKey; smart_objects::SmartObject menu_params = smart_objects::SmartObject(smart_objects::SmartType_Map); menu_params[am::strings::position] = 10; menu_params[am::strings::menu_name] = "LG"; smart_objects::SmartObject msg_params = smart_objects::SmartObject(smart_objects::SmartType_Map); msg_params[am::strings::cmd_id] = kCmdId; msg_params[am::strings::menu_params] = menu_params; msg_params[am::strings::app_id] = kAppId; msg_params[am::strings::cmd_icon] = 1; msg_params[am::strings::cmd_icon][am::strings::value] = "10"; (*msg)[am::strings::msg_params] = msg_params; return msg; } MessageSharedPtr CreateFullParamsVRSO() { MessageSharedPtr msg = CreateMessage(smart_objects::SmartType_Map); (*msg)[am::strings::params][am::strings::connection_key] = kConnectionKey; smart_objects::SmartObject msg_params = smart_objects::SmartObject(smart_objects::SmartType_Map); msg_params[am::strings::cmd_id] = kCmdId; msg_params[am::strings::vr_commands] = smart_objects::SmartObject(smart_objects::SmartType_Array); msg_params[am::strings::vr_commands][0] = "lamer"; msg_params[am::strings::type] = 34; msg_params[am::strings::grammar_id] = 12; msg_params[am::strings::app_id] = kAppId; (*msg)[am::strings::msg_params] = msg_params; return msg; } void ResultCommandExpectations(MessageSharedPtr msg, const std::string& info) { EXPECT_EQ((*msg)[am::strings::msg_params][am::strings::success].asBool(), true); EXPECT_EQ( (*msg)[am::strings::msg_params][am::strings::result_code].asInt(), static_cast<int32_t>(hmi_apis::Common_Result::UNSUPPORTED_RESOURCE)); EXPECT_EQ((*msg)[am::strings::msg_params][am::strings::info].asString(), info); } void SetUp() OVERRIDE { ON_CALL(app_mngr_, application(kConnectionKey)) .WillByDefault(Return(mock_app_)); ON_CALL(*mock_app_, app_id()).WillByDefault(Return(kConnectionKey)); } void TearDown() OVERRIDE { Mock::VerifyAndClearExpectations(&mock_message_helper_); } MockMessageHelper& mock_message_helper_; MockAppPtr mock_app_; }; TEST_F(DeleteCommandRequestTest, OnEvent_VrHmiSendUnsupportedResource_UNSUPPORTED_RESOURCE) { MessageSharedPtr command_msg = CreateFullParamsVRSO(); (*command_msg)[am::strings::msg_params][am::strings::cmd_id] = kCommandId; (*command_msg)[am::strings::params][am::strings::connection_key] = kConnectionKey; DeleteCommandPtr command(CreateCommand<DeleteCommandRequest>(command_msg)); ON_CALL(app_mngr_, application(_)).WillByDefault(Return(mock_app_)); MessageSharedPtr test_msg(CreateMessage(smart_objects::SmartType_Map)); (*test_msg)[am::strings::vr_commands] = 0; (*test_msg)[am::strings::menu_params] = 0; ON_CALL(mock_hmi_interfaces_, GetInterfaceFromFunction(_)) .WillByDefault(Return(am::HmiInterfaces::HMI_INTERFACE_VR)); ON_CALL(mock_hmi_interfaces_, GetInterfaceState(am::HmiInterfaces::HMI_INTERFACE_UI)) .WillByDefault(Return(am::HmiInterfaces::STATE_NOT_AVAILABLE)); ON_CALL(mock_hmi_interfaces_, GetInterfaceState(am::HmiInterfaces::HMI_INTERFACE_VR)) .WillByDefault(Return(am::HmiInterfaces::STATE_NOT_AVAILABLE)); ON_CALL(*mock_app_, FindCommand(kCommandId)) .WillByDefault(Return(test_msg.get())); ON_CALL(*mock_app_, get_grammar_id()).WillByDefault(Return(kConnectionKey)); MessageSharedPtr msg(CreateMessage(smart_objects::SmartType_Map)); (*msg)[am::strings::params][am::hmi_response::code] = hmi_apis::Common_Result::SUCCESS; Event event_ui(hmi_apis::FunctionID::UI_DeleteCommand); event_ui.set_smart_object(*msg); command->Run(); command->on_event(event_ui); MessageSharedPtr event_msg(CreateMessage(smart_objects::SmartType_Map)); (*event_msg)[am::strings::params][am::hmi_response::code] = hmi_apis::Common_Result::UNSUPPORTED_RESOURCE; (*event_msg)[am::strings::msg_params][am::strings::info] = "VR is not supported by system"; Event event_vr(hmi_apis::FunctionID::VR_DeleteCommand); event_vr.set_smart_object(*event_msg); EXPECT_CALL(*mock_app_, RemoveCommand(kCommandId)); MessageSharedPtr vr_command_result; EXPECT_CALL( app_mngr_, ManageMobileCommand(_, am::commands::Command::CommandOrigin::ORIGIN_SDL)) .WillOnce(DoAll(SaveArg<0>(&vr_command_result), Return(true))); command->on_event(event_vr); ResultCommandExpectations(vr_command_result, "VR is not supported by system"); } TEST_F(DeleteCommandRequestTest, OnEvent_UIHmiSendUnsupportedResource_UNSUPPORTED_RESOURCE) { MessageSharedPtr command_msg = CreateFullParamsUISO(); (*command_msg)[am::strings::msg_params][am::strings::cmd_id] = kCommandId; (*command_msg)[am::strings::params][am::strings::connection_key] = kConnectionKey; DeleteCommandPtr command(CreateCommand<DeleteCommandRequest>(command_msg)); MockAppPtr app = CreateMockApp(); ON_CALL(app_mngr_, application(_)).WillByDefault(Return(app)); MessageSharedPtr test_msg(CreateMessage(smart_objects::SmartType_Map)); (*test_msg)[am::strings::vr_commands] = 0; (*test_msg)[am::strings::menu_params] = 0; ON_CALL(mock_hmi_interfaces_, GetInterfaceFromFunction(_)) .WillByDefault(Return(am::HmiInterfaces::HMI_INTERFACE_UI)); ON_CALL(mock_hmi_interfaces_, GetInterfaceState(am::HmiInterfaces::HMI_INTERFACE_UI)) .WillByDefault(Return(am::HmiInterfaces::STATE_NOT_AVAILABLE)); ON_CALL(mock_hmi_interfaces_, GetInterfaceState(am::HmiInterfaces::HMI_INTERFACE_VR)) .WillByDefault(Return(am::HmiInterfaces::STATE_NOT_AVAILABLE)); ON_CALL(*app, FindCommand(kCommandId)).WillByDefault(Return(test_msg.get())); ON_CALL(*app, get_grammar_id()).WillByDefault(Return(kConnectionKey)); MessageSharedPtr msg(CreateMessage(smart_objects::SmartType_Map)); (*msg)[am::strings::params][am::hmi_response::code] = hmi_apis::Common_Result::SUCCESS; Event event_vr(hmi_apis::FunctionID::VR_DeleteCommand); event_vr.set_smart_object(*msg); command->Run(); command->on_event(event_vr); MessageSharedPtr event_msg(CreateMessage(smart_objects::SmartType_Map)); (*event_msg)[am::strings::params][am::hmi_response::code] = hmi_apis::Common_Result::UNSUPPORTED_RESOURCE; (*event_msg)[am::strings::msg_params][am::strings::info] = "UI is not supported by system"; Event event_ui(hmi_apis::FunctionID::UI_DeleteCommand); event_ui.set_smart_object(*event_msg); EXPECT_CALL(*app, RemoveCommand(kCommandId)); MessageSharedPtr result_msg( CatchMobileCommandResult(CallOnEvent(*command, event_ui))); ASSERT_TRUE(result_msg); ResultCommandExpectations(result_msg, "UI is not supported by system"); } } // namespace delete_command_request } // namespace mobile_commands_test } // namespace commands_test } // namespace components } // namespace test
LuxoftAKutsan/sdl_core
src/components/application_manager/test/commands/mobile/delete_command_request_test.cc
C++
bsd-3-clause
10,230
/* Copyright (C) 2009-2011, Stefan Hacker <[email protected]> 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 the Mumble Developers 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 FOUNDATION 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. */ #define _USE_MATH_DEFINES #include <QtCore/QtCore> #include <QtGui/QtGui> #include <QMessageBox> #include <QPointer> #include <math.h> #include <float.h> #include "manual.h" #include "ui_manual.h" #ifdef Q_OS_UNIX #define __cdecl typedef WId HWND; #define DLL_PUBLIC __attribute__((visibility("default"))) #else #define DLL_PUBLIC __declspec(dllexport) #endif #include "../mumble_plugin.h" static QPointer<Manual> mDlg = NULL; static bool bLinkable = false; static bool bActive = true; static int iAzimuth = 0; static int iElevation = 0; static struct { float avatar_pos[3]; float avatar_front[3]; float avatar_top[3]; float camera_pos[3]; float camera_front[3]; float camera_top[3]; std::string context; std::wstring identity; } my = {{0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, std::string(), std::wstring() }; Manual::Manual(QWidget *p) : QDialog(p) { setupUi(this); qgvPosition->viewport()->installEventFilter(this); qgvPosition->scale(1.0f, 1.0f); qgsScene = new QGraphicsScene(QRectF(-5.0f, -5.0f, 10.0f, 10.0f), this); qgiPosition = qgsScene->addEllipse(QRectF(-0.5f, -0.5f, 1.0f, 1.0f), QPen(Qt::black), QBrush(Qt::red)); qgvPosition->setScene(qgsScene); qgvPosition->fitInView(-5.0f, -5.0f, 10.0f, 10.0f, Qt::KeepAspectRatio); qdsbX->setRange(-FLT_MAX, FLT_MAX); qdsbY->setRange(-FLT_MAX, FLT_MAX); qdsbZ->setRange(-FLT_MAX, FLT_MAX); qdsbX->setValue(my.avatar_pos[0]); qdsbY->setValue(my.avatar_pos[1]); qdsbZ->setValue(my.avatar_pos[2]); qpbActivated->setChecked(bActive); qpbLinked->setChecked(bLinkable); qsbAzimuth->setValue(iAzimuth); qsbElevation->setValue(iElevation); updateTopAndFront(iAzimuth, iElevation); } bool Manual::eventFilter(QObject *obj, QEvent *evt) { if ((evt->type() == QEvent::MouseButtonPress) || (evt->type() == QEvent::MouseMove)) { QMouseEvent *qme = dynamic_cast<QMouseEvent *>(evt); if (qme) { if (qme->buttons() & Qt::LeftButton) { QPointF qpf = qgvPosition->mapToScene(qme->pos()); qdsbX->setValue(-qpf.x()); qdsbZ->setValue(-qpf.y()); qgiPosition->setPos(qpf); } } } return QDialog::eventFilter(obj, evt); } void Manual::changeEvent(QEvent *e) { QDialog::changeEvent(e); switch (e->type()) { case QEvent::LanguageChange: retranslateUi(this); break; default: break; } } void Manual::on_qpbUnhinge_pressed() { qpbUnhinge->setEnabled(false); mDlg->setParent(NULL); mDlg->show(); } void Manual::on_qpbLinked_clicked(bool b) { bLinkable = b; } void Manual::on_qpbActivated_clicked(bool b) { bActive = b; } void Manual::on_qdsbX_valueChanged(double d) { my.avatar_pos[0] = my.camera_pos[0] = static_cast<float>(d); qgiPosition->setPos(-my.avatar_pos[0], -my.avatar_pos[2]); } void Manual::on_qdsbY_valueChanged(double d) { my.avatar_pos[1] = my.camera_pos[1] = static_cast<float>(d); } void Manual::on_qdsbZ_valueChanged(double d) { my.avatar_pos[2] = my.camera_pos[2] = static_cast<float>(d); qgiPosition->setPos(-my.avatar_pos[0], -my.avatar_pos[2]); } void Manual::on_qsbAzimuth_valueChanged(int i) { if (i > 180) qdAzimuth->setValue(-360 + i); else qdAzimuth->setValue(i); updateTopAndFront(i, qsbElevation->value()); } void Manual::on_qsbElevation_valueChanged(int i) { qdElevation->setValue(90 - i); updateTopAndFront(qsbAzimuth->value(), i); } void Manual::on_qdAzimuth_valueChanged(int i) { if (i < 0) qsbAzimuth->setValue(360 + i); else qsbAzimuth->setValue(i); } void Manual::on_qdElevation_valueChanged(int i) { if (i < -90) qdElevation->setValue(180); else if (i < 0) qdElevation->setValue(0); else qsbElevation->setValue(90 - i); } void Manual::on_qleContext_editingFinished() { my.context = qleContext->text().toStdString(); } void Manual::on_qleIdentity_editingFinished() { my.identity = qleIdentity->text().toStdWString(); } void Manual::on_buttonBox_clicked(QAbstractButton *button) { if (buttonBox->buttonRole(button) == buttonBox->ResetRole) { qpbLinked->setChecked(false); qpbActivated->setChecked(true); bLinkable = false; bActive = true; qdsbX->setValue(0); qdsbY->setValue(0); qdsbZ->setValue(0); qleContext->clear(); qleIdentity->clear(); qsbElevation->setValue(0); qsbAzimuth->setValue(0); } } void Manual::updateTopAndFront(int azimuth, int elevation) { iAzimuth = azimuth; iElevation = elevation; double azim = azimuth * M_PI / 180.; double elev = elevation * M_PI / 180.; my.avatar_front[0] = static_cast<float>(cos(elev) * sin(azim)); my.avatar_front[1] = static_cast<float>(sin(elev)); my.avatar_front[2] = static_cast<float>(cos(elev) * cos(azim)); my.avatar_top[0] = static_cast<float>(-sin(elev) * sin(azim)); my.avatar_top[1] = static_cast<float>(cos(elev)); my.avatar_top[2] = static_cast<float>(-sin(elev) * cos(azim)); memcpy(my.camera_top, my.avatar_top, sizeof(float) * 3); memcpy(my.camera_front, my.avatar_front, sizeof(float) * 3); } static int trylock() { return bLinkable; } static void unlock() { if (mDlg) { mDlg->qpbLinked->setChecked(false); } bLinkable = false; } static void config(HWND h) { if (mDlg) { mDlg->setParent(QWidget::find(h), Qt::Dialog); mDlg->qpbUnhinge->setEnabled(true); } else { mDlg = new Manual(QWidget::find(h)); } mDlg->show(); } static int fetch(float *avatar_pos, float *avatar_front, float *avatar_top, float *camera_pos, float *camera_front, float *camera_top, std::string &context, std::wstring &identity) { if (!bLinkable) return false; if (!bActive) { memset(avatar_pos, 0, sizeof(float)*3); memset(camera_pos, 0, sizeof(float)*3); return true; } memcpy(avatar_pos, my.avatar_pos, sizeof(float)*3); memcpy(avatar_front, my.avatar_front, sizeof(float)*3); memcpy(avatar_top, my.avatar_top, sizeof(float)*3); memcpy(camera_pos, my.camera_pos, sizeof(float)*3); memcpy(camera_front, my.camera_front, sizeof(float)*3); memcpy(camera_top, my.camera_top, sizeof(float)*3); context.assign(my.context); identity.assign(my.identity); return true; } static const std::wstring longdesc() { return std::wstring(L"This is the manual placement plugin. It allows you to place yourself manually."); } static std::wstring description(L"Manual placement plugin"); static std::wstring shortname(L"Manual placement"); static void about(WId h) { QMessageBox::about(QWidget::find(h), QString::fromStdWString(description), QString::fromStdWString(longdesc())); } static MumblePlugin manual = { MUMBLE_PLUGIN_MAGIC, description, shortname, about, config, trylock, unlock, longdesc, fetch }; extern "C" DLL_PUBLIC MumblePlugin *getMumblePlugin() { return &manual; }
chancegarcia/mumble
plugins/manual/manual.cpp
C++
bsd-3-clause
8,213
/* Copyright (c) 2011-2016 <[email protected]> This file is part of the X13.Home project. http://X13home.org http://X13home.net http://X13home.github.io/ BSD New License See LICENSE file for license details. */ #include "config.h" #define EXT_MAX_PROC 8 typedef void (*cbEXT_t)(void); static void * extProcCB[EXT_MAX_PROC]; // Initialise extensions void extInit(void) { uint8_t pos; for(pos = 0; pos < EXT_MAX_PROC; pos++) extProcCB[pos] = NULL; #ifdef EXTDIO_USED dioInit(); #ifdef EXTAIN_USED ainInit(); #endif // EXTAIN_USED #endif // EXTDIO_USED #ifdef EXTTWI_USED twiInit(); #endif #ifdef EXTSER_USED serInit(); #endif // EXTSER_USED #ifdef EXTPLC_USED plcInit(); #endif // EXTPLC_USED } // Check Subindex: 0 - free / 1 - busy / 2 - invalid bool extCheckSubidx(subidx_t * pSubidx) { switch(pSubidx->Place) { #ifdef EXTDIO_USED case objDin: case objDout: return dioCheckSubidx(pSubidx); #ifdef EXTPWM_USED case objPWM: return pwmCheckSubidx(pSubidx); #endif // EXTPWM_USED #ifdef EXTAIN_USED case objAin: return ainCheckSubidx(pSubidx); #endif // EXTAIN_USED #endif // EXTDIO_USED #ifdef EXTSER_USED case objSer: return serCheckSubidx(pSubidx); #endif // EXTSER_USED #ifdef EXTPLC_USED case objMerker: return plcCheckSubidx(pSubidx); #endif // EXTPLC_USED default: break; } return false; } // Register Object e_MQTTSN_RETURNS_t extRegisterOD(indextable_t * pIdx) { pIdx->cbRead = NULL; pIdx->cbWrite = NULL; pIdx->cbPoll = NULL; switch(pIdx->sidx.Place) { #ifdef EXTDIO_USED case objDin: // Digital(bool) Input's case objDout: // Digital(bool) Output's return dioRegisterOD(pIdx); #ifdef EXTPWM_USED case objPWM: // PWM return pwmRegisterOD(pIdx); #endif // EXTPWM_USED #ifdef EXTAIN_USED case objAin: // Analog(int16_t) Input's return ainRegisterOD(pIdx); #endif // EXTAIN_USED #endif // EXTDIO_USED #ifdef EXTSER_USED case objSer: // User Serial I/O return serRegisterOD(pIdx); #endif // EXTSER_USED #ifdef EXTPLC_USED case objMerker: return plcRegisterOD(pIdx); #endif // EXTPLC_USED default: break; } return MQTTSN_RET_REJ_NOT_SUPP; } // Delete Object void extDeleteOD(subidx_t * pSubidx) { // Delete Objects switch(pSubidx->Place) { #ifdef EXTDIO_USED case objDin: case objDout: dioDeleteOD(pSubidx); break; #ifdef EXTPWM_USED case objPWM: // PWM pwmDeleteOD(pSubidx); break; #endif // EXTPWM_USED #ifdef EXTAIN_USED case objAin: ainDeleteOD(pSubidx); break; #endif // EXTAIN_USED #endif // EXTDIO_USED #ifdef EXTSER_USED case objSer: serDeleteOD(pSubidx); break; #endif // EXTSER_USED default: break; } } void extRegProc(void * cb) { uint8_t pos; for(pos = 0; pos < EXT_MAX_PROC; pos++) { if(extProcCB[pos] == cb) { return; } } for(pos = 0; pos < EXT_MAX_PROC; pos++) { if(extProcCB[pos] == NULL) { extProcCB[pos] = cb; return; } } } void extProc(void) { uint8_t pos; for(pos = 0; pos < EXT_MAX_PROC; pos++) { cbEXT_t cb = extProcCB[pos]; if(cb != NULL) { cb(); } } } #ifdef EXTPLC_USED uint32_t ext_in(subidx_t * pSubidx) { switch(pSubidx->Place) { #ifdef EXTDIO_USED case objDin: case objDout: return dioRead(pSubidx); #endif // EXTDIO_USED #ifdef EXTAIN_USED case objAin: return ainRead(pSubidx); #endif // EXTAIN_USED default: break; } return 0; } void ext_out(subidx_t * pSubidx, uint32_t val) { switch(pSubidx->Place) { #ifdef EXTDIO_USED case objDout: dioWrite(pSubidx, val != 0); break; #endif // EXTDIO_USED #ifdef EXTPWM_USED case objPWM: // PWM if(val > 0xFFFF) val = 0xFFFF; hal_pwm_write(pSubidx->Base, val); break; #endif // EXTPWM_USED default: break; } } // Convert Subindex to Input Dpin, 0xFF - pin not exist uint8_t ext_getDPin(subidx_t * pSubidx) { switch(pSubidx->Place) { #ifdef EXTDIO_USED case objDin: return pSubidx->Base & 0xFF; #endif // EXTDIO_USED #ifdef EXTAIN_USED case objAin: return pSubidx->Base & 0xFF; #endif // EXTAIN_USED default: break; } return 0xFF; } void * ext_getPoll(subidx_t * pSubidx) { switch(pSubidx->Place) { #ifdef EXTDIO_USED case objDin: return dioGetPoll(); #endif // EXTDIO_USED #ifdef EXTAIN_USED case objAin: return ainGetPoll(); #endif // EXTAIN_USED default: break; } return NULL; } #endif // EXTPLC_USED
X13home/X13.devices
Source/Common/ext.c
C
bsd-3-clause
5,270
#ifndef ROBOT_STANCE_CSPACE_H #define ROBOT_STANCE_CSPACE_H #include "ContactCSpace.h" #include "Contact/Stance.h" #include <KrisLibrary/robotics/Stability.h> #include <KrisLibrary/robotics/TorqueSolver.h> /** @brief A configuration space that constrains a robot to the IK constraints * in a stance, and checks for stability against gravity. * * The kinematic contraints of contact are handled by the ContactCSpace superclass. * Collisions are handled by the SingleRobotCSpace2 superclass of ContactCSpace. * * This class adds the functionality of testing two stability conditions: * - rigid-body stability * - articulated robot stability with torques * * This supports from-scratch testing of RB equilibrium or batch testing using * the SupportPolygon class by calling CalculateSP(). The latter is more * expensive at first but each IsFeasible call will be faster. * * Uing support polygons you can modify the margin using SetSPMargin(). */ class StanceCSpace : public ContactCSpace { public: StanceCSpace(RobotWorld& world,int index, WorldPlannerSettings* settings); StanceCSpace(const SingleRobotCSpace& space); StanceCSpace(const StanceCSpace& space); virtual ~StanceCSpace() {} virtual void Sample(Config& x); virtual void SampleNeighborhood(const Config& c,Real r,Config& x); virtual bool IsFeasible(const Config&); ///Sets the current stance for this space void SetStance(const Stance& s); ///Adds the given hold to the space's stance void SetHold(const Hold& h); ///Calculates the support polygon for faster equilibrium testing void CalculateSP(); ///Enables robust equilbrium solving by shrinking the margin void SetSPMargin(Real margin); ///Initializes the torque solver. This is done automatically, and you only ///should use this if you are modifying the torque solver's parameters void InitTorqueSolver(); ///Check if the current robot COM satisfies rigid body equilibrium bool CheckRBStability(); ///Check if the current robot configuration satisfies articulated robot ///equilibrium with torque limits bool CheckTorqueStability(); Stance stance; Vector3 gravity; int numFCEdges; bool spCalculated; Real spMargin; SupportPolygon sp; ContactFormation formation; TorqueSolver torqueSolver; }; #endif
arocchi/Klampt
Planning/StanceCSpace.h
C
bsd-3-clause
2,300
<!--main content start--> <section class="main-content-wrapper"> <section id="main-content"> <div class="row"> <div class="col-md-12"> <!--breadcrumbs start --> <ul class="breadcrumb"> <li><a href="#">公众号管理</a> </li> <li class="active">公众号编辑</li> </ul> <!--breadcrumbs end --> </div> </div> <div class="row"> <div class="col-md-12"> <div class="panel-body"> <form class="form-horizontal form-border" action="index.php?r=pubnum/update" method="post"> <input type="hidden" name="id" value="<?php echo $arr['aid']?>"/> <div class="form-group"> <label class="col-sm-3 control-label">公众号名称:</label> <div class="col-sm-6"> <input type="text" class="form-control" name="aname" value="<?php echo $arr['aname']?>"> </div> </div> <div class="form-group"> <label class="col-sm-3 control-label" style="color:red">接口地址:</label> <div class="col-sm-6"> <input type="text" class="form-control" name="aurl" value="<?php echo $arr['aurl']?>"> </div> </div> <div class="form-group"> <label class="col-sm-3 control-label" style="color:red">微信Token:</label> <div class="col-sm-6"> <input type="text" class="form-control" id="token" ids="<?php echo $arr['aid']?>" name="atoken" value="<?php echo $arr['atoken']?>"> <a href="javascript:void(0)" class="rand">生成新的</a> <div class="help-block">与微信公众平台接入设置值一致,必须为英文或者数字,长度为3到32个字符. 请妥善保管, Token 泄露将可能被窃取或篡改微信平台的操作数据.</div> </div> </div> <div class="form-group"> <label class="col-sm-3 control-label">Appid:</label> <div class="col-sm-6"> <input type="text" class="form-control" name="appid" value="<?php echo $arr['appid']?>"> </div> </div> <div class="form-group"> <label class="col-sm-3 control-label">Appsecret:</label> <div class="col-sm-6"> <input type="text" class="form-control" name="appsecret" value="<?php echo $arr['appsecret']?>"> </div> </div> <div class="form-group"> <div class="col-sm-offset-8 col-sm-10"> <button type="submit" class="btn btn-primary">添加</button> </div> </div> </form> </div> </div> </div> </div> </section> </section> <!--main content end--> <script src="assets/js/jq.js"></script> <script type="text/javascript"> $(".rand").click(function(){ var id=$("#token").attr("ids"); $.ajax({ url:"index.php?r=pubnum/rand", type:"POST", data:{ id:id }, success:function(data){ $("#token").val(data); } }) }) </script>
yanan001/weiliang
views/pubnum/save.php
PHP
bsd-3-clause
4,087
/////////////////////////////////////////////////////////////////////////////// /// \file parser.hpp /// Contains the definition of regex_compiler, a factory for building regex objects /// from strings. // // Copyright 2008 Eric Niebler. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_XPRESSIVE_DETAIL_DYNAMIC_PARSER_HPP_EAN_10_04_2005 #define BOOST_XPRESSIVE_DETAIL_DYNAMIC_PARSER_HPP_EAN_10_04_2005 // MS compatible compilers support #pragma once #if defined(_MSC_VER) && (_MSC_VER >= 1020) # pragma once # pragma warning(push) # pragma warning(disable : 4127) // conditional expression is constant #endif #include <boost/assert.hpp> #include <boost/xpressive/regex_constants.hpp> #include <boost/xpressive/detail/detail_fwd.hpp> #include <boost/xpressive/detail/core/matchers.hpp> #include <boost/xpressive/detail/utility/ignore_unused.hpp> #include <boost/xpressive/detail/dynamic/dynamic.hpp> // The Regular Expression grammar, in pseudo BNF: // // expression = alternates ; // // alternates = sequence, *('|', sequence) ; // // sequence = quant, *(quant) ; // // quant = atom, [*+?] ; // // atom = literal | // '.' | // '\' any | // '(' expression ')' ; // // literal = not a meta-character ; // namespace pdalboost {} namespace boost = pdalboost; namespace pdalboost { namespace xpressive { namespace detail { /////////////////////////////////////////////////////////////////////////////// // make_char_xpression // template<typename BidiIter, typename Char, typename Traits> inline sequence<BidiIter> make_char_xpression ( Char ch , regex_constants::syntax_option_type flags , Traits const &tr ) { if(0 != (regex_constants::icase_ & flags)) { literal_matcher<Traits, mpl::true_, mpl::false_> matcher(ch, tr); return make_dynamic<BidiIter>(matcher); } else { literal_matcher<Traits, mpl::false_, mpl::false_> matcher(ch, tr); return make_dynamic<BidiIter>(matcher); } } /////////////////////////////////////////////////////////////////////////////// // make_any_xpression // template<typename BidiIter, typename Traits> inline sequence<BidiIter> make_any_xpression ( regex_constants::syntax_option_type flags , Traits const &tr ) { using namespace regex_constants; typedef typename iterator_value<BidiIter>::type char_type; typedef detail::set_matcher<Traits, mpl::int_<2> > set_matcher; typedef literal_matcher<Traits, mpl::false_, mpl::true_> literal_matcher; char_type const newline = tr.widen('\n'); set_matcher s; s.set_[0] = newline; s.set_[1] = 0; s.inverse(); switch(((int)not_dot_newline | not_dot_null) & flags) { case not_dot_null: return make_dynamic<BidiIter>(literal_matcher(char_type(0), tr)); case not_dot_newline: return make_dynamic<BidiIter>(literal_matcher(newline, tr)); case (int)not_dot_newline | not_dot_null: return make_dynamic<BidiIter>(s); default: return make_dynamic<BidiIter>(any_matcher()); } } /////////////////////////////////////////////////////////////////////////////// // make_literal_xpression // template<typename BidiIter, typename Traits> inline sequence<BidiIter> make_literal_xpression ( typename Traits::string_type const &literal , regex_constants::syntax_option_type flags , Traits const &tr ) { BOOST_ASSERT(0 != literal.size()); if(1 == literal.size()) { return make_char_xpression<BidiIter>(literal[0], flags, tr); } if(0 != (regex_constants::icase_ & flags)) { string_matcher<Traits, mpl::true_> matcher(literal, tr); return make_dynamic<BidiIter>(matcher); } else { string_matcher<Traits, mpl::false_> matcher(literal, tr); return make_dynamic<BidiIter>(matcher); } } /////////////////////////////////////////////////////////////////////////////// // make_backref_xpression // template<typename BidiIter, typename Traits> inline sequence<BidiIter> make_backref_xpression ( int mark_nbr , regex_constants::syntax_option_type flags , Traits const &tr ) { if(0 != (regex_constants::icase_ & flags)) { return make_dynamic<BidiIter> ( mark_matcher<Traits, mpl::true_>(mark_nbr, tr) ); } else { return make_dynamic<BidiIter> ( mark_matcher<Traits, mpl::false_>(mark_nbr, tr) ); } } /////////////////////////////////////////////////////////////////////////////// // merge_charset // template<typename Char, typename Traits> inline void merge_charset ( basic_chset<Char> &basic , compound_charset<Traits> const &compound , Traits const &tr ) { detail::ignore_unused(tr); if(0 != compound.posix_yes()) { typename Traits::char_class_type mask = compound.posix_yes(); for(int i = 0; i <= static_cast<int>(UCHAR_MAX); ++i) { if(tr.isctype((Char)i, mask)) { basic.set((Char)i); } } } if(!compound.posix_no().empty()) { for(std::size_t j = 0; j < compound.posix_no().size(); ++j) { typename Traits::char_class_type mask = compound.posix_no()[j]; for(int i = 0; i <= static_cast<int>(UCHAR_MAX); ++i) { if(!tr.isctype((Char)i, mask)) { basic.set((Char)i); } } } } if(compound.is_inverted()) { basic.inverse(); } } /////////////////////////////////////////////////////////////////////////////// // make_charset_xpression // template<typename BidiIter, typename Traits> inline sequence<BidiIter> make_charset_xpression ( compound_charset<Traits> &chset , Traits const &tr , regex_constants::syntax_option_type flags ) { typedef typename Traits::char_type char_type; bool const icase = (0 != (regex_constants::icase_ & flags)); bool const optimize = is_narrow_char<char_type>::value && 0 != (regex_constants::optimize & flags); // don't care about compile speed -- fold eveything into a bitset<256> if(optimize) { typedef basic_chset<char_type> charset_type; charset_type charset(chset.base()); if(icase) { charset_matcher<Traits, mpl::true_, charset_type> matcher(charset); merge_charset(matcher.charset_, chset, tr); return make_dynamic<BidiIter>(matcher); } else { charset_matcher<Traits, mpl::false_, charset_type> matcher(charset); merge_charset(matcher.charset_, chset, tr); return make_dynamic<BidiIter>(matcher); } } // special case to make [[:digit:]] fast else if(chset.base().empty() && chset.posix_no().empty()) { BOOST_ASSERT(0 != chset.posix_yes()); posix_charset_matcher<Traits> matcher(chset.posix_yes(), chset.is_inverted()); return make_dynamic<BidiIter>(matcher); } // default, slow else { if(icase) { charset_matcher<Traits, mpl::true_> matcher(chset); return make_dynamic<BidiIter>(matcher); } else { charset_matcher<Traits, mpl::false_> matcher(chset); return make_dynamic<BidiIter>(matcher); } } } /////////////////////////////////////////////////////////////////////////////// // make_posix_charset_xpression // template<typename BidiIter, typename Traits> inline sequence<BidiIter> make_posix_charset_xpression ( typename Traits::char_class_type m , bool no , regex_constants::syntax_option_type //flags , Traits const & //traits ) { posix_charset_matcher<Traits> charset(m, no); return make_dynamic<BidiIter>(charset); } /////////////////////////////////////////////////////////////////////////////// // make_assert_begin_line // template<typename BidiIter, typename Traits> inline sequence<BidiIter> make_assert_begin_line ( regex_constants::syntax_option_type flags , Traits const &tr ) { if(0 != (regex_constants::single_line & flags)) { return detail::make_dynamic<BidiIter>(detail::assert_bos_matcher()); } else { detail::assert_bol_matcher<Traits> matcher(tr); return detail::make_dynamic<BidiIter>(matcher); } } /////////////////////////////////////////////////////////////////////////////// // make_assert_end_line // template<typename BidiIter, typename Traits> inline sequence<BidiIter> make_assert_end_line ( regex_constants::syntax_option_type flags , Traits const &tr ) { if(0 != (regex_constants::single_line & flags)) { return detail::make_dynamic<BidiIter>(detail::assert_eos_matcher()); } else { detail::assert_eol_matcher<Traits> matcher(tr); return detail::make_dynamic<BidiIter>(matcher); } } /////////////////////////////////////////////////////////////////////////////// // make_assert_word // template<typename BidiIter, typename Cond, typename Traits> inline sequence<BidiIter> make_assert_word(Cond, Traits const &tr) { typedef typename iterator_value<BidiIter>::type char_type; return detail::make_dynamic<BidiIter> ( detail::assert_word_matcher<Cond, Traits>(tr) ); } /////////////////////////////////////////////////////////////////////////////// // make_independent_end_xpression // template<typename BidiIter> inline sequence<BidiIter> make_independent_end_xpression(bool pure) { if(pure) { return detail::make_dynamic<BidiIter>(detail::true_matcher()); } else { return detail::make_dynamic<BidiIter>(detail::independent_end_matcher()); } } }}} // namespace pdalboost::xpressive::detail #if defined(_MSC_VER) && (_MSC_VER >= 1020) # pragma warning(pop) #endif #endif
verma/PDAL
boost/boost/xpressive/detail/dynamic/parser.hpp
C++
bsd-3-clause
10,082
<?php use yii\helpers\Html; use yii\widgets\ActiveForm; /* @var $this yii\web\View */ /* @var $model common\models\Advert */ /* @var $form yii\widgets\ActiveForm */ ?> <div class="advert-form"> <?php $form = ActiveForm::begin(); ?> <?= $form->field($model, 'price')->textInput() ?> <?= $form->field($model, 'address')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'bedroom')->textInput() ?> <?= $form->field($model, 'livingroom')->textInput() ?> <?= $form->field($model, 'parking')->textInput() ?> <?= $form->field($model, 'kitchen')->textInput() ?> <?= $form->field($model, 'description')->textarea(['rows' => 6]) ?> <?= $form->field($model, 'location')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'hot')->radioList(["No", "Yes"]) ?> <?= $form->field($model, 'sold')->radioList(["No", "Yes"]) ?> <?= $form->field($model, 'type')->dropDownList(['Apartment', 'Building', 'Office Space']) ?> <?= $form->field($model, 'recommend')->radioList(["No", "Yes"]) ?> <div class="form-group"> <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Next', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?> </div> <?php ActiveForm::end(); ?> </div>
Blackheartpoker/yii2_site
frontend/modules/cabinet/views/advert/_form.php
PHP
bsd-3-clause
1,292
<?php use yii\helpers\Html; /* @var $this yii\web\View */ /* @var $model app\modules\ac\models\User */ $this->title = 'Create User'; $this->params['breadcrumbs'][] = ['label' => 'Users', 'url' => ['index']]; $this->params['breadcrumbs'][] = $this->title; ?> <div class="content-wrapper"> <div class="content-heading"> Users List <small>Who are all these people?</small> </div> <div class="row"> <div class="col-xs-12"> <div class="support-default-index"> <?= $this->render('_form', [ 'model' => $model, ]) ?> </div> </div> </div> </div>
nihilco/NF2
modules/ac/views/users/create.php
PHP
bsd-3-clause
607
<?php $this->title = Yii::t('hipanel:client', 'Create client'); $this->params['breadcrumbs'][] = ['label' => Yii::t('hipanel', 'Client'), 'url' => ['index']]; $this->params['breadcrumbs'][] = $this->title; ?> <?= $this->render('_form', compact('model', 'models', 'currencies')) ?>
hiqdev/hipanel-module-client
src/views/client/create.php
PHP
bsd-3-clause
284
/* * Copyright (c) 2013 Gerard Green * All rights reserved * * Please see the file 'LICENSE' for further information */ #ifndef _AWGRIDH_HPP_INCLUDED #define _AWGRIDH_HPP_INCLUDED #include <vector> #include "Grid1d.hpp" #include "Aw.hpp" namespace Aw { class GridH : public Grid1d { public: GridH(); virtual ~GridH() {} void setSize(cairo_t *cr, Size size); void getMetrics(cairo_t *cr, Size& min_size, bool& expandh, bool& expandv); }; } #endif // _AWGRIDH_HPP_INCLUDED
gerryg400/anvilos
src/libaw/GridH.hpp
C++
bsd-3-clause
537
#ifndef JHNN_H #define JHNN_H #include <stdbool.h> #include <TH.h> #ifdef _OPENMP #include <omp.h> #endif #define JHNN_(NAME) TH_CONCAT_3(JHNN_, Real, NAME) #define THIndexTensor THLongTensor #define THIndexTensor_(NAME) THLongTensor_ ## NAME #define THIntegerTensor THIntTensor #define THIntegerTensor_(NAME) THIntTensor_ ## NAME typedef long THIndex_t; typedef int THInteger_t; typedef void JHNNState; #include "generic/JHNN.h" #include <THGenerateFloatTypes.h> #endif
noa/jhnn
lib/JHNN/JHNN.h
C
bsd-3-clause
478
--- title: Returning from the field splash_image: splash.jpg --- When you've completely finished with a field project (or are returning to periodic internet use), the following steps need to happen: 1. OMK data should be cleaned and uploaded to local OSM (see 'In the field' section) 2. Edits to local OSM (from iD, JOSM, and OMK) must be pushed to online-OSM. Between the time you created the AOI export to the time you are ready to push the data back, OSM users in online environments may have created changes to the map. Rather than overwriting this, you will need to go through a conflict detection process. To handle this, we've developed what we call the "POSM replay tool". ## POSM replay tool The POSM replay tool requires some command line knowledge and familiarity with GitHub. [Reach out](https://twitter.com/awesomeposm) if you get to this step and need some pointers. The complete instructions are [here](https://github.com/americanredcross/posm-replay-tool) and you can read more about the concepts and mechanics behind the process [here](https://hi.stamen.com/merging-offline-edits-with-the-posm-replay-tool-2f39a4410d2a#.47nht8th2). In general, the replay process works as follows: 1. Obtain an AOI extract (PBF or XML) corresponding to the point where the local OSM API branched from. (This is the PBF file you created through the AOI export and used to set up your POSM deployment ) 2. Gather local changesets. 3. Initialize a git repository containing locally-modified entities present in the AOI extract. 4. Obtain an AOI extract containing current data from your upstream (use export.posm.io and follow the same steps you did to create your POSM deployment in the first place... but with current data). 5. Extract and apply changes to locally-modified entities from the current AOI extract. 6. Create a branch representing the local history by applying all local changesets to a branch containing the starting AOI extract. 7. Apply each local changeset to the branch containing the current AOI extract. 8. Manually resolve merge conflicts between local and upstream edits. 9. Submit resolved changesets to your upstream API, renumbering references to locally-created entities as necessary. We are still improving and fine-tuning this part of the POSM workflow, and we would be interested in your feedback and experience with it.
posm/posm.github.io
src/pages/returning-from-the-field/index.md
Markdown
bsd-3-clause
2,358
<?php /** * This file is part of amfPHP * * LICENSE * * This source file is subject to the license that is bundled * with this package in the file license.txt. * @package Amfphp_Core */ /** * responsable for loading and maintaining Amfphp configuration * * @package Amfphp_Core * @author Ariel Sommeria-klein */ class Amfphp_Core_Config { /** * paths to folders containing services(relative or absolute) * @var <array> of paths */ public $serviceFolders; /** * a dictionary of service classes represented in a ClassFindInfo. * The key is the name of the service, the value is the class find info. * for example: $serviceNames2ClassFindInfo["AmfphpDiscoveryService"] = new Amfphp_Core_Common_ClassFindInfo( dirname(__FILE__) . '/AmfphpDiscoveryService.php', 'AmfphpDiscoveryService'); * The forward slash is important, don't use "\'! * @var <array> of ClassFindInfo */ public $serviceNames2ClassFindInfo; /** * set to true if you want the service router to check if the number of arguments received by amfPHP matches with the method being called. * This should be set to false in production for performance reasons * default is true * @var Boolean */ public $checkArgumentCount = true; /** * paths to the folder containing the plugins. defaults to AMFPHP_ROOTPATH . '/Plugins/' * @var array */ public $pluginsFolders; /** * array containing untyped plugin configuration data. Add as needed. The advised format is the name of the plugin as key, and then * paramName/paramValue pairs as an array. * example: array('plugin' => array( 'paramName' =>'paramValue')) * The array( 'paramName' =>'paramValue') will be passed as is to the plugin at construction time. * * @var array */ public $pluginsConfig; /** * array containing configuration data that is shared between the plugins. The format is paramName/paramValue pairs as an array. * * @var array */ public $sharedConfig; /** * if true, there will be detailed information in the error messages, including confidential information like paths. * So it is advised to set to true for development purposes and to false in production. * default is true. * Set in the shared config. * for example * $this->sharedConfig[self::CONFIG_RETURN_ERROR_DETAILS] = true; * @var Boolean */ const CONFIG_RETURN_ERROR_DETAILS = 'returnErrorDetails'; /** * array of plugins that are available but should be disabled * @var array */ public $disabledPlugins; /** * constructor */ public function __construct() { $this->serviceFolders = array(); $this->serviceFolders [] = dirname(__FILE__) . '/../Services/'; $this->serviceNames2ClassFindInfo = array(); $this->pluginsFolders = array(AMFPHP_ROOTPATH . 'Plugins/'); $this->pluginsConfig = array(); $this->sharedConfig = array(); $this->disabledPlugins = array(); //disable logging by default //$this->disabledPlugins[] = 'AmfphpLogger'; //uncomment to disable monitor //$this->disabledPlugins[] = 'AmfphpMonitor'; //some useful examples of setting a config value in a plugin: //$this->pluginsConfig['AmfphpDiscovery']['restrictAccess'] = false; //$this->pluginsConfig['AmfphpVoConverter']['enforceConversion'] = true; } } ?>
silexlabs/ZF2WithAmfphp
vendor/amfphp-2.2/Amfphp/Core/Config.php
PHP
bsd-3-clause
3,538
#include "kmeans.hpp" #include "inlineSIMDFunctions.hpp" using namespace std; using namespace cv; namespace cp { //static int CV_KMEANS_PARALLEL_GRANULARITY = (int)utils::getConfigurationParameterSizeT("OPENCV_KMEANS_PARALLEL_GRANULARITY", 1000); static int CV_KMEANS_PARALLEL_GRANULARITY = 1000; enum KMeansDistanceLoop { KND, NKD }; double KMeans::clustering(InputArray _data, int K, InputOutputArray _bestLabels, TermCriteria criteria, int attempts, int flags, OutputArray _centers, MeanFunction function, Schedule schedule) { double ret = 0.0; int channels = min(_data.size().width, _data.size().height); switch (schedule) { case cp::KMeans::Schedule::AoS_NKD: ret = clusteringAoS(_data, K, _bestLabels, criteria, attempts, flags, _centers, function, KMeansDistanceLoop::NKD); break; case cp::KMeans::Schedule::SoA_KND: ret = clusteringSoA(_data, K, _bestLabels, criteria, attempts, flags, _centers, function, KMeansDistanceLoop::KND); break; case cp::KMeans::Schedule::AoS_KND: ret = clusteringAoS(_data, K, _bestLabels, criteria, attempts, flags, _centers, function, KMeansDistanceLoop::KND); break; case cp::KMeans::Schedule::SoA_NKD: ret = clusteringSoA(_data, K, _bestLabels, criteria, attempts, flags, _centers, function, KMeansDistanceLoop::NKD); break; case cp::KMeans::Schedule::SoAoS_NKD: ret = clusteringSoAoS(_data, K, _bestLabels, criteria, attempts, flags, _centers, function, KMeansDistanceLoop::NKD); break; case cp::KMeans::Schedule::SoAoS_KND: ret = clusteringSoAoS(_data, K, _bestLabels, criteria, attempts, flags, _centers, function, KMeansDistanceLoop::KND); break; case cp::KMeans::Schedule::Auto: default: { if (channels < 7) { ret = clusteringSoA(_data, K, _bestLabels, criteria, attempts, flags, _centers, function, KMeansDistanceLoop::KND); } else { ret = clusteringAoS(_data, K, _bestLabels, criteria, attempts, flags, _centers, function, KMeansDistanceLoop::NKD); } } break; } return ret; } double kmeans(InputArray _data, int K, InputOutputArray _bestLabels, TermCriteria criteria, int attempts, int flags, OutputArray _centers) { KMeans km; return km.clustering(_data, K, _bestLabels, criteria, attempts, flags, _centers); } #pragma region SoA inline float normL2Sqr(float a, float b) { float temp = a - b; return temp * temp; } //(a-b)^2 inline __m256 normL2Sqr(__m256 a, __m256 b) { __m256 temp = _mm256_sub_ps(a, b); return _mm256_mul_ps(temp, temp); } //(a-b)^2 + c=fma(a-b, a-b, c); inline __m256 normL2SqrAdd(__m256 a, __m256 b, __m256 c) { __m256 temp = _mm256_sub_ps(a, b); return _mm256_fmadd_ps(temp, temp, c); } #pragma region initialCentroid void KMeans::generateKmeansRandomInitialCentroidSoA(const cv::Mat& data_points, cv::Mat& dest_centroids, const int K, cv::RNG& rng) { const int N = data_points.cols; const int dims = data_points.rows; cv::AutoBuffer<Vec2f, 64> box(dims);//min-max value for each dimension { int i = 0; for (int j = 0; j < dims; j++) { const float* sample = data_points.ptr<float>(j); box[j] = Vec2f(sample[i], sample[i]); } } for (int d = 0; d < dims; d++) { for (int i = 1; i < N; i++) { const float* sample = data_points.ptr<float>(d); float v = sample[i]; box[d][0] = std::min(box[d][0], v); box[d][1] = std::max(box[d][1], v); } } for (int k = 0; k < K; k++) { for (int d = 0; d < dims; d++) { dest_centroids.ptr<float>(k)[d] = rng.uniform(box[d][0], box[d][1]); } } } class KMeansPPDistanceComputer_AVX : public ParallelLoopBody { private: const __m256* src_distance; __m256* dest_distance; const Mat& data_points; const int centroid_index; public: KMeansPPDistanceComputer_AVX(__m256* dest_dist, const Mat& data_points, const __m256* src_distance, int centroid_index) : dest_distance(dest_dist), data_points(data_points), src_distance(src_distance), centroid_index(centroid_index) { } void operator()(const cv::Range& range) const CV_OVERRIDE { //CV_TRACE_FUNCTION(); const int begin = range.start; const int end = range.end; const int dims = data_points.rows; const int simd_width = data_points.cols / 8; std::vector<__m256*> dim(dims); { int d = 0; const float* p = data_points.ptr<float>(d); dim[d] = (__m256*)p; const __m256 centers_value = _mm256_set1_ps(p[centroid_index]); for (int i = 0; i < simd_width; i++) { dest_distance[i] = normL2Sqr(dim[d][i], centers_value); } } for (int d = 1; d < dims; d++) { const float* p = data_points.ptr<float>(d); dim[d] = (__m256*)p; const __m256 centers_value = _mm256_set1_ps(p[centroid_index]); for (int i = 0; i < simd_width; i++) { dest_distance[i] = normL2SqrAdd(dim[d][i], centers_value, dest_distance[i]); } } for (int i = 0; i < simd_width; i++) { dest_distance[i] = _mm256_min_ps(dest_distance[i], src_distance[i]); } } }; //k - means center initialization using the following algorithm : //Arthur & Vassilvitskii(2007) k-means++ : The Advantages of Careful Seeding void KMeans::generateKmeansPPInitialCentroidSoA(const Mat& data_points, Mat& dest_centroids, int K, RNG& rng, int trials) { //CV_TRACE_FUNCTION(); const int dims = data_points.rows, N = data_points.cols; cv::AutoBuffer<int, 64> _centers(K); int* centers = &_centers[0]; //3 buffers; dist, tdist, tdist2. if (_distance.size() != N * 3) _distance.allocate(N * 3); __m256* dist = (__m256*) & _distance[0]; __m256* tdist = dist + N / 8; __m256* tdist2 = tdist + N / 8; const int simd_sizeN = N / 8; //randomize the first centroid centers[0] = (unsigned)rng % N; //determin the first centroid by mean (not effective) if (false) { Scalar v0 = mean(data_points.row(0)); Scalar v1 = mean(data_points.row(1)); Scalar v2 = mean(data_points.row(2)); const float* d0 = data_points.ptr<float>(0); const float* d1 = data_points.ptr<float>(1); const float* d2 = data_points.ptr<float>(2); float diff_max = FLT_MAX; int argindex = 0; for (int i = 0; i < N; i++) { float diff = float((d0[i] - v0.val[0]) * (d0[i] - v0.val[0]) + (d1[i] - v1.val[0]) * (d1[i] - v1.val[0]) + (d2[i] - v2.val[0]) * (d2[i] - v2.val[0])); if (diff < diff_max) { diff_max = diff; argindex = i; } } centers[0] = argindex; } for (int i = 0; i < simd_sizeN; i++) { dist[i] = _mm256_setzero_ps(); } float distance_sum = 0.f; for (int d = 0; d < dims; d++) { const float* p = data_points.ptr<float>(d); __m256* mp = (__m256*)p; __m256 centers_value = _mm256_set1_ps(p[centers[0]]); __m256 dist_value_acc = _mm256_setzero_ps(); for (int i = 0; i < simd_sizeN; i++) { // dist[i]‚ð‹‚ß‚é‚½‚߂̏ˆ— __m256 dist_value = cp::normL2Sqr(mp[i], centers_value); dist[i] = _mm256_add_ps(dist[i], dist_value); // sum0‚ð‹‚ß‚é‚½‚߂̏ˆ— dist_value_acc = _mm256_add_ps(dist_value_acc, dist_value); } distance_sum += _mm256_reduceadd_ps(dist_value_acc); } for (int k = 1; k < K; k++) { float bestSum = FLT_MAX; int bestCenter = -1; for (int j = 0; j < trials; j++) { float p = (float)rng * distance_sum;//original //float p = (float)rng * distance_sum / dims;//better? case by case int ci = 0; for (; ci < N - 1; ci++) { p -= _distance[ci]; if (p <= 0) { break; } } // Range : start=0,end=N // KMeansPPDistanceComputer : tdist2=tdist2, data=data, dist=dist, ci=ci // divUp : (dims*N + CV_KMEANS_PARALLEL_GRANULIARITY - 1) / CV_KMEANS_PARALLEL_GRANULIARITY@ parallel_for_(Range(0, N), KMeansPPDistanceComputer_AVX(tdist2, data_points, dist, ci), cv::getNumThreads()); float distance_sum_local = 0.f; __m256 tdist2_acc = _mm256_setzero_ps(); for (int i = 0; i < simd_sizeN; i++) { tdist2_acc = _mm256_add_ps(tdist2_acc, tdist2[i]); } distance_sum_local += _mm256_reduceadd_ps(tdist2_acc); if (distance_sum_local < bestSum) { bestSum = distance_sum_local; bestCenter = ci; std::swap(tdist, tdist2); } } if (bestCenter < 0) CV_Error(Error::StsNoConv, "kmeans: can't update cluster center (check input for huge or NaN values)"); centers[k] = bestCenter;//in intensity index, where have minimum distance distance_sum = bestSum; std::swap(dist, tdist); } for (int k = 0; k < K; k++) { float* dst = dest_centroids.ptr<float>(k); for (int d = 0; d < dims; d++) { const float* src = data_points.ptr<float>(d); dst[d] = src[centers[k]]; } } } #pragma endregion #pragma region updateCentroid void KMeans::getOuterSample(cv::Mat& src_centroids, cv::Mat& dest_centroids, const cv::Mat& data_points, const cv::Mat& labels) { const int N = data_points.cols; const int dims = data_points.rows; const int K = src_centroids.rows; cv::AutoBuffer<float, 64> Hcounters(K); for (int k = 0; k < K; k++) Hcounters[k] = 0.f; const int* l = labels.ptr<int>(); for (int i = 0; i < N; i++) { const int arg_k = l[i]; float dist = 0.f; for (int d = 0; d < dims; d++) { const float* dataPtr = data_points.ptr<float>(d); float diff = (src_centroids.ptr<float>(arg_k)[d] - dataPtr[i]); dist += diff * diff; } if (dist > Hcounters[arg_k]) { Hcounters[arg_k] = dist; for (int d = 0; d < dims; d++) { const float* dataPtr = data_points.ptr<float>(d); dest_centroids.ptr<float>(arg_k)[d] = dataPtr[i]; } } } } //Nxdims void KMeans::boxMeanCentroidSoA(Mat& data_points, const int* labels, Mat& dest_centroid, int* counters) { //cannot vectorize it without scatter const int dims = data_points.rows; const int N = data_points.cols; { int d = 0; float* dataPtr = data_points.ptr<float>(d); for (int i = 0; i < N; i++) { int arg_k = labels[i]; dest_centroid.ptr<float>(arg_k)[d] += dataPtr[i]; counters[arg_k]++; } } for (int d = 1; d < dims; d++) { float* dataPtr = data_points.ptr<float>(d); for (int i = 0; i < N; i++) { int arg_k = labels[i]; dest_centroid.ptr<float>(arg_k)[d] += dataPtr[i]; } } } //N*dims void KMeans::weightedMeanCentroid(Mat& data_points, const int* labels, const Mat& src_centroid, const float* Table, const int tableSize, Mat& dest_centroid, float* dest_centroid_weight, int* dest_counters) { const int dims = data_points.rows; const int N = data_points.cols; const int K = src_centroid.rows; for (int k = 0; k < K; k++) dest_centroid_weight[k] = 0.f; cv::AutoBuffer<float*, 64> dataTop(dims); for (int d = 0; d < dims; d++) { dataTop[d] = data_points.ptr<float>(d); } #if 0 //scalar cv::AutoBuffer<const float*, 64> centroidTop(K); for (int k = 0; k < K; k++) { centroidTop[k] = src_centroid.ptr<float>(k); } for (int i = 0; i < N; i++) { const int arg_k = labels[i]; float dist = 0.f; for (int d = 0; d < dims; d++) { float diff = (centroidTop[arg_k][d] - dataTop[d][i]); dist += diff * diff; } const float wi = Table[int(sqrt(dist))]; centroid_weight[arg_k] += wi; counters[arg_k]++; for (int d = 0; d < dims; d++) { dest_centroid.ptr<float>(arg_k)[d] += wi * dataTop[d][i]; } } #else const float* centroidPtr = src_centroid.ptr<float>();//dim*K const __m256i mtsize = _mm256_set1_epi32(tableSize - 1); for (int i = 0; i < N; i += 8) { const __m256i marg_k = _mm256_load_si256((__m256i*)(labels + i)); const __m256i midx = _mm256_mullo_epi32(marg_k, _mm256_set1_epi32(dims)); __m256 mdist = _mm256_setzero_ps(); for (int d = 0; d < dims; d++) { __m256 mc = _mm256_i32gather_ps(centroidPtr, _mm256_add_epi32(midx, _mm256_set1_epi32(d)), 4); mc = _mm256_sub_ps(mc, _mm256_load_ps(&dataTop[d][i])); mdist = _mm256_fmadd_ps(mc, mc, mdist); } //__m256 mwi = _mm256_i32gather_ps(Table, _mm256_cvtps_epi32(_mm256_sqrt_ps(mdist)), 4); __m256 mwi = _mm256_i32gather_ps(Table, _mm256_min_epi32(mtsize, _mm256_cvtps_epi32(_mm256_sqrt_ps(mdist))), 4); for (int v = 0; v < 8; v++) { const int arg_k = ((int*)&marg_k)[v]; const float wi = ((float*)&mwi)[v]; dest_centroid_weight[arg_k] += wi; dest_counters[arg_k]++; float* dstCentroidPtr = dest_centroid.ptr<float>(arg_k); for (int d = 0; d < dims; d++) { dstCentroidPtr[d] += wi * dataTop[d][i + v]; } } } #endif } //N*dims void KMeans::harmonicMeanCentroid(Mat& data_points, const int* labels, const Mat& src_centroid, Mat& dest_centroid, float* centroid_weight, int* counters) { const int dims = data_points.rows; const int N = data_points.cols; const int K = src_centroid.rows; for (int k = 0; k < K; k++) centroid_weight[k] = 0.f; for (int i = 0; i < N; i++) { float w = 0.f; const float p = 3.5f; const int arg_k = labels[i]; float w0 = 0.f; float w1 = 0.f; for (int k = 0; k < K; k++) { float w0_ = 0.f; float w1_ = 0.f; for (int d = 0; d < dims; d++) { float* dataPtr = data_points.ptr<float>(d); float diff = abs(src_centroid.ptr<float>(k)[d] - dataPtr[i]); if (diff == 0.f)diff += FLT_EPSILON; w0_ += pow(diff, -p - 2.f); w1_ += pow(diff, -p); } w0 += pow(w0_, 1.f / (-p - 2.f)); w1 += pow(w1_, 1.f / (-p)); } w = w0 / (w1 * w1); //std::cout <<i<<":"<< w <<", "<<w0<<","<<w1<< std::endl; centroid_weight[arg_k] += w; counters[arg_k]++; for (int d = 0; d < dims; d++) { float* dataPtr = data_points.ptr<float>(d); dest_centroid.ptr<float>(arg_k)[d] += w * dataPtr[i]; } } } #pragma endregion #pragma region assignCentroid template<bool onlyDistance, int loop> class KMeansDistanceComputer_SoADim : public ParallelLoopBody { private: KMeansDistanceComputer_SoADim& operator=(const KMeansDistanceComputer_SoADim&); // = delete float* distances; int* labels; const Mat& dataPoints; const Mat& centroids; public: KMeansDistanceComputer_SoADim(float* dest_distance, int* dest_labels, const Mat& dataPoints, const Mat& centroids) : distances(dest_distance), labels(dest_labels), dataPoints(dataPoints), centroids(centroids) { } void operator()(const Range& range) const CV_OVERRIDE { const int dims = centroids.cols;//when color case, dim= 3 const int K = centroids.rows; const int BEGIN = range.start / 8; const int END = (range.end % 8 == 0) ? range.end / 8 : (range.end / 8) - 1; __m256i* mlabel_dest = (__m256i*) & labels[0]; __m256* mdist_dest = (__m256*) & distances[0]; if constexpr (onlyDistance) { AutoBuffer<__m256*> dptr(dims); AutoBuffer<__m256> mc(dims); const float* center = centroids.ptr<float>(); for (int d = 0; d < dims; d++) { dptr[d] = (__m256*)dataPoints.ptr<float>(d); mc[d] = _mm256_set1_ps(center[d]); } for (int n = BEGIN; n < END; n++) { __m256 mdist = _mm256_setzero_ps(); for (int d = 0; d < dims; d++) { mdist = normL2SqrAdd(dptr[d][n], mc[d], mdist); } mdist_dest[n] = mdist; } for (int n = END * 8; n < range.end; n++) { float dist = 0.f; for (int d = 0; d < dims; d++) { dist += normL2Sqr(dataPoints.at<float>(d, n), center[d]); } distances[n] = dist; } } else { //std::cout << "SoA: KND" << std::endl; if (loop == KMeansDistanceLoop::KND)//loop k-n-d { AutoBuffer<__m256*> dptr(dims); for (int d = 0; d < dims; d++) { dptr[d] = (__m256*)dataPoints.ptr<float>(d); } AutoBuffer<__m256> mc(dims); { //k=0 const float* center = centroids.ptr<float>(0); for (int d = 0; d < dims; d++) { mc[d] = _mm256_set1_ps(center[d]); } for (int n = BEGIN; n < END; n++) { __m256 mdist = normL2Sqr(dptr[0][n], mc[0]); for (int d = 1; d < dims; d++) { mdist = normL2SqrAdd(dptr[d][n], mc[d], mdist); } mdist_dest[n] = mdist; mlabel_dest[n] = _mm256_setzero_si256();//set K=0; } for (int n = END * 8; n < range.end; n++) { float dist = 0.f; for (int d = 0; d < dims; d++) { dist += normL2Sqr(dataPoints.at<float>(d, n), center[d]); } distances[n] = dist; labels[n] = 0; } } for (int k = 1; k < K; k++) { const float* center = centroids.ptr<float>(k); for (int d = 0; d < dims; d++) { mc[d] = _mm256_set1_ps(center[d]); } for (int n = BEGIN; n < END; n++) { __m256 mdist = normL2Sqr(dptr[0][n], mc[0]); for (int d = 1; d < dims; d++) { mdist = normL2SqrAdd(dptr[d][n], mc[d], mdist); } __m256 mask = _mm256_cmp_ps(mdist, mdist_dest[n], _CMP_GT_OQ); mdist_dest[n] = _mm256_blendv_ps(mdist, mdist_dest[n], mask); __m256i label_mask = _mm256_cmpeq_epi32(_mm256_setzero_si256(), _mm256_cvtps_epi32(mask)); mlabel_dest[n] = _mm256_blendv_epi8(mlabel_dest[n], _mm256_set1_epi32(k), label_mask); } for (int n = END * 8; n < range.end; n++) { float dist = 0.f; for (int d = 0; d < dims; d++) { dist += normL2Sqr(dataPoints.at<float>(d, n), center[d]); } if (dist < distances[n]) { distances[n] = dist; labels[n] = k; } } } } else //loop n-k-d { __m256* mdp = (__m256*)_mm_malloc(sizeof(__m256) * dims, AVX_ALIGN); for (int n = BEGIN; n < END; n++) { mlabel_dest[n] = _mm256_setzero_si256(); for (int d = 0; d < dims; d++) { mdp[d] = *((__m256*)(dataPoints.ptr<float>(d, 8 * n))); } { int k = 0; const float* center = centroids.ptr<float>(k); __m256 mdist = normL2Sqr(mdp[0], _mm256_set1_ps(center[0])); for (int d = 1; d < dims; d++) { mdist = normL2SqrAdd(mdp[d], _mm256_set1_ps(center[d]), mdist); } mdist_dest[n] = mdist; mlabel_dest[n] = _mm256_setzero_si256();//set K=0; } for (int k = 1; k < K; k++) { const float* center = centroids.ptr<float>(k); __m256 mdist = normL2Sqr(mdp[0], _mm256_set1_ps(center[0]));//d=0 for (int d = 1; d < dims; d++) { mdist = normL2SqrAdd(mdp[d], _mm256_set1_ps(center[d]), mdist); } __m256 mask = _mm256_cmp_ps(mdist, mdist_dest[n], _CMP_GT_OQ); mdist_dest[n] = _mm256_blendv_ps(mdist, mdist_dest[n], mask); __m256i label_mask = _mm256_cmpeq_epi32(_mm256_setzero_si256(), _mm256_cvtps_epi32(mask)); mlabel_dest[n] = _mm256_blendv_epi8(mlabel_dest[n], _mm256_set1_epi32(k), label_mask); } } for (int n = END * 8; n < range.end; n++) { { int k = 0; const float* center = centroids.ptr<float>(k); float dist = 0.f; for (int d = 0; d < dims; d++) { dist += normL2Sqr(dataPoints.at<float>(d, n), center[d]); } distances[n] = dist; labels[n] = 0; } for (int k = 1; k < K; k++) { const float* center = centroids.ptr<float>(k); float dist = 0.f; for (int d = 0; d < dims; d++) { dist += normL2Sqr(dataPoints.at<float>(d, n), center[d]); } if (dist < distances[n]) { distances[n] = dist; labels[n] = k; } } } _mm_free(mdp); } } } }; //copy from KMeansDistanceComputer_SoADim template<bool onlyDistance, int loop, int dims> class KMeansDistanceComputer_SoA : public ParallelLoopBody { private: KMeansDistanceComputer_SoA& operator=(const KMeansDistanceComputer_SoA&); // = delete float* distances; int* labels; const Mat& dataPoints; const Mat& centroids; public: KMeansDistanceComputer_SoA(float* dest_distance, int* dest_labels, const Mat& dataPoints, const Mat& centroids) : distances(dest_distance), labels(dest_labels), dataPoints(dataPoints), centroids(centroids) { } void operator()(const Range& range) const CV_OVERRIDE { //CV_TRACE_FUNCTION(); const int K = centroids.rows; const int BEGIN = range.start / 8; const int END = (range.end % 8 == 0) ? range.end / 8 : (range.end / 8) - 1; //const int END = range.end / 8; __m256i* mlabel_dest = (__m256i*) & labels[0]; __m256* mdist_dest = (__m256*) & distances[0]; if constexpr (onlyDistance) { AutoBuffer<__m256*> dptr(dims); AutoBuffer<__m256> mc(dims); { const float* center = centroids.ptr<float>(0); for (int d = 0; d < dims; d++) { dptr[d] = (__m256*)dataPoints.ptr<float>(d); mc[d] = _mm256_set1_ps(center[d]); } } for (int n = BEGIN; n < END; n++) { __m256 mdist = _mm256_setzero_ps(); for (int d = 0; d < dims; d++) { mdist = normL2SqrAdd(dptr[d][n], mc[d], mdist); } mdist_dest[n] = mdist; } } else { if (loop == KMeansDistanceLoop::KND)//loop k-n-d { AutoBuffer<__m256*> dptr(dims); for (int d = 0; d < dims; d++) { dptr[d] = (__m256*)dataPoints.ptr<float>(d); } AutoBuffer<__m256> mc(dims); { //k=0 const float* center = centroids.ptr<float>(0); for (int d = 0; d < dims; d++) { mc[d] = _mm256_set1_ps(center[d]); } for (int n = BEGIN; n < END; n++) { __m256 mdist = normL2Sqr(dptr[0][n], mc[0]); for (int d = 1; d < dims; d++) { mdist = normL2SqrAdd(dptr[d][n], mc[d], mdist); } mdist_dest[n] = mdist; mlabel_dest[n] = _mm256_setzero_si256();//set K=0; } } for (int k = 1; k < K; k++) { const float* center = centroids.ptr<float>(k); for (int d = 0; d < dims; d++) { mc[d] = _mm256_set1_ps(center[d]); } for (int n = BEGIN; n < END; n++) { __m256 mdist = normL2Sqr(dptr[0][n], mc[0]); for (int d = 1; d < dims; d++) { mdist = normL2SqrAdd(dptr[d][n], mc[d], mdist); } __m256 mask = _mm256_cmp_ps(mdist, mdist_dest[n], _CMP_GT_OQ); mdist_dest[n] = _mm256_blendv_ps(mdist, mdist_dest[n], mask); __m256i label_mask = _mm256_cmpeq_epi32(_mm256_setzero_si256(), _mm256_cvtps_epi32(mask)); mlabel_dest[n] = _mm256_blendv_epi8(mlabel_dest[n], _mm256_set1_epi32(k), label_mask); } } } else //loop n-k-d { __m256* mdp = (__m256*)_mm_malloc(sizeof(__m256) * dims, AVX_ALIGN); for (int n = BEGIN; n < END; n++) { const int N = 8 * n; mlabel_dest[n] = _mm256_setzero_si256(); for (int d = 0; d < dims; d++) { mdp[d] = *((__m256*)(dataPoints.ptr<float>(d, N))); } { int k = 0; const float* center = centroids.ptr<float>(k); __m256 mdist = normL2Sqr(mdp[0], _mm256_set1_ps(center[0])); for (int d = 1; d < dims; d++) { mdist = normL2SqrAdd(mdp[d], _mm256_set1_ps(center[d]), mdist); } mdist_dest[n] = mdist; mlabel_dest[n] = _mm256_setzero_si256();//set K=0; } for (int k = 1; k < K; k++) { const float* center = centroids.ptr<float>(k); __m256 mdist = normL2Sqr(mdp[0], _mm256_set1_ps(center[0]));//d=0 for (int d = 1; d < dims; d++) { mdist = normL2SqrAdd(mdp[d], _mm256_set1_ps(center[d]), mdist); } __m256 mask = _mm256_cmp_ps(mdist, mdist_dest[n], _CMP_GT_OQ); mdist_dest[n] = _mm256_blendv_ps(mdist, mdist_dest[n], mask); __m256i label_mask = _mm256_cmpeq_epi32(_mm256_setzero_si256(), _mm256_cvtps_epi32(mask)); mlabel_dest[n] = _mm256_blendv_epi8(mlabel_dest[n], _mm256_set1_epi32(k), label_mask); } } _mm_free(mdp); } } } }; #pragma endregion double KMeans::clusteringSoA(cv::InputArray _data, int K, cv::InputOutputArray _bestLabels, cv::TermCriteria criteria, int attempts, int flags, OutputArray dest_centroids, MeanFunction function, int loop) { const int SPP_TRIALS = 3; Mat src = _data.getMat(); const bool isrow = (src.rows == 1); const int N = max(src.cols, src.rows);//input data size const int dims = min(src.cols, src.rows) * src.channels();//input dimensions const int type = src.depth(); //std::cout << "KMeans::clustering" << std::endl; //std::cout << "sigma" << sigma << std::endl; weightTableSize = (int)ceil(sqrt(signal_max * signal_max * dims));//for 3channel 255 max case 442=ceil(sqrt(3*255^2)) //std::cout << "tableSize" << tableSize << std::endl; float* weight_table = (float*)_mm_malloc(sizeof(float) * weightTableSize, AVX_ALIGN); if (function == MeanFunction::GaussInv) { //cout << "MeanFunction::GaussInv sigma " << sigma << endl; for (int i = 0; i < weightTableSize; i++) { //weight_table[i] = 1.f; weight_table[i] = 1.f - exp(i * i / (-2.f * sigma * sigma)) + 0.001f; //weight_table[i] =Huber(i, sigma) + 0.001f; //weight_table[i] = i< sigma ? 0.001f: 1.f; //float n = 2.2f; //weight_table[i] = 1.f - exp(pow(i,n) / (-n * pow(sigma,n))) + 0.02f; //weight_table[i] = pow(i,sigma*0.1)+0.01; //w = 1.0 - exp(pow(sqrt(w), n) / (-n * pow(sigma, n))); //w = exp(w / (-2.0 * sigma * sigma)); //w = 1.0 - exp(sqrt(w) / (-1.0 * sigma)); } } if (function == MeanFunction::LnNorm) { for (int i = 0; i < weightTableSize; i++) { weight_table[i] = (float)pow(i, min(sigma, 10.f)) + FLT_EPSILON; } } if (function == MeanFunction::Gauss) { for (int i = 0; i < weightTableSize; i++) { weight_table[i] = exp(i * i / (-2.f * sigma * sigma)); //w = 1.0 - exp(pow(sqrt(w), n) / (-n * pow(sigma, n))); } } //AoS to SoA by using transpose Mat src_t = (src.cols < src.rows) ? src.t() : src; attempts = std::max(attempts, 1); CV_Assert(src.dims <= 2 && type == CV_32F && K > 0); CV_CheckGE(N, K, "Number of clusters should be more than number of elements"); // data format // Mat::Mat(int rows, int cols, int type, void* data, size_t step=AUTO_STEP) // data0.step = data0 byte(3*4byte(size_of_float)=12byte) // Mat data(N, dims, CV_32F, data0.ptr(), isrow ? dims * sizeof(float) : static_cast<size_t>(data0.step)); Mat data_points(dims, N, CV_32F, src_t.ptr(), isrow ? N * sizeof(float) : static_cast<size_t>(src_t.step)); _bestLabels.create(N, 1, CV_32S, -1, true);//8U is better for small label cases Mat best_labels = _bestLabels.getMat(); if (flags & cv::KMEANS_USE_INITIAL_LABELS)// for KMEANS_USE_INITIAL_LABELS { CV_Assert((best_labels.cols == 1 || best_labels.rows == 1) && best_labels.cols * best_labels.rows == N && best_labels.type() == CV_32S && best_labels.isContinuous()); best_labels.copyTo(labels_internal); for (int i = 0; i < N; i++) { CV_Assert((unsigned)labels_internal.at<int>(i) < (unsigned)K); } } else //alloc buffer { if (!((best_labels.cols == 1 || best_labels.rows == 1) && best_labels.cols * best_labels.rows == N && best_labels.type() == CV_32S && best_labels.isContinuous())) { _bestLabels.create(N, 1, CV_32S); best_labels = _bestLabels.getMat(); } labels_internal.create(best_labels.size(), best_labels.type()); } int* labels = labels_internal.ptr<int>(); Mat centroids(K, dims, type); if ((flags & KMEANS_USE_INITIAL_LABELS) && (function == MeanFunction::Gauss || function == MeanFunction::GaussInv || function == MeanFunction::LnNorm)) { dest_centroids.copyTo(centroids); } Mat old_centroids(K, dims, type); Mat temp(1, dims, type); cv::AutoBuffer<float, 64> centroid_weight(K); cv::AutoBuffer<int, 64> label_count(K); cv::AutoBuffer<float, 64> dists(N);//double->float RNG& rng = theRNG(); if (criteria.type & TermCriteria::EPS)criteria.epsilon = std::max(criteria.epsilon, 0.); else criteria.epsilon = FLT_EPSILON; criteria.epsilon *= criteria.epsilon; if (criteria.type & TermCriteria::COUNT)criteria.maxCount = std::min(std::max(criteria.maxCount, 2), 100); else criteria.maxCount = 100; if (K == 1) { attempts = 1; criteria.maxCount = 2; } float best_compactness = FLT_MAX; for (int attempt_index = 0; attempt_index < attempts; attempt_index++) { float compactness = 0.f; //main loop for (int iter = 0; ;) { float max_center_shift = (iter == 0) ? FLT_MAX : 0.f; swap(centroids, old_centroids); const bool isInit = ((iter == 0) && (attempt_index > 0 || !(flags & KMEANS_USE_INITIAL_LABELS)));//initial attemp && KMEANS_USE_INITIAL_LABELS is true if (isInit)//initialization for first loop { //cp::Timer t("generate sample"); //<1ns if (flags & KMEANS_PP_CENTERS)//kmean++ { generateKmeansPPInitialCentroidSoA(data_points, centroids, K, rng, SPP_TRIALS); } else //random initialization { generateKmeansRandomInitialCentroidSoA(data_points, centroids, K, rng); } } else { //cp::Timer t("compute centroid"); //<1msD //update centroid centroids.setTo(0.f); for (int k = 0; k < K; k++) label_count[k] = 0; //compute centroid without normalization; loop: N x d if (function == MeanFunction::Harmonic) { harmonicMeanCentroid(data_points, labels, old_centroids, centroids, centroid_weight, label_count); } else if (function == MeanFunction::Gauss || function == MeanFunction::GaussInv || function == MeanFunction::LnNorm) { weightedMeanCentroid(data_points, labels, old_centroids, weight_table, weightTableSize, centroids, centroid_weight, label_count); } else if (function == MeanFunction::Mean) { boxMeanCentroidSoA(data_points, labels, centroids, label_count); } //processing for empty cluster //loop: N x K loop; but the most parts are skipped //if some cluster appeared to be empty then: // 1. find the biggest cluster // 2. find the farthest from the center point in the biggest cluster // 3. exclude the farthest point from the biggest cluster and form a new 1-point cluster. //#define DEBUG_SHOW_SKIP #ifdef DEBUG_SHOW_SKIP int count = 0; //for cout #endif for (int k = 0; k < K; k++) { if (label_count[k] != 0) continue; //std::cout << "empty: " << k << std::endl; int k_count_max = 0; for (int k1 = 1; k1 < K; k1++) { if (label_count[k_count_max] < label_count[k1]) k_count_max = k1; } float max_dist = 0.f; int farthest_i = -1; float* base_centroids = centroids.ptr<float>(k_count_max); float* normalized_centroids = temp.ptr<float>(); // normalized const float count_normalize = 1.f / label_count[k_count_max]; for (int j = 0; j < dims; j++) { normalized_centroids[j] = base_centroids[j] * count_normalize; } for (int i = 0; i < N; i++) { if (labels[i] != k_count_max) continue; #ifdef DEBUG_SHOW_SKIP count++; //for cout #endif float dist = 0.f; for (int d = 0; d < dims; d++) { dist += (data_points.ptr<float>(d)[i] - normalized_centroids[d]) * (data_points.ptr<float>(d)[i] - normalized_centroids[d]); } if (max_dist <= dist) { max_dist = dist; farthest_i = i; } } label_count[k_count_max]--; label_count[k]++; labels[farthest_i] = k; float* cur_center = centroids.ptr<float>(k); for (int d = 0; d < dims; d++) { base_centroids[d] -= data_points.ptr<float>(d)[farthest_i]; cur_center[d] += data_points.ptr<float>(d)[farthest_i]; } } #ifdef DEBUG_SHOW_SKIP cout << iter << ": compute " << count / ((float)N * K) * 100.f << " %" << endl; #endif //normalization and compute max shift distance between old centroid and new centroid //small loop: K x d for (int k = 0; k < K; k++) { float* centroidsPtr = centroids.ptr<float>(k); CV_Assert(label_count[k] != 0); float count_normalize = 0.f; if (function == MeanFunction::Mean) count_normalize = 1.f / label_count[k]; else count_normalize = 1.f / centroid_weight[k];//weighted mean for (int d = 0; d < dims; d++) centroidsPtr[d] *= count_normalize; if (iter > 0) { float dist = 0.f; const float* old_center = old_centroids.ptr<float>(k); for (int d = 0; d < dims; d++) { float t = centroidsPtr[d] - old_center[d]; dist += t * t; } max_center_shift = std::max(max_center_shift, dist); } } } //compute distance and relabel //image size x dimensions x K (the most large loop) bool isLastIter = (++iter == MAX(criteria.maxCount, 2) || max_center_shift <= criteria.epsilon); //if (max_center_shift <= criteria.epsilon) cout << "exit (max_center_shift <= criteria.epsilon), iteration" << iter - 1 << endl; { //cp::Timer t(format("%d: distant computing", iter)); //last loop is fast if (isLastIter) { // compute distance only parallel_for_(Range(0, N), KMeansDistanceComputer_SoADim<true, KMeansDistanceLoop::KND>(dists.data(), labels, data_points, centroids), cv::getNumThreads()); compactness = float(sum(Mat(Size(N, 1), CV_32F, &dists[0]))[0]); //getOuterSample(centroids, old_centroids, data_points, labels_internal); //swap(centroids, old_centroids); break; } else { // assign labels //int parallel = CV_KMEANS_PARALLEL_GRANULARITY; int parallel = cv::getNumThreads(); if (loop == KMeansDistanceLoop::KND) { switch (dims) { case 1:parallel_for_(Range(0, N), KMeansDistanceComputer_SoA<false, KMeansDistanceLoop::KND, 1>(dists.data(), labels, data_points, centroids), parallel); break; case 2:parallel_for_(Range(0, N), KMeansDistanceComputer_SoA<false, KMeansDistanceLoop::KND, 2>(dists.data(), labels, data_points, centroids), parallel); break; case 3:parallel_for_(Range(0, N), KMeansDistanceComputer_SoA<false, KMeansDistanceLoop::KND, 3>(dists.data(), labels, data_points, centroids), parallel); break; case 64:parallel_for_(Range(0, N), KMeansDistanceComputer_SoA<false, KMeansDistanceLoop::KND, 64>(dists.data(), labels, data_points, centroids), parallel); break; default:parallel_for_(Range(0, N), KMeansDistanceComputer_SoADim<false, KMeansDistanceLoop::KND>(dists.data(), labels, data_points, centroids), parallel); break; } //parallel_for_(Range(0, N), KMeansDistanceComputer_SoADim<false, KMeansDistanceLoop::NKD>(dists.data(), labels, data_points, centroids), parallel); } else if (loop == KMeansDistanceLoop::NKD) { switch (dims) { case 1:parallel_for_(Range(0, N), KMeansDistanceComputer_SoA<false, KMeansDistanceLoop::NKD, 1>(dists.data(), labels, data_points, centroids), parallel); break; case 2:parallel_for_(Range(0, N), KMeansDistanceComputer_SoA<false, KMeansDistanceLoop::NKD, 2>(dists.data(), labels, data_points, centroids), parallel); break; case 3:parallel_for_(Range(0, N), KMeansDistanceComputer_SoA<false, KMeansDistanceLoop::NKD, 3>(dists.data(), labels, data_points, centroids), parallel); break; case 64:parallel_for_(Range(0, N), KMeansDistanceComputer_SoA<false, KMeansDistanceLoop::NKD, 64>(dists.data(), labels, data_points, centroids), parallel); break; default:parallel_for_(Range(0, N), KMeansDistanceComputer_SoADim<false, KMeansDistanceLoop::NKD>(dists.data(), labels, data_points, centroids), parallel); break; } //parallel_for_(Range(0, N), KMeansDistanceComputer_SoADim<false, KMeansDistanceLoop::KND>(dists.data(), labels, data_points, centroids), parallel); //parallel_for_(Range(0, N), KMeansDistanceComputer_SoADim<false, KMeansDistanceLoop::NKD>(dists.data(), labels, data_points, centroids), parallel); } } } } //reshape data structure for output if (compactness < best_compactness) { best_compactness = compactness; if (dest_centroids.needed()) { if (dest_centroids.fixedType() && dest_centroids.channels() == dims) centroids.reshape(dims).copyTo(dest_centroids); else centroids.copyTo(dest_centroids); } labels_internal.copyTo(best_labels); } } _mm_free(weight_table); return best_compactness; } #pragma endregion #pragma region AoS //static int CV_KMEANS_PARALLEL_GRANULARITY = (int)utils::getConfigurationParameterSizeT("OPENCV_KMEANS_PARALLEL_GRANULARITY", 1000); #pragma region normL2Sqr inline float normL2Sqr_(const float* a, const float* b, const int avxend, const int issse, const int rem) { __m256 v = _mm256_sub_ps(_mm256_loadu_ps(a), _mm256_loadu_ps(b)); __m256 msum = _mm256_mul_ps(v, v); for (int j = 0; j < avxend; j++) { __m256 v = _mm256_sub_ps(_mm256_loadu_ps(a), _mm256_loadu_ps(b)); msum = _mm256_fmadd_ps(v, v, msum); a += 8; b += 8; } float d = _mm256_reduceadd_ps(msum); if (issse) { __m128 v = _mm_sub_ps(_mm_loadu_ps(a), _mm_loadu_ps(b)); v = _mm_mul_ps(v, v); d += _mm_reduceadd_ps(v); a += 4; b += 4; } for (int j = 0; j < rem; j++) { float t = a[j] - b[j]; d += t * t; } return d; } inline float normL2Sqr_(const float* a, const float* b, int n) { float d = 0.f; for (int j = 0; j < n; j++) { float t = a[j] - b[j]; d += t * t; } return d; } template<int n> inline float normL2Sqr_(const float* a, const float* b) { float d = 0.f; for (int j = 0; j < n; j++) { float t = a[j] - b[j]; d += t * t; } return d; } template<> inline float normL2Sqr_<3>(const float* a, const float* b) { __m128 v = _mm_sub_ps(_mm_loadu_ps(a), _mm_loadu_ps(b)); v = _mm_mul_ps(v, v); return v.m128_f32[0] + v.m128_f32[1] + v.m128_f32[2]; //return _mm_reduceadd_ps(v); } template<> inline float normL2Sqr_<4>(const float* a, const float* b) { __m128 v = _mm_sub_ps(_mm_loadu_ps(a), _mm_loadu_ps(b)); v = _mm_mul_ps(v, v); return _mm_reduceadd_ps(v); } template<> inline float normL2Sqr_<5>(const float* a, const float* b) { __m128 v = _mm_sub_ps(_mm_loadu_ps(a), _mm_loadu_ps(b)); v = _mm_mul_ps(v, v); const float t = a[4] - b[4]; return _mm_reduceadd_ps(v) + t * t; } template<> inline float normL2Sqr_<6>(const float* a, const float* b) { __m128 v = _mm_sub_ps(_mm_loadu_ps(a), _mm_loadu_ps(b)); v = _mm_mul_ps(v, v); const float t1 = a[4] - b[4]; const float t2 = a[5] - b[5]; return _mm_reduceadd_ps(v) + t1 * t1 + t2 * t2; } template<> inline float normL2Sqr_<7>(const float* a, const float* b) { /*__m256 v = _mm256_sub_ps(_mm256_loadu_ps(a), _mm256_loadu_ps(b)); v = _mm256_mul_ps(v, v); v = *(__m256*) &_mm256_insert_epi32(*(__m256i*) & v, 0, 7); return _mm256_reduceadd_ps(v);*/ __m128 v = _mm_sub_ps(_mm_loadu_ps(a), _mm_loadu_ps(b)); v = _mm_mul_ps(v, v); const float t1 = a[4] - b[4]; const float t2 = a[5] - b[5]; const float t3 = a[6] - b[6]; return _mm_reduceadd_ps(v) + t1 * t1 + t2 * t2 + t3 * t3; } template<> inline float normL2Sqr_<8>(const float* a, const float* b) { __m256 v = _mm256_sub_ps(_mm256_loadu_ps(a), _mm256_loadu_ps(b)); v = _mm256_mul_ps(v, v); return _mm256_reduceadd_ps(v); } template<> inline float normL2Sqr_<9>(const float* a, const float* b) { __m256 v = _mm256_sub_ps(_mm256_loadu_ps(a), _mm256_loadu_ps(b)); v = _mm256_mul_ps(v, v); const float t1 = a[8] - b[8]; return _mm256_reduceadd_ps(v) + t1 * t1; } template<> inline float normL2Sqr_<10>(const float* a, const float* b) { __m256 v = _mm256_sub_ps(_mm256_loadu_ps(a), _mm256_loadu_ps(b)); v = _mm256_mul_ps(v, v); const float t1 = a[8] - b[8]; const float t2 = a[9] - b[9]; return _mm256_reduceadd_ps(v) + t1 * t1 + t2 * t2; } template<> inline float normL2Sqr_<11>(const float* a, const float* b) { __m256 v = _mm256_sub_ps(_mm256_loadu_ps(a), _mm256_loadu_ps(b)); v = _mm256_mul_ps(v, v); const float t1 = a[8] - b[8]; const float t2 = a[9] - b[9]; const float t3 = a[10] - b[10]; return _mm256_reduceadd_ps(v) + t1 * t1 + t2 * t2 + t3 * t3; } template<> inline float normL2Sqr_<12>(const float* a, const float* b) { __m256 v = _mm256_sub_ps(_mm256_loadu_ps(a), _mm256_loadu_ps(b)); v = _mm256_mul_ps(v, v); __m128 v2 = _mm_sub_ps(_mm_loadu_ps(a + 8), _mm_loadu_ps(b + 8)); v2 = _mm_mul_ps(v2, v2); v = _mm256_add_ps(v, _mm256_castps128_ps256(v2)); return _mm256_reduceadd_ps(v); } template<> inline float normL2Sqr_<16>(const float* a, const float* b) { __m256 v = _mm256_sub_ps(_mm256_loadu_ps(a), _mm256_loadu_ps(b)); v = _mm256_mul_ps(v, v); __m256 v2 = _mm256_sub_ps(_mm256_loadu_ps(a + 8), _mm256_loadu_ps(b + 8)); v = _mm256_fmadd_ps(v2, v2, v); return _mm256_reduceadd_ps(v); } template<> inline float normL2Sqr_<24>(const float* a, const float* b) { __m256 v = _mm256_sub_ps(_mm256_loadu_ps(a), _mm256_loadu_ps(b)); v = _mm256_mul_ps(v, v); __m256 v2 = _mm256_sub_ps(_mm256_loadu_ps(a + 8), _mm256_loadu_ps(b + 8)); v = _mm256_fmadd_ps(v2, v2, v); v2 = _mm256_sub_ps(_mm256_loadu_ps(a + 16), _mm256_loadu_ps(b + 16)); v = _mm256_fmadd_ps(v2, v2, v); return _mm256_reduceadd_ps(v); } template<> inline float normL2Sqr_<32>(const float* a, const float* b) { __m256 v = _mm256_sub_ps(_mm256_loadu_ps(a), _mm256_loadu_ps(b)); v = _mm256_mul_ps(v, v); __m256 v2 = _mm256_sub_ps(_mm256_loadu_ps(a + 8), _mm256_loadu_ps(b + 8)); v = _mm256_fmadd_ps(v2, v2, v); v2 = _mm256_sub_ps(_mm256_loadu_ps(a + 16), _mm256_loadu_ps(b + 16)); v = _mm256_fmadd_ps(v2, v2, v); v2 = _mm256_sub_ps(_mm256_loadu_ps(a + 24), _mm256_loadu_ps(b + 24)); v = _mm256_fmadd_ps(v2, v2, v); return _mm256_reduceadd_ps(v); } template<> inline float normL2Sqr_<40>(const float* a, const float* b) { __m256 v = _mm256_sub_ps(_mm256_loadu_ps(a), _mm256_loadu_ps(b)); v = _mm256_mul_ps(v, v); __m256 v2 = _mm256_sub_ps(_mm256_loadu_ps(a + 8), _mm256_loadu_ps(b + 8)); v = _mm256_fmadd_ps(v2, v2, v); v2 = _mm256_sub_ps(_mm256_loadu_ps(a + 16), _mm256_loadu_ps(b + 16)); v = _mm256_fmadd_ps(v2, v2, v); v2 = _mm256_sub_ps(_mm256_loadu_ps(a + 24), _mm256_loadu_ps(b + 24)); v = _mm256_fmadd_ps(v2, v2, v); v2 = _mm256_sub_ps(_mm256_loadu_ps(a + 32), _mm256_loadu_ps(b + 32)); v = _mm256_fmadd_ps(v2, v2, v); return _mm256_reduceadd_ps(v); } template<> inline float normL2Sqr_<41>(const float* a, const float* b) { __m256 v = _mm256_sub_ps(_mm256_loadu_ps(a), _mm256_loadu_ps(b)); v = _mm256_mul_ps(v, v); __m256 v2 = _mm256_sub_ps(_mm256_loadu_ps(a + 8), _mm256_loadu_ps(b + 8)); v = _mm256_fmadd_ps(v2, v2, v); v2 = _mm256_sub_ps(_mm256_loadu_ps(a + 16), _mm256_loadu_ps(b + 16)); v = _mm256_fmadd_ps(v2, v2, v); v2 = _mm256_sub_ps(_mm256_loadu_ps(a + 24), _mm256_loadu_ps(b + 24)); v = _mm256_fmadd_ps(v2, v2, v); v2 = _mm256_sub_ps(_mm256_loadu_ps(a + 32), _mm256_loadu_ps(b + 32)); v = _mm256_fmadd_ps(v2, v2, v); const float t1 = a[40] - b[40]; return _mm256_reduceadd_ps(v) + t1 * t1; } template<> inline float normL2Sqr_<42>(const float* a, const float* b) { __m256 v = _mm256_sub_ps(_mm256_loadu_ps(a), _mm256_loadu_ps(b)); v = _mm256_mul_ps(v, v); __m256 v2 = _mm256_sub_ps(_mm256_loadu_ps(a + 8), _mm256_loadu_ps(b + 8)); v = _mm256_fmadd_ps(v2, v2, v); v2 = _mm256_sub_ps(_mm256_loadu_ps(a + 16), _mm256_loadu_ps(b + 16)); v = _mm256_fmadd_ps(v2, v2, v); v2 = _mm256_sub_ps(_mm256_loadu_ps(a + 24), _mm256_loadu_ps(b + 24)); v = _mm256_fmadd_ps(v2, v2, v); v2 = _mm256_sub_ps(_mm256_loadu_ps(a + 32), _mm256_loadu_ps(b + 32)); v = _mm256_fmadd_ps(v2, v2, v); const float t1 = a[40] - b[40]; const float t2 = a[41] - b[41]; return _mm256_reduceadd_ps(v) + t1 * t1 + t2 * t2; } template<> inline float normL2Sqr_<43>(const float* a, const float* b) { __m256 v = _mm256_sub_ps(_mm256_loadu_ps(a), _mm256_loadu_ps(b)); v = _mm256_mul_ps(v, v); __m256 v2 = _mm256_sub_ps(_mm256_loadu_ps(a + 8), _mm256_loadu_ps(b + 8)); v = _mm256_fmadd_ps(v2, v2, v); v2 = _mm256_sub_ps(_mm256_loadu_ps(a + 16), _mm256_loadu_ps(b + 16)); v = _mm256_fmadd_ps(v2, v2, v); v2 = _mm256_sub_ps(_mm256_loadu_ps(a + 24), _mm256_loadu_ps(b + 24)); v = _mm256_fmadd_ps(v2, v2, v); v2 = _mm256_sub_ps(_mm256_loadu_ps(a + 32), _mm256_loadu_ps(b + 32)); v = _mm256_fmadd_ps(v2, v2, v); const float t1 = a[40] - b[40]; const float t2 = a[41] - b[41]; const float t3 = a[42] - b[42]; return _mm256_reduceadd_ps(v) + t1 * t1 + t2 * t2 + t3 * t3; } template<> inline float normL2Sqr_<44>(const float* a, const float* b) { __m256 v = _mm256_sub_ps(_mm256_loadu_ps(a), _mm256_loadu_ps(b)); v = _mm256_mul_ps(v, v); __m256 v2 = _mm256_sub_ps(_mm256_loadu_ps(a + 8), _mm256_loadu_ps(b + 8)); v = _mm256_fmadd_ps(v2, v2, v); v2 = _mm256_sub_ps(_mm256_loadu_ps(a + 16), _mm256_loadu_ps(b + 16)); v = _mm256_fmadd_ps(v2, v2, v); v2 = _mm256_sub_ps(_mm256_loadu_ps(a + 24), _mm256_loadu_ps(b + 24)); v = _mm256_fmadd_ps(v2, v2, v); v2 = _mm256_sub_ps(_mm256_loadu_ps(a + 32), _mm256_loadu_ps(b + 32)); v = _mm256_fmadd_ps(v2, v2, v); __m128 v3 = _mm_sub_ps(_mm_loadu_ps(a + 40), _mm_loadu_ps(b + 40)); v3 = _mm_mul_ps(v3, v3); v = _mm256_add_ps(v, _mm256_castps128_ps256(v3)); return _mm256_reduceadd_ps(v); } template<> inline float normL2Sqr_<48>(const float* a, const float* b) { __m256 v = _mm256_sub_ps(_mm256_loadu_ps(a), _mm256_loadu_ps(b)); v = _mm256_mul_ps(v, v); __m256 v2 = _mm256_sub_ps(_mm256_loadu_ps(a + 8), _mm256_loadu_ps(b + 8)); v = _mm256_fmadd_ps(v2, v2, v); v2 = _mm256_sub_ps(_mm256_loadu_ps(a + 16), _mm256_loadu_ps(b + 16)); v = _mm256_fmadd_ps(v2, v2, v); v2 = _mm256_sub_ps(_mm256_loadu_ps(a + 24), _mm256_loadu_ps(b + 24)); v = _mm256_fmadd_ps(v2, v2, v); v2 = _mm256_sub_ps(_mm256_loadu_ps(a + 32), _mm256_loadu_ps(b + 32)); v = _mm256_fmadd_ps(v2, v2, v); v2 = _mm256_sub_ps(_mm256_loadu_ps(a + 40), _mm256_loadu_ps(b + 40)); v = _mm256_fmadd_ps(v2, v2, v); return _mm256_reduceadd_ps(v); } template<> inline float normL2Sqr_<56>(const float* a, const float* b) { __m256 v = _mm256_sub_ps(_mm256_loadu_ps(a), _mm256_loadu_ps(b)); v = _mm256_mul_ps(v, v); __m256 v2 = _mm256_sub_ps(_mm256_loadu_ps(a + 8), _mm256_loadu_ps(b + 8)); v = _mm256_fmadd_ps(v2, v2, v); v2 = _mm256_sub_ps(_mm256_loadu_ps(a + 16), _mm256_loadu_ps(b + 16)); v = _mm256_fmadd_ps(v2, v2, v); v2 = _mm256_sub_ps(_mm256_loadu_ps(a + 24), _mm256_loadu_ps(b + 24)); v = _mm256_fmadd_ps(v2, v2, v); v2 = _mm256_sub_ps(_mm256_loadu_ps(a + 32), _mm256_loadu_ps(b + 32)); v = _mm256_fmadd_ps(v2, v2, v); v2 = _mm256_sub_ps(_mm256_loadu_ps(a + 40), _mm256_loadu_ps(b + 40)); v = _mm256_fmadd_ps(v2, v2, v); v2 = _mm256_sub_ps(_mm256_loadu_ps(a + 48), _mm256_loadu_ps(b + 48)); v = _mm256_fmadd_ps(v2, v2, v); return _mm256_reduceadd_ps(v); } template<> inline float normL2Sqr_<64>(const float* a, const float* b) { __m256 v = _mm256_sub_ps(_mm256_loadu_ps(a), _mm256_loadu_ps(b)); v = _mm256_mul_ps(v, v); __m256 v2 = _mm256_sub_ps(_mm256_loadu_ps(a + 8), _mm256_loadu_ps(b + 8)); v = _mm256_fmadd_ps(v2, v2, v); v2 = _mm256_sub_ps(_mm256_loadu_ps(a + 16), _mm256_loadu_ps(b + 16)); v = _mm256_fmadd_ps(v2, v2, v); v2 = _mm256_sub_ps(_mm256_loadu_ps(a + 24), _mm256_loadu_ps(b + 24)); v = _mm256_fmadd_ps(v2, v2, v); v2 = _mm256_sub_ps(_mm256_loadu_ps(a + 32), _mm256_loadu_ps(b + 32)); v = _mm256_fmadd_ps(v2, v2, v); v2 = _mm256_sub_ps(_mm256_loadu_ps(a + 40), _mm256_loadu_ps(b + 40)); v = _mm256_fmadd_ps(v2, v2, v); v2 = _mm256_sub_ps(_mm256_loadu_ps(a + 48), _mm256_loadu_ps(b + 48)); v = _mm256_fmadd_ps(v2, v2, v); v2 = _mm256_sub_ps(_mm256_loadu_ps(a + 56), _mm256_loadu_ps(b + 56)); v = _mm256_fmadd_ps(v2, v2, v); return _mm256_reduceadd_ps(v); } #pragma endregion void KMeans::generateKmeansRandomInitialCentroidAoS(const cv::Mat& data_points, Mat& dest_centroids, const int K, RNG& rng) { const int dims = data_points.cols; const int N = data_points.rows; cv::AutoBuffer<Vec2f, 64> box(dims); { const float* sample = data_points.ptr<float>(0); for (int j = 0; j < dims; j++) box[j] = Vec2f(sample[j], sample[j]); } for (int i = 1; i < N; i++) { const float* sample = data_points.ptr<float>(i); for (int j = 0; j < dims; j++) { float v = sample[j]; box[j][0] = std::min(box[j][0], v); box[j][1] = std::max(box[j][1], v); } } const bool isUseMargin = false;//using margin is OpenCV's implementation if (isUseMargin) { const float margin = 1.f / dims; for (int k = 0; k < K; k++) { float* dptr = dest_centroids.ptr<float>(k); for (int d = 0; d < dims; d++) { dptr[d] = ((float)rng * (1.f + margin * 2.f) - margin) * (box[d][1] - box[d][0]) + box[d][0]; } } } else { for (int k = 0; k < K; k++) { float* dptr = dest_centroids.ptr<float>(k); for (int d = 0; d < dims; d++) { dptr[d] = rng.uniform(box[d][0], box[d][1]); } } } } class KMeansPPDistanceComputerAoS : public ParallelLoopBody { public: KMeansPPDistanceComputerAoS(float* tdist2_, const Mat& data_, const float* dist_, int ci_) : tdist2(tdist2_), data(data_), dist(dist_), ci(ci_) { } void operator()(const cv::Range& range) const CV_OVERRIDE { //CV_TRACE_FUNCTION(); const int begin = range.start; const int end = range.end; const int dims = data.cols; for (int i = begin; i < end; i++) { tdist2[i] = std::min(normL2Sqr_(data.ptr<float>(i), data.ptr<float>(ci), dims), dist[i]); } } private: KMeansPPDistanceComputerAoS& operator=(const KMeansPPDistanceComputerAoS&); // = delete float* tdist2; const Mat& data; const float* dist; const int ci; }; void KMeans::generateKmeansPPInitialCentroidAoS(const Mat& data, Mat& _out_centers, int K, RNG& rng, int trials) { //CV_TRACE_FUNCTION(); const int dims = data.cols; const int N = data.rows; cv::AutoBuffer<int, 64> _centers(K); int* centers = &_centers[0]; cv::AutoBuffer<float, 0> _dist(N * 3); float* dist = &_dist[0], * tdist = dist + N, * tdist2 = tdist + N; double sum0 = 0; centers[0] = (unsigned)rng % N; for (int i = 0; i < N; i++) { dist[i] = normL2Sqr_(data.ptr<float>(i), data.ptr<float>(centers[0]), dims); sum0 += dist[i]; } for (int k = 1; k < K; k++) { double bestSum = DBL_MAX; int bestCenter = -1; for (int j = 0; j < trials; j++) { double p = (double)rng * sum0; int ci = 0; for (; ci < N - 1; ci++) { p -= dist[ci]; if (p <= 0) break; } parallel_for_(Range(0, N), KMeansPPDistanceComputerAoS(tdist2, data, dist, ci), (double)divUp((size_t)(dims * N), CV_KMEANS_PARALLEL_GRANULARITY)); double s = 0; for (int i = 0; i < N; i++) { s += tdist2[i]; } if (s < bestSum) { bestSum = s; bestCenter = ci; std::swap(tdist, tdist2); } } if (bestCenter < 0) CV_Error(Error::StsNoConv, "kmeans: can't update cluster center (check input for huge or NaN values)"); centers[k] = bestCenter; sum0 = bestSum; std::swap(dist, tdist); } for (int k = 0; k < K; k++) { const float* src = data.ptr<float>(centers[k]); float* dst = _out_centers.ptr<float>(k); for (int j = 0; j < dims; j++) dst[j] = src[j]; } } template<bool onlyDistance, int loop> class KMeansDistanceComputerAoSDim : public ParallelLoopBody { public: KMeansDistanceComputerAoSDim(float* distances_, int* labels_, const Mat& data_, const Mat& centers_) : distances(distances_), labels(labels_), data(data_), centers(centers_) { } void operator()(const Range& range) const CV_OVERRIDE { const int begin = range.start; const int end = range.end; const int K = centers.rows; const int dims = centers.cols; const int avxend = dims / 8; const int issse = (dims - avxend * 8) / 4; const int rem = dims - avxend * 8 - issse * 4; for (int i = begin; i < end; ++i) { const float* sample = data.ptr<float>(i); if (onlyDistance) { const float* center = centers.ptr<float>(labels[i]); distances[i] = normL2Sqr_(sample, center, dims); continue; } else { int k_best = 0; float min_dist = FLT_MAX; for (int k = 0; k < K; k++) { const float* center = centers.ptr<float>(k); const float dist = normL2Sqr_(sample, center, dims); //const float dist = normL2Sqr_(sample, center, avxend, issse, rem); if (min_dist > dist) { min_dist = dist; k_best = k; } } distances[i] = min_dist; labels[i] = k_best; } } } private: KMeansDistanceComputerAoSDim& operator=(const KMeansDistanceComputerAoSDim&); // = delete float* distances; int* labels; const Mat& data; const Mat& centers; }; template<bool onlyDistance, int dims, int loop> class KMeansDistanceComputerAoS : public ParallelLoopBody { public: KMeansDistanceComputerAoS(float* distances_, int* labels_, const Mat& data_, const Mat& centers_) : distances(distances_), labels(labels_), data(data_), centers(centers_) { } void operator()(const Range& range) const CV_OVERRIDE { const int begin = range.start; const int end = range.end; const int K = centers.rows; //n-k-d if (onlyDistance) { for (int n = begin; n < end; ++n) { const float* sample = data.ptr<float>(n); { const float* center = centers.ptr<float>(labels[n]); distances[n] = normL2Sqr_<dims>(sample, center); continue; } } } else { if (loop == KMeansDistanceLoop::NKD) { for (int n = begin; n < end; ++n) { const float* sample = data.ptr<float>(n); int k_best = 0; float min_dist = FLT_MAX; for (int k = 0; k < K; ++k) { const float* center = centers.ptr<float>(k); const float dist = normL2Sqr_<dims>(sample, center); if (min_dist > dist) { min_dist = dist; k_best = k; } } distances[n] = min_dist; labels[n] = k_best; } } else //k-n-d { { //int k = 0; const float* center = centers.ptr<float>(0); for (int n = begin; n < end; ++n) { const float* sample = data.ptr<float>(n); distances[n] = normL2Sqr_<dims>(sample, center); labels[n] = 0; } } for (int k = 1; k < K; ++k) { const float* center = centers.ptr<float>(k); for (int n = begin; n < end; ++n) { const float* sample = data.ptr<float>(n); const float dist = normL2Sqr_<dims>(sample, center); if (distances[n] > dist) { distances[n] = dist; labels[n] = k; } } } } } } private: KMeansDistanceComputerAoS& operator=(const KMeansDistanceComputerAoS&); // = delete float* distances; int* labels; const Mat& data; const Mat& centers; }; void KMeans::boxMeanCentroidAoS(Mat& data_points, const int* labels, Mat& centroids, int* counters) { const int N = data_points.rows; const int dims = data_points.cols; for (int i = 0; i < N; i++) { const float* sample = data_points.ptr<float>(i); int k = labels[i]; float* center = centroids.ptr<float>(k); for (int j = 0; j < dims; j++) { center[j] += sample[j]; } counters[k]++; } } double KMeans::clusteringAoS(InputArray _data, int K, InputOutputArray _bestLabels, TermCriteria criteria, int attempts, int flags, OutputArray _centers, MeanFunction function, int loop) { const int SPP_TRIALS = 3; Mat src = _data.getMat(); const bool isrow = (src.rows == 1); const int N = isrow ? src.cols : src.rows; const int dims = (isrow ? 1 : src.cols) * src.channels(); const int type = src.depth(); attempts = std::max(attempts, 1); CV_Assert(src.dims <= 2 && type == CV_32F && K > 0); CV_CheckGE(N, K, "Number of clusters should be more than number of elements"); Mat data_points(N, dims, CV_32F, src.ptr(), isrow ? dims * sizeof(float) : static_cast<size_t>(src.step)); _bestLabels.create(N, 1, CV_32S, -1, true); Mat best_labels = _bestLabels.getMat(); if (flags & cv::KMEANS_USE_INITIAL_LABELS) { CV_Assert((best_labels.cols == 1 || best_labels.rows == 1) && best_labels.cols * best_labels.rows == N && best_labels.type() == CV_32S && best_labels.isContinuous()); best_labels.reshape(1, N).copyTo(labels_internal); for (int i = 0; i < N; i++) { CV_Assert((unsigned)labels_internal.at<int>(i) < (unsigned)K); } } else { if (!((best_labels.cols == 1 || best_labels.rows == 1) && best_labels.cols * best_labels.rows == N && best_labels.type() == CV_32S && best_labels.isContinuous())) { _bestLabels.create(N, 1, CV_32S); best_labels = _bestLabels.getMat(); } labels_internal.create(best_labels.size(), best_labels.type()); } int* labels = labels_internal.ptr<int>(); Mat centroids(K, dims, type); Mat old_centroids(K, dims, type), temp(1, dims, type); cv::AutoBuffer<int, 64> counters(K); cv::AutoBuffer<float, 64> dists(N); //dists.resize(N); RNG& rng = theRNG(); if (criteria.type & TermCriteria::EPS) criteria.epsilon = std::max(criteria.epsilon, 0.); else criteria.epsilon = FLT_EPSILON; criteria.epsilon *= criteria.epsilon; if (criteria.type & TermCriteria::COUNT) criteria.maxCount = std::min(std::max(criteria.maxCount, 2), 100); else criteria.maxCount = 100; if (K == 1) { attempts = 1; criteria.maxCount = 2; } double best_compactness = DBL_MAX; for (int attempt_index = 0; attempt_index < attempts; attempt_index++) { double compactness = 0.0; //main loop for (int iter = 0; ;) { float max_center_shift = (iter == 0) ? FLT_MAX : 0.f; swap(centroids, old_centroids); const bool isInit = ((iter == 0) && (attempt_index > 0 || !(flags & KMEANS_USE_INITIAL_LABELS)));//initial attemp && KMEANS_USE_INITIAL_LABELS is true if (isInit) { if (flags & KMEANS_PP_CENTERS) { generateKmeansPPInitialCentroidAoS(data_points, centroids, K, rng, SPP_TRIALS); } else { generateKmeansRandomInitialCentroidAoS(data_points, centroids, K, rng); } } else { //update centroid centroids = Scalar(0.f); for (int k = 0; k < K; k++) counters[k] = 0; if (function == MeanFunction::Harmonic) { cout << "MeanFunction::Harmonic not support" << endl; } else if (function == MeanFunction::Gauss || function == MeanFunction::GaussInv) { cout << "MeanFunction::Gauss/MeanFunction::GaussInv not support" << endl; } else if (function == MeanFunction::Mean) { boxMeanCentroidAoS(data_points, labels, centroids, counters); } for (int k = 0; k < K; k++) { if (counters[k] != 0) continue; // if some cluster appeared to be empty then: // 1. find the biggest cluster // 2. find the farthest from the center point in the biggest cluster // 3. exclude the farthest point from the biggest cluster and form a new 1-point cluster. int k_count_max = 0; for (int k1 = 1; k1 < K; k1++) { if (counters[k_count_max] < counters[k1]) k_count_max = k1; } double max_dist = 0; int farthest_i = -1; float* base_center = centroids.ptr<float>(k_count_max); float* _base_center = temp.ptr<float>(); // normalized float scale = 1.f / counters[k_count_max]; for (int j = 0; j < dims; j++) _base_center[j] = base_center[j] * scale; for (int i = 0; i < N; i++) { if (labels[i] != k_count_max) continue; const float* sample = data_points.ptr<float>(i); double dist = normL2Sqr_(sample, _base_center, dims); if (max_dist <= dist) { max_dist = dist; farthest_i = i; } } counters[k_count_max]--; counters[k]++; labels[farthest_i] = k; const float* sample = data_points.ptr<float>(farthest_i); float* cur_center = centroids.ptr<float>(k); for (int j = 0; j < dims; j++) { base_center[j] -= sample[j]; cur_center[j] += sample[j]; } } for (int k = 0; k < K; k++) { float* center = centroids.ptr<float>(k); CV_Assert(counters[k] != 0); float scale = 1.f / counters[k]; for (int j = 0; j < dims; j++) center[j] *= scale; if (iter > 0) { float dist = 0.f; const float* old_center = old_centroids.ptr<float>(k); for (int j = 0; j < dims; j++) { float t = center[j] - old_center[j]; dist += t * t; } max_center_shift = std::max(max_center_shift, dist); } } } bool isLastIter = (++iter == MAX(criteria.maxCount, 2) || max_center_shift <= criteria.epsilon); if (isLastIter) { //int parallel = (double)divUp((size_t)(dims * N * K), CV_KMEANS_PARALLEL_GRANULARITY); int parallel = cv::getNumThreads(); // don't re-assign labels to avoid creation of empty clusters parallel_for_(Range(0, N), KMeansDistanceComputerAoSDim<true, KMeansDistanceLoop::NKD>(dists.data(), labels, data_points, centroids), parallel); compactness = sum(Mat(Size(N, 1), CV_32F, &dists[0]))[0]; break; } else { //int parallel = (double)divUp((size_t)(dims * N * K), CV_KMEANS_PARALLEL_GRANULARITY); int parallel = cv::getNumThreads(); // assign labels if (loop == KMeansDistanceLoop::NKD) { switch (dims) { case 1: parallel_for_(Range(0, N), KMeansDistanceComputerAoS<false, 1, KMeansDistanceLoop::NKD>(dists.data(), labels, data_points, centroids), parallel); break; case 2: parallel_for_(Range(0, N), KMeansDistanceComputerAoS<false, 2, KMeansDistanceLoop::NKD>(dists.data(), labels, data_points, centroids), parallel); break; case 3: parallel_for_(Range(0, N), KMeansDistanceComputerAoS<false, 3, KMeansDistanceLoop::NKD>(dists.data(), labels, data_points, centroids), parallel); break; case 4: parallel_for_(Range(0, N), KMeansDistanceComputerAoS<false, 4, KMeansDistanceLoop::NKD>(dists.data(), labels, data_points, centroids), parallel); break; case 5: parallel_for_(Range(0, N), KMeansDistanceComputerAoS<false, 5, KMeansDistanceLoop::NKD>(dists.data(), labels, data_points, centroids), parallel); break; case 6: parallel_for_(Range(0, N), KMeansDistanceComputerAoS<false, 6, KMeansDistanceLoop::NKD>(dists.data(), labels, data_points, centroids), parallel); break; case 7: parallel_for_(Range(0, N), KMeansDistanceComputerAoS<false, 7, KMeansDistanceLoop::NKD>(dists.data(), labels, data_points, centroids), parallel); break; case 8: parallel_for_(Range(0, N), KMeansDistanceComputerAoS<false, 8, KMeansDistanceLoop::NKD>(dists.data(), labels, data_points, centroids), parallel); break; case 9: parallel_for_(Range(0, N), KMeansDistanceComputerAoS<false, 9, KMeansDistanceLoop::NKD>(dists.data(), labels, data_points, centroids), parallel); break; case 10: parallel_for_(Range(0, N), KMeansDistanceComputerAoS<false, 10, KMeansDistanceLoop::NKD>(dists.data(), labels, data_points, centroids), parallel); break; case 11: parallel_for_(Range(0, N), KMeansDistanceComputerAoS<false, 11, KMeansDistanceLoop::NKD>(dists.data(), labels, data_points, centroids), parallel); break; case 12: parallel_for_(Range(0, N), KMeansDistanceComputerAoS<false, 12, KMeansDistanceLoop::NKD>(dists.data(), labels, data_points, centroids), parallel); break; case 16: parallel_for_(Range(0, N), KMeansDistanceComputerAoS<false, 16, KMeansDistanceLoop::NKD>(dists.data(), labels, data_points, centroids), parallel); break; case 24: parallel_for_(Range(0, N), KMeansDistanceComputerAoS<false, 24, KMeansDistanceLoop::NKD>(dists.data(), labels, data_points, centroids), parallel); break; case 32: parallel_for_(Range(0, N), KMeansDistanceComputerAoS<false, 32, KMeansDistanceLoop::NKD>(dists.data(), labels, data_points, centroids), parallel); break; case 40: parallel_for_(Range(0, N), KMeansDistanceComputerAoS<false, 40, KMeansDistanceLoop::NKD>(dists.data(), labels, data_points, centroids), parallel); break; case 41: parallel_for_(Range(0, N), KMeansDistanceComputerAoS<false, 41, KMeansDistanceLoop::NKD>(dists.data(), labels, data_points, centroids), parallel); break; case 42: parallel_for_(Range(0, N), KMeansDistanceComputerAoS<false, 42, KMeansDistanceLoop::NKD>(dists.data(), labels, data_points, centroids), parallel); break; case 43: parallel_for_(Range(0, N), KMeansDistanceComputerAoS<false, 43, KMeansDistanceLoop::NKD>(dists.data(), labels, data_points, centroids), parallel); break; case 44: parallel_for_(Range(0, N), KMeansDistanceComputerAoS<false, 44, KMeansDistanceLoop::NKD>(dists.data(), labels, data_points, centroids), parallel); break; case 48: parallel_for_(Range(0, N), KMeansDistanceComputerAoS<false, 48, KMeansDistanceLoop::NKD>(dists.data(), labels, data_points, centroids), parallel); break; case 56: parallel_for_(Range(0, N), KMeansDistanceComputerAoS<false, 56, KMeansDistanceLoop::NKD>(dists.data(), labels, data_points, centroids), parallel); break; case 64: parallel_for_(Range(0, N), KMeansDistanceComputerAoS<false, 64, KMeansDistanceLoop::NKD>(dists.data(), labels, data_points, centroids), parallel); break; default: parallel_for_(Range(0, N), KMeansDistanceComputerAoSDim<false, KMeansDistanceLoop::NKD>(dists.data(), labels, data_points, centroids), parallel); break; } } else { switch (dims) { case 1: parallel_for_(Range(0, N), KMeansDistanceComputerAoS<false, 1, KMeansDistanceLoop::KND>(dists.data(), labels, data_points, centroids), parallel); break; case 2: parallel_for_(Range(0, N), KMeansDistanceComputerAoS<false, 2, KMeansDistanceLoop::KND>(dists.data(), labels, data_points, centroids), parallel); break; case 3: parallel_for_(Range(0, N), KMeansDistanceComputerAoS<false, 3, KMeansDistanceLoop::KND>(dists.data(), labels, data_points, centroids), parallel); break; case 4: parallel_for_(Range(0, N), KMeansDistanceComputerAoS<false, 4, KMeansDistanceLoop::KND>(dists.data(), labels, data_points, centroids), parallel); break; case 5: parallel_for_(Range(0, N), KMeansDistanceComputerAoS<false, 5, KMeansDistanceLoop::KND>(dists.data(), labels, data_points, centroids), parallel); break; case 6: parallel_for_(Range(0, N), KMeansDistanceComputerAoS<false, 6, KMeansDistanceLoop::KND>(dists.data(), labels, data_points, centroids), parallel); break; case 7: parallel_for_(Range(0, N), KMeansDistanceComputerAoS<false, 7, KMeansDistanceLoop::KND>(dists.data(), labels, data_points, centroids), parallel); break; case 8: parallel_for_(Range(0, N), KMeansDistanceComputerAoS<false, 8, KMeansDistanceLoop::KND>(dists.data(), labels, data_points, centroids), parallel); break; case 9: parallel_for_(Range(0, N), KMeansDistanceComputerAoS<false, 9, KMeansDistanceLoop::KND>(dists.data(), labels, data_points, centroids), parallel); break; case 10: parallel_for_(Range(0, N), KMeansDistanceComputerAoS<false, 10, KMeansDistanceLoop::KND>(dists.data(), labels, data_points, centroids), parallel); break; case 11: parallel_for_(Range(0, N), KMeansDistanceComputerAoS<false, 11, KMeansDistanceLoop::KND>(dists.data(), labels, data_points, centroids), parallel); break; case 12: parallel_for_(Range(0, N), KMeansDistanceComputerAoS<false, 12, KMeansDistanceLoop::KND>(dists.data(), labels, data_points, centroids), parallel); break; case 16: parallel_for_(Range(0, N), KMeansDistanceComputerAoS<false, 16, KMeansDistanceLoop::KND>(dists.data(), labels, data_points, centroids), parallel); break; case 24: parallel_for_(Range(0, N), KMeansDistanceComputerAoS<false, 24, KMeansDistanceLoop::KND>(dists.data(), labels, data_points, centroids), parallel); break; case 32: parallel_for_(Range(0, N), KMeansDistanceComputerAoS<false, 32, KMeansDistanceLoop::KND>(dists.data(), labels, data_points, centroids), parallel); break; case 40: parallel_for_(Range(0, N), KMeansDistanceComputerAoS<false, 40, KMeansDistanceLoop::KND>(dists.data(), labels, data_points, centroids), parallel); break; case 41: parallel_for_(Range(0, N), KMeansDistanceComputerAoS<false, 41, KMeansDistanceLoop::KND>(dists.data(), labels, data_points, centroids), parallel); break; case 42: parallel_for_(Range(0, N), KMeansDistanceComputerAoS<false, 42, KMeansDistanceLoop::KND>(dists.data(), labels, data_points, centroids), parallel); break; case 43: parallel_for_(Range(0, N), KMeansDistanceComputerAoS<false, 43, KMeansDistanceLoop::KND>(dists.data(), labels, data_points, centroids), parallel); break; case 44: parallel_for_(Range(0, N), KMeansDistanceComputerAoS<false, 44, KMeansDistanceLoop::KND>(dists.data(), labels, data_points, centroids), parallel); break; case 48: parallel_for_(Range(0, N), KMeansDistanceComputerAoS<false, 48, KMeansDistanceLoop::KND>(dists.data(), labels, data_points, centroids), parallel); break; case 56: parallel_for_(Range(0, N), KMeansDistanceComputerAoS<false, 56, KMeansDistanceLoop::KND>(dists.data(), labels, data_points, centroids), parallel); break; case 64: parallel_for_(Range(0, N), KMeansDistanceComputerAoS<false, 64, KMeansDistanceLoop::KND>(dists.data(), labels, data_points, centroids), parallel); break; default: parallel_for_(Range(0, N), KMeansDistanceComputerAoSDim<false, KMeansDistanceLoop::KND>(dists.data(), labels, data_points, centroids), parallel); break; } } } } if (compactness < best_compactness) { best_compactness = compactness; if (_centers.needed()) { if (_centers.fixedType() && _centers.channels() == dims) centroids.reshape(dims).copyTo(_centers); else centroids.copyTo(_centers); } labels_internal.copyTo(best_labels); } } return best_compactness; } #pragma endregion #pragma region SoAoS double KMeans::clusteringSoAoS(InputArray _data, int K, InputOutputArray _bestLabels, TermCriteria criteria, int attempts, int flags, OutputArray _centers, MeanFunction function, int loop) { cout << "not implemented clusteringSoAoS" << endl; return 0.0; } #pragma endregion # }
norishigefukushima/OpenCP
OpenCP/kmeans.cpp
C++
bsd-3-clause
71,000
#ifndef _COLA_CIRCULAR_H_ #define _COLA_CIRCULAR_H_ /***************************************************************************** Definiciones de tipos ******************************************************************************/ typedef struct { int8_t *elemento; int32_t primero; int32_t ultimo; int32_t tamano; void (*cbColaVacia)( void ); void (*cbColaLlena)( void ); } cola_t; /***************************************************************************** Definiciones de funciones externas ******************************************************************************/ void configCola(cola_t *cola, int8_t *buffer, uint32_t tam, void (*cbColaVacia)( void ), void (*cbColaLlena)( void )); bool_t ponerEnCola(cola_t *cola, int8_t dato); bool_t sacarDeCola(cola_t *cola, int8_t *dato); #endif
gastonvallasciani/TPclase10
libs/cola_circular/inc/cola_circular.h
C
bsd-3-clause
800
package org.cagrid.gme.service.dao; import java.sql.SQLException; import java.util.Collection; import java.util.List; import javax.persistence.NonUniqueResultException; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.criterion.Example; import org.hibernate.criterion.MatchMode; import org.springframework.orm.hibernate3.HibernateCallback; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; public abstract class AbstractDao<T> extends HibernateDaoSupport { public abstract Class domainClass(); public T getByExample(final T sample) { T result = null; List<T> results = searchByExample(sample, false); if (results.size() > 1) { throw new NonUniqueResultException("Found " + results.size() + " " + sample.getClass().getName() + " objects."); } else if (results.size() == 1) { result = results.get(0); } return result; } @SuppressWarnings("unchecked") public T getById(int id) { return (T) getHibernateTemplate().get(domainClass(), id); } @SuppressWarnings("unchecked") public List<T> searchByExample(final T sample, final boolean inexactMatches) { return (List<T>) getHibernateTemplate().execute(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException, SQLException { Example example = Example.create(sample).excludeZeroes(); if (inexactMatches) { example.ignoreCase().enableLike(MatchMode.ANYWHERE); } return session.createCriteria(domainClass()).add(example).list(); } }); } public List<T> searchByExample(T example) { return searchByExample(example, true); } public void save(Collection<T> domainObjects) { getHibernateTemplate().saveOrUpdateAll(domainObjects); } public void save(T domainObject) { getHibernateTemplate().saveOrUpdate(domainObject); } public void update(T domainObject) { getHibernateTemplate().update(domainObject); } public void delete(T domainObject) { getHibernateTemplate().delete(domainObject); } public void delete(Collection<T> domainObjects) { getHibernateTemplate().deleteAll(domainObjects); } public List<T> getAll() { return getHibernateTemplate().find("from " + domainClass().getSimpleName()); } }
NCIP/cagrid
cagrid/Software/core/caGrid/projects/globalModelExchange/src/org/cagrid/gme/service/dao/AbstractDao.java
Java
bsd-3-clause
2,530
/* * Copyright (c) 2014-2015, Wanadev <http://www.wanadev.fr/> * 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 Wanadev 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. * * Authored by: Fabien LOISON <http://flozz.fr/> */ /** * PhotonUI - Javascript Web User Interface. * * @module PhotonUI * @submodule Interactive * @namespace photonui */ var Field = require("./field.js"); /** * Numeric field. * * @class NumericField * @constructor * @extends photonui.Field */ var NumericField = Field.$extend({ // Constructor __init__: function (params) { this.$super(params); this._bindFieldEvents(); this._unbindEvent("value-changed"); this._bindEvent("keypress", this.__html.field, "keypress", this.__onKeypress.bind(this)); this._bindEvent("keyup", this.__html.field, "keyup", this.__onKeyup.bind(this)); this._bindEvent("keydown", this.__html.field, "keydown", this.__onKeydown.bind(this)); this._bindEvent("change", this.__html.field, "change", this.__onChange.bind(this)); this._bindEvent("mousewheel", this.__html.field, "mousewheel", this.__onMouseWheel.bind(this)); this._bindEvent("mousewheel-firefox", this.__html.field, "DOMMouseScroll", this.__onMouseWheel.bind(this)); }, ////////////////////////////////////////// // Properties and Accessors // ////////////////////////////////////////// // ====== Public properties ====== /** * The minimum value of the field. * * @property min * @type Number * default null (no minimum); */ _min: null, getMin: function () { return this._min; }, setMin: function (min) { "@photonui-update"; this._min = min; this._updateValue(this.value); this._updateFieldValue(); }, /** * The maximum value of the field. * * @property max * @type Number * default null (no maximum); */ _max: null, getMax: function () { return this._max; }, setMax: function (max) { "@photonui-update"; this._max = max; this._updateValue(this.value); this._updateFieldValue(); }, /** * The incrementation step of the field. * * @property step * @type Number * default 1 */ _step: 1, getStep: function () { return this._step; }, setStep: function (step) { this._step = Math.abs(step); }, /** * The number of digit after the decimal dot. * * @property decimalDigits * @type Number * @default null (no limite) */ _decimalDigits: null, getDecimalDigits: function () { "@photonui-update"; return this._decimalDigits; }, setDecimalDigits: function (decimalDigits) { this._decimalDigits = decimalDigits; this._updateValue(this.value); this._updateFieldValue(); }, /** * The decimal symbol ("." or ","). * * @property decimalSymbol * @type String * @default: "." */ _decimalSymbol: ".", getDecimalSymbol: function () { "@photonui-update"; return this._decimalSymbol; }, setDecimalSymbol: function (decimalSymbol) { this._decimalSymbol = decimalSymbol; this._updateValue(this.value); this._updateFieldValue(); }, /** * The field value. * * @property value * @type Number * @default 0 */ _value: 0, getValue: function () { "@photonui-update"; return parseFloat(this._value); }, setValue: function (value) { this._updateValue(value); this._updateFieldValue(); }, ////////////////////////////////////////// // Methods // ////////////////////////////////////////// // ====== Private methods ====== /** * Update the value (in the widget). * * @method _updateValue * @private * @param {String|Number} value The raw value. */ _updateValue: function (value) { value = String(value).replace(",", "."); // "," value = value.replace(/ /g, ""); // remove spaces value = parseFloat(value); if (isNaN(value)) { value = 0; } if (this.min !== null) { value = Math.max(this.min, value); } if (this.max !== null) { value = Math.min(this.max, value); } if (this.decimalDigits !== null) { value = value.toFixed(this.decimalDigits); } this._value = value; }, /** * Update the value in the html field. * * @method _updateFieldValue * @private */ _updateFieldValue: function () { this.__html.field.value = String(this._value).replace(".", this.decimalSymbol); }, /** * Validate the user inputs. * * @method _validateInput * @private * @param {String} value * @return {Boolean} */ _validateInput: function (value) { value = String(value); value = value.replace(/ /g, ""); // remove spaces if (/^-?[0-9]*(\.|,)?[0-9]*$/.test(value)) { if (this.decimalDigits === 0 && !/^-?[0-9]*$/.test(value)) { return false; } if (this.min !== null && this.min >= 0 && value[0] == "-") { return false; } return true; } return false; }, /** * Build the widget HTML. * * @method _buildHtml * @private */ _buildHtml: function () { this.__html.field = document.createElement("input"); this.__html.field.className = "photonui-widget photonui-field photonui-numericfield"; this.__html.field.type = "text"; }, ////////////////////////////////////////// // Internal Events Callbacks // ////////////////////////////////////////// /** * @method __onKeypress * @private * @param event */ __onKeypress: function (event) { if (event.ctrlKey || event.key == "ArrowLeft" || event.key == "ArrowRight" || event.key == "Backspace" || event.key == "Delete" ) { return; } else if (event.keyCode == 13) { // Enter this._updateFieldValue(); this._callCallbacks("value-changed", [this.value]); this.__debValueChangedFinal(); } else { var field = this.__html.field; var value = field.value.slice(0, field.selectionStart) + String.fromCharCode(event.charCode) + field.value.slice(field.selectionEnd); if (!this._validateInput(value)) { event.preventDefault(); } } }, /** * @method __onKeyup * @private * @param event */ __onKeyup: function (event) { var value = this.__html.field.value.replace(/[^0-9.,-]*/g, ""); if (value != this.__html.field.value) { this.__html.field.value = value; } this._updateValue(this.__html.field.value); }, /** * @method __onChange * @private * @param event */ __onChange: function (event) { this._updateFieldValue(); this._callCallbacks("value-changed", [this.value]); this.__debValueChangedFinal(); }, /** * @method __onMouseWheel * @private * @param event */ __onMouseWheel: function (event) { if (document.activeElement != this.__html.field) { return; } var wheelDelta = null; // Webkit if (event.wheelDeltaY !== undefined) { wheelDelta = event.wheelDeltaY; } // MSIE if (event.wheelDelta !== undefined) { wheelDelta = event.wheelDelta; } // Firefox if (event.axis !== undefined && event.detail !== undefined) { if (event.axis == 2) { // Y wheelDelta = -event.detail; } } if (wheelDelta !== null) { if (wheelDelta >= 0) { this.value += this.step; } else { this.value -= this.step; } event.preventDefault(); } this._callCallbacks("value-changed", [this.value]); this.__debValueChangedFinal(); }, /** * @method __onKeydown * @private * @param event */ __onKeydown: function (event) { if (event.keyCode == 38) { this.value += this.step; event.preventDefault(); this._callCallbacks("value-changed", [this.value]); this.__debValueChangedFinal(); } else if (event.keyCode == 40) { this.value -= this.step; event.preventDefault(); this._callCallbacks("value-changed", [this.value]); this.__debValueChangedFinal(); } } }); module.exports = NumericField;
wanadev/PhotonUI
src/interactive/numericfield.js
JavaScript
bsd-3-clause
10,561
<?php namespace core\autoloader; use core\autoloader\Devisor as Devisor; /** * This class is used to autoload class files from (sub)directories * passed following the namespace convention. The spl_autoload_register * function is overridden to avoid the forced lowercase classname lookup. * This class can additionally be used to load files in a given namespace * if the namespace definition follows the directory structure. * @author Marc Bredt */ class AutoLoader { /** * Root directory where classes should be loaded from. * Should be the root directory of the aplication to fit * namespaces. */ private $rdir = null; /** * Stores (sub)directories containing class files. */ private $cdirs = array(); /** * Stores the old include path. */ private $old_include_path = null; /** * Stores the modified include path. */ private $include_path = null; /** * Stores old extension for loadable classes. */ private $old_extensions = ""; /** * Default extension for loadable classes. */ private $extensions = null; /** * Saves previously set spl autoloading functions. */ private $osaf = null; /** * Shows if the autoloader was already initialized. */ private $load = false; /** * Makes $this->rdir available to a callable scope * @see AutoLoader::register_autoload */ private $rd = null; /** * Makes $this->extension available to a callable scope * @see AutoLoader::register_autoload */ private $xt = null; /** * Makes $this->testing available to a callable scope * @see AutoLoader::register_autoload */ private $ts = null; /** * Loads autoloadable classes and modifies pathes. * @param $load set to false if the AutoLoader should not be * initialized on creation, default is true * @param $dir directory to search for classes. * @param $extensions default class filename extension. */ public function __construct($load = true, $dir = ".", $extensions = "") { // extensions if ( strncmp(gettype($extensions),"string",6)==0 && strncmp($extensions, "", 1)!=0 ) { $this->extensions = $extensions; } else { $this->extensions = ".class.php"; } // root directory $this->rdir = $dir; // initializing just once if(strncmp(gettype($load),"boolean",7)==0) $this->load = $load; if($this->load) { $this->load = false; $this->load(); } } /** * Loads and registers the main autoload functions. * @see http://www.php.net/manual/en/function.spl-autoload-register.php#96804 */ public function load() { // check if initilization was done on creation, if not initialize it if(!$this->load) { // save the old include path $this->old_include_path = get_include_path(); // set the include path with dirs from $this->cdirs set_include_path(get_include_path().PATH_SEPARATOR.$this->rdir); // register extensions $this->old_extensions = spl_autoload_extensions(); spl_autoload_extensions($this->extensions); // store registered autoloading functions $this->osaf = spl_autoload_functions(); // register the autoload function $this->register_autoload(); // update the current include path $this->include_path = get_include_path(); // avoid reinitialization $this->load = true; } } /** * Registers an autoload function. * @return true on success else false */ private function register_autoload() { // get some necessary variables to be passed as references to the closure // via "use" construct $rd = $this->rdir; $xt = $this->extensions; return spl_autoload_register( function($class) use (&$rd, &$xt) { call_user_func(array(new Devisor($rd,$xt),'load'), $class); } ); } /** * Register additonal extensions. * @param $extension extension that should be registered too */ public function expand($extension = "") { if(strncmp(gettype($extension),"string",6)!=0) $extension = ""; if(strncmp($extension,"",1)!=0) { $this->extensions = preg_replace("/^,+|,+$/","", $this->extensions.",".$extension); spl_autoload_extensions($this->extensions); } } /** * Unload the autoloader. * @see Devisor */ public function unload() { // just unload if the autoloader has already been initialized if($this->load) { set_include_path($this->getop()); spl_autoload_extensions($this->getoe()); $this->old_include_path = null; $this->include_path = null; $this->old_extensions = null; $this->extensions = null; $this->load = false; } } /** * Get current include path. * @return string modified include path. */ public function getp() { return $this->include_path; } /** * Get current old include path. * @return string containing old include path. */ public function getop() { return $this->old_include_path; } /** * Get the (spl) classes currently loaded. * @return array containing all available classes. */ public function getc() { return get_declared_classes(); } /** * Get the extensions currently registered. * @return string containing extension currently registered through * spl_autoload_extensions. */ public function gete() { return $this->extensions; } /** * Get the old extensions registered. * @return string containing old extension registered */ public function getoe() { return $this->old_extensions; } /** * Get the old spl autoloading functions stored. * @return array with previously stored spl autoloading functions */ public function getosaf() { return $this->osaf; } /** * Dump instace info. * @return string containing instance representation */ public function __toString() { return get_class($this)."-".spl_object_hash($this).": ". preg_replace("/ +/", " ", preg_replace("/[\r\n]/", "", var_export($this,true))); } } ?>
marcbredt/heili
trunk/src/core/autoloader/autoloader.class.php
PHP
bsd-3-clause
6,215
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <title>CLI: ui_less.cpp Source File</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <link href="doxygen.css" rel="stylesheet" type="text/css"/> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-20981143-1']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> </head> <body> <!-- Generated by Doxygen 1.7.1 --> <div class="navigation" id="top"> <div class="tabs"> <ul class="tablist"> <li><a href="main.html"><span>Main&nbsp;Page</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li><a href="annotated.html"><span>Classes</span></a></li> <li class="current"><a href="files.html"><span>Files</span></a></li> </ul> </div> <div class="tabs2"> <ul class="tablist"> <li><a href="files.html"><span>File&nbsp;List</span></a></li> <li><a href="globals.html"><span>File&nbsp;Members</span></a></li> </ul> </div> <div class="header"> <div class="headertitle"> <h1>ui_less.cpp</h1> </div> </div> <div class="contents"> <div class="fragment"><pre class="fragment"><a name="l00001"></a>00001 <span class="comment">/*</span> <a name="l00002"></a>00002 <span class="comment"> Copyright (c) 2006-2013, Alexis Royer, http://alexis.royer.free.fr/CLI</span> <a name="l00003"></a>00003 <span class="comment"></span> <a name="l00004"></a>00004 <span class="comment"> All rights reserved.</span> <a name="l00005"></a>00005 <span class="comment"></span> <a name="l00006"></a>00006 <span class="comment"> Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:</span> <a name="l00007"></a>00007 <span class="comment"></span> <a name="l00008"></a>00008 <span class="comment"> * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.</span> <a name="l00009"></a>00009 <span class="comment"> * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation</span> <a name="l00010"></a>00010 <span class="comment"> and/or other materials provided with the distribution.</span> <a name="l00011"></a>00011 <span class="comment"> * Neither the name of the CLI library project nor the names of its contributors may be used to endorse or promote products derived from this software</span> <a name="l00012"></a>00012 <span class="comment"> without specific prior written permission.</span> <a name="l00013"></a>00013 <span class="comment"></span> <a name="l00014"></a>00014 <span class="comment"> THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS</span> <a name="l00015"></a>00015 <span class="comment"> &quot;AS IS&quot; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT</span> <a name="l00016"></a>00016 <span class="comment"> LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR</span> <a name="l00017"></a>00017 <span class="comment"> A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR</span> <a name="l00018"></a>00018 <span class="comment"> CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,</span> <a name="l00019"></a>00019 <span class="comment"> EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,</span> <a name="l00020"></a>00020 <span class="comment"> PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR</span> <a name="l00021"></a>00021 <span class="comment"> PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF</span> <a name="l00022"></a>00022 <span class="comment"> LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING</span> <a name="l00023"></a>00023 <span class="comment"> NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS</span> <a name="l00024"></a>00024 <span class="comment"> SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.</span> <a name="l00025"></a>00025 <span class="comment">*/</span> <a name="l00026"></a>00026 <a name="l00027"></a>00027 <a name="l00028"></a>00028 <span class="preprocessor">#include &quot;<a class="code" href="pch_8h.html" title="CLI library default pre-compiled header.">cli/pch.h</a>&quot;</span> <a name="l00029"></a>00029 <a name="l00030"></a>00030 <span class="preprocessor">#include &quot;<a class="code" href="assert_8h.html" title="Assertion facilities.">cli/assert.h</a>&quot;</span> <a name="l00031"></a>00031 <span class="preprocessor">#include &quot;<a class="code" href="ui__less_8h.html" title="Less class definition.">cli/ui_less.h</a>&quot;</span> <a name="l00032"></a>00032 <span class="preprocessor">#include &quot;<a class="code" href="shell_8h.html" title="Shell class definition.">cli/shell.h</a>&quot;</span> <a name="l00033"></a>00033 <span class="preprocessor">#include &quot;<a class="code" href="string__device_8h.html" title="String device definition.">cli/string_device.h</a>&quot;</span> <a name="l00034"></a>00034 <span class="preprocessor">#include &quot;<a class="code" href="ui__text_8h.html" title="Text class definition.">ui_text.h</a>&quot;</span> <a name="l00035"></a>00035 <span class="preprocessor">#include &quot;<a class="code" href="command__line__edition_8h.html" title="CmdLineEdition class definition.">command_line_edition.h</a>&quot;</span> <a name="l00036"></a>00036 <a name="l00037"></a>00037 <a name="l00038"></a>00038 <a class="code" href="namespace_8h.html#a43bf79d829bcd245270f7ed0ba16155a" title="Begin a namespace definition.">CLI_NS_BEGIN</a>(cli) <a name="l00039"></a>00039 <a name="l00040"></a>00040 <a class="code" href="namespace_8h.html#a43bf79d829bcd245270f7ed0ba16155a" title="Begin a namespace definition.">CLI_NS_BEGIN</a>(ui) <a name="l00041"></a>00041 <a name="l00042"></a><a class="code" href="classLess.html#acb4ef33a5dfb39681e7da2f9b7e32b4c">00042</a> <a class="code" href="classLess.html" title="Simple line user interface object.">Less</a>::<a class="code" href="classLess.html" title="Simple line user interface object.">Less</a>(const <span class="keywordtype">unsigned</span> <span class="keywordtype">int</span> UI_MaxLines, const <span class="keywordtype">unsigned</span> <span class="keywordtype">int</span> UI_MaxLineLength) <a name="l00043"></a>00043 : <a class="code" href="classUI.html" title="Generic user interface class.">UI</a>(), <a name="l00044"></a>00044 m_uiText(* new <a class="code" href="classText.html" title="Simple line user interface object.">Text</a>(UI_MaxLines, UI_MaxLineLength)), m_puiTextIt(NULL), <a name="l00045"></a>00045 m_cliLessLine(* new <a class="code" href="classCmdLineEdition.html" title="Command line edition objet.">CmdLineEdition</a>()) <a name="l00046"></a>00046 { <a name="l00047"></a>00047 } <a name="l00048"></a>00048 <a name="l00049"></a><a class="code" href="classLess.html#a505844f3f4cbc002e4967051a80aa651">00049</a> <a class="code" href="classLess.html#acb4ef33a5dfb39681e7da2f9b7e32b4c" title="Top execution context constructor.">Less::Less</a>(<a class="code" href="classExecutionContext.html" title="Execution context.">ExecutionContext</a>&amp; CLI_ParentContext, <span class="keyword">const</span> <span class="keywordtype">unsigned</span> <span class="keywordtype">int</span> UI_MaxLines, <span class="keyword">const</span> <span class="keywordtype">unsigned</span> <span class="keywordtype">int</span> UI_MaxLineLength) <a name="l00050"></a>00050 : <a class="code" href="classUI.html" title="Generic user interface class.">UI</a>(CLI_ParentContext), <a name="l00051"></a>00051 m_uiText(* new <a class="code" href="classText.html" title="Simple line user interface object.">Text</a>(UI_MaxLines, UI_MaxLineLength)), m_puiTextIt(NULL), <a name="l00052"></a>00052 m_cliLessLine(* new <a class="code" href="classCmdLineEdition.html" title="Command line edition objet.">CmdLineEdition</a>()) <a name="l00053"></a>00053 { <a name="l00054"></a>00054 } <a name="l00055"></a>00055 <a name="l00056"></a><a class="code" href="classLess.html#ac33c52dc48e17e505f18d778db8662fb">00056</a> <a class="code" href="classLess.html#ac33c52dc48e17e505f18d778db8662fb" title="Destructor.">Less::~Less</a>(<span class="keywordtype">void</span>) <a name="l00057"></a>00057 { <a name="l00058"></a>00058 <span class="keyword">delete</span> &amp; m_uiText; <a name="l00059"></a>00059 <span class="keywordflow">if</span> (m_puiTextIt != NULL) <a name="l00060"></a>00060 { <a name="l00061"></a>00061 <span class="keyword">delete</span> m_puiTextIt; <a name="l00062"></a>00062 m_puiTextIt = NULL; <a name="l00063"></a>00063 } <a name="l00064"></a>00064 <span class="keyword">delete</span> &amp; m_cliLessLine; <a name="l00065"></a>00065 } <a name="l00066"></a>00066 <a name="l00067"></a><a class="code" href="classLess.html#a5121f272be93d257c5a4ff1db4adb7c9">00067</a> <span class="keyword">const</span> <a class="code" href="classOutputDevice.html" title="Generic output device.">OutputDevice</a>&amp; <a class="code" href="classLess.html#a5121f272be93d257c5a4ff1db4adb7c9" title="Text member accessor.">Less::GetText</a>(<span class="keywordtype">void</span>) <a name="l00068"></a>00068 { <a name="l00069"></a>00069 <span class="keywordflow">return</span> m_uiText; <a name="l00070"></a>00070 } <a name="l00071"></a>00071 <a name="l00072"></a><a class="code" href="classLess.html#ac1f9bfd760f4a479452275d92527eb84">00072</a> <span class="keywordtype">void</span> <a class="code" href="classLess.html#ac1f9bfd760f4a479452275d92527eb84" title="Handler called when data reset is required.">Less::Reset</a>(<span class="keywordtype">void</span>) <a name="l00073"></a>00073 { <a name="l00074"></a>00074 <span class="comment">// Nothing to do.</span> <a name="l00075"></a>00075 } <a name="l00076"></a>00076 <a name="l00077"></a><a class="code" href="classLess.html#a4f678d44d3f876d14e5c59567a757d4c">00077</a> <span class="keywordtype">void</span> <a class="code" href="classLess.html#a4f678d44d3f876d14e5c59567a757d4c" title="Handler called when default value is required to be restored.">Less::ResetToDefault</a>(<span class="keywordtype">void</span>) <a name="l00078"></a>00078 { <a name="l00079"></a>00079 <span class="comment">// Very first display.</span> <a name="l00080"></a>00080 <span class="keywordflow">if</span> (m_puiTextIt == NULL) <a name="l00081"></a>00081 { <a name="l00082"></a>00082 <span class="keyword">const</span> <a class="code" href="classOutputDevice_1_1ScreenInfo.html" title="Screen information.">OutputDevice::ScreenInfo</a> cli_ScreenInfo = <a class="code" href="classExecutionContext.html#a6fd7a732424cb3fd253079bbf704ebef" title="Output stream accessor.">GetStream</a>(<a class="code" href="exec__context_8h.html#a831be33be460d85af138038078ebd646a457a2dc04a7f380b028fc706855aefb9" title="Output stream.">OUTPUT_STREAM</a>).<a class="code" href="classOutputDevice.html#a3cec03b49e12d20ee63f5ca9037f67da" title="Screen info accessor.">GetScreenInfo</a>(); <a name="l00083"></a>00083 m_puiTextIt = <span class="keyword">new</span> <a class="code" href="classTextIterator.html" title="Text iterator class.">TextIterator</a>(cli_ScreenInfo, cli_ScreenInfo.<a class="code" href="classOutputDevice_1_1ScreenInfo.html#a31321c0db2bb312bd6eb8d636e33074c" title="Safe screen height accessor.">GetSafeHeight</a>() - 1); <a name="l00084"></a>00084 } <a name="l00085"></a>00085 <a class="code" href="assert_8h.html#a1fe8f84b5d89ceccc07361b1d0da0144" title="CLI assertion macro.">CLI_ASSERT</a>(m_puiTextIt != NULL); <a name="l00086"></a>00086 <span class="keywordflow">if</span> (m_puiTextIt != NULL) { m_uiText.<a class="code" href="classText.html#a9be38a8d0dffa3b6d0a24951d495ff92" title="Retrieves a text head iterator.">Begin</a>(*m_puiTextIt); } <a name="l00087"></a>00087 PrintScreen(); <a name="l00088"></a>00088 } <a name="l00089"></a>00089 <a name="l00090"></a><a class="code" href="classLess.html#af2ab68a5c2b8a95df7d3504306242df3">00090</a> <span class="keywordtype">void</span> <a class="code" href="classLess.html#af2ab68a5c2b8a95df7d3504306242df3" title="Handler called on character input.">Less::OnKey</a>(<span class="keyword">const</span> <a class="code" href="io__device_8h.html#a90d295cf6b6bc9873c186cc8851147f8" title="Input characters.">KEY</a> E_KeyCode) <a name="l00091"></a>00091 { <a name="l00092"></a>00092 <span class="comment">// Ensure m_puiTextIt is valid.</span> <a name="l00093"></a>00093 <a class="code" href="assert_8h.html#a1fe8f84b5d89ceccc07361b1d0da0144" title="CLI assertion macro.">CLI_ASSERT</a>(m_puiTextIt != NULL); <a name="l00094"></a>00094 <span class="keywordflow">if</span> (m_puiTextIt == NULL) { Quit(); } <a name="l00095"></a>00095 <span class="keywordflow">else</span> { <a name="l00096"></a>00096 <span class="keywordflow">switch</span> (E_KeyCode) <a name="l00097"></a>00097 { <a name="l00098"></a>00098 <span class="keywordflow">case</span> <a class="code" href="io__device_8h.html#a87c1c1677bb8199c62a3de0ebc270471aeed3bac3a74a2eaf9a84d1a9774b67c1" title="Begin key.">KEY_BEGIN</a>: <a name="l00099"></a>00099 m_uiText.<a class="code" href="classText.html#a9be38a8d0dffa3b6d0a24951d495ff92" title="Retrieves a text head iterator.">Begin</a>(*m_puiTextIt); <a name="l00100"></a>00100 PrintScreen(); <a name="l00101"></a>00101 <span class="keywordflow">break</span>; <a name="l00102"></a>00102 <span class="keywordflow">case</span> <a class="code" href="io__device_8h.html#a87c1c1677bb8199c62a3de0ebc270471a0442824c041b9618cd7c512205e7e6dc" title="Page up arrow key.">PAGE_UP</a>: <a name="l00103"></a>00103 <span class="keywordflow">if</span> (m_uiText.<a class="code" href="classText.html#aa732716bbdbb588f6b5fcc2dc68dfe4b" title="Moves iterator one page up.">PageUp</a>(*m_puiTextIt)) PrintScreen(); <a name="l00104"></a>00104 <span class="keywordflow">else</span> <a class="code" href="classExecutionContext.html#a64ad190dcdb2bf789d5e45f454304f8e" title="Sends a beep signal.">Beep</a>(); <a name="l00105"></a>00105 <span class="keywordflow">break</span>; <a name="l00106"></a>00106 <span class="keywordflow">case</span> <a class="code" href="io__device_8h.html#a87c1c1677bb8199c62a3de0ebc270471a0848a442d907968b211b97bc2bd88acd" title="Up arrow key.">KEY_UP</a>: <a name="l00107"></a>00107 <span class="keywordflow">if</span> (m_uiText.<a class="code" href="classText.html#a951e603e2d602b06b99d81941485bfb3" title="Moves iterator one line up.">LineUp</a>(*m_puiTextIt)) PrintScreen(); <a name="l00108"></a>00108 <span class="keywordflow">else</span> <a class="code" href="classExecutionContext.html#a64ad190dcdb2bf789d5e45f454304f8e" title="Sends a beep signal.">Beep</a>(); <a name="l00109"></a>00109 <span class="keywordflow">break</span>; <a name="l00110"></a>00110 <span class="keywordflow">case</span> <a class="code" href="io__device_8h.html#a87c1c1677bb8199c62a3de0ebc270471aa9cdac7967bf7d88fdb761138a2a3416" title="Down arrow key.">KEY_DOWN</a>: <a name="l00111"></a>00111 <span class="keywordflow">case</span> <a class="code" href="io__device_8h.html#a87c1c1677bb8199c62a3de0ebc270471a951ab68bb8f7daafb78951107080904e" title="Enter.">ENTER</a>: <a name="l00112"></a>00112 <span class="keywordflow">if</span> (m_uiText.<a class="code" href="classText.html#a2291b26ba8bcf5d5e5cd38aa775a1b6e" title="Moves iterator one line down.">LineDown</a>(*m_puiTextIt, NULL)) PrintScreen(); <a name="l00113"></a>00113 <span class="keywordflow">else</span> <a class="code" href="classExecutionContext.html#a64ad190dcdb2bf789d5e45f454304f8e" title="Sends a beep signal.">Beep</a>(); <a name="l00114"></a>00114 <span class="keywordflow">break</span>; <a name="l00115"></a>00115 <span class="keywordflow">case</span> <a class="code" href="io__device_8h.html#a87c1c1677bb8199c62a3de0ebc270471a714c5d27586a8bcbab274d9176da1539" title="Page down arrow key.">PAGE_DOWN</a>: <a name="l00116"></a>00116 <span class="keywordflow">case</span> <a class="code" href="io__device_8h.html#a87c1c1677bb8199c62a3de0ebc270471ac08dae7edcb5c5bb959fee5971fbad95" title="Space.">SPACE</a>: <a name="l00117"></a>00117 <span class="keywordflow">if</span> (m_uiText.<a class="code" href="classText.html#ac3e99bde2b439d387e9e3b9bc7fc7ced" title="Moves iterator one page down.">PageDown</a>(*m_puiTextIt, NULL)) PrintScreen(); <a name="l00118"></a>00118 <span class="keywordflow">else</span> <a class="code" href="classExecutionContext.html#a64ad190dcdb2bf789d5e45f454304f8e" title="Sends a beep signal.">Beep</a>(); <a name="l00119"></a>00119 <span class="keywordflow">break</span>; <a name="l00120"></a>00120 <span class="keywordflow">case</span> <a class="code" href="io__device_8h.html#a87c1c1677bb8199c62a3de0ebc270471aa8adb6fcb92dec58fb19410eacfdd403" title="End key.">KEY_END</a>: <a name="l00121"></a>00121 m_uiText.<a class="code" href="classText.html#a42e1552521bb00b6bd39e47f5d354ebe" title="Retrieves a text end iterator.">End</a>(*m_puiTextIt, NULL); <a name="l00122"></a>00122 PrintScreen(); <a name="l00123"></a>00123 <span class="keywordflow">break</span>; <a name="l00124"></a>00124 <span class="keywordflow">case</span> KEY_q: <a name="l00125"></a>00125 <span class="keywordflow">case</span> KEY_Q: <a name="l00126"></a>00126 <span class="keywordflow">case</span> <a class="code" href="io__device_8h.html#a87c1c1677bb8199c62a3de0ebc270471a0a311695a4f6c56869245418bebeb33d" title="Escape.">ESCAPE</a>: <a name="l00127"></a>00127 <span class="keywordflow">case</span> <a class="code" href="io__device_8h.html#a87c1c1677bb8199c62a3de0ebc270471a9524d094809858b9e4f778763913568a" title="Break (Ctrl+C).">BREAK</a>: <a name="l00128"></a>00128 <span class="keywordflow">case</span> <a class="code" href="io__device_8h.html#a87c1c1677bb8199c62a3de0ebc270471a86d6ca369e69a3a0f0c9bd063dd39a70" title="Logout (Ctrl+D).">LOGOUT</a>: <a name="l00129"></a>00129 <span class="keywordflow">case</span> <a class="code" href="io__device_8h.html#a87c1c1677bb8199c62a3de0ebc270471ae42682039e1a584113718465a202d0c0" title="Null key.">NULL_KEY</a>: <a name="l00130"></a>00130 <span class="comment">// Stop display</span> <a name="l00131"></a>00131 Quit(); <a name="l00132"></a>00132 <span class="keywordflow">break</span>; <a name="l00133"></a>00133 <span class="keywordflow">default</span>: <a name="l00134"></a>00134 <span class="comment">// Non managed character: beep.</span> <a name="l00135"></a>00135 <a class="code" href="classExecutionContext.html#a64ad190dcdb2bf789d5e45f454304f8e" title="Sends a beep signal.">Beep</a>(); <a name="l00136"></a>00136 <span class="keywordflow">break</span>; <a name="l00137"></a>00137 } <a name="l00138"></a>00138 } <a name="l00139"></a>00139 } <a name="l00140"></a>00140 <a name="l00141"></a>00141 <span class="keywordtype">void</span> Less::PrintScreen(<span class="keywordtype">void</span>) <a name="l00142"></a>00142 { <a name="l00143"></a>00143 <span class="keyword">const</span> <a class="code" href="classOutputDevice_1_1ScreenInfo.html" title="Screen information.">OutputDevice::ScreenInfo</a> cli_ScreenInfo = <a class="code" href="classExecutionContext.html#a6fd7a732424cb3fd253079bbf704ebef" title="Output stream accessor.">GetStream</a>(<a class="code" href="exec__context_8h.html#a831be33be460d85af138038078ebd646a457a2dc04a7f380b028fc706855aefb9" title="Output stream.">OUTPUT_STREAM</a>).<a class="code" href="classOutputDevice.html#a3cec03b49e12d20ee63f5ca9037f67da" title="Screen info accessor.">GetScreenInfo</a>(); <a name="l00144"></a>00144 <a name="l00145"></a>00145 <span class="comment">// Then let current bottom position move one page down while printing the page.</span> <a name="l00146"></a>00146 <span class="keyword">const</span> <a class="code" href="classStringDevice.html" title="String device.">StringDevice</a> cli_Out(cli_ScreenInfo.<a class="code" href="classOutputDevice_1_1ScreenInfo.html#a31321c0db2bb312bd6eb8d636e33074c" title="Safe screen height accessor.">GetSafeHeight</a>() * (cli_ScreenInfo.<a class="code" href="classOutputDevice_1_1ScreenInfo.html#a892fccab401f2226d48cb03cbb455298" title="Safe screen width accessor.">GetSafeWidth</a>() + 1), <span class="keyword">false</span>); <a name="l00147"></a>00147 <a class="code" href="assert_8h.html#a1fe8f84b5d89ceccc07361b1d0da0144" title="CLI assertion macro.">CLI_ASSERT</a>(m_puiTextIt != NULL); <a name="l00148"></a>00148 <span class="keywordflow">if</span> (m_puiTextIt != NULL) { m_uiText.<a class="code" href="classText.html#ac2300f69bf52fa085a80faa2ea1d2da6" title="Print out a page of text.">PrintPage</a>(*m_puiTextIt, cli_Out, <span class="keyword">true</span>); } <a name="l00149"></a>00149 <a name="l00150"></a>00150 <span class="comment">// Eventually clean out the screen and print out the computed string.</span> <a name="l00151"></a>00151 m_cliLessLine.<a class="code" href="classCmdLineEdition.html#a55c26585a8b2ef1c7540dd26e4ab26f1" title="Reset the object.">Reset</a>(); <a name="l00152"></a>00152 <a class="code" href="classExecutionContext.html#a6fd7a732424cb3fd253079bbf704ebef" title="Output stream accessor.">GetStream</a>(<a class="code" href="exec__context_8h.html#a831be33be460d85af138038078ebd646a457a2dc04a7f380b028fc706855aefb9" title="Output stream.">OUTPUT_STREAM</a>).<a class="code" href="classOutputDevice.html#a04c4210231e603e0d398698885a9c5de" title="Clean screen.">CleanScreen</a>(); <a name="l00153"></a>00153 <a class="code" href="classExecutionContext.html#a6fd7a732424cb3fd253079bbf704ebef" title="Output stream accessor.">GetStream</a>(<a class="code" href="exec__context_8h.html#a831be33be460d85af138038078ebd646a457a2dc04a7f380b028fc706855aefb9" title="Output stream.">OUTPUT_STREAM</a>) &lt;&lt; cli_Out.GetString(); <a name="l00154"></a>00154 m_cliLessLine.<a class="code" href="classCmdLineEdition.html#a9e54ef76c3967253fd6f1a8296c38587" title="Character addition.">Put</a>(<a class="code" href="classExecutionContext.html#a6fd7a732424cb3fd253079bbf704ebef" title="Output stream accessor.">GetStream</a>(<a class="code" href="exec__context_8h.html#a831be33be460d85af138038078ebd646a457a2dc04a7f380b028fc706855aefb9" title="Output stream.">OUTPUT_STREAM</a>), tk::String(10, <span class="stringliteral">&quot;:&quot;</span>)); <a name="l00155"></a>00155 } <a name="l00156"></a>00156 <a name="l00157"></a>00157 <span class="keywordtype">void</span> Less::Quit(<span class="keywordtype">void</span>) <a name="l00158"></a>00158 { <a name="l00159"></a>00159 m_cliLessLine.<a class="code" href="classCmdLineEdition.html#a4fe03e4ed78c4e2c9d66518ffc1102f6" title="Line deletion.">CleanAll</a>(<a class="code" href="classExecutionContext.html#a6fd7a732424cb3fd253079bbf704ebef" title="Output stream accessor.">GetStream</a>(<a class="code" href="exec__context_8h.html#a831be33be460d85af138038078ebd646a457a2dc04a7f380b028fc706855aefb9" title="Output stream.">OUTPUT_STREAM</a>)); <a name="l00160"></a>00160 <a class="code" href="classUI.html#abc0b37fbbb9e25d4bc8849468d1b931d" title="Method to call by child classes in order to end the control execution.">EndControl</a>(<span class="keyword">true</span>); <a name="l00161"></a>00161 } <a name="l00162"></a>00162 <a name="l00163"></a>00163 <a class="code" href="namespace_8h.html#accc91ffc41bd59ab273a690a7b425450" title="End a namespace definition.">CLI_NS_END</a>(ui) <a name="l00164"></a>00164 <a name="l00165"></a>00165 <a class="code" href="namespace_8h.html#accc91ffc41bd59ab273a690a7b425450" title="End a namespace definition.">CLI_NS_END</a>(cli) <a name="l00166"></a>00166 </pre></div></div> </div> <hr class="footer"/><address class="footer"><small>Generated on Wed Jul 24 2013 08:23:24 for CLI by&nbsp; <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.7.1 </small></address> </body> </html>
kn65op/cli-toolkit
web/doxygen/html/ui__less_8cpp_source.html
HTML
bsd-3-clause
25,910
module Spree module Admin module BaseHelper def flash_alert flash if flash.present? message = flash[:error] || flash[:notice] || flash[:success] flash_class = "danger" if flash[:error] flash_class = "info" if flash[:notice] flash_class = "success" if flash[:success] flash_div = content_tag(:div, message, class: "alert alert-#{flash_class} alert-auto-disappear") content_tag(:div, flash_div, class: 'col-md-12') end end def field_container(model, method, options = {}, &block) css_classes = options[:class].to_a css_classes << 'field' if error_message_on(model, method).present? css_classes << 'withError' end content_tag(:div, capture(&block), class: css_classes.join(' '), id: "#{model}_#{method}_field") end def error_message_on(object, method, options = {}) object = convert_to_model(object) obj = object.respond_to?(:errors) ? object : instance_variable_get("@#{object}") if obj && obj.errors[method].present? errors = safe_join(obj.errors[method], '<br />'.html_safe) content_tag(:span, errors, class: 'formError') else '' end end def datepicker_field_value(date) unless date.blank? l(date, format: Spree.t('date_picker.format', default: '%Y/%m/%d')) else nil end end def preference_field_tag(name, value, options) case options[:type] when :integer text_field_tag(name, value, preference_field_options(options)) when :boolean hidden_field_tag(name, 0, id: "#{name}_hidden") + check_box_tag(name, 1, value, preference_field_options(options)) when :string text_field_tag(name, value, preference_field_options(options)) when :password password_field_tag(name, value, preference_field_options(options)) when :text text_area_tag(name, value, preference_field_options(options)) else text_field_tag(name, value, preference_field_options(options)) end end def preference_field_for(form, field, options) case options[:type] when :integer form.text_field(field, preference_field_options(options)) when :boolean form.check_box(field, preference_field_options(options)) when :string form.text_field(field, preference_field_options(options)) when :password form.password_field(field, preference_field_options(options)) when :text form.text_area(field, preference_field_options(options)) else form.text_field(field, preference_field_options(options)) end end def preference_field_options(options) field_options = case options[:type] when :integer { size: 10, class: 'input_integer form-control' } when :boolean {} when :string { size: 10, class: 'input_string form-control' } when :password { size: 10, class: 'password_string form-control' } when :text { rows: 15, cols: 85, class: 'form-control' } else { size: 10, class: 'input_string form-control' } end field_options.merge!({ readonly: options[:readonly], disabled: options[:disabled], size: options[:size] }) end def preference_fields(object, form) return unless object.respond_to?(:preferences) fields = object.preferences.keys.map { |key| if object.has_preference?(key) form.label("preferred_#{key}", Spree.t(key) + ": ") + preference_field_for(form, "preferred_#{key}", type: object.preference_type(key)) end } safe_join(fields, '<br />'.html_safe) end # renders hidden field and link to remove record using nested_attributes def link_to_icon_remove_fields(f) url = f.object.persisted? ? [:admin, f.object] : '#' link_to_with_icon('delete', '', url, class: "spree_remove_fields btn btn-sm btn-danger", data: {action: 'remove'}, title: Spree.t(:remove)) + f.hidden_field(:_destroy) end def spree_dom_id(record) dom_id(record, 'spree') end I18N_PLURAL_MANY_COUNT = 2.1 def plural_resource_name(resource_class) resource_class.model_name.human(count: I18N_PLURAL_MANY_COUNT) end def back_to_list_button(resource, path) button_text = Spree.t(:back_to_resource_list, resource: resource) link_to_with_icon 'arrow-left', button_text, path, class: 'btn btn-default' end private def attribute_name_for(field_name) field_name.gsub(' ', '_').downcase end end end end
orenf/spree
backend/app/helpers/spree/admin/base_helper.rb
Ruby
bsd-3-clause
5,101
# # plots.py -- does matplotlib plots needed for observation planning # # Eric Jeschke ([email protected]) # # Some code based on "Observer" module by Daniel Magee # Copyright (c) 2008 UCO/Lick Observatory. # from __future__ import print_function from datetime import datetime, timedelta import pytz import numpy from matplotlib import figure import matplotlib.dates as mpl_dt import matplotlib as mpl from obsplan import misc class AirMassPlot(object): def __init__(self, width, height, dpi=96): # time increments, by minute self.time_inc_min = 15 # create matplotlib figure self.fig = figure.Figure(figsize=(width, height), dpi=dpi) # colors used for successive points self.colors = ['r', 'b', 'g', 'c', 'm', 'y'] def setup(self): pass def get_figure(self): return self.fig def make_canvas(self): canvas = FigureCanvas(self.fig) return canvas ## def get_ax(self): ## return self.ax def clear(self): #self.ax.cla() self.fig.clf() def plot_targets(self, site, targets, tz): num_tgts = len(targets) target_data = [] lengths = [] if num_tgts > 0: for tgt in targets: info_list = site.get_target_info(tgt) target_data.append(misc.Bunch(history=info_list, target=tgt)) lengths.append(len(info_list)) # clip all arrays to same length # TODO: won't work if these become generators instead of lists min_len = min(*lengths) for info in target_data: info.history = info.history[:min_len] self.plot_airmass(site, target_data, tz) def plot_airmass(self, site, tgt_data, tz): self._plot_airmass(self.fig, site, tgt_data, tz) def _plot_airmass(self, figure, site, tgt_data, tz): """ Plot into `figure` an airmass chart using target data from `info` with time plotted in timezone `tz` (a tzinfo instance). """ # Urk! This seems to be necessary even though we are plotting # python datetime objects with timezone attached and setting # date formatters with the timezone tz_str = tz.tzname(None) mpl.rcParams['timezone'] = tz_str # set major ticks to hours majorTick = mpl_dt.HourLocator(tz=tz) majorFmt = mpl_dt.DateFormatter('%Hh') # set minor ticks to 15 min intervals minorTick = mpl_dt.MinuteLocator(range(0,59,15), tz=tz) figure.clf() ax1 = figure.add_subplot(111) #lstyle = 'o' lstyle = '-' lt_data = map(lambda info: info.ut.astimezone(tz), tgt_data[0].history) # sanity check on dates in preferred timezone ## for dt in lt_data[:10]: ## print(dt.strftime("%Y-%m-%d %H:%M:%S")) # plot targets airmass vs. time for i, info in enumerate(tgt_data): am_data = numpy.array(map(lambda info: info.airmass, info.history)) am_min = numpy.argmin(am_data) am_data_dots = am_data color = self.colors[i % len(self.colors)] lc = color + lstyle # ax1.plot_date(lt_data, am_data, lc, linewidth=1.0, alpha=0.3, aa=True, tz=tz) ax1.plot_date(lt_data, am_data_dots, lc, linewidth=2.0, aa=True, tz=tz) #xs, ys = mpl.mlab.poly_between(lt_data, 2.02, am_data) #ax1.fill(xs, ys, facecolor=self.colors[i], alpha=0.2) # plot object label targname = info.target.name ax1.text(mpl_dt.date2num(lt_data[am_data.argmin()]), am_data.min() + 0.08, targname.upper(), color=color, ha='center', va='center') ax1.set_ylim(2.02, 0.98) ax1.set_xlim(lt_data[0], lt_data[-1]) ax1.xaxis.set_major_locator(majorTick) ax1.xaxis.set_minor_locator(minorTick) ax1.xaxis.set_major_formatter(majorFmt) labels = ax1.get_xticklabels() ax1.grid(True, color='#999999') # plot current hour lo = datetime.now(tz) #lo = datetime.now(tz=tz) hi = lo + timedelta(0, 3600.0) if lt_data[0] < lo < lt_data[-1]: ax1.axvspan(lo, hi, facecolor='#7FFFD4', alpha=0.25) # label axes localdate = lt_data[0].astimezone(tz).strftime("%Y-%m-%d") title = 'Airmass for the night of %s' % (localdate) ax1.set_title(title) ax1.set_xlabel(tz.tzname(None)) ax1.set_ylabel('Airmass') # Plot moon altitude and degree scale ax2 = ax1.twinx() moon_data = numpy.array(map(lambda info: numpy.degrees(info.moon_alt), tgt_data[0].history)) #moon_illum = site.moon_phase() ax2.plot_date(lt_data, moon_data, '#666666', linewidth=2.0, alpha=0.5, aa=True, tz=tz) mxs, mys = mpl.mlab.poly_between(lt_data, 0, moon_data) # ax2.fill(mxs, mys, facecolor='#666666', alpha=moon_illum) ax2.set_ylabel('Moon Altitude (deg)', color='#666666') ax2.set_ylim(0, 90) ax2.set_xlim(lt_data[0], lt_data[-1]) ax2.xaxis.set_major_locator(majorTick) ax2.xaxis.set_minor_locator(minorTick) ax2.xaxis.set_major_formatter(majorFmt) ax2.set_xlabel('') ax2.yaxis.tick_right() canvas = self.fig.canvas if canvas is not None: canvas.draw() if __name__ == '__main__': import sys from obsplan import entity from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas from PyQt4 import QtGui app = QtGui.QApplication([]) plot = AirMassPlot(10, 6) plot.setup() outfile = None if len(sys.argv) > 1: outfile = sys.argv[1] tz = pytz.timezone('US/Hawaii') site = entity.Observer('subaru', longitude='-155:28:48.900', latitude='+19:49:42.600', elevation=4163, pressure=615, temperature=0, timezone='US/Hawaii') start_time = datetime.strptime("2015-03-30 18:30:00", "%Y-%m-%d %H:%M:%S") start_time = tz.localize(start_time) t = start_time # if schedule starts after midnight, change start date to the # day before if 0 <= t.hour < 12: t -= timedelta(0, 3600*12) ndate = t.strftime("%Y/%m/%d") targets = [] site.set_date(t) tgt = entity.StaticTarget(name='S5', ra='14:20:00.00', dec='48:00:00.00') targets.append(tgt) tgt = entity.StaticTarget(name='Sf', ra='09:40:00.00', dec='43:00:00.00') targets.append(tgt) tgt = entity.StaticTarget(name='Sm', ra='10:30:00.00', dec='36:00:00.00') targets.append(tgt) tgt = entity.StaticTarget(name='Sn', ra='15:10:00.00', dec='34:00:00.00') targets.append(tgt) # make airmass plot plot.plot_targets(site, targets, tz) if outfile == None: canvas = plot.make_canvas() canvas.show() else: canvas = plot.make_canvas() # is this necessary? self.fig.savefig(outfile) app.exec_() #END
ejeschke/obsplan
obsplan/plots/airmass.py
Python
bsd-3-clause
7,316
<?php /** * @license © 2005 - 2016 by Zend Technologies Ltd. All rights reserved. */ namespace Admin\Controller; use Base\Controller\AbstractController; use Interop\Container\ContainerInterface; use Admin\Form\TraductionFilter; use Admin\Form\TraductionForm; use Admin\Model\Traduction\Traduction; use Admin\Model\Traduction\TraductionRepository; /** * SIGA-Smart * * Esta class foi gerada via Zend\Code\Generator. */ class TraductionController extends AbstractController { /** * __construct Factory Model * * @param ContainerInterface $containerInterface * @return \Admin\Controller\TraductionController */ public function __construct(ContainerInterface $containerInterface) { // Configurações iniciais do Controller $this->containerInterface=$containerInterface; $this->table=TraductionRepository::class; $this->model=Traduction::class; $this->form=TraductionForm::class; $this->filter=TraductionFilter::class; $this->route="admin"; $this->controller="traduction"; $this->colunas=1; } }
callcocam/siga
module/Admin/src/Controller/TraductionController.php
PHP
bsd-3-clause
1,117
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <?php foreach ($css as $style): echo html::style($style); endforeach; ?> <script type="text/javascript"> path = "<?php echo url::base(); ?>"; </script> <link rel="icon" href="<?php echo url::base(); ?>/assets/favicon.ico" type="image/x-icon" /> <link rel="shortcut icon" href="<?php echo url::base(); ?>/assets/favicon.ico" type="image/x-icon" /> <title>Modular Gaming - <?php echo $title; ?></title> </head> <body> <div class="header"> <?php echo html::anchor('', 'ModularGaming', array('class' => 'logo')); ?> <ul class="nav"> <?php if ( $user ) { echo '<li class="first">' . html::anchor( 'dashboard', 'Dashboard' ) . '</li>'; echo '<li>' . html::anchor( 'inventory', 'Inventory' ) . '</li>'; echo '<li>' . html::anchor( 'forum', 'Forum' ) . '</li>'; echo '<li>' . html::anchor( 'message', 'Messages' ) . '</li>'; echo '<li>' . html::anchor( 'account', 'Settings' ) . '</li>'; echo '<li class="last">' . html::anchor( 'account/logout', 'Logout' ) . '</li>'; } else { echo '<li class="first">' . html::anchor( '', 'Home' ) . '</li>'; echo '<li class="login">' . html::anchor( 'account/login', 'Login' ) . '</li>'; echo '<li class="last">' . html::anchor( 'account/register', 'Register' ) . '</li>'; } ?> </ul> </div> <div class="content"> <?php echo $content; ?> </div> <div class="footer"> <div class="wrapper"> <p class="copyright">&copy; 2010 the Modular Gaming Team.</p> </div> </div> <div id="login-dialog" title="Login" class="hidden"> <ul class="errors"></ul> <form> <fieldset class="small"> <dl> <dt><?php echo form::label('username', 'Username:'); ?></dt> <dd><?php echo form::input('username'); ?></dd> </dl> <dl> <dt><?php echo form::label('password', 'Password:'); ?></dt> <dd> <?php echo form::password('password'); ?> </dd> </dl> <dl> <dt>&nbsp;</dt> <dd><?php echo form::label('remember', form::checkbox('remember').'Remember me'); ?></dd> </dl> </fieldset> </form> </div> <?php if(Kohana::$environment == Kohana::DEVELOPMENT) echo View::factory('profiler/stats'); ?> <?php foreach ($js['files'] as $script): echo html::script($script); endforeach; foreach ($js['scripts'] as $script): echo '<script type="text/javascript">'.$script.'</script>'; endforeach; ?> </body> </html>
modulargaming/kohana-3.0
modules/modulargaming/views/template/old.php
PHP
bsd-3-clause
2,599
import React from 'react'; import Relay from 'react-relay'; class GuideTab extends React.Component { render() { return ( <div> Guide </div> ); } } export default GuideTab;
Ricky-Nz/gear-website
websrc/components/GuideTab.js
JavaScript
bsd-3-clause
189
from __future__ import unicode_literals from django.core.files import File from django.conf import settings from django.contrib.auth.models import User from PIL import Image, ImageDraw from example.models import Image as TestImage TEST_USERNAME = 'admin' TEST_PASSWORD = 'admin' TEST_EMAIL = '[email protected]' def create_cropped_image(**kwargs): defaults = { 'image_cropping': '50,50,170,100', # size: 120x100 as in model.py 'image_path': '%s%s' % (settings.STATIC_ROOT, "/images/example_image.jpg"), 'image_name': 'example_image', } defaults.update(kwargs) image = TestImage.objects.create( **{'cropping': defaults['image_cropping']} ) image.image_field.save( defaults['image_name'], File(open(defaults['image_path'], 'rb'))) return image def create_pil_image(size=(400, 400)): image = Image.new('RGB', size, (255, 255, 255)) draw = ImageDraw.Draw(image) draw.rectangle(((20, 20), (200, 200)), fill="red", outline="black") draw.rectangle(((220, 220), (390, 390)), fill="green", outline="black") draw.ellipse((100, 100, 310, 310), fill="yellow", outline="black") return image def create_superuser(**kwargs): defaults = { 'password': TEST_PASSWORD, 'username': TEST_USERNAME, 'email': TEST_EMAIL, } defaults.update(kwargs) return User.objects.create_superuser(**defaults)
winzard/django-image-cropping
example/tests/factory.py
Python
bsd-3-clause
1,423
using Toggl.Core.Models; using Toggl.Core.UI.Interfaces; using Toggl.Core.UI.Models; namespace Toggl.Core.UI.ViewModels.DateRangePicker { public sealed partial class DateRangePickerViewModel { public struct Shortcut : IDiffableByIdentifier<Shortcut> { public static Shortcut From(DateRangeShortcut shortcut, bool isSelected) => new Shortcut(shortcut.Period, shortcut.Text, isSelected); private Shortcut(DateRangePeriod period, string text, bool isSelected) { DateRangePeriod = period; Text = text; IsSelected = isSelected; } public string Text { get; } public DateRangePeriod DateRangePeriod { get; } public bool IsSelected { get; } public long Identifier => (long)DateRangePeriod; public bool Equals(Shortcut other) => other.DateRangePeriod == DateRangePeriod && other.IsSelected == IsSelected; } } }
toggl/mobileapp
Toggl.Core.UI/ViewModels/DateRangePicker/DateRangePickerViewModel.Shortcuts.cs
C#
bsd-3-clause
1,066
-- | -- Module : $Header$ -- Copyright : (c) 2013-2014 Galois, Inc. -- License : BSD3 -- Maintainer : [email protected] -- Stability : provisional -- Portability : portable {-# LANGUAGE RecordWildCards, CPP, Safe #-} #if __GLASGOW_HASKELL__ >= 706 {-# LANGUAGE RecursiveDo #-} #else {-# LANGUAGE DoRec #-} #endif module Cryptol.TypeCheck.Monad ( module Cryptol.TypeCheck.Monad , module Cryptol.TypeCheck.InferTypes ) where import Cryptol.Parser.Position import qualified Cryptol.Parser.AST as P import Cryptol.TypeCheck.AST import Cryptol.TypeCheck.Subst import Cryptol.TypeCheck.Unify(mgu, Result(..), UnificationError(..)) import Cryptol.TypeCheck.InferTypes import Cryptol.Utils.PP(pp, (<+>), Doc, text, quotes) import Cryptol.Utils.Panic(panic) import qualified Data.Map as Map import qualified Data.Set as Set import Data.Map (Map) import Data.Set (Set) import Data.List(find) import Data.Maybe(mapMaybe) import MonadLib import Control.Monad.Fix(MonadFix(..)) import Data.Functor -- | Information needed for type inference. data InferInput = InferInput { inpRange :: Range -- ^ Location of program source , inpVars :: Map QName Schema -- ^ Variables that are in scope , inpTSyns :: Map QName TySyn -- ^ Type synonyms that are in scope , inpNewtypes :: Map QName Newtype -- ^ Newtypes in scope , inpNameSeeds :: NameSeeds -- ^ Private state of type-checker } deriving Show -- | This is used for generating various names. data NameSeeds = NameSeeds { seedTVar :: !Int , seedGoal :: !Int } deriving Show -- | The initial seeds, used when checking a fresh program. nameSeeds :: NameSeeds nameSeeds = NameSeeds { seedTVar = 10, seedGoal = 0 } -- | The results of type inference. data InferOutput a = InferFailed [(Range,Warning)] [(Range,Error)] -- ^ We found some errors | InferOK [(Range,Warning)] NameSeeds a -- ^ Type inference was successful. deriving Show runInferM :: TVars a => InferInput -> InferM a -> IO (InferOutput a) runInferM info (IM m) = do rec ro <- return RO { iRange = inpRange info , iVars = Map.map ExtVar (inpVars info) , iTVars = [] , iTSyns = fmap mkExternal (inpTSyns info) , iNewtypes = fmap mkExternal (inpNewtypes info) , iSolvedHasLazy = iSolvedHas finalRW -- RECURSION } (result, finalRW) <- runStateT rw $ runReaderT ro m -- RECURSION let theSu = iSubst finalRW defSu = defaultingSubst theSu warns = [(r,apSubst theSu w) | (r,w) <- iWarnings finalRW ] case iErrors finalRW of [] -> case (iCts finalRW, iHasCts finalRW) of ([],[]) -> return $ InferOK warns (iNameSeeds finalRW) (apSubst defSu result) (cts,has) -> return $ InferFailed warns [ ( goalRange g , UnsolvedGoal (apSubst theSu g) ) | g <- cts ++ map hasGoal has ] errs -> return $ InferFailed warns [(r,apSubst theSu e) | (r,e) <- errs] where mkExternal x = (IsExternal, x) rw = RW { iErrors = [] , iWarnings = [] , iSubst = emptySubst , iExistTVars = [] , iNameSeeds = inpNameSeeds info , iCts = [] , iHasCts = [] , iSolvedHas = Map.empty } newtype InferM a = IM { unIM :: ReaderT RO (StateT RW IO) a } data DefLoc = IsLocal | IsExternal -- | Read-only component of the monad. data RO = RO { iRange :: Range -- ^ Source code being analysed , iVars :: Map QName VarType -- ^ Type of variable that are in scope {- NOTE: We assume no shadowing between these two, so it does not matter where we look first. Similarly, we assume no shadowing with the existential type variable (in RW). See `checkTShadowing`. -} , iTVars :: [TParam] -- ^ Type variable that are in scope , iTSyns :: Map QName (DefLoc, TySyn) -- ^ Type synonyms that are in scope , iNewtypes :: Map QName (DefLoc, Newtype) -- ^ Newtype delcarations in scope -- -- NOTE: type synonyms take precedence over newtype. The reason is -- that we can define local type synonyms, but not local newtypes. -- So, either a type-synonym shadows a newtype, or it was declared -- at the top-level, but then there can't be a newtype with the -- same name (this should be caught by the renamer). , iSolvedHasLazy :: Map Int (Expr -> Expr) -- ^ NOTE: This field is lazy in an important way! It is the -- final version of `iSolvedHas` in `RW`, and the two are tied -- together through recursion. The field is here so that we can -- look thing up before they are defined, which is OK because we -- don't need to know the results until everything is done. } -- | Read-write component of the monad. data RW = RW { iErrors :: ![(Range,Error)] -- ^ Collected errors , iWarnings :: ![(Range,Warning)] -- ^ Collected warnings , iSubst :: !Subst -- ^ Accumulated substitution , iExistTVars :: [Map QName Type] -- ^ These keeps track of what existential type variables are available. -- When we start checking a function, we push a new scope for -- its arguments, and we pop it when we are done checking the function -- body. The front element of the list is the current scope, which is -- the only thing that will be modified, as follows. When we encounter -- a existential type variable: -- 1. we look in all scopes to see if it is already defined. -- 2. if it was not defined, we create a fresh type variable, -- and we add it to the current scope. -- 3. it is an error if we encoutner an existential variable but we -- have no current scope. , iSolvedHas :: Map Int (Expr -> Expr) -- ^ Selector constraints that have been solved (ref. iSolvedSelectorsLazy) -- Generating names , iNameSeeds :: !NameSeeds -- Constraints that need solving , iCts :: ![Goal] -- ^ Ordinary constraints , iHasCts :: ![HasGoal] {- ^ Tuple/record projection constraints. The `Int` is the "name" of the constraint, used so that we can name it solution properly. -} } instance Functor InferM where fmap f (IM m) = IM (fmap f m) instance Monad InferM where return x = IM (return x) fail x = IM (fail x) IM m >>= f = IM (m >>= unIM . f) instance MonadFix InferM where mfix f = IM (mfix (unIM . f)) io :: IO a -> InferM a io m = IM $ inBase m -- | The monadic computation is about the given range of source code. -- This is useful for error reporting. inRange :: Range -> InferM a -> InferM a inRange r (IM m) = IM $ mapReader (\ro -> ro { iRange = r }) m inRangeMb :: Maybe Range -> InferM a -> InferM a inRangeMb Nothing m = m inRangeMb (Just r) m = inRange r m -- | This is the current range that we are working on. curRange :: InferM Range curRange = IM $ asks iRange -- | Report an error. recordError :: Error -> InferM () recordError e = do r <- curRange IM $ sets_ $ \s -> s { iErrors = (r,e) : iErrors s } recordWarning :: Warning -> InferM () recordWarning w = do r <- curRange IM $ sets_ $ \s -> s { iWarnings = (r,w) : iWarnings s } -------------------------------------------------------------------------------- newGoal :: ConstraintSource -> Prop -> InferM Goal newGoal goalSource goal = do goalRange <- curRange return Goal { .. } -- | Record some constraints that need to be solved. -- The string explains where the constraints came from. newGoals :: ConstraintSource -> [Prop] -> InferM () newGoals src ps = addGoals =<< mapM (newGoal src) ps {- | The constraints are removed, and returned to the caller. The substitution IS applied to them. -} getGoals :: InferM [Goal] getGoals = applySubst =<< IM (sets $ \s -> (iCts s, s { iCts = [] })) -- | Add a bunch of goals that need solving. addGoals :: [Goal] -> InferM () addGoals gs = IM $ sets_ $ \s -> s { iCts = gs ++ iCts s } -- | Collect the goals emitted by the given sub-computation. -- Does not emit any new goals. collectGoals :: InferM a -> InferM (a, [Goal]) collectGoals m = do origGs <- getGoals a <- m newGs <- getGoals addGoals origGs return (a, newGs) {- | Record a constraint that when we select from the first type, we should get a value of the second type. The returned function should be used to wrap the expression from which we are selecting (i.e., the record or tuple). Plese note that the resulting expression should not be forced before the constraint is solved. -} newHasGoal :: P.Selector -> Type -> Type -> InferM (Expr -> Expr) newHasGoal l ty f = do goalName <- newGoalName g <- newGoal CtSelector (pHas l ty f) IM $ sets_ $ \s -> s { iHasCts = HasGoal goalName g : iHasCts s } solns <- IM $ fmap iSolvedHasLazy ask return $ case Map.lookup goalName solns of Just e1 -> e1 Nothing -> panic "newHasGoal" ["Unsolved has goal in result"] -- | Add a previously generate has constrained addHasGoal :: HasGoal -> InferM () addHasGoal g = IM $ sets_ $ \s -> s { iHasCts = g : iHasCts s } -- | Get the `Has` constraints. Each of this should either be solved, -- or added back using `addHasGoal`. getHasGoals :: InferM [HasGoal] getHasGoals = do gs <- IM $ sets $ \s -> (iHasCts s, s { iHasCts = [] }) applySubst gs -- | Specify the solution (`Expr -> Expr`) for the given constraitn (`Int`). solveHasGoal :: Int -> (Expr -> Expr) -> InferM () solveHasGoal n e = IM $ sets_ $ \s -> s { iSolvedHas = Map.insert n e (iSolvedHas s) } -------------------------------------------------------------------------------- newName :: (NameSeeds -> (a , NameSeeds)) -> InferM a newName upd = IM $ sets $ \s -> let (x,seeds) = upd (iNameSeeds s) in (x, s { iNameSeeds = seeds }) -- | Generate a new name for a goal. newGoalName :: InferM Int newGoalName = newName $ \s -> let x = seedGoal s in (x, s { seedGoal = x + 1}) -- | Generate a new free type variable. newTVar :: Doc -> Kind -> InferM TVar newTVar src k = do bound <- getBoundInScope newName $ \s -> let x = seedTVar s in (TVFree x k bound src, s { seedTVar = x + 1 }) -- | Generate a new free type variable. newTParam :: Maybe QName -> Kind -> InferM TParam newTParam nm k = newName $ \s -> let x = seedTVar s in (TParam { tpUnique = x , tpKind = k , tpName = nm } , s { seedTVar = x + 1 }) -- | Generate an unknown type. The doc is a note about what is this type about. newType :: Doc -> Kind -> InferM Type newType src k = TVar `fmap` newTVar src k -------------------------------------------------------------------------------- -- | Record that the two types should be syntactically equal. unify :: Type -> Type -> InferM [Prop] unify t1 t2 = do t1' <- applySubst t1 t2' <- applySubst t2 case mgu t1' t2' of OK (su1,ps) -> extendSubst su1 >> return ps Error err -> do case err of UniTypeLenMismatch _ _ -> recordError (TypeMismatch t1' t2') UniTypeMismatch s1 s2 -> recordError (TypeMismatch s1 s2) UniKindMismatch k1 k2 -> recordError (KindMismatch k1 k2) UniRecursive x t -> recordError (RecursiveType (TVar x) t) UniNonPolyDepends x vs -> recordError (TypeVariableEscaped (TVar x) vs) UniNonPoly x t -> recordError (NotForAll x t) return [] -- | Apply the accumulated substitution to something with free type variables. applySubst :: TVars t => t -> InferM t applySubst t = do su <- getSubst return (apSubst su t) -- | Get the substitution that we have accumulated so far. getSubst :: InferM Subst getSubst = IM $ fmap iSubst get -- | Add to the accumulated substitution. extendSubst :: Subst -> InferM () extendSubst su = IM $ sets_ $ \s -> s { iSubst = su @@ iSubst s } -- | Variables that are either mentioned in the environment or in -- a selector constraint. varsWithAsmps :: InferM (Set TVar) varsWithAsmps = do env <- IM $ fmap (Map.elems . iVars) ask fromEnv <- forM env $ \v -> case v of ExtVar sch -> getVars sch CurSCC _ t -> getVars t sels <- IM $ fmap (map (goal . hasGoal) . iHasCts) get fromSels <- mapM getVars sels fromEx <- (getVars . concatMap Map.elems) =<< IM (fmap iExistTVars get) return (Set.unions fromEnv `Set.union` Set.unions fromSels `Set.union` fromEx) where getVars x = fvs `fmap` applySubst x -------------------------------------------------------------------------------- -- | Lookup the type of a variable. lookupVar :: QName -> InferM VarType lookupVar x = do mb <- IM $ asks $ Map.lookup x . iVars case mb of Just t -> return t Nothing -> do mbNT <- lookupNewtype x case mbNT of Just nt -> return (ExtVar (newtypeConType nt)) Nothing -> do recordError $ UndefinedVariable x a <- newType (text "type of" <+> pp x) KType return $ ExtVar $ Forall [] [] a -- | Lookup a type variable. Return `Nothing` if there is no such variable -- in scope, in schich case we must be dealing with a type constant. lookupTVar :: QName -> InferM (Maybe Type) lookupTVar x = IM $ asks $ fmap (TVar . tpVar) . find this . iTVars where this tp = tpName tp == Just x -- | Lookup the definition of a type synonym. lookupTSyn :: QName -> InferM (Maybe TySyn) lookupTSyn x = fmap (fmap snd . Map.lookup x) getTSyns -- | Lookup the definition of a newtype lookupNewtype :: QName -> InferM (Maybe Newtype) lookupNewtype x = fmap (fmap snd . Map.lookup x) getNewtypes -- | Check if we already have a name for this existential type variable and, -- if so, return the definition. If not, try to create a new definition, -- if this is allowed. If not, returns nothing. existVar :: QName -> Kind -> InferM Type existVar x k = do scopes <- iExistTVars <$> IM get case msum (map (Map.lookup x) scopes) of Just ty -> return ty Nothing -> case scopes of [] -> do recordError $ ErrorMsg $ text "Undefined type" <+> quotes (pp x) newType (text "undefined existential type varible" <+> quotes (pp x)) k sc : more -> do ty <- newType (text "existential type variable" <+> quotes (pp x)) k IM $ sets_ $ \s -> s{ iExistTVars = Map.insert x ty sc : more } return ty -- | Returns the type synonyms that are currently in scope. getTSyns :: InferM (Map QName (DefLoc,TySyn)) getTSyns = IM $ asks iTSyns -- | Returns the newtype declarations that are in scope. getNewtypes :: InferM (Map QName (DefLoc,Newtype)) getNewtypes = IM $ asks iNewtypes -- | Get the ste of bound type variable that are in scope. getTVars :: InferM (Set QName) getTVars = IM $ asks $ Set.fromList . mapMaybe tpName . iTVars -- | Return the keys of the bound variablese that are in scope. getBoundInScope :: InferM (Set TVar) getBoundInScope = IM $ asks $ Set.fromList . map tpVar . iTVars {- | We disallow shadowing between type synonyms and type variables because it is confusing. As a bonus, in the implementaiton we don't need to worry about where we lookup things (i.e., in the variable or type synonym environmnet. -} checkTShadowing :: String -> QName -> InferM () checkTShadowing this new = do ro <- IM ask rw <- IM get let shadowed = do _ <- Map.lookup new (iTSyns ro) return "type synonym" `mplus` do guard (new `elem` mapMaybe tpName (iTVars ro)) return "type variable" `mplus` do _ <- msum (map (Map.lookup new) (iExistTVars rw)) return "type" case shadowed of Nothing -> return () Just that -> recordError $ ErrorMsg $ text "Type" <+> text this <+> quotes (pp new) <+> text "shadows an existing" <+> text that <+> text "with the same name." -- | The sub-computation is performed with the given type parameter in scope. withTParam :: TParam -> InferM a -> InferM a withTParam p (IM m) = do case tpName p of Just x -> checkTShadowing "variable" x Nothing -> return () IM $ mapReader (\r -> r { iTVars = p : iTVars r }) m withTParams :: [TParam] -> InferM a -> InferM a withTParams ps m = foldr withTParam m ps -- | The sub-computation is performed with the given type-synonym in scope. withTySyn :: TySyn -> InferM a -> InferM a withTySyn t (IM m) = do let x = tsName t checkTShadowing "synonym" x IM $ mapReader (\r -> r { iTSyns = Map.insert x (IsLocal,t) (iTSyns r) }) m withNewtype :: Newtype -> InferM a -> InferM a withNewtype t (IM m) = IM $ mapReader (\r -> r { iNewtypes = Map.insert (ntName t) (IsLocal,t) (iNewtypes r) }) m -- | The sub-computation is performed with the given variable in scope. withVarType :: QName -> VarType -> InferM a -> InferM a withVarType x s (IM m) = IM $ mapReader (\r -> r { iVars = Map.insert x s (iVars r) }) m withVarTypes :: [(QName,VarType)] -> InferM a -> InferM a withVarTypes xs m = foldr (uncurry withVarType) m xs withVar :: QName -> Schema -> InferM a -> InferM a withVar x s = withVarType x (ExtVar s) -- | The sub-computation is performed with the given variables in scope. withMonoType :: (QName,Located Type) -> InferM a -> InferM a withMonoType (x,lt) = withVar x (Forall [] [] (thing lt)) -- | The sub-computation is performed with the given variables in scope. withMonoTypes :: Map QName (Located Type) -> InferM a -> InferM a withMonoTypes xs m = foldr withMonoType m (Map.toList xs) -- | The sub-computation is performed with the given type synonyms -- and variables in scope. withDecls :: ([TySyn], Map QName Schema) -> InferM a -> InferM a withDecls (ts,vs) m = foldr withTySyn (foldr add m (Map.toList vs)) ts where add (x,t) = withVar x t -- | Perform the given computation in a new scope (i.e., the subcomputation -- may use existential type variables). inNewScope :: InferM a -> InferM a inNewScope m = do curScopes <- iExistTVars <$> IM get IM $ sets_ $ \s -> s { iExistTVars = Map.empty : curScopes } a <- m IM $ sets_ $ \s -> s { iExistTVars = curScopes } return a -------------------------------------------------------------------------------- -- Kind checking newtype KindM a = KM { unKM :: ReaderT KRO (StateT KRW InferM) a } data KRO = KRO { lazyTVars :: Map QName Type -- ^ lazy map, with tyvars. , allowWild :: Bool -- ^ are type-wild cards allowed? } data KRW = KRW { typeParams :: Map QName Kind -- ^ kinds of (known) vars. } instance Functor KindM where fmap f (KM m) = KM (fmap f m) instance Monad KindM where return x = KM (return x) fail x = KM (fail x) KM m >>= k = KM (m >>= unKM . k) {- | The arguments to this function are as follows: (type param. name, kind signature (opt.), a type representing the param) The type representing the parameter is just a thunk that we should not force. The reason is that the type depnds on the kind of parameter, that we are in the process of computing. As a result we return the value of the sub-computation and the computed kinds of the type parameters. -} runKindM :: Bool -- Are type-wild cards allowed? -> [(QName, Maybe Kind, Type)] -- ^ See comment -> KindM a -> InferM (a, Map QName Kind) runKindM wildOK vs (KM m) = do (a,kw) <- runStateT krw (runReaderT kro m) return (a, typeParams kw) where tys = Map.fromList [ (x,t) | (x,_,t) <- vs ] kro = KRO { allowWild = wildOK, lazyTVars = tys } krw = KRW { typeParams = Map.fromList [ (x,k) | (x,Just k,_) <- vs ] } -- | This is waht's returned when we lookup variables during kind checking. data LkpTyVar = TLocalVar Type (Maybe Kind) -- ^ Locally bound variable. | TOuterVar Type -- ^ An outer binding. -- | Check if a name refers to a type variable. kLookupTyVar :: QName -> KindM (Maybe LkpTyVar) kLookupTyVar x = KM $ do vs <- lazyTVars `fmap` ask ss <- get case Map.lookup x vs of Just t -> return $ Just $ TLocalVar t $ Map.lookup x $ typeParams ss Nothing -> lift $ lift $ do t <- lookupTVar x return (fmap TOuterVar t) -- | Are type wild-cards OK in this context? kWildOK :: KindM Bool kWildOK = KM $ fmap allowWild ask -- | Reports an error. kRecordError :: Error -> KindM () kRecordError e = kInInferM $ recordError e kRecordWarning :: Warning -> KindM () kRecordWarning w = kInInferM $ recordWarning w -- | Generate a fresh unification variable of the given kind. kNewType :: Doc -> Kind -> KindM Type kNewType src k = kInInferM $ newType src k -- | Lookup the definition of a type synonym. kLookupTSyn :: QName -> KindM (Maybe TySyn) kLookupTSyn x = kInInferM $ lookupTSyn x -- | Lookup the definition of a newtype. kLookupNewtype :: QName -> KindM (Maybe Newtype) kLookupNewtype x = kInInferM $ lookupNewtype x kExistTVar :: QName -> Kind -> KindM Type kExistTVar x k = kInInferM $ existVar x k -- | Replace the given bound variables with concrete types. kInstantiateT :: Type -> [(TParam,Type)] -> KindM Type kInstantiateT t as = return (apSubst su t) where su = listSubst [ (tpVar x, t1) | (x,t1) <- as ] {- | Record the kind for a local type variable. This assumes that we already checked that there was no other valid kind for the variable (if there was one, it gets over-written). -} kSetKind :: QName -> Kind -> KindM () kSetKind v k = KM $ sets_ $ \s -> s{ typeParams = Map.insert v k (typeParams s)} -- | The sub-computation is about the given range of the source code. kInRange :: Range -> KindM a -> KindM a kInRange r (KM m) = KM $ do e <- ask s <- get (a,s1) <- lift $ lift $ inRange r $ runStateT s $ runReaderT e m set s1 return a kNewGoals :: ConstraintSource -> [Prop] -> KindM () kNewGoals c ps = kInInferM $ newGoals c ps kInInferM :: InferM a -> KindM a kInInferM m = KM $ lift $ lift m
dylanmc/cryptol
src/Cryptol/TypeCheck/Monad.hs
Haskell
bsd-3-clause
23,200
#ifndef LH_OS_TYPES_H #define LH_OS_TYPES_H #include <string> #include <cstdint> namespace litehtml { #if defined( WIN32 ) || defined( _WIN32 ) || defined( WINCE ) // noexcept appeared since Visual Studio 2013 #if defined(_MSC_VER) && _MSC_VER < 1900 #define noexcept #endif #ifndef LITEHTML_UTF8 typedef std::wstring tstring; typedef wchar_t tchar_t; typedef std::wstringstream tstringstream; #define _t(quote) L##quote #define t_strlen wcslen #define t_strcmp wcscmp #define t_strncmp wcsncmp #define t_strtol wcstol #define t_atoi _wtoi #define t_itoa(value, buffer, size, radix) _itow_s(value, buffer, size, radix) #define t_strstr wcsstr #define t_isspace iswspace #define t_to_string(val) std::to_wstring(val) #else typedef std::string tstring; typedef char tchar_t; typedef std::stringstream tstringstream; #define _t(quote) quote #define t_strlen strlen #define t_strcmp strcmp #define t_strncmp strncmp #define t_strtol strtol #define t_atoi atoi #define t_itoa(value, buffer, size, radix) _itoa_s(value, buffer, size, radix) #define t_strstr strstr #define t_isspace isspace #define t_to_string(val) std::to_string(val) #endif #ifdef _WIN64 typedef unsigned __int64 uint_ptr; #else typedef unsigned int uint_ptr; #endif #else #define LITEHTML_UTF8 typedef std::string tstring; typedef char tchar_t; typedef std::uintptr_t uint_ptr; typedef std::stringstream tstringstream; #define _t(quote) quote #define t_strlen strlen #define t_strcmp strcmp #define t_strncmp strncmp #define t_itoa(value, buffer, size, radix) snprintf(buffer, size, "%d", value) #define t_strtol strtol #define t_atoi atoi #define t_strstr strstr #define t_isspace isspace #define t_to_string(val) std::to_string(val) #endif } #endif // LH_OS_TYPES_H
litehtml/litehtml
include/litehtml/os_types.h
C
bsd-3-clause
1,868
/* * * Copyright (C) 1994-2010, OFFIS e.V. * All rights reserved. See COPYRIGHT file for details. * * This software and supporting documentation were developed by * * OFFIS e.V. * R&D Division Health * Escherweg 2 * D-26121 Oldenburg, Germany * * * Module: dcmdata * * Author: Andrew Hewett * * Purpose: * Generate a builtin data dictionary which can be compiled into * the dcmdata library. * */ #include "dcmtk/config/osconfig.h" /* make sure OS specific configuration is included first */ #define INCLUDE_CSTDLIB #define INCLUDE_CSTDIO #define INCLUDE_CSTRING #define INCLUDE_CCTYPE #define INCLUDE_LIBC #include "dcmtk/ofstd/ofstdinc.h" #ifdef HAVE_SYS_UTSNAME_H #include <sys/utsname.h> #endif #ifdef HAVE_WINDOWS_H #include <windows.h> /* this includes either winsock.h or winsock2.h */ #else #ifdef HAVE_WINSOCK_H #include <winsock.h> /* include winsock.h directly i.e. on MacOS */ #endif #endif #ifdef HAVE_GUSI_H #include <GUSI.h> #endif #include "dcmtk/dcmdata/dcdict.h" #include "dcmtk/dcmdata/cmdlnarg.h" #include "dcmtk/ofstd/ofstring.h" #include "dcmtk/ofstd/ofdatime.h" #include "dcmtk/dcmdata/dcdicent.h" #define PRIVATE_TAGS_IFNAME "WITH_PRIVATE_TAGS" static const char* rr2s(DcmDictRangeRestriction rr) { const char* s; switch (rr) { case DcmDictRange_Unspecified: s = "DcmDictRange_Unspecified"; break; case DcmDictRange_Odd: s = "DcmDictRange_Odd"; break; case DcmDictRange_Even: s = "DcmDictRange_Even"; break; default: s = "DcmDictRange_GENERATOR_ERROR"; break; } return s; } static void printSimpleEntry(FILE* fout, const DcmDictEntry* e, OFBool& isFirst, OFBool& isPrivate) { const char *c = e->getPrivateCreator(); if (c && !isPrivate) { fprintf(fout, "#ifdef %s\n", PRIVATE_TAGS_IFNAME); isPrivate = OFTrue; } else if (isPrivate && !c) { fprintf(fout, "#endif\n"); isPrivate = OFFalse; } if (isFirst) { fprintf(fout, " "); isFirst = OFFalse; } else fprintf(fout, " , "); fprintf(fout, "{ 0x%04x, 0x%04x, 0x%04x, 0x%04x,\n", e->getGroup(), e->getElement(), e->getUpperGroup(), e->getUpperElement()); fprintf(fout, " EVR_%s, \"%s\", %d, %d, \"%s\",\n", e->getVR().getVRName(), e->getTagName(), e->getVMMin(), e->getVMMax(), OFSTRING_GUARD(e->getStandardVersion())); fprintf(fout, " %s, %s,\n", rr2s(e->getGroupRangeRestriction()), rr2s(e->getElementRangeRestriction())); if (c) fprintf(fout, " \"%s\" }\n", c); else fprintf(fout, " NULL }\n"); } #ifdef HAVE_CUSERID static char* getUserName(char* userString, int /* maxLen */) { return cuserid(userString); // thread safe, maxLen >= L_cuserid ? } #elif HAVE_GETLOGIN static char* getUserName(char* userString, int maxLen) { #if defined(_REENTRANT) && !defined(_WIN32) && !defined(__CYGWIN__) // use getlogin_r instead of getlogin if (getlogin_r(userString, maxLen) != 0) strncpy(userString, "<no-utmp-entry>", maxLen); return userString; #else char* s; s = getlogin(); // thread unsafe? if (s == NULL) s = "<no-utmp-entry>"; return strncpy(userString, s, maxLen); #endif } #elif defined(_WIN32) #include <lm.h> static char* getUserName(char* userString, int maxLen) { WKSTA_USER_INFO_0 *userinfo; if (NetWkstaUserGetInfo(NULL, 0, (LPBYTE*)&userinfo) == NERR_Success) { // Convert the Unicode full name to ANSI. WideCharToMultiByte( CP_ACP, 0, (WCHAR*)userinfo->wkui0_username, -1, userString, maxLen, NULL, NULL ); } else { strncpy(userString, "<no-user-information-available>", maxLen); } return userString; } #else static char* getUserName(char* userString, int maxLen) { return strncpy(userString, "<unknown-user>", maxLen); } #endif #ifdef HAVE_UNAME static char* getHostName(char* hostString, int maxLen) { struct utsname n; uname(&n); strncpy(hostString, n.nodename, maxLen); return hostString; } #elif HAVE_GETHOSTNAME static char* getHostName(char* userString, int maxLen) { gethostname(userString, maxLen); return userString; } #else static char* getHostName(char* hostString, int maxLen) { return strncpy(hostString, "localhost", maxLen); } #endif int main(int argc, char* argv[]) { char* progname; FILE* fout = NULL; DcmDictEntry* e = NULL; #ifdef HAVE_GUSI_H GUSISetup(GUSIwithSIOUXSockets); GUSISetup(GUSIwithInternetSockets); #endif #ifdef HAVE_WINSOCK_H WSAData winSockData; /* we need at least version 1.1 */ WORD winSockVersionNeeded = MAKEWORD( 1, 1 ); WSAStartup(winSockVersionNeeded, &winSockData); #endif prepareCmdLineArgs(argc, argv, "mkdictbi"); DcmDataDictionary& globalDataDict = dcmDataDict.wrlock(); /* clear out any preloaded dictionary */ globalDataDict.clear(); progname = argv[0]; int i; for (i=1; i<argc; i++) { globalDataDict.loadDictionary(argv[i]); } fout = stdout; OFString dateString; OFDateTime::getCurrentDateTime().getISOFormattedDateTime(dateString); /* generate c++ code for static dictionary */ fprintf(fout, "/*\n"); fprintf(fout, "** DO NOT EDIT THIS FILE !!!\n"); fprintf(fout, "** It was generated automatically by:\n"); #ifndef SUPPRESS_CREATE_STAMP /* * Putting the date in the file will confuse CVS/RCS * if nothing has changed except the generation date. * This is only an issue if the header file is continually * generated new. */ fputs("**\n", fout); char tmpString[512]; getUserName(tmpString, 512); fprintf(fout, "** User: %s\n", tmpString); getHostName(tmpString, 512); fprintf(fout, "** Host: %s\n", tmpString); fprintf(fout, "** Date: %s\n", dateString.c_str()); #endif fprintf(fout, "** Prog: %s\n", progname); fputs("**\n", fout); if (argc > 1) { fprintf(fout, "** From: %s\n", argv[1]); for (i=2; i<argc; i++) { fprintf(fout, "** %s\n", argv[i]); } } fputs("**\n", fout); fprintf(fout, "*/\n"); fprintf(fout, "\n"); fprintf(fout, "#include \"dcmtk/dcmdata/dcdict.h\"\n"); fprintf(fout, "#include \"dcmtk/dcmdata/dcdicent.h\"\n"); fprintf(fout, "\n"); fprintf(fout, "const char* dcmBuiltinDictBuildDate = \"%s\";\n", dateString.c_str()); fprintf(fout, "\n"); fprintf(fout, "struct DBI_SimpleEntry {\n"); fprintf(fout, " Uint16 group;\n"); fprintf(fout, " Uint16 element;\n"); fprintf(fout, " Uint16 upperGroup;\n"); fprintf(fout, " Uint16 upperElement;\n"); fprintf(fout, " DcmEVR evr;\n"); fprintf(fout, " const char* tagName;\n"); fprintf(fout, " int vmMin;\n"); fprintf(fout, " int vmMax;\n"); fprintf(fout, " const char* standardVersion;\n"); fprintf(fout, " DcmDictRangeRestriction groupRestriction;\n"); fprintf(fout, " DcmDictRangeRestriction elementRestriction;\n"); fprintf(fout, " const char* privateCreator;\n"); fprintf(fout, "};\n"); fprintf(fout, "\n"); fprintf(fout, "static const DBI_SimpleEntry simpleBuiltinDict[] = {\n"); OFBool isFirst = OFTrue; OFBool isPrivate = OFFalse; /* ** the hash table does not maintain ordering so we must put ** all the entries into a sorted list. */ DcmDictEntryList list; DcmHashDictIterator iter(globalDataDict.normalBegin()); DcmHashDictIterator last(globalDataDict.normalEnd()); for (; iter != last; ++iter) { e = new DcmDictEntry(*(*iter)); list.insertAndReplace(e); } /* output the list contents */ /* non-repeating standard elements */ DcmDictEntryListIterator listIter(list.begin()); DcmDictEntryListIterator listLast(list.end()); for (; listIter != listLast; ++listIter) { printSimpleEntry(fout, *listIter, isFirst, isPrivate); } /* repeating standard elements */ DcmDictEntryListIterator repIter(globalDataDict.repeatingBegin()); DcmDictEntryListIterator repLast(globalDataDict.repeatingEnd()); for (; repIter != repLast; ++repIter) { printSimpleEntry(fout, *repIter, isFirst, isPrivate); } if (isPrivate) { fprintf(fout, "#endif\n"); } fprintf(fout, "\n};\n"); fprintf(fout, "\n"); fprintf(fout, "static const int simpleBuiltinDict_count = \n"); fprintf(fout, " sizeof(simpleBuiltinDict)/sizeof(DBI_SimpleEntry);\n"); fprintf(fout, "\n"); fprintf(fout, "\n"); fprintf(fout, "void\n"); fprintf(fout, "DcmDataDictionary::loadBuiltinDictionary()\n"); fprintf(fout, "{\n"); fprintf(fout, " DcmDictEntry* e = NULL;\n"); fprintf(fout, " const DBI_SimpleEntry *b = simpleBuiltinDict;\n"); fprintf(fout, " for (int i=0; i<simpleBuiltinDict_count; i++) {\n"); fprintf(fout, " b = simpleBuiltinDict + i;\n"); fprintf(fout, " e = new DcmDictEntry(b->group, b->element,\n"); fprintf(fout, " b->upperGroup, b->upperElement, b->evr,\n"); fprintf(fout, " b->tagName, b->vmMin, b->vmMax,\n"); fprintf(fout, " b->standardVersion, OFFalse, b->privateCreator);\n"); fprintf(fout, " e->setGroupRangeRestriction(b->groupRestriction);\n"); fprintf(fout, " e->setElementRangeRestriction(b->elementRestriction);\n"); fprintf(fout, " addEntry(e);\n"); fprintf(fout, " }\n"); fprintf(fout, "}\n"); fprintf(fout, "\n"); fprintf(fout, "\n"); dcmDataDict.unlock(); return 0; }
NCIP/annotation-and-image-markup
AIMToolkit_v4.1.0_rv44/source/dcmtk-3.6.1_20121102/dcmdata/libsrc/mkdictbi.cc
C++
bsd-3-clause
9,774
import six import unittest import warnings from scrapy.settings import (BaseSettings, Settings, SettingsAttribute, CrawlerSettings) from tests import mock from . import default_settings class SettingsAttributeTest(unittest.TestCase): def setUp(self): self.attribute = SettingsAttribute('value', 10) def test_set_greater_priority(self): self.attribute.set('value2', 20) self.assertEqual(self.attribute.value, 'value2') self.assertEqual(self.attribute.priority, 20) def test_set_equal_priority(self): self.attribute.set('value2', 10) self.assertEqual(self.attribute.value, 'value2') self.assertEqual(self.attribute.priority, 10) def test_set_less_priority(self): self.attribute.set('value2', 0) self.assertEqual(self.attribute.value, 'value') self.assertEqual(self.attribute.priority, 10) def test_set_per_key_priorities(self): attribute = SettingsAttribute( BaseSettings({'one': 10, 'two': 20}, 0), 0) new_dict = {'one': 11, 'two': 21} attribute.set(new_dict, 10) self.assertEqual(attribute.value['one'], 11) self.assertEqual(attribute.value['two'], 21) new_settings = BaseSettings() new_settings.set('one', 12, 20) new_settings.set('two', 12, 0) attribute.set(new_settings, 0) self.assertEqual(attribute.value['one'], 12) self.assertEqual(attribute.value['two'], 21) class BaseSettingsTest(unittest.TestCase): if six.PY3: assertItemsEqual = unittest.TestCase.assertCountEqual def setUp(self): self.settings = BaseSettings() def test_set_new_attribute(self): self.settings.set('TEST_OPTION', 'value', 0) self.assertIn('TEST_OPTION', self.settings.attributes) attr = self.settings.attributes['TEST_OPTION'] self.assertIsInstance(attr, SettingsAttribute) self.assertEqual(attr.value, 'value') self.assertEqual(attr.priority, 0) def test_set_settingsattribute(self): myattr = SettingsAttribute(0, 30) # Note priority 30 self.settings.set('TEST_ATTR', myattr, 10) self.assertEqual(self.settings.get('TEST_ATTR'), 0) self.assertEqual(self.settings.getpriority('TEST_ATTR'), 30) def test_set_instance_identity_on_update(self): attr = SettingsAttribute('value', 0) self.settings.attributes = {'TEST_OPTION': attr} self.settings.set('TEST_OPTION', 'othervalue', 10) self.assertIn('TEST_OPTION', self.settings.attributes) self.assertIs(attr, self.settings.attributes['TEST_OPTION']) def test_set_calls_settings_attributes_methods_on_update(self): attr = SettingsAttribute('value', 10) with mock.patch.object(attr, '__setattr__') as mock_setattr, \ mock.patch.object(attr, 'set') as mock_set: self.settings.attributes = {'TEST_OPTION': attr} for priority in (0, 10, 20): self.settings.set('TEST_OPTION', 'othervalue', priority) mock_set.assert_called_once_with('othervalue', priority) self.assertFalse(mock_setattr.called) mock_set.reset_mock() mock_setattr.reset_mock() def test_setitem(self): settings = BaseSettings() settings.set('key', 'a', 'default') settings['key'] = 'b' self.assertEqual(settings['key'], 'b') self.assertEqual(settings.getpriority('key'), 20) settings['key'] = 'c' self.assertEqual(settings['key'], 'c') settings['key2'] = 'x' self.assertIn('key2', settings) self.assertEqual(settings['key2'], 'x') self.assertEqual(settings.getpriority('key2'), 20) def test_setdict_alias(self): with mock.patch.object(self.settings, 'set') as mock_set: self.settings.setdict({'TEST_1': 'value1', 'TEST_2': 'value2'}, 10) self.assertEqual(mock_set.call_count, 2) calls = [mock.call('TEST_1', 'value1', 10), mock.call('TEST_2', 'value2', 10)] mock_set.assert_has_calls(calls, any_order=True) def test_setmodule_only_load_uppercase_vars(self): class ModuleMock(): UPPERCASE_VAR = 'value' MIXEDcase_VAR = 'othervalue' lowercase_var = 'anothervalue' self.settings.attributes = {} self.settings.setmodule(ModuleMock(), 10) self.assertIn('UPPERCASE_VAR', self.settings.attributes) self.assertNotIn('MIXEDcase_VAR', self.settings.attributes) self.assertNotIn('lowercase_var', self.settings.attributes) self.assertEqual(len(self.settings.attributes), 1) def test_setmodule_alias(self): with mock.patch.object(self.settings, 'set') as mock_set: self.settings.setmodule(default_settings, 10) mock_set.assert_any_call('TEST_DEFAULT', 'defvalue', 10) mock_set.assert_any_call('TEST_DICT', {'key': 'val'}, 10) def test_setmodule_by_path(self): self.settings.attributes = {} self.settings.setmodule(default_settings, 10) ctrl_attributes = self.settings.attributes.copy() self.settings.attributes = {} self.settings.setmodule( 'tests.test_settings.default_settings', 10) self.assertItemsEqual(six.iterkeys(self.settings.attributes), six.iterkeys(ctrl_attributes)) for key in six.iterkeys(ctrl_attributes): attr = self.settings.attributes[key] ctrl_attr = ctrl_attributes[key] self.assertEqual(attr.value, ctrl_attr.value) self.assertEqual(attr.priority, ctrl_attr.priority) def test_update(self): settings = BaseSettings({'key_lowprio': 0}, priority=0) settings.set('key_highprio', 10, priority=50) custom_settings = BaseSettings({'key_lowprio': 1, 'key_highprio': 11}, priority=30) custom_settings.set('newkey_one', None, priority=50) custom_dict = {'key_lowprio': 2, 'key_highprio': 12, 'newkey_two': None} settings.update(custom_dict, priority=20) self.assertEqual(settings['key_lowprio'], 2) self.assertEqual(settings.getpriority('key_lowprio'), 20) self.assertEqual(settings['key_highprio'], 10) self.assertIn('newkey_two', settings) self.assertEqual(settings.getpriority('newkey_two'), 20) settings.update(custom_settings) self.assertEqual(settings['key_lowprio'], 1) self.assertEqual(settings.getpriority('key_lowprio'), 30) self.assertEqual(settings['key_highprio'], 10) self.assertIn('newkey_one', settings) self.assertEqual(settings.getpriority('newkey_one'), 50) settings.update({'key_lowprio': 3}, priority=20) self.assertEqual(settings['key_lowprio'], 1) def test_update_jsonstring(self): settings = BaseSettings({'number': 0, 'dict': BaseSettings({'key': 'val'})}) settings.update('{"number": 1, "newnumber": 2}') self.assertEqual(settings['number'], 1) self.assertEqual(settings['newnumber'], 2) settings.set("dict", '{"key": "newval", "newkey": "newval2"}') self.assertEqual(settings['dict']['key'], "newval") self.assertEqual(settings['dict']['newkey'], "newval2") def test_delete(self): settings = BaseSettings({'key': None}) settings.set('key_highprio', None, priority=50) settings.delete('key') settings.delete('key_highprio') self.assertNotIn('key', settings) self.assertIn('key_highprio', settings) del settings['key_highprio'] self.assertNotIn('key_highprio', settings) def test_get(self): test_configuration = { 'TEST_ENABLED1': '1', 'TEST_ENABLED2': True, 'TEST_ENABLED3': 1, 'TEST_DISABLED1': '0', 'TEST_DISABLED2': False, 'TEST_DISABLED3': 0, 'TEST_INT1': 123, 'TEST_INT2': '123', 'TEST_FLOAT1': 123.45, 'TEST_FLOAT2': '123.45', 'TEST_LIST1': ['one', 'two'], 'TEST_LIST2': 'one,two', 'TEST_STR': 'value', 'TEST_DICT1': {'key1': 'val1', 'ke2': 3}, 'TEST_DICT2': '{"key1": "val1", "ke2": 3}', } settings = self.settings settings.attributes = {key: SettingsAttribute(value, 0) for key, value in six.iteritems(test_configuration)} self.assertTrue(settings.getbool('TEST_ENABLED1')) self.assertTrue(settings.getbool('TEST_ENABLED2')) self.assertTrue(settings.getbool('TEST_ENABLED3')) self.assertFalse(settings.getbool('TEST_ENABLEDx')) self.assertTrue(settings.getbool('TEST_ENABLEDx', True)) self.assertFalse(settings.getbool('TEST_DISABLED1')) self.assertFalse(settings.getbool('TEST_DISABLED2')) self.assertFalse(settings.getbool('TEST_DISABLED3')) self.assertEqual(settings.getint('TEST_INT1'), 123) self.assertEqual(settings.getint('TEST_INT2'), 123) self.assertEqual(settings.getint('TEST_INTx'), 0) self.assertEqual(settings.getint('TEST_INTx', 45), 45) self.assertEqual(settings.getfloat('TEST_FLOAT1'), 123.45) self.assertEqual(settings.getfloat('TEST_FLOAT2'), 123.45) self.assertEqual(settings.getfloat('TEST_FLOATx'), 0.0) self.assertEqual(settings.getfloat('TEST_FLOATx', 55.0), 55.0) self.assertEqual(settings.getlist('TEST_LIST1'), ['one', 'two']) self.assertEqual(settings.getlist('TEST_LIST2'), ['one', 'two']) self.assertEqual(settings.getlist('TEST_LISTx'), []) self.assertEqual(settings.getlist('TEST_LISTx', ['default']), ['default']) self.assertEqual(settings['TEST_STR'], 'value') self.assertEqual(settings.get('TEST_STR'), 'value') self.assertEqual(settings['TEST_STRx'], None) self.assertEqual(settings.get('TEST_STRx'), None) self.assertEqual(settings.get('TEST_STRx', 'default'), 'default') self.assertEqual(settings.getdict('TEST_DICT1'), {'key1': 'val1', 'ke2': 3}) self.assertEqual(settings.getdict('TEST_DICT2'), {'key1': 'val1', 'ke2': 3}) self.assertEqual(settings.getdict('TEST_DICT3'), {}) self.assertEqual(settings.getdict('TEST_DICT3', {'key1': 5}), {'key1': 5}) self.assertRaises(ValueError, settings.getdict, 'TEST_LIST1') def test_getpriority(self): settings = BaseSettings({'key': 'value'}, priority=99) self.assertEqual(settings.getpriority('key'), 99) self.assertEqual(settings.getpriority('nonexistentkey'), None) def test_getcomposite(self): s = BaseSettings({'TEST_BASE': {1: 1, 2: 2}, 'TEST': BaseSettings({1: 10, 3: 30}, 'default'), 'HASNOBASE': BaseSettings({1: 1}, 'default')}) s['TEST'].set(4, 4, priority='project') # When users specify a _BASE setting they explicitly don't want to use # Scrapy's defaults, so we don't want to see anything that has a # 'default' priority from TEST cs = s._getcomposite('TEST') self.assertEqual(len(cs), 3) self.assertEqual(cs[1], 1) self.assertEqual(cs[2], 2) self.assertEqual(cs[4], 4) cs = s._getcomposite('HASNOBASE') self.assertEqual(len(cs), 1) self.assertEqual(cs[1], 1) cs = s._getcomposite('NONEXISTENT') self.assertIsNone(cs) def test_maxpriority(self): # Empty settings should return 'default' self.assertEqual(self.settings.maxpriority(), 0) self.settings.set('A', 0, 10) self.settings.set('B', 0, 30) self.assertEqual(self.settings.maxpriority(), 30) def test_copy(self): values = { 'TEST_BOOL': True, 'TEST_LIST': ['one', 'two'], 'TEST_LIST_OF_LISTS': [['first_one', 'first_two'], ['second_one', 'second_two']] } self.settings.setdict(values) copy = self.settings.copy() self.settings.set('TEST_BOOL', False) self.assertTrue(copy.get('TEST_BOOL')) test_list = self.settings.get('TEST_LIST') test_list.append('three') self.assertListEqual(copy.get('TEST_LIST'), ['one', 'two']) test_list_of_lists = self.settings.get('TEST_LIST_OF_LISTS') test_list_of_lists[0].append('first_three') self.assertListEqual(copy.get('TEST_LIST_OF_LISTS')[0], ['first_one', 'first_two']) def test_freeze(self): self.settings.freeze() with self.assertRaises(TypeError) as cm: self.settings.set('TEST_BOOL', False) self.assertEqual(str(cm.exception), "Trying to modify an immutable Settings object") def test_frozencopy(self): frozencopy = self.settings.frozencopy() self.assertTrue(frozencopy.frozen) self.assertIsNot(frozencopy, self.settings) def test_deprecated_attribute_overrides(self): self.settings.set('BAR', 'fuz', priority='cmdline') with warnings.catch_warnings(record=True) as w: self.settings.overrides['BAR'] = 'foo' self.assertIn("Settings.overrides", str(w[0].message)) self.assertEqual(self.settings.get('BAR'), 'foo') self.assertEqual(self.settings.overrides.get('BAR'), 'foo') self.assertIn('BAR', self.settings.overrides) self.settings.overrides.update(BAR='bus') self.assertEqual(self.settings.get('BAR'), 'bus') self.assertEqual(self.settings.overrides.get('BAR'), 'bus') self.settings.overrides.setdefault('BAR', 'fez') self.assertEqual(self.settings.get('BAR'), 'bus') self.settings.overrides.setdefault('FOO', 'fez') self.assertEqual(self.settings.get('FOO'), 'fez') self.assertEqual(self.settings.overrides.get('FOO'), 'fez') def test_deprecated_attribute_defaults(self): self.settings.set('BAR', 'fuz', priority='default') with warnings.catch_warnings(record=True) as w: self.settings.defaults['BAR'] = 'foo' self.assertIn("Settings.defaults", str(w[0].message)) self.assertEqual(self.settings.get('BAR'), 'foo') self.assertEqual(self.settings.defaults.get('BAR'), 'foo') self.assertIn('BAR', self.settings.defaults) class SettingsTest(unittest.TestCase): if six.PY3: assertItemsEqual = unittest.TestCase.assertCountEqual def setUp(self): self.settings = Settings() @mock.patch.dict('scrapy.settings.SETTINGS_PRIORITIES', {'default': 10}) @mock.patch('scrapy.settings.default_settings', default_settings) def test_initial_defaults(self): settings = Settings() self.assertEqual(len(settings.attributes), 2) self.assertIn('TEST_DEFAULT', settings.attributes) attr = settings.attributes['TEST_DEFAULT'] self.assertIsInstance(attr, SettingsAttribute) self.assertEqual(attr.value, 'defvalue') self.assertEqual(attr.priority, 10) @mock.patch.dict('scrapy.settings.SETTINGS_PRIORITIES', {}) @mock.patch('scrapy.settings.default_settings', {}) def test_initial_values(self): settings = Settings({'TEST_OPTION': 'value'}, 10) self.assertEqual(len(settings.attributes), 1) self.assertIn('TEST_OPTION', settings.attributes) attr = settings.attributes['TEST_OPTION'] self.assertIsInstance(attr, SettingsAttribute) self.assertEqual(attr.value, 'value') self.assertEqual(attr.priority, 10) @mock.patch('scrapy.settings.default_settings', default_settings) def test_autopromote_dicts(self): settings = Settings() mydict = settings.get('TEST_DICT') self.assertIsInstance(mydict, BaseSettings) self.assertIn('key', mydict) self.assertEqual(mydict['key'], 'val') self.assertEqual(mydict.getpriority('key'), 0) @mock.patch('scrapy.settings.default_settings', default_settings) def test_getdict_autodegrade_basesettings(self): settings = Settings() mydict = settings.getdict('TEST_DICT') self.assertIsInstance(mydict, dict) self.assertEqual(len(mydict), 1) self.assertIn('key', mydict) self.assertEqual(mydict['key'], 'val') class CrawlerSettingsTest(unittest.TestCase): def test_deprecated_crawlersettings(self): def _get_settings(settings_dict=None): settings_module = type('SettingsModuleMock', (object,), settings_dict or {}) return CrawlerSettings(settings_module) with warnings.catch_warnings(record=True) as w: settings = _get_settings() self.assertIn("CrawlerSettings is deprecated", str(w[0].message)) # test_global_defaults self.assertEqual(settings.getint('DOWNLOAD_TIMEOUT'), 180) # test_defaults settings.defaults['DOWNLOAD_TIMEOUT'] = '99' self.assertEqual(settings.getint('DOWNLOAD_TIMEOUT'), 99) # test_settings_module settings = _get_settings({'DOWNLOAD_TIMEOUT': '3'}) self.assertEqual(settings.getint('DOWNLOAD_TIMEOUT'), 3) # test_overrides settings = _get_settings({'DOWNLOAD_TIMEOUT': '3'}) settings.overrides['DOWNLOAD_TIMEOUT'] = '15' self.assertEqual(settings.getint('DOWNLOAD_TIMEOUT'), 15) if __name__ == "__main__": unittest.main()
pombredanne/scrapy
tests/test_settings/__init__.py
Python
bsd-3-clause
17,815
## 6.2. 基于指针对象的方法 当调用一个函数时,会对其每一个参数值进行拷贝,如果一个函数需要更新一个变量,或者函数的其中一个参数实在太大我们希望能够避免进行这种默认的拷贝,这种情况下我们就需要用到指针了。对应到我们这里用来更新接收器的对象的方法,当这个接受者变量本身比较大时,我们就可以用其指针而不是对象来声明方法,如下: ```go func (p *Point) ScaleBy(factor float64) { p.X *= factor p.Y *= factor } ``` 这个方法的名字是`(*Point).ScaleBy`。这里的括号是必须的;没有括号的话这个表达式可能会被理解为`*(Point.ScaleBy)`。 在现实的程序里,一般会约定如果Point这个类有一个指针作为接收器的方法,那么所有Point的方法都必须有一个指针接收器,即使是那些并不需要这个指针接收器的函数。我们在这里打破了这个约定只是为了展示一下两种方法的异同而已。 只有类型(Point)和指向他们的指针(*Point),才是可能会出现在接收器声明里的两种接收器。此外,为了避免歧义,在声明方法时,如果一个类型名本身是一个指针的话,是不允许其出现在接收器中的,比如下面这个例子: ```go type P *int func (P) f() { /* ... */ } // compile error: invalid receiver type ``` 想要调用指针类型方法`(*Point).ScaleBy`,只要提供一个Point类型的指针即可,像下面这样。 ```go r := &Point{1, 2} r.ScaleBy(2) fmt.Println(*r) // "{2, 4}" ``` 或者这样: ```go p := Point{1, 2} pptr := &p pptr.ScaleBy(2) fmt.Println(p) // "{2, 4}" ``` 或者这样: ```go p := Point{1, 2} (&p).ScaleBy(2) fmt.Println(p) // "{2, 4}" ``` 不过后面两种方法有些笨拙。幸运的是,go语言本身在这种地方会帮到我们。如果接收器p是一个Point类型的变量,并且其方法需要一个Point指针作为接收器,我们可以用下面这种简短的写法: ```go p.ScaleBy(2) ``` 编译器会隐式地帮我们用&p去调用ScaleBy这个方法。这种简写方法只适用于“变量”,包括struct里的字段比如p.X,以及array和slice内的元素比如perim[0]。我们不能通过一个无法取到地址的接收器来调用指针方法,比如临时变量的内存地址就无法获取得到: ```go Point{1, 2}.ScaleBy(2) // compile error: can't take address of Point literal ``` 但是我们可以用一个`*Point`这样的接收器来调用Point的方法,因为我们可以通过地址来找到这个变量,只要用解引用符号`*`来取到该变量即可。编译器在这里也会给我们隐式地插入`*`这个操作符,所以下面这两种写法等价的: ```Go pptr.Distance(q) (*pptr).Distance(q) ``` 这里的几个例子可能让你有些困惑,所以我们总结一下:在每一个合法的方法调用表达式中,也就是下面三种情况里的任意一种情况都是可以的: 不论是接收器的实际参数和其接收器的形式参数相同,比如两者都是类型T或者都是类型`*T`: ```go Point{1, 2}.Distance(q) // Point pptr.ScaleBy(2) // *Point ``` 或者接收器形参是类型T,但接收器实参是类型`*T`,这种情况下编译器会隐式地为我们取变量的地址: ```go p.ScaleBy(2) // implicit (&p) ``` 或者接收器形参是类型`*T`,实参是类型T。编译器会隐式地为我们解引用,取到指针指向的实际变量: ```go pptr.Distance(q) // implicit (*pptr) ``` 如果类型T的所有方法都是用T类型自己来做接收器(而不是`*T`),那么拷贝这种类型的实例就是安全的;调用他的任何一个方法也就会产生一个值的拷贝。比如time.Duration的这个类型,在调用其方法时就会被全部拷贝一份,包括在作为参数传入函数的时候。但是如果一个方法使用指针作为接收器,你需要避免对其进行拷贝,因为这样可能会破坏掉该类型内部的不变性。比如你对bytes.Buffer对象进行了拷贝,那么可能会引起原始对象和拷贝对象只是别名而已,但实际上其指向的对象是一致的。紧接着对拷贝后的变量进行修改可能会有让你意外的结果。 **译注:** 作者这里说的比较绕,其实有两点: 1. 不管你的method的receiver是指针类型还是非指针类型,都是可以通过指针/非指针类型进行调用的,编译器会帮你做类型转换。 2. 在声明一个method的receiver该是指针还是非指针类型时,你需要考虑两方面的内部,第一方面是这个对象本身是不是特别大,如果声明为非指针变量时,调用会产生一次拷贝;第二方面是如果你用指针类型作为receiver,那么你一定要注意,这种指针类型指向的始终是一块内存地址,就算你对其进行了拷贝。熟悉C或者C艹的人这里应该很快能明白。 {% include "./ch6-02-1.md" %}
yar999/gopl-zh
ch6/ch6-02.md
Markdown
bsd-3-clause
5,023
using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Windows.Forms; using PoshSec.Framework.PShell; using PoshSec.Framework.Strings; namespace PoshSec.Framework.Controls { public class PSAlertList : ListView { #region Private Variables private ToolStrip parstrip = null; private const int SEVERITY_WIDTH = 100; private const int MESSAGE_WIDTH = 535; private const int TIMESTAMP_WIDTH = 135; private const int SCRIPT_WIDTH = 150; private string scriptname = ""; private ImageList imgListAlerts; private System.ComponentModel.IContainer components; private Syslog slog = null; private ToolStripLabel lblalertcount = new ToolStripLabel(String.Format(StringValue.AlertLabelFormat, "Alerts", 0)); private int alertcount = 0; PSTabItem parent = null; private string tablabel = ""; #endregion #region Public Methods public PSAlertList(String ScriptName, PSTabItem Parent) { scriptname = ScriptName; InitializeComponent(); Init(); parent = Parent; tablabel = Parent.Text; } public void Add(String message, int alerttype) { if (alerttype >= (int)PShell.psmethods.PSAlert.AlertType.Information && alerttype <= (int)PShell.psmethods.PSAlert.AlertType.Critical) { Add(message, (PShell.psmethods.PSAlert.AlertType)alerttype); } } #endregion #region Private Methods private void Init() { this.Dock = DockStyle.Fill; AddColumns(); AddButtons(); } private void AddColumns() { ColumnHeader chsev = new ColumnHeader(); chsev.Text = "Severity"; chsev.Width = SEVERITY_WIDTH; this.Columns.Add(chsev); ColumnHeader chmsg = new ColumnHeader(); chmsg.Text = "Message"; chmsg.Width = MESSAGE_WIDTH; this.Columns.Add(chmsg); ColumnHeader chtmst = new ColumnHeader(); chtmst.Text = "Timestamp"; chtmst.Width = TIMESTAMP_WIDTH; this.Columns.Add(chtmst); ColumnHeader chscpt = new ColumnHeader(); chscpt.Text = "Script"; chscpt.Width = SCRIPT_WIDTH; this.Columns.Add(chscpt); } private void AddButtons() { if (parstrip != null) { ToolStripButton exp = new ToolStripButton(); exp.Text = "Save"; exp.Image = Properties.Resources.table_save; exp.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; exp.ToolTipText = "Save"; exp.Alignment = ToolStripItemAlignment.Left; exp.Click += new EventHandler(Save); parstrip.Items.Add(exp); parstrip.Items.Add(lblalertcount); } } private void Add(String message, psmethods.PSAlert.AlertType alerttype) { if (this.InvokeRequired) { MethodInvoker del = delegate { Add(message, alerttype); }; this.Invoke(del); } else { alertcount++; lblalertcount.Text = String.Format(StringValue.AlertLabelFormat, "Alerts", alertcount); parent.Text = string.Format(StringValue.AlertLabelFormat, tablabel, alertcount); ListViewItem lvwitm = new ListViewItem(); lvwitm.Text = alerttype.ToString(); lvwitm.ImageIndex = (int)alerttype; lvwitm.SubItems.Add(message); lvwitm.ToolTipText = message; lvwitm.SubItems.Add(DateTime.Now.ToString(StringValue.TimeFormat)); lvwitm.SubItems.Add(scriptname); this.Items.Add(lvwitm); this.Update(); lvwitm.EnsureVisible(); string alert = String.Format(StringValue.AlertFormat, lvwitm.SubItems[0].Text, lvwitm.SubItems[1].Text, lvwitm.SubItems[2].Text, lvwitm.SubItems[3].Text).Replace("\\r\\n", Environment.NewLine); alert += Environment.NewLine; LogAlert(alert); if (Properties.Settings.Default.UseSyslog) { if (slog == null) { slog = new Syslog(new System.Net.IPEndPoint(System.Net.IPAddress.Parse(Properties.Settings.Default.SyslogServer), Properties.Settings.Default.SyslogPort)); } slog.SendMessage(alerttype, scriptname, message); slog.Close(); slog = null; } } } private void LogAlert(String text) { if (Properties.Settings.Default.LogAlerts) { if (!File.Exists(Properties.Settings.Default.AlertLogFile)) { DirectoryInfo dirinfo = new DirectoryInfo(Properties.Settings.Default.AlertLogFile); if (!Directory.Exists(dirinfo.Parent.FullName)) { Directory.CreateDirectory(dirinfo.Parent.FullName); } } StreamWriter wtr = File.AppendText(Properties.Settings.Default.AlertLogFile); wtr.Write(text); wtr.Flush(); wtr.Close(); } } private void Save(object sender, EventArgs e) { MessageBox.Show("Save not implemented yet."); } #endregion #region Public Properties public ToolStrip ParentStrip { set { parstrip = value; AddButtons(); } } #endregion private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(PSAlertList)); this.imgListAlerts = new System.Windows.Forms.ImageList(this.components); this.SuspendLayout(); // // imgListAlerts // this.imgListAlerts.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imgListAlerts.ImageStream"))); this.imgListAlerts.TransparentColor = System.Drawing.Color.Transparent; this.imgListAlerts.Images.SetKeyName(0, "dialog-information-3.png"); this.imgListAlerts.Images.SetKeyName(1, "dialog-error-4.png"); this.imgListAlerts.Images.SetKeyName(2, "dialog-warning-3.png"); this.imgListAlerts.Images.SetKeyName(3, "dialog-warning-2.png"); this.imgListAlerts.Images.SetKeyName(4, "exclamation.png"); // // PSAlertList // this.Font = new System.Drawing.Font("Tahoma", 8.25F); this.FullRowSelect = true; this.HideSelection = false; this.SmallImageList = this.imgListAlerts; this.View = System.Windows.Forms.View.Details; this.ResumeLayout(false); } } }
PoshSec/PoshSecFramework
poshsecframework/Controls/PSAlertList.cs
C#
bsd-3-clause
7,521
# The set of languages for which implicit dependencies are needed: SET(CMAKE_DEPENDS_LANGUAGES "CXX" ) # The set of files for implicit dependencies of each language: SET(CMAKE_DEPENDS_CHECK_CXX "/usr/src/gtest/src/gtest-all.cc" "/home/vsunder/ButlerBot/rosbuild_ws/src/behaviors/build/gtest/CMakeFiles/gtest.dir/src/gtest-all.cc.o" ) SET(CMAKE_CXX_COMPILER_ID "GNU") # Preprocessor definitions for this target. SET(CMAKE_TARGET_DEFINITIONS "GTEST_CREATE_SHARED_LIBRARY=1" ) # Targets to which this target links. SET(CMAKE_TARGET_LINKED_INFO_FILES )
Boberito25/ButlerBot
rosbuild_ws/src/behaviors/build/gtest/CMakeFiles/gtest.dir/DependInfo.cmake
CMake
bsd-3-clause
565
/** * BSD 3-Clause License * * Copyright (c) 2017, Gluon Software * 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 the copyright holder 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 HOLDER 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. */ @import "javaone_ios.css"; @import "common_ios_tablet.css";
gluonhq/jfokus2017
src/main/resources/com/gluonhq/otn/javaone_ios_tablet.css
CSS
bsd-3-clause
1,662
/* * Copyright (c) 2021, salesforce.com, inc. * All rights reserved. * SPDX-License-Identifier: BSD-3-Clause * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause */ package com.krux.hyperion.aws /** * AWS Data Pipeline database objects. * * Ref: http://docs.aws.amazon.com/datapipeline/latest/DeveloperGuide/dp-object-databases.html */ trait AdpDatabase extends AdpDataPipelineObject { /** The name of the logical database. */ def databaseName: Option[String] /** The properties of the JDBC connections for this database. */ def jdbcProperties: Option[Seq[String]] /** The user name to connect to the database. */ def username: String /** The password to connect to the database. */ def `*password`: String } /** * Defines an Amazon Redshift database. * * @param clusterId The identifier provided by the user when the Amazon Redshift cluster was * created. For example, if the endpoint for your Amazon Redshift cluster is * mydb.example.us-east-1.redshift.amazonaws.com, the correct clusterId value is mydb. In the * Amazon Redshift console, this value is "Cluster Name". * @param connectionString The JDBC endpoint for connecting to an Amazon Redshift instance owned by * an account different than the pipeline. */ case class AdpRedshiftDatabase( id: String, name: Option[String], clusterId: String, connectionString: Option[String], databaseName: Option[String], username: String, `*password`: String, jdbcProperties: Option[Seq[String]] ) extends AdpDatabase { val `type` = "RedshiftDatabase" } /** * Defines a JDBC database. * * @param connectionString The JDBC connection string to access the database. * @param jdbcDriverClass The driver class to load before establishing the JDBC connection. */ case class AdpJdbcDatabase( id: String, name: Option[String], connectionString: String, databaseName: Option[String], username: String, `*password`: String, jdbcDriverJarUri: Option[String], jdbcDriverClass: String, jdbcProperties: Option[Seq[String]] ) extends AdpDatabase { val `type` = "JdbcDatabase" } /** * Defines an Amazon RDS database. */ case class AdpRdsDatabase( id: String, name: Option[String], databaseName: Option[String], jdbcProperties: Option[Seq[String]], username: String, `*password`: String, rdsInstanceId: String, region: Option[String], jdbcDriverJarUri: Option[String] ) extends AdpDatabase { val `type` = "RdsDatabase" }
realstraw/hyperion
core/src/main/scala/com/krux/hyperion/aws/AdpDatabases.scala
Scala
bsd-3-clause
2,529
// // ModelCreationUtils.h // CoreML_tests // // Created by Anil Katti on 4/8/19. // Copyright © 2019 Apple Inc. All rights reserved. // #include "Format.hpp" #include "Model.hpp" #include "framework/TestUtils.hpp" typedef struct { const char *name; int dimension; } TensorAttributes; CoreML::Specification::NeuralNetwork* buildBasicUpdatableNeuralNetworkModel(CoreML::Specification::Model& m); CoreML::Specification::NeuralNetwork* buildBasicNeuralNetworkModel(CoreML::Specification::Model& m, bool isUpdatable, const TensorAttributes *inTensorAttr, const TensorAttributes *outTensorAttr, int numberOfLayers = 1, bool areWeightsQuantized = false, bool isBiasQuantized = false); CoreML::Specification::NeuralNetworkClassifier* buildBasicNeuralNetworkClassifierModel(CoreML::Specification::Model& m, bool isUpdatable, const TensorAttributes *inTensorAttr, std::vector<std::string> stringClassLabels, std::vector<int64_t> intClassLabels, bool includeBias); CoreML::Specification::KNearestNeighborsClassifier* buildBasicNearestNeighborClassifier(CoreML::Specification::Model& m, bool isUpdatable, const TensorAttributes *inTensorAttr, const char *outTensorName); CoreML::Specification::Pipeline* buildEmptyPipelineModel(CoreML::Specification::Model& m, bool isUpdatable, const TensorAttributes *inTensorAttr, const TensorAttributes *outTensorAttr); CoreML::Specification::Pipeline* buildEmptyPipelineModelWithStringOutput(CoreML::Specification::Model& m, bool isUpdatable, const TensorAttributes *inTensorAttr, const char *outTensorName); void addCategoricalCrossEntropyLossWithSoftmaxAndSGDOptimizer(CoreML::Specification::Model& m, const char *softmaxInputName); CoreML::Specification::NeuralNetwork* addInnerProductLayer(CoreML::Specification::Model& m, bool isUpdatable, const char *name, const TensorAttributes *inTensorAttr, const TensorAttributes *outTensorAttr, bool areWeightsQuantized = false, bool isBiasQuantized = false); CoreML::Specification::NeuralNetwork* addSoftmaxLayer(CoreML::Specification::Model& m, const char *name, const char *input, const char *output); void createSimpleNeuralNetworkClassifierModel(CoreML::Specification::Model *spec, const char *inputName, const char *outputName); void createSimpleFeatureVectorizerModel(CoreML::Specification::Model *spec, const char *outputName, CoreML::Specification::ArrayFeatureType_ArrayDataType arrayType, int inputSize = 3);
apple/coremltools
mlmodel/tests/ModelCreationUtils.hpp
C++
bsd-3-clause
2,420
/** * Framework for notifications of graph events. * * Author: Paul McCarthy <[email protected]> */ #include <stdlib.h> #include <stdint.h> #include "graph/graph.h" #include "graph/graph_event.h" #include "util/array.h" /** * Global counter used for assigning IDs to event listeners. */ static uint64_t _id_counter = 0; /** * Fires the edge added event on all listeners. */ static void _fire_edge_added( graph_t *g, edge_added_ctx_t *ctx ); /** * Fires the edge removed event on all listeners. */ static void _fire_edge_removed( graph_t *g, edge_removed_ctx_t *ctx ); uint8_t graph_add_event_listener(graph_t *g, graph_event_listener_t *l) { l->id = _id_counter ++; if (array_append(&g->event_listeners, l)) return 1; return 0; } void graph_remove_event_listener(graph_t *g, graph_event_listener_t *l) { array_remove_by_val(&g->event_listeners, l, 0); } void graph_event_fire(graph_t *g, graph_event_t type, void *ctx) { switch(type) { case GRAPH_EVENT_EDGE_ADDED: _fire_edge_added( g, ctx); break; case GRAPH_EVENT_EDGE_REMOVED: _fire_edge_removed(g, ctx); break; } } void _fire_edge_added(graph_t *g, edge_added_ctx_t *ctx) { uint64_t i; graph_event_listener_t l; for (i = 0; i < g->event_listeners.size; i++) { if (array_get(&g->event_listeners, i, &l)) return; if (!l.edge_added) continue; l.edge_added(g, l.ctx, ctx->u, ctx->v, ctx->uidx, ctx->vidx, ctx->wt); } } void _fire_edge_removed(graph_t *g, edge_removed_ctx_t *ctx) { uint64_t i; graph_event_listener_t l; for (i = 0; i < g->event_listeners.size; i++) { if (array_get(&g->event_listeners, i, &l)) return; if (!l.edge_removed) continue; l.edge_removed(g, l.ctx, ctx->u, ctx->v, ctx->uidx, ctx->vidx); } } int graph_compare_event_listeners(const void *a, const void *b) { graph_event_listener_t *gela; graph_event_listener_t *gelb; gela = (graph_event_listener_t *)a; gelb = (graph_event_listener_t *)b; if (gela->id == gelb->id) return 0; return 1; }
pauldmccarthy/ccnet
graph/graph_event.c
C
bsd-3-clause
2,091
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "media/base/mock_filters.h" #include "media/ffmpeg/ffmpeg_common.h" #include "media/filters/ffmpeg_glue.h" #include "testing/gtest/include/gtest/gtest.h" using ::testing::_; using ::testing::DoAll; using ::testing::InSequence; using ::testing::Return; using ::testing::SetArgumentPointee; using ::testing::StrictMock; namespace media { class MockProtocol : public FFmpegURLProtocol { public: MockProtocol() { } MOCK_METHOD2(Read, size_t(size_t size, uint8* data)); MOCK_METHOD1(GetPosition, bool(int64* position_out)); MOCK_METHOD1(SetPosition, bool(int64 position)); MOCK_METHOD1(GetSize, bool(int64* size_out)); MOCK_METHOD0(IsStreaming, bool()); private: DISALLOW_COPY_AND_ASSIGN(MockProtocol); }; class FFmpegGlueTest : public ::testing::Test { public: FFmpegGlueTest() : protocol_(NULL) {} static void SetUpTestCase() { // Singleton should initialize FFmpeg. CHECK(FFmpegGlue::GetInstance()); } virtual void SetUp() { // Assign our static copy of URLProtocol for the rest of the tests. protocol_ = FFmpegGlue::url_protocol(); CHECK(protocol_); } MOCK_METHOD1(CheckPoint, void(int val)); // Helper to open a URLContext pointing to the given mocked protocol. // Callers are expected to close the context at the end of their test. virtual void OpenContext(MockProtocol* protocol, URLContext* context) { // IsStreaming() is called when opening. EXPECT_CALL(*protocol, IsStreaming()).WillOnce(Return(true)); // Add the protocol to the glue layer and open a context. std::string key = FFmpegGlue::GetInstance()->AddProtocol(protocol); memset(context, 0, sizeof(*context)); EXPECT_EQ(0, protocol_->url_open(context, key.c_str(), 0)); FFmpegGlue::GetInstance()->RemoveProtocol(protocol); } protected: // Fixture members. URLProtocol* protocol_; private: DISALLOW_COPY_AND_ASSIGN(FFmpegGlueTest); }; TEST_F(FFmpegGlueTest, InitializeFFmpeg) { // Make sure URLProtocol was filled out correctly. EXPECT_STREQ("http", protocol_->name); EXPECT_TRUE(protocol_->url_close); EXPECT_TRUE(protocol_->url_open); EXPECT_TRUE(protocol_->url_read); EXPECT_TRUE(protocol_->url_seek); EXPECT_TRUE(protocol_->url_write); } TEST_F(FFmpegGlueTest, AddRemoveGetProtocol) { // Prepare testing data. FFmpegGlue* glue = FFmpegGlue::GetInstance(); // Create our protocols and add them to the glue layer. scoped_ptr<StrictMock<Destroyable<MockProtocol> > > protocol_a( new StrictMock<Destroyable<MockProtocol> >()); scoped_ptr<StrictMock<Destroyable<MockProtocol> > > protocol_b( new StrictMock<Destroyable<MockProtocol> >()); // Make sure the keys are unique. std::string key_a = glue->AddProtocol(protocol_a.get()); std::string key_b = glue->AddProtocol(protocol_b.get()); EXPECT_EQ(0u, key_a.find("http://")); EXPECT_EQ(0u, key_b.find("http://")); EXPECT_NE(key_a, key_b); // Our keys should return our protocols. FFmpegURLProtocol* protocol_c; FFmpegURLProtocol* protocol_d; glue->GetProtocol(key_a, &protocol_c); glue->GetProtocol(key_b, &protocol_d); EXPECT_EQ(protocol_a.get(), protocol_c); EXPECT_EQ(protocol_b.get(), protocol_d); // Adding the same Protocol should create the same key and not add an extra // reference. std::string key_a2 = glue->AddProtocol(protocol_a.get()); EXPECT_EQ(key_a, key_a2); glue->GetProtocol(key_a2, &protocol_c); EXPECT_EQ(protocol_a.get(), protocol_c); // Removes the protocols then releases our references. They should be // destroyed. InSequence s; EXPECT_CALL(*protocol_a, OnDestroy()); EXPECT_CALL(*protocol_b, OnDestroy()); EXPECT_CALL(*this, CheckPoint(0)); glue->RemoveProtocol(protocol_a.get()); glue->GetProtocol(key_a, &protocol_c); EXPECT_FALSE(protocol_c); glue->GetProtocol(key_b, &protocol_d); EXPECT_EQ(protocol_b.get(), protocol_d); glue->RemoveProtocol(protocol_b.get()); glue->GetProtocol(key_b, &protocol_d); EXPECT_FALSE(protocol_d); protocol_a.reset(); protocol_b.reset(); // Data sources should be deleted by this point. CheckPoint(0); } TEST_F(FFmpegGlueTest, OpenClose) { // Prepare testing data. FFmpegGlue* glue = FFmpegGlue::GetInstance(); // Create our protocol and add them to the glue layer. scoped_ptr<StrictMock<Destroyable<MockProtocol> > > protocol( new StrictMock<Destroyable<MockProtocol> >()); EXPECT_CALL(*protocol, IsStreaming()).WillOnce(Return(true)); std::string key = glue->AddProtocol(protocol.get()); // Prepare FFmpeg URLContext structure. URLContext context; memset(&context, 0, sizeof(context)); // Test opening a URLContext with a protocol that doesn't exist. EXPECT_EQ(AVERROR(EIO), protocol_->url_open(&context, "foobar", 0)); // Test opening a URLContext with our protocol. EXPECT_EQ(0, protocol_->url_open(&context, key.c_str(), 0)); EXPECT_EQ(URL_RDONLY, context.flags); EXPECT_EQ(protocol.get(), context.priv_data); EXPECT_TRUE(context.is_streamed); // We're going to remove references one by one until the last reference is // held by FFmpeg. Once we close the URLContext, the protocol should be // destroyed. InSequence s; EXPECT_CALL(*this, CheckPoint(0)); EXPECT_CALL(*this, CheckPoint(1)); EXPECT_CALL(*protocol, OnDestroy()); EXPECT_CALL(*this, CheckPoint(2)); // Remove the protocol from the glue layer, releasing a reference. glue->RemoveProtocol(protocol.get()); CheckPoint(0); // Remove our own reference -- URLContext should maintain a reference. CheckPoint(1); protocol.reset(); // Close the URLContext, which should release the final reference. EXPECT_EQ(0, protocol_->url_close(&context)); CheckPoint(2); } TEST_F(FFmpegGlueTest, Write) { scoped_ptr<StrictMock<MockProtocol> > protocol( new StrictMock<MockProtocol>()); URLContext context; OpenContext(protocol.get(), &context); const int kBufferSize = 16; uint8 buffer[kBufferSize]; // Writing should always fail and never call the protocol. EXPECT_EQ(AVERROR(EIO), protocol_->url_write(&context, NULL, 0)); EXPECT_EQ(AVERROR(EIO), protocol_->url_write(&context, buffer, 0)); EXPECT_EQ(AVERROR(EIO), protocol_->url_write(&context, buffer, kBufferSize)); // Destroy the protocol. protocol_->url_close(&context); } TEST_F(FFmpegGlueTest, Read) { scoped_ptr<StrictMock<MockProtocol> > protocol( new StrictMock<MockProtocol>()); URLContext context; OpenContext(protocol.get(), &context); const int kBufferSize = 16; uint8 buffer[kBufferSize]; // Reads are for the most part straight-through calls to Read(). InSequence s; EXPECT_CALL(*protocol, Read(0, buffer)) .WillOnce(Return(0)); EXPECT_CALL(*protocol, Read(kBufferSize, buffer)) .WillOnce(Return(kBufferSize)); EXPECT_CALL(*protocol, Read(kBufferSize, buffer)) .WillOnce(Return(DataSource::kReadError)); EXPECT_EQ(0, protocol_->url_read(&context, buffer, 0)); EXPECT_EQ(kBufferSize, protocol_->url_read(&context, buffer, kBufferSize)); EXPECT_EQ(AVERROR(EIO), protocol_->url_read(&context, buffer, kBufferSize)); // Destroy the protocol. protocol_->url_close(&context); } TEST_F(FFmpegGlueTest, Seek) { scoped_ptr<StrictMock<MockProtocol> > protocol( new StrictMock<MockProtocol>()); URLContext context; OpenContext(protocol.get(), &context); // SEEK_SET should be a straight-through call to SetPosition(), which when // successful will return the result from GetPosition(). InSequence s; EXPECT_CALL(*protocol, SetPosition(-16)) .WillOnce(Return(false)); EXPECT_CALL(*protocol, SetPosition(16)) .WillOnce(Return(true)); EXPECT_CALL(*protocol, GetPosition(_)) .WillOnce(DoAll(SetArgumentPointee<0>(8), Return(true))); EXPECT_EQ(AVERROR(EIO), protocol_->url_seek(&context, -16, SEEK_SET)); EXPECT_EQ(8, protocol_->url_seek(&context, 16, SEEK_SET)); // SEEK_CUR should call GetPosition() first, and if it succeeds add the offset // to the result then call SetPosition()+GetPosition(). EXPECT_CALL(*protocol, GetPosition(_)) .WillOnce(Return(false)); EXPECT_CALL(*protocol, GetPosition(_)) .WillOnce(DoAll(SetArgumentPointee<0>(8), Return(true))); EXPECT_CALL(*protocol, SetPosition(16)) .WillOnce(Return(false)); EXPECT_CALL(*protocol, GetPosition(_)) .WillOnce(DoAll(SetArgumentPointee<0>(8), Return(true))); EXPECT_CALL(*protocol, SetPosition(16)) .WillOnce(Return(true)); EXPECT_CALL(*protocol, GetPosition(_)) .WillOnce(DoAll(SetArgumentPointee<0>(16), Return(true))); EXPECT_EQ(AVERROR(EIO), protocol_->url_seek(&context, 8, SEEK_CUR)); EXPECT_EQ(AVERROR(EIO), protocol_->url_seek(&context, 8, SEEK_CUR)); EXPECT_EQ(16, protocol_->url_seek(&context, 8, SEEK_CUR)); // SEEK_END should call GetSize() first, and if it succeeds add the offset // to the result then call SetPosition()+GetPosition(). EXPECT_CALL(*protocol, GetSize(_)) .WillOnce(Return(false)); EXPECT_CALL(*protocol, GetSize(_)) .WillOnce(DoAll(SetArgumentPointee<0>(16), Return(true))); EXPECT_CALL(*protocol, SetPosition(8)) .WillOnce(Return(false)); EXPECT_CALL(*protocol, GetSize(_)) .WillOnce(DoAll(SetArgumentPointee<0>(16), Return(true))); EXPECT_CALL(*protocol, SetPosition(8)) .WillOnce(Return(true)); EXPECT_CALL(*protocol, GetPosition(_)) .WillOnce(DoAll(SetArgumentPointee<0>(8), Return(true))); EXPECT_EQ(AVERROR(EIO), protocol_->url_seek(&context, -8, SEEK_END)); EXPECT_EQ(AVERROR(EIO), protocol_->url_seek(&context, -8, SEEK_END)); EXPECT_EQ(8, protocol_->url_seek(&context, -8, SEEK_END)); // AVSEEK_SIZE should be a straight-through call to GetSize(). EXPECT_CALL(*protocol, GetSize(_)) .WillOnce(Return(false)); EXPECT_CALL(*protocol, GetSize(_)) .WillOnce(DoAll(SetArgumentPointee<0>(16), Return(true))); EXPECT_EQ(AVERROR(EIO), protocol_->url_seek(&context, 0, AVSEEK_SIZE)); EXPECT_EQ(16, protocol_->url_seek(&context, 0, AVSEEK_SIZE)); // Destroy the protocol. protocol_->url_close(&context); } TEST_F(FFmpegGlueTest, Destroy) { // Create our protocol and add them to the glue layer. scoped_ptr<StrictMock<Destroyable<MockProtocol> > > protocol( new StrictMock<Destroyable<MockProtocol> >()); std::string key = FFmpegGlue::GetInstance()->AddProtocol(protocol.get()); // We should expect the protocol to get destroyed when the unit test // exits. InSequence s; EXPECT_CALL(*this, CheckPoint(0)); EXPECT_CALL(*protocol, OnDestroy()); // Remove our own reference, we shouldn't be destroyed yet. CheckPoint(0); protocol.reset(); // ~FFmpegGlue() will be called when this unit test finishes execution. By // leaving something inside FFmpegGlue's map we get to test our cleanup code. } } // namespace media
aYukiSekiguchi/ACCESS-Chromium
media/filters/ffmpeg_glue_unittest.cc
C++
bsd-3-clause
11,059
/****************************************************************************** * * File: csa.c * * Created: 16/10/2002 * * Author: Pavel Sakov * CSIRO Marine Research * * Purpose: 2D data approximation with bivariate C1 cubic spline. * A set of library functions + standalone utility. * * Description: See J. Haber, F. Zeilfelder, O.Davydov and H.-P. Seidel, * Smooth approximation and rendering of large scattered data * sets, in ``Proceedings of IEEE Visualization 2001'' * (Th.Ertl, K.Joy and A.Varshney, Eds.), pp.341-347, 571, * IEEE Computer Society, 2001. * http://www.uni-giessen.de/www-Numerische-Mathematik/ * davydov/VIS2001.ps.gz * http://www.math.uni-mannheim.de/~lsmath4/paper/ * VIS2001.pdf.gz * * Revisions: 09/04/2003 PS: Modified points_read() to read from a * file specified by name, not by handle. * 25/05/2009 PS: Added csa_approximatepoints2(). * *****************************************************************************/ #include <stdlib.h> #include <stdio.h> #include <stdarg.h> #include <limits.h> #include <float.h> #include <math.h> #include <assert.h> #include <string.h> #include <errno.h> #include "config.h" #include "nan.h" #include "svd.h" #include "csa.h" int csa_verbose = 0; #define NPASTART_S 10 /* Number of Points Allocated at Start for a * square */ #define NPASTART_T 100 /* Number of Points Allocated at Start for a * triangle */ /* default algorithm parameters */ #define NPMIN_DEF 3 #define NPMAX_DEF 40 #define K_DEF 140 #define NPPC_DEF 5 #define EPS 1.0e-15 struct square; typedef struct square square; typedef struct { square* parent; double xc, yc; double r; /* data visibility radius */ int nallocated; int npoints; point** points; double** std; } triangle; struct square { csa* parent; int i, j; /* indices */ double xmin, ymin; double xc, yc; int nallocated; int npoints; point** points; double** std; triangle* t; int primary; /* flag -- whether this square contains a * primary triangle */ int order; /* spline order */ int hascoeffs[4]; /* flag -- whether there are no NaNs among * the spline coefficients */ double coeffs[25]; }; struct csa { double xmin; double xmax; double ymin; double ymax; int npoints; point** points; int npointsallocated; int nstd; double** std; int nstdallocated; /* * squarization */ int ni; int nj; double h; square*** squares; /* square* [j][i] */ int npt; /* Number of Primary Triangles */ triangle** pt; /* Primary Triangles -- triangle* [npt] */ int nincreased; /* Number of sub-datasets thinned */ int nthinned; /* Number of sub-datasets increased */ int norder[4]; /* Number of fittings of given interpolation * order */ /* * algorithm parameters */ int npmin; /* minimal number of points locally involved * in spline calculation (normally = 3) */ int npmax; /* maximal number of points locally involved * in spline calculation (required > 10, * recommended 20 < npmax < 60) */ double k; /* relative tolerance multiple in fitting * spline coefficients: the higher this * value, the higher degree of the locally * fitted spline (recommended 80 < k < 200) */ int nppc; /* average number of points per cell */ }; static void quit(char* format, ...) { va_list args; fflush(stdout); /* just in case -- to have the exit message * last */ fprintf(stderr, "\nerror: csa: "); va_start(args, format); vfprintf(stderr, format, args); va_end(args); exit(1); } /* Allocates n1xn2 matrix of something. Note that it will be accessed as * [n2][n1]. * @param n1 Number of columns * @param n2 Number of rows * @return Matrix */ static void* alloc2d(int n1, int n2, size_t unitsize) { unsigned int size; char* p; char** pp; int i; if (n1 <= 0 || n2 <= 0) quit("alloc2d(): invalid size (n1 = %d, n2 = %d)\n", n1, n2); size = n1 * n2; if ((p = calloc(size, unitsize)) == NULL) quit("alloc2d(): %s\n", strerror(errno)); size = n2 * sizeof(void*); if ((pp = malloc(size)) == NULL) quit("alloc2d(): %s\n", strerror(errno)); for (i = 0; i < n2; i++) pp[i] = &p[i * n1 * unitsize]; return pp; } /* Destroys a matrix. * @param pp Matrix */ static void free2d(void* pp) { void* p; p = ((void**) pp)[0]; free(pp); free(p); } /* * `index' changes from 0 to 3, indicating position of the triangle within * the parent square: * ----- * | 1 | * |0 2| * | 3 | * ----- */ static triangle* triangle_create(square* s) { triangle* t = malloc(sizeof(triangle)); double h = s->parent->h; t->parent = s; t->xc = s->xmin + h / 6.0; t->yc = s->ymin + h / 2.0; t->r = 0.0; t->points = NULL; t->std = NULL; t->nallocated = 0; t->npoints = 0; return t; } static void triangle_addpoint(triangle* t, point* p, double* std) { if (t->nallocated == t->npoints) { if (t->nallocated == 0) { t->points = malloc(NPASTART_T * sizeof(point*)); t->nallocated = NPASTART_T; if (std != NULL) t->std = malloc(NPASTART_T * sizeof(double*)); } else { t->nallocated *= 2; t->points = realloc(t->points, t->nallocated * sizeof(point*)); if (std != NULL) t->std = realloc(t->std, t->nallocated * sizeof(double*)); } } t->points[t->npoints] = p; if (t->std != NULL) t->std[t->npoints] = std; t->npoints++; } static void triangle_destroy(triangle* t) { if (t->points != NULL) free(t->points); if (t->std != NULL) free(t->std); free(t); } /* Calculates barycentric coordinates of a point. * Takes into account that possible triangles are rectangular, with the right * angle at t->vertices[0], the vertices[1] vertex being in * (-3*PI/4) + (PI/2) * t->index direction from vertices[0], and * vertices[2] being at (-5*PI/4) + (PI/2) * t->index. */ static void triangle_calculatebc(square* s, int tindex, point* p, double bc[]) { double dx = p->x - s->xc; double dy = p->y - s->yc; double h = s->parent->h; if (tindex == 0) { bc[1] = (dy - dx) / h; bc[2] = -(dx + dy) / h; } else if (tindex == 1) { bc[1] = (dx + dy) / h; bc[2] = (dy - dx) / h; } else if (tindex == 2) { bc[1] = (dx - dy) / h; bc[2] = (dx + dy) / h; } else { bc[1] = -(dx + dy) / h; bc[2] = (dx - dy) / h; } bc[0] = 1.0 - bc[1] - bc[2]; } static square* square_create(csa* parent, double xmin, double ymin, int i, int j) { int ii; square* s = malloc(sizeof(square)); double h = parent->h; s->parent = parent; s->i = i; s->j = j; s->xmin = xmin; s->ymin = ymin; s->xc = xmin + h / 2.0; s->yc = ymin + h / 2.0; s->points = NULL; s->std = NULL; s->nallocated = 0; s->npoints = 0; s->t = triangle_create(s); s->primary = 0; s->order = -1; for (ii = 0; ii < 4; ++ii) s->hascoeffs[ii] = 0; for (ii = 0; ii < 25; ++ii) s->coeffs[ii] = NaN; return s; } static void square_destroy(square* s) { if (s->t != NULL) triangle_destroy(s->t); if (s->points != NULL) free(s->points); if (s->std != NULL) free(s->std); free(s); } static void square_addpoint(square* s, point* p, double* std) { if (s->nallocated == s->npoints) { if (s->nallocated == 0) { s->points = malloc(NPASTART_S * sizeof(point*)); if (std != NULL) s->std = malloc(NPASTART_S * sizeof(double*)); s->nallocated = NPASTART_S; } else { s->nallocated *= 2; s->points = realloc(s->points, s->nallocated * sizeof(point*)); if (std != NULL) s->std = realloc(s->std, s->nallocated * sizeof(double*)); } } s->points[s->npoints] = p; if (std != NULL) s->std[s->npoints] = std; s->npoints++; } csa* csa_create() { csa* a = malloc(sizeof(csa)); a->xmin = DBL_MAX; a->xmax = -DBL_MAX; a->ymin = DBL_MAX; a->ymax = -DBL_MAX; a->npoints = 0; a->points = malloc(NPASTART_T * sizeof(point*)); a->npointsallocated = NPASTART_T; a->std = NULL; a->nstd = 0; a->nstdallocated = 0; a->ni = 0; a->nj = 0; a->h = NaN; a->squares = NULL; a->npt = 0; a->pt = NULL; a->nincreased = 0; a->nthinned = 0; a->norder[0] = 0; a->norder[1] = 0; a->norder[2] = 0; a->norder[3] = 0; a->npmin = NPMIN_DEF; a->npmax = NPMAX_DEF; a->k = K_DEF; a->nppc = NPPC_DEF; svd_verbose = (csa_verbose > 1) ? 1 : 0; return a; } void csa_destroy(csa* a) { int i, j; if (a->squares != NULL) { for (j = 0; j < a->nj; ++j) for (i = 0; i < a->ni; ++i) square_destroy(a->squares[j][i]); free2d(a->squares); } if (a->pt != NULL) free(a->pt); if (a->points != NULL) free(a->points); if (a->std != NULL) free(a->std); free(a); } void csa_addpoints(csa* a, int n, point points[]) { int na = a->npointsallocated; int i; assert(a->squares == NULL); /* * (can be called prior to squarization only) */ while (na < a->npoints + n) na *= 2; if (na != a->npointsallocated) { a->points = realloc(a->points, na * sizeof(point*)); a->npointsallocated = na; } for (i = 0; i < n; ++i) { point* p = &points[i]; a->points[a->npoints] = p; a->npoints++; if (p->x < a->xmin) a->xmin = p->x; if (p->x > a->xmax) a->xmax = p->x; if (p->y < a->ymin) a->ymin = p->y; if (p->y > a->ymax) a->ymax = p->y; } } /* Adds std data. */ void csa_addstd(csa* a, int n, double std[]) { int na = a->nstdallocated; int i; if (std == NULL) return; if (a->std == NULL) { na = (n < NPASTART_S) ? NPASTART_S : n; a->std = malloc(na * sizeof(double*)); a->nstdallocated = na; } while (na < a->nstd + n) na *= 2; if (na != a->nstdallocated) { a->std = realloc(a->std, na * sizeof(double*)); a->nstdallocated = na; } for (i = 0; i < n; ++i) { assert(std[i] > 0.0); a->std[a->nstd] = &std[i]; a->nstd++; } } /* Marks the squares containing "primary" triangles by setting "primary" flag * to 1. */ static void csa_setprimaryflag(csa* a) { square*** squares = a->squares; int nj1 = a->nj - 1; int ni1 = a->ni - 1; int i, j; for (j = 1; j < nj1; ++j) { for (i = 1; i < ni1; ++i) { if (squares[j][i]->npoints > 0) { if ((i + j) % 2 == 0) { squares[j][i]->primary = 1; squares[j - 1][i - 1]->primary = 1; squares[j + 1][i - 1]->primary = 1; squares[j - 1][i + 1]->primary = 1; squares[j + 1][i + 1]->primary = 1; } else { squares[j - 1][i]->primary = 1; squares[j + 1][i]->primary = 1; squares[j][i - 1]->primary = 1; squares[j][i + 1]->primary = 1; } } } } } /* Splits the data domain in a number of squares. */ static void csa_squarize(csa* a) { int nps[7] = { 0, 0, 0, 0, 0, 0 }; /* stats on number of points per * square */ double dx = a->xmax - a->xmin; double dy = a->ymax - a->ymin; int npoints = a->npoints; double h; int i, j, ii, nadj; if (csa_verbose) { fprintf(stderr, "squarizing:\n"); fflush(stderr); } if (npoints == 0) return; assert(a->squares == NULL); /* * (can be done only once) */ h = sqrt(dx * dy * a->nppc / npoints); /* square edge size */ if (dx < h) h = dy * a->nppc / npoints; if (dy < h) h = dx * a->nppc / npoints; a->h = h; a->ni = (int) ceil(dx / h) + 2; a->nj = (int) ceil(dy / h) + 2; if (csa_verbose) { fprintf(stderr, " %d x %d squares\n", a->ni, a->nj); fflush(stderr); } /* * create squares */ a->squares = alloc2d(a->ni, a->nj, sizeof(void*)); for (j = 0; j < a->nj; ++j) for (i = 0; i < a->ni; ++i) a->squares[j][i] = square_create(a, a->xmin + h * (i - 1), a->ymin + h * (j - 1), i, j); /* * map points to squares */ for (ii = 0; ii < npoints; ++ii) { point* p = a->points[ii]; i = (int) floor((p->x - a->xmin) / h) + 1; j = (int) floor((p->y - a->ymin) / h) + 1; square_addpoint(a->squares[j][i], p, (a->std == NULL) ? NULL : a->std[ii]); } /* * mark relevant squares with no points */ csa_setprimaryflag(a); /* * Create a list of "primary" triangles, for which spline coefficients * will be calculated directy (by least squares method), without using * C1 smoothness conditions. */ a->pt = malloc((a->ni / 2 + 1) * a->nj * sizeof(triangle*)); for (j = 0, ii = 0, nadj = 0; j < a->nj; ++j) { for (i = 0; i < a->ni; ++i) { square* s = a->squares[j][i]; if (s->npoints > 0) { int nn = s->npoints / 5; if (nn > 6) nn = 6; nps[nn]++; ii++; } if (s->primary && s->npoints == 0) nadj++; if (s->primary) { a->pt[a->npt] = s->t; a->npt++; } } } assert(a->npt > 0); if (csa_verbose) { fprintf(stderr, " %d non-empty squares\n", ii); fprintf(stderr, " %d primary squares\n", a->npt); fprintf(stderr, " %d primary squares with no data\n", nadj); fprintf(stderr, " %.2f points per square \n", (double) a->npoints / ii); } if (csa_verbose == 2) { for (i = 0; i < 6; ++i) fprintf(stderr, " %d-%d points -- %d squares\n", i * 5, i * 5 + 4, nps[i]); fprintf(stderr, " %d or more points -- %d squares\n", i * 5, nps[i]); } if (csa_verbose == 2) { fprintf(stderr, " j\\i"); for (i = 0; i < a->ni; ++i) fprintf(stderr, "%3d ", i); fprintf(stderr, "\n"); for (j = a->nj - 1; j >= 0; --j) { fprintf(stderr, "%3d ", j); for (i = 0; i < a->ni; ++i) { square* s = a->squares[j][i]; if (s->npoints > 0) fprintf(stderr, "%3d ", s->npoints); else fprintf(stderr, " . "); } fprintf(stderr, "\n"); } } /* * all necessary data is now copied to squares; * release redundant memory in the host structure */ free(a->points); a->points = NULL; a->npoints = 0; if (a->std != NULL) { free(a->std); a->std = NULL; } if (csa_verbose) fflush(stderr); } /* Returns all squares intersecting with a square with center in t->middle * and edges of length 2*t->r parallel to X and Y axes. */ static void getsquares(csa* a, triangle* t, int* n, square*** squares) { double h = t->parent->parent->h; int imin = (int) floor((t->xc - t->r - a->xmin) / h); int imax = (int) ceil((t->xc + t->r - a->xmin) / h); int jmin = (int) floor((t->yc - t->r - a->ymin) / h); int jmax = (int) ceil((t->yc + t->r - a->ymin) / h); int i, j; if (imin < 0) imin = 0; if (imax >= a->ni) imax = a->ni - 1; if (jmin < 0) jmin = 0; if (jmax >= a->nj) jmax = a->nj - 1; *n = 0; (*squares) = malloc((imax - imin + 1) * (jmax - jmin + 1) * sizeof(square*)); for (j = jmin; j <= jmax; ++j) { for (i = imin; i <= imax; ++i) { square* s = a->squares[j][i]; if (s->npoints > 0) { (*squares)[*n] = a->squares[j][i]; (*n)++; } } } } static double distance(point* p1, point* p2) { return hypot(p1->x - p2->x, p1->y - p2->y); } static double distance_xy(double x1, double y1, double x2, double y2) { return hypot(x1 - x2, y1 - y2); } /* Thins data by creating an auxiliary regular grid and leaving only the most * central point within each grid cell. * (I follow the paper here. It is possible that taking average -- in terms of * both value and position -- of all points within a cell would be a bit more * robust. However, because of keeping only shallow copies of input points, * this would require quite a bit of structural changes. So, leaving it as is * for now.) */ static void thindata(triangle* t, int npmax) { csa* a = t->parent->parent; int imax = (int) ceil(sqrt((double) (npmax * 3 / 2))); square*** squares = alloc2d(imax, imax, sizeof(void*)); double h = t->r * 2.0 / imax; double h2 = h / 2.0; double xmin = t->xc - t->r; double ymin = t->yc - t->r; int i, j, ii; for (j = 0; j < imax; ++j) for (i = 0; i < imax; ++i) squares[j][i] = square_create(a, xmin + h * i, ymin + h * j, i, j); for (ii = 0; ii < t->npoints; ++ii) { point* p = t->points[ii]; int i = (int) floor((p->x - xmin) / h); int j = (int) floor((p->y - ymin) / h); square* s = squares[j][i]; if (s->npoints == 0) square_addpoint(s, p, (t->std == NULL) ? NULL : t->std[ii]); else { /* npoints == 1 */ point pmiddle; pmiddle.x = xmin + h * i + h2; pmiddle.y = ymin + h * j + h2; if (s->std == NULL) { if (distance(s->points[0], &pmiddle) > distance(p, &pmiddle)) s->points[0] = p; } else { if ((*t->std[ii] < *s->std[0]) || (*t->std[ii] == *s->std[0] && distance(s->points[0], &pmiddle) > distance(p, &pmiddle))) { s->points[0] = p; s->std[0] = t->std[ii]; } } } } t->npoints = 0; for (j = 0; j < imax; ++j) { for (i = 0; i < imax; ++i) { square* s = squares[j][i]; if (squares[j][i]->npoints != 0) triangle_addpoint(t, s->points[0], (s->std == NULL) ? NULL : s->std[0]); square_destroy(s); } } free2d(squares); imax++; } /* Finds data points to be used in calculating spline coefficients for each * primary triangle. */ static void csa_attachpointstriangle(csa* a, triangle* t) { int increased = 0; if (csa_verbose) { fprintf(stderr, "."); fflush(stderr); } t->r = a->h * 1.25; while (1) { int nsquares = 0; square** squares = NULL; int ii; getsquares(a, t, &nsquares, &squares); for (ii = 0; ii < nsquares; ++ii) { square* s = squares[ii]; int iii; for (iii = 0; iii < s->npoints; ++iii) { point* p = s->points[iii]; if (distance_xy(p->x, p->y, t->xc, t->yc) <= t->r) triangle_addpoint(t, p, (s->std == NULL) ? NULL : s->std[iii]); } } free(squares); if (t->npoints < a->npmin) { if (!increased) { increased = 1; a->nincreased++; } t->r *= 1.25; t->npoints = 0; } else if (t->npoints > a->npmax) { a->nthinned++; thindata(t, a->npmax); if (t->npoints > a->npmin) break; else { /* * Sometimes you have too much data, you thin it and -- * oops -- you have too little. This is not a frequent * event, so let us not bother to put a new subdivision. */ t->r *= 1.25; t->npoints = 0; } } else break; } } static int n2q(int n) { assert(n >= 3); if (n >= 10) return 3; else if (n >= 6) return 2; else /* n == 3 */ return 1; } /* * square->coeffs[]: * * --------------------- * | 3 10 17 24 | * | 6 13 20 | * | 2 9 16 23 | * | 5 12 19 | * | 1 8 15 22 | * | 4 11 18 | * | 0 7 14 21 | * --------------------- */ static void csa_findprimarycoeffstriangle(csa* a, triangle* t) { square* s = t->parent; int npoints = t->npoints; point** points = t->points; double* z = malloc(npoints * sizeof(double)); double* std = NULL; int q = n2q(t->npoints); int ok = 1; double b[10]; double b1[6]; int ii; if (csa_verbose) { fprintf(stderr, "."); fflush(stderr); } for (ii = 0; ii < npoints; ++ii) z[ii] = points[ii]->z; if (t->std != NULL) { std = malloc(npoints * sizeof(double)); for (ii = 0; ii < npoints; ++ii) std[ii] = *t->std[ii]; } do { double bc[3]; double wmin, wmax; if (!ok) q--; assert(q >= 0); if (q == 3) { double** A = alloc2d(10, npoints, sizeof(double)); double w[10]; for (ii = 0; ii < npoints; ++ii) { double* aii = A[ii]; double tmp; triangle_calculatebc(s, 0, points[ii], bc); /* * 0 1 2 3 4 5 6 7 8 9 * 300 210 201 120 111 102 030 021 012 003 */ tmp = bc[0] * bc[0]; aii[0] = tmp * bc[0]; tmp *= 3.0; aii[1] = tmp * bc[1]; aii[2] = tmp * bc[2]; tmp = bc[1] * bc[1]; aii[6] = tmp * bc[1]; tmp *= 3.0; aii[3] = tmp * bc[0]; aii[7] = tmp * bc[2]; tmp = bc[2] * bc[2]; aii[9] = tmp * bc[2]; tmp *= 3.0; aii[5] = tmp * bc[0]; aii[8] = tmp * bc[1]; aii[4] = bc[0] * bc[1] * bc[2] * 6.0; } svd_lsq(A, 10, npoints, z, std, w, b); wmin = w[0]; wmax = w[0]; for (ii = 1; ii < 10; ++ii) { if (w[ii] < wmin) wmin = w[ii]; else if (w[ii] > wmax) wmax = w[ii]; } if (wmin < wmax / a->k) ok = 0; free2d(A); } else if (q == 2) { double** A = alloc2d(6, npoints, sizeof(double)); double w[6]; for (ii = 0; ii < npoints; ++ii) { double* aii = A[ii]; triangle_calculatebc(s, 0, points[ii], bc); /* * 0 1 2 3 4 5 * 200 110 101 020 011 002 */ aii[0] = bc[0] * bc[0]; aii[1] = bc[0] * bc[1] * 2.0; aii[2] = bc[0] * bc[2] * 2.0; aii[3] = bc[1] * bc[1]; aii[4] = bc[1] * bc[2] * 2.0; aii[5] = bc[2] * bc[2]; } svd_lsq(A, 6, npoints, z, std, w, b1); wmin = w[0]; wmax = w[0]; for (ii = 1; ii < 6; ++ii) { if (w[ii] < wmin) wmin = w[ii]; else if (w[ii] > wmax) wmax = w[ii]; } if (wmin < wmax / a->k) ok = 0; else { /* degree raising */ ok = 1; b[0] = b1[0]; b[1] = (b1[0] + 2.0 * b1[1]) / 3.0; b[2] = (b1[0] + 2.0 * b1[2]) / 3.0; b[3] = (b1[3] + 2.0 * b1[1]) / 3.0; b[4] = (b1[1] + b1[2] + b1[4]) / 3.0; b[5] = (b1[5] + 2.0 * b1[2]) / 3.0; b[6] = b1[3]; b[7] = (b1[3] + 2.0 * b1[4]) / 3.0; b[8] = (b1[5] + 2.0 * b1[4]) / 3.0; b[9] = b1[5]; } free2d(A); } else if (q == 1) { double** A = alloc2d(3, npoints, sizeof(double)); double w[3]; for (ii = 0; ii < npoints; ++ii) { double* aii = A[ii]; triangle_calculatebc(s, 0, points[ii], bc); aii[0] = bc[0]; aii[1] = bc[1]; aii[2] = bc[2]; } svd_lsq(A, 3, npoints, z, std, w, b1); wmin = w[0]; wmax = w[0]; for (ii = 1; ii < 3; ++ii) { if (w[ii] < wmin) wmin = w[ii]; else if (w[ii] > wmax) wmax = w[ii]; } if (wmin < wmax / a->k) ok = 0; else { /* degree raising */ ok = 1; b[0] = b1[0]; b[1] = (2.0 * b1[0] + b1[1]) / 3.0; b[2] = (2.0 * b1[0] + b1[2]) / 3.0; b[3] = (2.0 * b1[1] + b1[0]) / 3.0; b[4] = (b1[0] + b1[1] + b1[2]) / 3.0; b[5] = (2.0 * b1[2] + b1[0]) / 3.0; b[6] = b1[1]; b[7] = (2.0 * b1[1] + b1[2]) / 3.0; b[8] = (2.0 * b1[2] + b1[1]) / 3.0; b[9] = b1[2]; } free2d(A); } else if (q == 0) { double** A = alloc2d(1, npoints, sizeof(double)); double w[1]; for (ii = 0; ii < npoints; ++ii) A[ii][0] = 1.0; svd_lsq(A, 1, npoints, z, std, w, b1); ok = 1; b[0] = b1[0]; b[1] = b1[0]; b[2] = b1[0]; b[3] = b1[0]; b[4] = b1[0]; b[5] = b1[0]; b[6] = b1[0]; b[7] = b1[0]; b[8] = b1[0]; b[9] = b1[0]; free2d(A); } } while (!ok); a->norder[q]++; s->order = q; { square* s = t->parent; double* coeffs = s->coeffs; coeffs[12] = b[0]; coeffs[9] = b[1]; coeffs[6] = b[3]; coeffs[3] = b[6]; coeffs[2] = b[7]; coeffs[1] = b[8]; coeffs[0] = b[9]; coeffs[4] = b[5]; coeffs[8] = b[2]; coeffs[5] = b[4]; } free(z); if (std != NULL) free(std); if (t->points != NULL) { free(t->points); t->points = NULL; t->npoints = 0; t->nallocated = 0; } if (t->std != NULL) { free(t->std); t->std = NULL; } } /* Calculates spline coefficients in each primary triangle by least squares * fitting to data attached by csa_attachpointstriangle(). */ static void csa_findprimarycoeffs(csa* a) { int i; if (csa_verbose) fprintf(stderr, "calculating spline coefficients for primary triangles:\n "); for (i = 0; i < a->npt; ++i) { triangle* t = a->pt[i]; csa_attachpointstriangle(a, t); csa_findprimarycoeffstriangle(a, t); } if (csa_verbose) { fprintf(stderr, "\n 3rd order -- %d sets\n", a->norder[3]); fprintf(stderr, " 2nd order -- %d sets\n", a->norder[2]); fprintf(stderr, " 1st order -- %d sets\n", a->norder[1]); fprintf(stderr, " 0th order -- %d sets\n", a->norder[0]); fflush(stderr); } if (csa_verbose == 2) { int j; fprintf(stderr, " j\\i"); for (i = 0; i < a->ni; ++i) fprintf(stderr, "%2d ", i); fprintf(stderr, "\n"); for (j = a->nj - 1; j >= 0; --j) { fprintf(stderr, "%2d ", j); for (i = 0; i < a->ni; ++i) { square* s = a->squares[j][i]; if (s->primary) fprintf(stderr, "%2d ", s->order); else fprintf(stderr, " . "); } fprintf(stderr, "\n"); } } } /* Finds spline coefficients in (adjacent to primary triangles) secondary * triangles from C1 smoothness conditions. */ static void csa_findsecondarycoeffs(csa* a) { square*** squares = a->squares; int ni = a->ni; int nj = a->nj; int ii; if (csa_verbose) { fprintf(stderr, "propagating spline coefficients to the remaining triangles:\n"); fflush(stderr); } /* * red */ for (ii = 0; ii < a->npt; ++ii) { triangle* t = a->pt[ii]; square* s = t->parent; int i = s->i; int j = s->j; double* c = s->coeffs; double* cl = (i > 0) ? squares[j][i - 1]->coeffs : NULL; double* cb = (j > 0) ? squares[j - 1][i]->coeffs : NULL; double* cbl = (i > 0 && j > 0) ? squares[j - 1][i - 1]->coeffs : NULL; double* ca = (j < nj - 1) ? squares[j + 1][i]->coeffs : NULL; double* cal = (j < nj - 1 && i > 0) ? squares[j + 1][i - 1]->coeffs : NULL; c[7] = 2.0 * c[4] - c[1]; c[11] = 2.0 * c[8] - c[5]; c[15] = 2.0 * c[12] - c[9]; c[10] = 2.0 * c[6] - c[2]; c[13] = 2.0 * c[9] - c[5]; c[16] = 2.0 * c[12] - c[8]; c[19] = 2.0 * c[15] - c[11]; if (cl != NULL) { cl[21] = c[0]; cl[22] = c[1]; cl[23] = c[2]; cl[24] = c[3]; cl[18] = c[0] + c[1] - c[4]; cl[19] = c[1] + c[2] - c[5]; cl[20] = c[2] + c[3] - c[6]; cl[17] = 2.0 * cl[20] - cl[23]; cl[14] = 2.0 * cl[18] - cl[22]; } if (cb != NULL) { cb[3] = c[0]; cb[10] = c[7]; cb[6] = c[0] + c[7] - c[4]; cb[2] = 2.0 * cb[6] - cb[10]; } if (cbl != NULL) { cbl[23] = cb[2]; cbl[24] = cb[3]; cbl[20] = cb[2] + cb[3] - cb[6]; cbl[17] = cl[14]; } if (ca != NULL) { ca[0] = c[3]; ca[7] = c[10]; ca[4] = c[3] + c[10] - c[6]; ca[1] = 2.0 * ca[4] - ca[7]; } if (cal != NULL) { cal[21] = c[3]; cal[22] = ca[1]; cal[18] = ca[0] + ca[1] - ca[4]; cal[14] = cl[17]; } } /* * blue */ for (ii = 0; ii < a->npt; ++ii) { triangle* t = a->pt[ii]; square* s = t->parent; int i = s->i; int j = s->j; double* c = s->coeffs; double* cr = (i < ni - 1) ? squares[j][i + 1]->coeffs : NULL; double* car = (i < ni - 1 && j < nj - 1) ? squares[j + 1][i + 1]->coeffs : NULL; double* cbr = (i < ni - 1 && j > 0) ? squares[j - 1][i + 1]->coeffs : NULL; if (car != NULL) cr[13] = car[7] + car[14] - car[11]; if (cbr != NULL) cr[11] = cbr[10] + cbr[17] - cbr[13]; if (cr != NULL) cr[5] = c[22] + c[23] - c[19]; } /* * green & yellow */ for (ii = 0; ii < a->npt; ++ii) { triangle* t = a->pt[ii]; square* s = t->parent; int i = s->i; int j = s->j; double* cr = (i < ni - 1) ? squares[j][i + 1]->coeffs : NULL; if (cr != NULL) { cr[9] = (cr[5] + cr[13]) / 2.0; cr[8] = (cr[5] + cr[11]) / 2.0; cr[15] = (cr[11] + cr[19]) / 2.0; cr[16] = (cr[13] + cr[19]) / 2.0; cr[12] = (cr[8] + cr[16]) / 2.0; } } if (csa_verbose) { fprintf(stderr, "checking that all coefficients have been set:\n"); fflush(stderr); } for (ii = 0; ii < ni * nj; ++ii) { square* s = squares[0][ii]; double* c = s->coeffs; int i; if (s->npoints == 0) continue; for (i = 0; i < 25; ++i) if (isnan(c[i])) fprintf(stderr, " squares[%d][%d]->coeffs[%d] = NaN\n", s->j, s->i, i); } } static int i300[] = { 12, 12, 12, 12 }; static int i030[] = { 3, 24, 21, 0 }; static int i003[] = { 0, 3, 24, 21 }; static int i210[] = { 9, 16, 15, 8 }; static int i021[] = { 2, 17, 22, 7 }; static int i102[] = { 4, 6, 20, 18 }; static int i120[] = { 6, 20, 18, 4 }; static int i012[] = { 1, 10, 23, 14 }; static int i201[] = { 8, 9, 16, 15 }; static int i111[] = { 5, 13, 19, 11 }; static int* iall[] = { i300, i030, i003, i210, i021, i102, i120, i012, i201, i111 }; static void csa_sethascoeffsflag(csa* a) { int i, j; for (j = 0; j < a->nj; ++j) { for (i = 0; i < a->ni; ++i) { square* s = a->squares[j][i]; double* coeffs = s->coeffs; int ii; for (ii = 0; ii < 4; ++ii) { int cc; for (cc = 0; cc < 10; ++cc) if (isnan(coeffs[iall[cc][ii]])) break; if (cc == 10) s->hascoeffs[ii] = 1; } } } } void csa_calculatespline(csa* a) { if (a->std != NULL) assert(a->nstd == a->npoints); csa_squarize(a); csa_findprimarycoeffs(a); csa_findsecondarycoeffs(a); csa_sethascoeffsflag(a); } void csa_approximatepoint(csa* a, point* p) { double h = a->h; double ii = (p->x - a->xmin) / h + 1.0; double jj = (p->y - a->ymin) / h + 1.0; int i, j; square* s; double fi, fj; int ti; double bc[3]; if (a->squares == NULL) quit("csa_approximatepoint(): csa_calculatespline() had to be called\n"); if (fabs(rint(ii) - ii) / h < EPS) ii = rint(ii); if (fabs(rint(jj) - jj) / h < EPS) jj = rint(jj); if (ii < 0.0 || jj < 0.0 || ii > (double) a->ni - 1.0 || jj > (double) a->nj - 1.0) { p->z = NaN; return; } i = (int) floor(ii); j = (int) floor(jj); s = a->squares[j][i]; fi = ii - i; fj = jj - j; if (fj < fi) { if (fi + fj < 1.0) ti = 3; else ti = 2; } else { if (fi + fj < 1.0) ti = 0; else ti = 1; } if (!s->hascoeffs[ti]) { p->z = NaN; return; } triangle_calculatebc(s, ti, p, bc); { double* c = s->coeffs; double bc1 = bc[0]; double bc2 = bc[1]; double bc3 = bc[2]; double tmp1 = bc1 * bc1; double tmp2 = bc2 * bc2; double tmp3 = bc3 * bc3; switch (ti) { case 0: p->z = c[12] * bc1 * tmp1 + c[3] * bc2 * tmp2 + c[0] * bc3 * tmp3 + 3.0 * (c[9] * tmp1 * bc2 + c[2] * tmp2 * bc3 + c[4] * tmp3 * bc1 + c[6] * bc1 * tmp2 + c[1] * bc2 * tmp3 + c[8] * tmp1 * bc3) + 6.0 * c[5] * bc1 * bc2 * bc3; break; case 1: p->z = c[12] * bc1 * tmp1 + c[24] * bc2 * tmp2 + c[3] * bc3 * tmp3 + 3.0 * (c[16] * tmp1 * bc2 + c[17] * tmp2 * bc3 + c[6] * tmp3 * bc1 + c[20] * bc1 * tmp2 + c[10] * bc2 * tmp3 + c[9] * tmp1 * bc3) + 6.0 * c[13] * bc1 * bc2 * bc3; break; case 2: p->z = c[12] * bc1 * tmp1 + c[21] * bc2 * tmp2 + c[24] * bc3 * tmp3 + 3.0 * (c[15] * tmp1 * bc2 + c[22] * tmp2 * bc3 + c[20] * tmp3 * bc1 + c[18] * bc1 * tmp2 + c[23] * bc2 * tmp3 + c[16] * tmp1 * bc3) + 6.0 * c[19] * bc1 * bc2 * bc3; break; default: /* 3 */ p->z = c[12] * bc1 * tmp1 + c[0] * bc2 * tmp2 + c[21] * bc3 * tmp3 + 3.0 * (c[8] * tmp1 * bc2 + c[7] * tmp2 * bc3 + c[18] * tmp3 * bc1 + c[4] * bc1 * tmp2 + c[14] * bc2 * tmp3 + c[15] * tmp1 * bc3) + 6.0 * c[11] * bc1 * bc2 * bc3; } } } void csa_approximatepoints(csa* a, int n, point* points) { int ii; for (ii = 0; ii < n; ++ii) csa_approximatepoint(a, &points[ii]); } void csa_setnpmin(csa* a, int npmin) { a->npmin = npmin; } void csa_setnpmax(csa* a, int npmax) { a->npmax = npmax; } void csa_setk(csa* a, int k) { a->k = k; } void csa_setnppc(csa* a, int nppc) { a->nppc = nppc; } /** Approximates data in given locations. Specially for Rob. Allocates the ** output array - needs to be cleaned up by the calling code. * @param nin - number of input data points * @param xin - X coordinates of input data points [nin] * @param yin - Y coordinates of input data points [nin] * @param zin - Z coordinates of input data points [nin] * @param sigma - standard deviations of input data (optional) [nin]; or NULL * @param nout - number of output data points * @param xout - X coordinates of output data points [nout] * @param yout - Y coordinates of output data points [nout] * @param npmin - algorithm parameter NPMIN; 0 for default * @param npmax - algorithm parameter NPMAX; 0 for default * @param k - algorithm parameter K; 0.0 for default * @param nppc - algorithm parameter NPPC; 0 for default * @return - Z coordinates of output data points [nout] - to be deallocated by * the calling code */ double* csa_approximatepoints2(int nin, double xin[], double yin[], double zin[], double sigma[], int nout, double xout[], double yout[], int npmin, int npmax, int k, int nppc) { point* pin = NULL; point* pout = NULL; csa* a = NULL; double* zout = NULL; int ii; if (nin <= 0 || nout <= 0) return zout; /* * create approximator */ a = csa_create(); if (npmin > 0) csa_setnpmin(a, npmin); if (npmax > 0 && npmax > npmin) csa_setnpmax(a, npmax); if (k > 0.0) csa_setk(a, k); if (nppc > 0) csa_setnppc(a, nppc); /* * read input data into point array */ pin = malloc(sizeof(point) * nin); for (ii = 0; ii < nin; ++ii) { point* p = &pin[ii]; p->x = xin[ii]; p->y = yin[ii]; p->z = zin[ii]; } csa_addpoints(a, nin, pin); if (sigma != NULL) csa_addstd(a, nin, sigma); /* * calculate spline */ csa_calculatespline(a); /* * read ioutput data into point array */ pout = malloc(sizeof(point) * nout); for (ii = 0; ii < nout; ++ii) { point* p = &pout[ii]; p->x = xout[ii]; p->y = yout[ii]; p->z = NaN; } /* * approximate */ csa_approximatepoints(a, nout, pout); /* * write results to the output array */ zout = malloc(nout * sizeof(double)); for (ii = 0; ii < nout; ++ii) zout[ii] = pout[ii].z; /* * clean up */ csa_destroy(a); free(pin); free(pout); return zout; } #if defined(CSA_STANDALONE) #include "minell.h" #define NIMAX 2048 #define BUFSIZE 10240 #define STRBUFSIZE 64 static void points_generate(double xmin, double xmax, double ymin, double ymax, int nx, int ny, int* nout, point** pout) { double stepx, stepy; double x0, xx, yy; int i, j, ii; if (nx < 1 || ny < 1) { *pout = NULL; *nout = 0; return; } *nout = nx * ny; *pout = malloc(*nout * sizeof(point)); stepx = (nx > 1) ? (xmax - xmin) / (nx - 1) : 0.0; stepy = (ny > 1) ? (ymax - ymin) / (ny - 1) : 0.0; x0 = (nx > 1) ? xmin : (xmin + xmax) / 2.0; yy = (ny > 1) ? ymin : (ymin + ymax) / 2.0; ii = 0; for (j = 0; j < ny; ++j) { xx = x0; for (i = 0; i < nx; ++i) { point* p = &(*pout)[ii]; p->x = xx; p->y = yy; xx += stepx; ii++; } yy += stepy; } } static int str2double(char* token, double* value) { char* end = NULL; if (token == NULL) { *value = NaN; return 0; } *value = strtod(token, &end); if (end == token) { *value = NaN; return 0; } return 1; } #define NALLOCATED_START 1024 /* Reads array of points from a columnar file. * * @param fname File name (can be "stdin" or "-" for standard input) * @param dim Number of dimensions (must be 2 or 3) * @param n Pointer to number of points (output) * @param points Pointer to array of points [*n] (output) (to be freed) * @param std Pointer to array of data std (to be freed) */ static void points_read(char* fname, int dim, int* n, point** points, double** std) { FILE* f = NULL; int nallocated = NALLOCATED_START; char buf[BUFSIZE]; char seps[] = " ,;\t"; char* token; double stdval = NaN; if (dim < 2 || dim > 3) { *n = 0; *points = NULL; return; } if (fname == NULL) f = stdin; else { if (strcmp(fname, "stdin") == 0 || strcmp(fname, "-") == 0) f = stdin; else { f = fopen(fname, "r"); if (f == NULL) quit("%s: %s\n", fname, strerror(errno)); } } *points = malloc(nallocated * sizeof(point)); *n = 0; while (fgets(buf, BUFSIZE, f) != NULL) { point* p; if (*n == nallocated) { nallocated *= 2; *points = realloc(*points, nallocated * sizeof(point)); if (std != NULL && *std != NULL) *std = realloc(*std, nallocated * sizeof(double)); } p = &(*points)[*n]; if (buf[0] == '#') continue; if ((token = strtok(buf, seps)) == NULL) continue; if (!str2double(token, &p->x)) continue; if ((token = strtok(NULL, seps)) == NULL) continue; if (!str2double(token, &p->y)) continue; if (dim == 2) p->z = NaN; else { /* * z */ if ((token = strtok(NULL, seps)) == NULL) continue; if (!str2double(token, &p->z)) continue; /* * std */ if (std == NULL) continue; if (*n == 0) { if ((token = strtok(NULL, seps)) != NULL) *std = malloc(nallocated * sizeof(double)); if (csa_verbose) fprintf(stderr, "%s std data\n", (token != NULL) ? "found" : "no"); } if (*std != NULL) { if (*n != 0) token = strtok(NULL, seps); if (token != NULL && !str2double(token, &stdval)) quit("%s: could not convert \"%s\" to std\n", fname, token); (*std)[*n] = stdval; } } (*n)++; } if (*n == 0) { free(*points); *points = NULL; } else *points = realloc(*points, *n * sizeof(point)); if (std != NULL && *std != NULL) *std = realloc(*std, *n * sizeof(point)); if (f != stdin) if (fclose(f) != 0) quit("%s: %s\n", fname, strerror(errno)); } static void points_write(int n, point* points) { int i; if (csa_verbose) printf("Output:\n"); for (i = 0; i < n; ++i) { point* p = &points[i]; printf("%.15g %.15g %.15g\n", p->x, p->y, p->z); } } static double points_scaletosquare(int n, point* points) { double xmin, ymin, xmax, ymax; double k; int i; if (n <= 0) return NaN; xmin = xmax = points[0].x; ymin = ymax = points[0].y; for (i = 1; i < n; ++i) { point* p = &points[i]; if (p->x < xmin) xmin = p->x; else if (p->x > xmax) xmax = p->x; if (p->y < ymin) ymin = p->y; else if (p->y > ymax) ymax = p->y; } if (xmin == xmax || ymin == ymax) return NaN; else k = (ymax - ymin) / (xmax - xmin); for (i = 0; i < n; ++i) points[i].y /= k; return k; } static void points_scale(int n, point* points, double k) { int i; for (i = 0; i < n; ++i) points[i].y /= k; } static void usage() { printf("Usage: csabathy -i <XYZ file> {-o <XY file>|-n <nx>x<ny> [-c|-s] [-z <zoom>]}\n"); printf(" [-v|-V] [-P nppc=<value>] [-P k=<value>]\n"); printf("Options:\n"); printf(" -c -- scale internally so that the minimal ellipse turns into a\n"); printf(" circle\n"); printf(" -i <XYZ file> -- three-column file with points to approximate from (use\n"); printf(" \"-i stdin\" or \"-i -\" for standard input) (an optional\n"); printf(" fourth column with estimated sqrt(variance) is allowed;\n"); printf(" this data will be taken into account at spline fitting\n"); printf(" stage)\n"); printf(" -n <nx>x<ny> -- generate <nx>x<ny> output rectangular grid\n"); printf(" -o <XY file> -- two-column file with points to approximate in (use\n"); printf(" \"-o stdin\" or \"-o -\" for standard input)\n"); printf(" -s -- scale internally so that Xmax - Xmin = Ymax - Ymin\n"); printf(" -v -- verbose / version\n"); printf(" -z <zoom> -- zoom in (if <zoom> < 1) or out (<zoom> > 1) (activated\n"); printf(" only when used in conjunction with -n)\n"); printf(" -P nppc=<value> -- set the average number of points per cell (default = 5,\n"); printf(" works best for uniform data. Decrease to get smaller\n"); printf(" cells or increase to get larger cells)\n"); printf(" -P k=<value> -- set the spline sensitivity (default = 140, reduce to get\n"); printf(" smoother results)\n"); printf(" -V -- very verbose / version\n"); printf("Description:\n"); printf(" `csabathy' approximates irregular scalar 2D data in specified points using\n"); printf(" C1-continuous bivariate cubic spline. The calculated values are written to\n"); printf(" standard output.\n"); exit(0); } static void version() { exit(0); } static void parse_commandline(int argc, char* argv[], char** fdata, char** fpoints, int* invariant, int* square, int* generate_points, int* nx, int* ny, int* nppc, int* k, double* zoom) { int i; if (argc < 2) usage(); i = 1; while (i < argc) { if (argv[i][0] != '-') usage(); switch (argv[i][1]) { case 'c': i++; *invariant = 1; *square = 0; break; case 'i': i++; if (i >= argc) quit("no file name found after -i\n"); *fdata = argv[i]; i++; break; case 'n': i++; *fpoints = NULL; *generate_points = 1; if (i >= argc) quit("no grid dimensions found after -n\n"); if (sscanf(argv[i], "%dx%d", nx, ny) != 2) quit("could not read grid dimensions after \"-n\"\n"); if (*nx <= 0 || *nx > NIMAX || *ny <= 0 || *ny > NIMAX) quit("invalid size for output grid\n"); i++; break; case 'o': i++; if (i >= argc) quit("no file name found after -o\n"); *fpoints = argv[i]; i++; break; case 's': i++; *square = 1; *invariant = 0; break; case 'v': i++; csa_verbose = 1; break; case 'z': i++; if (i >= argc) quit("no zoom value found after -z\n"); *zoom = atof(argv[i]); i++; break; case 'P':{ char delim[] = "="; char prmstr[STRBUFSIZE] = ""; char* token; i++; if (i >= argc) quit("no input found after -P\n"); if (strlen(argv[i]) >= STRBUFSIZE) quit("could not interpret \"%s\" after -P option\n", argv[i]); strcpy(prmstr, argv[i]); token = strtok(prmstr, delim); if (token == NULL) quit("could not interpret \"%s\" after -P option\n", argv[i]); if (strcmp(token, "nppc") == 0) { long int n; token = strtok(NULL, delim); if (token == NULL) quit("could not interpret \"%s\" after -P option\n", argv[i]); n = strtol(token, NULL, 10); if (n == LONG_MIN || n == LONG_MAX) quit("could not interpret \"%s\" after -P option\n", argv[i]); else if (n <= 0) quit("non-sensible value for \"nppc\" parameter\n"); *nppc = (int) n; } else if (strcmp(token, "k") == 0) { long int n; token = strtok(NULL, delim); if (token == NULL) quit("could not interpret \"%s\" after -P option\n", argv[i]); n = strtol(token, NULL, 10); if (n == LONG_MIN || n == LONG_MAX) quit("could not interpret \"%s\" after -P option\n", argv[i]); else if (n <= 0) quit("non-sensible value for \"k\" parameter\n"); *k = (int) n; } else usage(); i++; break; } case 'V': i++; csa_verbose = 2; break; default: usage(); break; } } if (csa_verbose && argc == 2) version(); } int main(int argc, char* argv[]) { char* fdata = NULL; char* fpoints = NULL; int nin = 0; point* pin = NULL; double* std = NULL; int invariant = 0; minell* me = NULL; int square = 0; int nout = 0; int generate_points = 0; point* pout = NULL; int nx = -1; int ny = -1; csa* a = NULL; int nppc = -1; int k = -1; double ks = NaN; double zoom = NaN; parse_commandline(argc, argv, &fdata, &fpoints, &invariant, &square, &generate_points, &nx, &ny, &nppc, &k, &zoom); if (fdata == NULL) quit("no input data\n"); if (!generate_points && fpoints == NULL) quit("no output grid specified\n"); points_read(fdata, 3, &nin, &pin, &std); if (nin < 3) return 0; if (invariant) { me = minell_build(nin, pin); minell_scalepoints(me, nin, pin); } else if (square) ks = points_scaletosquare(nin, pin); a = csa_create(); csa_addpoints(a, nin, pin); csa_addstd(a, nin, std); if (nppc > 0) csa_setnppc(a, nppc); if (k > 0) csa_setk(a, k); csa_calculatespline(a); /* * after calculating the spline, there is no more need in the input data */ if (pin != NULL) free(pin); pin = NULL; if (std != NULL) free(std); std = NULL; if (generate_points) { if (isnan(zoom)) points_generate(a->xmin - a->h, a->xmax + a->h, a->ymin - a->h, a->ymax + a->h, nx, ny, &nout, &pout); else { double xdiff2 = (a->xmax - a->xmin) / 2.0; double ydiff2 = (a->ymax - a->ymin) / 2.0; double xav = (a->xmax + a->xmin) / 2.0; double yav = (a->ymax + a->ymin) / 2.0; points_generate(xav - xdiff2 * zoom, xav + xdiff2 * zoom, yav - ydiff2 * zoom, yav + ydiff2 * zoom, nx, ny, &nout, &pout); } } else { points_read(fpoints, 2, &nout, &pout, NULL); if (invariant) minell_scalepoints(me, nout, pout); else if (square) points_scale(nout, pout, ks); } csa_approximatepoints(a, nout, pout); csa_destroy(a); a = NULL; if (invariant) minell_rescalepoints(me, nout, pout); else if (square) points_scale(nout, pout, 1.0 / ks); if (me != NULL) { minell_destroy(me); me = NULL; } points_write(nout, pout); free(pout); return 0; } #endif /* STANDALONE */
kthyng/octant
octant/src/gridgen/csa.c
C
bsd-3-clause
53,562
#----------------------------------------------------------------------------- # Copyright (c) 2012 - 2017, Anaconda, Inc. All rights reserved. # # Powered by the Bokeh Development Team. # # The full license is in the file LICENSE.txt, distributed with this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Boilerplate #----------------------------------------------------------------------------- import pytest ; pytest #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- # External imports from flaky import flaky # Bokeh imports from bokeh._testing.util.selenium import RECORD from bokeh.layouts import column from bokeh.models import ( Circle, ColumnDataSource, CustomAction, CustomJS, Plot, RadioButtonGroup, Range1d, ) #----------------------------------------------------------------------------- # Tests #----------------------------------------------------------------------------- pytest_plugins = ( "bokeh._testing.plugins.project", ) LABELS = ["Option 1", "Option 2", "Option 3"] @pytest.mark.selenium class Test_RadioButtonGroup(object): @flaky(max_runs=10) def test_server_on_change_round_trip(self, bokeh_server_page) -> None: def modify_doc(doc): source = ColumnDataSource(dict(x=[1, 2], y=[1, 1], val=["a", "b"])) plot = Plot(plot_height=400, plot_width=400, x_range=Range1d(0, 1), y_range=Range1d(0, 1), min_border=0) plot.add_glyph(source, Circle(x='x', y='y', size=20)) plot.add_tools(CustomAction(callback=CustomJS(args=dict(s=source), code=RECORD("data", "s.data")))) group = RadioButtonGroup(labels=LABELS, css_classes=["foo"]) def cb(active): source.data['val'] = [active, "b"] group.on_click(cb) doc.add_root(column(group, plot)) page = bokeh_server_page(modify_doc) el = page.driver.find_element_by_css_selector('.foo .bk-btn:nth-child(3)') el.click() page.click_custom_action() results = page.results assert results['data']['val'] == [2, "b"] el = page.driver.find_element_by_css_selector('.foo .bk-btn:nth-child(1)') el.click() page.click_custom_action() results = page.results assert results['data']['val'] == [0, "b"] # XXX (bev) disabled until https://github.com/bokeh/bokeh/issues/7970 is resolved #assert page.has_no_console_errors() def test_js_on_change_executes(self, bokeh_model_page) -> None: group = RadioButtonGroup(labels=LABELS, css_classes=["foo"]) group.js_on_click(CustomJS(code=RECORD("active", "cb_obj.active"))) page = bokeh_model_page(group) el = page.driver.find_element_by_css_selector('.foo .bk-btn:nth-child(3)') el.click() results = page.results assert results['active'] == 2 el = page.driver.find_element_by_css_selector('.foo .bk-btn:nth-child(1)') el.click() results = page.results assert results['active'] == 0 assert page.has_no_console_errors()
ericmjl/bokeh
tests/integration/widgets/test_radio_button_group.py
Python
bsd-3-clause
3,330
<article class="blog-post"> <header> <div class="row item-top"> <div class="col-sm-12"> <h1 class="blog-post-title"><a href="/blog/{{substr($result->created_at, 0, 4)}}/{{substr($result->created_at, 5, 2)}}/{{substr($result->created_at, 8, 2)}}/{{$result->slug}}">{{$result->post_title}}</a></h1> <div class="blog-post-meta"> <p> {{date_links([substr($result->created_at, 0, 4), substr($result->created_at, 5, 2), substr($result->created_at, 8, 2)])}} @if ($result->modified_at !== '1000-01-01 00:00:00') <span class="edit-time">(edited {{format_time($result->modified_at)}} )</span> @endif </p> <p> on <a href="/blog/category/{{slugify($result->category)}}" >{{$result->category}}</a> in <a href="/blog/language/{{strtolower(slugify($result->language))}}" >{{ucfirst($result->language)}}</a> </p> <p> {{read_time($result->post_id, true, true)}} read </p> </div> </div> </header> <section class="blog-body"> <?=get_intro($result->post_id);?> </section> <section class="post-bottom"> <div class="col-sm-12"> <a class="btn btn-primary read-more" href="/blog/{{substr($result->created_at, 0, 4)}}/{{substr($result->created_at, 5, 2)}}/{{substr($result->created_at, 8, 2)}}/{{$result->slug}}">Read more</a> </div> </section> </article><!-- /.blog-post -->
eivind88/b3
public/themes/default/views/blog/item.blade.php
PHP
bsd-3-clause
1,714
package akka.persistence.eventstore.snapshot import com.typesafe.config.ConfigFactory class Json4sSnapshotStoreIntegrationSpec extends SnapshotStoreIntegrationSpec(ConfigFactory.load("json4s.conf")) { override def supportsSerialization = false }
EventStore/EventStore.Akka.Persistence
src/it/scala/akka/persistence/eventstore/snapshot/Json4sSnapshotStoreIntegrationSpec.scala
Scala
bsd-3-clause
252
# Copyright (C) 2008 University of Maryland # All rights reserved. # See LICENSE.txt for details. # Author: Christopher Metting #Starting Date:8/11/2010 from numpy import shape,size class mifData(object): def __init__ (self,H_strt_xyz = [0.0,500.0,0.0],H_end_xyz = [0.0,0.0,0.0], steps = 5): self.H_strt_xyz = H_strt_xyz self.H_end_xyz = H_end_xyz self.steps = steps self.fieldCount = size(self.steps) return def create_mif(unit, mifDataObj = None, filename = None): ''' **Overview:** This module creates a mif file of the unit cell so that the magnetic character can be solved for in the oommf software. Currently, it only inputs the Unit cell information and other magnetic properties like magnetic field and demag are not available. This will be added as the become needed. **Parameters:** *filename* (str,filename) The location that the user would like to save the .mif file to. ''' if filename == None: filename= '/tmp/temp_mif_one.mif' from numpy import size nofile = unit.mag_unit.flatten() if (mifDataObj == None): mifDataObj = mifData() f = open(filename,'w') print >>f, '#MIF 2.1' print >>f, '#Mif file created by off-specular modeling software' print >>f, '#Description: this file was made by taking a sample that' print >>f, '#was created by the off-spec modeling software and turning' print >>f, '#the formula used to discritize into a mif file' print >>f, '' print >>f, 'set pi [expr 4*atan(1.0)]' print >>f, 'set mu0 [expr 4*$pi*1e-7]' print >>f, '' idx = 0 print >>f, 'set ::data {' for i in range(unit.n[2]): for i in range(unit.n[1]): print>>f, '' for i in range(unit.n[0]): print >>f,'%.5e' %nofile[idx],' ', idx += 1.0 print >>f, ' ' print >>f, '}' print >>f, '' print >>f, '' print >>f, 'RandomSeed 1' print >>f, '' print >>f, 'Specify Oxs_BoxAtlas:atlas {' print >>f, ' xrange {0 ' + str(unit.Dxyz[0]*(1.0e-10)) + '}' print >>f, ' yrange {0 ' + str(unit.Dxyz[1]*(1.0e-10)) + '}' print >>f, ' zrange {0 ' + str(unit.Dxyz[2]*(1.0e-10)) + '}' print >>f, '}' print >>f, '' print >>f, 'Specify Oxs_RectangularMesh:mesh [subst {' print >>f, ' cellsize {' + str(unit.step[0]*(1.0e-10)), print >>f, str(unit.step[1]*(1.0e-10)), str(unit.step[2]*(1.0e-10))+ '}' print >>f, ' atlas :atlas' print >>f, '}]' print >>f, '' print >>f, 'Specify Oxs_UZeeman [subst {' print >>f, ' multiplier [expr 0.001/$mu0]' print >>f, ' Hrange {' if mifDataObj.fieldCount == 1: print >>f, ' {',mifDataObj.H_strt_xyz[0], print >>f, mifDataObj.H_strt_xyz[1],mifDataObj.H_strt_xyz[2], print >>f, mifDataObj.H_end_xyz[0],mifDataObj.H_end_xyz[1], print >>f, mifDataObj.H_end_xyz[2],mifDataObj.steps,'}' else: for i in range(mifDataObj.fieldCount): print >>f, ' {',mifDataObj.H_strt_xyz[i][0], mifDataObj.H_strt_xyz[i][1],mifDataObj.H_strt_xyz[i][2], mifDataObj.H_end_xyz[i][1],mifDataObj.H_end_xyz[i][1],mifDataObj.H_end_xyz[i][2],mifDataObj.steps[i],'}' print >>f, ' }' print >>f, '}]' print >>f, '' print >>f, 'Specify Oxs_Demag {}' print >>f, '' print >>f, 'Specify Oxs_CGEvolve:evolve {}' print >>f, '' print >>f, 'Specify Oxs_MinDriver {' print >>f, ' basename temp_mif' print >>f, ' evolver :evolve' print >>f, ' stopping_mxHxm 0.1' print >>f, ' mesh :mesh' print >>f, ' Ms { Oxs_ScriptScalarField {' print >>f, ' atlas :atlas' print >>f, ' script OffSpecFormula' print >>f, ' script_args relpt' print >>f, ' }}' print >>f, 'm0 { Oxs_RandomVectorField {' print >>f, ' min_norm 1.0' print >>f, ' max_norm 1.0' print >>f, ' }}' print >>f, '}' print >>f, '' print >>f, 'proc OffSpecFormula {x y z} {' print >>f, '' print >>f, ' set nx',str(unit.n[0]) print >>f, ' set ny',str(unit.n[1]) print >>f, ' set nz',str(unit.n[2]) print >>f, '' print >>f, ' set xindex [expr {int(floor($x * $nx))}]' print >>f, ' set yindex [expr {int(floor($y * $ny))}]' print >>f, ' set zindex [expr {int(floor($z * $nz))}]' print >>f, '' print >>f, ' set idx [expr {($xindex*$ny*$nz + $yindex*$nz + $zindex)}]' print >>f, ' set Ms [lindex $::data $idx]' print >>f, ' return $Ms' print >>f, '}' print >>f, 'Destination archive mmArchive' print >>f, 'Schedule DataTable archive Stage 1' print >>f, 'Schedule Oxs_MinDriver::Magnetization archive Stage 1' f.close() print 'Mif File Created at: ' + str(filename) return def _test(): import sample_prep Au = (sample_prep.Parallelapiped(SLD = 4.506842e-6, Ms = 8.6e5,dim=[5.0e4,5.0e4,2.0e4])) Cr = (sample_prep.Layer(SLD = 3.01e-6,Ms = 7.7e8, thickness_value = 1000.0)) #Au.on_top_of(Cr) scene = sample_prep.Scene([Au]) GeoUnit = (sample_prep.GeomUnit(Dxyz = [10.0e4,10.0e4,2.2e4], n = [10,10,10],scene = scene)) unit = GeoUnit.buildUnit() mif = mifData() #mif = mifData([[0,500,0],[0,500,0],[0,500,0]],[[0,500,0],[0,500,0],[0,500,0]],[1,2,3]) unit.generateMIF(mif) if __name__=="__main__":_test()
reflectometry/osrefl
osrefl/model/mif_creator.py
Python
bsd-3-clause
5,653
module PatternRecogn where
EsGeh/pattern-recognition
src/PatternRecogn.hs
Haskell
bsd-3-clause
27
<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN'> <html lang="en"> <head> <link media="all" href="style.css" type="text/css" rel="stylesheet" /> <title>Libnabo vs. FLANN benchmarking</title> </head> <body> <h1>Libnabo vs. FLANN benchmarking</h1> <hr /> <h1>T-rex_high</h1> <h3>Search times</h3> <table border="1"> <tr> <th> </th> <th>5</th> <th>10</th> <th>15</th> <th>20</th> <th>25</th> <th>30</th> <th>35</th> <th>40</th> <th>45</th> <th>50</th> <th>55</th> <th>60</th> <th>65</th> <th>70</th> <th>75</th> <th>80</th> <th>85</th> <th>90</th> <th>95</th> <th>100</th> </tr> <tr> <td> <b>FLANN</b> </td> <td>0.00000182</td> <td>0.00000208</td> <td>0.00000285</td> <td>0.00000339</td> <td>0.00000393</td> <td>0.00000478</td> <td>0.00000549</td> <td>0.00000635</td> <td>0.00000748</td> <td>0.00000836</td> <td>0.00000920</td> <td>0.00001022</td> <td>0.00001113</td> <td>0.00001205</td> <td>0.00001604</td> <td>0.00001424</td> <td>0.00001564</td> <td>0.00001671</td> <td>0.00001802</td> <td>0.00001912</td> </tr> <tr> <td> <b>libnabo (bruteforce)</b> </td> <td>0.00105708</td> <td>0.00108364</td> <td>0.00111614</td> <td>0.00113322</td> <td>0.00115827</td> <td>0.00116370</td> <td>0.00118333</td> <td>0.00120156</td> <td>0.00122366</td> <td>0.00122884</td> <td>0.00123941</td> <td>0.00124118</td> <td>0.00126259</td> <td>0.00126674</td> <td>0.00128513</td> <td>0.00130336</td> <td>0.00132033</td> <td>0.00132916</td> <td>0.00133648</td> <td>0.00134761</td> </tr> <tr> <td> <b>libnabo (lin. heap)</b> </td> <td>0.00000133</td> <td>0.00000195</td> <td>0.00000261</td> <td>0.00000320</td> <td>0.00000396</td> <td>0.00000472</td> <td>0.00000583</td> <td>0.00000669</td> <td>0.00000771</td> <td>0.00000873</td> <td>0.00000986</td> <td>0.00001087</td> <td>0.00001210</td> <td>0.00001362</td> <td>0.00001489</td> <td>0.00001638</td> <td>0.00001805</td> <td>0.00001972</td> <td>0.00002120</td> <td>0.00002322</td> </tr> <tr> <td> <b>libnabo (tree heap)</b> </td> <td>0.00000157</td> <td>0.00000246</td> <td>0.00000355</td> <td>0.00000458</td> <td>0.00000574</td> <td>0.00000670</td> <td>0.00000771</td> <td>0.00000909</td> <td>0.00001050</td> <td>0.00001225</td> <td>0.00001326</td> <td>0.00001424</td> <td>0.00001473</td> <td>0.00001580</td> <td>0.00001770</td> <td>0.00002515</td> <td>0.00002362</td> <td>0.00002121</td> <td>0.00002246</td> <td>0.00002381</td> </tr> </table> <img src="./all_search_times/T-rex_high.png" width="600" height="400" /> <h3>Build times</h3> <table border="1"> <tr> <th> </th> <th>5</th> <th>10</th> <th>15</th> <th>20</th> <th>25</th> <th>30</th> <th>35</th> <th>40</th> <th>45</th> <th>50</th> <th>55</th> <th>60</th> <th>65</th> <th>70</th> <th>75</th> <th>80</th> <th>85</th> <th>90</th> <th>95</th> <th>100</th> </tr> <tr> <td> <b>FLANN</b> </td> <td>0.07026047</td> <td>0.06961417</td> <td>0.06966877</td> <td>0.06991649</td> <td>0.06983924</td> <td>0.06997561</td> <td>0.07001257</td> <td>0.06981218</td> <td>0.07115746</td> <td>0.07014322</td> <td>0.07327569</td> <td>0.06993496</td> <td>0.07056308</td> <td>0.07004714</td> <td>0.08165181</td> <td>0.08023429</td> <td>0.07028413</td> <td>0.07630754</td> <td>0.06918287</td> <td>0.06843233</td> </tr> <tr> <td> <b>libnabo (bruteforce)</b> </td> <td>0.00179362</td> <td>0.00162292</td> <td>0.00161028</td> <td>0.00160551</td> <td>0.00161266</td> <td>0.00160837</td> <td>0.00161886</td> <td>0.00160646</td> <td>0.00160933</td> <td>0.00161171</td> <td>0.00162363</td> <td>0.00160742</td> <td>0.00160885</td> <td>0.00162601</td> <td>0.00160742</td> <td>0.00162268</td> <td>0.00160503</td> <td>0.00160694</td> <td>0.00160885</td> <td>0.00165653</td> </tr> <tr> <td> <b>libnabo (lin. heap)</b> </td> <td>0.05961514</td> <td>0.06150913</td> <td>0.06007862</td> <td>0.05983353</td> <td>0.05914688</td> <td>0.05932713</td> <td>0.05958843</td> <td>0.05889416</td> <td>0.06081104</td> <td>0.06025696</td> <td>0.05946636</td> <td>0.05977917</td> <td>0.05982780</td> <td>0.05931950</td> <td>0.05892467</td> <td>0.05998802</td> <td>0.05880165</td> <td>0.06029034</td> <td>0.05994034</td> <td>0.05986118</td> </tr> <tr> <td> <b>libnabo (tree heap)</b> </td> <td>0.06044006</td> <td>0.06043625</td> <td>0.06028271</td> <td>0.05958843</td> <td>0.05983734</td> <td>0.06062508</td> <td>0.06073189</td> <td>0.05984402</td> <td>0.05958080</td> <td>0.06057835</td> <td>0.05951309</td> <td>0.05937576</td> <td>0.06006527</td> <td>0.05921459</td> <td>0.06127357</td> <td>0.06906128</td> <td>0.07328224</td> <td>0.06479263</td> <td>0.06304073</td> <td>0.05996704</td> </tr> </table> <img src="./all_build_times/T-rex_high.png" width="600" height="400" /> <br /> <hr /> <h1>chicken_high</h1> <h3>Search times</h3> <table border="1"> <tr> <th> </th> <th>5</th> <th>10</th> <th>15</th> <th>20</th> <th>25</th> <th>30</th> <th>35</th> <th>40</th> <th>45</th> <th>50</th> <th>55</th> <th>60</th> <th>65</th> <th>70</th> <th>75</th> <th>80</th> <th>85</th> <th>90</th> <th>95</th> <th>100</th> </tr> <tr> <td> <b>FLANN</b> </td> <td>0.00000181</td> <td>0.00000209</td> <td>0.00000297</td> <td>0.00000324</td> <td>0.00000391</td> <td>0.00000460</td> <td>0.00000536</td> <td>0.00000606</td> <td>0.00000691</td> <td>0.00000777</td> <td>0.00000913</td> <td>0.00000941</td> <td>0.00001030</td> <td>0.00001128</td> <td>0.00001274</td> <td>0.00001376</td> <td>0.00001444</td> <td>0.00001553</td> <td>0.00001682</td> <td>0.00001819</td> </tr> <tr> <td> <b>libnabo (bruteforce)</b> </td> <td>0.00081747</td> <td>0.00084915</td> <td>0.00086801</td> <td>0.00088988</td> <td>0.00091528</td> <td>0.00091693</td> <td>0.00093702</td> <td>0.00095385</td> <td>0.00098090</td> <td>0.00098391</td> <td>0.00099884</td> <td>0.00100076</td> <td>0.00101591</td> <td>0.00102086</td> <td>0.00104027</td> <td>0.00104357</td> <td>0.00106119</td> <td>0.00106462</td> <td>0.00109283</td> <td>0.00109374</td> </tr> <tr> <td> <b>libnabo (lin. heap)</b> </td> <td>0.00000118</td> <td>0.00000186</td> <td>0.00000237</td> <td>0.00000279</td> <td>0.00000377</td> <td>0.00000455</td> <td>0.00000549</td> <td>0.00000620</td> <td>0.00000711</td> <td>0.00000802</td> <td>0.00000903</td> <td>0.00000984</td> <td>0.00001137</td> <td>0.00001302</td> <td>0.00001348</td> <td>0.00001469</td> <td>0.00001621</td> <td>0.00001779</td> <td>0.00001939</td> <td>0.00002132</td> </tr> <tr> <td> <b>libnabo (tree heap)</b> </td> <td>0.00000141</td> <td>0.00000237</td> <td>0.00000341</td> <td>0.00000416</td> <td>0.00000544</td> <td>0.00000638</td> <td>0.00000727</td> <td>0.00000842</td> <td>0.00000969</td> <td>0.00001086</td> <td>0.00001180</td> <td>0.00001273</td> <td>0.00001326</td> <td>0.00001427</td> <td>0.00001600</td> <td>0.00001658</td> <td>0.00001809</td> <td>0.00001940</td> <td>0.00002103</td> <td>0.00002240</td> </tr> </table> <img src="./all_search_times/chicken_high.png" width="600" height="400" /> <h3>Build times</h3> <table border="1"> <tr> <th> </th> <th>5</th> <th>10</th> <th>15</th> <th>20</th> <th>25</th> <th>30</th> <th>35</th> <th>40</th> <th>45</th> <th>50</th> <th>55</th> <th>60</th> <th>65</th> <th>70</th> <th>75</th> <th>80</th> <th>85</th> <th>90</th> <th>95</th> <th>100</th> </tr> <tr> <td> <b>FLANN</b> </td> <td>0.05955505</td> <td>0.05949116</td> <td>0.05802822</td> <td>0.05920506</td> <td>0.05762768</td> <td>0.05832195</td> <td>0.05821419</td> <td>0.05792332</td> <td>0.05842018</td> <td>0.05728722</td> <td>0.05798721</td> <td>0.05512047</td> <td>0.05404663</td> <td>0.05981541</td> <td>0.05798340</td> <td>0.05700874</td> <td>0.05367374</td> <td>0.05402088</td> <td>0.05329514</td> <td>0.05360985</td> </tr> <tr> <td> <b>libnabo (bruteforce)</b> </td> <td>0.00136757</td> <td>0.00122738</td> <td>0.00122643</td> <td>0.00122738</td> <td>0.00122643</td> <td>0.00123119</td> <td>0.00131989</td> <td>0.00123215</td> <td>0.00122643</td> <td>0.00122643</td> <td>0.00122833</td> <td>0.00122452</td> <td>0.00122643</td> <td>0.00122643</td> <td>0.00123024</td> <td>0.00122643</td> <td>0.00125122</td> <td>0.00125122</td> <td>0.00122643</td> <td>0.00122833</td> </tr> <tr> <td> <b>libnabo (lin. heap)</b> </td> <td>0.05028343</td> <td>0.05299377</td> <td>0.04741478</td> <td>0.04733276</td> <td>0.04729652</td> <td>0.04706955</td> <td>0.04713440</td> <td>0.04778481</td> <td>0.04725838</td> <td>0.04750824</td> <td>0.04716492</td> <td>0.04734421</td> <td>0.05166435</td> <td>0.05019760</td> <td>0.04760361</td> <td>0.04750633</td> <td>0.04738235</td> <td>0.04704857</td> <td>0.04767609</td> <td>0.04794121</td> </tr> <tr> <td> <b>libnabo (tree heap)</b> </td> <td>0.04763603</td> <td>0.04844856</td> <td>0.04783440</td> <td>0.04814911</td> <td>0.04903030</td> <td>0.04884911</td> <td>0.04857635</td> <td>0.04828262</td> <td>0.04891968</td> <td>0.04975700</td> <td>0.04874039</td> <td>0.04835701</td> <td>0.04894066</td> <td>0.04862785</td> <td>0.04888725</td> <td>0.04861450</td> <td>0.04839134</td> <td>0.04877281</td> <td>0.04844093</td> <td>0.04869461</td> </tr> </table> <img src="./all_build_times/chicken_high.png" width="600" height="400" /> <br /> <hr /> <h1>cheff</h1> <h3>Search times</h3> <table border="1"> <tr> <th> </th> <th>5</th> <th>10</th> <th>15</th> <th>20</th> <th>25</th> <th>30</th> <th>35</th> <th>40</th> <th>45</th> <th>50</th> <th>55</th> <th>60</th> <th>65</th> <th>70</th> <th>75</th> <th>80</th> <th>85</th> <th>90</th> <th>95</th> <th>100</th> </tr> <tr> <td> <b>FLANN</b> </td> <td>0.00000135</td> <td>0.00000220</td> <td>0.00000264</td> <td>0.00000326</td> <td>0.00000423</td> <td>0.00000477</td> <td>0.00000555</td> <td>0.00000601</td> <td>0.00000661</td> <td>0.00001111</td> <td>0.00000807</td> <td>0.00000886</td> <td>0.00000978</td> <td>0.00001060</td> <td>0.00001167</td> <td>0.00001268</td> <td>0.00001357</td> <td>0.00001441</td> <td>0.00001557</td> <td>0.00001699</td> </tr> <tr> <td> <b>libnabo (bruteforce)</b> </td> <td>0.00105465</td> <td>0.00108393</td> <td>0.00111153</td> <td>0.00113583</td> <td>0.00115418</td> <td>0.00115892</td> <td>0.00118247</td> <td>0.00119474</td> <td>0.00122895</td> <td>0.00121925</td> <td>0.00122812</td> <td>0.00122805</td> <td>0.00124243</td> <td>0.00125069</td> <td>0.00127476</td> <td>0.00128342</td> <td>0.00130029</td> <td>0.00130189</td> <td>0.00131519</td> <td>0.00131901</td> </tr> <tr> <td> <b>libnabo (lin. heap)</b> </td> <td>0.00000111</td> <td>0.00000188</td> <td>0.00000250</td> <td>0.00000317</td> <td>0.00000395</td> <td>0.00000473</td> <td>0.00000547</td> <td>0.00000631</td> <td>0.00000724</td> <td>0.00000818</td> <td>0.00000924</td> <td>0.00001021</td> <td>0.00001152</td> <td>0.00001286</td> <td>0.00001418</td> <td>0.00001532</td> <td>0.00001696</td> <td>0.00001829</td> <td>0.00001981</td> <td>0.00002163</td> </tr> <tr> <td> <b>libnabo (tree heap)</b> </td> <td>0.00000128</td> <td>0.00000242</td> <td>0.00000337</td> <td>0.00000434</td> <td>0.00000572</td> <td>0.00000675</td> <td>0.00000757</td> <td>0.00000884</td> <td>0.00000998</td> <td>0.00001092</td> <td>0.00001214</td> <td>0.00001311</td> <td>0.00001376</td> <td>0.00001485</td> <td>0.00001617</td> <td>0.00001720</td> <td>0.00001883</td> <td>0.00001937</td> <td>0.00002068</td> <td>0.00002181</td> </tr> </table> <img src="./all_search_times/cheff.png" width="600" height="400" /> <h3>Build times</h3> <table border="1"> <tr> <th> </th> <th>5</th> <th>10</th> <th>15</th> <th>20</th> <th>25</th> <th>30</th> <th>35</th> <th>40</th> <th>45</th> <th>50</th> <th>55</th> <th>60</th> <th>65</th> <th>70</th> <th>75</th> <th>80</th> <th>85</th> <th>90</th> <th>95</th> <th>100</th> </tr> <tr> <td> <b>FLANN</b> </td> <td>0.07285690</td> <td>0.07156944</td> <td>0.07180214</td> <td>0.07169724</td> <td>0.07107925</td> <td>0.07068253</td> <td>0.07108307</td> <td>0.07169724</td> <td>0.07087708</td> <td>0.07139206</td> <td>0.07031059</td> <td>0.07107544</td> <td>0.07082367</td> <td>0.07041740</td> <td>0.07039070</td> <td>0.07111931</td> <td>0.07004547</td> <td>0.07066536</td> <td>0.07047653</td> <td>0.07031822</td> </tr> <tr> <td> <b>libnabo (bruteforce)</b> </td> <td>0.00173950</td> <td>0.00161171</td> <td>0.00161362</td> <td>0.00162315</td> <td>0.00161362</td> <td>0.00163460</td> <td>0.00162125</td> <td>0.00164223</td> <td>0.00161934</td> <td>0.00171280</td> <td>0.00162506</td> <td>0.00161552</td> <td>0.00161171</td> <td>0.00161743</td> <td>0.00161362</td> <td>0.00164413</td> <td>0.00161552</td> <td>0.00168419</td> <td>0.00161743</td> <td>0.00164795</td> </tr> <tr> <td> <b>libnabo (lin. heap)</b> </td> <td>0.06367111</td> <td>0.06336212</td> <td>0.06256485</td> <td>0.06262589</td> <td>0.06272125</td> <td>0.06311417</td> <td>0.06316757</td> <td>0.06276703</td> <td>0.06329727</td> <td>0.06317139</td> <td>0.06265640</td> <td>0.06288147</td> <td>0.06306458</td> <td>0.06258774</td> <td>0.06296158</td> <td>0.06279373</td> <td>0.06236649</td> <td>0.06311035</td> <td>0.06340408</td> <td>0.06282425</td> </tr> <tr> <td> <b>libnabo (tree heap)</b> </td> <td>0.06361008</td> <td>0.06304550</td> <td>0.06349182</td> <td>0.06333160</td> <td>0.06351471</td> <td>0.06282806</td> <td>0.06405258</td> <td>0.06690216</td> <td>0.06715775</td> <td>0.06728363</td> <td>0.06647491</td> <td>0.06798172</td> <td>0.06594849</td> <td>0.06647491</td> <td>0.06578445</td> <td>0.06670761</td> <td>0.06340408</td> <td>0.06293869</td> <td>0.06320190</td> <td>0.06325912</td> </tr> </table> <img src="./all_build_times/cheff.png" width="600" height="400" /> <br /> <hr /> <h1>rhino</h1> <h3>Search times</h3> <table border="1"> <tr> <th> </th> <th>5</th> <th>10</th> <th>15</th> <th>20</th> <th>25</th> <th>30</th> <th>35</th> <th>40</th> <th>45</th> <th>50</th> <th>55</th> <th>60</th> <th>65</th> <th>70</th> <th>75</th> <th>80</th> <th>85</th> <th>90</th> <th>95</th> <th>100</th> </tr> <tr> <td> <b>FLANN</b> </td> <td>0.00000150</td> <td>0.00000209</td> <td>0.00000263</td> <td>0.00000308</td> <td>0.00000367</td> <td>0.00000444</td> <td>0.00000511</td> <td>0.00000587</td> <td>0.00000679</td> <td>0.00000741</td> <td>0.00000844</td> <td>0.00000922</td> <td>0.00001064</td> <td>0.00001144</td> <td>0.00001202</td> <td>0.00001302</td> <td>0.00001408</td> <td>0.00001527</td> <td>0.00001648</td> <td>0.00001874</td> </tr> <tr> <td> <b>libnabo (bruteforce)</b> </td> <td>0.00051605</td> <td>0.00054624</td> <td>0.00057972</td> <td>0.00059544</td> <td>0.00062185</td> <td>0.00062119</td> <td>0.00064435</td> <td>0.00066261</td> <td>0.00068255</td> <td>0.00068567</td> <td>0.00069791</td> <td>0.00071452</td> <td>0.00071576</td> <td>0.00071963</td> <td>0.00074336</td> <td>0.00075508</td> <td>0.00077011</td> <td>0.00077535</td> <td>0.00078893</td> <td>0.00080650</td> </tr> <tr> <td> <b>libnabo (lin. heap)</b> </td> <td>0.00000135</td> <td>0.00000212</td> <td>0.00000284</td> <td>0.00000350</td> <td>0.00000437</td> <td>0.00000521</td> <td>0.00000595</td> <td>0.00000699</td> <td>0.00000792</td> <td>0.00000889</td> <td>0.00000997</td> <td>0.00001113</td> <td>0.00001232</td> <td>0.00001354</td> <td>0.00001500</td> <td>0.00001644</td> <td>0.00001802</td> <td>0.00001971</td> <td>0.00002174</td> <td>0.00002318</td> </tr> <tr> <td> <b>libnabo (tree heap)</b> </td> <td>0.00000146</td> <td>0.00000270</td> <td>0.00000385</td> <td>0.00000476</td> <td>0.00000612</td> <td>0.00000712</td> <td>0.00000804</td> <td>0.00000949</td> <td>0.00001059</td> <td>0.00001184</td> <td>0.00001298</td> <td>0.00001411</td> <td>0.00001438</td> <td>0.00001540</td> <td>0.00001740</td> <td>0.00001845</td> <td>0.00001995</td> <td>0.00002099</td> <td>0.00002271</td> <td>0.00002444</td> </tr> </table> <img src="./all_search_times/rhino.png" width="600" height="400" /> <h3>Build times</h3> <table border="1"> <tr> <th> </th> <th>5</th> <th>10</th> <th>15</th> <th>20</th> <th>25</th> <th>30</th> <th>35</th> <th>40</th> <th>45</th> <th>50</th> <th>55</th> <th>60</th> <th>65</th> <th>70</th> <th>75</th> <th>80</th> <th>85</th> <th>90</th> <th>95</th> <th>100</th> </tr> <tr> <td> <b>FLANN</b> </td> <td>0.02981949</td> <td>0.03072357</td> <td>0.03082275</td> <td>0.03070068</td> <td>0.03057480</td> <td>0.03003311</td> <td>0.03017044</td> <td>0.02984238</td> <td>0.02986145</td> <td>0.02970505</td> <td>0.03069305</td> <td>0.02996063</td> <td>0.03066635</td> <td>0.03016663</td> <td>0.03043747</td> <td>0.03046417</td> <td>0.03066635</td> <td>0.03034210</td> <td>0.03094482</td> <td>0.03009415</td> </tr> <tr> <td> <b>libnabo (bruteforce)</b> </td> <td>0.00087738</td> <td>0.00072479</td> <td>0.00072861</td> <td>0.00072479</td> <td>0.00072479</td> <td>0.00072479</td> <td>0.00072861</td> <td>0.00072861</td> <td>0.00072479</td> <td>0.00072479</td> <td>0.00072479</td> <td>0.00072479</td> <td>0.00074005</td> <td>0.00083542</td> <td>0.00072479</td> <td>0.00072479</td> <td>0.00073242</td> <td>0.00072861</td> <td>0.00072479</td> <td>0.00072479</td> </tr> <tr> <td> <b>libnabo (lin. heap)</b> </td> <td>0.02747726</td> <td>0.02788925</td> <td>0.03276443</td> <td>0.02561951</td> <td>0.02534103</td> <td>0.02564240</td> <td>0.02573395</td> <td>0.02570724</td> <td>0.02554321</td> <td>0.02560806</td> <td>0.02566147</td> <td>0.02564621</td> <td>0.02547455</td> <td>0.02600098</td> <td>0.02576828</td> <td>0.02555084</td> <td>0.02555466</td> <td>0.02571869</td> <td>0.02565002</td> <td>0.02555466</td> </tr> <tr> <td> <b>libnabo (tree heap)</b> </td> <td>0.02598572</td> <td>0.02605057</td> <td>0.02586365</td> <td>0.02614975</td> <td>0.02670288</td> <td>0.02670288</td> <td>0.02673340</td> <td>0.02672577</td> <td>0.02674484</td> <td>0.02636337</td> <td>0.02693176</td> <td>0.02661133</td> <td>0.02662659</td> <td>0.02632904</td> <td>0.02629089</td> <td>0.02664566</td> <td>0.02640533</td> <td>0.02655411</td> <td>0.02660751</td> <td>0.02592087</td> </tr> </table> <img src="./all_build_times/rhino.png" width="600" height="400" /> <br /> <hr /> <h1>rs21</h1> <h3>Search times</h3> <table border="1"> <tr> <th> </th> <th>5</th> <th>10</th> <th>15</th> <th>20</th> <th>25</th> <th>30</th> <th>35</th> <th>40</th> <th>45</th> <th>50</th> <th>55</th> <th>60</th> <th>65</th> <th>70</th> <th>75</th> <th>80</th> <th>85</th> <th>90</th> <th>95</th> <th>100</th> </tr> <tr> <td> <b>FLANN</b> </td> <td>0.00000154</td> <td>0.00000217</td> <td>0.00000281</td> <td>0.00000346</td> <td>0.00000398</td> <td>0.00000458</td> <td>0.00000519</td> <td>0.00000598</td> <td>0.00000680</td> <td>0.00000764</td> <td>0.00000827</td> <td>0.00000933</td> <td>0.00001020</td> <td>0.00001137</td> <td>0.00001216</td> <td>0.00001326</td> <td>0.00001434</td> <td>0.00001545</td> <td>0.00001667</td> <td>0.00001809</td> </tr> <tr> <td> <b>libnabo (bruteforce)</b> </td> <td>0.00076213</td> <td>0.00082827</td> <td>0.00089174</td> <td>0.00093647</td> <td>0.00099050</td> <td>0.00099210</td> <td>0.00103925</td> <td>0.00108363</td> <td>0.00112512</td> <td>0.00113935</td> <td>0.00115095</td> <td>0.00114783</td> <td>0.00117387</td> <td>0.00119799</td> <td>0.00123844</td> <td>0.00127649</td> <td>0.00131092</td> <td>0.00132167</td> <td>0.00134740</td> <td>0.00134552</td> </tr> <tr> <td> <b>libnabo (lin. heap)</b> </td> <td>0.00000137</td> <td>0.00000198</td> <td>0.00000273</td> <td>0.00000340</td> <td>0.00000408</td> <td>0.00000483</td> <td>0.00000570</td> <td>0.00000648</td> <td>0.00000740</td> <td>0.00000830</td> <td>0.00000955</td> <td>0.00001054</td> <td>0.00001181</td> <td>0.00001333</td> <td>0.00001438</td> <td>0.00001570</td> <td>0.00001808</td> <td>0.00001888</td> <td>0.00002032</td> <td>0.00002220</td> </tr> <tr> <td> <b>libnabo (tree heap)</b> </td> <td>0.00000160</td> <td>0.00000357</td> <td>0.00000370</td> <td>0.00000478</td> <td>0.00000587</td> <td>0.00000675</td> <td>0.00000745</td> <td>0.00000852</td> <td>0.00000983</td> <td>0.00001096</td> <td>0.00001232</td> <td>0.00001345</td> <td>0.00001423</td> <td>0.00001556</td> <td>0.00001686</td> <td>0.00001829</td> <td>0.00001970</td> <td>0.00002079</td> <td>0.00002176</td> <td>0.00002356</td> </tr> </table> <img src="./all_search_times/rs21.png" width="600" height="400" /> <h3>Build times</h3> <table border="1"> <tr> <th> </th> <th>5</th> <th>10</th> <th>15</th> <th>20</th> <th>25</th> <th>30</th> <th>35</th> <th>40</th> <th>45</th> <th>50</th> <th>55</th> <th>60</th> <th>65</th> <th>70</th> <th>75</th> <th>80</th> <th>85</th> <th>90</th> <th>95</th> <th>100</th> </tr> <tr> <td> <b>FLANN</b> </td> <td>0.04418182</td> <td>0.04415894</td> <td>0.04424286</td> <td>0.04416656</td> <td>0.04423141</td> <td>0.04415512</td> <td>0.04418182</td> <td>0.04427338</td> <td>0.04440308</td> <td>0.04416275</td> <td>0.04450989</td> <td>0.04434204</td> <td>0.04420090</td> <td>0.04409409</td> <td>0.04419327</td> <td>0.04415512</td> <td>0.04433441</td> <td>0.04409027</td> <td>0.04421616</td> <td>0.04407120</td> </tr> <tr> <td> <b>libnabo (bruteforce)</b> </td> <td>0.00122833</td> <td>0.00107574</td> <td>0.00107574</td> <td>0.00108337</td> <td>0.00107574</td> <td>0.00107193</td> <td>0.00107574</td> <td>0.00109863</td> <td>0.00107193</td> <td>0.00107574</td> <td>0.00109100</td> <td>0.00107193</td> <td>0.00107574</td> <td>0.00107193</td> <td>0.00107574</td> <td>0.00107193</td> <td>0.00107193</td> <td>0.00107574</td> <td>0.00110245</td> <td>0.00107193</td> </tr> <tr> <td> <b>libnabo (lin. heap)</b> </td> <td>0.04173279</td> <td>0.03802109</td> <td>0.03890991</td> <td>0.03886795</td> <td>0.03738022</td> <td>0.03764343</td> <td>0.03749466</td> <td>0.03771973</td> <td>0.03692627</td> <td>0.03719711</td> <td>0.03761673</td> <td>0.03768158</td> <td>0.03701019</td> <td>0.03939056</td> <td>0.03668213</td> <td>0.03650665</td> <td>0.03666306</td> <td>0.03943253</td> <td>0.03644943</td> <td>0.03727341</td> </tr> <tr> <td> <b>libnabo (tree heap)</b> </td> <td>0.03702545</td> <td>0.04010010</td> <td>0.03907394</td> <td>0.03712845</td> <td>0.03694916</td> <td>0.03649902</td> <td>0.03677368</td> <td>0.03733444</td> <td>0.03742599</td> <td>0.03681183</td> <td>0.03712463</td> <td>0.03782654</td> <td>0.03664017</td> <td>0.03684235</td> <td>0.03698349</td> <td>0.03669739</td> <td>0.03698349</td> <td>0.03678894</td> <td>0.03673172</td> <td>0.03716278</td> </tr> </table> <img src="./all_build_times/rs21.png" width="600" height="400" /> <br /> <hr /> <h1>rs7</h1> <h3>Search times</h3> <table border="1"> <tr> <th> </th> <th>5</th> <th>10</th> <th>15</th> <th>20</th> <th>25</th> <th>30</th> <th>35</th> <th>40</th> <th>45</th> <th>50</th> <th>55</th> <th>60</th> <th>65</th> <th>70</th> <th>75</th> <th>80</th> <th>85</th> <th>90</th> <th>95</th> <th>100</th> </tr> <tr> <td> <b>FLANN</b> </td> <td>0.00000136</td> <td>0.00000206</td> <td>0.00000267</td> <td>0.00000347</td> <td>0.00000399</td> <td>0.00000467</td> <td>0.00000525</td> <td>0.00000593</td> <td>0.00000664</td> <td>0.00000955</td> <td>0.00000806</td> <td>0.00000926</td> <td>0.00001001</td> <td>0.00001078</td> <td>0.00001170</td> <td>0.00001270</td> <td>0.00001380</td> <td>0.00001504</td> <td>0.00001607</td> <td>0.00001722</td> </tr> <tr> <td> <b>libnabo (bruteforce)</b> </td> <td>0.00068779</td> <td>0.00075185</td> <td>0.00078677</td> <td>0.00083605</td> <td>0.00089876</td> <td>0.00089914</td> <td>0.00093174</td> <td>0.00095332</td> <td>0.00099445</td> <td>0.00098337</td> <td>0.00099801</td> <td>0.00100105</td> <td>0.00100346</td> <td>0.00102596</td> <td>0.00105927</td> <td>0.00107974</td> <td>0.00110266</td> <td>0.00112228</td> <td>0.00112851</td> <td>0.00113242</td> </tr> <tr> <td> <b>libnabo (lin. heap)</b> </td> <td>0.00000123</td> <td>0.00000202</td> <td>0.00000271</td> <td>0.00000331</td> <td>0.00000409</td> <td>0.00000481</td> <td>0.00000559</td> <td>0.00000664</td> <td>0.00000731</td> <td>0.00000832</td> <td>0.00000919</td> <td>0.00001031</td> <td>0.00001156</td> <td>0.00001316</td> <td>0.00001424</td> <td>0.00001559</td> <td>0.00001709</td> <td>0.00001864</td> <td>0.00002027</td> <td>0.00002163</td> </tr> <tr> <td> <b>libnabo (tree heap)</b> </td> <td>0.00000148</td> <td>0.00000250</td> <td>0.00000351</td> <td>0.00000456</td> <td>0.00000600</td> <td>0.00000674</td> <td>0.00000765</td> <td>0.00000877</td> <td>0.00001002</td> <td>0.00001120</td> <td>0.00001222</td> <td>0.00001322</td> <td>0.00001401</td> <td>0.00001490</td> <td>0.00001650</td> <td>0.00001757</td> <td>0.00001959</td> <td>0.00002009</td> <td>0.00002136</td> <td>0.00002246</td> </tr> </table> <img src="./all_search_times/rs7.png" width="600" height="400" /> <h3>Build times</h3> <table border="1"> <tr> <th> </th> <th>5</th> <th>10</th> <th>15</th> <th>20</th> <th>25</th> <th>30</th> <th>35</th> <th>40</th> <th>45</th> <th>50</th> <th>55</th> <th>60</th> <th>65</th> <th>70</th> <th>75</th> <th>80</th> <th>85</th> <th>90</th> <th>95</th> <th>100</th> </tr> <tr> <td> <b>FLANN</b> </td> <td>0.04434586</td> <td>0.04215622</td> <td>0.03940964</td> <td>0.03959656</td> <td>0.03955841</td> <td>0.03939056</td> <td>0.03965378</td> <td>0.04040527</td> <td>0.03972626</td> <td>0.03968430</td> <td>0.04053116</td> <td>0.04009628</td> <td>0.03996658</td> <td>0.03961945</td> <td>0.04295731</td> <td>0.04197311</td> <td>0.03963470</td> <td>0.03953552</td> <td>0.03953171</td> <td>0.03976822</td> </tr> <tr> <td> <b>libnabo (bruteforce)</b> </td> <td>0.00110626</td> <td>0.00097656</td> <td>0.00098419</td> <td>0.00097275</td> <td>0.00098419</td> <td>0.00097656</td> <td>0.00098038</td> <td>0.00107193</td> <td>0.00097656</td> <td>0.00097275</td> <td>0.00097656</td> <td>0.00097656</td> <td>0.00097275</td> <td>0.00097656</td> <td>0.00097656</td> <td>0.00097656</td> <td>0.00097656</td> <td>0.00098038</td> <td>0.00099564</td> <td>0.00101089</td> </tr> <tr> <td> <b>libnabo (lin. heap)</b> </td> <td>0.03394318</td> <td>0.03494263</td> <td>0.03474045</td> <td>0.03452682</td> <td>0.03468323</td> <td>0.03477478</td> <td>0.03412247</td> <td>0.03394318</td> <td>0.03427887</td> <td>0.03454208</td> <td>0.03489685</td> <td>0.03406906</td> <td>0.03433228</td> <td>0.03451538</td> <td>0.03413773</td> <td>0.03399658</td> <td>0.03431702</td> <td>0.03478622</td> <td>0.03578186</td> <td>0.03406906</td> </tr> <tr> <td> <b>libnabo (tree heap)</b> </td> <td>0.03392792</td> <td>0.03409958</td> <td>0.03425980</td> <td>0.03405762</td> <td>0.03352356</td> <td>0.03373718</td> <td>0.03431320</td> <td>0.03432465</td> <td>0.03583145</td> <td>0.03448868</td> <td>0.03451538</td> <td>0.03477478</td> <td>0.03416824</td> <td>0.03462219</td> <td>0.03443527</td> <td>0.03424072</td> <td>0.03403473</td> <td>0.03473282</td> <td>0.03452682</td> <td>0.03415680</td> </tr> </table> <img src="./all_build_times/rs7.png" width="600" height="400" /> <br /> <hr /> <h1>rs9</h1> <h3>Search times</h3> <table border="1"> <tr> <th> </th> <th>5</th> <th>10</th> <th>15</th> <th>20</th> <th>25</th> <th>30</th> <th>35</th> <th>40</th> <th>45</th> <th>50</th> <th>55</th> <th>60</th> <th>65</th> <th>70</th> <th>75</th> <th>80</th> <th>85</th> <th>90</th> <th>95</th> <th>100</th> </tr> <tr> <td> <b>FLANN</b> </td> <td>0.00000167</td> <td>0.00000244</td> <td>0.00000292</td> <td>0.00000357</td> <td>0.00000448</td> <td>0.00000501</td> <td>0.00000575</td> <td>0.00000650</td> <td>0.00000740</td> <td>0.00000788</td> <td>0.00000862</td> <td>0.00000968</td> <td>0.00001048</td> <td>0.00001148</td> <td>0.00001301</td> <td>0.00001326</td> <td>0.00001428</td> <td>0.00001553</td> <td>0.00001616</td> <td>0.00001741</td> </tr> <tr> <td> <b>libnabo (bruteforce)</b> </td> <td>0.00084156</td> <td>0.00089522</td> <td>0.00093268</td> <td>0.00098231</td> <td>0.00102023</td> <td>0.00101941</td> <td>0.00105137</td> <td>0.00108795</td> <td>0.00111816</td> <td>0.00112826</td> <td>0.00114332</td> <td>0.00115395</td> <td>0.00117279</td> <td>0.00120725</td> <td>0.00121506</td> <td>0.00123934</td> <td>0.00126139</td> <td>0.00127360</td> <td>0.00129105</td> <td>0.00128955</td> </tr> <tr> <td> <b>libnabo (lin. heap)</b> </td> <td>0.00000145</td> <td>0.00000221</td> <td>0.00000272</td> <td>0.00000336</td> <td>0.00000417</td> <td>0.00000496</td> <td>0.00000582</td> <td>0.00000676</td> <td>0.00000760</td> <td>0.00000870</td> <td>0.00000956</td> <td>0.00001078</td> <td>0.00001205</td> <td>0.00001355</td> <td>0.00001432</td> <td>0.00001564</td> <td>0.00001694</td> <td>0.00001859</td> <td>0.00002057</td> <td>0.00002157</td> </tr> <tr> <td> <b>libnabo (tree heap)</b> </td> <td>0.00000168</td> <td>0.00000270</td> <td>0.00000366</td> <td>0.00000476</td> <td>0.00000615</td> <td>0.00000702</td> <td>0.00000801</td> <td>0.00000921</td> <td>0.00001053</td> <td>0.00001155</td> <td>0.00001231</td> <td>0.00001371</td> <td>0.00001386</td> <td>0.00001544</td> <td>0.00001612</td> <td>0.00001709</td> <td>0.00001836</td> <td>0.00001940</td> <td>0.00002062</td> <td>0.00002157</td> </tr> </table> <img src="./all_search_times/rs9.png" width="600" height="400" /> <h3>Build times</h3> <table border="1"> <tr> <th> </th> <th>5</th> <th>10</th> <th>15</th> <th>20</th> <th>25</th> <th>30</th> <th>35</th> <th>40</th> <th>45</th> <th>50</th> <th>55</th> <th>60</th> <th>65</th> <th>70</th> <th>75</th> <th>80</th> <th>85</th> <th>90</th> <th>95</th> <th>100</th> </tr> <tr> <td> <b>FLANN</b> </td> <td>0.05068207</td> <td>0.05113602</td> <td>0.05054855</td> <td>0.05089188</td> <td>0.05093002</td> <td>0.05056763</td> <td>0.05081558</td> <td>0.05039978</td> <td>0.05039978</td> <td>0.05034637</td> <td>0.05045700</td> <td>0.05098724</td> <td>0.05080032</td> <td>0.05106354</td> <td>0.05113602</td> <td>0.05038834</td> <td>0.05099487</td> <td>0.05118179</td> <td>0.05083084</td> <td>0.05103683</td> </tr> <tr> <td> <b>libnabo (bruteforce)</b> </td> <td>0.00137329</td> <td>0.00124359</td> <td>0.00126266</td> <td>0.00124741</td> <td>0.00122452</td> <td>0.00122452</td> <td>0.00122452</td> <td>0.00122070</td> <td>0.00125122</td> <td>0.00129700</td> <td>0.00122833</td> <td>0.00122833</td> <td>0.00122833</td> <td>0.00122833</td> <td>0.00135040</td> <td>0.00122070</td> <td>0.00123596</td> <td>0.00123596</td> <td>0.00122070</td> <td>0.00122070</td> </tr> <tr> <td> <b>libnabo (lin. heap)</b> </td> <td>0.04288483</td> <td>0.04331970</td> <td>0.04384613</td> <td>0.04325867</td> <td>0.04301453</td> <td>0.04299927</td> <td>0.04296112</td> <td>0.04309082</td> <td>0.04367065</td> <td>0.04297638</td> <td>0.04300690</td> <td>0.04335785</td> <td>0.04442596</td> <td>0.04373169</td> <td>0.04308319</td> <td>0.04398346</td> <td>0.04315948</td> <td>0.04297638</td> <td>0.04404449</td> <td>0.04306030</td> </tr> <tr> <td> <b>libnabo (tree heap)</b> </td> <td>0.04347229</td> <td>0.04438782</td> <td>0.04356384</td> <td>0.04332733</td> <td>0.04381561</td> <td>0.04504395</td> <td>0.04348755</td> <td>0.04330444</td> <td>0.04485321</td> <td>0.04344940</td> <td>0.04362488</td> <td>0.04388428</td> <td>0.04344177</td> <td>0.04468536</td> <td>0.04364014</td> <td>0.04425812</td> <td>0.04403687</td> <td>0.04358673</td> <td>0.04415894</td> <td>0.04341125</td> </tr> </table> <img src="./all_build_times/rs9.png" width="600" height="400" /> <br /> <hr /> <h1>parasaurolophus_high</h1> <h3>Search times</h3> <table border="1"> <tr> <th> </th> <th>5</th> <th>10</th> <th>15</th> <th>20</th> <th>25</th> <th>30</th> <th>35</th> <th>40</th> <th>45</th> <th>50</th> <th>55</th> <th>60</th> <th>65</th> <th>70</th> <th>75</th> <th>80</th> <th>85</th> <th>90</th> <th>95</th> <th>100</th> </tr> <tr> <td> <b>FLANN</b> </td> <td>0.00000127</td> <td>0.00000203</td> <td>0.00000203</td> <td>0.00000331</td> <td>0.00000356</td> <td>0.00000407</td> <td>0.00000534</td> <td>0.00000610</td> <td>0.00000712</td> <td>0.00000788</td> <td>0.00000865</td> <td>0.00000992</td> <td>0.00001094</td> <td>0.00001678</td> <td>0.00001831</td> <td>0.00002035</td> <td>0.00002162</td> <td>0.00001755</td> <td>0.00001856</td> <td>0.00001933</td> </tr> <tr> <td> <b>libnabo (bruteforce)</b> </td> <td>0.00130819</td> <td>0.00138117</td> <td>0.00121358</td> <td>0.00126597</td> <td>0.00128098</td> <td>0.00129420</td> <td>0.00131327</td> <td>0.00132599</td> <td>0.00133947</td> <td>0.00134277</td> <td>0.00135244</td> <td>0.00135396</td> <td>0.00138245</td> <td>0.00139847</td> <td>0.00140432</td> <td>0.00143153</td> <td>0.00141449</td> <td>0.00144933</td> <td>0.00144552</td> <td>0.00145416</td> </tr> <tr> <td> <b>libnabo (lin. heap)</b> </td> <td>0.00000102</td> <td>0.00000178</td> <td>0.00000229</td> <td>0.00000305</td> <td>0.00000356</td> <td>0.00000458</td> <td>0.00000559</td> <td>0.00000687</td> <td>0.00000814</td> <td>0.00000916</td> <td>0.00000992</td> <td>0.00001119</td> <td>0.00001272</td> <td>0.00001348</td> <td>0.00001475</td> <td>0.00001602</td> <td>0.00001780</td> <td>0.00001933</td> <td>0.00002136</td> <td>0.00002263</td> </tr> <tr> <td> <b>libnabo (tree heap)</b> </td> <td>0.00000127</td> <td>0.00000229</td> <td>0.00000305</td> <td>0.00000407</td> <td>0.00000559</td> <td>0.00000661</td> <td>0.00000788</td> <td>0.00000966</td> <td>0.00001119</td> <td>0.00001221</td> <td>0.00001322</td> <td>0.00001450</td> <td>0.00001475</td> <td>0.00001526</td> <td>0.00001628</td> <td>0.00001729</td> <td>0.00001958</td> <td>0.00002060</td> <td>0.00002238</td> <td>0.00002365</td> </tr> </table> <img src="./all_search_times/parasaurolophus_high.png" width="600" height="400" /> <h3>Build times</h3> <table border="1"> <tr> <th> </th> <th>5</th> <th>10</th> <th>15</th> <th>20</th> <th>25</th> <th>30</th> <th>35</th> <th>40</th> <th>45</th> <th>50</th> <th>55</th> <th>60</th> <th>65</th> <th>70</th> <th>75</th> <th>80</th> <th>85</th> <th>90</th> <th>95</th> <th>100</th> </tr> <tr> <td> <b>FLANN</b> </td> <td>0.07385254</td> <td>0.07462311</td> <td>0.07405853</td> <td>0.07535553</td> <td>0.07443237</td> <td>0.07433319</td> <td>0.07489014</td> <td>0.07831573</td> <td>0.07847595</td> <td>0.07901001</td> <td>0.07808685</td> <td>0.07825470</td> <td>0.07742310</td> <td>0.07738495</td> <td>0.07779694</td> <td>0.07785034</td> <td>0.07832336</td> <td>0.07851410</td> <td>0.07888031</td> <td>0.07822418</td> </tr> <tr> <td> <b>libnabo (bruteforce)</b> </td> <td>0.00190735</td> <td>0.00169373</td> <td>0.00170898</td> <td>0.00186157</td> <td>0.00202942</td> <td>0.00169373</td> <td>0.00214386</td> <td>0.00180817</td> <td>0.00169373</td> <td>0.00173187</td> <td>0.00169373</td> <td>0.00169373</td> <td>0.00167847</td> <td>0.00175476</td> <td>0.00170135</td> <td>0.00173187</td> <td>0.00228882</td> <td>0.00168610</td> <td>0.00186920</td> <td>0.00171661</td> </tr> <tr> <td> <b>libnabo (lin. heap)</b> </td> <td>0.06636047</td> <td>0.06420898</td> <td>0.06339264</td> <td>0.06462860</td> <td>0.06354523</td> <td>0.06386566</td> <td>0.06493378</td> <td>0.06401825</td> <td>0.06535339</td> <td>0.06403351</td> <td>0.06488800</td> <td>0.06416321</td> <td>0.06493378</td> <td>0.06404114</td> <td>0.06473541</td> <td>0.06448364</td> <td>0.06429291</td> <td>0.06391144</td> <td>0.06401062</td> <td>0.06423950</td> </tr> <tr> <td> <b>libnabo (tree heap)</b> </td> <td>0.06523132</td> <td>0.06490326</td> <td>0.06430817</td> <td>0.06443787</td> <td>0.06425476</td> <td>0.06441498</td> <td>0.06445312</td> <td>0.06453705</td> <td>0.06473541</td> <td>0.06462860</td> <td>0.06443787</td> <td>0.06463623</td> <td>0.06409454</td> <td>0.06419373</td> <td>0.06381989</td> <td>0.06433105</td> <td>0.06400299</td> <td>0.06449127</td> <td>0.06425476</td> <td>0.06454468</td> </tr> </table> <img src="./all_build_times/parasaurolophus_high.png" width="600" height="400" /> <br /> <hr /> <h1>office1</h1> <h3>Search times</h3> <table border="1"> <tr> <th> </th> <th>5</th> <th>10</th> <th>15</th> <th>20</th> <th>25</th> <th>30</th> <th>35</th> <th>40</th> <th>45</th> <th>50</th> <th>55</th> <th>60</th> <th>65</th> <th>70</th> <th>75</th> <th>80</th> <th>85</th> <th>90</th> <th>95</th> <th>100</th> </tr> <tr> <td> <b>FLANN</b> </td> <td>0.00000145</td> <td>0.00000201</td> <td>0.00000264</td> <td>0.00000320</td> <td>0.00000384</td> <td>0.00000455</td> <td>0.00000509</td> <td>0.00000577</td> <td>0.00000638</td> <td>0.00000740</td> <td>0.00000793</td> <td>0.00000875</td> <td>0.00000949</td> <td>0.00001035</td> <td>0.00001111</td> <td>0.00001195</td> <td>0.00001279</td> <td>0.00001396</td> <td>0.00001500</td> <td>0.00001587</td> </tr> <tr> <td> <b>libnabo (bruteforce)</b> </td> <td>0.00156405</td> <td>0.00161652</td> <td>0.00164881</td> <td>0.00170784</td> <td>0.00173569</td> <td>0.00174909</td> <td>0.00178993</td> <td>0.00182749</td> <td>0.00184446</td> <td>0.00186577</td> <td>0.00187701</td> <td>0.00189084</td> <td>0.00190982</td> <td>0.00192477</td> <td>0.00196775</td> <td>0.00198079</td> <td>0.00200722</td> <td>0.00202545</td> <td>0.00204282</td> <td>0.00206134</td> </tr> <tr> <td> <b>libnabo (lin. heap)</b> </td> <td>0.00000125</td> <td>0.00000198</td> <td>0.00000270</td> <td>0.00000351</td> <td>0.00000417</td> <td>0.00000478</td> <td>0.00000549</td> <td>0.00000636</td> <td>0.00000715</td> <td>0.00000819</td> <td>0.00000910</td> <td>0.00000997</td> <td>0.00001111</td> <td>0.00001228</td> <td>0.00001350</td> <td>0.00001470</td> <td>0.00001600</td> <td>0.00001742</td> <td>0.00001902</td> <td>0.00002057</td> </tr> <tr> <td> <b>libnabo (tree heap)</b> </td> <td>0.00000148</td> <td>0.00000247</td> <td>0.00000359</td> <td>0.00000473</td> <td>0.00000600</td> <td>0.00000669</td> <td>0.00000738</td> <td>0.00000844</td> <td>0.00000944</td> <td>0.00001083</td> <td>0.00001180</td> <td>0.00001272</td> <td>0.00001325</td> <td>0.00001478</td> <td>0.00001554</td> <td>0.00001663</td> <td>0.00001798</td> <td>0.00001902</td> <td>0.00002050</td> <td>0.00002190</td> </tr> </table> <img src="./all_search_times/office1.png" width="600" height="400" /> <h3>Build times</h3> <table border="1"> <tr> <th> </th> <th>5</th> <th>10</th> <th>15</th> <th>20</th> <th>25</th> <th>30</th> <th>35</th> <th>40</th> <th>45</th> <th>50</th> <th>55</th> <th>60</th> <th>65</th> <th>70</th> <th>75</th> <th>80</th> <th>85</th> <th>90</th> <th>95</th> <th>100</th> </tr> <tr> <td> <b>FLANN</b> </td> <td>0.09644318</td> <td>0.09408569</td> <td>0.09486389</td> <td>0.09428406</td> <td>0.09545898</td> <td>0.09593201</td> <td>0.09469604</td> <td>0.09607697</td> <td>0.09619904</td> <td>0.09532166</td> <td>0.09541321</td> <td>0.09429932</td> <td>0.09531403</td> <td>0.09485626</td> <td>0.09537506</td> <td>0.09610748</td> <td>0.09635925</td> <td>0.09584808</td> <td>0.09642029</td> <td>0.09603119</td> </tr> <tr> <td> <b>libnabo (bruteforce)</b> </td> <td>0.00273895</td> <td>0.00295258</td> <td>0.00267029</td> <td>0.00289154</td> <td>0.00251007</td> <td>0.00264740</td> <td>0.00257111</td> <td>0.00265503</td> <td>0.00259399</td> <td>0.00261688</td> <td>0.00247955</td> <td>0.00263977</td> <td>0.00265503</td> <td>0.00289917</td> <td>0.00270844</td> <td>0.00247192</td> <td>0.00254822</td> <td>0.00267029</td> <td>0.00257874</td> <td>0.00244904</td> </tr> <tr> <td> <b>libnabo (lin. heap)</b> </td> <td>0.08694458</td> <td>0.08809662</td> <td>0.08738708</td> <td>0.08678436</td> <td>0.08666992</td> <td>0.08605957</td> <td>0.08706665</td> <td>0.08670044</td> <td>0.08704376</td> <td>0.08735657</td> <td>0.08815002</td> <td>0.08660126</td> <td>0.08686829</td> <td>0.08778381</td> <td>0.08720398</td> <td>0.08725739</td> <td>0.08732605</td> <td>0.08765411</td> <td>0.08691406</td> <td>0.08739471</td> </tr> <tr> <td> <b>libnabo (tree heap)</b> </td> <td>0.08879089</td> <td>0.08876038</td> <td>0.08871460</td> <td>0.08850861</td> <td>0.08873749</td> <td>0.08877563</td> <td>0.08721161</td> <td>0.08787537</td> <td>0.08809662</td> <td>0.08741760</td> <td>0.08783722</td> <td>0.08786774</td> <td>0.08784485</td> <td>0.08810425</td> <td>0.08746338</td> <td>0.08764648</td> <td>0.08832550</td> <td>0.08742523</td> <td>0.08375549</td> <td>0.08399963</td> </tr> </table> <img src="./all_build_times/office1.png" width="600" height="400" /> <br /> <hr /> <h1>office2</h1> <h3>Search times</h3> <table border="1"> <tr> <th> </th> <th>5</th> <th>10</th> <th>15</th> <th>20</th> <th>25</th> <th>30</th> <th>35</th> <th>40</th> <th>45</th> <th>50</th> <th>55</th> <th>60</th> <th>65</th> <th>70</th> <th>75</th> <th>80</th> <th>85</th> <th>90</th> <th>95</th> <th>100</th> </tr> <tr> <td> <b>FLANN</b> </td> <td>0.00000137</td> <td>0.00000196</td> <td>0.00000264</td> <td>0.00000348</td> <td>0.00000389</td> <td>0.00000450</td> <td>0.00000524</td> <td>0.00000600</td> <td>0.00000682</td> <td>0.00000778</td> <td>0.00000839</td> <td>0.00000921</td> <td>0.00001005</td> <td>0.00001162</td> <td>0.00001213</td> <td>0.00001378</td> <td>0.00001961</td> <td>0.00002131</td> <td>0.00002263</td> <td>0.00002322</td> </tr> <tr> <td> <b>libnabo (bruteforce)</b> </td> <td>0.00123433</td> <td>0.00127561</td> <td>0.00124677</td> <td>0.00134758</td> <td>0.00132477</td> <td>0.00131299</td> <td>0.00132746</td> <td>0.00136520</td> <td>0.00137789</td> <td>0.00138504</td> <td>0.00139531</td> <td>0.00139806</td> <td>0.00140788</td> <td>0.00143171</td> <td>0.00145274</td> <td>0.00148964</td> <td>0.00151090</td> <td>0.00152290</td> <td>0.00154447</td> <td>0.00156830</td> </tr> <tr> <td> <b>libnabo (lin. heap)</b> </td> <td>0.00000140</td> <td>0.00000196</td> <td>0.00000257</td> <td>0.00000326</td> <td>0.00000387</td> <td>0.00000473</td> <td>0.00000562</td> <td>0.00000636</td> <td>0.00000740</td> <td>0.00000829</td> <td>0.00000949</td> <td>0.00001043</td> <td>0.00001167</td> <td>0.00001297</td> <td>0.00001455</td> <td>0.00001536</td> <td>0.00001673</td> <td>0.00001821</td> <td>0.00001979</td> <td>0.00002121</td> </tr> <tr> <td> <b>libnabo (tree heap)</b> </td> <td>0.00000160</td> <td>0.00000247</td> <td>0.00000348</td> <td>0.00000453</td> <td>0.00000565</td> <td>0.00000671</td> <td>0.00000763</td> <td>0.00000865</td> <td>0.00000999</td> <td>0.00001119</td> <td>0.00001231</td> <td>0.00001371</td> <td>0.00001411</td> <td>0.00001531</td> <td>0.00001633</td> <td>0.00001740</td> <td>0.00001867</td> <td>0.00001961</td> <td>0.00002073</td> <td>0.00002187</td> </tr> </table> <img src="./all_search_times/office2.png" width="600" height="400" /> <h3>Build times</h3> <table border="1"> <tr> <th> </th> <th>5</th> <th>10</th> <th>15</th> <th>20</th> <th>25</th> <th>30</th> <th>35</th> <th>40</th> <th>45</th> <th>50</th> <th>55</th> <th>60</th> <th>65</th> <th>70</th> <th>75</th> <th>80</th> <th>85</th> <th>90</th> <th>95</th> <th>100</th> </tr> <tr> <td> <b>FLANN</b> </td> <td>0.07472992</td> <td>0.07323456</td> <td>0.07275391</td> <td>0.07314301</td> <td>0.07286072</td> <td>0.07328796</td> <td>0.07344055</td> <td>0.07286072</td> <td>0.07336426</td> <td>0.07320404</td> <td>0.07286072</td> <td>0.07324219</td> <td>0.07265472</td> <td>0.07334900</td> <td>0.07316589</td> <td>0.07378387</td> <td>0.07908630</td> <td>0.07446289</td> <td>0.07990265</td> <td>0.07822418</td> </tr> <tr> <td> <b>libnabo (bruteforce)</b> </td> <td>0.00200653</td> <td>0.00190735</td> <td>0.00180054</td> <td>0.00179291</td> <td>0.00178528</td> <td>0.00178528</td> <td>0.00180817</td> <td>0.00178528</td> <td>0.00178528</td> <td>0.00180817</td> <td>0.00181580</td> <td>0.00186157</td> <td>0.00179291</td> <td>0.00178528</td> <td>0.00181580</td> <td>0.00178528</td> <td>0.00178528</td> <td>0.00179291</td> <td>0.00179291</td> <td>0.00181580</td> </tr> <tr> <td> <b>libnabo (lin. heap)</b> </td> <td>0.07089233</td> <td>0.06580353</td> <td>0.06346893</td> <td>0.06340027</td> <td>0.06382751</td> <td>0.06351471</td> <td>0.06440735</td> <td>0.06374359</td> <td>0.06353760</td> <td>0.06317902</td> <td>0.06400299</td> <td>0.06372070</td> <td>0.06369781</td> <td>0.06955719</td> <td>0.06864166</td> <td>0.06512451</td> <td>0.06451416</td> <td>0.06434631</td> <td>0.06440735</td> <td>0.06472015</td> </tr> <tr> <td> <b>libnabo (tree heap)</b> </td> <td>0.06468964</td> <td>0.06429291</td> <td>0.06494904</td> <td>0.06493378</td> <td>0.06446075</td> <td>0.06463623</td> <td>0.06465912</td> <td>0.06501770</td> <td>0.06421661</td> <td>0.06500244</td> <td>0.06521606</td> <td>0.06502533</td> <td>0.06768799</td> <td>0.06692505</td> <td>0.06703949</td> <td>0.06718445</td> <td>0.06443024</td> <td>0.06470490</td> <td>0.06392670</td> <td>0.06452942</td> </tr> </table> <img src="./all_build_times/office2.png" width="600" height="400" /> <br /> <hr /> <h1>office3</h1> <h3>Search times</h3> <table border="1"> <tr> <th> </th> <th>5</th> <th>10</th> <th>15</th> <th>20</th> <th>25</th> <th>30</th> <th>35</th> <th>40</th> <th>45</th> <th>50</th> <th>55</th> <th>60</th> <th>65</th> <th>70</th> <th>75</th> <th>80</th> <th>85</th> <th>90</th> <th>95</th> <th>100</th> </tr> <tr> <td> <b>FLANN</b> </td> <td>0.00000132</td> <td>0.00000181</td> <td>0.00000234</td> <td>0.00000298</td> <td>0.00000348</td> <td>0.00000409</td> <td>0.00000478</td> <td>0.00000549</td> <td>0.00000621</td> <td>0.00000697</td> <td>0.00000778</td> <td>0.00000867</td> <td>0.00000949</td> <td>0.00001035</td> <td>0.00001129</td> <td>0.00001231</td> <td>0.00001378</td> <td>0.00001574</td> <td>0.00001567</td> <td>0.00001691</td> </tr> <tr> <td> <b>libnabo (bruteforce)</b> </td> <td>0.00135262</td> <td>0.00139877</td> <td>0.00141871</td> <td>0.00144346</td> <td>0.00147039</td> <td>0.00147514</td> <td>0.00152082</td> <td>0.00153976</td> <td>0.00156113</td> <td>0.00156553</td> <td>0.00157565</td> <td>0.00157283</td> <td>0.00157087</td> <td>0.00158379</td> <td>0.00161128</td> <td>0.00162463</td> <td>0.00164289</td> <td>0.00164904</td> <td>0.00168371</td> <td>0.00169291</td> </tr> <tr> <td> <b>libnabo (lin. heap)</b> </td> <td>0.00000127</td> <td>0.00000178</td> <td>0.00000224</td> <td>0.00000290</td> <td>0.00000364</td> <td>0.00000445</td> <td>0.00000532</td> <td>0.00000623</td> <td>0.00000692</td> <td>0.00000793</td> <td>0.00000890</td> <td>0.00000999</td> <td>0.00001124</td> <td>0.00001231</td> <td>0.00001361</td> <td>0.00001488</td> <td>0.00001633</td> <td>0.00001801</td> <td>0.00001948</td> <td>0.00002118</td> </tr> <tr> <td> <b>libnabo (tree heap)</b> </td> <td>0.00000145</td> <td>0.00000224</td> <td>0.00000308</td> <td>0.00000407</td> <td>0.00000534</td> <td>0.00000643</td> <td>0.00000702</td> <td>0.00000821</td> <td>0.00000961</td> <td>0.00001111</td> <td>0.00001195</td> <td>0.00001305</td> <td>0.00001340</td> <td>0.00001424</td> <td>0.00001572</td> <td>0.00001691</td> <td>0.00001895</td> <td>0.00001971</td> <td>0.00002093</td> <td>0.00002253</td> </tr> </table> <img src="./all_search_times/office3.png" width="600" height="400" /> <h3>Build times</h3> <table border="1"> <tr> <th> </th> <th>5</th> <th>10</th> <th>15</th> <th>20</th> <th>25</th> <th>30</th> <th>35</th> <th>40</th> <th>45</th> <th>50</th> <th>55</th> <th>60</th> <th>65</th> <th>70</th> <th>75</th> <th>80</th> <th>85</th> <th>90</th> <th>95</th> <th>100</th> </tr> <tr> <td> <b>FLANN</b> </td> <td>0.08633423</td> <td>0.08754730</td> <td>0.08759308</td> <td>0.08988953</td> <td>0.09067535</td> <td>0.09155273</td> <td>0.09050751</td> <td>0.09101868</td> <td>0.09081268</td> <td>0.09049988</td> <td>0.09086609</td> <td>0.09078217</td> <td>0.09050751</td> <td>0.09124756</td> <td>0.09056091</td> <td>0.09086609</td> <td>0.09088135</td> <td>0.09094238</td> <td>0.09104156</td> <td>0.08699799</td> </tr> <tr> <td> <b>libnabo (bruteforce)</b> </td> <td>0.00238037</td> <td>0.00251007</td> <td>0.00215912</td> <td>0.00217438</td> <td>0.00214386</td> <td>0.00212860</td> <td>0.00212860</td> <td>0.00210571</td> <td>0.00212860</td> <td>0.00210571</td> <td>0.00212860</td> <td>0.00210571</td> <td>0.00211334</td> <td>0.00212097</td> <td>0.00217438</td> <td>0.00208282</td> <td>0.00243378</td> <td>0.00209808</td> <td>0.00211334</td> <td>0.00220490</td> </tr> <tr> <td> <b>libnabo (lin. heap)</b> </td> <td>0.07704926</td> <td>0.07591248</td> <td>0.07540894</td> <td>0.07508087</td> <td>0.07522583</td> <td>0.07528687</td> <td>0.07508850</td> <td>0.07536316</td> <td>0.07469940</td> <td>0.07492828</td> <td>0.07456207</td> <td>0.07409668</td> <td>0.07408905</td> <td>0.07413483</td> <td>0.07460785</td> <td>0.07415009</td> <td>0.07522583</td> <td>0.07497406</td> <td>0.07534027</td> <td>0.07456207</td> </tr> <tr> <td> <b>libnabo (tree heap)</b> </td> <td>0.07583618</td> <td>0.07543182</td> <td>0.07641602</td> <td>0.07544708</td> <td>0.07506561</td> <td>0.07458496</td> <td>0.07491302</td> <td>0.07479858</td> <td>0.07573700</td> <td>0.07478333</td> <td>0.07507324</td> <td>0.07496643</td> <td>0.07566071</td> <td>0.07524109</td> <td>0.07507324</td> <td>0.07579041</td> <td>0.07523346</td> <td>0.07594299</td> <td>0.07530212</td> <td>0.07563782</td> </tr> </table> <img src="./all_build_times/office3.png" width="600" height="400" /> <br /> <hr /> <h1>office4</h1> <h3>Search times</h3> <table border="1"> <tr> <th> </th> <th>5</th> <th>10</th> <th>15</th> <th>20</th> <th>25</th> <th>30</th> <th>35</th> <th>40</th> <th>45</th> <th>50</th> <th>55</th> <th>60</th> <th>65</th> <th>70</th> <th>75</th> <th>80</th> <th>85</th> <th>90</th> <th>95</th> <th>100</th> </tr> <tr> <td> <b>FLANN</b> </td> <td>0.00000142</td> <td>0.00000224</td> <td>0.00000308</td> <td>0.00000359</td> <td>0.00000453</td> <td>0.00000478</td> <td>0.00000542</td> <td>0.00000618</td> <td>0.00000702</td> <td>0.00000776</td> <td>0.00000877</td> <td>0.00000974</td> <td>0.00001083</td> <td>0.00001157</td> <td>0.00001266</td> <td>0.00001361</td> <td>0.00001478</td> <td>0.00001595</td> <td>0.00001737</td> <td>0.00001846</td> </tr> <tr> <td> <b>libnabo (bruteforce)</b> </td> <td>0.00159124</td> <td>0.00161326</td> <td>0.00163961</td> <td>0.00167480</td> <td>0.00170202</td> <td>0.00171412</td> <td>0.00172801</td> <td>0.00174845</td> <td>0.00177684</td> <td>0.00178157</td> <td>0.00178986</td> <td>0.00179672</td> <td>0.00181183</td> <td>0.00181396</td> <td>0.00184062</td> <td>0.00185084</td> <td>0.00186681</td> <td>0.00187800</td> <td>0.00189667</td> <td>0.00189295</td> </tr> <tr> <td> <b>libnabo (lin. heap)</b> </td> <td>0.00000153</td> <td>0.00000219</td> <td>0.00000285</td> <td>0.00000376</td> <td>0.00000463</td> <td>0.00000514</td> <td>0.00000585</td> <td>0.00000676</td> <td>0.00000768</td> <td>0.00000854</td> <td>0.00000966</td> <td>0.00001073</td> <td>0.00001200</td> <td>0.00001312</td> <td>0.00001460</td> <td>0.00001592</td> <td>0.00001760</td> <td>0.00001902</td> <td>0.00002070</td> <td>0.00002253</td> </tr> <tr> <td> <b>libnabo (tree heap)</b> </td> <td>0.00000178</td> <td>0.00000280</td> <td>0.00000392</td> <td>0.00000504</td> <td>0.00000666</td> <td>0.00000727</td> <td>0.00000788</td> <td>0.00000926</td> <td>0.00001033</td> <td>0.00001134</td> <td>0.00001251</td> <td>0.00001353</td> <td>0.00001409</td> <td>0.00001521</td> <td>0.00001678</td> <td>0.00001790</td> <td>0.00001943</td> <td>0.00002055</td> <td>0.00002192</td> <td>0.00002314</td> </tr> </table> <img src="./all_search_times/office4.png" width="600" height="400" /> <h3>Build times</h3> <table border="1"> <tr> <th> </th> <th>5</th> <th>10</th> <th>15</th> <th>20</th> <th>25</th> <th>30</th> <th>35</th> <th>40</th> <th>45</th> <th>50</th> <th>55</th> <th>60</th> <th>65</th> <th>70</th> <th>75</th> <th>80</th> <th>85</th> <th>90</th> <th>95</th> <th>100</th> </tr> <tr> <td> <b>FLANN</b> </td> <td>0.10466003</td> <td>0.10286713</td> <td>0.10184479</td> <td>0.10289001</td> <td>0.10164642</td> <td>0.10237885</td> <td>0.10368347</td> <td>0.10205078</td> <td>0.10384369</td> <td>0.10246277</td> <td>0.10279846</td> <td>0.10363007</td> <td>0.10182190</td> <td>0.10360718</td> <td>0.10346985</td> <td>0.10218811</td> <td>0.10391235</td> <td>0.10341644</td> <td>0.10375977</td> <td>0.10389709</td> </tr> <tr> <td> <b>libnabo (bruteforce)</b> </td> <td>0.00288391</td> <td>0.00263977</td> <td>0.00273132</td> <td>0.00263977</td> <td>0.00271606</td> <td>0.00273132</td> <td>0.00268555</td> <td>0.00274658</td> <td>0.00318909</td> <td>0.00259399</td> <td>0.00259399</td> <td>0.00265503</td> <td>0.00274658</td> <td>0.00302124</td> <td>0.00267029</td> <td>0.00282288</td> <td>0.00271606</td> <td>0.00268555</td> <td>0.00267029</td> <td>0.00259399</td> </tr> <tr> <td> <b>libnabo (lin. heap)</b> </td> <td>0.08688354</td> <td>0.08766174</td> <td>0.08761597</td> <td>0.08752441</td> <td>0.08750916</td> <td>0.08781433</td> <td>0.08818054</td> <td>0.08854675</td> <td>0.08674622</td> <td>0.08699036</td> <td>0.08691406</td> <td>0.08819580</td> <td>0.08706665</td> <td>0.08773804</td> <td>0.08662415</td> <td>0.08659363</td> <td>0.08679199</td> <td>0.08697510</td> <td>0.08654785</td> <td>0.08697510</td> </tr> <tr> <td> <b>libnabo (tree heap)</b> </td> <td>0.08747864</td> <td>0.08726501</td> <td>0.08743286</td> <td>0.09095764</td> <td>0.08654785</td> <td>0.08726501</td> <td>0.08787537</td> <td>0.08918762</td> <td>0.08685303</td> <td>0.08767700</td> <td>0.08668518</td> <td>0.08709717</td> <td>0.08677673</td> <td>0.08699036</td> <td>0.08659363</td> <td>0.08711243</td> <td>0.08711243</td> <td>0.08628845</td> <td>0.08738708</td> <td>0.08772278</td> </tr> </table> <img src="./all_build_times/office4.png" width="600" height="400" /> <br /> <hr /> Benchmarking figures and html page automatically generated with the automated benchmarking framework written in Python and C++, developed by Nick Vanbaelen. </body> </html>
PointCloudLibrary/blog
blogweb/gsoc/nickon/BenchResults/NNNandLibnabo/Nabo_benchmark/index.html
HTML
bsd-3-clause
52,765
#include <stdio.h> #include "kh.h" #include "defs.h" #include "drtrace.h" #include "deck_glfw.h" #include "ui_glfw.h" #include "color.h" #include "wid.h" int dr::ui::configure(void) { color_t bg_0 = {1, 1, 1, 0}; color_t bg_1 = {1, 1, 1, 1}; color_t bg_2 = {1, 0, 1, 1}; color_t bg_3 = {1, 1, 0, 0}; add_wid(new wid(WID_DECK, 0, 0, 0.5, 0.5, bg_0)); add_wid(new wid(WID_DECK, 0.5, 0, 0.5, 0.5, bg_1)); add_wid(new wid(WID_DECK, 0.5, 0.5, 0.5, 0.5, bg_2)); add_wid(new wid(WID_DECK, 0.6f, 0.6f, 0.2f, 0.2f, bg_3)); return 0; } int dr::key_handler::configure(void) { return 0; } int main(int argc, char **argv) { (void) argc; (void) argv; dr::key_handler kh; dr::ui_glfw ui(kh); int quit = 0; ASSERT_ZERO_GOTO_ERR(ui.open()); do { quit |= ui.update(); } while (!quit); ASSERT_ZERO_GOTO_ERR(ui.close()); R_INFO("happy end"); return (0); err: R_ERR("sad end"); return (1); }
manuel-m/discoride
dr3/samples/sample00_drGlwOpen/sample00_drGlfwOpen.cpp
C++
bsd-3-clause
988
<!DOCTYPE html> <html> <meta charset="utf-8"> <title>Date parser test — 1000&lt;=x&lt;=9999 and 100&lt;=y&lt;=999 and January&lt;=z&lt;=December — 1270.518.may</title> <script src="../date_test.js"></script> <p>Failed (Script did not run)</p> <script> test_date_invalid("1270.518.may", "Invalid Date") </script> </html>
operasoftware/presto-testo
core/features/dateParsing/TestCases/individual/PointSeparator/935.html
HTML
bsd-3-clause
339
<!DOCTYPE html> <html> <meta charset="utf-8"> <title>Date parser test — 1000&lt;=x&lt;=9999 and 0&lt;=y&lt;=69 and 0&lt;=z&lt;=69 — 1000/15/31</title> <script src="../date_test.js"></script> <p>Failed (Script did not run)</p> <script> test_date("1000/15/31", 1001, 2, 30, 22, 0, 0) </script> </html>
operasoftware/presto-testo
core/features/dateParsing/TestCases/individual/SlashSeparator/557.html
HTML
bsd-3-clause
319
// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin dragonfly freebsd linux nacl netbsd openbsd solaris vita package os import ( "errors" "runtime" "syscall" "time" ) func (p *Process) wait() (ps *ProcessState, err error) { if p.Pid == -1 { return nil, syscall.EINVAL } // If we can block until Wait4 will succeed immediately, do so. ready, err := p.blockUntilWaitable() if err != nil { return nil, err } if ready { // Mark the process done now, before the call to Wait4, // so that Process.signal will not send a signal. p.setDone() // Acquire a write lock on sigMu to wait for any // active call to the signal method to complete. p.sigMu.Lock() p.sigMu.Unlock() } var status syscall.WaitStatus var rusage syscall.Rusage pid1, e := syscall.Wait4(p.Pid, &status, 0, &rusage) if e != nil { return nil, NewSyscallError("wait", e) } if pid1 != 0 { p.setDone() } ps = &ProcessState{ pid: pid1, status: status, rusage: &rusage, } return ps, nil } var errFinished = errors.New("os: process already finished") func (p *Process) signal(sig Signal) error { if p.Pid == -1 { return errors.New("os: process already released") } if p.Pid == 0 { return errors.New("os: process not initialized") } p.sigMu.RLock() defer p.sigMu.RUnlock() if p.done() { return errFinished } s, ok := sig.(syscall.Signal) if !ok { return errors.New("os: unsupported signal type") } if e := syscall.Kill(p.Pid, s); e != nil { if e == syscall.ESRCH { return errFinished } return e } return nil } func (p *Process) release() error { // NOOP for unix. p.Pid = -1 // no need for a finalizer anymore runtime.SetFinalizer(p, nil) return nil } func findProcess(pid int) (p *Process, err error) { // NOOP for unix. return newProcess(pid, 0), nil } func (p *ProcessState) userTime() time.Duration { return time.Duration(p.rusage.Utime.Nano()) * time.Nanosecond } func (p *ProcessState) systemTime() time.Duration { return time.Duration(p.rusage.Stime.Nano()) * time.Nanosecond }
codestation/go
src/os/exec_unix.go
GO
bsd-3-clause
2,165
\begin{circuitikz} \draw[ultra thick] (-2, -1.5) rectangle (2, 1.5); \draw (0,0) node {ICL8038}; \draw[/tikz/circuitikz/bipoles/length=1cm] (-1.5, 1.5) node[below] {4} to [R, l=$R_A$: \SI{10}{\kilo\ohm}] ++(0, 1.5) to [short, -o] (4, 3) node[right] {\SI{+10}{\volt}} (0, 1.5) node[below] {5} to [R, l=\SI{+10}{\kilo\ohm}] ++(0, 1.5) (1.5, 1.5) node[below] {6} to [short] ++(0, 1.5) (3, 3) to [R, l_=\SI{10}{\kilo\ohm}] ++(0, -1.5) to [short] ++(0, -.5) (1.5, -1.5) node[above] {12} to [R, l=\SI{82}{\kilo\ohm}] ++(0, -1.5) (0, -1.5) node[above] {11} to [short] ++(0, -1.5) (-1.5, -1.5) node[above] {10} to [C, l_=$C_T$: \SI{3.3}{\nano\farad}] ++(0, -1.5) to [short, -o] (4, -3) node[right] {\SI{-10}{\volt}} (-2, 0) node[right] {8} to [short] ++(-.5, 0) to [short] ++(0, 1) to [short] ++(.5, 0) node[right] {7}; % short stuff on the side \draw[/tikz/circuitikz/bipoles/length=.75cm] (2, 1) node[left] {9} to [short, -o] ++(2, 0) (2, .5) node[left] {3} to [short, -o] ++(2, 0) (3, .5) to [R, l=$R_\text{TRI}$] ++(0, -1) node[ground] {} (2, -1) node[left] {2} to [short, -o] ++(2, 0) (3, -1) to [R, l=$R_\text{SINE}$] ++(0, -1) node[ground] {}; % square wave \draw[thick] (4.2, .85) -- ++(.1, 0) -- ++(0, .3) -- ++(.2, 0) -- ++(0, -.3) -- ++(.2, 0) -- ++(0, .3) -- ++(.2, 0) -- ++(0, -.3) -- ++(.1, 0); % triangle \draw[thick] (4.2, .5) -- ++(.1, .15) -- ++(.2, -.3) -- ++(.2, .3) -- ++(.2, -.3) -- ++(.1, .15); % sinusoid \draw[thick] (4.2, -1) sin ++(.1, .15) cos ++(.1, -.15) sin ++(.1, -.15) cos ++(.1, .15) sin ++(.1, .15) cos ++(.1, -.15) sin ++(.1, -.15) cos ++(.1, .15); \end{circuitikz}
sjbarag/ECE-L303-Reports
lab7/src/schem/free_run.tex
TeX
bsd-3-clause
1,643
/* * Copyright (C) 2006, 2007, 2008, 2011, 2014, 2015 XStream Committers. * All rights reserved. * * The software in this package is published under the terms of the BSD * style license a copy of which has been included with this distribution in * the LICENSE.txt file. * * Created on 15. March 2007 by Joerg Schaible */ package com.thoughtworks.xstream.core; import java.util.HashMap; import java.util.Map; import com.thoughtworks.xstream.converters.ConversionException; import com.thoughtworks.xstream.converters.Converter; import com.thoughtworks.xstream.converters.ConverterLookup; import com.thoughtworks.xstream.core.util.FastStack; import com.thoughtworks.xstream.io.HierarchicalStreamReader; import com.thoughtworks.xstream.mapper.Mapper; /** * Abstract base class for a TreeUnmarshaller, that resolves references. * * @author Joe Walnes * @author J&ouml;rg Schaible * @author Mauro Talevi * @since 1.2 */ public abstract class AbstractReferenceUnmarshaller<R> extends TreeUnmarshaller { private static final Object NULL = new Object(); private final Map<R, Object> values = new HashMap<>(); private final FastStack<R> parentStack = new FastStack<>(16); public AbstractReferenceUnmarshaller( final Object root, final HierarchicalStreamReader reader, final ConverterLookup converterLookup, final Mapper mapper) { super(root, reader, converterLookup, mapper); } @Override protected Object convert(final Object parent, final Class<?> type, final Converter converter) { if (parentStack.size() > 0) { // handles circular references final R parentReferenceKey = parentStack.peek(); if (parentReferenceKey != null) { // see AbstractCircularReferenceTest.testWeirdCircularReference() if (!values.containsKey(parentReferenceKey)) { values.put(parentReferenceKey, parent); } } } final Object result; final String attributeName = getMapper().aliasForSystemAttribute("reference"); final String reference = attributeName == null ? null : reader.getAttribute(attributeName); final boolean isReferenceable = getMapper().isReferenceable(type); if (reference != null) { final Object cache = isReferenceable ? values.get(getReferenceKey(reference)) : null; if (cache == null) { final ConversionException ex = new ConversionException("Invalid reference"); ex.add("reference", reference); ex.add("referenced-type", type.getName()); ex.add("referenceable", Boolean.toString(isReferenceable)); throw ex; } result = cache == NULL ? null : cache; } else if (!isReferenceable) { result = super.convert(parent, type, converter); } else { final R currentReferenceKey = getCurrentReferenceKey(); parentStack.push(currentReferenceKey); result = super.convert(parent, type, converter); if (currentReferenceKey != null) { values.put(currentReferenceKey, result == null ? NULL : result); } parentStack.popSilently(); } return result; } protected abstract R getReferenceKey(String reference); protected abstract R getCurrentReferenceKey(); }
emopers/xstream
xstream/src/java/com/thoughtworks/xstream/core/AbstractReferenceUnmarshaller.java
Java
bsd-3-clause
3,434
<?php class GalleryImage extends DataObject implements RenderableAsPortlet { public static $db = array( 'SortOrder' => 'Int', 'Title' => 'Varchar', 'Caption' => 'Text' ); // One-to-one relationship with gallery page public static $has_one = array( 'Image' => 'Image', 'GalleryPage' => 'GalleryPage', ); // tidy up the CMS by not showing these fields public function getCMSFields() { $fields = parent::getCMSFields(); $fields->removeFieldFromTab('Root.Main', 'GalleryPageID'); $fields->removeFieldFromTab('Root.Main', 'ExifRead'); $fields->removeFieldFromTab('Root.Main', 'SortOrder'); $fields->renameField('Title', _t('GalleryImage.TITLE', 'Title')); $fields->renameField('Image', _t('GalleryImage.IMAGE', 'Image')); return $fields; } // Tell the datagrid what fields to show in the table public static $summary_fields = array( 'ID' => 'ID', 'Title' => 'Title', 'Thumbnail' => 'Thumbnail', ); // this function creates the thumnail for the summary fields to use public function getThumbnail() { return $this->Image()->CMSThumbnail(); } public function getPortletTitle() { return $this->Title; } /** * An accessor method for an image for a portlet. * * @example * <code> * return $this->NewsItemImage; * </code> * * @return string */ public function getPortletImage() { return $this->Image(); } /** * An accessor for text associated with the portlet. * * @example * <code> * return $this->Summary * </code> * * @return string */ public function getPortletCaption() { return ''; } }
gordonbanderson/ss3gallery
code/GalleryImage.php
PHP
bsd-3-clause
1,821