code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
import urllib from canvas import util def make_cookie_key(key): return 'after_signup_' + str(key) def _get(request, key): key = make_cookie_key(key) val = request.COOKIES.get(key) if val is not None: val = util.loads(urllib.unquote(val)) return (key, val,) def get_posted_comment(request): ''' Gets a comment waiting to be posted, if one exists. Returns a pair containing the cookie key used to retrieve it and its deserialized JSON. ''' #TODO use dcramer's django-cookies so that we don't rely on having the response object to mutate cookies. # That would make this API much cleaner and isolated. return _get(request, 'post_comment')
canvasnetworks/canvas
website/canvas/after_signup.py
Python
bsd-3-clause
698
/* -- MAGMA (version 1.6.1) -- Univ. of Tennessee, Knoxville Univ. of California, Berkeley Univ. of Colorado, Denver @date January 2015 @author Mark Gates @generated from testing_zunmqr.cpp normal z -> s, Fri Jan 30 19:00:25 2015 */ // includes, system #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include <assert.h> // includes, project #include "flops.h" #include "magma.h" #include "magma_lapack.h" #include "testings.h" /* //////////////////////////////////////////////////////////////////////////// -- Testing sormqr */ int main( int argc, char** argv ) { TESTING_INIT(); real_Double_t gflops, gpu_perf, gpu_time, cpu_perf, cpu_time; float error, work[1]; float c_neg_one = MAGMA_S_NEG_ONE; magma_int_t ione = 1; magma_int_t mm, m, n, k, size, info; magma_int_t ISEED[4] = {0,0,0,1}; magma_int_t nb, ldc, lda, lwork, lwork_max; float *C, *R, *A, *W, *tau; magma_int_t status = 0; magma_opts opts; parse_opts( argc, argv, &opts ); // need slightly looser bound (60*eps instead of 30*eps) for some tests opts.tolerance = max( 60., opts.tolerance ); float tol = opts.tolerance * lapackf77_slamch("E"); // test all combinations of input parameters magma_side_t side [] = { MagmaLeft, MagmaRight }; magma_trans_t trans[] = { MagmaTrans, MagmaNoTrans }; printf(" M N K side trans CPU GFlop/s (sec) GPU GFlop/s (sec) ||R||_F / ||QC||_F\n"); printf("===============================================================================================\n"); for( int itest = 0; itest < opts.ntest; ++itest ) { for( int iside = 0; iside < 2; ++iside ) { for( int itran = 0; itran < 2; ++itran ) { for( int iter = 0; iter < opts.niter; ++iter ) { m = opts.msize[itest]; n = opts.nsize[itest]; k = opts.ksize[itest]; nb = magma_get_sgeqrf_nb( m ); ldc = m; // A is m x k (left) or n x k (right) mm = (side[iside] == MagmaLeft ? m : n); lda = mm; gflops = FLOPS_SORMQR( m, n, k, side[iside] ) / 1e9; if ( side[iside] == MagmaLeft && m < k ) { printf( "%5d %5d %5d %4c %5c skipping because side=left and m < k\n", (int) m, (int) n, (int) k, lapacke_side_const( side[iside] ), lapacke_trans_const( trans[itran] ) ); continue; } if ( side[iside] == MagmaRight && n < k ) { printf( "%5d %5d %5d %4c %5c skipping because side=right and n < k\n", (int) m, (int) n, (int) k, lapacke_side_const( side[iside] ), lapacke_trans_const( trans[itran] ) ); continue; } // need at least 2*nb*nb for geqrf lwork_max = max( max( m*nb, n*nb ), 2*nb*nb ); TESTING_MALLOC_CPU( C, float, ldc*n ); TESTING_MALLOC_CPU( R, float, ldc*n ); TESTING_MALLOC_CPU( A, float, lda*k ); TESTING_MALLOC_CPU( W, float, lwork_max ); TESTING_MALLOC_CPU( tau, float, k ); // C is full, m x n size = ldc*n; lapackf77_slarnv( &ione, ISEED, &size, C ); lapackf77_slacpy( "Full", &m, &n, C, &ldc, R, &ldc ); size = lda*k; lapackf77_slarnv( &ione, ISEED, &size, A ); // compute QR factorization to get Householder vectors in A, tau magma_sgeqrf( mm, k, A, lda, tau, W, lwork_max, &info ); if (info != 0) printf("magma_sgeqrf returned error %d: %s.\n", (int) info, magma_strerror( info )); /* ===================================================================== Performs operation using LAPACK =================================================================== */ cpu_time = magma_wtime(); lapackf77_sormqr( lapack_side_const( side[iside] ), lapack_trans_const( trans[itran] ), &m, &n, &k, A, &lda, tau, C, &ldc, W, &lwork_max, &info ); cpu_time = magma_wtime() - cpu_time; cpu_perf = gflops / cpu_time; if (info != 0) printf("lapackf77_sormqr returned error %d: %s.\n", (int) info, magma_strerror( info )); /* ==================================================================== Performs operation using MAGMA =================================================================== */ // query for workspace size lwork = -1; magma_sormqr( side[iside], trans[itran], m, n, k, A, lda, tau, R, ldc, W, lwork, &info ); if (info != 0) printf("magma_sormqr (lwork query) returned error %d: %s.\n", (int) info, magma_strerror( info )); lwork = (magma_int_t) MAGMA_S_REAL( W[0] ); if ( lwork < 0 || lwork > lwork_max ) { printf("optimal lwork %d > lwork_max %d\n", (int) lwork, (int) lwork_max ); lwork = lwork_max; } gpu_time = magma_wtime(); magma_sormqr( side[iside], trans[itran], m, n, k, A, lda, tau, R, ldc, W, lwork, &info ); gpu_time = magma_wtime() - gpu_time; gpu_perf = gflops / gpu_time; if (info != 0) printf("magma_sormqr returned error %d: %s.\n", (int) info, magma_strerror( info )); /* ===================================================================== compute relative error |QC_magma - QC_lapack| / |QC_lapack| =================================================================== */ error = lapackf77_slange( "Fro", &m, &n, C, &ldc, work ); size = ldc*n; blasf77_saxpy( &size, &c_neg_one, C, &ione, R, &ione ); error = lapackf77_slange( "Fro", &m, &n, R, &ldc, work ) / error; printf( "%5d %5d %5d %4c %5c %7.2f (%7.2f) %7.2f (%7.2f) %8.2e %s\n", (int) m, (int) n, (int) k, lapacke_side_const( side[iside] ), lapacke_trans_const( trans[itran] ), cpu_perf, cpu_time, gpu_perf, gpu_time, error, (error < tol ? "ok" : "failed") ); status += ! (error < tol); TESTING_FREE_CPU( C ); TESTING_FREE_CPU( R ); TESTING_FREE_CPU( A ); TESTING_FREE_CPU( W ); TESTING_FREE_CPU( tau ); fflush( stdout ); } if ( opts.niter > 1 ) { printf( "\n" ); } }} // end iside, itran printf( "\n" ); } TESTING_FINALIZE(); return status; }
shengren/magma-1.6.1
testing/testing_sormqr.cpp
C++
bsd-3-clause
7,358
// 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 "chrome/browser/chromeos/bluetooth/bluetooth_adapter.h" #include "base/bind.h" #include "base/lazy_instance.h" #include "base/logging.h" #include "base/stl_util.h" #include "base/values.h" #include "chrome/browser/chromeos/bluetooth/bluetooth_device.h" #include "chromeos/dbus/bluetooth_adapter_client.h" #include "chromeos/dbus/bluetooth_device_client.h" #include "chromeos/dbus/bluetooth_manager_client.h" #include "chromeos/dbus/bluetooth_out_of_band_client.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "dbus/object_path.h" namespace { // Shared default adapter instance, we don't want to keep this class around // if nobody is using it so use a WeakPtr and create the object when needed; // since Google C++ Style (and clang's static analyzer) forbids us having // exit-time destructors we use a leaky lazy instance for it. base::LazyInstance<base::WeakPtr<chromeos::BluetoothAdapter> >::Leaky default_adapter = LAZY_INSTANCE_INITIALIZER; } // namespace namespace chromeos { BluetoothAdapter::BluetoothAdapter() : weak_ptr_factory_(this), track_default_(false), powered_(false), discovering_(false) { DBusThreadManager::Get()->GetBluetoothManagerClient()-> AddObserver(this); DBusThreadManager::Get()->GetBluetoothAdapterClient()-> AddObserver(this); DBusThreadManager::Get()->GetBluetoothDeviceClient()-> AddObserver(this); } BluetoothAdapter::~BluetoothAdapter() { DBusThreadManager::Get()->GetBluetoothDeviceClient()-> RemoveObserver(this); DBusThreadManager::Get()->GetBluetoothAdapterClient()-> RemoveObserver(this); DBusThreadManager::Get()->GetBluetoothManagerClient()-> RemoveObserver(this); STLDeleteValues(&devices_); } void BluetoothAdapter::AddObserver(Observer* observer) { DCHECK(observer); observers_.AddObserver(observer); } void BluetoothAdapter::RemoveObserver(Observer* observer) { DCHECK(observer); observers_.RemoveObserver(observer); } bool BluetoothAdapter::IsPresent() const { return !object_path_.value().empty(); } bool BluetoothAdapter::IsPowered() const { return powered_; } void BluetoothAdapter::SetPowered(bool powered, const base::Closure& callback, const ErrorCallback& error_callback) { DBusThreadManager::Get()->GetBluetoothAdapterClient()-> GetProperties(object_path_)->powered.Set( powered, base::Bind(&BluetoothAdapter::OnSetPowered, weak_ptr_factory_.GetWeakPtr(), callback, error_callback)); } bool BluetoothAdapter::IsDiscovering() const { return discovering_; } void BluetoothAdapter::SetDiscovering(bool discovering, const base::Closure& callback, const ErrorCallback& error_callback) { if (discovering) { DBusThreadManager::Get()->GetBluetoothAdapterClient()-> StartDiscovery(object_path_, base::Bind(&BluetoothAdapter::OnStartDiscovery, weak_ptr_factory_.GetWeakPtr(), callback, error_callback)); } else { DBusThreadManager::Get()->GetBluetoothAdapterClient()-> StopDiscovery(object_path_, base::Bind(&BluetoothAdapter::OnStopDiscovery, weak_ptr_factory_.GetWeakPtr(), callback, error_callback)); } } BluetoothAdapter::DeviceList BluetoothAdapter::GetDevices() { ConstDeviceList const_devices = const_cast<const BluetoothAdapter *>(this)->GetDevices(); DeviceList devices; for (ConstDeviceList::const_iterator i = const_devices.begin(); i != const_devices.end(); ++i) devices.push_back(const_cast<BluetoothDevice *>(*i)); return devices; } BluetoothAdapter::ConstDeviceList BluetoothAdapter::GetDevices() const { ConstDeviceList devices; for (DevicesMap::const_iterator iter = devices_.begin(); iter != devices_.end(); ++iter) devices.push_back(iter->second); return devices; } BluetoothDevice* BluetoothAdapter::GetDevice(const std::string& address) { return const_cast<BluetoothDevice *>( const_cast<const BluetoothAdapter *>(this)->GetDevice(address)); } const BluetoothDevice* BluetoothAdapter::GetDevice( const std::string& address) const { DevicesMap::const_iterator iter = devices_.find(address); if (iter != devices_.end()) return iter->second; return NULL; } void BluetoothAdapter::ReadLocalOutOfBandPairingData( const BluetoothOutOfBandPairingDataCallback& callback, const ErrorCallback& error_callback) { DBusThreadManager::Get()->GetBluetoothOutOfBandClient()-> ReadLocalData(object_path_, base::Bind(&BluetoothAdapter::OnReadLocalData, weak_ptr_factory_.GetWeakPtr(), callback, error_callback)); } void BluetoothAdapter::TrackDefaultAdapter() { DVLOG(1) << "Tracking default adapter"; track_default_ = true; DBusThreadManager::Get()->GetBluetoothManagerClient()-> DefaultAdapter(base::Bind(&BluetoothAdapter::AdapterCallback, weak_ptr_factory_.GetWeakPtr())); } void BluetoothAdapter::FindAdapter(const std::string& address) { DVLOG(1) << "Using adapter " << address; track_default_ = false; DBusThreadManager::Get()->GetBluetoothManagerClient()-> FindAdapter(address, base::Bind(&BluetoothAdapter::AdapterCallback, weak_ptr_factory_.GetWeakPtr())); } void BluetoothAdapter::AdapterCallback(const dbus::ObjectPath& adapter_path, bool success) { if (success) { ChangeAdapter(adapter_path); } else if (!object_path_.value().empty()) { RemoveAdapter(); } } void BluetoothAdapter::DefaultAdapterChanged( const dbus::ObjectPath& adapter_path) { if (track_default_) ChangeAdapter(adapter_path); } void BluetoothAdapter::AdapterRemoved(const dbus::ObjectPath& adapter_path) { if (adapter_path == object_path_) RemoveAdapter(); } void BluetoothAdapter::ChangeAdapter(const dbus::ObjectPath& adapter_path) { if (adapter_path == object_path_) return; // Determine whether this is a change of adapter or gaining an adapter, // remember for later so we can send the right notification. const bool new_adapter = object_path_.value().empty(); if (new_adapter) { DVLOG(1) << "Adapter path initialized to " << adapter_path.value(); } else { DVLOG(1) << "Adapter path changed from " << object_path_.value() << " to " << adapter_path.value(); // Invalidate the devices list, since the property update does not // remove them. ClearDevices(); } object_path_ = adapter_path; // Update properties to their new values. BluetoothAdapterClient::Properties* properties = DBusThreadManager::Get()->GetBluetoothAdapterClient()-> GetProperties(object_path_); address_ = properties->address.value(); PoweredChanged(properties->powered.value()); DiscoveringChanged(properties->discovering.value()); DevicesChanged(properties->devices.value()); // Notify observers if we did not have an adapter before, the case of // moving from one to another is hidden from layers above. if (new_adapter) FOR_EACH_OBSERVER(BluetoothAdapter::Observer, observers_, AdapterPresentChanged(this, true)); } void BluetoothAdapter::RemoveAdapter() { DVLOG(1) << "Adapter lost."; PoweredChanged(false); DiscoveringChanged(false); ClearDevices(); object_path_ = dbus::ObjectPath(""); address_.clear(); FOR_EACH_OBSERVER(BluetoothAdapter::Observer, observers_, AdapterPresentChanged(this, false)); } void BluetoothAdapter::OnSetPowered(const base::Closure& callback, const ErrorCallback& error_callback, bool success) { if (success) callback.Run(); else error_callback.Run(); } void BluetoothAdapter::PoweredChanged(bool powered) { if (powered == powered_) return; powered_ = powered; FOR_EACH_OBSERVER(BluetoothAdapter::Observer, observers_, AdapterPoweredChanged(this, powered_)); } void BluetoothAdapter::OnStartDiscovery(const base::Closure& callback, const ErrorCallback& error_callback, const dbus::ObjectPath& adapter_path, bool success) { if (success) { DVLOG(1) << object_path_.value() << ": started discovery."; // Clear devices found in previous discovery attempts ClearDiscoveredDevices(); callback.Run(); } else { // TODO(keybuk): in future, don't run the callback if the error was just // that we were already discovering. error_callback.Run(); } } void BluetoothAdapter::OnStopDiscovery(const base::Closure& callback, const ErrorCallback& error_callback, const dbus::ObjectPath& adapter_path, bool success) { if (success) { DVLOG(1) << object_path_.value() << ": stopped discovery."; callback.Run(); // Leave found devices available for perusing. } else { // TODO(keybuk): in future, don't run the callback if the error was just // that we weren't discovering. error_callback.Run(); } } void BluetoothAdapter::DiscoveringChanged(bool discovering) { if (discovering == discovering_) return; discovering_ = discovering; FOR_EACH_OBSERVER(BluetoothAdapter::Observer, observers_, AdapterDiscoveringChanged(this, discovering_)); } void BluetoothAdapter::OnReadLocalData( const BluetoothOutOfBandPairingDataCallback& callback, const ErrorCallback& error_callback, const BluetoothOutOfBandPairingData& data, bool success) { if (success) callback.Run(data); else error_callback.Run(); } void BluetoothAdapter::AdapterPropertyChanged( const dbus::ObjectPath& adapter_path, const std::string& property_name) { if (adapter_path != object_path_) return; BluetoothAdapterClient::Properties* properties = DBusThreadManager::Get()->GetBluetoothAdapterClient()-> GetProperties(object_path_); if (property_name == properties->powered.name()) { PoweredChanged(properties->powered.value()); } else if (property_name == properties->discovering.name()) { DiscoveringChanged(properties->discovering.value()); } else if (property_name == properties->devices.name()) { DevicesChanged(properties->devices.value()); } } void BluetoothAdapter::DevicePropertyChanged( const dbus::ObjectPath& device_path, const std::string& property_name) { UpdateDevice(device_path); } void BluetoothAdapter::UpdateDevice(const dbus::ObjectPath& device_path) { BluetoothDeviceClient::Properties* properties = DBusThreadManager::Get()->GetBluetoothDeviceClient()-> GetProperties(device_path); // When we first see a device, we may not know the address yet and need to // wait for the DevicePropertyChanged signal before adding the device. const std::string address = properties->address.value(); if (address.empty()) return; // The device may be already known to us, either because this is an update // to properties, or the device going from discovered to connected and // pairing gaining an object path in the process. In any case, we want // to update the existing object, not create a new one. DevicesMap::iterator iter = devices_.find(address); BluetoothDevice* device; const bool update_device = (iter != devices_.end()); if (update_device) { device = iter->second; } else { device = BluetoothDevice::Create(this); devices_[address] = device; } const bool was_paired = device->IsPaired(); if (!was_paired) { DVLOG(1) << "Assigned object path " << device_path.value() << " to device " << address; device->SetObjectPath(device_path); } device->Update(properties, true); // Don't send a duplicate added event for supported devices that were // previously visible or for already paired devices, send a changed // event instead. We always send one event or the other since we always // inform observers about paired devices whether or not they're supported. if (update_device && (device->IsSupported() || was_paired)) { FOR_EACH_OBSERVER(BluetoothAdapter::Observer, observers_, DeviceChanged(this, device)); } else { FOR_EACH_OBSERVER(BluetoothAdapter::Observer, observers_, DeviceAdded(this, device)); } } void BluetoothAdapter::ClearDevices() { DevicesMap replace; devices_.swap(replace); for (DevicesMap::iterator iter = replace.begin(); iter != replace.end(); ++iter) { BluetoothDevice* device = iter->second; if (device->IsSupported() || device->IsPaired()) FOR_EACH_OBSERVER(BluetoothAdapter::Observer, observers_, DeviceRemoved(this, device)); delete device; } } void BluetoothAdapter::DeviceCreated(const dbus::ObjectPath& adapter_path, const dbus::ObjectPath& device_path) { if (adapter_path != object_path_) return; UpdateDevice(device_path); } void BluetoothAdapter::DeviceRemoved(const dbus::ObjectPath& adapter_path, const dbus::ObjectPath& device_path) { if (adapter_path != object_path_) return; DevicesMap::iterator iter = devices_.begin(); while (iter != devices_.end()) { BluetoothDevice* device = iter->second; DevicesMap::iterator temp = iter; ++iter; if (device->object_path_ != device_path) continue; // DeviceRemoved can also be called to indicate a device that is visible // during discovery has disconnected, but it is still visible to the // adapter, so don't remove in that case and only clear the object path. if (!device->IsVisible()) { FOR_EACH_OBSERVER(BluetoothAdapter::Observer, observers_, DeviceRemoved(this, device)); DVLOG(1) << "Removed device " << device->address(); delete device; devices_.erase(temp); } else { DVLOG(1) << "Removed object path from device " << device->address(); device->RemoveObjectPath(); // If the device is not supported then we want to act as if it was // removed, even though it is still visible to the adapter. if (!device->IsSupported()) { FOR_EACH_OBSERVER(BluetoothAdapter::Observer, observers_, DeviceRemoved(this, device)); } else { FOR_EACH_OBSERVER(BluetoothAdapter::Observer, observers_, DeviceChanged(this, device)); } } } } void BluetoothAdapter::DevicesChanged( const std::vector<dbus::ObjectPath>& devices) { for (std::vector<dbus::ObjectPath>::const_iterator iter = devices.begin(); iter != devices.end(); ++iter) UpdateDevice(*iter); } void BluetoothAdapter::ClearDiscoveredDevices() { DevicesMap::iterator iter = devices_.begin(); while (iter != devices_.end()) { BluetoothDevice* device = iter->second; DevicesMap::iterator temp = iter; ++iter; if (!device->IsPaired()) { if (device->IsSupported()) FOR_EACH_OBSERVER(BluetoothAdapter::Observer, observers_, DeviceRemoved(this, device)); delete device; devices_.erase(temp); } } } void BluetoothAdapter::DeviceFound( const dbus::ObjectPath& adapter_path, const std::string& address, const BluetoothDeviceClient::Properties& properties) { if (adapter_path != object_path_) return; // DeviceFound can also be called to indicate that a device we've // paired with is now visible to the adapter during discovery, in which // case we want to update the existing object, not create a new one. BluetoothDevice* device; DevicesMap::iterator iter = devices_.find(address); const bool update_device = (iter != devices_.end()); if (update_device) { device = iter->second; } else { device = BluetoothDevice::Create(this); devices_[address] = device; } DVLOG(1) << "Device " << address << " is visible to the adapter"; device->SetVisible(true); device->Update(&properties, false); // Don't send a duplicated added event for duplicate signals for supported // devices that were previously visible (should never happen) or for already // paired devices, send a changed event instead. We do not inform observers // if we find or update an unconnected and unsupported device. if (update_device && (device->IsSupported() || device->IsPaired())) { FOR_EACH_OBSERVER(BluetoothAdapter::Observer, observers_, DeviceChanged(this, device)); } else if (device->IsSupported()) { FOR_EACH_OBSERVER(BluetoothAdapter::Observer, observers_, DeviceAdded(this, device)); } } void BluetoothAdapter::DeviceDisappeared(const dbus::ObjectPath& adapter_path, const std::string& address) { if (adapter_path != object_path_) return; DevicesMap::iterator iter = devices_.find(address); if (iter == devices_.end()) return; BluetoothDevice* device = iter->second; // DeviceDisappeared can also be called to indicate that a device we've // paired with is no longer visible to the adapter, so don't remove // in that case and only clear the visible flag. if (!device->IsPaired()) { if (device->IsSupported()) FOR_EACH_OBSERVER(BluetoothAdapter::Observer, observers_, DeviceRemoved(this, device)); DVLOG(1) << "Discovered device " << device->address() << " is no longer visible to the adapter"; delete device; devices_.erase(iter); } else { DVLOG(1) << "Paired device " << device->address() << " is no longer visible to the adapter"; device->SetVisible(false); FOR_EACH_OBSERVER(BluetoothAdapter::Observer, observers_, DeviceChanged(this, device)); } } // static scoped_refptr<BluetoothAdapter> BluetoothAdapter::DefaultAdapter() { if (!default_adapter.Get().get()) { BluetoothAdapter* new_adapter = new BluetoothAdapter; default_adapter.Get() = new_adapter->weak_ptr_factory_.GetWeakPtr(); default_adapter.Get()->TrackDefaultAdapter(); } return scoped_refptr<BluetoothAdapter>(default_adapter.Get()); } // static BluetoothAdapter* BluetoothAdapter::Create(const std::string& address) { BluetoothAdapter* adapter = new BluetoothAdapter; adapter->FindAdapter(address); return adapter; } } // namespace chromeos
keishi/chromium
chrome/browser/chromeos/bluetooth/bluetooth_adapter.cc
C++
bsd-3-clause
19,256
/* this ALWAYS GENERATED file contains the IIDs and CLSIDs */ /* link this file in with the server and any clients */ /* File created by MIDL compiler version 7.00.0499 */ /* at Mon Dec 01 09:02:10 2008 */ /* Compiler settings for e:/builds/tinderbox/XR-Trunk/WINNT_5.2_Depend/mozilla/other-licenses/ia2/Accessible2.idl: Oicf, W1, Zp8, env=Win32 (32b run) protocol : dce , ms_ext, app_config, c_ext error checks: allocation ref bounds_check enum stub_data VC __declspec() decoration level: __declspec(uuid()), __declspec(selectany), __declspec(novtable) DECLSPEC_UUID(), MIDL_INTERFACE() */ //@@MIDL_FILE_HEADING( ) #pragma warning( disable: 4049 ) /* more than 64k source lines */ #ifdef __cplusplus extern "C"{ #endif #include <rpc.h> #include <rpcndr.h> #ifdef _MIDL_USE_GUIDDEF_ #ifndef INITGUID #define INITGUID #include <guiddef.h> #undef INITGUID #else #include <guiddef.h> #endif #define MIDL_DEFINE_GUID(type,name,l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8) \ DEFINE_GUID(name,l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8) #else // !_MIDL_USE_GUIDDEF_ #ifndef __IID_DEFINED__ #define __IID_DEFINED__ typedef struct _IID { unsigned long x; unsigned short s1; unsigned short s2; unsigned char c[8]; } IID; #endif // __IID_DEFINED__ #ifndef CLSID_DEFINED #define CLSID_DEFINED typedef IID CLSID; #endif // CLSID_DEFINED #define MIDL_DEFINE_GUID(type,name,l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8) \ const type name = {l,w1,w2,{b1,b2,b3,b4,b5,b6,b7,b8}} #endif !_MIDL_USE_GUIDDEF_ MIDL_DEFINE_GUID(IID, IID_IAccessible2,0xE89F726E,0xC4F4,0x4c19,0xBB,0x19,0xB6,0x47,0xD7,0xFA,0x84,0x78); #undef MIDL_DEFINE_GUID #ifdef __cplusplus } #endif
leighpauls/k2cro4
third_party/xulrunner-sdk/win/include/accessibility/Accessible2_i.c
C
bsd-3-clause
1,711
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; namespace Inbox2.Platform.Channels.Entities { [Serializable] [DataContract] public enum ProfileType { [EnumMember(Value = "1")] Default = 0, [EnumMember(Value = "2")] Social = 10, } }
Klaudit/inbox2_desktop
Code/Platform/Channels/Entities/ProfileType.cs
C#
bsd-3-clause
342
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Class Simpletools\Page\Layout</title> <link rel="stylesheet" href="resources/style.css?e99947befd7bf673c6b43ff75e9e0f170c88a60e"> </head> <body> <div id="left"> <div id="menu"> <a href="index.html" title="Overview"><span>Overview</span></a> <div id="groups"> <h3>Namespaces</h3> <ul> <li class="active"> <a href="namespace-Simpletools.html"> Simpletools<span></span> </a> <ul> <li> <a href="namespace-Simpletools.Autoload.html"> Autoload </a> </li> <li> <a href="namespace-Simpletools.Config.html"> Config </a> </li> <li> <a href="namespace-Simpletools.Db.html"> Db<span></span> </a> <ul> <li> <a href="namespace-Simpletools.Db.Mysql.html"> Mysql </a> </li> </ul></li> <li> <a href="namespace-Simpletools.Event.html"> Event </a> </li> <li> <a href="namespace-Simpletools.Http.html"> Http </a> </li> <li> <a href="namespace-Simpletools.Mvc.html"> Mvc </a> </li> <li class="active"> <a href="namespace-Simpletools.Page.html"> Page </a> </li> <li> <a href="namespace-Simpletools.Store.html"> Store </a> </li> </ul></li> </ul> </div> <hr> <div id="elements"> <h3>Classes</h3> <ul> <li class="active"><a href="class-Simpletools.Page.Layout.html">Layout</a></li> </ul> </div> </div> </div> <div id="splitter"></div> <div id="right"> <div id="rightInner"> <form id="search"> <input type="hidden" name="cx" value=""> <input type="hidden" name="ie" value="UTF-8"> <input type="text" name="q" class="text" placeholder="Search"> </form> <div id="navigation"> <ul> <li> <a href="index.html" title="Overview"><span>Overview</span></a> </li> <li> <a href="namespace-Simpletools.Page.html" title="Summary of Simpletools\Page"><span>Namespace</span></a> </li> <li class="active"> <span>Class</span> </li> </ul> <ul> </ul> <ul> </ul> </div> <div id="content" class="class"> <h1>Class Layout</h1> <div class="info"> <b>Namespace:</b> <a href="namespace-Simpletools.html">Simpletools</a>\<a href="namespace-Simpletools.Page.html">Page</a><br> <b>Located at</b> <a href="source-class-Simpletools.Page.Layout.html#44-413" title="Go to source code">Simpletools/Page/Layout.php</a> <br> </div> <table class="summary methods" id="methods"> <caption>Methods summary</caption> <tr data-order="__construct" id="___construct"> <td class="attributes"><code> public </code> </td> <td class="name"><div> <a class="anchor" href="#___construct">#</a> <code><a href="source-class-Simpletools.Page.Layout.html#67-89" title="Go to source code">__construct</a>( <span>array <var>$settings</var></span> )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="settings" id="_settings"> <td class="attributes"><code> public static &amp; </code> </td> <td class="name"><div> <a class="anchor" href="#_settings">#</a> <code><a href="source-class-Simpletools.Page.Layout.html#91-104" title="Go to source code">settings</a>( <span>array <var>$settings</var></span> )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="getInstance" id="_getInstance"> <td class="attributes"><code> public static &amp; </code> </td> <td class="name"><div> <a class="anchor" href="#_getInstance">#</a> <code><a href="source-class-Simpletools.Page.Layout.html#112-125" title="Go to source code">getInstance</a>( <span> <var>$settings</var> = <span class="php-keyword1">null</span></span> )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="setLayout" id="_setLayout"> <td class="attributes"><code> public &amp; </code> </td> <td class="name"><div> <a class="anchor" href="#_setLayout">#</a> <code><a href="source-class-Simpletools.Page.Layout.html#127-135" title="Go to source code">setLayout</a>( <span> <var>$layDir</var></span> )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="registerLayouts" id="_registerLayouts"> <td class="attributes"><code> public &amp; </code> </td> <td class="name"><div> <a class="anchor" href="#_registerLayouts">#</a> <code><a href="source-class-Simpletools.Page.Layout.html#137-147" title="Go to source code">registerLayouts</a>( <span>array <var>$layouts</var></span> )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="start" id="_start"> <td class="attributes"><code> public &amp; </code> </td> <td class="name"><div> <a class="anchor" href="#_start">#</a> <code><a href="source-class-Simpletools.Page.Layout.html#149-152" title="Go to source code">start</a>( )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="startBuffer" id="_startBuffer"> <td class="attributes"><code> public &amp; </code> </td> <td class="name"><div> <a class="anchor" href="#_startBuffer">#</a> <code><a href="source-class-Simpletools.Page.Layout.html#154-159" title="Go to source code">startBuffer</a>( )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="clearBuffer" id="_clearBuffer"> <td class="attributes"><code> public </code> </td> <td class="name"><div> <a class="anchor" href="#_clearBuffer">#</a> <code><a href="source-class-Simpletools.Page.Layout.html#161-164" title="Go to source code">clearBuffer</a>( )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="render" id="_render"> <td class="attributes"><code> public </code> </td> <td class="name"><div> <a class="anchor" href="#_render">#</a> <code><a href="source-class-Simpletools.Page.Layout.html#166-195" title="Go to source code">render</a>( <span> <var>$minify</var> = <span class="php-keyword1">false</span></span> )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="layout" id="_layout"> <td class="attributes"><code> public &amp; </code> </td> <td class="name"><div> <a class="anchor" href="#_layout">#</a> <code><a href="source-class-Simpletools.Page.Layout.html#197-200" title="Go to source code">layout</a>( )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="displayContent" id="_displayContent"> <td class="attributes"><code> public </code> </td> <td class="name"><div> <a class="anchor" href="#_displayContent">#</a> <code><a href="source-class-Simpletools.Page.Layout.html#202-205" title="Go to source code">displayContent</a>( )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="disable" id="_disable"> <td class="attributes"><code> public &amp; </code> </td> <td class="name"><div> <a class="anchor" href="#_disable">#</a> <code><a href="source-class-Simpletools.Page.Layout.html#207-213" title="Go to source code">disable</a>( )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="set" id="_set"> <td class="attributes"><code> public &amp; </code> </td> <td class="name"><div> <a class="anchor" href="#_set">#</a> <code><a href="source-class-Simpletools.Page.Layout.html#215-223" title="Go to source code">set</a>( <span> <var>$layout</var> = <span class="php-quote">'default'</span></span> )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="enable" id="_enable"> <td class="attributes"><code> public &amp; </code> </td> <td class="name"><div> <a class="anchor" href="#_enable">#</a> <code><a href="source-class-Simpletools.Page.Layout.html#225-235" title="Go to source code">enable</a>( <span> <var>$layout</var> = <span class="php-quote">'default'</span></span> )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="setTitle" id="_setTitle"> <td class="attributes"><code> public &amp; </code> </td> <td class="name"><div> <a class="anchor" href="#_setTitle">#</a> <code><a href="source-class-Simpletools.Page.Layout.html#244-248" title="Go to source code">setTitle</a>( <span> <var>$title</var></span> )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="setDefaultLayoutTitle" id="_setDefaultLayoutTitle"> <td class="attributes"><code> public &amp; </code> </td> <td class="name"><div> <a class="anchor" href="#_setDefaultLayoutTitle">#</a> <code><a href="source-class-Simpletools.Page.Layout.html#250-254" title="Go to source code">setDefaultLayoutTitle</a>( <span> <var>$title</var></span> )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="displayTitle" id="_displayTitle"> <td class="attributes"><code> public </code> </td> <td class="name"><div> <a class="anchor" href="#_displayTitle">#</a> <code><a href="source-class-Simpletools.Page.Layout.html#256-259" title="Go to source code">displayTitle</a>( )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="setDescription" id="_setDescription"> <td class="attributes"><code> public &amp; </code> </td> <td class="name"><div> <a class="anchor" href="#_setDescription">#</a> <code><a href="source-class-Simpletools.Page.Layout.html#261-265" title="Go to source code">setDescription</a>( <span> <var>$description</var></span> )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="displayDescription" id="_displayDescription"> <td class="attributes"><code> public </code> </td> <td class="name"><div> <a class="anchor" href="#_displayDescription">#</a> <code><a href="source-class-Simpletools.Page.Layout.html#267-270" title="Go to source code">displayDescription</a>( )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="addInternalCss" id="_addInternalCss"> <td class="attributes"><code> public &amp; </code> </td> <td class="name"><div> <a class="anchor" href="#_addInternalCss">#</a> <code><a href="source-class-Simpletools.Page.Layout.html#272-276" title="Go to source code">addInternalCss</a>( <span> <var>$style</var></span> )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="displayInternalCss" id="_displayInternalCss"> <td class="attributes"><code> public </code> </td> <td class="name"><div> <a class="anchor" href="#_displayInternalCss">#</a> <code><a href="source-class-Simpletools.Page.Layout.html#278-288" title="Go to source code">displayInternalCss</a>( )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="clearInternalCss" id="_clearInternalCss"> <td class="attributes"><code> public &amp; </code> </td> <td class="name"><div> <a class="anchor" href="#_clearInternalCss">#</a> <code><a href="source-class-Simpletools.Page.Layout.html#290-294" title="Go to source code">clearInternalCss</a>( )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="addExternalCss" id="_addExternalCss"> <td class="attributes"><code> public &amp; </code> </td> <td class="name"><div> <a class="anchor" href="#_addExternalCss">#</a> <code><a href="source-class-Simpletools.Page.Layout.html#296-306" title="Go to source code">addExternalCss</a>( <span> <var>$href</var></span> )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="addExternalCss_" id="_addExternalCss_"> <td class="attributes"><code> public &amp; </code> </td> <td class="name"><div> <a class="anchor" href="#_addExternalCss_">#</a> <code><a href="source-class-Simpletools.Page.Layout.html#308-312" title="Go to source code">addExternalCss_</a>( <span> <var>$href</var></span>, <span> <var>$media</var> = <span class="php-quote">'screen'</span></span>, <span> <var>$rel</var> = <span class="php-quote">'stylesheet'</span></span> )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="clearExternalCss" id="_clearExternalCss"> <td class="attributes"><code> public &amp; </code> </td> <td class="name"><div> <a class="anchor" href="#_clearExternalCss">#</a> <code><a href="source-class-Simpletools.Page.Layout.html#314-318" title="Go to source code">clearExternalCss</a>( )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="displayExternalCss" id="_displayExternalCss"> <td class="attributes"><code> public </code> </td> <td class="name"><div> <a class="anchor" href="#_displayExternalCss">#</a> <code><a href="source-class-Simpletools.Page.Layout.html#320-323" title="Go to source code">displayExternalCss</a>( )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="addMetaTag" id="_addMetaTag"> <td class="attributes"><code> public &amp; </code> </td> <td class="name"><div> <a class="anchor" href="#_addMetaTag">#</a> <code><a href="source-class-Simpletools.Page.Layout.html#325-330" title="Go to source code">addMetaTag</a>( <span> <var>$name</var></span>, <span> <var>$content</var></span> )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="displayMetaTags" id="_displayMetaTags"> <td class="attributes"><code> public </code> </td> <td class="name"><div> <a class="anchor" href="#_displayMetaTags">#</a> <code><a href="source-class-Simpletools.Page.Layout.html#332-344" title="Go to source code">displayMetaTags</a>( )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="addHeadLink" id="_addHeadLink"> <td class="attributes"><code> public &amp; </code> </td> <td class="name"><div> <a class="anchor" href="#_addHeadLink">#</a> <code><a href="source-class-Simpletools.Page.Layout.html#346-357" title="Go to source code">addHeadLink</a>( <span>array <var>$options</var></span> )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="displayHeadLinks" id="_displayHeadLinks"> <td class="attributes"><code> public </code> </td> <td class="name"><div> <a class="anchor" href="#_displayHeadLinks">#</a> <code><a href="source-class-Simpletools.Page.Layout.html#359-362" title="Go to source code">displayHeadLinks</a>( )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="addExternalJs" id="_addExternalJs"> <td class="attributes"><code> public &amp; </code> </td> <td class="name"><div> <a class="anchor" href="#_addExternalJs">#</a> <code><a href="source-class-Simpletools.Page.Layout.html#364-374" title="Go to source code">addExternalJs</a>( <span> <var>$href</var></span> )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="clearExternalJs" id="_clearExternalJs"> <td class="attributes"><code> public &amp; </code> </td> <td class="name"><div> <a class="anchor" href="#_clearExternalJs">#</a> <code><a href="source-class-Simpletools.Page.Layout.html#376-380" title="Go to source code">clearExternalJs</a>( )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="displayExternalJs" id="_displayExternalJs"> <td class="attributes"><code> public </code> </td> <td class="name"><div> <a class="anchor" href="#_displayExternalJs">#</a> <code><a href="source-class-Simpletools.Page.Layout.html#382-385" title="Go to source code">displayExternalJs</a>( )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="addInternalJs" id="_addInternalJs"> <td class="attributes"><code> public &amp; </code> </td> <td class="name"><div> <a class="anchor" href="#_addInternalJs">#</a> <code><a href="source-class-Simpletools.Page.Layout.html#387-391" title="Go to source code">addInternalJs</a>( <span> <var>$source</var></span> )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="clearInternalJs" id="_clearInternalJs"> <td class="attributes"><code> public &amp; </code> </td> <td class="name"><div> <a class="anchor" href="#_clearInternalJs">#</a> <code><a href="source-class-Simpletools.Page.Layout.html#393-397" title="Go to source code">clearInternalJs</a>( )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="displayInternalJs" id="_displayInternalJs"> <td class="attributes"><code> public </code> </td> <td class="name"><div> <a class="anchor" href="#_displayInternalJs">#</a> <code><a href="source-class-Simpletools.Page.Layout.html#399-411" title="Go to source code">displayInternalJs</a>( )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> </table> <table class="summary properties" id="properties"> <caption>Properties summary</caption> <tr data-order="content" id="$content"> <td class="attributes"><code> public string </code></td> <td class="name"> <a href="source-class-Simpletools.Page.Layout.html#52" title="Go to source code"><var>$content</var></a> <div class="description short"> </div> <div class="description detailed hidden"> </div> </td> <td class="value"> <div> <a href="#$content" class="anchor">#</a> <code><span class="php-quote">''</span></code> </div> </td> </tr> <tr data-order="description" id="$description"> <td class="attributes"><code> public </code></td> <td class="name"> <a href="source-class-Simpletools.Page.Layout.html#57" title="Go to source code"><var>$description</var></a> <div class="description short"> </div> <div class="description detailed hidden"> </div> </td> <td class="value"> <div> <a href="#$description" class="anchor">#</a> <code><span class="php-keyword1">null</span></code> </div> </td> </tr> <tr data-order="title" id="$title"> <td class="attributes"><code> public </code></td> <td class="name"> <a href="source-class-Simpletools.Page.Layout.html#58" title="Go to source code"><var>$title</var></a> <div class="description short"> </div> <div class="description detailed hidden"> </div> </td> <td class="value"> <div> <a href="#$title" class="anchor">#</a> <code><span class="php-keyword1">null</span></code> </div> </td> </tr> <tr data-order="_layouts" id="$_layouts"> <td class="attributes"><code> protected array </code></td> <td class="name"> <a href="source-class-Simpletools.Page.Layout.html#62" title="Go to source code"><var>$_layouts</var></a> <div class="description short"> </div> <div class="description detailed hidden"> </div> </td> <td class="value"> <div> <a href="#$_layouts" class="anchor">#</a> <code><span class="php-keyword1">array</span>()</code> </div> </td> </tr> <tr data-order="_currentLayout" id="$_currentLayout"> <td class="attributes"><code> protected string </code></td> <td class="name"> <a href="source-class-Simpletools.Page.Layout.html#63" title="Go to source code"><var>$_currentLayout</var></a> <div class="description short"> </div> <div class="description detailed hidden"> </div> </td> <td class="value"> <div> <a href="#$_currentLayout" class="anchor">#</a> <code><span class="php-quote">'default'</span></code> </div> </td> </tr> </table> </div> <div id="footer"> API documentation generated by <a href="http://apigen.org">ApiGen</a> </div> </div> </div> <script src="resources/combined.js"></script> <script src="elementlist.js"></script> </body> </html>
getsimpletools/getsimpletools.github.io
api/class-Simpletools.Page.Layout.html
HTML
bsd-3-clause
23,075
#ifndef NT2_GALLERY_INCLUDE_FUNCTIONS_SCALAR_PARTER_HPP_INCLUDED #define NT2_GALLERY_INCLUDE_FUNCTIONS_SCALAR_PARTER_HPP_INCLUDED #include <nt2/gallery/functions/parter.hpp> #endif
hainm/pythran
third_party/nt2/gallery/include/functions/scalar/parter.hpp
C++
bsd-3-clause
183
// Copyright 2014 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. package ppc64 import ( "cmd/compile/internal/gc" "cmd/internal/obj" "cmd/internal/obj/ppc64" ) const ( LeftRdwr uint32 = gc.LeftRead | gc.LeftWrite RightRdwr uint32 = gc.RightRead | gc.RightWrite ) // This table gives the basic information about instruction // generated by the compiler and processed in the optimizer. // See opt.h for bit definitions. // // Instructions not generated need not be listed. // As an exception to that rule, we typically write down all the // size variants of an operation even if we just use a subset. // // The table is formatted for 8-space tabs. var progtable = [ppc64.ALAST]obj.ProgInfo{ obj.ATYPE: {Flags: gc.Pseudo | gc.Skip}, obj.ATEXT: {Flags: gc.Pseudo}, obj.AFUNCDATA: {Flags: gc.Pseudo}, obj.APCDATA: {Flags: gc.Pseudo}, obj.AUNDEF: {Flags: gc.Break}, obj.AUSEFIELD: {Flags: gc.OK}, obj.ACHECKNIL: {Flags: gc.LeftRead}, obj.AVARDEF: {Flags: gc.Pseudo | gc.RightWrite}, obj.AVARKILL: {Flags: gc.Pseudo | gc.RightWrite}, obj.AVARLIVE: {Flags: gc.Pseudo | gc.LeftRead}, // NOP is an internal no-op that also stands // for USED and SET annotations, not the Power opcode. obj.ANOP: {Flags: gc.LeftRead | gc.RightWrite}, // Integer ppc64.AADD: {Flags: gc.SizeQ | gc.LeftRead | gc.RegRead | gc.RightWrite}, ppc64.ASUB: {Flags: gc.SizeQ | gc.LeftRead | gc.RegRead | gc.RightWrite}, ppc64.ANEG: {Flags: gc.SizeQ | gc.LeftRead | gc.RegRead | gc.RightWrite}, ppc64.AAND: {Flags: gc.SizeQ | gc.LeftRead | gc.RegRead | gc.RightWrite}, ppc64.AOR: {Flags: gc.SizeQ | gc.LeftRead | gc.RegRead | gc.RightWrite}, ppc64.AXOR: {Flags: gc.SizeQ | gc.LeftRead | gc.RegRead | gc.RightWrite}, ppc64.AMULLD: {Flags: gc.SizeQ | gc.LeftRead | gc.RegRead | gc.RightWrite}, ppc64.AMULLW: {Flags: gc.SizeL | gc.LeftRead | gc.RegRead | gc.RightWrite}, ppc64.AMULHD: {Flags: gc.SizeL | gc.LeftRead | gc.RegRead | gc.RightWrite}, ppc64.AMULHDU: {Flags: gc.SizeL | gc.LeftRead | gc.RegRead | gc.RightWrite}, ppc64.ADIVD: {Flags: gc.SizeQ | gc.LeftRead | gc.RegRead | gc.RightWrite}, ppc64.ADIVDU: {Flags: gc.SizeQ | gc.LeftRead | gc.RegRead | gc.RightWrite}, ppc64.ASLD: {Flags: gc.SizeQ | gc.LeftRead | gc.RegRead | gc.RightWrite}, ppc64.ASRD: {Flags: gc.SizeQ | gc.LeftRead | gc.RegRead | gc.RightWrite}, ppc64.ASRAD: {Flags: gc.SizeQ | gc.LeftRead | gc.RegRead | gc.RightWrite}, ppc64.ACMP: {Flags: gc.SizeQ | gc.LeftRead | gc.RightRead}, ppc64.ACMPU: {Flags: gc.SizeQ | gc.LeftRead | gc.RightRead}, ppc64.ATD: {Flags: gc.SizeQ | gc.RightRead}, // Floating point. ppc64.AFADD: {Flags: gc.SizeD | gc.LeftRead | gc.RegRead | gc.RightWrite}, ppc64.AFADDS: {Flags: gc.SizeF | gc.LeftRead | gc.RegRead | gc.RightWrite}, ppc64.AFSUB: {Flags: gc.SizeD | gc.LeftRead | gc.RegRead | gc.RightWrite}, ppc64.AFSUBS: {Flags: gc.SizeF | gc.LeftRead | gc.RegRead | gc.RightWrite}, ppc64.AFMUL: {Flags: gc.SizeD | gc.LeftRead | gc.RegRead | gc.RightWrite}, ppc64.AFMULS: {Flags: gc.SizeF | gc.LeftRead | gc.RegRead | gc.RightWrite}, ppc64.AFDIV: {Flags: gc.SizeD | gc.LeftRead | gc.RegRead | gc.RightWrite}, ppc64.AFDIVS: {Flags: gc.SizeF | gc.LeftRead | gc.RegRead | gc.RightWrite}, ppc64.AFCTIDZ: {Flags: gc.SizeF | gc.LeftRead | gc.RegRead | gc.RightWrite}, ppc64.AFCFID: {Flags: gc.SizeF | gc.LeftRead | gc.RegRead | gc.RightWrite}, ppc64.AFCMPU: {Flags: gc.SizeD | gc.LeftRead | gc.RightRead}, ppc64.AFRSP: {Flags: gc.SizeD | gc.LeftRead | gc.RightWrite | gc.Conv}, // Moves ppc64.AMOVB: {Flags: gc.SizeB | gc.LeftRead | gc.RightWrite | gc.Move | gc.Conv}, ppc64.AMOVBU: {Flags: gc.SizeB | gc.LeftRead | gc.RightWrite | gc.Move | gc.Conv | gc.PostInc}, ppc64.AMOVBZ: {Flags: gc.SizeB | gc.LeftRead | gc.RightWrite | gc.Move | gc.Conv}, ppc64.AMOVH: {Flags: gc.SizeW | gc.LeftRead | gc.RightWrite | gc.Move | gc.Conv}, ppc64.AMOVHU: {Flags: gc.SizeW | gc.LeftRead | gc.RightWrite | gc.Move | gc.Conv | gc.PostInc}, ppc64.AMOVHZ: {Flags: gc.SizeW | gc.LeftRead | gc.RightWrite | gc.Move | gc.Conv}, ppc64.AMOVW: {Flags: gc.SizeL | gc.LeftRead | gc.RightWrite | gc.Move | gc.Conv}, // there is no AMOVWU. ppc64.AMOVWZU: {Flags: gc.SizeL | gc.LeftRead | gc.RightWrite | gc.Move | gc.Conv | gc.PostInc}, ppc64.AMOVWZ: {Flags: gc.SizeL | gc.LeftRead | gc.RightWrite | gc.Move | gc.Conv}, ppc64.AMOVD: {Flags: gc.SizeQ | gc.LeftRead | gc.RightWrite | gc.Move}, ppc64.AMOVDU: {Flags: gc.SizeQ | gc.LeftRead | gc.RightWrite | gc.Move | gc.PostInc}, ppc64.AFMOVS: {Flags: gc.SizeF | gc.LeftRead | gc.RightWrite | gc.Move | gc.Conv}, ppc64.AFMOVD: {Flags: gc.SizeD | gc.LeftRead | gc.RightWrite | gc.Move}, // Jumps ppc64.ABR: {Flags: gc.Jump | gc.Break}, ppc64.ABL: {Flags: gc.Call}, ppc64.ABEQ: {Flags: gc.Cjmp}, ppc64.ABNE: {Flags: gc.Cjmp}, ppc64.ABGE: {Flags: gc.Cjmp}, ppc64.ABLT: {Flags: gc.Cjmp}, ppc64.ABGT: {Flags: gc.Cjmp}, ppc64.ABLE: {Flags: gc.Cjmp}, obj.ARET: {Flags: gc.Break}, obj.ADUFFZERO: {Flags: gc.Call}, obj.ADUFFCOPY: {Flags: gc.Call}, } var initproginfo_initialized int func initproginfo() { var addvariant = []int{V_CC, V_V, V_CC | V_V} if initproginfo_initialized != 0 { return } initproginfo_initialized = 1 // Perform one-time expansion of instructions in progtable to // their CC, V, and VCC variants var as2 int var i int var variant int for as := int(0); as < len(progtable); as++ { if progtable[as].Flags == 0 { continue } variant = as2variant(as) for i = 0; i < len(addvariant); i++ { as2 = variant2as(as, variant|addvariant[i]) if as2 != 0 && progtable[as2].Flags == 0 { progtable[as2] = progtable[as] } } } } func proginfo(p *obj.Prog) { initproginfo() info := &p.Info *info = progtable[p.As] if info.Flags == 0 { gc.Fatalf("proginfo: unknown instruction %v", p) } if (info.Flags&gc.RegRead != 0) && p.Reg == 0 { info.Flags &^= gc.RegRead info.Flags |= gc.RightRead /*CanRegRead |*/ } if (p.From.Type == obj.TYPE_MEM || p.From.Type == obj.TYPE_ADDR) && p.From.Reg != 0 { info.Regindex |= RtoB(int(p.From.Reg)) if info.Flags&gc.PostInc != 0 { info.Regset |= RtoB(int(p.From.Reg)) } } if (p.To.Type == obj.TYPE_MEM || p.To.Type == obj.TYPE_ADDR) && p.To.Reg != 0 { info.Regindex |= RtoB(int(p.To.Reg)) if info.Flags&gc.PostInc != 0 { info.Regset |= RtoB(int(p.To.Reg)) } } if p.From.Type == obj.TYPE_ADDR && p.From.Sym != nil && (info.Flags&gc.LeftRead != 0) { info.Flags &^= gc.LeftRead info.Flags |= gc.LeftAddr } if p.As == obj.ADUFFZERO { info.Reguse |= 1<<0 | RtoB(ppc64.REG_R3) info.Regset |= RtoB(ppc64.REG_R3) } if p.As == obj.ADUFFCOPY { // TODO(austin) Revisit when duffcopy is implemented info.Reguse |= RtoB(ppc64.REG_R3) | RtoB(ppc64.REG_R4) | RtoB(ppc64.REG_R5) info.Regset |= RtoB(ppc64.REG_R3) | RtoB(ppc64.REG_R4) } } // Instruction variants table. Initially this contains entries only // for the "base" form of each instruction. On the first call to // as2variant or variant2as, we'll add the variants to the table. var varianttable = [ppc64.ALAST][4]int{ ppc64.AADD: {ppc64.AADD, ppc64.AADDCC, ppc64.AADDV, ppc64.AADDVCC}, ppc64.AADDC: {ppc64.AADDC, ppc64.AADDCCC, ppc64.AADDCV, ppc64.AADDCVCC}, ppc64.AADDE: {ppc64.AADDE, ppc64.AADDECC, ppc64.AADDEV, ppc64.AADDEVCC}, ppc64.AADDME: {ppc64.AADDME, ppc64.AADDMECC, ppc64.AADDMEV, ppc64.AADDMEVCC}, ppc64.AADDZE: {ppc64.AADDZE, ppc64.AADDZECC, ppc64.AADDZEV, ppc64.AADDZEVCC}, ppc64.AAND: {ppc64.AAND, ppc64.AANDCC, 0, 0}, ppc64.AANDN: {ppc64.AANDN, ppc64.AANDNCC, 0, 0}, ppc64.ACNTLZD: {ppc64.ACNTLZD, ppc64.ACNTLZDCC, 0, 0}, ppc64.ACNTLZW: {ppc64.ACNTLZW, ppc64.ACNTLZWCC, 0, 0}, ppc64.ADIVD: {ppc64.ADIVD, ppc64.ADIVDCC, ppc64.ADIVDV, ppc64.ADIVDVCC}, ppc64.ADIVDU: {ppc64.ADIVDU, ppc64.ADIVDUCC, ppc64.ADIVDUV, ppc64.ADIVDUVCC}, ppc64.ADIVW: {ppc64.ADIVW, ppc64.ADIVWCC, ppc64.ADIVWV, ppc64.ADIVWVCC}, ppc64.ADIVWU: {ppc64.ADIVWU, ppc64.ADIVWUCC, ppc64.ADIVWUV, ppc64.ADIVWUVCC}, ppc64.AEQV: {ppc64.AEQV, ppc64.AEQVCC, 0, 0}, ppc64.AEXTSB: {ppc64.AEXTSB, ppc64.AEXTSBCC, 0, 0}, ppc64.AEXTSH: {ppc64.AEXTSH, ppc64.AEXTSHCC, 0, 0}, ppc64.AEXTSW: {ppc64.AEXTSW, ppc64.AEXTSWCC, 0, 0}, ppc64.AFABS: {ppc64.AFABS, ppc64.AFABSCC, 0, 0}, ppc64.AFADD: {ppc64.AFADD, ppc64.AFADDCC, 0, 0}, ppc64.AFADDS: {ppc64.AFADDS, ppc64.AFADDSCC, 0, 0}, ppc64.AFCFID: {ppc64.AFCFID, ppc64.AFCFIDCC, 0, 0}, ppc64.AFCTID: {ppc64.AFCTID, ppc64.AFCTIDCC, 0, 0}, ppc64.AFCTIDZ: {ppc64.AFCTIDZ, ppc64.AFCTIDZCC, 0, 0}, ppc64.AFCTIW: {ppc64.AFCTIW, ppc64.AFCTIWCC, 0, 0}, ppc64.AFCTIWZ: {ppc64.AFCTIWZ, ppc64.AFCTIWZCC, 0, 0}, ppc64.AFDIV: {ppc64.AFDIV, ppc64.AFDIVCC, 0, 0}, ppc64.AFDIVS: {ppc64.AFDIVS, ppc64.AFDIVSCC, 0, 0}, ppc64.AFMADD: {ppc64.AFMADD, ppc64.AFMADDCC, 0, 0}, ppc64.AFMADDS: {ppc64.AFMADDS, ppc64.AFMADDSCC, 0, 0}, ppc64.AFMOVD: {ppc64.AFMOVD, ppc64.AFMOVDCC, 0, 0}, ppc64.AFMSUB: {ppc64.AFMSUB, ppc64.AFMSUBCC, 0, 0}, ppc64.AFMSUBS: {ppc64.AFMSUBS, ppc64.AFMSUBSCC, 0, 0}, ppc64.AFMUL: {ppc64.AFMUL, ppc64.AFMULCC, 0, 0}, ppc64.AFMULS: {ppc64.AFMULS, ppc64.AFMULSCC, 0, 0}, ppc64.AFNABS: {ppc64.AFNABS, ppc64.AFNABSCC, 0, 0}, ppc64.AFNEG: {ppc64.AFNEG, ppc64.AFNEGCC, 0, 0}, ppc64.AFNMADD: {ppc64.AFNMADD, ppc64.AFNMADDCC, 0, 0}, ppc64.AFNMADDS: {ppc64.AFNMADDS, ppc64.AFNMADDSCC, 0, 0}, ppc64.AFNMSUB: {ppc64.AFNMSUB, ppc64.AFNMSUBCC, 0, 0}, ppc64.AFNMSUBS: {ppc64.AFNMSUBS, ppc64.AFNMSUBSCC, 0, 0}, ppc64.AFRES: {ppc64.AFRES, ppc64.AFRESCC, 0, 0}, ppc64.AFRSP: {ppc64.AFRSP, ppc64.AFRSPCC, 0, 0}, ppc64.AFRSQRTE: {ppc64.AFRSQRTE, ppc64.AFRSQRTECC, 0, 0}, ppc64.AFSEL: {ppc64.AFSEL, ppc64.AFSELCC, 0, 0}, ppc64.AFSQRT: {ppc64.AFSQRT, ppc64.AFSQRTCC, 0, 0}, ppc64.AFSQRTS: {ppc64.AFSQRTS, ppc64.AFSQRTSCC, 0, 0}, ppc64.AFSUB: {ppc64.AFSUB, ppc64.AFSUBCC, 0, 0}, ppc64.AFSUBS: {ppc64.AFSUBS, ppc64.AFSUBSCC, 0, 0}, ppc64.AMTFSB0: {ppc64.AMTFSB0, ppc64.AMTFSB0CC, 0, 0}, ppc64.AMTFSB1: {ppc64.AMTFSB1, ppc64.AMTFSB1CC, 0, 0}, ppc64.AMULHD: {ppc64.AMULHD, ppc64.AMULHDCC, 0, 0}, ppc64.AMULHDU: {ppc64.AMULHDU, ppc64.AMULHDUCC, 0, 0}, ppc64.AMULHW: {ppc64.AMULHW, ppc64.AMULHWCC, 0, 0}, ppc64.AMULHWU: {ppc64.AMULHWU, ppc64.AMULHWUCC, 0, 0}, ppc64.AMULLD: {ppc64.AMULLD, ppc64.AMULLDCC, ppc64.AMULLDV, ppc64.AMULLDVCC}, ppc64.AMULLW: {ppc64.AMULLW, ppc64.AMULLWCC, ppc64.AMULLWV, ppc64.AMULLWVCC}, ppc64.ANAND: {ppc64.ANAND, ppc64.ANANDCC, 0, 0}, ppc64.ANEG: {ppc64.ANEG, ppc64.ANEGCC, ppc64.ANEGV, ppc64.ANEGVCC}, ppc64.ANOR: {ppc64.ANOR, ppc64.ANORCC, 0, 0}, ppc64.AOR: {ppc64.AOR, ppc64.AORCC, 0, 0}, ppc64.AORN: {ppc64.AORN, ppc64.AORNCC, 0, 0}, ppc64.AREM: {ppc64.AREM, ppc64.AREMCC, ppc64.AREMV, ppc64.AREMVCC}, ppc64.AREMD: {ppc64.AREMD, ppc64.AREMDCC, ppc64.AREMDV, ppc64.AREMDVCC}, ppc64.AREMDU: {ppc64.AREMDU, ppc64.AREMDUCC, ppc64.AREMDUV, ppc64.AREMDUVCC}, ppc64.AREMU: {ppc64.AREMU, ppc64.AREMUCC, ppc64.AREMUV, ppc64.AREMUVCC}, ppc64.ARLDC: {ppc64.ARLDC, ppc64.ARLDCCC, 0, 0}, ppc64.ARLDCL: {ppc64.ARLDCL, ppc64.ARLDCLCC, 0, 0}, ppc64.ARLDCR: {ppc64.ARLDCR, ppc64.ARLDCRCC, 0, 0}, ppc64.ARLDMI: {ppc64.ARLDMI, ppc64.ARLDMICC, 0, 0}, ppc64.ARLWMI: {ppc64.ARLWMI, ppc64.ARLWMICC, 0, 0}, ppc64.ARLWNM: {ppc64.ARLWNM, ppc64.ARLWNMCC, 0, 0}, ppc64.ASLD: {ppc64.ASLD, ppc64.ASLDCC, 0, 0}, ppc64.ASLW: {ppc64.ASLW, ppc64.ASLWCC, 0, 0}, ppc64.ASRAD: {ppc64.ASRAD, ppc64.ASRADCC, 0, 0}, ppc64.ASRAW: {ppc64.ASRAW, ppc64.ASRAWCC, 0, 0}, ppc64.ASRD: {ppc64.ASRD, ppc64.ASRDCC, 0, 0}, ppc64.ASRW: {ppc64.ASRW, ppc64.ASRWCC, 0, 0}, ppc64.ASUB: {ppc64.ASUB, ppc64.ASUBCC, ppc64.ASUBV, ppc64.ASUBVCC}, ppc64.ASUBC: {ppc64.ASUBC, ppc64.ASUBCCC, ppc64.ASUBCV, ppc64.ASUBCVCC}, ppc64.ASUBE: {ppc64.ASUBE, ppc64.ASUBECC, ppc64.ASUBEV, ppc64.ASUBEVCC}, ppc64.ASUBME: {ppc64.ASUBME, ppc64.ASUBMECC, ppc64.ASUBMEV, ppc64.ASUBMEVCC}, ppc64.ASUBZE: {ppc64.ASUBZE, ppc64.ASUBZECC, ppc64.ASUBZEV, ppc64.ASUBZEVCC}, ppc64.AXOR: {ppc64.AXOR, ppc64.AXORCC, 0, 0}, } var initvariants_initialized int func initvariants() { if initvariants_initialized != 0 { return } initvariants_initialized = 1 var j int for i := int(0); i < len(varianttable); i++ { if varianttable[i][0] == 0 { // Instruction has no variants varianttable[i][0] = i continue } // Copy base form to other variants if varianttable[i][0] == i { for j = 0; j < len(varianttable[i]); j++ { varianttable[varianttable[i][j]] = varianttable[i] } } } } // as2variant returns the variant (V_*) flags of instruction as. func as2variant(as int) int { initvariants() for i := int(0); i < len(varianttable[as]); i++ { if varianttable[as][i] == as { return i } } gc.Fatalf("as2variant: instruction %v is not a variant of itself", obj.Aconv(as)) return 0 } // variant2as returns the instruction as with the given variant (V_*) flags. // If no such variant exists, this returns 0. func variant2as(as int, flags int) int { initvariants() return varianttable[as][flags] }
mwhudson/go
src/cmd/compile/internal/ppc64/prog.go
GO
bsd-3-clause
13,297
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_int_loop_04.cpp Label Definition File: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805.label.xml Template File: sources-sink-04.tmpl.cpp */ /* * @description * CWE: 122 Heap Based Buffer Overflow * BadSource: Allocate using new[] and set data pointer to a small buffer * GoodSource: Allocate using new[] and set data pointer to a large buffer * Sink: loop * BadSink : Copy int array to data using a loop * Flow Variant: 04 Control flow: if(STATIC_CONST_TRUE) and if(STATIC_CONST_FALSE) * * */ #include "std_testcase.h" /* The two variables below are declared "const", so a tool should be able to identify that reads of these will always return their initialized values. */ static const int STATIC_CONST_TRUE = 1; /* true */ static const int STATIC_CONST_FALSE = 0; /* false */ namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_int_loop_04 { #ifndef OMITBAD void bad() { int * data; data = NULL; if(STATIC_CONST_TRUE) { /* FLAW: Allocate using new[] and point data to a small buffer that is smaller than the large buffer used in the sinks */ data = new int[50]; } { int source[100] = {0}; /* fill with 0's */ { size_t i; /* POTENTIAL FLAW: Possible buffer overflow if data < 100 */ for (i = 0; i < 100; i++) { data[i] = source[i]; } printIntLine(data[0]); delete [] data; } } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B1() - use goodsource and badsink by changing the STATIC_CONST_TRUE to STATIC_CONST_FALSE */ static void goodG2B1() { int * data; data = NULL; if(STATIC_CONST_FALSE) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); } else { /* FIX: Allocate using new[] and point data to a large buffer that is at least as large as the large buffer used in the sink */ data = new int[100]; } { int source[100] = {0}; /* fill with 0's */ { size_t i; /* POTENTIAL FLAW: Possible buffer overflow if data < 100 */ for (i = 0; i < 100; i++) { data[i] = source[i]; } printIntLine(data[0]); delete [] data; } } } /* goodG2B2() - use goodsource and badsink by reversing the blocks in the if statement */ static void goodG2B2() { int * data; data = NULL; if(STATIC_CONST_TRUE) { /* FIX: Allocate using new[] and point data to a large buffer that is at least as large as the large buffer used in the sink */ data = new int[100]; } { int source[100] = {0}; /* fill with 0's */ { size_t i; /* POTENTIAL FLAW: Possible buffer overflow if data < 100 */ for (i = 0; i < 100; i++) { data[i] = source[i]; } printIntLine(data[0]); delete [] data; } } } void good() { goodG2B1(); goodG2B2(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_int_loop_04; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
JianpingZeng/xcc
xcc/test/juliet/testcases/CWE122_Heap_Based_Buffer_Overflow/s03/CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_int_loop_04.cpp
C++
bsd-3-clause
4,189
using System; using System.Collections; namespace MyGeneration.CodeSmithConversion.Template { public enum CstTokenType { Code = 0, ResponseWriteShortcutCode, RunAtServerCode, Literal, Comment, EscapedStartTag, EscapedEndTag } /// <summary> /// Summary description for CstToken. /// </summary> public class CstToken { private string text; private CstTokenType tokenType = CstTokenType.Literal; public CstToken(CstTokenType tokenType, string text) { this.tokenType = tokenType; this.text = text; } public string Text { get { return text; } set { text = value; } } public CstTokenType TokenType { get { return tokenType; } set { tokenType = value; } } } }
cafephin/mygeneration
src/plugins/MyGeneration.UI.Plugins.CodeSmith2MyGen/Template/CstToken.cs
C#
bsd-3-clause
726
<div> <a href="#" title="Click or press enter to display help" class="dropdown standalone-help" data-toggle="reset-page-help" tab-index="0"> <span class="icon-circle"><i class="fa fa-info"></i></span> </a> </div> <div class="dropdown-pane" id="reset-page-help" data-dropdown data-hover="true" data-hover-pane="true" data-auto-focus="true"> <p>If you cannot complete the password reset form, please bring University-issued photo identification to the Bruin OnLine Help Desk located in Suite 124, Kerckhoff Hall. If you are not able to visit the Help Desk, please fax in a completed copy of the <a href="/files/service_request.pdf">UCLA Logon Service Request Form</a>, with all required supporting documentation.</p> </div>
ucla/iam
src/partials/help-reset.html
HTML
bsd-3-clause
786
/* * @description Expression is always true via if (unsigned int >= 0) * * */ #include "std_testcase.h" #ifndef OMITBAD void CWE571_Expression_Always_True__unsigned_int_01_bad() { /* Ensure (0 <= intBad < UINT_MAX) and that uIntBad is pseudo-random */ unsigned int uIntBad = (unsigned int)(rand() * 2); /* FLAW: This expression is always true */ if (uIntBad >= 0) { printLine("Always prints"); } } #endif /* OMITBAD */ #ifndef OMITGOOD static void good1() { int intGood = rand(); /* FIX: Possibly evaluate to true */ if (intGood > (RAND_MAX / 2)) { printLine("Sometimes prints"); } } void CWE571_Expression_Always_True__unsigned_int_01_good() { good1(); } #endif /* OMITGOOD */ /* Below is the main(). It is only used when building this testcase on * its own for testing or for building a binary to use in testing binary * analysis tools. It is not used when compiling all the testcases as one * application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); CWE571_Expression_Always_True__unsigned_int_01_good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); CWE571_Expression_Always_True__unsigned_int_01_bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
JianpingZeng/xcc
xcc/test/juliet/testcases/CWE571_Expression_Always_True/CWE571_Expression_Always_True__unsigned_int_01.c
C
bsd-3-clause
1,609
// 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. #ifndef CHROME_BROWSER_UI_WEBUI_OPTIONS_CHROMEOS_STATS_OPTIONS_HANDLER_H_ #define CHROME_BROWSER_UI_WEBUI_OPTIONS_CHROMEOS_STATS_OPTIONS_HANDLER_H_ #pragma once #include "base/compiler_specific.h" #include "chrome/browser/ui/webui/options/options_ui.h" namespace chromeos { // ChromeOS handler for "Stats/crash reporting to Google" option of the Advanced // settings page. This handler does only ChromeOS-specific actions while default // code is in Chrome's AdvancedOptionsHandler // (chrome/browser/webui/advanced_options_handler.cc). class StatsOptionsHandler : public OptionsPageUIHandler { public: StatsOptionsHandler(); // OptionsPageUIHandler implementation. virtual void GetLocalizedValues( base::DictionaryValue* localized_strings) OVERRIDE; virtual void Initialize() OVERRIDE; // WebUIMessageHandler implementation. virtual void RegisterMessages() OVERRIDE; private: void HandleMetricsReportingCheckbox(const base::ListValue* args); DISALLOW_COPY_AND_ASSIGN(StatsOptionsHandler); }; } // namespace chromeos #endif // CHROME_BROWSER_UI_WEBUI_OPTIONS_CHROMEOS_STATS_OPTIONS_HANDLER_H_
aYukiSekiguchi/ACCESS-Chromium
chrome/browser/ui/webui/options/chromeos/stats_options_handler.h
C
bsd-3-clause
1,298
ENV['RAILS_ENV'] ||= 'test' if ENV['TRAVIS'] require 'coveralls' Coveralls.wear!('rails') SimpleCov.start do add_filter '.bundle' add_filter 'spec' end end require 'spec_helper' require File.expand_path('../../config/environment', __FILE__) require 'rspec/rails' require 'rspec/its' require 'shoulda/matchers' require 'capybara/poltergeist' Capybara.javascript_driver = :poltergeist Capybara.default_wait_time = 30 Rails.logger.level = 4 # Requires supporting ruby files with custom matchers and macros, etc, in # spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are # run as spec files by default. This means that files in spec/support that end # in _spec.rb will both be required and run as specs, causing the specs to be # run twice. It is recommended that you do not name files matching this glob to # end with _spec.rb. You can configure this pattern with the --pattern # option on the command line or in ~/.rspec, .rspec or `.rspec-local`. Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f } # Checks for pending migrations before tests are run. ActiveRecord::Migration.maintain_test_schema! RSpec.configure do |config| config.include FactoryGirl::Syntax::Methods config.include Features::SessionHelpers, type: :feature config.include Features::FormHelpers, type: :feature config.include Features::ScheduleHelpers, type: :feature config.include Features::PhoneHelpers, type: :feature config.include Features::ContactHelpers, type: :feature config.include Requests::RequestHelpers, type: :request config.include DefaultHeaders, type: :request config.include MailerMacros # rspec-rails 3+ will no longer automatically infer an example group's spec # type from the file location. You can explicitly opt-in to this feature by # uncommenting the setting below. config.infer_spec_type_from_file_location! # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures config.fixture_path = "#{::Rails.root}/spec/support/fixtures" # If you're not using ActiveRecord, or you'd prefer not to run each of your # examples within a transaction, remove the following line or assign false # instead of true. config.use_transactional_fixtures = false # require 'active_record_spec_helper' end
volkanunsal/nyc-prepared
spec/rails_helper.rb
Ruby
bsd-3-clause
2,305
/** * Copyright (c) 2013-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. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @emails oncall+jsinfra */ 'use strict'; jest.unmock('everyObject'); var everyObject = require('everyObject'); describe('everyObject', function() { var mockObject; var mockCallback; beforeEach(() => { mockObject = {foo: 1, bar: 2, baz: 3}; mockCallback = jest.fn(); }); it('handles null', () => { everyObject(null, mockCallback); expect(mockCallback).not.toBeCalled(); }); it('returns true if all properties pass the test', () => { mockCallback.mockImplementation(() => true); var result = everyObject(mockObject, mockCallback); expect(result).toBeTruthy(); expect(mockCallback.mock.calls).toEqual([ [1, 'foo', mockObject], [2, 'bar', mockObject], [3, 'baz', mockObject] ]); }); it('returns false if any of the properties fail the test', () => { mockCallback.mockImplementation(() => false); var result = everyObject(mockObject, mockCallback); expect(result).toBeFalsy(); expect(mockCallback).toBeCalled(); }); it('returns immediately upon finding a property that fails the test', () => { mockCallback.mockImplementation(() => false); var result = everyObject(mockObject, mockCallback); expect(result).toBeFalsy(); expect(mockCallback.mock.calls.length).toEqual(1); }); });
chicoxyzzy/fbjs
packages/fbjs/src/functional/__tests__/everyObject-test.js
JavaScript
bsd-3-clause
1,608
// 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. #ifndef CHROME_BROWSER_UI_VIEWS_OMNIBOX_OMNIBOX_POPUP_CONTENTS_VIEW_H_ #define CHROME_BROWSER_UI_VIEWS_OMNIBOX_OMNIBOX_POPUP_CONTENTS_VIEW_H_ #include <stddef.h> #include "base/memory/weak_ptr.h" #include "components/omnibox/browser/omnibox_popup_selection.h" #include "components/omnibox/browser/omnibox_popup_view.h" #include "components/prefs/pref_change_registrar.h" #include "ui/base/metadata/metadata_header_macros.h" #include "ui/base/window_open_disposition.h" #include "ui/gfx/font_list.h" #include "ui/gfx/image/image.h" #include "ui/views/view.h" #include "ui/views/widget/widget_observer.h" struct AutocompleteMatch; class LocationBarView; class OmniboxEditModel; class OmniboxResultView; class OmniboxViewViews; class WebUIOmniboxPopupView; // A view representing the contents of the autocomplete popup. class OmniboxPopupContentsView : public views::View, public OmniboxPopupView, public views::WidgetObserver { public: METADATA_HEADER(OmniboxPopupContentsView); OmniboxPopupContentsView(OmniboxViewViews* omnibox_view, OmniboxEditModel* edit_model, LocationBarView* location_bar_view); OmniboxPopupContentsView(const OmniboxPopupContentsView&) = delete; OmniboxPopupContentsView& operator=(const OmniboxPopupContentsView&) = delete; ~OmniboxPopupContentsView() override; // Opens a match from the list specified by |index| with the type of tab or // window specified by |disposition|. void OpenMatch(WindowOpenDisposition disposition, base::TimeTicks match_selection_timestamp); void OpenMatch(size_t index, WindowOpenDisposition disposition, base::TimeTicks match_selection_timestamp); // Returns the icon that should be displayed next to |match|. If the icon is // available as a vector icon, it will be |vector_icon_color|. gfx::Image GetMatchIcon(const AutocompleteMatch& match, SkColor vector_icon_color) const; // Sets the line specified by |index| as selected and, if |index| is // different than the previous index, sets the line state to NORMAL. virtual void SetSelectedIndex(size_t index); // Returns the selected line. // Note: This and `SetSelectedIndex` above are used by property // metadata and must follow the metadata conventions. virtual size_t GetSelectedIndex() const; // Returns current popup selection (includes line index). virtual OmniboxPopupSelection GetSelection() const; // Called by the active result view to inform model (due to mouse event). void UnselectButton(); // Gets the OmniboxResultView for match |i|. OmniboxResultView* result_view_at(size_t i); // Currently selected OmniboxResultView, or nullptr if nothing is selected. OmniboxResultView* GetSelectedResultView(); // Returns whether we're in experimental keyword mode and the input gives // sufficient confidence that the user wants keyword mode. bool InExplicitExperimentalKeywordMode(); // OmniboxPopupView: bool IsOpen() const override; void InvalidateLine(size_t line) override; void OnSelectionChanged(OmniboxPopupSelection old_selection, OmniboxPopupSelection new_selection) override; void UpdatePopupAppearance() override; void ProvideButtonFocusHint(size_t line) override; void OnMatchIconUpdated(size_t match_index) override; void OnDragCanceled() override; // views::View: bool OnMouseDragged(const ui::MouseEvent& event) override; void OnGestureEvent(ui::GestureEvent* event) override; void GetAccessibleNodeData(ui::AXNodeData* node_data) override; // views::WidgetObserver: void OnWidgetBoundsChanged(views::Widget* widget, const gfx::Rect& new_bounds) override; void FireAXEventsForNewActiveDescendant(View* descendant_view); private: friend class OmniboxPopupContentsViewTest; friend class OmniboxSuggestionButtonRowBrowserTest; class AutocompletePopupWidget; // Returns the target popup bounds in screen coordinates based on the bounds // of |location_bar_view_|. gfx::Rect GetTargetBounds() const; // Returns true if the model has a match at the specified index. bool HasMatchAt(size_t index) const; // Returns the match at the specified index within the model. const AutocompleteMatch& GetMatchAtIndex(size_t index) const; // Find the index of the match under the given |point|, specified in window // coordinates. Returns OmniboxPopupSelection::kNoMatch if there isn't a match // at the specified point. size_t GetIndexForPoint(const gfx::Point& point); // Update which result views are visible when the group visibility changes. void OnSuggestionGroupVisibilityUpdate(); // Gets the pref service for this view. May return nullptr in tests. PrefService* GetPrefService() const; // The popup that contains this view. We create this, but it deletes itself // when its window is destroyed. This is a WeakPtr because it's possible for // the OS to destroy the window and thus delete this object before we're // deleted, or without our knowledge. base::WeakPtr<AutocompletePopupWidget> popup_; // The edit view that invokes us. OmniboxViewViews* omnibox_view_; // The location bar view that owns |omnibox_view_|. May be nullptr in tests. LocationBarView* location_bar_view_; // The child WebView for the suggestions. This only exists if the // omnibox::kWebUIOmniboxPopup flag is on. WebUIOmniboxPopupView* webui_view_ = nullptr; // A pref change registrar for toggling result view visibility. PrefChangeRegistrar pref_change_registrar_; OmniboxEditModel* edit_model_; }; #endif // CHROME_BROWSER_UI_VIEWS_OMNIBOX_OMNIBOX_POPUP_CONTENTS_VIEW_H_
scheib/chromium
chrome/browser/ui/views/omnibox/omnibox_popup_contents_view.h
C
bsd-3-clause
5,980
<!DOCTYPE html> <html dir="ltr" lang="pl"> <head> <title>Foreign Function Interface - Rubinius</title> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta content='pl' http-equiv='content-language'> <meta content='Rubinius is an implementation of the Ruby programming language. The Rubinius bytecode virtual machine is written in C++. The bytecode compiler is written in pure Ruby. The vast majority of the core library is also written in Ruby, with some supporting primitives that interact with the VM directly.' name='description'> <link href='/' rel='home'> <link href='/' rel='start'> <link href='/doc/pl/systems/primitives' rel='prev' title='Primitives'> <link href='/doc/pl/systems/concurrency' rel='next' title='Współbieżność'> <!--[if IE]><script src="http://html5shiv.googlecode.com/svn/trunk/html5.js" type="text/javascript"></script><![endif]--> <script src="/javascripts/jquery-1.3.2.js"></script> <script src="/javascripts/paging_keys.js"></script> <script src="/javascripts/application.js"></script> <style>article, aside, dialog, figure, footer, header, hgroup, menu, nav, section { display: block; }</style> <link href="/stylesheets/blueprint/screen.css" media="screen" rel="stylesheet" /> <link href="/stylesheets/application.css" media="screen" rel="stylesheet" /> <link href="/stylesheets/blueprint/print.css" media="print" rel="stylesheet" /> <!--[if IE]><link href="/stylesheets/blueprint/ie.css" media="screen" rel="stylesheet" type="text/css" /><![endif]--> <!--[if IE]><link href="/stylesheets/ie.css" media="screen" rel="stylesheet" type="text/css" /><![endif]--> <link href="/stylesheets/pygments.css" media="screen" rel="stylesheet" /> </head> <body> <div class='container'> <div class='span-21 doc_menu'> <header> <nav> <ul> <li><a href="/">Home</a></li> <li><a id="blog" href="/blog">Blog</a></li> <li><a id="documentation" href="/doc/en">Documentation</a></li> <li><a href="/projects">Projects</a></li> <li><a href="/roadmap">Roadmap</a></li> <li><a href="/releases">Releases</a></li> </ul> </nav> </header> </div> <div class='span-3 last'> <div id='version'> <a href="/releases/1.2.4">1.2.4</a> </div> </div> </div> <div class="container languages"> <nav> <span class="label">Język:</span> <ul> <li><a href="/doc/de/systems/ffi/" >de</a></li> <li><a href="/doc/en/systems/ffi/" >en</a></li> <li><a href="/doc/es/systems/ffi/" >es</a></li> <li><a href="/doc/fr/systems/ffi/" >fr</a></li> <li><a href="/doc/ja/systems/ffi/" >ja</a></li> <li><a href="/doc/pl/systems/ffi/" class="current" >pl</a></li> <li><a href="/doc/pt-br/systems/ffi/" >pt-br</a></li> <li><a href="/doc/ru/systems/ffi/" >ru</a></li> </ul> </nav> </div> <div class="container doc_page_nav"> <span class="label">Wstecz:</span> <a href="/doc/pl/systems/primitives">Primitives</a> <span class="label">Do góry:</span> <a href="/doc/pl/">Spis treści</a> <span class="label">Dalej:</span> <a href="/doc/pl/systems/concurrency">Współbieżność</a> </div> <div class="container documentation"> <h2>Foreign Function Interface</h2> <div class="review"> <p>This topic has missing or partial documentation. Please help us improve it.</p> <p> See <a href="/doc/pl/how-to/write-documentation">How-To - Write Documentation</a> </p> </div> </div> <div class="container doc_page_nav"> <span class="label">Wstecz:</span> <a href="/doc/pl/systems/primitives">Primitives</a> <span class="label">Do góry:</span> <a href="/doc/pl/">Spis treści</a> <span class="label">Dalej:</span> <a href="/doc/pl/systems/concurrency">Współbieżność</a> </div> <div class="container"> <div id="disqus_thread"></div> <script type="text/javascript"> var disqus_shortname = 'rubinius'; var disqus_identifier = '/doc/pl/systems/ffi/'; var disqus_url = 'http://rubini.us/doc/pl/systems/ffi/'; (function() { var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true; dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js'; (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq); })(); </script> <noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript> </div> <footer> <div class='container'> <nav> <ul> <li><a rel="external" href="http://twitter.com/rubinius">Follow Rubinius on Twitter</a></li> <li><a rel="external" href="http://github.com/rubinius/rubinius">Fork Rubinius on github</a></li> <li><a rel="external" href="http://engineyard.com">An Engine Yard project</a></li> </ul> </nav> </div> </footer> <script> var _gaq=[['_setAccount','UA-12328521-1'],['_trackPageview']]; (function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];g.async=1; g.src=('https:'==location.protocol?'//ssl':'//www')+'.google-analytics.com/ga.js'; s.parentNode.insertBefore(g,s)}(document,'script')); </script> </body> </html>
slawosz/rubinius
web/_site/doc/pl/systems/ffi/index.html
HTML
bsd-3-clause
5,609
/* * Copyright (c) 2015, 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. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include "UmbrellaProtocol.h" #include <folly/Bits.h> #include "mcrouter/lib/McReply.h" #include "mcrouter/lib/McRequest.h" #include "mcrouter/lib/mc/umbrella.h" #ifndef LIBMC_FBTRACE_DISABLE #include "mcrouter/lib/mc/mc_fbtrace_info.h" #endif static_assert( mc_nops == 27, "If you add a new mc_op, make sure to update lib/mc/umbrella_conv.h"); static_assert( UM_NOPS == 28, "If you add a new mc_op, make sure to update lib/mc/umbrella_conv.h"); static_assert( mc_nres == 31, "If you add a new mc_res, make sure to update lib/mc/umbrella_conv.h"); namespace facebook { namespace memcache { UmbrellaParseStatus umbrellaParseHeader(const uint8_t* buf, size_t nbuf, UmbrellaMessageInfo& infoOut) { if (nbuf < sizeof(entry_list_msg_t)) { return UmbrellaParseStatus::NOT_ENOUGH_DATA; } entry_list_msg_t* header = (entry_list_msg_t*) buf; if (header->msg_header.magic_byte != ENTRY_LIST_MAGIC_BYTE) { return UmbrellaParseStatus::MESSAGE_PARSE_ERROR; } infoOut.version = static_cast<UmbrellaVersion>(header->msg_header.version); if (infoOut.version == UmbrellaVersion::BASIC) { /* Basic version layout: }0NNSSSS, <um_elist_entry_t>*nentries, body Where N is nentries and S is message size, both big endian */ size_t messageSize = folly::Endian::big<uint32_t>(header->total_size); uint16_t nentries = folly::Endian::big<uint16_t>(header->nentries); infoOut.headerSize = sizeof(entry_list_msg_t) + sizeof(um_elist_entry_t) * nentries; if (infoOut.headerSize > messageSize) { return UmbrellaParseStatus::MESSAGE_PARSE_ERROR; } infoOut.bodySize = messageSize - infoOut.headerSize; } else if (infoOut.version == UmbrellaVersion::TYPED_REQUEST) { /* Typed request layout: }1TTSSSSFFFFRRRR, body Where T is type ID, S is message size, F is flags and R is reqid (all little-endian) */ size_t messageSize = folly::Endian::little<uint32_t>(header->total_size); infoOut.typeId = folly::Endian::little<uint16_t>(header->nentries); infoOut.headerSize = sizeof(entry_list_msg_t) + sizeof(uint32_t) + sizeof(uint32_t); if (infoOut.headerSize > messageSize) { return UmbrellaParseStatus::MESSAGE_PARSE_ERROR; } infoOut.bodySize = messageSize - infoOut.headerSize; } else { return UmbrellaParseStatus::MESSAGE_PARSE_ERROR; } return UmbrellaParseStatus::OK; } uint64_t umbrellaDetermineReqId(const uint8_t* header, size_t nheader) { auto msg = reinterpret_cast<const entry_list_msg_t*>(header); size_t nentries = folly::Endian::big((uint16_t)msg->nentries); if (reinterpret_cast<const uint8_t*>(&msg->entries[nentries]) != header + nheader) { throw std::runtime_error("Invalid number of entries"); } for (size_t i = 0; i < nentries; ++i) { auto& entry = msg->entries[i]; size_t tag = folly::Endian::big((uint16_t)entry.tag); if (tag == msg_reqid) { uint64_t val = folly::Endian::big((uint64_t)entry.data.val); if (val == 0) { throw std::runtime_error("invalid reqid"); } return val; } } throw std::runtime_error("missing reqid"); } McRequest umbrellaParseRequest(const folly::IOBuf& source, const uint8_t* header, size_t nheader, const uint8_t* body, size_t nbody, mc_op_t& opOut, uint64_t& reqidOut) { McRequest req; opOut = mc_op_unknown; reqidOut = 0; auto msg = reinterpret_cast<const entry_list_msg_t*>(header); size_t nentries = folly::Endian::big((uint16_t)msg->nentries); if (reinterpret_cast<const uint8_t*>(&msg->entries[nentries]) != header + nheader) { throw std::runtime_error("Invalid number of entries"); } for (size_t i = 0; i < nentries; ++i) { auto& entry = msg->entries[i]; size_t tag = folly::Endian::big((uint16_t)entry.tag); size_t val = folly::Endian::big((uint64_t)entry.data.val); switch (tag) { case msg_op: if (val >= UM_NOPS) { throw std::runtime_error("op out of range"); } opOut = static_cast<mc_op_t>(umbrella_op_to_mc[val]); break; case msg_reqid: if (val == 0) { throw std::runtime_error("invalid reqid"); } reqidOut = val; break; case msg_flags: req.setFlags(val); break; case msg_exptime: req.setExptime(val); break; case msg_delta: req.setDelta(val); break; case msg_cas: req.setCas(val); break; case msg_lease_id: req.setLeaseToken(val); break; case msg_key: if (!req.setKeyFrom( source, body + folly::Endian::big((uint32_t)entry.data.str.offset), folly::Endian::big((uint32_t)entry.data.str.len) - 1)) { throw std::runtime_error("Key: invalid offset/length"); } break; case msg_value: if (!req.setValueFrom( source, body + folly::Endian::big((uint32_t)entry.data.str.offset), folly::Endian::big((uint32_t)entry.data.str.len) - 1)) { throw std::runtime_error("Value: invalid offset/length"); } break; #ifndef LIBMC_FBTRACE_DISABLE case msg_fbtrace: { auto off = folly::Endian::big((uint32_t)entry.data.str.offset); auto len = folly::Endian::big((uint32_t)entry.data.str.len) - 1; if (len > FBTRACE_METADATA_SZ) { throw std::runtime_error("Fbtrace metadata too large"); } if (off + len > nbody || off + len < off) { throw std::runtime_error("Fbtrace metadata field invalid"); } auto fbtraceInfo = new_mc_fbtrace_info(0); memcpy(fbtraceInfo->metadata, body + off, len); req.setFbtraceInfo(fbtraceInfo); break; } #endif default: /* Ignore unknown tags silently */ break; } } if (opOut == mc_op_unknown) { throw std::runtime_error("Request missing operation"); } if (!reqidOut) { throw std::runtime_error("Request missing reqid"); } return req; } UmbrellaSerializedMessage::UmbrellaSerializedMessage() { /* These will not change from message to message */ msg_.msg_header.magic_byte = ENTRY_LIST_MAGIC_BYTE; msg_.msg_header.version = UMBRELLA_VERSION_BASIC; iovs_[0].iov_base = &msg_; iovs_[0].iov_len = sizeof(msg_); iovs_[1].iov_base = entries_; } void UmbrellaSerializedMessage::clear() { nEntries_ = nStrings_ = offset_ = 0; error_ = false; } bool UmbrellaSerializedMessage::prepare(const McReply& reply, mc_op_t op, uint64_t reqid, struct iovec*& iovOut, size_t& niovOut) { niovOut = 0; appendInt(I32, msg_op, umbrella_op_from_mc[op]); appendInt(U64, msg_reqid, reqid); appendInt(I32, msg_result, umbrella_res_from_mc[reply.result()]); if (reply.appSpecificErrorCode()) { appendInt(I32, msg_err_code, reply.appSpecificErrorCode()); } if (reply.flags()) { appendInt(U64, msg_flags, reply.flags()); } if (reply.exptime()) { appendInt(U64, msg_exptime, reply.exptime()); } if (reply.delta()) { appendInt(U64, msg_delta, reply.delta()); } if (reply.leaseToken()) { appendInt(U64, msg_lease_id, reply.leaseToken()); } if (reply.cas()) { appendInt(U64, msg_cas, reply.cas()); } if (reply.number()) { appendInt(U64, msg_number, reply.number()); } /* TODO: if we intend to pass chained IOBufs as values, we can optimize this to write multiple iovs directly */ if (reply.hasValue()) { auto valueRange = reply.valueRangeSlow(); appendString(msg_value, reinterpret_cast<const uint8_t*>(valueRange.begin()), valueRange.size()); } /* NOTE: this check must come after all append*() calls */ if (error_) { return false; } niovOut = finalizeMessage(); iovOut = iovs_; return true; } void UmbrellaSerializedMessage::appendInt( entry_type_t type, int32_t tag, uint64_t val) { if (nEntries_ >= kInlineEntries) { error_ = true; return; } um_elist_entry_t& entry = entries_[nEntries_++]; entry.type = folly::Endian::big((uint16_t)type); entry.tag = folly::Endian::big((uint16_t)tag); entry.data.val = folly::Endian::big((uint64_t)val); } void UmbrellaSerializedMessage::appendString( int32_t tag, const uint8_t* data, size_t len, entry_type_t type) { if (nStrings_ >= kInlineStrings) { error_ = true; return; } strings_[nStrings_++] = folly::StringPiece((const char*)data, len); um_elist_entry_t& entry = entries_[nEntries_++]; entry.type = folly::Endian::big((uint16_t)type); entry.tag = folly::Endian::big((uint16_t)tag); entry.data.str.offset = folly::Endian::big((uint32_t)offset_); entry.data.str.len = folly::Endian::big((uint32_t)(len + 1)); offset_ += len + 1; } size_t UmbrellaSerializedMessage::finalizeMessage() { static char nul = '\0'; size_t size = sizeof(entry_list_msg_t) + sizeof(um_elist_entry_t) * nEntries_ + offset_; msg_.total_size = folly::Endian::big((uint32_t)size); msg_.nentries = folly::Endian::big((uint16_t)nEntries_); iovs_[1].iov_len = sizeof(um_elist_entry_t) * nEntries_; size_t niovOut = 2; for (size_t i = 0; i < nStrings_; i++) { iovs_[niovOut].iov_base = (char *)strings_[i].begin(); iovs_[niovOut].iov_len = strings_[i].size(); niovOut++; iovs_[niovOut].iov_base = &nul; iovs_[niovOut].iov_len = 1; niovOut++; } return niovOut; } }}
evertrue/mcrouter
mcrouter/lib/network/UmbrellaProtocol.cpp
C++
bsd-3-clause
10,000
/* * nvbio * Copyright (c) 2011-2014, NVIDIA CORPORATION. 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 NVIDIA CORPORATION 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 NVIDIA CORPORATION 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. */ // // This software is a modification of: // // https://github.com/nmcclatchey/Priority-Deque/blob/master/priority_deque.hpp // // /*----------------------------------------------------------------------------*\ | Copyright (C) 2012-2013 Nathaniel McClatchey | | Released under the Boost Software License Version 1.0, which may be found | | at http://www.boost.org/LICENSE_1_0.txt | \*----------------------------------------------------------------------------*/ /*! @file priority_deque.h // priority_deque.hpp provides the class priority_deque as a thin wrapper // around the functions provided by interval_heap.hpp. // @remark Exception-safety: If the means of movement -- move, copy, or swap, // depending on exception specifications -- do not throw, the guarantee is as // strong as that of the action on the underlying container. (Unless otherwise // specified) // @note Providing a stronger guarantee is impractical. */ #pragma once #include <nvbio/basic/types.h> #include <nvbio/basic/interval_heap.h> // Default comparison (std::less) #include <functional> // Default container (std::vector) #include <vector> namespace nvbio { /// \page priority_deques_page Priority Deques /// /// This module implements a priority deque adaptor, allowing to push/pop from both ends of the container: /// /// - priority_deque /// /// \section ExampleSection Example /// ///\code /// // build a simple priority_deque over 4 integers /// typedef vector_view<uint32*> vector_type; /// typedef priority_deque<uint32, vector_type> deque_type; /// /// uint32 deque_storage[4] = { 5, 3, 8, 1 } /// /// // construct the deque /// deque_type deque( vector_type( 4u, deque_storage ) ); /// /// // pop from both ends /// printf( "%u\n", deque.top() ); // -> 8 /// deque.pop_top(); /// printf( "%u\n", deque.bottom() ); // -> 1 /// deque.pop_bottom(); /// printf( "%u\n", deque.top() ); // -> 5 /// deque.pop_top(); /// /// // perhaps push one more item /// deque.push( 7 ); /// /// // and keep popping /// printf( "%u\n", deque.bottom() ); // -> 3 /// deque.pop_bottom(); /// printf( "%u\n", deque.bottom() ); // -> 7 /// deque.pop_bottom(); ///\endcode /// ///@addtogroup Basic ///@{ ///@defgroup PriorityDeques Priority Deques /// This module implements a priority deque adaptor, allowing to push/pop from both ends of the container. ///@{ //! @brief Efficient double-ended priority queue. template <typename Type, typename Sequence =std::vector<Type>, typename Compare =::std::less<typename Sequence::value_type> > class priority_deque; //! @brief Swaps the elements of two priority deques. template <typename Type, typename Sequence, typename Compare> void swap (priority_deque<Type, Sequence, Compare>& deque1, priority_deque<Type, Sequence, Compare>& deque2); //----------------------------Priority Deque Class-----------------------------| /*! @brief Efficient double-ended priority queue. * @author Nathaniel McClatchey * @copyright Boost Software License Version 1.0 * @param Type Type of elements in the priority deque. * @param Sequence Underlying sequence container. Must provide random-access * iterators, %front(), %push_back(Type const &), and %pop_back(). * Defaults to std::vector<Type>. * @param Compare Comparison class. %Compare(A, B) should return true if %A * should be placed earlier than %B in a strict weak ordering. * Defaults to std::less<Type>, which encapsulates operator<. * @details Priority deques are adaptors, designed to provide efficient * insertion and access to both ends of a weakly-ordered list of elements. * As a container adaptor, priority_deque is implemented on top of another * container type. By default, this is std::vector, but a different container * may be specified explicitly. * Although the priority deque does permit iteration through its elements, * there is no ordering guaranteed, as different implementations may benefit * from different structures, and all iterators should be discarded after using * any function not labeled const. * @note %priority_deque does not provide a stable ordering. If both A<B and * B<A are false, then the order in which they appear may differ from the order * in which they were added to the priority deque. * @remark %priority_deque replicates the interface of the STL * @a priority_queue class template. * @remark %priority_deque is most useful when removals are interspersed with * insertions. If no further insertions are to be performed after the first * removal, consider using an array and a sorting algorithm instead. * @remark %priority_deque sorts elements as they are added, removed, and * modified by its member functions. If the elements are modified by some means * other than the public member functions, the order must be restoreed before * the priority_deque is used. * @see priority_queue */ template <typename Type, typename Sequence, typename Compare> class priority_deque { //----------------------------------Public-------------------------------------| public: //---------------------------------Typedefs------------------------------------| //! @details Underlying container type. typedef Sequence container_type; typedef typename container_type::value_type value_type; typedef Compare value_compare; //! @details STL Container specifies that this is an unsigned integral type. typedef typename container_type::size_type size_type; //! @details May be used to examine, but not modify, an element in the deque. typedef typename container_type::const_reference const_reference; typedef typename container_type::reference reference; typedef typename container_type::pointer pointer; typedef pointer const_pointer; //! @details May be used to examine, but not modify, elements in the deque. typedef typename container_type::const_iterator const_iterator; typedef const_iterator iterator; //! @details STL Container specifies that this is a signed integral type. typedef typename container_type::difference_type difference_type; //-------------------------------Constructors----------------------------------| enum Constructed { CONSTRUCTED }; //! @brief Constructs a new priority deque. NVBIO_FORCEINLINE NVBIO_HOST_DEVICE explicit priority_deque (const Compare& =Compare(), const Sequence& =Sequence()); template <typename InputIterator> NVBIO_FORCEINLINE NVBIO_HOST_DEVICE priority_deque (InputIterator first, InputIterator last, const Compare& =Compare(), const Sequence& =Sequence()); /// O(1) Creates a new priority deque from an already heapified container /// NVBIO_FORCEINLINE NVBIO_HOST_DEVICE priority_deque(const Sequence& seq, const bool constructed = false); /// O(1) Creates a new priority deque from an already heapified container /// NVBIO_FORCEINLINE NVBIO_HOST_DEVICE priority_deque(const Sequence& seq, const Constructed flag) : sequence_(seq) {} //-----------------------------Restricted Access-------------------------------| //! @brief Copies an element into the priority deque. NVBIO_FORCEINLINE NVBIO_HOST_DEVICE void push (const value_type&); //!@{ //! @brief Accesses a maximal element in the deque. NVBIO_FORCEINLINE NVBIO_HOST_DEVICE const_reference maximum (void) const; //! @brief Accesses a minimal element in the deque. NVBIO_FORCEINLINE NVBIO_HOST_DEVICE const_reference minimum (void) const; //! @details Identical to std::priority_queue top(). @see @a maximum NVBIO_FORCEINLINE NVBIO_HOST_DEVICE const_reference top (void) const { return maximum(); }; //! @details Identical to std::priority_queue top(). @see @a maximum NVBIO_FORCEINLINE NVBIO_HOST_DEVICE const_reference bottom (void) const { return bottom(); }; //!@} //!@{ //! @brief Removes a maximal element from the deque. NVBIO_FORCEINLINE NVBIO_HOST_DEVICE void pop_top (void); //! @brief Removes a minimal element from the deque. NVBIO_FORCEINLINE NVBIO_HOST_DEVICE void pop_bottom (void); //! @details Identical to std::priority_queue pop(). @see @a pop_maximum NVBIO_FORCEINLINE NVBIO_HOST_DEVICE void pop (void) { pop_top(); }; //!@} //--------------------------------Deque Size-----------------------------------| //!@{ //! @brief Returns true if the priority deque is empty, false if it is not. NVBIO_FORCEINLINE NVBIO_HOST_DEVICE bool empty (void) const {return sequence_.empty();}; //! @brief Returns the number of elements in the priority deque. NVBIO_FORCEINLINE NVBIO_HOST_DEVICE size_type size (void) const {return sequence_.size(); }; //! @brief Returns the maximum number of elements that can be contained. NVBIO_FORCEINLINE NVBIO_HOST_DEVICE size_type max_size (void) const {return sequence_.max_size();}; //!@} //--------------------------Whole-Deque Operations-----------------------------| //! @brief Removes all elements from the priority deque. NVBIO_FORCEINLINE NVBIO_HOST_DEVICE void clear (void) { sequence_.clear(); }; //! @brief Moves the elements from this deque into another, and vice-versa. NVBIO_FORCEINLINE NVBIO_HOST_DEVICE void swap (priority_deque<Type, Sequence,Compare>&); //!@{ //! @brief Merges a sequence of elements into the priority deque. template <typename InputIterator> NVBIO_FORCEINLINE NVBIO_HOST_DEVICE void merge (InputIterator first, InputIterator last); //! @brief Merges a container's elements into the priority deque. template <typename SourceContainer> NVBIO_FORCEINLINE NVBIO_HOST_DEVICE void merge (const SourceContainer& source) { merge(source.begin(), source.end()); } //!@} //-------------------------------Random Access---------------------------------| //!@{ //! @brief Returns a const iterator at the beginning of the sequence. NVBIO_FORCEINLINE NVBIO_HOST_DEVICE const_iterator begin (void) const {return sequence_.begin();}; //! @brief Returns a const iterator past the end of the sequence. NVBIO_FORCEINLINE NVBIO_HOST_DEVICE const_iterator end (void) const { return sequence_.end(); }; //! @brief Modifies a specified element of the deque. NVBIO_FORCEINLINE NVBIO_HOST_DEVICE void update (const_iterator, const value_type&); //! @brief Removes a specified element from the deque. NVBIO_FORCEINLINE NVBIO_HOST_DEVICE void erase (const_iterator); //!@} //---------------------------Boost.Heap Concepts-------------------------------| // size() has constant complexity static const bool constant_time_size = true; // priority deque does not have ordered iterators static const bool has_ordered_iterators = false; // priority deque is efficiently mergable static const bool is_mergable = true; // priority deque does not have a stable heap order static const bool is_stable = false; // priority deque does not have a reserve() member static const bool has_reserve = false; //--------------------------------Protected------------------------------------| protected: NVBIO_FORCEINLINE NVBIO_HOST_DEVICE container_type& sequence (void) { return sequence_; }; NVBIO_FORCEINLINE NVBIO_HOST_DEVICE const container_type& sequence (void) const { return sequence_; }; NVBIO_FORCEINLINE NVBIO_HOST_DEVICE value_compare& compare (void) { return compare_; }; NVBIO_FORCEINLINE NVBIO_HOST_DEVICE const value_compare& compare (void) const { return compare_; }; //---------------------------------Private-------------------------------------| private: Sequence sequence_; Compare compare_; }; //-------------------------------Constructors----------------------------------| //----------------------------Default Constructor------------------------------| /** @param comp Comparison class. // @param seq Container class. // @post Deque contains copies of all elements from @a sequence. // // @remark Complexity: O(n) */ template <typename T, typename S, typename C> priority_deque<T, S, C>::priority_deque (const C& comp, const S& seq) : sequence_(seq), compare_(comp) { heap::make_interval_heap(sequence_.begin(), sequence_.end(), compare_); } template <typename T, typename S, typename C> NVBIO_FORCEINLINE NVBIO_HOST_DEVICE priority_deque<T, S, C>::priority_deque(const S& seq, const bool constructed) : sequence_(seq) { if (!constructed) heap::make_interval_heap(sequence_.begin(), sequence_.end(), compare_); } //---------------------------Create from Iterators-----------------------------| /** @param first,last Range of elements. // @param comp Instance of comparison class. // @param seq Instance of container class. // @post Deque contains copies of all elements in @a sequence (if specified) // and in the range [ @a first, @a last). // // @remark Complexity: O(n) */ template <typename T, typename S, typename C> template <typename InputIterator> priority_deque<T, S, C>::priority_deque (InputIterator first,InputIterator last, const C& comp, const S& seq) : sequence_(seq), compare_(comp) { sequence_.insert(sequence_.end(), first, last); heap::make_interval_heap(sequence_.begin(), sequence_.end(), compare_); } //-----------------------------Restricted Access-------------------------------| //------------------------------Insert / Emplace-------------------------------| /** @param value Element to add the the priority deque. // @post Priority deque contains @a value or a copy of @a value. // @post All iterators and references are invalidated. // // @remark Complexity: O(log n) */ template <typename T, typename Sequence, typename Compare> void priority_deque<T, Sequence, Compare>::push (const value_type& value) { sequence_.push_back(value); heap::push_interval_heap(sequence_.begin(), sequence_.end(), compare_); } //---------------------------Observe Maximum/Minimum---------------------------| /** @return Const reference to a maximal element in the priority deque. // @pre Priority deque contains one or more elements. // @see minimum, pop_maximum // // @remark Complexity: O(1) */ template <typename T, typename Sequence, typename Compare> typename priority_deque<T, Sequence, Compare>::const_reference priority_deque<T, Sequence, Compare>::maximum (void) const { NVBIO_CUDA_DEBUG_ASSERT(!empty(), "Empty priority deque has no maximal element. Reference undefined."); const_iterator it = sequence_.begin() + 1; return (it == sequence_.end()) ? sequence_.front() : *it; } /** @return Const reference to a minimal element in the priority deque. // @pre Priority deque contains one or more elements. // @see maximum, pop_minimum // // @remark Complexity: O(1) */ template <typename T, typename Sequence, typename Compare> typename priority_deque<T, Sequence, Compare>::const_reference priority_deque<T, Sequence, Compare>::minimum (void) const { NVBIO_CUDA_DEBUG_ASSERT(!empty(), "Empty priority deque has no minimal element. Reference undefined."); return sequence_.front(); } //---------------------------Remove Maximum/Minimum----------------------------| /** @pre Priority deque contains one or more elements. // @post A maximal element has been removed from the priority deque. // @post All iterators and references are invalidated. // @see maximum, pop, pop_minimum // // @remark Complexity: O(log n) */ template <typename T, typename Sequence, typename Compare> void priority_deque<T, Sequence, Compare>::pop_bottom (void) { NVBIO_CUDA_DEBUG_ASSERT(!empty(), "Empty priority deque has no maximal element. Removal impossible."); heap::pop_interval_heap_min(sequence_.begin(), sequence_.end(), compare_); sequence_.pop_back(); } /** @pre Priority deque contains one or more elements. // @post A minimal element has been removed from the priority deque. // @post All iterators and references are invalidated. // @see minimum, pop_maximum // // @remark Complexity: O(log n) */ template <typename T, typename Sequence, typename Compare> void priority_deque<T, Sequence, Compare>::pop_top (void) { NVBIO_CUDA_DEBUG_ASSERT(!empty(), "Empty priority deque has no minimal element. Removal undefined."); heap::pop_interval_heap_max(sequence_.begin(), sequence_.end(), compare_); sequence_.pop_back(); } //--------------------------Whole-Deque Operations-----------------------------| //-----------------------------------Merge-------------------------------------| /** @param first,last Input iterators bounding the range [ @a first, @a last) // @post Priority deque contains its original elements, and copies of those in // the range. // @post All iterators and references are invalidated. // // @remark Complexity: O(n) // @remark Exception safety: Basic. */ template <typename T, typename S, typename C> template <typename InputIterator> void priority_deque<T, S, C>::merge (InputIterator first, InputIterator last) { sequence_.insert(sequence_.end(), first, last); heap::make_interval_heap(sequence_.begin(), sequence_.end(), compare_); } //----------------------------Swap Specialization------------------------------| /** @param other Priority deque with which to swap. // @post Deque contains the elements from @a source, and @a source contains the // elements from this deque. // @post All iterators and references are invalidated. // @note Sequence containers are required to have swap functions. // @remark Complexity: O(1) */ template <typename T, typename S, typename C> void priority_deque<T, S, C>::swap (priority_deque<T, S, C>& other) { sequence_.swap(other.sequence_); } /** @relates priority_deque // @param deque1,deque2 Priority deques. // @post @a deque1 contains the elements originally in @a deque2, and @a deque2 // contains the elements originally in @a deque1 // @post All iterators and references are invalidated. // // @remark Complexity: O(1) */ template <typename T, typename S, typename C> void swap (priority_deque<T, S, C>& deque1, priority_deque<T, S, C>& deque2) { deque1.swap(deque2); } //---------------------------Random-Access Mutators----------------------------| /** @param random_it A valid iterator in the range [begin, end). // @param value The new value. // @pre Priority deque contains one or more elements. // @post The element at @a random_it is set to @a value. // @post All iterators and references are invalidated. // @see erase // // Elements within the deque may be unordered. // @remark Complexity: O(log n) // @remark Exception safety: Basic. Exceptions won't lose elements, but may // corrupt the heap. */ template <typename T, typename S, typename C> void priority_deque<T, S, C>::update (const_iterator random_it, const value_type& value) { const difference_type index = random_it - begin(); NVBIO_CUDA_DEBUG_ASSERT((0 <= index) && (index < end() - begin()), "Iterator out of bounds; can't set element."); // Providing the strong guarantee would require saving a copy. *(sequence_.begin() + index) = value; heap::update_interval_heap(sequence_.begin(),sequence_.end(),index,compare_); } /** @param random_it An iterator in the range [begin, end) // @pre Priority deque contains one or more elements. // @post The deque no longer contains the element previously at @a random_it. // @post All iterators and references are invalidated. // @see set // @remark Complexity: O(log n) */ template <typename T, typename Sequence, typename Compare> void priority_deque<T, Sequence, Compare>::erase (const_iterator random_it) { const difference_type index = random_it - begin(); NVBIO_CUDA_DEBUG_ASSERT((0 <= index) && (index < end() - begin()), "Iterator out of bounds; can't erase element."); heap::pop_interval_heap(sequence_.begin(), sequence_.end(),index,compare_); sequence_.pop_back(); } ///@} PriorityDeques ///@} Basic } // namespace nvbio
NVlabs/nvbio
nvbio/basic/priority_deque.h
C
bsd-3-clause
22,231
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Mail * @subpackage Protocol * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ /** * @namespace */ namespace Zend\Mail; use Zend\Validator\Hostname as HostnameValidator, Zend\Validator, Zend\Mail\Protocol; /** * Zend_Mail_Protocol_Abstract * * Provides low-level methods for concrete adapters to communicate with a remote mail server and track requests and responses. * * @uses \Zend\Mail\Protocol\Exception * @uses \Zend\Validator\ValidatorChain * @uses \Zend\Validator\Hostname\Hostname * @category Zend * @package Zend_Mail * @subpackage Protocol * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @todo Implement proxy settings */ abstract class AbstractProtocol { /** * Mail default EOL string */ const EOL = "\r\n"; /** * Default timeout in seconds for initiating session */ const TIMEOUT_CONNECTION = 30; /** * Maximum of the transaction log * @var integer */ protected $_maximumLog = 64; /** * Hostname or IP address of remote server * @var string */ protected $_host; /** * Port number of connection * @var integer */ protected $_port; /** * Instance of Zend\Validator\ValidatorChain to check hostnames * @var \Zend\Validator\ValidatorChain */ protected $_validHost; /** * Socket connection resource * @var resource */ protected $_socket; /** * Last request sent to server * @var string */ protected $_request; /** * Array of server responses to last request * @var array */ protected $_response; /** * String template for parsing server responses using sscanf (default: 3 digit code and response string) * @var resource * @deprecated Since 1.10.3 */ protected $_template = '%d%s'; /** * Log of mail requests and server responses for a session * @var array */ private $_log = array(); /** * Constructor. * * @param string $host OPTIONAL Hostname of remote connection (default: 127.0.0.1) * @param integer $port OPTIONAL Port number (default: null) * @throws \Zend\Mail\Protocol\Exception * @return void */ public function __construct($host = '127.0.0.1', $port = null) { $this->_validHost = new Validator\ValidatorChain(); $this->_validHost->addValidator(new HostnameValidator(HostnameValidator::ALLOW_ALL)); if (!$this->_validHost->isValid($host)) { throw new Protocol\Exception\RuntimeException(implode(', ', $this->_validHost->getMessages())); } $this->_host = $host; $this->_port = $port; } /** * Class destructor to cleanup open resources * * @return void */ public function __destruct() { $this->_disconnect(); } /** * Set the maximum log size * * @param integer $maximumLog Maximum log size * @return void */ public function setMaximumLog($maximumLog) { $this->_maximumLog = (int) $maximumLog; } /** * Get the maximum log size * * @return int the maximum log size */ public function getMaximumLog() { return $this->_maximumLog; } /** * Create a connection to the remote host * * Concrete adapters for this class will implement their own unique connect scripts, using the _connect() method to create the socket resource. */ abstract public function connect(); /** * Retrieve the last client request * * @return string */ public function getRequest() { return $this->_request; } /** * Retrieve the last server response * * @return array */ public function getResponse() { return $this->_response; } /** * Retrieve the transaction log * * @return string */ public function getLog() { return implode('', $this->_log); } /** * Reset the transaction log * * @return void */ public function resetLog() { $this->_log = array(); } /** * Add the transaction log * * @param string new transaction * @return void */ protected function _addLog($value) { if ($this->_maximumLog >= 0 && count($this->_log) >= $this->_maximumLog) { array_shift($this->_log); } $this->_log[] = $value; } /** * Connect to the server using the supplied transport and target * * An example $remote string may be 'tcp://mail.example.com:25' or 'ssh://hostname.com:2222' * * @param string $remote Remote * @throws \Zend\Mail\Protocol\Exception * @return boolean */ protected function _connect($remote) { $errorNum = 0; $errorStr = ''; // open connection $this->_socket = @stream_socket_client($remote, $errorNum, $errorStr, self::TIMEOUT_CONNECTION); if ($this->_socket === false) { if ($errorNum == 0) { $errorStr = 'Could not open socket'; } throw new Protocol\Exception\RuntimeException($errorStr); } if (($result = stream_set_timeout($this->_socket, self::TIMEOUT_CONNECTION)) === false) { throw new Protocol\Exception\RuntimeException('Could not set stream timeout'); } return $result; } /** * Disconnect from remote host and free resource * * @return void */ protected function _disconnect() { if (is_resource($this->_socket)) { fclose($this->_socket); } } /** * Send the given request followed by a LINEEND to the server. * * @param string $request * @throws \Zend\Mail\Protocol\Exception * @return integer|boolean Number of bytes written to remote host */ protected function _send($request) { if (!is_resource($this->_socket)) { throw new Protocol\Exception\RuntimeException('No connection has been established to ' . $this->_host); } $this->_request = $request; $result = fwrite($this->_socket, $request . self::EOL); // Save request to internal log $this->_addLog($request . self::EOL); if ($result === false) { throw new Protocol\Exception\RuntimeException('Could not send request to ' . $this->_host); } return $result; } /** * Get a line from the stream. * * @var integer $timeout Per-request timeout value if applicable * @throws \Zend\Mail\Protocol\Exception * @return string */ protected function _receive($timeout = null) { if (!is_resource($this->_socket)) { throw new Protocol\Exception\RuntimeException('No connection has been established to ' . $this->_host); } // Adapters may wish to supply per-commend timeouts according to appropriate RFC if ($timeout !== null) { stream_set_timeout($this->_socket, $timeout); } // Retrieve response $reponse = fgets($this->_socket, 1024); // Save request to internal log $this->_addLog($reponse); // Check meta data to ensure connection is still valid $info = stream_get_meta_data($this->_socket); if (!empty($info['timed_out'])) { throw new Protocol\Exception\RuntimeException($this->_host . ' has timed out'); } if ($reponse === false) { throw new Protocol\Exception\RuntimeException('Could not read from ' . $this->_host); } return $reponse; } /** * Parse server response for successful codes * * Read the response from the stream and check for expected return code. * Throws a Zend_Mail_Protocol_Exception if an unexpected code is returned. * * @param string|array $code One or more codes that indicate a successful response * @throws \Zend\Mail\Protocol\Exception * @return string Last line of response string */ protected function _expect($code, $timeout = null) { $this->_response = array(); $cmd = ''; $more = ''; $msg = ''; $errMsg = ''; if (!is_array($code)) { $code = array($code); } do { $this->_response[] = $result = $this->_receive($timeout); list($cmd, $more, $msg) = preg_split('/([\s-]+)/', $result, 2, PREG_SPLIT_DELIM_CAPTURE); if ($errMsg !== '') { $errMsg .= ' ' . $msg; } elseif ($cmd === null || !in_array($cmd, $code)) { $errMsg = $msg; } } while (strpos($more, '-') === 0); // The '-' message prefix indicates an information string instead of a response string. if ($errMsg !== '') { throw new Protocol\Exception\RuntimeException($errMsg); } return $msg; } }
magicobject/zf2
library/Zend/Mail/AbstractProtocol.php
PHP
bsd-3-clause
9,877
/* Copyright (c) 2013, Groupon, 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 GROUPON 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. */ package com.groupon.mapreduce.mongo.in; import com.groupon.mapreduce.mongo.WritableBSONObject; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.InputSplit; import org.apache.hadoop.mapreduce.RecordReader; import org.apache.hadoop.mapreduce.TaskAttemptContext; import java.io.IOException; import java.util.Iterator; /** * This reads Mongo Records from an Extent and returns Hadoop Records as WritableBSONObjects. The key * returned to the Mapper is the _id field from the Mongo Record as Text. */ public class MongoRecordReader extends RecordReader<Text, WritableBSONObject> { private Record current = null; private Iterator<Record> iterator = null; private FileSystem fs; @Override public void initialize(InputSplit inputSplit, TaskAttemptContext taskAttemptContext) throws IOException, InterruptedException { MongoInputSplit mongoInputSplit = (MongoInputSplit) inputSplit; fs = ((MongoInputSplit) inputSplit).getExtent().getPath().getFileSystem(taskAttemptContext.getConfiguration()); iterator = mongoInputSplit.getExtent().iterator(fs); } @Override public boolean nextKeyValue() throws IOException, InterruptedException { if (!iterator.hasNext()) return false; current = iterator.next(); return true; } @Override public Text getCurrentKey() throws IOException, InterruptedException { return new Text(current.getId(fs)); } @Override public WritableBSONObject getCurrentValue() throws IOException, InterruptedException { return new WritableBSONObject(current.getContent(fs)); } @Override public float getProgress() throws IOException, InterruptedException { if (!iterator.hasNext()) return 1.0f; return 0.0f; } @Override public void close() throws IOException { } }
groupon/mongo-deep-mapreduce
src/main/java/com/groupon/mapreduce/mongo/in/MongoRecordReader.java
Java
bsd-3-clause
3,408
import numpy as np from Coupling import Coupling class Coupling2DCavities2D(Coupling): """ Coupling for cavity2D to cavity transmission. """ @property def impedance_from(self): """ Choses the right impedance of subsystem_from. Applies boundary conditions correction as well. """ return self.subsystem_from.impedance @property def impedance_to(self): """ Choses the right impedance of subsystem_from. Applies boundary conditions correction as well. """ return self.subsystem_to.impedance @property def tau(self): """ Transmission coefficient. """ return np.zeros(self.frequency.amount) @property def clf(self): """ Coupling loss factor for transmission from a 2D cavity to a cavity. .. math:: \\eta_{12} = \\frac{ \\tau_{12}}{4 \\pi} See BAC, equation 3.14 """ return self.tau / (4.0 * np.pi)
FRidh/Sea
Sea/model/couplings/Coupling2DCavities2D.py
Python
bsd-3-clause
1,049
/* Generated by Font Squirrel (http://www.fontsquirrel.com) on June 7, 2012 02:07:42 PM America/New_York */ @font-face { font-family: 'OpenSans'; src: url('OpenSans-Light-webfont.eot'); src: url('OpenSans-Light-webfont.eot?#iefix') format('embedded-opentype'), url('OpenSans-Light-webfont.woff') format('woff'), url('OpenSans-Light-webfont.ttf') format('truetype'), url('OpenSans-Light-webfont.svg#OpenSansLight') format('svg'); font-weight: lighter; font-weight: 300; font-style: normal; } @font-face { font-family: 'OpenSans'; src: url('OpenSans-LightItalic-webfont.eot'); src: url('OpenSans-LightItalic-webfont.eot?#iefix') format('embedded-opentype'), url('OpenSans-LightItalic-webfont.woff') format('woff'), url('OpenSans-LightItalic-webfont.ttf') format('truetype'), url('OpenSans-LightItalic-webfont.svg#OpenSansLightItalic') format('svg'); font-weight: lighter; font-weight: 300; font-style: italic; } @font-face { font-family: 'OpenSans'; src: url('OpenSans-Regular-webfont.eot'); src: url('OpenSans-Regular-webfont.eot?#iefix') format('embedded-opentype'), url('OpenSans-Regular-webfont.woff') format('woff'), url('OpenSans-Regular-webfont.ttf') format('truetype'), url('OpenSans-Regular-webfont.svg#OpenSansRegular') format('svg'); font-weight: normal; font-weight: 400; font-style: normal; } @font-face { font-family: 'OpenSans'; src: url('OpenSans-Italic-webfont.eot'); src: url('OpenSans-Italic-webfont.eot?#iefix') format('embedded-opentype'), url('OpenSans-Italic-webfont.woff') format('woff'), url('OpenSans-Italic-webfont.ttf') format('truetype'), url('OpenSans-Italic-webfont.svg#OpenSansItalic') format('svg'); font-weight: normal; font-weight: 400; font-style: italic; } @font-face { font-family: 'OpenSans'; src: url('OpenSans-Semibold-webfont.eot'); src: url('OpenSans-Semibold-webfont.eot?#iefix') format('embedded-opentype'), url('OpenSans-Semibold-webfont.woff') format('woff'), url('OpenSans-Semibold-webfont.ttf') format('truetype'), url('OpenSans-Semibold-webfont.svg#OpenSansSemibold') format('svg'); font-weight: bold; font-weight: 700; font-style: normal; } @font-face { font-family: 'OpenSans'; src: url('OpenSans-SemiboldItalic-webfont.eot'); src: url('OpenSans-SemiboldItalic-webfont.eot?#iefix') format('embedded-opentype'), url('OpenSans-SemiboldItalic-webfont.woff') format('woff'), url('OpenSans-SemiboldItalic-webfont.ttf') format('truetype'), url('OpenSans-SemiboldItalic-webfont.svg#OpenSansSemiboldItalic') format('svg'); font-weight: bold; font-weight: 700; font-style: italic; } @font-face { font-family: 'OpenSans'; src: url('OpenSans-Bold-webfont.eot'); src: url('OpenSans-Bold-webfont.eot?#iefix') format('embedded-opentype'), url('OpenSans-Bold-webfont.woff') format('woff'), url('OpenSans-Bold-webfont.ttf') format('truetype'), url('OpenSans-Bold-webfont.svg#OpenSansBold') format('svg'); font-weight: bolder; font-weight: 700; font-style: normal; } @font-face { font-family: 'OpenSans'; src: url('OpenSans-BoldItalic-webfont.eot'); src: url('OpenSans-BoldItalic-webfont.eot?#iefix') format('embedded-opentype'), url('OpenSans-BoldItalic-webfont.woff') format('woff'), url('OpenSans-BoldItalic-webfont.ttf') format('truetype'), url('OpenSans-BoldItalic-webfont.svg#OpenSansBoldItalic') format('svg'); font-weight: bolder; font-weight: 700; font-style: italic; }
Airlift-Framework/airlift-framework.github.com
fonts/open-sans.css
CSS
bsd-3-clause
3,735
#include "Stencil1D.h" int cncMain(int argc, char *argv[]) { CNC_REQUIRE(argc == 4, "Usage: %s NUM_TILES TILE_SIZE NUM_TIMESTEPS\n", argv[0]); // Create a new graph context Stencil1DCtx *context = Stencil1D_create(); // initialize graph context parameters context->numTiles = atoi(argv[1]); context->tileSize = atoi(argv[2]); context->lastTimestep = atoi(argv[3]); // Launch the graph for execution Stencil1D_launch(NULL, context); // Exit when the graph execution completes CNC_SHUTDOWN_ON_FINISH(context); return 0; }
habanero-rice/cnc-framework
examples/tutorial/4-improved.app/Main.c
C
bsd-3-clause
575
// 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. #include "ui/base/clipboard/test/test_clipboard.h" #include <stddef.h> #include <memory> #include <utility> #include "base/containers/contains.h" #include "base/memory/ptr_util.h" #include "base/notreached.h" #include "base/numerics/safe_conversions.h" #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" #include "build/buildflag.h" #include "build/chromecast_buildflags.h" #include "build/chromeos_buildflags.h" #include "skia/ext/skia_utils_base.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/base/clipboard/clipboard.h" #include "ui/base/clipboard/clipboard_constants.h" #include "ui/base/clipboard/clipboard_monitor.h" #include "ui/base/clipboard/custom_data_helper.h" #include "ui/base/data_transfer_policy/data_transfer_endpoint.h" #include "ui/base/data_transfer_policy/data_transfer_policy_controller.h" #include "ui/gfx/codec/png_codec.h" namespace ui { namespace { bool IsReadAllowed(const DataTransferEndpoint* src, const DataTransferEndpoint* dst) { auto* policy_controller = DataTransferPolicyController::Get(); if (!policy_controller) return true; return policy_controller->IsClipboardReadAllowed(src, dst, absl::nullopt); } } // namespace TestClipboard::TestClipboard() : default_store_buffer_(ClipboardBuffer::kCopyPaste) {} TestClipboard::~TestClipboard() = default; TestClipboard* TestClipboard::CreateForCurrentThread() { base::AutoLock lock(Clipboard::ClipboardMapLock()); auto* clipboard = new TestClipboard; (*Clipboard::ClipboardMapPtr())[base::PlatformThread::CurrentId()] = base::WrapUnique(clipboard); return clipboard; } void TestClipboard::SetLastModifiedTime(const base::Time& time) { last_modified_time_ = time; } void TestClipboard::OnPreShutdown() {} DataTransferEndpoint* TestClipboard::GetSource(ClipboardBuffer buffer) const { return GetStore(buffer).GetDataSource(); } const ClipboardSequenceNumberToken& TestClipboard::GetSequenceNumber( ClipboardBuffer buffer) const { return GetStore(buffer).sequence_number; } bool TestClipboard::IsFormatAvailable( const ClipboardFormatType& format, ClipboardBuffer buffer, const ui::DataTransferEndpoint* data_dst) const { if (!IsReadAllowed(GetStore(buffer).data_src.get(), data_dst)) return false; #if defined(OS_LINUX) || defined(OS_CHROMEOS) // The linux clipboard treats the presence of text on the clipboard // as the url format being available. if (format == ClipboardFormatType::UrlType()) return IsFormatAvailable(ClipboardFormatType::PlainTextType(), buffer, data_dst); #endif // defined(OS_LINUX) || defined(OS_CHROMEOS) const DataStore& store = GetStore(buffer); if (format == ClipboardFormatType::FilenamesType()) return !store.filenames.empty(); // Chrome can retrieve an image from the clipboard as either a bitmap or PNG. if (format == ClipboardFormatType::PngType() || format == ClipboardFormatType::BitmapType()) { return base::Contains(store.data, ClipboardFormatType::PngType()) || base::Contains(store.data, ClipboardFormatType::BitmapType()); } return base::Contains(store.data, format); } void TestClipboard::Clear(ClipboardBuffer buffer) { GetStore(buffer).Clear(); } std::vector<std::u16string> TestClipboard::GetStandardFormats( ClipboardBuffer buffer, const DataTransferEndpoint* data_dst) const { std::vector<std::u16string> types; const DataStore& store = GetStore(buffer); if (!IsReadAllowed(store.data_src.get(), data_dst)) return types; if (IsFormatAvailable(ClipboardFormatType::PlainTextType(), buffer, data_dst)) { types.push_back(base::UTF8ToUTF16(kMimeTypeText)); } if (IsFormatAvailable(ClipboardFormatType::HtmlType(), buffer, data_dst)) types.push_back(base::UTF8ToUTF16(kMimeTypeHTML)); if (IsFormatAvailable(ClipboardFormatType::SvgType(), buffer, data_dst)) types.push_back(base::UTF8ToUTF16(kMimeTypeSvg)); if (IsFormatAvailable(ClipboardFormatType::RtfType(), buffer, data_dst)) types.push_back(base::UTF8ToUTF16(kMimeTypeRTF)); if (IsFormatAvailable(ClipboardFormatType::PngType(), buffer, data_dst) || IsFormatAvailable(ClipboardFormatType::BitmapType(), buffer, data_dst)) types.push_back(base::UTF8ToUTF16(kMimeTypePNG)); if (IsFormatAvailable(ClipboardFormatType::FilenamesType(), buffer, data_dst)) types.push_back(base::UTF8ToUTF16(kMimeTypeURIList)); auto it = store.data.find(ClipboardFormatType::WebCustomDataType()); if (it != store.data.end()) ReadCustomDataTypes(it->second.c_str(), it->second.size(), &types); return types; } void TestClipboard::ReadAvailableTypes( ClipboardBuffer buffer, const DataTransferEndpoint* data_dst, std::vector<std::u16string>* types) const { DCHECK(types); types->clear(); if (!IsReadAllowed(GetStore(buffer).data_src.get(), data_dst)) return; *types = GetStandardFormats(buffer, data_dst); } void TestClipboard::ReadText(ClipboardBuffer buffer, const DataTransferEndpoint* data_dst, std::u16string* result) const { if (!IsReadAllowed(GetStore(buffer).data_src.get(), data_dst)) return; std::string result8; ReadAsciiText(buffer, data_dst, &result8); *result = base::UTF8ToUTF16(result8); } // TODO(crbug.com/1103215): |data_dst| should be supported. void TestClipboard::ReadAsciiText(ClipboardBuffer buffer, const DataTransferEndpoint* data_dst, std::string* result) const { const DataStore& store = GetStore(buffer); if (!IsReadAllowed(store.data_src.get(), data_dst)) return; result->clear(); auto it = store.data.find(ClipboardFormatType::PlainTextType()); if (it != store.data.end()) *result = it->second; } void TestClipboard::ReadHTML(ClipboardBuffer buffer, const DataTransferEndpoint* data_dst, std::u16string* markup, std::string* src_url, uint32_t* fragment_start, uint32_t* fragment_end) const { const DataStore& store = GetStore(buffer); if (!IsReadAllowed(store.data_src.get(), data_dst)) return; markup->clear(); src_url->clear(); auto it = store.data.find(ClipboardFormatType::HtmlType()); if (it != store.data.end()) *markup = base::UTF8ToUTF16(it->second); *src_url = store.html_src_url; *fragment_start = 0; *fragment_end = base::checked_cast<uint32_t>(markup->size()); } void TestClipboard::ReadSvg(ClipboardBuffer buffer, const DataTransferEndpoint* data_dst, std::u16string* result) const { const DataStore& store = GetStore(buffer); if (!IsReadAllowed(store.data_src.get(), data_dst)) return; result->clear(); auto it = store.data.find(ClipboardFormatType::SvgType()); if (it != store.data.end()) *result = base::UTF8ToUTF16(it->second); } void TestClipboard::ReadRTF(ClipboardBuffer buffer, const DataTransferEndpoint* data_dst, std::string* result) const { const DataStore& store = GetStore(buffer); if (!IsReadAllowed(store.data_src.get(), data_dst)) return; result->clear(); auto it = store.data.find(ClipboardFormatType::RtfType()); if (it != store.data.end()) *result = it->second; } void TestClipboard::ReadPng(ClipboardBuffer buffer, const DataTransferEndpoint* data_dst, ReadPngCallback callback) const { const DataStore& store = GetStore(buffer); if (!IsReadAllowed(store.data_src.get(), data_dst)) { std::move(callback).Run(std::vector<uint8_t>()); return; } std::move(callback).Run(store.png); } // TODO(crbug.com/1103215): |data_dst| should be supported. void TestClipboard::ReadCustomData(ClipboardBuffer buffer, const std::u16string& type, const DataTransferEndpoint* data_dst, std::u16string* result) const {} void TestClipboard::ReadFilenames(ClipboardBuffer buffer, const DataTransferEndpoint* data_dst, std::vector<ui::FileInfo>* result) const { const DataStore& store = GetStore(buffer); if (!IsReadAllowed(store.data_src.get(), data_dst)) return; *result = store.filenames; } // TODO(crbug.com/1103215): |data_dst| should be supported. void TestClipboard::ReadBookmark(const DataTransferEndpoint* data_dst, std::u16string* title, std::string* url) const { const DataStore& store = GetDefaultStore(); if (!IsReadAllowed(store.data_src.get(), data_dst)) return; if (url) { auto it = store.data.find(ClipboardFormatType::UrlType()); if (it != store.data.end()) *url = it->second; } if (title) *title = base::UTF8ToUTF16(store.url_title); } void TestClipboard::ReadData(const ClipboardFormatType& format, const DataTransferEndpoint* data_dst, std::string* result) const { const DataStore& store = GetDefaultStore(); if (!IsReadAllowed(store.data_src.get(), data_dst)) return; result->clear(); auto it = store.data.find(format); if (it != store.data.end()) *result = it->second; } base::Time TestClipboard::GetLastModifiedTime() const { return last_modified_time_; } void TestClipboard::ClearLastModifiedTime() { last_modified_time_ = base::Time(); } #if defined(USE_OZONE) bool TestClipboard::IsSelectionBufferAvailable() const { return true; } #endif // defined(USE_OZONE) void TestClipboard::WritePortableAndPlatformRepresentations( ClipboardBuffer buffer, const ObjectMap& objects, std::vector<Clipboard::PlatformRepresentation> platform_representations, std::unique_ptr<DataTransferEndpoint> data_src) { Clear(buffer); default_store_buffer_ = buffer; DispatchPlatformRepresentations(std::move(platform_representations)); for (const auto& kv : objects) DispatchPortableRepresentation(kv.first, kv.second); default_store_buffer_ = ClipboardBuffer::kCopyPaste; GetStore(buffer).SetDataSource(std::move(data_src)); } void TestClipboard::WriteText(const char* text_data, size_t text_len) { std::string text(text_data, text_len); GetDefaultStore().data[ClipboardFormatType::PlainTextType()] = text; #if defined(OS_WIN) // Create a dummy entry. GetDefaultStore().data[ClipboardFormatType::PlainTextAType()]; #endif if (IsSupportedClipboardBuffer(ClipboardBuffer::kSelection)) GetStore(ClipboardBuffer::kSelection) .data[ClipboardFormatType::PlainTextType()] = text; ClipboardMonitor::GetInstance()->NotifyClipboardDataChanged(); } void TestClipboard::WriteHTML(const char* markup_data, size_t markup_len, const char* url_data, size_t url_len) { std::u16string markup; base::UTF8ToUTF16(markup_data, markup_len, &markup); GetDefaultStore().data[ClipboardFormatType::HtmlType()] = base::UTF16ToUTF8(markup); GetDefaultStore().html_src_url = std::string(url_data, url_len); } void TestClipboard::WriteSvg(const char* markup_data, size_t markup_len) { std::u16string markup; base::UTF8ToUTF16(markup_data, markup_len, &markup); GetDefaultStore().data[ClipboardFormatType::SvgType()] = base::UTF16ToUTF8(markup); } void TestClipboard::WriteRTF(const char* rtf_data, size_t data_len) { GetDefaultStore().data[ClipboardFormatType::RtfType()] = std::string(rtf_data, data_len); } void TestClipboard::WriteFilenames(std::vector<ui::FileInfo> filenames) { GetDefaultStore().filenames = std::move(filenames); } void TestClipboard::WriteBookmark(const char* title_data, size_t title_len, const char* url_data, size_t url_len) { GetDefaultStore().data[ClipboardFormatType::UrlType()] = std::string(url_data, url_len); #if !defined(OS_WIN) GetDefaultStore().url_title = std::string(title_data, title_len); #endif } void TestClipboard::WriteWebSmartPaste() { // Create a dummy entry. GetDefaultStore().data[ClipboardFormatType::WebKitSmartPasteType()]; } void TestClipboard::WriteBitmap(const SkBitmap& bitmap) { // We expect callers to sanitize `bitmap` to be N32 color type, to avoid // out-of-bounds issues due to unexpected bits-per-pixel while copying the // bitmap's pixel buffer. This DCHECK is to help alert us if we've missed // something. DCHECK_EQ(bitmap.colorType(), kN32_SkColorType); // Create a dummy entry. GetDefaultStore().data[ClipboardFormatType::BitmapType()]; gfx::PNGCodec::EncodeBGRASkBitmap(bitmap, false, &GetDefaultStore().png); ClipboardMonitor::GetInstance()->NotifyClipboardDataChanged(); } void TestClipboard::WriteData(const ClipboardFormatType& format, const char* data_data, size_t data_len) { GetDefaultStore().data[format] = std::string(data_data, data_len); } TestClipboard::DataStore::DataStore() = default; TestClipboard::DataStore::DataStore(const DataStore& other) { sequence_number = other.sequence_number; data = other.data; url_title = other.url_title; html_src_url = other.html_src_url; png = other.png; data_src = other.data_src ? std::make_unique<DataTransferEndpoint>( DataTransferEndpoint(*(other.data_src))) : nullptr; } TestClipboard::DataStore& TestClipboard::DataStore::operator=( const DataStore& other) { sequence_number = other.sequence_number; data = other.data; url_title = other.url_title; html_src_url = other.html_src_url; png = other.png; data_src = other.data_src ? std::make_unique<DataTransferEndpoint>( DataTransferEndpoint(*(other.data_src))) : nullptr; return *this; } TestClipboard::DataStore::~DataStore() = default; void TestClipboard::DataStore::Clear() { data.clear(); url_title.clear(); html_src_url.clear(); png.clear(); filenames.clear(); data_src.reset(); } void TestClipboard::DataStore::SetDataSource( std::unique_ptr<DataTransferEndpoint> new_data_src) { data_src = std::move(new_data_src); } DataTransferEndpoint* TestClipboard::DataStore::GetDataSource() const { return data_src.get(); } const TestClipboard::DataStore& TestClipboard::GetStore( ClipboardBuffer buffer) const { CHECK(IsSupportedClipboardBuffer(buffer)); return stores_[buffer]; } TestClipboard::DataStore& TestClipboard::GetStore(ClipboardBuffer buffer) { CHECK(IsSupportedClipboardBuffer(buffer)); DataStore& store = stores_[buffer]; store.sequence_number = ClipboardSequenceNumberToken(); return store; } const TestClipboard::DataStore& TestClipboard::GetDefaultStore() const { return GetStore(default_store_buffer_); } TestClipboard::DataStore& TestClipboard::GetDefaultStore() { return GetStore(default_store_buffer_); } } // namespace ui
scheib/chromium
ui/base/clipboard/test/test_clipboard.cc
C++
bsd-3-clause
15,520
''' The `Filter` hierarchy contains Transformer classes that take a `Stim` of one type as input and return a `Stim` of the same type as output (but with some changes to its data). ''' from .audio import (AudioTrimmingFilter, AudioResamplingFilter) from .base import TemporalTrimmingFilter from .image import (ImageCroppingFilter, ImageResizingFilter, PillowImageFilter) from .text import (WordStemmingFilter, TokenizingFilter, TokenRemovalFilter, PunctuationRemovalFilter, LowerCasingFilter) from .video import (FrameSamplingFilter, VideoTrimmingFilter) __all__ = [ 'AudioTrimmingFilter', 'AudioResamplingFilter', 'TemporalTrimmingFilter', 'ImageCroppingFilter', 'ImageResizingFilter', 'PillowImageFilter', 'WordStemmingFilter', 'TokenizingFilter', 'TokenRemovalFilter', 'PunctuationRemovalFilter', 'LowerCasingFilter', 'FrameSamplingFilter', 'VideoTrimmingFilter' ]
tyarkoni/pliers
pliers/filters/__init__.py
Python
bsd-3-clause
1,079
package ch.epfl.yinyang package transformers import ch.epfl.yinyang._ import ch.epfl.yinyang.transformers._ import scala.reflect.macros.blackbox.Context import language.experimental.macros import scala.collection.mutable import scala.collection.mutable.ArrayBuffer /** * Converts captured variables to holes, which will be passed to the generated * code at runtime as arguments to the apply method. Exposes all holes in the * holeTable, which maps from holeIds to symbolIds. * * Features covered are: * - identifiers -> `hole[T](classTag[T], holeId)` * - fields (TODO) * - no parameter methods (TODO) * - no parameter functions (TODO) */ trait HoleTransformation extends MacroModule with TransformationUtils { def holeMethod: String import c.universe._ /** SymbolIds indexed by holeIds. */ val holeTable = new ArrayBuffer[Int] object HoleTransformer { def apply(toHoles: List[Symbol] = Nil, className: String)(tree: Tree) = { val t = new HoleTransformer(toHoles map symbolId).transform(tree) log("holeTransformed (transforming " + toHoles + "): " + code(t), 2) log("holeTable (holeId -> symbolId): " + holeTable, 2) t } } /** * Transforms all identifiers with symbolIds in `toHoles` to * `hole[T](classTag[T], holeId)` and builds the holeTable mapping from * holeIds to symbolIds. */ class HoleTransformer(toHoles: List[Int]) extends Transformer { override def transform(tree: Tree): Tree = tree match { case i @ Ident(s) if toHoles contains symbolId(i.symbol) => { val index = { val sId = symbolId(i.symbol) if (holeTable.contains(sId)) holeTable.indexOf(sId) else { holeTable += symbolId(i.symbol) holeTable.size - 1 } } Apply( Select(This(typeNames.EMPTY), TermName(holeMethod)), List( TypeApply( Select(This(typeNames.EMPTY), TermName("runtimeType")), List(TypeTree(i.tpe.widen))), Literal(Constant(index)))) } case _ => super.transform(tree) } } }
vjovanov/scala-yinyang
components/core/src/transformers/HoleTransformation.scala
Scala
bsd-3-clause
2,133
# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = build # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest help: @echo "Please use \`make <target>' where <target> is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " text to make text files" @echo " man to make manual pages" @echo " changes to make an overview of all changed/added/deprecated items" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: -rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." livehtml: sphinx-autobuild -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/python-sunlight.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/python-sunlight.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/python-sunlight" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/python-sunlight" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." make -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt."
sunlightlabs/python-sunlight
docs/Makefile
Makefile
bsd-3-clause
4,701
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Tool * @subpackage Framework * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ /** * @namespace */ namespace Zend\Tool\Project\Provider; /** * @uses \Zend\Tool\Framework\Provider\Pretendable * @uses \Zend\Tool\Project\Exception * @uses \Zend\Tool\Project\Provider\AbstractProvider * @category Zend * @package Zend_Tool * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Application extends AbstractProvider implements \Zend\Tool\Framework\Provider\Pretendable { protected $_specialties = array('ClassNamePrefix'); /** * * @param $classNamePrefix Prefix of classes * @param $force */ public function changeClassNamePrefix($classNamePrefix /* , $force = false */) { $profile = $this->_loadProfile(self::NO_PROFILE_THROW_EXCEPTION); $originalClassNamePrefix = $classNamePrefix; if (substr($classNamePrefix, -1) != '\\') { $classNamePrefix .= '\\'; } $configFileResource = $profile->search('ApplicationConfigFile'); $zc = $configFileResource->getAsZendConfig('production'); if ($zc->appnamespace == $classNamePrefix) { throw new \Zend\Tool\Project\Exception('The requested name ' . $classNamePrefix . ' is already the prefix.'); } // remove the old $configFileResource->removeStringItem('appnamespace', 'production'); $configFileResource->create(); // add the new $configFileResource->addStringItem('appnamespace', $classNamePrefix, 'production', true); $configFileResource->create(); // update the project profile $applicationDirectory = $profile->search('ApplicationDirectory'); $applicationDirectory->setClassNamePrefix($classNamePrefix); $response = $this->_registry->getResponse(); if ($originalClassNamePrefix !== $classNamePrefix) { $response->appendContent( 'Note: the name provided "' . $originalClassNamePrefix . '" was' . ' altered to "' . $classNamePrefix . '" for correctness.', array('color' => 'yellow') ); } // note to the user $response->appendContent('Note: All existing models will need to be altered to this new namespace by hand', array('color' => 'yellow')); $response->appendContent('application.ini updated with new appnamespace ' . $classNamePrefix); // store profile $this->_storeProfile(); } }
magicobject/zf2
library/Zend/Tool/Project/Provider/Application.php
PHP
bsd-3-clause
3,334
/* * Copyright (c) 2013 The WebM project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "vp9/common/vp9_convolve.h" #include <assert.h> #include "./vpx_config.h" #include "./vp9_rtcd.h" #include "vp9/common/vp9_common.h" #include "vpx/vpx_integer.h" #include "vpx_ports/mem.h" #define VP9_FILTER_WEIGHT 128 #define VP9_FILTER_SHIFT 7 /* Assume a bank of 16 filters to choose from. There are two implementations * for filter wrapping behavior, since we want to be able to pick which filter * to start with. We could either: * * 1) make filter_ a pointer to the base of the filter array, and then add an * additional offset parameter, to choose the starting filter. * 2) use a pointer to 2 periods worth of filters, so that even if the original * phase offset is at 15/16, we'll have valid data to read. The filter * tables become [32][8], and the second half is duplicated. * 3) fix the alignment of the filter tables, so that we know the 0/16 is * always 256 byte aligned. * * Implementations 2 and 3 are likely preferable, as they avoid an extra 2 * parameters, and switching between them is trivial, with the * ALIGN_FILTERS_256 macro, below. */ #define ALIGN_FILTERS_256 1 static void convolve_horiz_c(const uint8_t *src, int src_stride, uint8_t *dst, int dst_stride, const int16_t *filter_x0, int x_step_q4, const int16_t *filter_y, int y_step_q4, int w, int h, int taps) { int x, y, k, sum; const int16_t *filter_x_base = filter_x0; #if ALIGN_FILTERS_256 filter_x_base = (const int16_t *)(((intptr_t)filter_x0) & ~(intptr_t)0xff); #endif /* Adjust base pointer address for this source line */ src -= taps / 2 - 1; for (y = 0; y < h; ++y) { /* Pointer to filter to use */ const int16_t *filter_x = filter_x0; /* Initial phase offset */ int x0_q4 = (filter_x - filter_x_base) / taps; int x_q4 = x0_q4; for (x = 0; x < w; ++x) { /* Per-pixel src offset */ int src_x = (x_q4 - x0_q4) >> 4; for (sum = 0, k = 0; k < taps; ++k) { sum += src[src_x + k] * filter_x[k]; } sum += (VP9_FILTER_WEIGHT >> 1); dst[x] = clip_pixel(sum >> VP9_FILTER_SHIFT); /* Adjust source and filter to use for the next pixel */ x_q4 += x_step_q4; filter_x = filter_x_base + (x_q4 & 0xf) * taps; } src += src_stride; dst += dst_stride; } } static void convolve_avg_horiz_c(const uint8_t *src, int src_stride, uint8_t *dst, int dst_stride, const int16_t *filter_x0, int x_step_q4, const int16_t *filter_y, int y_step_q4, int w, int h, int taps) { int x, y, k, sum; const int16_t *filter_x_base = filter_x0; #if ALIGN_FILTERS_256 filter_x_base = (const int16_t *)(((intptr_t)filter_x0) & ~(intptr_t)0xff); #endif /* Adjust base pointer address for this source line */ src -= taps / 2 - 1; for (y = 0; y < h; ++y) { /* Pointer to filter to use */ const int16_t *filter_x = filter_x0; /* Initial phase offset */ int x0_q4 = (filter_x - filter_x_base) / taps; int x_q4 = x0_q4; for (x = 0; x < w; ++x) { /* Per-pixel src offset */ int src_x = (x_q4 - x0_q4) >> 4; for (sum = 0, k = 0; k < taps; ++k) { sum += src[src_x + k] * filter_x[k]; } sum += (VP9_FILTER_WEIGHT >> 1); dst[x] = (dst[x] + clip_pixel(sum >> VP9_FILTER_SHIFT) + 1) >> 1; /* Adjust source and filter to use for the next pixel */ x_q4 += x_step_q4; filter_x = filter_x_base + (x_q4 & 0xf) * taps; } src += src_stride; dst += dst_stride; } } static void convolve_vert_c(const uint8_t *src, int src_stride, uint8_t *dst, int dst_stride, const int16_t *filter_x, int x_step_q4, const int16_t *filter_y0, int y_step_q4, int w, int h, int taps) { int x, y, k, sum; const int16_t *filter_y_base = filter_y0; #if ALIGN_FILTERS_256 filter_y_base = (const int16_t *)(((intptr_t)filter_y0) & ~(intptr_t)0xff); #endif /* Adjust base pointer address for this source column */ src -= src_stride * (taps / 2 - 1); for (x = 0; x < w; ++x) { /* Pointer to filter to use */ const int16_t *filter_y = filter_y0; /* Initial phase offset */ int y0_q4 = (filter_y - filter_y_base) / taps; int y_q4 = y0_q4; for (y = 0; y < h; ++y) { /* Per-pixel src offset */ int src_y = (y_q4 - y0_q4) >> 4; for (sum = 0, k = 0; k < taps; ++k) { sum += src[(src_y + k) * src_stride] * filter_y[k]; } sum += (VP9_FILTER_WEIGHT >> 1); dst[y * dst_stride] = clip_pixel(sum >> VP9_FILTER_SHIFT); /* Adjust source and filter to use for the next pixel */ y_q4 += y_step_q4; filter_y = filter_y_base + (y_q4 & 0xf) * taps; } ++src; ++dst; } } static void convolve_avg_vert_c(const uint8_t *src, int src_stride, uint8_t *dst, int dst_stride, const int16_t *filter_x, int x_step_q4, const int16_t *filter_y0, int y_step_q4, int w, int h, int taps) { int x, y, k, sum; const int16_t *filter_y_base = filter_y0; #if ALIGN_FILTERS_256 filter_y_base = (const int16_t *)(((intptr_t)filter_y0) & ~(intptr_t)0xff); #endif /* Adjust base pointer address for this source column */ src -= src_stride * (taps / 2 - 1); for (x = 0; x < w; ++x) { /* Pointer to filter to use */ const int16_t *filter_y = filter_y0; /* Initial phase offset */ int y0_q4 = (filter_y - filter_y_base) / taps; int y_q4 = y0_q4; for (y = 0; y < h; ++y) { /* Per-pixel src offset */ int src_y = (y_q4 - y0_q4) >> 4; for (sum = 0, k = 0; k < taps; ++k) { sum += src[(src_y + k) * src_stride] * filter_y[k]; } sum += (VP9_FILTER_WEIGHT >> 1); dst[y * dst_stride] = (dst[y * dst_stride] + clip_pixel(sum >> VP9_FILTER_SHIFT) + 1) >> 1; /* Adjust source and filter to use for the next pixel */ y_q4 += y_step_q4; filter_y = filter_y_base + (y_q4 & 0xf) * taps; } ++src; ++dst; } } static void convolve_c(const uint8_t *src, int src_stride, uint8_t *dst, int dst_stride, const int16_t *filter_x, int x_step_q4, const int16_t *filter_y, int y_step_q4, int w, int h, int taps) { /* Fixed size intermediate buffer places limits on parameters. * Maximum intermediate_height is 135, for y_step_q4 == 32, * h == 64, taps == 8. */ uint8_t temp[64 * 135]; int intermediate_height = ((h * y_step_q4) >> 4) + taps - 1; assert(w <= 64); assert(h <= 64); assert(taps <= 8); assert(y_step_q4 <= 32); if (intermediate_height < h) intermediate_height = h; convolve_horiz_c(src - src_stride * (taps / 2 - 1), src_stride, temp, 64, filter_x, x_step_q4, filter_y, y_step_q4, w, intermediate_height, taps); convolve_vert_c(temp + 64 * (taps / 2 - 1), 64, dst, dst_stride, filter_x, x_step_q4, filter_y, y_step_q4, w, h, taps); } static void convolve_avg_c(const uint8_t *src, int src_stride, uint8_t *dst, int dst_stride, const int16_t *filter_x, int x_step_q4, const int16_t *filter_y, int y_step_q4, int w, int h, int taps) { /* Fixed size intermediate buffer places limits on parameters. * Maximum intermediate_height is 135, for y_step_q4 == 32, * h == 64, taps == 8. */ uint8_t temp[64 * 135]; int intermediate_height = ((h * y_step_q4) >> 4) + taps - 1; assert(w <= 64); assert(h <= 64); assert(taps <= 8); assert(y_step_q4 <= 32); if (intermediate_height < h) intermediate_height = h; convolve_horiz_c(src - src_stride * (taps / 2 - 1), src_stride, temp, 64, filter_x, x_step_q4, filter_y, y_step_q4, w, intermediate_height, taps); convolve_avg_vert_c(temp + 64 * (taps / 2 - 1), 64, dst, dst_stride, filter_x, x_step_q4, filter_y, y_step_q4, w, h, taps); } void vp9_convolve8_horiz_c(const uint8_t *src, int src_stride, uint8_t *dst, int dst_stride, const int16_t *filter_x, int x_step_q4, const int16_t *filter_y, int y_step_q4, int w, int h) { convolve_horiz_c(src, src_stride, dst, dst_stride, filter_x, x_step_q4, filter_y, y_step_q4, w, h, 8); } void vp9_convolve8_avg_horiz_c(const uint8_t *src, int src_stride, uint8_t *dst, int dst_stride, const int16_t *filter_x, int x_step_q4, const int16_t *filter_y, int y_step_q4, int w, int h) { convolve_avg_horiz_c(src, src_stride, dst, dst_stride, filter_x, x_step_q4, filter_y, y_step_q4, w, h, 8); } void vp9_convolve8_vert_c(const uint8_t *src, int src_stride, uint8_t *dst, int dst_stride, const int16_t *filter_x, int x_step_q4, const int16_t *filter_y, int y_step_q4, int w, int h) { convolve_vert_c(src, src_stride, dst, dst_stride, filter_x, x_step_q4, filter_y, y_step_q4, w, h, 8); } void vp9_convolve8_avg_vert_c(const uint8_t *src, int src_stride, uint8_t *dst, int dst_stride, const int16_t *filter_x, int x_step_q4, const int16_t *filter_y, int y_step_q4, int w, int h) { convolve_avg_vert_c(src, src_stride, dst, dst_stride, filter_x, x_step_q4, filter_y, y_step_q4, w, h, 8); } void vp9_convolve8_c(const uint8_t *src, int src_stride, uint8_t *dst, int dst_stride, const int16_t *filter_x, int x_step_q4, const int16_t *filter_y, int y_step_q4, int w, int h) { convolve_c(src, src_stride, dst, dst_stride, filter_x, x_step_q4, filter_y, y_step_q4, w, h, 8); } void vp9_convolve8_avg_c(const uint8_t *src, int src_stride, uint8_t *dst, int dst_stride, const int16_t *filter_x, int x_step_q4, const int16_t *filter_y, int y_step_q4, int w, int h) { /* Fixed size intermediate buffer places limits on parameters. */ DECLARE_ALIGNED_ARRAY(16, uint8_t, temp, 64 * 64); assert(w <= 64); assert(h <= 64); vp9_convolve8(src, src_stride, temp, 64, filter_x, x_step_q4, filter_y, y_step_q4, w, h); vp9_convolve_avg(temp, 64, dst, dst_stride, NULL, 0, /* These unused parameter should be removed! */ NULL, 0, /* These unused parameter should be removed! */ w, h); } void vp9_convolve_copy(const uint8_t *src, int src_stride, uint8_t *dst, int dst_stride, const int16_t *filter_x, int filter_x_stride, const int16_t *filter_y, int filter_y_stride, int w, int h) { if (w == 16 && h == 16) { vp9_copy_mem16x16(src, src_stride, dst, dst_stride); } else if (w == 8 && h == 8) { vp9_copy_mem8x8(src, src_stride, dst, dst_stride); } else if (w == 8 && h == 4) { vp9_copy_mem8x4(src, src_stride, dst, dst_stride); } else { int r; for (r = h; r > 0; --r) { memcpy(dst, src, w); src += src_stride; dst += dst_stride; } } } void vp9_convolve_avg(const uint8_t *src, int src_stride, uint8_t *dst, int dst_stride, const int16_t *filter_x, int filter_x_stride, const int16_t *filter_y, int filter_y_stride, int w, int h) { int x, y; for (y = 0; y < h; ++y) { for (x = 0; x < w; ++x) { dst[x] = (dst[x] + src[x] + 1) >> 1; } src += src_stride; dst += dst_stride; } }
windyuuy/opera
chromium/src/third_party/libvpx/source/libvpx/vp9/common/vp9_convolve.c
C
bsd-3-clause
13,122
#!/usr/bin/env python from setuptools import setup, find_packages setup(name='reddit_gold', description='reddit gold', version='0.1', author='Chad Birch', author_email='chad@reddit.com', packages=find_packages(), install_requires=[ 'r2', ], entry_points={ 'r2.plugin': ['gold = reddit_gold:Gold'] }, include_package_data=True, zip_safe=False, )
madbook/reddit-plugin-gold
setup.py
Python
bsd-3-clause
418
<?php /* * ircPlanet Services for ircu * Copyright (c) 2005 Brian Cline. * 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. * 3. Neither the name of ircPlanet 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. */ if (!($chan = $this->getChannel($chan_name))) { $bot->noticef($user, "Nobody is on channel %s.", $chan_name); return false; } if (!$chan->isOn($bot->getNumeric())) { $bot->noticef($user, 'I am not on %s.', $chan->getName()); return false; } $reason = assemble($pargs, 2); $users = $this->getChannelUsersByMask($chan_name); foreach ($users as $numeric => $chan_user) { if (!$chan_user->isBot() && $chan_user != $user) { $mask = $chan_user->getHostMask(); $ban = new DB_Ban($chan_reg->getId(), $user->getAccountId(), $mask); $ban->setReason($reason); $chan_reg->addBan($ban); $bot->mode($chan->getName(), "-o+b $numeric $mask"); $bot->kick($chan->getName(), $numeric, $reason); $chan->addBan($mask); } } $chan_reg->save();
briancline/googlecode-ircplanet
Channel/commands/kickbanall.php
PHP
bsd-3-clause
2,380
# -*- coding: utf-8 -*- from django.contrib import admin from ionyweb.plugin_app.plugin_video.models import Plugin_Video admin.site.register(Plugin_Video)
makinacorpus/ionyweb
ionyweb/plugin_app/plugin_video/admin.py
Python
bsd-3-clause
157
/* Copyright (C) 2009-2010 Electronic Arts, 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: 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 Electronic Arts, Inc. ("EA") 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 ELECTRONIC ARTS AND ITS 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 ELECTRONIC ARTS OR ITS 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. */ /////////////////////////////////////////////////////////////////////////////// // FnEncode.h // // Copyright (c) 2007, Electronic Arts Inc. All rights reserved. // Created by Alex Liberman and Talin. // // Character transcoding functions for filenames /////////////////////////////////////////////////////////////////////////////// #ifndef EAIO_FNENCODE_H #define EAIO_FNENCODE_H #ifndef INCLUDED_eabase_H #include <EABase/eabase.h> #endif #include <EAIO/internal/Config.h> #ifndef EAIO_EASTREAM_H #include <EAIO/EAStream.h> // for kLengthNull #endif #ifndef EAIO_PATHSTRING_H #include <EAIO/PathString.h> // for ConvertPathUTF{8,16}ToUTF{8,16} #endif namespace EA { namespace IO { /// StrlcpyUTF16ToUTF8 /// Copies a UTF16 string to a UTF8 string, but otherwise acts similar to strlcpy except for the /// return value. /// Returns the strlen of the destination string. If destination pointer is NULL, returns the /// strlen of the would-be string. /// Specifying a source length of kLengthNull copies from the source string up to the first NULL /// character. EAIO_API size_t StrlcpyUTF16ToUTF8(char8_t* pDest, size_t nDestLength, const char16_t* pSrc, size_t nSrcLength = kLengthNull); /// StrlcpyUTF8ToUTF16 /// Copies a UTF8 string to a UTF16 string, but otherwise acts similar to strlcpy except for the /// return value. /// Returns the strlen of the destination string. If destination pointer is NULL, returns the /// strlen of the would-be string. /// Specifying a source length of kLengthNull copies from the source string up to the first NULL /// character. EAIO_API size_t StrlcpyUTF8ToUTF16(char16_t* pDest, size_t nDestLength, const char8_t* pSrc, size_t nSrcLength = kLengthNull); /////////////////////////////////////////////////////////////////////////////// /// Convenient conversion functions used by EAFileUtil and EAFileNotification /////////////////////////////////////////////////////////////////////////////// /// ConvertPathUTF8ToUTF16 /// Expands the destination to the desired size and then performs a Strlcpy /// with UTF8->UTF16 conversion. /// Returns the number of characters written. EAIO_API uint32_t ConvertPathUTF8ToUTF16(Path::PathString16& dstPath16, const char8_t* pSrcPath8); /// ConvertPathUTF16ToUTF8 /// Expands the destination to the desired size and then performs a Strlcpy with /// UTF16->UTF8 conversion. /// Returns the number of characters written. EAIO_API uint32_t ConvertPathUTF16ToUTF8(Path::PathString8& dstPath8, const char16_t* pSrcPath16); /////////////////////////////////////////////////////////////////////////////// // String comparison, strlen, and strlcpy for this module, since we don't have // access to EACRT. /////////////////////////////////////////////////////////////////////////////// EAIO_API bool StrEq16(const char16_t* str1, const char16_t* str2); EAIO_API size_t EAIOStrlen8(const char8_t* str); EAIO_API size_t EAIOStrlen16(const char16_t* str); EAIO_API size_t EAIOStrlcpy8(char8_t* pDestination, const char8_t* pSource, size_t nDestCapacity); EAIO_API size_t EAIOStrlcpy16(char16_t* pDestination, const char16_t* pSource, size_t nDestCapacity); } // namespace IO } // namespace EA #endif // EAIO_FNENCODE_H
kitsilanosoftware/EAIO
include/EAIO/FnEncode.h
C
bsd-3-clause
5,095
/* * Copyright (c) 2009-2015, United States Government, as represented by the Secretary of Health and Human Services. * 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 United States Government 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 UNITED STATES GOVERNMENT 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 gov.hhs.fha.nhinc.docquery.nhin.proxy; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.any; import gov.hhs.fha.nhinc.aspect.NwhinInvocationEvent; import gov.hhs.fha.nhinc.common.nhinccommon.AssertionType; import gov.hhs.fha.nhinc.common.nhinccommon.HomeCommunityType; import gov.hhs.fha.nhinc.common.nhinccommon.NhinTargetSystemType; import gov.hhs.fha.nhinc.connectmgr.ConnectionManager; import gov.hhs.fha.nhinc.connectmgr.ConnectionManagerCache; import gov.hhs.fha.nhinc.docquery.aspect.AdhocQueryRequestDescriptionBuilder; import gov.hhs.fha.nhinc.docquery.aspect.AdhocQueryResponseDescriptionBuilder; import gov.hhs.fha.nhinc.messaging.client.CONNECTClient; import gov.hhs.fha.nhinc.messaging.service.port.ServicePortDescriptor; import gov.hhs.fha.nhinc.nhinclib.NhincConstants.UDDI_SPEC_VERSION; import ihe.iti.xds_b._2007.RespondingGatewayQueryPortType; import java.lang.reflect.Method; import javax.xml.ws.Service; import oasis.names.tc.ebxml_regrep.xsd.query._3.AdhocQueryRequest; import org.jmock.Mockery; import org.jmock.integration.junit4.JMock; import org.jmock.integration.junit4.JUnit4Mockery; import org.jmock.lib.legacy.ClassImposteriser; import org.junit.Test; import org.junit.runner.RunWith; /** * * @author Neil Webb */ @RunWith(JMock.class) public class NhinDocQueryWebServiceProxyTest { Mockery context = new JUnit4Mockery() { { setImposteriser(ClassImposteriser.INSTANCE); } }; final Service mockService = context.mock(Service.class); final RespondingGatewayQueryPortType mockPort = context.mock(RespondingGatewayQueryPortType.class); @SuppressWarnings("unchecked") private CONNECTClient<RespondingGatewayQueryPortType> client = mock(CONNECTClient.class); private ConnectionManagerCache cache = mock(ConnectionManagerCache.class); private AdhocQueryRequest request; private AssertionType assertion; @Test public void hasBeginOutboundProcessingEvent() throws Exception { Class<NhinDocQueryProxyWebServiceSecuredImpl> clazz = NhinDocQueryProxyWebServiceSecuredImpl.class; Method method = clazz.getMethod("respondingGatewayCrossGatewayQuery", AdhocQueryRequest.class, AssertionType.class, NhinTargetSystemType.class); NwhinInvocationEvent annotation = method.getAnnotation(NwhinInvocationEvent.class); assertNotNull(annotation); assertEquals(AdhocQueryRequestDescriptionBuilder.class, annotation.beforeBuilder()); assertEquals(AdhocQueryResponseDescriptionBuilder.class, annotation.afterReturningBuilder()); assertEquals("Document Query", annotation.serviceType()); assertEquals("", annotation.version()); } @Test public void testNoMtom() throws Exception { NhinDocQueryProxyWebServiceSecuredImpl impl = getImpl(); NhinTargetSystemType target = getTarget("1.1"); impl.respondingGatewayCrossGatewayQuery(request, assertion, target); verify(client, never()).enableMtom(); } @Test public void testUsingGuidance() throws Exception { NhinDocQueryProxyWebServiceSecuredImpl impl = getImpl(); NhinTargetSystemType target = getTarget("1.1"); impl.respondingGatewayCrossGatewayQuery(request, assertion, target); verify(cache).getEndpointURLByServiceNameSpecVersion(any(String.class), any(String.class), any(UDDI_SPEC_VERSION.class)); } /** * @param hcidValue * @return */ private NhinTargetSystemType getTarget(String hcidValue) { NhinTargetSystemType target = new NhinTargetSystemType(); HomeCommunityType hcid = new HomeCommunityType(); hcid.setHomeCommunityId(hcidValue); target.setHomeCommunity(hcid); target.setUseSpecVersion("2.0"); return target; } /** * @return */ private NhinDocQueryProxyWebServiceSecuredImpl getImpl() { return new NhinDocQueryProxyWebServiceSecuredImpl() { /* * (non-Javadoc) * * @see * gov.hhs.fha.nhinc.docquery.nhin.proxy.NhinDocQueryProxyWebServiceSecuredImpl#getCONNECTClientSecured( * gov.hhs.fha.nhinc.messaging.service.port.ServicePortDescriptor, * gov.hhs.fha.nhinc.common.nhinccommon.AssertionType, java.lang.String, * gov.hhs.fha.nhinc.common.nhinccommon.NhinTargetSystemType) */ @Override public CONNECTClient<RespondingGatewayQueryPortType> getCONNECTClientSecured( ServicePortDescriptor<RespondingGatewayQueryPortType> portDescriptor, AssertionType assertion, String url, NhinTargetSystemType target) { return client; } /* (non-Javadoc) * @see gov.hhs.fha.nhinc.docquery.nhin.proxy.NhinDocQueryProxyWebServiceSecuredImpl#getCMInstance() */ @Override protected ConnectionManager getCMInstance() { return cache; } }; } }
beiyuxinke/CONNECT
Product/Production/Services/DocumentQueryCore/src/test/java/gov/hhs/fha/nhinc/docquery/nhin/proxy/NhinDocQueryWebServiceProxyTest.java
Java
bsd-3-clause
6,930
// Copyright (c) 2009 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 CHROME_BROWSER_VIEWS_TABS_NATIVE_VIEW_PHOTOBOOTH_GTK_H_ #define CHROME_BROWSER_VIEWS_TABS_NATIVE_VIEW_PHOTOBOOTH_GTK_H_ #include "chrome/browser/views/tabs/native_view_photobooth.h" class NativeViewPhotoboothGtk : public NativeViewPhotobooth { public: explicit NativeViewPhotoboothGtk(gfx::NativeView new_view); // Destroys the photo booth window. virtual ~NativeViewPhotoboothGtk(); // Replaces the view in the photo booth with the specified one. virtual void Replace(gfx::NativeView new_view); // Paints the current display image of the window into |canvas|, clipped to // |target_bounds|. virtual void PaintScreenshotIntoCanvas(gfx::Canvas* canvas, const gfx::Rect& target_bounds); private: DISALLOW_COPY_AND_ASSIGN(NativeViewPhotoboothGtk); }; #endif // #ifndef CHROME_BROWSER_VIEWS_TABS_NATIVE_VIEW_PHOTOBOOTH_GTK_H_
kuiche/chromium
chrome/browser/views/tabs/native_view_photobooth_gtk.h
C
bsd-3-clause
1,069
<?php /** * Zend Framework (http://framework.zend.com/) * * @link http://github.com/zendframework/zf2 for the canonical source repository * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace Zend\Form\Element; use Traversable; use Zend\Form\Element; use Zend\Form\ElementInterface; use Zend\Form\Exception; use Zend\Form\Fieldset; use Zend\Form\FieldsetInterface; use Zend\Form\FormInterface; use Zend\Stdlib\ArrayUtils; class Collection extends Fieldset { /** * Default template placeholder */ const DEFAULT_TEMPLATE_PLACEHOLDER = '__index__'; /** * Element used in the collection * * @var ElementInterface */ protected $targetElement; /** * Initial count of target element * * @var int */ protected $count = 1; /** * Are new elements allowed to be added dynamically ? * * @var bool */ protected $allowAdd = true; /** * Are existing elements allowed to be removed dynamically ? * * @var bool */ protected $allowRemove = true; /** * Is the template generated ? * * @var bool */ protected $shouldCreateTemplate = false; /** * Placeholder used in template content for making your life easier with JavaScript * * @var string */ protected $templatePlaceholder = self::DEFAULT_TEMPLATE_PLACEHOLDER; /** * Whether or not to create new objects during modify * * @var bool */ protected $createNewObjects = false; /** * Element used as a template * * @var ElementInterface|FieldsetInterface */ protected $templateElement; /** * The index of the last child element or fieldset * * @var int */ protected $lastChildIndex = -1; /** * Should child elements must be created on self::prepareElement()? * * @var bool */ protected $shouldCreateChildrenOnPrepareElement = true; /** * Accepted options for Collection: * - target_element: an array or element used in the collection * - count: number of times the element is added initially * - allow_add: if set to true, elements can be added to the form dynamically (using JavaScript) * - allow_remove: if set to true, elements can be removed to the form * - should_create_template: if set to true, a template is generated (inside a <span>) * - template_placeholder: placeholder used in the data template * * @param array|Traversable $options * @return Collection */ public function setOptions($options) { parent::setOptions($options); if (isset($options['target_element'])) { $this->setTargetElement($options['target_element']); } if (isset($options['count'])) { $this->setCount($options['count']); } if (isset($options['allow_add'])) { $this->setAllowAdd($options['allow_add']); } if (isset($options['allow_remove'])) { $this->setAllowRemove($options['allow_remove']); } if (isset($options['should_create_template'])) { $this->setShouldCreateTemplate($options['should_create_template']); } if (isset($options['template_placeholder'])) { $this->setTemplatePlaceholder($options['template_placeholder']); } if (isset($options['create_new_objects'])) { $this->setCreateNewObjects($options['create_new_objects']); } return $this; } /** * Checks if the object can be set in this fieldset * * @param object $object * @return bool */ public function allowObjectBinding($object) { return true; } /** * Set the object used by the hydrator * In this case the "object" is a collection of objects * * @param array|Traversable $object * @return Fieldset|FieldsetInterface * @throws Exception\InvalidArgumentException */ public function setObject($object) { if (!is_array($object) && !$object instanceof Traversable) { throw new Exception\InvalidArgumentException(sprintf( '%s expects an array or Traversable object argument; received "%s"', __METHOD__, (is_object($object) ? get_class($object) : gettype($object)) )); } $this->object = $object; $this->count = count($object) > $this->count ? count($object) : $this->count; return $this; } /** * Populate values * * @param array|Traversable $data * @throws \Zend\Form\Exception\InvalidArgumentException * @throws \Zend\Form\Exception\DomainException * @return void */ public function populateValues($data) { if (!is_array($data) && !$data instanceof Traversable) { throw new Exception\InvalidArgumentException(sprintf( '%s expects an array or Traversable set of data; received "%s"', __METHOD__, (is_object($data) ? get_class($data) : gettype($data)) )); } // Can't do anything with empty data if (empty($data)) { return; } if (!$this->allowRemove && count($data) < $this->count) { throw new Exception\DomainException(sprintf( 'There are fewer elements than specified in the collection (%s). Either set the allow_remove option ' . 'to true, or re-submit the form.', get_class($this) )); } // Check to see if elements have been replaced or removed foreach ($this->byName as $name => $elementOrFieldset) { if (isset($data[$name])) { continue; } if (!$this->allowRemove) { throw new Exception\DomainException(sprintf( 'Elements have been removed from the collection (%s) but the allow_remove option is not true.', get_class($this) )); } $this->remove($name); } foreach ($data as $key => $value) { if ($this->has($key)) { $elementOrFieldset = $this->get($key); } else { $elementOrFieldset = $this->addNewTargetElementInstance($key); if ($key > $this->lastChildIndex) { $this->lastChildIndex = $key; } } if ($elementOrFieldset instanceof FieldsetInterface) { $elementOrFieldset->populateValues($value); } else { $elementOrFieldset->setAttribute('value', $value); } } if (!$this->createNewObjects()) { $this->replaceTemplateObjects(); } } /** * Checks if this fieldset can bind data * * @return bool */ public function allowValueBinding() { return true; } /** * Bind values to the object * * @param array $values * @return array|mixed|void */ public function bindValues(array $values = array()) { $collection = array(); foreach ($values as $name => $value) { $element = $this->get($name); if ($element instanceof FieldsetInterface) { $collection[] = $element->bindValues($value); } else { $collection[] = $value; } } return $collection; } /** * Set the initial count of target element * * @param $count * @return Collection */ public function setCount($count) { $this->count = $count > 0 ? $count : 0; return $this; } /** * Get the initial count of target element * * @return int */ public function getCount() { return $this->count; } /** * Set the target element * * @param ElementInterface|array|Traversable $elementOrFieldset * @return Collection * @throws \Zend\Form\Exception\InvalidArgumentException */ public function setTargetElement($elementOrFieldset) { if (is_array($elementOrFieldset) || ($elementOrFieldset instanceof Traversable && !$elementOrFieldset instanceof ElementInterface) ) { $factory = $this->getFormFactory(); $elementOrFieldset = $factory->create($elementOrFieldset); } if (!$elementOrFieldset instanceof ElementInterface) { throw new Exception\InvalidArgumentException(sprintf( '%s requires that $elementOrFieldset be an object implementing %s; received "%s"', __METHOD__, __NAMESPACE__ . '\ElementInterface', (is_object($elementOrFieldset) ? get_class($elementOrFieldset) : gettype($elementOrFieldset)) )); } $this->targetElement = $elementOrFieldset; return $this; } /** * Get target element * * @return ElementInterface|null */ public function getTargetElement() { return $this->targetElement; } /** * Get allow add * * @param bool $allowAdd * @return Collection */ public function setAllowAdd($allowAdd) { $this->allowAdd = (bool) $allowAdd; return $this; } /** * Get allow add * * @return bool */ public function allowAdd() { return $this->allowAdd; } /** * @param bool $allowRemove * @return Collection */ public function setAllowRemove($allowRemove) { $this->allowRemove = (bool) $allowRemove; return $this; } /** * @return bool */ public function allowRemove() { return $this->allowRemove; } /** * If set to true, a template prototype is automatically added to the form to ease the creation of dynamic elements through JavaScript * * @param bool $shouldCreateTemplate * @return Collection */ public function setShouldCreateTemplate($shouldCreateTemplate) { $this->shouldCreateTemplate = (bool) $shouldCreateTemplate; return $this; } /** * Get if the collection should create a template * * @return bool */ public function shouldCreateTemplate() { return $this->shouldCreateTemplate; } /** * Set the placeholder used in the template generated to help create new elements in JavaScript * * @param string $templatePlaceholder * @return Collection */ public function setTemplatePlaceholder($templatePlaceholder) { if (is_string($templatePlaceholder)) { $this->templatePlaceholder = $templatePlaceholder; } return $this; } /** * Get the template placeholder * * @return string */ public function getTemplatePlaceholder() { return $this->templatePlaceholder; } /** * @param bool $createNewObjects * @return Collection */ public function setCreateNewObjects($createNewObjects) { $this->createNewObjects = (bool) $createNewObjects; return $this; } /** * @return bool */ public function createNewObjects() { return $this->createNewObjects; } /** * Get a template element used for rendering purposes only * * @return null|ElementInterface|FieldsetInterface */ public function getTemplateElement() { if ($this->templateElement === null) { $this->templateElement = $this->createTemplateElement(); } return $this->templateElement; } /** * Prepare the collection by adding a dummy template element if the user want one * * @param FormInterface $form * @return mixed|void */ public function prepareElement(FormInterface $form) { if (true === $this->shouldCreateChildrenOnPrepareElement) { if ($this->targetElement !== null && $this->count > 0) { while ($this->count > $this->lastChildIndex + 1) { $this->addNewTargetElementInstance(++$this->lastChildIndex); } } } // Create a template that will also be prepared if ($this->shouldCreateTemplate) { $templateElement = $this->getTemplateElement(); $this->add($templateElement); } parent::prepareElement($form); // The template element has been prepared, but we don't want it to be rendered nor validated, so remove it from the list if ($this->shouldCreateTemplate) { $this->remove($this->templatePlaceholder); } } /** * @return array * @throws \Zend\Form\Exception\InvalidArgumentException * @throws \Zend\Stdlib\Exception\InvalidArgumentException * @throws \Zend\Form\Exception\DomainException * @throws \Zend\Form\Exception\InvalidElementException */ public function extract() { if ($this->object instanceof Traversable) { $this->object = ArrayUtils::iteratorToArray($this->object, false); } if (!is_array($this->object)) { return array(); } $values = array(); foreach ($this->object as $key => $value) { // If a hydrator is provided, our work here is done if ($this->hydrator) { $values[$key] = $this->hydrator->extract($value); continue; } // If the target element is a fieldset that can accept the provided value // we should clone it, inject the value and extract the data if ( $this->targetElement instanceof FieldsetInterface ) { if ( ! $this->targetElement->allowObjectBinding($value) ) { continue; } $targetElement = clone $this->targetElement; $targetElement->setObject($value); $values[$key] = $targetElement->extract(); if (!$this->createNewObjects() && $this->has($key)) { $this->get($key)->setObject($value); } continue; } // If the target element is a non-fieldset element, just use the value if ( $this->targetElement instanceof ElementInterface ) { $values[$key] = $value; if (!$this->createNewObjects() && $this->has($key)) { $this->get($key)->setValue($value); } continue; } } return $values; } /** * Create a new instance of the target element * * @return ElementInterface */ protected function createNewTargetElementInstance() { return clone $this->targetElement; } /** * Add a new instance of the target element * * @param string $name * @return ElementInterface * @throws Exception\DomainException */ protected function addNewTargetElementInstance($name) { $this->shouldCreateChildrenOnPrepareElement = false; $elementOrFieldset = $this->createNewTargetElementInstance(); $elementOrFieldset->setName($name); $this->add($elementOrFieldset); if (!$this->allowAdd && $this->count() > $this->count) { throw new Exception\DomainException(sprintf( 'There are more elements than specified in the collection (%s). Either set the allow_add option ' . 'to true, or re-submit the form.', get_class($this) )); } return $elementOrFieldset; } /** * Create a dummy template element * * @return null|ElementInterface|FieldsetInterface */ protected function createTemplateElement() { if (!$this->shouldCreateTemplate) { return null; } if ($this->templateElement) { return $this->templateElement; } $elementOrFieldset = $this->createNewTargetElementInstance(); $elementOrFieldset->setName($this->templatePlaceholder); return $elementOrFieldset; } /** * Replaces the default template object of a sub element with the corresponding * real entity so that all properties are preserved. * * @return void */ protected function replaceTemplateObjects() { $fieldsets = $this->getFieldsets(); if (!count($fieldsets) || !$this->object) { return; } foreach ($fieldsets as $fieldset) { $i = $fieldset->getName(); if (isset($this->object[$i])) { $fieldset->setObject($this->object[$i]); } } } }
stromengine/10001
vendor/zendframework/zendframework/library/Zend/Form/Element/Collection.php
PHP
bsd-3-clause
17,810
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE415_Double_Free__new_delete_wchar_t_83.h Label Definition File: CWE415_Double_Free__new_delete.label.xml Template File: sources-sinks-83.tmpl.h */ /* * @description * CWE: 415 Double Free * BadSource: Allocate data using new and Deallocae data using delete * GoodSource: Allocate data using new * Sinks: * GoodSink: do nothing * BadSink : Deallocate data using delete * Flow Variant: 83 Data flow: data passed to class constructor and destructor by declaring the class object on the stack * * */ #include "std_testcase.h" #include <wchar.h> namespace CWE415_Double_Free__new_delete_wchar_t_83 { #ifndef OMITBAD class CWE415_Double_Free__new_delete_wchar_t_83_bad { public: CWE415_Double_Free__new_delete_wchar_t_83_bad(wchar_t * dataCopy); ~CWE415_Double_Free__new_delete_wchar_t_83_bad(); private: wchar_t * data; }; #endif /* OMITBAD */ #ifndef OMITGOOD class CWE415_Double_Free__new_delete_wchar_t_83_goodG2B { public: CWE415_Double_Free__new_delete_wchar_t_83_goodG2B(wchar_t * dataCopy); ~CWE415_Double_Free__new_delete_wchar_t_83_goodG2B(); private: wchar_t * data; }; class CWE415_Double_Free__new_delete_wchar_t_83_goodB2G { public: CWE415_Double_Free__new_delete_wchar_t_83_goodB2G(wchar_t * dataCopy); ~CWE415_Double_Free__new_delete_wchar_t_83_goodB2G(); private: wchar_t * data; }; #endif /* OMITGOOD */ }
JianpingZeng/xcc
xcc/test/juliet/testcases/CWE415_Double_Free/s02/CWE415_Double_Free__new_delete_wchar_t_83.h
C
bsd-3-clause
1,497
*> \brief <b> ZCPOSV computes the solution to system of linear equations A * X = B for PO matrices</b> * * =========== DOCUMENTATION =========== * * Online html documentation available at * http://www.netlib.org/lapack/explore-html/ * *> \htmlonly *> Download ZCPOSV + dependencies *> <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/zcposv.f"> *> [TGZ]</a> *> <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/zcposv.f"> *> [ZIP]</a> *> <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/zcposv.f"> *> [TXT]</a> *> \endhtmlonly * * Definition: * =========== * * SUBROUTINE ZCPOSV( UPLO, N, NRHS, A, LDA, B, LDB, X, LDX, WORK, * SWORK, RWORK, ITER, INFO ) * * .. Scalar Arguments .. * CHARACTER UPLO * INTEGER INFO, ITER, LDA, LDB, LDX, N, NRHS * .. * .. Array Arguments .. * DOUBLE PRECISION RWORK( * ) * COMPLEX SWORK( * ) * COMPLEX*16 A( LDA, * ), B( LDB, * ), WORK( N, * ), * $ X( LDX, * ) * .. * * *> \par Purpose: * ============= *> *> \verbatim *> *> ZCPOSV computes the solution to a complex system of linear equations *> A * X = B, *> where A is an N-by-N Hermitian positive definite matrix and X and B *> are N-by-NRHS matrices. *> *> ZCPOSV first attempts to factorize the matrix in COMPLEX and use this *> factorization within an iterative refinement procedure to produce a *> solution with COMPLEX*16 normwise backward error quality (see below). *> If the approach fails the method switches to a COMPLEX*16 *> factorization and solve. *> *> The iterative refinement is not going to be a winning strategy if *> the ratio COMPLEX performance over COMPLEX*16 performance is too *> small. A reasonable strategy should take the number of right-hand *> sides and the size of the matrix into account. This might be done *> with a call to ILAENV in the future. Up to now, we always try *> iterative refinement. *> *> The iterative refinement process is stopped if *> ITER > ITERMAX *> or for all the RHS we have: *> RNRM < SQRT(N)*XNRM*ANRM*EPS*BWDMAX *> where *> o ITER is the number of the current iteration in the iterative *> refinement process *> o RNRM is the infinity-norm of the residual *> o XNRM is the infinity-norm of the solution *> o ANRM is the infinity-operator-norm of the matrix A *> o EPS is the machine epsilon returned by DLAMCH('Epsilon') *> The value ITERMAX and BWDMAX are fixed to 30 and 1.0D+00 *> respectively. *> \endverbatim * * Arguments: * ========== * *> \param[in] UPLO *> \verbatim *> UPLO is CHARACTER*1 *> = 'U': Upper triangle of A is stored; *> = 'L': Lower triangle of A is stored. *> \endverbatim *> *> \param[in] N *> \verbatim *> N is INTEGER *> The number of linear equations, i.e., the order of the *> matrix A. N >= 0. *> \endverbatim *> *> \param[in] NRHS *> \verbatim *> NRHS is INTEGER *> The number of right hand sides, i.e., the number of columns *> of the matrix B. NRHS >= 0. *> \endverbatim *> *> \param[in,out] A *> \verbatim *> A is COMPLEX*16 array, *> dimension (LDA,N) *> On entry, the Hermitian matrix A. If UPLO = 'U', the leading *> N-by-N upper triangular part of A contains the upper *> triangular part of the matrix A, and the strictly lower *> triangular part of A is not referenced. If UPLO = 'L', the *> leading N-by-N lower triangular part of A contains the lower *> triangular part of the matrix A, and the strictly upper *> triangular part of A is not referenced. *> *> Note that the imaginary parts of the diagonal *> elements need not be set and are assumed to be zero. *> *> On exit, if iterative refinement has been successfully used *> (INFO = 0 and ITER >= 0, see description below), then A is *> unchanged, if double precision factorization has been used *> (INFO = 0 and ITER < 0, see description below), then the *> array A contains the factor U or L from the Cholesky *> factorization A = U**H*U or A = L*L**H. *> \endverbatim *> *> \param[in] LDA *> \verbatim *> LDA is INTEGER *> The leading dimension of the array A. LDA >= max(1,N). *> \endverbatim *> *> \param[in] B *> \verbatim *> B is COMPLEX*16 array, dimension (LDB,NRHS) *> The N-by-NRHS right hand side matrix B. *> \endverbatim *> *> \param[in] LDB *> \verbatim *> LDB is INTEGER *> The leading dimension of the array B. LDB >= max(1,N). *> \endverbatim *> *> \param[out] X *> \verbatim *> X is COMPLEX*16 array, dimension (LDX,NRHS) *> If INFO = 0, the N-by-NRHS solution matrix X. *> \endverbatim *> *> \param[in] LDX *> \verbatim *> LDX is INTEGER *> The leading dimension of the array X. LDX >= max(1,N). *> \endverbatim *> *> \param[out] WORK *> \verbatim *> WORK is COMPLEX*16 array, dimension (N,NRHS) *> This array is used to hold the residual vectors. *> \endverbatim *> *> \param[out] SWORK *> \verbatim *> SWORK is COMPLEX array, dimension (N*(N+NRHS)) *> This array is used to use the single precision matrix and the *> right-hand sides or solutions in single precision. *> \endverbatim *> *> \param[out] RWORK *> \verbatim *> RWORK is DOUBLE PRECISION array, dimension (N) *> \endverbatim *> *> \param[out] ITER *> \verbatim *> ITER is INTEGER *> < 0: iterative refinement has failed, COMPLEX*16 *> factorization has been performed *> -1 : the routine fell back to full precision for *> implementation- or machine-specific reasons *> -2 : narrowing the precision induced an overflow, *> the routine fell back to full precision *> -3 : failure of CPOTRF *> -31: stop the iterative refinement after the 30th *> iterations *> > 0: iterative refinement has been successfully used. *> Returns the number of iterations *> \endverbatim *> *> \param[out] INFO *> \verbatim *> INFO is INTEGER *> = 0: successful exit *> < 0: if INFO = -i, the i-th argument had an illegal value *> > 0: if INFO = i, the leading minor of order i of *> (COMPLEX*16) A is not positive definite, so the *> factorization could not be completed, and the solution *> has not been computed. *> \endverbatim * * Authors: * ======== * *> \author Univ. of Tennessee *> \author Univ. of California Berkeley *> \author Univ. of Colorado Denver *> \author NAG Ltd. * *> \date June 2016 * *> \ingroup complex16POsolve * * ===================================================================== SUBROUTINE ZCPOSV( UPLO, N, NRHS, A, LDA, B, LDB, X, LDX, WORK, $ SWORK, RWORK, ITER, INFO ) * * -- LAPACK driver routine (version 3.8.0) -- * -- LAPACK is a software package provided by Univ. of Tennessee, -- * -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- * June 2016 * * .. Scalar Arguments .. CHARACTER UPLO INTEGER INFO, ITER, LDA, LDB, LDX, N, NRHS * .. * .. Array Arguments .. DOUBLE PRECISION RWORK( * ) COMPLEX SWORK( * ) COMPLEX*16 A( LDA, * ), B( LDB, * ), WORK( N, * ), $ X( LDX, * ) * .. * * ===================================================================== * * .. Parameters .. LOGICAL DOITREF PARAMETER ( DOITREF = .TRUE. ) * INTEGER ITERMAX PARAMETER ( ITERMAX = 30 ) * DOUBLE PRECISION BWDMAX PARAMETER ( BWDMAX = 1.0E+00 ) * COMPLEX*16 NEGONE, ONE PARAMETER ( NEGONE = ( -1.0D+00, 0.0D+00 ), $ ONE = ( 1.0D+00, 0.0D+00 ) ) * * .. Local Scalars .. INTEGER I, IITER, PTSA, PTSX DOUBLE PRECISION ANRM, CTE, EPS, RNRM, XNRM COMPLEX*16 ZDUM * * .. External Subroutines .. EXTERNAL ZAXPY, ZHEMM, ZLACPY, ZLAT2C, ZLAG2C, CLAG2Z, $ CPOTRF, CPOTRS, XERBLA, ZPOTRF, ZPOTRS * .. * .. External Functions .. INTEGER IZAMAX DOUBLE PRECISION DLAMCH, ZLANHE LOGICAL LSAME EXTERNAL IZAMAX, DLAMCH, ZLANHE, LSAME * .. * .. Intrinsic Functions .. INTRINSIC ABS, DBLE, MAX, SQRT * .. Statement Functions .. DOUBLE PRECISION CABS1 * .. * .. Statement Function definitions .. CABS1( ZDUM ) = ABS( DBLE( ZDUM ) ) + ABS( DIMAG( ZDUM ) ) * .. * .. Executable Statements .. * INFO = 0 ITER = 0 * * Test the input parameters. * IF( .NOT.LSAME( UPLO, 'U' ) .AND. .NOT.LSAME( UPLO, 'L' ) ) THEN INFO = -1 ELSE IF( N.LT.0 ) THEN INFO = -2 ELSE IF( NRHS.LT.0 ) THEN INFO = -3 ELSE IF( LDA.LT.MAX( 1, N ) ) THEN INFO = -5 ELSE IF( LDB.LT.MAX( 1, N ) ) THEN INFO = -7 ELSE IF( LDX.LT.MAX( 1, N ) ) THEN INFO = -9 END IF IF( INFO.NE.0 ) THEN CALL XERBLA( 'ZCPOSV', -INFO ) RETURN END IF * * Quick return if (N.EQ.0). * IF( N.EQ.0 ) $ RETURN * * Skip single precision iterative refinement if a priori slower * than double precision factorization. * IF( .NOT.DOITREF ) THEN ITER = -1 GO TO 40 END IF * * Compute some constants. * ANRM = ZLANHE( 'I', UPLO, N, A, LDA, RWORK ) EPS = DLAMCH( 'Epsilon' ) CTE = ANRM*EPS*SQRT( DBLE( N ) )*BWDMAX * * Set the indices PTSA, PTSX for referencing SA and SX in SWORK. * PTSA = 1 PTSX = PTSA + N*N * * Convert B from double precision to single precision and store the * result in SX. * CALL ZLAG2C( N, NRHS, B, LDB, SWORK( PTSX ), N, INFO ) * IF( INFO.NE.0 ) THEN ITER = -2 GO TO 40 END IF * * Convert A from double precision to single precision and store the * result in SA. * CALL ZLAT2C( UPLO, N, A, LDA, SWORK( PTSA ), N, INFO ) * IF( INFO.NE.0 ) THEN ITER = -2 GO TO 40 END IF * * Compute the Cholesky factorization of SA. * CALL CPOTRF( UPLO, N, SWORK( PTSA ), N, INFO ) * IF( INFO.NE.0 ) THEN ITER = -3 GO TO 40 END IF * * Solve the system SA*SX = SB. * CALL CPOTRS( UPLO, N, NRHS, SWORK( PTSA ), N, SWORK( PTSX ), N, $ INFO ) * * Convert SX back to COMPLEX*16 * CALL CLAG2Z( N, NRHS, SWORK( PTSX ), N, X, LDX, INFO ) * * Compute R = B - AX (R is WORK). * CALL ZLACPY( 'All', N, NRHS, B, LDB, WORK, N ) * CALL ZHEMM( 'Left', UPLO, N, NRHS, NEGONE, A, LDA, X, LDX, ONE, $ WORK, N ) * * Check whether the NRHS normwise backward errors satisfy the * stopping criterion. If yes, set ITER=0 and return. * DO I = 1, NRHS XNRM = CABS1( X( IZAMAX( N, X( 1, I ), 1 ), I ) ) RNRM = CABS1( WORK( IZAMAX( N, WORK( 1, I ), 1 ), I ) ) IF( RNRM.GT.XNRM*CTE ) $ GO TO 10 END DO * * If we are here, the NRHS normwise backward errors satisfy the * stopping criterion. We are good to exit. * ITER = 0 RETURN * 10 CONTINUE * DO 30 IITER = 1, ITERMAX * * Convert R (in WORK) from double precision to single precision * and store the result in SX. * CALL ZLAG2C( N, NRHS, WORK, N, SWORK( PTSX ), N, INFO ) * IF( INFO.NE.0 ) THEN ITER = -2 GO TO 40 END IF * * Solve the system SA*SX = SR. * CALL CPOTRS( UPLO, N, NRHS, SWORK( PTSA ), N, SWORK( PTSX ), N, $ INFO ) * * Convert SX back to double precision and update the current * iterate. * CALL CLAG2Z( N, NRHS, SWORK( PTSX ), N, WORK, N, INFO ) * DO I = 1, NRHS CALL ZAXPY( N, ONE, WORK( 1, I ), 1, X( 1, I ), 1 ) END DO * * Compute R = B - AX (R is WORK). * CALL ZLACPY( 'All', N, NRHS, B, LDB, WORK, N ) * CALL ZHEMM( 'L', UPLO, N, NRHS, NEGONE, A, LDA, X, LDX, ONE, $ WORK, N ) * * Check whether the NRHS normwise backward errors satisfy the * stopping criterion. If yes, set ITER=IITER>0 and return. * DO I = 1, NRHS XNRM = CABS1( X( IZAMAX( N, X( 1, I ), 1 ), I ) ) RNRM = CABS1( WORK( IZAMAX( N, WORK( 1, I ), 1 ), I ) ) IF( RNRM.GT.XNRM*CTE ) $ GO TO 20 END DO * * If we are here, the NRHS normwise backward errors satisfy the * stopping criterion, we are good to exit. * ITER = IITER * RETURN * 20 CONTINUE * 30 CONTINUE * * If we are at this place of the code, this is because we have * performed ITER=ITERMAX iterations and never satisfied the * stopping criterion, set up the ITER flag accordingly and follow * up on double precision routine. * ITER = -ITERMAX - 1 * 40 CONTINUE * * Single-precision iterative refinement failed to converge to a * satisfactory solution, so we resort to double precision. * CALL ZPOTRF( UPLO, N, A, LDA, INFO ) * IF( INFO.NE.0 ) $ RETURN * CALL ZLACPY( 'All', N, NRHS, B, LDB, X, LDX ) CALL ZPOTRS( UPLO, N, NRHS, A, LDA, X, LDX, INFO ) * RETURN * * End of ZCPOSV. * END
xianyi/OpenBLAS
lapack-netlib/SRC/zcposv.f
FORTRAN
bsd-3-clause
13,922
/* The <sys/stat.h> header defines a struct that is used in the stat() and * fstat functions. The information in this struct comes from the i-node of * some file. These calls are the only approved way to inspect i-nodes. */ #ifndef _STAT_H #define _STAT_H struct stat { dev_t st_dev; /* major/minor device number */ ino_t st_ino; /* i-node number */ mode_t st_mode; /* file mode, protection bits, etc. */ short int st_nlink; /* # links; TEMPORARY HACK: should be nlink_t*/ uid_t st_uid; /* uid of the file's owner */ short int st_gid; /* gid; TEMPORARY HACK: should be gid_t */ dev_t st_rdev; off_t st_size; /* file size */ time_t st_atime; /* time of last access */ time_t st_mtime; /* time of last data modification */ time_t st_ctime; /* time of last file status change */ }; /* Traditional mask definitions for st_mode. */ /* The ugly casts on only some of the definitions are to avoid suprising sign * extensions such as S_IFREG != (mode_t) S_IFREG when ints are 32 bits. */ #define S_IFMT ((mode_t) 0170000) /* type of file */ #define S_IFREG ((mode_t) 0100000) /* regular */ #define S_IFBLK 0060000 /* block special */ #define S_IFDIR 0040000 /* directory */ #define S_IFCHR 0020000 /* character special */ #define S_IFIFO 0010000 /* this is a FIFO */ #define S_ISUID 0004000 /* set user id on execution */ #define S_ISGID 0002000 /* set group id on execution */ /* next is reserved for future use */ #define S_ISVTX 01000 /* save swapped text even after use */ /* POSIX masks for st_mode. */ #define S_IRWXU 00700 /* owner: rwx------ */ #define S_IRUSR 00400 /* owner: r-------- */ #define S_IWUSR 00200 /* owner: -w------- */ #define S_IXUSR 00100 /* owner: --x------ */ #define S_IRWXG 00070 /* group: ---rwx--- */ #define S_IRGRP 00040 /* group: ---r----- */ #define S_IWGRP 00020 /* group: ----w---- */ #define S_IXGRP 00010 /* group: -----x--- */ #define S_IRWXO 00007 /* others: ------rwx */ #define S_IROTH 00004 /* others: ------r-- */ #define S_IWOTH 00002 /* others: -------w- */ #define S_IXOTH 00001 /* others: --------x */ /* The following macros test st_mode (from POSIX Sec. 5.6.1.1). */ #define S_ISREG(m) (((m) & S_IFMT) == S_IFREG) /* is a reg file */ #define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR) /* is a directory */ #define S_ISCHR(m) (((m) & S_IFMT) == S_IFCHR) /* is a char spec */ #define S_ISBLK(m) (((m) & S_IFMT) == S_IFBLK) /* is a block spec */ #define S_ISFIFO(m) (((m) & S_IFMT) == S_IFIFO) /* is a pipe/FIFO */ /* Function Prototypes. */ #ifndef _ANSI_H #include <ansi.h> #endif _PROTOTYPE( int chmod, (const char *_path, Mode_t _mode) ); _PROTOTYPE( int fstat, (int _fildes, struct stat *_buf) ); _PROTOTYPE( int mkdir, (const char *_path, int _mode) ); _PROTOTYPE( int mkfifo, (const char *_path, int _mode) ); _PROTOTYPE( int stat , (const char *_path, struct stat *_buf) ); _PROTOTYPE( mode_t umask, (int _cmask) ); #endif /* _STAT_H */
Godzil/ack
lib/minix/include/sys/stat.h
C
bsd-3-clause
3,007
/* * Copyright (c) 2011-2013, Longxiang He <helongxiang@smeshlink.com>, * SmeshLink Technology Co. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY. * * This file is part of the CoAP.NET, a CoAP framework in C#. * Please see README for more information. */ using System; namespace CoAP { /// <summary> /// Represents an event when a response arrives for a request. /// </summary> public class ResponseEventArgs : EventArgs { private Response _response; /// <summary> /// /// </summary> public ResponseEventArgs(Response response) { _response = response; } /// <summary> /// Gets the incoming response. /// </summary> public Response Response { get { return _response; } } } }
martindevans/CoAP.NET
CoAP.NET/ResponseEventArgs.cs
C#
bsd-3-clause
893
// 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 MOJO_SERVICES_HTML_VIEWER_BLINK_PLATFORM_IMPL_H_ #define MOJO_SERVICES_HTML_VIEWER_BLINK_PLATFORM_IMPL_H_ #include "base/memory/scoped_ptr.h" #include "base/message_loop/message_loop.h" #include "base/threading/thread_local_storage.h" #include "base/timer/timer.h" #include "cc/blink/web_compositor_support_impl.h" #include "mojo/services/html_viewer/blink_resource_map.h" #include "mojo/services/html_viewer/webmimeregistry_impl.h" #include "mojo/services/html_viewer/webthemeengine_impl.h" #include "third_party/WebKit/public/platform/Platform.h" #include "third_party/WebKit/public/platform/WebScrollbarBehavior.h" namespace html_viewer { class BlinkPlatformImpl : public blink::Platform { public: explicit BlinkPlatformImpl(); virtual ~BlinkPlatformImpl(); // blink::Platform methods: virtual blink::WebMimeRegistry* mimeRegistry(); virtual blink::WebThemeEngine* themeEngine(); virtual blink::WebString defaultLocale(); virtual double currentTime(); virtual double monotonicallyIncreasingTime(); virtual void cryptographicallyRandomValues( unsigned char* buffer, size_t length); virtual void setSharedTimerFiredFunction(void (*func)()); virtual void setSharedTimerFireInterval(double interval_seconds); virtual void stopSharedTimer(); virtual void callOnMainThread(void (*func)(void*), void* context); virtual bool isThreadedCompositingEnabled(); virtual blink::WebCompositorSupport* compositorSupport(); virtual blink::WebURLLoader* createURLLoader(); virtual blink::WebSocketHandle* createWebSocketHandle(); virtual blink::WebString userAgent(); virtual blink::WebData parseDataURL( const blink::WebURL& url, blink::WebString& mime_type, blink::WebString& charset); virtual blink::WebURLError cancelledError(const blink::WebURL& url) const; virtual blink::WebThread* createThread(const char* name); virtual blink::WebThread* currentThread(); virtual void yieldCurrentThread(); virtual blink::WebWaitableEvent* createWaitableEvent(); virtual blink::WebWaitableEvent* waitMultipleEvents( const blink::WebVector<blink::WebWaitableEvent*>& events); virtual blink::WebScrollbarBehavior* scrollbarBehavior(); virtual const unsigned char* getTraceCategoryEnabledFlag( const char* category_name); virtual blink::WebData loadResource(const char* name); private: void SuspendSharedTimer(); void ResumeSharedTimer(); void DoTimeout() { if (shared_timer_func_ && !shared_timer_suspended_) shared_timer_func_(); } static void DestroyCurrentThread(void*); base::MessageLoop* main_loop_; base::OneShotTimer<BlinkPlatformImpl> shared_timer_; void (*shared_timer_func_)(); double shared_timer_fire_time_; bool shared_timer_fire_time_was_set_while_suspended_; int shared_timer_suspended_; // counter base::ThreadLocalStorage::Slot current_thread_slot_; cc_blink::WebCompositorSupportImpl compositor_support_; WebThemeEngineImpl theme_engine_; WebMimeRegistryImpl mime_registry_; blink::WebScrollbarBehavior scrollbar_behavior_; BlinkResourceMap blink_resource_map_; DISALLOW_COPY_AND_ASSIGN(BlinkPlatformImpl); }; } // namespace html_viewer #endif // MOJO_SERVICES_HTML_VIEWER_BLINK_PLATFORM_IMPL_H_
hefen1/chromium
mojo/services/html_viewer/blink_platform_impl.h
C
bsd-3-clause
3,411
/* * Copyright 2009, 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. */ // This file contains the definition of DrawElement. #include "core/cross/precompile.h" #include "core/cross/draw_element.h" #include "core/cross/renderer.h" #include "core/cross/error.h" namespace o3d { O3D_DEFN_CLASS(DrawElement, ParamObject); const char* DrawElement::kMaterialParamName = O3D_STRING_CONSTANT("material"); ObjectBase::Ref DrawElement::Create(ServiceLocator* service_locator) { Renderer* renderer = service_locator->GetService<Renderer>(); if (NULL == renderer) { O3D_ERROR(service_locator) << "No Render Device Available"; return ObjectBase::Ref(); } return ObjectBase::Ref(renderer->CreateDrawElement()); } DrawElement::DrawElement(ServiceLocator* service_locator) : ParamObject(service_locator), owner_(NULL) { RegisterParamRef(kMaterialParamName, &material_param_ref_); } DrawElement::~DrawElement() { } void DrawElement::SetOwner(Element* new_owner) { // Hold a ref to ourselves so we make sure we don't get deleted while // as we remove ourself from our current owner. DrawElement::Ref temp(this); if (owner_ != NULL) { bool removed = owner_->RemoveDrawElement(this); DLOG_ASSERT(removed); } owner_ = new_owner; if (new_owner) { new_owner->AddDrawElement(this); } } } // namespace o3d
amyvmiwei/chromium
o3d/core/cross/draw_element.cc
C++
bsd-3-clause
2,847
#ifndef NT2_INCLUDE_FUNCTIONS_SLIDE_HPP_INCLUDED #define NT2_INCLUDE_FUNCTIONS_SLIDE_HPP_INCLUDED #include <nt2/memory/include/functions/slide.hpp> #include <nt2/memory/include/functions/scalar/slide.hpp> #include <nt2/memory/include/functions/simd/slide.hpp> #endif
hainm/pythran
third_party/nt2/include/functions/slide.hpp
C++
bsd-3-clause
269
// 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 "content/browser/download/mhtml_generation_manager.h" #include <map> #include <queue> #include <utility> #include "base/bind.h" #include "base/files/file.h" #include "base/guid.h" #include "base/macros.h" #include "base/scoped_observer.h" #include "base/stl_util.h" #include "base/strings/stringprintf.h" #include "content/browser/bad_message.h" #include "content/browser/frame_host/frame_tree_node.h" #include "content/browser/frame_host/render_frame_host_impl.h" #include "content/common/frame_messages.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_process_host_observer.h" #include "content/public/browser/web_contents.h" #include "content/public/common/mhtml_generation_params.h" #include "net/base/mime_util.h" namespace content { // The class and all of its members live on the UI thread. Only static methods // are executed on other threads. class MHTMLGenerationManager::Job : public RenderProcessHostObserver { public: Job(int job_id, WebContents* web_contents, const MHTMLGenerationParams& params, const GenerateMHTMLCallback& callback); ~Job() override; int id() const { return job_id_; } void set_browser_file(base::File file) { browser_file_ = std::move(file); } const GenerateMHTMLCallback& callback() const { return callback_; } // Indicates whether we expect a message from the |sender| at this time. // We expect only one message per frame - therefore calling this method // will always clear |frame_tree_node_id_of_busy_frame_|. bool IsMessageFromFrameExpected(RenderFrameHostImpl* sender); // Handler for FrameHostMsg_SerializeAsMHTMLResponse (a notification from the // renderer that the MHTML generation for previous frame has finished). // Returns |true| upon success; |false| otherwise. bool OnSerializeAsMHTMLResponse( const std::set<std::string>& digests_of_uris_of_serialized_resources); // Sends IPC to the renderer, asking for MHTML generation of the next frame. // // Returns true if the message was sent successfully; false otherwise. bool SendToNextRenderFrame(); // Indicates if more calls to SendToNextRenderFrame are needed. bool IsDone() const { bool waiting_for_response_from_renderer = frame_tree_node_id_of_busy_frame_ != FrameTreeNode::kFrameTreeNodeInvalidId; bool no_more_requests_to_send = pending_frame_tree_node_ids_.empty(); return !waiting_for_response_from_renderer && no_more_requests_to_send; } // Close the file on the file thread and respond back on the UI thread with // file size. void CloseFile(base::Callback<void(int64_t file_size)> callback); // RenderProcessHostObserver: void RenderProcessExited(RenderProcessHost* host, base::TerminationStatus status, int exit_code) override; void RenderProcessHostDestroyed(RenderProcessHost* host) override; void MarkAsFinished(); private: static int64_t CloseFileOnFileThread(base::File file); void AddFrame(RenderFrameHost* render_frame_host); // Creates a new map with values (content ids) the same as in // |frame_tree_node_to_content_id_| map, but with the keys translated from // frame_tree_node_id into a |site_instance|-specific routing_id. std::map<int, std::string> CreateFrameRoutingIdToContentId( SiteInstance* site_instance); // Id used to map renderer responses to jobs. // See also MHTMLGenerationManager::id_to_job_ map. int job_id_; // User-configurable parameters. Includes the file location, binary encoding // choices, and whether to skip storing resources marked // Cache-Control: no-store. MHTMLGenerationParams params_; // The IDs of frames that still need to be processed. std::queue<int> pending_frame_tree_node_ids_; // Identifies a frame to which we've sent FrameMsg_SerializeAsMHTML but for // which we didn't yet process FrameHostMsg_SerializeAsMHTMLResponse via // OnSerializeAsMHTMLResponse. int frame_tree_node_id_of_busy_frame_; // The handle to the file the MHTML is saved to for the browser process. base::File browser_file_; // Map from frames to content ids (see WebFrameSerializer::generateMHTMLParts // for more details about what "content ids" are and how they are used). std::map<int, std::string> frame_tree_node_to_content_id_; // MIME multipart boundary to use in the MHTML doc. std::string mhtml_boundary_marker_; // Digests of URIs of already generated MHTML parts. std::set<std::string> digests_of_already_serialized_uris_; std::string salt_; // The callback to call once generation is complete. const GenerateMHTMLCallback callback_; // Whether the job is finished (set to true only for the short duration of // time between MHTMLGenerationManager::JobFinished is called and the job is // destroyed by MHTMLGenerationManager::OnFileClosed). bool is_finished_; // RAII helper for registering this Job as a RenderProcessHost observer. ScopedObserver<RenderProcessHost, MHTMLGenerationManager::Job> observed_renderer_process_host_; DISALLOW_COPY_AND_ASSIGN(Job); }; MHTMLGenerationManager::Job::Job(int job_id, WebContents* web_contents, const MHTMLGenerationParams& params, const GenerateMHTMLCallback& callback) : job_id_(job_id), params_(params), frame_tree_node_id_of_busy_frame_(FrameTreeNode::kFrameTreeNodeInvalidId), mhtml_boundary_marker_(net::GenerateMimeMultipartBoundary()), salt_(base::GenerateGUID()), callback_(callback), is_finished_(false), observed_renderer_process_host_(this) { DCHECK_CURRENTLY_ON(BrowserThread::UI); web_contents->ForEachFrame(base::Bind( &MHTMLGenerationManager::Job::AddFrame, base::Unretained(this))); // Safe because ForEachFrame is synchronous. // Main frame needs to be processed first. DCHECK(!pending_frame_tree_node_ids_.empty()); DCHECK(FrameTreeNode::GloballyFindByID(pending_frame_tree_node_ids_.front()) ->parent() == nullptr); } MHTMLGenerationManager::Job::~Job() { DCHECK_CURRENTLY_ON(BrowserThread::UI); } std::map<int, std::string> MHTMLGenerationManager::Job::CreateFrameRoutingIdToContentId( SiteInstance* site_instance) { std::map<int, std::string> result; for (const auto& it : frame_tree_node_to_content_id_) { int ftn_id = it.first; const std::string& content_id = it.second; FrameTreeNode* ftn = FrameTreeNode::GloballyFindByID(ftn_id); if (!ftn) continue; int routing_id = ftn->render_manager()->GetRoutingIdForSiteInstance(site_instance); if (routing_id == MSG_ROUTING_NONE) continue; result[routing_id] = content_id; } return result; } bool MHTMLGenerationManager::Job::SendToNextRenderFrame() { DCHECK(browser_file_.IsValid()); DCHECK(!pending_frame_tree_node_ids_.empty()); FrameMsg_SerializeAsMHTML_Params ipc_params; ipc_params.job_id = job_id_; ipc_params.mhtml_boundary_marker = mhtml_boundary_marker_; ipc_params.mhtml_binary_encoding = params_.use_binary_encoding; ipc_params.mhtml_cache_control_policy = params_.cache_control_policy; int frame_tree_node_id = pending_frame_tree_node_ids_.front(); pending_frame_tree_node_ids_.pop(); ipc_params.is_last_frame = pending_frame_tree_node_ids_.empty(); FrameTreeNode* ftn = FrameTreeNode::GloballyFindByID(frame_tree_node_id); if (!ftn) // The contents went away. return false; RenderFrameHost* rfh = ftn->current_frame_host(); // Get notified if the target of the IPC message dies between responding. observed_renderer_process_host_.RemoveAll(); observed_renderer_process_host_.Add(rfh->GetProcess()); // Tell the renderer to skip (= deduplicate) already covered MHTML parts. ipc_params.salt = salt_; ipc_params.digests_of_uris_to_skip = digests_of_already_serialized_uris_; ipc_params.destination_file = IPC::GetPlatformFileForTransit( browser_file_.GetPlatformFile(), false); // |close_source_handle|. ipc_params.frame_routing_id_to_content_id = CreateFrameRoutingIdToContentId(rfh->GetSiteInstance()); // Send the IPC asking the renderer to serialize the frame. DCHECK_EQ(FrameTreeNode::kFrameTreeNodeInvalidId, frame_tree_node_id_of_busy_frame_); frame_tree_node_id_of_busy_frame_ = frame_tree_node_id; rfh->Send(new FrameMsg_SerializeAsMHTML(rfh->GetRoutingID(), ipc_params)); return true; } void MHTMLGenerationManager::Job::RenderProcessExited( RenderProcessHost* host, base::TerminationStatus status, int exit_code) { DCHECK_CURRENTLY_ON(BrowserThread::UI); MHTMLGenerationManager::GetInstance()->RenderProcessExited(this); } void MHTMLGenerationManager::Job::MarkAsFinished() { DCHECK(!is_finished_); is_finished_ = true; // Stopping RenderProcessExited notifications is needed to avoid calling // JobFinished twice. See also https://crbug.com/612098. observed_renderer_process_host_.RemoveAll(); } void MHTMLGenerationManager::Job::AddFrame(RenderFrameHost* render_frame_host) { auto* rfhi = static_cast<RenderFrameHostImpl*>(render_frame_host); int frame_tree_node_id = rfhi->frame_tree_node()->frame_tree_node_id(); pending_frame_tree_node_ids_.push(frame_tree_node_id); std::string guid = base::GenerateGUID(); std::string content_id = base::StringPrintf("<frame-%d-%s@mhtml.blink>", frame_tree_node_id, guid.c_str()); frame_tree_node_to_content_id_[frame_tree_node_id] = content_id; } void MHTMLGenerationManager::Job::RenderProcessHostDestroyed( RenderProcessHost* host) { DCHECK_CURRENTLY_ON(BrowserThread::UI); observed_renderer_process_host_.Remove(host); } void MHTMLGenerationManager::Job::CloseFile( base::Callback<void(int64_t)> callback) { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (!browser_file_.IsValid()) { callback.Run(-1); return; } BrowserThread::PostTaskAndReplyWithResult( BrowserThread::FILE, FROM_HERE, base::Bind(&MHTMLGenerationManager::Job::CloseFileOnFileThread, base::Passed(std::move(browser_file_))), callback); } bool MHTMLGenerationManager::Job::IsMessageFromFrameExpected( RenderFrameHostImpl* sender) { int sender_id = sender->frame_tree_node()->frame_tree_node_id(); if (sender_id != frame_tree_node_id_of_busy_frame_) return false; // We only expect one message per frame - let's make sure subsequent messages // from the same |sender| will be rejected. frame_tree_node_id_of_busy_frame_ = FrameTreeNode::kFrameTreeNodeInvalidId; return true; } bool MHTMLGenerationManager::Job::OnSerializeAsMHTMLResponse( const std::set<std::string>& digests_of_uris_of_serialized_resources) { // Renderer should be deduping resources with the same uris. DCHECK_EQ(0u, base::STLSetIntersection<std::set<std::string>>( digests_of_already_serialized_uris_, digests_of_uris_of_serialized_resources).size()); digests_of_already_serialized_uris_.insert( digests_of_uris_of_serialized_resources.begin(), digests_of_uris_of_serialized_resources.end()); if (pending_frame_tree_node_ids_.empty()) return true; // Report success - all frames have been processed. return SendToNextRenderFrame(); } // static int64_t MHTMLGenerationManager::Job::CloseFileOnFileThread(base::File file) { DCHECK_CURRENTLY_ON(BrowserThread::FILE); DCHECK(file.IsValid()); int64_t file_size = file.GetLength(); file.Close(); return file_size; } MHTMLGenerationManager* MHTMLGenerationManager::GetInstance() { return base::Singleton<MHTMLGenerationManager>::get(); } MHTMLGenerationManager::MHTMLGenerationManager() : next_job_id_(0) {} MHTMLGenerationManager::~MHTMLGenerationManager() { STLDeleteValues(&id_to_job_); } void MHTMLGenerationManager::SaveMHTML(WebContents* web_contents, const MHTMLGenerationParams& params, const GenerateMHTMLCallback& callback) { DCHECK_CURRENTLY_ON(BrowserThread::UI); int job_id = NewJob(web_contents, params, callback); BrowserThread::PostTaskAndReplyWithResult( BrowserThread::FILE, FROM_HERE, base::Bind(&MHTMLGenerationManager::CreateFile, params.file_path), base::Bind(&MHTMLGenerationManager::OnFileAvailable, base::Unretained(this), // Safe b/c |this| is a singleton. job_id)); } void MHTMLGenerationManager::OnSerializeAsMHTMLResponse( RenderFrameHostImpl* sender, int job_id, bool mhtml_generation_in_renderer_succeeded, const std::set<std::string>& digests_of_uris_of_serialized_resources) { DCHECK_CURRENTLY_ON(BrowserThread::UI); Job* job = FindJob(job_id); if (!job || !job->IsMessageFromFrameExpected(sender)) { NOTREACHED(); ReceivedBadMessage(sender->GetProcess(), bad_message::DWNLD_INVALID_SERIALIZE_AS_MHTML_RESPONSE); return; } if (!mhtml_generation_in_renderer_succeeded) { JobFinished(job, JobStatus::FAILURE); return; } if (!job->OnSerializeAsMHTMLResponse( digests_of_uris_of_serialized_resources)) { JobFinished(job, JobStatus::FAILURE); return; } if (job->IsDone()) JobFinished(job, JobStatus::SUCCESS); } // static base::File MHTMLGenerationManager::CreateFile(const base::FilePath& file_path) { DCHECK_CURRENTLY_ON(BrowserThread::FILE); // SECURITY NOTE: A file descriptor to the file created below will be passed // to multiple renderer processes which (in out-of-process iframes mode) can // act on behalf of separate web principals. Therefore it is important to // only allow writing to the file and forbid reading from the file (as this // would allow reading content generated by other renderers / other web // principals). uint32_t file_flags = base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE; base::File browser_file(file_path, file_flags); if (!browser_file.IsValid()) { LOG(ERROR) << "Failed to create file to save MHTML at: " << file_path.value(); } return browser_file; } void MHTMLGenerationManager::OnFileAvailable(int job_id, base::File browser_file) { DCHECK_CURRENTLY_ON(BrowserThread::UI); Job* job = FindJob(job_id); DCHECK(job); if (!browser_file.IsValid()) { LOG(ERROR) << "Failed to create file"; JobFinished(job, JobStatus::FAILURE); return; } job->set_browser_file(std::move(browser_file)); if (!job->SendToNextRenderFrame()) { JobFinished(job, JobStatus::FAILURE); } } void MHTMLGenerationManager::JobFinished(Job* job, JobStatus job_status) { DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(job); job->MarkAsFinished(); job->CloseFile( base::Bind(&MHTMLGenerationManager::OnFileClosed, base::Unretained(this), // Safe b/c |this| is a singleton. job->id(), job_status)); } void MHTMLGenerationManager::OnFileClosed(int job_id, JobStatus job_status, int64_t file_size) { DCHECK_CURRENTLY_ON(BrowserThread::UI); Job* job = FindJob(job_id); job->callback().Run(job_status == JobStatus::SUCCESS ? file_size : -1); id_to_job_.erase(job_id); delete job; } int MHTMLGenerationManager::NewJob(WebContents* web_contents, const MHTMLGenerationParams& params, const GenerateMHTMLCallback& callback) { DCHECK_CURRENTLY_ON(BrowserThread::UI); int job_id = next_job_id_++; id_to_job_[job_id] = new Job(job_id, web_contents, params, callback); return job_id; } MHTMLGenerationManager::Job* MHTMLGenerationManager::FindJob(int job_id) { DCHECK_CURRENTLY_ON(BrowserThread::UI); IDToJobMap::iterator iter = id_to_job_.find(job_id); if (iter == id_to_job_.end()) { NOTREACHED(); return nullptr; } return iter->second; } void MHTMLGenerationManager::RenderProcessExited(Job* job) { DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(job); JobFinished(job, JobStatus::FAILURE); } } // namespace content
danakj/chromium
content/browser/download/mhtml_generation_manager.cc
C++
bsd-3-clause
16,585
package com.skcraft.plume.event.block; import com.google.common.base.Functions; import com.google.common.base.Predicate; import com.skcraft.plume.event.BulkEvent; import com.skcraft.plume.event.Cause; import com.skcraft.plume.event.DelegateEvent; import com.skcraft.plume.event.Result; import com.skcraft.plume.util.Location3i; import net.minecraft.world.World; import java.util.List; import static com.google.common.base.Preconditions.checkNotNull; abstract class BlockEvent extends DelegateEvent implements BulkEvent { private final World world; protected BlockEvent(Cause cause, World world) { super(cause); checkNotNull(world, "world"); this.world = world; } /** * Get the world. * * @return The world */ public World getWorld() { return world; } /** * Get a list of affected locations. * * @return A list of affected locations */ public abstract List<Location3i> getLocations(); /** * Filter the list of affected blocks with the given predicate. If the * predicate returns {@code false}, then the block is removed. * * @param predicate the predicate * @param cancelEventOnFalse true to cancel the event and clear the block * list once the predicate returns {@code false} * @return Whether one or more blocks were filtered out */ public boolean filterLocations(Predicate<Location3i> predicate, boolean cancelEventOnFalse) { return filter(getLocations(), Functions.<Location3i>identity(), predicate, cancelEventOnFalse); } @Override public Result getResult() { if (getLocations().isEmpty()) { return Result.DENY; } return super.getResult(); } @Override public Result getExplicitResult() { return super.getResult(); } }
wizjany/Plume
src/main/java/com/skcraft/plume/event/block/BlockEvent.java
Java
bsd-3-clause
1,892
class Blog < ActiveRecord::Base has_many :posts has_many :comments, :through => :posts attr_accessible :name, :subdomain searchable :include => { :posts => :author } do string :subdomain text :name end # Make sure that includes are added to with multiple searchable calls searchable(:include => :comments) {} end
hafeild/alice
vendor/bundle/ruby/2.3.0/gems/sunspot_rails-2.3.0/spec/rails_app/app/models/blog.rb
Ruby
bsd-3-clause
338
<!doctype html> <html> <title>shrinkwrap</title> <meta http-equiv="content-type" value="text/html;utf-8"> <link rel="stylesheet" type="text/css" href="../static/style.css"> <body> <div id="wrapper"> <h1><a href="../doc/shrinkwrap.html">shrinkwrap</a></h1> <p>Lock down dependency versions</p> <h2 id="SYNOPSIS">SYNOPSIS</h2> <pre><code>npm shrinkwrap</code></pre> <h2 id="DESCRIPTION">DESCRIPTION</h2> <p>This command locks down the versions of a package&#39;s dependencies so that you can control exactly which versions of each dependency will be used when your package is installed.</p> <p>By default, &quot;npm install&quot; recursively installs the target&#39;s dependencies (as specified in package.json), choosing the latest available version that satisfies the dependency&#39;s semver pattern. In some situations, particularly when shipping software where each change is tightly managed, it&#39;s desirable to fully specify each version of each dependency recursively so that subsequent builds and deploys do not inadvertently pick up newer versions of a dependency that satisfy the semver pattern. Specifying specific semver patterns in each dependency&#39;s package.json would facilitate this, but that&#39;s not always possible or desirable, as when another author owns the npm package. It&#39;s also possible to check dependencies directly into source control, but that may be undesirable for other reasons.</p> <p>As an example, consider package A:</p> <pre><code>{ &quot;name&quot;: &quot;A&quot;, &quot;version&quot;: &quot;0.1.0&quot;, &quot;dependencies&quot;: { &quot;B&quot;: &quot;&lt;0.1.0&quot; } }</code></pre> <p>package B:</p> <pre><code>{ &quot;name&quot;: &quot;B&quot;, &quot;version&quot;: &quot;0.0.1&quot;, &quot;dependencies&quot;: { &quot;C&quot;: &quot;&lt;0.1.0&quot; } }</code></pre> <p>and package C:</p> <pre><code>{ &quot;name&quot;: &quot;C, &quot;version&quot;: &quot;0.0.1&quot; }</code></pre> <p>If these are the only versions of A, B, and C available in the registry, then a normal &quot;npm install A&quot; will install:</p> <pre><code>A@0.1.0 `-- B@0.0.1 `-- C@0.0.1</code></pre> <p>However, if B@0.0.2 is published, then a fresh &quot;npm install A&quot; will install:</p> <pre><code>A@0.1.0 `-- B@0.0.2 `-- C@0.0.1</code></pre> <p>assuming the new version did not modify B&#39;s dependencies. Of course, the new version of B could include a new version of C and any number of new dependencies. If such changes are undesirable, the author of A could specify a dependency on B@0.0.1. However, if A&#39;s author and B&#39;s author are not the same person, there&#39;s no way for A&#39;s author to say that he or she does not want to pull in newly published versions of C when B hasn&#39;t changed at all.</p> <p>In this case, A&#39;s author can run</p> <pre><code>npm shrinkwrap</code></pre> <p>This generates npm-shrinkwrap.json, which will look something like this:</p> <pre><code>{ &quot;name&quot;: &quot;A&quot;, &quot;version&quot;: &quot;0.1.0&quot;, &quot;dependencies&quot;: { &quot;B&quot;: { &quot;version&quot;: &quot;0.0.1&quot;, &quot;dependencies&quot;: { &quot;C&quot;: { &quot;version&quot;: &quot;0.1.0&quot; } } } } }</code></pre> <p>The shrinkwrap command has locked down the dependencies based on what&#39;s currently installed in node_modules. When &quot;npm install&quot; installs a package with a npm-shrinkwrap.json file in the package root, the shrinkwrap file (rather than package.json files) completely drives the installation of that package and all of its dependencies (recursively). So now the author publishes A@0.1.0, and subsequent installs of this package will use B@0.0.1 and C@0.1.0, regardless the dependencies and versions listed in A&#39;s, B&#39;s, and C&#39;s package.json files.</p> <h3 id="Using-shrinkwrapped-packages">Using shrinkwrapped packages</h3> <p>Using a shrinkwrapped package is no different than using any other package: you can &quot;npm install&quot; it by hand, or add a dependency to your package.json file and &quot;npm install&quot; it.</p> <h3 id="Building-shrinkwrapped-packages">Building shrinkwrapped packages</h3> <p>To shrinkwrap an existing package:</p> <ol><li>Run &quot;npm install&quot; in the package root to install the current versions of all dependencies.</li><li>Validate that the package works as expected with these versions.</li><li>Run &quot;npm shrinkwrap&quot;, add npm-shrinkwrap.json to git, and publish your package.</li></ol> <p>To add or update a dependency in a shrinkwrapped package:</p> <ol><li>Run &quot;npm install&quot; in the package root to install the current versions of all dependencies.</li><li>Add or update dependencies. &quot;npm install&quot; each new or updated package individually and then update package.json. Note that they must be explicitly named in order to be installed: running <code>npm install</code> with no arguments will merely reproduce the existing shrinkwrap.</li><li>Validate that the package works as expected with the new dependencies.</li><li>Run &quot;npm shrinkwrap&quot;, commit the new npm-shrinkwrap.json, and publish your package.</li></ol> <p>You can use <a href="../doc/outdated.html">outdated(1)</a> to view dependencies with newer versions available.</p> <h3 id="Other-Notes">Other Notes</h3> <p>Since &quot;npm shrinkwrap&quot; uses the locally installed packages to construct the shrinkwrap file, devDependencies will be included if and only if you&#39;ve installed them already when you make the shrinkwrap.</p> <p>A shrinkwrap file must be consistent with the package&#39;s package.json file. &quot;npm shrinkwrap&quot; will fail if required dependencies are not already installed, since that would result in a shrinkwrap that wouldn&#39;t actually work. Similarly, the command will fail if there are extraneous packages (not referenced by package.json), since that would indicate that package.json is not correct.</p> <p>If shrinkwrapped package A depends on shrinkwrapped package B, B&#39;s shrinkwrap will not be used as part of the installation of A. However, because A&#39;s shrinkwrap is constructed from a valid installation of B and recursively specifies all dependencies, the contents of B&#39;s shrinkwrap will implicitly be included in A&#39;s shrinkwrap.</p> <h3 id="Caveats">Caveats</h3> <p>Shrinkwrap files only lock down package versions, not actual package contents. While discouraged, a package author can republish an existing version of a package, causing shrinkwrapped packages using that version to pick up different code than they were before. If you want to avoid any risk that a byzantine author replaces a package you&#39;re using with code that breaks your application, you could modify the shrinkwrap file to use git URL references rather than version numbers so that npm always fetches all packages from git.</p> <p>If you wish to lock down the specific bytes included in a package, for example to have 100% confidence in being able to reproduce a deployment or build, then you ought to check your dependencies into source control, or pursue some other mechanism that can verify contents rather than versions.</p> <h2 id="SEE-ALSO">SEE ALSO</h2> <ul><li><a href="../doc/install.html">install(1)</a></li><li><a href="../doc/json.html">json(1)</a></li><li><a href="../doc/list.html">list(1)</a></li></ul> </div> <p id="footer">shrinkwrap &mdash; npm@1.2.14</p> <script> ;(function () { var wrapper = document.getElementById("wrapper") var els = Array.prototype.slice.call(wrapper.getElementsByTagName("*"), 0) .filter(function (el) { return el.parentNode === wrapper && el.tagName.match(/H[1-6]/) && el.id }) var l = 2 , toc = document.createElement("ul") toc.innerHTML = els.map(function (el) { var i = el.tagName.charAt(1) , out = "" while (i > l) { out += "<ul>" l ++ } while (i < l) { out += "</ul>" l -- } out += "<li><a href='#" + el.id + "'>" + ( el.innerText || el.text || el.innerHTML) + "</a>" return out }).join("\n") toc.id = "toc" document.body.appendChild(toc) })() </script> </body></html>
exhibia/exhibia
include/addons/design_suite/js/html2image/node-v0.10.0-linux-x64/lib/node_modules/npm/html/doc/shrinkwrap.html
HTML
bsd-3-clause
8,261
from __future__ import unicode_literals __all__ = ( 'Key', 'Keys', ) class Key(object): def __init__(self, name): #: Descriptive way of writing keys in configuration files. e.g. <C-A> #: for ``Control-A``. self.name = name def __repr__(self): return '%s(%r)' % (self.__class__.__name__, self.name) class Keys(object): Escape = Key('<Escape>') ControlA = Key('<C-A>') ControlB = Key('<C-B>') ControlC = Key('<C-C>') ControlD = Key('<C-D>') ControlE = Key('<C-E>') ControlF = Key('<C-F>') ControlG = Key('<C-G>') ControlH = Key('<C-H>') ControlI = Key('<C-I>') # Tab ControlJ = Key('<C-J>') # Enter ControlK = Key('<C-K>') ControlL = Key('<C-L>') ControlM = Key('<C-M>') # Enter ControlN = Key('<C-N>') ControlO = Key('<C-O>') ControlP = Key('<C-P>') ControlQ = Key('<C-Q>') ControlR = Key('<C-R>') ControlS = Key('<C-S>') ControlT = Key('<C-T>') ControlU = Key('<C-U>') ControlV = Key('<C-V>') ControlW = Key('<C-W>') ControlX = Key('<C-X>') ControlY = Key('<C-Y>') ControlZ = Key('<C-Z>') ControlSpace = Key('<C-Space>') ControlBackslash = Key('<C-Backslash>') ControlSquareClose = Key('<C-SquareClose>') ControlCircumflex = Key('<C-Circumflex>') ControlUnderscore = Key('<C-Underscore>') ControlLeft = Key('<C-Left>') ControlRight = Key('<C-Right>') ControlUp = Key('<C-Up>') ControlDown = Key('<C-Down>') Up = Key('<Up>') Down = Key('<Down>') Right = Key('<Right>') Left = Key('<Left>') Home = Key('<Home>') End = Key('<End>') Delete = Key('<Delete>') ShiftDelete = Key('<ShiftDelete>') PageUp = Key('<PageUp>') PageDown = Key('<PageDown>') BackTab = Key('<BackTab>') # shift + tab Tab = ControlI Backspace = ControlH F1 = Key('<F1>') F2 = Key('<F2>') F3 = Key('<F3>') F4 = Key('<F4>') F5 = Key('<F5>') F6 = Key('<F6>') F7 = Key('<F7>') F8 = Key('<F8>') F9 = Key('<F9>') F10 = Key('<F10>') F11 = Key('<F11>') F12 = Key('<F12>') F13 = Key('<F13>') F14 = Key('<F14>') F15 = Key('<F15>') F16 = Key('<F16>') F17 = Key('<F17>') F18 = Key('<F18>') F19 = Key('<F19>') F20 = Key('<F20>') # Matches any key. Any = Key('<Any>') # Special CPRResponse = Key('<Cursor-Position-Response>')
jaseg/python-prompt-toolkit
prompt_toolkit/keys.py
Python
bsd-3-clause
2,546
/* * Copyright (c) 2004-2022, University of Oslo * 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 HISP project 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 org.hisp.dhis.expression; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import org.hisp.dhis.analytics.DataType; import org.hisp.dhis.common.DimensionalItemId; import org.hisp.dhis.common.DimensionalItemObject; import org.hisp.dhis.constant.Constant; import org.hisp.dhis.dataelement.DataElement; import org.hisp.dhis.indicator.Indicator; import org.hisp.dhis.indicator.IndicatorValue; import org.hisp.dhis.organisationunit.OrganisationUnitGroup; import org.hisp.dhis.period.Period; /** * Expressions are mathematical formulas and can contain references to various * elements. * * @author Margrethe Store * @author Lars Helge Overland * @author Jim Grace */ public interface ExpressionService { String ID = ExpressionService.class.getName(); String DAYS_DESCRIPTION = "[Number of days]"; String SYMBOL_DAYS = "[days]"; String SYMBOL_WILDCARD = "*"; String UID_EXPRESSION = "[a-zA-Z]\\w{10}"; String INT_EXPRESSION = "^(0|-?[1-9]\\d*)$"; // ------------------------------------------------------------------------- // Expression CRUD operations // ------------------------------------------------------------------------- /** * Adds a new Expression to the database. * * @param expression The Expression to add. * @return The generated identifier for this Expression. */ long addExpression( Expression expression ); /** * Updates an Expression. * * @param expression The Expression to update. */ void updateExpression( Expression expression ); /** * Deletes an Expression from the database. * * @param expression the expression. */ void deleteExpression( Expression expression ); /** * Get the Expression with the given identifier. * * @param id The identifier. * @return an Expression with the given identifier. */ Expression getExpression( long id ); /** * Gets all Expressions. * * @return A list with all Expressions. */ List<Expression> getAllExpressions(); // ------------------------------------------------------------------------- // Indicator expression logic // ------------------------------------------------------------------------- /** * Returns all dimensional item objects which are present in numerator and * denominator of the given indicators, as a map from id to object. * * @param indicators the collection of indicators. * @return a map from dimensional item id to object. */ Map<DimensionalItemId, DimensionalItemObject> getIndicatorDimensionalItemMap( Collection<Indicator> indicators ); /** * Returns all OrganisationUnitGroups in the numerator and denominator * expressions in the given Indicators. Returns an empty set if the given * indicators are null or empty. * * @param indicators the set of indicators. * @return a Set of OrganisationUnitGroups. */ List<OrganisationUnitGroup> getOrgUnitGroupCountGroups( Collection<Indicator> indicators ); /** * Generates the calculated value for the given parameters based on the * values in the given maps. * * @param indicator the indicator for which to calculate the value. * @param periods a List of periods for which to calculate the value. * @param itemMap map of dimensional item id to object in expression. * @param valueMap the map of data values. * @param orgUnitCountMap the map of organisation unit group member counts. * @return the calculated value as a double. */ IndicatorValue getIndicatorValueObject( Indicator indicator, List<Period> periods, Map<DimensionalItemId, DimensionalItemObject> itemMap, Map<DimensionalItemObject, Object> valueMap, Map<String, Integer> orgUnitCountMap ); /** * Substitutes any constants and org unit group member counts in the * numerator and denominator on all indicators in the given collection. * * @param indicators the set of indicators. */ void substituteIndicatorExpressions( Collection<Indicator> indicators ); // ------------------------------------------------------------------------- // Get information about the expression // ------------------------------------------------------------------------- /** * Tests whether the expression is valid. * * @param expression the expression string. * @param parseType the type of expression to parse. * @return the ExpressionValidationOutcome of the validation. */ ExpressionValidationOutcome expressionIsValid( String expression, ParseType parseType ); /** * Creates an expression description containing the names of the * DimensionalItemObjects from a numeric valued expression. * * @param expression the expression string. * @param parseType the type of expression to parse. * @return An description containing DimensionalItemObjects names. */ String getExpressionDescription( String expression, ParseType parseType ); /** * Creates an expression description containing the names of the * DimensionalItemObjects from an expression string, for an expression that * will return the specified data type. * * @param expression the expression string. * @param parseType the type of expression to parse. * @param dataType the data type for the expression to return. * @return An description containing DimensionalItemObjects names. */ String getExpressionDescription( String expression, ParseType parseType, DataType dataType ); /** * Gets information we need from an expression string. * * @param params the expression parameters. * @return the expression information. */ ExpressionInfo getExpressionInfo( ExpressionParams params ); /** * From expression info, create a "base" expression parameters object with * certain metadata fields supplied that are needed for later evaluation. * <p> * Before evaluation, the caller will need to add to this "base" object * fields such as expression, parseType, dataType, valueMap, etc. * * @param info the expression information. * @return the expression parameters with metadata pre-filled. */ ExpressionParams getBaseExpressionParams( ExpressionInfo info ); /** * Returns UIDs of Data Elements and associated Option Combos (if any) found * in the Data Element Operands an expression. * <p/> * If the Data Element Operand consists of just a Data Element, or if the * Option Combo is a wildcard "*", returns just dataElementUID. * <p/> * If an Option Combo is present, returns dataElementUID.optionComboUID. * * @param expression the expression string. * @param parseType the type of expression to parse. * @return a Set of data element identifiers. */ Set<String> getExpressionElementAndOptionComboIds( String expression, ParseType parseType ); /** * Returns all data elements found in the given expression string, including * those found in data element operands. Returns an empty set if the given * expression is null. * * @param expression the expression string. * @param parseType the type of expression to parse. * @return a Set of data elements included in the expression string. */ Set<DataElement> getExpressionDataElements( String expression, ParseType parseType ); /** * Returns all CategoryOptionCombo uids in the given expression string that * are used as a data element operand categoryOptionCombo or * attributeOptionCombo. Returns an empty set if the expression is null. * * @param expression the expression string. * @param parseType the type of expression to parse. * @return a Set of CategoryOptionCombo uids in the expression string. */ Set<String> getExpressionOptionComboIds( String expression, ParseType parseType ); /** * Returns all dimensional item object ids in the given expression. * * @param expression the expression string. * @param parseType the type of expression to parse. * @return a Set of dimensional item object ids. */ Set<DimensionalItemId> getExpressionDimensionalItemIds( String expression, ParseType parseType ); /** * Returns set of all OrganisationUnitGroup UIDs in the given expression. * * @param expression the expression string. * @param parseType the type of expression to parse. * @return Map of UIDs to OrganisationUnitGroups in the expression string. */ Set<String> getExpressionOrgUnitGroupIds( String expression, ParseType parseType ); // ------------------------------------------------------------------------- // Compute the value of the expression // ------------------------------------------------------------------------- /** * Generates the calculated value for an expression. * * @param params the expression parameters. * @return the calculated value. */ Object getExpressionValue( ExpressionParams params ); // ------------------------------------------------------------------------- // Gets a (possibly cached) constant map // ------------------------------------------------------------------------- /** * Gets the (possibly cached) constant map. * * @return the constant map. */ Map<String, Constant> getConstantMap(); }
hispindia/dhis2-Core
dhis-2/dhis-api/src/main/java/org/hisp/dhis/expression/ExpressionService.java
Java
bsd-3-clause
11,199
#!/usr/bin/env python """ ================ sMRI: FreeSurfer ================ This script, smri_freesurfer.py, demonstrates the ability to call reconall on a set of subjects and then make an average subject. python smri_freesurfer.py Import necessary modules from nipype. """ import os import nipype.pipeline.engine as pe import nipype.interfaces.io as nio from nipype.interfaces.freesurfer.preprocess import ReconAll from nipype.interfaces.freesurfer.utils import MakeAverageSubject subject_list = ['s1', 's3'] data_dir = os.path.abspath('data') subjects_dir = os.path.abspath('amri_freesurfer_tutorial/subjects_dir') wf = pe.Workflow(name="l1workflow") wf.base_dir = os.path.abspath('amri_freesurfer_tutorial/workdir') """ Grab data """ datasource = pe.MapNode(interface=nio.DataGrabber(infields=['subject_id'], outfields=['struct']), name='datasource', iterfield=['subject_id']) datasource.inputs.base_directory = data_dir datasource.inputs.template = '%s/%s.nii' datasource.inputs.template_args = dict(struct=[['subject_id', 'struct']]) datasource.inputs.subject_id = subject_list """ Run recon-all """ recon_all = pe.MapNode(interface=ReconAll(), name='recon_all', iterfield=['subject_id', 'T1_files']) recon_all.inputs.subject_id = subject_list if not os.path.exists(subjects_dir): os.mkdir(subjects_dir) recon_all.inputs.subjects_dir = subjects_dir wf.connect(datasource, 'struct', recon_all, 'T1_files') """ Make average subject """ average = pe.Node(interface=MakeAverageSubject(), name="average") average.inputs.subjects_dir = subjects_dir wf.connect(recon_all, 'subject_id', average, 'subjects_ids') wf.run("MultiProc", plugin_args={'n_procs': 4})
FredLoney/nipype
examples/smri_freesurfer.py
Python
bsd-3-clause
1,804
{% extends "email/_notification.html" %} {% set replied_comment = notification.comment.parent_comment %} {% set replied_content = notification.comment.parent_comment.reply_content %} {% block headline %} <span><strong>Your thread</strong> received a <strong>reply</strong> from {% endblock %} {% block email_type %}thread reply notifications{% endblock %}
canvasnetworks/canvas
website/templates/email/thread_replied.html
HTML
bsd-3-clause
359
/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkUSNavigationProcessWidget.h" #include "ui_QmitkUSNavigationProcessWidget.h" #include "../NavigationStepWidgets/QmitkUSAbstractNavigationStep.h" #include "../SettingsWidgets/QmitkUSNavigationAbstractSettingsWidget.h" #include "mitkDataNode.h" #include "mitkNavigationDataToNavigationDataFilter.h" #include <QTimer> #include <QSignalMapper> #include <QShortcut> QmitkUSNavigationProcessWidget::QmitkUSNavigationProcessWidget(QWidget* parent) : QWidget(parent), m_SettingsWidget(0), m_BaseNode(mitk::DataNode::New()), m_CurrentTabIndex(0), m_CurrentMaxStep(0), m_ImageAlreadySetToNode(false), m_ReadySignalMapper(new QSignalMapper(this)), m_NoLongerReadySignalMapper(new QSignalMapper(this)), m_StdMultiWidget(0), m_UsePlanningStepWidget(false), ui(new Ui::QmitkUSNavigationProcessWidget) { m_Parent = parent; ui->setupUi(this); // remove the default page ui->stepsToolBox->removeItem(0); //set shortcuts QShortcut *nextShortcut = new QShortcut(QKeySequence("F10"), parent); QShortcut *prevShortcut = new QShortcut(QKeySequence("F11"), parent); connect(nextShortcut, SIGNAL(activated()), this, SLOT(OnNextButtonClicked())); connect(prevShortcut, SIGNAL(activated()), this, SLOT(OnPreviousButtonClicked())); //connect other slots connect( ui->restartStepButton, SIGNAL(clicked()), this, SLOT(OnRestartStepButtonClicked()) ); connect( ui->previousButton, SIGNAL(clicked()), this, SLOT(OnPreviousButtonClicked()) ); connect( ui->nextButton, SIGNAL(clicked()), this, SLOT(OnNextButtonClicked()) ); connect( ui->stepsToolBox, SIGNAL(currentChanged(int)), this, SLOT(OnTabChanged(int)) ); connect (ui->settingsButton, SIGNAL(clicked()), this, SLOT(OnSettingsButtonClicked()) ); connect( m_ReadySignalMapper, SIGNAL(mapped(int)), this, SLOT(OnStepReady(int)) ); connect( m_NoLongerReadySignalMapper, SIGNAL(mapped(int)), this, SLOT(OnStepNoLongerReady(int)) ); ui->settingsFrameWidget->setHidden(true); } QmitkUSNavigationProcessWidget::~QmitkUSNavigationProcessWidget() { ui->stepsToolBox->blockSignals(true); for ( NavigationStepVector::iterator it = m_NavigationSteps.begin(); it != m_NavigationSteps.end(); ++it ) { if ( (*it)->GetNavigationStepState() > QmitkUSAbstractNavigationStep::State_Stopped ) { (*it)->StopStep(); } delete *it; } m_NavigationSteps.clear(); if ( m_SettingsNode.IsNotNull() && m_DataStorage.IsNotNull() ) { m_DataStorage->Remove(m_SettingsNode); } delete ui; } void QmitkUSNavigationProcessWidget::EnableInteraction(bool enable) { if (enable) { ui->restartStepButton->setEnabled(true); ui->previousButton->setEnabled(true); ui->nextButton->setEnabled(true); ui->stepsToolBox->setEnabled(true); } else { ui->restartStepButton->setEnabled(false); ui->previousButton->setEnabled(false); ui->nextButton->setEnabled(false); ui->stepsToolBox->setEnabled(false); } } void QmitkUSNavigationProcessWidget::SetDataStorage(itk::SmartPointer<mitk::DataStorage> dataStorage) { m_DataStorage = dataStorage; if ( dataStorage.IsNull() ) { mitkThrow() << "Data Storage must not be null for QmitkUSNavigationProcessWidget."; } // test if base node is already in the data storage and add it if not m_BaseNode = dataStorage->GetNamedNode(QmitkUSAbstractNavigationStep::DATANAME_BASENODE); if ( m_BaseNode.IsNull() ) { m_BaseNode = mitk::DataNode::New(); m_BaseNode->SetName(QmitkUSAbstractNavigationStep::DATANAME_BASENODE); dataStorage->Add(m_BaseNode); } // base node and image stream node may be the same node if ( strcmp(QmitkUSAbstractNavigationStep::DATANAME_BASENODE, QmitkUSAbstractNavigationStep::DATANAME_IMAGESTREAM) != 0) { m_ImageStreamNode = dataStorage->GetNamedNode(QmitkUSAbstractNavigationStep::DATANAME_IMAGESTREAM); if (m_ImageStreamNode.IsNull()) { // Create Node for US Stream m_ImageStreamNode = mitk::DataNode::New(); m_ImageStreamNode->SetName(QmitkUSAbstractNavigationStep::DATANAME_IMAGESTREAM); dataStorage->Add(m_ImageStreamNode); } } else { m_ImageStreamNode = m_BaseNode; } m_SettingsNode = dataStorage->GetNamedDerivedNode(QmitkUSAbstractNavigationStep::DATANAME_SETTINGS, m_BaseNode); if ( m_SettingsNode.IsNull() ) { m_SettingsNode = mitk::DataNode::New(); m_SettingsNode->SetName(QmitkUSAbstractNavigationStep::DATANAME_SETTINGS); dataStorage->Add(m_SettingsNode, m_BaseNode); } if (m_SettingsWidget) { m_SettingsWidget->SetSettingsNode(m_SettingsNode); } } void QmitkUSNavigationProcessWidget::SetSettingsWidget(QmitkUSNavigationAbstractSettingsWidget* settingsWidget) { // disconnect slots to settings widget if there was a widget before if ( m_SettingsWidget ) { disconnect( ui->settingsSaveButton, SIGNAL(clicked()), m_SettingsWidget, SLOT(OnSave()) ); disconnect( ui->settingsCancelButton, SIGNAL(clicked()), m_SettingsWidget, SLOT(OnCancel()) ); disconnect (m_SettingsWidget, SIGNAL(Saved()), this, SLOT(OnSettingsWidgetReturned()) ); disconnect (m_SettingsWidget, SIGNAL(Canceled()), this, SLOT(OnSettingsWidgetReturned()) ); disconnect (m_SettingsWidget, SIGNAL(SettingsChanged(itk::SmartPointer<mitk::DataNode>)), this, SLOT(OnSettingsChanged(itk::SmartPointer<mitk::DataNode>)) ); ui->settingsWidget->removeWidget(m_SettingsWidget); } m_SettingsWidget = settingsWidget; if ( m_SettingsWidget ) { m_SettingsWidget->LoadSettings(); connect( ui->settingsSaveButton, SIGNAL(clicked()), m_SettingsWidget, SLOT(OnSave()) ); connect( ui->settingsCancelButton, SIGNAL(clicked()), m_SettingsWidget, SLOT(OnCancel()) ); connect (m_SettingsWidget, SIGNAL(Saved()), this, SLOT(OnSettingsWidgetReturned()) ); connect (m_SettingsWidget, SIGNAL(Canceled()), this, SLOT(OnSettingsWidgetReturned()) ); connect (m_SettingsWidget, SIGNAL(SettingsChanged(itk::SmartPointer<mitk::DataNode>)), this, SLOT(OnSettingsChanged(itk::SmartPointer<mitk::DataNode>)) ); if ( m_SettingsNode.IsNotNull() ) { m_SettingsWidget->SetSettingsNode(m_SettingsNode, true); } ui->settingsWidget->addWidget(m_SettingsWidget); } ui->settingsButton->setEnabled(m_SettingsWidget != 0); } void QmitkUSNavigationProcessWidget::SetNavigationSteps(NavigationStepVector navigationSteps) { disconnect( this, SLOT(OnTabChanged(int)) ); for ( int n = ui->stepsToolBox->count()-1; n >= 0; --n ) { ui->stepsToolBox->removeItem(n); } connect( ui->stepsToolBox, SIGNAL(currentChanged(int)), this, SLOT(OnTabChanged(int)) ); m_NavigationSteps.clear(); m_NavigationSteps = navigationSteps; this->InitializeNavigationStepWidgets(); // notify all navigation step widgets about the current settings for (NavigationStepIterator it = m_NavigationSteps.begin(); it != m_NavigationSteps.end(); ++it) { (*it)->OnSettingsChanged(m_SettingsNode); } } void QmitkUSNavigationProcessWidget::ResetNavigationProcess() { MITK_INFO("QmitkUSNavigationProcessWidget") << "Resetting navigation process."; ui->stepsToolBox->blockSignals(true); for ( int n = 0; n <= m_CurrentMaxStep; ++n ) { m_NavigationSteps.at(n)->StopStep(); if ( n > 0 ) { ui->stepsToolBox->setItemEnabled(n, false); } } ui->stepsToolBox->blockSignals(false); m_CurrentMaxStep = 0; ui->stepsToolBox->setCurrentIndex(0); if ( m_NavigationSteps.size() > 0 ) { m_NavigationSteps.at(0)->ActivateStep(); } this->UpdatePrevNextButtons(); } void QmitkUSNavigationProcessWidget::UpdateNavigationProgress() { if ( m_CombinedModality.IsNotNull() && !m_CombinedModality->GetIsFreezed() ) { m_CombinedModality->Modified(); m_CombinedModality->Update(); if ( m_LastNavigationDataFilter.IsNotNull() ) { m_LastNavigationDataFilter->Update(); } mitk::Image::Pointer image = m_CombinedModality->GetOutput(); // make sure that always the current image is set to the data node if ( image.IsNotNull() && m_ImageStreamNode->GetData() != image.GetPointer() && image->IsInitialized() ) { m_ImageStreamNode->SetData(image); m_ImageAlreadySetToNode = true; } } if ( m_CurrentTabIndex > 0 && static_cast<unsigned int>(m_CurrentTabIndex) < m_NavigationSteps.size() ) { m_NavigationSteps.at(m_CurrentTabIndex)->Update(); } } void QmitkUSNavigationProcessWidget::OnNextButtonClicked() { if (m_CombinedModality.IsNotNull() && m_CombinedModality->GetIsFreezed()) {return;} //no moving through steps when the modality is NULL or frozen int currentIndex = ui->stepsToolBox->currentIndex(); if (currentIndex >= m_CurrentMaxStep) { MITK_WARN << "Next button clicked though no next tab widget is available."; return; } ui->stepsToolBox->setCurrentIndex(++currentIndex); this->UpdatePrevNextButtons(); } void QmitkUSNavigationProcessWidget::OnPreviousButtonClicked() { if (m_CombinedModality.IsNotNull() && m_CombinedModality->GetIsFreezed()) {return;} //no moving through steps when the modality is NULL or frozen int currentIndex = ui->stepsToolBox->currentIndex(); if (currentIndex <= 0) { MITK_WARN << "Previous button clicked though no previous tab widget is available."; return; } ui->stepsToolBox->setCurrentIndex(--currentIndex); this->UpdatePrevNextButtons(); } void QmitkUSNavigationProcessWidget::OnRestartStepButtonClicked() { MITK_INFO("QmitkUSNavigationProcessWidget") << "Restarting step " << m_CurrentTabIndex << " (" << m_NavigationSteps.at(m_CurrentTabIndex)->GetTitle().toStdString() << ")."; m_NavigationSteps.at(ui->stepsToolBox->currentIndex())->RestartStep(); m_NavigationSteps.at(ui->stepsToolBox->currentIndex())->ActivateStep(); } void QmitkUSNavigationProcessWidget::OnTabChanged(int index) { if ( index < 0 || index >= static_cast<int>(m_NavigationSteps.size()) ) { return; } else if ( m_CurrentTabIndex == index ) { // just activate the step if it is the same step againg m_NavigationSteps.at(index)->ActivateStep(); return; } MITK_INFO("QmitkUSNavigationProcessWidget") << "Activating navigation step " << index << " (" << m_NavigationSteps.at(index)->GetTitle().toStdString() <<")."; if (index > m_CurrentTabIndex) { this->UpdateFilterPipeline(); // finish all previous steps to make sure that all data is valid for (int n = m_CurrentTabIndex; n < index; ++n) { m_NavigationSteps.at(n)->FinishStep(); } } // deactivate the previously active step if ( m_CurrentTabIndex > 0 && m_NavigationSteps.size() > static_cast<unsigned int>(m_CurrentTabIndex) ) { m_NavigationSteps.at(m_CurrentTabIndex)->DeactivateStep(); } // start step of the current tab if it wasn't started before if ( m_NavigationSteps.at(index)->GetNavigationStepState() == QmitkUSAbstractNavigationStep::State_Stopped ) { m_NavigationSteps.at(index)->StartStep(); } m_NavigationSteps.at(index)->ActivateStep(); if (static_cast<unsigned int>(index) < m_NavigationSteps.size()) ui->restartStepButton->setEnabled(m_NavigationSteps.at(index)->GetIsRestartable()); this->UpdatePrevNextButtons(); m_CurrentTabIndex = index; emit SignalActiveNavigationStepChanged(index); } void QmitkUSNavigationProcessWidget::OnSettingsButtonClicked() { this->SetSettingsWidgetVisible(true); } void QmitkUSNavigationProcessWidget::OnSettingsWidgetReturned() { this->SetSettingsWidgetVisible(false); } void QmitkUSNavigationProcessWidget::OnSettingsNodeChanged(itk::SmartPointer<mitk::DataNode> dataNode) { if ( m_SettingsWidget ) m_SettingsWidget->SetSettingsNode(dataNode); } void QmitkUSNavigationProcessWidget::OnStepReady(int index) { if (m_CurrentMaxStep <= index) { m_CurrentMaxStep = index + 1; this->UpdatePrevNextButtons(); for (int n = 0; n <= m_CurrentMaxStep; ++n) { ui->stepsToolBox->setItemEnabled(n, true); } } emit SignalNavigationStepFinished(index, true); } void QmitkUSNavigationProcessWidget::OnStepNoLongerReady(int index) { if (m_CurrentMaxStep > index) { m_CurrentMaxStep = index; this->UpdatePrevNextButtons(); this->UpdateFilterPipeline(); for (int n = m_CurrentMaxStep+1; n < ui->stepsToolBox->count(); ++n) { ui->stepsToolBox->setItemEnabled(n, false); m_NavigationSteps.at(n)->StopStep(); } } emit SignalNavigationStepFinished(index, false); } void QmitkUSNavigationProcessWidget::OnCombinedModalityChanged(itk::SmartPointer<mitk::USCombinedModality> combinedModality) { m_CombinedModality = combinedModality; m_ImageAlreadySetToNode = false; if ( combinedModality.IsNotNull() ) { if ( combinedModality->GetNavigationDataSource().IsNull() ) { MITK_WARN << "There is no navigation data source set for the given combined modality."; return; } this->UpdateFilterPipeline(); } for (NavigationStepIterator it = m_NavigationSteps.begin(); it != m_NavigationSteps.end(); ++it) { (*it)->SetCombinedModality(combinedModality); } emit SignalCombinedModalityChanged(combinedModality); } void QmitkUSNavigationProcessWidget::OnSettingsChanged(const mitk::DataNode::Pointer dataNode) { static bool methodEntered = false; if ( methodEntered ) { MITK_WARN("QmitkUSNavigationProcessWidget") << "Ignoring recursive call to 'OnSettingsChanged()'. " << "Make sure to no emit 'SignalSettingsNodeChanged' in an 'OnSettingsChanged()' method."; return; } methodEntered = true; std::string application; if ( dataNode->GetStringProperty("settings.application", application) ) { QString applicationQString = QString::fromStdString(application); if ( applicationQString != ui->titleLabel->text() ) { ui->titleLabel->setText(applicationQString); } } // notify all navigation step widgets about the changed settings for (NavigationStepIterator it = m_NavigationSteps.begin(); it != m_NavigationSteps.end(); ++it) { (*it)->OnSettingsChanged(dataNode); } emit SignalSettingsChanged(dataNode); methodEntered = false; } void QmitkUSNavigationProcessWidget::InitializeNavigationStepWidgets() { // do not listen for steps tool box signal during insertion of items into tool box disconnect( ui->stepsToolBox, SIGNAL(currentChanged(int)), this, SLOT(OnTabChanged(int)) ); m_CurrentMaxStep = 0; mitk::DataStorage::Pointer dataStorage = m_DataStorage; for (unsigned int n = 0; n < m_NavigationSteps.size(); ++n) { QmitkUSAbstractNavigationStep* curNavigationStep = m_NavigationSteps.at(n); curNavigationStep->SetDataStorage(dataStorage); connect( curNavigationStep, SIGNAL(SignalReadyForNextStep()), m_ReadySignalMapper, SLOT(map())); connect( curNavigationStep, SIGNAL(SignalNoLongerReadyForNextStep()), m_NoLongerReadySignalMapper, SLOT(map()) ); connect( curNavigationStep, SIGNAL(SignalCombinedModalityChanged(itk::SmartPointer<mitk::USCombinedModality>)), this, SLOT(OnCombinedModalityChanged(itk::SmartPointer<mitk::USCombinedModality>)) ); connect( curNavigationStep, SIGNAL(SignalIntermediateResult(const itk::SmartPointer<mitk::DataNode>)), this, SIGNAL(SignalIntermediateResult(const itk::SmartPointer<mitk::DataNode>)) ); connect( curNavigationStep, SIGNAL(SignalSettingsNodeChanged(itk::SmartPointer<mitk::DataNode>)), this, SLOT(OnSettingsNodeChanged(itk::SmartPointer<mitk::DataNode>)) ); m_ReadySignalMapper->setMapping(curNavigationStep, n); m_NoLongerReadySignalMapper->setMapping(curNavigationStep, n); ui->stepsToolBox->insertItem(n, curNavigationStep, QString("Step ") + QString::number(n+1) + ": " + curNavigationStep->GetTitle()); if ( n > 0 ) { ui->stepsToolBox->setItemEnabled(n, false); } } ui->restartStepButton->setEnabled(m_NavigationSteps.at(0)->GetIsRestartable()); ui->stepsToolBox->setCurrentIndex(0); // activate the first navigation step widgets if ( ! m_NavigationSteps.empty() ) { m_NavigationSteps.at(0)->ActivateStep(); } // after filling the steps tool box the signal is interesting again connect( ui->stepsToolBox, SIGNAL(currentChanged(int)), this, SLOT(OnTabChanged(int)) ); this->UpdateFilterPipeline(); } void QmitkUSNavigationProcessWidget::UpdatePrevNextButtons() { int currentIndex = ui->stepsToolBox->currentIndex(); ui->previousButton->setEnabled(currentIndex > 0); ui->nextButton->setEnabled(currentIndex < m_CurrentMaxStep); } void QmitkUSNavigationProcessWidget::UpdateFilterPipeline() { if ( m_CombinedModality.IsNull() ) { return; } std::vector<mitk::NavigationDataToNavigationDataFilter::Pointer> filterList; mitk::NavigationDataSource::Pointer navigationDataSource = m_CombinedModality->GetNavigationDataSource(); for (unsigned int n = 0; n <= m_CurrentMaxStep && n < m_NavigationSteps.size(); ++n) { QmitkUSAbstractNavigationStep::FilterVector filter = m_NavigationSteps.at(n)->GetFilter(); if ( ! filter.empty() ) { filterList.insert(filterList.end(), filter.begin(), filter.end()); } } if ( ! filterList.empty() ) { for (unsigned int n = 0; n < navigationDataSource->GetNumberOfOutputs(); ++n) { filterList.at(0)->SetInput(n, navigationDataSource->GetOutput(n)); } for (std::vector<mitk::NavigationDataToNavigationDataFilter::Pointer>::iterator it = filterList.begin()+1; it != filterList.end(); ++it) { std::vector<mitk::NavigationDataToNavigationDataFilter::Pointer>::iterator prevIt = it-1; for (unsigned int n = 0; n < (*prevIt)->GetNumberOfOutputs(); ++n) { (*it)->SetInput(n, (*prevIt)->GetOutput(n)); } } m_LastNavigationDataFilter = filterList.at(filterList.size()-1); } else { m_LastNavigationDataFilter = navigationDataSource.GetPointer(); } } void QmitkUSNavigationProcessWidget::SetSettingsWidgetVisible(bool visible) { ui->settingsFrameWidget->setVisible(visible); ui->stepsToolBox->setHidden(visible); ui->settingsButton->setHidden(visible); ui->restartStepButton->setHidden(visible); ui->previousButton->setHidden(visible); ui->nextButton->setHidden(visible); } void QmitkUSNavigationProcessWidget::FinishCurrentNavigationStep() { int currentIndex = ui->stepsToolBox->currentIndex(); QmitkUSAbstractNavigationStep* curNavigationStep = m_NavigationSteps.at(currentIndex); curNavigationStep->FinishStep(); }
iwegner/MITK
Plugins/org.mitk.gui.qt.igt.app.echotrack/src/internal/Widgets/QmitkUSNavigationProcessWidget.cpp
C++
bsd-3-clause
18,872
// Copyright 2021 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 "chrome/browser/image_editor/screenshot_flow.h" #include <memory> #include "base/logging.h" #include "build/build_config.h" #include "content/public/browser/render_widget_host.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents_observer.h" #include "third_party/skia/include/core/SkColor.h" #include "ui/compositor/paint_recorder.h" #include "ui/gfx/canvas.h" #include "ui/gfx/geometry/point.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/geometry/rect_f.h" #include "ui/gfx/image/image.h" #include "ui/gfx/native_widget_types.h" #include "ui/gfx/render_text.h" #include "ui/snapshot/snapshot.h" #include "ui/views/background.h" #if defined(OS_MAC) #include "chrome/browser/image_editor/event_capture_mac.h" #include "components/lens/lens_features.h" #include "content/public/browser/render_view_host.h" #include "ui/views/widget/widget.h" #endif #if defined(USE_AURA) #include "ui/aura/window.h" #include "ui/wm/core/window_util.h" #endif namespace image_editor { // Colors for semitransparent overlay. static constexpr SkColor kColorSemitransparentOverlayMask = SkColorSetARGB(0x7F, 0x00, 0x00, 0x00); static constexpr SkColor kColorSemitransparentOverlayVisible = SkColorSetARGB(0x00, 0x00, 0x00, 0x00); static constexpr SkColor kColorSelectionRect = SkColorSetRGB(0xEE, 0xEE, 0xEE); // Minimum selection rect edge size to treat as a valid capture region. static constexpr int kMinimumValidSelectionEdgePixels = 30; ScreenshotFlow::ScreenshotFlow(content::WebContents* web_contents) : content::WebContentsObserver(web_contents), web_contents_(web_contents->GetWeakPtr()) { weak_this_ = weak_factory_.GetWeakPtr(); } ScreenshotFlow::~ScreenshotFlow() { RemoveUIOverlay(); } void ScreenshotFlow::CreateAndAddUIOverlay() { if (screen_capture_layer_) return; web_contents_observer_ = std::make_unique<UnderlyingWebContentsObserver>( web_contents_.get(), this); screen_capture_layer_ = std::make_unique<ui::Layer>(ui::LayerType::LAYER_TEXTURED); screen_capture_layer_->SetName("ScreenshotRegionSelectionLayer"); screen_capture_layer_->SetFillsBoundsOpaquely(false); screen_capture_layer_->set_delegate(this); #if defined(OS_MAC) gfx::Rect bounds = web_contents_->GetViewBounds(); const gfx::NativeView web_contents_view = web_contents_->GetContentNativeView(); views::Widget* widget = views::Widget::GetWidgetForNativeView(web_contents_view); ui::Layer* content_layer = widget->GetLayer(); const gfx::Rect offset_bounds = widget->GetWindowBoundsInScreen(); bounds.Offset(-offset_bounds.x(), -offset_bounds.y()); event_capture_mac_ = std::make_unique<EventCaptureMac>( this, web_contents_->GetTopLevelNativeWindow()); #else const gfx::NativeWindow& native_window = web_contents_->GetNativeView(); ui::Layer* content_layer = native_window->layer(); const gfx::Rect bounds = native_window->bounds(); // Capture mouse down and drag events on our window. native_window->AddPreTargetHandler(this); #endif content_layer->Add(screen_capture_layer_.get()); content_layer->StackAtTop(screen_capture_layer_.get()); screen_capture_layer_->SetBounds(bounds); screen_capture_layer_->SetVisible(true); SetCursor(ui::mojom::CursorType::kCross); // After setup is done, we should set the capture mode to active. capture_mode_ = CaptureMode::SELECTION_RECTANGLE; } void ScreenshotFlow::RemoveUIOverlay() { if (capture_mode_ == CaptureMode::NOT_CAPTURING) return; capture_mode_ = CaptureMode::NOT_CAPTURING; if (!web_contents_ || !screen_capture_layer_) return; #if defined(OS_MAC) views::Widget* widget = views::Widget::GetWidgetForNativeView( web_contents_->GetContentNativeView()); if (!widget) return; ui::Layer* content_layer = widget->GetLayer(); event_capture_mac_.reset(); #else const gfx::NativeWindow& native_window = web_contents_->GetNativeView(); native_window->RemovePreTargetHandler(this); ui::Layer* content_layer = native_window->layer(); #endif content_layer->Remove(screen_capture_layer_.get()); screen_capture_layer_->set_delegate(nullptr); screen_capture_layer_.reset(); // Restore the cursor to pointer; there's no corresponding GetCursor() // to store the pre-capture-mode cursor, and the pointer will have moved // in the meantime. SetCursor(ui::mojom::CursorType::kPointer); } void ScreenshotFlow::Start(ScreenshotCaptureCallback flow_callback) { flow_callback_ = std::move(flow_callback); CreateAndAddUIOverlay(); RequestRepaint(gfx::Rect()); } void ScreenshotFlow::StartFullscreenCapture( ScreenshotCaptureCallback flow_callback) { // Start and finish the capture process by screenshotting the full window. // There is no region selection step in this mode. flow_callback_ = std::move(flow_callback); CaptureAndRunScreenshotCompleteCallback(ScreenshotCaptureResultCode::SUCCESS, gfx::Rect(web_contents_->GetSize())); } void ScreenshotFlow::CaptureAndRunScreenshotCompleteCallback( ScreenshotCaptureResultCode result_code, gfx::Rect region) { if (region.IsEmpty()) { RunScreenshotCompleteCallback(result_code, gfx::Rect(), gfx::Image()); return; } gfx::Rect bounds = web_contents_->GetViewBounds(); #if defined(OS_MAC) const gfx::NativeView& native_view = web_contents_->GetContentNativeView(); gfx::Image img; bool rval = ui::GrabViewSnapshot(native_view, region, &img); // If |img| is empty, clients should treat it as a canceled action, but // we have a DCHECK for development as we expected this call to succeed. DCHECK(rval); RunScreenshotCompleteCallback(result_code, bounds, img); #else ui::GrabWindowSnapshotAsyncCallback screenshot_callback = base::BindOnce(&ScreenshotFlow::RunScreenshotCompleteCallback, weak_this_, result_code, bounds); const gfx::NativeWindow& native_window = web_contents_->GetNativeView(); ui::GrabWindowSnapshotAsync(native_window, region, std::move(screenshot_callback)); #endif } void ScreenshotFlow::CancelCapture() { RemoveUIOverlay(); } void ScreenshotFlow::OnKeyEvent(ui::KeyEvent* event) { if (event->type() == ui::ET_KEY_PRESSED && event->key_code() == ui::VKEY_ESCAPE) { event->StopPropagation(); CompleteCapture(ScreenshotCaptureResultCode::USER_ESCAPE_EXIT, gfx::Rect()); } } void ScreenshotFlow::OnMouseEvent(ui::MouseEvent* event) { if (!event->IsLocatedEvent()) return; const ui::LocatedEvent* located_event = ui::LocatedEvent::FromIfValid(event); if (!located_event) return; gfx::Point location = located_event->location(); #if defined(OS_MAC) // Offset |location| be relative to the WebContents widget, vs the parent // window, recomputed rather than cached in case e.g. user disables // bookmarks bar from another window. gfx::Rect web_contents_bounds = web_contents_->GetViewBounds(); const gfx::NativeView web_contents_view = web_contents_->GetContentNativeView(); views::Widget* widget = views::Widget::GetWidgetForNativeView(web_contents_view); const gfx::Rect widget_bounds = widget->GetWindowBoundsInScreen(); location.set_x(location.x() + (widget_bounds.x() - web_contents_bounds.x())); location.set_y(location.y() + (widget_bounds.y() - web_contents_bounds.y())); // Don't capture clicks on browser ui outside the webcontents. if (location.x() < 0 || location.y() < 0 || location.x() > web_contents_bounds.width() || location.y() > web_contents_bounds.height()) { return; } #endif switch (event->type()) { case ui::ET_MOUSE_MOVED: SetCursor(ui::mojom::CursorType::kCross); event->SetHandled(); break; case ui::ET_MOUSE_PRESSED: if (event->IsLeftMouseButton()) { drag_start_ = location; drag_end_ = location; event->SetHandled(); } break; case ui::ET_MOUSE_DRAGGED: if (event->IsLeftMouseButton()) { drag_end_ = location; RequestRepaint(gfx::Rect()); event->SetHandled(); } break; case ui::ET_MOUSE_RELEASED: if (capture_mode_ == CaptureMode::SELECTION_RECTANGLE || capture_mode_ == CaptureMode::SELECTION_ELEMENT) { event->SetHandled(); gfx::Rect selection = gfx::BoundingRect(drag_start_, drag_end_); drag_start_.SetPoint(0, 0); drag_end_.SetPoint(0, 0); if (selection.width() >= kMinimumValidSelectionEdgePixels && selection.height() >= kMinimumValidSelectionEdgePixels) { CompleteCapture(ScreenshotCaptureResultCode::SUCCESS, selection); } else { RequestRepaint(gfx::Rect()); } } break; default: break; } } void ScreenshotFlow::CompleteCapture(ScreenshotCaptureResultCode result_code, const gfx::Rect& region) { RemoveUIOverlay(); CaptureAndRunScreenshotCompleteCallback(result_code, region); } void ScreenshotFlow::RunScreenshotCompleteCallback( ScreenshotCaptureResultCode result_code, gfx::Rect bounds, gfx::Image image) { ScreenshotCaptureResult result; result.result_code = result_code; result.image = image; result.screen_bounds = bounds; std::move(flow_callback_).Run(result); } void ScreenshotFlow::OnPaintLayer(const ui::PaintContext& context) { if (!screen_capture_layer_) return; const gfx::Rect& screen_bounds(screen_capture_layer_->bounds()); ui::PaintRecorder recorder(context, screen_bounds.size()); gfx::Canvas* canvas = recorder.canvas(); auto selection_rect = gfx::BoundingRect(drag_start_, drag_end_); PaintSelectionLayer(canvas, selection_rect, gfx::Rect()); paint_invalidation_ = gfx::Rect(); } void ScreenshotFlow::RequestRepaint(gfx::Rect region) { if (!screen_capture_layer_) return; if (region.IsEmpty()) { const gfx::Size& layer_size = screen_capture_layer_->size(); region = gfx::Rect(0, 0, layer_size.width(), layer_size.height()); } paint_invalidation_.Union(region); screen_capture_layer_->SchedulePaint(region); } void ScreenshotFlow::PaintSelectionLayer(gfx::Canvas* canvas, const gfx::Rect& selection, const gfx::Rect& invalidation_region) { // Adjust for hidpi and lodpi support. canvas->UndoDeviceScaleFactor(); // Clear the canvas with our mask color. canvas->DrawColor(kColorSemitransparentOverlayMask); // Allow the user's selection to show through, and add a border around it. if (!selection.IsEmpty()) { float scale_factor = screen_capture_layer_->device_scale_factor(); gfx::Rect selection_scaled = gfx::ScaleToEnclosingRect(selection, scale_factor); canvas->FillRect(selection_scaled, kColorSemitransparentOverlayVisible, SkBlendMode::kClear); canvas->DrawRect(gfx::RectF(selection_scaled), kColorSelectionRect); } } void ScreenshotFlow::SetCursor(ui::mojom::CursorType cursor_type) { if (!web_contents_) { return; } #if defined(OS_MAC) if (cursor_type == ui::mojom::CursorType::kCross && lens::features::kRegionSearchMacCursorFix.Get()) { EventCaptureMac::SetCrossCursor(); return; } #endif content::RenderWidgetHost* host = web_contents_->GetMainFrame()->GetRenderWidgetHost(); if (host) { ui::Cursor cursor(cursor_type); host->SetCursor(cursor); } } bool ScreenshotFlow::IsCaptureModeActive() { return capture_mode_ != CaptureMode::NOT_CAPTURING; } void ScreenshotFlow::WebContentsDestroyed() { if (IsCaptureModeActive()) { CancelCapture(); } } void ScreenshotFlow::OnVisibilityChanged(content::Visibility visibility) { if (IsCaptureModeActive()) { CancelCapture(); } } // UnderlyingWebContentsObserver monitors the WebContents and exits screen // capture mode if a navigation occurs. class ScreenshotFlow::UnderlyingWebContentsObserver : public content::WebContentsObserver { public: UnderlyingWebContentsObserver(content::WebContents* web_contents, ScreenshotFlow* screenshot_flow) : content::WebContentsObserver(web_contents), screenshot_flow_(screenshot_flow) {} ~UnderlyingWebContentsObserver() override = default; UnderlyingWebContentsObserver(const UnderlyingWebContentsObserver&) = delete; UnderlyingWebContentsObserver& operator=( const UnderlyingWebContentsObserver&) = delete; // content::WebContentsObserver void PrimaryPageChanged(content::Page& page) override { // We only care to complete/cancel a capture if the capture mode is // currently active. if (screenshot_flow_->IsCaptureModeActive()) screenshot_flow_->CompleteCapture( ScreenshotCaptureResultCode::USER_NAVIGATED_EXIT, gfx::Rect()); } private: ScreenshotFlow* screenshot_flow_; }; } // namespace image_editor
scheib/chromium
chrome/browser/image_editor/screenshot_flow.cc
C++
bsd-3-clause
13,138
// 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. #ifndef CHROME_COMMON_CHROME_CONTENT_CLIENT_H_ #define CHROME_COMMON_CHROME_CONTENT_CLIENT_H_ #pragma once #include "base/compiler_specific.h" #include "content/public/common/content_client.h" namespace chrome { class ChromeContentClient : public content::ContentClient { public: static const char* const kPDFPluginName; static const char* const kNaClPluginName; static const char* const kNaClOldPluginName; virtual void SetActiveURL(const GURL& url) OVERRIDE; virtual void SetGpuInfo(const content::GPUInfo& gpu_info) OVERRIDE; virtual void AddPepperPlugins( std::vector<content::PepperPluginInfo>* plugins) OVERRIDE; virtual void AddNPAPIPlugins( webkit::npapi::PluginList* plugin_list) OVERRIDE; virtual bool CanSendWhileSwappedOut(const IPC::Message* msg) OVERRIDE; virtual bool CanHandleWhileSwappedOut(const IPC::Message& msg) OVERRIDE; virtual std::string GetUserAgent(bool* overriding) const OVERRIDE; virtual string16 GetLocalizedString(int message_id) const OVERRIDE; virtual base::StringPiece GetDataResource(int resource_id) const OVERRIDE; #if defined(OS_WIN) virtual bool SandboxPlugin(CommandLine* command_line, sandbox::TargetPolicy* policy) OVERRIDE; #endif #if defined(OS_MACOSX) virtual bool GetSandboxProfileForSandboxType( int sandbox_type, int* sandbox_profile_resource_id) const OVERRIDE; #endif }; } // namespace chrome #endif // CHROME_COMMON_CHROME_CONTENT_CLIENT_H_
aYukiSekiguchi/ACCESS-Chromium
chrome/common/chrome_content_client.h
C
bsd-3-clause
1,655
/* * Copyright (C) 2007, 2008, 2013 Apple 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: * * 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 Apple Computer, Inc. ("Apple") 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 APPLE AND ITS 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 APPLE OR ITS 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. */ #ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_WEBDATABASE_DATABASE_TRACKER_H_ #define THIRD_PARTY_BLINK_RENDERER_MODULES_WEBDATABASE_DATABASE_TRACKER_H_ #include <memory> #include "base/callback.h" #include "base/macros.h" #include "third_party/blink/renderer/modules/modules_export.h" #include "third_party/blink/renderer/modules/webdatabase/database_error.h" #include "third_party/blink/renderer/platform/heap/persistent.h" #include "third_party/blink/renderer/platform/wtf/hash_map.h" #include "third_party/blink/renderer/platform/wtf/hash_set.h" #include "third_party/blink/renderer/platform/wtf/text/string_hash.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" #include "third_party/blink/renderer/platform/wtf/threading_primitives.h" namespace blink { class Database; class DatabaseContext; class Page; class SecurityOrigin; class MODULES_EXPORT DatabaseTracker { USING_FAST_MALLOC(DatabaseTracker); public: static DatabaseTracker& Tracker(); DatabaseTracker(const DatabaseTracker&) = delete; DatabaseTracker& operator=(const DatabaseTracker&) = delete; // This singleton will potentially be used from multiple worker threads and // the page's context thread simultaneously. To keep this safe, it's // currently using 4 locks. In order to avoid deadlock when taking multiple // locks, you must take them in the correct order: // m_databaseGuard before quotaManager if both locks are needed. // m_openDatabaseMapGuard before quotaManager if both locks are needed. // m_databaseGuard and m_openDatabaseMapGuard currently don't overlap. // notificationMutex() is currently independent of the other locks. bool CanEstablishDatabase(DatabaseContext*, DatabaseError&); String FullPathForDatabase(const SecurityOrigin*, const String& name, bool create_if_does_not_exist = true); void AddOpenDatabase(Database*); void RemoveOpenDatabase(Database*); uint64_t GetMaxSizeForDatabase(const Database*); void CloseDatabasesImmediately(const SecurityOrigin*, const String& name); using DatabaseCallback = base::RepeatingCallback<void(Database*)>; void ForEachOpenDatabaseInPage(Page*, DatabaseCallback); void PrepareToOpenDatabase(Database*); void FailedToOpenDatabase(Database*); private: using DatabaseSet = HashSet<CrossThreadPersistent<Database>>; using DatabaseNameMap = HashMap<String, DatabaseSet*>; using DatabaseOriginMap = HashMap<String, DatabaseNameMap*>; DatabaseTracker(); void CloseOneDatabaseImmediately(const String& origin_identifier, const String& name, Database*); Mutex open_database_map_guard_; mutable std::unique_ptr<DatabaseOriginMap> open_database_map_; }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_MODULES_WEBDATABASE_DATABASE_TRACKER_H_
scheib/chromium
third_party/blink/renderer/modules/webdatabase/database_tracker.h
C
bsd-3-clause
4,513
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE457_Use_of_Uninitialized_Variable__char_pointer_64b.c Label Definition File: CWE457_Use_of_Uninitialized_Variable.c.label.xml Template File: sources-sinks-64b.tmpl.c */ /* * @description * CWE: 457 Use of Uninitialized Variable * BadSource: no_init Don't initialize data * GoodSource: Initialize data * Sinks: use * GoodSink: Initialize then use data * BadSink : Use data * Flow Variant: 64 Data flow: void pointer to data passed from one function to another in different source files * * */ #include "std_testcase.h" #include <wchar.h> #ifndef OMITBAD void CWE457_Use_of_Uninitialized_Variable__char_pointer_64b_badSink(void * dataVoidPtr) { /* cast void pointer to a pointer of the appropriate type */ char * * dataPtr = (char * *)dataVoidPtr; /* dereference dataPtr into data */ char * data = (*dataPtr); /* POTENTIAL FLAW: Use data without initializing it */ printLine(data); } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ void CWE457_Use_of_Uninitialized_Variable__char_pointer_64b_goodG2BSink(void * dataVoidPtr) { /* cast void pointer to a pointer of the appropriate type */ char * * dataPtr = (char * *)dataVoidPtr; /* dereference dataPtr into data */ char * data = (*dataPtr); /* POTENTIAL FLAW: Use data without initializing it */ printLine(data); } /* goodB2G uses the BadSource with the GoodSink */ void CWE457_Use_of_Uninitialized_Variable__char_pointer_64b_goodB2GSink(void * dataVoidPtr) { /* cast void pointer to a pointer of the appropriate type */ char * * dataPtr = (char * *)dataVoidPtr; /* dereference dataPtr into data */ char * data = (*dataPtr); /* FIX: Ensure data is initialized before use */ data = "string"; printLine(data); } #endif /* OMITGOOD */
JianpingZeng/xcc
xcc/test/juliet/testcases/CWE457_Use_of_Uninitialized_Variable/s01/CWE457_Use_of_Uninitialized_Variable__char_pointer_64b.c
C
bsd-3-clause
1,932
// 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 "content/common/child_histogram_message_filter.h" #include <ctype.h> #include "base/bind.h" #include "base/message_loop.h" #include "base/metrics/statistics_recorder.h" #include "base/pickle.h" #include "content/common/child_process.h" #include "content/common/child_process_messages.h" #include "content/common/child_thread.h" namespace content { ChildHistogramMessageFilter::ChildHistogramMessageFilter() : channel_(NULL), ALLOW_THIS_IN_INITIALIZER_LIST(histogram_snapshot_manager_(this)) { } ChildHistogramMessageFilter::~ChildHistogramMessageFilter() { } void ChildHistogramMessageFilter::OnFilterAdded(IPC::Channel* channel) { channel_ = channel; } void ChildHistogramMessageFilter::OnFilterRemoved() { } bool ChildHistogramMessageFilter::OnMessageReceived( const IPC::Message& message) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(ChildHistogramMessageFilter, message) IPC_MESSAGE_HANDLER(ChildProcessMsg_GetChildHistogramData, OnGetChildHistogramData) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } void ChildHistogramMessageFilter::SendHistograms(int sequence_number) { ChildProcess::current()->io_message_loop_proxy()->PostTask( FROM_HERE, base::Bind(&ChildHistogramMessageFilter::UploadAllHistograms, this, sequence_number)); } void ChildHistogramMessageFilter::OnGetChildHistogramData(int sequence_number) { UploadAllHistograms(sequence_number); } void ChildHistogramMessageFilter::UploadAllHistograms(int sequence_number) { DCHECK_EQ(0u, pickled_histograms_.size()); base::StatisticsRecorder::CollectHistogramStats("ChildProcess"); // Push snapshots into our pickled_histograms_ vector. // Note: Before serializing, we set the kIPCSerializationSourceFlag for all // the histograms, so that the receiving process can distinguish them from the // local histograms. histogram_snapshot_manager_.PrepareDeltas( base::Histogram::kIPCSerializationSourceFlag, false); channel_->Send(new ChildProcessHostMsg_ChildHistogramData( sequence_number, pickled_histograms_)); pickled_histograms_.clear(); static int count = 0; count++; DHISTOGRAM_COUNTS("Histogram.ChildProcessHistogramSentCount", count); } void ChildHistogramMessageFilter::RecordDelta( const base::HistogramBase& histogram, const base::HistogramSamples& snapshot) { DCHECK_NE(0, snapshot.TotalCount()); Pickle pickle; histogram.SerializeInfo(&pickle); snapshot.Serialize(&pickle); pickled_histograms_.push_back( std::string(static_cast<const char*>(pickle.data()), pickle.size())); } void ChildHistogramMessageFilter::InconsistencyDetected( base::Histogram::Inconsistencies problem) { UMA_HISTOGRAM_ENUMERATION("Histogram.InconsistenciesChildProcess", problem, base::Histogram::NEVER_EXCEEDED_VALUE); } void ChildHistogramMessageFilter::UniqueInconsistencyDetected( base::Histogram::Inconsistencies problem) { UMA_HISTOGRAM_ENUMERATION("Histogram.InconsistenciesChildProcessUnique", problem, base::Histogram::NEVER_EXCEEDED_VALUE); } void ChildHistogramMessageFilter::InconsistencyDetectedInLoggedCount( int amount) { UMA_HISTOGRAM_COUNTS("Histogram.InconsistentSnapshotChildProcess", std::abs(amount)); } } // namespace content
zcbenz/cefode-chromium
content/common/child_histogram_message_filter.cc
C++
bsd-3-clause
3,578
/* * Copyright (C) 2013 Soumith Chintala * */ #include <jni.h> #include <stdio.h> #include <stdlib.h> #include "torchandroid.h" #include <assert.h> extern "C" { JNIEXPORT jstring JNICALL Java_com_torch_Torch_jni_1call( JNIEnv* env, jobject thiz, jobject assetManager, jstring nativeLibraryDir_, jstring luaFile_ ) { // D("Hello from C"); // get native asset manager AAssetManager* manager = AAssetManager_fromJava(env, assetManager); assert( NULL != manager); const char *nativeLibraryDir = env->GetStringUTFChars(nativeLibraryDir_, 0); const char *file = env->GetStringUTFChars(luaFile_, 0); char buffer[4096]; // buffer for textview output D("Torch.call(%s), nativeLibraryDir=%s", file, nativeLibraryDir); buffer[0] = 0; lua_State *L = inittorch(manager, nativeLibraryDir); // create a lua_State assert( NULL != manager); // load and run file int ret; long size = android_asset_get_size(file); if (size != -1) { char *filebytes = android_asset_get_bytes(file); ret = luaL_dobuffer(L, filebytes, size, "main"); } // check if script ran succesfully. If not, print error to logcat if (ret == 1) { D("Error doing resource: %s:%s\n", file, lua_tostring(L,-1)); strlcat(buffer, lua_tostring(L,-1), sizeof(buffer)); } else strlcat(buffer, "Torch script ran succesfully. Check Logcat for more details.", sizeof(buffer)); // destroy the Lua State lua_close(L); return env->NewStringUTF(buffer); } }
Jeff-Huang/th-android
src/torchcall.cpp
C++
bsd-3-clause
1,727
<?php use yii\helpers\Html; ?> <?php foreach ($_model as $photo): ?> <div class="thumb" style="float:left;padding: 2px" data-name="<?= $photo->name ?>" onclick="ShowFullImage('<?= $photo->name ?>')" > <div> <?= Html::img('/upload/multy-thumbs/' . $photo->name, ['height' => '70px']); ?> </div> <div style="" > <?= $photo->name; ?> </div> </div> <?php endforeach; ?> <style> .jpreloader.back_background{ background-color: #111214; bottom: 0; height: 100%; left: 0; opacity: 0.9; position: fixed; right: 0; top: 0; width: 100%; display: block; background-image: url("/img/preloader.gif"); background-repeat: no-repeat; background-position:center center; } </style>
kotmonstr/kotmonstr
frontend/modules/image/views/default/get-photo.php
PHP
bsd-3-clause
1,011
package io.flutter.embedding.engine.mutatorsstack; import static junit.framework.TestCase.*; import static org.mockito.Mockito.*; import android.graphics.Matrix; import android.view.MotionEvent; import io.flutter.embedding.android.AndroidTouchProcessor; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.robolectric.RobolectricTestRunner; import org.robolectric.RuntimeEnvironment; import org.robolectric.annotation.Config; @Config(manifest = Config.NONE) @RunWith(RobolectricTestRunner.class) public class FlutterMutatorViewTest { @Test public void canDragViews() { final AndroidTouchProcessor touchProcessor = mock(AndroidTouchProcessor.class); final FlutterMutatorView view = new FlutterMutatorView(RuntimeEnvironment.systemContext, 1.0f, touchProcessor); final FlutterMutatorsStack mutatorStack = mock(FlutterMutatorsStack.class); assertTrue(view.onInterceptTouchEvent(mock(MotionEvent.class))); { view.readyToDisplay(mutatorStack, /*left=*/ 1, /*top=*/ 2, /*width=*/ 0, /*height=*/ 0); view.onTouchEvent(MotionEvent.obtain(0, 0, MotionEvent.ACTION_DOWN, 0.0f, 0.0f, 0)); final ArgumentCaptor<Matrix> matrixCaptor = ArgumentCaptor.forClass(Matrix.class); verify(touchProcessor).onTouchEvent(any(), matrixCaptor.capture()); final Matrix screenMatrix = new Matrix(); screenMatrix.postTranslate(1, 2); assertTrue(matrixCaptor.getValue().equals(screenMatrix)); } reset(touchProcessor); { view.readyToDisplay(mutatorStack, /*left=*/ 3, /*top=*/ 4, /*width=*/ 0, /*height=*/ 0); view.onTouchEvent(MotionEvent.obtain(0, 0, MotionEvent.ACTION_MOVE, 0.0f, 0.0f, 0)); final ArgumentCaptor<Matrix> matrixCaptor = ArgumentCaptor.forClass(Matrix.class); verify(touchProcessor).onTouchEvent(any(), matrixCaptor.capture()); final Matrix screenMatrix = new Matrix(); screenMatrix.postTranslate(1, 2); assertTrue(matrixCaptor.getValue().equals(screenMatrix)); } reset(touchProcessor); { view.readyToDisplay(mutatorStack, /*left=*/ 5, /*top=*/ 6, /*width=*/ 0, /*height=*/ 0); view.onTouchEvent(MotionEvent.obtain(0, 0, MotionEvent.ACTION_MOVE, 0.0f, 0.0f, 0)); final ArgumentCaptor<Matrix> matrixCaptor = ArgumentCaptor.forClass(Matrix.class); verify(touchProcessor).onTouchEvent(any(), matrixCaptor.capture()); final Matrix screenMatrix = new Matrix(); screenMatrix.postTranslate(3, 4); assertTrue(matrixCaptor.getValue().equals(screenMatrix)); } reset(touchProcessor); { view.readyToDisplay(mutatorStack, /*left=*/ 7, /*top=*/ 8, /*width=*/ 0, /*height=*/ 0); view.onTouchEvent(MotionEvent.obtain(0, 0, MotionEvent.ACTION_DOWN, 0.0f, 0.0f, 0)); final ArgumentCaptor<Matrix> matrixCaptor = ArgumentCaptor.forClass(Matrix.class); verify(touchProcessor).onTouchEvent(any(), matrixCaptor.capture()); final Matrix screenMatrix = new Matrix(); screenMatrix.postTranslate(7, 8); assertTrue(matrixCaptor.getValue().equals(screenMatrix)); } } }
chinmaygarde/flutter_engine
shell/platform/android/test/io/flutter/embedding/engine/mutatorsstack/FlutterMutatorViewTest.java
Java
bsd-3-clause
3,135
package org.hisp.dhis.dxf2.adx; /* * Copyright (c) 2015, UiO * 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. * * 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 java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.apache.xerces.util.XMLChar; import org.hisp.dhis.dataelement.DataElementCategory; import org.hisp.dhis.dataelement.DataElementCategoryCombo; import org.hisp.dhis.dataelement.DataElementCategoryOptionCombo; import org.hisp.dhis.dataset.DataSet; import org.hisp.dhis.dataset.DataSetElement; /** * @author bobj */ public class AdxDataSetMetadata { // Lookup category options per cat option combo private final Map<Integer, Map<String, String>> categoryOptionMap; AdxDataSetMetadata( DataSet dataSet ) throws AdxException { categoryOptionMap = new HashMap<>(); Set<DataElementCategoryCombo> catCombos = new HashSet<>(); catCombos.add( dataSet.getCategoryCombo() ); for ( DataSetElement element : dataSet.getDataSetElements() ) { catCombos.add( element.getResolvedCategoryCombo() ); } for ( DataElementCategoryCombo categoryCombo : catCombos ) { for ( DataElementCategoryOptionCombo catOptCombo : categoryCombo.getOptionCombos() ) { addExplodedCategoryAttributes( catOptCombo ); } } } private void addExplodedCategoryAttributes( DataElementCategoryOptionCombo coc ) throws AdxException { Map<String, String> categoryAttributes = new HashMap<>(); if ( !coc.isDefault() ) { for ( DataElementCategory category : coc.getCategoryCombo().getCategories() ) { String categoryCode = category.getCode(); if ( categoryCode == null || !XMLChar.isValidName( categoryCode ) ) { throw new AdxException( "Category code for " + category.getName() + " is missing or invalid: " + categoryCode ); } String catOptCode = category.getCategoryOption( coc ).getCode(); if ( catOptCode == null || catOptCode.isEmpty() ) { throw new AdxException( "CategoryOption code for " + category.getCategoryOption( coc ).getName() + " is missing" ); } categoryAttributes.put( categoryCode, catOptCode ); } } categoryOptionMap.put( coc.getId(), categoryAttributes ); } public Map<String, String> getExplodedCategoryAttributes( int cocId ) { return this.categoryOptionMap.get( cocId ); } }
uonafya/jphes-core
dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/adx/AdxDataSetMetadata.java
Java
bsd-3-clause
4,017
<?php /** * Created by PhpStorm. * User: qhuy * Date: 18/12/2014 * Time: 21:59 */ namespace backend\models; use common\helpers\CommonUtils; use common\helpers\CVietnameseTools; use common\helpers\MediaToolBoxHelper; use common\helpers\MyCurl; use common\models\Content; use common\models\News; use garyjl\simplehtmldom\SimpleHtmlDom; use Imagine\Image\Box; use Imagine\Image\ManipulatorInterface; use Yii; use yii\base\Model; use yii\helpers\FileHelper; use yii\helpers\Url; use yii\validators\ImageValidator; use yii\validators\UrlValidator; use yii\web\UploadedFile; class Image extends Model { const TYPE_POSTER = 1; const TYPE_THUMBNAIL = 2; const TYPE_SLIDESHOW = 3; const TYPE_AUTO = 4; const ORIENTATION_PORTRAIT = 1; const ORIENTATION_LANDSCAPE = 2; const RATIO_W = 16; const RATIO_H = 9; const RATIO_MULIPLIER_UPPER_LIMIT = 120;//Ty le toi da limit (1920x1080) public static $imageConfig = null; private $_id = ''; public $content_id; public $name; public $url; public $type = self::TYPE_POSTER; public $orientation; public static $image_types = [ self::TYPE_POSTER => 'poster', self::TYPE_SLIDESHOW => 'slide show', self::TYPE_THUMBNAIL => 'thumbnail', self::TYPE_AUTO => 'auto' ]; public static $image_orient = [ self::ORIENTATION_LANDSCAPE => 'landscape', self::ORIENTATION_PORTRAIT => 'portrait' ]; /** * @var $image UploadedFile */ public $image; /** * Create snapshot param * @param Content $video */ private static function initParamSnapshot($video, $position) { $snapshots = []; $folderSave = self::createFolderImage($video->id); if (!$folderSave) { return false; } if($position <= 0 || $position > $video->duration){ $position = rand(1, $video->duration); } $saveFileName = time() . '_' . CVietnameseTools::makeValidFileName($video->display_name . '_' . $position . '_snapshot.jpg'); $snapshot = new Snapshot(); $snapshot->time = $position; $snapshot->file_path = Yii::getAlias($folderSave) . $saveFileName; $snapshot->size = '100%'; $snapshots[] = $snapshot; return $snapshots; } private static function toAlias($path) { $basePath = Yii::getAlias('@webroot'); Yii::info(preg_quote($basePath, '/')); return preg_replace('/'.preg_quote($basePath, '/').'/', '@webroot', $path); } /** * @inheritdoc */ public function rules() { return [ [['image'], 'file', 'extensions' => ['jpg', 'png', 'jpeg', 'gif']], ['id', 'safe'], [['type', 'orientation'], 'integer'], [['url', 'name'], 'string', 'max' => 500], ]; } public function fields() { // if ($this->scenario == static::SCENARIO_DEFAULT) { // return parent::fields(); // } //List scenario $res = [ // field name is "email", the corresponding attribute name is "email_address" 'name', 'url', 'type', 'orientation', ]; return $res; } public function getId() { if (empty($this->_id)) { $this->_id = md5($this->url); } return $this->_id; } /** * Return full path url */ public function getImageUrl() { $validator = new UrlValidator(); if ($validator->validate($this->url)) { return $this->url; } else { if (preg_match('/(@[a-z]*)/', $this->url)) { return Yii::getAlias($this->url); } else { $configImage = self::getImageConfig(); $baseUrl = isset($configImage['base_url']) ? $configImage['base_url'] : Yii::getAlias('@web'); return $baseUrl . $this->url; } } } public function getFilePath() { $validator = new UrlValidator(); if ($validator->validate($this->url)) { return null; } else { if (preg_match('/(@[a-z]*)/', $this->url)) { return Yii::getAlias(str_replace('@web', '@webroot', $this->url)); } else { $configImage = self::getImageConfig(); $baseUrl = isset($configImage['base_url']) ? $configImage['base_url'] : Yii::getAlias('@webroot'); return $baseUrl . $this->url; } } } public function getWidthHeight() { if(is_file($this->getFilePath())){ $imageSize = getimagesize($this->getFilePath()); if ($imageSize) { return $imageSize[0] . 'x'. $imageSize[1]; } else { return 'N/A'; } }else{ return 'File not found'; } } public function getNameImageFullSave() { return time() . '_' . CVietnameseTools::makeValidFileName($this->name); } public static function getImageConfig() { if (Image::$imageConfig == null) { Image::$imageConfig = [ 'folder' => '@webroot' . DIRECTORY_SEPARATOR . Yii::getAlias('@content_images') . DIRECTORY_SEPARATOR, 'base_url' => Yii::getAlias('@web') . '/' . Yii::getAlias('@content_images') . DIRECTORY_SEPARATOR ]; } return Image::$imageConfig; } /** * Create folder to store image * Each store have image separate with video id * @return full path folder with alias (@webroot/...) */ public static function createFolderImage($video_id) { $configImage = self::getImageConfig(); $basePath = Yii::getAlias($configImage['folder']); if (!is_dir($basePath)) { FileHelper::createDirectory($basePath, 0777); } if (!is_dir($basePath) || $video_id == null) { Yii::error("Folder base path not exist: " . $basePath); return false; } $fullPath = $basePath . $video_id; if (!is_dir($fullPath)) { if (!FileHelper::createDirectory($fullPath, 0777)) { Yii::error("Can not create folder save image: " . $fullPath); return false; } } if (!substr($configImage['folder'], -1) == '/') { $configImage['folder'] .= '/'; } return $configImage['folder'] . $video_id . '/'; } /** * Thuc hien save image khi dc upload len * @param $content News * @return bool * @throws \yii\web\UnauthorizedHttpException */ public function saveImage($content) { $video_id = $content->id; $folderSave = self::createFolderImage($video_id); if (!$folderSave) { $this->addError('image', 'Folder save image not found'); return false; } if ($this->image == null) { $this->addError('image', "Image file not found!"); return false; } $saveFileName = $this->getNameImageFullSave(); $imagePath = Yii::getAlias($folderSave) . $saveFileName; Yii::info("Save file to " . $imagePath, 'VideoImage'); if (!$this->image->saveAs($imagePath)) { $this->addError('image', 'Can not save '); return false; } $imageSize = getimagesize($imagePath); if (count($imageSize) > 0) { if ($imageSize[0] > $imageSize[1]) { //neu width > height $this->orientation = self::ORIENTATION_LANDSCAPE; } else { $this->orientation = self::ORIENTATION_PORTRAIT; } } $this->url = $this->resolveUrl($folderSave) . $saveFileName; if ($this->type == self::TYPE_AUTO) { $this->autoGenerateImages($content, $folderSave, $saveFileName); } return true; } /** * replaces '/(@[a-z]*)root/' => '$1' * @param string $path * @return string */ public function resolveUrl($path) { return preg_replace('/(@[a-z]*)root/', '$1', $path); } /** * @param $content News */ public function save($content) { return $content->addImage($this->getArray()); } public function getArray() { return [ 'name' => $this->name, 'url' => $this->url, 'type' => $this->type, 'orientation' => $this->orientation ]; } public function delete() { //Delete image $file_path = $this->getFilePath(); if (is_dir($file_path)) { return true; } if ($file_path && file_exists($file_path)) { return unlink($this->getFilePath()); } return true; } /** * @param $video Content * @return bool */ public function loadImageYt($video) { $ch = new MyCurl(); $folderSave = self::createFolderImage($video->id); if (!$folderSave) { $this->addError('image', 'Folder save image not found'); return false; } $yt_info = CommonUtils::getVideoYoutubeInfo($video->youtube_id); if ($yt_info == null || $yt_info->snippet == null || $yt_info->snippet->thumbnails == null) { return false; } $img_yt_url = ''; $thumbnails = $yt_info->snippet->thumbnails; $img_yt_url = $this->getHighestImage($thumbnails); if (empty($img_yt_url)) { return false; } $image_extention = end(explode('.', $img_yt_url)); $this->name = $video->display_name . '_yt.' . $image_extention; $this->type = self::TYPE_AUTO; $saveFileName = $this->getNameImageFullSave(); $imagePath = Yii::getAlias($folderSave) . $saveFileName; Yii::info("Save file to " . $imagePath, 'VideoImage'); $response = $ch->download($img_yt_url, Yii::getAlias($folderSave), $saveFileName); if (!$response) { $this->addError('image', 'Can not save '); return false; } $imageSize = getimagesize($imagePath); if (count($imageSize) > 0) { if ($imageSize[0] > $imageSize[1]) { //neu width > height $this->orientation = self::ORIENTATION_LANDSCAPE; } else { $this->orientation = self::ORIENTATION_PORTRAIT; } } $this->url = $this->resolveUrl($folderSave) . $saveFileName; $this->autoGenerateImages($video, $folderSave, $saveFileName); if ($yt_info->contentDetails != null) { $video->duration = CommonUtils::convertYtDurationToSeconds($yt_info->contentDetails->duration); $video->update(false); } return true; } /** * @param Content $video * @return bool */ public static function loadImageSnapshot($video, $video_file, $position = 0) { $snapshots = self::initParamSnapshot($video,$position); $response = MediaToolBoxHelper::getVideoSnapshot($video_file, $snapshots); if (!$response) { Yii::error('Can not get snapshot'); return false; } foreach ($response as $snapshot) { $image = new Image(); $folderSave = self::toAlias(pathinfo($snapshot->file_path, PATHINFO_DIRNAME).DIRECTORY_SEPARATOR); $saveFileName = pathinfo($snapshot->file_path, PATHINFO_BASENAME); $image->name = $saveFileName; $image->autoGenerateImages($video, $folderSave, $saveFileName); } return true; } /** * Load first image from content to create some image * @param $content Content */ public function loadImageFromContent($content) { $ch = new MyCurl(); $folderSave = self::createFolderImage($content->id); if (!$folderSave) { $this->addError('image', 'Folder save image not found'); return false; } $img_content_url = ''; $html = SimpleHtmlDom::str_get_html($content->content); // Get first image foreach($html->find('img') as $element){ $img_content_url = $element->src; if(!empty($img_content_url)) break; } if(empty($img_content_url)){ return false; } $url_validator = new UrlValidator(); if(!$url_validator->validate($img_content_url)){ $img_content_url = Yii::$app->getUrlManager()->getHostInfo().$img_content_url; } Yii::info($img_content_url); $image_extention = end(explode('.', $img_content_url)); $this->name = $content->display_name . '_content.' . $image_extention; $this->type = self::TYPE_AUTO; $saveFileName = $this->getNameImageFullSave(); $imagePath = Yii::getAlias($folderSave) . $saveFileName; Yii::info("Save file to " . $imagePath, 'Image'); $response = $ch->download($img_content_url, Yii::getAlias($folderSave), $saveFileName); if (!$response || !CommonUtils::validateImage($imagePath)) { $this->addError('image', 'Can not save '); return false; } $imageSize = getimagesize($imagePath); if (count($imageSize) > 0) { if ($imageSize[0] > $imageSize[1]) { //neu width > height $this->orientation = self::ORIENTATION_LANDSCAPE; } else { $this->orientation = self::ORIENTATION_PORTRAIT; } } $this->url = $this->resolveUrl($folderSave) . $saveFileName; $this->autoGenerateImages($content, $folderSave, $saveFileName); return true; } /** * Tu dong generate ra cac file dinh dang khac nhau * @param $video * @param $folderSave //Dang tuong doi example '@webroot/content_images/45/ * @param $saveFileName * @return bool */ public function autoGenerateImages($video, $folderSave, $saveFileName) { $imagePath = Yii::getAlias($folderSave) . $saveFileName; $imageSize = getimagesize($imagePath); $img_width = 1; $img_height = 1; if (count($imageSize) > 0) { $img_width = $imageSize[0]; $img_height = $imageSize[1]; } else { return false; } //Resize to slide $slide = $this->resizeImage($folderSave, $imagePath, $img_width, $img_height, self::TYPE_SLIDESHOW); if (!$slide->save($video)) { return false; } //Resize to poster $poster = $this->resizeImage($folderSave, $imagePath, $img_width, $img_height); if (!$poster->save($video)) { return false; }; //Resize to thumbnail $poster = $this->resizeImage($folderSave, $imagePath, $img_width, $img_height, self::TYPE_THUMBNAIL); if (!$poster->save($video)) { return false; } } /** * @param $imageTool \yii\imagine\Image * @param $width * @param $heigh */ private function resizeImage($folder, $filename, $width, $height, $type = self::TYPE_POSTER) { $model = new Image(); $box_src = new Box($width, $height); $box = null; switch ($type) { case self::TYPE_THUMBNAIL: $box = new Box(320, 180); break; default: if (($width / $height) === (self::RATIO_W / self::RATIO_H)) { $box = $box_src; } else { list($new_width, $new_height) = $this->getNewSize($width, $height, self::RATIO_W / self::RATIO_H); $box = new Box($new_width, $new_height); } } $imageTool = \yii\imagine\Image::getImagine()->open($filename); $image = $imageTool->thumbnail($box, ManipulatorInterface::THUMBNAIL_OUTBOUND); $model->name = self::$image_types[$type] . '_' . $this->name; $model->type = $type; $saveFileName = $model->getNameImageFullSave(); $imagePath = Yii::getAlias($folder) . $saveFileName; Yii::info("Save file to " . $imagePath, 'VideoImage'); if (!$image->save($imagePath)) { return null; } $imageSize = getimagesize($imagePath); if (count($imageSize) > 0) { if ($imageSize[0] > $imageSize[1]) { //neu width > height $model->orientation = self::ORIENTATION_LANDSCAPE; } else { $model->orientation = self::ORIENTATION_PORTRAIT; } } $model->url = $this->resolveUrl($folder) . $saveFileName; return $model; } private function getHighestImage($thumbnails) { if ($thumbnails->maxres != null) { return $thumbnails->maxres->url; } if ($thumbnails->standard != null) { return $thumbnails->standard->url; } if ($thumbnails->high != null) { return $thumbnails->high->url; } if ($thumbnails->medium != null) { return $thumbnails->medium->url; } if ($thumbnails->default != null) { return $thumbnails->default->url; } } private function getNewSize($width, $height, $ratio) { // Find closest ratio multiple to image size if ($width > $height) { // landscape $ratioMultiple = round($height / self::RATIO_H, 0, PHP_ROUND_HALF_DOWN); } else { // portrait $ratioMultiple = round($width / self::RATIO_W, 0, PHP_ROUND_HALF_DOWN); } $newWidth = $ratioMultiple * self::RATIO_W; $newHeight = $ratioMultiple * self::RATIO_H; if ($newWidth > self::RATIO_W * self::RATIO_MULIPLIER_UPPER_LIMIT || $newHeight > self::RATIO_H * self::RATIO_MULIPLIER_UPPER_LIMIT) { // File is larger than upper limit $ratioMultiple = self::RATIO_MULIPLIER_UPPER_LIMIT; } $this->tweakMultiplier($ratioMultiple, $width, $height); $newWidth = $ratioMultiple * self::RATIO_W; $newHeight = $ratioMultiple * self::RATIO_H; return [ $newWidth, $newHeight ]; } /** * Xac dinh ratio sao cho new_width, new_height kho qua kich thuoc anh that * @param $ratioMultiple * @param $fitInsideWidth * @param $fitInsideHeight */ protected function tweakMultiplier(&$ratioMultiple, $fitInsideWidth, $fitInsideHeight) { $newWidth = $ratioMultiple * self::RATIO_W; $newHeight = $ratioMultiple * self::RATIO_H; if ($newWidth > $fitInsideWidth || $newHeight > $fitInsideHeight) { $ratioMultiple--; $this->tweakMultiplier($ratioMultiple, $fitInsideWidth, $fitInsideHeight); } else { return; } } }
tuanpv1/news
backend/models/Image.php
PHP
bsd-3-clause
19,090
Ext.define('Ozone.data.Dashboard', { extend: 'Ext.data.Model', idProperty: 'guid', fields:[ 'alteredByAdmin', 'guid', {name:'id', mapping: 'guid'}, { name: 'isdefault', type: 'boolean', defaultValue: false }, { name: 'dashboardPosition', type: 'int' }, 'EDashboardLayoutList', 'name', { name: 'state', defaultValue: [] }, 'removed', 'groups', 'isGroupDashboard', 'description', 'createdDate', 'prettyCreatedDate', 'editedDate', 'prettyEditedDate', { name: 'stack', defaultValue: null }, { name: 'locked', type: 'boolean', defaultValue: false }, { name: 'layoutConfig', defaultValue: null }, { name: 'createdBy', model: 'User'}, { name: 'user', model: 'User'} ], constructor: function(data, id, raw) { if(data.layoutConfig && typeof data.layoutConfig === 'string' && data.layoutConfig !== Object.prototype.toString()) { data.layoutConfig = Ext.JSON.decode(data.layoutConfig); } //todo see if we still need this if(data.layoutConfig === Object.prototype.toString()) { data.layoutConfig = ""; } if(!data.guid) { data.guid = guid.util.guid(); } this.callParent(arguments); } }); Ext.define('Ozone.data.stores.AdminDashboardStore', { extend:'Ozone.data.OWFStore', model: 'Ozone.data.Dashboard', alias: 'store.admindashboardstore', remoteSort: true, totalProperty:'results', sorters: [ { property : 'dashboardPosition', direction: 'ASC' } ], constructor: function(config) { Ext.applyIf(config, { api: { read: "/dashboard", create: "/dashboard", update: "/dashboard", destroy: "/dashboard" }, reader: { root: 'data' }, writer: { root: 'data' } }); this.callParent(arguments); }, reorder: function() { if (this.getCount() > 0) { for (var i = 0; i < this.getCount(); i++) { var dashboard = this.getAt(i); dashboard.set('dashboardPosition', i + 1); } } } }); Ext.define('Ozone.components.admin.grid.DashboardGroupsGrid', { extend: 'Ext.grid.Panel', alias: ['widget.dashboardgroupsgrid'], quickSearchFields: ['name'], plugins: new Ozone.components.focusable.FocusableGridPanel(), cls: 'grid-dashboard', defaultPageSize: 50, multiSelect: true, forceFit: true, baseParams: null, initComponent: function() { //create new store if (this.store == null) { this.store = Ext.StoreMgr.lookup({ type: 'admindashboardstore', pageSize: this.defaultPageSize }); } if (this.baseParams) { this.setBaseParams(this.baseParams); } Ext.apply(this, { columnLines:true, columns: [ { itemId: 'guid', header: 'GUID', dataIndex: 'guid', flex: 1, width: 210, minWidth: 210, sortable: true, hidden: true, renderer: function(value, metaData, record, rowIndex, columnIndex, store, view) { return '<div class="grid-text">' + value +'</div>'; } },{ itemId: 'name', header: 'Dashboard Title', dataIndex: 'name', flex: 3, minWidth: 200, sortable: true, renderer: function(value, metaData, record, rowIndex, columnIndex, store, view) { var title = value; var dashboardLayoutList = record.get('EDashboardLayoutList'); //List of valid ENUM Dashboard Layout Strings var dashboardLayout = record.get('layout'); //current dashboard layout string var iconClass = "grid-dashboard-default-icon-layout"; // if(dashboardLayout && dashboardLayoutList){ // if(dashboardLayoutList.indexOf(dashboardLayout) != -1){ // iconClass = "grid-dashboard-icon-layout-" + dashboardLayout; // } // } // var retVal = '<div class="grid-dashboard-title-box"><div class="grid-dashboard-icon ' + iconClass +'"></div>'; // retVal += '<div class="grid-dashboard-title">' + title + '</div>'; // retVal += '</div>'; return '<p class="grid-dashboard-title '+ iconClass + '">' + Ext.htmlEncode(title) + '</p>'; } }, { itemId: 'groups', header: 'Groups', dataIndex: 'groups', flex: 1, sortable: false, renderer: function(value, metaData, record, rowIndex, columnIndex, store, view) { return '<div class="grid-text grid-dashboard-group-count">' + value.length +'</div>'; } }, { itemId: 'widgets', header: 'Widgets', dataIndex: 'layoutConfig', flex: 1, sortable: false, renderer: function(value, metaData, record, rowIndex, columnIndex, store, view) { var widgetCount = 0; if (value) { var countWidgets = function(cfg) { if(!cfg || !cfg.items) return; if(cfg.items.length === 0) { if(cfg.widgets && cfg.widgets.length > 0) { widgetCount += cfg.widgets.length; } } else { for(var i = 0, len = cfg.items.length; i < len; i++) { countWidgets(cfg.items[i]); } } return widgetCount; }; widgetCount = countWidgets(value); } return '<div class="grid-text grid-dashboard-widget-count">' + widgetCount +'</div>'; } } ] }); Ext.apply(this, { multiSelect: true, dockedItems: [Ext.create('Ext.toolbar.Paging', { dock: 'bottom', store: this.store, displayInfo: true, hidden: this.hidePagingToolbar, itemId: 'dashboard-groups-grid-paging' })] }); this.callParent(arguments); }, getSelectedDashboards: function(){ return this.getSelectionModel().getSelection(); }, load: function() { this.store.loadPage(1); }, refresh: function() { this.store.loadPage(this.store.currentPage); }, getTopToolbar: function() { return this.getDockedItems('toolbar[dock="top"]')[0]; }, getBottomToolbar: function() { return this.getDockedItems('toolbar[dock="bottom"]')[0]; }, applyFilter: function(filterText, fields) { this.store.proxy.extraParams = undefined; if (filterText) { var filters = []; for (var i = 0; i < fields.length; i++) { filters.push({ filterField: fields[i], filterValue: filterText }); } this.store.proxy.extraParams = { filters: Ext.JSON.encode(filters), filterOperator: 'OR' }; } if (this.baseParams) { this.setBaseParams(this.baseParams); } this.store.loadPage(1,{ params: { offset: 0, max: this.store.pageSize } }); }, clearFilters: function() { this.store.proxy.extraParams = undefined; if (this.baseParams) { this.setBaseParams(this.baseParams); } this.store.load({ params: { start: 0, max: this.store.pageSize } }); }, setBaseParams: function(params) { this.baseParams = params; if (this.store.proxy.extraParams) { Ext.apply(this.store.proxy.extraParams, params); } else { this.store.proxy.extraParams = params; } }, setStore: function(store, cols) { this.reconfigure(store, cols); var pgtb = this.getBottomToolbar(); if (pgtb) { pgtb.bindStore(store); } } }); Ext.define('Ozone.components.admin.dashboard.DashboardDetailPanel', { extend: 'Ext.panel.Panel', alias: ['widget.dashboarddetailpanel', 'widget.dashboarddetail'], viewDashboard: null, loadedRecord: null, initComponent: function() { //init quicktips Ext.tip.QuickTipManager.init(true,{ dismissDelay: 60000, showDelay: 2000 }); this.viewDashboard = Ext.create('Ext.view.View', { store: Ext.create('Ext.data.Store', { storeId: 'storeDashboardItem', fields: [ { name: 'name', type: 'string' }, { name: 'layout', type: 'string' }, { name: 'EDashboardLayoutList', type: 'string' }, { name: 'isGroupDashboard', type: 'boolean'}, { name: 'groups', model: 'Group'}, { name: 'description', type: 'string' }, { name: 'createdDate', type: 'string' }, { name: 'prettyCreatedDate', type: 'string' }, { name: 'editedDate', type: 'string' }, { name: 'prettyEditedDate', type: 'string' }, { name: 'createdBy', model: 'User' }, { name: 'stack', model: 'Stack'} ] }), deferEmptyText: false, tpl: new Ext.XTemplate( '<tpl for=".">', '<div class="selector">', '<div id="detail-info" class="detail-info">', '<div class="dashboard-detail-icon-block">', '{[this.renderIconBlock(values)]}', '</div>', '<div class="dashboard-detail-info-block">', '<div class="detail-header-block">', '{[this.renderDetailHeaderBlock(values)]}', '</div>', '<div class="detail-block">', '<div><span class="detail-label">Description:</span> {description:htmlEncode}</span></div><br>', '<div><span class="detail-label">Groups:</span> {[this.renderGroups(values)]}</div>', '<div><span class="detail-label">Created:</span> <span {createdDate:this.renderToolTip}>{prettyCreatedDate:this.renderDate}</span></div>', '<div><span class="detail-label">Author:</span> {[this.renderUserRealName(values)]}</div>', '<div><span class="detail-label">Last Modified:</span> <span {editedDate:this.renderToolTip}>{prettyEditedDate:this.renderDate}</span></div>', '</div>', '</div>', '</div>', '</div>', '</tpl>', { compiled: true, renderDate: function(value) { return value ? value : ''; }, renderToolTip: function (value) { var str = 'data-qtip="' + value + '"'; return str; }, renderUserRealName: function(values) { var createdBy = values.createdBy; return (createdBy.userRealName ? Ext.htmlEncode(createdBy.userRealName) : '') }, renderGroups: function(values) { var groups = values.groups; var stack = values.stack; var retVal = ''; if (!stack && groups && groups.length > 0) { for (var i = -1; ++i < groups.length;) { retVal += Ext.htmlEncode(groups[i].name) + ', '; } retVal = retVal.substring(0, retVal.length - 2); } return retVal; }, renderIconBlock: function(values) { var iconClass = "dashboard-default-icon-layout"; var retVal = '<div class="dashboard-icon ' + iconClass + '"></div>'; return retVal; }, renderDetailHeaderBlock: function(values){ var isGroupDashboard = values.isGroupDashboard; var title = values.name; var retVal = '<div class="dashboard-title-block">'; retVal += '<div class="dashboard-title detail-title">' + Ext.htmlEncode(title) + '</div>'; retVal += (isGroupDashboard) ? '<div>This is a group dashboard.</div>' : ''; retVal += '</div>'; return retVal; } } ), emptyText: 'No dashboard selected', itemSelector: 'div.selector', autoScroll: 'true' }); this.items = [this.viewDashboard]; this.callParent(arguments); }, loadData: function(record) { this.viewDashboard.store.loadData([record], false); this.loadedRecord = record; }, removeData: function() { this.viewDashboard.store.removeAll(false); this.loadedRecord = null; } }); Ext.define('Ozone.components.admin.dashboard.GroupDashboardManagementPanel', { extend: 'Ozone.components.admin.ManagementPanel', alias: ['widget.groupdashboardmanagement','widget.groupdashboardmanagementpanel','widget.Ozone.components.admin.GroupDashboardManagementPanel'], layout: 'fit', cls: 'groupdashboardmanagementpanel', gridDashboards: null, pnlDashboardDetail: null, txtHeading: null, lastAction: null, guid_EditCopyWidget: null, widgetStateHandler: null, dragAndDrop: true, launchesWidgets: true, channel: 'AdminChannel', defaultTitle: 'Group Dashboards', minButtonWidth: 80, detailsAutoOpen: true, initComponent: function() { var me = this; OWF.Preferences.getUserPreference({ namespace: 'owf.admin.DashboardEditCopy', name: 'guid_to_launch', onSuccess: function(result) { me.guid_EditCopyWidget = result.value; }, onFailure: function(err){ /* No op */ me.showAlert('Preferences Error', 'Error looking up Dashboard Editor: ' + err); } }); this.gridDashboards = Ext.create('Ozone.components.admin.grid.DashboardGroupsGrid', { preventHeader: true, region: 'center', border: false }); this.gridDashboards.setBaseParams({ adminEnabled: true, isGroupDashboard: true, isStackDashboard: false }); this.gridDashboards.store.load({ params: { offset: 0, max: this.pageSize } }); this.relayEvents(this.gridDashboards, ['datachanged', 'select', 'deselect', 'itemdblclick']); this.pnlDashboardDetail = Ext.create('Ozone.components.admin.dashboard.DashboardDetailPanel', { layout: { type: 'fit', align: 'stretch' }, region: 'east', preventHeader: true, collapseMode: 'mini', collapsible: true, collapsed: true, split: true, border: false, width: 266 }); this.txtHeading = Ext.create('Ext.toolbar.TextItem', { text: '<span class="heading-bold">'+this.defaultTitle+'</span>' }); this.searchBox = Ext.widget('searchbox'); this.items = [{ xtype: 'panel', layout: 'border', border: false, items: [ this.gridDashboards, this.pnlDashboardDetail ] }]; this.dockedItems = [{ xtype: 'toolbar', dock: 'top', layout: { type: 'hbox', align: 'stretchmax' }, items: [ this.txtHeading, { xtype: 'tbfill' }, this.searchBox ] }, { xtype: 'toolbar', dock: 'bottom', ui: 'footer', defaults: { minWidth: this.minButtonWidth }, items: [{ xtype: 'button', text: 'Create', handler: function(button, evt) { evt.stopPropagation(); me.doCreate(); } }, { xtype: 'button', text: 'Edit', handler: function() { me.doEdit(); } }, { xtype: 'button', text: 'Delete', handler: function(button) { me.doDelete(); } }] }]; this.gridDashboards.store.on( 'load', function(thisStore, records, options){ if ((this.pnlDashboardDetail != null ) && (!this.pnlDashboardDetail.collapsed) && (this.pnlDashboardDetail.loadedRecord != null)){ for(var idx=0; idx < records.length; idx++){ if(records[idx].id == this.pnlDashboardDetail.loadedRecord.id){ this.pnlDashboardDetail.loadData(records[idx]); break; } } } }, this ); this.on( 'datachanged', function(store, opts) { //collapse and clear detail panel if the store is refreshed if (this.pnlDashboardDetail != null ) { this.pnlDashboardDetail.collapse(); this.pnlDashboardDetail.removeData(); } //refresh launch menu if (!this.disableLaunchMenuRefresh) { this.refreshWidgetLaunchMenu(); } }, this ); this.on( 'select', function(rowModel, record, index, opts) { this.pnlDashboardDetail.loadData(record); if (this.pnlDashboardDetail.collapsed && this.detailsAutoOpen) {this.pnlDashboardDetail.expand();} }, this ); this.searchBox.on( 'searchChanged', function(searchbox, value) { var grid = this.gridDashboards; if (grid) { if (!value) this.gridDashboards.clearFilters(); else this.gridDashboards.applyFilter(value, ['name', 'description']); } }, this ); this.on({ 'itemdblclick': { scope: this, fn: this.doEdit } }); this.gridDashboards.getView().on({ itemkeydown: { scope: this, fn: function(view, record, dom, index, evt) { switch(evt.getKey()) { case evt.SPACE: case evt.ENTER: this.doEdit(); } } } }); this.callParent(arguments); OWF.Eventing.subscribe('AdminChannel', owfdojo.hitch(this, function(sender, msg, channel) { if(msg.domain === 'Dashboard') { this.gridDashboards.getBottomToolbar().doRefresh(); } })); this.on( 'afterrender', function() { var splitterEl = this.el.down(".x-collapse-el"); splitterEl.on('click', function() { var collapsed = this.el.down(".x-splitter-collapsed"); if(collapsed) { this.detailsAutoOpen = true; } else { this.detailsAutoOpen = false; } }, this); }, this ); }, onLaunchFailed: function(response) { if (response.error) { this.showAlert('Launch Error', 'Dashboard Editor Launch Failed: ' + response.message); } }, doCreate: function() { var dataString = Ozone.util.toString({ copyFlag: false, isCreate: true, isGroupDashboard: true }); OWF.Launcher.launch({ guid: this.guid_EditCopyWidget, launchOnlyIfClosed: false, data: dataString }, this.onLaunchFailed); }, doEdit: function() { var records = this.gridDashboards.getSelectedDashboards(); if (records && records.length > 0) { for (var i = 0; i < records.length; i++) { var id = records[i].getId();//From Id property of Dashboard Model var dataString = Ozone.util.toString({ id: id, copyFlag: false, isCreate: false, isGroupDashboard: true }); OWF.Launcher.launch({ title: '$1 - ' + records[i].get('name'), titleRegex: /(.*)/, guid: this.guid_EditCopyWidget, launchOnlyIfClosed: false, data: dataString }, this.onLaunchFailed); } } else { this.showAlert("Error", "You must select at least one dashboard to edit"); } }, doDelete: function() { var records = this.gridDashboards.getSelectionModel().getSelection(); if (records && records.length > 0) { var msg = 'This action will permanently delete '; if (records.length == 1) { msg += '<span class="heading-bold">' + Ext.htmlEncode(records[0].data.name) + '</span>.'; } else { msg += 'the selected <span class="heading-bold">' + records.length + ' dashboards</span>.'; } this.showConfirmation('Warning', msg, function(btn, text, opts) { if(btn == 'ok') { var store = this.gridDashboards.getStore(); store.remove(records); var remainingRecords = store.getTotalCount() - records.length; store.on({ write: { fn: function() { if(store.data.items.length == 0 && store.currentPage > 1) { var lastPage = store.getPageFromRecordIndex(remainingRecords - 1); var pageToLoad = (lastPage >= store.currentPage) ? store.currentPage : lastPage; store.loadPage(pageToLoad); } this.gridDashboards.getBottomToolbar().doRefresh(); this.pnlDashboardDetail.removeData(); if(!this.pnlDashboardDetail.collapsed) { this.pnlDashboardDetail.collapse();} this.refreshWidgetLaunchMenu(); }, scope: this, single: true } }); store.save(); } }); } else { this.showAlert("Error", "You must select at least one dashboard to delete"); } } });
Nanonid/tcsolrsvc
webapps/owf/js/owf-group-dashboard-management-widget.js
JavaScript
bsd-3-clause
24,987
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE36_Absolute_Path_Traversal__wchar_t_file_fopen_45.cpp Label Definition File: CWE36_Absolute_Path_Traversal.label.xml Template File: sources-sink-45.tmpl.cpp */ /* * @description * CWE: 36 Absolute Path Traversal * BadSource: file Read input from a file * GoodSource: Full path and file name * Sinks: fopen * BadSink : Open the file named in data using fopen() * Flow Variant: 45 Data flow: data passed as a static global variable from one function to another in the same source file * * */ #include "std_testcase.h" #ifndef _WIN32 #include <wchar.h> #endif #ifdef _WIN32 #define FILENAME "C:\\temp\\file.txt" #else #define FILENAME "/tmp/file.txt" #endif #ifdef _WIN32 #define FOPEN _wfopen #else #define FOPEN fopen #endif namespace CWE36_Absolute_Path_Traversal__wchar_t_file_fopen_45 { static wchar_t * badData; static wchar_t * goodG2BData; #ifndef OMITBAD static void badSink() { wchar_t * data = badData; { FILE *pFile = NULL; /* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */ pFile = FOPEN(data, L"wb+"); if (pFile != NULL) { fclose(pFile); } } } void bad() { wchar_t * data; wchar_t dataBuffer[FILENAME_MAX] = L""; data = dataBuffer; { /* Read input from a file */ size_t dataLen = wcslen(data); FILE * pFile; /* if there is room in data, attempt to read the input from a file */ if (FILENAME_MAX-dataLen > 1) { pFile = fopen(FILENAME, "r"); if (pFile != NULL) { /* POTENTIAL FLAW: Read data from a file */ if (fgetws(data+dataLen, (int)(FILENAME_MAX-dataLen), pFile) == NULL) { printLine("fgetws() failed"); /* Restore NUL terminator if fgetws fails */ data[dataLen] = L'\0'; } fclose(pFile); } } } badData = data; badSink(); } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B() uses the GoodSource with the BadSink */ static void goodG2BSink() { wchar_t * data = goodG2BData; { FILE *pFile = NULL; /* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */ pFile = FOPEN(data, L"wb+"); if (pFile != NULL) { fclose(pFile); } } } static void goodG2B() { wchar_t * data; wchar_t dataBuffer[FILENAME_MAX] = L""; data = dataBuffer; #ifdef _WIN32 /* FIX: Use a fixed, full path and file name */ wcscat(data, L"c:\\temp\\file.txt"); #else /* FIX: Use a fixed, full path and file name */ wcscat(data, L"/tmp/file.txt"); #endif goodG2BData = data; goodG2BSink(); } void good() { goodG2B(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE36_Absolute_Path_Traversal__wchar_t_file_fopen_45; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
JianpingZeng/xcc
xcc/test/juliet/testcases/CWE36_Absolute_Path_Traversal/s04/CWE36_Absolute_Path_Traversal__wchar_t_file_fopen_45.cpp
C++
bsd-3-clause
3,879
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE401_Memory_Leak__new_twoIntsStruct_52b.cpp Label Definition File: CWE401_Memory_Leak__new.label.xml Template File: sources-sinks-52b.tmpl.cpp */ /* * @description * CWE: 401 Memory Leak * BadSource: Allocate data using new * GoodSource: Allocate data on the stack * Sinks: * GoodSink: call delete on data * BadSink : no deallocation of data * Flow Variant: 52 Data flow: data passed as an argument from one function to another to another in three different source files * * */ #include "std_testcase.h" #ifndef _WIN32 #include <wchar.h> #endif namespace CWE401_Memory_Leak__new_twoIntsStruct_52 { #ifndef OMITBAD /* bad function declaration */ void badSink_c(twoIntsStruct * data); void badSink_b(twoIntsStruct * data) { badSink_c(data); } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ void goodG2BSink_c(twoIntsStruct * data); void goodG2BSink_b(twoIntsStruct * data) { goodG2BSink_c(data); } /* goodB2G uses the BadSource with the GoodSink */ void goodB2GSink_c(twoIntsStruct * data); void goodB2GSink_b(twoIntsStruct * data) { goodB2GSink_c(data); } #endif /* OMITGOOD */ } /* close namespace */
JianpingZeng/xcc
xcc/test/juliet/testcases/CWE401_Memory_Leak/s02/CWE401_Memory_Leak__new_twoIntsStruct_52b.cpp
C++
bsd-3-clause
1,293
/*********************************************************************** * Copyright (c) 2009, Secure Endpoints 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. * * 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 <config.h> #include <roken.h> #include <strsafe.h> #ifndef _WIN32 #error This implementation is Windows specific. #endif /** * wait_for_process_timed waits for a process to terminate or until a * specified timeout occurs. * * @param[in] pid Process id for the monitored process * @param[in] func Timeout callback function. When the wait times out, * the callback function is called. The possible return values * from the callback function are: * * - ((time_t) -2) Exit loop without killing child and return SE_E_EXECTIMEOUT. * - ((time_t) -1) Kill child with SIGTERM and wait for child to exit. * - 0 Don't timeout again * - n Seconds to next timeout * * @param[in] ptr Optional parameter for func() * * @param[in] timeout Seconds to first timeout. * * @retval SE_E_UNSPECIFIED Unspecified system error * @retval SE_E_FORKFAILED Fork failure (not applicable for _WIN32 targets) * @retval SE_E_WAITPIDFAILED waitpid errors * @retval SE_E_EXECTIMEOUT exec timeout * @retval 0 <= Return value from subprocess * @retval SE_E_NOTFOUND The program coudln't be found * @retval 128- The signal that killed the subprocess +128. */ ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL wait_for_process_timed(pid_t pid, time_t (*func)(void *), void *ptr, time_t timeout) { HANDLE hProcess; DWORD wrv = 0; DWORD dtimeout; int rv = 0; hProcess = OpenProcess(SYNCHRONIZE, FALSE, pid); if (hProcess == NULL) { return SE_E_WAITPIDFAILED; } dtimeout = (DWORD) ((timeout == 0)? INFINITE: timeout * 1000); do { wrv = WaitForSingleObject(hProcess, dtimeout); if (wrv == WAIT_OBJECT_0) { DWORD prv = 0; GetExitCodeProcess(hProcess, &prv); rv = (int) prv; break; } else if (wrv == WAIT_TIMEOUT) { if (func == NULL) continue; timeout = (*func)(ptr); if (timeout == (time_t)-1) { if (TerminateProcess(hProcess, 128 + 9)) { dtimeout = INFINITE; continue; } rv = SE_E_UNSPECIFIED; break; } else if (timeout == (time_t) -2) { rv = SE_E_EXECTIMEOUT; break; } else { dtimeout = (DWORD) ((timeout == 0)? INFINITE: timeout * 1000); continue; } } else { rv = SE_E_UNSPECIFIED; break; } } while(TRUE); CloseHandle(hProcess); return rv; } ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL wait_for_process(pid_t pid) { return wait_for_process_timed(pid, NULL, NULL, 0); } static char * collect_commandline(const char * fn, va_list * ap) { size_t len = 0; size_t alloc_len = 0; const char * s; char * cmd = NULL; for (s = fn; s; s = (char *) va_arg(*ap, char *)) { size_t cmp_len; int need_quote = FALSE; if (FAILED(StringCchLength(s, MAX_PATH, &cmp_len))) { if (cmd) free(cmd); return NULL; } if (cmp_len == 0) continue; if (strchr(s, ' ') && /* need to quote any component that has embedded spaces, but not if they are already quoted. */ s[0] != '"' && s[cmp_len - 1] != '"') { need_quote = TRUE; cmp_len += 2 * sizeof(char); } if (s != fn) cmp_len += 1 * sizeof(char); if (alloc_len < len + cmp_len + 1) { char * nc; alloc_len += ((len + cmp_len - alloc_len) / MAX_PATH + 1) * MAX_PATH; nc = (char *) realloc(cmd, alloc_len * sizeof(char)); if (nc == NULL) { if (cmd) free(cmd); return NULL; } } if (cmd == NULL) return NULL; if (s != fn) cmd[len++] = ' '; if (need_quote) { StringCchPrintf(cmd + len, alloc_len - len, "\"%s\"", s); } else { StringCchCopy(cmd + len, alloc_len - len, s); } len += cmp_len; } return cmd; } ROKEN_LIB_FUNCTION pid_t ROKEN_LIB_CALL pipe_execv(FILE **stdin_fd, FILE **stdout_fd, FILE **stderr_fd, const char *file, ...) { HANDLE hOut_r = NULL; HANDLE hOut_w = NULL; HANDLE hIn_r = NULL; HANDLE hIn_w = NULL; HANDLE hErr_r = NULL; HANDLE hErr_w = NULL; SECURITY_ATTRIBUTES sa; STARTUPINFO si; PROCESS_INFORMATION pi; char * commandline = NULL; pid_t rv = (pid_t) -1; { va_list ap; va_start(ap, file); commandline = collect_commandline(file, &ap); if (commandline == NULL) return rv; } ZeroMemory(&si, sizeof(si)); ZeroMemory(&pi, sizeof(pi)); ZeroMemory(&sa, sizeof(sa)); pi.hProcess = NULL; pi.hThread = NULL; sa.nLength = sizeof(sa); sa.bInheritHandle = TRUE; sa.lpSecurityDescriptor = NULL; if ((stdout_fd && !CreatePipe(&hOut_r, &hOut_w, &sa, 0 /* Use default */)) || (stdin_fd && !CreatePipe(&hIn_r, &hIn_w, &sa, 0)) || (stderr_fd && !CreatePipe(&hErr_r, &hErr_w, &sa, 0)) || (!stdout_fd && (hOut_w = CreateFile("CON", GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, &sa, OPEN_EXISTING, 0, NULL)) == INVALID_HANDLE_VALUE) || (!stdin_fd && (hIn_r = CreateFile("CON",GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, &sa, OPEN_EXISTING, 0, NULL)) == INVALID_HANDLE_VALUE) || (!stderr_fd && (hErr_w = CreateFile("CON", GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, &sa, OPEN_EXISTING, 0, NULL)) == INVALID_HANDLE_VALUE)) goto _exit; /* We don't want the child processes inheriting these */ if (hOut_r) SetHandleInformation(hOut_r, HANDLE_FLAG_INHERIT, FALSE); if (hIn_w) SetHandleInformation(hIn_w, HANDLE_FLAG_INHERIT, FALSE); if (hErr_r) SetHandleInformation(hErr_r, HANDLE_FLAG_INHERIT, FALSE); si.cb = sizeof(si); si.lpReserved = NULL; si.lpDesktop = NULL; si.lpTitle = NULL; si.dwFlags = STARTF_USESTDHANDLES; si.hStdInput = hIn_r; si.hStdOutput = hOut_w; si.hStdError = hErr_w; if (!CreateProcess(file, commandline, NULL, NULL, TRUE, /* bInheritHandles */ CREATE_NO_WINDOW, /* dwCreationFlags */ NULL, /* lpEnvironment */ NULL, /* lpCurrentDirectory */ &si, &pi)) { rv = (pid_t) (GetLastError() == ERROR_FILE_NOT_FOUND)? 127 : -1; goto _exit; } if (stdin_fd) { *stdin_fd = _fdopen(_open_osfhandle((intptr_t) hIn_w, 0), "wb"); if (*stdin_fd) hIn_w = NULL; } if (stdout_fd) { *stdout_fd = _fdopen(_open_osfhandle((intptr_t) hOut_r, _O_RDONLY), "rb"); if (*stdout_fd) hOut_r = NULL; } if (stderr_fd) { *stderr_fd = _fdopen(_open_osfhandle((intptr_t) hErr_r, _O_RDONLY), "rb"); if (*stderr_fd) hErr_r = NULL; } rv = (pid_t) pi.dwProcessId; _exit: if (pi.hProcess) CloseHandle(pi.hProcess); if (pi.hThread) CloseHandle(pi.hThread); if (hIn_r) CloseHandle(hIn_r); if (hIn_w) CloseHandle(hIn_w); if (hOut_r) CloseHandle(hOut_r); if (hOut_w) CloseHandle(hOut_w); if (hErr_r) CloseHandle(hErr_r); if (hErr_w) CloseHandle(hErr_w); return rv; } ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL simple_execvp_timed(const char *file, char *const args[], time_t (*func)(void *), void *ptr, time_t timeout) { intptr_t hp; int rv; hp = spawnvp(_P_NOWAIT, file, args); if (hp == -1) return (errno == ENOENT)? 127: 126; else if (hp == 0) return 0; rv = wait_for_process_timed(GetProcessId((HANDLE) hp), func, ptr, timeout); CloseHandle((HANDLE) hp); return rv; } ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL simple_execvp(const char *file, char *const args[]) { return simple_execvp_timed(file, args, NULL, NULL, 0); } ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL simple_execve_timed(const char *file, char *const args[], char *const envp[], time_t (*func)(void *), void *ptr, time_t timeout) { intptr_t hp; int rv; hp = spawnve(_P_NOWAIT, file, args, envp); if (hp == -1) return (errno == ENOENT)? 127: 126; else if (hp == 0) return 0; rv = wait_for_process_timed(GetProcessId((HANDLE) hp), func, ptr, timeout); CloseHandle((HANDLE) hp); return rv; } ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL simple_execve(const char *file, char *const args[], char *const envp[]) { return simple_execve_timed(file, args, envp, NULL, NULL, 0); } ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL simple_execlp(const char *file, ...) { va_list ap; char **argv; int ret; va_start(ap, file); argv = vstrcollect(&ap); va_end(ap); if(argv == NULL) return SE_E_UNSPECIFIED; ret = simple_execvp(file, argv); free(argv); return ret; } ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL simple_execle(const char *file, ... /* ,char *const envp[] */) { va_list ap; char **argv; char *const* envp; int ret; va_start(ap, file); argv = vstrcollect(&ap); envp = va_arg(ap, char **); va_end(ap); if(argv == NULL) return SE_E_UNSPECIFIED; ret = simple_execve(file, argv, envp); free(argv); return ret; }
pexip/os-heimdal
lib/roken/simple_exec_w32.c
C
bsd-3-clause
10,338
/* * Copyright (c) 2007-2009 The LIBLINEAR Project. * 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. * * 3. Neither name of copyright holders 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 REGENTS 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. */ #ifndef DOXYGEN_SHOULD_SKIP_THIS #ifndef _LIBLINEAR_H #define _LIBLINEAR_H #include <shogun/lib/config.h> #include <shogun/optimization/liblinear/tron.h> #include <shogun/features/DotFeatures.h> namespace shogun { #undef I #ifdef __cplusplus extern "C" { #endif /** problem */ struct liblinear_problem { /** l */ int32_t l; /** n */ int32_t n; /** y */ float64_t* y; /** sparse features x */ std::shared_ptr<DotFeatures> x; /** if bias shall be used */ bool use_bias; }; /** parameter */ struct liblinear_parameter { /** solver type */ int32_t solver_type; /* these are for training only */ /** stopping criteria */ float64_t eps; /** C */ float64_t C; /** number of weights */ int32_t nr_weight; /** weight label */ int32_t *weight_label; /** weight */ float64_t* weight; }; /** model */ struct liblinear_model { /** parameter */ struct liblinear_parameter param; /** number of classes */ int32_t nr_class; /** number of features */ int32_t nr_feature; /** w */ float64_t *w; /** label of each class (label[n]) */ int32_t *label; /** bias */ float64_t bias; }; void destroy_model(struct liblinear_model *model_); void destroy_param(struct liblinear_parameter *param); #ifdef __cplusplus } #endif /** class l2loss_svm_vun */ class l2loss_svm_fun : public function { public: /** constructor * * @param prob prob * @param Cp Cp * @param Cn Cn */ l2loss_svm_fun(const liblinear_problem *prob, float64_t Cp, float64_t Cn); ~l2loss_svm_fun(); /** fun * * @param w w * @return something floaty */ float64_t fun(float64_t *w); /** grad * * @param w w * @param g g */ void grad(float64_t *w, float64_t *g); /** Hv * * @param s s * @param Hs Hs */ void Hv(float64_t *s, float64_t *Hs); /** get number of variables * * @return number of variables */ int32_t get_nr_variable(); private: void Xv(float64_t *v, float64_t *Xv); void subXv(float64_t *v, float64_t *Xv); void subXTv(float64_t *v, float64_t *XTv); float64_t *C; float64_t *z; float64_t *D; int32_t *I; int32_t sizeI; const liblinear_problem *prob; }; /** class l2r_lr_fun */ class l2r_lr_fun : public function { public: /** constructor * * @param prob prob * @param Cp Cp * @param Cn Cn */ l2r_lr_fun(const liblinear_problem *prob, float64_t* C); ~l2r_lr_fun(); /** fun * * @param w w * @return something floaty */ float64_t fun(float64_t *w); /** grad * * @param w w * @param g g */ void grad(float64_t *w, float64_t *g); /** Hv * * @param s s * @param Hs Hs */ void Hv(float64_t *s, float64_t *Hs); int32_t get_nr_variable(); private: void Xv(float64_t *v, float64_t *Xv); void XTv(float64_t *v, float64_t *XTv); float64_t *C; float64_t *z; float64_t *D; const liblinear_problem *m_prob; }; class l2r_l2_svc_fun : public function { public: l2r_l2_svc_fun(const liblinear_problem *prob, float64_t* Cs); ~l2r_l2_svc_fun(); double fun(double *w); void grad(double *w, double *g); void Hv(double *s, double *Hs); int get_nr_variable(); protected: void Xv(double *v, double *Xv); void subXv(double *v, double *Xv); void subXTv(double *v, double *XTv); double *C; double *z; double *D; int *I; int sizeI; const liblinear_problem *m_prob; }; class l2r_l2_svr_fun: public l2r_l2_svc_fun { public: l2r_l2_svr_fun(const liblinear_problem *prob, double *Cs, double p); double fun(double *w); void grad(double *w, double *g); private: double m_p; }; struct mcsvm_state { double* w; double* B; double* G; double* alpha; double* alpha_new; int* index; double* QD; int* d_ind; double* d_val; int* alpha_index; int* y_index; int* active_size_i; bool allocated,inited; mcsvm_state() { w = NULL; B = NULL; G = NULL; alpha = NULL; alpha_new = NULL; index = NULL; QD = NULL; d_ind = NULL; d_val = NULL; alpha_index = NULL; y_index = NULL; active_size_i = NULL; allocated = false; inited = false; } ~mcsvm_state() { SG_FREE(w); SG_FREE(B); SG_FREE(G); SG_FREE(alpha); SG_FREE(alpha_new); SG_FREE(index); SG_FREE(QD); SG_FREE(d_ind); SG_FREE(d_val); SG_FREE(alpha_index); SG_FREE(y_index); SG_FREE(active_size_i); } }; class Solver_MCSVM_CS { public: Solver_MCSVM_CS(const liblinear_problem *prob, int nr_class, double *C, double *w0, double eps, int max_iter, double train_time, mcsvm_state* given_state); ~Solver_MCSVM_CS(); template <typename PRNG> void solve(PRNG& prng); private: void solve_sub_problem(double A_i, int yi, double C_yi, int active_i, double *alpha_new); bool be_shrunk(int i, int m, int yi, double alpha_i, double minG); double *C; int w_size, l; int nr_class; int max_iter; double eps; double max_train_time; double* w0; const liblinear_problem *prob; mcsvm_state* state; }; } #endif //_LIBLINEAR_H #endif // DOXYGEN_SHOULD_SKIP_THIS
besser82/shogun
src/shogun/optimization/liblinear/shogun_liblinear.h
C
bsd-3-clause
6,507
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_memcpy_22a.c Label Definition File: CWE122_Heap_Based_Buffer_Overflow__c_CWE805.label.xml Template File: sources-sink-22a.tmpl.c */ /* * @description * CWE: 122 Heap Based Buffer Overflow * BadSource: Allocate using malloc() and set data pointer to a small buffer * GoodSource: Allocate using malloc() and set data pointer to a large buffer * Sink: memcpy * BadSink : Copy twoIntsStruct array to data using memcpy * Flow Variant: 22 Control flow: Flow controlled by value of a global variable. Sink functions are in a separate file from sources. * * */ #include "std_testcase.h" #ifndef OMITBAD /* The global variable below is used to drive control flow in the source function */ int CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_memcpy_22_badGlobal = 0; twoIntsStruct * CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_memcpy_22_badSource(twoIntsStruct * data); void CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_memcpy_22_bad() { twoIntsStruct * data; data = NULL; CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_memcpy_22_badGlobal = 1; /* true */ data = CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_memcpy_22_badSource(data); { twoIntsStruct source[100]; { size_t i; /* Initialize array */ for (i = 0; i < 100; i++) { source[i].intOne = 0; source[i].intTwo = 0; } } /* POTENTIAL FLAW: Possible buffer overflow if data < 100 */ memcpy(data, source, 100*sizeof(twoIntsStruct)); printStructLine(&data[0]); free(data); } } #endif /* OMITBAD */ #ifndef OMITGOOD /* The global variables below are used to drive control flow in the source functions. */ int CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_memcpy_22_goodG2B1Global = 0; int CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_memcpy_22_goodG2B2Global = 0; /* goodG2B1() - use goodsource and badsink by setting the static variable to false instead of true */ twoIntsStruct * CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_memcpy_22_goodG2B1Source(twoIntsStruct * data); static void goodG2B1() { twoIntsStruct * data; data = NULL; CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_memcpy_22_goodG2B1Global = 0; /* false */ data = CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_memcpy_22_goodG2B1Source(data); { twoIntsStruct source[100]; { size_t i; /* Initialize array */ for (i = 0; i < 100; i++) { source[i].intOne = 0; source[i].intTwo = 0; } } /* POTENTIAL FLAW: Possible buffer overflow if data < 100 */ memcpy(data, source, 100*sizeof(twoIntsStruct)); printStructLine(&data[0]); free(data); } } /* goodG2B2() - use goodsource and badsink by reversing the blocks in the if in the source function */ twoIntsStruct * CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_memcpy_22_goodG2B2Source(twoIntsStruct * data); static void goodG2B2() { twoIntsStruct * data; data = NULL; CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_memcpy_22_goodG2B2Global = 1; /* true */ data = CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_memcpy_22_goodG2B2Source(data); { twoIntsStruct source[100]; { size_t i; /* Initialize array */ for (i = 0; i < 100; i++) { source[i].intOne = 0; source[i].intTwo = 0; } } /* POTENTIAL FLAW: Possible buffer overflow if data < 100 */ memcpy(data, source, 100*sizeof(twoIntsStruct)); printStructLine(&data[0]); free(data); } } void CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_memcpy_22_good() { goodG2B1(); goodG2B2(); } #endif /* OMITGOOD */ /* Below is the main(). It is only used when building this testcase on * its own for testing or for building a binary to use in testing binary * analysis tools. It is not used when compiling all the testcases as one * application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_memcpy_22_good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_memcpy_22_bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
JianpingZeng/xcc
xcc/test/juliet/testcases/CWE122_Heap_Based_Buffer_Overflow/s08/CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_memcpy_22a.c
C
bsd-3-clause
4,955
// 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. #include "chrome/browser/chromeos/login/users/chrome_user_manager_impl.h" #include <cstddef> #include <set> #include "ash/multi_profile_uma.h" #include "base/bind.h" #include "base/bind_helpers.h" #include "base/command_line.h" #include "base/compiler_specific.h" #include "base/format_macros.h" #include "base/logging.h" #include "base/metrics/histogram.h" #include "base/prefs/pref_registry_simple.h" #include "base/prefs/pref_service.h" #include "base/prefs/scoped_user_pref_update.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/thread_task_runner_handle.h" #include "base/values.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/chromeos/login/demo_mode/demo_app_launcher.h" #include "chrome/browser/chromeos/login/session/user_session_manager.h" #include "chrome/browser/chromeos/login/signin/auth_sync_observer.h" #include "chrome/browser/chromeos/login/signin/auth_sync_observer_factory.h" #include "chrome/browser/chromeos/login/users/avatar/user_image_manager_impl.h" #include "chrome/browser/chromeos/login/users/multi_profile_user_controller.h" #include "chrome/browser/chromeos/login/users/supervised_user_manager_impl.h" #include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h" #include "chrome/browser/chromeos/policy/device_local_account.h" #include "chrome/browser/chromeos/profiles/multiprofiles_session_aborted_dialog.h" #include "chrome/browser/chromeos/profiles/profile_helper.h" #include "chrome/browser/chromeos/session_length_limiter.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/supervised_user/chromeos/manager_password_service_factory.h" #include "chrome/browser/supervised_user/chromeos/supervised_user_password_service_factory.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/crash_keys.h" #include "chrome/common/pref_names.h" #include "chrome/grit/theme_resources.h" #include "chromeos/chromeos_switches.h" #include "chromeos/login/user_names.h" #include "chromeos/settings/cros_settings_names.h" #include "components/session_manager/core/session_manager.h" #include "components/user_manager/remove_user_delegate.h" #include "components/user_manager/user_image/user_image.h" #include "components/user_manager/user_type.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/notification_service.h" #include "policy/policy_constants.h" #include "ui/base/resource/resource_bundle.h" #include "ui/wm/core/wm_core_switches.h" using content::BrowserThread; namespace chromeos { namespace { // A vector pref of the the regular users known on this device, arranged in LRU // order. const char kRegularUsers[] = "LoggedInUsers"; // A vector pref of the public accounts defined on this device. const char kPublicAccounts[] = "PublicAccounts"; // A string pref that gets set when a public account is removed but a user is // currently logged into that account, requiring the account's data to be // removed after logout. const char kPublicAccountPendingDataRemoval[] = "PublicAccountPendingDataRemoval"; } // namespace // static void ChromeUserManagerImpl::RegisterPrefs(PrefRegistrySimple* registry) { ChromeUserManager::RegisterPrefs(registry); registry->RegisterListPref(kPublicAccounts); registry->RegisterStringPref(kPublicAccountPendingDataRemoval, std::string()); SupervisedUserManager::RegisterPrefs(registry); SessionLengthLimiter::RegisterPrefs(registry); } // static scoped_ptr<ChromeUserManager> ChromeUserManagerImpl::CreateChromeUserManager() { return scoped_ptr<ChromeUserManager>(new ChromeUserManagerImpl()); } ChromeUserManagerImpl::ChromeUserManagerImpl() : ChromeUserManager(base::ThreadTaskRunnerHandle::Get(), BrowserThread::GetBlockingPool()), cros_settings_(CrosSettings::Get()), device_local_account_policy_service_(NULL), supervised_user_manager_(new SupervisedUserManagerImpl(this)), weak_factory_(this) { UpdateNumberOfUsers(); // UserManager instance should be used only on UI thread. DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); registrar_.Add(this, chrome::NOTIFICATION_OWNERSHIP_STATUS_CHANGED, content::NotificationService::AllSources()); registrar_.Add(this, chrome::NOTIFICATION_LOGIN_USER_PROFILE_PREPARED, content::NotificationService::AllSources()); registrar_.Add(this, chrome::NOTIFICATION_PROFILE_CREATED, content::NotificationService::AllSources()); // Since we're in ctor postpone any actions till this is fully created. if (base::MessageLoop::current()) { base::MessageLoop::current()->PostTask( FROM_HERE, base::Bind(&ChromeUserManagerImpl::RetrieveTrustedDevicePolicies, weak_factory_.GetWeakPtr())); } local_accounts_subscription_ = cros_settings_->AddSettingsObserver( kAccountsPrefDeviceLocalAccounts, base::Bind(&ChromeUserManagerImpl::RetrieveTrustedDevicePolicies, weak_factory_.GetWeakPtr())); multi_profile_user_controller_.reset( new MultiProfileUserController(this, GetLocalState())); policy::BrowserPolicyConnectorChromeOS* connector = g_browser_process->platform_part()->browser_policy_connector_chromeos(); avatar_policy_observer_.reset(new policy::CloudExternalDataPolicyObserver( cros_settings_, connector->GetDeviceLocalAccountPolicyService(), policy::key::kUserAvatarImage, this)); avatar_policy_observer_->Init(); wallpaper_policy_observer_.reset(new policy::CloudExternalDataPolicyObserver( cros_settings_, connector->GetDeviceLocalAccountPolicyService(), policy::key::kWallpaperImage, this)); wallpaper_policy_observer_->Init(); } ChromeUserManagerImpl::~ChromeUserManagerImpl() { } void ChromeUserManagerImpl::Shutdown() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); ChromeUserManager::Shutdown(); local_accounts_subscription_.reset(); // Stop the session length limiter. session_length_limiter_.reset(); if (device_local_account_policy_service_) device_local_account_policy_service_->RemoveObserver(this); for (UserImageManagerMap::iterator it = user_image_managers_.begin(), ie = user_image_managers_.end(); it != ie; ++it) { it->second->Shutdown(); } multi_profile_user_controller_.reset(); avatar_policy_observer_.reset(); wallpaper_policy_observer_.reset(); registrar_.RemoveAll(); } MultiProfileUserController* ChromeUserManagerImpl::GetMultiProfileUserController() { return multi_profile_user_controller_.get(); } UserImageManager* ChromeUserManagerImpl::GetUserImageManager( const std::string& user_id) { UserImageManagerMap::iterator ui = user_image_managers_.find(user_id); if (ui != user_image_managers_.end()) return ui->second.get(); linked_ptr<UserImageManagerImpl> mgr(new UserImageManagerImpl(user_id, this)); user_image_managers_[user_id] = mgr; return mgr.get(); } SupervisedUserManager* ChromeUserManagerImpl::GetSupervisedUserManager() { return supervised_user_manager_.get(); } user_manager::UserList ChromeUserManagerImpl::GetUsersAdmittedForMultiProfile() const { // Supervised users are not allowed to use multi-profiles. if (GetLoggedInUsers().size() == 1 && GetPrimaryUser()->GetType() != user_manager::USER_TYPE_REGULAR) { return user_manager::UserList(); } user_manager::UserList result; const user_manager::UserList& users = GetUsers(); for (user_manager::UserList::const_iterator it = users.begin(); it != users.end(); ++it) { if ((*it)->GetType() == user_manager::USER_TYPE_REGULAR && !(*it)->is_logged_in()) { MultiProfileUserController::UserAllowedInSessionReason check; multi_profile_user_controller_->IsUserAllowedInSession((*it)->email(), &check); if (check == MultiProfileUserController::NOT_ALLOWED_PRIMARY_USER_POLICY_FORBIDS) { return user_manager::UserList(); } // Users with a policy that prevents them being added to a session will be // shown in login UI but will be grayed out. // Same applies to owner account (see http://crbug.com/385034). if (check == MultiProfileUserController::ALLOWED || check == MultiProfileUserController::NOT_ALLOWED_POLICY_FORBIDS || check == MultiProfileUserController::NOT_ALLOWED_OWNER_AS_SECONDARY || check == MultiProfileUserController::NOT_ALLOWED_POLICY_CERT_TAINTED) { result.push_back(*it); } } } return result; } user_manager::UserList ChromeUserManagerImpl::GetUnlockUsers() const { const user_manager::UserList& logged_in_users = GetLoggedInUsers(); if (logged_in_users.empty()) return user_manager::UserList(); user_manager::UserList unlock_users; Profile* profile = ProfileHelper::Get()->GetProfileByUserUnsafe(GetPrimaryUser()); std::string primary_behavior = profile->GetPrefs()->GetString(prefs::kMultiProfileUserBehavior); // Specific case: only one logged in user or // primary user has primary-only multi-profile policy. if (logged_in_users.size() == 1 || primary_behavior == MultiProfileUserController::kBehaviorPrimaryOnly) { if (GetPrimaryUser()->can_lock()) unlock_users.push_back(primary_user_); } else { // Fill list of potential unlock users based on multi-profile policy state. for (user_manager::UserList::const_iterator it = logged_in_users.begin(); it != logged_in_users.end(); ++it) { user_manager::User* user = (*it); Profile* profile = ProfileHelper::Get()->GetProfileByUserUnsafe(user); const std::string behavior = profile->GetPrefs()->GetString(prefs::kMultiProfileUserBehavior); if (behavior == MultiProfileUserController::kBehaviorUnrestricted && user->can_lock()) { unlock_users.push_back(user); } else if (behavior == MultiProfileUserController::kBehaviorPrimaryOnly) { NOTREACHED() << "Spotted primary-only multi-profile policy for non-primary user"; } } } return unlock_users; } void ChromeUserManagerImpl::SessionStarted() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); ChromeUserManager::SessionStarted(); content::NotificationService::current()->Notify( chrome::NOTIFICATION_SESSION_STARTED, content::Source<UserManager>(this), content::Details<const user_manager::User>(GetActiveUser())); } void ChromeUserManagerImpl::RemoveUserInternal( const std::string& user_email, user_manager::RemoveUserDelegate* delegate) { CrosSettings* cros_settings = CrosSettings::Get(); const base::Closure& callback = base::Bind(&ChromeUserManagerImpl::RemoveUserInternal, weak_factory_.GetWeakPtr(), user_email, delegate); // Ensure the value of owner email has been fetched. if (CrosSettingsProvider::TRUSTED != cros_settings->PrepareTrustedValues(callback)) { // Value of owner email is not fetched yet. RemoveUserInternal will be // called again after fetch completion. return; } std::string owner; cros_settings->GetString(kDeviceOwner, &owner); if (user_email == owner) { // Owner is not allowed to be removed from the device. return; } RemoveNonOwnerUserInternal(user_email, delegate); } void ChromeUserManagerImpl::SaveUserOAuthStatus( const std::string& user_id, user_manager::User::OAuthTokenStatus oauth_token_status) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); ChromeUserManager::SaveUserOAuthStatus(user_id, oauth_token_status); GetUserFlow(user_id)->HandleOAuthTokenStatusChange(oauth_token_status); } void ChromeUserManagerImpl::SaveUserDisplayName( const std::string& user_id, const base::string16& display_name) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); ChromeUserManager::SaveUserDisplayName(user_id, display_name); // Do not update local state if data stored or cached outside the user's // cryptohome is to be treated as ephemeral. if (!IsUserNonCryptohomeDataEphemeral(user_id)) supervised_user_manager_->UpdateManagerName(user_id, display_name); } void ChromeUserManagerImpl::StopPolicyObserverForTesting() { avatar_policy_observer_.reset(); wallpaper_policy_observer_.reset(); } void ChromeUserManagerImpl::Observe( int type, const content::NotificationSource& source, const content::NotificationDetails& details) { switch (type) { case chrome::NOTIFICATION_OWNERSHIP_STATUS_CHANGED: if (!device_local_account_policy_service_) { policy::BrowserPolicyConnectorChromeOS* connector = g_browser_process->platform_part() ->browser_policy_connector_chromeos(); device_local_account_policy_service_ = connector->GetDeviceLocalAccountPolicyService(); if (device_local_account_policy_service_) device_local_account_policy_service_->AddObserver(this); } RetrieveTrustedDevicePolicies(); UpdateOwnership(); break; case chrome::NOTIFICATION_LOGIN_USER_PROFILE_PREPARED: { Profile* profile = content::Details<Profile>(details).ptr(); if (IsUserLoggedIn() && !IsLoggedInAsGuest() && !IsLoggedInAsKioskApp()) { if (IsLoggedInAsSupervisedUser()) SupervisedUserPasswordServiceFactory::GetForProfile(profile); if (IsLoggedInAsRegularUser()) ManagerPasswordServiceFactory::GetForProfile(profile); if (!profile->IsOffTheRecord()) { AuthSyncObserver* sync_observer = AuthSyncObserverFactory::GetInstance()->GetForProfile(profile); sync_observer->StartObserving(); multi_profile_user_controller_->StartObserving(profile); } } break; } case chrome::NOTIFICATION_PROFILE_CREATED: { Profile* profile = content::Source<Profile>(source).ptr(); user_manager::User* user = ProfileHelper::Get()->GetUserByProfile(profile); if (user != NULL) user->set_profile_is_created(); // If there is pending user switch, do it now. if (!GetPendingUserSwitchID().empty()) { // Call SwitchActiveUser async because otherwise it may cause // ProfileManager::GetProfile before the profile gets registered // in ProfileManager. It happens in case of sync profile load when // NOTIFICATION_PROFILE_CREATED is called synchronously. base::MessageLoop::current()->PostTask( FROM_HERE, base::Bind(&ChromeUserManagerImpl::SwitchActiveUser, weak_factory_.GetWeakPtr(), GetPendingUserSwitchID())); SetPendingUserSwitchID(std::string()); } break; } default: NOTREACHED(); } } void ChromeUserManagerImpl::OnExternalDataSet(const std::string& policy, const std::string& user_id) { if (policy == policy::key::kUserAvatarImage) GetUserImageManager(user_id)->OnExternalDataSet(policy); else if (policy == policy::key::kWallpaperImage) WallpaperManager::Get()->OnPolicySet(policy, user_id); else NOTREACHED(); } void ChromeUserManagerImpl::OnExternalDataCleared(const std::string& policy, const std::string& user_id) { if (policy == policy::key::kUserAvatarImage) GetUserImageManager(user_id)->OnExternalDataCleared(policy); else if (policy == policy::key::kWallpaperImage) WallpaperManager::Get()->OnPolicyCleared(policy, user_id); else NOTREACHED(); } void ChromeUserManagerImpl::OnExternalDataFetched( const std::string& policy, const std::string& user_id, scoped_ptr<std::string> data) { if (policy == policy::key::kUserAvatarImage) GetUserImageManager(user_id)->OnExternalDataFetched(policy, data.Pass()); else if (policy == policy::key::kWallpaperImage) WallpaperManager::Get()->OnPolicyFetched(policy, user_id, data.Pass()); else NOTREACHED(); } void ChromeUserManagerImpl::OnPolicyUpdated(const std::string& user_id) { const user_manager::User* user = FindUser(user_id); if (!user || user->GetType() != user_manager::USER_TYPE_PUBLIC_ACCOUNT) return; UpdatePublicAccountDisplayName(user_id); } void ChromeUserManagerImpl::OnDeviceLocalAccountsChanged() { // No action needed here, changes to the list of device-local accounts get // handled via the kAccountsPrefDeviceLocalAccounts device setting observer. } bool ChromeUserManagerImpl::CanCurrentUserLock() const { return ChromeUserManager::CanCurrentUserLock() && GetCurrentUserFlow()->CanLockScreen(); } bool ChromeUserManagerImpl::IsUserNonCryptohomeDataEphemeral( const std::string& user_id) const { // Data belonging to the obsolete public accounts whose data has not been // removed yet is not ephemeral. bool is_obsolete_public_account = IsPublicAccountMarkedForRemoval(user_id); return !is_obsolete_public_account && ChromeUserManager::IsUserNonCryptohomeDataEphemeral(user_id); } bool ChromeUserManagerImpl::AreEphemeralUsersEnabled() const { policy::BrowserPolicyConnectorChromeOS* connector = g_browser_process->platform_part()->browser_policy_connector_chromeos(); return GetEphemeralUsersEnabled() && (connector->IsEnterpriseManaged() || !GetOwnerEmail().empty()); } const std::string& ChromeUserManagerImpl::GetApplicationLocale() const { return g_browser_process->GetApplicationLocale(); } PrefService* ChromeUserManagerImpl::GetLocalState() const { return g_browser_process ? g_browser_process->local_state() : NULL; } void ChromeUserManagerImpl::HandleUserOAuthTokenStatusChange( const std::string& user_id, user_manager::User::OAuthTokenStatus status) const { GetUserFlow(user_id)->HandleOAuthTokenStatusChange(status); } bool ChromeUserManagerImpl::IsEnterpriseManaged() const { policy::BrowserPolicyConnectorChromeOS* connector = g_browser_process->platform_part()->browser_policy_connector_chromeos(); return connector->IsEnterpriseManaged(); } void ChromeUserManagerImpl::LoadPublicAccounts( std::set<std::string>* public_sessions_set) { const base::ListValue* prefs_public_sessions = GetLocalState()->GetList(kPublicAccounts); std::vector<std::string> public_sessions; ParseUserList(*prefs_public_sessions, std::set<std::string>(), &public_sessions, public_sessions_set); for (std::vector<std::string>::const_iterator it = public_sessions.begin(); it != public_sessions.end(); ++it) { users_.push_back(user_manager::User::CreatePublicAccountUser(*it)); UpdatePublicAccountDisplayName(*it); } } void ChromeUserManagerImpl::PerformPreUserListLoadingActions() { // Clean up user list first. All code down the path should be synchronous, // so that local state after transaction rollback is in consistent state. // This process also should not trigger EnsureUsersLoaded again. if (supervised_user_manager_->HasFailedUserCreationTransaction()) supervised_user_manager_->RollbackUserCreationTransaction(); } void ChromeUserManagerImpl::PerformPostUserListLoadingActions() { for (user_manager::UserList::iterator ui = users_.begin(), ue = users_.end(); ui != ue; ++ui) { GetUserImageManager((*ui)->email())->LoadUserImage(); } } void ChromeUserManagerImpl::PerformPostUserLoggedInActions( bool browser_restart) { // Initialize the session length limiter and start it only if // session limit is defined by the policy. session_length_limiter_.reset( new SessionLengthLimiter(NULL, browser_restart)); } bool ChromeUserManagerImpl::IsDemoApp(const std::string& user_id) const { return DemoAppLauncher::IsDemoAppSession(user_id); } bool ChromeUserManagerImpl::IsKioskApp(const std::string& user_id) const { policy::DeviceLocalAccount::Type device_local_account_type; return policy::IsDeviceLocalAccountUser(user_id, &device_local_account_type) && device_local_account_type == policy::DeviceLocalAccount::TYPE_KIOSK_APP; } bool ChromeUserManagerImpl::IsPublicAccountMarkedForRemoval( const std::string& user_id) const { return user_id == GetLocalState()->GetString(kPublicAccountPendingDataRemoval); } void ChromeUserManagerImpl::RetrieveTrustedDevicePolicies() { // Local state may not be initialized in unit_tests. if (!GetLocalState()) return; SetEphemeralUsersEnabled(false); SetOwnerEmail(std::string()); // Schedule a callback if device policy has not yet been verified. if (CrosSettingsProvider::TRUSTED != cros_settings_->PrepareTrustedValues( base::Bind(&ChromeUserManagerImpl::RetrieveTrustedDevicePolicies, weak_factory_.GetWeakPtr()))) { return; } bool ephemeral_users_enabled = false; cros_settings_->GetBoolean(kAccountsPrefEphemeralUsersEnabled, &ephemeral_users_enabled); SetEphemeralUsersEnabled(ephemeral_users_enabled); std::string owner_email; cros_settings_->GetString(kDeviceOwner, &owner_email); SetOwnerEmail(owner_email); EnsureUsersLoaded(); bool changed = UpdateAndCleanUpPublicAccounts( policy::GetDeviceLocalAccounts(cros_settings_)); // If ephemeral users are enabled and we are on the login screen, take this // opportunity to clean up by removing all regular users except the owner. if (GetEphemeralUsersEnabled() && !IsUserLoggedIn()) { ListPrefUpdate prefs_users_update(GetLocalState(), kRegularUsers); prefs_users_update->Clear(); for (user_manager::UserList::iterator it = users_.begin(); it != users_.end();) { const std::string user_email = (*it)->email(); if ((*it)->GetType() == user_manager::USER_TYPE_REGULAR && user_email != GetOwnerEmail()) { RemoveNonCryptohomeData(user_email); DeleteUser(*it); it = users_.erase(it); changed = true; } else { if ((*it)->GetType() != user_manager::USER_TYPE_PUBLIC_ACCOUNT) prefs_users_update->Append(new base::StringValue(user_email)); ++it; } } } if (changed) NotifyUserListChanged(); } void ChromeUserManagerImpl::GuestUserLoggedIn() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); ChromeUserManager::GuestUserLoggedIn(); // TODO(nkostylev): Add support for passing guest session cryptohome // mount point. Legacy (--login-profile) value will be used for now. // http://crosbug.com/230859 active_user_->SetStubImage( user_manager::UserImage( *ResourceBundle::GetSharedInstance().GetImageSkiaNamed( IDR_PROFILE_PICTURE_LOADING)), user_manager::User::USER_IMAGE_INVALID, false); // Initializes wallpaper after active_user_ is set. WallpaperManager::Get()->SetUserWallpaperNow(chromeos::login::kGuestUserName); } void ChromeUserManagerImpl::RegularUserLoggedIn(const std::string& user_id) { ChromeUserManager::RegularUserLoggedIn(user_id); if (IsCurrentUserNew()) WallpaperManager::Get()->SetUserWallpaperNow(user_id); GetUserImageManager(user_id)->UserLoggedIn(IsCurrentUserNew(), false); WallpaperManager::Get()->EnsureLoggedInUserWallpaperLoaded(); // Make sure that new data is persisted to Local State. GetLocalState()->CommitPendingWrite(); } void ChromeUserManagerImpl::RegularUserLoggedInAsEphemeral( const std::string& user_id) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); ChromeUserManager::RegularUserLoggedInAsEphemeral(user_id); GetUserImageManager(user_id)->UserLoggedIn(IsCurrentUserNew(), false); WallpaperManager::Get()->SetUserWallpaperNow(user_id); } void ChromeUserManagerImpl::SupervisedUserLoggedIn(const std::string& user_id) { // TODO(nkostylev): Refactor, share code with RegularUserLoggedIn(). // Remove the user from the user list. active_user_ = RemoveRegularOrSupervisedUserFromList(user_id); // If the user was not found on the user list, create a new user. if (!GetActiveUser()) { SetIsCurrentUserNew(true); active_user_ = user_manager::User::CreateSupervisedUser(user_id); // Leaving OAuth token status at the default state = unknown. WallpaperManager::Get()->SetUserWallpaperNow(user_id); } else { if (supervised_user_manager_->CheckForFirstRun(user_id)) { SetIsCurrentUserNew(true); WallpaperManager::Get()->SetUserWallpaperNow(user_id); } else { SetIsCurrentUserNew(false); } } // Add the user to the front of the user list. ListPrefUpdate prefs_users_update(GetLocalState(), kRegularUsers); prefs_users_update->Insert(0, new base::StringValue(user_id)); users_.insert(users_.begin(), active_user_); // Now that user is in the list, save display name. if (IsCurrentUserNew()) { SaveUserDisplayName(GetActiveUser()->email(), GetActiveUser()->GetDisplayName()); } GetUserImageManager(user_id)->UserLoggedIn(IsCurrentUserNew(), true); WallpaperManager::Get()->EnsureLoggedInUserWallpaperLoaded(); // Make sure that new data is persisted to Local State. GetLocalState()->CommitPendingWrite(); } void ChromeUserManagerImpl::PublicAccountUserLoggedIn( user_manager::User* user) { SetIsCurrentUserNew(true); active_user_ = user; // The UserImageManager chooses a random avatar picture when a user logs in // for the first time. Tell the UserImageManager that this user is not new to // prevent the avatar from getting changed. GetUserImageManager(user->email())->UserLoggedIn(false, true); WallpaperManager::Get()->EnsureLoggedInUserWallpaperLoaded(); } void ChromeUserManagerImpl::KioskAppLoggedIn(const std::string& app_id) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); policy::DeviceLocalAccount::Type device_local_account_type; DCHECK(policy::IsDeviceLocalAccountUser(app_id, &device_local_account_type)); DCHECK_EQ(policy::DeviceLocalAccount::TYPE_KIOSK_APP, device_local_account_type); active_user_ = user_manager::User::CreateKioskAppUser(app_id); active_user_->SetStubImage( user_manager::UserImage( *ResourceBundle::GetSharedInstance().GetImageSkiaNamed( IDR_PROFILE_PICTURE_LOADING)), user_manager::User::USER_IMAGE_INVALID, false); WallpaperManager::Get()->SetUserWallpaperNow(app_id); // TODO(bartfab): Add KioskAppUsers to the users_ list and keep metadata like // the kiosk_app_id in these objects, removing the need to re-parse the // device-local account list here to extract the kiosk_app_id. const std::vector<policy::DeviceLocalAccount> device_local_accounts = policy::GetDeviceLocalAccounts(cros_settings_); const policy::DeviceLocalAccount* account = NULL; for (std::vector<policy::DeviceLocalAccount>::const_iterator it = device_local_accounts.begin(); it != device_local_accounts.end(); ++it) { if (it->user_id == app_id) { account = &*it; break; } } std::string kiosk_app_id; if (account) { kiosk_app_id = account->kiosk_app_id; } else { LOG(ERROR) << "Logged into nonexistent kiosk-app account: " << app_id; NOTREACHED(); } CommandLine* command_line = CommandLine::ForCurrentProcess(); command_line->AppendSwitch(::switches::kForceAppMode); command_line->AppendSwitchASCII(::switches::kAppId, kiosk_app_id); // Disable window animation since kiosk app runs in a single full screen // window and window animation causes start-up janks. command_line->AppendSwitch(wm::switches::kWindowAnimationsDisabled); } void ChromeUserManagerImpl::DemoAccountLoggedIn() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); active_user_ = user_manager::User::CreateKioskAppUser(DemoAppLauncher::kDemoUserName); active_user_->SetStubImage( user_manager::UserImage( *ResourceBundle::GetSharedInstance().GetImageSkiaNamed( IDR_PROFILE_PICTURE_LOADING)), user_manager::User::USER_IMAGE_INVALID, false); WallpaperManager::Get()->SetUserWallpaperNow(DemoAppLauncher::kDemoUserName); CommandLine* command_line = CommandLine::ForCurrentProcess(); command_line->AppendSwitch(::switches::kForceAppMode); command_line->AppendSwitchASCII(::switches::kAppId, DemoAppLauncher::kDemoAppId); // Disable window animation since the demo app runs in a single full screen // window and window animation causes start-up janks. CommandLine::ForCurrentProcess()->AppendSwitch( wm::switches::kWindowAnimationsDisabled); } void ChromeUserManagerImpl::RetailModeUserLoggedIn() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); SetIsCurrentUserNew(true); active_user_ = user_manager::User::CreateRetailModeUser(); GetUserImageManager(chromeos::login::kRetailModeUserName) ->UserLoggedIn(IsCurrentUserNew(), true); WallpaperManager::Get()->SetUserWallpaperNow( chromeos::login::kRetailModeUserName); } void ChromeUserManagerImpl::NotifyOnLogin() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); UserSessionManager::OverrideHomedir(); UpdateNumberOfUsers(); ChromeUserManager::NotifyOnLogin(); // TODO(nkostylev): Deprecate this notification in favor of // ActiveUserChanged() observer call. content::NotificationService::current()->Notify( chrome::NOTIFICATION_LOGIN_USER_CHANGED, content::Source<UserManager>(this), content::Details<const user_manager::User>(GetActiveUser())); UserSessionManager::GetInstance()->PerformPostUserLoggedInActions(); } void ChromeUserManagerImpl::UpdateOwnership() { bool is_owner = DeviceSettingsService::Get()->HasPrivateOwnerKey(); VLOG(1) << "Current user " << (is_owner ? "is owner" : "is not owner"); SetCurrentUserIsOwner(is_owner); } void ChromeUserManagerImpl::RemoveNonCryptohomeData( const std::string& user_id) { ChromeUserManager::RemoveNonCryptohomeData(user_id); WallpaperManager::Get()->RemoveUserWallpaperInfo(user_id); GetUserImageManager(user_id)->DeleteUserImage(); supervised_user_manager_->RemoveNonCryptohomeData(user_id); multi_profile_user_controller_->RemoveCachedValues(user_id); } void ChromeUserManagerImpl::CleanUpPublicAccountNonCryptohomeDataPendingRemoval() { PrefService* local_state = GetLocalState(); const std::string public_account_pending_data_removal = local_state->GetString(kPublicAccountPendingDataRemoval); if (public_account_pending_data_removal.empty() || (IsUserLoggedIn() && public_account_pending_data_removal == GetActiveUser()->email())) { return; } RemoveNonCryptohomeData(public_account_pending_data_removal); local_state->ClearPref(kPublicAccountPendingDataRemoval); } void ChromeUserManagerImpl::CleanUpPublicAccountNonCryptohomeData( const std::vector<std::string>& old_public_accounts) { std::set<std::string> users; for (user_manager::UserList::const_iterator it = users_.begin(); it != users_.end(); ++it) users.insert((*it)->email()); // If the user is logged into a public account that has been removed from the // user list, mark the account's data as pending removal after logout. if (IsLoggedInAsPublicAccount()) { const std::string active_user_id = GetActiveUser()->email(); if (users.find(active_user_id) == users.end()) { GetLocalState()->SetString(kPublicAccountPendingDataRemoval, active_user_id); users.insert(active_user_id); } } // Remove the data belonging to any other public accounts that are no longer // found on the user list. for (std::vector<std::string>::const_iterator it = old_public_accounts.begin(); it != old_public_accounts.end(); ++it) { if (users.find(*it) == users.end()) RemoveNonCryptohomeData(*it); } } bool ChromeUserManagerImpl::UpdateAndCleanUpPublicAccounts( const std::vector<policy::DeviceLocalAccount>& device_local_accounts) { // Try to remove any public account data marked as pending removal. CleanUpPublicAccountNonCryptohomeDataPendingRemoval(); // Get the current list of public accounts. std::vector<std::string> old_public_accounts; for (user_manager::UserList::const_iterator it = users_.begin(); it != users_.end(); ++it) { if ((*it)->GetType() == user_manager::USER_TYPE_PUBLIC_ACCOUNT) old_public_accounts.push_back((*it)->email()); } // Get the new list of public accounts from policy. std::vector<std::string> new_public_accounts; for (std::vector<policy::DeviceLocalAccount>::const_iterator it = device_local_accounts.begin(); it != device_local_accounts.end(); ++it) { // TODO(mnissler, nkostylev, bartfab): Process Kiosk Apps within the // standard login framework: http://crbug.com/234694 if (it->type == policy::DeviceLocalAccount::TYPE_PUBLIC_SESSION) new_public_accounts.push_back(it->user_id); } // If the list of public accounts has not changed, return. if (new_public_accounts.size() == old_public_accounts.size()) { bool changed = false; for (size_t i = 0; i < new_public_accounts.size(); ++i) { if (new_public_accounts[i] != old_public_accounts[i]) { changed = true; break; } } if (!changed) return false; } // Persist the new list of public accounts in a pref. ListPrefUpdate prefs_public_accounts_update(GetLocalState(), kPublicAccounts); prefs_public_accounts_update->Clear(); for (std::vector<std::string>::const_iterator it = new_public_accounts.begin(); it != new_public_accounts.end(); ++it) { prefs_public_accounts_update->AppendString(*it); } // Remove the old public accounts from the user list. for (user_manager::UserList::iterator it = users_.begin(); it != users_.end();) { if ((*it)->GetType() == user_manager::USER_TYPE_PUBLIC_ACCOUNT) { if (*it != GetLoggedInUser()) DeleteUser(*it); it = users_.erase(it); } else { ++it; } } // Add the new public accounts to the front of the user list. for (std::vector<std::string>::const_reverse_iterator it = new_public_accounts.rbegin(); it != new_public_accounts.rend(); ++it) { if (IsLoggedInAsPublicAccount() && *it == GetActiveUser()->email()) users_.insert(users_.begin(), GetLoggedInUser()); else users_.insert(users_.begin(), user_manager::User::CreatePublicAccountUser(*it)); UpdatePublicAccountDisplayName(*it); } for (user_manager::UserList::iterator ui = users_.begin(), ue = users_.begin() + new_public_accounts.size(); ui != ue; ++ui) { GetUserImageManager((*ui)->email())->LoadUserImage(); } // Remove data belonging to public accounts that are no longer found on the // user list. CleanUpPublicAccountNonCryptohomeData(old_public_accounts); return true; } void ChromeUserManagerImpl::UpdatePublicAccountDisplayName( const std::string& user_id) { std::string display_name; if (device_local_account_policy_service_) { policy::DeviceLocalAccountPolicyBroker* broker = device_local_account_policy_service_->GetBrokerForUser(user_id); if (broker) display_name = broker->GetDisplayName(); } // Set or clear the display name. SaveUserDisplayName(user_id, base::UTF8ToUTF16(display_name)); } UserFlow* ChromeUserManagerImpl::GetCurrentUserFlow() const { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (!IsUserLoggedIn()) return GetDefaultUserFlow(); return GetUserFlow(GetLoggedInUser()->email()); } UserFlow* ChromeUserManagerImpl::GetUserFlow(const std::string& user_id) const { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); FlowMap::const_iterator it = specific_flows_.find(user_id); if (it != specific_flows_.end()) return it->second; return GetDefaultUserFlow(); } void ChromeUserManagerImpl::SetUserFlow(const std::string& user_id, UserFlow* flow) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); ResetUserFlow(user_id); specific_flows_[user_id] = flow; } void ChromeUserManagerImpl::ResetUserFlow(const std::string& user_id) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); FlowMap::iterator it = specific_flows_.find(user_id); if (it != specific_flows_.end()) { delete it->second; specific_flows_.erase(it); } } bool ChromeUserManagerImpl::AreSupervisedUsersAllowed() const { bool supervised_users_allowed = false; cros_settings_->GetBoolean(kAccountsPrefSupervisedUsersEnabled, &supervised_users_allowed); return supervised_users_allowed; } UserFlow* ChromeUserManagerImpl::GetDefaultUserFlow() const { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (!default_flow_.get()) default_flow_.reset(new DefaultUserFlow()); return default_flow_.get(); } void ChromeUserManagerImpl::NotifyUserListChanged() { content::NotificationService::current()->Notify( chrome::NOTIFICATION_USER_LIST_CHANGED, content::Source<UserManager>(this), content::NotificationService::NoDetails()); } void ChromeUserManagerImpl::NotifyUserAddedToSession( const user_manager::User* added_user, bool user_switch_pending) { if (user_switch_pending) SetPendingUserSwitchID(added_user->email()); UpdateNumberOfUsers(); ChromeUserManager::NotifyUserAddedToSession(added_user, user_switch_pending); } void ChromeUserManagerImpl::OnUserNotAllowed(const std::string& user_email) { LOG(ERROR) << "Shutdown session because a user is not allowed to be in the " "current session"; chromeos::ShowMultiprofilesSessionAbortedDialog(user_email); } void ChromeUserManagerImpl::UpdateNumberOfUsers() { size_t users = GetLoggedInUsers().size(); if (users) { // Write the user number as UMA stat when a multi user session is possible. if ((users + GetUsersAdmittedForMultiProfile().size()) > 1) ash::MultiProfileUMA::RecordUserCount(users); } base::debug::SetCrashKeyValue( crash_keys::kNumberOfUsers, base::StringPrintf("%" PRIuS, GetLoggedInUsers().size())); } } // namespace chromeos
7kbird/chrome
chrome/browser/chromeos/login/users/chrome_user_manager_impl.cc
C++
bsd-3-clause
39,004
/* * pointcloud_publisher_node.cpp * * Created on: Aug 19, 2021 * Author: Edo Jelavic * Institute: ETH Zurich, Robotic Systems Lab */ #include <pcl_conversions/pcl_conversions.h> #include <ros/ros.h> #include <sensor_msgs/PointCloud2.h> #include "grid_map_pcl/helpers.hpp" namespace gm = ::grid_map::grid_map_pcl; using Point = ::pcl::PointXYZ; using PointCloud = ::pcl::PointCloud<Point>; void publishCloud(const std::string& filename, const ros::Publisher& pub, const std::string& frame) { PointCloud::Ptr cloud(new pcl::PointCloud<pcl::PointXYZ>); cloud = gm::loadPointcloudFromPcd(filename); cloud->header.frame_id = frame; sensor_msgs::PointCloud2 msg; pcl::toROSMsg(*cloud, msg); ROS_INFO_STREAM("Publishing loaded cloud, number of points: " << cloud->points.size()); msg.header.stamp = ros::Time::now(); pub.publish(msg); } int main(int argc, char** argv) { ros::init(argc, argv, "point_cloud_pub_node"); ros::NodeHandle nh("~"); const std::string pathToCloud = gm::getPcdFilePath(nh); const std::string cloudFrame = nh.param<std::string>("cloud_frame", ""); // publish cloud ros::Publisher cloudPub = nh.advertise<sensor_msgs::PointCloud2>("raw_pointcloud", 1, true); publishCloud(pathToCloud, cloudPub, cloudFrame); // run ros::spin(); return EXIT_SUCCESS; }
ethz-asl/grid_map
grid_map_pcl/src/pointcloud_publisher_node.cpp
C++
bsd-3-clause
1,327
// 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 CHROME_BROWSER_METRICS_CHROMEOS_METRICS_PROVIDER_H_ #define CHROME_BROWSER_METRICS_CHROMEOS_METRICS_PROVIDER_H_ #include "base/memory/weak_ptr.h" #include "chrome/browser/metrics/perf_provider_chromeos.h" #include "components/metrics/metrics_provider.h" namespace device { class BluetoothAdapter; } namespace metrics { class ChromeUserMetricsExtension; } class PrefRegistrySimple; class PrefService; // Performs ChromeOS specific metrics logging. class ChromeOSMetricsProvider : public metrics::MetricsProvider { public: ChromeOSMetricsProvider(); ~ChromeOSMetricsProvider() override; static void RegisterPrefs(PrefRegistrySimple* registry); // Records a crash. static void LogCrash(const std::string& crash_type); // Loads hardware class information. When this task is complete, |callback| // is run. void InitTaskGetHardwareClass(const base::Closure& callback); // metrics::MetricsProvider: void OnDidCreateMetricsLog() override; void ProvideSystemProfileMetrics( metrics::SystemProfileProto* system_profile_proto) override; void ProvideStabilityMetrics( metrics::SystemProfileProto* system_profile_proto) override; void ProvideGeneralMetrics( metrics::ChromeUserMetricsExtension* uma_proto) override; private: // Called on the FILE thread to load hardware class information. void InitTaskGetHardwareClassOnFileThread(); // Update the number of users logged into a multi-profile session. // If the number of users change while the log is open, the call invalidates // the user count value. void UpdateMultiProfileUserCount( metrics::SystemProfileProto* system_profile_proto); // Sets the Bluetooth Adapter instance used for the WriteBluetoothProto() // call. void SetBluetoothAdapter(scoped_refptr<device::BluetoothAdapter> adapter); // Writes info about paired Bluetooth devices on this system. void WriteBluetoothProto(metrics::SystemProfileProto* system_profile_proto); metrics::PerfProvider perf_provider_; // Bluetooth Adapter instance for collecting information about paired devices. scoped_refptr<device::BluetoothAdapter> adapter_; // Whether the user count was registered at the last log initialization. bool registered_user_count_at_log_initialization_; // The user count at the time that a log was last initialized. Contains a // valid value only if |registered_user_count_at_log_initialization_| is // true. uint64 user_count_at_log_initialization_; // Hardware class (e.g., hardware qualification ID). This class identifies // the configured system components such as CPU, WiFi adapter, etc. std::string hardware_class_; base::WeakPtrFactory<ChromeOSMetricsProvider> weak_ptr_factory_; DISALLOW_COPY_AND_ASSIGN(ChromeOSMetricsProvider); }; #endif // CHROME_BROWSER_METRICS_CHROMEOS_METRICS_PROVIDER_H_
hefen1/chromium
chrome/browser/metrics/chromeos_metrics_provider.h
C
bsd-3-clause
3,015
// Copyright 2019 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 MEDIA_GPU_VAAPI_VAAPI_JPEG_DECODER_H_ #define MEDIA_GPU_VAAPI_VAAPI_JPEG_DECODER_H_ #include <stdint.h> #include <memory> #include "base/macros.h" #include "media/gpu/vaapi/vaapi_image_decoder.h" namespace media { namespace fuzzing { class VaapiJpegDecoderWrapper; } // namespace fuzzing struct JpegFrameHeader; struct JpegParseResult; class ScopedVAImage; // Returns the internal format required for a JPEG image given its parsed // |frame_header|. If the image's subsampling format is not one of 4:2:0, 4:2:2, // or 4:4:4, returns kInvalidVaRtFormat. unsigned int VaSurfaceFormatForJpeg(const JpegFrameHeader& frame_header); class VaapiJpegDecoder : public VaapiImageDecoder { public: VaapiJpegDecoder(); VaapiJpegDecoder(const VaapiJpegDecoder&) = delete; VaapiJpegDecoder& operator=(const VaapiJpegDecoder&) = delete; ~VaapiJpegDecoder() override; // VaapiImageDecoder implementation. gpu::ImageDecodeAcceleratorType GetType() const override; SkYUVColorSpace GetYUVColorSpace() const override; // Get the decoded data from the last Decode() call as a ScopedVAImage. The // VAImage's format will be either |preferred_image_fourcc| if the conversion // from the internal format is supported or a fallback FOURCC (see // VaapiWrapper::GetJpegDecodeSuitableImageFourCC() for details). Returns // nullptr on failure and sets *|status| to the reason for failure. std::unique_ptr<ScopedVAImage> GetImage(uint32_t preferred_image_fourcc, VaapiImageDecodeStatus* status); private: friend class fuzzing::VaapiJpegDecoderWrapper; // VaapiImageDecoder implementation. VaapiImageDecodeStatus AllocateVASurfaceAndSubmitVABuffers( base::span<const uint8_t> encoded_image) override; // AllocateVASurfaceAndSubmitVABuffers() is implemented by calling the // following methods. They are here so that a fuzzer can inject (almost) // arbitrary data into libva by skipping the parsing and image support checks // in AllocateVASurfaceAndSubmitVABuffers(). bool MaybeCreateSurface(unsigned int picture_va_rt_format, const gfx::Size& new_coded_size, const gfx::Size& new_visible_size); bool SubmitBuffers(const JpegParseResult& parse_result); }; } // namespace media #endif // MEDIA_GPU_VAAPI_VAAPI_JPEG_DECODER_H_
youtube/cobalt
third_party/chromium/media/gpu/vaapi/vaapi_jpeg_decoder.h
C
bsd-3-clause
2,534
using System; using Inbox2.Framework; namespace Inbox2.Core.Configuration { public static class CloudApi { public static string ApiBaseUrl { get { return String.Format("http://api{0}.inbox2.com/", String.IsNullOrEmpty(CommandLine.Current.Environment) ? String.Empty : "." + CommandLine.Current.Environment); } } public static string ApplicationKey { get { return "ZABhADQAMgA4AGQAYQAyAA=="; } } public static string AccessToken { get { return SettingsManager.ClientSettings.AppConfiguration.AuthToken; } } } }
Klaudit/inbox2_desktop
Code/Client/Inbox2/Core/Configuration/CloudApi.cs
C#
bsd-3-clause
616
// Copyright 2017 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 "content/browser/payments/payment_app_info_fetcher.h" #include <limits> #include <utility> #include "base/base64.h" #include "base/bind.h" #include "base/callback_helpers.h" #include "components/payments/content/icon/icon_size.h" #include "content/browser/renderer_host/render_frame_host_impl.h" #include "content/browser/service_worker/service_worker_context_wrapper.h" #include "content/browser/web_contents/web_contents_impl.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/global_routing_id.h" #include "content/public/browser/manifest_icon_downloader.h" #include "content/public/browser/page.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/blink/public/common/manifest/manifest_icon_selector.h" #include "third_party/blink/public/common/manifest/manifest_util.h" #include "third_party/blink/public/common/storage_key/storage_key.h" #include "third_party/blink/public/mojom/devtools/console_message.mojom.h" #include "third_party/blink/public/mojom/manifest/manifest.mojom.h" #include "ui/gfx/codec/png_codec.h" #include "url/origin.h" namespace content { PaymentAppInfoFetcher::PaymentAppInfo::PaymentAppInfo() {} PaymentAppInfoFetcher::PaymentAppInfo::~PaymentAppInfo() {} void PaymentAppInfoFetcher::Start( const GURL& context_url, scoped_refptr<ServiceWorkerContextWrapper> service_worker_context, PaymentAppInfoFetchCallback callback) { DCHECK_CURRENTLY_ON(BrowserThread::UI); std::unique_ptr<std::vector<GlobalRenderFrameHostId>> frame_routing_ids = service_worker_context->GetWindowClientFrameRoutingIds( blink::StorageKey(url::Origin::Create(context_url))); SelfDeleteFetcher* fetcher = new SelfDeleteFetcher(std::move(callback)); fetcher->Start(context_url, std::move(frame_routing_ids)); } PaymentAppInfoFetcher::WebContentsHelper::WebContentsHelper( WebContents* web_contents) : WebContentsObserver(web_contents) { DCHECK_CURRENTLY_ON(BrowserThread::UI); } PaymentAppInfoFetcher::WebContentsHelper::~WebContentsHelper() { DCHECK_CURRENTLY_ON(BrowserThread::UI); } PaymentAppInfoFetcher::SelfDeleteFetcher::SelfDeleteFetcher( PaymentAppInfoFetchCallback callback) : fetched_payment_app_info_(std::make_unique<PaymentAppInfo>()), callback_(std::move(callback)) { DCHECK_CURRENTLY_ON(BrowserThread::UI); } PaymentAppInfoFetcher::SelfDeleteFetcher::~SelfDeleteFetcher() { DCHECK_CURRENTLY_ON(BrowserThread::UI); } void PaymentAppInfoFetcher::SelfDeleteFetcher::Start( const GURL& context_url, const std::unique_ptr<std::vector<GlobalRenderFrameHostId>>& frame_routing_ids) { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (frame_routing_ids->empty()) { // Cannot print this error to the developer console, because the appropriate // developer console has not been found. LOG(ERROR) << "Unable to find the top level web content for retrieving the web " "app manifest of a payment handler for \"" << context_url << "\"."; RunCallbackAndDestroy(); return; } for (const auto& frame : *frame_routing_ids) { // Find out the render frame host registering the payment app. Although a // service worker can manage instruments, the first instrument must be set // on a page that has a link to a web app manifest, so it can be fetched // here. RenderFrameHostImpl* render_frame_host = RenderFrameHostImpl::FromID(frame.child_id, frame.frame_routing_id); if (!render_frame_host || context_url.spec().compare( render_frame_host->GetLastCommittedURL().spec()) != 0) { continue; } // Get the main frame since web app manifest is only available in the main // frame's document by definition. The main frame's document must come from // the same origin. RenderFrameHostImpl* top_level_render_frame_host = render_frame_host; while (top_level_render_frame_host->GetParent() != nullptr) { top_level_render_frame_host = top_level_render_frame_host->GetParent(); } WebContentsImpl* top_level_web_content = static_cast<WebContentsImpl*>( WebContents::FromRenderFrameHost(top_level_render_frame_host)); if (!top_level_web_content) { top_level_render_frame_host->AddMessageToConsole( blink::mojom::ConsoleMessageLevel::kError, "Unable to find the web page for \"" + context_url.spec() + "\" to fetch payment handler manifest (for name and icon)."); continue; } if (top_level_web_content->IsHidden()) { top_level_render_frame_host->AddMessageToConsole( blink::mojom::ConsoleMessageLevel::kError, "Unable to fetch payment handler manifest (for name and icon) for " "\"" + context_url.spec() + "\" from a hidden top level web page \"" + top_level_web_content->GetLastCommittedURL().spec() + "\"."); continue; } if (!url::IsSameOriginWith(context_url, top_level_web_content->GetLastCommittedURL())) { top_level_render_frame_host->AddMessageToConsole( blink::mojom::ConsoleMessageLevel::kError, "Unable to fetch payment handler manifest (for name and icon) for " "\"" + context_url.spec() + "\" from a cross-origin top level web page \"" + top_level_web_content->GetLastCommittedURL().spec() + "\"."); continue; } web_contents_helper_ = std::make_unique<WebContentsHelper>(top_level_web_content); top_level_render_frame_host->GetPage().GetManifest( base::BindOnce(&PaymentAppInfoFetcher::SelfDeleteFetcher:: FetchPaymentAppManifestCallback, weak_ptr_factory_.GetWeakPtr())); return; } // Cannot print this error to the developer console, because the appropriate // developer console has not been found. LOG(ERROR) << "Unable to find the top level web content for retrieving the web " "app manifest of a payment handler for \"" << context_url << "\"."; RunCallbackAndDestroy(); } void PaymentAppInfoFetcher::SelfDeleteFetcher::RunCallbackAndDestroy() { DCHECK_CURRENTLY_ON(BrowserThread::UI); base::SequencedTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(std::move(callback_), std::move(fetched_payment_app_info_))); delete this; } void PaymentAppInfoFetcher::SelfDeleteFetcher::FetchPaymentAppManifestCallback( const GURL& url, blink::mojom::ManifestPtr manifest) { DCHECK_CURRENTLY_ON(BrowserThread::UI); manifest_url_ = url; if (manifest_url_.is_empty()) { WarnIfPossible( "The page that installed the payment handler does not contain a web " "app manifest link: <link rel=\"manifest\" " "href=\"some-file-name-here\">. This manifest defines the payment " "handler's name and icon. User may not recognize this payment handler " "in UI, because it will be labeled only by its origin."); RunCallbackAndDestroy(); return; } if (blink::IsEmptyManifest(manifest)) { WarnIfPossible( "Unable to download a valid payment handler web app manifest from \"" + manifest_url_.spec() + "\". This manifest cannot be empty and must in JSON format. The " "manifest defines the payment handler's name and icon. User may not " "recognize this payment handler in UI, because it will be labeled only " "by its origin."); RunCallbackAndDestroy(); return; } fetched_payment_app_info_->prefer_related_applications = manifest->prefer_related_applications; for (const auto& related_application : manifest->related_applications) { fetched_payment_app_info_->related_applications.emplace_back( StoredRelatedApplication()); if (related_application.platform) { base::UTF16ToUTF8( related_application.platform->c_str(), related_application.platform->length(), &(fetched_payment_app_info_->related_applications.back().platform)); } if (related_application.id) { base::UTF16ToUTF8( related_application.id->c_str(), related_application.id->length(), &(fetched_payment_app_info_->related_applications.back().id)); } } if (!manifest->name) { WarnIfPossible("The payment handler's web app manifest \"" + manifest_url_.spec() + "\" does not contain a \"name\" field. User may not " "recognize this payment handler in UI, because it will be " "labeled only by its origin."); } else if (manifest->name->empty()) { WarnIfPossible( "The \"name\" field in the payment handler's web app manifest \"" + manifest_url_.spec() + "\" is empty. User may not recognize this payment handler in UI, " "because it will be labeled only by its origin."); } else { base::UTF16ToUTF8(manifest->name->c_str(), manifest->name->length(), &(fetched_payment_app_info_->name)); } if (manifest->icons.empty()) { WarnIfPossible( "Unable to download the payment handler's icon, because the web app " "manifest \"" + manifest_url_.spec() + "\" does not contain an \"icons\" field with a valid URL in \"src\" " "sub-field. User may not recognize this payment handler in UI."); RunCallbackAndDestroy(); return; } WebContents* web_contents = web_contents_helper_->web_contents(); if (!web_contents) { LOG(WARNING) << "Unable to download the payment handler's icon because no " "renderer was found, possibly because the page was closed " "or navigated away during installation. User may not " "recognize this payment handler in UI, because it will be " "labeled only by its name and origin."; RunCallbackAndDestroy(); return; } gfx::NativeView native_view = web_contents->GetNativeView(); icon_url_ = blink::ManifestIconSelector::FindBestMatchingIcon( manifest->icons, payments::IconSizeCalculator::IdealIconHeight(native_view), payments::IconSizeCalculator::MinimumIconHeight(), ManifestIconDownloader::kMaxWidthToHeightRatio, blink::mojom::ManifestImageResource_Purpose::ANY); if (!icon_url_.is_valid()) { WarnIfPossible( "No suitable payment handler icon found in the \"icons\" field defined " "in the web app manifest \"" + manifest_url_.spec() + "\". This is most likely due to unsupported MIME types in the " "\"icons\" field. User may not recognize this payment handler in UI."); RunCallbackAndDestroy(); return; } bool can_download = ManifestIconDownloader::Download( web_contents, icon_url_, payments::IconSizeCalculator::IdealIconHeight(native_view), payments::IconSizeCalculator::MinimumIconHeight(), /* maximum_icon_size_in_px= */ std::numeric_limits<int>::max(), base::BindOnce(&PaymentAppInfoFetcher::SelfDeleteFetcher::OnIconFetched, weak_ptr_factory_.GetWeakPtr()), false /* square_only */); // |can_download| is false only if web contents are null or the icon URL is // not valid. Both of these conditions are manually checked above, so // |can_download| should never be false. The manual checks above are necessary // to provide more detailed error messages. DCHECK(can_download); } void PaymentAppInfoFetcher::SelfDeleteFetcher::OnIconFetched( const SkBitmap& icon) { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (icon.drawsNothing()) { WarnIfPossible("Unable to download a valid payment handler icon from \"" + icon_url_.spec() + "\", which is defined in the web app manifest \"" + manifest_url_.spec() + "\". User may not recognize this payment handler in UI."); RunCallbackAndDestroy(); return; } std::vector<unsigned char> bitmap_data; bool success = gfx::PNGCodec::EncodeBGRASkBitmap(icon, false, &bitmap_data); DCHECK(success); base::Base64Encode( base::StringPiece(reinterpret_cast<const char*>(&bitmap_data[0]), bitmap_data.size()), &(fetched_payment_app_info_->icon)); RunCallbackAndDestroy(); } void PaymentAppInfoFetcher::SelfDeleteFetcher::WarnIfPossible( const std::string& message) { DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(web_contents_helper_); if (web_contents_helper_->web_contents()) { web_contents_helper_->web_contents()->GetMainFrame()->AddMessageToConsole( blink::mojom::ConsoleMessageLevel::kWarning, message); } else { LOG(WARNING) << message; } } } // namespace content
scheib/chromium
content/browser/payments/payment_app_info_fetcher.cc
C++
bsd-3-clause
13,104
// Copyright 2016 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 NET_THIRD_PARTY_QUIC_TEST_TOOLS_QUIC_STREAM_SEQUENCER_BUFFER_PEER_H_ #define NET_THIRD_PARTY_QUIC_TEST_TOOLS_QUIC_STREAM_SEQUENCER_BUFFER_PEER_H_ #include "net/third_party/quic/core/quic_stream_sequencer_buffer.h" namespace quic { namespace test { class QuicStreamSequencerBufferPeer { public: explicit QuicStreamSequencerBufferPeer(QuicStreamSequencerBuffer* buffer); QuicStreamSequencerBufferPeer(const QuicStreamSequencerBufferPeer&) = delete; QuicStreamSequencerBufferPeer& operator=( const QuicStreamSequencerBufferPeer&) = delete; // Read from this buffer_ into the given destination buffer_ up to the // size of the destination. Returns the number of bytes read. Reading from // an empty buffer_->returns 0. size_t Read(char* dest_buffer, size_t size); // If buffer is empty, the blocks_ array must be empty, which means all // blocks are deallocated. bool CheckEmptyInvariants(); bool IsBlockArrayEmpty(); bool CheckInitialState(); bool CheckBufferInvariants(); size_t GetInBlockOffset(QuicStreamOffset offset); QuicStreamSequencerBuffer::BufferBlock* GetBlock(size_t index); int IntervalSize(); size_t max_buffer_capacity(); size_t ReadableBytes(); void set_total_bytes_read(QuicStreamOffset total_bytes_read); void AddBytesReceived(QuicStreamOffset offset, QuicByteCount length); bool IsBufferAllocated(); size_t block_count(); const QuicIntervalSet<QuicStreamOffset>& bytes_received(); private: QuicStreamSequencerBuffer* buffer_; }; } // namespace test } // namespace quic #endif // NET_THIRD_PARTY_QUIC_TEST_TOOLS_QUIC_STREAM_SEQUENCER_BUFFER_PEER_H_
youtube/cobalt
net/third_party/quic/test_tools/quic_stream_sequencer_buffer_peer.h
C
bsd-3-clause
1,819
// 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. /** * @fileoverview A command is an abstraction of an action a user can do in the * UI. * * When the focus changes in the document for each command a canExecute event * is dispatched on the active element. By listening to this event you can * enable and disable the command by setting the event.canExecute property. * * When a command is executed a command event is dispatched on the active * element. Note that you should stop the propagation after you have handled the * command if there might be other command listeners higher up in the DOM tree. */ cr.define('cr.ui', function() { /** * This is used to identify keyboard shortcuts. * @param {string} shortcut The text used to describe the keys for this * keyboard shortcut. * @constructor */ function KeyboardShortcut(shortcut) { var mods = {}; var ident = ''; shortcut.split('-').forEach(function(part) { var partLc = part.toLowerCase(); switch (partLc) { case 'alt': case 'ctrl': case 'meta': case 'shift': mods[partLc + 'Key'] = true; break; default: if (ident) throw Error('Invalid shortcut'); ident = part; } }); this.ident_ = ident; this.mods_ = mods; } KeyboardShortcut.prototype = { /** * Whether the keyboard shortcut object matches a keyboard event. * @param {!Event} e The keyboard event object. * @return {boolean} Whether we found a match or not. */ matchesEvent: function(e) { if (e.keyIdentifier == this.ident_) { // All keyboard modifiers needs to match. var mods = this.mods_; return ['altKey', 'ctrlKey', 'metaKey', 'shiftKey'].every(function(k) { return e[k] == !!mods[k]; }); } return false; } }; /** * Creates a new command element. * @constructor * @extends {HTMLElement} */ var Command = cr.ui.define('command'); Command.prototype = { __proto__: HTMLElement.prototype, /** * Initializes the command. */ decorate: function() { CommandManager.init(this.ownerDocument); if (this.hasAttribute('shortcut')) this.shortcut = this.getAttribute('shortcut'); }, /** * Executes the command by dispatching a command event on the given element. * If |element| isn't given, the active element is used instead. * If the command is {@code disabled} this does nothing. * @param {HTMLElement=} opt_element Optional element to dispatch event on. */ execute: function(opt_element) { if (this.disabled) return; var doc = this.ownerDocument; if (doc.activeElement) { var e = new cr.Event('command', true, false); e.command = this; (opt_element || doc.activeElement).dispatchEvent(e); } }, /** * Call this when there have been changes that might change whether the * command can be executed or not. * @param {Node=} opt_node Node for which to actuate command state. */ canExecuteChange: function(opt_node) { dispatchCanExecuteEvent(this, opt_node || this.ownerDocument.activeElement); }, /** * The keyboard shortcut that triggers the command. This is a string * consisting of a keyIdentifier (as reported by WebKit in keydown) as * well as optional key modifiers joinded with a '-'. * * Multiple keyboard shortcuts can be provided by separating them by * whitespace. * * For example: * "F1" * "U+0008-Meta" for Apple command backspace. * "U+0041-Ctrl" for Control A * "U+007F U+0008-Meta" for Delete and Command Backspace * * @type {string} */ shortcut_: '', get shortcut() { return this.shortcut_; }, set shortcut(shortcut) { var oldShortcut = this.shortcut_; if (shortcut !== oldShortcut) { this.keyboardShortcuts_ = shortcut.split(/\s+/).map(function(shortcut) { return new KeyboardShortcut(shortcut); }); // Set this after the keyboardShortcuts_ since that might throw. this.shortcut_ = shortcut; cr.dispatchPropertyChange(this, 'shortcut', this.shortcut_, oldShortcut); } }, /** * Whether the event object matches the shortcut for this command. * @param {!Event} e The key event object. * @return {boolean} Whether it matched or not. */ matchesEvent: function(e) { if (!this.keyboardShortcuts_) return false; return this.keyboardShortcuts_.some(function(keyboardShortcut) { return keyboardShortcut.matchesEvent(e); }); } }; /** * The label of the command. * @type {string} */ cr.defineProperty(Command, 'label', cr.PropertyKind.ATTR); /** * Whether the command is disabled or not. * @type {boolean} */ cr.defineProperty(Command, 'disabled', cr.PropertyKind.BOOL_ATTR); /** * Whether the command is hidden or not. * @type {boolean} */ cr.defineProperty(Command, 'hidden', cr.PropertyKind.BOOL_ATTR); /** * Whether the command is checked or not. * @type {boolean} */ cr.defineProperty(Command, 'checked', cr.PropertyKind.BOOL_ATTR); /** * Dispatches a canExecute event on the target. * @param {cr.ui.Command} command The command that we are testing for. * @param {Element} target The target element to dispatch the event on. */ function dispatchCanExecuteEvent(command, target) { var e = new CanExecuteEvent(command, true); target.dispatchEvent(e); command.disabled = !e.canExecute; } /** * The command managers for different documents. */ var commandManagers = {}; /** * Keeps track of the focused element and updates the commands when the focus * changes. * @param {!Document} doc The document that we are managing the commands for. * @constructor */ function CommandManager(doc) { doc.addEventListener('focus', this.handleFocus_.bind(this), true); // Make sure we add the listener to the bubbling phase so that elements can // prevent the command. doc.addEventListener('keydown', this.handleKeyDown_.bind(this), false); } /** * Initializes a command manager for the document as needed. * @param {!Document} doc The document to manage the commands for. */ CommandManager.init = function(doc) { var uid = cr.getUid(doc); if (!(uid in commandManagers)) { commandManagers[uid] = new CommandManager(doc); } }; CommandManager.prototype = { /** * Handles focus changes on the document. * @param {Event} e The focus event object. * @private */ handleFocus_: function(e) { var target = e.target; // Ignore focus on a menu button or command item if (target.menu || target.command) return; var commands = Array.prototype.slice.call( target.ownerDocument.querySelectorAll('command')); commands.forEach(function(command) { dispatchCanExecuteEvent(command, target); }); }, /** * Handles the keydown event and routes it to the right command. * @param {!Event} e The keydown event. */ handleKeyDown_: function(e) { var target = e.target; var commands = Array.prototype.slice.call( target.ownerDocument.querySelectorAll('command')); for (var i = 0, command; command = commands[i]; i++) { if (!command.disabled && command.matchesEvent(e)) { e.preventDefault(); // We do not want any other element to handle this. e.stopPropagation(); command.execute(); return; } } } }; /** * The event type used for canExecute events. * @param {!cr.ui.Command} command The command that we are evaluating. * @extends {Event} * @constructor * @class */ function CanExecuteEvent(command) { var e = command.ownerDocument.createEvent('Event'); e.initEvent('canExecute', true, false); e.__proto__ = CanExecuteEvent.prototype; e.command = command; return e; } CanExecuteEvent.prototype = { __proto__: Event.prototype, /** * The current command * @type {cr.ui.Command} */ command: null, /** * Whether the target can execute the command. Setting this also stops the * propagation. * @type {boolean} */ canExecute_: false, get canExecute() { return this.canExecute_; }, set canExecute(canExecute) { this.canExecute_ = !!canExecute; this.stopPropagation(); } }; // Export return { Command: Command, CanExecuteEvent: CanExecuteEvent }; });
timopulkkinen/BubbleFish
ui/webui/resources/js/cr/ui/command.js
JavaScript
bsd-3-clause
8,976
/** ****************************************************************************** * api-scanner - Scan for API imports from a packaged 360 game * ****************************************************************************** * Copyright 2015 x1nixmzeng. All rights reserved. * * Released under the BSD license - see LICENSE in the root for more details. * ****************************************************************************** */ #include "api_scanner_loader.h" namespace xe { namespace tools { DEFINE_string(target, "", "List of file to extract imports from"); int api_scanner_main(std::vector<std::wstring>& args) { // XXX we need gflags to split multiple flags into arrays for us if (args.size() == 2 || !FLAGS_target.empty()) { apiscanner_loader loader_; std::wstring target(cvars::target.empty() ? args[1] : xe::to_wstring(cvars::target)); std::wstring target_abs = xe::to_absolute_path(target); // XXX For each target? if (loader_.LoadTitleImports(target)) { for (const auto title : loader_.GetAllTitles()) { printf("%08x\n", title.title_id); for (const auto import : title.imports) { printf("\t%s\n", import.c_str()); } } } } return 0; } } // namespace tools } // namespace xe DEFINE_ENTRY_POINT(L"api-scanner", L"api-scanner --target=<target file>", xe::tools::api_scanner_main);
sephiroth99/xenia
src/xenia/tools/api-scanner/api_scanner_main.cc
C++
bsd-3-clause
1,501
// 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. #ifndef COMPONENTS_ERROR_PAGE_COMMON_LOCALIZED_ERROR_H_ #define COMPONENTS_ERROR_PAGE_COMMON_LOCALIZED_ERROR_H_ #include <memory> #include <string> #include "base/values.h" #include "url/gurl.h" namespace base { class DictionaryValue; } namespace error_page { class LocalizedError { public: // Information about elements shown on the error page. struct PageState { PageState(); ~PageState(); PageState(const PageState& other) = delete; PageState(PageState&& other); PageState& operator=(PageState&& other); // Strings used within the error page HTML/JS. base::DictionaryValue strings; bool is_offline_error = false; bool reload_button_shown = false; bool download_button_shown = false; bool offline_content_feature_enabled = false; bool auto_fetch_allowed = false; }; LocalizedError() = delete; LocalizedError(const LocalizedError&) = delete; LocalizedError& operator=(const LocalizedError&) = delete; // Returns a |PageState| that describes the elements that should be shown on // on HTTP errors, like 404 or connection reset. static PageState GetPageState( int error_code, const std::string& error_domain, const GURL& failed_url, bool is_post, bool is_secure_dns_network_error, bool stale_copy_in_cache, bool can_show_network_diagnostics_dialog, bool is_incognito, bool offline_content_feature_enabled, bool auto_fetch_feature_enabled, bool is_kiosk_mode, // whether device is currently in single app (kiosk) // mode const std::string& locale, bool is_blocked_by_extension); // Returns a description of the encountered error. static std::u16string GetErrorDetails(const std::string& error_domain, int error_code, bool is_secure_dns_network_error, bool is_post); // Returns true if an error page exists for the specified parameters. static bool HasStrings(const std::string& error_domain, int error_code); }; } // namespace error_page #endif // COMPONENTS_ERROR_PAGE_COMMON_LOCALIZED_ERROR_H_
scheib/chromium
components/error_page/common/localized_error.h
C
bsd-3-clause
2,380
using System.Linq.Expressions; using NHibernate.Metadata; namespace NHibernate.Linq.Expressions { public class EntityExpression : NHibernateExpression { private readonly string _alias; private readonly string _associationPath; private readonly IClassMetadata _metaData; private readonly Expression _expression; public string Alias { get { return _alias; } } public string AssociationPath { get { return _associationPath; } } public IClassMetadata MetaData { get { return _metaData; } } public Expression Expression { get { return _expression; } } public EntityExpression(string associationPath, string alias, System.Type type, IClassMetadata metaData, Expression expression) : base(IsRoot(expression) ? NHibernateExpressionType.RootEntity : NHibernateExpressionType.Entity, type) { _associationPath = associationPath; _alias = alias; _metaData = metaData; _expression = expression; } private static bool IsRoot(Expression expr) { if (expr == null) return true; if (!(expr is EntityExpression)) return true; return false; } public override string ToString() { return Alias; } public virtual string GetAliasedIdentifierPropertyName() { if ((NHibernateExpressionType)this.NodeType == NHibernateExpressionType.RootEntity) { return this.MetaData.IdentifierPropertyName; } return string.Format("{0}.{1}", this.Alias, this.MetaData.IdentifierPropertyName); } } }
OrchardCMS/Orchard
src/Libraries/NHibernate/NHibernate.Linq/Expressions/EntityExpression.cs
C#
bsd-3-clause
1,479
/* * Copyright (C) 2006 Alexey Proskuryakov (ap@webkit.org) * Copyright (C) 2009 Google Inc. All rights reserved. * Copyright (C) 2011 Apple 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: * * 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 Apple Computer, Inc. ("Apple") 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 APPLE AND ITS 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 APPLE OR ITS 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. */ #ifndef HTTPParsers_h #define HTTPParsers_h #include "platform/PlatformExport.h" #include "wtf/Allocator.h" #include "wtf/Forward.h" #include "wtf/HashSet.h" #include "wtf/Vector.h" #include "wtf/text/StringHash.h" namespace blink { typedef enum { ContentDispositionNone, ContentDispositionInline, ContentDispositionAttachment, ContentDispositionOther } ContentDispositionType; enum ContentTypeOptionsDisposition { ContentTypeOptionsNone, ContentTypeOptionsNosniff }; enum XFrameOptionsDisposition { XFrameOptionsInvalid, XFrameOptionsDeny, XFrameOptionsSameOrigin, XFrameOptionsAllowAll, XFrameOptionsConflict }; // Be sure to update the behavior of XSSAuditor::combineXSSProtectionHeaderAndCSP whenever you change this enum's content or ordering. enum ReflectedXSSDisposition { ReflectedXSSUnset = 0, AllowReflectedXSS, ReflectedXSSInvalid, FilterReflectedXSS, BlockReflectedXSS }; using CommaDelimitedHeaderSet = HashSet<String, CaseFoldingHash>; struct CacheControlHeader { DISALLOW_NEW(); bool parsed : 1; bool containsNoCache : 1; bool containsNoStore : 1; bool containsMustRevalidate : 1; double maxAge; double staleWhileRevalidate; CacheControlHeader() : parsed(false) , containsNoCache(false) , containsNoStore(false) , containsMustRevalidate(false) , maxAge(0.0) , staleWhileRevalidate(0.0) { } }; PLATFORM_EXPORT ContentDispositionType contentDispositionType(const String&); PLATFORM_EXPORT bool isValidHTTPHeaderValue(const String&); PLATFORM_EXPORT bool isValidHTTPFieldContentRFC7230(const String&); PLATFORM_EXPORT bool isValidHTTPToken(const String&); PLATFORM_EXPORT bool parseHTTPRefresh(const String& refresh, bool fromHttpEquivMeta, double& delay, String& url); PLATFORM_EXPORT double parseDate(const String&); // Given a Media Type (like "foo/bar; baz=gazonk" - usually from the // 'Content-Type' HTTP header), extract and return the "type/subtype" portion // ("foo/bar"). // Note: This function does not in any way check that the "type/subtype" pair // is well-formed. PLATFORM_EXPORT AtomicString extractMIMETypeFromMediaType(const AtomicString&); PLATFORM_EXPORT String extractCharsetFromMediaType(const String&); PLATFORM_EXPORT void findCharsetInMediaType(const String& mediaType, unsigned& charsetPos, unsigned& charsetLen, unsigned start = 0); PLATFORM_EXPORT ReflectedXSSDisposition parseXSSProtectionHeader(const String& header, String& failureReason, unsigned& failurePosition, String& reportURL); PLATFORM_EXPORT XFrameOptionsDisposition parseXFrameOptionsHeader(const String&); PLATFORM_EXPORT CacheControlHeader parseCacheControlDirectives(const AtomicString& cacheControlHeader, const AtomicString& pragmaHeader); PLATFORM_EXPORT void parseCommaDelimitedHeader(const String& headerValue, CommaDelimitedHeaderSet&); PLATFORM_EXPORT ContentTypeOptionsDisposition parseContentTypeOptionsHeader(const String& header); } // namespace blink #endif
ds-hwang/chromium-crosswalk
third_party/WebKit/Source/platform/network/HTTPParsers.h
C
bsd-3-clause
4,724
// Copyright 2011 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. package x509 import ( "strings" "time" "unicode/utf8" ) type InvalidReason int const ( // NotAuthorizedToSign results when a certificate is signed by another // which isn't marked as a CA certificate. NotAuthorizedToSign InvalidReason = iota // Expired results when a certificate has expired, based on the time // given in the VerifyOptions. Expired // CANotAuthorizedForThisName results when an intermediate or root // certificate has a name constraint which doesn't include the name // being checked. CANotAuthorizedForThisName ) // CertificateInvalidError results when an odd error occurs. Users of this // library probably want to handle all these errors uniformly. type CertificateInvalidError struct { Cert *Certificate Reason InvalidReason } func (e CertificateInvalidError) Error() string { switch e.Reason { case NotAuthorizedToSign: return "x509: certificate is not authorized to sign other other certificates" case Expired: return "x509: certificate has expired or is not yet valid" case CANotAuthorizedForThisName: return "x509: a root or intermediate certificate is not authorized to sign in this domain" } return "x509: unknown error" } // HostnameError results when the set of authorized names doesn't match the // requested name. type HostnameError struct { Certificate *Certificate Host string } func (h HostnameError) Error() string { var valid string c := h.Certificate if len(c.DNSNames) > 0 { valid = strings.Join(c.DNSNames, ", ") } else { valid = c.Subject.CommonName } return "certificate is valid for " + valid + ", not " + h.Host } // UnknownAuthorityError results when the certificate issuer is unknown type UnknownAuthorityError struct { cert *Certificate } func (e UnknownAuthorityError) Error() string { return "x509: certificate signed by unknown authority" } // VerifyOptions contains parameters for Certificate.Verify. It's a structure // because other PKIX verification APIs have ended up needing many options. type VerifyOptions struct { DNSName string Intermediates *CertPool Roots *CertPool CurrentTime time.Time // if zero, the current time is used } const ( leafCertificate = iota intermediateCertificate rootCertificate ) // isValid performs validity checks on the c. func (c *Certificate) isValid(certType int, opts *VerifyOptions) error { now := opts.CurrentTime if now.IsZero() { now = time.Now() } if now.Before(c.NotBefore) || now.After(c.NotAfter) { return CertificateInvalidError{c, Expired} } if len(c.PermittedDNSDomains) > 0 { for _, domain := range c.PermittedDNSDomains { if opts.DNSName == domain || (strings.HasSuffix(opts.DNSName, domain) && len(opts.DNSName) >= 1+len(domain) && opts.DNSName[len(opts.DNSName)-len(domain)-1] == '.') { continue } return CertificateInvalidError{c, CANotAuthorizedForThisName} } } // KeyUsage status flags are ignored. From Engineering Security, Peter // Gutmann: A European government CA marked its signing certificates as // being valid for encryption only, but no-one noticed. Another // European CA marked its signature keys as not being valid for // signatures. A different CA marked its own trusted root certificate // as being invalid for certificate signing. Another national CA // distributed a certificate to be used to encrypt data for the // country’s tax authority that was marked as only being usable for // digital signatures but not for encryption. Yet another CA reversed // the order of the bit flags in the keyUsage due to confusion over // encoding endianness, essentially setting a random keyUsage in // certificates that it issued. Another CA created a self-invalidating // certificate by adding a certificate policy statement stipulating // that the certificate had to be used strictly as specified in the // keyUsage, and a keyUsage containing a flag indicating that the RSA // encryption key could only be used for Diffie-Hellman key agreement. if certType == intermediateCertificate && (!c.BasicConstraintsValid || !c.IsCA) { return CertificateInvalidError{c, NotAuthorizedToSign} } return nil } // Verify attempts to verify c by building one or more chains from c to a // certificate in opts.roots, using certificates in opts.Intermediates if // needed. If successful, it returns one or more chains where the first // element of the chain is c and the last element is from opts.Roots. // // WARNING: this doesn't do any revocation checking. func (c *Certificate) Verify(opts VerifyOptions) (chains [][]*Certificate, err error) { err = c.isValid(leafCertificate, &opts) if err != nil { return } if len(opts.DNSName) > 0 { err = c.VerifyHostname(opts.DNSName) if err != nil { return } } return c.buildChains(make(map[int][][]*Certificate), []*Certificate{c}, &opts) } func appendToFreshChain(chain []*Certificate, cert *Certificate) []*Certificate { n := make([]*Certificate, len(chain)+1) copy(n, chain) n[len(chain)] = cert return n } func (c *Certificate) buildChains(cache map[int][][]*Certificate, currentChain []*Certificate, opts *VerifyOptions) (chains [][]*Certificate, err error) { for _, rootNum := range opts.Roots.findVerifiedParents(c) { root := opts.Roots.certs[rootNum] err = root.isValid(rootCertificate, opts) if err != nil { continue } chains = append(chains, appendToFreshChain(currentChain, root)) } nextIntermediate: for _, intermediateNum := range opts.Intermediates.findVerifiedParents(c) { intermediate := opts.Intermediates.certs[intermediateNum] for _, cert := range currentChain { if cert == intermediate { continue nextIntermediate } } err = intermediate.isValid(intermediateCertificate, opts) if err != nil { continue } var childChains [][]*Certificate childChains, ok := cache[intermediateNum] if !ok { childChains, err = intermediate.buildChains(cache, appendToFreshChain(currentChain, intermediate), opts) cache[intermediateNum] = childChains } chains = append(chains, childChains...) } if len(chains) > 0 { err = nil } if len(chains) == 0 && err == nil { err = UnknownAuthorityError{c} } return } func matchHostnames(pattern, host string) bool { if len(pattern) == 0 || len(host) == 0 { return false } patternParts := strings.Split(pattern, ".") hostParts := strings.Split(host, ".") if len(patternParts) != len(hostParts) { return false } for i, patternPart := range patternParts { if patternPart == "*" { continue } if patternPart != hostParts[i] { return false } } return true } // toLowerCaseASCII returns a lower-case version of in. See RFC 6125 6.4.1. We use // an explicitly ASCII function to avoid any sharp corners resulting from // performing Unicode operations on DNS labels. func toLowerCaseASCII(in string) string { // If the string is already lower-case then there's nothing to do. isAlreadyLowerCase := true for _, c := range in { if c == utf8.RuneError { // If we get a UTF-8 error then there might be // upper-case ASCII bytes in the invalid sequence. isAlreadyLowerCase = false break } if 'A' <= c && c <= 'Z' { isAlreadyLowerCase = false break } } if isAlreadyLowerCase { return in } out := []byte(in) for i, c := range out { if 'A' <= c && c <= 'Z' { out[i] += 'a' - 'A' } } return string(out) } // VerifyHostname returns nil if c is a valid certificate for the named host. // Otherwise it returns an error describing the mismatch. func (c *Certificate) VerifyHostname(h string) error { lowered := toLowerCaseASCII(h) if len(c.DNSNames) > 0 { for _, match := range c.DNSNames { if matchHostnames(toLowerCaseASCII(match), lowered) { return nil } } // If Subject Alt Name is given, we ignore the common name. } else if matchHostnames(toLowerCaseASCII(c.Subject.CommonName), lowered) { return nil } return HostnameError{c, h} }
tav/go
src/pkg/crypto/x509/verify.go
GO
bsd-3-clause
8,108
/* * Implements dynamic task queues to provide load balancing * Sanjeev Kumar --- December, 2004 */ #ifndef __TASKQ_INTERNAL_H__ #define __TASKQ_INTERNAL_H__ #include <stdio.h> #include <stdlib.h> #include <string.h> #ifdef MAXFLOW #include <taskQMaxflow.h> #else #include "../include/taskQ.h" #endif #ifdef USE_ATHREADS // Alamere threads #include "taskQAThread.h" #endif #define CACHE_LINE_SIZE 256 /* Largest cache line size */ // #define HERE printf( ">>> at %s : %d\n", __FILE__, __LINE__) // #define HERE printf( "%ld $$$ at %s : %d\n", ( long)alt_index(), __FILE__, __LINE__) #define HERE // #define TRACE printf( "%ld ### at %s : %d\n", ( long)alt_index(), __FILE__, __LINE__); fflush( stdout); // #define TRACE printf( ">>> at %s : %d\n", __FILE__, __LINE__) // #define TRACE printf( ">>> %10d at %s : %d\n", pthread_self(), __FILE__, __LINE__) #define TRACE #define ERROR { printf( "Error in TaskQ: This function should not have been called at %s : %d\n", __FILE__, __LINE__); exit(0); } // #define IF_STATS(s) s #define IF_STATS(s) #define TQ_ASSERT(v) { \ if ( !(v)) { \ printf( "TQ Assertion failed at %s:%d\n", __FILE__, __LINE__); \ exit(1); \ } \ } #define UNDEFINED_VALUE ( ( void *)-999) // #define DEBUG_TASKQ #ifdef DEBUG_TASKQ #define DEBUG_ASSERT(v) TQ_ASSERT(v) #define IF_DEBUG(v) v #define DEBUG_ANNOUNCE { printf( "\n\n>>>>>>>>>>>>>>>>>>>>>> Running the DEBUG version of the TaskQ <<<<<<<<<<<<<<<<<<<\n\n\n"); } #else #define DEBUG_ASSERT(v) #define IF_DEBUG(v) #define DEBUG_ANNOUNCE #endif #define NUM_FIELDS (MAX_DIMENSION+1) static inline void copyTask( void *taskDest[NUM_FIELDS], void *taskSrc[NUM_FIELDS]) { int i; for ( i = 0; i < NUM_FIELDS; i++) taskDest[i] = taskSrc[i]; } static inline void copyArgs1( void *task[NUM_FIELDS], TaskQTask1 taskFunction, void *arg1) { TQ_ASSERT( NUM_FIELDS >= 2); task[0] = ( void *)taskFunction; task[1] = arg1; IF_DEBUG( { int i; for ( i = 2; i < NUM_FIELDS; i++) task[i] = UNDEFINED_VALUE; }); } static inline void copyArgs2( void *task[NUM_FIELDS], TaskQTask2 taskFunction, void *arg1, void *arg2) { TQ_ASSERT( NUM_FIELDS >= 3); task[0] = ( void *)taskFunction; task[1] = arg1; task[2] = arg2; IF_DEBUG( { int i; for ( i = 3; i < NUM_FIELDS; i++) task[i] = UNDEFINED_VALUE; }); } static inline void copyArgs3( void *task[NUM_FIELDS], TaskQTask3 taskFunction, void *arg1, void *arg2, void *arg3) { TQ_ASSERT( NUM_FIELDS >= 4); task[0] = ( void *)taskFunction; task[1] = arg1; task[2] = arg2; task[3] = arg3; IF_DEBUG( { int i; for ( i = 4; i < NUM_FIELDS; i++) task[i] = UNDEFINED_VALUE; }); } // The following functions are used to enqueue a grid of tasks typedef void ( *AssignTasksFn)( TaskQTask3 taskFn, int numDimensions, int queueNo, long min[MAX_DIMENSION], long max[MAX_DIMENSION], long step[MAX_DIMENSION]); void standardize( int n, long min1[MAX_DIMENSION], long max1[MAX_DIMENSION], long step1[MAX_DIMENSION], long min2[MAX_DIMENSION], long max2[MAX_DIMENSION], long step2[MAX_DIMENSION]) { long k; DEBUG_ASSERT( MAX_DIMENSION == 3); for ( k = 0; k < MAX_DIMENSION; k++) { if ( k < n) { min1[k] = min2[k]; max1[k] = max2[k]; step1[k] = step2[k]; } else { min1[k] = 0; max1[k] = 1; step1[k] = 1; } } } static inline void assignTasksStandardized( AssignTasksFn fn, TaskQTask3 taskFn, int numDimensions, int queueNo, long min[MAX_DIMENSION], long max[MAX_DIMENSION], long step[MAX_DIMENSION]) { long min1[MAX_DIMENSION], max1[MAX_DIMENSION], step1[MAX_DIMENSION]; standardize( numDimensions, min1, max1, step1, min, max, step); fn( taskFn, numDimensions, queueNo, min1, max1, step1); } static void enqueueGridRec( AssignTasksFn fn, TaskQTask3 taskFn, int numDimensions, int startQueue, int totalQueues, int currentDimension, long min[MAX_DIMENSION], long max[MAX_DIMENSION], long step[MAX_DIMENSION]) { if ( totalQueues == 1) { assignTasksStandardized( fn, taskFn, numDimensions, startQueue, min, max, step); } else { long j, k; for ( j = 0, k = currentDimension; j < numDimensions; j++, k = (k+1) % numDimensions) if ( max[k] - min[k] > 1) break; if ( max[k] - min[k] == 1) { // Only one task left. Put it in the first queue assignTasksStandardized( fn, taskFn, numDimensions, startQueue, min, max, step); // The rest get nothing for ( j = 0; j < numDimensions; j++) max[j] = min[j]; for ( j = 1; j < totalQueues; j++) assignTasksStandardized( fn, taskFn, numDimensions, startQueue+j, min, max, step); } else { // Split it into two halfs and give half to each long next, middle, half, alt[MAX_DIMENSION]; middle = min[k] + ( max[k] - min[k])/2; next = (k+1) % numDimensions; half = totalQueues/2; // First half for ( j = 0; j < numDimensions; j++) if ( j == k) alt[j] = middle; else alt[j] = max[j]; enqueueGridRec( fn, taskFn, numDimensions, startQueue, half, next, min, alt, step); // Seconf half for ( j = 0; j < numDimensions; j++) if ( j == k) alt[j] = middle; else alt[j] = min[j]; enqueueGridRec( fn, taskFn, numDimensions, startQueue+half, totalQueues-half, next, alt, max, step); } } } long countTasks( int n, long max[MAX_DIMENSION], long step[MAX_DIMENSION]) { long k, count = 1; for ( k = 0; k < n; k++) count *= max[k]/step[k]; return count; } static inline void enqueueGridHelper( AssignTasksFn assignFunction, TaskQTask3 taskFunction, int numDimensions, int numTaskQs, long dimensionSize[MAX_DIMENSION], long tileSize[MAX_DIMENSION]) { long i, min[MAX_DIMENSION], max[MAX_DIMENSION]; for ( i = 0; i < numDimensions; i++) { DEBUG_ASSERT( dimensionSize[i] > 0); TQ_ASSERT( dimensionSize[i] % tileSize[i] == 0); min[i] = 0; max[i] = dimensionSize[i] / tileSize[i]; } enqueueGridRec( assignFunction, taskFunction, numDimensions, 0, numTaskQs, 0, min, max, tileSize); } // These are used to get/set task queue parameters static long paramValues[] = { ( long)UNDEFINED_VALUE, 1, ( long)UNDEFINED_VALUE }; void taskQSetParam( enum TaskQParam param, long value) { TQ_ASSERT( ( param > 0) && ( param < TaskQNumParams)); TQ_ASSERT( paramValues[TaskQNumParams] == ( long)UNDEFINED_VALUE); paramValues[param] = value; } long taskQGetParam( enum TaskQParam param) { TQ_ASSERT( ( param > 0) && ( param < TaskQNumParams)); TQ_ASSERT( paramValues[TaskQNumParams] == ( long)UNDEFINED_VALUE); return paramValues[param]; } #endif
anasazi/POP-REU-Project
pkgs/apps/facesim/src/TaskQ/lib/taskQInternal.h
C
bsd-3-clause
7,506
/* * * Copyright 2015, 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. * */ #include "src/core/lib/surface/completion_queue.h" #include <stdio.h> #include <string.h> #include <grpc/support/alloc.h> #include <grpc/support/atm.h> #include <grpc/support/log.h> #include <grpc/support/time.h> #include "src/core/lib/iomgr/pollset.h" #include "src/core/lib/iomgr/timer.h" #include "src/core/lib/profiling/timers.h" #include "src/core/lib/support/string.h" #include "src/core/lib/surface/api_trace.h" #include "src/core/lib/surface/call.h" #include "src/core/lib/surface/event_string.h" #include "src/core/lib/surface/surface_trace.h" typedef struct { grpc_pollset_worker **worker; void *tag; } plucker; /* Completion queue structure */ struct grpc_completion_queue { /** owned by pollset */ gpr_mu *mu; /** completed events */ grpc_cq_completion completed_head; grpc_cq_completion *completed_tail; /** Number of pending events (+1 if we're not shutdown) */ gpr_refcount pending_events; /** Once owning_refs drops to zero, we will destroy the cq */ gpr_refcount owning_refs; /** 0 initially, 1 once we've begun shutting down */ int shutdown; int shutdown_called; int is_server_cq; int num_pluckers; plucker pluckers[GRPC_MAX_COMPLETION_QUEUE_PLUCKERS]; grpc_closure pollset_shutdown_done; #ifndef NDEBUG void **outstanding_tags; size_t outstanding_tag_count; size_t outstanding_tag_capacity; #endif grpc_completion_queue *next_free; }; #define POLLSET_FROM_CQ(cq) ((grpc_pollset *)(cq + 1)) static gpr_mu g_freelist_mu; static grpc_completion_queue *g_freelist; static void on_pollset_shutdown_done(grpc_exec_ctx *exec_ctx, void *cc, bool success); void grpc_cq_global_init(void) { gpr_mu_init(&g_freelist_mu); } void grpc_cq_global_shutdown(void) { gpr_mu_destroy(&g_freelist_mu); while (g_freelist) { grpc_completion_queue *next = g_freelist->next_free; grpc_pollset_destroy(POLLSET_FROM_CQ(g_freelist)); #ifndef NDEBUG gpr_free(g_freelist->outstanding_tags); #endif gpr_free(g_freelist); g_freelist = next; } } struct grpc_cq_alarm { grpc_timer alarm; grpc_cq_completion completion; /** completion queue where events about this alarm will be posted */ grpc_completion_queue *cq; /** user supplied tag */ void *tag; }; grpc_completion_queue *grpc_completion_queue_create(void *reserved) { grpc_completion_queue *cc; GPR_ASSERT(!reserved); GPR_TIMER_BEGIN("grpc_completion_queue_create", 0); GRPC_API_TRACE("grpc_completion_queue_create(reserved=%p)", 1, (reserved)); gpr_mu_lock(&g_freelist_mu); if (g_freelist == NULL) { gpr_mu_unlock(&g_freelist_mu); cc = gpr_malloc(sizeof(grpc_completion_queue) + grpc_pollset_size()); grpc_pollset_init(POLLSET_FROM_CQ(cc), &cc->mu); #ifndef NDEBUG cc->outstanding_tags = NULL; cc->outstanding_tag_capacity = 0; #endif } else { cc = g_freelist; g_freelist = g_freelist->next_free; gpr_mu_unlock(&g_freelist_mu); /* pollset already initialized */ } /* Initial ref is dropped by grpc_completion_queue_shutdown */ gpr_ref_init(&cc->pending_events, 1); /* One for destroy(), one for pollset_shutdown */ gpr_ref_init(&cc->owning_refs, 2); cc->completed_tail = &cc->completed_head; cc->completed_head.next = (uintptr_t)cc->completed_tail; cc->shutdown = 0; cc->shutdown_called = 0; cc->is_server_cq = 0; cc->num_pluckers = 0; #ifndef NDEBUG cc->outstanding_tag_count = 0; #endif grpc_closure_init(&cc->pollset_shutdown_done, on_pollset_shutdown_done, cc); GPR_TIMER_END("grpc_completion_queue_create", 0); return cc; } #ifdef GRPC_CQ_REF_COUNT_DEBUG void grpc_cq_internal_ref(grpc_completion_queue *cc, const char *reason, const char *file, int line) { gpr_log(file, line, GPR_LOG_SEVERITY_DEBUG, "CQ:%p ref %d -> %d %s", cc, (int)cc->owning_refs.count, (int)cc->owning_refs.count + 1, reason); #else void grpc_cq_internal_ref(grpc_completion_queue *cc) { #endif gpr_ref(&cc->owning_refs); } static void on_pollset_shutdown_done(grpc_exec_ctx *exec_ctx, void *arg, bool success) { grpc_completion_queue *cc = arg; GRPC_CQ_INTERNAL_UNREF(cc, "pollset_destroy"); } #ifdef GRPC_CQ_REF_COUNT_DEBUG void grpc_cq_internal_unref(grpc_completion_queue *cc, const char *reason, const char *file, int line) { gpr_log(file, line, GPR_LOG_SEVERITY_DEBUG, "CQ:%p unref %d -> %d %s", cc, (int)cc->owning_refs.count, (int)cc->owning_refs.count - 1, reason); #else void grpc_cq_internal_unref(grpc_completion_queue *cc) { #endif if (gpr_unref(&cc->owning_refs)) { GPR_ASSERT(cc->completed_head.next == (uintptr_t)&cc->completed_head); grpc_pollset_reset(POLLSET_FROM_CQ(cc)); gpr_mu_lock(&g_freelist_mu); cc->next_free = g_freelist; g_freelist = cc; gpr_mu_unlock(&g_freelist_mu); } } void grpc_cq_begin_op(grpc_completion_queue *cc, void *tag) { #ifndef NDEBUG gpr_mu_lock(cc->mu); GPR_ASSERT(!cc->shutdown_called); if (cc->outstanding_tag_count == cc->outstanding_tag_capacity) { cc->outstanding_tag_capacity = GPR_MAX(4, 2 * cc->outstanding_tag_capacity); cc->outstanding_tags = gpr_realloc(cc->outstanding_tags, sizeof(*cc->outstanding_tags) * cc->outstanding_tag_capacity); } cc->outstanding_tags[cc->outstanding_tag_count++] = tag; gpr_mu_unlock(cc->mu); #endif gpr_ref(&cc->pending_events); } /* Signal the end of an operation - if this is the last waiting-to-be-queued event, then enter shutdown mode */ /* Queue a GRPC_OP_COMPLETED operation */ void grpc_cq_end_op(grpc_exec_ctx *exec_ctx, grpc_completion_queue *cc, void *tag, int success, void (*done)(grpc_exec_ctx *exec_ctx, void *done_arg, grpc_cq_completion *storage), void *done_arg, grpc_cq_completion *storage) { int shutdown; int i; grpc_pollset_worker *pluck_worker; #ifndef NDEBUG int found = 0; #endif GPR_TIMER_BEGIN("grpc_cq_end_op", 0); storage->tag = tag; storage->done = done; storage->done_arg = done_arg; storage->next = ((uintptr_t)&cc->completed_head) | ((uintptr_t)(success != 0)); gpr_mu_lock(cc->mu); #ifndef NDEBUG for (i = 0; i < (int)cc->outstanding_tag_count; i++) { if (cc->outstanding_tags[i] == tag) { cc->outstanding_tag_count--; GPR_SWAP(void *, cc->outstanding_tags[i], cc->outstanding_tags[cc->outstanding_tag_count]); found = 1; break; } } GPR_ASSERT(found); #endif shutdown = gpr_unref(&cc->pending_events); if (!shutdown) { cc->completed_tail->next = ((uintptr_t)storage) | (1u & (uintptr_t)cc->completed_tail->next); cc->completed_tail = storage; pluck_worker = NULL; for (i = 0; i < cc->num_pluckers; i++) { if (cc->pluckers[i].tag == tag) { pluck_worker = *cc->pluckers[i].worker; break; } } grpc_pollset_kick(POLLSET_FROM_CQ(cc), pluck_worker); gpr_mu_unlock(cc->mu); } else { cc->completed_tail->next = ((uintptr_t)storage) | (1u & (uintptr_t)cc->completed_tail->next); cc->completed_tail = storage; GPR_ASSERT(!cc->shutdown); GPR_ASSERT(cc->shutdown_called); cc->shutdown = 1; grpc_pollset_shutdown(exec_ctx, POLLSET_FROM_CQ(cc), &cc->pollset_shutdown_done); gpr_mu_unlock(cc->mu); } GPR_TIMER_END("grpc_cq_end_op", 0); } grpc_event grpc_completion_queue_next(grpc_completion_queue *cc, gpr_timespec deadline, void *reserved) { grpc_event ret; grpc_pollset_worker *worker = NULL; int first_loop = 1; gpr_timespec now; grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; GPR_TIMER_BEGIN("grpc_completion_queue_next", 0); GRPC_API_TRACE( "grpc_completion_queue_next(" "cc=%p, " "deadline=gpr_timespec { tv_sec: %lld, tv_nsec: %d, clock_type: %d }, " "reserved=%p)", 5, (cc, (long long)deadline.tv_sec, (int)deadline.tv_nsec, (int)deadline.clock_type, reserved)); GPR_ASSERT(!reserved); deadline = gpr_convert_clock_type(deadline, GPR_CLOCK_MONOTONIC); GRPC_CQ_INTERNAL_REF(cc, "next"); gpr_mu_lock(cc->mu); for (;;) { if (cc->completed_tail != &cc->completed_head) { grpc_cq_completion *c = (grpc_cq_completion *)cc->completed_head.next; cc->completed_head.next = c->next & ~(uintptr_t)1; if (c == cc->completed_tail) { cc->completed_tail = &cc->completed_head; } gpr_mu_unlock(cc->mu); ret.type = GRPC_OP_COMPLETE; ret.success = c->next & 1u; ret.tag = c->tag; c->done(&exec_ctx, c->done_arg, c); break; } if (cc->shutdown) { gpr_mu_unlock(cc->mu); memset(&ret, 0, sizeof(ret)); ret.type = GRPC_QUEUE_SHUTDOWN; break; } now = gpr_now(GPR_CLOCK_MONOTONIC); if (!first_loop && gpr_time_cmp(now, deadline) >= 0) { gpr_mu_unlock(cc->mu); memset(&ret, 0, sizeof(ret)); ret.type = GRPC_QUEUE_TIMEOUT; break; } first_loop = 0; /* Check alarms - these are a global resource so we just ping each time through on every pollset. May update deadline to ensure timely wakeups. TODO(ctiller): can this work be localized? */ gpr_timespec iteration_deadline = deadline; if (grpc_timer_check(&exec_ctx, now, &iteration_deadline)) { GPR_TIMER_MARK("alarm_triggered", 0); gpr_mu_unlock(cc->mu); grpc_exec_ctx_flush(&exec_ctx); gpr_mu_lock(cc->mu); continue; } else { grpc_pollset_work(&exec_ctx, POLLSET_FROM_CQ(cc), &worker, now, iteration_deadline); } } GRPC_SURFACE_TRACE_RETURNED_EVENT(cc, &ret); GRPC_CQ_INTERNAL_UNREF(cc, "next"); grpc_exec_ctx_finish(&exec_ctx); GPR_TIMER_END("grpc_completion_queue_next", 0); return ret; } static int add_plucker(grpc_completion_queue *cc, void *tag, grpc_pollset_worker **worker) { if (cc->num_pluckers == GRPC_MAX_COMPLETION_QUEUE_PLUCKERS) { return 0; } cc->pluckers[cc->num_pluckers].tag = tag; cc->pluckers[cc->num_pluckers].worker = worker; cc->num_pluckers++; return 1; } static void del_plucker(grpc_completion_queue *cc, void *tag, grpc_pollset_worker **worker) { int i; for (i = 0; i < cc->num_pluckers; i++) { if (cc->pluckers[i].tag == tag && cc->pluckers[i].worker == worker) { cc->num_pluckers--; GPR_SWAP(plucker, cc->pluckers[i], cc->pluckers[cc->num_pluckers]); return; } } GPR_UNREACHABLE_CODE(return ); } grpc_event grpc_completion_queue_pluck(grpc_completion_queue *cc, void *tag, gpr_timespec deadline, void *reserved) { grpc_event ret; grpc_cq_completion *c; grpc_cq_completion *prev; grpc_pollset_worker *worker = NULL; gpr_timespec now; int first_loop = 1; grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; GPR_TIMER_BEGIN("grpc_completion_queue_pluck", 0); GRPC_API_TRACE( "grpc_completion_queue_pluck(" "cc=%p, tag=%p, " "deadline=gpr_timespec { tv_sec: %lld, tv_nsec: %d, clock_type: %d }, " "reserved=%p)", 6, (cc, tag, (long long)deadline.tv_sec, (int)deadline.tv_nsec, (int)deadline.clock_type, reserved)); GPR_ASSERT(!reserved); deadline = gpr_convert_clock_type(deadline, GPR_CLOCK_MONOTONIC); GRPC_CQ_INTERNAL_REF(cc, "pluck"); gpr_mu_lock(cc->mu); for (;;) { prev = &cc->completed_head; while ((c = (grpc_cq_completion *)(prev->next & ~(uintptr_t)1)) != &cc->completed_head) { if (c->tag == tag) { prev->next = (prev->next & (uintptr_t)1) | (c->next & ~(uintptr_t)1); if (c == cc->completed_tail) { cc->completed_tail = prev; } gpr_mu_unlock(cc->mu); ret.type = GRPC_OP_COMPLETE; ret.success = c->next & 1u; ret.tag = c->tag; c->done(&exec_ctx, c->done_arg, c); goto done; } prev = c; } if (cc->shutdown) { gpr_mu_unlock(cc->mu); memset(&ret, 0, sizeof(ret)); ret.type = GRPC_QUEUE_SHUTDOWN; break; } if (!add_plucker(cc, tag, &worker)) { gpr_log(GPR_DEBUG, "Too many outstanding grpc_completion_queue_pluck calls: maximum " "is %d", GRPC_MAX_COMPLETION_QUEUE_PLUCKERS); gpr_mu_unlock(cc->mu); memset(&ret, 0, sizeof(ret)); /* TODO(ctiller): should we use a different result here */ ret.type = GRPC_QUEUE_TIMEOUT; break; } now = gpr_now(GPR_CLOCK_MONOTONIC); if (!first_loop && gpr_time_cmp(now, deadline) >= 0) { del_plucker(cc, tag, &worker); gpr_mu_unlock(cc->mu); memset(&ret, 0, sizeof(ret)); ret.type = GRPC_QUEUE_TIMEOUT; break; } first_loop = 0; /* Check alarms - these are a global resource so we just ping each time through on every pollset. May update deadline to ensure timely wakeups. TODO(ctiller): can this work be localized? */ gpr_timespec iteration_deadline = deadline; if (grpc_timer_check(&exec_ctx, now, &iteration_deadline)) { GPR_TIMER_MARK("alarm_triggered", 0); gpr_mu_unlock(cc->mu); grpc_exec_ctx_flush(&exec_ctx); gpr_mu_lock(cc->mu); } else { grpc_pollset_work(&exec_ctx, POLLSET_FROM_CQ(cc), &worker, now, iteration_deadline); } del_plucker(cc, tag, &worker); } done: GRPC_SURFACE_TRACE_RETURNED_EVENT(cc, &ret); GRPC_CQ_INTERNAL_UNREF(cc, "pluck"); grpc_exec_ctx_finish(&exec_ctx); GPR_TIMER_END("grpc_completion_queue_pluck", 0); return ret; } /* Shutdown simply drops a ref that we reserved at creation time; if we drop to zero here, then enter shutdown mode and wake up any waiters */ void grpc_completion_queue_shutdown(grpc_completion_queue *cc) { grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; GPR_TIMER_BEGIN("grpc_completion_queue_shutdown", 0); GRPC_API_TRACE("grpc_completion_queue_shutdown(cc=%p)", 1, (cc)); gpr_mu_lock(cc->mu); if (cc->shutdown_called) { gpr_mu_unlock(cc->mu); GPR_TIMER_END("grpc_completion_queue_shutdown", 0); return; } cc->shutdown_called = 1; if (gpr_unref(&cc->pending_events)) { GPR_ASSERT(!cc->shutdown); cc->shutdown = 1; grpc_pollset_shutdown(&exec_ctx, POLLSET_FROM_CQ(cc), &cc->pollset_shutdown_done); } gpr_mu_unlock(cc->mu); grpc_exec_ctx_finish(&exec_ctx); GPR_TIMER_END("grpc_completion_queue_shutdown", 0); } void grpc_completion_queue_destroy(grpc_completion_queue *cc) { GRPC_API_TRACE("grpc_completion_queue_destroy(cc=%p)", 1, (cc)); GPR_TIMER_BEGIN("grpc_completion_queue_destroy", 0); grpc_completion_queue_shutdown(cc); GRPC_CQ_INTERNAL_UNREF(cc, "destroy"); GPR_TIMER_END("grpc_completion_queue_destroy", 0); } grpc_pollset *grpc_cq_pollset(grpc_completion_queue *cc) { return POLLSET_FROM_CQ(cc); } void grpc_cq_mark_server_cq(grpc_completion_queue *cc) { cc->is_server_cq = 1; } int grpc_cq_is_server_cq(grpc_completion_queue *cc) { return cc->is_server_cq; }
miselin/grpc
src/core/lib/surface/completion_queue.c
C
bsd-3-clause
16,842
import shutil from nose.tools import * from holland.lib.lvm import LogicalVolume from holland.lib.lvm.snapshot import * from tests.constants import * class TestSnapshot(object): def setup(self): self.tmpdir = tempfile.mkdtemp() def teardown(self): shutil.rmtree(self.tmpdir) def test_snapshot_fsm(self): lv = LogicalVolume.lookup('%s/%s' % (TEST_VG, TEST_LV)) name = lv.lv_name + '_snapshot' size = 1 # extent snapshot = Snapshot(name, size, self.tmpdir) snapshot.start(lv) def test_snapshot_fsm_with_callbacks(self): lv = LogicalVolume.lookup('%s/%s' % (TEST_VG, TEST_LV)) name = lv.lv_name + '_snapshot' size = 1 # extent snapshot = Snapshot(name, size, self.tmpdir) def handle_event(event, *args, **kwargs): pass snapshot.register('pre-mount', handle_event) snapshot.register('post-mount', handle_event) snapshot.start(lv) def test_snapshot_fsm_with_failures(self): lv = LogicalVolume.lookup('%s/%s' % (TEST_VG, TEST_LV)) name = lv.lv_name + '_snapshot' size = 1 # extent snapshot = Snapshot(name, size, self.tmpdir) def bad_callback(event, *args, **kwargs): raise Exception("Oooh nooo!") for evt in ('initialize', 'pre-snapshot', 'post-snapshot', 'pre-mount', 'post-mount', 'pre-unmount', 'post-unmount', 'pre-remove', 'post-remove', 'finish'): snapshot.register(evt, bad_callback) assert_raises(CallbackFailuresError, snapshot.start, lv) snapshot.unregister(evt, bad_callback) if snapshot.sigmgr._handlers: raise Exception("WTF. sigmgr handlers still exist when checking event => %r", evt)
m00dawg/holland
plugins/holland.lib.lvm/tests/xfs/test_snapshot.py
Python
bsd-3-clause
1,824
/* * This file is part of Pebble. * * Copyright (c) 2014 by Mitchell Bösecke * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ package com.mitchellbosecke.pebble.extension; import com.mitchellbosecke.pebble.attributes.AttributeResolver; import com.mitchellbosecke.pebble.operator.BinaryOperator; import com.mitchellbosecke.pebble.operator.UnaryOperator; import com.mitchellbosecke.pebble.tokenParser.TokenParser; import java.util.List; import java.util.Map; public abstract class AbstractExtension implements Extension { @Override public List<TokenParser> getTokenParsers() { return null; } @Override public List<BinaryOperator> getBinaryOperators() { return null; } @Override public List<UnaryOperator> getUnaryOperators() { return null; } @Override public Map<String, Filter> getFilters() { return null; } @Override public Map<String, Test> getTests() { return null; } @Override public Map<String, Function> getFunctions() { return null; } @Override public Map<String, Object> getGlobalVariables() { return null; } @Override public List<NodeVisitorFactory> getNodeVisitors() { return null; } @Override public List<AttributeResolver> getAttributeResolver() { return null; } }
mbosecke/pebble
pebble/src/main/java/com/mitchellbosecke/pebble/extension/AbstractExtension.java
Java
bsd-3-clause
1,366
<!DOCTYPE html> <!-- Copyright (c) 2013 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. --> <link rel="import" href="/core/analysis/analysis_sub_view.html"> <link rel="import" href="/core/analysis/util.html"> <link rel="import" href="/core/analysis/analysis_link.html"> <link rel="import" href="/base/utils.html"> <polymer-element name="tv-c-single-cpu-slice-sub-view" extends="tracing-analysis-sub-view"> <template> <style> table { border-collapse: collapse; border-width: 0; margin-bottom: 25px; width: 100%; } table tr > td:first-child { padding-left: 2px; } table tr > td { padding: 2px 4px 2px 4px; vertical-align: text-top; width: 150px; } table td td { padding: 0 0 0 0; width: auto; } tr { vertical-align: top; } tr:nth-child(2n+0) { background-color: #e2e2e2; } </style> <table> <tr> <td>Running process:</td><td id="process-name"></td> </tr> <tr> <td>Running thread:</td><td id="thread-name"></td> </tr> <tr> <td>Start:</td><td id="start"></td> </tr> <tr> <td>Duration:</td><td id="duration"></td> </tr> <tr> <td>Active slices:</td><td id="running-thread"></td> </tr> <tr> <td>Args:</td> <td> <tv-c-analysis-generic-object-view id="args"> </tv-c-analysis-generic-object-view> </td> </tr> </table> </template> <script> 'use strict'; Polymer({ created: function() { this.currentSelection_ = undefined; }, get selection() { return this.currentSelection_; }, set selection(selection) { if (selection.length !== 1) throw new Error('Only supports single slices'); if (!(selection[0] instanceof tv.c.trace_model.CpuSlice)) throw new Error('Only supports thread time slices'); this.currentSelection_ = selection; var cpuSlice = selection[0]; var thread = cpuSlice.threadThatWasRunning; var shadowRoot = this.shadowRoot; if (thread) { shadowRoot.querySelector('#process-name').textContent = thread.parent.userFriendlyName; shadowRoot.querySelector('#thread-name').textContent = thread.userFriendlyName; } else { shadowRoot.querySelector('#process-name').parentElement.style.display = 'none'; shadowRoot.querySelector('#thread-name').textContent = cpuSlice.title; } shadowRoot.querySelector('#start').textContent = tv.c.analysis.tsString(cpuSlice.start); shadowRoot.querySelector('#duration').textContent = tv.c.analysis.tsString(cpuSlice.duration); var runningThreadEl = shadowRoot.querySelector('#running-thread'); var timeSlice = cpuSlice.getAssociatedTimeslice(); if (!timeSlice) { runningThreadEl.parentElement.style.display = 'none'; } else { var threadLink = document.createElement('tv-c-analysis-link'); threadLink.selection = new tv.c.Selection(timeSlice); threadLink.textContent = 'Click to select'; runningThreadEl.parentElement.style.display = ''; runningThreadEl.textContent = ''; runningThreadEl.appendChild(threadLink); } shadowRoot.querySelector('#args').object = cpuSlice.args; } }); </script> </polymer-element>
vmpstr/trace-viewer
trace_viewer/core/analysis/single_cpu_slice_sub_view.html
HTML
bsd-3-clause
3,547
//***************************************************************************** // // fontcmss46b.c - Font definition for the 46 point Cmss bold font. // // Copyright (c) 2008-2010 Texas Instruments Incorporated. All rights reserved. // Software License Agreement // // Texas Instruments (TI) is supplying this software for use solely and // exclusively on TI's microcontroller products. The software is owned by // TI and/or its suppliers, and is protected under applicable copyright // laws. You may not combine this software with "viral" open-source // software in order to form a larger program. // // THIS SOFTWARE IS PROVIDED "AS IS" AND WITH ALL FAULTS. // NO WARRANTIES, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT // NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. TI SHALL NOT, UNDER ANY // CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR CONSEQUENTIAL // DAMAGES, FOR ANY REASON WHATSOEVER. // // This is part of revision 6288 of the Stellaris Graphics Library. // //***************************************************************************** //***************************************************************************** // // This file is generated by ftrasterize; DO NOT EDIT BY HAND! // //***************************************************************************** #include "grlib.h" //***************************************************************************** // // Details of this font: // Style: cmss // Size: 46 point // Bold: yes // Italic: no // Memory usage: 5636 bytes // //***************************************************************************** //***************************************************************************** // // The compressed data for the 46 point Cmss bold font. // //***************************************************************************** static const unsigned char g_pucCmss46bData[5434] = { 5, 18, 0, 101, 32, 37, 10, 240, 86, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 240, 240, 70, 70, 70, 70, 70, 70, 0, 14, 32, 29, 20, 240, 240, 166, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 84, 100, 100, 100, 99, 115, 100, 100, 99, 115, 0, 80, 112, 129, 40, 0, 12, 18, 131, 240, 180, 115, 240, 180, 100, 240, 180, 100, 240, 164, 116, 240, 164, 116, 240, 164, 100, 240, 164, 116, 240, 164, 116, 240, 164, 100, 240, 180, 100, 240, 164, 116, 240, 164, 116, 223, 15, 4, 95, 15, 6, 79, 15, 6, 95, 15, 4, 240, 36, 100, 240, 164, 116, 240, 164, 116, 240, 164, 100, 240, 164, 116, 240, 164, 116, 240, 164, 100, 240, 47, 15, 4, 95, 15, 6, 79, 15, 6, 95, 15, 4, 228, 100, 240, 164, 116, 240, 164, 115, 240, 180, 100, 240, 164, 116, 240, 164, 116, 240, 164, 100, 240, 179, 116, 240, 164, 116, 240, 164, 115, 240, 180, 100, 240, 179, 116, 240, 179, 130, 0, 12, 80, 70, 23, 131, 240, 83, 240, 56, 206, 143, 1, 111, 2, 102, 19, 37, 86, 35, 67, 85, 51, 197, 51, 197, 51, 198, 35, 198, 35, 203, 219, 205, 190, 174, 173, 189, 218, 219, 195, 38, 195, 38, 195, 53, 195, 53, 195, 53, 66, 99, 53, 68, 67, 38, 70, 35, 22, 95, 3, 95, 2, 127, 172, 230, 240, 67, 240, 83, 0, 24, 64, 124, 44, 86, 240, 82, 234, 240, 36, 204, 245, 181, 54, 213, 196, 85, 212, 197, 101, 181, 197, 101, 165, 213, 101, 164, 229, 101, 149, 229, 101, 133, 245, 101, 117, 240, 21, 101, 116, 240, 53, 70, 101, 240, 53, 54, 101, 240, 78, 85, 240, 108, 100, 240, 152, 117, 240, 240, 133, 240, 240, 148, 104, 240, 165, 91, 240, 117, 92, 240, 101, 85, 54, 240, 84, 101, 69, 240, 69, 85, 101, 240, 37, 101, 101, 240, 36, 117, 101, 240, 20, 133, 101, 245, 133, 101, 229, 149, 101, 228, 165, 101, 213, 165, 101, 197, 181, 101, 181, 213, 69, 196, 229, 54, 181, 252, 196, 240, 42, 226, 240, 86, 0, 45, 16, 93, 37, 0, 6, 5, 240, 249, 240, 203, 240, 165, 53, 240, 133, 69, 240, 132, 101, 240, 101, 101, 240, 101, 101, 240, 101, 101, 240, 101, 101, 240, 101, 85, 240, 117, 69, 240, 134, 53, 240, 149, 22, 132, 219, 149, 201, 181, 200, 196, 230, 197, 215, 197, 201, 165, 188, 149, 165, 39, 117, 166, 39, 102, 165, 71, 85, 166, 87, 54, 166, 103, 22, 182, 109, 198, 123, 215, 121, 247, 91, 114, 95, 15, 2, 111, 15, 1, 126, 61, 167, 168, 0, 47, 17, 10, 240, 86, 70, 70, 70, 70, 70, 84, 100, 99, 100, 99, 0, 40, 112, 48, 16, 147, 196, 180, 180, 181, 180, 181, 165, 181, 181, 165, 181, 166, 166, 166, 165, 181, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 181, 182, 166, 166, 181, 181, 182, 181, 181, 197, 196, 197, 196, 212, 212, 211, 64, 48, 16, 3, 212, 212, 212, 197, 196, 197, 197, 181, 182, 181, 181, 182, 166, 166, 181, 182, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 165, 181, 166, 166, 165, 181, 166, 165, 181, 165, 180, 181, 180, 180, 180, 195, 208, 52, 23, 131, 240, 69, 240, 53, 240, 53, 195, 67, 67, 85, 51, 53, 70, 35, 38, 71, 19, 23, 95, 2, 155, 240, 19, 240, 27, 159, 2, 87, 19, 23, 70, 35, 38, 69, 51, 53, 83, 67, 67, 197, 240, 53, 240, 53, 240, 67, 0, 70, 64, 103, 38, 0, 30, 66, 240, 240, 84, 240, 240, 68, 240, 240, 68, 240, 240, 68, 240, 240, 68, 240, 240, 68, 240, 240, 68, 240, 240, 68, 240, 240, 68, 240, 240, 68, 240, 240, 68, 240, 240, 68, 240, 240, 68, 240, 95, 15, 2, 95, 15, 4, 79, 15, 4, 95, 15, 2, 240, 84, 240, 240, 68, 240, 240, 68, 240, 240, 68, 240, 240, 68, 240, 240, 68, 240, 240, 68, 240, 240, 68, 240, 240, 68, 240, 240, 68, 240, 240, 68, 240, 240, 68, 240, 240, 68, 240, 240, 68, 240, 240, 82, 0, 31, 18, 10, 0, 35, 6, 70, 70, 70, 70, 70, 84, 100, 99, 100, 99, 0, 8, 48, 9, 17, 0, 46, 109, 77, 77, 0, 43, 13, 10, 0, 35, 6, 70, 70, 70, 70, 70, 0, 14, 32, 94, 23, 240, 18, 240, 84, 240, 68, 240, 68, 240, 52, 240, 68, 240, 52, 240, 68, 240, 68, 240, 52, 240, 68, 240, 68, 240, 52, 240, 68, 240, 52, 240, 68, 240, 68, 240, 52, 240, 68, 240, 68, 240, 52, 240, 68, 240, 67, 240, 68, 240, 68, 240, 52, 240, 68, 240, 68, 240, 52, 240, 68, 240, 68, 240, 52, 240, 68, 240, 52, 240, 68, 240, 68, 240, 52, 240, 68, 240, 68, 240, 52, 240, 68, 240, 52, 240, 68, 240, 68, 240, 82, 240, 80, 71, 24, 240, 240, 22, 240, 26, 221, 165, 69, 149, 101, 133, 102, 102, 102, 101, 133, 101, 133, 86, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 85, 133, 101, 133, 102, 102, 102, 102, 118, 85, 149, 69, 174, 202, 240, 22, 0, 31, 48, 44, 21, 240, 243, 240, 21, 231, 156, 156, 156, 162, 54, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 175, 1, 79, 2, 95, 1, 0, 29, 48, 69, 24, 0, 6, 103, 252, 190, 159, 1, 118, 72, 85, 119, 85, 135, 83, 166, 98, 166, 98, 166, 240, 54, 240, 54, 240, 54, 240, 38, 240, 54, 240, 38, 240, 53, 240, 53, 240, 53, 240, 53, 240, 53, 240, 53, 240, 53, 240, 53, 240, 53, 240, 53, 240, 53, 240, 63, 4, 95, 4, 95, 4, 95, 4, 95, 4, 0, 33, 64, 66, 24, 240, 240, 23, 236, 190, 159, 1, 118, 86, 116, 134, 114, 150, 114, 150, 240, 54, 240, 54, 240, 53, 240, 54, 240, 53, 240, 54, 218, 233, 251, 240, 70, 240, 70, 240, 69, 240, 70, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 81, 198, 67, 182, 68, 150, 87, 87, 95, 3, 143, 173, 232, 0, 31, 32, 70, 25, 0, 7, 86, 240, 55, 240, 40, 240, 40, 240, 25, 240, 25, 244, 21, 244, 21, 229, 21, 228, 37, 213, 37, 212, 53, 197, 53, 196, 69, 181, 69, 180, 85, 165, 85, 149, 101, 149, 101, 133, 117, 133, 117, 143, 6, 79, 6, 79, 6, 79, 6, 240, 21, 240, 85, 240, 85, 240, 85, 240, 85, 240, 85, 240, 85, 0, 35, 48, 68, 24, 0, 6, 47, 1, 143, 1, 143, 1, 143, 1, 143, 1, 134, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 240, 61, 191, 159, 1, 135, 70, 117, 102, 117, 117, 131, 134, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 82, 182, 83, 165, 85, 134, 87, 87, 111, 2, 143, 188, 231, 0, 31, 48, 67, 24, 240, 240, 55, 235, 204, 189, 167, 82, 150, 240, 54, 240, 38, 240, 54, 240, 53, 240, 69, 240, 54, 54, 150, 41, 118, 27, 104, 70, 103, 102, 87, 117, 87, 118, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 85, 134, 85, 134, 85, 134, 86, 117, 117, 102, 118, 71, 143, 173, 203, 247, 0, 31, 32, 73, 24, 0, 6, 15, 4, 95, 5, 79, 5, 79, 5, 79, 4, 240, 53, 240, 54, 240, 53, 240, 53, 240, 54, 240, 53, 240, 54, 240, 53, 240, 54, 240, 53, 240, 54, 240, 53, 240, 54, 240, 54, 240, 54, 240, 38, 240, 54, 240, 54, 240, 54, 240, 53, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 0, 31, 96, 65, 24, 240, 248, 236, 190, 159, 1, 118, 87, 101, 133, 101, 133, 101, 133, 101, 133, 101, 133, 101, 133, 101, 133, 102, 102, 118, 70, 158, 202, 206, 150, 70, 118, 102, 101, 133, 86, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 86, 102, 103, 71, 127, 1, 158, 188, 232, 0, 31, 32, 67, 24, 240, 240, 22, 251, 206, 159, 150, 70, 118, 101, 117, 118, 86, 133, 86, 133, 86, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 119, 85, 119, 86, 103, 102, 57, 107, 22, 121, 38, 150, 54, 240, 53, 240, 69, 240, 69, 240, 54, 240, 53, 145, 134, 132, 86, 158, 158, 188, 247, 0, 31, 64, 21, 10, 0, 16, 38, 70, 70, 70, 70, 70, 0, 11, 102, 70, 70, 70, 70, 70, 0, 14, 32, 26, 10, 0, 16, 38, 70, 70, 70, 70, 70, 0, 11, 102, 70, 70, 70, 70, 70, 84, 100, 99, 100, 99, 0, 8, 48, 37, 10, 0, 13, 102, 70, 70, 70, 70, 70, 240, 240, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 240, 144, 32, 37, 0, 69, 79, 15, 1, 95, 15, 3, 79, 15, 3, 95, 15, 1, 0, 33, 31, 15, 1, 95, 15, 3, 79, 15, 3, 95, 15, 1, 0, 70, 57, 22, 0, 31, 5, 240, 23, 247, 247, 247, 240, 21, 0, 10, 53, 240, 37, 240, 37, 240, 37, 240, 37, 240, 37, 240, 21, 240, 37, 240, 22, 240, 21, 240, 22, 246, 247, 246, 246, 240, 22, 240, 22, 240, 22, 146, 86, 132, 86, 86, 95, 2, 111, 153, 0, 6, 80, 49, 21, 0, 5, 104, 174, 111, 1, 85, 86, 84, 118, 81, 150, 246, 246, 246, 231, 215, 230, 230, 230, 245, 240, 21, 245, 240, 21, 240, 21, 240, 20, 240, 36, 240, 36, 240, 36, 0, 9, 118, 246, 246, 246, 246, 246, 0, 30, 16, 84, 31, 0, 9, 25, 240, 78, 255, 3, 199, 102, 182, 165, 149, 198, 117, 124, 117, 94, 101, 95, 1, 85, 69, 72, 85, 53, 118, 84, 69, 118, 69, 53, 149, 69, 53, 149, 69, 53, 149, 69, 53, 149, 69, 53, 149, 69, 53, 149, 69, 53, 149, 69, 53, 149, 69, 53, 149, 85, 53, 117, 101, 53, 117, 101, 70, 69, 133, 77, 149, 91, 181, 103, 215, 240, 168, 150, 175, 4, 239, 240, 73, 0, 44, 80, 33, 0, 9, 87, 240, 169, 240, 139, 240, 123, 240, 123, 240, 109, 240, 93, 240, 86, 22, 240, 70, 39, 240, 54, 39, 240, 54, 39, 240, 38, 71, 240, 22, 71, 240, 22, 71, 246, 103, 230, 103, 230, 103, 214, 135, 198, 135, 198, 135, 182, 167, 175, 8, 175, 8, 159, 10, 143, 10, 134, 214, 118, 231, 102, 231, 102, 246, 86, 240, 23, 70, 240, 23, 69, 240, 54, 0, 45, 112, 71, 30, 0, 7, 79, 3, 207, 6, 159, 7, 143, 8, 118, 153, 102, 183, 102, 199, 86, 214, 86, 214, 86, 214, 86, 198, 102, 198, 102, 182, 118, 151, 143, 6, 159, 4, 191, 7, 134, 168, 102, 199, 86, 214, 86, 215, 70, 230, 70, 230, 70, 230, 70, 230, 70, 215, 70, 214, 86, 184, 95, 9, 111, 8, 127, 7, 143, 4, 0, 42, 80, 71, 30, 0, 8, 122, 240, 47, 2, 191, 4, 175, 5, 152, 118, 135, 195, 119, 225, 134, 240, 134, 240, 150, 240, 150, 240, 134, 240, 150, 240, 150, 240, 150, 240, 150, 240, 150, 240, 150, 240, 150, 240, 150, 240, 150, 240, 166, 240, 150, 240, 150, 240, 166, 240, 151, 241, 135, 211, 137, 118, 143, 7, 175, 5, 207, 1, 240, 42, 0, 42, 48, 87, 33, 0, 8, 47, 4, 239, 7, 191, 9, 159, 10, 134, 170, 118, 215, 118, 231, 102, 246, 102, 240, 22, 86, 240, 22, 86, 240, 37, 86, 240, 38, 70, 240, 38, 70, 240, 38, 70, 240, 38, 70, 240, 38, 70, 240, 38, 70, 240, 38, 70, 240, 38, 70, 240, 38, 70, 240, 38, 70, 240, 38, 70, 240, 22, 86, 240, 22, 86, 247, 86, 231, 102, 215, 118, 185, 127, 10, 143, 9, 159, 7, 191, 4, 0, 47, 16, 71, 26, 0, 6, 79, 6, 95, 6, 95, 6, 95, 6, 95, 6, 86, 240, 86, 240, 86, 240, 86, 240, 86, 240, 86, 240, 86, 240, 86, 240, 86, 240, 95, 5, 111, 5, 111, 5, 111, 5, 102, 240, 86, 240, 86, 240, 86, 240, 86, 240, 86, 240, 86, 240, 86, 240, 86, 240, 95, 7, 79, 7, 79, 7, 79, 7, 79, 7, 0, 36, 32, 70, 25, 0, 6, 47, 5, 95, 6, 79, 6, 79, 6, 79, 5, 86, 240, 70, 240, 70, 240, 70, 240, 70, 240, 70, 240, 70, 240, 70, 240, 70, 240, 79, 3, 127, 4, 111, 4, 111, 3, 118, 240, 70, 240, 70, 240, 70, 240, 70, 240, 70, 240, 70, 240, 70, 240, 70, 240, 70, 240, 70, 240, 70, 240, 70, 240, 70, 0, 36, 96, 72, 30, 0, 8, 122, 240, 47, 1, 207, 5, 159, 6, 136, 134, 119, 195, 119, 226, 118, 240, 17, 102, 240, 150, 240, 150, 240, 134, 240, 150, 240, 150, 240, 150, 240, 150, 240, 150, 240, 150, 170, 70, 170, 70, 170, 70, 170, 86, 214, 86, 214, 87, 198, 102, 198, 103, 182, 119, 166, 136, 134, 159, 6, 175, 5, 207, 1, 240, 42, 0, 42, 48, 71, 31, 0, 7, 102, 246, 70, 246, 70, 246, 70, 246, 70, 246, 70, 246, 70, 246, 70, 246, 70, 246, 70, 246, 70, 246, 70, 246, 70, 246, 70, 246, 79, 12, 79, 12, 79, 12, 79, 12, 70, 246, 70, 246, 70, 246, 70, 246, 70, 246, 70, 246, 70, 246, 70, 246, 70, 246, 70, 246, 70, 246, 70, 246, 70, 246, 70, 246, 0, 43, 16, 38, 10, 240, 86, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 0, 14, 32, 43, 21, 0, 6, 86, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 81, 150, 82, 134, 84, 71, 111, 95, 125, 184, 0, 27, 48, 75, 32, 0, 8, 6, 246, 86, 231, 86, 215, 102, 199, 118, 183, 134, 167, 150, 151, 166, 135, 182, 119, 198, 103, 214, 87, 230, 71, 246, 55, 240, 22, 24, 240, 47, 1, 240, 31, 2, 255, 2, 255, 3, 234, 39, 217, 71, 200, 87, 199, 119, 182, 151, 166, 166, 166, 167, 150, 183, 134, 199, 118, 199, 118, 215, 102, 231, 86, 247, 70, 240, 21, 0, 44, 80, 71, 23, 0, 5, 102, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 47, 4, 79, 4, 79, 4, 79, 4, 79, 4, 0, 32, 16, 117, 40, 0, 10, 8, 240, 88, 73, 240, 57, 74, 240, 26, 74, 240, 26, 74, 240, 26, 75, 235, 75, 235, 70, 20, 228, 22, 70, 21, 197, 22, 70, 21, 197, 22, 70, 37, 165, 38, 70, 37, 165, 38, 70, 37, 165, 38, 70, 53, 133, 54, 70, 53, 133, 54, 70, 54, 101, 70, 70, 69, 101, 70, 70, 69, 101, 70, 70, 85, 69, 86, 70, 85, 69, 86, 70, 85, 69, 86, 70, 101, 37, 102, 70, 101, 37, 102, 70, 107, 118, 70, 122, 118, 70, 122, 118, 70, 136, 134, 70, 136, 134, 70, 135, 150, 70, 150, 150, 70, 164, 166, 70, 240, 150, 0, 55, 64, 89, 32, 0, 8, 24, 229, 74, 198, 74, 198, 75, 182, 75, 182, 76, 166, 76, 166, 70, 22, 150, 70, 22, 150, 70, 38, 134, 70, 38, 134, 70, 54, 118, 70, 54, 118, 70, 70, 102, 70, 70, 102, 70, 86, 86, 70, 86, 86, 70, 102, 70, 70, 102, 70, 70, 118, 54, 70, 118, 54, 70, 134, 38, 70, 134, 38, 70, 150, 22, 70, 150, 22, 70, 172, 70, 172, 70, 187, 70, 187, 70, 202, 70, 202, 70, 217, 0, 44, 64, 86, 33, 240, 240, 217, 240, 111, 240, 47, 3, 223, 6, 199, 120, 166, 182, 150, 214, 134, 214, 118, 246, 102, 246, 102, 246, 101, 240, 38, 70, 240, 38, 70, 240, 38, 70, 240, 38, 70, 240, 38, 70, 240, 38, 70, 240, 38, 70, 240, 38, 70, 240, 38, 70, 240, 38, 70, 240, 38, 70, 240, 38, 86, 246, 102, 246, 102, 246, 118, 214, 135, 183, 151, 151, 169, 104, 191, 6, 223, 4, 240, 31, 240, 105, 0, 43, 70, 29, 0, 7, 47, 3, 191, 6, 143, 7, 127, 8, 102, 168, 86, 198, 86, 199, 70, 214, 70, 214, 70, 214, 70, 214, 70, 214, 70, 214, 70, 199, 70, 198, 86, 168, 95, 8, 111, 7, 127, 6, 143, 3, 182, 240, 134, 240, 134, 240, 134, 240, 134, 240, 134, 240, 134, 240, 134, 240, 134, 240, 134, 240, 134, 240, 134, 0, 42, 96, 104, 34, 240, 240, 234, 240, 127, 240, 47, 3, 255, 6, 200, 104, 183, 167, 151, 199, 134, 230, 118, 240, 22, 102, 240, 22, 102, 240, 22, 101, 240, 54, 70, 240, 54, 70, 240, 54, 70, 240, 54, 70, 240, 54, 70, 240, 54, 70, 240, 54, 70, 240, 54, 70, 240, 54, 70, 240, 54, 70, 240, 54, 70, 240, 54, 86, 240, 23, 86, 102, 70, 102, 103, 54, 118, 103, 23, 119, 94, 151, 93, 153, 75, 191, 7, 239, 3, 240, 47, 3, 240, 79, 1, 240, 200, 240, 184, 240, 200, 240, 199, 0, 26, 32, 71, 29, 0, 7, 47, 3, 191, 6, 143, 7, 127, 8, 102, 168, 86, 198, 86, 199, 70, 214, 70, 214, 70, 214, 70, 214, 70, 214, 70, 199, 70, 198, 86, 167, 111, 7, 127, 6, 143, 4, 166, 103, 166, 103, 166, 119, 150, 134, 150, 135, 134, 150, 134, 151, 118, 167, 102, 182, 102, 183, 86, 198, 86, 199, 70, 214, 70, 229, 0, 40, 48, 65, 26, 0, 7, 57, 239, 159, 3, 143, 3, 119, 102, 118, 148, 102, 193, 118, 240, 86, 240, 86, 240, 87, 240, 73, 240, 59, 255, 207, 1, 191, 1, 191, 1, 207, 236, 240, 56, 240, 87, 240, 71, 240, 86, 240, 86, 66, 230, 67, 214, 69, 167, 71, 119, 95, 6, 95, 5, 127, 3, 175, 233, 0, 33, 112, 70, 32, 0, 8, 15, 13, 79, 13, 79, 13, 79, 13, 79, 13, 246, 240, 182, 240, 182, 240, 182, 240, 182, 240, 182, 240, 182, 240, 182, 240, 182, 240, 182, 240, 182, 240, 182, 240, 182, 240, 182, 240, 182, 240, 182, 240, 182, 240, 182, 240, 182, 240, 182, 240, 182, 240, 182, 240, 182, 240, 182, 240, 182, 240, 182, 240, 182, 0, 45, 112, 72, 30, 0, 7, 70, 230, 70, 230, 70, 230, 70, 230, 70, 230, 70, 230, 70, 230, 70, 230, 70, 230, 70, 230, 70, 230, 70, 230, 70, 230, 70, 230, 70, 230, 70, 230, 70, 230, 70, 230, 70, 230, 70, 230, 70, 230, 70, 230, 70, 230, 70, 230, 70, 230, 86, 199, 86, 198, 103, 167, 120, 104, 159, 5, 191, 3, 223, 240, 57, 0, 39, 16, 82, 35, 0, 8, 102, 240, 70, 71, 240, 54, 87, 240, 22, 103, 240, 22, 103, 247, 119, 230, 135, 230, 135, 215, 151, 198, 167, 198, 167, 183, 183, 166, 199, 166, 214, 150, 231, 134, 231, 119, 247, 102, 240, 23, 102, 240, 23, 87, 240, 39, 70, 240, 55, 70, 240, 55, 55, 240, 71, 38, 240, 87, 38, 240, 102, 22, 240, 125, 240, 125, 240, 139, 240, 155, 240, 155, 240, 169, 240, 185, 0, 50, 122, 49, 0, 12, 37, 231, 228, 86, 216, 198, 70, 201, 197, 102, 185, 197, 102, 185, 197, 102, 171, 166, 102, 171, 165, 134, 149, 21, 165, 134, 149, 21, 165, 134, 133, 38, 134, 134, 133, 38, 133, 166, 117, 53, 133, 166, 117, 54, 102, 166, 101, 70, 102, 166, 101, 70, 101, 198, 85, 85, 101, 198, 85, 86, 70, 198, 69, 102, 69, 230, 53, 102, 69, 230, 53, 117, 69, 230, 53, 118, 38, 230, 37, 134, 37, 240, 22, 21, 134, 37, 240, 22, 21, 149, 37, 240, 22, 20, 172, 240, 27, 171, 240, 58, 186, 240, 58, 186, 240, 57, 202, 240, 57, 201, 240, 88, 216, 240, 87, 231, 0, 69, 77, 34, 0, 8, 87, 215, 120, 184, 136, 167, 152, 151, 184, 120, 200, 103, 232, 71, 240, 23, 56, 240, 24, 39, 240, 63, 240, 93, 240, 124, 240, 123, 240, 153, 240, 184, 240, 184, 240, 169, 240, 170, 240, 140, 240, 110, 240, 71, 23, 240, 71, 39, 240, 39, 56, 247, 88, 216, 103, 215, 135, 183, 152, 152, 168, 135, 199, 119, 216, 88, 232, 71, 240, 23, 0, 47, 32, 74, 34, 0, 8, 71, 240, 38, 72, 247, 87, 231, 104, 215, 120, 183, 151, 167, 168, 151, 184, 119, 215, 103, 232, 87, 248, 55, 240, 39, 39, 240, 56, 23, 240, 78, 240, 108, 240, 124, 240, 138, 240, 168, 240, 199, 240, 198, 240, 214, 240, 214, 240, 214, 240, 214, 240, 214, 240, 214, 240, 214, 240, 214, 240, 214, 240, 214, 240, 214, 240, 214, 0, 48, 96, 72, 29, 0, 7, 63, 9, 95, 9, 95, 9, 95, 9, 95, 9, 240, 88, 240, 103, 240, 103, 240, 104, 240, 103, 240, 103, 240, 103, 240, 104, 240, 103, 240, 103, 240, 103, 240, 104, 240, 103, 240, 103, 240, 104, 240, 103, 240, 103, 240, 103, 240, 104, 240, 103, 240, 103, 240, 103, 240, 127, 9, 79, 10, 79, 10, 79, 10, 79, 10, 0, 40, 48, 48, 15, 10, 91, 74, 86, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 154, 91, 74, 80, 29, 21, 240, 240, 243, 131, 100, 116, 99, 131, 100, 116, 100, 116, 86, 86, 70, 86, 70, 86, 70, 86, 70, 86, 70, 86, 0, 84, 64, 48, 15, 26, 75, 90, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 90, 75, 90, 64, 17, 19, 240, 240, 213, 215, 185, 149, 21, 117, 52, 100, 100, 83, 132, 0, 86, 10, 10, 240, 86, 70, 70, 70, 70, 0, 48, 17, 10, 240, 131, 100, 99, 100, 100, 86, 70, 70, 70, 70, 70, 0, 40, 64, 48, 24, 0, 36, 105, 206, 159, 2, 117, 102, 115, 150, 98, 166, 240, 54, 240, 54, 240, 54, 204, 143, 1, 103, 86, 87, 102, 86, 118, 70, 134, 70, 134, 70, 134, 71, 103, 87, 72, 92, 22, 106, 38, 134, 84, 0, 33, 80, 71, 24, 0, 6, 6, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 54, 150, 26, 127, 3, 104, 71, 86, 118, 86, 118, 86, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 118, 86, 118, 87, 86, 111, 3, 102, 25, 149, 38, 0, 34, 32, 45, 23, 0, 35, 56, 205, 159, 127, 1, 103, 100, 102, 146, 101, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 54, 161, 102, 146, 103, 101, 111, 2, 127, 157, 200, 0, 32, 96, 69, 25, 0, 8, 37, 240, 70, 240, 70, 240, 70, 240, 70, 240, 70, 240, 70, 240, 70, 240, 70, 240, 70, 240, 70, 166, 54, 138, 22, 127, 3, 103, 87, 86, 134, 86, 134, 70, 150, 70, 150, 70, 150, 70, 150, 70, 150, 70, 150, 70, 150, 70, 150, 70, 150, 86, 134, 86, 134, 102, 88, 111, 4, 138, 22, 166, 68, 0, 35, 45, 25, 0, 41, 72, 253, 175, 1, 135, 86, 102, 133, 102, 148, 101, 165, 70, 165, 70, 165, 79, 6, 79, 6, 70, 240, 70, 240, 70, 240, 86, 240, 70, 194, 102, 163, 103, 102, 127, 3, 158, 232, 0, 35, 64, 41, 20, 0, 6, 8, 170, 155, 134, 66, 118, 97, 118, 230, 230, 230, 230, 230, 204, 125, 140, 166, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 0, 28, 112, 63, 27, 0, 44, 89, 68, 143, 4, 127, 5, 102, 70, 181, 102, 150, 102, 150, 102, 150, 102, 150, 102, 150, 102, 150, 102, 166, 70, 206, 221, 225, 40, 243, 240, 147, 240, 159, 1, 191, 3, 175, 4, 143, 4, 111, 7, 85, 182, 69, 213, 69, 213, 70, 197, 86, 150, 127, 4, 159, 2, 219, 0, 8, 71, 23, 0, 5, 102, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 70, 118, 42, 86, 27, 89, 55, 71, 102, 71, 102, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 0, 32, 16, 35, 10, 240, 86, 70, 70, 70, 70, 70, 0, 6, 102, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 0, 14, 32, 46, 17, 240, 240, 182, 167, 167, 167, 167, 182, 0, 12, 6, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 66, 71, 76, 92, 91, 150, 240, 240, 192, 65, 23, 0, 5, 101, 240, 53, 240, 53, 240, 53, 240, 53, 240, 53, 240, 53, 240, 53, 240, 53, 240, 53, 240, 53, 240, 53, 118, 85, 103, 85, 87, 101, 71, 117, 55, 133, 39, 149, 23, 172, 187, 203, 204, 189, 174, 150, 38, 149, 70, 133, 86, 117, 87, 101, 102, 101, 118, 85, 134, 69, 134, 0, 32, 16, 38, 10, 240, 86, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 0, 14, 32, 71, 37, 0, 60, 22, 70, 134, 118, 42, 58, 102, 27, 44, 86, 18, 58, 71, 71, 104, 102, 71, 103, 118, 70, 118, 134, 70, 118, 134, 70, 118, 134, 70, 118, 134, 70, 118, 134, 70, 118, 134, 70, 118, 134, 70, 118, 134, 70, 118, 134, 70, 118, 134, 70, 118, 134, 70, 118, 134, 70, 118, 134, 70, 118, 134, 70, 118, 134, 0, 51, 48, 50, 23, 0, 37, 54, 70, 118, 42, 86, 27, 86, 18, 55, 71, 102, 71, 102, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 0, 32, 16, 45, 26, 0, 43, 24, 254, 191, 1, 150, 102, 118, 134, 102, 134, 101, 165, 86, 166, 70, 166, 70, 166, 70, 166, 70, 166, 70, 166, 70, 166, 86, 135, 86, 134, 104, 87, 127, 3, 159, 1, 190, 248, 0, 37, 16, 67, 24, 0, 37, 37, 150, 41, 118, 27, 111, 4, 88, 71, 86, 118, 86, 119, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 118, 86, 118, 87, 71, 111, 2, 118, 25, 134, 38, 166, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 0, 8, 32, 69, 24, 0, 36, 101, 69, 137, 22, 127, 2, 111, 3, 88, 56, 86, 103, 86, 118, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 86, 118, 86, 103, 102, 72, 111, 3, 122, 22, 150, 54, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 0, 6, 64, 32, 17, 0, 27, 86, 67, 70, 37, 70, 22, 70, 22, 74, 120, 151, 167, 166, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 0, 24, 96, 34, 19, 0, 29, 8, 156, 109, 101, 68, 85, 114, 85, 229, 231, 203, 156, 140, 139, 170, 214, 244, 81, 148, 67, 132, 69, 85, 78, 94, 123, 167, 0, 27, 16, 35, 20, 0, 17, 118, 230, 230, 230, 230, 230, 191, 95, 95, 134, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 231, 51, 125, 140, 138, 197, 0, 28, 80, 50, 23, 0, 37, 54, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 103, 70, 103, 71, 72, 91, 22, 105, 37, 135, 0, 30, 48, 43, 24, 0, 39, 5, 165, 70, 149, 70, 134, 85, 133, 101, 133, 102, 102, 117, 101, 133, 101, 134, 70, 149, 69, 165, 69, 166, 38, 166, 38, 181, 37, 204, 204, 218, 234, 234, 248, 240, 24, 0, 34, 32, 71, 35, 0, 56, 117, 147, 149, 69, 133, 133, 70, 117, 118, 85, 102, 117, 101, 103, 101, 102, 87, 101, 102, 87, 86, 117, 67, 21, 69, 133, 67, 21, 69, 134, 51, 21, 69, 134, 36, 21, 53, 165, 36, 37, 37, 165, 35, 53, 37, 166, 19, 53, 22, 185, 53, 21, 201, 74, 200, 90, 200, 90, 215, 89, 230, 120, 245, 119, 0, 49, 48, 45, 24, 0, 39, 6, 133, 86, 118, 102, 86, 134, 70, 150, 38, 188, 203, 233, 240, 24, 240, 38, 240, 54, 240, 39, 240, 40, 250, 213, 37, 182, 38, 150, 69, 149, 101, 118, 102, 86, 134, 69, 165, 0, 33, 64, 61, 24, 0, 39, 5, 165, 70, 149, 70, 134, 86, 117, 102, 117, 118, 86, 118, 85, 149, 70, 150, 54, 165, 53, 182, 37, 182, 21, 213, 21, 219, 233, 249, 240, 24, 240, 23, 240, 54, 240, 54, 240, 53, 240, 69, 240, 69, 240, 68, 240, 69, 194, 69, 219, 218, 233, 240, 22, 0, 8, 16, 34, 22, 0, 35, 127, 2, 95, 2, 95, 2, 246, 247, 231, 246, 246, 247, 231, 246, 246, 247, 246, 246, 246, 247, 246, 255, 3, 79, 3, 79, 3, 0, 30, 96, 13, 29, 0, 72, 79, 10, 79, 10, 79, 10, 0, 80, 32, 22, 54, 0, 127, 0, 8, 15, 15, 15, 5, 79, 15, 15, 5, 79, 15, 15, 5, 0, 127, 0, 22, 21, 19, 240, 240, 150, 38, 85, 53, 101, 53, 85, 68, 100, 69, 100, 68, 115, 83, 0, 86, 64, 19, 20, 240, 240, 212, 99, 103, 67, 90, 20, 68, 26, 83, 72, 83, 100, 0, 93, 48, }; //***************************************************************************** // // The font definition for the 46 point Cmss bold font. // //***************************************************************************** const tFont g_sFontCmss46b = { // // The format of the font. // FONT_FMT_PIXEL_RLE, // // The maximum width of the font. // 49, // // The height of the font. // 45, // // The baseline of the font. // 34, // // The offset to each character in the font. // { 0, 5, 42, 71, 200, 270, 394, 487, 504, 552, 600, 652, 755, 773, 782, 795, 889, 960, 1004, 1073, 1139, 1209, 1277, 1344, 1417, 1482, 1549, 1570, 1596, 1633, 1665, 1722, 1771, 1855, 1935, 2006, 2077, 2164, 2235, 2305, 2377, 2448, 2486, 2529, 2604, 2675, 2792, 2881, 2967, 3037, 3141, 3212, 3277, 3347, 3419, 3501, 3623, 3700, 3774, 3846, 3894, 3923, 3971, 3988, 3998, 4015, 4063, 4134, 4179, 4248, 4293, 4334, 4397, 4468, 4503, 4549, 4614, 4652, 4723, 4773, 4818, 4885, 4954, 4986, 5020, 5055, 5105, 5148, 5219, 5264, 5325, 5359, 5372, 5394, 5415, }, // // A pointer to the actual font data // g_pucCmss46bData };
vastsoun/bbmc-starterware
grlib/fonts/fontcmss46b.c
C
bsd-3-clause
32,274
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.cluster.routing.allocation; import org.elasticsearch.Version; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.metadata.IndexMetaData; import org.elasticsearch.cluster.metadata.MetaData; import org.elasticsearch.cluster.node.DiscoveryNodes; import org.elasticsearch.cluster.routing.IndexRoutingTable; import org.elasticsearch.cluster.routing.IndexShardRoutingTable; import org.elasticsearch.cluster.routing.RoutingTable; import org.elasticsearch.cluster.routing.ShardRouting; import org.elasticsearch.cluster.routing.ShardRoutingState; import org.elasticsearch.cluster.routing.TestShardRouting; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.cluster.ESAllocationTestCase; import java.io.BufferedReader; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import static org.elasticsearch.cluster.routing.ShardRoutingState.INITIALIZING; /** * A base testcase that allows to run tests based on the output of the CAT API * The input is a line based cat/shards output like: * kibana-int 0 p STARTED 2 24.8kb 10.202.245.2 r5-9-35 * * the test builds up a clusterstate from the cat input and optionally runs a full balance on it. * This can be used to debug cluster allocation decisions. */ public abstract class CatAllocationTestCase extends ESAllocationTestCase { protected abstract Path getCatPath() throws IOException; public void testRun() throws IOException { Set<String> nodes = new HashSet<>(); Map<String, Idx> indices = new HashMap<>(); try (BufferedReader reader = Files.newBufferedReader(getCatPath(), StandardCharsets.UTF_8)) { String line = null; // regexp FTW Pattern pattern = Pattern.compile("^(.+)\\s+(\\d)\\s+([rp])\\s+(STARTED|RELOCATING|INITIALIZING|UNASSIGNED)" + "\\s+\\d+\\s+[0-9.a-z]+\\s+(\\d+\\.\\d+\\.\\d+\\.\\d+).*$"); while((line = reader.readLine()) != null) { final Matcher matcher; if ((matcher = pattern.matcher(line)).matches()) { final String index = matcher.group(1); Idx idx = indices.get(index); if (idx == null) { idx = new Idx(index); indices.put(index, idx); } final int shard = Integer.parseInt(matcher.group(2)); final boolean primary = matcher.group(3).equals("p"); ShardRoutingState state = ShardRoutingState.valueOf(matcher.group(4)); String ip = matcher.group(5); nodes.add(ip); ShardRouting routing = TestShardRouting.newShardRouting(index, shard, ip, null, primary, state); idx.add(routing); logger.debug("Add routing {}", routing); } else { fail("can't read line: " + line); } } } logger.info("Building initial routing table"); MetaData.Builder builder = MetaData.builder(); RoutingTable.Builder routingTableBuilder = RoutingTable.builder(); for(Idx idx : indices.values()) { IndexMetaData.Builder idxMetaBuilder = IndexMetaData.builder(idx.name).settings(settings(Version.CURRENT)) .numberOfShards(idx.numShards()).numberOfReplicas(idx.numReplicas()); for (ShardRouting shardRouting : idx.routing) { if (shardRouting.active()) { Set<String> allocationIds = idxMetaBuilder.getInSyncAllocationIds(shardRouting.id()); if (allocationIds == null) { allocationIds = new HashSet<>(); } else { allocationIds = new HashSet<>(allocationIds); } allocationIds.add(shardRouting.allocationId().getId()); idxMetaBuilder.putInSyncAllocationIds(shardRouting.id(), allocationIds); } } IndexMetaData idxMeta = idxMetaBuilder.build(); builder.put(idxMeta, false); IndexRoutingTable.Builder tableBuilder = new IndexRoutingTable.Builder(idxMeta.getIndex()).initializeAsRecovery(idxMeta); Map<Integer, IndexShardRoutingTable> shardIdToRouting = new HashMap<>(); for (ShardRouting r : idx.routing) { IndexShardRoutingTable refData = new IndexShardRoutingTable.Builder(r.shardId()).addShard(r).build(); if (shardIdToRouting.containsKey(r.getId())) { refData = new IndexShardRoutingTable.Builder(shardIdToRouting.get(r.getId())).addShard(r).build(); } shardIdToRouting.put(r.getId(), refData); } for (IndexShardRoutingTable t: shardIdToRouting.values()) { tableBuilder.addIndexShard(t); } IndexRoutingTable table = tableBuilder.build(); routingTableBuilder.add(table); } MetaData metaData = builder.build(); RoutingTable routingTable = routingTableBuilder.build(); DiscoveryNodes.Builder builderDiscoNodes = DiscoveryNodes.builder(); for (String node : nodes) { builderDiscoNodes.add(newNode(node)); } ClusterState clusterState = ClusterState.builder(org.elasticsearch.cluster.ClusterName.CLUSTER_NAME_SETTING .getDefault(Settings.EMPTY)).metaData(metaData).routingTable(routingTable).nodes(builderDiscoNodes.build()).build(); if (balanceFirst()) { clusterState = rebalance(clusterState); } clusterState = allocateNew(clusterState); } protected abstract ClusterState allocateNew(ClusterState clusterState); protected boolean balanceFirst() { return true; } private ClusterState rebalance(ClusterState clusterState) { RoutingTable routingTable;AllocationService strategy = createAllocationService(Settings.builder() .build()); RoutingAllocation.Result routingResult = strategy.reroute(clusterState, "reroute"); clusterState = ClusterState.builder(clusterState).routingResult(routingResult).build(); int numRelocations = 0; while (true) { List<ShardRouting> initializing = clusterState.routingTable().shardsWithState(INITIALIZING); if (initializing.isEmpty()) { break; } logger.debug("Initializing shards: {}", initializing); numRelocations += initializing.size(); routingResult = strategy.applyStartedShards(clusterState, initializing); clusterState = ClusterState.builder(clusterState).routingResult(routingResult).build(); } logger.debug("--> num relocations to get balance: {}", numRelocations); return clusterState; } public class Idx { final String name; final List<ShardRouting> routing = new ArrayList<>(); public Idx(String name) { this.name = name; } public void add(ShardRouting r) { routing.add(r); } public int numReplicas() { int count = 0; for (ShardRouting msr : routing) { if (msr.primary() == false && msr.id()==0) { count++; } } return count; } public int numShards() { int max = 0; for (ShardRouting msr : routing) { if (msr.primary()) { max = Math.max(msr.getId()+1, max); } } return max; } } }
strahanjen/strahanjen.github.io
elasticsearch-master/core/src/test/java/org/elasticsearch/cluster/routing/allocation/CatAllocationTestCase.java
Java
bsd-3-clause
8,869
.editable:hover { background-color: #FDFDFF; box-shadow: 0 0 20px #D5E3ED; -webkit-background-clip: padding-box; -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; } #wysihtml5-toolbar { box-shadow: 0 0 5px #999; position: fixed; top: 10px; left: 10px; width: 50px; -webkit-background-clip: padding-box; -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; } #wysihtml5-toolbar .dialog { background-color: #f8f8f7; box-shadow: 0 0 10px #999; display: block; left: 60px; padding: 10px; position: absolute; top: 120px; width: 300px; -webkit-background-clip: padding-box; -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; } #wysihtml5-toolbar a { display: inline-block; height: 50px; width: 48px; border: 1px solid #ddd; } #wysihtml5-toolbar a.cmd { background-color: #f8f8f7; background-position: center center; background-repeat: no-repeat; text-indent: -999px; } #wysihtml5-toolbar a.cmd:first-child { -webkit-border-radius: 5px 5px 0 0; -moz-border-radius: 5px 5px 0 0; border-radius: 5px 5px 0 0; } #wysihtml5-toolbar a.cmd:last-child { background-color: red; -webkit-border-radius: 0 0 5px 5px; -moz-border-radius: 0 0 5px 5px; border-radius: 0 0 5px 5px; } #wysihtml5-toolbar a.italic { background-image: url(/static/images/icons/glyphicons_101_italic.png); } #wysihtml5-toolbar a.bold { background-image: url(/static/images/icons/glyphicons_102_bold.png); } #wysihtml5-toolbar a.link { background-image: url(/static/images/icons/glyphicons_050_link.png); } #wysihtml5-toolbar a.img { background-image: url(/static/images/icons/glyphicons_011_camera.png); } #wysihtml5-toolbar a.list { background-image: url(/static/images/icons/glyphicons_114_list.png); } #wysihtml5-toolbar a.blockquote { background-image: url(/static/images/icons/glyphicons_108_left_indent.png); } #wysihtml5-toolbar a.heading { color: #000; font-weight: bold; height: 30px; padding: 10px 0 0 0; text-align: center; text-indent: 0; } #wysihtml5-toolbar a.save { background-color: #C1E3D4; background-image: url(/static/images/icons/glyphicons_206_ok_2.png); } #wysihtml5-toolbar a.cancel { background-color: #E3C1D1; background-image: url(/static/images/icons/glyphicons_207_remove_2.png); }
handlers/openingparliament
static/wysihtml5/css/editor.css
CSS
bsd-3-clause
2,346
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.rules.design; import net.sourceforge.pmd.AbstractRule; import net.sourceforge.pmd.ast.ASTAssignmentOperator; import net.sourceforge.pmd.ast.ASTConditionalExpression; import net.sourceforge.pmd.ast.ASTEqualityExpression; import net.sourceforge.pmd.ast.ASTExpression; import net.sourceforge.pmd.ast.ASTName; import net.sourceforge.pmd.ast.ASTNullLiteral; import net.sourceforge.pmd.ast.ASTStatementExpression; import net.sourceforge.pmd.symboltable.VariableNameDeclaration; // TODO - should check that this is not the first assignment. e.g., this is OK: // Object x; // x = null; public class NullAssignmentRule extends AbstractRule { public Object visit(ASTNullLiteral node, Object data) { if (node.getNthParent(5) instanceof ASTStatementExpression) { ASTStatementExpression n = (ASTStatementExpression) node.getNthParent(5); if (isAssignmentToFinalField(n)) { return data; } if (n.jjtGetNumChildren() > 2 && n.jjtGetChild(1) instanceof ASTAssignmentOperator) { addViolation(data, node); } } else if (node.getNthParent(4) instanceof ASTConditionalExpression) { // "false" expression of ternary if (isBadTernary((ASTConditionalExpression)node.getNthParent(4))) { addViolation(data, node); } } else if (node.getNthParent(5) instanceof ASTConditionalExpression && node.getNthParent(4) instanceof ASTExpression) { // "true" expression of ternary if (isBadTernary((ASTConditionalExpression)node.getNthParent(5))) { addViolation(data, node); } } return data; } private boolean isAssignmentToFinalField(ASTStatementExpression n) { ASTName name = n.getFirstChildOfType(ASTName.class); return name != null && name.getNameDeclaration() instanceof VariableNameDeclaration && ((VariableNameDeclaration) name.getNameDeclaration()).getAccessNodeParent().isFinal(); } private boolean isBadTernary(ASTConditionalExpression n) { return n.isTernary() && !(n.jjtGetChild(0) instanceof ASTEqualityExpression); } }
pscadiz/pmd-4.2.6-gds
src/net/sourceforge/pmd/rules/design/NullAssignmentRule.java
Java
bsd-3-clause
2,343
/** * Copyright (c) 2015-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. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; jest.disableAutomock(); const React = require('React'); const ReactTestRenderer = require('react-test-renderer'); const VirtualizedList = require('VirtualizedList'); describe('VirtualizedList', () => { it('renders simple list', () => { const component = ReactTestRenderer.create( <VirtualizedList data={[{key: 'i1'}, {key: 'i2'}, {key: 'i3'}]} renderItem={({item}) => <item value={item.key} />} /> ); expect(component).toMatchSnapshot(); }); it('renders empty list', () => { const component = ReactTestRenderer.create( <VirtualizedList data={[]} renderItem={({item}) => <item value={item.key} />} /> ); expect(component).toMatchSnapshot(); }); it('renders null list', () => { const component = ReactTestRenderer.create( <VirtualizedList data={undefined} renderItem={({item}) => <item value={item.key} />} /> ); expect(component).toMatchSnapshot(); }); it('renders all the bells and whistles', () => { const component = ReactTestRenderer.create( <VirtualizedList ItemSeparatorComponent={() => <separator />} ListFooterComponent={() => <footer />} ListHeaderComponent={() => <header />} data={new Array(5).fill().map((_, ii) => ({id: String(ii)}))} keyExtractor={(item, index) => item.id} getItemLayout={({index}) => ({length: 50, offset: index * 50})} numColumns={2} refreshing={false} onRefresh={jest.fn()} renderItem={({item}) => <item value={item.id} />} /> ); expect(component).toMatchSnapshot(); }); it('test getItem functionality where data is not an Array', () => { const component = ReactTestRenderer.create( <VirtualizedList data={new Map([['id_0', {key: 'item_0'}]])} getItem={(data, index) => data.get('id_' + index)} getItemCount={(data: Map) => data.size} renderItem={({item}) => <item value={item.key} />} /> ); expect(component).toMatchSnapshot(); }); });
Maxwell2022/react-native
Libraries/Lists/__tests__/VirtualizedList-test.js
JavaScript
bsd-3-clause
2,405
<?php namespace Sabre\DAVACL\PrincipalBackend; /** * Abstract Principal Backend * * Currently this class has no function. It's here for consistency and so we * have a non-bc-breaking way to add a default generic implementation to * functions we may add in the future. * * @copyright Copyright (C) 2007-2014 fruux GmbH (https://fruux.com/). * @author Evert Pot (http://evertpot.com/) * @license http://sabre.io/license/ Modified BSD License */ abstract class AbstractBackend implements BackendInterface { /** * Finds a principal by its URI. * * This method may receive any type of uri, but mailto: addresses will be * the most common. * * Implementation of this API is optional. It is currently used by the * CalDAV system to find principals based on their email addresses. If this * API is not implemented, some features may not work correctly. * * This method must return a relative principal path, or null, if the * principal was not found or you refuse to find it. * * @param string $uri * @return string */ function findByUri($uri) { // Note that the default implementation here is a bit slow and could // likely be optimized. if (substr($uri,0,7)!=='mailto:') { return; } $result = $this->searchPrincipals( '', ['{http://sabredav.org/ns}email-address' => substr($uri,7)] ); if ($result) { return $result[0]; } } }
evert/sabre-dav
lib/DAVACL/PrincipalBackend/AbstractBackend.php
PHP
bsd-3-clause
1,535
#include <omp.h> #include <math.h> #define ceild(n,d) ceil(((double)(n))/((double)(d))) #define floord(n,d) floor(((double)(n))/((double)(d))) #define max(x,y) ((x) > (y)? (x) : (y)) #define min(x,y) ((x) < (y)? (x) : (y)) /* * Order-1, 3D 7 point stencil * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+2; Ny = atoi(argv[2])+2; Nz = atoi(argv[3])+2; } if (argc > 4) Nt = atoi(argv[4]); double ****A = (double ****) malloc(sizeof(double***)*2); A[0] = (double ***) malloc(sizeof(double**)*Nz); A[1] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[0][i] = (double**) malloc(sizeof(double*)*Ny); A[1][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[0][i][j] = (double*) malloc(sizeof(double)*Nx); A[1][i][j] = (double*) malloc(sizeof(double)*Nx); } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 4; tile_size[1] = 4; tile_size[2] = 8; tile_size[3] = 64; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; const double alpha = 0.0876; const double beta = 0.0765; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 /* Copyright (C) 1991-2014 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ /* This header is separate from features.h so that the compiler can include it implicitly at the start of every compilation. It must not itself include <features.h> or any other header that includes <features.h> because the implicit include comes before any feature test macros that may be defined in a source file before it first explicitly includes a system header. GCC knows the name of this header in order to preinclude it. */ /* glibc's intent is to support the IEC 559 math functionality, real and complex. If the GCC (4.9 and later) predefined macros specifying compiler intent are available, use them to determine whether the overall intent is to support these features; otherwise, presume an older compiler has intent to support these features and define these macros by default. */ /* wchar_t uses ISO/IEC 10646 (2nd ed., published 2011-03-15) / Unicode 6.0. */ /* We do not support C11 <threads.h>. */ int t1, t2, t3, t4, t5, t6, t7, t8; int lb, ub, lbp, ubp, lb2, ub2; register int lbv, ubv; /* Start of CLooG code */ if ((Nt >= 2) && (Nx >= 3) && (Ny >= 3) && (Nz >= 3)) { for (t1=-1;t1<=floord(Nt-2,2);t1++) { lbp=max(ceild(t1,2),ceild(4*t1-Nt+3,4)); ubp=min(floord(Nt+Nz-4,4),floord(2*t1+Nz-1,4)); #pragma omp parallel for private(lbv,ubv,t3,t4,t5,t6,t7,t8) for (t2=lbp;t2<=ubp;t2++) { for (t3=max(max(0,ceild(t1-3,4)),ceild(4*t2-Nz-4,8));t3<=min(min(min(floord(4*t2+Ny,8),floord(Nt+Ny-4,8)),floord(2*t1+Ny+1,8)),floord(4*t1-4*t2+Nz+Ny-1,8));t3++) { for (t4=max(max(max(0,ceild(t1-31,32)),ceild(4*t2-Nz-60,64)),ceild(8*t3-Ny-60,64));t4<=min(min(min(min(floord(4*t2+Nx,64),floord(Nt+Nx-4,64)),floord(2*t1+Nx+1,64)),floord(8*t3+Nx+4,64)),floord(4*t1-4*t2+Nz+Nx-1,64));t4++) { for (t5=max(max(max(max(max(0,2*t1),4*t1-4*t2+1),4*t2-Nz+2),8*t3-Ny+2),64*t4-Nx+2);t5<=min(min(min(min(min(Nt-2,2*t1+3),4*t2+2),8*t3+6),64*t4+62),4*t1-4*t2+Nz+1);t5++) { for (t6=max(max(4*t2,t5+1),-4*t1+4*t2+2*t5-3);t6<=min(min(4*t2+3,-4*t1+4*t2+2*t5),t5+Nz-2);t6++) { for (t7=max(8*t3,t5+1);t7<=min(8*t3+7,t5+Ny-2);t7++) { lbv=max(64*t4,t5+1); ubv=min(64*t4+63,t5+Nx-2); #pragma ivdep #pragma vector always for (t8=lbv;t8<=ubv;t8++) { A[( t5 + 1) % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] = ((alpha * A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)]) + (beta * (((((A[ t5 % 2][ (-t5+t6) - 1][ (-t5+t7)][ (-t5+t8)] + A[ t5 % 2][ (-t5+t6)][ (-t5+t7) - 1][ (-t5+t8)]) + A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8) - 1]) + A[ t5 % 2][ (-t5+t6) + 1][ (-t5+t7)][ (-t5+t8)]) + A[ t5 % 2][ (-t5+t6)][ (-t5+t7) + 1][ (-t5+t8)]) + A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8) + 1])));; } } } } } } } } } /* End of CLooG code */ gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = min(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(1, "constant") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays (Causing performance degradation /* for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); } free(A[0][i]); free(A[1][i]); } free(A[0]); free(A[1]); */ return 0; }
tareqmalas/girih
pluto_examples/gen_kernels/lbpar_3d7pt4_4_8_64/3d7pt.lbpar.c
C
bsd-3-clause
7,590
/* * Copyright © 2018-2019, VideoLAN and dav1d authors * Copyright © 2018-2019, Two Orioles, LLC * 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 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. */ #include "config.h" #include <stddef.h> #include <stdint.h> #include <string.h> #include "common/attributes.h" #include "common/intops.h" #include "src/itx.h" #include "src/itx_1d.h" static NOINLINE void inv_txfm_add_c(pixel *dst, const ptrdiff_t stride, coef *const coeff, const int eob, const int w, const int h, const int shift, const itx_1d_fn first_1d_fn, const itx_1d_fn second_1d_fn, const int has_dconly HIGHBD_DECL_SUFFIX) { assert(w >= 4 && w <= 64); assert(h >= 4 && h <= 64); assert(eob >= 0); const int is_rect2 = w * 2 == h || h * 2 == w; const int rnd = (1 << shift) >> 1; if (eob < has_dconly) { int dc = coeff[0]; coeff[0] = 0; if (is_rect2) dc = (dc * 181 + 128) >> 8; dc = (dc * 181 + 128) >> 8; dc = (dc + rnd) >> shift; dc = (dc * 181 + 128 + 2048) >> 12; for (int y = 0; y < h; y++, dst += PXSTRIDE(stride)) for (int x = 0; x < w; x++) dst[x] = iclip_pixel(dst[x] + dc); return; } const int sh = imin(h, 32), sw = imin(w, 32); #if BITDEPTH == 8 const int row_clip_min = INT16_MIN; const int col_clip_min = INT16_MIN; #else const int row_clip_min = (int) ((unsigned) ~bitdepth_max << 7); const int col_clip_min = (int) ((unsigned) ~bitdepth_max << 5); #endif const int row_clip_max = ~row_clip_min; const int col_clip_max = ~col_clip_min; int32_t tmp[64 * 64], *c = tmp; for (int y = 0; y < sh; y++, c += w) { if (is_rect2) for (int x = 0; x < sw; x++) c[x] = (coeff[y + x * sh] * 181 + 128) >> 8; else for (int x = 0; x < sw; x++) c[x] = coeff[y + x * sh]; first_1d_fn(c, 1, row_clip_min, row_clip_max); } memset(coeff, 0, sizeof(*coeff) * sw * sh); for (int i = 0; i < w * sh; i++) tmp[i] = iclip((tmp[i] + rnd) >> shift, col_clip_min, col_clip_max); for (int x = 0; x < w; x++) second_1d_fn(&tmp[x], w, col_clip_min, col_clip_max); c = tmp; for (int y = 0; y < h; y++, dst += PXSTRIDE(stride)) for (int x = 0; x < w; x++) dst[x] = iclip_pixel(dst[x] + ((*c++ + 8) >> 4)); } #define inv_txfm_fn(type1, type2, w, h, shift, has_dconly) \ static void \ inv_txfm_add_##type1##_##type2##_##w##x##h##_c(pixel *dst, \ const ptrdiff_t stride, \ coef *const coeff, \ const int eob \ HIGHBD_DECL_SUFFIX) \ { \ inv_txfm_add_c(dst, stride, coeff, eob, w, h, shift, \ dav1d_inv_##type1##w##_1d_c, dav1d_inv_##type2##h##_1d_c, \ has_dconly HIGHBD_TAIL_SUFFIX); \ } #define inv_txfm_fn64(w, h, shift) \ inv_txfm_fn(dct, dct, w, h, shift, 1) #define inv_txfm_fn32(w, h, shift) \ inv_txfm_fn64(w, h, shift) \ inv_txfm_fn(identity, identity, w, h, shift, 0) #define inv_txfm_fn16(w, h, shift) \ inv_txfm_fn32(w, h, shift) \ inv_txfm_fn(adst, dct, w, h, shift, 0) \ inv_txfm_fn(dct, adst, w, h, shift, 0) \ inv_txfm_fn(adst, adst, w, h, shift, 0) \ inv_txfm_fn(dct, flipadst, w, h, shift, 0) \ inv_txfm_fn(flipadst, dct, w, h, shift, 0) \ inv_txfm_fn(adst, flipadst, w, h, shift, 0) \ inv_txfm_fn(flipadst, adst, w, h, shift, 0) \ inv_txfm_fn(flipadst, flipadst, w, h, shift, 0) \ inv_txfm_fn(identity, dct, w, h, shift, 0) \ inv_txfm_fn(dct, identity, w, h, shift, 0) \ #define inv_txfm_fn84(w, h, shift) \ inv_txfm_fn16(w, h, shift) \ inv_txfm_fn(identity, flipadst, w, h, shift, 0) \ inv_txfm_fn(flipadst, identity, w, h, shift, 0) \ inv_txfm_fn(identity, adst, w, h, shift, 0) \ inv_txfm_fn(adst, identity, w, h, shift, 0) \ inv_txfm_fn84( 4, 4, 0) inv_txfm_fn84( 4, 8, 0) inv_txfm_fn84( 4, 16, 1) inv_txfm_fn84( 8, 4, 0) inv_txfm_fn84( 8, 8, 1) inv_txfm_fn84( 8, 16, 1) inv_txfm_fn32( 8, 32, 2) inv_txfm_fn84(16, 4, 1) inv_txfm_fn84(16, 8, 1) inv_txfm_fn16(16, 16, 2) inv_txfm_fn32(16, 32, 1) inv_txfm_fn64(16, 64, 2) inv_txfm_fn32(32, 8, 2) inv_txfm_fn32(32, 16, 1) inv_txfm_fn32(32, 32, 2) inv_txfm_fn64(32, 64, 1) inv_txfm_fn64(64, 16, 2) inv_txfm_fn64(64, 32, 1) inv_txfm_fn64(64, 64, 2) static void inv_txfm_add_wht_wht_4x4_c(pixel *dst, const ptrdiff_t stride, coef *const coeff, const int eob HIGHBD_DECL_SUFFIX) { int32_t tmp[4 * 4], *c = tmp; for (int y = 0; y < 4; y++, c += 4) { for (int x = 0; x < 4; x++) c[x] = coeff[y + x * 4] >> 2; dav1d_inv_wht4_1d_c(c, 1); } memset(coeff, 0, sizeof(*coeff) * 4 * 4); for (int x = 0; x < 4; x++) dav1d_inv_wht4_1d_c(&tmp[x], 4); c = tmp; for (int y = 0; y < 4; y++, dst += PXSTRIDE(stride)) for (int x = 0; x < 4; x++) dst[x] = iclip_pixel(dst[x] + *c++); } COLD void bitfn(dav1d_itx_dsp_init)(Dav1dInvTxfmDSPContext *const c) { #define assign_itx_all_fn64(w, h, pfx) \ c->itxfm_add[pfx##TX_##w##X##h][DCT_DCT ] = \ inv_txfm_add_dct_dct_##w##x##h##_c #define assign_itx_all_fn32(w, h, pfx) \ assign_itx_all_fn64(w, h, pfx); \ c->itxfm_add[pfx##TX_##w##X##h][IDTX] = \ inv_txfm_add_identity_identity_##w##x##h##_c #define assign_itx_all_fn16(w, h, pfx) \ assign_itx_all_fn32(w, h, pfx); \ c->itxfm_add[pfx##TX_##w##X##h][DCT_ADST ] = \ inv_txfm_add_adst_dct_##w##x##h##_c; \ c->itxfm_add[pfx##TX_##w##X##h][ADST_DCT ] = \ inv_txfm_add_dct_adst_##w##x##h##_c; \ c->itxfm_add[pfx##TX_##w##X##h][ADST_ADST] = \ inv_txfm_add_adst_adst_##w##x##h##_c; \ c->itxfm_add[pfx##TX_##w##X##h][ADST_FLIPADST] = \ inv_txfm_add_flipadst_adst_##w##x##h##_c; \ c->itxfm_add[pfx##TX_##w##X##h][FLIPADST_ADST] = \ inv_txfm_add_adst_flipadst_##w##x##h##_c; \ c->itxfm_add[pfx##TX_##w##X##h][DCT_FLIPADST] = \ inv_txfm_add_flipadst_dct_##w##x##h##_c; \ c->itxfm_add[pfx##TX_##w##X##h][FLIPADST_DCT] = \ inv_txfm_add_dct_flipadst_##w##x##h##_c; \ c->itxfm_add[pfx##TX_##w##X##h][FLIPADST_FLIPADST] = \ inv_txfm_add_flipadst_flipadst_##w##x##h##_c; \ c->itxfm_add[pfx##TX_##w##X##h][H_DCT] = \ inv_txfm_add_dct_identity_##w##x##h##_c; \ c->itxfm_add[pfx##TX_##w##X##h][V_DCT] = \ inv_txfm_add_identity_dct_##w##x##h##_c #define assign_itx_all_fn84(w, h, pfx) \ assign_itx_all_fn16(w, h, pfx); \ c->itxfm_add[pfx##TX_##w##X##h][H_FLIPADST] = \ inv_txfm_add_flipadst_identity_##w##x##h##_c; \ c->itxfm_add[pfx##TX_##w##X##h][V_FLIPADST] = \ inv_txfm_add_identity_flipadst_##w##x##h##_c; \ c->itxfm_add[pfx##TX_##w##X##h][H_ADST] = \ inv_txfm_add_adst_identity_##w##x##h##_c; \ c->itxfm_add[pfx##TX_##w##X##h][V_ADST] = \ inv_txfm_add_identity_adst_##w##x##h##_c; \ memset(c, 0, sizeof(*c)); /* Zero unused function pointer elements. */ c->itxfm_add[TX_4X4][WHT_WHT] = inv_txfm_add_wht_wht_4x4_c; assign_itx_all_fn84( 4, 4, ); assign_itx_all_fn84( 4, 8, R); assign_itx_all_fn84( 4, 16, R); assign_itx_all_fn84( 8, 4, R); assign_itx_all_fn84( 8, 8, ); assign_itx_all_fn84( 8, 16, R); assign_itx_all_fn32( 8, 32, R); assign_itx_all_fn84(16, 4, R); assign_itx_all_fn84(16, 8, R); assign_itx_all_fn16(16, 16, ); assign_itx_all_fn32(16, 32, R); assign_itx_all_fn64(16, 64, R); assign_itx_all_fn32(32, 8, R); assign_itx_all_fn32(32, 16, R); assign_itx_all_fn32(32, 32, ); assign_itx_all_fn64(32, 64, R); assign_itx_all_fn64(64, 16, R); assign_itx_all_fn64(64, 32, R); assign_itx_all_fn64(64, 64, ); #if HAVE_ASM #if ARCH_AARCH64 || ARCH_ARM bitfn(dav1d_itx_dsp_init_arm)(c); #endif #if ARCH_X86 bitfn(dav1d_itx_dsp_init_x86)(c); #endif #endif }
endlessm/chromium-browser
third_party/dav1d/libdav1d/src/itx_tmpl.c
C
bsd-3-clause
9,450
// Copyright 2013 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 <limits.h> #include <stddef.h> #include <stdint.h> #include "base/files/file_path.h" #include "base/files/memory_mapped_file.h" #include "base/logging.h" #include "base/macros.h" #include "base/memory/ptr_util.h" #include "base/strings/string_piece.h" #include "ipc/ipc_message.h" #include "tools/ipc_fuzzer/message_lib/message_cracker.h" #include "tools/ipc_fuzzer/message_lib/message_file.h" #include "tools/ipc_fuzzer/message_lib/message_file_format.h" #include "tools/ipc_fuzzer/message_lib/message_names.h" namespace ipc_fuzzer { namespace { // Helper class to read IPC message file into a MessageVector and // fix message types. class Reader { public: Reader(const base::FilePath& path); bool Read(MessageVector* messages); private: template <typename T> bool CutObject(const T** object); // Reads the header, checks magic and version. bool ReadHeader(); bool MapFile(); bool ReadMessages(); // Last part of the file is a string table for message names. bool ReadStringTable(); // Reads type <-> name mapping into name_map_. References string table. bool ReadNameTable(); // Removes obsolete messages from the vector. bool RemoveUnknownMessages(); // Does type -> name -> correct_type fixup. void FixMessageTypes(); // Raw data. base::FilePath path_; base::MemoryMappedFile mapped_file_; base::StringPiece file_data_; base::StringPiece string_table_; // Parsed data. const FileHeader* header_; MessageVector* messages_; MessageNames name_map_; DISALLOW_COPY_AND_ASSIGN(Reader); }; Reader::Reader(const base::FilePath& path) : path_(path), header_(NULL), messages_(NULL) { } template <typename T> bool Reader::CutObject(const T** object) { if (file_data_.size() < sizeof(T)) { LOG(ERROR) << "Unexpected EOF."; return false; } *object = reinterpret_cast<const T*>(file_data_.data()); file_data_.remove_prefix(sizeof(T)); return true; } bool Reader::ReadHeader() { if (!CutObject<FileHeader>(&header_)) return false; if (header_->magic != FileHeader::kMagicValue) { LOG(ERROR) << path_.value() << " is not an IPC message file."; return false; } if (header_->version != FileHeader::kCurrentVersion) { LOG(ERROR) << "Wrong version for message file " << path_.value() << ". " << "File version is " << header_->version << ", " << "current version is " << FileHeader::kCurrentVersion << "."; return false; } return true; } bool Reader::MapFile() { if (!mapped_file_.Initialize(path_)) { LOG(ERROR) << "Failed to map testcase: " << path_.value(); return false; } const char* data = reinterpret_cast<const char*>(mapped_file_.data()); file_data_ = base::StringPiece(data, mapped_file_.length()); return true; } bool Reader::ReadMessages() { for (size_t i = 0; i < header_->message_count; ++i) { const char* begin = file_data_.begin(); const char* end = file_data_.end(); IPC::Message::NextMessageInfo info; IPC::Message::FindNext(begin, end, &info); if (!info.message_found) { LOG(ERROR) << "Failed to parse message."; return false; } CHECK_EQ(info.message_end, info.pickle_end); size_t msglen = info.message_end - begin; if (msglen > INT_MAX) { LOG(ERROR) << "Message too large."; return false; } // Copy is necessary to fix message type later. IPC::Message const_message(begin, msglen); messages_->push_back(std::make_unique<IPC::Message>(const_message)); file_data_.remove_prefix(msglen); } return true; } bool Reader::ReadStringTable() { size_t name_count = header_->name_count; if (!name_count) return true; if (name_count > file_data_.size() / sizeof(NameTableEntry)) { LOG(ERROR) << "Invalid name table size: " << name_count; return false; } size_t string_table_offset = name_count * sizeof(NameTableEntry); string_table_ = file_data_.substr(string_table_offset); if (string_table_.empty()) { LOG(ERROR) << "Missing string table."; return false; } if (string_table_.end()[-1] != '\0') { LOG(ERROR) << "String table doesn't end with NUL."; return false; } return true; } bool Reader::ReadNameTable() { for (size_t i = 0; i < header_->name_count; ++i) { const NameTableEntry* entry; if (!CutObject<NameTableEntry>(&entry)) return false; size_t offset = entry->string_table_offset; if (offset >= string_table_.size()) { LOG(ERROR) << "Invalid string table offset: " << offset; return false; } name_map_.Add(entry->type, string_table_.data() + offset); } return true; } bool Reader::RemoveUnknownMessages() { MessageVector::iterator it = messages_->begin(); while (it != messages_->end()) { uint32_t type = (*it)->type(); if (!name_map_.TypeExists(type)) { LOG(ERROR) << "Missing name table entry for type " << type; return false; } const std::string& name = name_map_.TypeToName(type); if (!MessageNames::GetInstance()->NameExists(name)) { LOG(WARNING) << "Unknown message " << name; it = messages_->erase(it); } else { ++it; } } return true; } // Message types are based on line numbers, so a minor edit of *_messages.h // changes the types of messages in that file. The types are fixed here to // increase the lifetime of message files. This is only a partial fix because // message arguments and structure layouts can change as well. void Reader::FixMessageTypes() { for (const auto& message : *messages_) { uint32_t type = message->type(); const std::string& name = name_map_.TypeToName(type); uint32_t correct_type = MessageNames::GetInstance()->NameToType(name); if (type != correct_type) MessageCracker::SetMessageType(message.get(), correct_type); } } bool Reader::Read(MessageVector* messages) { messages_ = messages; if (!MapFile()) return false; if (!ReadHeader()) return false; if (!ReadMessages()) return false; if (!ReadStringTable()) return false; if (!ReadNameTable()) return false; if (!RemoveUnknownMessages()) return false; FixMessageTypes(); return true; } } // namespace bool MessageFile::Read(const base::FilePath& path, MessageVector* messages) { Reader reader(path); return reader.Read(messages); } } // namespace ipc_fuzzer
endlessm/chromium-browser
tools/ipc_fuzzer/message_lib/message_file_reader.cc
C++
bsd-3-clause
6,548
// 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 "chrome/browser/renderer_host/chrome_url_request_user_data.h" namespace { const char* const kKeyName = "chrome_url_request_user_data"; } // namespace ChromeURLRequestUserData::ChromeURLRequestUserData() : is_prerender_(false) { } // static ChromeURLRequestUserData* ChromeURLRequestUserData::Get( const net::URLRequest* request) { DCHECK(request); return static_cast<ChromeURLRequestUserData*>(request->GetUserData(kKeyName)); } // static ChromeURLRequestUserData* ChromeURLRequestUserData::Create( net::URLRequest* request) { DCHECK(request); DCHECK(!Get(request)); ChromeURLRequestUserData* user_data = new ChromeURLRequestUserData(); request->SetUserData(kKeyName, user_data); return user_data; } // static void ChromeURLRequestUserData::Delete(net::URLRequest* request) { DCHECK(request); request->SetUserData(kKeyName, NULL); }
aYukiSekiguchi/ACCESS-Chromium
chrome/browser/renderer_host/chrome_url_request_user_data.cc
C++
bsd-3-clause
1,050
// 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. #ifndef CONTENT_BROWSER_RENDERER_HOST_RENDER_PROCESS_HOST_H_ #define CONTENT_BROWSER_RENDERER_HOST_RENDER_PROCESS_HOST_H_ #pragma once #include <set> #include "base/id_map.h" #include "base/memory/scoped_ptr.h" #include "base/process.h" #include "base/process_util.h" #include "base/time.h" #include "chrome/common/visitedlink_common.h" #include "ipc/ipc_sync_channel.h" #include "ui/gfx/surface/transport_dib.h" class Profile; struct ViewMsg_ClosePage_Params; namespace base { class SharedMemory; } namespace net { class URLRequestContextGetter; } // Virtual interface that represents the browser side of the browser <-> // renderer communication channel. There will generally be one // RenderProcessHost per renderer process. // // The concrete implementation of this class for normal use is the // BrowserRenderProcessHost. It may also be implemented by a testing interface // for mocking purposes. class RenderProcessHost : public IPC::Channel::Sender, public IPC::Channel::Listener { public: typedef IDMap<RenderProcessHost>::iterator iterator; // We classify renderers according to their highest privilege, and try // to group pages into renderers with similar privileges. // Note: it may be possible for a renderer to have multiple privileges, // in which case we call it an "extension" renderer. enum Type { TYPE_NORMAL, // Normal renderer, no extra privileges. TYPE_WEBUI, // Renderer with WebUI privileges, like New Tab. TYPE_EXTENSION, // Renderer with extension privileges. }; // Details for RENDERER_PROCESS_CLOSED notifications. struct RendererClosedDetails { RendererClosedDetails(base::TerminationStatus status, int exit_code, bool was_extension_renderer) { this->status = status; this->exit_code = exit_code; this->was_extension_renderer = was_extension_renderer; } base::TerminationStatus status; int exit_code; bool was_extension_renderer; }; explicit RenderProcessHost(Profile* profile); virtual ~RenderProcessHost(); // Returns the user profile associated with this renderer process. Profile* profile() const { return profile_; } // Returns the unique ID for this child process. This can be used later in // a call to FromID() to get back to this object (this is used to avoid // sending non-threadsafe pointers to other threads). // // This ID will be unique for all child processes, including workers, plugins, // etc. It is generated by ChildProcessInfo. int id() const { return id_; } // Returns true iff channel_ has been set to non-NULL. Use this for checking // if there is connection or not. bool HasConnection() { return channel_.get() != NULL; } bool sudden_termination_allowed() const { return sudden_termination_allowed_; } void set_sudden_termination_allowed(bool enabled) { sudden_termination_allowed_ = enabled; } // Used for refcounting, each holder of this object must Attach and Release // just like it would for a COM object. This object should be allocated on // the heap; when no listeners own it any more, it will delete itself. void Attach(IPC::Channel::Listener* listener, int routing_id); // See Attach() void Release(int listener_id); // Listeners should call this when they've sent a "Close" message and // they're waiting for a "Close_ACK", so that if the renderer process // goes away we'll know that it was intentional rather than a crash. void ReportExpectingClose(int32 listener_id); // Allows iteration over this RenderProcessHost's RenderViewHost listeners. // Use from UI thread only. typedef IDMap<IPC::Channel::Listener>::const_iterator listeners_iterator; listeners_iterator ListenersIterator() { return listeners_iterator(&listeners_); } IPC::Channel::Listener* GetListenerByID(int routing_id) { return listeners_.Lookup(routing_id); } IPC::SyncChannel* channel() { return channel_.get(); } // Called to inform the render process host of a new "max page id" for a // render view host. The render process host computes the largest page id // across all render view hosts and uses the value when it needs to // initialize a new renderer in place of the current one. void UpdateMaxPageID(int32 page_id); void set_ignore_input_events(bool ignore_input_events) { ignore_input_events_ = ignore_input_events; } bool ignore_input_events() { return ignore_input_events_; } // Returns how long the child has been idle. The definition of idle // depends on when a derived class calls mark_child_process_activity_time(). // This is a rough indicator and its resolution should not be better than // 10 milliseconds. base::TimeDelta get_child_process_idle_time() const { return base::TimeTicks::Now() - child_process_activity_time_; } // Call this function when it is evident that the child process is actively // performing some operation, for example if we just received an IPC message. void mark_child_process_activity_time() { child_process_activity_time_ = base::TimeTicks::Now(); } // Try to shutdown the associated render process as fast as possible, but // only if |count| matches the number of render widgets that this process // controls. bool FastShutdownForPageCount(size_t count); bool fast_shutdown_started() { return fast_shutdown_started_; } // Virtual interface --------------------------------------------------------- // Initialize the new renderer process, returning true on success. This must // be called once before the object can be used, but can be called after // that with no effect. Therefore, if the caller isn't sure about whether // the process has been created, it should just call Init(). virtual bool Init( bool is_accessibility_enabled, bool is_extensions_process) = 0; // Gets the next available routing id. virtual int GetNextRoutingID() = 0; // Called on the UI thread to cancel any outstanding resource requests for // the specified render widget. virtual void CancelResourceRequests(int render_widget_id) = 0; // Called on the UI thread to simulate a ClosePage_ACK message to the // ResourceDispatcherHost. Necessary for a cross-site request, in the case // that the original RenderViewHost is not live and thus cannot run an // onunload handler. virtual void CrossSiteClosePageACK( const ViewMsg_ClosePage_Params& params) = 0; // Called on the UI thread to wait for the next UpdateRect message for the // specified render widget. Returns true if successful, and the msg out- // param will contain a copy of the received UpdateRect message. virtual bool WaitForUpdateMsg(int render_widget_id, const base::TimeDelta& max_delay, IPC::Message* msg) = 0; // Called when a received message cannot be decoded. virtual void ReceivedBadMessage() = 0; // Track the count of visible widgets. Called by listeners to register and // unregister visibility. virtual void WidgetRestored() = 0; virtual void WidgetHidden() = 0; // Called when RenderView is created by a listener. virtual void ViewCreated() = 0; // Informs the renderer about a new visited link table. virtual void SendVisitedLinkTable(base::SharedMemory* table_memory) = 0; // Notify the renderer that a link was visited. virtual void AddVisitedLinks( const VisitedLinkCommon::Fingerprints& links) = 0; // Clear internal visited links buffer and ask the renderer to update link // coloring state for all of its links. virtual void ResetVisitedLinks() = 0; // Try to shutdown the associated renderer process as fast as possible. // If this renderer has any RenderViews with unload handlers, then this // function does nothing. The current implementation uses TerminateProcess. // Returns True if it was able to do fast shutdown. virtual bool FastShutdownIfPossible() = 0; // Synchronously sends the message, waiting for the specified timeout. The // implementor takes ownership of the given Message regardless of whether or // not this method succeeds. Returns true on success. virtual bool SendWithTimeout(IPC::Message* msg, int timeout_ms) = 0; // Returns the process object associated with the child process. In certain // tests or single-process mode, this will actually represent the current // process. // // NOTE: this is not necessarily valid immediately after calling Init, as // Init starts the process asynchronously. It's guaranteed to be valid after // the first IPC arrives. virtual base::ProcessHandle GetHandle() = 0; // Transport DIB functions --------------------------------------------------- // Return the TransportDIB for the given id. On Linux, this can involve // mapping shared memory. On Mac, the shared memory is created in the browser // process and the cached metadata is returned. On Windows, this involves // duplicating the handle from the remote process. The RenderProcessHost // still owns the returned DIB. virtual TransportDIB* GetTransportDIB(TransportDIB::Id dib_id) = 0; // Static management functions ----------------------------------------------- // Flag to run the renderer in process. This is primarily // for debugging purposes. When running "in process", the // browser maintains a single RenderProcessHost which communicates // to a RenderProcess which is instantiated in the same process // with the Browser. All IPC between the Browser and the // Renderer is the same, it's just not crossing a process boundary. static bool run_renderer_in_process() { return run_renderer_in_process_; } static void set_run_renderer_in_process(bool value) { run_renderer_in_process_ = value; } // Allows iteration over all the RenderProcessHosts in the browser. Note // that each host may not be active, and therefore may have NULL channels. static iterator AllHostsIterator(); // Returns the RenderProcessHost given its ID. Returns NULL if the ID does // not correspond to a live RenderProcessHost. static RenderProcessHost* FromID(int render_process_id); // Returns true if the caller should attempt to use an existing // RenderProcessHost rather than creating a new one. static bool ShouldTryToUseExistingProcessHost(); // Get an existing RenderProcessHost associated with the given profile, if // possible. The renderer process is chosen randomly from suitable renderers // that share the same profile and type. // Returns NULL if no suitable renderer process is available, in which case // the caller is free to create a new renderer. static RenderProcessHost* GetExistingProcessHost(Profile* profile, Type type); // Overrides the default heuristic for limiting the max renderer process // count. This is useful for unit testing process limit behaviors. // A value of zero means to use the default heuristic. static void SetMaxRendererProcessCount(size_t count); protected: // A proxy for our IPC::Channel that lives on the IO thread (see // browser_process.h) scoped_ptr<IPC::SyncChannel> channel_; // The registered listeners. When this list is empty or all NULL, we should // delete ourselves IDMap<IPC::Channel::Listener> listeners_; // The maximum page ID we've ever seen from the renderer process. int32 max_page_id_; // True if fast shutdown has been performed on this RPH. bool fast_shutdown_started_; // True if we've posted a DeleteTask and will be deleted soon. bool deleting_soon_; private: // The globally-unique identifier for this RPH. int id_; Profile* profile_; // set of listeners that expect the renderer process to close std::set<int> listeners_expecting_close_; // True if the process can be shut down suddenly. If this is true, then we're // sure that all the RenderViews in the process can be shutdown suddenly. If // it's false, then specific RenderViews might still be allowed to be shutdown // suddenly by checking their SuddenTerminationAllowed() flag. This can occur // if one tab has an unload event listener but another tab in the same process // doesn't. bool sudden_termination_allowed_; // Set to true if we shouldn't send input events. We actually do the // filtering for this at the render widget level. bool ignore_input_events_; // See getter above. static bool run_renderer_in_process_; // Records the last time we regarded the child process active. base::TimeTicks child_process_activity_time_; DISALLOW_COPY_AND_ASSIGN(RenderProcessHost); }; // Factory object for RenderProcessHosts. Using this factory allows tests to // swap out a different one to use a TestRenderProcessHost. class RenderProcessHostFactory { public: virtual ~RenderProcessHostFactory() {} virtual RenderProcessHost* CreateRenderProcessHost( Profile* profile) const = 0; }; #endif // CONTENT_BROWSER_RENDERER_HOST_RENDER_PROCESS_HOST_H_
meego-tablet-ux/meego-app-browser
content/browser/renderer_host/render_process_host.h
C
bsd-3-clause
13,234
package org.scalameter import org.scalameter.examples.BoxingCountBench import org.scalameter.examples.MethodInvocationCountBench class BoxingCountBenchTest extends InvocationCountMeasurerTest { test("BoxingCountTest.all should be deterministic") { checkInvocationCountMeasurerTest(new BoxingCountBench) } } class MethodInvocationCountBenchTest extends InvocationCountMeasurerTest { test("MethodInvocationCountTest.allocations should be deterministic") { checkInvocationCountMeasurerTest(new MethodInvocationCountBench) } }
storm-enroute/scalameter
src/test/scala/org/scalameter/invocationCountMeasurersTests.scala
Scala
bsd-3-clause
546
define(["require"], function (require) { function boot(ev) { ev.target.removeEventListener("click", boot); require(["demos/water/water"]); } const start = document.querySelector(".code-demo.water [data-trigger='water.start']"); start.addEventListener("click", boot); start.disabled = false; });
canena/canena.github.io
src/_resources/js/demos/water/boot.js
JavaScript
bsd-3-clause
333