repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
smartdevicelink/sdl_android
android/sdl_android/src/main/java/com/smartdevicelink/transport/utl/SdlDeviceListener.java
12302
/* * Copyright (c) 2020 Livio, 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 the Livio 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 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.smartdevicelink.transport.utl; import android.bluetooth.BluetoothDevice; import android.content.Context; import android.content.SharedPreferences; import android.os.Handler; import android.os.Looper; import android.os.Message; import androidx.annotation.NonNull; import com.smartdevicelink.transport.MultiplexBaseTransport; import com.smartdevicelink.transport.MultiplexBluetoothTransport; import com.smartdevicelink.transport.SdlRouterService; import com.smartdevicelink.util.DebugTool; import com.smartdevicelink.util.SdlAppInfo; import java.lang.ref.WeakReference; import java.util.List; public class SdlDeviceListener { private static final String TAG = "SdlListener"; private static final int MIN_VERSION_REQUIRED = 13; private static final String SDL_DEVICE_STATUS_SHARED_PREFS = "sdl.device.status"; private static final Object LOCK = new Object(), RUNNING_LOCK = new Object(); private final WeakReference<Context> contextWeakReference; private final Callback callback; private final BluetoothDevice connectedDevice; private MultiplexBluetoothTransport bluetoothTransport; private TransportHandler bluetoothHandler; private Handler timeoutHandler; private Runnable timeoutRunner; private boolean isRunning = false; public SdlDeviceListener(Context context, BluetoothDevice device, Callback callback) { this.contextWeakReference = new WeakReference<>(context); this.connectedDevice = device; this.callback = callback; } /** * This will start the SDL Device Listener with two paths. The first path will be a check * against the supplied bluetooth device to see if it has already successfully connected as an * SDL device. If it has, the supplied callback will be called immediately. If the device hasn't * connected as an SDL device before, the SDL Device Listener will then open up an RFCOMM channel * using the SDL UUID and await a potential connection. A timeout is used to ensure this only * listens for a finite amount of time. If this is the first time the device has been seen, this * will listen for 30 seconds, if it is not, this will listen for 15 seconds instead. */ public void start() { if (connectedDevice == null) { DebugTool.logInfo(TAG, ": No supplied bluetooth device"); if (callback != null) { callback.onTransportError(null); } return; } if (hasSDLConnected(contextWeakReference.get(), connectedDevice.getAddress())) { DebugTool.logInfo(TAG, ": Confirmed SDL device, should start router service"); //This device has connected to SDL previously, it is ok to start the RS right now callback.onTransportConnected(contextWeakReference.get(), connectedDevice); return; } synchronized (RUNNING_LOCK) { isRunning = true; // set timeout = if first time seeing BT device, 30s, if not 15s int timeout = isFirstStatusCheck(connectedDevice.getAddress()) ? 30000 : 15000; //Set our preference as false for this device for now setSDLConnectedStatus(contextWeakReference.get(), connectedDevice.getAddress(), false); bluetoothHandler = new TransportHandler(this); bluetoothTransport = new MultiplexBluetoothTransport(bluetoothHandler); bluetoothTransport.start(); timeoutRunner = new Runnable() { @Override public void run() { if (bluetoothTransport != null) { int state = bluetoothTransport.getState(); if (state != MultiplexBluetoothTransport.STATE_CONNECTED) { DebugTool.logInfo(TAG, ": No bluetooth connection made"); bluetoothTransport.stop(); } //else BT is connected; it will close itself through callbacks } } }; timeoutHandler = new Handler(Looper.getMainLooper()); timeoutHandler.postDelayed(timeoutRunner, timeout); } } /** * Check to see if this instance is in the middle of running or not * * @return if this is already in the process of running */ public boolean isRunning() { synchronized (RUNNING_LOCK) { return isRunning; } } private static class TransportHandler extends Handler { final WeakReference<SdlDeviceListener> provider; TransportHandler(SdlDeviceListener provider) { this.provider = new WeakReference<>(provider); } @Override public void handleMessage(@NonNull Message msg) { if (this.provider.get() == null) { return; } SdlDeviceListener sdlListener = this.provider.get(); switch (msg.what) { case SdlRouterService.MESSAGE_STATE_CHANGE: switch (msg.arg1) { case MultiplexBaseTransport.STATE_CONNECTED: sdlListener.setSDLConnectedStatus(sdlListener.contextWeakReference.get(), sdlListener.connectedDevice.getAddress(), true); boolean keepConnectionOpen = sdlListener.callback.onTransportConnected(sdlListener.contextWeakReference.get(), sdlListener.connectedDevice); if (!keepConnectionOpen) { sdlListener.bluetoothTransport.stop(); sdlListener.bluetoothTransport = null; sdlListener.timeoutHandler.removeCallbacks(sdlListener.timeoutRunner); } break; case MultiplexBaseTransport.STATE_NONE: // We've just lost the connection sdlListener.callback.onTransportDisconnected(sdlListener.connectedDevice); break; case MultiplexBaseTransport.STATE_ERROR: sdlListener.callback.onTransportError(sdlListener.connectedDevice); break; } break; case com.smartdevicelink.transport.SdlRouterService.MESSAGE_READ: break; } } } /** * Set the connection establishment status of the particular device * * @param address address of the device in question * @param hasSDLConnected true if a connection has been established, false if not */ public static void setSDLConnectedStatus(Context context, String address, boolean hasSDLConnected) { synchronized (LOCK) { if (context != null) { DebugTool.logInfo(TAG, ": Saving connected status - " + address + " : " + hasSDLConnected); SharedPreferences preferences = context.getSharedPreferences(SDL_DEVICE_STATUS_SHARED_PREFS, Context.MODE_PRIVATE); if (preferences.contains(address) && hasSDLConnected == preferences.getBoolean(address, false)) { //The same key/value exists in our shared preferences. No reason to write again. return; } SharedPreferences.Editor editor = preferences.edit(); editor.putBoolean(address, hasSDLConnected); editor.commit(); } } } /** * Checks to see if a device address has connected to SDL before. * * @param address the mac address of the device in question * @return if this is the first status check of this device */ private boolean isFirstStatusCheck(String address) { synchronized (LOCK) { Context context = contextWeakReference.get(); if (context != null) { SharedPreferences preferences = context.getSharedPreferences(SDL_DEVICE_STATUS_SHARED_PREFS, Context.MODE_PRIVATE); return !preferences.contains(address); } return false; } } /** * Checks to see if a device address has connected to SDL before. * * @param address the mac address of the device in question * @return if an SDL connection has ever been established with this device */ public static boolean hasSDLConnected(Context context, String address) { synchronized (LOCK) { if (context != null) { SharedPreferences preferences = context.getSharedPreferences(SDL_DEVICE_STATUS_SHARED_PREFS, Context.MODE_PRIVATE); return preferences.contains(address) && preferences.getBoolean(address, false); } return false; } } /** * This method will check the current device and list of SDL enabled apps to derive if the * feature can be supported. Due to older libraries sending their intents to start the router * service right at the bluetooth A2DP/HFS connections, this feature can't be used until all * applications are updated to the point they include the feature. * * @param sdlAppInfoList current list of SDL enabled applications on the device * @return if this feature is supported or not. If it is not, the caller should follow the * previously used flow, ie start the router service. */ public static boolean isFeatureSupported(List<SdlAppInfo> sdlAppInfoList) { SdlAppInfo appInfo; for (int i = sdlAppInfoList.size() - 1; i >= 0; i--) { appInfo = sdlAppInfoList.get(i); if (appInfo != null && !appInfo.isCustomRouterService() && appInfo.getRouterServiceVersion() < MIN_VERSION_REQUIRED) { return false; } } return true; } /** * Callback for the SdlDeviceListener. It will return if the supplied device makes a bluetooth * connection on the SDL UUID RFCOMM chanel or not. Most of the time the only callback that * matters will be the onTransportConnected. */ public interface Callback { /** * @param bluetoothDevice the BT device that successfully connected to SDL's UUID * @return if the RFCOMM connection should stay open. In most cases this should be false */ boolean onTransportConnected(Context context, BluetoothDevice bluetoothDevice); void onTransportDisconnected(BluetoothDevice bluetoothDevice); void onTransportError(BluetoothDevice bluetoothDevice); } }
bsd-3-clause
NCIP/cagrid
cagrid/Software/core/caGrid/projects/globalModelExchange/test/src/org/cagrid/gme/service/dao/XMLSchemaInformationDaoTestCase.java
1899
package org.cagrid.gme.service.dao; import java.net.URI; import java.net.URISyntaxException; import java.util.Collection; import java.util.HashSet; import java.util.Set; import org.cagrid.gme.domain.XMLSchema; import org.cagrid.gme.domain.XMLSchemaDocument; import org.cagrid.gme.service.domain.XMLSchemaInformation; import org.cagrid.gme.test.GMEIntegrationTestCaseBase; public class XMLSchemaInformationDaoTestCase extends GMEIntegrationTestCaseBase { protected XMLSchemaInformationDao xmlSchemaInformationDao; public void testWithoutDependencies() throws URISyntaxException { XMLSchemaInformation schemaInfo = new XMLSchemaInformation(); XMLSchema schema = new XMLSchema(); schemaInfo.setSchema(schema); URI namespace = new URI("http://foo"); schema.setTargetNamespace(namespace); XMLSchemaDocument doc = new XMLSchemaDocument(); doc.setSystemID("foo"); doc.setSchemaText("my schema"); XMLSchemaDocument doc2 = new XMLSchemaDocument(); doc2.setSystemID("foo2"); doc2.setSchemaText("my schema"); schema.setRootDocument(doc); Set<XMLSchemaDocument> docSet = new HashSet<XMLSchemaDocument>(); docSet.add(doc2); schema.setAdditionalSchemaDocuments(docSet); this.xmlSchemaInformationDao.save(schemaInfo); Collection<URI> allNamespaces = this.xmlSchemaInformationDao.getAllNamespaces(); assertEquals(1, allNamespaces.size()); assertTrue(allNamespaces.contains(namespace)); XMLSchema schemaForURI = this.xmlSchemaInformationDao.getXMLSchemaByTargetNamespace(namespace); assertEquals(schema, schemaForURI); Collection<XMLSchemaInformation> dependingSchemas = this.xmlSchemaInformationDao .getDependingXMLSchemaInformation(namespace); assertEquals(0, dependingSchemas.size()); } }
bsd-3-clause
erhs-robotics/Robo2013
board/Board.py
1668
#!/usr/bin/python2 import sys import os sys.path.append('lib') import cv2 from cv2 import cv import numpy as np import freenect from imgproc import * from Kinect import Kinect import Lock imgproc = Imgproc(-1) kinect = Kinect() params = [cv.CV_IMWRITE_PNG_COMPRESSION, 8] SCALE_FACTOR = 3 msg = "" def getTargets(): image = kinect.get_IR_image() depth = kinect.get_depth() targets = imgproc.getRect(image) targets = imgproc.filterRects(targets) imgproc.labelRects(image, targets) return targets, image def encodeTargets(targets): json_template = '{"status": "%s", "message" : "%s", "target" : "%s"}' target_str = "" for target in targets: dist = kinect.get_depth_at(target[0].x, target[0].y) print dist string = "%s,%s,%s" % (target.center_mass_x, dist, target.target_height) target_str += string + "|" status = "Found " + str(len(targets)) + " Targets" json = json_template % (status, msg, target_str) return json def writeInfo(image, json): Lock.waitforlock("info.json") Lock.lockfile("info.json") info = open("info.json", "w") info.seek(0) info.write(json) info.truncate() info.close() Lock.unlockfile("info.json") Lock.waitforlock("target.png") Lock.lockfile("target.png") cv2.imwrite("target.png", cv2.resize(bgr, (bgr.shape[1]/SCALE_FACTOR, bgr.shape[0]/SCALE_FACTOR)), params) Lock.unlockfile("target.png") if __name__ == '__main__': while True: #print "Looping" rects, bgr = getTargets() json = encodeTargets(rects) writeInfo(bgr, json)
bsd-3-clause
hainm/pythran
pythran/pythonic/time/time.hpp
531
#ifndef PYTHONIC_TIME_TIME_HPP #define PYTHONIC_TIME_TIME_HPP #include "pythonic/include/time/time.hpp" #include "pythonic/utils/proxy.hpp" #include <chrono> namespace pythonic { namespace time { double time() { std::chrono::time_point<std::chrono::steady_clock> tp = std::chrono::steady_clock::now(); return std::chrono::duration_cast<std::chrono::milliseconds>( tp.time_since_epoch()).count() / 1000.; } PROXY_IMPL(pythonic::time, time) } } #endif
bsd-3-clause
cRhodan/RMIP
ROS_Nodes/distance_calculator/src/distance_calculator/msg/__init__.py
39
from ._distance_travelled_msg import *
bsd-3-clause
dynoweb/optionTrader
src/model/Result.java
4729
package model; import java.io.Serializable; import javax.persistence.*; import java.util.Date; /** * The persistent class for the results database table. * */ @Entity @Table(name="results") @NamedQuery(name="Result.findAll", query="SELECT r FROM Result r") public class Result implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private int id; @Column(name="avg_days_in_trade") private double avgDaysInTrade; @Column(name="close_dte") private int closeDte; @Column(name = "created", insertable = false, updatable = false) @Temporal(TemporalType.TIMESTAMP) private Date created; @Column(name="credit_per_trade") private double creditPerTrade; private int dte; @Column(name="max_dd") private double maxDd; @Column(name="net_profit") private double netProfit; @Column(name="profit_per_day") private double profitPerDay; @Column(name="profit_per_trade") private double profitPerTrade; @Column(name="profit_target") private double profitTarget; private double profitable; @Column(name="return_per_trade") private double returnPerTrade; @Column(name="short_delta") private double shortDelta; @Column(name="long_delta") private double longDelta; @Column(name="stop_loss") private double stopLoss; private String symbol; @Column(name="trade_type") private String tradeType; private int trades; @Column(name = "updated", insertable = false, updatable = true) @Temporal(TemporalType.TIMESTAMP) private Date updated; private double width; public Result() { } public int getId() { return this.id; } public void setId(int id) { this.id = id; } public double getAvgDaysInTrade() { return this.avgDaysInTrade; } public void setAvgDaysInTrade(double avgDaysInTrade) { this.avgDaysInTrade = avgDaysInTrade; } public int getCloseDte() { return closeDte; } public void setCloseDte(int closeDte) { this.closeDte = closeDte; } public Date getCreated() { return this.created; } public void setCreated(Date created) { this.created = created; } public double getCreditPerTrade() { return this.creditPerTrade; } public void setCreditPerTrade(double creditPerTrade) { this.creditPerTrade = creditPerTrade; } public int getDte() { return this.dte; } public void setDte(int dte) { this.dte = dte; } public double getMaxDd() { return this.maxDd; } public void setMaxDd(double maxDd) { this.maxDd = maxDd; } public double getNetProfit() { return this.netProfit; } public void setNetProfit(double netProfit) { this.netProfit = netProfit; } public double getProfitPerDay() { return this.profitPerDay; } public void setProfitPerDay(double profitPerDay) { this.profitPerDay = profitPerDay; } public double getProfitPerTrade() { return this.profitPerTrade; } public void setProfitPerTrade(double profitPerTrade) { this.profitPerTrade = profitPerTrade; } public double getProfitTarget() { return this.profitTarget; } public void setProfitTarget(double profitTarget) { this.profitTarget = profitTarget; } public double getProfitable() { return this.profitable; } public void setProfitable(double profitable) { this.profitable = profitable; } public double getReturnPerTrade() { return this.returnPerTrade; } public void setReturnPerTrade(double returnPerTrade) { this.returnPerTrade = returnPerTrade; } public double getShortDelta() { return this.shortDelta; } public void setShortDelta(double shortDelta) { this.shortDelta = shortDelta; } public double getLongDelta() { return longDelta; } public void setLongDelta(double longDelta) { this.longDelta = longDelta; } public double getStopLoss() { return this.stopLoss; } public void setStopLoss(double stopLoss) { this.stopLoss = stopLoss; } public String getSymbol() { return symbol; } public void setSymbol(String symbol) { this.symbol = symbol; } public int getTrades() { return this.trades; } public void setTrades(int trades) { this.trades = trades; } public String getTradeType() { return tradeType; } public void setTradeType(String tradeType) { this.tradeType = tradeType; } public Date getUpdated() { return this.updated; } public void setUpdated(Date updated) { this.updated = updated; } public double getWidth() { return this.width; } public void setWidth(double width) { this.width = width; } }
bsd-3-clause
youtube/cobalt
starboard/evergreen/x86/sbversion/13/gyp_configuration.py
932
# Copyright 2021 The Cobalt Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Starboard evergreen-x86 platform configuration for gyp_cobalt.""" from starboard.evergreen.x86 import gyp_configuration as parent_configuration def CreatePlatformConfig(): return parent_configuration.EvergreenX86Configuration( 'evergreen-x86-sbversion-13', sabi_json_path='starboard/sabi/x86/sabi-v13.json')
bsd-3-clause
jajce/osquery
tools/tests/test_osqueryi.py
5569
#!/usr/bin/env python # Copyright (c) 2014, 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. from __future__ import absolute_import from __future__ import division from __future__ import print_function # pyexpect.replwrap will not work with unicode_literals #from __future__ import unicode_literals import os import random import unittest # osquery-specific testing utils import test_base SHELL_TIMEOUT = 10 class OsqueryiTest(unittest.TestCase): def setUp(self): self.binary = os.path.join(test_base.ARGS.build, "osquery", "osqueryi") self.osqueryi = test_base.OsqueryWrapper(self.binary) self.dbpath = "%s%s" % ( test_base.CONFIG["options"]["database_path"], str(random.randint(1000, 9999))) def test_error(self): '''Test that we throw an error on bad query''' self.osqueryi.run_command(' ') self.assertRaises(test_base.OsqueryException, self.osqueryi.run_query, 'foo') def test_config_check_success(self): '''Test that a 0-config passes''' proc = test_base.TimeoutRunner([ self.binary, "--config_check", "--database_path=%s" % (self.dbpath), "--config_path=%s/test.config" % test_base.SCRIPT_DIR ], SHELL_TIMEOUT) self.assertEqual(proc.stdout, "") print (proc.stdout) print (proc.stderr) self.assertEqual(proc.proc.poll(), 0) def test_config_check_failure(self): '''Test that a missing config fails''' proc = test_base.TimeoutRunner([ self.binary, "--config_check", "--database_path=%s" % (self.dbpath), "--config_path=/this/path/does/not/exist" ], SHELL_TIMEOUT) self.assertNotEqual(proc.stderr, "") print (proc.stdout) print (proc.stderr) self.assertEqual(proc.proc.poll(), 1) # Now with a valid path, but invalid content. proc = test_base.TimeoutRunner([ self.binary, "--config_check", "--database_path=%s" % (self.dbpath), "--config_path=%s/test.badconfig" % test_base.SCRIPT_DIR ], SHELL_TIMEOUT) self.assertEqual(proc.proc.poll(), 1) self.assertNotEqual(proc.stderr, "") # Finally with a missing config plugin proc = test_base.TimeoutRunner([ self.binary, "--config_check", "--database_path=%s" % (self.dbpath), "--config_plugin=does_not_exist" ], SHELL_TIMEOUT) self.assertNotEqual(proc.stderr, "") self.assertNotEqual(proc.proc.poll(), 0) def test_config_check_example(self): '''Test that the example config passes''' example_path = "deployment/osquery.example.conf" proc = test_base.TimeoutRunner([ self.binary, "--config_check", "--config_path=%s/../%s" % (test_base.SCRIPT_DIR, example_path) ], SHELL_TIMEOUT) self.assertEqual(proc.stdout, "") print (proc.stdout) print (proc.stderr) self.assertEqual(proc.proc.poll(), 0) def test_meta_commands(self): '''Test the supported meta shell/help/info commands''' commands = [ '.help', '.all', '.all osquery_info', '.all this_table_does_not_exist', '.echo', '.echo on', '.echo off', '.header', '.header off', '.header on', '.mode', '.mode csv', '.mode column', '.mode line', '.mode list', '.mode pretty', '.mode this_mode_does_not_exists', '.nullvalue', '.nullvalue ""', '.print', '.print hello', '.schema osquery_info', '.schema this_table_does_not_exist', '.schema', '.separator', '.separator ,', '.show', '.tables osquery', '.tables osquery_info', '.tables this_table_does_not_exist', '.tables', '.trace', '.width', '.width 80', '.timer', '.timer on', '.timer off' ] for command in commands: result = self.osqueryi.run_command(command) pass def test_time(self): '''Demonstrating basic usage of OsqueryWrapper with the time table''' self.osqueryi.run_command(' ') # flush error output result = self.osqueryi.run_query( 'SELECT hour, minutes, seconds FROM time;') self.assertEqual(len(result), 1) row = result[0] self.assertTrue(0 <= int(row['hour']) <= 24) self.assertTrue(0 <= int(row['minutes']) <= 60) self.assertTrue(0 <= int(row['seconds']) <= 60) def test_config_bad_json(self): self.osqueryi = test_base.OsqueryWrapper(self.binary, args={"config_path": "/"}) result = self.osqueryi.run_query('SELECT * FROM time;') self.assertEqual(len(result), 1) if __name__ == '__main__': test_base.Tester().run()
bsd-3-clause
dineshkummarc/zf2
tests/Zend/Code/Reflection/DocBlockReflectionTest.php
4261
<?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_Reflection * @subpackage UnitTests * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace ZendTest\Code\Reflection; use Zend\Code\Reflection\DocBlockReflection, Zend\Code\Reflection\ClassReflection; /** * @category Zend * @package Zend_Reflection * @subpackage UnitTests * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Reflection * @group Zend_Reflection_Docblock */ class DocBlockReflectionTest extends \PHPUnit_Framework_TestCase { public function testDocblockShortDescription() { $classReflection = new ClassReflection('ZendTest\Code\Reflection\TestAsset\TestSampleClass5'); $this->assertEquals('TestSampleClass5 DocBlock Short Desc', $classReflection->getDocblock()->getShortDescription()); } public function testDocblockLongDescription() { $classReflection = new ClassReflection('ZendTest\Code\Reflection\TestAsset\TestSampleClass5'); $expectedOutput = 'This is a long description for the docblock of this class, it should be longer than 3 lines. It indeed is longer than 3 lines now.'; $this->assertEquals($expectedOutput, $classReflection->getDocblock()->getLongDescription()); } public function testDocblockTags() { $classReflection = new ClassReflection('ZendTest\Code\Reflection\TestAsset\TestSampleClass5'); $this->assertEquals(1, count($classReflection->getDocblock()->getTags())); $this->assertEquals(1, count($classReflection->getDocblock()->getTags('author'))); $this->assertFalse($classReflection->getDocblock()->getTag('version')); $this->assertTrue($classReflection->getMethod('doSomething')->getDocblock()->hasTag('return')); $returnTag = $classReflection->getMethod('doSomething')->getDocblock()->getTag('return'); $this->assertInstanceOf('Zend\Code\Reflection\DocBlock\Tag', $returnTag); $this->assertEquals('mixed', $returnTag->getType()); } public function testDocblockLines() { //$this->markTestIncomplete('Line numbers incomplete'); $classReflection = new ClassReflection('ZendTest\Code\Reflection\TestAsset\TestSampleClass5'); $classDocblock = $classReflection->getDocblock(); $this->assertEquals(5, $classDocblock->getStartLine()); $this->assertEquals(15, $classDocblock->getEndLine()); } public function testDocblockContents() { $classReflection = new ClassReflection('ZendTest\Code\Reflection\TestAsset\TestSampleClass5'); $classDocblock = $classReflection->getDocblock(); $expectedContents = <<<EOS TestSampleClass5 DocBlock Short Desc This is a long description for the docblock of this class, it should be longer than 3 lines. It indeed is longer than 3 lines now. @author Ralph Schindler <ralph.schindler@zend.com> EOS; $this->assertEquals($expectedContents, $classDocblock->getContents()); } public function testToString() { $classReflection = new ClassReflection('ZendTest\Code\Reflection\TestAsset\TestSampleClass5'); $classDocblock = $classReflection->getDocblock(); $expectedString = 'DocBlock [ /* DocBlock */ ] {' . PHP_EOL . PHP_EOL . ' - Tags [1] {' . PHP_EOL . ' DocBlock Tag [ * @author ]' . PHP_EOL . ' }' . PHP_EOL . '}' . PHP_EOL; $this->assertEquals($expectedString, (string)$classDocblock); } }
bsd-3-clause
davidadamsphd/hellbender
src/main/java/org/broadinstitute/hellbender/utils/read/GoogleGenomicsReadToGATKReadAdapter.java
23444
package org.broadinstitute.hellbender.utils.read; import com.google.api.services.genomics.model.LinearAlignment; import com.google.api.services.genomics.model.Position; import com.google.api.services.genomics.model.Read; import com.google.cloud.dataflow.sdk.coders.CustomCoder; import com.google.cloud.dataflow.sdk.coders.KvCoder; import com.google.cloud.dataflow.sdk.values.KV; import com.google.cloud.genomics.dataflow.coders.GenericJsonCoder; import com.google.cloud.genomics.gatk.common.GenomicsConverter; import htsjdk.samtools.Cigar; import htsjdk.samtools.SAMFileHeader; import htsjdk.samtools.SAMRecord; import htsjdk.samtools.SAMUtils; import htsjdk.samtools.TextCigarCodec; import htsjdk.samtools.util.Locatable; import htsjdk.samtools.util.StringUtil; import org.broadinstitute.hellbender.engine.dataflow.coders.UUIDCoder; import org.broadinstitute.hellbender.exceptions.GATKException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.UUID; /** * Implementation of the {@link GATKRead} interface for the Google Genomics {@link Read} class. * * This adapter wraps a {@link Read} without making a copy, so construction is cheap, * but care must be exercised if the underlying read has been exposed somewhere before * wrapping. */ public final class GoogleGenomicsReadToGATKReadAdapter implements GATKRead { private final Read genomicsRead; private final UUID uuid; public GoogleGenomicsReadToGATKReadAdapter( final Read genomicsRead ) { this(genomicsRead, UUID.randomUUID()); } /** * Constructor that allows an explicit UUID to be passed in -- only meant * for internal use and test class use, which is why it's package protected. */ GoogleGenomicsReadToGATKReadAdapter( final Read genomicsRead, final UUID uuid ) { this.genomicsRead = genomicsRead; this.uuid = uuid; } /** * Dataflow coder for this adapter class */ public static final CustomCoder<GoogleGenomicsReadToGATKReadAdapter> CODER = new CustomCoder<GoogleGenomicsReadToGATKReadAdapter>() { private static final long serialVersionUID = 1l; @Override public void encode(GoogleGenomicsReadToGATKReadAdapter value, OutputStream outStream, Context context) throws IOException { KvCoder.of(UUIDCoder.CODER,GenericJsonCoder.of(Read.class)).encode(KV.of(value.getUUID(), value.genomicsRead), outStream, context); } @Override public GoogleGenomicsReadToGATKReadAdapter decode(InputStream inStream, Context context) throws IOException { final KV<UUID, Read> decode = KvCoder.of(UUIDCoder.CODER, GenericJsonCoder.of(Read.class)).decode(inStream, context); final UUID uuid = decode.getKey(); final Read read = decode.getValue(); return new GoogleGenomicsReadToGATKReadAdapter(read, uuid); } }; private static <T> T assertFieldValueNotNull( final T fieldValue, final String fieldName ) { if ( fieldValue == null ) { throw new GATKException.MissingReadField(fieldName); } return fieldValue; } private void assertHasAlignment() { assertFieldValueNotNull(genomicsRead.getAlignment(), "alignment"); } private void assertHasPosition() { assertHasAlignment(); assertFieldValueNotNull(genomicsRead.getAlignment().getPosition(), "position"); } private boolean positionIsUnmapped( final Position position ) { return position == null || position.getReferenceName() == null || position.getReferenceName().equals(SAMRecord.NO_ALIGNMENT_REFERENCE_NAME) || position.getPosition() == null || position.getPosition() < 0; } private void makeAlignmentIfNecessary() { if ( genomicsRead.getAlignment() == null ) { genomicsRead.setAlignment(new LinearAlignment()); } } private void makePositionIfNecessary() { makeAlignmentIfNecessary(); if ( genomicsRead.getAlignment().getPosition() == null ) { genomicsRead.getAlignment().setPosition(new Position()); } } private void makeMatePositionIfNecessary() { if ( genomicsRead.getNextMatePosition() == null ) { genomicsRead.setNextMatePosition(new Position()); } } @Override public UUID getUUID() { return uuid; } @Override public String getName() { return genomicsRead.getFragmentName(); } @Override public void setName( final String name ) { genomicsRead.setFragmentName(name); } @Override public String getContig() { if ( isUnmapped() ) { return null; } // Guaranteed non-null due to isUnmapped() check above. return genomicsRead.getAlignment().getPosition().getReferenceName(); } @Override public int getStart() { if ( isUnmapped() ) { return ReadConstants.UNSET_POSITION; } // Guaranteed non-null due to isUnmapped() check above. // Convert from 0-based to 1-based start position return genomicsRead.getAlignment().getPosition().getPosition().intValue() + 1; } @Override public int getEnd() { if ( isUnmapped() ) { return ReadConstants.UNSET_POSITION; } // Guaranteed non-null due to isUnmapped() check above. // Position in genomicsRead is 0-based, so add getCigar().getReferenceLength() to it, // not getCigar().getReferenceLength() - 1, in order to convert to a 1-based end position. return genomicsRead.getAlignment().getPosition().getPosition().intValue() + getCigar().getReferenceLength(); } @Override public void setPosition( final String contig, final int start ) { if ( contig == null || contig.equals(SAMRecord.NO_ALIGNMENT_REFERENCE_NAME) || start < 1 ) { throw new IllegalArgumentException("contig must be non-null and not equal to " + SAMRecord.NO_ALIGNMENT_REFERENCE_NAME + ", and start must be >= 1"); } makePositionIfNecessary(); genomicsRead.getAlignment().getPosition().setReferenceName(contig); // Convert from a 1-based to a 0-based position genomicsRead.getAlignment().getPosition().setPosition((long)start - 1); } @Override public void setPosition( final Locatable locatable ) { if ( locatable == null ) { throw new IllegalArgumentException("Cannot set read position to null"); } setPosition(locatable.getContig(), locatable.getStart()); } @Override public int getUnclippedStart() { final int start = getStart(); return start == ReadConstants.UNSET_POSITION ? ReadConstants.UNSET_POSITION : SAMUtils.getUnclippedStart(start, getCigar()); } @Override public int getUnclippedEnd() { final int end = getEnd(); return end == ReadConstants.UNSET_POSITION ? ReadConstants.UNSET_POSITION : SAMUtils.getUnclippedEnd(getEnd(), getCigar()); } @Override public String getMateContig() { if ( mateIsUnmapped() ) { return null; } // Guaranteed non-null due to mateIsUnmapped() check above. return genomicsRead.getNextMatePosition().getReferenceName(); } @Override public int getMateStart() { if ( mateIsUnmapped() ) { return ReadConstants.UNSET_POSITION; } // Guaranteed non-null due to mateIsUnmapped() check above. // Convert from 0-based to 1-based position. return genomicsRead.getNextMatePosition().getPosition().intValue() + 1; } @Override public void setMatePosition( final String contig, final int start ) { if ( contig == null || contig.equals(SAMRecord.NO_ALIGNMENT_REFERENCE_NAME) || start < 1 ) { throw new IllegalArgumentException("contig must be non-null and not equal to " + SAMRecord.NO_ALIGNMENT_REFERENCE_NAME + ", and start must be >= 1"); } // Calling this method has the additional effect of marking the read as paired setIsPaired(true); makeMatePositionIfNecessary(); genomicsRead.getNextMatePosition().setReferenceName(contig); // Convert from a 1-based to a 0-based position genomicsRead.getNextMatePosition().setPosition((long)start - 1); } @Override public void setMatePosition( final Locatable locatable ) { if ( locatable == null ) { throw new IllegalArgumentException("Cannot set mate position to null"); } setMatePosition(locatable.getContig(), locatable.getStart()); } @Override public int getFragmentLength() { return genomicsRead.getFragmentLength() != null ? genomicsRead.getFragmentLength() : 0; } @Override public void setFragmentLength( final int fragmentLength ) { // May be negative if mate maps to lower position than read genomicsRead.setFragmentLength(fragmentLength); } @Override public int getMappingQuality() { if ( genomicsRead.getAlignment() == null || genomicsRead.getAlignment().getMappingQuality() == null ) { return ReadConstants.NO_MAPPING_QUALITY; } return genomicsRead.getAlignment().getMappingQuality(); } @Override public void setMappingQuality( final int mappingQuality ) { if ( mappingQuality < 0 || mappingQuality > 255 ) { throw new IllegalArgumentException("mapping quality must be >= 0 and <= 255"); } makeAlignmentIfNecessary(); genomicsRead.getAlignment().setMappingQuality(mappingQuality); } @Override public byte[] getBases() { final String basesString = genomicsRead.getAlignedSequence(); if ( basesString == null || basesString.isEmpty() || basesString.equals(SAMRecord.NULL_SEQUENCE_STRING) ) { return new byte[0]; } return StringUtil.stringToBytes(basesString); } @Override public void setBases( final byte[] bases ) { genomicsRead.setAlignedSequence(bases != null ? StringUtil.bytesToString(bases) : null); } @Override public byte[] getBaseQualities() { final List<Integer> baseQualities = genomicsRead.getAlignedQuality(); if ( baseQualities == null || baseQualities.isEmpty() ) { return new byte[0]; } byte[] convertedBaseQualities = new byte[baseQualities.size()]; for ( int i = 0; i < baseQualities.size(); ++i ) { if ( baseQualities.get(i) < 0 || baseQualities.get(i) > Byte.MAX_VALUE ) { throw new GATKException("Base quality score " + baseQualities.get(i) + " is invalid and/or not convertible to byte"); } convertedBaseQualities[i] = baseQualities.get(i).byteValue(); } return convertedBaseQualities; } @Override public void setBaseQualities( final byte[] baseQualities ) { if ( baseQualities == null ) { genomicsRead.setAlignedQuality(null); return; } final List<Integer> convertedBaseQualities = new ArrayList<>(baseQualities.length); for ( byte b : baseQualities ) { if ( b < 0 ) { throw new GATKException("Base quality score " + b + " is invalid"); } convertedBaseQualities.add((int)b); } genomicsRead.setAlignedQuality(convertedBaseQualities.isEmpty() ? null : convertedBaseQualities); } @Override public Cigar getCigar() { if ( genomicsRead.getAlignment() == null || genomicsRead.getAlignment().getCigar() == null ) { return new Cigar(); } return CigarConversionUtils.convertCigarUnitListToSAMCigar(genomicsRead.getAlignment().getCigar()); } @Override public void setCigar( final Cigar cigar ) { makeAlignmentIfNecessary(); genomicsRead.getAlignment().setCigar(cigar != null ? CigarConversionUtils.convertSAMCigarToCigarUnitList(cigar) : null); } @Override public void setCigar( final String cigarString ) { makeAlignmentIfNecessary(); genomicsRead.getAlignment().setCigar(cigarString != null ? CigarConversionUtils.convertSAMCigarToCigarUnitList(TextCigarCodec.decode(cigarString)) : null); } @Override public String getReadGroup() { return genomicsRead.getReadGroupId(); } @Override public void setReadGroup( final String readGroupID ) { genomicsRead.setReadGroupId(readGroupID); } @Override public boolean isPaired() { assertFieldValueNotNull(genomicsRead.getNumberReads(), "number of reads"); return genomicsRead.getNumberReads() == 2; } @Override public void setIsPaired( final boolean isPaired ) { genomicsRead.setNumberReads(isPaired ? 2 : 1); if ( ! isPaired ) { genomicsRead.setProperPlacement(false); } } @Override public boolean isProperlyPaired() { assertFieldValueNotNull(genomicsRead.getProperPlacement(), "proper placement"); return isPaired() && genomicsRead.getProperPlacement(); } @Override public void setIsProperlyPaired( final boolean isProperlyPaired ) { if ( isProperlyPaired ) { setIsPaired(true); } genomicsRead.setProperPlacement(isProperlyPaired); } @Override public boolean isUnmapped() { return genomicsRead.getAlignment() == null || positionIsUnmapped(genomicsRead.getAlignment().getPosition()); } @Override public void setIsUnmapped() { genomicsRead.setAlignment(null); } @Override public boolean mateIsUnmapped() { if ( ! isPaired() ) { throw new IllegalStateException("Cannot get mate information for an unpaired read"); } return positionIsUnmapped(genomicsRead.getNextMatePosition()); } @Override public void setMateIsUnmapped() { // Calling this method has the side effect of marking the read as paired. setIsPaired(true); genomicsRead.setNextMatePosition(null); } @Override public boolean isReverseStrand() { assertHasPosition(); return assertFieldValueNotNull(genomicsRead.getAlignment().getPosition().getReverseStrand(), "strand"); } @Override public void setIsReverseStrand( final boolean isReverseStrand ) { makePositionIfNecessary(); genomicsRead.getAlignment().getPosition().setReverseStrand(isReverseStrand); } @Override public boolean mateIsReverseStrand() { if ( ! isPaired() ) { throw new IllegalStateException("Cannot get mate information for an unpaired read"); } final Position matePosition = assertFieldValueNotNull(genomicsRead.getNextMatePosition(), "mate position"); return assertFieldValueNotNull(matePosition.getReverseStrand(), "mate strand"); } @Override public void setMateIsReverseStrand( final boolean mateIsReverseStrand ) { // Calling this method has the side effect of marking the read as paired. setIsPaired(true); makeMatePositionIfNecessary(); genomicsRead.getNextMatePosition().setReverseStrand(mateIsReverseStrand); } @Override public boolean isFirstOfPair() { final int readNumber = assertFieldValueNotNull(genomicsRead.getReadNumber(), "read number"); return isPaired() && readNumber == 0; } @Override public void setIsFirstOfPair() { // Calling this method has the side effect of marking the read as paired. setIsPaired(true); genomicsRead.setReadNumber(0); } @Override public boolean isSecondOfPair() { final int readNumber = assertFieldValueNotNull(genomicsRead.getReadNumber(), "read number"); return isPaired() && readNumber == 1; } @Override public void setIsSecondOfPair() { // Calling this method has the side effect of marking the read as paired. setIsPaired(true); genomicsRead.setReadNumber(1); } @Override public boolean isSecondaryAlignment() { return assertFieldValueNotNull(genomicsRead.getSecondaryAlignment(), "secondary alignment"); } @Override public void setIsSecondaryAlignment( final boolean isSecondaryAlignment ) { genomicsRead.setSecondaryAlignment(isSecondaryAlignment); } @Override public boolean isSupplementaryAlignment() { return assertFieldValueNotNull(genomicsRead.getSupplementaryAlignment(), "supplementary alignment"); } @Override public void setIsSupplementaryAlignment( final boolean isSupplementaryAlignment ) { genomicsRead.setSupplementaryAlignment(isSupplementaryAlignment); } @Override public boolean failsVendorQualityCheck() { return assertFieldValueNotNull(genomicsRead.getFailedVendorQualityChecks(), "failed vendor quality checks"); } @Override public void setFailsVendorQualityCheck( final boolean failsVendorQualityCheck ) { genomicsRead.setFailedVendorQualityChecks(failsVendorQualityCheck); } @Override public boolean isDuplicate() { return assertFieldValueNotNull(genomicsRead.getDuplicateFragment(), "duplicate fragment"); } @Override public void setIsDuplicate( final boolean isDuplicate ) { genomicsRead.setDuplicateFragment(isDuplicate); } @Override public boolean hasAttribute( final String attributeName ) { ReadUtils.assertAttributeNameIsLegal(attributeName); return genomicsRead.getInfo() != null && genomicsRead.getInfo().containsKey(attributeName); } private String getRawAttributeValue( final String attributeName, final String targetType ) { ReadUtils.assertAttributeNameIsLegal(attributeName); if ( genomicsRead.getInfo() == null ) { return null; } final List<String> rawValue = genomicsRead.getInfo().get(attributeName); if ( rawValue == null || rawValue.isEmpty() || rawValue.get(0) == null ) { return null; } // We don't support decoding attribute values represented as multiple Strings if ( rawValue.size() > 1 ) { throw new GATKException.ReadAttributeTypeMismatch(attributeName, targetType); } return rawValue.get(0); } @Override public Integer getAttributeAsInteger( final String attributeName ) { try { // Assume that integer attributes are encoded as a single String in the first position of the List of values for an attribute final String rawValue = getRawAttributeValue(attributeName, "integer"); return rawValue != null ? Integer.parseInt(rawValue) : null; } catch ( NumberFormatException e ) { throw new GATKException.ReadAttributeTypeMismatch(attributeName, "integer", e); } } @Override public String getAttributeAsString( final String attributeName ) { // Assume that String attributes are encoded as a single String in the first position of the List of values for an attribute return getRawAttributeValue(attributeName, "String"); } @Override public byte[] getAttributeAsByteArray( final String attributeName ) { // Assume that byte array attributes are encoded as a single String in the first position of the List of values for an attribute, // and that the bytes of this String are directly convertible to byte array. final String rawValue = getRawAttributeValue(attributeName, "byte array"); return rawValue != null ? rawValue.getBytes() : null; } private void makeInfoMapIfNecessary() { if ( genomicsRead.getInfo() == null ) { genomicsRead.setInfo(new LinkedHashMap<>()); } } @Override public void setAttribute( final String attributeName, final Integer attributeValue ) { ReadUtils.assertAttributeNameIsLegal(attributeName); makeInfoMapIfNecessary(); if ( attributeValue == null ) { clearAttribute(attributeName); return; } final List<String> encodedValue = Arrays.asList(attributeValue.toString()); genomicsRead.getInfo().put(attributeName, encodedValue); } @Override public void setAttribute( final String attributeName, final String attributeValue ) { ReadUtils.assertAttributeNameIsLegal(attributeName); makeInfoMapIfNecessary(); if ( attributeValue == null ) { clearAttribute(attributeName); return; } final List<String> encodedValue = Arrays.asList(attributeValue); genomicsRead.getInfo().put(attributeName, encodedValue); } @Override public void setAttribute( final String attributeName, final byte[] attributeValue ) { ReadUtils.assertAttributeNameIsLegal(attributeName); makeInfoMapIfNecessary(); if ( attributeValue == null ) { clearAttribute(attributeName); return; } final List<String> encodedValue = Arrays.asList(new String(attributeValue)); genomicsRead.getInfo().put(attributeName, encodedValue); } @Override public void clearAttribute( final String attributeName ) { ReadUtils.assertAttributeNameIsLegal(attributeName); if ( genomicsRead.getInfo() != null ) { genomicsRead.getInfo().remove(attributeName); } } @Override public void clearAttributes() { genomicsRead.setInfo(null); } @Override public GATKRead copy() { // clone() actually makes a deep copy of all fields here (via GenericData.clone()) return new GoogleGenomicsReadToGATKReadAdapter(genomicsRead.clone()); } @Override public SAMRecord convertToSAMRecord( final SAMFileHeader header ) { // TODO: this converter is imperfect and should either be patched or replaced completely. return GenomicsConverter.makeSAMRecord(genomicsRead, header); } @Override public Read convertToGoogleGenomicsRead() { return genomicsRead; } @Override public boolean equalsIgnoreUUID( final Object other ) { if ( this == other ) return true; if ( other == null || getClass() != other.getClass() ) return false; GoogleGenomicsReadToGATKReadAdapter that = (GoogleGenomicsReadToGATKReadAdapter)other; // The Read class does have a working equals() method (inherited from AbstractMap) return genomicsRead != null ? genomicsRead.equals(that.genomicsRead) : that.genomicsRead == null; } @Override public boolean equals( Object other ) { return equalsIgnoreUUID(other) && uuid.equals(((GoogleGenomicsReadToGATKReadAdapter)other).uuid); } @Override public int hashCode() { int result = genomicsRead != null ? genomicsRead.hashCode() : 0; result = 31 * result + uuid.hashCode(); return result; } }
bsd-3-clause
maverick3609/yii2-ckeditor-widget
src/assets/ckeditor/build-config.js
3297
/** * @license Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md or http://ckeditor.com/license */ /** * This file was added automatically by CKEditor builder. * You may re-use it at any time to build CKEditor again. * * If you would like to build CKEditor online again * (for example to upgrade), visit one the following links: * * (1) http://ckeditor.com/builder * Visit online builder to build CKEditor from scratch. * * (2) http://ckeditor.com/builder/e6b8a045f8f984a69463975ca3e6524a * Visit online builder to build CKEditor, starting with the same setup as before. * * (3) http://ckeditor.com/builder/download/e6b8a045f8f984a69463975ca3e6524a * Straight download link to the latest version of CKEditor (Optimized) with the same setup as before. * * NOTE: * This file is not used by CKEditor, you may remove it. * Changing this file will not change your CKEditor configuration. */ var CKBUILDER_CONFIG = { skin: 'bootstrapck', preset: 'full', ignore: [ '.bender', 'bender.js', 'bender-err.log', 'bender-out.log', 'dev', '.DS_Store', '.editorconfig', '.gitattributes', '.gitignore', 'gruntfile.js', '.idea', '.jscsrc', '.jshintignore', '.jshintrc', '.mailmap', 'node_modules', 'package.json', 'README.md', 'tests' ], plugins : { 'a11yhelp' : 1, 'about' : 1, 'basicstyles' : 1, 'bidi' : 1, 'blockquote' : 1, 'clipboard' : 1, 'colorbutton' : 1, 'colordialog' : 1, 'contextmenu' : 1, 'dialogadvtab' : 1, 'div' : 1, 'elementspath' : 1, 'enterkey' : 1, 'entities' : 1, 'eqneditor': 1, 'filebrowser' : 1, 'find' : 1, 'flash' : 1, 'floatingspace' : 1, 'font' : 1, 'format' : 1, 'forms' : 1, 'horizontalrule' : 1, 'htmlwriter' : 1, 'iframe' : 1, 'image' : 1, 'indentblock' : 1, 'indentlist' : 1, 'justify' : 1, 'language' : 1, 'link' : 1, 'list' : 1, 'liststyle' : 1, 'magicline' : 1, 'maximize' : 1, 'newpage' : 1, 'pagebreak' : 1, 'pastefromword' : 1, 'pastetext' : 1, 'preview' : 1, 'print' : 1, 'removeformat' : 1, 'resize' : 1, 'save' : 1, 'scayt' : 1, 'selectall' : 1, 'showblocks' : 1, 'showborders' : 1, 'smiley' : 1, 'sourcearea' : 1, 'specialchar' : 1, 'stylescombo' : 1, 'tab' : 1, 'table' : 1, 'tabletools' : 1, 'templates' : 1, 'toolbar' : 1, 'undo' : 1, 'wsc' : 1, 'wysiwygarea' : 1 }, languages : { 'af' : 1, 'ar' : 1, 'bg' : 1, 'bn' : 1, 'bs' : 1, 'ca' : 1, 'cs' : 1, 'cy' : 1, 'da' : 1, 'de' : 1, 'el' : 1, 'en' : 1, 'en-au' : 1, 'en-ca' : 1, 'en-gb' : 1, 'eo' : 1, 'es' : 1, 'et' : 1, 'eu' : 1, 'fa' : 1, 'fi' : 1, 'fo' : 1, 'fr' : 1, 'fr-ca' : 1, 'gl' : 1, 'gu' : 1, 'he' : 1, 'hi' : 1, 'hr' : 1, 'hu' : 1, 'id' : 1, 'is' : 1, 'it' : 1, 'ja' : 1, 'ka' : 1, 'km' : 1, 'ko' : 1, 'ku' : 1, 'lt' : 1, 'lv' : 1, 'mk' : 1, 'mn' : 1, 'ms' : 1, 'nb' : 1, 'nl' : 1, 'no' : 1, 'pl' : 1, 'pt' : 1, 'pt-br' : 1, 'ro' : 1, 'ru' : 1, 'si' : 1, 'sk' : 1, 'sl' : 1, 'sq' : 1, 'sr' : 1, 'sr-latn' : 1, 'sv' : 1, 'th' : 1, 'tr' : 1, 'tt' : 1, 'ug' : 1, 'uk' : 1, 'vi' : 1, 'zh' : 1, 'zh-cn' : 1 } };
bsd-3-clause
Konnor95/la_boutique
views/site/login.php
2666
<?php use yii\bootstrap\ActiveForm; use yii\helpers\Html; /* @var $this yii\web\View */ /* @var $form yii\bootstrap\ActiveForm */ /* @var $model app\models\LoginForm */ $this->title = 'Login'; $this->params['breadcrumbs'][] = $this->title; ?> <section class="login_register"> <div class="container"> <div class="row row-centered"> <div class="span6 col-centered"> <div class="login"> <div class="box"> <?php $form = ActiveForm::begin([ 'id' => 'login-form', 'fieldConfig' => [ 'template' => "<div class=\"span6\"> <div class=\"control-group\">{label} <div class=\"controls\">{input} <div class=\"col-lg-3\">{error}</div> </div> </div> </div>", 'labelOptions' => ['class' => 'control-label'], ], ]); ?> <div class="hgroup title"> <h3><?= Html::encode($this->title) ?></h3> <h5>Please login using your existing account</h5> </div> <div class="box-content"> <div class="row-fluid"> <?= $form->field($model, 'username')?> <?= $form->field($model, 'password')->passwordInput() ?> <?= $form->field($model, 'rememberMe', [ 'template' => "<div class=\"col-lg-offset-1 col-lg-3\">{input}</div>\n<div class=\"col-lg-8\">{error}</div>", ])->checkbox() ?> </div> </div> <div class="buttons"> <div class="pull-left"> <button type="submit" class="btn btn-primary btn-small" name="login" value="Login"> Login </button> </div> </div> <?php ActiveForm::end(); ?> </div> </div> </div> </div> </div> </section>
bsd-3-clause
vadimtk/chrome4sdp
chrome/android/java/src/org/chromium/chrome/browser/ChromeSwitches.java
8562
// 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. package org.chromium.chrome.browser; /** * Contains all of the command line switches that are specific to the chrome/ * portion of Chromium on Android. */ public abstract class ChromeSwitches { // Switches used from Java. Please continue switch style used Chrome where // options-have-hypens and are_not_split_with_underscores. /** Testing: pretend that the switch value is the name of a child account. */ public static final String CHILD_ACCOUNT = "child-account"; /** Testing: This will unblock the FRE and partner customizations as well as other * UI that is related to SignIn */ public static final String ENABLE_SUPPRESSED_CHROMIUM_FEATURES = "enable-suppressed-chromium-features"; /** Mimic a low end device */ public static final String ENABLE_ACCESSIBILITY_TAB_SWITCHER = "enable-accessibility-tab-switcher"; /** Whether fullscreen support is disabled (auto hiding controls, etc...). */ public static final String DISABLE_FULLSCREEN = "disable-fullscreen"; /** Show the undo bar for high end UI devices. */ public static final String ENABLE_HIGH_END_UI_UNDO = "enable-high-end-ui-undo"; /** Enable toolbar swipe to change tabs in document mode */ public static final String ENABLE_TOOLBAR_SWIPE_IN_DOCUMENT_MODE = "enable-toolbar-swipe-in-document-mode"; /** Whether instant is disabled. */ public static final String DISABLE_INSTANT = "disable-instant"; /** Enables StrictMode violation detection. By default this logs violations to logcat. */ public static final String STRICT_MODE = "strict-mode"; /** Don't restore persistent state from saved files on startup. */ public static final String NO_RESTORE_STATE = "no-restore-state"; /** Disable the First Run Experience. */ public static final String DISABLE_FIRST_RUN_EXPERIENCE = "disable-fre"; /** Force the crash dump to be uploaded regardless of preferences. */ public static final String FORCE_CRASH_DUMP_UPLOAD = "force-dump-upload"; /** Enable debug logs for the video casting feature. */ public static final String ENABLE_CAST_DEBUG_LOGS = "enable-cast-debug"; /** Prevent automatic reconnection to current Cast video when Chrome restarts. */ public static final String DISABLE_CAST_RECONNECTION = "disable-cast-reconnection"; /** Whether or not to enable the experimental tablet tab stack. */ public static final String ENABLE_TABLET_TAB_STACK = "enable-tablet-tab-stack"; /** Disables support for playing videos remotely via Android MediaRouter API. */ public static final String DISABLE_CAST = "disable-cast"; /** Never forward URL requests to external intents. */ public static final String DISABLE_EXTERNAL_INTENT_REQUESTS = "disable-external-intent-requests"; /** Disable document mode. */ public static final String DISABLE_DOCUMENT_MODE = "disable-document-mode"; /** Disable Contextual Search. */ public static final String DISABLE_CONTEXTUAL_SEARCH = "disable-contextual-search"; /** Enable Contextual Search. */ public static final String ENABLE_CONTEXTUAL_SEARCH = "enable-contextual-search"; /** Enable Contextual Search for instrumentation testing. Not exposed to user. */ public static final String ENABLE_CONTEXTUAL_SEARCH_FOR_TESTING = "enable-contextual-search-for-testing"; /** Enable new Website Settings UI, which does not have controls for editing settings */ public static final String DISABLE_READ_ONLY_WEBSITE_SETTINGS_POPUP = "disable-read-only-website-settings-popup"; // How many thumbnails should we allow in the cache (per tab stack)? public static final String THUMBNAILS = "thumbnails"; // How many "approximated" thumbnails should we allow in the cache // (per tab stack)? These take very low memory but have poor quality. public static final String APPROXIMATION_THUMBNAILS = "approximation-thumbnails"; /** * Disable bottom infobar-like Reader Mode panel. */ public static final String DISABLE_READER_MODE_BOTTOM_BAR = "disable-reader-mode-bottom-bar"; /////////////////////////////////////////////////////////////////////////////////////////////// // Native Switches /////////////////////////////////////////////////////////////////////////////////////////////// /** * Sets the max number of render processes to use. * Native switch - content_switches::kRendererProcessLimit. */ public static final String RENDER_PROCESS_LIMIT = "renderer-process-limit"; /** * Enable enhanced bookmarks feature. * Native switch - switches::kEnhancedBookmarksExperiment */ public static final String ENABLE_ENHANCED_BOOKMARKS = "enhanced-bookmarks-experiment"; /** Enable the DOM Distiller. */ public static final String ENABLE_DOM_DISTILLER = "enable-dom-distiller"; /** Enable experimental web-platform features, such as Push Messaging. */ public static final String EXPERIMENTAL_WEB_PLAFTORM_FEATURES = "enable-experimental-web-platform-features"; /** Enable Reader Mode button animation. */ public static final String ENABLE_READER_MODE_BUTTON_ANIMATION = "enable-dom-distiller-button-animation"; /** Enable the native app banners. */ public static final String ENABLE_APP_INSTALL_ALERTS = "enable-app-install-alerts"; /** * Use sandbox Wallet environment for requestAutocomplete. * Native switch - autofill::switches::kWalletServiceUseSandbox. */ public static final String USE_SANDBOX_WALLET_ENVIRONMENT = "wallet-service-use-sandbox"; /** * Change Google base URL. * Native switch - switches::kGoogleBaseURL. */ public static final String GOOGLE_BASE_URL = "google-base-url"; /** * Use fake device for Media Stream to replace actual camera and microphone. * Native switch - switches::kUseFakeDeviceForMediaStream. */ public static final String USE_FAKE_DEVICE_FOR_MEDIA_STREAM = "use-fake-device-for-media-stream"; /** * Disables the new icon-centric NTP design. * Native switch - switches::kDisableIconNtp */ public static final String DISABLE_ICON_NTP = "disable-icon-ntp"; /** * Enables the new icon-centric NTP design. * Native switch - switches::kEnableIconNtp */ public static final String ENABLE_ICON_NTP = "enable-icon-ntp"; /** * Enable Reader Mode button. * Native switch - switches::kEnableReaderModeToolbarIcon */ public static final String ENABLE_READER_MODE_BUTTON = "enable-reader-mode-toolbar-icon"; /** * Disable domain reliability * Native switch - switches::kDisableDomainReliability */ public static final String DISABLE_DOMAIN_RELIABILITY = "disable-domain-reliability"; /** * Enable use of Android's built-in spellchecker. * Native switch - switches::kEnableAndroidSpellChecker */ public static final String ENABLE_ANDROID_SPELLCHECKER = "enable-android-spellchecker"; /** * Enable the menu trimming that removes "Bookmarks" and "Recent tabs" menu items. */ public static final String ENABLE_MENU_TRIMMING = "enable-menu-trimming"; /** * Disable speculative TCP/IP preconnection. * Native switch - switches::kDisablePreconnect */ public static final String DISABLE_PRECONNECT = "disable-preconnect"; /** * Specifies Android phone page loading progress bar animation. * Native switch - switches::kProgressBarAnimation */ public static final String PROGRESS_BAR_ANIMATION = "progress-bar-animation"; /** * Enable offline pages. */ public static final String ENABLE_OFFLINE_PAGES = "enable-offline-pages"; /** * Feedback email */ public static final String CMD_LINE_SWITCH_FEEDBACK = "mail-feedback-to"; /** * Crash log server url */ public static final String CRASH_LOG_SERVER_CMD = "crash-log-server"; /** * Auto-update server url */ public static final String AUTO_UPDATE_SERVER_CMD = "auto-update-server"; /** * Enable Debug Mode/Logs */ public static final String ENABLE_DEBUG_MODE = "enable-debug-mode"; // Prevent instantiation. private ChromeSwitches() {} }
bsd-3-clause
devoyster/FasterTests
Source/Core/Integration/Nunit/SetupFixturesContexts/SetupFixtures/SucceededSetupFixtureState.cs
1468
using System; using FasterTests.Core.Interfaces.Models; namespace FasterTests.Core.Integration.Nunit.SetupFixturesContexts.SetupFixtures { public class SucceededSetupFixtureState : ISetupFixtureState { private readonly Lazy<ISetupFixtureAdapter> _lazyAdapter; private bool _isTeardownExecuted; public SucceededSetupFixtureState(Lazy<ISetupFixtureAdapter> lazyAdapter) { _lazyAdapter = lazyAdapter; } public bool IsExecuted { get { return true; } } public bool IsSucceeded { get { return true; } } public bool IsFailed { get { return false; } } public void SetParentFailed(IObserver<TestResult> resultsObserver) { throw new InvalidOperationException("Fixture was already set up"); } public void Setup(IObserver<TestResult> resultsObserver) { throw new InvalidOperationException("Fixture was already set up"); } public void Teardown(IObserver<TestResult> resultsObserver) { _lazyAdapter.Value.Teardown(); _isTeardownExecuted = true; } public ISetupFixtureState NextState() { if (_isTeardownExecuted) { return new NotExecutedSetupFixtureState(_lazyAdapter); } return this; } } }
bsd-3-clause
leighpauls/k2cro4
third_party/WebKit/Tools/Scripts/webkitpy/common/read_checksum_from_png_unittest.py
3633
#!/usr/bin/env python # Copyright (C) 2011 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 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 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. import StringIO import unittest from webkitpy.common import read_checksum_from_png class ReadChecksumFromPngTest(unittest.TestCase): def test_read_checksum(self): # Test a file with the comment. filehandle = StringIO.StringIO('''\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x03 \x00\x00\x02X\x08\x02\x00\x00\x00\x15\x14\x15'\x00\x00\x00)tEXtchecksum\x003c4134fe2739880353f91c5b84cadbaaC\xb8?\xec\x00\x00\x16\xfeIDATx\x9c\xed\xdd[\x8cU\xe5\xc1\xff\xf15T\x18\x0ea,)\xa6\x80XZ<\x10\n\xd6H\xc4V\x88}\xb5\xa9\xd6r\xd5\x0bki0\xa6\xb5ih\xd2\xde\x98PHz\xd1\x02=\\q#\x01\x8b\xa5rJ\x8b\x88i\xacM\xc5h\x8cbMk(\x1ez@!\x0c\xd5\xd2\xc2\xb44\x1c\x848\x1dF(\xeb\x7f\xb1\xff\xd9\xef~g\xd6\xde3\xe0o\x10\xec\xe7sa6{\xd6z\xd6\xb3\xd7\xf3\xa8_7\xdbM[Y\x96\x05\x00\x009\xc3\xde\xeb\t\x00\x00\xbc\xdf\x08,\x00\x800\x81\x05\x00\x10&\xb0\x00\x00\xc2\x04\x16\x00@\x98\xc0\x02\x00\x08\x13X\x00\x00a\x02\x0b\x00 Lx01\x00\x84\t,\x00\x800\x81\x05\x00\x10\xd64\xb0\xda\x9a\xdb\xb6m\xdb\xb4i\xd3\xfa\x9fr\xf3\xcd7\x0f\xe5T\x07\xe5\xd4\xa9''') checksum = read_checksum_from_png.read_checksum(filehandle) self.assertEqual('3c4134fe2739880353f91c5b84cadbaa', checksum) # Test a file without the comment. filehandle = StringIO.StringIO('''\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x03 \x00\x00\x02X\x08\x02\x00\x00\x00\x15\x14\x15'\x00\x00\x16\xfeIDATx\x9c\xed\xdd[\x8cU\xe5\xc1\xff\xf15T\x18\x0ea,)\xa6\x80XZ<\x10\n\xd6H\xc4V\x88}\xb5\xa9\xd6r\xd5\x0bki0\xa6\xb5ih\xd2\xde\x98PHz\xd1\x02=\\q#\x01\x8b\xa5rJ\x8b\x88i\xacM\xc5h\x8cbMk(\x1ez@!\x0c\xd5\xd2\xc2\xb44\x1c\x848\x1dF(\xeb\x7f\xb1\xff\xd9\xef~g\xd6\xde3\xe0o\x10\xec\xe7sa6{\xd6z\xd6\xb3\xd7\xf3\xa8_7\xdbM[Y\x96\x05\x00\x009\xc3\xde\xeb\t\x00\x00\xbc\xdf\x08,\x00\x800\x81\x05\x00\x10&\xb0\x00\x00\xc2\x04\x16\x00@\x98\xc0\x02\x00\x08\x13X\x00\x00a\x02\x0b\x00 Lx01\x00\x84\t,\x00\x800\x81\x05\x00\x10\xd64\xb0\xda\x9a\xdb\xb6m\xdb\xb4i\xd3\xfa\x9fr\xf3\xcd7\x0f\xe5T\x07\xe5\xd4\xa9S\x8b\x17/\x1e?~\xfc\xf8\xf1\xe3\xef\xbf\xff\xfe\xf7z:M5\xbb\x87\x17\xcbUZ\x8f|V\xd7\xbd\x10\xb6\xcd{b\x88\xf6j\xb3\x9b?\x14\x9b\xa1>\xe6\xf9\xd9\xcf\x00\x17\x93''') checksum = read_checksum_from_png.read_checksum(filehandle) self.assertEqual(None, checksum) if __name__ == '__main__': unittest.main()
bsd-3-clause
mkloubert/phpLINQ
System/IO/DirectoryNotFoundException.php
4551
<?php /********************************************************************************************************************** * phpLINQ (https://github.com/mkloubert/phpLINQ) * * * * Copyright (c) 2015, Marcel Joachim Kloubert <marcel.kloubert@gmx.net> * * 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 the copyright holder nor the names of its contributors may be used to endorse or promote * * products derived from this software without specific prior written permission. * * * * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * * **********************************************************************************************************************/ namespace System\IO; use \System\ClrString; use \System\Exception; /** * Indicates that a directory was not found / does not exist. * * @package System\IO * @author Marcel Joachim Kloubert <marcel.kloubert@gmx.net> */ class DirectoryNotFoundException extends Exception { /** * @var string */ private $_path; /** * Initializes a new instance of that class. * * @param string $path The path of the directory. * @param string $message The message. * @param \Exception $innerException The inner exception. * @param int $code The code. */ public function __construct($path = null, $message = null, \Exception $innerException = null, int $code = 0) { $this->_path = ClrString::valueToString($path, false); parent::__construct($message, $innerException, $code); } /** * Gets the path of file that does not exist. * * @return string The path of the file. */ public final function path() { return $this->_path; } }
bsd-3-clause
hashrock/JavaOutlineEditor
src/com/organic/maynard/outliner/menus/outline/MoveLeftMenuItem.java
3017
/** * Copyright (C) 2000, 2001 Maynard Demmon, maynard@organic.com * 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 names "Java Outline Editor", "JOE" 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 HOLDERS 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.organic.maynard.outliner.menus.outline; import com.organic.maynard.outliner.menus.*; import com.organic.maynard.outliner.*; import com.organic.maynard.outliner.guitree.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; import org.xml.sax.*; import com.organic.maynard.outliner.actions.*; /** * @author $Author: maynardd $ * @version $Revision: 1.2 $, $Date: 2004/02/02 10:17:42 $ */ public class MoveLeftMenuItem extends AbstractOutlinerMenuItem implements ActionListener, GUITreeComponent { // GUITreeComponent interface public void startSetup(Attributes atts) { super.startSetup(atts); addActionListener(this); } // ActionListener Interface public void actionPerformed(ActionEvent e) { OutlinerDocument doc = (OutlinerDocument) Outliner.documents.getMostRecentDocumentTouched(); OutlinerCellRendererImpl textArea = doc.panel.layout.getUIComponent(doc.tree.getEditingNode()); if (textArea == null) { return; } Node node = textArea.node; JoeTree tree = node.getTree(); OutlineLayoutManager layout = tree.getDocument().panel.layout; if (doc.tree.getComponentFocus() == OutlineLayoutManager.TEXT) { LeftAction.moveLeftText(textArea, tree, layout); } else if (doc.tree.getComponentFocus() == OutlineLayoutManager.ICON) { LeftAction.moveLeft(textArea, tree, layout); } } }
bsd-3-clause
daejunpark/jsaf
third_party/pmd/src/test/java/net/sourceforge/pmd/lang/ParserOptionsTest.java
2859
package net.sourceforge.pmd.lang; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import net.sourceforge.pmd.lang.ParserOptions; import org.junit.Test; public class ParserOptionsTest { @Test public void testSuppressMarker() throws Exception { ParserOptions parserOptions = new ParserOptions(); assertNull(parserOptions.getSuppressMarker()); parserOptions.setSuppressMarker("foo"); assertEquals("foo", parserOptions.getSuppressMarker()); } @Test public void testEqualsHashcode() throws Exception { ParserOptions options1 = new ParserOptions(); options1.setSuppressMarker("foo"); ParserOptions options2 = new ParserOptions(); options2.setSuppressMarker("bar"); ParserOptions options3 = new ParserOptions(); options3.setSuppressMarker("foo"); ParserOptions options4 = new ParserOptions(); options4.setSuppressMarker("bar"); verifyOptionsEqualsHashcode(options1, options2, options3, options4); } // 1 and 3 are equals, as are 2 and 4. @SuppressWarnings("PMD.UseAssertSameInsteadOfAssertTrue") public static void verifyOptionsEqualsHashcode(ParserOptions options1, ParserOptions options2, ParserOptions options3, ParserOptions options4) { // Objects should be different assertNotSame(options1, options2); assertNotSame(options1, options2); assertNotSame(options1, options3); assertNotSame(options2, options3); assertNotSame(options2, options4); assertNotSame(options3, options4); // Check all 16 equality combinations assertEquals(options1, options1); assertFalse(options1.equals(options2)); assertEquals(options1, options3); assertFalse(options1.equals(options4)); assertFalse(options2.equals(options1)); assertEquals(options2, options2); assertFalse(options2.equals(options3)); assertEquals(options2, options4); assertEquals(options3, options1); assertFalse(options3.equals(options2)); assertEquals(options3, options3); assertFalse(options3.equals(options4)); assertFalse(options4.equals(options1)); assertEquals(options4, options2); assertFalse(options4.equals(options3)); assertEquals(options4, options4); // Hashcodes should match up assertFalse(options1.hashCode() == options2.hashCode()); assertTrue(options1.hashCode() == options3.hashCode()); assertFalse(options1.hashCode() == options4.hashCode()); assertFalse(options2.hashCode() == options3.hashCode()); assertTrue(options2.hashCode() == options4.hashCode()); assertFalse(options3.hashCode() == options4.hashCode()); } public static junit.framework.Test suite() { return new junit.framework.JUnit4TestAdapter(ParserOptionsTest.class); } }
bsd-3-clause
Treeway/sandbox
common/tb/sdk/top/domain/WaybillApplyNewRequest.php
450
<?php /** * 面单申请 * @author auto create */ class WaybillApplyNewRequest { /** * TOP appkey **/ public $appKey; /** * 物流服务商编码 **/ public $cpCode; /** * -- **/ public $cpId; /** * 使用者ID **/ public $realUserId; /** * 商家ID **/ public $sellerId; /** * 发货地址 **/ public $shippingAddress; /** * 面单详细信息 **/ public $tradeOrderInfoCols; } ?>
bsd-3-clause
synesissoftware/recls
src/impl.entryinfo.cpp
27023
/* ///////////////////////////////////////////////////////////////////////// * File: impl.entryinfo.cpp * * Purpose: Implementation of the create_entryinfo() function. * * Created: 31st May 2004 * Updated: 24th January 2017 * * Home: http://recls.org/ * * Copyright (c) 2004-2017, Matthew Wilson and Synesis Software * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * - Neither the name(s) of Matthew Wilson and Synesis Software nor the * names of any 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. * * ////////////////////////////////////////////////////////////////////// */ /* ///////////////////////////////////////////////////////////////////////// * includes */ #include <recls/recls.h> #include <recls/assert.h> #include "impl.root.h" #include "incl.stlsoft.h" #ifdef RECLS_STLSOFT_1_12_OR_LATER # include <stlsoft/synch/util/concepts.hpp> #else /* ? STLSoft 1.12+ */ # include <stlsoft/synch/concepts.hpp> // Required to workaround VC++ 6 ICE #endif /* STLSoft 1.12+ */ #include "impl.types.hpp" #include "impl.util.h" #include "impl.entryinfo.hpp" #include "impl.entryfunctions.h" #include "impl.cover.h" #include "impl.trace.h" #if defined(RECLS_CHAR_TYPE_IS_WCHAR) # if defined(RECLS_PLATFORM_IS_WINDOWS) # include <winstl/conversion/char_conversions.hpp> # endif /* RECLS_PLATFORM_IS_WINDOWS */ #endif /* RECLS_CHAR_TYPE_IS_???? */ #include <stlsoft/shims/conversion/to_uint64.hpp> #if defined(RECLS_PLATFORM_IS_UNIX) # include <unixstl/shims/conversion/to_uint64/stat.hpp> #elif defined(RECLS_PLATFORM_IS_WINDOWS) # include <winstl/shims/conversion/to_uint64/WIN32_FIND_DATA.hpp> #endif /* OS */ #if ( _STLSOFT_VER >= 0x010a0000 || \ ( defined(_STLSOFT_1_10_VER) && \ _STLSOFT_1_10_VER >= 0x010a0110)) && \ defined(_WIN32) # define RECLS_USE_WINSTL_LINK_FUNCTIONS_ # include <winstl/filesystem/link_functions.h> #else /* ? OS */ # ifdef RECLS_USE_WINSTL_LINK_FUNCTIONS_ # undef RECLS_USE_WINSTL_LINK_FUNCTIONS_ # endif /*RECLS_USE_WINSTL_LINK_FUNCTIONS_*/ #endif /* OS */ /* ///////////////////////////////////////////////////////////////////////// * namespace */ #if !defined(RECLS_NO_NAMESPACE) namespace recls { namespace impl { #endif /* !RECLS_NO_NAMESPACE */ /* ///////////////////////////////////////////////////////////////////////// * coverage */ RECLS_ASSOCIATE_FILE_WITH_CORE_GROUP() RECLS_ASSOCIATE_FILE_WITH_GROUP("recls.core.search") RECLS_MARK_FILE_START() /* ///////////////////////////////////////////////////////////////////////// * utility functions */ recls_entry_t create_entryinfo( size_t rootDirLen , recls_char_t const* searchDir , size_t searchDirLen , recls_char_t const* entryPath , size_t entryPathLen , recls_char_t const* entryFile , size_t entryFileLen , recls_uint32_t flags , types::stat_data_type const* st ) { function_scope_trace("create_entryinfo"); const int bSearchDirOverlap = 0 == types::traits_type::str_n_compare(searchDir, entryPath, searchDirLen); STLSOFT_SUPPRESS_UNUSED(searchDir); STLSOFT_SUPPRESS_UNUSED(entryFile); RECLS_MESSAGE_ASSERT("Directory length cannot be 0", 0 != searchDirLen); RECLS_MESSAGE_ASSERT("Path length cannot be 0", 0 != entryPathLen); RECLS_MESSAGE_ASSERT("File length cannot be 0", 0 != entryFileLen); RECLS_MESSAGE_ASSERT("Invalid directory length", searchDirLen <= types::traits_type::str_len(searchDir)); RECLS_MESSAGE_ASSERT("Invalid path length", entryPathLen == types::traits_type::str_len(entryPath)); RECLS_MESSAGE_ASSERT("Invalid file length", entryFileLen == types::traits_type::str_len(entryFile)); RECLS_ASSERT(!bSearchDirOverlap || searchDirLen < entryPathLen); RECLS_ASSERT(!bSearchDirOverlap || searchDirLen + entryFileLen <= entryPathLen); RECLS_ASSERT(!bSearchDirOverlap || 0 == types::traits_type::str_n_compare(searchDir, entryPath, searchDirLen)); RECLS_ASSERT(0 == types::traits_type::str_n_compare(entryFile, entryPath + (entryPathLen - entryFileLen), entryFileLen)); RECLS_ASSERT(searchDir[searchDirLen - 1] == types::traits_type::path_name_separator()); RECLS_ASSERT(types::traits_type::str_rchr(entryPath, types::traits_type::path_name_separator()) + 1 == entryPath + (entryPathLen - entryFileLen)); RECLS_COVER_MARK_LINE(); // size of structure is: // // offsetof(struct recls_entryinfo_t, data) // + directory parts // + full path (+ null) // + short name (+ null) // + 1 in case we need to MARK_DIRS // [+ 1 + searchDirLen if searchDir and entryPath do not overlap] recls_char_t const* const dir0 = recls_find_directory_0_(entryPath); recls_char_t const* const end = entryPath + (entryPathLen - entryFileLen); const size_t cchFileName = entryFileLen; const size_t cDirParts = (RECLS_F_DIRECTORY_PARTS == (flags & RECLS_F_DIRECTORY_PARTS)) ? types::count_dir_parts(dir0, end) : 0; const size_t cbPath = recls_align_up_size_(sizeof(recls_char_t) * (1 + entryPathLen)); #if defined(RECLS_PLATFORM_IS_UNIX) const size_t cbAlt = 0; // UNIX doesn't have alt paths #elif defined(RECLS_PLATFORM_IS_WINDOWS) const size_t cbAlt = recls_align_up_size_(sizeof(recls_char_t) * (1 + RECLS_NUM_ELEMENTS(st->cAlternateFileName))); #else /* ? platform */ # error Platform not discriminated #endif /* platform */ const size_t cb = offsetof(struct recls_entryinfo_t, data) + cDirParts * sizeof(recls_strptrs_t) + cbPath + cbAlt + 1 // In case we need to expand for MARK_DIRS + (bSearchDirOverlap ? 0 : (1 + searchDirLen + 1)) ; struct recls_entryinfo_t* info = const_cast<struct recls_entryinfo_t*>(Entry_Allocate(cb)); if(NULL != info) { RECLS_COVER_MARK_LINE(); recls_byte_t* const pData = &info->data[0]; recls_byte_t* const pParts = pData + 0; recls_byte_t* const pPath = pParts + (cDirParts * sizeof(recls_strptrs_t)); #if defined(RECLS_PLATFORM_IS_WINDOWS) recls_byte_t* const pAltName = pPath + cbPath; #endif /* platform */ recls_byte_t* const pSearchCopy = pPath + cbPath + cbAlt; recls_char_t* fullPath = ::stlsoft::sap_cast<recls_char_t*>(pPath); #if defined(RECLS_PLATFORM_IS_WINDOWS) recls_char_t* altName = ::stlsoft::sap_cast<recls_char_t*>(pAltName); #endif /* platform */ RECLS_ASSERT(::stlsoft::sap_cast<recls_char_t*>(pData + (cDirParts * sizeof(recls_strptrs_t))) == fullPath); #if defined(RECLS_PLATFORM_IS_WINDOWS) RECLS_ASSERT(::stlsoft::sap_cast<recls_char_t*>(pData + (cDirParts * sizeof(recls_strptrs_t) + cbPath)) == altName); #endif /* platform */ info->checkSum = 0; info->extendedFlags[0] = 0; info->extendedFlags[1] = 0; // full path types::traits_type::char_copy(&fullPath[0], entryPath, entryPathLen + 1); info->path.begin = fullPath; info->path.end = fullPath + entryPathLen; // search-relative path if(bSearchDirOverlap) { RECLS_COVER_MARK_LINE(); info->searchRelativePath.begin = info->path.begin + rootDirLen; info->searchRelativePath.end = info->path.end; } else { RECLS_COVER_MARK_LINE(); info->searchRelativePath.begin = info->path.begin; info->searchRelativePath.end = info->path.end; } // Number of relative directory parts info->numRelativeDirectoryParts = (RECLS_F_DIRECTORY_PARTS == (flags & RECLS_F_DIRECTORY_PARTS)) ? types::count_dir_parts(info->searchRelativePath.begin, info->searchRelativePath.end) : 0; // Number of (hard) links; node index & device Id if( 0 != ((RECLS_F_LINK_COUNT|RECLS_F_NODE_INDEX) & flags) && NULL != st) { recls_log_printf_(RECLS_SEVIX_DBG1, RECLS_LITERAL("looking up additional attributes; flags=0x%08x"), flags); #if defined(RECLS_PLATFORM_IS_WINDOWS) || \ defined(RECLS_PLATFORM_IS_UNIX_EMULATED_ON_WINDOWS) info->numLinks = 0; info->nodeIndex = 0; info->deviceId = 0; # ifdef RECLS_USE_WINSTL_LINK_FUNCTIONS_ DWORD fileIndexHigh; DWORD fileIndexLow; DWORD deviceId; DWORD numLinks; if(winstl::hard_link_get_link_information( entryPath , &fileIndexHigh , &fileIndexLow , &deviceId , &numLinks )) { if(RECLS_F_LINK_COUNT & flags) { info->numLinks = numLinks; } if(RECLS_F_NODE_INDEX & flags) { info->nodeIndex = recls_uint64_t(fileIndexHigh) << 32 | fileIndexLow; info->deviceId = deviceId; } } # else /*? RECLS_USE_WINSTL_LINK_FUNCTIONS_*/ HANDLE hFile = ::CreateFile(entryPath, 0, 0, NULL, OPEN_EXISTING, 0, NULL); if(INVALID_HANDLE_VALUE != hFile) { BY_HANDLE_FILE_INFORMATION bhfi; if(::GetFileInformationByHandle(hFile, &bhfi)) { if(RECLS_F_LINK_COUNT & flags) { info->numLinks = bhfi.nNumberOfLinks; } if(RECLS_F_NODE_INDEX & flags) { info->nodeIndex = recls_uint64_t(bhfi.nFileIndexHigh) << 32 | bhfi.nFileIndexLow; info->deviceId = bhfi.dwVolumeSerialNumber; } } ::CloseHandle(hFile); } # endif /*RECLS_USE_WINSTL_LINK_FUNCTIONS_*/ #else /* ? OS */ if(RECLS_F_LINK_COUNT & flags) { RECLS_ASSERT(NULL != st); info->numLinks = st->st_nlink; } if(RECLS_F_NODE_INDEX & flags) { RECLS_ASSERT(NULL != st); info->nodeIndex = st->st_ino; info->deviceId = st->st_dev; } #endif /* OS */ } else { info->numLinks = 0; info->nodeIndex = 0; info->deviceId = 0; } // drive, directory, file (name + ext) #if defined(RECLS_PLATFORM_IS_UNIX) info->directory.begin = &fullPath[dir0 - entryPath]; #elif defined(RECLS_PLATFORM_IS_WINDOWS) info->drive = ('\\' == fullPath[0]) ? '\0' : fullPath[0]; info->directory.begin = &fullPath[dir0 - entryPath]; #else /* ? platform */ # error Platform not discriminated #endif /* platform */ info->directory.end = fullPath + (entryPathLen - entryFileLen); info->fileName.begin = info->directory.end; info->fileName.end = types::traits_type::str_rchr(info->directory.end, RECLS_LITERAL('.')); if(NULL != info->fileName.end) { RECLS_COVER_MARK_LINE(); info->fileExt.begin = info->fileName.end + 1; info->fileExt.end = info->directory.end + cchFileName; } else { RECLS_COVER_MARK_LINE(); info->fileName.end = info->directory.end + cchFileName; info->fileExt.begin = info->directory.end + cchFileName; info->fileExt.end = info->directory.end + cchFileName; } // determine the directory parts recls_char_t const* p = info->directory.begin; recls_char_t const* l = info->directory.end; struct recls_strptrs_t* begin = ::stlsoft::sap_cast<struct recls_strptrs_t*>(&info->data[0]); info->directoryParts.begin = begin; info->directoryParts.end = begin + cDirParts; if(bSearchDirOverlap) { RECLS_COVER_MARK_LINE(); info->searchDirectory.begin = info->path.begin; info->searchDirectory.end = info->searchDirectory.begin + rootDirLen; } else { RECLS_COVER_MARK_LINE(); recls_char_t* searchCopy = ::stlsoft::sap_cast<recls_char_t*>(pSearchCopy); info->searchDirectory.begin = searchCopy; info->searchDirectory.end = info->searchDirectory.begin + searchDirLen; types::traits_type::char_copy(searchCopy, searchDir, searchDirLen); searchCopy[searchDirLen] = '\0'; } if(info->directoryParts.begin != info->directoryParts.end) { RECLS_ASSERT((flags & RECLS_F_DIRECTORY_PARTS) == RECLS_F_DIRECTORY_PARTS); RECLS_COVER_MARK_LINE(); begin->begin = p; for(; p != l; ++p) { RECLS_COVER_MARK_LINE(); if(*p == types::traits_type::path_name_separator()) { RECLS_COVER_MARK_LINE(); begin->end = p + 1; if(++begin != info->directoryParts.end) { RECLS_COVER_MARK_LINE(); begin->begin = p + 1; } } } } if(NULL == st) { RECLS_COVER_MARK_LINE(); recls_time_t no_time; recls_filesize_t no_size; memset(&no_time, 0, sizeof(no_time)); memset(&no_size, 0, sizeof(no_size)); // alt name #if defined(RECLS_PLATFORM_IS_WINDOWS) altName[0] = '\0'; info->shortFile.begin = altName; info->shortFile.end = altName; #endif /* platform */ // attributes info->attributes = 0; // time, size #if defined(RECLS_PLATFORM_IS_UNIX) info->lastStatusChangeTime = no_time; #elif defined(RECLS_PLATFORM_IS_WINDOWS) info->creationTime = no_time; #else /* ? platform */ # error Platform not discriminated #endif /* platform */ info->modificationTime = no_time; info->lastAccessTime = no_time; info->size = no_size; } else { RECLS_COVER_MARK_LINE(); RECLS_ASSERT(NULL != st); // alt name #if defined(RECLS_PLATFORM_IS_WINDOWS) size_t altLen = types::traits_type::str_len(st->cAlternateFileName); types::traits_type::char_copy(altName, st->cAlternateFileName, altLen); altName[altLen] = '\0'; info->shortFile.begin = altName; info->shortFile.end = altName + altLen; #endif /* platform */ // attributes #if defined(RECLS_PLATFORM_IS_UNIX) info->attributes = st->st_mode; #elif defined(RECLS_PLATFORM_IS_WINDOWS) info->attributes = st->dwFileAttributes; #else /* ? platform */ # error Platform not discriminated #endif /* platform */ // time, size #if defined(RECLS_PLATFORM_IS_UNIX) info->lastStatusChangeTime = st->st_ctime; info->modificationTime = st->st_mtime; info->lastAccessTime = st->st_atime; info->size = stlsoft::to_uint64(*st); #elif defined(RECLS_PLATFORM_IS_WINDOWS) info->creationTime = st->ftCreationTime; info->modificationTime = st->ftLastWriteTime; info->lastAccessTime = st->ftLastAccessTime; info->size = stlsoft::to_uint64(*st); #else /* ? platform */ # error Platform not discriminated #endif /* platform */ // Handle MARK_DIRS if( RECLS_F_MARK_DIRS == (flags & RECLS_F_MARK_DIRS) && types::traits_type::is_directory(st)) { RECLS_COVER_MARK_LINE(); *const_cast<recls_char_t*>(info->path.end) = types::traits_type::path_name_separator(); ++info->path.end; *const_cast<recls_char_t*>(info->path.end) = '\0'; } } // Checks RECLS_ASSERT(info->path.begin < info->path.end); RECLS_ASSERT(info->directory.begin < info->directory.end); RECLS_ASSERT(info->path.begin <= info->directory.begin); RECLS_ASSERT(info->directory.end <= info->path.end); RECLS_ASSERT(info->fileName.begin <= info->fileName.end); RECLS_ASSERT(info->fileExt.begin <= info->fileExt.end); RECLS_ASSERT(info->fileName.begin < info->fileExt.end); RECLS_ASSERT(info->fileName.end <= info->fileExt.begin); } return info; } recls_entry_t create_drive_entryinfo( recls_char_t const* entryPath , size_t entryPathLen , recls_uint32_t flags , types::stat_data_type const* st ) { RECLS_COVER_MARK_LINE(); #if 0 return create_entryinfo(0, NULL, 0, entryPath, entryPathLen, NULL, 0, flags, st); #else /* ? 0 */ /* const */ size_t cDirParts = 0; // This is declared non-const to placate Borland C/C++ const size_t cbPath = recls_align_up_size_(sizeof(recls_char_t) * (1 + entryPathLen)); const size_t cb = offsetof(struct recls_entryinfo_t, data) + cbPath + 1 // In case we need to expand for MARK_DIRS ; struct recls_entryinfo_t* info = const_cast<struct recls_entryinfo_t*>(Entry_Allocate(cb)); if(NULL != info) { RECLS_COVER_MARK_LINE(); recls_byte_t* const pData = &info->data[0]; recls_byte_t* const pParts = pData + 0; recls_byte_t* const pPath = pParts + (cDirParts * sizeof(recls_strptrs_t)); recls_char_t* fullPath = ::stlsoft::sap_cast<recls_char_t*>(pPath); RECLS_ASSERT(::stlsoft::sap_cast<recls_char_t*>(pData + (cDirParts * sizeof(recls_strptrs_t))) == fullPath); info->checkSum = 0; info->extendedFlags[0] = 0; info->extendedFlags[1] = 0; // full path types::traits_type::char_copy(&fullPath[0], entryPath, entryPathLen); fullPath[entryPathLen] = '\0'; info->path.begin = fullPath; info->path.end = fullPath + entryPathLen; // search-relative path info->searchRelativePath.begin = info->path.begin; info->searchRelativePath.end = info->path.end; // Number of relative directory parts info->numRelativeDirectoryParts = 0; // Number of (hard) links #if defined(RECLS_PLATFORM_IS_UNIX) if( 0 != (RECLS_F_LINK_COUNT & flags) && NULL != st) { RECLS_ASSERT(NULL != st); info->numLinks = st->st_nlink; } else #else /* ? OS */ { info->numLinks = 0; } #endif /* OS */ // node index and device Id #if defined(RECLS_PLATFORM_IS_UNIX) if( 0 != (RECLS_F_NODE_INDEX & flags) && NULL != st) { RECLS_ASSERT(NULL != st); info->nodeIndex = st->st_ino; info->deviceId = st->st_dev; } else #else /* ? OS */ { info->nodeIndex = 0; info->deviceId = 0; } #endif /* OS */ // drive, directory, file (name + ext) info->directory.begin = info->path.end; #if defined(RECLS_PLATFORM_IS_WINDOWS) info->drive = ('\\' == fullPath[0]) ? '\0' : fullPath[0]; #elif defined(RECLS_PLATFORM_IS_UNIX) #else /* ? platform */ # error Platform not discriminated #endif /* platform */ info->directory.begin = info->path.end; info->directory.end = info->path.end; info->fileName.begin = info->path.end; info->fileName.end = info->path.end; info->fileExt.begin = info->path.end; info->fileExt.end = info->path.end; // determine the directory parts info->directoryParts.begin = NULL; info->directoryParts.end = NULL; info->searchDirectory.begin = info->path.end; info->searchDirectory.end = info->path.end; if(NULL == st) { RECLS_COVER_MARK_LINE(); recls_time_t no_time; recls_filesize_t no_size; memset(&no_time, 0, sizeof(no_time)); memset(&no_size, 0, sizeof(no_size)); // alt name #if defined(RECLS_PLATFORM_IS_WINDOWS) info->shortFile.begin = info->path.end; info->shortFile.end = info->path.end; #endif /* platform */ // attributes #if defined(RECLS_PLATFORM_IS_UNIX) info->attributes = S_IFDIR; #elif defined(RECLS_PLATFORM_IS_WINDOWS) info->attributes = FILE_ATTRIBUTE_DIRECTORY; #else /* ? platform */ # error Platform not discriminated #endif /* platform */ // time, size #if defined(RECLS_PLATFORM_IS_UNIX) info->lastStatusChangeTime = no_time; #elif defined(RECLS_PLATFORM_IS_WINDOWS) info->creationTime = no_time; #else /* ? platform */ # error Platform not discriminated #endif /* platform */ info->modificationTime = no_time; info->lastAccessTime = no_time; info->size = no_size; } else { RECLS_COVER_MARK_LINE(); // alt name #if defined(RECLS_PLATFORM_IS_WINDOWS) info->shortFile.begin = info->path.begin; info->shortFile.end = info->path.end; #endif /* platform */ // attributes #if defined(RECLS_PLATFORM_IS_UNIX) info->attributes = st->st_mode; #elif defined(RECLS_PLATFORM_IS_WINDOWS) info->attributes = st->dwFileAttributes; #else /* ? platform */ # error Platform not discriminated #endif /* platform */ // time, size #if defined(RECLS_PLATFORM_IS_UNIX) info->lastStatusChangeTime = st->st_ctime; info->modificationTime = st->st_mtime; info->lastAccessTime = st->st_atime; info->size = stlsoft::to_uint64(*st); #elif defined(RECLS_PLATFORM_IS_WINDOWS) info->creationTime = st->ftCreationTime; info->modificationTime = st->ftLastWriteTime; info->lastAccessTime = st->ftLastAccessTime; info->size = stlsoft::to_uint64(*st); #else /* ? platform */ # error Platform not discriminated #endif /* platform */ // Handle MARK_DIRS if( RECLS_F_MARK_DIRS == (flags & RECLS_F_MARK_DIRS) && types::traits_type::is_directory(st)) { RECLS_COVER_MARK_LINE(); *const_cast<recls_char_t*>(info->path.end) = types::traits_type::path_name_separator(); ++info->path.end; *const_cast<recls_char_t*>(info->path.end) = '\0'; } } // Checks RECLS_ASSERT(info->path.begin < info->path.end); RECLS_ASSERT(info->directory.begin == info->directory.end); RECLS_ASSERT(info->path.begin < info->directory.begin); RECLS_ASSERT(info->directory.end == info->path.end); RECLS_ASSERT(info->fileName.begin == info->fileName.end); RECLS_ASSERT(info->fileExt.begin == info->fileExt.end); RECLS_ASSERT(info->fileName.begin == info->fileExt.end); RECLS_ASSERT(info->fileName.end == info->fileExt.begin); } return info; #endif /* 0 */ } /* ///////////////////////////////////////////////////////////////////////// * coverage */ RECLS_MARK_FILE_END() /* ///////////////////////////////////////////////////////////////////////// * namespace */ #if !defined(RECLS_NO_NAMESPACE) } /* namespace impl */ } /* namespace recls */ #endif /* !RECLS_NO_NAMESPACE */ /* ///////////////////////////// end of file //////////////////////////// */
bsd-3-clause
godaddy/spree_madmimi
spec/services/mad_mimi_spec.rb
13043
require 'spec_helper' describe MadMimi do subject { MadMimi } before(:each) do @originals = [:access_token, :refresh_token, :webform_id].inject({}) do |hash, attribute| hash.tap do |h| h[attribute] = ::Spree::MadMimi::Config[attribute] ::Spree::MadMimi::Config[attribute] = '' end end end after(:each) do @originals.each_pair do |attribute, value| ::Spree::MadMimi::Config[attribute] = value end end let(:sample_access_token) { 'fef30b33104f976f842d6c06da8c34afedd7c6089d872d41857a76d411b6266e' } let(:sample_refresh_token) { '81cfd40cbfa3a246e84198892a6e0792d4393afaef7e035da54054f7f8e121cd' } let(:sample_api_key) { 'fa7521dbbdbe80a3107ab96890b1485a968e2b736e316ac8' } let(:sample_store_url) { 'http://localhost:4000' } let(:sample_webform_id) { 29 } let(:sample_connect_params) do { access_token: sample_access_token, refresh_token: sample_refresh_token, store_url: sample_store_url } end let(:sample_activate_addon_params) do { body: { access_token: sample_access_token, api_key: sample_api_key, store_url: sample_store_url } } end let(:sample_deactivate_addon_params) do { body: { access_token: sample_access_token } } end let(:sample_fetch_webforms_params) do sample_deactivate_addon_params end let(:sample_fetch_webform_params) do sample_fetch_webforms_params end let!(:user) { create(:admin_user, spree_api_key: sample_api_key) } context 'when MadMimi API works' do use_vcr_cassette "mad_mimi/success", record: :new_episodes context '.access_token' do it "reads from config" do ::Spree::MadMimi::Config[:access_token] = sample_access_token subject.access_token.should eq(sample_access_token) end end context '.access_token=' do it "assigns to config" do expect { subject.access_token = sample_access_token } .to change{ ::Spree::MadMimi::Config[:access_token] } .from('') .to(sample_access_token) end end context '.refresh_token' do it "reads from config" do ::Spree::MadMimi::Config[:refresh_token] = sample_refresh_token subject.refresh_token.should eq(sample_refresh_token) end end context '.refresh_token=' do it "assigns to config" do expect { subject.refresh_token = sample_refresh_token } .to change{ ::Spree::MadMimi::Config[:refresh_token] } .from('') .to(sample_refresh_token) end end context '.webform_id' do it "reads from config" do ::Spree::MadMimi::Config[:webform_id] = sample_webform_id subject.webform_id.should eq(sample_webform_id) end end context '.webform_id=' do it "assigns to config" do expect { subject.webform_id = sample_webform_id } .to change{ ::Spree::MadMimi::Config[:webform_id] } .from(0) .to(sample_webform_id) end end context '.webform_visible?' do it "returns true if .webform_id is not zero" do subject.webform_id = 3 subject.webform_visible?.should be_truthy end it "returns false if .webform_id is zero" do subject.webform_id = 0 subject.webform_visible?.should be_falsy end end context '.connect' do it "should be successful" do subject.connect(user, sample_connect_params).should be_successful end it "assigns config values" do MadMimi.access_token.should be_empty MadMimi.refresh_token.should be_empty subject.connect(user, sample_connect_params) MadMimi.access_token.should eq(sample_access_token) MadMimi.refresh_token.should eq(sample_refresh_token) end it "activates addon" do MadMimi.any_instance.should_receive(:activate_addon).with(user, sample_store_url) subject.connect(user, sample_connect_params) end end context '.disconnect' do it "should be successful" do subject.disconnect.should be_successful end it "clears config values" do MadMimi.access_token = sample_access_token MadMimi.refresh_token = sample_refresh_token subject.disconnect MadMimi.access_token.should be_empty MadMimi.refresh_token.should be_empty end it "deactivates addon" do MadMimi.any_instance.should_receive(:deactivate_addon) subject.disconnect end end context '.activate_addon' do before(:each) do MadMimi.access_token = sample_access_token MadMimi.refresh_token = sample_refresh_token end it "should be successful" do subject.activate_addon(user, sample_store_url).should be_successful end it "makes a post request to MadMimi API" do user.spree_api_key = sample_api_key MadMimi.should_receive(:post).with( "/spree/activate", sample_activate_addon_params ).and_call_original subject.activate_addon(user, sample_store_url) end end context '.deactivate_addon' do before(:each) do MadMimi.access_token = sample_access_token MadMimi.refresh_token = sample_refresh_token end it "should be successful" do result = subject.deactivate_addon result.should be_successful end it "makes a post request to MadMimi API" do MadMimi.any_instance.stub(:valid? => true) MadMimi.should_receive(:post).with( "/spree/deactivate", sample_deactivate_addon_params ).and_call_original subject.deactivate_addon end end context '.fetch_webforms' do before(:each) do MadMimi.access_token = sample_access_token MadMimi.refresh_token = sample_refresh_token end it "should be successful" do result = subject.fetch_webforms result.should be_successful end it "makes a get request to MadMimi API" do MadMimi.any_instance.stub(:valid? => true) MadMimi.should_receive(:get).with( "/apiv2/signups", sample_fetch_webforms_params ).and_call_original subject.fetch_webforms end it "populates webforms attribute" do subject.fetch_webforms.tap do |result| result.webforms.should be_present end end end context '.webforms' do before(:each) do MadMimi.access_token = sample_access_token MadMimi.refresh_token = sample_refresh_token end it "should not be empty" do subject.webforms.should be_present end end context '.fetch_webform' do before(:each) do MadMimi.access_token = sample_access_token MadMimi.refresh_token = sample_refresh_token end it "should be successful" do result = subject.fetch_webform(sample_webform_id) result.should be_successful end it "makes a get request to MadMimi API" do MadMimi.any_instance.stub(:valid? => true) MadMimi.should_receive(:get).with( "/apiv2/signups/#{ sample_webform_id }", sample_fetch_webform_params ).and_call_original subject.fetch_webform(sample_webform_id) end it "populates webforms attribute" do subject.fetch_webform(sample_webform_id).tap do |result| result.webform.should be_present end end end context '.webform' do before(:each) do MadMimi.access_token = sample_access_token MadMimi.refresh_token = sample_refresh_token end it "should not be empty" do subject.webform(sample_webform_id).should be_present end it "should use webform_id from config if nothing specified" do MadMimi.webform_id = sample_webform_id subject.webform.should be_present subject.webform.id.should eq(sample_webform_id) end end context '.connected?' do it "returns true if both access_token and refresh_token are present" do MadMimi.access_token = sample_access_token MadMimi.refresh_token = sample_refresh_token subject.connected?.should be_truthy end it "returns false if only access_token is present" do MadMimi.access_token = sample_access_token subject.connected?.should be_falsy end it "returns false if only refresh_token is present" do MadMimi.refresh_token = sample_refresh_token subject.connected?.should be_falsy end it "returns false if both access_token and refresh_token are empty" do subject.connected?.should be_falsy end end context '.validate' do it "should be successful if valid" do MadMimi.any_instance.stub(:valid? => true) subject.validate.should be_successful end it "should be successful if not valid but successfully refreshed access token" do MadMimi.access_token = sample_access_token MadMimi.refresh_token = sample_refresh_token MadMimi.any_instance.stub(:valid? => false) subject.validate.should be_successful end it "does not update tokens if valid" do MadMimi.any_instance.stub(:valid? => true) MadMimi.access_token = sample_access_token MadMimi.refresh_token = sample_refresh_token subject.validate MadMimi.access_token.should eq(sample_access_token) MadMimi.refresh_token.should eq(sample_refresh_token) end it "updates tokens if not valid" do MadMimi.any_instance.stub(:valid? => false) MadMimi.any_instance.stub(:refresh_access_token => true) MadMimi.any_instance.stub(:response => { 'access_token' => 'TEST_ACCESS_TOKEN', 'refresh_token' => 'TEST_REFRESH_TOKEN' }) subject.validate MadMimi.access_token.should eq('TEST_ACCESS_TOKEN') MadMimi.refresh_token.should eq('TEST_REFRESH_TOKEN') end end end shared_examples "failing MadMimi API calls" do context '.connect' do it "should not be successful" do subject.connect(user, sample_connect_params).should_not be_successful end it "holds an error message" do subject.connect(user, sample_connect_params).tap do |result| result.errors.should_not be_empty end end end context '.disconnect' do it "should not be successful" do subject.disconnect.should_not be_successful end it "holds an error message" do subject.disconnect.tap do |result| result.errors.should_not be_empty end end end context '.activate_addon' do it "should not be successful" do subject.activate_addon(user, sample_store_url).should_not be_successful end it "holds an error message" do subject.activate_addon(user, sample_store_url).tap do |result| result.errors.should_not be_empty end end end context '.deactivate_addon' do it "should not be successful" do subject.deactivate_addon.should_not be_successful end it "holds an error message" do subject.deactivate_addon.tap do |result| result.errors.should_not be_empty end end end context '.fetch_webforms' do it "should not be successful" do subject.fetch_webforms.should_not be_successful end it "holds an error message" do subject.fetch_webforms.tap do |result| result.errors.should_not be_empty end end end context '.webforms' do it "should be empty" do subject.webforms.should be_blank end end context '.fetch_webform' do it "should not be successful" do subject.fetch_webform(sample_webform_id).should_not be_successful end it "holds an error message" do subject.fetch_webform(sample_webform_id).tap do |result| result.errors.should_not be_empty end end end context '.webform' do it "should be empty" do subject.webform(sample_webform_id).should be_blank end end context '.validate' do it "should not be successful if not valid and unsuccessfully refreshed access tokens" do MadMimi.any_instance.stub(:valid? => false) subject.validate.should_not be_successful end end end context "when MadMimi API fails" do use_vcr_cassette "mad_mimi/failure", record: :new_episodes include_examples "failing MadMimi API calls" end context "when no connection" do before(:each) do MadMimi.stub(:get).and_raise Errno::EHOSTUNREACH MadMimi.stub(:post).and_raise Errno::EHOSTUNREACH end include_examples "failing MadMimi API calls" end end
bsd-3-clause
lciolecki/webshot
application/models/Entity/Service.php
5810
<?php namespace Entity; use Doctrine\ORM\Mapping as ORM; /** * Service * * @ORM\Table(name="service", * uniqueConstraints={ * @ORM\UniqueConstraint(name="UNIQUE_name", columns={"name"}), * @ORM\UniqueConstraint(name="UNIQUE_hash", columns={"hash"}), * @ORM\UniqueConstraint(name="UNIQUE_secret_key", columns={"secret_key"}) * } * ) * @ORM\Entity(repositoryClass="Repository\Service") * @ORM\HasLifecycleCallbacks */ class Service extends \Entity\AbstractEntity { const HASH_LEN = 32; const SECRET_KEY_LEN = 16; /** * @var string * * @ORM\Column(name="name", type="string", length=255, nullable=false) */ private $name; /** * @var string * * @ORM\Column(name="hash", type="string", length=32, nullable=false) */ private $hash; /** * @var string * * @ORM\Column(name="secret_key", type="string", length=16, nullable=false) */ private $secretKey; /** * @var \Zend_Date * * @ORM\Column(name="date_create", type="zenddate", nullable=false) */ private $dateCreate; /** * @var integer * * @ORM\Column(name="webshots_per_day", type="integer", nullable=false) */ private $webshotsPerDay = 0; /** * @var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $id; /** * @var \Entity\Users * * @ORM\ManyToOne(targetEntity="Entity\User") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="create_user_id", referencedColumnName="id") * }) */ private $createUser; /** * Lista screenshotow wykonanych dla aplikacji * * @ORM\OneToMany(targetEntity="Entity\Webshot", mappedBy="service", orphanRemoval=true, cascade={"all"}) * @ORM\OrderBy({"id" = "ASC"}) * @var \Doctrine\Common\Collections\ArrayCollection */ private $webshots; /** * Instancja konstruktora * * @param array $data */ public function __construct(array $data = array()) { $this->webshots = new \Doctrine\Common\Collections\ArrayCollection(); parent::__construct($data); } /** * @ORM\PrePersist */ public function preInsert() { $this->dateCreate = new \Zend_Date(); $this->hash = \Extlib\Generator::generateDoctrine2($this->getEm(), get_class($this), 'hash', self::HASH_LEN); $this->secretKey = \Extlib\Generator::generateDoctrine2($this->getEm(), get_class($this), 'secretKey', self::SECRET_KEY_LEN); } /** * Set name * * @param string $name * @return Service */ public function setName($name) { $this->name = $name; return $this; } /** * Get name * * @return string */ public function getName() { return $this->name; } /** * Set hash * * @param string $hash * @return Service */ public function setHash($hash) { $this->hash = $hash; return $this; } /** * Get hash * * @return string */ public function getHash() { return $this->hash; } /** * Set secretKey * * @param string $secretKey * @return Service */ public function setSecretKey($secretKey) { $this->secretKey = $secretKey; return $this; } /** * Get secretKey * * @return string */ public function getSecretKey() { return $this->secretKey; } /** * Set dateCreate * * @param \Zend_Date $dateCreate * @return Service */ public function setDateCreate(\Zend_Date $dateCreate) { $this->dateCreate = $dateCreate; return $this; } /** * Get dateCreate * * @return \Zend_Date */ public function getDateCreate() { return $this->dateCreate; } /** * Set webshotsPerDay * * @param integer $webshotsPerDay * @return Service */ public function setWebshotsPerDay($webshotsPerDay) { $this->webshotsPerDay = (int) $webshotsPerDay; return $this; } /** * Get webshotsPerDay * * @return integer */ public function getWebshotsPerDay() { return $this->webshotsPerDay; } /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set createUser * * @param \Entity\User $createUser * @return Service */ public function setCreateUser(\Entity\User $createUser = null) { $this->createUser = $createUser; return $this; } /** * Get createUser * * @return \Entity\Users */ public function getCreateUser() { return $this->createUser; } /** * Metoda dodajaca webshot do aplikacji * * @param \Entity\Webshot $webshot * @return \Entity\Service */ public function addWebshot(\Entity\Webshot $webshot) { if (!$this->webshots->contains($webshot)) { $this->webshots->add($webshot); $webshot->setService($this); } return $this; } /** * Metoda usuwajaca webshot z aplikacji * * @param \Entity\Webshot $webshot * @return \Entity\Service */ public function removeWebshot(\Entity\Webshot $webshot) { if ($this->webshots->contains($webshot)) { $this->webshots->removeElement($webshot); $webshot->setService(null); } return $this; } }
bsd-3-clause
hurduring/smolyakoff
backend/views/address/address-widget/createMicroDistrictModal.php
527
<?php use yii\helpers\Html; /* @var $this yii\web\View */ /* @var $model common\models\address\MicroDistrict */ $this->title = Yii::t('app', 'Создать Микрорайон', [ 'modelClass' => 'MicroDistrict', ]); ?> <div class="microdistrict-create"> <h2><?= Html::encode($this->title) ?></h2> <?= $this->render('_formMicroDistrictModal', [ 'model' => $model, ]) ?> </div> <?php $js = <<<JS submitform('microdistrictForm'); JS; $this->registerJs($js); ?>
bsd-3-clause
wenlongzhou/blog
protected/modules/admin/views/article/add.php
5514
<head> <link rel="stylesheet" href="<?php echo yii::app()->request->baseUrl;?>/assets/editor/css/editormd.css" /> </head> <br/> <div class="panel panel-default"> <div class="panel-heading"> <a href='<?php echo $this->createUrl('article/index') ?>' style="color:#666">返回列表</a> </div> <div class="panel-body"> <?php $form = $this->beginwidget('CActiveForm') ?> <div class="form-group"> <div class="row"> <div class="col-lg-2 col-md-3 col-sm-3" align="right" style="line-height:34px"> <?php echo $form->labelEX($model, 'title'); ?> </div> <div class="col-lg-6 col-md-7 col-sm-7"> <?php echo $form->textField($model, 'title', array('class' => 'form-control')); ?> </div> <div class="col-lg-2 col-md-2 col-sm-2" style="color:orangered;font-size: 0.8rem;line-height:34px"> <?php echo $form->error($model, 'title'); ?> </div> </div> </div> <div class="form-group"> <div class="row"> <div class="col-lg-2 col-md-3 col-sm-3" align="right" style="line-height:34px"> <?php echo $form->labelEX($model, 'tag_id'); ?> </div> <div class="col-lg-6 col-md-7 col-sm-7"> <select class="form-control" name="Article[tag_id]"> <?php foreach ($label as $v) { ?> <option value="<?php echo $v->id; ?>"><?php echo $v->value; ?></option> <?php } ?> </select> </div> <div class="col-lg-2 col-md-2 col-sm-2" style="color:orangered;font-size: 0.8rem;line-height:34px"> <?php echo $form->error($model, 'tag_id'); ?> </div> </div> </div> <div class="form-group"> <div class="row"> <div class="col-lg-2 col-md-3 col-sm-3" align="right" style="line-height:34px"> <?php echo $form->labelEX($model, 'content'); ?> </div> <div class="col-lg-6 col-md-7 col-sm-7"> <div id="test-editormd" style="z-index:999"> <textarea style="display:none;" name="Article[md_content]"></textarea> </div> </div> <div class="col-lg-2 col-md-2 col-sm-2" style="color:orangered;font-size: 0.8rem;line-height:34px"> <?php echo $form->error($model, 'content'); ?> </div> </div> </div> <input type='hidden' name="id" id="back_id"/> <div class="row"> <div class="col-lg-4 col-md-4 col-sm-4"></div> <div class="col-lg-4 col-md-4 col-sm-4"> <button class="btn btn-default" type="submit">提交</button> <button class="btn btn-default" type="reset">重置</button> </div> <div class="col-lg-4 col-md-4 col-sm-4"></div> </div> <?php $this->endwidget(); ?> </div> </div> </div> <script> window.onload = function(){ var testEditor; $(function() { $.get("<?php echo yii::app()->request->baseUrl;?>/assets/editor/examples/null.md", function(md){ testEditor = editormd("test-editormd", { width: "90%", height: 740, path : '<?php echo yii::app()->request->baseUrl;?>/assets/editor/lib/', markdown : md, codeFold : true, saveHTMLToTextarea : true, searchReplace : true, htmlDecode : "style,script,iframe|on*", emoji : true, taskList : true, tocm : true, // Using [TOCM] tex : true, // 开启科学公式TeX语言支持,默认关闭 flowChart : true, // 开启流程图支持,默认关闭 sequenceDiagram : true, // 开启时序/序列图支持,默认关闭, imageUpload : true, imageFormats : ["jpg", "jpeg", "gif", "png", "bmp", "webp"], imageUploadURL : "<?php echo yii::app()->request->baseUrl;?>/assets/editor/examples/php/upload.php", onload : function() { console.log('onload', this); } }); }); }); // ctrl + s监听事件 $(document).keydown(function(e){ if( e.ctrlKey == true && e.keyCode == 83 ){ if($('[name*="Article[title]"]').val() =='' || $('[name*="Article[path]"]').val() == ''){ return false; } var data = $('form').serialize(); data += '&' + encodeURIComponent('Article[content]') + '=' + encodeURIComponent($('.editormd-preview-container').html()); $.post('',data,function(id){ $('#back_id').val(id); } ); return false; // 截取返回false就不会保存网页了 } }); } </script>
bsd-3-clause
kohler/tamer
tamer/http.hh
14524
#ifndef TAMER_HTTP_HH #define TAMER_HTTP_HH 1 #include "fd.hh" #include "http_parser.h" #include <vector> #include <string> #include <sstream> #include <memory> #include <unordered_map> #include <time.h> namespace tamer { class http_parser; struct http_header { std::string name; std::string value; inline http_header(std::string n, std::string v) : name(TAMER_MOVE(n)), value(TAMER_MOVE(v)) { } inline bool is(const char* s, size_t len) const { return name.length() == len && memcmp(name.data(), s, len) == 0; } inline bool is(const std::string& s) const { return is(s.data(), s.length()); } static inline bool equals_canonical(const char* s1, const char* s2, size_t len) { const char* end2 = s2 + len; for (; s2 != end2; ++s1, ++s2) if (*s1 != *s2 && (*s1 < 'A' || *s1 > 'Z' || (*s1 - 'A' + 'a') != *s2)) return false; return true; } static inline bool equals_canonical(const std::string& str, const char* s, size_t len) { return str.length() == len && equals_canonical(str.data(), s, len); } inline bool is_canonical(const char* s, size_t len) const { return equals_canonical(name, s, len); } inline bool is_canonical(const std::string& s) const { return is_canonical(s.data(), s.length()); } inline bool is_content_length() const { return is_canonical("content-length", 14); } }; class http_message { public: typedef std::vector<http_header>::const_iterator header_iterator; inline http_message(); inline bool ok() const; inline bool operator!() const; inline enum http_errno error() const; inline unsigned http_major() const; inline unsigned http_minor() const; inline unsigned status_code() const; inline const std::string& status_message() const; inline enum http_method method() const; inline const std::string& url() const; inline bool has_canonical_header(const char* name, size_t length) const; inline bool has_canonical_header(const char* name) const; inline bool has_canonical_header(const std::string& name) const; header_iterator find_canonical_header(const char* name, size_t length) const; inline header_iterator find_canonical_header(const char* name) const; inline header_iterator find_canonical_header(const std::string& name) const; std::string canonical_header(const char* name, size_t length) const; inline std::string canonical_header(const char* name) const; inline std::string canonical_header(const std::string& name) const; inline bool has_header(const std::string& name) const; inline header_iterator find_header(const std::string& name) const; inline std::string header(const std::string& name) const; inline const std::string& body() const; std::string host() const; inline std::string url_schema() const; inline std::string url_host() const; std::string url_host_port() const; inline std::string url_path() const; inline bool has_query() const; inline std::string query() const; bool has_query(const std::string& name) const; std::string query(const std::string& name) const; inline header_iterator header_begin() const; inline header_iterator header_end() const; inline header_iterator query_begin() const; inline header_iterator query_end() const; inline http_message& clear(); void add_header(std::string key, std::string value); inline http_message& http_major(unsigned v); inline http_message& http_minor(unsigned v); inline http_message& error(enum http_errno e); inline http_message& status_code(unsigned code); inline http_message& status_code(unsigned code, std::string message); inline http_message& method(enum http_method method); inline http_message& url(std::string url); inline http_message& header(std::string key, std::string value); inline http_message& header(std::string key, size_t value); inline http_message& date_header(std::string key, time_t value); inline http_message& body(std::string body); inline http_message& append_body(const std::string& x); static std::string canonicalize(std::string x); static const char* default_status_message(unsigned code); private: enum { info_url = 1, info_query = 2 }; struct info_type { unsigned flags; struct http_parser_url urlp; std::vector<http_header> raw_query; inline info_type() : flags(0) { } }; unsigned short major_; unsigned short minor_; unsigned status_code_ : 16; unsigned method_ : 8; unsigned error_ : 7; unsigned upgrade_ : 1; std::string url_; std::string status_message_; std::vector<http_header> raw_headers_; std::string body_; mutable std::shared_ptr<info_type> info_; inline void kill_info(unsigned f) const; inline info_type& info(unsigned f) const; void make_info(unsigned f) const; inline bool has_url_field(int field) const; inline std::string url_field(int field) const; void do_clear(); friend class http_parser; }; class http_parser : public tamed_class { public: http_parser(enum http_parser_type type); void clear(); inline bool ok() const; inline enum http_errno error() const; inline bool should_keep_alive() const; void receive(fd f, event<http_message> done); void send(fd f, const http_message& m, event<> done); static void send_request(fd f, const http_message& m, event<> done); static void send_request(fd f, http_message&& m, event<> done); static void send_response(fd f, const http_message& m, event<> done); static void send_response(fd f, http_message&& m, event<> done); static void send_response_headers(fd f, const http_message& m, event<> done); static void send_response_chunk(fd f, std::string s, event<> done); static void send_response_end(fd f, event<> done); inline void clear_should_keep_alive(); private: ::http_parser hp_; struct message_data { http_message hm; std::string key; std::ostringstream sbuf; bool done; }; static const http_parser_settings settings; static http_parser* get_parser(::http_parser* hp); static message_data* get_message_data(::http_parser* hp); static int on_message_begin(::http_parser* hp); static int on_url(::http_parser* hp, const char* s, size_t len); static int on_status(::http_parser* hp, const char* s, size_t len); static int on_header_field(::http_parser* hp, const char* s, size_t len); static int on_header_value(::http_parser* hp, const char* s, size_t len); static int on_headers_complete(::http_parser* hp); static int on_body(::http_parser* hp, const char* s, size_t len); static int on_message_complete(::http_parser* hp); inline void copy_parser_status(message_data& md); static void unparse_request_headers(std::ostringstream& buf, const http_message& m); static void unparse_response_headers(std::ostringstream& buf, const http_message& m, bool include_content_length); static inline std::string prepare_headers(const http_message& m, std::string& body, bool is_response); static inline void send_message(fd f, std::string headers, std::string body, event<> done); static void send_two(fd f, std::string a, std::string b, event<> done); class closure__receive__2fdQ12http_message_; void receive(closure__receive__2fdQ12http_message_&); class closure__send_response_chunk__2fdSsQ_; static void send_response_chunk(closure__send_response_chunk__2fdSsQ_&); class closure__send_two__2fdSsSsQ_; static void send_two(closure__send_two__2fdSsSsQ_&); }; inline http_message::http_message() : major_(1), minor_(1), status_code_(200), method_(HTTP_GET), error_(HPE_OK), upgrade_(0) { } inline void http_message::kill_info(unsigned f) const { if (info_) info_->flags &= ~f; } inline unsigned http_message::http_major() const { return major_; } inline unsigned http_message::http_minor() const { return minor_; } inline bool http_message::ok() const { return error_ == HPE_OK; } inline bool http_message::operator!() const { return !ok(); } inline enum http_errno http_message::error() const { return (enum http_errno) error_; } inline unsigned http_message::status_code() const { return status_code_; } inline const std::string& http_message::status_message() const { return status_message_; } inline enum http_method http_message::method() const { return (enum http_method) method_; } inline const std::string& http_message::url() const { return url_; } inline bool http_message::has_canonical_header(const char* name, size_t length) const { return find_canonical_header(name, length) != header_end(); } inline bool http_message::has_canonical_header(const char* name) const { return find_canonical_header(name) != header_end(); } inline bool http_message::has_canonical_header(const std::string& name) const { return find_canonical_header(name) != header_end(); } inline http_message::header_iterator http_message::find_canonical_header(const char* name) const { return find_canonical_header(name, strlen(name)); } inline http_message::header_iterator http_message::find_canonical_header(const std::string& name) const { return find_canonical_header(name.data(), name.length()); } inline std::string http_message::canonical_header(const char* name) const { return canonical_header(name, strlen(name)); } inline std::string http_message::canonical_header(const std::string& name) const { return canonical_header(name.data(), name.length()); } inline bool http_message::has_header(const std::string& name) const { return has_canonical_header(canonicalize(name)); } inline http_message::header_iterator http_message::find_header(const std::string& name) const { return find_canonical_header(canonicalize(name)); } inline std::string http_message::header(const std::string& name) const { return canonical_header(canonicalize(name)); } inline const std::string& http_message::body() const { return body_; } inline bool http_message::has_url_field(int field) const { return info(info_url).urlp.field_set & (1 << field); } inline std::string http_message::url_field(int field) const { const info_type& i = info(info_url); if (i.urlp.field_set & (1 << field)) return url_.substr(i.urlp.field_data[field].off, i.urlp.field_data[field].len); else return std::string(); } inline bool http_message::has_query() const { return has_url_field(UF_QUERY); } inline std::string http_message::query() const { return url_field(UF_QUERY); } inline std::string http_message::url_schema() const { return url_field(UF_SCHEMA); } inline std::string http_message::url_host() const { return url_field(UF_HOST); } inline std::string http_message::url_path() const { return url_field(UF_PATH); } inline http_message& http_message::http_major(unsigned v) { major_ = v; return *this; } inline http_message& http_message::http_minor(unsigned v) { minor_ = v; return *this; } inline http_message& http_message::clear() { do_clear(); return *this; } inline http_message& http_message::error(enum http_errno e) { error_ = e; return *this; } inline http_message& http_message::status_code(unsigned code) { status_code_ = code; status_message_ = std::string(); return *this; } inline http_message& http_message::status_code(unsigned code, std::string message) { status_code_ = code; status_message_ = TAMER_MOVE(message); return *this; } inline http_message& http_message::method(enum http_method method) { method_ = (unsigned) method; return *this; } inline http_message& http_message::url(std::string url) { url_ = TAMER_MOVE(url); kill_info(info_url | info_query); return *this; } inline http_message& http_message::header(std::string key, std::string value) { add_header(TAMER_MOVE(key), TAMER_MOVE(value)); return *this; } inline http_message& http_message::header(std::string key, size_t value) { std::ostringstream buf; buf << value; add_header(TAMER_MOVE(key), buf.str()); return *this; } inline http_message& http_message::date_header(std::string key, time_t value) { char buf[128]; // XXX current locale strftime(buf, sizeof(buf), "%a, %d %b %Y %H:%M:%S GMT", gmtime(&value)); add_header(TAMER_MOVE(key), std::string(buf)); return *this; } inline http_message& http_message::body(std::string body) { body_ = TAMER_MOVE(body); return *this; } inline http_message& http_message::append_body(const std::string& x) { body_ += x; return *this; } inline http_message::info_type& http_message::info(unsigned f) const { if (!info_ || !info_.unique() || (info_->flags & f) != f) make_info(f); return *info_.get(); } inline http_message::header_iterator http_message::header_begin() const { return raw_headers_.begin(); } inline http_message::header_iterator http_message::header_end() const { return raw_headers_.end(); } inline http_message::header_iterator http_message::query_begin() const { return info(info_query).raw_query.begin(); } inline http_message::header_iterator http_message::query_end() const { return info(info_query).raw_query.end(); } inline bool http_parser::ok() const { return hp_.http_errno == (unsigned) HPE_OK; } inline enum http_errno http_parser::error() const { return (enum http_errno) hp_.http_errno; } inline bool http_parser::should_keep_alive() const { return http_should_keep_alive(&hp_); } inline void http_parser::clear_should_keep_alive() { hp_.flags = (hp_.flags & ~F_CONNECTION_KEEP_ALIVE) | F_CONNECTION_CLOSE; } inline void http_parser::send_message(fd f, std::string headers, std::string body, event<> done) { if (body.empty()) f.write(headers, done); else send_two(f, headers, body, done); } } // namespace tamer #endif
bsd-3-clause
soonhokong/cdash
ajax/showtesttimegraph.php
4711
<?php /*========================================================================= Program: CDash - Cross-Platform Dashboard System Module: $Id: showtesttimegraph.php 3401 2013-11-27 12:19:01Z jjomier $ Language: PHP Date: $Date: 2013-11-27 07:19:01 -0500 (Wed, 27 Nov 2013) $ Version: $Revision: 3401 $ Copyright (c) 2002 Kitware, Inc. All rights reserved. See Copyright.txt or http://www.cmake.org/HTML/Copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ // To be able to access files in this CDash installation regardless // of getcwd() value: // $cdashpath = str_replace('\\', '/', dirname(dirname(__FILE__))); set_include_path($cdashpath . PATH_SEPARATOR . get_include_path()); require_once("cdash/config.php"); require_once("cdash/pdo.php"); require_once("cdash/common.php"); $testid = pdo_real_escape_numeric($_GET["testid"]); $buildid = pdo_real_escape_numeric($_GET["buildid"]); @$zoomout = $_GET["zoomout"]; if(!isset($buildid) || !is_numeric($buildid)) { echo "Not a valid buildid!"; return; } if(!isset($testid) || !is_numeric($testid)) { echo "Not a valid testid!"; return; } $db = pdo_connect("$CDASH_DB_HOST", "$CDASH_DB_LOGIN","$CDASH_DB_PASS"); pdo_select_db("$CDASH_DB_NAME",$db); // Find the project variables $test = pdo_query("SELECT name FROM test WHERE id='$testid'"); $test_array = pdo_fetch_array($test); $testname = $test_array["name"]; $build = pdo_query("SELECT name,type,siteid,projectid,starttime FROM build WHERE id='$buildid'"); $build_array = pdo_fetch_array($build); $buildname = $build_array["name"]; $siteid = $build_array["siteid"]; $buildtype = $build_array["type"]; $starttime = $build_array["starttime"]; $projectid = $build_array["projectid"]; // Find the other builds $previousbuilds = pdo_query("SELECT build.id,build.starttime,build2test.time,build2test.testid FROM build JOIN build2test ON (build.id = build2test.buildid) WHERE build.siteid = '$siteid' AND build.projectid = '$projectid' AND build.starttime <= '$starttime' AND build.type = '$buildtype' AND build.name = '$buildname' AND build2test.testid IN (SELECT id FROM test WHERE name = '$testname') ORDER BY build.starttime DESC "); ?> &nbsp; <script language="javascript" type="text/javascript"> $(function () { var d1 = []; var buildids = []; var testids = []; <?php $tarray = array(); while($build_array = pdo_fetch_array($previousbuilds)) { $t['x'] = strtotime($build_array["starttime"])*1000; $t['y'] = $build_array["time"]; $t['builid'] = $build_array["id"]; $t['testid'] = $build_array["testid"]; $tarray[]=$t; ?> <?php } $tarray = array_reverse($tarray); foreach($tarray as $axis) { ?> buildids[<?php echo $axis['x']; ?>]=<?php echo $axis['builid']; ?>; testids[<?php echo $axis['x']; ?>]=<?php echo $axis['testid']; ?>; d1.push([<?php echo $axis['x']; ?>,<?php echo $axis['y']; ?>]); <?php $t = $axis['x']; } ?> var options = { //bars: { show: true, barWidth: 35000000, lineWidth:0.9 }, lines: { show: true }, points: { show: true }, xaxis: { mode: "time"}, grid: {backgroundColor: "#fffaff", clickable: true, hoverable: true, hoverFill: '#444', hoverRadius: 4 }, selection: { mode: "xy" }, colors: ["#0000FF", "#dba255", "#919733"] }; $("#graph_holder").bind("selected", function (event, area) { plot = $.plot($("#graph_holder"), [{label: "Execution Time (seconds)", data: d1}], $.extend(true, {}, options, {xaxis: { min: area.x1, max: area.x2 }})); }); $("#graph_holder").bind("plotclick", function (e, pos, item) { if (item) { plot.highlight(item.series, item.datapoint); buildid = buildids[item.datapoint[0]]; testid = testids[item.datapoint[0]]; window.location = "testDetails.php?test="+testid+"&build="+buildid; } }); <?php if(isset($zoomout)) { ?> plot = $.plot($("#graph_holder"), [{label: "Execution Time (seconds)",data: d1}],options); <?php } else { ?> plot = $.plot($("#graph_holder"), [{label: "Execution Time (seconds)", data: d1}], $.extend(true,{}, options, {xaxis: { min: <?php echo $t-2000000000?>, max: <?php echo $t+50000000; ?>}} )); <?php } ?> }); </script>
bsd-3-clause
Drewno90/blotnix
src/main/java/controller/Login_Controller.java
251
package controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class Login_Controller { @RequestMapping("/log") public String index() { return "log"; } }
bsd-3-clause
benhastings/SeGrid_EC2
sdTestCapacity.py
14008
from selenium import webdriver import selenium.webdriver.support.ui as ui from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.action_chains import ActionChains import time import datetime import csv import random import sys import urllib2 #from pyvirtualdisplay import Display #--- Start Virtual Display ------------------- #display = Display(visible=1, size=(1280, 800)) #display.start() #--- Browser definition for Grid usage ---------- browser = sys.argv[3] #--- Get Interactive Input for number of loops to execute --- numLoops = int(sys.argv[1]) baseURL = sys.argv[2] hub = sys.argv[4] count = sys.argv[5] size = sys.argv[6] #--- Read List of PIIs ----------------- PII=[] csvRd = csv.reader(open('PIIs_250k.csv','rb')) for j in csvRd: PII.append(j) #--- Read List of Journals ----------------- JRNL=[] csvRd = csv.reader(open('Journals.csv','rb')) for j in csvRd: JRNL.append(j) #--- Read List of Search Terms ----------------- SRCH=[] csvRd = csv.reader(open('SDSrchTerms.csv','rb')) for j in csvRd: SRCH.append(j) #--------------------------------------- # Function to gracefully exit the browser # after incrementing loop variables #----------- def egress(): try: driver.quit() #except WindowsError: # print ("****WindowsError - pass? ****") # pass except urllib2.URLError: print ("----URLError - pass? ----") pass #------------------------------------------------------ # Function to execute a request or page interaction # handles associated error conditions # Makes call to collect page timing #------------- def getPage(resource): try: #driver.get("http://"+baseURL) resource if 'Unable to process' in driver.title: print 'Error - Unable to process, wait 60 seconds' time.sleep(60) pass elif 'Error' in driver.title: print 'Error, wait 60 seconds' time.sleep(60) pass else: if 'SD Content Delivery' in titl: metricsCollect(titl,Pii) else: metricsCollect(titl,'NA') time.sleep(.25) except urllib2.URLError: print 'URLError' pass except: print (titl+' fail') pass #------------------------------------------------------- # Function to capture various page timing metrics # and output to screen for log tailing and troubleshooting #--------------- #def metricsCollect(dtitl,PII,sections): def metricsCollect(dtitl,ID): try: navS = driver.execute_script("return performance.timing.navigationStart") #print(navS) respS = driver.execute_script("return performance.timing.responseStart") respE = driver.execute_script("return performance.timing.responseEnd") dom = driver.execute_script("return performance.timing.domInteractive") loadE = driver.execute_script("return performance.timing.loadEventEnd") domC = str(driver.execute_script("return document.getElementsByTagName('*').length")) if loadE > navS: pgLoad = str(int(loadE-navS)) domI = str(int(dom-navS)) cont = str(int(respE-navS)) ttfb = str(int(respS-navS)) #print('\nperf details found\n') else: pgLoad = 'NA' domI='NA' cont='NA' ttfb = 'NA' #print('perf details NOT found') # Datetime for Timestamp dt = datetime.datetime.now() dTm = str(dt.strftime("%Y/%m/%d %H:%M:%S%Z")) if 'SD Content Delivery' in dtitl: # if sections > 0: # print(browser+'\t'+dTm+'\t'+pgLoad+'\t'+domI+'\t'+cont+'\t'+ttfb+'\t'+domC+'\t'+PII+'\t'+sections) # else: print(size+'\t'+count+'\t'+browser+'\t'+dTm+'\t'+pgLoad+'\t'+domI+'\t'+cont+'\t'+ttfb+'\t'+domC+'\t'+ID) else: print(size+'\t'+count+'\t'+browser+'\t'+dTm+'\t'+pgLoad+'\t'+domI+'\t'+cont+'\t'+ttfb+'\t'+domC+'\t'+dtitl) except: if 'Pii' in globals(): print('Unable to print perfTiming details, PII:'+Pii) else: print('Unable to print perfTiming details') try: driver.quit() #except WindowsError: # print ("******WindowsError - pass? ****") # pass except urllib2.URLError: print ("------URLError - pass? ----") pass # # End metricsCollect() # #============================================================= #------------------------------------------------------------- # Script Begins Here #------------------------------------------------------------- #============================================================= #--- Define static Article Value for looping idx=0 while numLoops > 0: #print('iteration: '+str(numLoops)+' browser:'+browser) """ Define capabilities of remote webdriver Specifically: assign browser type """ driver=webdriver.Remote( "http://"+hub+":4200/wd/hub", desired_capabilities={ "browserName": browser } #desired_capabilities.chrome() ) time.sleep(.25) #------------------------------------------------- # Load Home Page & Authenticate x% of iterations #------------------------------------------------- login = int(random.random()*100) if (login%100 < 100): #--- Request Home Page ---------------------------------------- titl='Home Page' getPage(driver.get("http://"+baseURL)) #--- Find Login Form & Fill in data --------------------------- try: driver.find_element_by_id("loginPlusScript").click() driver.find_element_by_id('username').send_keys(USERNAME) driver.find_element_by_id('password').send_keys(PASSWORD) #--- Submit the form based on element ID ---------------- titl='U/P Auth to Home Page' getPage(driver.find_element_by_name("arrow").click()) #--- If choose Org screen displayed, select appropriate value if 'Choose Organization' in driver.title: titl='Choose Org to Home Page' try: driver.find_element_by_id('1').click() driver.find_element_by_class_name('button').click() #metricsCollect(titl) except: pass except: pass #------------------------------------------------- # View Article(s) with scrolling where possible # View multiple articles in same session 33% #------------------------------------------------- artLoop = 5 """ if (login%3==0): artLoop=8 if (login%3==1): artLoop=4 else: artLoop=2 """ #print ('artLoop: '+str(artLoop)) while artLoop > 0: #--- Define Random Value --------------- #idx = int(random.random()*250000) idxPii=idx Pii=str(PII[idxPii]).strip('[\']') titl = 'SD Content Delivery' #sStart = time.time() try: #print('try to get: '+"http://"+baseURL+"/science/article/pii/"+Pii) getPage(driver.get("http://"+baseURL+"/science/article/pii/"+Pii)) except urllib2.URLError: pass time.sleep(.25) try: dtitl=driver.title[:50] #print(dtitl[:50]) except: egress(numLoops,idx) """ if 'ScienceDirect.com' in dtitl: titl='SD Content Delivery' time.sleep(.25) try: secs=driver.find_elements_by_class_name("svArticle") #print 'Sections:'+str(len(secs)) if len(secs) > 0 and numLoops%2 > 0: if len(secs) > 2: #print 'scroll to 1' driver.execute_script("arguments[0].scrollIntoView();",secs[1]) time.sleep(.75) if len(secs) > 10: #print 'scroll to 9' driver.execute_script("arguments[0].scrollIntoView();",secs[9]) time.sleep(.75) if len(secs) > 30: #print 'scroll to 29' driver.execute_script("arguments[0].scrollIntoView();",secs[29]) time.sleep(.75) if len(secs) > 70: #print 'scroll to 69' driver.execute_script("arguments[0].scrollIntoView();",secs[69]) time.sleep(.75) try: refs = driver.find_element_by_class_name("references") scStart = time.time() #print 'scroll to References' driver.execute_script("arguments[0].scrollIntoView();",refs) try: wait.until(lambda driver: driver.find_elements_by_partial_link_text('Cited By in Scopus (')) except: # end waiting for references to resolve pass except: # end try scrolling to references pass except: # end try scrolling pass elif 'Article Locator' in dtitl: titl='ALP' pass else: titl='Other' pass """ #secStr=str(len(secs)) #metricsCollect(titl,Pii,secStr) if artLoop > 0: artLoop = artLoop-1 idx = idx+1 """ try: if ('ScienceDirect.com' in driver.title): #if (login%6 == 0): if (login%6 < 3): titl='Search' SrIdx = int(random.random()*100)%100 try: inputElement = driver.find_element_by_id("quickSearch") #print('search element found') inputElement.send_keys(SRCH[SrIdx]) #print('search text entered') time.sleep(.5) #--- Submit Form -------- getPage(driver.find_element_by_xpath("//button[contains(@title,'Submit quick search')]").click()) except: print 'Search form not found' pass #if (login%6 > 4): if (login%6 > 3): #--- Load Browse List - "Category List" ------------- titl='Category List' getPage(driver.get("http://"+baseURL+"/science/browse")) #--- Load Journal Home Pages - "Category Home" ------ jrnLoop = 2 while jrnLoop > 0: titl='Category Home' idx=idx+jrnLoop jIdx=idx%2500 getPage(driver.get("http://"+baseURL+"/science/journal/"+str(JRNL[jIdx]).strip('[\']'))) jrnLoop=jrnLoop-1 except: pass """ numLoops = numLoops-1 idx=idx+1 egress() #--- Stop Virtual Display ------------ #display.stop()
bsd-3-clause
16nsk/kohana-egotist
modules/oauth/classes/kohana/oauth/token/access.php
510
<?php defined('SYSPATH') or die('No direct script access.'); /** * OAuth Access Token * * @package Kohana/OAuth * @category Token * @author Kohana Team * @copyright (c) 2010 Kohana Team * @license http://kohanaframework.org/license * @since 3.0.7 */ class Kohana_OAuth_Token_Access extends OAuth_Token { protected $name = 'access'; /** * @var string token secret */ protected $secret; protected $required = array( 'token', 'secret', ); } // End OAuth_Token_Access
bsd-3-clause
manchuck/five-foot-step
public/js/jquery.bootstrap-growl.min.js
1976
(function() { var $; $ = jQuery; $.bootstrapGrowl = function(message, options) { var $alert, css, offsetAmount; options = $.extend({}, $.bootstrapGrowl.default_options, options); $alert = $("<div>"); $alert.attr("class", "bootstrap-growl alert"); if (options.type) { $alert.addClass("alert-" + options.type); } if (options.allow_dismiss) { $alert.append("<a class=\"close\" data-dismiss=\"alert\" href=\"#\">&times;</a>"); } $alert.append(message); if (options.top_offset) { options.offset = { from: "top", amount: options.top_offset }; } offsetAmount = options.offset.amount; $(".bootstrap-growl").each(function() { return offsetAmount = Math.max(offsetAmount, parseInt($(this).css(options.offset.from)) + $(this).outerHeight() + options.stackup_spacing); }); css = { "position": (options.ele === "body" ? "fixed" : "absolute"), "margin": 0, "z-index": "9999", "display": "none" }; css[options.offset.from] = offsetAmount + "px"; $alert.css(css); if (options.width !== "auto") { $alert.css("width", options.width + "px"); } $(options.ele).append($alert); switch (options.align) { case "center": $alert.css({ "left": "50%", "margin-left": "-" + ($alert.outerWidth() / 2) + "px" }); break; case "left": $alert.css("left", "20px"); break; default: $alert.css("right", "20px"); } $alert.fadeIn(); if (options.delay > 0) { $alert.delay(options.delay).fadeOut(function() { return $(this).alert("close"); }); } return $alert; }; $.bootstrapGrowl.default_options = { ele: "body", type: null, offset: { from: "top", amount: 20 }, align: "right", width: 250, delay: 4000, allow_dismiss: true, stackup_spacing: 10 }; }).call(this);
bsd-3-clause
jguittard/zpress
cookbooks/vhost/recipes/default.rb
237
include_recipe "apache2" web_app "vagrant_vhost" do server_port 80 directory_options ["FollowSymLinks","MultiViews"] allow_override "FileInfo" server_name node['hostname'] server_aliases [node['fqdn']] docroot "/vagrant" end
bsd-3-clause
bg0jr/Maui
src/Data/Maui.Data/Recognition/Html/HtmlExtractionSettings.cs
936
using System; using System.Collections.Generic; using System.Text; using System.Data; using System.Windows.Forms; using System.Globalization; namespace Maui.Data.Recognition.Html { /// <summary> /// Defines the settings used to extract data from a Html document. /// See <c>ExtractTable</c> methods of the <see cref="HtmlDocumentExtensions"/>. /// </summary> public class HtmlExtractionSettings { /// <summary> /// Defines the defaults. /// Defaults: no link extraction. /// </summary> public HtmlExtractionSettings() { ExtractLinkUrl = false; } /// <summary> /// The href attribute of an A element will be extracted instead of the text of it. /// <remarks>Only the url of the first "A" child.</remarks> /// </summary> public bool ExtractLinkUrl { get; set; } } }
bsd-3-clause
TheLuckyOwl/rshell
src/RShell.cpp
1378
#include "RShell.h" #include <unistd.h> #include <limits.h> using namespace std; string RShell::readCommandLine() { string tempString; getline(cin, tempString); return tempString; } void RShell::inputLoop() { exitStatus = 0; char hostname[HOST_NAME_MAX]; char username[LOGIN_NAME_MAX]; /*The following if statements will check to get the * current host and the current login. If not possible * an error statement will display letting the user know. */ if ( gethostname(hostname, HOST_NAME_MAX) ) { cout << "Error getting host name" << endl; return; } if ( getlogin_r(username, LOGIN_NAME_MAX) ) { cout << "Error getting user name" << endl; return; } /*While the program is running this do statement will display * the current user name and the current host name to the terminal. */ do { cout << username << "@" << hostname << "$ "; commandLine = readCommandLine(); parseString(); } while ( !exitStatus ); } void RShell::outputString(string givenString) { cout << givenString; } /*This function creates a Parser object to take the command * line string to seperate the commands, comments, arguments, * and the connectors. This way they can be used to exectue. */ void RShell::parseString() { parser.stringSplitter( commandLine, &exitStatus ); } void RShell::setExit() { exitStatus = 1; }
bsd-3-clause
ridhobc/sitampan
backend/modules/bcf15/views/bcf15/cetaksppdf.php
7586
<?php use yii\helpers\Html; use yii\grid\GridView; use yii\bootstrap\Modal; use backend\models\Bcf15DetailCont; /* @var $this yii\web\View */ /* @var $searchModel backend\models\TrainingSearch */ /* @var $dataProvider yii\data\ActiveDataProvider */ $this->title = 'Cetak BCF 1.5'; $this->params['breadcrumbs'][] = $this->title; ?> <div class="training-index "> <div class="row"> <div class="col-sm-12"> <table border="0" > <tr > <td rowspan="6" valign="top" > <?php echo Html::img('@web/images/logo.jpg', ['width' => '120', 'height' => '110']) ?> </td> <td colspan="3" class="text text-uppercase" align="center" style="font-size:15px;font:arial;font-weight: bold"><?php echo $modelindetitas->kementerian ?></td> </tr> <tr> <td colspan="3" class="text text-uppercase" align="center" style="font-size:13px;font:arial"><?php echo $modelindetitas->eseloni ?></td> </tr> <tr> <td colspan="3" class="text text-uppercase" align="center" style="font-size:13px;font:arial"><?php echo $modelindetitas->kanwil ?></td> </tr> <tr> <td colspan="3" class="text text-uppercase" align="center" style="font-size:14px;font:arial"><?php echo $modelindetitas->kppbc ?></td> </tr> <tr> <td colspan="3" align="center" style="font-size:11px" ><small><?php echo $modelindetitas->alamat1 ?></small></td> </tr> <tr> <td colspan="3" align="center" style="font-size:11px"><small><?php echo $modelindetitas->alamat2 ?> <?php echo $modelindetitas->alamat3 ?></small></td> </tr> <tr> <td colspan="4" align="center" style="font-size:11px"><font style="text-decoration: underline;"> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </font></td> </tr> </table> <table style="font-size:12px" border="0" width="100%"> <tr > <td width="50%" >Kepada </td> <td class="text text-right"><?php echo Yii::$app->formatter->asDate($model->tgl_sp) ?></td> </tr> <tr > <td >Yth <?php echo $model->kepada_sp ?></td> <td ></td> </tr> <tr > <td height="40" colspan=2 align="center"></td> </tr> <tr> <td colspan=2 style="font-size:13px;font-weight: " align="center"><font style="text-decoration: underline;">&nbsp;&nbsp; SURAT PENGANTAR &nbsp;&nbsp; </font></td> </tr> <tr> <td colspan=2 style="font-size:12px" align="center">NOMOR : <?php echo $model->no_sp ?></td> </tr> </table> </div> </div> <table class="table table-cell table-bordered" style="font-size:10px"> <thead> <tr> <th align="center" style="font-size:13px" >NO</th> <th align="center" style="font-size:13px">JENIS SURAT /BERKAS YANG DIKIRIM</th> <th align="center" style="font-size:13px">BANYAKNYA</th> <th align="center" style="font-size:13px">KETERANGAN</th> </tr> </thead> <tbody> <tr valign="top"> <td style="font-size:12px">1</td> <td width="50%" style="font-size:12px">BCF 1.5 nomor : <?php echo $model->bcf15no ?><br/> Tanggal <?php echo Yii::$app->formatter->asDate($model->bcf15tgl) ?> </td> <td style="font-size:12px">1 (Satu) Berkas</td> <td style="font-size:12px;" align="justify" width="30%" height="200">Disampaikan kepada Saudara untuk penyelesaian lebih lanjut sesuai dengan Peraturan Menteri Keuangan nomor : PMK-62/PMK.04/2011 tanggal 30 Maret 2011 </td> </tr> </tbody> </table> <table class="table-condensed" border="0" > <?php if ($modelPenandatangan) : ?> <?php foreach ($modelPenandatangan as $k2 => $v2) : ?> <tr> <td width="400px"></td><td><?= $v2['jabatan']; ?></td> </tr> <tr> <td ></td><td height="100px">&nbsp;</td> </tr> <tr> <td ></td><td><?= $v2['namapejabat']; ?></td> </tr> <tr> <td ></td><td>NIP <?= $v2['nippejabat']; ?></td> </tr> <?php endforeach; ?> <?php else : ?> <tr> <td colspan="6" class="text-danger text-center"><?php echo Yii::t('app', 'No results found.'); ?></td> </tr> <?php endif; ?> </table> <table> <tr><td height="40" colspan="3"></td></tr> <tr><td colspan="3" style="font-size:11px"><font style="text-decoration: underline;font-weight: bold">TANDA TERIMA</font></td></tr> <tr><td colspan="3" style="font-size:10px">Diterima Oleh :</td></tr> <tr><td style="font-size:10px">Nama / NIP</td><td>:</td><td></td></tr> <tr><td style="font-size:10px">Tanggal </td><td>:</td><td></td></tr> <tr><td style="font-size:10px">Tanda Tangan </td><td>:</td><td></td></tr> </table> <table class="table table-bordered"> <tr> <td height="50" style="font-size:10px"> Catatan : Harap setelah tanda terima diisi, lembar ke 2 dikirim kembali kepada Kami </td> </tr> </table> </div>
bsd-3-clause
mikejurka/engine
shell/platform/android/io/flutter/embedding/android/FlutterActivity.java
41572
// Copyright 2013 The Flutter 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 io.flutter.embedding.android; import static io.flutter.embedding.android.FlutterActivityLaunchConfigs.DART_ENTRYPOINT_META_DATA_KEY; import static io.flutter.embedding.android.FlutterActivityLaunchConfigs.DEFAULT_BACKGROUND_MODE; import static io.flutter.embedding.android.FlutterActivityLaunchConfigs.DEFAULT_DART_ENTRYPOINT; import static io.flutter.embedding.android.FlutterActivityLaunchConfigs.DEFAULT_INITIAL_ROUTE; import static io.flutter.embedding.android.FlutterActivityLaunchConfigs.EXTRA_BACKGROUND_MODE; import static io.flutter.embedding.android.FlutterActivityLaunchConfigs.EXTRA_CACHED_ENGINE_ID; import static io.flutter.embedding.android.FlutterActivityLaunchConfigs.EXTRA_DESTROY_ENGINE_WITH_ACTIVITY; import static io.flutter.embedding.android.FlutterActivityLaunchConfigs.EXTRA_INITIAL_ROUTE; import static io.flutter.embedding.android.FlutterActivityLaunchConfigs.INITIAL_ROUTE_META_DATA_KEY; import static io.flutter.embedding.android.FlutterActivityLaunchConfigs.NORMAL_THEME_META_DATA_KEY; import static io.flutter.embedding.android.FlutterActivityLaunchConfigs.SPLASH_SCREEN_META_DATA_KEY; import android.app.Activity; import android.arch.lifecycle.Lifecycle; import android.arch.lifecycle.LifecycleOwner; import android.arch.lifecycle.LifecycleRegistry; import android.content.Context; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.VisibleForTesting; import android.view.View; import android.view.Window; import android.view.WindowManager; import io.flutter.Log; import io.flutter.embedding.android.FlutterActivityLaunchConfigs.BackgroundMode; import io.flutter.embedding.engine.FlutterEngine; import io.flutter.embedding.engine.FlutterShellArgs; import io.flutter.embedding.engine.plugins.activity.ActivityControlSurface; import io.flutter.plugin.platform.PlatformPlugin; import io.flutter.view.FlutterMain; import java.lang.reflect.Method; /** * {@code Activity} which displays a fullscreen Flutter UI. * * <p>{@code FlutterActivity} is the simplest and most direct way to integrate Flutter within an * Android app. * * <p><strong>Dart entrypoint, initial route, and app bundle path</strong> * * <p>The Dart entrypoint executed within this {@code Activity} is "main()" by default. To change * the entrypoint that a {@code FlutterActivity} executes, subclass {@code FlutterActivity} and * override {@link #getDartEntrypointFunctionName()}. * * <p>The Flutter route that is initially loaded within this {@code Activity} is "/". The initial * route may be specified explicitly by passing the name of the route as a {@code String} in {@link * FlutterActivityLaunchConfigs#EXTRA_INITIAL_ROUTE}, e.g., "my/deep/link". * * <p>The initial route can each be controlled using a {@link NewEngineIntentBuilder} via {@link * NewEngineIntentBuilder#initialRoute}. * * <p>The app bundle path, Dart entrypoint, and initial route can also be controlled in a subclass * of {@code FlutterActivity} by overriding their respective methods: * * <ul> * <li>{@link #getAppBundlePath()} * <li>{@link #getDartEntrypointFunctionName()} * <li>{@link #getInitialRoute()} * </ul> * * <p>The Dart entrypoint and app bundle path are not supported as {@code Intent} parameters due to * security concerns. If such configurations were exposed via {@code Intent}, then a {@code * FlutterActivity} that is {@code exported} from your Android app would allow other apps to invoke * arbitrary Dart entrypoints in your app by specifying different Dart entrypoints for your {@code * FlutterActivity}. Therefore, these configurations are not available via {@code Intent}. * * <p><strong>Using a cached FlutterEngine</strong> * * <p>{@code FlutterActivity} can be used with a cached {@link FlutterEngine} instead of creating a * new one. Use {@link #withCachedEngine(String)} to build a {@code FlutterActivity} {@code Intent} * that is configured to use an existing, cached {@link FlutterEngine}. {@link * io.flutter.embedding.engine.FlutterEngineCache} is the cache that is used to obtain a given * cached {@link FlutterEngine}. An {@code IllegalStateException} will be thrown if a cached engine * is requested but does not exist in the cache. * * <p>When using a cached {@link FlutterEngine}, that {@link FlutterEngine} should already be * executing Dart code, which means that the Dart entrypoint and initial route have already been * defined. Therefore, {@link CachedEngineIntentBuilder} does not offer configuration of these * properties. * * <p>It is generally recommended to use a cached {@link FlutterEngine} to avoid a momentary delay * when initializing a new {@link FlutterEngine}. The two exceptions to using a cached {@link * FlutterEngine} are: * * <p> * * <ul> * <li>When {@code FlutterActivity} is the first {@code Activity} displayed by the app, because * pre-warming a {@link FlutterEngine} would have no impact in this situation. * <li>When you are unsure when/if you will need to display a Flutter experience. * </ul> * * <p>The following illustrates how to pre-warm and cache a {@link FlutterEngine}: * * <pre>{@code * // Create and pre-warm a FlutterEngine. * FlutterEngine flutterEngine = new FlutterEngine(context); * flutterEngine.getDartExecutor().executeDartEntrypoint(DartEntrypoint.createDefault()); * * // Cache the pre-warmed FlutterEngine in the FlutterEngineCache. * FlutterEngineCache.getInstance().put("my_engine", flutterEngine); * }</pre> * * <p><strong>Alternatives to FlutterActivity</strong> * * <p>If Flutter is needed in a location that cannot use an {@code Activity}, consider using a * {@link FlutterFragment}. Using a {@link FlutterFragment} requires forwarding some calls from an * {@code Activity} to the {@link FlutterFragment}. * * <p>If Flutter is needed in a location that can only use a {@code View}, consider using a {@link * FlutterView}. Using a {@link FlutterView} requires forwarding some calls from an {@code * Activity}, as well as forwarding lifecycle calls from an {@code Activity} or a {@code Fragment}. * * <p><strong>FlutterActivity responsibilities</strong> * * <p>{@code FlutterActivity} maintains the following responsibilities: * * <ul> * <li>Displays an Android launch screen. * <li>Displays a Flutter splash screen. * <li>Configures the status bar appearance. * <li>Chooses the Dart execution app bundle path and entrypoint. * <li>Chooses Flutter's initial route. * <li>Renders {@code Activity} transparently, if desired. * <li>Offers hooks for subclasses to provide and configure a {@link FlutterEngine}. * </ul> * * <p><strong>Launch Screen and Splash Screen</strong> * * <p>{@code FlutterActivity} supports the display of an Android "launch screen" as well as a * Flutter-specific "splash screen". The launch screen is displayed while the Android application * loads. It is only applicable if {@code FlutterActivity} is the first {@code Activity} displayed * upon loading the app. After the launch screen passes, a splash screen is optionally displayed. * The splash screen is displayed for as long as it takes Flutter to initialize and render its first * frame. * * <p>Use Android themes to display a launch screen. Create two themes: a launch theme and a normal * theme. In the launch theme, set {@code windowBackground} to the desired {@code Drawable} for the * launch screen. In the normal theme, set {@code windowBackground} to any desired background color * that should normally appear behind your Flutter content. In most cases this background color will * never be seen, but for possible transition edge cases it is a good idea to explicitly replace the * launch screen window background with a neutral color. * * <p>Do not change aspects of system chrome between a launch theme and normal theme. Either define * both themes to be fullscreen or not, and define both themes to display the same status bar and * navigation bar settings. To adjust system chrome once the Flutter app renders, use platform * channels to instruct Android to do so at the appropriate time. This will avoid any jarring visual * changes during app startup. * * <p>In the AndroidManifest.xml, set the theme of {@code FlutterActivity} to the defined launch * theme. In the metadata section for {@code FlutterActivity}, defined the following reference to * your normal theme: * * <p>{@code <meta-data android:name="io.flutter.embedding.android.NormalTheme" * android:resource="@style/YourNormalTheme" /> } * * <p>With themes defined, and AndroidManifest.xml updated, Flutter displays the specified launch * screen until the Android application is initialized. * * <p>Flutter also requires initialization time. To specify a splash screen for Flutter * initialization, subclass {@code FlutterActivity} and override {@link #provideSplashScreen()}. See * {@link SplashScreen} for details on implementing a splash screen. * * <p>Flutter ships with a splash screen that automatically displays the exact same {@code * windowBackground} as the launch theme discussed previously. To use that splash screen, include * the following metadata in AndroidManifest.xml for this {@code FlutterActivity}: * * <p>{@code <meta-data android:name="io.flutter.app.android.SplashScreenUntilFirstFrame" * android:value="true" /> } * * <p><strong>Alternative Activity</strong> {@link FlutterFragmentActivity} is also available, which * is similar to {@code FlutterActivity} but it extends {@code FragmentActivity}. You should use * {@code FlutterActivity}, if possible, but if you need a {@code FragmentActivity} then you should * use {@link FlutterFragmentActivity}. */ // A number of methods in this class have the same implementation as FlutterFragmentActivity. These // methods are duplicated for readability purposes. Be sure to replicate any change in this class in // FlutterFragmentActivity, too. public class FlutterActivity extends Activity implements FlutterActivityAndFragmentDelegate.Host, LifecycleOwner { private static final String TAG = "FlutterActivity"; /** * Creates an {@link Intent} that launches a {@code FlutterActivity}, which executes a {@code * main()} Dart entrypoint, and displays the "/" route as Flutter's initial route. */ @NonNull public static Intent createDefaultIntent(@NonNull Context launchContext) { return withNewEngine().build(launchContext); } /** * Creates an {@link NewEngineIntentBuilder}, which can be used to configure an {@link Intent} to * launch a {@code FlutterActivity} that internally creates a new {@link FlutterEngine} using the * desired Dart entrypoint, initial route, etc. */ @NonNull public static NewEngineIntentBuilder withNewEngine() { return new NewEngineIntentBuilder(FlutterActivity.class); } /** * Builder to create an {@code Intent} that launches a {@code FlutterActivity} with a new {@link * FlutterEngine} and the desired configuration. */ public static class NewEngineIntentBuilder { private final Class<? extends FlutterActivity> activityClass; private String initialRoute = DEFAULT_INITIAL_ROUTE; private String backgroundMode = DEFAULT_BACKGROUND_MODE; /** * Constructor that allows this {@code NewEngineIntentBuilder} to be used by subclasses of * {@code FlutterActivity}. * * <p>Subclasses of {@code FlutterActivity} should provide their own static version of {@link * #withNewEngine()}, which returns an instance of {@code NewEngineIntentBuilder} constructed * with a {@code Class} reference to the {@code FlutterActivity} subclass, e.g.: * * <p>{@code return new NewEngineIntentBuilder(MyFlutterActivity.class); } */ protected NewEngineIntentBuilder(@NonNull Class<? extends FlutterActivity> activityClass) { this.activityClass = activityClass; } /** * The initial route that a Flutter app will render in this {@link FlutterFragment}, defaults to * "/". */ @NonNull public NewEngineIntentBuilder initialRoute(@NonNull String initialRoute) { this.initialRoute = initialRoute; return this; } /** * The mode of {@code FlutterActivity}'s background, either {@link BackgroundMode#opaque} or * {@link BackgroundMode#transparent}. * * <p>The default background mode is {@link BackgroundMode#opaque}. * * <p>Choosing a background mode of {@link BackgroundMode#transparent} will configure the inner * {@link FlutterView} of this {@code FlutterActivity} to be configured with a {@link * FlutterTextureView} to support transparency. This choice has a non-trivial performance * impact. A transparent background should only be used if it is necessary for the app design * being implemented. * * <p>A {@code FlutterActivity} that is configured with a background mode of {@link * BackgroundMode#transparent} must have a theme applied to it that includes the following * property: {@code <item name="android:windowIsTranslucent">true</item>}. */ @NonNull public NewEngineIntentBuilder backgroundMode(@NonNull BackgroundMode backgroundMode) { this.backgroundMode = backgroundMode.name(); return this; } /** * Creates and returns an {@link Intent} that will launch a {@code FlutterActivity} with the * desired configuration. */ @NonNull public Intent build(@NonNull Context context) { return new Intent(context, activityClass) .putExtra(EXTRA_INITIAL_ROUTE, initialRoute) .putExtra(EXTRA_BACKGROUND_MODE, backgroundMode) .putExtra(EXTRA_DESTROY_ENGINE_WITH_ACTIVITY, true); } } /** * Creates a {@link CachedEngineIntentBuilder}, which can be used to configure an {@link Intent} * to launch a {@code FlutterActivity} that internally uses an existing {@link FlutterEngine} that * is cached in {@link io.flutter.embedding.engine.FlutterEngineCache}. */ public static CachedEngineIntentBuilder withCachedEngine(@NonNull String cachedEngineId) { return new CachedEngineIntentBuilder(FlutterActivity.class, cachedEngineId); } /** * Builder to create an {@code Intent} that launches a {@code FlutterActivity} with an existing * {@link FlutterEngine} that is cached in {@link io.flutter.embedding.engine.FlutterEngineCache}. */ public static class CachedEngineIntentBuilder { private final Class<? extends FlutterActivity> activityClass; private final String cachedEngineId; private boolean destroyEngineWithActivity = false; private String backgroundMode = DEFAULT_BACKGROUND_MODE; /** * Constructor that allows this {@code CachedEngineIntentBuilder} to be used by subclasses of * {@code FlutterActivity}. * * <p>Subclasses of {@code FlutterActivity} should provide their own static version of {@link * #withNewEngine()}, which returns an instance of {@code CachedEngineIntentBuilder} constructed * with a {@code Class} reference to the {@code FlutterActivity} subclass, e.g.: * * <p>{@code return new CachedEngineIntentBuilder(MyFlutterActivity.class, engineId); } */ protected CachedEngineIntentBuilder( @NonNull Class<? extends FlutterActivity> activityClass, @NonNull String engineId) { this.activityClass = activityClass; this.cachedEngineId = engineId; } /** * Returns true if the cached {@link FlutterEngine} should be destroyed and removed from the * cache when this {@code FlutterActivity} is destroyed. * * <p>The default value is {@code false}. */ public CachedEngineIntentBuilder destroyEngineWithActivity(boolean destroyEngineWithActivity) { this.destroyEngineWithActivity = destroyEngineWithActivity; return this; } /** * The mode of {@code FlutterActivity}'s background, either {@link BackgroundMode#opaque} or * {@link BackgroundMode#transparent}. * * <p>The default background mode is {@link BackgroundMode#opaque}. * * <p>Choosing a background mode of {@link BackgroundMode#transparent} will configure the inner * {@link FlutterView} of this {@code FlutterActivity} to be configured with a {@link * FlutterTextureView} to support transparency. This choice has a non-trivial performance * impact. A transparent background should only be used if it is necessary for the app design * being implemented. * * <p>A {@code FlutterActivity} that is configured with a background mode of {@link * BackgroundMode#transparent} must have a theme applied to it that includes the following * property: {@code <item name="android:windowIsTranslucent">true</item>}. */ @NonNull public CachedEngineIntentBuilder backgroundMode(@NonNull BackgroundMode backgroundMode) { this.backgroundMode = backgroundMode.name(); return this; } /** * Creates and returns an {@link Intent} that will launch a {@code FlutterActivity} with the * desired configuration. */ @NonNull public Intent build(@NonNull Context context) { return new Intent(context, activityClass) .putExtra(EXTRA_CACHED_ENGINE_ID, cachedEngineId) .putExtra(EXTRA_DESTROY_ENGINE_WITH_ACTIVITY, destroyEngineWithActivity) .putExtra(EXTRA_BACKGROUND_MODE, backgroundMode); } } // Delegate that runs all lifecycle and OS hook logic that is common between // FlutterActivity and FlutterFragment. See the FlutterActivityAndFragmentDelegate // implementation for details about why it exists. @VisibleForTesting protected FlutterActivityAndFragmentDelegate delegate; @NonNull private LifecycleRegistry lifecycle; public FlutterActivity() { lifecycle = new LifecycleRegistry(this); } /** * This method exists so that JVM tests can ensure that a delegate exists without putting this * Activity through any lifecycle events, because JVM tests cannot handle executing any lifecycle * methods, at the time of writing this. * * <p>The testing infrastructure should be upgraded to make FlutterActivity tests easy to write * while exercising real lifecycle methods. At such a time, this method should be removed. */ // TODO(mattcarroll): remove this when tests allow for it // (https://github.com/flutter/flutter/issues/43798) @VisibleForTesting /* package */ void setDelegate(@NonNull FlutterActivityAndFragmentDelegate delegate) { this.delegate = delegate; } @Override protected void onCreate(@Nullable Bundle savedInstanceState) { switchLaunchThemeForNormalTheme(); super.onCreate(savedInstanceState); lifecycle.handleLifecycleEvent(Lifecycle.Event.ON_CREATE); delegate = new FlutterActivityAndFragmentDelegate(this); delegate.onAttach(this); delegate.onActivityCreated(savedInstanceState); configureWindowForTransparency(); setContentView(createFlutterView()); configureStatusBarForFullscreenFlutterExperience(); } /** * Switches themes for this {@code Activity} from the theme used to launch this {@code Activity} * to a "normal theme" that is intended for regular {@code Activity} operation. * * <p>This behavior is offered so that a "launch screen" can be displayed while the application * initially loads. To utilize this behavior in an app, do the following: * * <ol> * <li>Create 2 different themes in style.xml: one theme for the launch screen and one theme for * normal display. * <li>In the launch screen theme, set the "windowBackground" property to a {@code Drawable} of * your choice. * <li>In the normal theme, customize however you'd like. * <li>In the AndroidManifest.xml, set the theme of your {@code FlutterActivity} to your launch * theme. * <li>Add a {@code <meta-data>} property to your {@code FlutterActivity} with a name of * "io.flutter.embedding.android.NormalTheme" and set the resource to your normal theme, * e.g., {@code android:resource="@style/MyNormalTheme}. * </ol> * * With the above settings, your launch theme will be used when loading the app, and then the * theme will be switched to your normal theme once the app has initialized. * * <p>Do not change aspects of system chrome between a launch theme and normal theme. Either * define both themes to be fullscreen or not, and define both themes to display the same status * bar and navigation bar settings. If you wish to adjust system chrome once your Flutter app * renders, use platform channels to instruct Android to do so at the appropriate time. This will * avoid any jarring visual changes during app startup. */ private void switchLaunchThemeForNormalTheme() { try { ActivityInfo activityInfo = getPackageManager().getActivityInfo(getComponentName(), PackageManager.GET_META_DATA); if (activityInfo.metaData != null) { int normalThemeRID = activityInfo.metaData.getInt(NORMAL_THEME_META_DATA_KEY, -1); if (normalThemeRID != -1) { setTheme(normalThemeRID); } } else { Log.v(TAG, "Using the launch theme as normal theme."); } } catch (PackageManager.NameNotFoundException exception) { Log.e( TAG, "Could not read meta-data for FlutterActivity. Using the launch theme as normal theme."); } } @Nullable @Override public SplashScreen provideSplashScreen() { Drawable manifestSplashDrawable = getSplashScreenFromManifest(); if (manifestSplashDrawable != null) { return new DrawableSplashScreen(manifestSplashDrawable); } else { return null; } } /** * Returns a {@link Drawable} to be used as a splash screen as requested by meta-data in the * {@code AndroidManifest.xml} file, or null if no such splash screen is requested. * * <p>See {@link FlutterActivityLaunchConfigs#SPLASH_SCREEN_META_DATA_KEY} for the meta-data key * to be used in a manifest file. */ @Nullable @SuppressWarnings("deprecation") private Drawable getSplashScreenFromManifest() { try { ActivityInfo activityInfo = getPackageManager().getActivityInfo(getComponentName(), PackageManager.GET_META_DATA); Bundle metadata = activityInfo.metaData; int splashScreenId = metadata != null ? metadata.getInt(SPLASH_SCREEN_META_DATA_KEY) : 0; return splashScreenId != 0 ? Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP ? getResources().getDrawable(splashScreenId, getTheme()) : getResources().getDrawable(splashScreenId) : null; } catch (PackageManager.NameNotFoundException e) { // This is never expected to happen. return null; } } /** * Sets this {@code Activity}'s {@code Window} background to be transparent, and hides the status * bar, if this {@code Activity}'s desired {@link BackgroundMode} is {@link * BackgroundMode#transparent}. * * <p>For {@code Activity} transparency to work as expected, the theme applied to this {@code * Activity} must include {@code <item name="android:windowIsTranslucent">true</item>}. */ private void configureWindowForTransparency() { BackgroundMode backgroundMode = getBackgroundMode(); if (backgroundMode == BackgroundMode.transparent) { getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); } } @NonNull private View createFlutterView() { return delegate.onCreateView( null /* inflater */, null /* container */, null /* savedInstanceState */); } private void configureStatusBarForFullscreenFlutterExperience() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { Window window = getWindow(); window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); window.setStatusBarColor(0x40000000); window.getDecorView().setSystemUiVisibility(PlatformPlugin.DEFAULT_SYSTEM_UI); } } @Override protected void onStart() { super.onStart(); lifecycle.handleLifecycleEvent(Lifecycle.Event.ON_START); delegate.onStart(); } @Override protected void onResume() { super.onResume(); lifecycle.handleLifecycleEvent(Lifecycle.Event.ON_RESUME); delegate.onResume(); } @Override public void onPostResume() { super.onPostResume(); delegate.onPostResume(); } @Override protected void onPause() { super.onPause(); delegate.onPause(); lifecycle.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE); } @Override protected void onStop() { super.onStop(); delegate.onStop(); lifecycle.handleLifecycleEvent(Lifecycle.Event.ON_STOP); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); delegate.onSaveInstanceState(outState); } @Override protected void onDestroy() { super.onDestroy(); delegate.onDestroyView(); delegate.onDetach(); lifecycle.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { delegate.onActivityResult(requestCode, resultCode, data); } @Override protected void onNewIntent(@NonNull Intent intent) { // TODO(mattcarroll): change G3 lint rule that forces us to call super super.onNewIntent(intent); delegate.onNewIntent(intent); } @Override public void onBackPressed() { delegate.onBackPressed(); } @Override public void onRequestPermissionsResult( int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { delegate.onRequestPermissionsResult(requestCode, permissions, grantResults); } @Override public void onUserLeaveHint() { delegate.onUserLeaveHint(); } @Override public void onTrimMemory(int level) { super.onTrimMemory(level); delegate.onTrimMemory(level); } /** * {@link FlutterActivityAndFragmentDelegate.Host} method that is used by {@link * FlutterActivityAndFragmentDelegate} to obtain a {@code Context} reference as needed. */ @Override @NonNull public Context getContext() { return this; } /** * {@link FlutterActivityAndFragmentDelegate.Host} method that is used by {@link * FlutterActivityAndFragmentDelegate} to obtain an {@code Activity} reference as needed. This * reference is used by the delegate to instantiate a {@link FlutterView}, a {@link * PlatformPlugin}, and to determine if the {@code Activity} is changing configurations. */ @Override @NonNull public Activity getActivity() { return this; } /** * {@link FlutterActivityAndFragmentDelegate.Host} method that is used by {@link * FlutterActivityAndFragmentDelegate} to obtain a {@code Lifecycle} reference as needed. This * reference is used by the delegate to provide Flutter plugins with access to lifecycle events. */ @Override @NonNull public Lifecycle getLifecycle() { return lifecycle; } /** * {@link FlutterActivityAndFragmentDelegate.Host} method that is used by {@link * FlutterActivityAndFragmentDelegate} to obtain Flutter shell arguments when initializing * Flutter. */ @NonNull @Override public FlutterShellArgs getFlutterShellArgs() { return FlutterShellArgs.fromIntent(getIntent()); } /** * Returns the ID of a statically cached {@link FlutterEngine} to use within this {@code * FlutterActivity}, or {@code null} if this {@code FlutterActivity} does not want to use a cached * {@link FlutterEngine}. */ @Override @Nullable public String getCachedEngineId() { return getIntent().getStringExtra(EXTRA_CACHED_ENGINE_ID); } /** * Returns false if the {@link FlutterEngine} backing this {@code FlutterActivity} should outlive * this {@code FlutterActivity}, or true to be destroyed when the {@code FlutterActivity} is * destroyed. * * <p>The default value is {@code true} in cases where {@code FlutterActivity} created its own * {@link FlutterEngine}, and {@code false} in cases where a cached {@link FlutterEngine} was * provided. */ @Override public boolean shouldDestroyEngineWithHost() { boolean explicitDestructionRequested = getIntent().getBooleanExtra(EXTRA_DESTROY_ENGINE_WITH_ACTIVITY, false); if (getCachedEngineId() != null || delegate.isFlutterEngineFromHost()) { // Only destroy a cached engine if explicitly requested by app developer. return explicitDestructionRequested; } else { // If this Activity created the FlutterEngine, destroy it by default unless // explicitly requested not to. return getIntent().getBooleanExtra(EXTRA_DESTROY_ENGINE_WITH_ACTIVITY, true); } } /** * The Dart entrypoint that will be executed as soon as the Dart snapshot is loaded. * * <p>This preference can be controlled by setting a {@code <meta-data>} called {@link * FlutterActivityLaunchConfigs#DART_ENTRYPOINT_META_DATA_KEY} within the Android manifest * definition for this {@code FlutterActivity}. * * <p>Subclasses may override this method to directly control the Dart entrypoint. */ @NonNull public String getDartEntrypointFunctionName() { try { ActivityInfo activityInfo = getPackageManager().getActivityInfo(getComponentName(), PackageManager.GET_META_DATA); Bundle metadata = activityInfo.metaData; String desiredDartEntrypoint = metadata != null ? metadata.getString(DART_ENTRYPOINT_META_DATA_KEY) : null; return desiredDartEntrypoint != null ? desiredDartEntrypoint : DEFAULT_DART_ENTRYPOINT; } catch (PackageManager.NameNotFoundException e) { return DEFAULT_DART_ENTRYPOINT; } } /** * The initial route that a Flutter app will render upon loading and executing its Dart code. * * <p>This preference can be controlled with 2 methods: * * <ol> * <li>Pass a boolean as {@link FlutterActivityLaunchConfigs#EXTRA_INITIAL_ROUTE} with the * launching {@code Intent}, or * <li>Set a {@code <meta-data>} called {@link * FlutterActivityLaunchConfigs#INITIAL_ROUTE_META_DATA_KEY} for this {@code Activity} in * the Android manifest. * </ol> * * If both preferences are set, the {@code Intent} preference takes priority. * * <p>The reason that a {@code <meta-data>} preference is supported is because this {@code * Activity} might be the very first {@code Activity} launched, which means the developer won't * have control over the incoming {@code Intent}. * * <p>Subclasses may override this method to directly control the initial route. */ @NonNull public String getInitialRoute() { if (getIntent().hasExtra(EXTRA_INITIAL_ROUTE)) { return getIntent().getStringExtra(EXTRA_INITIAL_ROUTE); } try { ActivityInfo activityInfo = getPackageManager().getActivityInfo(getComponentName(), PackageManager.GET_META_DATA); Bundle metadata = activityInfo.metaData; String desiredInitialRoute = metadata != null ? metadata.getString(INITIAL_ROUTE_META_DATA_KEY) : null; return desiredInitialRoute != null ? desiredInitialRoute : DEFAULT_INITIAL_ROUTE; } catch (PackageManager.NameNotFoundException e) { return DEFAULT_INITIAL_ROUTE; } } /** * The path to the bundle that contains this Flutter app's resources, e.g., Dart code snapshots. * * <p>When this {@code FlutterActivity} is run by Flutter tooling and a data String is included in * the launching {@code Intent}, that data String is interpreted as an app bundle path. * * <p>By default, the app bundle path is obtained from {@link FlutterMain#findAppBundlePath()}. * * <p>Subclasses may override this method to return a custom app bundle path. */ @NonNull public String getAppBundlePath() { // If this Activity was launched from tooling, and the incoming Intent contains // a custom app bundle path, return that path. // TODO(mattcarroll): determine if we should have an explicit FlutterTestActivity instead of // conflating. if (isDebuggable() && Intent.ACTION_RUN.equals(getIntent().getAction())) { String appBundlePath = getIntent().getDataString(); if (appBundlePath != null) { return appBundlePath; } } // Return the default app bundle path. // TODO(mattcarroll): move app bundle resolution into an appropriately named class. return FlutterMain.findAppBundlePath(); } /** * Returns true if Flutter is running in "debug mode", and false otherwise. * * <p>Debug mode allows Flutter to operate with hot reload and hot restart. Release mode does not. */ private boolean isDebuggable() { return (getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0; } /** * {@link FlutterActivityAndFragmentDelegate.Host} method that is used by {@link * FlutterActivityAndFragmentDelegate} to obtain the desired {@link RenderMode} that should be * used when instantiating a {@link FlutterView}. */ @NonNull @Override public RenderMode getRenderMode() { return getBackgroundMode() == BackgroundMode.opaque ? RenderMode.surface : RenderMode.texture; } /** * {@link FlutterActivityAndFragmentDelegate.Host} method that is used by {@link * FlutterActivityAndFragmentDelegate} to obtain the desired {@link TransparencyMode} that should * be used when instantiating a {@link FlutterView}. */ @NonNull @Override public TransparencyMode getTransparencyMode() { return getBackgroundMode() == BackgroundMode.opaque ? TransparencyMode.opaque : TransparencyMode.transparent; } /** * The desired window background mode of this {@code Activity}, which defaults to {@link * BackgroundMode#opaque}. */ @NonNull protected BackgroundMode getBackgroundMode() { if (getIntent().hasExtra(EXTRA_BACKGROUND_MODE)) { return BackgroundMode.valueOf(getIntent().getStringExtra(EXTRA_BACKGROUND_MODE)); } else { return BackgroundMode.opaque; } } /** * Hook for subclasses to easily provide a custom {@link FlutterEngine}. * * <p>This hook is where a cached {@link FlutterEngine} should be provided, if a cached {@link * FlutterEngine} is desired. */ @Nullable @Override public FlutterEngine provideFlutterEngine(@NonNull Context context) { // No-op. Hook for subclasses. return null; } /** * Hook for subclasses to obtain a reference to the {@link FlutterEngine} that is owned by this * {@code FlutterActivity}. */ @Nullable protected FlutterEngine getFlutterEngine() { return delegate.getFlutterEngine(); } @Nullable @Override public PlatformPlugin providePlatformPlugin( @Nullable Activity activity, @NonNull FlutterEngine flutterEngine) { if (activity != null) { return new PlatformPlugin(getActivity(), flutterEngine.getPlatformChannel()); } else { return null; } } /** * Hook for subclasses to easily configure a {@code FlutterEngine}. * * <p>This method is called after {@link #provideFlutterEngine(Context)}. * * <p>All plugins listed in the app's pubspec are registered in the base implementation of this * method. To avoid automatic plugin registration, override this method without invoking super(). * To keep automatic plugin registration and further configure the flutterEngine, override this * method, invoke super(), and then configure the flutterEngine as desired. */ @Override public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) { registerPlugins(flutterEngine); } /** * Hook for the host to cleanup references that were established in {@link * #configureFlutterEngine(FlutterEngine)} before the host is destroyed or detached. * * <p>This method is called in {@link #onDestroy()}. */ @Override public void cleanUpFlutterEngine(@NonNull FlutterEngine flutterEngine) { // No-op. Hook for subclasses. } /** * Hook for subclasses to control whether or not the {@link FlutterFragment} within this {@code * Activity} automatically attaches its {@link FlutterEngine} to this {@code Activity}. * * <p>This property is controlled with a protected method instead of an {@code Intent} argument * because the only situation where changing this value would help, is a situation in which {@code * FlutterActivity} is being subclassed to utilize a custom and/or cached {@link FlutterEngine}. * * <p>Defaults to {@code true}. * * <p>Control surfaces are used to provide Android resources and lifecycle events to plugins that * are attached to the {@link FlutterEngine}. If {@code shouldAttachEngineToActivity} is true then * this {@code FlutterActivity} will connect its {@link FlutterEngine} to itself, along with any * plugins that are registered with that {@link FlutterEngine}. This allows plugins to access the * {@code Activity}, as well as receive {@code Activity}-specific calls, e.g., {@link * Activity#onNewIntent(Intent)}. If {@code shouldAttachEngineToActivity} is false, then this * {@code FlutterActivity} will not automatically manage the connection between its {@link * FlutterEngine} and itself. In this case, plugins will not be offered a reference to an {@code * Activity} or its OS hooks. * * <p>Returning false from this method does not preclude a {@link FlutterEngine} from being * attaching to a {@code FlutterActivity} - it just prevents the attachment from happening * automatically. A developer can choose to subclass {@code FlutterActivity} and then invoke * {@link ActivityControlSurface#attachToActivity(Activity, Lifecycle)} and {@link * ActivityControlSurface#detachFromActivity()} at the desired times. * * <p>One reason that a developer might choose to manually manage the relationship between the * {@code Activity} and {@link FlutterEngine} is if the developer wants to move the {@link * FlutterEngine} somewhere else. For example, a developer might want the {@link FlutterEngine} to * outlive this {@code FlutterActivity} so that it can be used later in a different {@code * Activity}. To accomplish this, the {@link FlutterEngine} may need to be disconnected from this * {@code FluttterActivity} at an unusual time, preventing this {@code FlutterActivity} from * correctly managing the relationship between the {@link FlutterEngine} and itself. */ @Override public boolean shouldAttachEngineToActivity() { return true; } @Override public void onFlutterSurfaceViewCreated(@NonNull FlutterSurfaceView flutterSurfaceView) { // Hook for subclasses. } @Override public void onFlutterTextureViewCreated(@NonNull FlutterTextureView flutterTextureView) { // Hook for subclasses. } @Override public void onFlutterUiDisplayed() { // Notifies Android that we're fully drawn so that performance metrics can be collected by // Flutter performance tests. // This was supported in KitKat (API 19), but has a bug around requiring // permissions. See https://github.com/flutter/flutter/issues/46172 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { reportFullyDrawn(); } } @Override public void onFlutterUiNoLongerDisplayed() { // no-op } /** * Registers all plugins that an app lists in its pubspec.yaml. * * <p>The Flutter tool generates a class called GeneratedPluginRegistrant, which includes the code * necessary to register every plugin in the pubspec.yaml with a given {@code FlutterEngine}. The * GeneratedPluginRegistrant must be generated per app, because each app uses different sets of * plugins. Therefore, the Android embedding cannot place a compile-time dependency on this * generated class. This method uses reflection to attempt to locate the generated file and then * use it at runtime. * * <p>This method fizzles if the GeneratedPluginRegistrant cannot be found or invoked. This * situation should never occur, but if any eventuality comes up that prevents an app from using * this behavior, that app can still write code that explicitly registers plugins. */ private static void registerPlugins(@NonNull FlutterEngine flutterEngine) { try { Class<?> generatedPluginRegistrant = Class.forName("io.flutter.plugins.GeneratedPluginRegistrant"); Method registrationMethod = generatedPluginRegistrant.getDeclaredMethod("registerWith", FlutterEngine.class); registrationMethod.invoke(null, flutterEngine); } catch (Exception e) { Log.w( TAG, "Tried to automatically register plugins with FlutterEngine (" + flutterEngine + ") but could not find and invoke the GeneratedPluginRegistrant."); } } }
bsd-3-clause
sordonia/rnn-lm
utils.py
6328
import numpy import adam import theano import theano.tensor as T from collections import OrderedDict PRINT_VARS = True def DPrint(name, var): if PRINT_VARS is False: return var return theano.printing.Print(name)(var) def sharedX(value, name=None, borrow=False, dtype=None): if dtype is None: dtype = theano.config.floatX return theano.shared(theano._asarray(value, dtype=dtype), name=name, borrow=borrow) def Adam(grads, lr=0.0002, b1=0.1, b2=0.001, e=1e-8): return adam.Adam(grads, lr, b1, b2, e) def Adagrad(grads, lr): updates = OrderedDict() for param in grads.keys(): # sum_square_grad := \sum g^2 sum_square_grad = sharedX(param.get_value() * 0.) if param.name is not None: sum_square_grad.name = 'sum_square_grad_' + param.name # Accumulate gradient new_sum_squared_grad = sum_square_grad + T.sqr(grads[param]) # Compute update delta_x_t = (- lr / T.sqrt(numpy.float32(1e-5) + new_sum_squared_grad)) * grads[param] # Apply update updates[sum_square_grad] = new_sum_squared_grad updates[param] = param + delta_x_t return updates def Adadelta(grads, decay=0.95, epsilon=1e-6): updates = OrderedDict() for param in grads.keys(): # mean_squared_grad := E[g^2]_{t-1} mean_square_grad = sharedX(param.get_value() * 0.) # mean_square_dx := E[(\Delta x)^2]_{t-1} mean_square_dx = sharedX(param.get_value() * 0.) if param.name is not None: mean_square_grad.name = 'mean_square_grad_' + param.name mean_square_dx.name = 'mean_square_dx_' + param.name # Accumulate gradient new_mean_squared_grad = ( decay * mean_square_grad + (1 - decay) * T.sqr(grads[param]) ) # Compute update rms_dx_tm1 = T.sqrt(mean_square_dx + epsilon) rms_grad_t = T.sqrt(new_mean_squared_grad + epsilon) delta_x_t = - rms_dx_tm1 / rms_grad_t * grads[param] # Accumulate updates new_mean_square_dx = ( decay * mean_square_dx + (1 - decay) * T.sqr(delta_x_t) ) # Apply update updates[mean_square_grad] = new_mean_squared_grad updates[mean_square_dx] = new_mean_square_dx updates[param] = param + delta_x_t return updates def RMSProp(grads, lr, decay=0.95, eta=0.9, epsilon=1e-6): """ RMSProp gradient method """ updates = OrderedDict() for param in grads.keys(): # mean_squared_grad := E[g^2]_{t-1} mean_square_grad = sharedX(param.get_value() * 0.) mean_grad = sharedX(param.get_value() * 0.) delta_grad = sharedX(param.get_value() * 0.) if param.name is None: raise ValueError("Model parameters must be named.") mean_square_grad.name = 'mean_square_grad_' + param.name # Accumulate gradient new_mean_grad = (decay * mean_grad + (1 - decay) * grads[param]) new_mean_squared_grad = (decay * mean_square_grad + (1 - decay) * T.sqr(grads[param])) # Compute update scaled_grad = grads[param] / T.sqrt(new_mean_squared_grad - new_mean_grad ** 2 + epsilon) new_delta_grad = eta * delta_grad - lr * scaled_grad # Apply update updates[delta_grad] = new_delta_grad updates[mean_grad] = new_mean_grad updates[mean_square_grad] = new_mean_squared_grad updates[param] = param + new_delta_grad return updates class Maxout(object): def __init__(self, maxout_part): self.maxout_part = maxout_part def __call__(self, x): shape = x.shape if x.ndim == 2: shape1 = T.cast(shape[1] / self.maxout_part, 'int64') shape2 = T.cast(self.maxout_part, 'int64') x = x.reshape([shape[0], shape1, shape2]) x = x.max(2) else: shape1 = T.cast(shape[2] / self.maxout_part, 'int64') shape2 = T.cast(self.maxout_part, 'int64') x = x.reshape([shape[0], shape[1], shape1, shape2]) x = x.max(3) return x def UniformInit(rng, sizeX, sizeY, lb=-0.01, ub=0.01): """ Uniform Init """ return rng.uniform(size=(sizeX, sizeY), low=lb, high=ub).astype(theano.config.floatX) def OrthogonalInit(rng, sizeX, sizeY, sparsity=-1, scale=1): """ Orthogonal Initialization """ sizeX = int(sizeX) sizeY = int(sizeY) assert sizeX == sizeY, 'for orthogonal init, sizeX == sizeY' if sparsity < 0: sparsity = sizeY else: sparsity = numpy.minimum(sizeY, sparsity) values = numpy.zeros((sizeX, sizeY), dtype=theano.config.floatX) for dx in xrange(sizeX): perm = rng.permutation(sizeY) new_vals = rng.normal(loc=0, scale=scale, size=(sparsity,)) values[dx, perm[:sparsity]] = new_vals u,s,v = numpy.linalg.svd(values) values = u * scale return values.astype(theano.config.floatX) def GrabProbs(classProbs, target, gRange=None): if classProbs.ndim > 2: classProbs = classProbs.reshape((classProbs.shape[0] * classProbs.shape[1], classProbs.shape[2])) else: classProbs = classProbs if target.ndim > 1: tflat = target.flatten() else: tflat = target return T.diag(classProbs.T[tflat]) def NormalInit(rng, sizeX, sizeY, scale=0.01, sparsity=-1): """ Normal Initialization """ sizeX = int(sizeX) sizeY = int(sizeY) if sparsity < 0: sparsity = sizeY sparsity = numpy.minimum(sizeY, sparsity) values = numpy.zeros((sizeX, sizeY), dtype=theano.config.floatX) for dx in xrange(sizeX): perm = rng.permutation(sizeY) new_vals = rng.normal(loc=0, scale=scale, size=(sparsity,)) values[dx, perm[:sparsity]] = new_vals return values.astype(theano.config.floatX) def ConvertTimedelta(seconds_diff): hours = seconds_diff // 3600 minutes = (seconds_diff % 3600) // 60 seconds = (seconds_diff % 60) return hours, minutes, seconds def SoftMax(x): x = T.exp(x - T.max(x, axis=x.ndim-1, keepdims=True)) return x / T.sum(x, axis=x.ndim-1, keepdims=True)
bsd-3-clause
verma/PDAL
src/drivers/nitf/NitfFile.hpp
3261
/****************************************************************************** * Copyright (c) 2012, Michael P. Gerlek (mpg@flaxen.com) * * 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 Hobu, Inc. or Flaxen Consulting LLC 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. ****************************************************************************/ #ifndef INCLUDED_DRIVERS_NITF_FILE_HPP #define INCLUDED_DRIVERS_NITF_FILE_HPP #include <pdal/pdal_internal.hpp> #ifdef PDAL_HAVE_GDAL #include <vector> #include "nitflib.h" namespace pdal { class Metadata; namespace metadata { class Entry; } } namespace pdal { namespace drivers { namespace nitf { // // all the processing that is NITF-file specific goes in here // class PDAL_DLL NitfFile { public: NitfFile(const std::string& filename); ~NitfFile(); void open(); void close(); void getLasPosition(boost::uint64_t& offset, boost::uint64_t& length) const; void extractMetadata(pdal::Metadata& m); private: std::string getSegmentIdentifier(NITFSegmentInfo* psSegInfo); std::string getDESVER(NITFSegmentInfo* psSegInfo); int findIMSegment(); int findLIDARASegment(); static void processTREs(int nTREBytes, const char *pszTREData, pdal::Metadata& m, const std::string& parentkey); static void processTREs_DES(NITFDES*, pdal::Metadata& m, const std::string& parentkey); static void processMetadata(char** papszMetadata, pdal::Metadata& m, const std::string& parentkey); void processImageInfo(pdal::Metadata& m, const std::string& parentkey); const std::string m_filename; NITFFile* m_file; int m_imageSegmentNumber; int m_lidarSegmentNumber; NitfFile(const NitfFile&); // nope NitfFile& operator=(const NitfFile&); // nope }; } } } // namespaces #endif #endif
bsd-3-clause
aYukiSekiguchi/ACCESS-Chromium
chrome/test/perf/sunspider_uitest.cc
4177
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "base/file_util.h" #include "base/json/json_value_serializer.h" #include "base/path_service.h" #include "base/string_util.h" #include "base/test/test_timeouts.h" #include "base/utf_string_conversions.h" #include "base/values.h" #include "chrome/common/chrome_paths.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/perf/perf_test.h" #include "chrome/test/ui/javascript_test_util.h" #include "chrome/test/ui/ui_perf_test.h" #include "googleurl/src/gurl.h" #include "net/base/net_util.h" namespace { static const FilePath::CharType kStartFile[] = FILE_PATH_LITERAL("sunspider-driver.html"); const char kRunSunSpider[] = "run-sunspider"; class SunSpiderTest : public UIPerfTest { public: typedef std::map<std::string, std::string> ResultsMap; SunSpiderTest() : reference_(false) { dom_automation_enabled_ = true; show_window_ = true; } void RunTest() { FilePath::StringType start_file(kStartFile); FilePath test_path = GetSunSpiderDir(); test_path = test_path.Append(start_file); GURL test_url(net::FilePathToFileURL(test_path)); scoped_refptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab.get()); ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS, tab->NavigateToURL(test_url)); // Wait for the test to finish. ASSERT_TRUE(WaitUntilTestCompletes(tab.get(), test_url)); PrintResults(tab.get()); } protected: bool reference_; // True if this is a reference build. private: // Return the path to the SunSpider directory on the local filesystem. FilePath GetSunSpiderDir() { FilePath test_dir; PathService::Get(chrome::DIR_TEST_DATA, &test_dir); return test_dir.AppendASCII("sunspider"); } bool WaitUntilTestCompletes(TabProxy* tab, const GURL& test_url) { return WaitUntilCookieValue(tab, test_url, "__done", TestTimeouts::large_test_timeout_ms(), "1"); } bool GetTotal(TabProxy* tab, std::string* total) { std::wstring total_wide; bool succeeded = tab->ExecuteAndExtractString(L"", L"window.domAutomationController.send(automation.GetTotal());", &total_wide); // Note that we don't use ASSERT_TRUE here (and in some other places) as it // doesn't work inside a function with a return type other than void. EXPECT_TRUE(succeeded); if (!succeeded) return false; total->assign(WideToUTF8(total_wide)); return true; } bool GetResults(TabProxy* tab, ResultsMap* results) { std::wstring json_wide; bool succeeded = tab->ExecuteAndExtractString(L"", L"window.domAutomationController.send(" L" JSON.stringify(automation.GetResults()));", &json_wide); EXPECT_TRUE(succeeded); if (!succeeded) return false; std::string json = WideToUTF8(json_wide); return JsonDictionaryToMap(json, results); } void PrintResults(TabProxy* tab) { std::string total; ASSERT_TRUE(GetTotal(tab, &total)); ResultsMap results; ASSERT_TRUE(GetResults(tab, &results)); std::string trace_name = reference_ ? "t_ref" : "t"; perf_test::PrintResultMeanAndError("total", "", trace_name, total, "ms", true); ResultsMap::const_iterator it = results.begin(); for (; it != results.end(); ++it) perf_test::PrintResultList(it->first, "", trace_name, it->second, "ms", false); } DISALLOW_COPY_AND_ASSIGN(SunSpiderTest); }; class SunSpiderReferenceTest : public SunSpiderTest { public: SunSpiderReferenceTest() : SunSpiderTest() { reference_ = true; } void SetUp() { UseReferenceBuild(); SunSpiderTest::SetUp(); } }; TEST_F(SunSpiderTest, Perf) { if (!CommandLine::ForCurrentProcess()->HasSwitch(kRunSunSpider)) return; RunTest(); } TEST_F(SunSpiderReferenceTest, Perf) { if (!CommandLine::ForCurrentProcess()->HasSwitch(kRunSunSpider)) return; RunTest(); } } // namespace
bsd-3-clause
patriziotufarolo/ispconfig
interface/lib/classes/db_mysql.inc.php
22699
<?php /* Copyright (c) 2005, Till Brehm, projektfarm Gmbh 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 ISPConfig 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. */ class db extends mysqli { private $dbHost = ''; // hostname of the MySQL server private $dbName = ''; // logical database name on that server private $dbUser = ''; // database authorized user private $dbPass = ''; // user's password private $dbCharset = 'utf8';// Database charset private $dbNewLink = false; // Return a new linkID when connect is called again private $dbClientFlags = 0; // MySQL Client falgs private $linkId = 0; // last result of mysqli_connect() private $queryId = 0; // last result of mysqli_query() private $record = array(); // last record fetched private $autoCommit = 1; // Autocommit Transactions private $currentRow; // current row number private $errorNumber = 0; // last error number public $errorMessage = ''; // last error message private $errorLocation = '';// last error location public $show_error_messages = false; // false in server, true in interface private $isConnected = false; // needed to know if we have a valid mysqli object from the constructor // constructor public function __construct($prefix = '') { global $conf; if($prefix != '') $prefix .= '_'; $this->dbHost = $conf[$prefix.'db_host']; $this->dbName = $conf[$prefix.'db_database']; $this->dbUser = $conf[$prefix.'db_user']; $this->dbPass = $conf[$prefix.'db_password']; $this->dbCharset = $conf[$prefix.'db_charset']; $this->dbNewLink = $conf[$prefix.'db_new_link']; $this->dbClientFlags = $conf[$prefix.'db_client_flags']; parent::__construct($conf[$prefix.'db_host'], $conf[$prefix.'db_user'], $conf[$prefix.'db_password'], $conf[$prefix.'db_database']); $try = 0; //while(!is_null($this->connect_error) && $try < 5) { while(mysqli_connect_error() && $try < 5) { if($try > 0) sleep(1); $try++; $this->updateError('DB::__construct'); parent::__construct($conf[$prefix.'db_host'], $conf[$prefix.'db_user'], $conf[$prefix.'db_password'], $conf[$prefix.'db_database']); } //if(is_null($this->connect_error)) $this->isConnected = true; //else return false; if(!mysqli_connect_error()) $this->isConnected = true; else return false; $this->setCharacterEncoding(); } public function __destruct() { $this->close(); // helps avoid memory leaks, and persitent connections that don't go away. } // error handler public function updateError($location) { global $app, $conf; /* if(!is_null($this->connect_error)) { $this->errorNumber = $this->connect_errno; $this->errorMessage = $this->connect_error; } else { $this->errorNumber = $this->errno; $this->errorMessage = $this->error; } */ if(mysqli_connect_error()) { $this->errorNumber = mysqli_connect_errno(); $this->errorMessage = mysqli_connect_error(); } else { $this->errorNumber = mysqli_errno($this); $this->errorMessage = mysqli_error($this); } $this->errorLocation = $location; if($this->errorNumber) { $error_msg = $this->errorLocation .' '. $this->errorMessage; // This right here will allow us to use the same file for server & interface if($this->show_error_messages && $conf['demo_mode'] === false) { echo $error_msg; } else if(is_object($app) && method_exists($app, 'log')) { $app->log($error_msg, LOGLEVEL_WARN); } } } private function setCharacterEncoding() { if($this->isConnected == false) return false; parent::query( 'SET NAMES '.$this->dbCharset); parent::query( "SET character_set_results = '".$this->dbCharset."', character_set_client = '".$this->dbCharset."', character_set_connection = '".$this->dbCharset."', character_set_database = '".$this->dbCharset."', character_set_server = '".$this->dbCharset."'"); } public function query($queryString) { global $conf; if($this->isConnected == false) return false; $try = 0; do { $try++; $ok = $this->ping(); if(!$ok) { if(!$this->real_connect($this->dbHost, $this->dbUser, $this->dbPass, $this->dbName)) { if($try > 4) { $this->updateError('DB::query -> reconnect'); return false; } else { sleep(1); } } else { $this->setCharacterEncoding(); $ok = true; } } } while($ok == false); $this->queryId = parent::query($queryString); $this->updateError('DB::query('.$queryString.') -> mysqli_query'); if($this->errorNumber && $conf['demo_mode'] === false) debug_print_backtrace(); if(!$this->queryId) { return false; } $this->currentRow = 0; return $this->queryId; } // returns all records in an array public function queryAllRecords($queryString) { if(!$this->query($queryString)) { return false; } $ret = array(); while($line = $this->nextRecord()) { $ret[] = $line; } return $ret; } // returns one record in an array public function queryOneRecord($queryString) { if(!$this->query($queryString) || $this->numRows() == 0) { return false; } return $this->nextRecord(); } // returns the next record in an array public function nextRecord() { $this->record = $this->queryId->fetch_assoc(); $this->updateError('DB::nextRecord()-> mysql_fetch_array'); if(!$this->record || !is_array($this->record)) { return false; } $this->currentRow++; return $this->record; } // returns number of rows returned by the last select query public function numRows() { return intval($this->queryId->num_rows); } public function affectedRows() { return intval($this->queryId->affected_rows); } // returns mySQL insert id public function insertID() { return $this->insert_id; } //* Function to quote strings public function quote($formfield) { return $this->escape_string($formfield); } //* Function to unquotae strings public function unquote($formfield) { return stripslashes($formfield); } public function toLower($record) { if(is_array($record)) { foreach($record as $key => $val) { $key = strtolower($key); $out[$key] = $val; } } return $out; } public function diffrec($record_old, $record_new) { $diffrec_full = array(); $diff_num = 0; if(is_array($record_old) && count($record_old) > 0) { foreach($record_old as $key => $val) { // if(!isset($record_new[$key]) || $record_new[$key] != $val) { if(@$record_new[$key] != $val) { // Record has changed $diffrec_full['old'][$key] = $val; $diffrec_full['new'][$key] = @$record_new[$key]; $diff_num++; } else { $diffrec_full['old'][$key] = $val; $diffrec_full['new'][$key] = $val; } } } elseif(is_array($record_new)) { foreach($record_new as $key => $val) { if(isset($record_new[$key]) && @$record_old[$key] != $val) { // Record has changed $diffrec_full['new'][$key] = $val; $diffrec_full['old'][$key] = @$record_old[$key]; $diff_num++; } else { $diffrec_full['new'][$key] = $val; $diffrec_full['old'][$key] = $val; } } } return array('diff_num' => $diff_num, 'diff_rec' => $diffrec_full); } //** Function to fill the datalog with a full differential record. public function datalogSave($db_table, $action, $primary_field, $primary_id, $record_old, $record_new, $force_update = false) { global $app, $conf; // Check fields if(!preg_match('/^[a-zA-Z0-9\-\_\.]{1,64}$/',$db_table)) $app->error('Invalid table name '.$db_table); if(!preg_match('/^[a-zA-Z0-9\-\_]{1,64}$/',$primary_field)) $app->error('Invalid primary field '.$primary_field.' in table '.$db_table); $primary_field = $this->quote($primary_field); $primary_id = intval($primary_id); if($force_update == true) { //* We force a update even if no record has changed $diffrec_full = array('new' => $record_new, 'old' => $record_old); $diff_num = count($record_new); } else { //* get the difference record between old and new record $tmp = $this->diffrec($record_old, $record_new); $diffrec_full = $tmp['diff_rec']; $diff_num = $tmp['diff_num']; unset($tmp); } // Insert the server_id, if the record has a server_id $server_id = (isset($record_old['server_id']) && $record_old['server_id'] > 0)?$record_old['server_id']:0; if(isset($record_new['server_id'])) $server_id = $record_new['server_id']; $server_id = intval($server_id); if($diff_num > 0) { //print_r($diff_num); //print_r($diffrec_full); $diffstr = $app->db->quote(serialize($diffrec_full)); $username = $app->db->quote($_SESSION['s']['user']['username']); $dbidx = $primary_field.':'.$primary_id; if($action == 'INSERT') $action = 'i'; if($action == 'UPDATE') $action = 'u'; if($action == 'DELETE') $action = 'd'; $sql = "INSERT INTO sys_datalog (dbtable,dbidx,server_id,action,tstamp,user,data) VALUES ('".$db_table."','$dbidx','$server_id','$action','".time()."','$username','$diffstr')"; $app->db->query($sql); } return true; } //** Inserts a record and saves the changes into the datalog public function datalogInsert($tablename, $insert_data, $index_field) { global $app; // Check fields if(!preg_match('/^[a-zA-Z0-9\-\_\.]{1,64}$/',$tablename)) $app->error('Invalid table name '.$tablename); if(!preg_match('/^[a-zA-Z0-9\-\_]{1,64}$/',$index_field)) $app->error('Invalid index field '.$index_field.' in table '.$tablename); if(strpos($tablename, '.') !== false) { $tablename_escaped = preg_replace('/^(.+)\.(.+)$/', '`$1`.`$2`', $tablename); } else { $tablename_escaped = '`' . $tablename . '`'; } $index_field = $this->quote($index_field); if(is_array($insert_data)) { $key_str = ''; $val_str = ''; foreach($insert_data as $key => $val) { $key_str .= "`".$key ."`,"; $val_str .= "'".$this->quote($val)."',"; } $key_str = substr($key_str, 0, -1); $val_str = substr($val_str, 0, -1); $insert_data_str = '('.$key_str.') VALUES ('.$val_str.')'; } else { $insert_data_str = $insert_data; } $old_rec = array(); $this->query("INSERT INTO $tablename_escaped $insert_data_str"); $index_value = $this->insertID(); $new_rec = $this->queryOneRecord("SELECT * FROM $tablename_escaped WHERE $index_field = '$index_value'"); $this->datalogSave($tablename, 'INSERT', $index_field, $index_value, $old_rec, $new_rec); return $index_value; } //** Updates a record and saves the changes into the datalog public function datalogUpdate($tablename, $update_data, $index_field, $index_value, $force_update = false) { global $app; // Check fields if(!preg_match('/^[a-zA-Z0-9\-\_\.]{1,64}$/',$tablename)) $app->error('Invalid table name '.$tablename); if(!preg_match('/^[a-zA-Z0-9\-\_]{1,64}$/',$index_field)) $app->error('Invalid index field '.$index_field.' in table '.$tablename); if(strpos($tablename, '.') !== false) { $tablename_escaped = preg_replace('/^(.+)\.(.+)$/', '`$1`.`$2`', $tablename); } else { $tablename_escaped = '`' . $tablename . '`'; } $index_field = $this->quote($index_field); $index_value = $this->quote($index_value); $old_rec = $this->queryOneRecord("SELECT * FROM $tablename_escaped WHERE $index_field = '$index_value'"); if(is_array($update_data)) { $update_data_str = ''; foreach($update_data as $key => $val) { $update_data_str .= "`".$key ."` = '".$this->quote($val)."',"; } $update_data_str = substr($update_data_str, 0, -1); } else { $update_data_str = $update_data; } $this->query("UPDATE $tablename_escaped SET $update_data_str WHERE $index_field = '$index_value'"); $new_rec = $this->queryOneRecord("SELECT * FROM $tablename_escaped WHERE $index_field = '$index_value'"); $this->datalogSave($tablename, 'UPDATE', $index_field, $index_value, $old_rec, $new_rec, $force_update); return true; } //** Deletes a record and saves the changes into the datalog public function datalogDelete($tablename, $index_field, $index_value) { global $app; // Check fields if(!preg_match('/^[a-zA-Z0-9\-\_\.]{1,64}$/',$tablename)) $app->error('Invalid table name '.$tablename); if(!preg_match('/^[a-zA-Z0-9\-\_]{1,64}$/',$index_field)) $app->error('Invalid index field '.$index_field.' in table '.$tablename); if(strpos($tablename, '.') !== false) { $tablename_escaped = preg_replace('/^(.+)\.(.+)$/', '`$1`.`$2`', $tablename); } else { $tablename_escaped = '`' . $tablename . '`'; } $index_field = $this->quote($index_field); $index_value = $this->quote($index_value); $old_rec = $this->queryOneRecord("SELECT * FROM $tablename_escaped WHERE $index_field = '$index_value'"); $this->query("DELETE FROM $tablename_escaped WHERE $index_field = '$index_value'"); $new_rec = array(); $this->datalogSave($tablename, 'DELETE', $index_field, $index_value, $old_rec, $new_rec); return true; } //* get the current datalog status for the specified login (or currently logged in user) public function datalogStatus($login = '') { global $app; $return = array('count' => 0, 'entries' => array()); if($_SESSION['s']['user']['typ'] == 'admin') return $return; // these information should not be displayed to admin users if($login == '' && isset($_SESSION['s']['user'])) { $login = $_SESSION['s']['user']['username']; } $result = $this->queryAllRecords("SELECT COUNT( * ) AS cnt, sys_datalog.action, sys_datalog.dbtable FROM sys_datalog, server WHERE server.server_id = sys_datalog.server_id AND sys_datalog.user = '" . $this->quote($login) . "' AND sys_datalog.datalog_id > server.updated GROUP BY sys_datalog.dbtable, sys_datalog.action"); foreach($result as $row) { if(!$row['dbtable'] || in_array($row['dbtable'], array('aps_instances', 'aps_instances_settings', 'mail_access', 'mail_content_filter'))) continue; // ignore some entries, maybe more to come $return['entries'][] = array('table' => $row['dbtable'], 'action' => $row['action'], 'count' => $row['cnt'], 'text' => $app->lng('datalog_status_' . $row['action'] . '_' . $row['dbtable'])); $return['count'] += $row['cnt']; } unset($result); return $return; } public function freeResult($query) { if(is_object($query) && (get_class($query) == "mysqli_result")) { $query->free(); return true; } else { return false; } } /* TODO: Does anything use this? */ public function delete() { } /* TODO: Does anything use this? */ public function Transaction($action) { //action = begin, commit oder rollback } /* $columns = array(action => add | alter | drop name => Spaltenname name_new => neuer Spaltenname, nur bei 'alter' belegt type => 42go-Meta-Type: int16, int32, int64, double, char, varchar, text, blob typeValue => Wert z.B. bei Varchar defaultValue => Default Wert notNull => true | false autoInc => true | false option => unique | primary | index) */ public function createTable($table_name, $columns) { $index = ''; $sql = "CREATE TABLE $table_name ("; foreach($columns as $col){ $sql .= $col['name'].' '.$this->mapType($col['type'], $col['typeValue']).' '; if($col['defaultValue'] != '') $sql .= "DEFAULT '".$col['defaultValue']."' "; if($col['notNull'] == true) { $sql .= 'NOT NULL '; } else { $sql .= 'NULL '; } if($col['autoInc'] == true) $sql .= 'auto_increment '; $sql.= ','; // key Definitionen if($col['option'] == 'primary') $index .= 'PRIMARY KEY ('.$col['name'].'),'; if($col['option'] == 'index') $index .= 'INDEX ('.$col['name'].'),'; if($col['option'] == 'unique') $index .= 'UNIQUE ('.$col['name'].'),'; } $sql .= $index; $sql = substr($sql, 0, -1); $sql .= ')'; $this->query($sql); return true; } /* $columns = array(action => add | alter | drop name => Spaltenname name_new => neuer Spaltenname, nur bei 'alter' belegt type => 42go-Meta-Type: int16, int32, int64, double, char, varchar, text, blob typeValue => Wert z.B. bei Varchar defaultValue => Default Wert notNull => true | false autoInc => true | false option => unique | primary | index) */ public function alterTable($table_name, $columns) { $index = ''; $sql = "ALTER TABLE $table_name "; foreach($columns as $col){ if($col['action'] == 'add') { $sql .= 'ADD '.$col['name'].' '.$this->mapType($col['type'], $col['typeValue']).' '; } elseif ($col['action'] == 'alter') { $sql .= 'CHANGE '.$col['name'].' '.$col['name_new'].' '.$this->mapType($col['type'], $col['typeValue']).' '; } elseif ($col['action'] == 'drop') { $sql .= 'DROP '.$col['name'].' '; } if($col['action'] != 'drop') { if($col['defaultValue'] != '') $sql .= "DEFAULT '".$col['defaultValue']."' "; if($col['notNull'] == true) { $sql .= 'NOT NULL '; } else { $sql .= 'NULL '; } if($col['autoInc'] == true) $sql .= 'auto_increment '; $sql.= ','; // Index definitions if($col['option'] == 'primary') $index .= 'PRIMARY KEY ('.$col['name'].'),'; if($col['option'] == 'index') $index .= 'INDEX ('.$col['name'].'),'; if($col['option'] == 'unique') $index .= 'UNIQUE ('.$col['name'].'),'; } } $sql .= $index; $sql = substr($sql, 0, -1); //die($sql); $this->query($sql); return true; } public function dropTable($table_name) { $this->check($table_name); $sql = "DROP TABLE '". $table_name."'"; return $this->query($sql); } // gibt Array mit Tabellennamen zur�ck public function getTables($database_name = '') { if($this->isConnected == false) return false; if($database_name == '') $database_name = $this->dbName; $result = parent::query("SHOW TABLES FROM $database_name"); for ($i = 0; $i < $result->num_rows; $i++) { $tb_names[$i] = (($result->data_seek( $i) && (($___mysqli_tmp = $result->fetch_row()) !== NULL)) ? array_shift($___mysqli_tmp) : false); } return $tb_names; } // gibt Feldinformationen zur Tabelle zur�ck /* $columns = array(action => add | alter | drop name => Spaltenname name_new => neuer Spaltenname, nur bei 'alter' belegt type => 42go-Meta-Type: int16, int32, int64, double, char, varchar, text, blob typeValue => Wert z.B. bei Varchar defaultValue => Default Wert notNull => true | false autoInc => true | false option => unique | primary | index) */ function tableInfo($table_name) { global $go_api, $go_info, $app; // Tabellenfelder einlesen if($rows = $app->db->queryAllRecords('SHOW FIELDS FROM '.$table_name)){ foreach($rows as $row) { /* $name = $row[0]; $default = $row[4]; $key = $row[3]; $extra = $row[5]; $isnull = $row[2]; $type = $row[1]; */ $name = $row['Field']; $default = $row['Default']; $key = $row['Key']; $extra = $row['Extra']; $isnull = $row['Null']; $type = $row['Type']; $column = array(); $column['name'] = $name; //$column['type'] = $type; $column['defaultValue'] = $default; if(stristr($key, 'PRI')) $column['option'] = 'primary'; if(stristr($isnull, 'YES')) { $column['notNull'] = false; } else { $column['notNull'] = true; } if($extra == 'auto_increment') $column['autoInc'] = true; // Type in Metatype umsetzen if(stristr($type, 'int(')) $metaType = 'int32'; if(stristr($type, 'bigint')) $metaType = 'int64'; if(stristr($type, 'char')) { $metaType = 'char'; $tmp_typeValue = explode('(', $type); $column['typeValue'] = substr($tmp_typeValue[1], 0, -1); } if(stristr($type, 'varchar')) { $metaType = 'varchar'; $tmp_typeValue = explode('(', $type); $column['typeValue'] = substr($tmp_typeValue[1], 0, -1); } if(stristr($type, 'text')) $metaType = 'text'; if(stristr($type, 'double')) $metaType = 'double'; if(stristr($type, 'blob')) $metaType = 'blob'; $column['type'] = $metaType; $columns[] = $column; } return $columns; } else { return false; } //$this->createTable('tester',$columns); /* $result = mysql_list_fields($go_info["server"]["db_name"],$table_name); $fields = mysql_num_fields ($result); $i = 0; $table = mysql_field_table ($result, $i); while ($i < $fields) { $name = mysql_field_name ($result, $i); $type = mysql_field_type ($result, $i); $len = mysql_field_len ($result, $i); $flags = mysql_field_flags ($result, $i); print_r($flags); $columns = array(name => $name, type => "", defaultValue => "", isnull => 1, option => ""); $returnvar[] = $columns; $i++; } */ } public function mapType($metaType, $typeValue) { global $go_api; $metaType = strtolower($metaType); switch ($metaType) { case 'int16': return 'smallint'; break; case 'int32': return 'int'; break; case 'int64': return 'bigint'; break; case 'double': return 'double'; break; case 'char': return 'char'; break; case 'varchar': if($typeValue < 1) die('Database failure: Lenght required for these data types.'); return 'varchar('.$typeValue.')'; break; case 'text': return 'text'; break; case 'blob': return 'blob'; break; case 'date': return 'date'; break; } } } ?>
bsd-3-clause
Bomberlt/fhir-net-api
src/Hl7.Fhir.Specification/XPath/JsonXPathNavigator.cs
16147
/* * Copyright (c) 2014, Furore (info@furore.com) and contributors * See the file CONTRIBUTORS for details. * * This file is licensed under the BSD 3-Clause license */ using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; using System.Xml.XPath; using Hl7.Fhir.Support; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Hl7.Fhir.XPath { public class JsonXPathNavigator : XPathNavigator, IXPathNavigable { public const string FHIR_PREFIX = "f"; public const string XHTML_PREFIX = "html"; public const string XML_PREFIX = "xml"; public const string SPEC_CHILD_ID = "id"; public const string SPEC_CHILD_URL = "url"; public const string SPEC_CHILD_CONTENTTYPE = "contentType"; public const string SPEC_CHILD_CONTENT = "content"; private const string SPEC_CHILD_VALUE = "value"; private const string ROOT_PROP_NAME = "(root)"; private readonly NameTable _nameTable = new NameTable(); private readonly Stack<NavigatorState> _state = new Stack<NavigatorState>(); private NavigatorState position { get { return _state.Peek(); } } public JsonXPathNavigator(JsonReader reader) { reader.DateParseHandling = DateParseHandling.None; reader.FloatParseHandling = FloatParseHandling.Decimal; try { var docChild = (JObject)JObject.Load(reader); // Add symbolic 'root' child, so initially, we are at a virtual "root" element, just like in the DOM model var root = new JProperty(ROOT_PROP_NAME, docChild); _state.Push(new NavigatorState(root)); } catch (Exception e) { throw new FormatException("Cannot parse json: " + e.Message); } _nameTable.Add(XmlNs.FHIR); _nameTable.Add(XmlNs.XHTML); _nameTable.Add(XmlNs.NAMESPACE); _nameTable.Add(String.Empty); _nameTable.Add(FHIR_PREFIX); _nameTable.Add(XML_PREFIX); _nameTable.Add(XHTML_PREFIX); _nameTable.Add(SPEC_CHILD_VALUE); } public JsonXPathNavigator(JsonXPathNavigator source) { copyState(source._state); _nameTable = source._nameTable; } private IEnumerable<JProperty> elementChildren() { return position.Children.Where(c => !isAttribute(c)); } private IEnumerable<JProperty> attributeChildren() { return position.Children.Where(c => isAttribute(c)); } private Lazy<List<Tuple<string,string>>> _namespaces = new Lazy<List<Tuple<string,string>>>( () => new List<Tuple<string,string>>() { Tuple.Create(FHIR_PREFIX,XmlNs.FHIR), Tuple.Create(XHTML_PREFIX,XmlNs.XHTML), // Tuple.Create(XML_PREFIX,XML_NS), }); private IEnumerable<Tuple<string,string>> namespaceChildren() { //switch (scope) //{ // case XPathNamespaceScope.All: // return _namespaces.Value; // case XPathNamespaceScope.ExcludeXml: // return _namespaces.Value.Where(ns => ns.Item1 != "xml"); // case XPathNamespaceScope.Local: // if (position.Element.Name == "Patient") // return _namespaces.Value; // else // return new List<Tuple<string, string>>(); // default: // break; //} return _namespaces.Value; } private bool isAttribute(JProperty property) { return property.IsValueProperty() || property.Name == SPEC_CHILD_ID || // id attr that all types can have (property.Name == SPEC_CHILD_URL && position.Element.Name == "extension") || // url attr of extension (property.Name == SPEC_CHILD_URL && position.Element.Name == "modifierExtension") || // url attr of modifierExtension parent (property.Name == SPEC_CHILD_CONTENTTYPE && position.Element.Name == "Binary"); // contentType attr of Binary resource } private bool isTextNode(JProperty prop) { return prop.Name == SPEC_CHILD_CONTENT; // && position.Element.Name == "Binary"; } private void copyState(IEnumerable<NavigatorState> other) { _state.Clear(); foreach (var state in other.Reverse()) { _state.Push(state.Copy()); } } public override string BaseURI { get { return _nameTable.Get(String.Empty); } } public override XPathNavigator Clone() { return new JsonXPathNavigator(this); } public override bool IsSamePosition(XPathNavigator nav) { var other = nav as JsonXPathNavigator; if (other == null) return false; return _state.SequenceEqual(other._state); } public override bool MoveTo(XPathNavigator other) { var xpn = other as JsonXPathNavigator; if (xpn != null) { copyState(xpn._state); return true; } else return false; } public override bool MoveToFirstChild() { if (NodeType == XPathNodeType.Element || NodeType == XPathNodeType.Root) { return moveToElementChild(0); } else return false; } public override bool MoveToNext() { if (NodeType == XPathNodeType.Element || NodeType == XPathNodeType.Text) return tryMoveToSibling(1); else return false; } public override bool MoveToPrevious() { if (NodeType == XPathNodeType.Element || NodeType == XPathNodeType.Text) return tryMoveToSibling(-1); else return false; } public override bool MoveToParent() { switch(NodeType) { case XPathNodeType.Root: return false; case XPathNodeType.Element: case XPathNodeType.Text: _state.Pop(); return true; case XPathNodeType.Attribute: position.AttributePos = null; return true; case XPathNodeType.Namespace: position.NamespacePos = null; return true; default: return false; } } private bool tryMoveToSibling(int delta) { // Move to the next/prev sibling. This means moving up to the parent, and continue with the next/prev node if (!_state.Any()) return false; // Keep the current state, when we cannot move after we've moved up to the parent, we'll need to stay // where we are var currentState = _state.Pop(); // Can we move? if (NodeType == XPathNodeType.Element || NodeType == XPathNodeType.Text) { var newPos = position.ChildPos.Value + delta; if (newPos >= 0 && newPos < elementChildren().Count()) { moveToElementChild(newPos); return true; } else { // we cannot, roll back to old state _state.Push(currentState); return false; } } else if (NodeType == XPathNodeType.Root) { // we cannot, roll back to old state _state.Push(currentState); return false; } else throw new InvalidOperationException( "Internal logic error: popping state on tryMove does not end up on element"); } private bool moveToElementChild(int index) { var child = elementChildren().Skip(index).FirstOrDefault(); if (child == null) return false; position.ChildPos = index; var newState = new NavigatorState(child); _state.Push(newState); return true; } private bool moveToAttributeChild(int index) { var child = attributeChildren().Skip(index).FirstOrDefault(); if (child == null) return false; position.AttributePos = index; return true; } private bool moveToNamespaceChild(int index, XPathNamespaceScope scope) { if ((scope == XPathNamespaceScope.Local && _state.Count == 2) || scope == XPathNamespaceScope.All) { var child = namespaceChildren().Skip(index).FirstOrDefault(); if (child == null) return false; position.NamespacePos = index; return true; } else return false; } private JProperty currentAttribute { get { if (position.AttributePos != null) { return attributeChildren().Skip(position.AttributePos.Value).First(); } return null; } } private Tuple<string,string> currentNamespace { get { if (position.NamespacePos != null) { return namespaceChildren().Skip(position.NamespacePos.Value).First(); } return null; } } public override bool MoveToId(string id) { throw new NotImplementedException("Sorry, not too important for me"); } public override bool MoveToFirstAttribute() { if (NodeType == XPathNodeType.Element) return moveToAttributeChild(0); else return false; } public override bool MoveToNextAttribute() { if (NodeType == XPathNodeType.Attribute) return moveToAttributeChild(position.AttributePos.Value + 1); else return false; } public override bool MoveToFirstNamespace(XPathNamespaceScope namespaceScope) { if (NodeType == XPathNodeType.Element) { return moveToNamespaceChild(0, namespaceScope); } else return false; } public override bool MoveToNextNamespace(XPathNamespaceScope namespaceScope) { if (NodeType == XPathNodeType.Namespace) return moveToNamespaceChild(position.NamespacePos.Value + 1, namespaceScope); else return false; } private string nt(string val) { return _nameTable.Get(val); } public override bool IsEmptyElement { get { if (NodeType == XPathNodeType.Element || NodeType == XPathNodeType.Root) return !position.Children.Any(); else return false; } } public override string Name { get { var pref = Prefix != String.Empty ? Prefix + ":" : String.Empty; return _nameTable.Add(pref + LocalName); } } public override string LocalName { get { switch (NodeType) { case XPathNodeType.Root: case XPathNodeType.Text: return nt(String.Empty); case XPathNodeType.Element: return _nameTable.Add(position.Element.Name); case XPathNodeType.Attribute: if (currentAttribute.IsValueProperty()) return nt(SPEC_CHILD_VALUE); else return _nameTable.Add(currentAttribute.Name); case XPathNodeType.Namespace: return nt(currentNamespace.Item1); default: throw new NotImplementedException("Don't know how to get LocalName when at node of type " + NodeType.ToString()); } } } public override System.Xml.XmlNameTable NameTable { get { return _nameTable; } } public override string NamespaceURI { get { if (NodeType == XPathNodeType.Element) { // Check for the special <div> element, which comes from the xhtml namespace. Otherwise, // return the FHIR namespace if (LocalName == "div") return nt(XmlNs.XHTML); else return nt(XmlNs.FHIR); } else return nt(String.Empty); } } public override string Prefix { get { if (NodeType == XPathNodeType.Element) { // Check for the special <div> element, which comes from the xhtml namespace. Otherwise, // return the FHIR namespace if (LocalName == "div") return nt(XHTML_PREFIX); else return nt(FHIR_PREFIX); } else return nt(String.Empty); } } public override XPathNodeType NodeType { get { if (position.Element.Name == ROOT_PROP_NAME) return XPathNodeType.Root; else if (isTextNode(position.Element)) return XPathNodeType.Text; else if (position.AttributePos != null) return XPathNodeType.Attribute; else if (position.NamespacePos != null) return XPathNodeType.Namespace; else return XPathNodeType.Element; } } public override string Value { get { if (NodeType == XPathNodeType.Attribute) { if (currentAttribute.IsValueProperty()) return currentAttribute.ElementText(); else { // This is a named attribute (like id and contentType) for which only the // primitive value is relevant, they cannot be extended // Note that ElementText() will join all subnodes (in this case only one) into // one string, so this *currently* works. return currentAttribute.ElementText(); } } else if (NodeType == XPathNodeType.Namespace) { return nt(currentNamespace.Item2); } else return position.Element.ElementText(); } } public override string ToString() { return String.Join("/", _state); } } }
bsd-3-clause
minhtienct/belong_mockup
init_autoloader.php
3464
<?php /** * Zend Framework (http://framework.zend.com/) * * @link http://github.com/zendframework/ZendSkeletonApplication 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 */ /** * This autoloading setup is really more complicated than it needs to be for most * applications. The added complexity is simply to reduce the time it takes for * new developers to be productive with a fresh skeleton. It allows autoloading * to be correctly configured, regardless of the installation method and keeps * the use of composer completely optional. This setup should work fine for * most users, however, feel free to configure autoloading however you'd like. */ // Composer autoloading if (file_exists('vendor/autoload.php')) { $loader = include 'vendor/autoload.php'; } if (class_exists('Zend\Loader\AutoloaderFactory')) { return; } $zf2Path = false; if (getenv('ZF2_PATH')) { // Support for ZF2_PATH environment variable $zf2Path = getenv('ZF2_PATH'); } elseif (get_cfg_var('zf2_path')) { // Support for zf2_path directive value $zf2Path = get_cfg_var('zf2_path'); } if ($zf2Path) { if (isset($loader)) { $loader->add('Zend', $zf2Path); $loader->add('ZendXml', $zf2Path); } else { include $zf2Path . '/Zend/Loader/AutoloaderFactory.php'; Zend\Loader\AutoloaderFactory::factory(array( 'Zend\Loader\StandardAutoloader' => array( 'autoregister_zf' => true ) )); } } if (!class_exists('Zend\Loader\AutoloaderFactory')) { throw new RuntimeException('Unable to load ZF2. Run `php composer.phar install` or define a ZF2_PATH environment variable.'); } //// Composer autoloading //if (file_exists('vendor/autoload.php')) { // $loader = include 'vendor/autoload.php'; //} // //if (class_exists('Zend\Loader\AutoloaderFactory')) { // return; //} // //$zf2Path = false; // //if (is_dir('vendor/ZF2/library')) { // $zf2Path = 'vendor/ZF2/library'; //} elseif (getenv('ZF2_PATH')) { // Support for ZF2_PATH environment variable or git submodule // $zf2Path = getenv('ZF2_PATH'); //} elseif (get_cfg_var('zf2_path')) { // Support for zf2_path directive value // $zf2Path = get_cfg_var('zf2_path'); //} // //if ($zf2Path) { // if (isset($loader)) { // $loader->add('Zend', $zf2Path); // $loader->add('ZendXml', $zf2Path); // } else { // include $zf2Path . '/Zend/Loader/AutoloaderFactory.php'; // Zend\Loader\AutoloaderFactory::factory(array( // 'Zend\Loader\StandardAutoloader' => array( // 'autoregister_zf' => true // ) // )); // } //} // //require_once HOME_DIR . '/vendor/Kdl/library/autoload_classmap.php'; //require_once $zf2Path . '/Zend/Loader/ClassMapAutoloader.php'; //$loader = new Zend\Loader\ClassMapAutoloader(); //$loader->registerAutoloadMap(HOME_DIR . '/vendor/Kdl/library/autoload_classmap.php'); //$loader->register(); // // //if (!class_exists('Kdl\Validator\NotEmpty') || !class_exists('Kdl\Mail\Mailer')) { // throw new RuntimeException('Unable to load Kdl Library'); //} // //if (!class_exists('Zend\Loader\AutoloaderFactory')) { // throw new RuntimeException('Unable to load ZF2. Run `php composer.phar install` or define a ZF2_PATH environment variable.'); //}
bsd-3-clause
Gustik/yii2-app-light
views/site/resetPassword.php
872
<?php /* @var $this yii\web\View */ /* @var $form yii\bootstrap\ActiveForm */ /* @var $model \app\models\ResetPasswordForm */ use yii\helpers\Html; use yii\bootstrap\ActiveForm; $this->title = 'Восстановление пароля'; $this->params['breadcrumbs'][] = $this->title; ?> <div class="site-reset-password"> <h1><?= Html::encode($this->title) ?></h1> <p>Введите новый пароль:</p> <div class="row"> <div class="col-lg-5"> <?php $form = ActiveForm::begin(['id' => 'reset-password-form']); ?> <?= $form->field($model, 'password')->passwordInput() ?> <div class="form-group"> <?= Html::submitButton('Сохранить', ['class' => 'btn btn-primary']) ?> </div> <?php ActiveForm::end(); ?> </div> </div> </div>
bsd-3-clause
uwdata/vega-lite
src/compile/selection/interval.ts
8653
import {NewSignal, OnEvent, Stream} from 'vega'; import {array, stringValue} from 'vega-util'; import {SelectionCompiler, SelectionComponent, STORE, TUPLE, unitName} from '.'; import {ScaleChannel, X, Y} from '../../channel'; import {warn} from '../../log'; import {hasContinuousDomain} from '../../scale'; import {SelectionInitInterval} from '../../selection'; import {keys} from '../../util'; import {UnitModel} from '../unit'; import {assembleInit} from './assemble'; import {SelectionProjection, TUPLE_FIELDS} from './project'; import scales from './scales'; export const BRUSH = '_brush'; export const SCALE_TRIGGER = '_scale_trigger'; const interval: SelectionCompiler<'interval'> = { defined: selCmpt => selCmpt.type === 'interval', signals: (model, selCmpt, signals) => { const name = selCmpt.name; const fieldsSg = name + TUPLE_FIELDS; const hasScales = scales.defined(selCmpt); const init = selCmpt.init ? selCmpt.init[0] : null; const dataSignals: string[] = []; const scaleTriggers: { scaleName: string; expr: string; }[] = []; if (selCmpt.translate && !hasScales) { const filterExpr = `!event.item || event.item.mark.name !== ${stringValue(name + BRUSH)}`; events(selCmpt, (on: OnEvent[], evt: Stream) => { const filters = array((evt.between[0].filter ??= [])); if (!filters.includes(filterExpr)) { filters.push(filterExpr); } return on; }); } selCmpt.project.items.forEach((proj, i) => { const channel = proj.channel; if (channel !== X && channel !== Y) { warn('Interval selections only support x and y encoding channels.'); return; } const val = init ? init[i] : null; const cs = channelSignals(model, selCmpt, proj, val); const dname = proj.signals.data; const vname = proj.signals.visual; const scaleName = stringValue(model.scaleName(channel)); const scaleType = model.getScaleComponent(channel).get('type'); const toNum = hasContinuousDomain(scaleType) ? '+' : ''; signals.push(...cs); dataSignals.push(dname); scaleTriggers.push({ scaleName: model.scaleName(channel), expr: `(!isArray(${dname}) || ` + `(${toNum}invert(${scaleName}, ${vname})[0] === ${toNum}${dname}[0] && ` + `${toNum}invert(${scaleName}, ${vname})[1] === ${toNum}${dname}[1]))` }); }); // Proxy scale reactions to ensure that an infinite loop doesn't occur // when an interval selection filter touches the scale. if (!hasScales && scaleTriggers.length) { signals.push({ name: name + SCALE_TRIGGER, value: {}, on: [ { events: scaleTriggers.map(t => ({scale: t.scaleName})), update: `${scaleTriggers.map(t => t.expr).join(' && ')} ? ${name + SCALE_TRIGGER} : {}` } ] }); } // Only add an interval to the store if it has valid data extents. Data extents // are set to null if pixel extents are equal to account for intervals over // ordinal/nominal domains which, when inverted, will still produce a valid datum. const update = `unit: ${unitName(model)}, fields: ${fieldsSg}, values`; return signals.concat({ name: name + TUPLE, ...(init ? {init: `{${update}: ${assembleInit(init)}}`} : {}), ...(dataSignals.length ? { on: [ { events: [{signal: dataSignals.join(' || ')}], // Prevents double invocation, see https://github.com/vega/vega#1672. update: `${dataSignals.join(' && ')} ? {${update}: [${dataSignals}]} : null` } ] } : {}) }); }, marks: (model, selCmpt, marks) => { const name = selCmpt.name; const {x, y} = selCmpt.project.hasChannel; const xvname = x && x.signals.visual; const yvname = y && y.signals.visual; const store = `data(${stringValue(selCmpt.name + STORE)})`; // Do not add a brush if we're binding to scales // or we don't have a valid interval projection if (scales.defined(selCmpt) || (!x && !y)) { return marks; } const update: any = { x: x !== undefined ? {signal: `${xvname}[0]`} : {value: 0}, y: y !== undefined ? {signal: `${yvname}[0]`} : {value: 0}, x2: x !== undefined ? {signal: `${xvname}[1]`} : {field: {group: 'width'}}, y2: y !== undefined ? {signal: `${yvname}[1]`} : {field: {group: 'height'}} }; // If the selection is resolved to global, only a single interval is in // the store. Wrap brush mark's encodings with a production rule to test // this based on the `unit` property. Hide the brush mark if it corresponds // to a unit different from the one in the store. if (selCmpt.resolve === 'global') { for (const key of keys(update)) { update[key] = [ { test: `${store}.length && ${store}[0].unit === ${unitName(model)}`, ...update[key] }, {value: 0} ]; } } // Two brush marks ensure that fill colors and other aesthetic choices do // not interefere with the core marks, but that the brushed region can still // be interacted with (e.g., dragging it around). const {fill, fillOpacity, cursor, ...stroke} = selCmpt.mark; const vgStroke = keys(stroke).reduce((def, k) => { def[k] = [ { test: [x !== undefined && `${xvname}[0] !== ${xvname}[1]`, y !== undefined && `${yvname}[0] !== ${yvname}[1]`] .filter(t => t) .join(' && '), value: stroke[k] }, {value: null} ]; return def; }, {}); return [ { name: `${name + BRUSH}_bg`, type: 'rect', clip: true, encode: { enter: { fill: {value: fill}, fillOpacity: {value: fillOpacity} }, update: update } }, ...marks, { name: name + BRUSH, type: 'rect', clip: true, encode: { enter: { ...(cursor ? {cursor: {value: cursor}} : {}), fill: {value: 'transparent'} }, update: {...update, ...vgStroke} } } ]; } }; export default interval; /** * Returns the visual and data signals for an interval selection. */ function channelSignals( model: UnitModel, selCmpt: SelectionComponent<'interval'>, proj: SelectionProjection, init?: SelectionInitInterval ): NewSignal[] { const channel = proj.channel; const vname = proj.signals.visual; const dname = proj.signals.data; const hasScales = scales.defined(selCmpt); const scaleName = stringValue(model.scaleName(channel)); const scale = model.getScaleComponent(channel as ScaleChannel); const scaleType = scale ? scale.get('type') : undefined; const scaled = (str: string) => `scale(${scaleName}, ${str})`; const size = model.getSizeSignalRef(channel === X ? 'width' : 'height').signal; const coord = `${channel}(unit)`; const on = events(selCmpt, (def: OnEvent[], evt: Stream) => { return [ ...def, {events: evt.between[0], update: `[${coord}, ${coord}]`}, // Brush Start {events: evt, update: `[${vname}[0], clamp(${coord}, 0, ${size})]`} // Brush End ]; }); // React to pan/zooms of continuous scales. Non-continuous scales // (band, point) cannot be pan/zoomed and any other changes // to their domains (e.g., filtering) should clear the brushes. on.push({ events: {signal: selCmpt.name + SCALE_TRIGGER}, update: hasContinuousDomain(scaleType) ? `[${scaled(`${dname}[0]`)}, ${scaled(`${dname}[1]`)}]` : `[0, 0]` }); return hasScales ? [{name: dname, on: []}] : [ { name: vname, ...(init ? {init: assembleInit(init, true, scaled)} : {value: []}), on: on }, { name: dname, ...(init ? {init: assembleInit(init)} : {}), // Cannot be `value` as `init` may require datetime exprs. on: [ { events: {signal: vname}, update: `${vname}[0] === ${vname}[1] ? null : invert(${scaleName}, ${vname})` } ] } ]; } function events(selCmpt: SelectionComponent<'interval'>, cb: (def: OnEvent[], evt: Stream) => OnEvent[]): OnEvent[] { return selCmpt.events.reduce((on, evt) => { if (!evt.between) { warn(`${evt} is not an ordered event stream for interval selections.`); return on; } return cb(on, evt); }, [] as OnEvent[]); }
bsd-3-clause
oyoy8629/yii2.new
backend/models/ApiMonthSetting.php
3014
<?php namespace backend\models; use backend\helpers\MonthLogic; use kartik\helpers\Html; use Yii; use \yii\behaviors\TimestampBehavior; use yii\db\ActiveRecord; /** * This is the model class for table "{{%api_month_detail}}". * * @property string $id * @property string $start * @property string $end * @property string $status * @property string $updated_count * @property string $selected_count * @property string $created_at * @property string $updated_at */ class ApiMonthSetting extends ActiveRecord { /** * @inheritdoc */ public static function tableName() { return '{{%api_month_setting}}'; } /* * 更新时间 */ public function behaviors() { return [ [ 'class' => TimestampBehavior::className(), ], ]; } /** * @inheritdoc */ public function rules() { return [ [[ 'status', 'updated_count', 'selected_count', 'created_at', 'updated_at'], 'integer'], [['start','end'],'validateTime'], ]; } public function scenarios() { return [ 'create' => ['start','end'], 'default'=>['status'] ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => 'ID', 'start' => '开始时间', 'viewStart' => '开始时间', 'end' => '结束时间', 'viewEnd' => '结束时间', 'viewTime' => '月份', 'viewIsUpdating' => '状态', 'status' => '状态', 'data' => '生成报表日期', 'viewStatus' => '状态', 'updatedCount' => '更新量', 'allCount' => '总量', 'created_at' => '创建时间', 'updated_at' => '更新时间', ]; } public function beforeSave($insert) { return parent::beforeSave($insert); // TODO: Change the autogenerated stub } public function validateTime($attribute, $params) { $this->$attribute = strtotime($this->$attribute); } public function getData(){ return Html::a($this->getViewStart().'~'.$this->getViewEnd(),\yii\helpers\Url::to(['/api-month-detail/index','ApiMonthDetailSearch[job_id]'=>$this->id]),[ 'target'=>'_blank' ]); } public function getViewStart(){ return date('Y-m-d',$this->start); } public function getViewEnd(){ return date('Y-m-d',$this->end); } // public function getUpdating(){ // return self::find()->where('status > 0')->one(); // } public function getViewIsUpdating(){ return $this->status ? ' [正在更新]' : ''; } public static $statusArray = [ 0 =>'待更新', 2 =>'正在更新', 3 =>'更新完毕' ]; public function getViewStatus(){ return self::$statusArray[$this->status]; } }
bsd-3-clause
laprej/ROSS-CXX
models/phold/phold.cpp
4620
#include "phold.h" tw_peid phold_map(tw_lpid gid) { return (tw_peid) gid / g_tw_nlp; } void phold_init(phold_state * s, tw_lp * lp) { int i; new (s) phold_state; if( stagger ) { for (i = 0; i < g_phold_start_events; i++) { tw_event_send( tw_event_new(lp->gid, tw_rand_exponential(&lp->cur_state->rng, mean) + lookahead + (tw_stime)(lp->gid % (unsigned int)g_tw_ts_end), lp)); } } else { for (i = 0; i < g_phold_start_events; i++) { tw_event_send( tw_event_new(lp->gid, tw_rand_exponential(&lp->cur_state->rng, mean) + lookahead, lp)); } } } void phold_pre_run(phold_state * s, tw_lp * lp) { tw_lpid dest; if(tw_rand_unif(&lp->cur_state->rng) <= percent_remote) { dest = tw_rand_integer(&lp->cur_state->rng, 0, ttl_lps - 1); } else { dest = lp->gid; } if(dest >= (g_tw_nlp * tw_nnodes())) tw_error(TW_LOC, "bad dest"); tw_event_send(tw_event_new(dest, tw_rand_exponential(&lp->cur_state->rng, mean) + lookahead, lp)); } void phold_event_handler(phold_state * s, tw_bf * bf, phold_message * m, tw_lp * lp) { tw_lpid dest; if(tw_rand_unif(&lp->cur_state->rng) <= percent_remote) { bf->c1 = 1; dest = tw_rand_integer(&lp->cur_state->rng, 0, ttl_lps - 1); // Makes PHOLD non-deterministic across processors! Don't uncomment /* dest += offset_lpid; */ /* if(dest >= ttl_lps) */ /* dest -= ttl_lps; */ s->set_dummy_state(tw_rand_ulong(&lp->cur_state->rng, 0, 1000000)); } else { bf->c1 = 0; dest = lp->gid; } if(dest >= (g_tw_nlp * tw_nnodes())) tw_error(TW_LOC, "bad dest"); tw_event_send(tw_event_new(dest, tw_rand_exponential(&lp->cur_state->rng, mean) + lookahead, lp)); } void phold_event_handler_rc(phold_state * s, tw_bf * bf, phold_message * m, tw_lp * lp) { tw_rand_reverse_unif(&lp->cur_state->rng); tw_rand_reverse_unif(&lp->cur_state->rng); if(bf->c1 == 1) tw_rand_reverse_unif(&lp->cur_state->rng); } void phold_finish(phold_state * s, tw_lp * lp) { } phold_state ps; tw_lptype mylps[] = { {(init_f) phold_init, (pre_run_f) phold_pre_run, /* (pre_run_f) NULL, */ (event_f) phold_event_handler, (revent_f) phold_event_handler_rc, (final_f) phold_finish, (map_f) phold_map, sizeof(phold_state), &ps} }; const tw_optdef app_opt[] = { TWOPT_GROUP("PHOLD Model"), TWOPT_STIME("remote", percent_remote, "desired remote event rate"), TWOPT_UINT("nlp", nlp_per_pe, "number of LPs per processor"), TWOPT_STIME("mean", mean, "exponential distribution mean for timestamps"), TWOPT_STIME("mult", mult, "multiplier for event memory allocation"), TWOPT_STIME("lookahead", lookahead, "lookahead for events"), TWOPT_UINT("start-events", g_phold_start_events, "number of initial messages per LP"), TWOPT_UINT("stagger", stagger, "Set to 1 to stagger event uniformly across 0 to end time."), TWOPT_UINT("memory", optimistic_memory, "additional memory buffers"), TWOPT_CHAR("run", run_id, "user supplied run name"), TWOPT_END() }; int main(int argc, char **argv, char **env) { int i; i = 0; while (i) { continue; } // get rid of error if compiled w/ MEMORY queues g_tw_memory_nqueues=1; // set a min lookahead of 1.0 lookahead = 1.0; tw_opt_add(app_opt); tw_init(&argc, &argv); if( lookahead > 1.0 ) tw_error(TW_LOC, "Lookahead > 1.0 .. needs to be less\n"); //reset mean based on lookahead mean = mean - lookahead; g_tw_memory_nqueues = 16; // give at least 16 memory queue event offset_lpid = g_tw_mynode * nlp_per_pe; ttl_lps = tw_nnodes() * g_tw_npe * nlp_per_pe; g_tw_events_per_pe = (mult * nlp_per_pe * g_phold_start_events) + optimistic_memory; //g_tw_rng_default = TW_FALSE; g_tw_lookahead = lookahead; tw_define_lps(nlp_per_pe, sizeof(phold_message)); for(i = 0; i < g_tw_nlp; i++) tw_lp_settype(i, &mylps[0]); if( g_tw_mynode == 0 ) { printf("========================================\n"); printf("PHOLD Model Configuration..............\n"); printf(" Lookahead..............%lf\n", lookahead); printf(" Start-events...........%u\n", g_phold_start_events); printf(" stagger................%u\n", stagger); printf(" Mean...................%lf\n", mean); printf(" Mult...................%lf\n", mult); printf(" Memory.................%u\n", optimistic_memory); printf(" Remote.................%lf\n", percent_remote); printf("========================================\n\n"); } tw_run(); tw_end(); return 0; }
bsd-3-clause
weigj/django-multidb
django/contrib/admin/util.py
7337
from django.core.exceptions import ObjectDoesNotExist from django.db import models from django.utils.html import escape from django.utils.safestring import mark_safe from django.utils.text import capfirst from django.utils.encoding import force_unicode from django.utils.translation import ugettext as _ def quote(s): """ Ensure that primary key values do not confuse the admin URLs by escaping any '/', '_' and ':' characters. Similar to urllib.quote, except that the quoting is slightly different so that it doesn't get automatically unquoted by the Web browser. """ if not isinstance(s, basestring): return s res = list(s) for i in range(len(res)): c = res[i] if c in """:/_#?;@&=+$,"<>%\\""": res[i] = '_%02X' % ord(c) return ''.join(res) def unquote(s): """ Undo the effects of quote(). Based heavily on urllib.unquote(). """ mychr = chr myatoi = int list = s.split('_') res = [list[0]] myappend = res.append del list[0] for item in list: if item[1:2]: try: myappend(mychr(myatoi(item[:2], 16)) + item[2:]) except ValueError: myappend('_' + item) else: myappend('_' + item) return "".join(res) def flatten_fieldsets(fieldsets): """Returns a list of field names from an admin fieldsets structure.""" field_names = [] for name, opts in fieldsets: for field in opts['fields']: # type checking feels dirty, but it seems like the best way here if type(field) == tuple: field_names.extend(field) else: field_names.append(field) return field_names def _nest_help(obj, depth, val): current = obj for i in range(depth): current = current[-1] current.append(val) def get_deleted_objects(deleted_objects, perms_needed, user, obj, opts, current_depth, admin_site): "Helper function that recursively populates deleted_objects." nh = _nest_help # Bind to local variable for performance if current_depth > 16: return # Avoid recursing too deep. opts_seen = [] for related in opts.get_all_related_objects(): has_admin = related.model in admin_site._registry if related.opts in opts_seen: continue opts_seen.append(related.opts) rel_opts_name = related.get_accessor_name() if isinstance(related.field.rel, models.OneToOneRel): try: sub_obj = getattr(obj, rel_opts_name) except ObjectDoesNotExist: pass else: if has_admin: p = '%s.%s' % (related.opts.app_label, related.opts.get_delete_permission()) if not user.has_perm(p): perms_needed.add(related.opts.verbose_name) # We don't care about populating deleted_objects now. continue if not has_admin: # Don't display link to edit, because it either has no # admin or is edited inline. nh(deleted_objects, current_depth, [u'%s: %s' % (capfirst(related.opts.verbose_name), force_unicode(sub_obj)), []]) else: # Display a link to the admin page. nh(deleted_objects, current_depth, [mark_safe(u'%s: <a href="../../../../%s/%s/%s/">%s</a>' % (escape(capfirst(related.opts.verbose_name)), related.opts.app_label, related.opts.object_name.lower(), sub_obj._get_pk_val(), escape(sub_obj))), []]) get_deleted_objects(deleted_objects, perms_needed, user, sub_obj, related.opts, current_depth+2, admin_site) else: has_related_objs = False for sub_obj in getattr(obj, rel_opts_name).all(): has_related_objs = True if not has_admin: # Don't display link to edit, because it either has no # admin or is edited inline. nh(deleted_objects, current_depth, [u'%s: %s' % (capfirst(related.opts.verbose_name), force_unicode(sub_obj)), []]) else: # Display a link to the admin page. nh(deleted_objects, current_depth, [mark_safe(u'%s: <a href="../../../../%s/%s/%s/">%s</a>' % (escape(capfirst(related.opts.verbose_name)), related.opts.app_label, related.opts.object_name.lower(), sub_obj._get_pk_val(), escape(sub_obj))), []]) get_deleted_objects(deleted_objects, perms_needed, user, sub_obj, related.opts, current_depth+2, admin_site) # If there were related objects, and the user doesn't have # permission to delete them, add the missing perm to perms_needed. if has_admin and has_related_objs: p = '%s.%s' % (related.opts.app_label, related.opts.get_delete_permission()) if not user.has_perm(p): perms_needed.add(related.opts.verbose_name) for related in opts.get_all_related_many_to_many_objects(): has_admin = related.model in admin_site._registry if related.opts in opts_seen: continue opts_seen.append(related.opts) rel_opts_name = related.get_accessor_name() has_related_objs = False # related.get_accessor_name() could return None for symmetrical relationships if rel_opts_name: rel_objs = getattr(obj, rel_opts_name, None) if rel_objs: has_related_objs = True if has_related_objs: for sub_obj in rel_objs.all(): if not has_admin: # Don't display link to edit, because it either has no # admin or is edited inline. nh(deleted_objects, current_depth, [_('One or more %(fieldname)s in %(name)s: %(obj)s') % \ {'fieldname': force_unicode(related.field.verbose_name), 'name': force_unicode(related.opts.verbose_name), 'obj': escape(sub_obj)}, []]) else: # Display a link to the admin page. nh(deleted_objects, current_depth, [ mark_safe((_('One or more %(fieldname)s in %(name)s:') % {'fieldname': escape(force_unicode(related.field.verbose_name)), 'name': escape(force_unicode(related.opts.verbose_name))}) + \ (u' <a href="../../../../%s/%s/%s/">%s</a>' % \ (related.opts.app_label, related.opts.module_name, sub_obj._get_pk_val(), escape(sub_obj)))), []]) # If there were related objects, and the user doesn't have # permission to change them, add the missing perm to perms_needed. if has_admin and has_related_objs: p = u'%s.%s' % (related.opts.app_label, related.opts.get_change_permission()) if not user.has_perm(p): perms_needed.add(related.opts.verbose_name)
bsd-3-clause
sharaf84/digi
common/models/custom/search/Brand.php
2663
<?php namespace common\models\custom\search; use Yii; use yii\base\Model; use yii\data\ActiveDataProvider; /** * Tree represents the model behind the search form about `common\models\base\Tree`. */ class Brand extends \common\models\custom\Brand { /** * @inheritdoc */ public function rules() { return [ [['id', 'root', 'lft', 'rgt', 'lvl', 'icon_type', 'active', 'selected', 'disabled', 'readonly', 'visible', 'collapsed', 'movable_u', 'movable_d', 'movable_l', 'movable_r', 'removable', 'removable_all'], 'integer'], [['name', 'slug', 'link', 'description', 'icon', 'created', 'updated'], 'safe'], ]; } /** * @inheritdoc */ public function scenarios() { // bypass scenarios() implementation in the parent class return Model::scenarios(); } /** * Creates data provider instance with search query applied * * @param array $params * * @return ActiveDataProvider */ public function search($params) { $query = parent::find(); $dataProvider = new ActiveDataProvider([ 'query' => $query, ]); $this->load($params); if (!$this->validate()) { // uncomment the following line if you do not want to any records when validation fails // $query->where('0=1'); return $dataProvider; } $query->andFilterWhere([ 'id' => $this->id, //'root' => $this->root, 'lft' => $this->lft, 'rgt' => $this->rgt, 'lvl' => $this->lvl, 'icon_type' => $this->icon_type, 'active' => $this->active, 'selected' => $this->selected, 'disabled' => $this->disabled, 'readonly' => $this->readonly, 'visible' => $this->visible, 'collapsed' => $this->collapsed, 'movable_u' => $this->movable_u, 'movable_d' => $this->movable_d, 'movable_l' => $this->movable_l, 'movable_r' => $this->movable_r, 'removable' => $this->removable, 'removable_all' => $this->removable_all, 'created' => $this->created, 'updated' => $this->updated, ]); $query->andFilterWhere(['like', 'name', $this->name]) ->andFilterWhere(['like', 'slug', $this->slug]) ->andFilterWhere(['like', 'link', $this->link]) ->andFilterWhere(['like', 'description', $this->description]) ->andFilterWhere(['like', 'icon', $this->icon]); return $dataProvider; } }
bsd-3-clause
toasttab/jdbishard
jdbishard-sharding/src/main/java/jdbishard/sharding/IdOnlyShardNamer.java
214
package jdbishard.sharding; public class IdOnlyShardNamer implements HumanFriendlyShardNamer { @Override public String nameShard(ShardInfo shardInfo) { return shardInfo.id().toString(); } }
bsd-3-clause
char0n/ramda-adjunct
src/liftF.js
1398
import { curryN } from 'ramda'; import liftFN from './liftFN'; /** * "lifts" a function to be the specified arity, so that it may "map over" objects that satisfy * the fantasy land Apply spec of algebraic structures. * * Lifting is specific for {@link https://github.com/scalaz/scalaz|scalaz} and {@link http://functionaljava.org/|function Java} implementations. * Old version of fantasy land spec were not compatible with this approach, * but as of fantasy land 1.0.0 Apply spec also adopted this approach. * * This function acts as interop for ramda <= 0.23.0 and {@link https://monet.github.io/monet.js/|monet.js}. * * More info {@link https://github.com/fantasyland/fantasy-land/issues/50|here}. * * @func liftF * @memberOf RA * @since {@link https://char0n.github.io/ramda-adjunct/1.2.0|v1.2.0} * @category Function * @sig Apply a => (a... -> a) -> (a... -> a) * @param {Function} fn The function to lift into higher context * @return {Function} The lifted function * @see {@link RA.liftFN|liftFN} * @example * * const { Maybe } = require('monet'); * * const add3 = (a, b, c) => a + b + c; * const madd3 = RA.liftF(add3); * * madd3(Maybe.Some(10), Maybe.Some(15), Maybe.Some(17)); //=> Maybe.Some(42) * madd3(Maybe.Some(10), Maybe.Nothing(), Maybe.Some(17)); //=> Maybe.Nothing() */ const liftF = curryN(1, (fn) => liftFN(fn.length, fn)); export default liftF;
bsd-3-clause
hu2008yinxiang/phalcon-pure-php
src/Phalcon/Mvc/Model/Validator/PresenceOf.php
1060
<?php namespace Phalcon\Mvc\Model\Validator { /** * Phalcon\Mvc\Model\Validator\PresenceOf * * Allows to validate if a filed have a value different of null and empty string ("") * * <code> * use Phalcon\Mvc\Model\Validator\PresenceOf; * * class Subscriptors extends \Phalcon\Mvc\Model * { * * public function validation() * { * this->validate(new PresenceOf(array( * "field" => 'name', * "message" => 'The name is required' * ))); * if (this->validationHasFailed() == true) { * return false; * } * } * * } * </code> */ class PresenceOf extends \Phalcon\Mvc\Model\Validator implements \Phalcon\Mvc\Model\ValidatorInterface { /** * Executes the validator * * @param * \Phalcon\Mvc\ModelInterface record * @return boolean */ public function validate(\Phalcon\Mvc\ModelInterface $record) {} } }
bsd-3-clause
mural/spm
SPM/src/main/java/com/spm/android/common/listener/MapperAsyncOnClickListener.java
856
package com.spm.android.common.listener; import android.app.Activity; import android.view.View; import android.view.View.OnClickListener; import com.spm.common.annotation.FieldModelMapper; import com.spm.common.utils.ThreadUtils; /** * Asynchronous {@link OnClickListener} * * @author Luciano Rey */ public abstract class MapperAsyncOnClickListener implements OnClickListener { /** * @see android.view.View.OnClickListener#onClick(android.view.View) */ @Override public final void onClick(final View view) { FieldModelMapper.mapFieldsModel((Activity)view.getContext()); ThreadUtils.execute(new Runnable() { @Override public void run() { onAsyncRun(view); } }); } /** * Called when a view has been clicked. * * @param view The view that was clicked. */ public abstract void onAsyncRun(View view); }
bsd-3-clause
highweb-project/highweb-webcl-html5spec
chrome/browser/ui/views/frame/immersive_mode_controller_ash.cc
9703
// Copyright 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/ui/views/frame/immersive_mode_controller_ash.h" #include "ash/shell.h" #include "ash/wm/immersive_revealed_lock.h" #include "ash/wm/window_state.h" #include "base/macros.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/ui/exclusive_access/exclusive_access_manager.h" #include "chrome/browser/ui/exclusive_access/fullscreen_controller.h" #include "chrome/browser/ui/views/frame/browser_view.h" #include "chrome/browser/ui/views/frame/top_container_view.h" #include "chrome/browser/ui/views/tabs/tab_strip.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/web_contents.h" #include "ui/aura/window.h" #include "ui/views/view.h" #include "ui/views/widget/widget.h" #include "ui/views/window/non_client_view.h" namespace { // Revealing the TopContainerView looks better if the animation starts and ends // just a few pixels before the view goes offscreen, which reduces the visual // "pop" as the 3-pixel tall "light bar" style tab strip becomes visible. const int kAnimationOffsetY = 3; // Converts from ImmersiveModeController::AnimateReveal to // ash::ImmersiveFullscreenController::AnimateReveal. ash::ImmersiveFullscreenController::AnimateReveal ToImmersiveFullscreenControllerAnimateReveal( ImmersiveModeController::AnimateReveal animate_reveal) { switch (animate_reveal) { case ImmersiveModeController::ANIMATE_REVEAL_YES: return ash::ImmersiveFullscreenController::ANIMATE_REVEAL_YES; case ImmersiveModeController::ANIMATE_REVEAL_NO: return ash::ImmersiveFullscreenController::ANIMATE_REVEAL_NO; } NOTREACHED(); return ash::ImmersiveFullscreenController::ANIMATE_REVEAL_NO; } class ImmersiveRevealedLockAsh : public ImmersiveRevealedLock { public: explicit ImmersiveRevealedLockAsh(ash::ImmersiveRevealedLock* lock) : lock_(lock) {} private: scoped_ptr<ash::ImmersiveRevealedLock> lock_; DISALLOW_COPY_AND_ASSIGN(ImmersiveRevealedLockAsh); }; } // namespace ImmersiveModeControllerAsh::ImmersiveModeControllerAsh() : controller_(new ash::ImmersiveFullscreenController), browser_view_(nullptr), native_window_(nullptr), observers_enabled_(false), use_tab_indicators_(false), visible_fraction_(1) { } ImmersiveModeControllerAsh::~ImmersiveModeControllerAsh() { EnableWindowObservers(false); } void ImmersiveModeControllerAsh::Init(BrowserView* browser_view) { browser_view_ = browser_view; native_window_ = browser_view_->GetNativeWindow(); controller_->Init(this, browser_view_->frame(), browser_view_->top_container()); } void ImmersiveModeControllerAsh::SetEnabled(bool enabled) { if (controller_->IsEnabled() == enabled) return; EnableWindowObservers(enabled); controller_->SetEnabled(browser_view_->browser()->is_app() ? ash::ImmersiveFullscreenController::WINDOW_TYPE_HOSTED_APP : ash::ImmersiveFullscreenController::WINDOW_TYPE_BROWSER , enabled); } bool ImmersiveModeControllerAsh::IsEnabled() const { return controller_->IsEnabled(); } bool ImmersiveModeControllerAsh::ShouldHideTabIndicators() const { return !use_tab_indicators_; } bool ImmersiveModeControllerAsh::ShouldHideTopViews() const { return controller_->IsEnabled() && !controller_->IsRevealed(); } bool ImmersiveModeControllerAsh::IsRevealed() const { return controller_->IsRevealed(); } int ImmersiveModeControllerAsh::GetTopContainerVerticalOffset( const gfx::Size& top_container_size) const { if (!IsEnabled()) return 0; // The TopContainerView is flush with the top of |browser_view_| when the // top-of-window views are fully closed so that when the tab indicators are // used, the "light bar" style tab strip is flush with the top of // |browser_view_|. if (!IsRevealed()) return 0; int height = top_container_size.height() - kAnimationOffsetY; return static_cast<int>(height * (visible_fraction_ - 1)); } ImmersiveRevealedLock* ImmersiveModeControllerAsh::GetRevealedLock( AnimateReveal animate_reveal) { return new ImmersiveRevealedLockAsh(controller_->GetRevealedLock( ToImmersiveFullscreenControllerAnimateReveal(animate_reveal))); } void ImmersiveModeControllerAsh::OnFindBarVisibleBoundsChanged( const gfx::Rect& new_visible_bounds_in_screen) { find_bar_visible_bounds_in_screen_ = new_visible_bounds_in_screen; } void ImmersiveModeControllerAsh::SetupForTest() { controller_->SetupForTest(); } void ImmersiveModeControllerAsh::EnableWindowObservers(bool enable) { if (observers_enabled_ == enable) return; observers_enabled_ = enable; content::Source<FullscreenController> source(browser_view_->browser() ->exclusive_access_manager() ->fullscreen_controller()); if (enable) { ash::wm::GetWindowState(native_window_)->AddObserver(this); registrar_.Add(this, chrome::NOTIFICATION_FULLSCREEN_CHANGED, source); } else { ash::wm::GetWindowState(native_window_)->RemoveObserver(this); registrar_.Remove(this, chrome::NOTIFICATION_FULLSCREEN_CHANGED, source); } } void ImmersiveModeControllerAsh::LayoutBrowserRootView() { views::Widget* widget = browser_view_->frame(); // Update the window caption buttons. widget->non_client_view()->frame_view()->ResetWindowControls(); widget->non_client_view()->frame_view()->InvalidateLayout(); browser_view_->InvalidateLayout(); widget->GetRootView()->Layout(); } bool ImmersiveModeControllerAsh::UpdateTabIndicators() { bool has_tabstrip = browser_view_->IsBrowserTypeNormal(); if (!IsEnabled() || !has_tabstrip) { use_tab_indicators_ = false; } else { bool in_tab_fullscreen = browser_view_->browser() ->exclusive_access_manager() ->fullscreen_controller() ->IsWindowFullscreenForTabOrPending(); use_tab_indicators_ = !in_tab_fullscreen; } bool show_tab_indicators = use_tab_indicators_ && !IsRevealed(); if (show_tab_indicators != browser_view_->tabstrip()->IsImmersiveStyle()) { browser_view_->tabstrip()->SetImmersiveStyle(show_tab_indicators); return true; } return false; } void ImmersiveModeControllerAsh::OnImmersiveRevealStarted() { visible_fraction_ = 0; browser_view_->top_container()->SetPaintToLayer(true); browser_view_->top_container()->layer()->SetFillsBoundsOpaquely(false); UpdateTabIndicators(); LayoutBrowserRootView(); FOR_EACH_OBSERVER(Observer, observers_, OnImmersiveRevealStarted()); } void ImmersiveModeControllerAsh::OnImmersiveRevealEnded() { visible_fraction_ = 0; browser_view_->top_container()->SetPaintToLayer(false); UpdateTabIndicators(); LayoutBrowserRootView(); } void ImmersiveModeControllerAsh::OnImmersiveFullscreenExited() { browser_view_->top_container()->SetPaintToLayer(false); UpdateTabIndicators(); LayoutBrowserRootView(); } void ImmersiveModeControllerAsh::SetVisibleFraction(double visible_fraction) { if (visible_fraction_ != visible_fraction) { visible_fraction_ = visible_fraction; browser_view_->Layout(); } } std::vector<gfx::Rect> ImmersiveModeControllerAsh::GetVisibleBoundsInScreen() const { views::View* top_container_view = browser_view_->top_container(); gfx::Rect top_container_view_bounds = top_container_view->GetVisibleBounds(); // TODO(tdanderson): Implement View::ConvertRectToScreen(). gfx::Point top_container_view_bounds_in_screen_origin( top_container_view_bounds.origin()); views::View::ConvertPointToScreen(top_container_view, &top_container_view_bounds_in_screen_origin); gfx::Rect top_container_view_bounds_in_screen( top_container_view_bounds_in_screen_origin, top_container_view_bounds.size()); std::vector<gfx::Rect> bounds_in_screen; bounds_in_screen.push_back(top_container_view_bounds_in_screen); bounds_in_screen.push_back(find_bar_visible_bounds_in_screen_); return bounds_in_screen; } void ImmersiveModeControllerAsh::OnPostWindowStateTypeChange( ash::wm::WindowState* window_state, ash::wm::WindowStateType old_type) { // Disable immersive fullscreen when the user exits fullscreen without going // through FullscreenController::ToggleBrowserFullscreenMode(). This is the // case if the user exits fullscreen via the restore button. if (controller_->IsEnabled() && !window_state->IsFullscreen() && !window_state->IsMinimized()) { browser_view_->FullscreenStateChanged(); } } void ImmersiveModeControllerAsh::Observe( int type, const content::NotificationSource& source, const content::NotificationDetails& details) { DCHECK_EQ(chrome::NOTIFICATION_FULLSCREEN_CHANGED, type); if (!controller_->IsEnabled()) return; bool tab_indicator_visibility_changed = UpdateTabIndicators(); // Auto hide the shelf in immersive browser fullscreen. When auto hidden, the // shelf displays a 3px 'light bar' when it is closed. When in immersive // browser fullscreen and tab fullscreen, hide the shelf completely and // prevent it from being revealed. bool in_tab_fullscreen = content::Source<FullscreenController>(source)-> IsWindowFullscreenForTabOrPending(); ash::wm::GetWindowState(native_window_)->set_hide_shelf_when_fullscreen( in_tab_fullscreen); ash::Shell::GetInstance()->UpdateShelfVisibility(); if (tab_indicator_visibility_changed) LayoutBrowserRootView(); }
bsd-3-clause
hongqipiaoyang/houtai
views/index/index.php
84
<?php use yii\helpers\Html; echo 'hello world'; ?>
bsd-3-clause
olivierverdier/sfepy
sfepy/terms/terms_constraints.py
3253
from sfepy.terms.terms import * from sfepy.linalg import dot_sequences class NonPenetrationTerm(Term): r""" :Description: Non-penetration condition in the weak sense. :Definition: .. math:: \int_{\Gamma} \lambda \ul{n} \cdot \ul{v} \mbox{ , } \int_{\Gamma} \hat\lambda \ul{n} \cdot \ul{u} :Arguments 1: virtual : :math:`\ul{v}`, state : :math:`\lambda` :Arguments 2: state : :math:`\ul{u}`, virtual : :math:`\hat\lambda` """ name = 'dw_non_penetration' arg_types = (('virtual', 'state'), ('state', 'virtual')) modes = ('grad', 'div') integration = 'surface' use_caches = {'state_in_surface_qp' : [['state']]} def __call__(self, diff_var=None, **kwargs): if self.mode == 'grad': virtual, state = self.get_args(**kwargs) ap, sg = self.get_approximation(virtual) cache = self.get_cache('state_in_surface_qp', 0) else: state, virtual = self.get_args(**kwargs) ap, sg = self.get_approximation(state) cache = self.get_cache('state_in_surface_qp', 0) n_fa, n_qp, dim, n_fp = ap.get_s_data_shape(self.integral, self.region.name) rdim, cdim = virtual.n_components, state.n_components if diff_var is None: shape = (n_fa, 1, rdim * n_fp, 1) elif diff_var == self.get_arg_name('state'): shape = (n_fa, 1, rdim * n_fp, cdim * n_fp) else: raise StopIteration sd = ap.surface_data[self.region.name] # ap corresponds to \ul{u} field. bf = ap.get_base(sd.face_type, 0, integral=self.integral) ebf = nm.zeros((bf.shape[0], dim, n_fp * dim), dtype=nm.float64) for ir in xrange(dim): ebf[:, ir, ir*n_fp:(ir+1)*n_fp] = bf[:,0,:] normals = sg.variable(0) out = nm.zeros(shape, dtype=nm.float64) lchunk = nm.arange(n_fa, dtype=nm.int32) if diff_var is None: vec_qp = cache('state', self, 0, state=state, get_vector=self.get_vector) if self.mode == 'grad': ebf_t = nm.tile(ebf.transpose((0, 2, 1)), (n_fa, 1, 1, 1)) nl = normals * vec_qp eftnl = dot_sequences(ebf_t, nl, use_rows=True) sg.integrate_chunk(out, eftnl, lchunk, 1) else: bf_t = nm.tile(bf.transpose((0, 2, 1)), (n_fa, 1, 1, 1)) ntu = (normals * vec_qp).sum(axis=-2)[...,None] ftntu = (bf_t * ntu) sg.integrate_chunk(out, ftntu, lchunk, 1) else: ebf_t = nm.tile(ebf.transpose((0, 2, 1)), (n_fa, 1, 1, 1)) bf_ = nm.tile(bf, (n_fa, 1, 1, 1)) eftn = dot_sequences(ebf_t, normals, use_rows=True) eftnf = eftn * bf_ if self.mode == 'grad': sg.integrate_chunk(out, eftnf, lchunk, 1) else: ftntef = nm.ascontiguousarray(eftnf.transpose((0, 1, 3, 2))) sg.integrate_chunk(out, ftntef, lchunk, 1) yield out, lchunk, 0
bsd-3-clause
zvelo/pantheios
examples/cpp/contract/example.cpp.contract.PANTHEIOS_MESSAGE_ASSERT/example.cpp.contract.PANTHEIOS_MESSAGE_ASSERT.cpp
2137
/* ///////////////////////////////////////////////////////////////////////// * File: examples/cpp/contract/example.cpp.contract.PANTHEIOS_MESSAGE_ASSERT/example.cpp.contract.PANTHEIOS_MESSAGE_ASSERT.cpp * * Purpose: C++ example program for Pantheios. Demonstrates: * * - use of Pantheios inserter for thread ids * - use of pantheios::logputs() in bail-out conditions * * Created: 8th May 2009 * Updated: 7th December 2010 * * www: http://www.pantheios.org/ * * License: This source code is placed into the public domain 2006 * by Synesis Software Pty Ltd. There are no restrictions * whatsoever to your use of the software. * * This software is provided "as is", and any warranties, * express or implied, of any kind and for any purpose, are * disclaimed. * * ////////////////////////////////////////////////////////////////////// */ #define PANTHEIOS_NO_INCLUDE_OS_AND_3PTYLIB_STRING_ACCESS // Faster compilation /* Pantheios Header Files */ #include <pantheios/assert.h> /* Standard C Header Files */ #include <stdlib.h> /* ///////////////////////////////////////////////////////////////////////// * Compiler compatibility */ #ifdef STLSOFT_COMPILER_IS_BORLAND # pragma warn -8008 # pragma warn -8066 #endif /* ////////////////////////////////////////////////////////////////////// */ /* Define the stock front-end process identity, so that it links when using * fe.N, fe.simple, etc. */ PANTHEIOS_EXTERN_C const PAN_CHAR_T PANTHEIOS_FE_PROCESS_IDENTITY[] = PANTHEIOS_LITERAL_STRING("example.cpp.contract.PANTHEIOS_MESSAGE_ASSERT"); /* ////////////////////////////////////////////////////////////////////// */ int main() { int i = pantheios::init(); if(i >= 0) { PANTHEIOS_MESSAGE_ASSERT(true, "it was true"); PANTHEIOS_MESSAGE_ASSERT(false, "it was false"); pantheios::uninit(); } return EXIT_SUCCESS; } /* ///////////////////////////// end of file //////////////////////////// */
bsd-3-clause
straight-street/straight-street
_reporters.php
3537
<? abstract class ReporterABC { function __construct($sql, $wide=False, $getHdr=null, $getRow=null) { $this->sql = $sql; $this->wide = $wide; $this->getHeader = $getHdr; $this->getRow = $getRow; } function __destruct() { } abstract protected function openOutput(); abstract protected function closeOutput(); abstract protected function putHeader($row); abstract protected function putLine($row); abstract protected function putFooter(); public function run() { db_connect(); $result = db_runQuery($this->sql); if (!$result) { die("query failed" ); } $this->openOutput(); if ($this->getHeader) { $f = $this->getHeader; $row = $f($result); } else { $row = mysql_fetch_assoc($result); $row = array_keys($row); } $this->putHeader($row); mysql_data_seek($result, 0); $fRow; if ($this->getRow) { $fRow = $this->getRow; // string of name - oh give me Python } else { $fRow = 'mysql_fetch_row'; } while (!is_bool($row = $fRow($result) )) { if (count($row)) // bit fragile $this->putLine($row); } $this->putFooter(); $this->closeOutput(); db_disconnect(); } } class CSVReporter extends ReporterABC { protected $handle; protected $filename; protected function openOutput() { global $loggedUser; $filename = 'tmp/report_'.$loggedUser.'.csv'; if (($handle = @fopen($filename, 'wb')) == 0) { echo "error opening report file"; exit; } $this->handle = $handle; $this->filename = $filename; } protected function closeOutput() { fclose($this->handle); header("Location: " . $this->filename); exit(); } protected function write_csv_line($handle, $arLine) { $arLine = str_replace('"', '""', $arLine); $line = "\"" . join('","', $arLine) . "\"\r\n"; print($line).'<br>'; return fwrite($handle, $line); } protected function putHeader($row) { @$this->write_csv_line($this->handle, $row); } protected function putLine($row) { @$this->write_csv_line($this->handle, $row); } protected function putFooter() { } } class HTMLReporter extends ReporterABC { protected function openOutput() { } protected function closeOutput() { } protected function write_HTML_line($arLine, $pre, $post) { $line = $pre . join($post.$pre, $arLine) . $post; print($line); } protected function putHeader($row) { $klass = 'adreport' . (($this->wide) ? ' wide' : ''); print('<table class="'.$klass.'" ><thead><tr>'); @$this->write_HTML_line($row, '<th>', '</th>'); print('</tr></thead>'); } protected function putLine($row) { print('<body><tr>'); @$this->write_HTML_line($row, '<td>', '</td>'); print('</tbody><tr>'); } protected function putFooter() { print('</table>'); } } ?>
bsd-3-clause
cfobel/sconspiracy
Python/racy/plugins/libext/libextproject.py
19035
# -*- coding: UTF8 -*- # ***** BEGIN LICENSE BLOCK ***** # Sconspiracy - Copyright (C) IRCAD, 2004-2010. # Distributed under the terms of the BSD Licence as # published by the Open Source Initiative. # ****** END LICENSE BLOCK ****** import os import time import SCons.Defaults import SCons.Node from os.path import join as opjoin import racy from racy import rutils from racy.renv import constants from racy.rproject import ConstructibleRacyProject, LibName from racy.rutils import cached_property, memoize, run_once from sconsbuilders.utils import marker from libexterror import LibextError from nodeholder import NodeHolder from builderwrapper import BuilderWrapper class CommandWrapper(BuilderWrapper): def __init__(self, *args, **kwargs): kwargs['builder'] = self.builder super(CommandWrapper, self).__init__(*args, **kwargs) def builder_args(self, options, pwd, **kwargs): args = kwargs.setdefault('ARGS', []) args.extend(options) target = marker(self.builder_name, self.prj.full_name, options) kwargs.setdefault('target', [target]) kwargs.setdefault('source', [pwd]) return kwargs def builder(self, options, pwd, **kwargs): kwargs = self.builder_args(options, pwd, **kwargs) scons_builder = getattr(self.prj.env, self.builder_name) if not pwd: msg = "{0}: missing or invalid pwd." racy.RacyPluginError, msg.format(self.__class__.__name__) return scons_builder(**kwargs) class ConfigureWrapper(CommandWrapper): def __call__(self, *args, **kwargs): prj = self.prj ENV = prj.env['ENV'] ENV['CXXFLAGS'] = ENV.get('CXXFLAGS','') ENV['CFLAGS'] = ENV.get('CFLAGS','') ENV['LINKFLAGS'] = ENV.get('LINKFLAGS','') ENV['CXXFLAGS'] += ' ' + kwargs.get('CXXFLAGS','') ENV['CFLAGS'] += ' ' + kwargs.get('CFLAGS','') ENV['LINKFLAGS'] += ' ' + kwargs.get('LINKFLAGS','') ENV['CXXFLAGS'] += '${DEPS_INCLUDE_FLAGS}' ENV['CFLAGS'] += '${DEPS_INCLUDE_FLAGS}' ENV['LINKFLAGS'] += '${DEPS_LIB_FLAGS}' #ENV['CXXFLAGS'] += ' -I'.join([''] + prj.deps_include_path) #ENV['CFLAGS'] += ' -I'.join([''] + prj.deps_include_path) #ENV['LINKFLAGS'] += ' -L'.join([''] + prj.deps_lib_path) ENV['CXXFLAGS'] = prj.env.subst(ENV['CXXFLAGS']) ENV['CFLAGS'] = prj.env.subst(ENV['CFLAGS']) ENV['LINKFLAGS'] = prj.env.subst(ENV['LINKFLAGS']) ENV['LDFLAGS'] = ENV['LINKFLAGS'] ARGS = kwargs.setdefault('ARGS', []) ARGS.append('--prefix=${LOCAL_DIR}') if prj.is_debug: ARGS.append('--enable-debug') else: ARGS.append('--disable-debug') super(ConfigureWrapper, self).__call__(*args, **kwargs) class CMakeWrapper(CommandWrapper): def __call__(self, *args, **kwargs): prj = self.prj def build_type(): if prj.is_debug: return 'Debug' else: return 'Release' ARGS = kwargs.setdefault('ARGS', []) ARGS.insert(0,'-DCMAKE_BUILD_TYPE:STRING={0}'.format(build_type())) ARGS.insert(0,'-DCMAKE_PREFIX_PATH:PATH=${winpathsep(DEPS)}') ARGS.append('-DCMAKE_INSTALL_PREFIX:PATH=${LOCAL_DIR}') if racy.renv.is_windows(): ARGS.insert(0,'NMake Makefiles') else: ARGS.insert(0,'Unix Makefiles') ARGS.insert(0,'-G') super(CMakeWrapper, self).__call__(*args, **kwargs) def builder(self, options, source, builddir, **kwargs): kwargs = self.builder_args(options, pwd=source, **kwargs) kwargs['CMAKE_BUILD_PATH'] = builddir return self.prj.env.CMake(**kwargs) class EditWrapper(CommandWrapper): def builder(self, expr, files, **kwargs): kwargs = self.builder_args(files + expr, pwd=[], **kwargs) return self.prj.env.Edit(FILES=files, EXPR=expr, **kwargs) class WaitDependenciesWrapper(BuilderWrapper): def __init__(self, *args, **kwargs): builder = self.wait_dependencies_builder kwargs['name'] = 'WaitDependencies' kwargs['builder'] = builder super(WaitDependenciesWrapper, self).__init__(*args, **kwargs) def wait_dependencies_builder(self, *args, **kwargs): return self.prj class WhereIsWrapper(object): def __init__(self, prj): self.prj = prj def __call__(self, *args, **kwargs): subst = self.prj.env.subst for k,v in kwargs.items(): kwargs[k] = subst(v) return self.prj.env.WhereIs(*subst(args), **kwargs) class AppendENVPathWrapper(object): def __init__(self, prj): self.prj = prj def __call__(self, *args, **kwargs): subst = self.prj.env.subst for k,v in kwargs.items(): kwargs[k] = subst(v) return self.prj.env.AppendENVPath(*subst(args), **kwargs) class PrependENVPathWrapper(object): def __init__(self, prj): self.prj = prj def __call__(self, *args, **kwargs): subst = self.prj.env.subst for k,v in kwargs.items(): kwargs[k] = subst(v) return self.prj.env.PrependENVPath(*subst(args), **kwargs) class SetENVWrapper(object): def __init__(self, prj): self.prj = prj def __call__(self, name, newpath): subst = self.prj.env.subst self.prj.env['ENV'][name] = subst(newpath) return None class SetWrapper(object): def __init__(self, prj): self.prj = prj def __call__(self, var, val): subst = self.prj.env.subst self.prj.env[var] = subst(val) return None class LibextProject(ConstructibleRacyProject): LIBEXT = ('libext', ) ENV = None def __init__(self, *args, **kwargs): self.generate_functions = generate_functions = {} builder_wrappers = [ BuilderWrapper (self,'Download'), BuilderWrapper (self,'UnTar'), BuilderWrapper (self,'UnZip'), BuilderWrapper (self,'Delete',self.DeleteBuilder), BuilderWrapper (self,'Copy' ,self.CopyBuilder), BuilderWrapper (self,'Mkdir' ,self.MkdirBuilder), CMakeWrapper (self,'CMake'), EditWrapper (self,'Edit'), CommandWrapper (self,'Make'), CommandWrapper (self,'Patch'), CommandWrapper (self,'SysCommand', reg_name='Command'), ConfigureWrapper(self, 'Configure'), WaitDependenciesWrapper(self), ] for bld in builder_wrappers: bld.subscribe_to(generate_functions) self.env_functions = functions = { 'WhereIs' : WhereIsWrapper(self), 'AppendENVPath' : AppendENVPathWrapper(self), 'PreprendENVPath' : PrependENVPathWrapper(self), 'SetENV' : SetENVWrapper(self), 'Set' : SetWrapper(self), } generate_functions.update(functions) kwargs['_globals']=kwargs.get('_globals',{}) kwargs['_globals'].update(generate_functions) kwargs['_globals']['prj'] = self self.ENV = kwargs['_globals']['ENV'] = {} super(LibextProject, self).__init__( *args, **kwargs ) def DeleteBuilder(self, file, **kwargs): env = self.env args = [file] res = env.LibextDelete([marker('Delete',self.full_name, args)], [], ARGS=args) return res def CopyBuilder(self, source, to, **kwargs): env = self.env args = [source, to] marker_name = kwargs.get("marker_name", 'Copy') res = env.LibextCopyFile([marker(marker_name, self.full_name, args)], [], ARGS=args) env.Clean(res, to) return res def MkdirBuilder(self, dir, **kwargs): env = self.env args = [dir] res = env.Mkdir([marker('Mkdir',self.full_name, args)], [], ARGS=args) env.Clean(res, dir) return res def WriteBuilder(self, file, content, **kwargs): env = self.env args = [file, content] res = env.Write( [marker('Write',self.full_name, args)], [], FILES = [file], CONTENTS = [env.subst(content, raw=1)], ) env.Clean(res, file) return res @cached_property def download_target (self): path = [racy.renv.dirs.build, 'LibextDownload'] fmt = "{0.name}_{0.version}" path.append(fmt.format(self)) return os.path.join(*path) @cached_property def extract_dir (self): path = [self.build_dir, 'sources'] return os.path.join(*path) @cached_property def local_dir (self): path = [self.build_dir, 'local'] return os.path.join(*path) @cached_property def include_path (self): path = [self.local_dir, 'include'] return [os.path.join(*path)] @cached_property def build_bin_path (self): path = [self.local_dir, 'bin'] return os.path.join(*path) @cached_property def lib_path (self): path = [self.local_dir, 'lib'] return os.path.join(*path) @cached_property def deps_include_path (self): inc = [] for lib in self.source_rec_deps: inc += lib.include_path return inc @cached_property def deps_lib_path (self): inc = [lib.lib_path for lib in self.source_rec_deps] return inc @cached_property def install_pkg_path(self): install_dir = racy.renv.dirs.install_binpkg install_dir = opjoin(install_dir, self.full_name) return install_dir @cached_property def deps_build_nodes (self): inc = [lib.build() for lib in self.source_rec_deps] return inc @cached_property def deps_install_nodes (self): inc = [lib.install() for lib in self.source_rec_deps] return inc @cached_property def environment(self): prj = self env = self.env direct_deps = self.source_deps all_deps = set(self.source_rec_deps) indirect_deps = set(all_deps) - set(self.source_deps) all_deps.add(self) ld_var = racy.renv.LD_VAR local_bins = [ opjoin(dep.local_dir, 'bin') for dep in all_deps ] local_libs = [ opjoin(dep.local_dir, 'lib') for dep in all_deps ] env.PrependENVPath('PATH', local_bins) env.PrependENVPath(ld_var, local_libs) keys_deps = ( ('DIRECT_DEP' , direct_deps), ('INDIRECT_DEP', indirect_deps), ('DEP' , all_deps), ) if self.compiler.startswith('cl'): inc_opt = ' /I' lib_opt = ' /L' else: inc_opt = ' -I' lib_opt = ' -L' kwdeps = {} for prefix, dependencies in keys_deps: deps_prj = dict( ('{0}_{1}'.format(prefix, p.name).upper(), p) for p in dependencies ) deps = dict( (n , p.local_dir) for n, p in deps_prj.items()) items = deps.items() deps_include = dict((k+'_INCLUDE', v+'/include') for k,v in items) deps_lib = dict((k+'_LIB' , v+'/lib' ) for k,v in items) deps_bin = dict((k+'_BIN' , v+'/bin' ) for k,v in items) deps_ver = dict((k+'_VERSION', p.version) for k,p in deps_prj.items()) if prefix == 'DEP': kwdeps.update(deps) kwdeps.update(deps_include) kwdeps.update(deps_lib) kwdeps.update(deps_bin) kwdeps.update(deps_ver) join = os.pathsep.join vars = { '{0}S' : join(deps.values()), '{0}S_INCLUDE': join(deps_include.values()), '{0}S_LIB' : join(deps_lib.values()), '{0}S_BIN' : join(deps_bin.values()), '{0}S_INCLUDE_FLAGS' : inc_opt.join([''] + deps_include.values()), '{0}S_LIB_FLAGS' : lib_opt.join([''] + deps_lib.values()), } for k, v in vars.items(): kwdeps[k.format(prefix)] = v download_target = env.Dir(prj.download_target) extract_dir = env.Dir(prj.extract_dir) kwargs = { 'DOWNLOAD_DIR' : download_target, 'EXTRACT_DIR' : extract_dir , 'BUILD_DIR' : prj.build_dir , 'LOCAL_DIR' : prj.local_dir , 'RC_DIR' : prj.rc_path , 'NAME' : prj.name , 'VERSION' : prj.version , 'VERSION_DASHED' : prj.version.dashed , 'VERSION_DOTTED' : prj.version.dotted , 'VERSION_UNDERSCORED' : prj.version.underscored , '_VERSION_' : prj.version.underscored , #'LIBEXT_INCLUDE_PATH' : os.pathsep.join(prj.deps_include_path), #'LIBEXT_LIBRARY_PATH' : os.pathsep.join(prj.deps_lib_path), 'CURRENT_PROJECT' : self.name , } kwargs.update(kwdeps) if self.is_debug: BuildType = 'Debug' kwargs['IS_DEBUG'] = True kwargs['DEBUG_FLAG'] = 'd' kwargs['RELEASE_FLAG'] = '' kwargs['DEBUGONOFF'] = 'on' kwargs['DEBUGYESNO'] = 'yes' else: BuildType = 'Release' kwargs['IS_DEBUG'] = False kwargs['DEBUG_FLAG'] = '' kwargs['RELEASE_FLAG'] = 'r' kwargs['DEBUGONOFF'] = 'off' kwargs['DEBUGYESNO'] = 'no' kwargs['BuildType'] = BuildType kwargs['BUILDTYPE'] = BuildType.upper() kwargs['buildtype'] = BuildType.lower() kwargs['lower'] = str.upper kwargs['upper'] = str.lower kwargs['winpathsep'] = lambda s:s.replace(':',';') kwargs['unixpathsep'] = lambda s:s.replace(';',':') kwargs['winsep'] = lambda s:s.replace('/','\\') kwargs['unixsep'] = lambda s:s.replace('\\','/') kwargs['winlinesep'] = lambda s:s.replace('\n','\r\n') kwargs['unixlinesep'] = lambda s:s.replace('\r\n','\n') kwargs['SYSTEM'] = racy.renv.platform() kwargs['COMPILER'] = str(prj.compiler) kwargs['NOW'] = time.ctime() return kwargs def configure_consumer(self, consumer, self_configure = True): direct_deps = self.source_deps for d in direct_deps: d.configure_consumer(consumer) if self_configure: configure = self.prj_locals.get('configure_consumer') if configure is not None: configure(consumer) @run_once def configure_env(self): prj = self env = self.env self.ENV.update(self.environment) env.Append(**self.ENV) #super(LibextProject, self).configure_env() @memoize def result(self, deps_results=True): prj = self env = self.env result = [] class ConfigureMethods(object): prj = self for name, f in self.env_functions.items(): locals()[name] = f prj.configure_env() prj.configure_consumer(ConfigureMethods, False) command = CommandWrapper(prj,'SysCommand') prj.prj_locals['generate']() if racy.renv.is_darwin(): install_tool = opjoin(racy.get_bin_path(),'..','Utils', 'osx_install_name_tool.py') libs = [self.lib_path] deps_lib = self.ENV['DEPS_LIB'] if deps_lib: libs += deps_lib.split(':') command(['python', install_tool, '-i', '-a', '-P','*', '-s',self.build_bin_path] + libs , pwd = '.') #import defined strings and functions from generate method for k,v in self.ENV.items(): if isinstance(v, basestring) or callable(v): env[k] = v res = [ self.MkdirBuilder('${LOCAL_DIR}'), self.MkdirBuilder('${LOCAL_DIR}/bin'), self.MkdirBuilder('${LOCAL_DIR}/lib'), self.MkdirBuilder('${LOCAL_DIR}/include'), ] res += BuilderWrapper.apply_calls( prj, **self.ENV ) downloads = [x for x in res if self.download_target in str(x)] map(res.remove, downloads) res = downloads + res previous_node = [] for nodes in res: if not isinstance(nodes, LibextProject): for node in nodes: #HACK: scons need a name attribute to manage dependencies if not hasattr(node, "name"): node.name = '' env.Depends( node, previous_node ) previous_node = node elif deps_results: previous_node = [previous_node, nodes.deps_build_nodes] if not isinstance(nodes, LibextProject): result += nodes else: result += previous_node for node in [prj.extract_dir]: env.Clean(node, node) alias = 'result-{prj.type}-{prj.full_name}' result = env.Alias (alias.format(prj=self), result) return result def build(self, build_deps = True): """build_deps = False is not available""" res = self.result(build_deps) return res @cached_property def install_nodes(self): prj = self env = self.env initmodel = opjoin(prj.rc_path,'__init__.py') if os.path.isfile(initmodel): content = rutils.get_file_content(initmodel) initfile = opjoin(prj.local_dir, '__init__.py') write = prj.WriteBuilder(initfile, content) copy = prj.CopyBuilder( '${LOCAL_DIR}', prj.install_pkg_path, marker_name='InstallPkgs' ) env.Depends(copy, write) return [copy, write] @memoize def install (self, opts = ['rc','deps']): prj = self env = self.env install_deps = 'deps' in opts result = prj.build(build_deps=install_deps) nodes = self.install_nodes env.Depends(nodes, result) result = nodes alias = 'install-{prj.type}-{prj.full_name}' result = env.Alias (alias.format(prj=prj), result) if install_deps: env.Depends(result, prj.deps_install_nodes) return result
bsd-3-clause
mikejurka/engine
lib/ui/compositing/scene_host.cc
7988
// Copyright 2013 The Flutter 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 "flutter/lib/ui/compositing/scene_host.h" #include <lib/ui/scenic/cpp/view_token_pair.h> #include <lib/zx/eventpair.h> #include <third_party/tonic/dart_args.h> #include <third_party/tonic/dart_binding_macros.h> #include <third_party/tonic/logging/dart_invoke.h> #include "flutter/flow/view_holder.h" #include "flutter/fml/thread_local.h" #include "flutter/lib/ui/ui_dart_state.h" #include "third_party/dart/runtime/include/dart_api.h" namespace { struct SceneHostBindingKey { std::string isolate_service_id; zx_koid_t koid; SceneHostBindingKey(const zx_koid_t koid, const std::string isolate_service_id) { this->koid = koid; this->isolate_service_id = isolate_service_id; } bool operator==(const SceneHostBindingKey& other) const { return isolate_service_id == other.isolate_service_id && koid == other.koid; } }; struct SceneHostBindingKeyHasher { std::size_t operator()(const SceneHostBindingKey& key) const { std::size_t koid_hash = std::hash<zx_koid_t>()(key.koid); std::size_t isolate_hash = std::hash<std::string>()(key.isolate_service_id); return koid_hash ^ isolate_hash; } }; using SceneHostBindings = std::unordered_map<SceneHostBindingKey, flutter::SceneHost*, SceneHostBindingKeyHasher>; static SceneHostBindings scene_host_bindings; void SceneHost_constructor(Dart_NativeArguments args) { tonic::DartCallConstructor(&flutter::SceneHost::Create, args); } flutter::SceneHost* GetSceneHost(scenic::ResourceId id, std::string isolate_service_id) { auto binding = scene_host_bindings.find(SceneHostBindingKey(id, isolate_service_id)); if (binding == scene_host_bindings.end()) { return nullptr; } else { return binding->second; } } flutter::SceneHost* GetSceneHostForCurrentIsolate(scenic::ResourceId id) { auto isolate = Dart_CurrentIsolate(); if (!isolate) { return nullptr; } else { std::string isolate_service_id = Dart_IsolateServiceId(isolate); return GetSceneHost(id, isolate_service_id); } } void InvokeDartClosure(const tonic::DartPersistentValue& closure) { auto dart_state = closure.dart_state().lock(); if (!dart_state) { return; } tonic::DartState::Scope scope(dart_state); auto dart_handle = closure.value(); FML_DCHECK(dart_handle && !Dart_IsNull(dart_handle) && Dart_IsClosure(dart_handle)); tonic::DartInvoke(dart_handle, {}); } template <typename T> void InvokeDartFunction(const tonic::DartPersistentValue& function, T& arg) { auto dart_state = function.dart_state().lock(); if (!dart_state) { return; } tonic::DartState::Scope scope(dart_state); auto dart_handle = function.value(); FML_DCHECK(dart_handle && !Dart_IsNull(dart_handle) && Dart_IsClosure(dart_handle)); tonic::DartInvoke(dart_handle, {tonic::ToDart(arg)}); } zx_koid_t GetKoid(zx_handle_t handle) { zx_info_handle_basic_t info; zx_status_t status = zx_object_get_info(handle, ZX_INFO_HANDLE_BASIC, &info, sizeof(info), nullptr, nullptr); return status == ZX_OK ? info.koid : ZX_KOID_INVALID; } } // namespace namespace flutter { IMPLEMENT_WRAPPERTYPEINFO(ui, SceneHost); #define FOR_EACH_BINDING(V) \ V(SceneHost, dispose) \ V(SceneHost, setProperties) FOR_EACH_BINDING(DART_NATIVE_CALLBACK) void SceneHost::RegisterNatives(tonic::DartLibraryNatives* natives) { natives->Register({{"SceneHost_constructor", SceneHost_constructor, 5, true}, FOR_EACH_BINDING(DART_REGISTER_NATIVE)}); } fml::RefPtr<SceneHost> SceneHost::Create( fml::RefPtr<zircon::dart::Handle> viewHolderToken, Dart_Handle viewConnectedCallback, Dart_Handle viewDisconnectedCallback, Dart_Handle viewStateChangedCallback) { return fml::MakeRefCounted<SceneHost>(viewHolderToken, viewConnectedCallback, viewDisconnectedCallback, viewStateChangedCallback); } void SceneHost::OnViewConnected(scenic::ResourceId id) { auto* scene_host = GetSceneHostForCurrentIsolate(id); if (scene_host && !scene_host->view_connected_callback_.is_empty()) { InvokeDartClosure(scene_host->view_connected_callback_); } } void SceneHost::OnViewDisconnected(scenic::ResourceId id) { auto* scene_host = GetSceneHostForCurrentIsolate(id); if (scene_host && !scene_host->view_disconnected_callback_.is_empty()) { InvokeDartClosure(scene_host->view_disconnected_callback_); } } void SceneHost::OnViewStateChanged(scenic::ResourceId id, bool state) { auto* scene_host = GetSceneHostForCurrentIsolate(id); if (scene_host && !scene_host->view_state_changed_callback_.is_empty()) { InvokeDartFunction(scene_host->view_state_changed_callback_, state); } } SceneHost::SceneHost(fml::RefPtr<zircon::dart::Handle> viewHolderToken, Dart_Handle viewConnectedCallback, Dart_Handle viewDisconnectedCallback, Dart_Handle viewStateChangedCallback) : gpu_task_runner_( UIDartState::Current()->GetTaskRunners().GetGPUTaskRunner()), koid_(GetKoid(viewHolderToken->handle())) { auto dart_state = UIDartState::Current(); isolate_service_id_ = Dart_IsolateServiceId(Dart_CurrentIsolate()); // Initialize callbacks it they are non-null in Dart. if (!Dart_IsNull(viewConnectedCallback)) { view_connected_callback_.Set(dart_state, viewConnectedCallback); } if (!Dart_IsNull(viewDisconnectedCallback)) { view_disconnected_callback_.Set(dart_state, viewDisconnectedCallback); } if (!Dart_IsNull(viewStateChangedCallback)) { view_state_changed_callback_.Set(dart_state, viewStateChangedCallback); } // This callback will be posted as a task when the |scenic::ViewHolder| // resource is created and given an id by the GPU thread. auto bind_callback = [scene_host = this, isolate_service_id = isolate_service_id_](scenic::ResourceId id) { const auto key = SceneHostBindingKey(id, isolate_service_id); scene_host_bindings.emplace(std::make_pair(key, scene_host)); }; // Pass the raw handle to the GPU thead; destroying a |zircon::dart::Handle| // on that thread can cause a race condition. gpu_task_runner_->PostTask( [id = koid_, ui_task_runner = UIDartState::Current()->GetTaskRunners().GetUITaskRunner(), raw_handle = viewHolderToken->ReleaseHandle(), bind_callback]() { flutter::ViewHolder::Create( id, std::move(ui_task_runner), scenic::ToViewHolderToken(zx::eventpair(raw_handle)), std::move(bind_callback)); }); } SceneHost::~SceneHost() { scene_host_bindings.erase(SceneHostBindingKey(koid_, isolate_service_id_)); gpu_task_runner_->PostTask( [id = koid_]() { flutter::ViewHolder::Destroy(id); }); } void SceneHost::dispose() { ClearDartWrapper(); } void SceneHost::setProperties(double width, double height, double insetTop, double insetRight, double insetBottom, double insetLeft, bool focusable) { gpu_task_runner_->PostTask([id = koid_, width, height, insetTop, insetRight, insetBottom, insetLeft, focusable]() { auto* view_holder = flutter::ViewHolder::FromId(id); FML_DCHECK(view_holder); view_holder->SetProperties(width, height, insetTop, insetRight, insetBottom, insetLeft, focusable); }); } } // namespace flutter
bsd-3-clause
helderfpires/io-tools
easystream/src/main/java/com/gc/iotools/stream/is/CloseOnceInputStream.java
2295
package com.gc.iotools.stream.is; /* * Copyright (c) 2008, 2014 Gabriele Contini. This source code is released * under the BSD License. */ import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; /** * <p> * A <code>CloseOnceInputStream</code> contains some other input stream, which * it uses as its basic source of data. The class * <code>CloseOnceInputStream</code> pass all requests to the contained input * stream, except the {@linkplain #close()} method that is passed only one * time to the underlying stream. * </p> * <p> * Multiple invocation of the <code>close()</code> method will result in only * one invocation of the same method on the underlying stream. This is useful * with some buggy <code>InputStream</code> that don't allow * <code>close()</code> to be called multiple times. * </p> * * @author dvd.smnt * @since 1.2.6 * @param <T> * Type of the InputStream passed in the constructor. * @version $Id$ */ public class CloseOnceInputStream<T extends InputStream> extends FilterInputStream { private int closeCount = 0; /** * Construct a <code>CloseOnceInputStream</code> that forwards the calls * to the source InputStream passed in the constructor. * * @param source * original InputStream */ public CloseOnceInputStream(final T source) { super(source); } /** * {@inheritDoc} * * <p> * Multiple invocation of this method will result in only one invocation * of the <code>close()</code> on the underlying stream. * </p> */ @Override public void close() throws IOException { synchronized (this) { this.closeCount++; if (this.closeCount > 1) { return; } } super.close(); } /** * Returns the number of time that close was called. * * @see com.gc.iotools.stream.is.inspection.DiagnosticInputStream * @return Number of times that close was called */ public int getCloseCount() { return this.closeCount; } /** * <p> * Returns the wrapped (original) <code>InputStream</code> passed in the * constructor. * </p> * * @return The original <code>InputStream</code> passed in the constructor */ public T getWrappedInputStream() { @SuppressWarnings("unchecked") final T result = (T) super.in; return result; } }
bsd-3-clause
ComponentFactory/Krypton
Source/Krypton Components/ComponentFactory.Krypton.Navigator/View Draw/ViewDrawNavRibbonTab.cs
27773
// ***************************************************************************** // // © Component Factory Pty Ltd 2017. All rights reserved. // The software and associated documentation supplied hereunder are the // proprietary information of Component Factory Pty Ltd, 13 Swallows Close, // Mornington, Vic 3931, Australia and are supplied subject to licence terms. // // Version 4.6.0.0 www.ComponentFactory.com // ***************************************************************************** using System; using System.Text; using System.Drawing; using System.Drawing.Drawing2D; using System.Collections.Generic; using System.Windows.Forms; using System.Diagnostics; using System.ComponentModel; using ComponentFactory.Krypton.Toolkit; namespace ComponentFactory.Krypton.Navigator { internal class ViewDrawNavRibbonTab : ViewComposite, IContentValues, INavCheckItem { #region Static Fields private static Padding _preferredBorder = new Padding(5, 5, 5, 2); private static Padding _layoutBorderTop = new Padding(4, 4, 4, 1); private static Padding _layoutBorderLeft = new Padding(5, 4, 3, 1); private static Padding _layoutBorderRight = new Padding(4, 5, 4, 0); private static Padding _layoutBorderBottom = new Padding(4, 2, 4, 3); private static Padding _drawBorder = new Padding(1, 0, 1, 0); #endregion #region Events /// <summary> /// Occurs when the drag rectangle for the button is required. /// </summary> public event EventHandler<ButtonDragRectangleEventArgs> ButtonDragRectangle; /// <summary> /// Occurs when the drag button offset changes. /// </summary> public event EventHandler<ButtonDragOffsetEventArgs> ButtonDragOffset; #endregion #region Instance Fields private KryptonPage _page; private KryptonNavigator _navigator; private ButtonSpecNavManagerLayoutBar _buttonManager; private PageButtonController _buttonController; private IPaletteRibbonGeneral _paletteGeneral; private PaletteRibbonTabContentInheritOverride _overrideStateNormal; private PaletteRibbonTabContentInheritOverride _overrideStateTracking; private PaletteRibbonTabContentInheritOverride _overrideStatePressed; private PaletteRibbonTabContentInheritOverride _overrideStateSelected; private IPaletteRibbonText _currentText; private IPaletteRibbonBack _currentBack; private IPaletteContent _currentContent; private RibbonTabToContent _contentProvider; private VisualOrientation _borderBackOrient; private NeedPaintHandler _needPaint; private ViewDrawContent _viewContent; private ViewLayoutDocker _layoutDocker; private PaletteRibbonShape _lastRibbonShape; private IDisposable[] _mementos; private DateTime _lastClick; private bool _checked; #endregion #region Identity /// <summary> /// Initialize a new instance of the ViewDrawNavRibbonTab class. /// </summary> /// <param name="navigator">Owning navigator instance.</param> /// <param name="page">Page this ribbon tab represents.</param> public ViewDrawNavRibbonTab(KryptonNavigator navigator, KryptonPage page) { Debug.Assert(navigator != null); Debug.Assert(page != null); _navigator = navigator; _page = page; _lastClick = DateTime.Now.AddDays(-1); // Associate the page component with this view element Component = page; // Create a controller for managing button behavior _buttonController = new PageButtonController(this, new NeedPaintHandler(OnNeedPaint)); _buttonController.ClickOnDown = true; _buttonController.Click += new MouseEventHandler(OnClick); _buttonController.RightClick += new MouseEventHandler(OnRightClick); // Allow the page to be dragged and hook into drag events _buttonController.AllowDragging = true; _buttonController.DragStart += new EventHandler<DragStartEventCancelArgs>(OnDragStart); _buttonController.DragMove += new EventHandler<PointEventArgs>(OnDragMove); _buttonController.DragEnd += new EventHandler<PointEventArgs>(OnDragEnd); _buttonController.DragQuit += new EventHandler(OnDragQuit); _buttonController.ButtonDragRectangle += new EventHandler<ButtonDragRectangleEventArgs>(OnButtonDragRectangle); _buttonController.ButtonDragOffset += new EventHandler<ButtonDragOffsetEventArgs>(OnButtonDragOffset); // A tab is selected on being pressed and not on the mouse up _buttonController.ClickOnDown = true; // We need to be notified of got/lost focus and keyboard events SourceController = _buttonController; KeyController = _buttonController; // Create a decorator to interface with the tooltip manager ToolTipController toolTipController = new ToolTipController(_navigator.ToolTipManager, this, _buttonController); ToolTipController hoverController = new ToolTipController(_navigator.HoverManager, this, toolTipController); // Assign controller for handing mouse input MouseController = hoverController; // Create overrides for handling a focus state _paletteGeneral = _navigator.StateCommon.RibbonGeneral; _overrideStateNormal = new PaletteRibbonTabContentInheritOverride(_page.OverrideFocus.RibbonTab.TabDraw, _page.OverrideFocus.RibbonTab.TabDraw, _page.OverrideFocus.RibbonTab.Content, _page.StateNormal.RibbonTab.TabDraw, _page.StateNormal.RibbonTab.TabDraw, _page.StateNormal.RibbonTab.Content, PaletteState.FocusOverride); _overrideStateTracking = new PaletteRibbonTabContentInheritOverride(_page.OverrideFocus.RibbonTab.TabDraw, _page.OverrideFocus.RibbonTab.TabDraw, _page.OverrideFocus.RibbonTab.Content, _page.StateTracking.RibbonTab.TabDraw, _page.StateTracking.RibbonTab.TabDraw, _page.StateTracking.RibbonTab.Content, PaletteState.FocusOverride); _overrideStatePressed = new PaletteRibbonTabContentInheritOverride(_page.OverrideFocus.RibbonTab.TabDraw, _page.OverrideFocus.RibbonTab.TabDraw, _page.OverrideFocus.RibbonTab.Content, _page.StatePressed.RibbonTab.TabDraw, _page.StatePressed.RibbonTab.TabDraw, _page.StatePressed.RibbonTab.Content, PaletteState.FocusOverride); _overrideStateSelected = new PaletteRibbonTabContentInheritOverride(_page.OverrideFocus.RibbonTab.TabDraw, _page.OverrideFocus.RibbonTab.TabDraw, _page.OverrideFocus.RibbonTab.Content, _page.StateSelected.RibbonTab.TabDraw, _page.StateSelected.RibbonTab.TabDraw, _page.StateSelected.RibbonTab.Content, PaletteState.FocusOverride); // Use a class to convert from ribbon tab to content interface _contentProvider = new RibbonTabToContent(_paletteGeneral, _overrideStateNormal, _overrideStateNormal); // Create the content view element and use the content provider as a way to // convert from the ribbon palette entries to the content palette entries _viewContent = new ViewDrawContent(_contentProvider, this, VisualOrientation.Top); // Add content to the view _layoutDocker = new ViewLayoutDocker(); _layoutDocker.Add(_viewContent, ViewDockStyle.Fill); Add(_layoutDocker); // Create button specification collection manager _buttonManager = new ButtonSpecNavManagerLayoutBar(Navigator, Navigator.InternalRedirector, Page.ButtonSpecs, null, new ViewLayoutDocker[] { _layoutDocker }, new IPaletteMetric[] { Navigator.StateCommon }, new PaletteMetricInt[] { PaletteMetricInt.PageButtonInset }, new PaletteMetricInt[] { PaletteMetricInt.PageButtonInset }, new PaletteMetricPadding[] { PaletteMetricPadding.PageButtonPadding }, new GetToolStripRenderer(Navigator.CreateToolStripRenderer), new NeedPaintHandler(OnNeedPaint)); // Hook up the tooltip manager so that tooltips can be generated _buttonManager.ToolTipManager = Navigator.ToolTipManager; _buttonManager.RemapTarget = ButtonSpecNavRemap.ButtonSpecRemapTarget.ButtonStandalone; // Ensure current button specs are created _buttonManager.RecreateButtons(); // Create the state specific memento array _mementos = new IDisposable[Enum.GetValues(typeof(PaletteState)).Length]; // Cache the last shape encountered _lastRibbonShape = PaletteRibbonShape.Office2010; } /// <summary> /// Obtains the String representation of this instance. /// </summary> /// <returns>User readable name of the instance.</returns> public override string ToString() { // Return the class name and instance identifier return "ViewDrawNavRibbonTab:" + Id; } /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing) { if (_mementos != null) { // Dispose of all the mementos in the array foreach (IDisposable memento in _mementos) if (memento != null) memento.Dispose(); _mementos = null; } if (_buttonManager != null) { _buttonManager.Destruct(); _buttonManager = null; } } base.Dispose(disposing); } #endregion #region Public /// <summary> /// Gets the view associated with the ribbon tab. /// </summary> public ViewBase View { get { return this; } } /// <summary> /// Gets the page this ribbon tab represents. /// </summary> public KryptonPage Page { get { return _page; } } /// <summary> /// Gets the navigator this check item is inside. /// </summary> public KryptonNavigator Navigator { get { return _navigator; } } /// <summary> /// Gets and sets the checked state of the ribbon tab. /// </summary> public bool Checked { get { return _checked; } set { _checked = value; } } /// <summary> /// Gets and sets if the ribbon tab has the focus. /// </summary> public bool HasFocus { get { return _overrideStateNormal.Apply; } set { if (_overrideStateNormal.Apply != value) { _overrideStateNormal.Apply = value; _overrideStateTracking.Apply = value; _overrideStatePressed.Apply = value; _overrideStateSelected.Apply = value; } } } /// <summary> /// Gets and sets the need paint delegate for notifying paint requests. /// </summary> public NeedPaintHandler NeedPaint { get { return _needPaint; } set { // Warn if multiple sources want to hook their single delegate Debug.Assert(((_needPaint == null) && (value != null)) || ((_needPaint != null) && (value == null))); _needPaint = value; } } /// <summary> /// Gets the ButtonSpec associated with the provided item. /// </summary> /// <param name="element">Element to search against.</param> /// <returns>Reference to ButtonSpec; otherwise null.</returns> public ButtonSpec ButtonSpecFromView(ViewBase element) { if (_buttonManager != null) return _buttonManager.ButtonSpecFromView(element); else return null; } /// <summary> /// Gets access to the button spec manager used for this button. /// </summary> public ButtonSpecNavManagerLayoutBar ButtonSpecManager { get { return _buttonManager; } } /// <summary> /// Raises the Click event for the button. /// </summary> public void PerformClick() { OnClick(this, EventArgs.Empty); } /// <summary> /// Set the orientation of the background/border and content. /// </summary> /// <param name="borderBackOrient">Orientation of the button border and background..</param> /// <param name="contentOrient">Orientation of the button contents.</param> public void SetOrientation(VisualOrientation borderBackOrient, VisualOrientation contentOrient) { _borderBackOrient = borderBackOrient; _viewContent.Orientation = contentOrient; } #endregion #region Layout /// <summary> /// Discover the preferred size of the element. /// </summary> /// <param name="context">Layout context.</param> public override Size GetPreferredSize(ViewLayoutContext context) { // Work out the size needed for the child items Size childSize = base.GetPreferredSize(context); // Add the preferred border based on our orientation return CommonHelper.ApplyPadding(_borderBackOrient, childSize, _preferredBorder); } /// <summary> /// Perform a layout of the elements. /// </summary> /// <param name="context">Layout context.</param> public override void Layout(ViewLayoutContext context) { // Ensure we are using the correct palette CheckPaletteState(context); // Cache the ribbon shape _lastRibbonShape = (_navigator.Palette == null ? PaletteRibbonShape.Office2007 : _navigator.Palette.GetRibbonShape()); // We take on all the provided size ClientRectangle = context.DisplayRectangle; Padding layoutPadding = Padding.Empty; switch (_borderBackOrient) { case VisualOrientation.Top: layoutPadding = _layoutBorderTop; break; case VisualOrientation.Left: layoutPadding = _layoutBorderLeft; break; case VisualOrientation.Right: layoutPadding = _layoutBorderRight; break; case VisualOrientation.Bottom: layoutPadding = _layoutBorderBottom; break; } // Reduce the display size by our border spacing context.DisplayRectangle = CommonHelper.ApplyPadding(_borderBackOrient, context.DisplayRectangle, layoutPadding); // Layout the content using the reduced size base.Layout(context); // Put back the original size before returning context.DisplayRectangle = ClientRectangle; } #endregion #region Paint /// <summary> /// Perform a render of the elements. /// </summary> /// <param name="context">Rendering context.</param> public override void Render(RenderContext context) { // Ensure we are using the correct palette CheckPaletteState(context); // Use renderer to draw the tab background int mementoIndex = StateIndex(State); _mementos[mementoIndex] = context.Renderer.RenderRibbon.DrawRibbonBack(_lastRibbonShape, context, CommonHelper.ApplyPadding(_borderBackOrient, ClientRectangle, _drawBorder), State, _currentBack, _borderBackOrient, false, _mementos[mementoIndex]); // Let base class draw the child items base.Render(context); } #endregion #region IContentValues /// <summary> /// Gets the content short text. /// </summary> /// <returns>String value.</returns> public string GetShortText() { return _page.GetTextMapping(_navigator.Bar.BarMapText); } /// <summary> /// Gets the content image. /// </summary> /// <param name="state">The state for which the image is needed.</param> /// <returns>Image value.</returns> public Image GetImage(PaletteState state) { return _page.GetImageMapping(_navigator.Bar.BarMapImage); } /// <summary> /// Gets the image color that should be transparent. /// </summary> /// <param name="state">The state for which the image is needed.</param> /// <returns>Color value.</returns> public Color GetImageTransparentColor(PaletteState state) { return Color.Empty; } /// <summary> /// Gets the content long text. /// </summary> /// <returns>String value.</returns> public string GetLongText() { return _page.GetTextMapping(_navigator.Bar.BarMapExtraText); } #endregion #region Protected /// <summary> /// Processes the RightClick event from the button. /// </summary> /// <param name="sender">Source of the event.</param> /// <param name="e">An EventArgs containing the event data.</param> protected virtual void OnRightClick(object sender, MouseEventArgs e) { // Can only select the page if not already selected and allowed to select a tab if ((_navigator.SelectedPage != _page) && _navigator.AllowTabSelect) _navigator.SelectedPage = _page; // Generate event so user can decide what, if any, context menu to show ShowContextMenuArgs scma = new ShowContextMenuArgs(_page, _navigator.Pages.IndexOf(_page)); _navigator.OnShowContextMenu(scma); // Do we need to show a context menu if (!scma.Cancel) { if (CommonHelper.ValidKryptonContextMenu(scma.KryptonContextMenu)) scma.KryptonContextMenu.Show(_navigator, _navigator.PointToScreen(new Point(e.X, e.Y))); else if (scma.ContextMenuStrip != null) { if (CommonHelper.ValidContextMenuStrip(scma.ContextMenuStrip) && (scma.ContextMenuStrip != null)) scma.ContextMenuStrip.Show(_navigator.PointToScreen(new Point(e.X, e.Y))); } } } /// <summary> /// Raises the NeedPaint event. /// </summary> /// <param name="sender">Source of the event.</param> /// <param name="e">An NeedLayoutEventArgs containing event data.</param> protected virtual void OnNeedPaint(object sender, NeedLayoutEventArgs e) { if (_needPaint != null) _needPaint(this, e); } #endregion #region Implementation private int StateIndex(PaletteState state) { Array stateValues = Enum.GetValues(typeof(PaletteState)); for (int i = 0; i < stateValues.Length; i++) if ((PaletteState)stateValues.GetValue(i) == state) return i; return 0; } private void CheckPaletteState(ViewContext context) { // Default to using this element calculated state PaletteState buttonState = State; // If the actual control is not enabled, force to disabled state if (!IsFixed && !context.Control.Enabled) buttonState = PaletteState.Disabled; else if (buttonState == PaletteState.Disabled) buttonState = PaletteState.Normal; if (!IsFixed) { if (Checked) { switch (buttonState) { case PaletteState.Normal: case PaletteState.CheckedNormal: buttonState = PaletteState.CheckedNormal; break; case PaletteState.Tracking: case PaletteState.CheckedTracking: buttonState = PaletteState.CheckedTracking; break; case PaletteState.Pressed: case PaletteState.CheckedPressed: buttonState = PaletteState.CheckedPressed; break; } } else { switch (buttonState) { case PaletteState.Normal: case PaletteState.CheckedNormal: buttonState = PaletteState.Normal; break; case PaletteState.Tracking: case PaletteState.CheckedTracking: buttonState = PaletteState.Tracking; break; case PaletteState.Pressed: case PaletteState.CheckedPressed: buttonState = PaletteState.Pressed; break; } } } // Set the correct palette based on state switch (buttonState) { case PaletteState.Disabled: _currentText = Navigator.StateDisabled.RibbonTab.TabDraw; _currentBack = Navigator.StateDisabled.RibbonTab.TabDraw; _currentContent = Navigator.StateDisabled.RibbonTab.Content; break; case PaletteState.Normal: _currentText = _overrideStateNormal; _currentBack = _overrideStateNormal; _currentContent = _overrideStateNormal; break; case PaletteState.Tracking: _currentText = _overrideStateTracking; _currentBack = _overrideStateTracking; _currentContent = _overrideStateTracking; break; case PaletteState.Pressed: _currentText = _overrideStatePressed; _currentBack = _overrideStatePressed; _currentContent = _overrideStatePressed; break; case PaletteState.CheckedNormal: case PaletteState.CheckedTracking: case PaletteState.CheckedPressed: _currentText = _overrideStateSelected; _currentBack = _overrideStateSelected; _currentContent = _overrideStateSelected; break; default: // Should never happen! Debug.Assert(false); break; } // Switch the child elements over to correct state ElementState = buttonState; this[0][0].ElementState = buttonState; // Update content palette with the current ribbon text palette _contentProvider.PaletteRibbonText = _currentText; _contentProvider.PaletteContent = _currentContent; } private void OnClick(object sender, EventArgs e) { // Generate click event for the page header Navigator.OnTabClicked(new KryptonPageEventArgs(_page, Navigator.Pages.IndexOf(_page))); // If this click is within the double click time of the last one, generate the double click event. DateTime now = DateTime.Now; if ((now - _lastClick).TotalMilliseconds < SystemInformation.DoubleClickTime) { // Tell button controller to abort any drag attempt _buttonController.ClearDragRect(); // Generate click event for the page header Navigator.OnTabDoubleClicked(new KryptonPageEventArgs(_page, Navigator.Pages.IndexOf(_page))); // Prevent a third click causing another double click by resetting the now time backwards now = now.AddDays(-1); } _lastClick = now; // Can only select the page if not already selected and allowed a selected tab if ((Navigator.SelectedPage != _page) && Navigator.AllowTabSelect) Navigator.SelectedPage = _page; // If the page is actually now selected if (Navigator.SelectedPage == _page) { // If in a tabs only mode then show the popup for the page if (Navigator.NavigatorMode == NavigatorMode.BarRibbonTabOnly) Navigator.ShowPopupPage(Page, this, null); } } private void OnDragStart(object sender, DragStartEventCancelArgs e) { _navigator.InternalDragStart(e, _page); } private void OnDragMove(object sender, PointEventArgs e) { _navigator.InternalDragMove(e); } private void OnDragEnd(object sender, PointEventArgs e) { _navigator.InternalDragEnd(e); } private void OnDragQuit(object sender, EventArgs e) { _navigator.InternalDragQuit(); } private void OnButtonDragRectangle(object sender, ButtonDragRectangleEventArgs e) { if (ButtonDragRectangle != null) ButtonDragRectangle(this, e); } private void OnButtonDragOffset(object sender, ButtonDragOffsetEventArgs e) { if (ButtonDragOffset != null) ButtonDragOffset(this, e); } #endregion } }
bsd-3-clause
globocom/database-as-a-service
dbaas/maintenance/scripts/filer_migrate.py
4891
from datetime import datetime from socket import gethostname from notification.models import TaskHistory from logical.models import Database from util.providers import get_filer_migrate_steps from workflow.workflow import steps_for_instances from maintenance.models import FilerMigrate as FilerMigrateManager class FilerMigrate(object): TASK_NAME = "migrate_filer_disk_for_database" def __init__(self, databases=None): self._task = None self._databases = databases or None @property def databases(self): if not self._databases: self._databases = Database.objects.all() return self._databases @databases.setter def databases(self, val): self._databases = val @property def task(self): if not self._task: self._task = self.register_task() return self._task def do(self): if not self.databases: self.load_all_databases() self.start_migration() def load_all_databases(self): self.task.add_detail("Getting all databases...") self.databases = Database.objects.all() self.task.add_detail("Loaded\n", level=2) def _can_run(self, database, task): if database.is_being_used_elsewhere([self.TASK_NAME]): task.add_detail( "ERROR-{}-Being used to another task".format(database.name), level=2 ) task.set_status_error( 'Database is being used by another task' ) return return True def set_error(self, task, step_manager): task.set_status_error('Could not migrate filer') step_manager.set_error() print('task {} with status {}.'.format( task.id, task.task_status) ) def migrate_filer_disk_for_database(self, database): infra = database.infra class_path = infra.plan.replication_topology.class_path steps = get_filer_migrate_steps(class_path) task = self.register_task(database) instances = self._get_instances(infra) step_manager = self.register_step_manager(task, instances) if not self._can_run(database, task): self.set_error(task, step_manager) return task.add_detail( "Migrating disk for database {}...".format(database.name), level=2 ) steps_result = steps_for_instances( steps, instances, task, step_counter_method=step_manager.update_step, since_step=step_manager.current_step ) if not steps_result: self.set_error(task, step_manager) return task.set_status_success('Migrate filer finished with success') def start_migration(self): for database in self.databases: self.migrate_filer_disk_for_database(database) def _get_instances(self, infra): instances = [] for host in infra.hosts: database_instance = host.database_instance() if database_instance: instances.append(database_instance) return instances def register_step_manager(self, task, instances): old_step_manager = FilerMigrateManager.objects.filter( database_id=task.db_id, can_do_retry=True, status=FilerMigrateManager.ERROR ) if old_step_manager.exists(): step_manager = old_step_manager[0] step_manager.id = None step_manager.save() else: step_manager = FilerMigrateManager() step_manager.task = task original_export_id = '' for instance in instances: active_volume = instance.hostname.volumes.get(is_active=True) original_export_id += 'host_{}: export_{} '.format( active_volume.host.id, active_volume.identifier ) step_manager.original_export_id = original_export_id step_manager.database_id = task.db_id step_manager.save() return step_manager def register_task(self, database): task_history = TaskHistory() task_history.task_id = datetime.now().strftime("%Y%m%d%H%M%S") task_history.task_name = self.TASK_NAME task_history.relevance = TaskHistory.RELEVANCE_WARNING task_history.task_status = TaskHistory.STATUS_RUNNING task_history.context = {'hostname': gethostname()} task_history.user = 'admin' task_history.db_id = database.id task_history.object_class = "logical_database" task_history.object_id = database.id task_history.database_name = database.name task_history.arguments = 'Database_name: {}'.format(database.name) task_history.save() return task_history
bsd-3-clause
broadinstitute/firecloud-orchestration
src/main/scala/org/broadinstitute/dsde/firecloud/dataaccess/GoogleServicesDAO.scala
2316
package org.broadinstitute.dsde.firecloud.dataaccess import java.io.InputStream import akka.http.scaladsl.model.HttpResponse import com.google.api.services.storage.model.Bucket import org.broadinstitute.dsde.firecloud.model.{ObjectMetadata, WithAccessToken} import org.broadinstitute.dsde.firecloud.service.PerRequest.PerRequestMessage import org.broadinstitute.dsde.rawls.model.ErrorReportSource import org.broadinstitute.dsde.workbench.model.google.{GcsBucketName, GcsObjectName, GcsPath} import org.broadinstitute.dsde.workbench.util.health.SubsystemStatus import scala.concurrent.{ExecutionContext, Future} object GoogleServicesDAO { lazy val serviceName = "Google" } trait GoogleServicesDAO extends ReportsSubsystemStatus { implicit val errorReportSource = ErrorReportSource(GoogleServicesDAO.serviceName) def getAdminUserAccessToken: String def getBucketObjectAsInputStream(bucketName: String, objectKey: String): InputStream def getObjectResourceUrl(bucketName: String, objectKey: String): String def getUserProfile(accessToken: WithAccessToken) (implicit executionContext: ExecutionContext): Future[HttpResponse] def getDownload(bucketName: String, objectKey: String, userAuthToken: WithAccessToken) (implicit executionContext: ExecutionContext): Future[PerRequestMessage] def getObjectMetadata(bucketName: String, objectKey: String, userAuthToken: String) (implicit executionContext: ExecutionContext): Future[ObjectMetadata] def listObjectsAsRawlsSA(bucketName: String, prefix: String): List[String] def getObjectContentsAsRawlsSA(bucketName: String, objectKey: String): String val fetchPriceList: Future[GooglePriceList] def writeObjectAsRawlsSA(bucketName: GcsBucketName, objectKey: GcsObjectName, objectContents: Array[Byte]): GcsPath def deleteGoogleGroup(groupEmail: String) : Unit def createGoogleGroup(groupName: String): Option[String] def addMemberToAnonymizedGoogleGroup(groupName: String, targetUserEmail: String): Option[String] def status: Future[SubsystemStatus] override def serviceName: String = GoogleServicesDAO.serviceName def publishMessages(fullyQualifiedTopic: String, messages: Seq[String]): Future[Unit] def getBucket(bucketName: String, petKey: String): Option[Bucket] }
bsd-3-clause
0X1A/kuma
src/flip.cpp
642
#include "flip.h" using namespace kuma; void Flippable::flip_vertical() { if (orientation != Flip::Vertical) { orientation = Flip::Vertical; } else { orientation_reset(); } } void Flippable::flip_horizontal() { if (orientation != Flip::Horizontal) { orientation = Flip::Horizontal; } else { orientation_reset(); } } void Flippable::flip_diagonal() { if (orientation != Flip::Diagonal) { orientation = Flip::Diagonal; } else { orientation_reset(); } } void Flippable::orientation_reset() { if (orientation != Flip::None) { orientation = Flip::None; } } Flip &Flippable::get_orientation() { return orientation; }
bsd-3-clause
elorian/crm.inreserve.kz
protected/modules/balance/views/merchantBalanceBackend/_form.php
3801
<?php /** * Отображение для _form: * * @category YupeView * @package yupe * @author Yupe Team <team@yupe.ru> * @license https://github.com/yupe/yupe/blob/master/LICENSE BSD * @link http://yupe.ru * * @var $model MerchantBalance * @var $form TbActiveForm * @var $this MerchantBalanceBackendController **/ $form = $this->beginWidget( 'bootstrap.widgets.TbActiveForm', [ 'id' => 'merchant-balance-form', 'enableAjaxValidation' => false, 'enableClientValidation' => true, 'htmlOptions' => ['class' => 'well'], ] ); ?> <div class="alert alert-info"> <?php echo Yii::t('BalanceModule.balance', 'Поля, отмеченные'); ?> <span class="required">*</span> <?php echo Yii::t('BalanceModule.balance', 'обязательны.'); ?> </div> <?php echo $form->errorSummary($model); ?> <div class="row"> <div class="col-sm-7"> <? if ($model->isNewRecord): echo $form->textFieldGroup($model, 'merchant_id', [ 'widgetOptions' => [ 'htmlOptions' => [ 'class' => 'popover-help', 'data-original-title' => $model->getAttributeLabel('merchant_id'), 'data-content' => $model->getAttributeDescription('merchant_id') ] ] ]); else: echo $form->dropDownListGroup($model, 'merchant_id', array( 'widgetOptions' => array( 'data' => $model->getMerchantList(), 'htmlOptions' => [ 'disabled' => true ], ))); endif; ?> </div> </div> <div class="row"> <div class="col-sm-7"> <?php echo $form->textFieldGroup($model, 'balance', [ 'widgetOptions' => [ 'htmlOptions' => [ 'class' => 'popover-help', 'data-original-title' => $model->getAttributeLabel('balance'), 'data-content' => $model->getAttributeDescription('balance') ] ] ]); ?> </div> </div> <div class="row"> <div class="col-sm-7"> <?php echo $form->dropDownListGroup($model, 'type', array( 'widgetOptions' => array( 'data' => $model->getTypeList(), ))); ?> </div> </div> <div class="row"> <div class="col-sm-7"> <?php echo $form->textFieldGroup($model, 'description', [ 'widgetOptions' => [ 'htmlOptions' => [ 'class' => 'popover-help', 'data-original-title' => $model->getAttributeLabel('description'), 'data-content' => $model->getAttributeDescription('description') ] ] ]); ?> </div> </div> <?php $this->widget( 'bootstrap.widgets.TbButton', [ 'buttonType' => 'submit', 'context' => 'primary', 'label' => Yii::t('BalanceModule.balance', 'Сохранить операцию и продолжить'), ] ); ?> <?php $this->widget( 'bootstrap.widgets.TbButton', [ 'buttonType' => 'submit', 'htmlOptions'=> ['name' => 'submit-type', 'value' => 'index'], 'label' => Yii::t('BalanceModule.balance', 'Сохранить операцию и закрыть'), ] ); ?> <?php $this->endWidget(); ?>
bsd-3-clause
mstriemer/zamboni
mkt/site/log.py
19207
from inspect import isclass from django.conf import settings from django.core.files.storage import get_storage_class from celery.datastructures import AttributeDict from tower import ugettext_lazy as _ __all__ = ('LOG', 'LOG_BY_ID', 'LOG_KEEP',) class _LOG(object): action_class = None class CREATE_ADDON(_LOG): id = 1 action_class = 'add' format = _(u'{addon} was created.') keep = True class EDIT_PROPERTIES(_LOG): """ Expects: addon """ id = 2 action_class = 'edit' format = _(u'{addon} properties edited.') class EDIT_DESCRIPTIONS(_LOG): id = 3 action_class = 'edit' format = _(u'{addon} description edited.') class EDIT_CATEGORIES(_LOG): id = 4 action_class = 'edit' format = _(u'Categories edited for {addon}.') class ADD_USER_WITH_ROLE(_LOG): id = 5 action_class = 'add' format = _(u'{0.name} ({1}) added to {addon}.') keep = True class REMOVE_USER_WITH_ROLE(_LOG): id = 6 action_class = 'delete' # L10n: {0} is the user being removed, {1} is their role. format = _(u'{0.name} ({1}) removed from {addon}.') keep = True class EDIT_CONTRIBUTIONS(_LOG): id = 7 action_class = 'edit' format = _(u'Contributions for {addon}.') class USER_DISABLE(_LOG): id = 8 format = _(u'{addon} disabled.') keep = True class USER_ENABLE(_LOG): id = 9 format = _(u'{addon} enabled.') keep = True # TODO(davedash): Log these types when pages are present class SET_PUBLIC_STATS(_LOG): id = 10 format = _(u'Stats set public for {addon}.') keep = True # TODO(davedash): Log these types when pages are present class UNSET_PUBLIC_STATS(_LOG): id = 11 format = _(u'{addon} stats set to private.') keep = True class CHANGE_STATUS(_LOG): id = 12 # L10n: {0} is the status format = _(u'{addon} status changed to {0}.') keep = True class ADD_PREVIEW(_LOG): id = 13 action_class = 'add' format = _(u'Preview added to {addon}.') class EDIT_PREVIEW(_LOG): id = 14 action_class = 'edit' format = _(u'Preview edited for {addon}.') class DELETE_PREVIEW(_LOG): id = 15 action_class = 'delete' format = _(u'Preview deleted from {addon}.') class ADD_VERSION(_LOG): id = 16 action_class = 'add' format = _(u'{version} added to {addon}.') keep = True class EDIT_VERSION(_LOG): id = 17 action_class = 'edit' format = _(u'{version} edited for {addon}.') class DELETE_VERSION(_LOG): id = 18 action_class = 'delete' # Note, {0} is a string not a version since the version is deleted. # L10n: {0} is the version number format = _(u'Version {0} deleted from {addon}.') keep = True class ADD_FILE_TO_VERSION(_LOG): id = 19 action_class = 'add' format = _(u'File {0.name} added to {version} of {addon}.') class DELETE_FILE_FROM_VERSION(_LOG): """ Expecting: addon, filename, version Because the file is being deleted, filename and version should be strings and not the object. """ id = 20 action_class = 'delete' format = _(u'File {0} deleted from {version} of {addon}.') class APPROVE_VERSION(_LOG): id = 21 action_class = 'approve' format = _(u'{addon} {version} approved.') short = _(u'Approved') keep = True review_email_user = True review_queue = True class PRELIMINARY_VERSION(_LOG): id = 42 action_class = 'approve' format = _(u'{addon} {version} given preliminary review.') short = _(u'Preliminarily approved') keep = True review_email_user = True review_queue = True class REJECT_VERSION(_LOG): # takes add-on, version, reviewtype id = 43 action_class = 'reject' format = _(u'{addon} {version} rejected.') short = _(u'Rejected') keep = True review_email_user = True review_queue = True class RETAIN_VERSION(_LOG): # takes add-on, version, reviewtype id = 22 format = _(u'{addon} {version} retained.') short = _(u'Retained') keep = True review_email_user = True review_queue = True class ESCALATE_VERSION(_LOG): # takes add-on, version, reviewtype id = 23 format = _(u'{addon} {version} escalated.') short = _(u'Escalated') keep = True review_email_user = True review_queue = True class REQUEST_VERSION(_LOG): # takes add-on, version, reviewtype id = 24 format = _(u'{addon} {version} review requested.') short = _(u'Review requested') keep = True review_email_user = True review_queue = True class REQUEST_INFORMATION(_LOG): id = 44 format = _(u'{addon} {version} more information requested.') short = _(u'More information requested') keep = True review_email_user = True review_queue = True class REQUEST_SUPER_REVIEW(_LOG): id = 45 format = _(u'{addon} {version} super review requested.') short = _(u'Super review requested') keep = True review_queue = True class COMMENT_VERSION(_LOG): id = 49 format = _(u'Comment on {addon} {version}.') short = _(u'Comment') keep = True review_queue = True hide_developer = True class ADD_TAG(_LOG): id = 25 action_class = 'tag' format = _(u'{tag} added to {addon}.') class REMOVE_TAG(_LOG): id = 26 action_class = 'tag' format = _(u'{tag} removed from {addon}.') class ADD_TO_COLLECTION(_LOG): id = 27 action_class = 'collection' format = _(u'{addon} added to {collection}.') class REMOVE_FROM_COLLECTION(_LOG): id = 28 action_class = 'collection' format = _(u'{addon} removed from {collection}.') class ADD_REVIEW(_LOG): id = 29 action_class = 'review' format = _(u'{review} for {addon} written.') # TODO(davedash): Add these when we do the admin site class ADD_RECOMMENDED_CATEGORY(_LOG): id = 31 action_class = 'edit' # L10n: {0} is a category name. format = _(u'{addon} featured in {0}.') class REMOVE_RECOMMENDED_CATEGORY(_LOG): id = 32 action_class = 'edit' # L10n: {0} is a category name. format = _(u'{addon} no longer featured in {0}.') class ADD_RECOMMENDED(_LOG): id = 33 format = _(u'{addon} is now featured.') keep = True class REMOVE_RECOMMENDED(_LOG): id = 34 format = _(u'{addon} is no longer featured.') keep = True class ADD_APPVERSION(_LOG): id = 35 action_class = 'add' # L10n: {0} is the application, {1} is the version of the app format = _(u'{0} {1} added.') class CHANGE_USER_WITH_ROLE(_LOG): """ Expects: author.user, role, addon """ id = 36 # L10n: {0} is a user, {1} is their role format = _(u'{0.name} role changed to {1} for {addon}.') keep = True class CHANGE_POLICY(_LOG): id = 38 action_class = 'edit' format = _(u'{addon} policy changed.') class CHANGE_ICON(_LOG): id = 39 action_class = 'edit' format = _(u'{addon} icon changed.') class APPROVE_REVIEW(_LOG): id = 40 action_class = 'approve' format = _(u'{review} for {addon} approved.') editor_format = _(u'{user} approved {review} for {addon}.') keep = True editor_event = True class DELETE_REVIEW(_LOG): """Requires review.id and add-on objects.""" id = 41 action_class = 'review' format = _(u'Review {review} for {addon} deleted.') editor_format = _(u'{user} deleted {review} for {addon}.') keep = True editor_event = True class MAX_APPVERSION_UPDATED(_LOG): id = 46 format = _(u'Application max version for {version} updated.') class BULK_VALIDATION_EMAILED(_LOG): id = 47 format = _(u'Authors emailed about compatibility of {version}.') class BULK_VALIDATION_USER_EMAILED(_LOG): id = 130 format = _(u'Email sent to Author about add-on compatibility.') class CHANGE_PASSWORD(_LOG): id = 48 format = _(u'Password changed.') class MAKE_PREMIUM(_LOG): id = 50 format = _(u'{addon} changed to premium.') class MANIFEST_UPDATED(_LOG): id = 52 format = _(u'{addon} manifest updated.') class APPROVE_VERSION_PRIVATE(_LOG): id = 53 action_class = 'approve' format = _(u'{addon} {version} approved but private.') short = _(u'Approved but private') keep = True review_email_user = True review_queue = True class PURCHASE_ADDON(_LOG): id = 54 format = _(u'{addon} purchased.') class INSTALL_ADDON(_LOG): id = 55 format = _(u'{addon} installed.') class REFUND_REQUESTED(_LOG): id = 56 format = _(u'Refund requested for {addon}') class REFUND_DECLINED(_LOG): id = 57 format = _(u'Refund declined for {addon} for {0}.') class REFUND_GRANTED(_LOG): id = 58 format = _(u'Refund granted for {addon} for {0}.') class REFUND_INSTANT(_LOG): id = 59 format = _(u'Instant refund granted for {addon}.') class USER_EDITED(_LOG): id = 60 format = _(u'Account updated.') class RECEIPT_CHECKED(_LOG): id = 65 format = _(u'Valid receipt was checked for {addon}.') class ESCALATION_CLEARED(_LOG): id = 66 format = _(u'Escalation cleared for {addon}.') short = _(u'Escalation cleared') keep = True review_queue = True class APP_DISABLED(_LOG): id = 67 format = _(u'{addon} banned.') short = _(u'App banned') keep = True review_queue = True class ESCALATED_HIGH_ABUSE(_LOG): id = 68 format = _(u'{addon} escalated because of high number of abuse reports.') short = _(u'High Abuse Reports') keep = True review_queue = True class ESCALATED_HIGH_REFUNDS(_LOG): id = 69 format = _(u'{addon} escalated because of high number of refund requests.') short = _(u'High Refund Requests') keep = True review_queue = True class REREVIEW_MANIFEST_CHANGE(_LOG): id = 70 format = _(u'{addon} re-reviewed because of manifest change.') short = _(u'Manifest Change') keep = True review_queue = True class REREVIEW_PREMIUM_TYPE_UPGRADE(_LOG): id = 71 format = _(u'{addon} re-reviewed because app upgraded premium type.') short = _(u'Premium Type Upgrade') keep = True review_queue = True class REREVIEW_CLEARED(_LOG): id = 72 format = _(u'Re-review cleared for {addon}.') short = _(u'Re-review cleared') keep = True review_queue = True class ESCALATE_MANUAL(_LOG): id = 73 format = _(u'{addon} escalated by reviewer.') short = _(u'Reviewer escalation') keep = True review_queue = True # TODO(robhudson): Escalation log for editor escalation.. class VIDEO_ERROR(_LOG): id = 74 format = _(u'Video removed from {addon} because of a problem with ' u'the video. ') short = _(u'Video removed') class REREVIEW_DEVICES_ADDED(_LOG): id = 75 format = _(u'{addon} re-review because of new device(s) added.') short = _(u'Device(s) Added') keep = True review_queue = True class REVIEW_DEVICE_OVERRIDE(_LOG): id = 76 format = _(u'{addon} device support manually changed by reviewer.') short = _(u'Device(s) Changed by Reviewer') keep = True review_queue = True class WEBAPP_RESUBMIT(_LOG): id = 77 format = _(u'{addon} resubmitted for review.') short = _(u'App Resubmission') keep = True review_queue = True class ESCALATION_VIP_APP(_LOG): id = 78 format = _(u'{addon} auto-escalated because its a VIP app.') short = _(u'VIP auto-escalation') keep = True review_queue = True class REREVIEW_MANIFEST_URL_CHANGE(_LOG): id = 79 format = _(u'{addon} re-reviewed because of manifest URL change.') short = _(u'Manifest URL Change') keep = True review_queue = True class ESCALATION_PRERELEASE_APP(_LOG): id = 80 format = _(u'{addon} auto-escalated because its a prerelease app.') short = _(u'Prerelease auto-escalation') keep = True review_queue = True class CUSTOM_TEXT(_LOG): id = 98 format = '{0}' class CUSTOM_HTML(_LOG): id = 99 format = '{0}' class OBJECT_ADDED(_LOG): id = 100 format = _(u'Created: {0}.') admin_event = True class OBJECT_EDITED(_LOG): id = 101 format = _(u'Edited field: {2} set to: {0}.') admin_event = True class OBJECT_DELETED(_LOG): id = 102 format = _(u'Deleted: {1}.') admin_event = True class ADMIN_USER_EDITED(_LOG): id = 103 format = _(u'User {user} edited, reason: {1}') admin_event = True class ADMIN_USER_ANONYMIZED(_LOG): id = 104 format = _(u'User {user} anonymized.') admin_event = True class ADMIN_USER_RESTRICTED(_LOG): id = 105 format = _(u'User {user} restricted.') admin_event = True class ADMIN_VIEWED_LOG(_LOG): id = 106 format = _(u'Admin {0} viewed activity log for {user}.') admin_event = True class EDIT_REVIEW(_LOG): id = 107 action_class = 'review' format = _(u'{review} for {addon} updated.') class THEME_REVIEW(_LOG): id = 108 action_class = 'review' format = _(u'{addon} reviewed.') class GROUP_USER_ADDED(_LOG): id = 120 action_class = 'access' format = _(u'User {0.name} added to {group}.') keep = True admin_event = True class GROUP_USER_REMOVED(_LOG): id = 121 action_class = 'access' format = _(u'User {0.name} removed from {group}.') keep = True admin_event = True class REVIEW_FEATURES_OVERRIDE(_LOG): id = 122 format = _(u'{addon} minimum requirements manually changed by reviewer.') short = _(u'Requirements Changed by Reviewer') keep = True review_queue = True class REREVIEW_FEATURES_CHANGED(_LOG): id = 123 format = _(u'{addon} minimum requirements manually changed.') short = _(u'Requirements Changed') keep = True review_queue = True class CHANGE_VERSION_STATUS(_LOG): id = 124 # L10n: {0} is the status format = _(u'{version} status changed to {0}.') keep = True class DELETE_USER_LOOKUP(_LOG): id = 125 # L10n: {0} is the status format = _(u'User {0.name} {0.id} deleted via lookup tool.') keep = True class CONTENT_RATING_TO_ADULT(_LOG): id = 126 format = _('{addon} content rating changed to Adult.') review_queue = True class CONTENT_RATING_CHANGED(_LOG): id = 127 format = _('{addon} content rating changed.') class PRIORITY_REVIEW_REQUESTED(_LOG): id = 128 format = _(u'Priority review requested for {addon}.') short = _(u'Priority Review') keep = True review_queue = True class PASS_ADDITIONAL_REVIEW(_LOG): id = 129 action_class = 'review' format = _(u'{addon} {version} passed the {queue} review.') review_queue = True class FAIL_ADDITIONAL_REVIEW(_LOG): id = 130 action_class = 'review' format = _(u'{addon} {version} failed the {queue} review.') review_queue = True class APP_ABUSE_MARKREAD(_LOG): """Requires report.id and add-on objects.""" id = 131 format = _(u'Abuse report {report} for {addon} read.') editor_format = _(u'{user} marked read {report} for {addon}.') keep = True editor_event = True class WEBSITE_ABUSE_MARKREAD(_LOG): """Requires report.id and website objects.""" id = 132 format = _(u'Abuse report {report} for {website} read.') editor_format = _(u'{user} marked read {report} for {website}.') keep = True editor_event = True # Adding a log type? If it's a review_queue log type, you have to add a # note_type to constants/comm.py. LOGS = [x for x in vars().values() if isclass(x) and issubclass(x, _LOG) and x != _LOG] LOG_BY_ID = dict((l.id, l) for l in LOGS) LOG = AttributeDict((l.__name__, l) for l in LOGS) LOG_ADMINS = [l.id for l in LOGS if hasattr(l, 'admin_event')] LOG_KEEP = [l.id for l in LOGS if hasattr(l, 'keep')] LOG_EDITORS = [l.id for l in LOGS if hasattr(l, 'editor_event')] LOG_REVIEW_QUEUE = [l.id for l in LOGS if hasattr(l, 'review_queue')] # Is the user emailed the message? LOG_REVIEW_EMAIL_USER = [l.id for l in LOGS if hasattr(l, 'review_email_user')] # Logs *not* to show to the developer. LOG_HIDE_DEVELOPER = [l.id for l in LOGS if (getattr(l, 'hide_developer', False) or l.id in LOG_ADMINS)] def log(action, *args, **kw): """ e.g. mkt.log(mkt.LOG.CREATE_ADDON, []), mkt.log(mkt.LOG.ADD_FILE_TO_VERSION, file, version) """ from mkt import get_user from mkt.developers.models import (ActivityLog, ActivityLogAttachment, AppLog, CommentLog, GroupLog, UserLog, VersionLog) from mkt.access.models import Group from mkt.site.utils import log as logger_log from mkt.webapps.models import Webapp from mkt.users.models import UserProfile from mkt.versions.models import Version user = kw.get('user', get_user()) if not user: logger_log.warning('Activity log called with no user: %s' % action.id) return al = ActivityLog(user=user, action=action.id) al.arguments = args if 'details' in kw: al.details = kw['details'] al.save() if 'details' in kw and 'comments' in al.details: CommentLog(comments=al.details['comments'], activity_log=al).save() # TODO(davedash): post-remora this may not be necessary. if 'created' in kw: al.created = kw['created'] # Double save necessary since django resets the created date on save. al.save() if 'attachments' in kw: formset = kw['attachments'] storage = get_storage_class()() for form in formset: data = form.cleaned_data if 'attachment' in data: attachment = data['attachment'] storage.save('%s/%s' % (settings.REVIEWER_ATTACHMENTS_PATH, attachment.name), attachment) ActivityLogAttachment(activity_log=al, description=data['description'], mimetype=attachment.content_type, filepath=attachment.name).save() for arg in args: if isinstance(arg, tuple): if arg[0] == Webapp: AppLog(addon_id=arg[1], activity_log=al).save() elif arg[0] == Version: VersionLog(version_id=arg[1], activity_log=al).save() elif arg[0] == UserProfile: UserLog(user_id=arg[1], activity_log=al).save() elif arg[0] == Group: GroupLog(group_id=arg[1], activity_log=al).save() if isinstance(arg, Webapp): AppLog(addon=arg, activity_log=al).save() elif isinstance(arg, Version): VersionLog(version=arg, activity_log=al).save() elif isinstance(arg, UserProfile): # Index by any user who is mentioned as an argument. UserLog(activity_log=al, user=arg).save() elif isinstance(arg, Group): GroupLog(group=arg, activity_log=al).save() # Index by every user UserLog(activity_log=al, user=user).save() return al
bsd-3-clause
youtube/cobalt
third_party/ots/src/silf.cc
35530
// Copyright (c) 2009-2017 The OTS 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 "silf.h" #include "name.h" #include "lz4.h" #include <cmath> namespace ots { bool OpenTypeSILF::Parse(const uint8_t* data, size_t length, bool prevent_decompression) { if (GetFont()->dropped_graphite) { return Drop("Skipping Graphite table"); } Buffer table(data, length); if (!table.ReadU32(&this->version)) { return DropGraphite("Failed to read version"); } if (this->version >> 16 != 1 && this->version >> 16 != 2 && this->version >> 16 != 3 && this->version >> 16 != 4 && this->version >> 16 != 5) { return DropGraphite("Unsupported table version: %u", this->version >> 16); } if (this->version >> 16 >= 3 && !table.ReadU32(&this->compHead)) { return DropGraphite("Failed to read compHead"); } if (this->version >> 16 >= 5) { switch ((this->compHead & SCHEME) >> 27) { case 0: // uncompressed break; case 1: { // lz4 if (prevent_decompression) { return DropGraphite("Illegal nested compression"); } std::vector<uint8_t> decompressed(this->compHead & FULL_SIZE); int ret = LZ4_decompress_safe_partial( reinterpret_cast<const char*>(data + table.offset()), reinterpret_cast<char*>(decompressed.data()), table.remaining(), // input buffer size (input size + padding) decompressed.size(), // target output size decompressed.size()); // output buffer size if (ret != decompressed.size()) { return DropGraphite("Decompression failed with error code %d", ret); } return this->Parse(decompressed.data(), decompressed.size(), true); } default: return DropGraphite("Unknown compression scheme"); } } if (!table.ReadU16(&this->numSub)) { return DropGraphite("Failed to read numSub"); } if (this->version >> 16 >= 2 && !table.ReadU16(&this->reserved)) { return DropGraphite("Failed to read reserved"); } if (this->version >> 16 >= 2 && this->reserved != 0) { Warning("Nonzero reserved"); } unsigned long last_offset = 0; //this->offset.resize(this->numSub); for (unsigned i = 0; i < this->numSub; ++i) { this->offset.emplace_back(); if (!table.ReadU32(&this->offset[i]) || this->offset[i] < last_offset) { return DropGraphite("Failed to read offset[%u]", i); } last_offset = this->offset[i]; } for (unsigned i = 0; i < this->numSub; ++i) { if (table.offset() != this->offset[i]) { return DropGraphite("Offset check failed for tables[%lu]", i); } SILSub subtable(this); if (!subtable.ParsePart(table)) { return DropGraphite("Failed to read tables[%u]", i); } tables.push_back(subtable); } if (table.remaining()) { return Warning("%zu bytes unparsed", table.remaining()); } return true; } bool OpenTypeSILF::Serialize(OTSStream* out) { if (!out->WriteU32(this->version) || (this->version >> 16 >= 3 && !out->WriteU32(this->compHead)) || !out->WriteU16(this->numSub) || (this->version >> 16 >= 2 && !out->WriteU16(this->reserved)) || !SerializeParts(this->offset, out) || !SerializeParts(this->tables, out)) { return Error("Failed to write table"); } return true; } bool OpenTypeSILF::SILSub::ParsePart(Buffer& table) { size_t init_offset = table.offset(); if (parent->version >> 16 >= 3) { if (!table.ReadU32(&this->ruleVersion)) { return parent->Error("SILSub: Failed to read ruleVersion"); } if (!table.ReadU16(&this->passOffset)) { return parent->Error("SILSub: Failed to read passOffset"); } if (!table.ReadU16(&this->pseudosOffset)) { return parent->Error("SILSub: Failed to read pseudosOffset"); } } if (!table.ReadU16(&this->maxGlyphID)) { return parent->Error("SILSub: Failed to read maxGlyphID"); } if (!table.ReadS16(&this->extraAscent)) { return parent->Error("SILSub: Failed to read extraAscent"); } if (!table.ReadS16(&this->extraDescent)) { return parent->Error("SILSub: Failed to read extraDescent"); } if (!table.ReadU8(&this->numPasses)) { return parent->Error("SILSub: Failed to read numPasses"); } if (!table.ReadU8(&this->iSubst) || this->iSubst > this->numPasses) { return parent->Error("SILSub: Failed to read valid iSubst"); } if (!table.ReadU8(&this->iPos) || this->iPos > this->numPasses) { return parent->Error("SILSub: Failed to read valid iPos"); } if (!table.ReadU8(&this->iJust) || this->iJust > this->numPasses) { return parent->Error("SILSub: Failed to read valid iJust"); } if (!table.ReadU8(&this->iBidi) || !(iBidi == 0xFF || this->iBidi <= this->iPos)) { return parent->Error("SILSub: Failed to read valid iBidi"); } if (!table.ReadU8(&this->flags)) { return parent->Error("SILSub: Failed to read flags"); // checks omitted } if (!table.ReadU8(&this->maxPreContext)) { return parent->Error("SILSub: Failed to read maxPreContext"); } if (!table.ReadU8(&this->maxPostContext)) { return parent->Error("SILSub: Failed to read maxPostContext"); } if (!table.ReadU8(&this->attrPseudo)) { return parent->Error("SILSub: Failed to read attrPseudo"); } if (!table.ReadU8(&this->attrBreakWeight)) { return parent->Error("SILSub: Failed to read attrBreakWeight"); } if (!table.ReadU8(&this->attrDirectionality)) { return parent->Error("SILSub: Failed to read attrDirectionality"); } if (parent->version >> 16 >= 2) { if (!table.ReadU8(&this->attrMirroring)) { return parent->Error("SILSub: Failed to read attrMirroring"); } if (parent->version >> 16 < 4 && this->attrMirroring != 0) { parent->Warning("SILSub: Nonzero attrMirroring (reserved before v4)"); } if (!table.ReadU8(&this->attrSkipPasses)) { return parent->Error("SILSub: Failed to read attrSkipPasses"); } if (parent->version >> 16 < 4 && this->attrSkipPasses != 0) { parent->Warning("SILSub: Nonzero attrSkipPasses (reserved2 before v4)"); } if (!table.ReadU8(&this->numJLevels)) { return parent->Error("SILSub: Failed to read numJLevels"); } //this->jLevels.resize(this->numJLevels, parent); for (unsigned i = 0; i < this->numJLevels; ++i) { this->jLevels.emplace_back(parent); if (!this->jLevels[i].ParsePart(table)) { return parent->Error("SILSub: Failed to read jLevels[%u]", i); } } } if (!table.ReadU16(&this->numLigComp)) { return parent->Error("SILSub: Failed to read numLigComp"); } if (!table.ReadU8(&this->numUserDefn)) { return parent->Error("SILSub: Failed to read numUserDefn"); } if (!table.ReadU8(&this->maxCompPerLig)) { return parent->Error("SILSub: Failed to read maxCompPerLig"); } if (!table.ReadU8(&this->direction)) { return parent->Error("SILSub: Failed to read direction"); } if (!table.ReadU8(&this->attCollisions)) { return parent->Error("SILSub: Failed to read attCollisions"); } if (parent->version >> 16 < 5 && this->attCollisions != 0) { parent->Warning("SILSub: Nonzero attCollisions (reserved before v5)"); } if (!table.ReadU8(&this->reserved4)) { return parent->Error("SILSub: Failed to read reserved4"); } if (this->reserved4 != 0) { parent->Warning("SILSub: Nonzero reserved4"); } if (!table.ReadU8(&this->reserved5)) { return parent->Error("SILSub: Failed to read reserved5"); } if (this->reserved5 != 0) { parent->Warning("SILSub: Nonzero reserved5"); } if (parent->version >> 16 >= 2) { if (!table.ReadU8(&this->reserved6)) { return parent->Error("SILSub: Failed to read reserved6"); } if (this->reserved6 != 0) { parent->Warning("SILSub: Nonzero reserved6"); } if (!table.ReadU8(&this->numCritFeatures)) { return parent->Error("SILSub: Failed to read numCritFeatures"); } //this->critFeatures.resize(this->numCritFeatures); for (unsigned i = 0; i < this->numCritFeatures; ++i) { this->critFeatures.emplace_back(); if (!table.ReadU16(&this->critFeatures[i])) { return parent->Error("SILSub: Failed to read critFeatures[%u]", i); } } if (!table.ReadU8(&this->reserved7)) { return parent->Error("SILSub: Failed to read reserved7"); } if (this->reserved7 != 0) { parent->Warning("SILSub: Nonzero reserved7"); } } if (!table.ReadU8(&this->numScriptTag)) { return parent->Error("SILSub: Failed to read numScriptTag"); } //this->scriptTag.resize(this->numScriptTag); for (unsigned i = 0; i < this->numScriptTag; ++i) { this->scriptTag.emplace_back(); if (!table.ReadU32(&this->scriptTag[i])) { return parent->Error("SILSub: Failed to read scriptTag[%u]", i); } } if (!table.ReadU16(&this->lbGID)) { return parent->Error("SILSub: Failed to read lbGID"); } if (this->lbGID > this->maxGlyphID) { parent->Warning("SILSub: lbGID %u outside range 0..%u, replaced with 0", this->lbGID, this->maxGlyphID); this->lbGID = 0; } if (parent->version >> 16 >= 3 && table.offset() != init_offset + this->passOffset) { return parent->Error("SILSub: passOffset check failed"); } unsigned long last_oPass = 0; //this->oPasses.resize(static_cast<unsigned>(this->numPasses) + 1); for (unsigned i = 0; i <= this->numPasses; ++i) { this->oPasses.emplace_back(); if (!table.ReadU32(&this->oPasses[i]) || this->oPasses[i] < last_oPass) { return false; } last_oPass = this->oPasses[i]; } if (parent->version >> 16 >= 3 && table.offset() != init_offset + this->pseudosOffset) { return parent->Error("SILSub: pseudosOffset check failed"); } if (!table.ReadU16(&this->numPseudo)) { return parent->Error("SILSub: Failed to read numPseudo"); } // The following three fields are deprecated and ignored. We fix them up here // just for internal consistency, but the Graphite engine doesn't care. if (!table.ReadU16(&this->searchPseudo) || !table.ReadU16(&this->pseudoSelector) || !table.ReadU16(&this->pseudoShift)) { return parent->Error("SILSub: Failed to read searchPseudo..pseudoShift"); } if (this->numPseudo == 0) { if (this->searchPseudo != 0 || this->pseudoSelector != 0 || this->pseudoShift != 0) { this->searchPseudo = this->pseudoSelector = this->pseudoShift = 0; } } else { unsigned floorLog2 = std::floor(log2(this->numPseudo)); if (this->searchPseudo != 6 * (unsigned)std::pow(2, floorLog2) || this->pseudoSelector != floorLog2 || this->pseudoShift != 6 * this->numPseudo - this->searchPseudo) { this->searchPseudo = 6 * (unsigned)std::pow(2, floorLog2); this->pseudoSelector = floorLog2; this->pseudoShift = 6 * this->numPseudo - this->searchPseudo; } } //this->pMaps.resize(this->numPseudo, parent); for (unsigned i = 0; i < numPseudo; i++) { this->pMaps.emplace_back(parent); if (!this->pMaps[i].ParsePart(table)) { return parent->Error("SILSub: Failed to read pMaps[%u]", i); } } if (!this->classes.ParsePart(table)) { return parent->Error("SILSub: Failed to read classes"); } //this->passes.resize(this->numPasses, parent); for (unsigned i = 0; i < this->numPasses; ++i) { this->passes.emplace_back(parent); if (table.offset() != init_offset + this->oPasses[i]) { return parent->Error("SILSub: Offset check failed for passes[%u]", i); } if (!this->passes[i].ParsePart(table, init_offset, this->oPasses[i+1])) { return parent->Error("SILSub: Failed to read passes[%u]", i); } } return true; } bool OpenTypeSILF::SILSub::SerializePart(OTSStream* out) const { if ((parent->version >> 16 >= 3 && (!out->WriteU32(this->ruleVersion) || !out->WriteU16(this->passOffset) || !out->WriteU16(this->pseudosOffset))) || !out->WriteU16(this->maxGlyphID) || !out->WriteS16(this->extraAscent) || !out->WriteS16(this->extraDescent) || !out->WriteU8(this->numPasses) || !out->WriteU8(this->iSubst) || !out->WriteU8(this->iPos) || !out->WriteU8(this->iJust) || !out->WriteU8(this->iBidi) || !out->WriteU8(this->flags) || !out->WriteU8(this->maxPreContext) || !out->WriteU8(this->maxPostContext) || !out->WriteU8(this->attrPseudo) || !out->WriteU8(this->attrBreakWeight) || !out->WriteU8(this->attrDirectionality) || (parent->version >> 16 >= 2 && (!out->WriteU8(this->attrMirroring) || !out->WriteU8(this->attrSkipPasses) || !out->WriteU8(this->numJLevels) || !SerializeParts(this->jLevels, out))) || !out->WriteU16(this->numLigComp) || !out->WriteU8(this->numUserDefn) || !out->WriteU8(this->maxCompPerLig) || !out->WriteU8(this->direction) || !out->WriteU8(this->attCollisions) || !out->WriteU8(this->reserved4) || !out->WriteU8(this->reserved5) || (parent->version >> 16 >= 2 && (!out->WriteU8(this->reserved6) || !out->WriteU8(this->numCritFeatures) || !SerializeParts(this->critFeatures, out) || !out->WriteU8(this->reserved7))) || !out->WriteU8(this->numScriptTag) || !SerializeParts(this->scriptTag, out) || !out->WriteU16(this->lbGID) || !SerializeParts(this->oPasses, out) || !out->WriteU16(this->numPseudo) || !out->WriteU16(this->searchPseudo) || !out->WriteU16(this->pseudoSelector) || !out->WriteU16(this->pseudoShift) || !SerializeParts(this->pMaps, out) || !this->classes.SerializePart(out) || !SerializeParts(this->passes, out)) { return parent->Error("SILSub: Failed to write"); } return true; } bool OpenTypeSILF::SILSub:: JustificationLevel::ParsePart(Buffer& table) { if (!table.ReadU8(&this->attrStretch)) { return parent->Error("JustificationLevel: Failed to read attrStretch"); } if (!table.ReadU8(&this->attrShrink)) { return parent->Error("JustificationLevel: Failed to read attrShrink"); } if (!table.ReadU8(&this->attrStep)) { return parent->Error("JustificationLevel: Failed to read attrStep"); } if (!table.ReadU8(&this->attrWeight)) { return parent->Error("JustificationLevel: Failed to read attrWeight"); } if (!table.ReadU8(&this->runto)) { return parent->Error("JustificationLevel: Failed to read runto"); } if (!table.ReadU8(&this->reserved)) { return parent->Error("JustificationLevel: Failed to read reserved"); } if (this->reserved != 0) { parent->Warning("JustificationLevel: Nonzero reserved"); } if (!table.ReadU8(&this->reserved2)) { return parent->Error("JustificationLevel: Failed to read reserved2"); } if (this->reserved2 != 0) { parent->Warning("JustificationLevel: Nonzero reserved2"); } if (!table.ReadU8(&this->reserved3)) { return parent->Error("JustificationLevel: Failed to read reserved3"); } if (this->reserved3 != 0) { parent->Warning("JustificationLevel: Nonzero reserved3"); } return true; } bool OpenTypeSILF::SILSub:: JustificationLevel::SerializePart(OTSStream* out) const { if (!out->WriteU8(this->attrStretch) || !out->WriteU8(this->attrShrink) || !out->WriteU8(this->attrStep) || !out->WriteU8(this->attrWeight) || !out->WriteU8(this->runto) || !out->WriteU8(this->reserved) || !out->WriteU8(this->reserved2) || !out->WriteU8(this->reserved3)) { return parent->Error("JustificationLevel: Failed to write"); } return true; } bool OpenTypeSILF::SILSub:: PseudoMap::ParsePart(Buffer& table) { if (parent->version >> 16 >= 2 && !table.ReadU32(&this->unicode)) { return parent->Error("PseudoMap: Failed to read unicode"); } if (parent->version >> 16 == 1) { uint16_t unicode; if (!table.ReadU16(&unicode)) { return parent->Error("PseudoMap: Failed to read unicode"); } this->unicode = unicode; } if (!table.ReadU16(&this->nPseudo)) { return parent->Error("PseudoMap: Failed to read nPseudo"); } return true; } bool OpenTypeSILF::SILSub:: PseudoMap::SerializePart(OTSStream* out) const { if ((parent->version >> 16 >= 2 && !out->WriteU32(this->unicode)) || (parent->version >> 16 == 1 && !out->WriteU16(static_cast<uint16_t>(this->unicode))) || !out->WriteU16(this->nPseudo)) { return parent->Error("PseudoMap: Failed to write"); } return true; } bool OpenTypeSILF::SILSub:: ClassMap::ParsePart(Buffer& table) { size_t init_offset = table.offset(); if (!table.ReadU16(&this->numClass)) { return parent->Error("ClassMap: Failed to read numClass"); } if (!table.ReadU16(&this->numLinear) || this->numLinear > this->numClass) { return parent->Error("ClassMap: Failed to read valid numLinear"); } //this->oClass.resize(static_cast<unsigned long>(this->numClass) + 1); if (parent->version >> 16 >= 4) { unsigned long last_oClass = 0; for (unsigned long i = 0; i <= this->numClass; ++i) { this->oClass.emplace_back(); if (!table.ReadU32(&this->oClass[i]) || this->oClass[i] < last_oClass) { return parent->Error("ClassMap: Failed to read oClass[%lu]", i); } last_oClass = this->oClass[i]; } } if (parent->version >> 16 < 4) { unsigned last_oClass = 0; for (unsigned long i = 0; i <= this->numClass; ++i) { uint16_t offset; if (!table.ReadU16(&offset) || offset < last_oClass) { return parent->Error("ClassMap: Failed to read oClass[%lu]", i); } last_oClass = offset; this->oClass.push_back(static_cast<uint32_t>(offset)); } } if (table.offset() - init_offset > this->oClass[this->numLinear]) { return parent->Error("ClassMap: Failed to calculate length of glyphs"); } unsigned long glyphs_len = (this->oClass[this->numLinear] - (table.offset() - init_offset))/2; //this->glyphs.resize(glyphs_len); for (unsigned long i = 0; i < glyphs_len; ++i) { this->glyphs.emplace_back(); if (!table.ReadU16(&this->glyphs[i])) { return parent->Error("ClassMap: Failed to read glyphs[%lu]", i); } } unsigned lookups_len = this->numClass - this->numLinear; // this->numLinear <= this->numClass //this->lookups.resize(lookups_len, parent); for (unsigned i = 0; i < lookups_len; ++i) { this->lookups.emplace_back(parent); if (table.offset() != init_offset + oClass[this->numLinear + i]) { return parent->Error("ClassMap: Offset check failed for lookups[%u]", i); } if (!this->lookups[i].ParsePart(table)) { return parent->Error("ClassMap: Failed to read lookups[%u]", i); } } return true; } bool OpenTypeSILF::SILSub:: ClassMap::SerializePart(OTSStream* out) const { if (!out->WriteU16(this->numClass) || !out->WriteU16(this->numLinear) || (parent->version >> 16 >= 4 && !SerializeParts(this->oClass, out)) || (parent->version >> 16 < 4 && ![&] { for (uint32_t offset : this->oClass) { if (!out->WriteU16(static_cast<uint16_t>(offset))) { return false; } } return true; }()) || !SerializeParts(this->glyphs, out) || !SerializeParts(this->lookups, out)) { return parent->Error("ClassMap: Failed to write"); } return true; } bool OpenTypeSILF::SILSub::ClassMap:: LookupClass::ParsePart(Buffer& table) { if (!table.ReadU16(&this->numIDs)) { return parent->Error("LookupClass: Failed to read numIDs"); } if (!table.ReadU16(&this->searchRange) || !table.ReadU16(&this->entrySelector) || !table.ReadU16(&this->rangeShift)) { return parent->Error("LookupClass: Failed to read searchRange..rangeShift"); } if (this->numIDs == 0) { if (this->searchRange != 0 || this->entrySelector != 0 || this->rangeShift != 0) { parent->Warning("LookupClass: Correcting binary-search header for zero-length LookupPair list"); this->searchRange = this->entrySelector = this->rangeShift = 0; } } else { unsigned floorLog2 = std::floor(log2(this->numIDs)); if (this->searchRange != (unsigned)std::pow(2, floorLog2) || this->entrySelector != floorLog2 || this->rangeShift != this->numIDs - this->searchRange) { parent->Warning("LookupClass: Correcting binary-search header for LookupPair list"); this->searchRange = (unsigned)std::pow(2, floorLog2); this->entrySelector = floorLog2; this->rangeShift = this->numIDs - this->searchRange; } } //this->lookups.resize(this->numIDs, parent); for (unsigned i = 0; i < numIDs; ++i) { this->lookups.emplace_back(parent); if (!this->lookups[i].ParsePart(table)) { return parent->Error("LookupClass: Failed to read lookups[%u]", i); } } return true; } bool OpenTypeSILF::SILSub::ClassMap:: LookupClass::SerializePart(OTSStream* out) const { if (!out->WriteU16(this->numIDs) || !out->WriteU16(this->searchRange) || !out->WriteU16(this->entrySelector) || !out->WriteU16(this->rangeShift) || !SerializeParts(this->lookups, out)) { return parent->Error("LookupClass: Failed to write"); } return true; } bool OpenTypeSILF::SILSub::ClassMap::LookupClass:: LookupPair::ParsePart(Buffer& table) { if (!table.ReadU16(&this->glyphId)) { return parent->Error("LookupPair: Failed to read glyphId"); } if (!table.ReadU16(&this->index)) { return parent->Error("LookupPair: Failed to read index"); } return true; } bool OpenTypeSILF::SILSub::ClassMap::LookupClass:: LookupPair::SerializePart(OTSStream* out) const { if (!out->WriteU16(this->glyphId) || !out->WriteU16(this->index)) { return parent->Error("LookupPair: Failed to write"); } return true; } bool OpenTypeSILF::SILSub:: SILPass::ParsePart(Buffer& table, const size_t SILSub_init_offset, const size_t next_pass_offset) { size_t init_offset = table.offset(); if (!table.ReadU8(&this->flags)) { return parent->Error("SILPass: Failed to read flags"); // checks omitted } if (!table.ReadU8(&this->maxRuleLoop)) { return parent->Error("SILPass: Failed to read valid maxRuleLoop"); } if (!table.ReadU8(&this->maxRuleContext)) { return parent->Error("SILPass: Failed to read maxRuleContext"); } if (!table.ReadU8(&this->maxBackup)) { return parent->Error("SILPass: Failed to read maxBackup"); } if (!table.ReadU16(&this->numRules)) { return parent->Error("SILPass: Failed to read numRules"); } if (parent->version >> 16 >= 2) { if (!table.ReadU16(&this->fsmOffset)) { return parent->Error("SILPass: Failed to read fsmOffset"); } if (parent->version >> 16 == 2 && this->fsmOffset != 0) { parent->Warning("SILPass: Nonzero fsmOffset (reserved in SILSub v2)"); } if (!table.ReadU32(&this->pcCode) || (parent->version >= 3 && this->pcCode < this->fsmOffset)) { return parent->Error("SILPass: Failed to read pcCode"); } } if (!table.ReadU32(&this->rcCode) || (parent->version >> 16 >= 2 && this->rcCode < this->pcCode)) { return parent->Error("SILPass: Failed to read valid rcCode"); } if (!table.ReadU32(&this->aCode) || this->aCode < this->rcCode) { return parent->Error("SILPass: Failed to read valid aCode"); } if (!table.ReadU32(&this->oDebug) || (this->oDebug && this->oDebug < this->aCode)) { return parent->Error("SILPass: Failed to read valid oDebug"); } if (parent->version >> 16 >= 3 && table.offset() != init_offset + this->fsmOffset) { return parent->Error("SILPass: fsmOffset check failed"); } if (!table.ReadU16(&this->numRows) || (this->oDebug && this->numRows < this->numRules)) { return parent->Error("SILPass: Failed to read valid numRows"); } if (!table.ReadU16(&this->numTransitional)) { return parent->Error("SILPass: Failed to read numTransitional"); } if (!table.ReadU16(&this->numSuccess)) { return parent->Error("SILPass: Failed to read numSuccess"); } if (!table.ReadU16(&this->numColumns)) { return parent->Error("SILPass: Failed to read numColumns"); } if (!table.ReadU16(&this->numRange)) { return parent->Error("SILPass: Failed to read numRange"); } // The following three fields are deprecated and ignored. We fix them up here // just for internal consistency, but the Graphite engine doesn't care. if (!table.ReadU16(&this->searchRange) || !table.ReadU16(&this->entrySelector) || !table.ReadU16(&this->rangeShift)) { return parent->Error("SILPass: Failed to read searchRange..rangeShift"); } if (this->numRange == 0) { if (this->searchRange != 0 || this->entrySelector != 0 || this->rangeShift != 0) { this->searchRange = this->entrySelector = this->rangeShift = 0; } } else { unsigned floorLog2 = std::floor(log2(this->numRange)); if (this->searchRange != 6 * (unsigned)std::pow(2, floorLog2) || this->entrySelector != floorLog2 || this->rangeShift != 6 * this->numRange - this->searchRange) { this->searchRange = 6 * (unsigned)std::pow(2, floorLog2); this->entrySelector = floorLog2; this->rangeShift = 6 * this->numRange - this->searchRange; } } //this->ranges.resize(this->numRange, parent); for (unsigned i = 0 ; i < this->numRange; ++i) { this->ranges.emplace_back(parent); if (!this->ranges[i].ParsePart(table)) { return parent->Error("SILPass: Failed to read ranges[%u]", i); } } unsigned ruleMap_len = 0; // maximum value in oRuleMap //this->oRuleMap.resize(static_cast<unsigned long>(this->numSuccess) + 1); for (unsigned long i = 0; i <= this->numSuccess; ++i) { this->oRuleMap.emplace_back(); if (!table.ReadU16(&this->oRuleMap[i])) { return parent->Error("SILPass: Failed to read oRuleMap[%u]", i); } if (oRuleMap[i] > ruleMap_len) { ruleMap_len = oRuleMap[i]; } } //this->ruleMap.resize(ruleMap_len); for (unsigned i = 0; i < ruleMap_len; ++i) { this->ruleMap.emplace_back(); if (!table.ReadU16(&this->ruleMap[i])) { return parent->Error("SILPass: Failed to read ruleMap[%u]", i); } } if (!table.ReadU8(&this->minRulePreContext)) { return parent->Error("SILPass: Failed to read minRulePreContext"); } if (!table.ReadU8(&this->maxRulePreContext) || this->maxRulePreContext < this->minRulePreContext) { return parent->Error("SILPass: Failed to read valid maxRulePreContext"); } unsigned startStates_len = this->maxRulePreContext - this->minRulePreContext + 1; // this->minRulePreContext <= this->maxRulePreContext //this->startStates.resize(startStates_len); for (unsigned i = 0; i < startStates_len; ++i) { this->startStates.emplace_back(); if (!table.ReadS16(&this->startStates[i])) { return parent->Error("SILPass: Failed to read startStates[%u]", i); } } //this->ruleSortKeys.resize(this->numRules); for (unsigned i = 0; i < this->numRules; ++i) { this->ruleSortKeys.emplace_back(); if (!table.ReadU16(&this->ruleSortKeys[i])) { return parent->Error("SILPass: Failed to read ruleSortKeys[%u]", i); } } //this->rulePreContext.resize(this->numRules); for (unsigned i = 0; i < this->numRules; ++i) { this->rulePreContext.emplace_back(); if (!table.ReadU8(&this->rulePreContext[i])) { return parent->Error("SILPass: Failed to read rulePreContext[%u]", i); } } if (parent->version >> 16 >= 2) { if (!table.ReadU8(&this->collisionThreshold)) { return parent->Error("SILPass: Failed to read collisionThreshold"); } if (parent->version >> 16 < 5 && this->collisionThreshold != 0) { parent->Warning("SILPass: Nonzero collisionThreshold" " (reserved before v5)"); } if (!table.ReadU16(&this->pConstraint)) { return parent->Error("SILPass: Failed to read pConstraint"); } } unsigned long ruleConstraints_len = this->aCode - this->rcCode; // this->rcCode <= this->aCode //this->oConstraints.resize(static_cast<unsigned long>(this->numRules) + 1); for (unsigned long i = 0; i <= this->numRules; ++i) { this->oConstraints.emplace_back(); if (!table.ReadU16(&this->oConstraints[i]) || this->oConstraints[i] > ruleConstraints_len) { return parent->Error("SILPass: Failed to read valid oConstraints[%lu]", i); } } if (!this->oDebug && this->aCode > next_pass_offset) { return parent->Error("SILPass: Failed to calculate length of actions"); } unsigned long actions_len = this->oDebug ? this->oDebug - this->aCode : next_pass_offset - this->aCode; // if this->oDebug, then this->aCode <= this->oDebug //this->oActions.resize(static_cast<unsigned long>(this->numRules) + 1); for (unsigned long i = 0; i <= this->numRules; ++i) { this->oActions.emplace_back(); if (!table.ReadU16(&this->oActions[i]) || (this->oActions[i] > actions_len)) { return parent->Error("SILPass: Failed to read valid oActions[%lu]", i); } } //this->stateTrans.resize(this->numTransitional); for (unsigned i = 0; i < this->numTransitional; ++i) { this->stateTrans.emplace_back(); //this->stateTrans[i].resize(this->numColumns); for (unsigned j = 0; j < this->numColumns; ++j) { this->stateTrans[i].emplace_back(); if (!table.ReadU16(&stateTrans[i][j])) { return parent->Error("SILPass: Failed to read stateTrans[%u][%u]", i, j); } } } if (parent->version >> 16 >= 2) { if (!table.ReadU8(&this->reserved2)) { return parent->Error("SILPass: Failed to read reserved2"); } if (this->reserved2 != 0) { parent->Warning("SILPass: Nonzero reserved2"); } if (table.offset() != SILSub_init_offset + this->pcCode) { return parent->Error("SILPass: pcCode check failed"); } //this->passConstraints.resize(this->pConstraint); for (unsigned i = 0; i < this->pConstraint; ++i) { this->passConstraints.emplace_back(); if (!table.ReadU8(&this->passConstraints[i])) { return parent->Error("SILPass: Failed to read passConstraints[%u]", i); } } } if (table.offset() != SILSub_init_offset + this->rcCode) { return parent->Error("SILPass: rcCode check failed"); } //this->ruleConstraints.resize(ruleConstraints_len); // calculated above for (unsigned long i = 0; i < ruleConstraints_len; ++i) { this->ruleConstraints.emplace_back(); if (!table.ReadU8(&this->ruleConstraints[i])) { return parent->Error("SILPass: Failed to read ruleConstraints[%u]", i); } } if (table.offset() != SILSub_init_offset + this->aCode) { return parent->Error("SILPass: aCode check failed"); } //this->actions.resize(actions_len); // calculated above for (unsigned long i = 0; i < actions_len; ++i) { this->actions.emplace_back(); if (!table.ReadU8(&this->actions[i])) { return parent->Error("SILPass: Failed to read actions[%u]", i); } } if (this->oDebug) { OpenTypeNAME* name = static_cast<OpenTypeNAME*>( parent->GetFont()->GetTypedTable(OTS_TAG_NAME)); if (!name) { return parent->Error("SILPass: Required name table is missing"); } if (table.offset() != SILSub_init_offset + this->oDebug) { return parent->Error("SILPass: oDebug check failed"); } //this->dActions.resize(this->numRules); for (unsigned i = 0; i < this->numRules; ++i) { this->dActions.emplace_back(); if (!table.ReadU16(&this->dActions[i]) || !name->IsValidNameId(this->dActions[i])) { return parent->Error("SILPass: Failed to read valid dActions[%u]", i); } } unsigned dStates_len = this->numRows - this->numRules; // this->numRules <= this->numRows //this->dStates.resize(dStates_len); for (unsigned i = 0; i < dStates_len; ++i) { this->dStates.emplace_back(); if (!table.ReadU16(&this->dStates[i]) || !name->IsValidNameId(this->dStates[i])) { return parent->Error("SILPass: Failed to read valid dStates[%u]", i); } } //this->dCols.resize(this->numRules); for (unsigned i = 0; i < this->numRules; ++i) { this->dCols.emplace_back(); if (!table.ReadU16(&this->dCols[i]) || !name->IsValidNameId(this->dCols[i])) { return parent->Error("SILPass: Failed to read valid dCols[%u]"); } } } return true; } bool OpenTypeSILF::SILSub:: SILPass::SerializePart(OTSStream* out) const { if (!out->WriteU8(this->flags) || !out->WriteU8(this->maxRuleLoop) || !out->WriteU8(this->maxRuleContext) || !out->WriteU8(this->maxBackup) || !out->WriteU16(this->numRules) || (parent->version >> 16 >= 2 && (!out->WriteU16(this->fsmOffset) || !out->WriteU32(this->pcCode))) || !out->WriteU32(this->rcCode) || !out->WriteU32(this->aCode) || !out->WriteU32(this->oDebug) || !out->WriteU16(this->numRows) || !out->WriteU16(this->numTransitional) || !out->WriteU16(this->numSuccess) || !out->WriteU16(this->numColumns) || !out->WriteU16(this->numRange) || !out->WriteU16(this->searchRange) || !out->WriteU16(this->entrySelector) || !out->WriteU16(this->rangeShift) || !SerializeParts(this->ranges, out) || !SerializeParts(this->oRuleMap, out) || !SerializeParts(this->ruleMap, out) || !out->WriteU8(this->minRulePreContext) || !out->WriteU8(this->maxRulePreContext) || !SerializeParts(this->startStates, out) || !SerializeParts(this->ruleSortKeys, out) || !SerializeParts(this->rulePreContext, out) || (parent->version >> 16 >= 2 && (!out->WriteU8(this->collisionThreshold) || !out->WriteU16(this->pConstraint))) || !SerializeParts(this->oConstraints, out) || !SerializeParts(this->oActions, out) || !SerializeParts(this->stateTrans, out) || (parent->version >> 16 >= 2 && (!out->WriteU8(this->reserved2) || !SerializeParts(this->passConstraints, out))) || !SerializeParts(this->ruleConstraints, out) || !SerializeParts(this->actions, out) || !SerializeParts(this->dActions, out) || !SerializeParts(this->dStates, out) || !SerializeParts(this->dCols, out)) { return parent->Error("SILPass: Failed to write"); } return true; } bool OpenTypeSILF::SILSub::SILPass:: PassRange::ParsePart(Buffer& table) { if (!table.ReadU16(&this->firstId)) { return parent->Error("PassRange: Failed to read firstId"); } if (!table.ReadU16(&this->lastId)) { return parent->Error("PassRange: Failed to read lastId"); } if (!table.ReadU16(&this->colId)) { return parent->Error("PassRange: Failed to read colId"); } return true; } bool OpenTypeSILF::SILSub::SILPass:: PassRange::SerializePart(OTSStream* out) const { if (!out->WriteU16(this->firstId) || !out->WriteU16(this->lastId) || !out->WriteU16(this->colId)) { return parent->Error("PassRange: Failed to write"); } return true; } } // namespace ots
bsd-3-clause
jjfiv/waltz
base/src/main/java/edu/umass/cs/ciir/waltz/example/CountComparisonQuery.java
957
package edu.umass.cs.ciir.waltz.example; import ciir.jfoley.chai.collections.list.IntList; import edu.umass.cs.ciir.waltz.dociter.movement.PostingMover; import edu.umass.cs.ciir.waltz.index.Index; /** * @author jfoley */ public class CountComparisonQuery { // Find me documents where Term A occurs more than Term B public static IntList greaterThan(Index index, String termA, String termB) { PostingMover<Integer> iterA = index.getCountsMover(termA); PostingMover<Integer> iterB = index.getCountsMover(termB); IntList output = new IntList(); for(; !iterA.isDone(); iterA.next()) { int docId = iterA.currentKey(); assert(iterA.matches(docId)); iterB.moveTo(docId); int countB = 0; if(iterB.matches(docId)) { countB = iterB.getCurrentPosting(); } int countA = iterA.getCurrentPosting(); if(countA > countB) { output.add(docId); } } return output; } }
bsd-3-clause
mikehelmick/CascadeLMS
db/migrate/20111014033511_create_feeds.rb
356
class CreateFeeds < ActiveRecord::Migration def self.up create_table :feeds do |t| t.column :user_id, :integer, :null => true t.column :course_id, :integer, :null => true end add_index(:feeds, [:user_id], :unique => true) add_index(:feeds, [:course_id], :unique => true) end def self.down drop_table :feeds end end
bsd-3-clause
joshblour/spree_no_shipping
lib/spree_no_shipping/version.rb
48
module SpreeNoShipping VERSION = "0.0.04" end
bsd-3-clause
binzume/mikumikudroid
src/jp/gauzau/MikuMikuDroid/util/MotionDetector.java
835
package jp.gauzau.MikuMikuDroid.util; import android.hardware.Sensor; import android.hardware.SensorEvent; public class MotionDetector { private float[] gravHistory = new float[10]; // Gravity (G) private int gravHistoryPos = 0; float[] mAxV = new float[3]; public boolean jump = false; public void onSensorEvent(SensorEvent event) { if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) { System.arraycopy(event.values, 0, mAxV, 0, 3); gravHistoryPos = (gravHistoryPos + 1) % gravHistory.length; gravHistory[gravHistoryPos] = (float) Math.sqrt(mAxV[0] * mAxV[0] + mAxV[1] * mAxV[1] + mAxV[2] * mAxV[2]) / 9.8f; } jump = false; if (gravHistory[gravHistoryPos] < 0.4) { // 0.3G if (gravHistory[(gravHistoryPos + 5) % gravHistory.length] > 1.5) { // jump! jump = true; } return; } } }
bsd-3-clause
nerminramichhinc/multiplex
backend/models/GenreForm.php
336
<?php namespace backend\models; use Yii; use yii\base\Model; class GenreForm extends Model { public $genre_name; public function rules() { return [ //genre name is required ['genre_name', 'required'], ['genre_name', 'string'], ]; } }
bsd-3-clause
bbhlondon/s3-auth-js
src/client/register.js
1579
import Logger from '../logger'; import { ERROR_SERVICE_WORKER_NOT_SUPPORTED, ERROR_SERVICE_WORKER_ALREADY_EXISTS, ERROR_SERVICE_WORKER_REGISTRATION_FAILED } from '../consts'; import { supportsServiceWorker, hasServiceWorker } from './_register'; /** * Registers Service Worker * * @param {String} swPath * @returns {Promise} */ export default function registerServiceWorker(swPath) { return new Promise((resolve, reject) => { if (!supportsServiceWorker()) { Logger.log('[Page] This browser doesn\'t support service workers'); return reject(ERROR_SERVICE_WORKER_NOT_SUPPORTED); } if (navigator.serviceWorker.controller) { if (hasServiceWorker(swPath)) { Logger.log('[Client] The service worker is already active'); return resolve(true); } Logger.error(`[Client] The page already has another service worker: ${navigator.serviceWorker.controller.scriptURL}`); return reject(ERROR_SERVICE_WORKER_ALREADY_EXISTS); } window.addEventListener('load', () => { navigator.serviceWorker.register(swPath).then((registration) => { Logger.log(`[Client] ServiceWorker registration successful with scope: ${registration.scope}`); return resolve(true); }, (err) => { Logger.log(`[Client] ServiceWorker registration failed: ${err}`); return reject(ERROR_SERVICE_WORKER_REGISTRATION_FAILED); }); }); return null; }); }
bsd-3-clause
za4me/blog.dev
frontend/assets/AppAsset.php
417
<?php namespace frontend\assets; use yii\web\AssetBundle; /** * Main frontend application asset bundle. */ class AppAsset extends AssetBundle { public $basePath = '@webroot'; public $baseUrl = '@web'; public $css = [ 'css/theme.css', 'css/site.css', ]; public $js = [ ]; public $depends = [ 'yii\web\YiiAsset', 'yii\bootstrap\BootstrapAsset', ]; }
bsd-3-clause
sidrakesh93/grpc
tools/run_tests/run_tests.py
18892
#!/usr/bin/env python # 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. """Run tests in parallel.""" import argparse import glob import itertools import json import multiprocessing import os import platform import random import re import subprocess import sys import time import xml.etree.cElementTree as ET import jobset import watch_dirs ROOT = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), '../..')) os.chdir(ROOT) _FORCE_ENVIRON_FOR_WRAPPERS = {} # SimpleConfig: just compile with CONFIG=config, and run the binary to test class SimpleConfig(object): def __init__(self, config, environ=None): if environ is None: environ = {} self.build_config = config self.allow_hashing = (config != 'gcov') self.environ = environ self.environ['CONFIG'] = config def job_spec(self, cmdline, hash_targets, shortname=None, environ={}): """Construct a jobset.JobSpec for a test under this config Args: cmdline: a list of strings specifying the command line the test would like to run hash_targets: either None (don't do caching of test results), or a list of strings specifying files to include in a binary hash to check if a test has changed -- if used, all artifacts needed to run the test must be listed """ actual_environ = self.environ.copy() for k, v in environ.iteritems(): actual_environ[k] = v return jobset.JobSpec(cmdline=cmdline, shortname=shortname, environ=actual_environ, hash_targets=hash_targets if self.allow_hashing else None) # ValgrindConfig: compile with some CONFIG=config, but use valgrind to run class ValgrindConfig(object): def __init__(self, config, tool, args=None): if args is None: args = [] self.build_config = config self.tool = tool self.args = args self.allow_hashing = False def job_spec(self, cmdline, hash_targets): return jobset.JobSpec(cmdline=['valgrind', '--tool=%s' % self.tool] + self.args + cmdline, shortname='valgrind %s' % cmdline[0], hash_targets=None) class CLanguage(object): def __init__(self, make_target, test_lang): self.make_target = make_target if platform.system() == 'Windows': plat = 'windows' else: plat = 'posix' self.platform = plat with open('tools/run_tests/tests.json') as f: js = json.load(f) self.binaries = [tgt for tgt in js if tgt['language'] == test_lang and plat in tgt['platforms']] def test_specs(self, config, travis): out = [] for target in self.binaries: if travis and target['flaky']: continue if self.platform == 'windows': binary = 'vsprojects/test_bin/%s.exe' % (target['name']) else: binary = 'bins/%s/%s' % (config.build_config, target['name']) out.append(config.job_spec([binary], [binary])) return sorted(out) def make_targets(self): return ['buildtests_%s' % self.make_target, 'tools_%s' % self.make_target] def build_steps(self): return [] def supports_multi_config(self): return True def __str__(self): return self.make_target class NodeLanguage(object): def test_specs(self, config, travis): return [config.job_spec(['tools/run_tests/run_node.sh'], None, environ=_FORCE_ENVIRON_FOR_WRAPPERS)] def make_targets(self): return ['static_c', 'shared_c'] def build_steps(self): return [['tools/run_tests/build_node.sh']] def supports_multi_config(self): return False def __str__(self): return 'node' class PhpLanguage(object): def test_specs(self, config, travis): return [config.job_spec(['src/php/bin/run_tests.sh'], None, environ=_FORCE_ENVIRON_FOR_WRAPPERS)] def make_targets(self): return ['static_c', 'shared_c'] def build_steps(self): return [['tools/run_tests/build_php.sh']] def supports_multi_config(self): return False def __str__(self): return 'php' class PythonLanguage(object): def __init__(self): with open('tools/run_tests/python_tests.json') as f: self._tests = json.load(f) def test_specs(self, config, travis): modules = [config.job_spec(['tools/run_tests/run_python.sh', '-m', test['module']], None, environ=_FORCE_ENVIRON_FOR_WRAPPERS, shortname=test['module']) for test in self._tests if 'module' in test] files = [config.job_spec(['tools/run_tests/run_python.sh', test['file']], None, environ=_FORCE_ENVIRON_FOR_WRAPPERS, shortname=test['file']) for test in self._tests if 'file' in test] return files + modules def make_targets(self): return ['static_c', 'grpc_python_plugin', 'shared_c'] def build_steps(self): return [['tools/run_tests/build_python.sh']] def supports_multi_config(self): return False def __str__(self): return 'python' class RubyLanguage(object): def test_specs(self, config, travis): return [config.job_spec(['tools/run_tests/run_ruby.sh'], None, environ=_FORCE_ENVIRON_FOR_WRAPPERS)] def make_targets(self): return ['run_dep_checks'] def build_steps(self): return [['tools/run_tests/build_ruby.sh']] def supports_multi_config(self): return False def __str__(self): return 'ruby' class CSharpLanguage(object): def __init__(self): if platform.system() == 'Windows': plat = 'windows' else: plat = 'posix' self.platform = plat def test_specs(self, config, travis): assemblies = ['Grpc.Core.Tests', 'Grpc.Examples.Tests', 'Grpc.IntegrationTesting'] if self.platform == 'windows': cmd = 'tools\\run_tests\\run_csharp.bat' else: cmd = 'tools/run_tests/run_csharp.sh' return [config.job_spec([cmd, assembly], None, shortname=assembly, environ=_FORCE_ENVIRON_FOR_WRAPPERS) for assembly in assemblies ] def make_targets(self): # For Windows, this target doesn't really build anything, # everything is build by buildall script later. return ['grpc_csharp_ext'] def build_steps(self): if self.platform == 'windows': return [['src\\csharp\\buildall.bat']] else: return [['tools/run_tests/build_csharp.sh']] def supports_multi_config(self): return False def __str__(self): return 'csharp' class Sanity(object): def test_specs(self, config, travis): return [config.job_spec('tools/run_tests/run_sanity.sh', None), config.job_spec('tools/run_tests/check_sources_and_headers.py', None)] def make_targets(self): return ['run_dep_checks'] def build_steps(self): return [] def supports_multi_config(self): return False def __str__(self): return 'sanity' class Build(object): def test_specs(self, config, travis): return [] def make_targets(self): return ['static'] def build_steps(self): return [] def supports_multi_config(self): return True def __str__(self): return self.make_target # different configurations we can run under _CONFIGS = { 'dbg': SimpleConfig('dbg'), 'opt': SimpleConfig('opt'), 'tsan': SimpleConfig('tsan', environ={ 'TSAN_OPTIONS': 'suppressions=tools/tsan_suppressions.txt:halt_on_error=1'}), 'msan': SimpleConfig('msan'), 'ubsan': SimpleConfig('ubsan'), 'asan': SimpleConfig('asan', environ={ 'ASAN_OPTIONS': 'detect_leaks=1:color=always:suppressions=tools/tsan_suppressions.txt', 'LSAN_OPTIONS': 'report_objects=1'}), 'asan-noleaks': SimpleConfig('asan', environ={ 'ASAN_OPTIONS': 'detect_leaks=0:color=always:suppressions=tools/tsan_suppressions.txt'}), 'gcov': SimpleConfig('gcov'), 'memcheck': ValgrindConfig('valgrind', 'memcheck', ['--leak-check=full']), 'helgrind': ValgrindConfig('dbg', 'helgrind') } _DEFAULT = ['opt'] _LANGUAGES = { 'c++': CLanguage('cxx', 'c++'), 'c': CLanguage('c', 'c'), 'node': NodeLanguage(), 'php': PhpLanguage(), 'python': PythonLanguage(), 'ruby': RubyLanguage(), 'csharp': CSharpLanguage(), 'sanity': Sanity(), 'build': Build(), } # parse command line argp = argparse.ArgumentParser(description='Run grpc tests.') argp.add_argument('-c', '--config', choices=['all'] + sorted(_CONFIGS.keys()), nargs='+', default=_DEFAULT) def runs_per_test_type(arg_str): """Auxilary function to parse the "runs_per_test" flag. Returns: A positive integer or 0, the latter indicating an infinite number of runs. Raises: argparse.ArgumentTypeError: Upon invalid input. """ if arg_str == 'inf': return 0 try: n = int(arg_str) if n <= 0: raise ValueError return n except: msg = "'{}' isn't a positive integer or 'inf'".format(arg_str) raise argparse.ArgumentTypeError(msg) argp.add_argument('-n', '--runs_per_test', default=1, type=runs_per_test_type, help='A positive integer or "inf". If "inf", all tests will run in an ' 'infinite loop. Especially useful in combination with "-f"') argp.add_argument('-r', '--regex', default='.*', type=str) argp.add_argument('-j', '--jobs', default=2 * multiprocessing.cpu_count(), type=int) argp.add_argument('-s', '--slowdown', default=1.0, type=float) argp.add_argument('-f', '--forever', default=False, action='store_const', const=True) argp.add_argument('-t', '--travis', default=False, action='store_const', const=True) argp.add_argument('--newline_on_success', default=False, action='store_const', const=True) argp.add_argument('-l', '--language', choices=['all'] + sorted(_LANGUAGES.keys()), nargs='+', default=['all']) argp.add_argument('-S', '--stop_on_failure', default=False, action='store_const', const=True) argp.add_argument('-a', '--antagonists', default=0, type=int) argp.add_argument('-x', '--xml_report', default=None, type=str, help='Generates a JUnit-compatible XML report') args = argp.parse_args() # grab config run_configs = set(_CONFIGS[cfg] for cfg in itertools.chain.from_iterable( _CONFIGS.iterkeys() if x == 'all' else [x] for x in args.config)) build_configs = set(cfg.build_config for cfg in run_configs) if args.travis: _FORCE_ENVIRON_FOR_WRAPPERS = {'GRPC_TRACE': 'surface,batch'} make_targets = [] languages = set(_LANGUAGES[l] for l in itertools.chain.from_iterable( _LANGUAGES.iterkeys() if x == 'all' else [x] for x in args.language)) if len(build_configs) > 1: for language in languages: if not language.supports_multi_config(): print language, 'does not support multiple build configurations' sys.exit(1) if platform.system() == 'Windows': def make_jobspec(cfg, targets): return jobset.JobSpec(['make.bat', 'CONFIG=%s' % cfg] + targets, cwd='vsprojects', shell=True) else: def make_jobspec(cfg, targets): return jobset.JobSpec(['make', '-j', '%d' % (multiprocessing.cpu_count() + 1), 'EXTRA_DEFINES=GRPC_TEST_SLOWDOWN_MACHINE_FACTOR=%f' % args.slowdown, 'CONFIG=%s' % cfg] + targets) build_steps = [make_jobspec(cfg, list(set(itertools.chain.from_iterable( l.make_targets() for l in languages)))) for cfg in build_configs] build_steps.extend(set( jobset.JobSpec(cmdline, environ={'CONFIG': cfg}) for cfg in build_configs for l in languages for cmdline in l.build_steps())) one_run = set( spec for config in run_configs for language in languages for spec in language.test_specs(config, args.travis) if re.search(args.regex, spec.shortname)) runs_per_test = args.runs_per_test forever = args.forever class TestCache(object): """Cache for running tests.""" def __init__(self, use_cache_results): self._last_successful_run = {} self._use_cache_results = use_cache_results self._last_save = time.time() def should_run(self, cmdline, bin_hash): if cmdline not in self._last_successful_run: return True if self._last_successful_run[cmdline] != bin_hash: return True if not self._use_cache_results: return True return False def finished(self, cmdline, bin_hash): self._last_successful_run[cmdline] = bin_hash if time.time() - self._last_save > 1: self.save() def dump(self): return [{'cmdline': k, 'hash': v} for k, v in self._last_successful_run.iteritems()] def parse(self, exdump): self._last_successful_run = dict((o['cmdline'], o['hash']) for o in exdump) def save(self): with open('.run_tests_cache', 'w') as f: f.write(json.dumps(self.dump())) self._last_save = time.time() def maybe_load(self): if os.path.exists('.run_tests_cache'): with open('.run_tests_cache') as f: self.parse(json.loads(f.read())) def _build_and_run(check_cancelled, newline_on_success, travis, cache, xml_report=None): """Do one pass of building & running tests.""" # build latest sequentially if not jobset.run(build_steps, maxjobs=1, newline_on_success=newline_on_success, travis=travis): return 1 # start antagonists antagonists = [subprocess.Popen(['tools/run_tests/antagonist.py']) for _ in range(0, args.antagonists)] try: infinite_runs = runs_per_test == 0 # When running on travis, we want out test runs to be as similar as possible # for reproducibility purposes. if travis: massaged_one_run = sorted(one_run, key=lambda x: x.shortname) else: # whereas otherwise, we want to shuffle things up to give all tests a # chance to run. massaged_one_run = list(one_run) # random.shuffle needs an indexable seq. random.shuffle(massaged_one_run) # which it modifies in-place. if infinite_runs: assert len(massaged_one_run) > 0, 'Must have at least one test for a -n inf run' runs_sequence = (itertools.repeat(massaged_one_run) if infinite_runs else itertools.repeat(massaged_one_run, runs_per_test)) all_runs = itertools.chain.from_iterable(runs_sequence) root = ET.Element('testsuites') if xml_report else None testsuite = ET.SubElement(root, 'testsuite', id='1', package='grpc', name='tests') if xml_report else None if not jobset.run(all_runs, check_cancelled, newline_on_success=newline_on_success, travis=travis, infinite_runs=infinite_runs, maxjobs=args.jobs, stop_on_failure=args.stop_on_failure, cache=cache if not xml_report else None, xml_report=testsuite): return 2 finally: for antagonist in antagonists: antagonist.kill() if xml_report: tree = ET.ElementTree(root) tree.write(xml_report, encoding='UTF-8') if cache: cache.save() return 0 test_cache = TestCache(runs_per_test == 1) test_cache.maybe_load() if forever: success = True while True: dw = watch_dirs.DirWatcher(['src', 'include', 'test', 'examples']) initial_time = dw.most_recent_change() have_files_changed = lambda: dw.most_recent_change() != initial_time previous_success = success success = _build_and_run(check_cancelled=have_files_changed, newline_on_success=False, travis=args.travis, cache=test_cache) == 0 if not previous_success and success: jobset.message('SUCCESS', 'All tests are now passing properly', do_newline=True) jobset.message('IDLE', 'No change detected') while not have_files_changed(): time.sleep(1) else: result = _build_and_run(check_cancelled=lambda: False, newline_on_success=args.newline_on_success, travis=args.travis, cache=test_cache, xml_report=args.xml_report) if result == 0: jobset.message('SUCCESS', 'All tests passed', do_newline=True) else: jobset.message('FAILED', 'Some tests failed', do_newline=True) sys.exit(result)
bsd-3-clause
305806761/babyfs
models/TermModel.php
2801
<?php /** * Created by PhpStorm. * User: malil * Date: 2016/11/17 * Time: 15:09 */ namespace app\models; use app\models\base\BaseModel; use Yii; class TermModel extends BaseModel { public function rules() { return [ //[['id'], 'integer', 'min' => 0, 'max' => 2147483647], //['id', 'default', 'value' => 0], [['section_id'], 'integer', 'min' => 1, 'max' => 2147483647], ['section_id', 'default', 'value' => 1], [['term' ], 'required'], ['term', 'integer', 'min' => 1, 'max' => 2147483647], [['start_time' ], 'required'], //['expire_time', 'integer', 'min' => 1, 'max' => 2147483647], [['end_time'], 'required', ], //['create_time', 'integer', 'min' => 1, 'max' => 2147483647], [['order_start_time'], 'required', ], [['order_end_time'], 'required', ], ['status', 'default', 'value' => self::STATUS_ACTIVE], ['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_INACTIVE, self::STATUS_DELETED]], ['created_at', 'integer', 'min' => 1, 'max' => 2147483647], ['created_at', 'default', 'value' => 0], ['updated_at', 'integer', 'min' => 1, 'max' => 2147483647], ['updated_at', 'default', 'value' => 0], ]; } /** * @表名字 * @return string */ public static function tableName() { return 'section_term'; } /** * @阶段 * @return \yii\db\ActiveQuery */ public function getStage() { return $this->hasOne(Section::className(),['section_id' => 'section_id']); } public function getTerm() { return $this->hasMany(Section::className(), ['section_id' => 'section_id']); } public static function getTermNames() { $temp = self::find()->joinWith(['stage'])->asArray()->all(); $term = array(); foreach ($temp as $key=> $value){ $term[$value['id']] = $value['stage']['name'] .' | ' .$value['term'] .' | ' .date('Y-m-d',$value['start_time']); } // echo "<pre>"; // print_r($term);die; return $term; } /** * @return array */ public function attributeLabels() { return [ 'term' => '学期', 'start_time' => '开始时间', 'end_time' => '结束时间', 'created_at' => '添加时间', 'status' => '状态', 'order_start_time' => '订单开始时间', 'order_end_time' => '订单结束时间' ]; } public function getSectionInfo() { return $this->hasMany(Section::className(), ['section_id' => 'section_id']); } }
bsd-3-clause
asamgir/openspecimen
WEB-INF/src/com/krishagni/catissueplus/core/common/events/ResponseEvent.java
2423
package com.krishagni.catissueplus.core.common.events; import com.krishagni.catissueplus.core.common.errors.ErrorCode; import com.krishagni.catissueplus.core.common.errors.OpenSpecimenException; public class ResponseEvent<T> { private T payload; private boolean forceTxCommitEnabled; private OpenSpecimenException error; public ResponseEvent(T payload) { this.payload = payload; } public ResponseEvent(OpenSpecimenException error) { this.error = error; } public ResponseEvent(OpenSpecimenException error, boolean forceTxCommitEnabled) { this.error = error; this.forceTxCommitEnabled = forceTxCommitEnabled; } public T getPayload() { return payload; } public void setPayload(T payload) { this.payload = payload; } public OpenSpecimenException getError() { return error; } public void setError(OpenSpecimenException error) { this.error = error; } public boolean isForceTxCommitEnabled() { return forceTxCommitEnabled; } public void setForceTxCommitEnabled(boolean forceTxCommitEnabled) { this.forceTxCommitEnabled = forceTxCommitEnabled; } public void throwErrorIfUnsuccessful() { if (error != null) { throw error; } } public boolean isSuccessful() { return error == null; } public static <P> ResponseEvent<P> response(P payload) { return new ResponseEvent<P>(payload); } public static <P> ResponseEvent<P> error(OpenSpecimenException error) { return new ResponseEvent<P>(error); } public static <P> ResponseEvent<P> error(OpenSpecimenException error, boolean forceTxCommitEnabled) { return new ResponseEvent<P>(error, forceTxCommitEnabled); } public static <P> ResponseEvent<P> userError(ErrorCode error) { return new ResponseEvent<P>(OpenSpecimenException.userError(error)); } public static <P> ResponseEvent<P> serverError(ErrorCode error) { return new ResponseEvent<P>(OpenSpecimenException.serverError(error)); } public static <P> ResponseEvent<P> userError(ErrorCode error, boolean forceTxCommitEnabled) { return new ResponseEvent<P>(OpenSpecimenException.userError(error), forceTxCommitEnabled); } public static <P> ResponseEvent<P> userError(ErrorCode error, Object ... params) { return new ResponseEvent<P>(OpenSpecimenException.userError(error, params)); } public static <P> ResponseEvent<P> serverError(Exception e) { return new ResponseEvent<P>(OpenSpecimenException.serverError(e)); } }
bsd-3-clause
cafephin/mygeneration
src/mymeta/VistaDB/Source/vnDataAdapter.cs
10958
#if !IGNORE_VISTA using System; using System.Data; using System.Data.Common; using System.ComponentModel; namespace Provider.VistaDB { /// <summary> /// Represents a set of data commands and a database connection that are used to fill the DataSet /// and update a VistaDB database. This class cannot be inherited. /// </summary> [Designer("VistaDB.Designer.VistaDBDataAdapterDesigner, VistaDB.Designer.VS2003")] public sealed class VistaDBDataAdapter: DbDataAdapter, IDbDataAdapter { private VistaDBCommand selectCommand; private VistaDBCommand insertCommand; private VistaDBCommand updateCommand; private VistaDBCommand deleteCommand; /// <summary> /// Occurs during Update before a command is executed against the data source. /// The attempt to update is made, so the event fires. /// </summary> public event VistaDBRowUpdatingEventHandler RowUpdating; /// <summary> /// Occurs during Update after a command is executed against the data source. /// The attempt to update is made, so the event fires. /// </summary> public event VistaDBRowUpdatedEventHandler RowUpdated; /// <summary> /// Overloaded constructor. /// </summary> public VistaDBDataAdapter() { RowUpdating = null; RowUpdated = null; } /// <summary> /// Overloaded constructor. /// </summary> /// <param name="comm">VistaDBCommand select command object</param> public VistaDBDataAdapter( VistaDBCommand comm ) { selectCommand = comm; } /// <summary> /// Overloaded constructor. /// </summary> /// <param name="commText">V-SQL query text</param> /// <param name="conn">VistaDBConnection object</param> public VistaDBDataAdapter( string commText, VistaDBConnection conn) { selectCommand = new VistaDBCommand(commText, conn); } /// <summary> /// Overloaded constructor. /// </summary> /// <param name="commText">V-SQL query text</param> /// <param name="connString">Connectionstring to a VistaDB database</param> public VistaDBDataAdapter( string commText, string connString ) { VistaDBConnection conn = new VistaDBConnection(connString); selectCommand = new VistaDBCommand(commText, conn); } /// <summary> /// VistaDBAdapter destructor /// </summary> ~VistaDBDataAdapter() { Dispose(false); } /// <summary> /// Gets or sets the select command object. /// </summary> IDbCommand IDbDataAdapter.SelectCommand { get { return selectCommand; } set { selectCommand = (VistaDBCommand)value; } } /// <summary> /// Gets or sets the insert command object. /// </summary> IDbCommand IDbDataAdapter.InsertCommand { get { return insertCommand; } set { insertCommand = (VistaDBCommand)value; } } /// <summary> /// Gets or sets the update command object. /// </summary> IDbCommand IDbDataAdapter.UpdateCommand { get { return updateCommand; } set { updateCommand = (VistaDBCommand)value; } } /// <summary> /// Gets or sets the delete command object. /// </summary> IDbCommand IDbDataAdapter.DeleteCommand { get { return deleteCommand; } set { deleteCommand = (VistaDBCommand)value; } } /// <summary> /// Gets or sets a V-SQL statement to select records from the data set. /// </summary> [TypeConverter(typeof(ComponentConverter))] public VistaDBCommand SelectCommand { get { return selectCommand; } set { selectCommand = (VistaDBCommand)value; } } /// <summary> /// Gets or sets a V-SQL statement to insert records into the data set. /// </summary> [TypeConverter(typeof(ComponentConverter))] public VistaDBCommand InsertCommand { get { return insertCommand; } set { insertCommand = (VistaDBCommand)value; } } /// <summary> /// Gets or sets a V-SQL statement to update records in the data set. /// </summary> [TypeConverter(typeof(ComponentConverter))] public VistaDBCommand UpdateCommand { get { return updateCommand; } set { updateCommand = (VistaDBCommand)value; } } /// <summary> /// Gets or sets a V-SQL statement to delete records from the data set. /// </summary> [TypeConverter(typeof(ComponentConverter))] public VistaDBCommand DeleteCommand { get { return deleteCommand; } set { deleteCommand = (VistaDBCommand)value; } } /// <summary> /// Initializes a new instance of the RowUpdatedEventArgs class. /// </summary> /// <param name="dataRow">The DataRow used to update the data source. </param> /// <param name="command">The IDbCommand executed during the Update. </param> /// <param name="statementType">Whether the command is an UPDATE, INSERT, DELETE, or SELECT statement. </param> /// <param name="tableMapping">A DataTableMapping object. </param> /// <returns>A new instance of the RowUpdatingEventArgs class.</returns> protected override RowUpdatedEventArgs CreateRowUpdatedEvent(DataRow dataRow, IDbCommand command, StatementType statementType, DataTableMapping tableMapping) { return new VistaDBRowUpdatedEventArgs(dataRow, command, statementType, tableMapping); } /// <summary> /// Initializes a new instance of the RowUpdatingEventArgs class. /// </summary> /// <param name="dataRow">The DataRow used to update the data source. </param> /// <param name="command">The IDbCommand executed during the Update. </param> /// <param name="statementType">Whether the command is an UPDATE, INSERT, DELETE, or SELECT statement. </param> /// <param name="tableMapping">A DataTableMapping object. </param> /// <returns>A new instance of the RowUpdatingEventArgs class.</returns> protected override RowUpdatingEventArgs CreateRowUpdatingEvent(DataRow dataRow, IDbCommand command, StatementType statementType, DataTableMapping tableMapping) { return new VistaDBRowUpdatingEventArgs(dataRow, command, statementType, tableMapping); } /// <summary> /// Raises the RowUpdating event. /// </summary> /// <param name="value">RowUpdatingEventArgs</param> protected override void OnRowUpdating(RowUpdatingEventArgs value) { if(RowUpdating != null) RowUpdating(this, (VistaDBRowUpdatingEventArgs)value); } /// <summary> /// Raises the RowUpdated event. /// </summary> /// <param name="value">RowUpdatedEventArgs</param> protected override void OnRowUpdated(RowUpdatedEventArgs value) { if(RowUpdated != null) RowUpdated(this, (VistaDBRowUpdatedEventArgs)value); } /// <summary> /// Creates a new DataTableMappingCollection. /// </summary> /// <returns></returns> protected override DataTableMappingCollection CreateTableMappings() { DataTableMappingCollection collection1; collection1 = base.CreateTableMappings(); return collection1; } /// <summary> /// Overloaded. Releases the resources used by the component. /// </summary> /// <param name="disposing"></param> protected override void Dispose(bool disposing) { selectCommand = null; insertCommand = null; updateCommand = null; deleteCommand = null; } /// <summary> /// /// </summary> protected override int Fill(DataSet dataSet, int startRecord, int maxRecords, string srcTable, IDbCommand command, CommandBehavior behavior) { DataTable dataTable = dataSet.Tables[srcTable]; if(dataTable != null) dataSet.Tables[srcTable].Clear(); return base.Fill(dataSet, startRecord, maxRecords, srcTable, command, behavior); } /// <summary> /// /// </summary> protected override int Fill(DataSet dataSet, string srcTable, IDataReader dataReader, int startRecord, int maxRecords) { DataTable dataTable = dataSet.Tables[srcTable]; if(dataTable != null) dataSet.Tables[srcTable].Clear(); return base.Fill(dataSet, srcTable, dataReader, startRecord, maxRecords); } /// <summary> /// /// </summary> protected override int Fill(DataTable dataTable, IDataReader dataReader) { if(dataTable != null) dataTable.Clear(); return base.Fill(dataTable, dataReader); } /// <summary> /// /// </summary> protected override int Fill(DataTable dataTable, IDbCommand command, CommandBehavior behavior) { if(dataTable != null) dataTable.Clear(); return base.Fill(dataTable, command, behavior); } /// <summary> /// Initializes a new instance of the DataTableMappingCollection class. This new instance is empty /// and does not yet contain any DataTableMapping objects. /// </summary> [Browsable(true), Editor("VistaDB.Designer.VistaDBTableMappingsEditor, VistaDB.Designer.VS2003", "System.Drawing.Design.UITypeEditor")] public new DataTableMappingCollection TableMappings { get { return base.TableMappings; } } } /// <summary> /// Represents the method that will handle the RowUpdating event of a VistaDBDataAdapter. /// </summary> public delegate void VistaDBRowUpdatingEventHandler(object sender, VistaDBRowUpdatingEventArgs e); /// <summary> /// Represents the method that will handle the RowUpdated event of a VistaDBDataAdapter. /// </summary> public delegate void VistaDBRowUpdatedEventHandler(object sender, VistaDBRowUpdatedEventArgs e); /// <summary> /// Manages RowUpdating events of the VistaDB ADO.NET Data Provider. /// </summary> public class VistaDBRowUpdatingEventArgs: RowUpdatingEventArgs { /// <summary> /// Provides the data for the RowUpdating event of the VistaDB ADO.NET Data Provider. /// </summary> /// <param name="row"></param> /// <param name="command"></param> /// <param name="statementType"></param> /// <param name="tableMapping"></param> public VistaDBRowUpdatingEventArgs(DataRow row, IDbCommand command, StatementType statementType, DataTableMapping tableMapping): base(row, command, statementType, tableMapping) { } /// <summary> /// Gets or sets a new instance of the VistaDBCommand class. /// </summary> public new VistaDBCommand Command { get { return (VistaDBCommand)(base.Command); } set { base.Command = value; } } } /// <summary> /// Provides data for the RowUpdated event of the VistaDB ADO.NET Data Provider. /// </summary> public class VistaDBRowUpdatedEventArgs: RowUpdatedEventArgs { /// <summary> /// Provides the data for the RowUpdating event of the VistaDB ADO.NET Data Provider. /// </summary> /// <param name="row"></param> /// <param name="command"></param> /// <param name="statementType"></param> /// <param name="tableMapping"></param> public VistaDBRowUpdatedEventArgs(DataRow row, IDbCommand command, StatementType statementType, DataTableMapping tableMapping): base(row, command, statementType, tableMapping) { } /// <summary> /// Constructor. /// </summary> public new VistaDBCommand Command { get { return (VistaDBCommand)(base.Command); } } } } #endif
bsd-3-clause
naohisas/KVS
Source/Core/Visualization/Exporter/PointExporter.cpp
1743
/*****************************************************************************/ /** * @file PointExporter.cpp * @author Naohisa Sakamoto */ /*****************************************************************************/ #include "PointExporter.h" #include <kvs/Message> namespace kvs { /*===========================================================================*/ /** * @brief Constructs a new PointExporter class for KVMLObjectPoint format. * @param object [in] pointer to the input point object */ /*===========================================================================*/ PointExporter<kvs::KVSMLPointObject>::PointExporter( const kvs::PointObject* object ) { this->exec( object ); } /*===========================================================================*/ /** * @brief Executes the export process. * @param object [in] pointer to the input object * @return pointer to the KVSMLPointObject format */ /*===========================================================================*/ kvs::KVSMLPointObject* PointExporter<kvs::KVSMLPointObject>::exec( const kvs::ObjectBase* object ) { BaseClass::setSuccess( true ); if ( !object ) { BaseClass::setSuccess( false ); kvsMessageError("Input object is NULL."); return NULL; } const kvs::PointObject* point = kvs::PointObject::DownCast( object ); if ( !point ) { BaseClass::setSuccess( false ); kvsMessageError("Input object is not point object."); return NULL; } this->setCoords( point->coords() ); this->setColors( point->colors() ); this->setNormals( point->normals() ); this->setSizes( point->sizes() ); return this; } } // end of namespace kvs
bsd-3-clause
rkimball/tinytcp
tcp_stack/ProtocolIPv4.cpp
7571
//---------------------------------------------------------------------------- // Copyright(c) 2015-2021, Robert Kimball // 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 the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. //---------------------------------------------------------------------------- #include <iostream> #include <stdio.h> #include "DataBuffer.hpp" #include "FCS.hpp" #include "InterfaceMAC.hpp" #include "ProtocolARP.hpp" #include "ProtocolICMP.hpp" #include "ProtocolIPv4.hpp" #include "ProtocolTCP.hpp" #include "ProtocolUDP.hpp" #include "Utility.hpp" // Version - 4 bits // Header Length - 4 bits // Type of Service - 8 bits // TotalLength - 16 bits // Identification - 16 bits // Flags - 3 bits // FragmentOffset - 13 bits // TTL - 8 bits // Protocol - 8 bits // HeaderChecksum - 16 bits ProtocolIPv4::ProtocolIPv4( InterfaceMAC& mac, ProtocolARP& arp, ProtocolICMP& icmp, ProtocolTCP& tcp, ProtocolUDP& udp) : PacketID(0) , UnresolvedQueue("IP", TX_BUFFER_COUNT, TxBuffer) , Address() , MAC(mac) , ARP(arp) , ICMP(icmp) , TCP(tcp) , UDP(udp) { Address.DataValid = false; } bool ProtocolIPv4::IsLocal(const uint8_t* addr) { bool rc; uint8_t broadcast[] = {0xFF, 0xFF, 0xFF, 0xFF}; if (Address.DataValid) { rc = AddressCompare(addr, broadcast, AddressSize()) || AddressCompare(addr, GetUnicastAddress(), AddressSize()) || AddressCompare(addr, GetBroadcastAddress(), AddressSize()); } else { rc = AddressCompare(addr, broadcast, AddressSize()); } return rc; } void ProtocolIPv4::ProcessRx(DataBuffer* buffer) { uint8_t headerLength; uint8_t protocol; uint8_t* sourceIP; uint8_t* targetIP; uint8_t* packet = buffer->Packet; uint16_t length = buffer->Length; uint16_t dataLength; headerLength = (packet[0] & 0x0F) * 4; dataLength = Unpack16(packet, 2); protocol = packet[9]; sourceIP = &packet[12]; targetIP = &packet[16]; if (IsLocal(targetIP)) { buffer->Packet += headerLength; dataLength -= headerLength; buffer->Length = dataLength; switch (protocol) { case 0x01: // ICMP ICMP.ProcessRx(buffer, sourceIP, targetIP); break; case 0x02: // IGMP break; case 0x06: // TCP TCP.ProcessRx(buffer, sourceIP, targetIP); break; case 0x11: // UDP UDP.ProcessRx(buffer, sourceIP, targetIP); break; default: printf("Unsupported IP Protocol 0x%02X\n", protocol); break; } } } DataBuffer* ProtocolIPv4::GetTxBuffer(InterfaceMAC* mac) { DataBuffer* buffer; buffer = mac->GetTxBuffer(); if (buffer != nullptr) { buffer->Packet += header_size(); buffer->Remainder -= header_size(); } return buffer; } void ProtocolIPv4::Transmit(DataBuffer* buffer, uint8_t protocol, const uint8_t* targetIP, const uint8_t* sourceIP) { uint16_t checksum; const uint8_t* targetMAC; uint8_t* packet; buffer->Packet -= header_size(); buffer->Length += header_size(); packet = buffer->Packet; packet[0] = 0x45; // Version and HeaderSize packet[1] = 0; // ToS Pack16(packet, 2, buffer->Length); PacketID++; Pack16(packet, 4, PacketID); packet[6] = 0; // Flags & FragmentOffset packet[7] = 0; // rest of FragmentOffset packet[8] = 32; // TTL packet[9] = protocol; Pack16(packet, 10, 0); // checksum placeholder PackBytes(packet, 12, sourceIP, 4); PackBytes(packet, 16, targetIP, 4); checksum = FCS::Checksum(packet, 20); Pack16(packet, 10, checksum); targetMAC = ARP.Protocol2Hardware(targetIP); if (targetMAC != nullptr) { MAC.Transmit(buffer, targetMAC, 0x0800); } else { // Could not find MAC address, ARP for it UnresolvedQueue.Put(buffer); } } void ProtocolIPv4::Retransmit(DataBuffer* buffer) { MAC.Retransmit(buffer); } void ProtocolIPv4::Retry() { int count; DataBuffer* buffer; const uint8_t* targetMAC; count = UnresolvedQueue.GetCount(); for (int i = 0; i < count; i++) { buffer = (DataBuffer*)UnresolvedQueue.Get(); targetMAC = ARP.Protocol2Hardware(&buffer->Packet[16]); if (targetMAC != nullptr) { MAC.Transmit(buffer, targetMAC, 0x0800); } else { printf("Still could not find MAC for IP\n"); UnresolvedQueue.Put(buffer); } } } void ProtocolIPv4::FreeTxBuffer(DataBuffer* buffer) { MAC.FreeTxBuffer(buffer); } void ProtocolIPv4::FreeRxBuffer(DataBuffer* buffer) { MAC.FreeRxBuffer(buffer); } std::ostream& operator<<(std::ostream& out, const ProtocolIPv4& obj) { out << "IPv4 Configuration\n"; out << " Address: " << ipv4toa(obj.Address.Address) << "\n"; out << " Subnet Mask: " << ipv4toa(obj.Address.SubnetMask) << "\n"; out << " Gateway: " << ipv4toa(obj.Address.Gateway) << "\n"; out << " Domain Name Server: " << ipv4toa(obj.Address.DomainNameServer) << "\n"; out << " Broadcast Address: " << ipv4toa(obj.Address.BroadcastAddress) << "\n"; out << " Address Lease Time: " << obj.Address.IpAddressLeaseTime << " seconds\n"; out << " RenewTime: " << obj.Address.RenewTime << " seconds\n"; out << " RebindTime: " << obj.Address.RebindTime << " seconds\n"; return out; } size_t ProtocolIPv4::AddressSize() { return ADDRESS_SIZE; } const uint8_t* ProtocolIPv4::GetUnicastAddress() { return Address.Address; } const uint8_t* ProtocolIPv4::GetBroadcastAddress() { return Address.BroadcastAddress; } const uint8_t* ProtocolIPv4::GetGatewayAddress() { return Address.Gateway; } const uint8_t* ProtocolIPv4::GetSubnetMask() { return Address.SubnetMask; } void ProtocolIPv4::SetAddressInfo(const AddressInfo& info) { Address = info; }
bsd-3-clause
opentoonz/dwango_opentoonz_plugins
ImageQuilting/src/main.cpp
16047
#define TNZU_DEFINE_INTERFACE #include <toonz_utility.hpp> #include <opencv2/imgproc/imgproc.hpp> class MyFx : public tnzu::Fx { public: // // PORT // enum { PORT_BACKGROUND, PORT_FOREGROUND, PORT_COUNT, }; int port_count() const override { return PORT_COUNT; } char const* port_name(int i) const override { static std::array<char const*, PORT_COUNT> names = { "background", "foreground", }; return names[i]; } // // GROUP COUNT // enum { PARAM_GROUP_DEFAULT, PARAM_GROUP_COUNT, }; int param_group_count() const override { return PARAM_GROUP_COUNT; } char const* param_group_name(int i) const override { static std::array<char const*, PARAM_GROUP_COUNT> names = { "Default", }; return names[i]; } // // PARAM // enum { PARAM_BORDER, PARAM_DEBUG, PARAM_COUNT, }; int param_count() const override { return PARAM_COUNT; } ParamPrototype const* param_prototype(int i) const override { static std::array<ParamPrototype, PARAM_COUNT> const params = { ParamPrototype{"border", 0, 0.2, 0, 1}, ParamPrototype{"debug", 0, 0.0, 0, 1}, }; return &params[i]; } public: int compute(Config const& config, Params const& params, Args const& args, cv::Mat& retimg) override; }; namespace tnzu { PluginInfo const* plugin_info() { static PluginInfo const info(TNZU_PP_STR(PLUGIN_NAME), // name TNZU_PP_STR(PLUGIN_VENDOR), // vendor "", // note "http://dwango.co.jp/"); // helpurl return &info; } Fx* make_fx() { return new MyFx(); } } template <typename Vec4T> float manhattan_distance(Vec4T const& a, Vec4T const& b) { float sum = 0; for (int c = 0; c < 4; c++) { sum += std::abs(a[c] - b[c]); } return sum; } template <typename Vec4T> void calculate_cost(cv::Mat& cost, cv::Mat const& dst, cv::Mat const& src, int const left, int const top, int const right, int const bottom) { cv::Size const size = cost.size(); int y = 0; for (; y < top; ++y) { Vec4T const* b = dst.ptr<Vec4T>(y); Vec4T const* f = src.ptr<Vec4T>(y); float* cst = cost.ptr<float>(y); for (int x = 0; x < size.width; x++) { cst[x] = manhattan_distance(b[x], f[x]); } } for (; y < bottom; ++y) { Vec4T const* b = dst.ptr<Vec4T>(y); Vec4T const* f = src.ptr<Vec4T>(y); float* cst = cost.ptr<float>(y); for (int x = 0; x < left; x++) { cst[x] = manhattan_distance(b[x], f[x]); } for (int x = right; x < size.width; x++) { cst[x] = manhattan_distance(b[x], f[x]); } } for (; y < size.height; ++y) { Vec4T const* b = dst.ptr<Vec4T>(y); Vec4T const* f = src.ptr<Vec4T>(y); float* cst = cost.ptr<float>(y); for (int x = 0; x < size.width; x++) { cst[x] = manhattan_distance(b[x], f[x]); } } } void calculate_path(cv::Mat& cost, int const left, int const top, int const right, int const bottom) { // (h) | (a) | (b) // ----+-----+----- // (g) | | (c) // ----+-----+----- // (f) | (e) | (d) cv::Size const size = cost.size(); // (a) w/o first column for (int x = left + 1; x < right; ++x) { int y = top - 1; cost.at<float>(y, x) += std::min(cost.at<float>(y + 0, x - 1), cost.at<float>(y - 1, x - 1)); for (--y; y > 0; --y) { cost.at<float>(y, x) += std::min( std::min(cost.at<float>(y + 1, x - 1), cost.at<float>(y + 0, x - 1)), cost.at<float>(y - 1, x - 1)); } cost.at<float>(y, x) += std::min(cost.at<float>(y + 1, x - 1), cost.at<float>(y + 0, x - 1)); } // (b) for (int x = right; x < size.width; ++x) { int y = 0; cost.at<float>(y, x) += cost.at<float>(y + 0, x - 1); for (++y; y < top; ++y) { cost.at<float>(y, x) += std::min( std::min(cost.at<float>(y + 0, x - 1), cost.at<float>(y - 1, x - 1)), cost.at<float>(y - 1, x + 0)); } } // (c) for (int y = top; y < bottom; ++y) { int x = size.width - 1; cost.at<float>(y, x) += std::min(cost.at<float>(y - 1, x + 0), cost.at<float>(y - 1, x - 1)); for (--x; x > right; --x) { cost.at<float>(y, x) += std::min( std::min(cost.at<float>(y - 1, x + 1), cost.at<float>(y - 1, x + 0)), cost.at<float>(y - 1, x - 1)); } cost.at<float>(y, x) += std::min(cost.at<float>(y - 1, x + 1), cost.at<float>(y - 1, x + 0)); } // (d) for (int y = bottom; y < size.height; y++) { int x = size.width - 1; cost.at<float>(y, x) += cost.at<float>(y - 1, x + 0); for (--x; x >= right; --x) { cost.at<float>(y, x) += std::min( std::min(cost.at<float>(y + 0, x + 1), cost.at<float>(y - 1, x + 1)), cost.at<float>(y - 1, x + 0)); } } // (e) for (int x = right - 1; x >= left; --x) { int y = size.height - 1; cost.at<float>(y, x) += std::min(cost.at<float>(y + 0, x + 1), cost.at<float>(y - 1, x + 1)); for (--y; y > bottom; --y) { cost.at<float>(y, x) += std::min( std::min(cost.at<float>(y + 1, x + 1), cost.at<float>(y + 0, x + 1)), cost.at<float>(y - 1, x + 1)); } cost.at<float>(y, x) += std::min(cost.at<float>(y + 1, x + 1), cost.at<float>(y + 0, x + 1)); } // (f) for (int x = right - 1; x >= 0; --x) { int y = size.height - 1; cost.at<float>(y, x) += cost.at<float>(y, x + 1); for (--y; y >= bottom; --y) { cost.at<float>(y, x) += std::min( std::min(cost.at<float>(y + 0, x + 1), cost.at<float>(y + 1, x + 1)), cost.at<float>(y + 1, x + 0)); } } // (g) for (int y = bottom - 1; y >= top; --y) { int x = left - 1; cost.at<float>(y, x) += std::min(cost.at<float>(y + 1, x + 0), cost.at<float>(y + 1, x - 1)); for (--x; x > 0; --x) { cost.at<float>(y, x) += std::min( std::min(cost.at<float>(y + 1, x + 1), cost.at<float>(y + 1, x + 0)), cost.at<float>(y + 1, x - 1)); } cost.at<float>(y, x) += std::min(cost.at<float>(y + 1, x + 1), cost.at<float>(y + 1, x + 0)); } // (h) for (int y = top - 1; y >= 0; --y) { int x = 0; cost.at<float>(y, x) += cost.at<float>(y + 1, x + 0); for (++x; x < left; ++x) { cost.at<float>(y, x) += std::min( std::min(cost.at<float>(y + 0, x - 1), cost.at<float>(y + 1, x - 1)), cost.at<float>(y + 1, x + 0)); } } // (a) first column { int x = left; int y = top - 1; cost.at<float>(y, x) += std::min(cost.at<float>(y + 0, x - 1), cost.at<float>(y - 1, x - 1)); for (--y; y > 0; --y) { cost.at<float>(y, x) += std::min( std::min(cost.at<float>(y + 1, x - 1), cost.at<float>(y + 0, x - 1)), cost.at<float>(y - 1, x - 1)); } cost.at<float>(y, x) += std::min(cost.at<float>(y + 1, x - 1), cost.at<float>(y + 0, x - 1)); } } // find a position which has minimum cost cv::Point find_next_pos(std::array<cv::Point, 3> const& ps, cv::Mat const& cost, int const left, int const top, int const right, int const bottom) { cv::Size const size = cost.size(); float min_cost = std::numeric_limits<float>::infinity(); cv::Point min_pos; for (cv::Point const& cur : ps) { if ((cur.x < 0) || (cur.x >= size.width) || (cur.y < 0) || (cur.y >= size.height)) { continue; } if ((left <= cur.x) && (cur.x < right) && (top <= cur.y) && (cur.y < bottom)) { continue; } float const cc = cost.at<float>(cur); if (min_cost > cc) { min_cost = cc, min_pos = cur; } } return min_pos; } template <typename Vec4T> void copy_vertically(cv::Mat& dst, cv::Mat const& src, int const x, int const top, int const bottom) { for (int y = top; y < bottom; ++y) { dst.at<Vec4T>(y, x) = src.at<Vec4T>(y, x); } } template <typename Vec4T> void copy_horizontally(cv::Mat& dst, cv::Mat const& src, int const left, int const right, int const y) { for (int x = left; x < right; ++x) { dst.at<Vec4T>(y, x) = src.at<Vec4T>(y, x); } } template <typename Vec4T> void trace_path(cv::Mat& dst, cv::Mat const& src, cv::Mat const& cost, int const left, int const top, int const right, int const bottom, bool const debug) { // (h) | (a) | (b) // ----+-----+----- // (g) | | (c) // ----+-----+----- // (f) | (e) | (d) using value_type = typename Vec4T::value_type; int const g = std::numeric_limits<value_type>::max(); Vec4T const mark_color(g, 0, g, g); cv::Size const size = cost.size(); // (a) cv::Point pos(left, 0); { // find a starting point float min_cost = std::numeric_limits<float>::infinity(); for (int yy = 0; yy < top; ++yy) { float const cc = cost.at<float>(yy, pos.x); // current cost if (min_cost > cc) { min_cost = cc, pos.y = yy; } } // copy copy_vertically<Vec4T>(dst, src, pos.x, pos.y, top); if (debug) { dst.at<Vec4T>(pos) = mark_color; } // (a) to (h) std::array<cv::Point, 3> const ps = { cv::Point(pos.x - 1, pos.y - 1), cv::Point(pos.x - 1, pos.y + 0), cv::Point(pos.x - 1, pos.y + 1), }; pos = find_next_pos(ps, cost, left, top, right, bottom); } // (h) copy_vertically<Vec4T>(dst, src, pos.x, pos.y, top); if (debug) { dst.at<Vec4T>(pos) = mark_color; } while ((pos.x != 0) && (pos.y != top)) { std::array<cv::Point, 3> const ps = { cv::Point(pos.x - 1, pos.y + 0), cv::Point(pos.x - 1, pos.y + 1), cv::Point(pos.x + 0, pos.y + 1), }; cv::Point const cur = find_next_pos(ps, cost, left, top, right, bottom); if (pos.x != cur.x) { copy_vertically<Vec4T>(dst, src, cur.x, cur.y, top); if (debug) { dst.at<Vec4T>(cur) = mark_color; } } pos = cur; // move } pos.y = top; // (g) while (pos.y < bottom) { copy_horizontally<Vec4T>(dst, src, pos.x, left, pos.y); if (debug) { dst.at<Vec4T>(pos) = mark_color; } std::array<cv::Point, 3> const ps = { cv::Point(pos.x - 1, pos.y + 1), cv::Point(pos.x + 0, pos.y + 1), cv::Point(pos.x + 1, pos.y + 1), }; pos = find_next_pos(ps, cost, left, top, right, bottom); } // (f) copy_horizontally<Vec4T>(dst, src, pos.x, left, pos.y); if (debug) { dst.at<Vec4T>(pos) = mark_color; } while ((pos.x != left) && (pos.y != size.height - 1)) { std::array<cv::Point, 3> const ps = { cv::Point(pos.x + 0, pos.y + 1), cv::Point(pos.x + 1, pos.y + 1), cv::Point(pos.x + 1, pos.y + 0), }; cv::Point const cur = find_next_pos(ps, cost, left, top, right, bottom); if (pos.y != cur.y) { copy_horizontally<Vec4T>(dst, src, cur.x, left, cur.y); if (debug) { dst.at<Vec4T>(cur) = mark_color; } } pos = cur; // move } pos.x = left; // (e) while (pos.x < right) { copy_vertically<Vec4T>(dst, src, pos.x, bottom, pos.y + 1); if (debug) { dst.at<Vec4T>(pos) = mark_color; } std::array<cv::Point, 3> const ps = { cv::Point(pos.x + 1, pos.y + 1), cv::Point(pos.x + 1, pos.y + 0), cv::Point(pos.x + 1, pos.y - 1), }; pos = find_next_pos(ps, cost, left, top, right, bottom); } // (d) copy_vertically<Vec4T>(dst, src, pos.x, bottom, pos.y + 1); if (debug) { dst.at<Vec4T>(pos) = mark_color; } while ((pos.x != size.width - 1) && (pos.y != bottom - 1)) { std::array<cv::Point, 3> const ps = { cv::Point(pos.x + 1, pos.y + 0), cv::Point(pos.x + 1, pos.y - 1), cv::Point(pos.x + 0, pos.y - 1), }; cv::Point const cur = find_next_pos(ps, cost, left, top, right, bottom); if (pos.x < cur.x) { copy_vertically<Vec4T>(dst, src, cur.x, bottom, cur.y + 1); if (debug) { dst.at<Vec4T>(cur) = mark_color; } } pos = cur; // move } pos.y = bottom - 1; // (c) while (pos.y > top) { copy_horizontally<Vec4T>(dst, src, right, pos.x + 1, pos.y); if (debug) { dst.at<Vec4T>(pos) = mark_color; } std::array<cv::Point, 3> const ps = { cv::Point(pos.x + 1, pos.y - 1), cv::Point(pos.x + 0, pos.y - 1), cv::Point(pos.x - 1, pos.y - 1), }; pos = find_next_pos(ps, cost, left, top, right, bottom); } // (b) copy_horizontally<Vec4T>(dst, src, right, pos.x + 1, pos.y); if (debug) { dst.at<Vec4T>(pos) = mark_color; } while ((pos.x != right - 1) && (pos.y != 0)) { std::array<cv::Point, 3> const ps = { cv::Point(pos.x + 0, pos.y - 1), cv::Point(pos.x - 1, pos.y - 1), cv::Point(pos.x - 1, pos.y + 0), }; cv::Point const cur = find_next_pos(ps, cost, left, top, right, bottom); if (pos.y > cur.y) { copy_horizontally<Vec4T>(dst, src, right, cur.x + 1, cur.y); if (debug) { dst.at<Vec4T>(cur) = mark_color; } } pos = cur; // move } pos.x = right - 1; // (a) while (pos.x > left) { copy_vertically<Vec4T>(dst, src, pos.x, pos.y, top); if (debug) { dst.at<Vec4T>(pos) = mark_color; } std::array<cv::Point, 3> const ps = { cv::Point(pos.x - 1, pos.y - 1), cv::Point(pos.x - 1, pos.y + 0), cv::Point(pos.x - 1, pos.y + 1), }; pos = find_next_pos(ps, cost, left, top, right, bottom); } } int MyFx::compute(Config const& config, Params const& params, Args const& args, cv::Mat& retimg) try { DEBUG_PRINT(__FUNCTION__); if (args.invalid(PORT_BACKGROUND) && args.invalid(PORT_FOREGROUND)) { return 0; } if (args.invalid(PORT_BACKGROUND)) { args.get(PORT_BACKGROUND).copyTo(retimg(args.rect(PORT_BACKGROUND))); return 0; } if (args.invalid(PORT_FOREGROUND)) { args.get(PORT_FOREGROUND).copyTo(retimg(args.rect(PORT_FOREGROUND))); return 0; } cv::Mat const src = args.get(PORT_FOREGROUND); cv::Size const size = src.size(); // foreground size if ((size.width < 3) || (size.height < 3)) { return 0; } int const border = params.get<int>(PARAM_BORDER, size.height / 2); if (border <= 0) { args.get(PORT_FOREGROUND).copyTo(retimg(args.rect(PORT_FOREGROUND))); return 0; } bool const debug = params.get<bool>(PARAM_DEBUG); cv::Rect roi; roi.x = border; roi.y = border; roi.width = size.width - 2 * border; roi.height = size.height - 2 * border; if ((roi.width <= 0) || (roi.height <= 0)) { return 0; } // background args.get(PORT_BACKGROUND).copyTo(retimg(args.rect(PORT_BACKGROUND))); // foreground cv::Mat dst = retimg(cv::Rect(args.offset(PORT_FOREGROUND), size)); args.get(PORT_FOREGROUND)(roi).copyTo(dst(roi)); // quilting cost cv::Mat cost(size, CV_32FC1, std::numeric_limits<cv::Scalar>::infinity()); int const left = roi.x; int const right = roi.x + roi.width; int const top = roi.y; int const bottom = roi.y + roi.height; if (retimg.type() == CV_8UC4) { // calculate cost calculate_cost<cv::Vec4b>(cost, dst, src, left, top, right, bottom); } else { // calculate cost calculate_cost<cv::Vec4w>(cost, dst, src, left, top, right, bottom); } // calculate a path by dynamic programming calculate_path(cost, left, top, right, bottom); // trace the path if (retimg.type() == CV_8UC4) { trace_path<cv::Vec4b>(dst, src, cost, left, top, right, bottom, debug); } else { trace_path<cv::Vec4w>(dst, src, cost, left, top, right, bottom, debug); } if (debug) { double const g = (retimg.type() == CV_8UC4) ? std::numeric_limits<uchar>::max() : std::numeric_limits<ushort>::max(); cv::rectangle(dst, roi, cv::Scalar(g, g, 0, g)); } return 0; } catch (cv::Exception const& e) { DEBUG_PRINT(e.what()); }
bsd-3-clause
fintroll/mdkp
config/db.php
177
<?php return [ 'class' => 'yii\db\Connection', 'dsn' => 'mysql:host=localhost;dbname=mdkr', 'username' => 'root', 'password' => '', 'charset' => 'utf8', ];
bsd-3-clause
sts-CAD-Software/PCB-Investigator-Scripts
Main-Folder/Calculate Job Bounds.cs
2456
//----------------------------------------------------------------------------------- // PCB-Investigator Automation Script // Created on 2014-04-24 // Autor support@easylogix.de // www.pcb-investigator.com // SDK online reference http://www.pcb-investigator.com/sites/default/files/documents/InterfaceDocumentation/Index.html // SDK http://www.pcb-investigator.com/en/sdk-participate // Check all elements and calculate bounds. //----------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Text; using PCBI.Plugin; using PCBI.Plugin.Interfaces; using System.Windows.Forms; using System.Drawing; using PCBI.Automation; using System.IO; using System.Drawing.Drawing2D; using PCBI.MathUtils; namespace PCBIScript { public class PScript : IPCBIScript { public PScript() { } public void Execute(IPCBIWindow parent) { RectangleF boundsJob = parent.GetJobBounds(); if (boundsJob.IsEmpty) { IStep step = parent.GetCurrentStep(); if (step == null) return; boundsJob = step.GetBounds(); if (boundsJob.IsEmpty) { IMatrix matrix = parent.GetMatrix(); if (matrix == null) return; RectangleD boundsLayerCombination = new RectangleD(); //check signal layers foreach (string layerName in step.GetAllLayerNames()) { if (matrix.IsSignalLayer(layerName)) { IODBLayer odbLayer = (IODBLayer)step.GetLayer(layerName); RectangleF layerBounds = odbLayer.GetBounds(); boundsLayerCombination = IMath.AddRectangleD(boundsLayerCombination, new RectangleD(layerBounds)); } } boundsJob = boundsLayerCombination.ToRectangleF(); } } MessageBox.Show("The Job has following bounds in mils:" + Environment.NewLine + " X " + boundsJob.X.ToString() + " ; Y " + boundsJob.Y.ToString() + " ; width " + boundsJob.Width + " ; height " + boundsJob.Height, "Job Bounds", MessageBoxButtons.OK, MessageBoxIcon.Information); } } }
bsd-3-clause
marmolejo/chromium
url/url_canon_internal.cc
10757
// 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 "url/url_canon_internal.h" #include <errno.h> #include <stdlib.h> #include <cstdio> #include <string> namespace url { namespace { // Overrides one component, see the Replacements structure for // what the various combionations of source pointer and component mean. void DoOverrideComponent(const char* override_source, const Component& override_component, const char** dest, Component* dest_component) { if (override_source) { *dest = override_source; *dest_component = override_component; } } } // namespace // See the header file for this array's declaration. const unsigned char kSharedCharTypeTable[0x100] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x00 - 0x0f 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x10 - 0x1f 0, // 0x20 ' ' (escape spaces in queries) CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x21 ! 0, // 0x22 " 0, // 0x23 # (invalid in query since it marks the ref) CHAR_QUERY | CHAR_USERINFO, // 0x24 $ CHAR_QUERY | CHAR_USERINFO, // 0x25 % CHAR_QUERY | CHAR_USERINFO, // 0x26 & 0, // 0x27 ' (Try to prevent XSS.) CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x28 ( CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x29 ) CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x2a * CHAR_QUERY | CHAR_USERINFO, // 0x2b + CHAR_QUERY | CHAR_USERINFO, // 0x2c , CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x2d - CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_COMPONENT, // 0x2e . CHAR_QUERY, // 0x2f / CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_HEX | CHAR_DEC | CHAR_OCT | CHAR_COMPONENT, // 0x30 0 CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_HEX | CHAR_DEC | CHAR_OCT | CHAR_COMPONENT, // 0x31 1 CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_HEX | CHAR_DEC | CHAR_OCT | CHAR_COMPONENT, // 0x32 2 CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_HEX | CHAR_DEC | CHAR_OCT | CHAR_COMPONENT, // 0x33 3 CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_HEX | CHAR_DEC | CHAR_OCT | CHAR_COMPONENT, // 0x34 4 CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_HEX | CHAR_DEC | CHAR_OCT | CHAR_COMPONENT, // 0x35 5 CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_HEX | CHAR_DEC | CHAR_OCT | CHAR_COMPONENT, // 0x36 6 CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_HEX | CHAR_DEC | CHAR_OCT | CHAR_COMPONENT, // 0x37 7 CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_HEX | CHAR_DEC | CHAR_COMPONENT, // 0x38 8 CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_HEX | CHAR_DEC | CHAR_COMPONENT, // 0x39 9 CHAR_QUERY, // 0x3a : CHAR_QUERY, // 0x3b ; 0, // 0x3c < (Try to prevent certain types of XSS.) CHAR_QUERY, // 0x3d = 0, // 0x3e > (Try to prevent certain types of XSS.) CHAR_QUERY, // 0x3f ? CHAR_QUERY, // 0x40 @ CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_HEX | CHAR_COMPONENT, // 0x41 A CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_HEX | CHAR_COMPONENT, // 0x42 B CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_HEX | CHAR_COMPONENT, // 0x43 C CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_HEX | CHAR_COMPONENT, // 0x44 D CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_HEX | CHAR_COMPONENT, // 0x45 E CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_HEX | CHAR_COMPONENT, // 0x46 F CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x47 G CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x48 H CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x49 I CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x4a J CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x4b K CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x4c L CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x4d M CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x4e N CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x4f O CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x50 P CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x51 Q CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x52 R CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x53 S CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x54 T CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x55 U CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x56 V CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x57 W CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_COMPONENT, // 0x58 X CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x59 Y CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x5a Z CHAR_QUERY, // 0x5b [ CHAR_QUERY, // 0x5c '\' CHAR_QUERY, // 0x5d ] CHAR_QUERY, // 0x5e ^ CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x5f _ CHAR_QUERY, // 0x60 ` CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_HEX | CHAR_COMPONENT, // 0x61 a CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_HEX | CHAR_COMPONENT, // 0x62 b CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_HEX | CHAR_COMPONENT, // 0x63 c CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_HEX | CHAR_COMPONENT, // 0x64 d CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_HEX | CHAR_COMPONENT, // 0x65 e CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_HEX | CHAR_COMPONENT, // 0x66 f CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x67 g CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x68 h CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x69 i CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x6a j CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x6b k CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x6c l CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x6d m CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x6e n CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x6f o CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x70 p CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x71 q CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x72 r CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x73 s CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x74 t CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x75 u CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x76 v CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x77 w CHAR_QUERY | CHAR_USERINFO | CHAR_IPV4 | CHAR_COMPONENT, // 0x78 x CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x79 y CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x7a z CHAR_QUERY, // 0x7b { CHAR_QUERY, // 0x7c | CHAR_QUERY, // 0x7d } CHAR_QUERY | CHAR_USERINFO | CHAR_COMPONENT, // 0x7e ~ 0, // 0x7f 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x80 - 0x8f 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x90 - 0x9f 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xa0 - 0xaf 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xb0 - 0xbf 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xc0 - 0xcf 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xd0 - 0xdf 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xe0 - 0xef 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xf0 - 0xff }; const char kHexCharLookup[0x10] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', }; const char kCharToHexLookup[8] = { 0, // 0x00 - 0x1f '0', // 0x20 - 0x3f: digits 0 - 9 are 0x30 - 0x39 'A' - 10, // 0x40 - 0x5f: letters A - F are 0x41 - 0x46 'a' - 10, // 0x60 - 0x7f: letters a - f are 0x61 - 0x66 0, // 0x80 - 0x9F 0, // 0xA0 - 0xBF 0, // 0xC0 - 0xDF 0, // 0xE0 - 0xFF }; const base::char16 kUnicodeReplacementCharacter = 0xfffd; void SetupOverrideComponents(const char* base, const Replacements<char>& repl, URLComponentSource<char>* source, Parsed* parsed) { // Get the source and parsed structures of the things we are replacing. const URLComponentSource<char>& repl_source = repl.sources(); const Parsed& repl_parsed = repl.components(); DoOverrideComponent(repl_source.scheme, repl_parsed.scheme, &source->scheme, &parsed->scheme); DoOverrideComponent(repl_source.username, repl_parsed.username, &source->username, &parsed->username); DoOverrideComponent(repl_source.password, repl_parsed.password, &source->password, &parsed->password); // Our host should be empty if not present, so override the default setup. DoOverrideComponent(repl_source.host, repl_parsed.host, &source->host, &parsed->host); if (parsed->host.len == -1) parsed->host.len = 0; DoOverrideComponent(repl_source.port, repl_parsed.port, &source->port, &parsed->port); DoOverrideComponent(repl_source.path, repl_parsed.path, &source->path, &parsed->path); DoOverrideComponent(repl_source.query, repl_parsed.query, &source->query, &parsed->query); DoOverrideComponent(repl_source.ref, repl_parsed.ref, &source->ref, &parsed->ref); } #ifndef WIN32 int _itoa_s(int value, char* buffer, size_t size_in_chars, int radix) { const char* format_str; if (radix == 10) format_str = "%d"; else if (radix == 16) format_str = "%x"; else return EINVAL; int written = snprintf(buffer, size_in_chars, format_str, value); if (static_cast<size_t>(written) >= size_in_chars) { // Output was truncated, or written was negative. return EINVAL; } return 0; } int _itow_s(int value, base::char16* buffer, size_t size_in_chars, int radix) { if (radix != 10) return EINVAL; // No more than 12 characters will be required for a 32-bit integer. // Add an extra byte for the terminating null. char temp[13]; int written = snprintf(temp, sizeof(temp), "%d", value); if (static_cast<size_t>(written) >= size_in_chars) { // Output was truncated, or written was negative. return EINVAL; } for (int i = 0; i < written; ++i) { buffer[i] = static_cast<base::char16>(temp[i]); } buffer[written] = '\0'; return 0; } #endif // !WIN32 } // namespace url
bsd-3-clause
davidadamsphd/hellbender
src/test/java/org/broadinstitute/hellbender/tools/walkers/bqsr/AnalyzeCovariatesIntegrationTest.java
12104
package org.broadinstitute.hellbender.tools.walkers.bqsr; import org.broadinstitute.hellbender.CommandLineProgramTest; import org.broadinstitute.hellbender.exceptions.UserException; import org.broadinstitute.hellbender.tools.IntegrationTestSpec; import org.broadinstitute.hellbender.utils.Utils; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.io.File; import java.io.IOException; import java.lang.reflect.Method; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import static org.testng.Assert.assertTrue; /** * Tests Analyze Covariates. * <p/> * Notice that since PDF report generated by R are different every-time this program * is executed their content won't be tested. It only will verify that file has a healthy size. * */ public final class AnalyzeCovariatesIntegrationTest extends CommandLineProgramTest{ /** * Directory where the testdata is located. */ private static final File TEST_DATA_DIR = new File(CommandLineProgramTest.getTestDataDir(),"AnalyzeCovariates"); /** * File containing the before report for normal testing. */ private static final File BEFORE_FILE = new File(TEST_DATA_DIR,"before.table.gz"); /** * File containing the after report for normal testing. */ private static final File AFTER_FILE = new File(TEST_DATA_DIR,"after.table.gz"); /** * File containing the bqsr report for normal testing. */ private static final File BQSR_FILE = new File(TEST_DATA_DIR,"bqsr.table.gz"); /** * Test the content of the generated csv file. * * @throws java.io.IOException should never happen. It would be an indicator of a * problem with the testing environment. */ @Test public void testCsvGeneration() throws IOException { final IntegrationTestSpec spec = new IntegrationTestSpec( buildCommandLine("%s",null,true,true,true), Collections.singletonList(new File(getTestDataDir(), "expected.AnalyzeCovariatesIntegrationTest.csv.gz").getAbsolutePath())); spec.executeTest("testCsvGeneration", this); } /** * Test the effect of changing some recalibration parameters. * @param afterFileName name of the alternative after recalibration file. * @param description describes what has been changed. * @throws java.io.IOException should never happen. It would be an * indicator of a problem with the testing environment. */ @Test(dataProvider="alternativeAfterFileProvider") public void testParameterChangeException(final String afterFileName, final String description) throws IOException { final File afterFile = new File(TEST_DATA_DIR,afterFileName); final IntegrationTestSpec spec = new IntegrationTestSpec( buildCommandLine(null,"%s",true,true,afterFile), 1,UserException.IncompatibleRecalibrationTableParameters.class); spec.executeTest("testParameterChangeException - " + description, this); } /** * Test combinations of input and output inclusion exclusion of the command * line that cause an exception to be thrown. * * @param useCsvFile whether to include the output csv file. * @param usePdfFile whether to include the output pdf file. * @param useBQSRFile whether to include the -BQSR input file. * @param useBeforeFile whether to include the -before input file. * @param useAfterFile whether to include the -after input file. * @throws java.io.IOException never thrown, unless there is a problem with the testing environment. */ @Test(dataProvider="alternativeInOutAbsenceCombinations") public void testInOutAbsenceException(final boolean useCsvFile, final boolean usePdfFile, final boolean useBQSRFile, final boolean useBeforeFile, final boolean useAfterFile) throws IOException { final IntegrationTestSpec spec = new IntegrationTestSpec(buildCommandLine(useCsvFile,usePdfFile, useBQSRFile,useBeforeFile,useAfterFile),0,UserException.class); spec.executeTest("testInOutAbsencePresenceException", this); } /** * Test combinations of input and output inclusion exclusion of the * command line that won't cause an exception. * * @param useCsvFile whether to include the output csv file. * @param usePdfFile whether to include the output pdf file. * @param useBQSRFile whether to include the -BQSR input file. * @param useBeforeFile whether to include the -before input file. * @param useAfterFile whether to include the -after input file. * @throws java.io.IOException never thrown, unless there is a problem with the testing environment. */ @Test(groups = {"R"}, dataProvider="alternativeInOutAbsenceCombinations") public void testInOutAbsence(final boolean useCsvFile, final boolean usePdfFile, final boolean useBQSRFile, final boolean useBeforeFile, final boolean useAfterFile) throws IOException { final List<String> empty = Collections.emptyList(); final IntegrationTestSpec spec = new IntegrationTestSpec(buildCommandLine(useCsvFile,usePdfFile, useBQSRFile,useBeforeFile,useAfterFile),empty); spec.executeTest("testInOutAbsencePresence", this); } @DataProvider public Iterator<Object[]> alternativeInOutAbsenceCombinations(Method m) { List<Object[]> result = new LinkedList<>(); if (m.getName().endsWith("Exception")) { result.add(new Object[] { true, false, false, false ,false}); } else { result.add(new Object[] { true, false, true, false, false }); result.add(new Object[] { true, false, false, true, false }); result.add(new Object[] { true, false, false, false, true }); result.add(new Object[] { true, false, false, true, false }); } return result.iterator(); } /** * Provide recalibration parameter change data to relevant tests. * @param m target test method. * @return never <code>null</code>. */ @DataProvider public Iterator<Object[]> alternativeAfterFileProvider (Method m) { final boolean expectsException = m.getName().endsWith("Exception"); final List<Object[]> result = new LinkedList<>(); for (final Object[] data : DIFFERENT_PARAMETERS_AFTER_FILES) { if (data[1].equals(expectsException)) { result.add(new Object[] { data[0], data[2] }); } } return result.iterator(); } /** * Triplets &lt; alfter-grp-file, whether it should fail, what is different &gt; */ private final Object[][] DIFFERENT_PARAMETERS_AFTER_FILES = { {"after-noDp.table.gz",true, "Unset the default platform" }, {"after-mcs4.table.gz", true, "Changed -mcs parameter from 2 to 4" } }; /** * Build the AC command line given what combinations of input and output files should be included. * * @param useCsvFile whether to include the output csv file. * @param usePdfFile whether to include the output pdf file. * @param useBQSRFile whether to include the -BQSR input file. * @param useBeforeFile whether to include the -before input file. * @param useAfterFile whether to include the -after input file. * @return never <code>null</code>. * @throws java.io.IOException never thrown, unless there is a problem with the testing environment. */ private String buildCommandLine(final boolean useCsvFile, final boolean usePdfFile, final boolean useBQSRFile, final boolean useBeforeFile, final boolean useAfterFile) throws IOException { final File csvFile = useCsvFile ? createTempFile("ACTest",".csv") : null; final File pdfFile = usePdfFile ? createTempFile("ACTest",".pdf") : null; return buildCommandLine(csvFile == null ? null : csvFile.toString(), pdfFile == null ? null : pdfFile.toString(), useBQSRFile,useBeforeFile,useAfterFile); } /** * Build the AC command line given the output file names explicitly and what test input files to use. * <p/> * * @param csvFileName the csv output file, <code>null</code> if none should be provided. * @param pdfFileName the plots output file, <code>null</code> if none should be provided. * @param useBQSRFile whether to include the -BQSR input file. * @param useBeforeFile whether to include the -before input file. * @param useAfterFile whether to include the -after input file. * * @return never <code>null</code>. */ private String buildCommandLine(final String csvFileName, final String pdfFileName, final boolean useBQSRFile, final boolean useBeforeFile, final boolean useAfterFile) { return buildCommandLine(csvFileName,pdfFileName,useBQSRFile ? BQSR_FILE : null, useBeforeFile ? BEFORE_FILE : null, useAfterFile ? AFTER_FILE : null); } /** * Build the AC command line given the output file names and the after file name explicitly and what other * test input files to use. * <p/> * * @param csvFileName the csv output file, <code>null</code> if none should be provided. * @param pdfFileName the plots output file, <code>null</code> if none should be provided. * @param useBQSRFile whether to include the -BQSR input file. * @param useBeforeFile whether to include the -before input file. * @param afterFile the after input report file, <code>null</code> if none should be provided. * * @return never <code>null</code>. */ private String buildCommandLine(final String csvFileName, final String pdfFileName, final boolean useBQSRFile, final boolean useBeforeFile, final File afterFile) { return buildCommandLine(csvFileName,pdfFileName,useBQSRFile ? BQSR_FILE : null, useBeforeFile ? BEFORE_FILE : null, afterFile); } /** * Build the AC command line given the output file names and the after file name explicitly and what other * test input files to use. * <p/> * * @param csvFileName the csv output file, <code>null</code> if none should be provided. * @param pdfFileName the plots output file, <code>null</code> if none should be provided. * @param bqsrFile the BQSR input report file, <code>null</code> if none should be provided. * @param beforeFile the before input report file, <code>null</code> if non should be provided. * @param afterFile the after input report file, <code>null</code> if none should be provided. * * @return never <code>null</code>. */ private String buildCommandLine(final String csvFileName, final String pdfFileName, final File bqsrFile, final File beforeFile, final File afterFile) { final List<String> args = new LinkedList<>(); args.add("-ignoreLMT"); if (csvFileName != null) { args.add("-" + AnalyzeCovariates.CSV_ARG_SHORT_NAME); args.add("'" + csvFileName + "'"); } if (pdfFileName != null) { args.add("-" + AnalyzeCovariates.PDF_ARG_SHORT_NAME); args.add("'" + pdfFileName + "'"); } if (bqsrFile != null) { args.add("-bqsr"); args.add("'" + bqsrFile.getAbsoluteFile().toString() + "'"); } if (beforeFile != null) { args.add("-" + AnalyzeCovariates.BEFORE_ARG_SHORT_NAME); args.add("'" + beforeFile.getAbsolutePath() + "'"); } if (afterFile != null) { args.add("-" + AnalyzeCovariates.AFTER_ARG_SHORT_NAME); args.add("'" + afterFile.getAbsolutePath() + "'"); } return Utils.join(" ", args); } }
bsd-3-clause
smartdevicelink/sdl_android
base/src/main/java/com/smartdevicelink/proxy/rpc/OnHMIStatus.java
10595
/* * Copyright (c) 2017 - 2019, SmartDeviceLink Consortium, 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 the SmartDeviceLink Consortium, 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 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.smartdevicelink.proxy.rpc; import androidx.annotation.NonNull; import com.smartdevicelink.protocol.enums.FunctionID; import com.smartdevicelink.proxy.RPCNotification; import com.smartdevicelink.proxy.rpc.enums.AudioStreamingState; import com.smartdevicelink.proxy.rpc.enums.HMILevel; import com.smartdevicelink.proxy.rpc.enums.SystemContext; import com.smartdevicelink.proxy.rpc.enums.VideoStreamingState; import java.util.Hashtable; /** * <p>Notifies an application that HMI conditions have changed for the application. This indicates whether the application * can speak phrases, display text, perform interactions, receive button presses and events, stream audio, etc. This * notification will be sent to the application when there has been a change in any one or several of the indicated * states ({@linkplain HMILevel}, {@linkplain AudioStreamingState} or {@linkplain SystemContext}) for the application</p> * <p>All three values are, in principle, independent of each other (though there may be some relationships). A value for * one parameter should not be interpreted from the value of another parameter.</p> * <p>There are no guarantees about the timeliness or latency of the OnHMIStatus notification. Therefore, for example, * information such as {@linkplain AudioStreamingState} may not indicate that the audio stream became inaudible to the user * exactly when the OnHMIStatus notification was received.</p> * * <p> * <b>Parameter List:</b> * <table border="1" rules="all"> * <tr> * <th>Name</th> * <th>Type</th> * <th>Description</th> * <th>SmartDeviceLink Ver Available</th> * </tr> * <tr> * <td>hmiLevel</td> * <td>{@linkplain HMILevel}</td> * <td>The current HMI Level in effect for the application.</td> * <td>SmartDeviceLink 1.0</td> * </tr> * <tr> * <td>audioStreamingState</td> * <td>{@linkplain AudioStreamingState}</td> * <td>Current state of audio streaming for the application. * When this parameter has a value of NOT_AUDIBLE, * the application must stop streaming audio to SDL. * Informs app whether any currently streaming audio is * audible to user (AUDIBLE) or not (NOT_AUDIBLE). A * value of NOT_AUDIBLE means that either the * application's audio will not be audible to the user, or * that the application's audio should not be audible to * the user (i.e. some other application on the mobile * device may be streaming audio and the application's * audio would be blended with that other audio). </td> * <td>SmartDeviceLink 1.0</td> * </tr> * <tr> * <td>videoStreamingState</td> * <td>{@linkplain VideoStreamingState}</td> * <td>If it is NOT_STREAMABLE, the app must stop streaming video to SDL Core(stop service).</td> * <td>SmartDeviceLink 5.0</td> * </tr> * <tr> * <td>systemContext</td> * <td>{@linkplain SystemContext}</td> * <td>Indicates that a user-initiated interaction is in-progress * (VRSESSION or MENU), or not (MAIN)</td> * <td>SmartDeviceLink 1.0</td> * </tr> * </table> * </p> * * @see RegisterAppInterface * @since SmartDeviceLink 1.0 */ public class OnHMIStatus extends RPCNotification { public static final String KEY_AUDIO_STREAMING_STATE = "audioStreamingState"; public static final String KEY_VIDEO_STREAMING_STATE = "videoStreamingState"; public static final String KEY_SYSTEM_CONTEXT = "systemContext"; public static final String KEY_HMI_LEVEL = "hmiLevel"; public static final String KEY_WINDOW_ID = "windowID"; private Boolean firstRun; /** * Constructs a newly allocated OnHMIStatus object */ public OnHMIStatus() { super(FunctionID.ON_HMI_STATUS.toString()); } /** * <p>Constructs a newly allocated OnHMIStatus object indicated by the Hashtable parameter</p> * * @param hash The Hashtable to use */ public OnHMIStatus(Hashtable<String, Object> hash) { super(hash); } /** * Constructs a newly allocated OnHMIStatus object * * @param hmiLevel the HMILevel to set * @param audioStreamingState the state of audio streaming of the application * @param systemContext Indicates that a user-initiated interaction is in-progress */ public OnHMIStatus(@NonNull HMILevel hmiLevel, @NonNull AudioStreamingState audioStreamingState, @NonNull SystemContext systemContext) { this(); setHmiLevel(hmiLevel); setAudioStreamingState(audioStreamingState); setSystemContext(systemContext); } @Override public void format(com.smartdevicelink.util.Version rpcVersion, boolean formatParams) { if (rpcVersion.getMajor() < 5) { if (getVideoStreamingState() == null) { setVideoStreamingState(VideoStreamingState.STREAMABLE); } } super.format(rpcVersion, formatParams); } /** * <p>Get HMILevel in effect for the application</p> * * @return {@linkplain HMILevel} the current HMI Level in effect for the application */ public HMILevel getHmiLevel() { return (HMILevel) getObject(HMILevel.class, KEY_HMI_LEVEL); } /** * <p>Set the HMILevel of OnHMIStatus</p> * * @param hmiLevel the HMILevel to set */ public OnHMIStatus setHmiLevel(@NonNull HMILevel hmiLevel) { setParameters(KEY_HMI_LEVEL, hmiLevel); return this; } /** * <p>Get current state of audio streaming for the application</p> * * @return {@linkplain AudioStreamingState} Returns current state of audio streaming for the application */ public AudioStreamingState getAudioStreamingState() { return (AudioStreamingState) getObject(AudioStreamingState.class, KEY_AUDIO_STREAMING_STATE); } /** * <p>Set the audio streaming state</p> * * @param audioStreamingState the state of audio streaming of the application */ public OnHMIStatus setAudioStreamingState(@NonNull AudioStreamingState audioStreamingState) { setParameters(KEY_AUDIO_STREAMING_STATE, audioStreamingState); return this; } /** * <p>Get current state of video streaming for the application</p> * * @return {@linkplain VideoStreamingState} Returns current state of video streaming for the application */ public VideoStreamingState getVideoStreamingState() { return (VideoStreamingState) getObject(VideoStreamingState.class, KEY_VIDEO_STREAMING_STATE); } /** * <p>Set the video streaming state</p> * * @param videoStreamingState the state of video streaming of the application */ public OnHMIStatus setVideoStreamingState(VideoStreamingState videoStreamingState) { setParameters(KEY_VIDEO_STREAMING_STATE, videoStreamingState); return this; } /** * <p>Get the System Context</p> * * @return {@linkplain SystemContext} whether a user-initiated interaction is in-progress (VRSESSION or MENU), or not (MAIN). */ public SystemContext getSystemContext() { return (SystemContext) getObject(SystemContext.class, KEY_SYSTEM_CONTEXT); } /** * <p>Set the System Context of OnHMIStatus</p> * * @param systemContext Indicates that a user-initiated interaction is in-progress * (VRSESSION or MENU), or not (MAIN) */ public OnHMIStatus setSystemContext(@NonNull SystemContext systemContext) { setParameters(KEY_SYSTEM_CONTEXT, systemContext); return this; } /** * <p>Query whether it's the first run</p> * * @return boolean whether it's the first run */ public Boolean getFirstRun() { return this.firstRun; } /** * <p>Set the firstRun value</p> * * @param firstRun True if it is the first run, False or not */ public OnHMIStatus setFirstRun(Boolean firstRun) { this.firstRun = firstRun; return this; } /** * <p>Set the windowID value</p> * * @param windowID This is the unique ID assigned to the window that this RPC is intended. * If this param is not included, it will be assumed that this request is specifically for the main window on the main display. * See PredefinedWindows enum. * @since 6.0 */ public OnHMIStatus setWindowID(Integer windowID) { setParameters(KEY_WINDOW_ID, windowID); return this; } /** * <p>Get the windowID value</p> * * @return Integer This is the unique ID assigned to the window that this RPC is intended. * @since 6.0 */ public Integer getWindowID() { return getInteger(KEY_WINDOW_ID); } }
bsd-3-clause
threerings/depot
src/test/java/com/samskivert/depot/TestCacheAdapter.java
3054
// // Depot library - a Java relational persistence library // https://github.com/threerings/depot/blob/master/LICENSE package com.samskivert.depot; import java.io.Serializable; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.samskivert.util.Tuple; /** * A simple cache adapter that stores all cached values in an in-memory map and never flushes. * Don't use this for anything other than testing or you'll regret it. */ public class TestCacheAdapter implements CacheAdapter { // from interface CacheAdapter public <T> CacheAdapter.CachedValue<T> lookup (String cacheId, Serializable key) { // System.err.println("GET " + key + ": " + _cache.containsKey(key)); @SuppressWarnings("unchecked") CachedValue<T> value = (CachedValue<T>) _cache.get( new Tuple<String, Serializable>(cacheId, key)); return value; } // from interface CacheAdapter public <T> void store (CacheCategory category, String cacheId, Serializable key, T value) { // System.err.println("STORE " + key); _cache.put(new Tuple<String, Serializable>(cacheId, key), new TestCachedValue<T>(value)); } // from interface CacheAdapter public void remove (String cacheId, Serializable key) { // System.err.println("REMOVE " + key); _cache.remove(new Tuple<String, Serializable>(cacheId, key)); } // from interface CacheAdapter public <T> Iterable<Serializable> enumerate (String cacheId) { // in a real implementation this would be a lazily constructed iterable List<Serializable> result = Lists.newArrayList(); for (Map.Entry<Tuple<String, Serializable>, CachedValue<?>> entry: _cache.entrySet()) { if (entry.getKey().left.equals(cacheId)) { result.add(entry.getKey().right); } } return result; } // from interface CacheAdapter public void clear (String cacheId, boolean localOnly) { synchronized (_cache) { for (Iterator<Tuple<String, Serializable>> iter = _cache.keySet().iterator(); iter.hasNext(); ) { Tuple<String, Serializable> key = iter.next(); if (key.left.equals(cacheId)) { iter.remove(); } } } } // from interface CacheAdapter public void shutdown () { // nothing doing! } protected static class TestCachedValue<T> implements CacheAdapter.CachedValue<T> { public TestCachedValue (T value) { _value = value; } public T getValue () { return _value; } protected final T _value; } protected Map<Tuple<String, Serializable>, CachedValue<?>> _cache = Collections.synchronizedMap( Maps.<Tuple<String, Serializable>, CachedValue<?>>newHashMap()); }
bsd-3-clause
hyakugei/rot.js
lib/display/display.js
8286
import Hex from "./hex.js"; import Rect from "./rect.js"; import Tile from "./tile.js"; import TileGL from "./tile-gl.js"; import Term from "./term.js"; import * as Text from "../text.js"; import { DEFAULT_WIDTH, DEFAULT_HEIGHT } from "../constants.js"; const BACKENDS = { "hex": Hex, "rect": Rect, "tile": Tile, "tile-gl": TileGL, "term": Term }; const DEFAULT_OPTIONS = { width: DEFAULT_WIDTH, height: DEFAULT_HEIGHT, transpose: false, layout: "rect", fontSize: 15, spacing: 1, border: 0, forceSquareRatio: false, fontFamily: "monospace", fontStyle: "", fg: "#ccc", bg: "#000", tileWidth: 32, tileHeight: 32, tileMap: {}, tileSet: null, tileColorize: false }; /** * @class Visual map display */ export default class Display { constructor(options = {}) { this._data = {}; this._dirty = false; // false = nothing, true = all, object = dirty cells this._options = {}; options = Object.assign({}, DEFAULT_OPTIONS, options); this.setOptions(options); this.DEBUG = this.DEBUG.bind(this); this._tick = this._tick.bind(this); this._backend.schedule(this._tick); } /** * Debug helper, ideal as a map generator callback. Always bound to this. * @param {int} x * @param {int} y * @param {int} what */ DEBUG(x, y, what) { let colors = [this._options.bg, this._options.fg]; this.draw(x, y, null, null, colors[what % colors.length]); } /** * Clear the whole display (cover it with background color) */ clear() { this._data = {}; this._dirty = true; } /** * @see ROT.Display */ setOptions(options) { Object.assign(this._options, options); if (options.width || options.height || options.fontSize || options.fontFamily || options.spacing || options.layout) { if (options.layout) { let ctor = BACKENDS[options.layout]; this._backend = new ctor(); } this._backend.setOptions(this._options); this._dirty = true; } return this; } /** * Returns currently set options */ getOptions() { return this._options; } /** * Returns the DOM node of this display */ getContainer() { return this._backend.getContainer(); } /** * Compute the maximum width/height to fit into a set of given constraints * @param {int} availWidth Maximum allowed pixel width * @param {int} availHeight Maximum allowed pixel height * @returns {int[2]} cellWidth,cellHeight */ computeSize(availWidth, availHeight) { return this._backend.computeSize(availWidth, availHeight); } /** * Compute the maximum font size to fit into a set of given constraints * @param {int} availWidth Maximum allowed pixel width * @param {int} availHeight Maximum allowed pixel height * @returns {int} fontSize */ computeFontSize(availWidth, availHeight) { return this._backend.computeFontSize(availWidth, availHeight); } computeTileSize(availWidth, availHeight) { let width = Math.floor(availWidth / this._options.width); let height = Math.floor(availHeight / this._options.height); return [width, height]; } /** * Convert a DOM event (mouse or touch) to map coordinates. Uses first touch for multi-touch. * @param {Event} e event * @returns {int[2]} -1 for values outside of the canvas */ eventToPosition(e) { let x, y; if ("touches" in e) { x = e.touches[0].clientX; y = e.touches[0].clientY; } else { x = e.clientX; y = e.clientY; } return this._backend.eventToPosition(x, y); } /** * @param {int} x * @param {int} y * @param {string || string[]} ch One or more chars (will be overlapping themselves) * @param {string} [fg] foreground color * @param {string} [bg] background color */ draw(x, y, ch, fg, bg) { if (!fg) { fg = this._options.fg; } if (!bg) { bg = this._options.bg; } let key = `${x},${y}`; this._data[key] = [x, y, ch, fg, bg]; if (this._dirty === true) { return; } // will already redraw everything if (!this._dirty) { this._dirty = {}; } // first! this._dirty[key] = true; } /** * Draws a text at given position. Optionally wraps at a maximum length. Currently does not work with hex layout. * @param {int} x * @param {int} y * @param {string} text May contain color/background format specifiers, %c{name}/%b{name}, both optional. %c{}/%b{} resets to default. * @param {int} [maxWidth] wrap at what width? * @returns {int} lines drawn */ drawText(x, y, text, maxWidth) { let fg = null; let bg = null; let cx = x; let cy = y; let lines = 1; if (!maxWidth) { maxWidth = this._options.width - x; } let tokens = Text.tokenize(text, maxWidth); while (tokens.length) { // interpret tokenized opcode stream let token = tokens.shift(); switch (token.type) { case Text.TYPE_TEXT: let isSpace = false, isPrevSpace = false, isFullWidth = false, isPrevFullWidth = false; for (let i = 0; i < token.value.length; i++) { let cc = token.value.charCodeAt(i); let c = token.value.charAt(i); // Assign to `true` when the current char is full-width. isFullWidth = (cc > 0xff00 && cc < 0xff61) || (cc > 0xffdc && cc < 0xffe8) || cc > 0xffee; // Current char is space, whatever full-width or half-width both are OK. isSpace = (c.charCodeAt(0) == 0x20 || c.charCodeAt(0) == 0x3000); // The previous char is full-width and // current char is nether half-width nor a space. if (isPrevFullWidth && !isFullWidth && !isSpace) { cx++; } // add an extra position // The current char is full-width and // the previous char is not a space. if (isFullWidth && !isPrevSpace) { cx++; } // add an extra position this.draw(cx++, cy, c, fg, bg); isPrevSpace = isSpace; isPrevFullWidth = isFullWidth; } break; case Text.TYPE_FG: fg = token.value || null; break; case Text.TYPE_BG: bg = token.value || null; break; case Text.TYPE_NEWLINE: cx = x; cy++; lines++; break; } } return lines; } /** * Timer tick: update dirty parts */ _tick() { this._backend.schedule(this._tick); if (!this._dirty) { return; } if (this._dirty === true) { // draw all this._backend.clear(); for (let id in this._data) { this._draw(id, false); } // redraw cached data } else { // draw only dirty for (let key in this._dirty) { this._draw(key, true); } } this._dirty = false; } /** * @param {string} key What to draw * @param {bool} clearBefore Is it necessary to clean before? */ _draw(key, clearBefore) { let data = this._data[key]; if (data[4] != this._options.bg) { clearBefore = true; } this._backend.draw(data, clearBefore); } } Display.Rect = Rect; Display.Hex = Hex; Display.Tile = Tile; Display.TileGL = TileGL; Display.Term = Term;
bsd-3-clause
sinemetu1/chronos
ui/modules/www/SiteMain/SiteMain.js
1240
// import import React, {Component, PropTypes} from 'react'; import Helmet from 'react-helmet'; import config from '../config.js'; import cn from 'classnames'; import styles from './SiteMain.css'; import {connect} from 'react-redux'; import RunsList from '../RunsList/RunsList.js'; // fns function formatTitle(title) { if (!title) { return config.siteTitle + config.siteTitleSep + config.siteTitleSlogan; } return title + config.siteTitleSep + config.siteTitle; } // export @connect((state) => { return { hideSidebar: state.localStorage.hideSidebar === 'true', }; }) export default class SiteMain extends Component { static propTypes = { children: PropTypes.node, className: PropTypes.string, hideSidebar: PropTypes.bool.isRequired, routeParams: PropTypes.object.isRequired, title: PropTypes.string, }; render() { const {className, title, children, hideSidebar, routeParams, ...props} = this.props; return ( <main {...props} className={cn(styles.SiteMain, className, {[styles.hideSidebar]: hideSidebar})}> <Helmet title={formatTitle(title)}/> {children} <RunsList className={styles.runsList} id={routeParams.id || null}/> </main> ); } }
bsd-3-clause
ozak/geopandas
examples/plotting_basemap_background.py
2671
""" Adding a background map to plots -------------------------------- This example shows how you can add a background basemap to plots created with the geopandas ``.plot()`` method. This makes use of the `contextily <https://github.com/darribas/contextily>`__ package to retrieve web map tiles from several sources (OpenStreetMap, Stamen). """ # sphinx_gallery_thumbnail_number = 3 import geopandas ############################################################################### # Let's use the NYC borough boundary data that is available in geopandas # datasets. Plotting this gives the following result: df = geopandas.read_file(geopandas.datasets.get_path('nybb')) ax = df.plot(figsize=(10, 10), alpha=0.5, edgecolor='k') ############################################################################### # Convert the data to Web Mercator # ================================ # # Web map tiles are typically provided in # `Web Mercator <https://en.wikipedia.org/wiki/Web_Mercator>`__ # (`EPSG 3857 <https://epsg.io/3857>`__), so we need to make sure to convert # our data first to the same CRS to combine our polygons and background tiles # in the same map: df = df.to_crs(epsg=3857) ############################################################################### # Contextily helper function # ========================== # # We define a small helper function that uses # `contextily <https://github.com/darribas/contextily>`__ to add a map # as background to an existing plot: import contextily as ctx def add_basemap(ax, zoom, url='http://tile.stamen.com/terrain/tileZ/tileX/tileY.png'): xmin, xmax, ymin, ymax = ax.axis() basemap, extent = ctx.bounds2img(xmin, ymin, xmax, ymax, zoom=zoom, url=url) ax.imshow(basemap, extent=extent, interpolation='bilinear') # restore original x/y limits ax.axis((xmin, xmax, ymin, ymax)) ############################################################################### # Add background tiles to plot # ============================ # # Now we can use the above function to easily add a background map to our # plot. The `zoom` keyword is required and let's you specify the detail of the # map tiles (be careful to not specify a too high `zoom` level, as this can # result in a large download): ax = df.plot(figsize=(10, 10), alpha=0.5, edgecolor='k') add_basemap(ax, zoom=10) ############################################################################### # By default, contextily uses the Stamen Terrain style. We can specify a # different style using ``ctx.sources``: ax = df.plot(figsize=(10, 10), alpha=0.5, edgecolor='k') add_basemap(ax, zoom=11, url=ctx.sources.ST_TONER_LITE) ax.set_axis_off()
bsd-3-clause
clime/pimcore-custom
static/js/pimcore/object/classes/data/numeric.js
1710
/** * Pimcore * * 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://www.pimcore.org/license * * @copyright Copyright (c) 2009-2010 elements.at New Media Solutions GmbH (http://www.elements.at) * @license http://www.pimcore.org/license New BSD License */ pimcore.registerNS("pimcore.object.classes.data.numeric"); pimcore.object.classes.data.numeric = Class.create(pimcore.object.classes.data.data, { type: "numeric", /** * define where this datatype is allowed */ allowIn: { object: true, objectbrick: true, fieldcollection: true, localizedfield: true }, initialize: function (treeNode, initData) { this.type = "numeric"; this.initData(initData); this.treeNode = treeNode; }, getTypeName: function () { return t("numeric"); }, getGroup: function () { return "numeric"; }, getIconClass: function () { return "pimcore_icon_numeric"; }, getLayout: function ($super) { $super(); this.specificPanel.removeAll(); this.specificPanel.add([ { xtype: "spinnerfield", fieldLabel: t("width"), name: "width", value: this.datax.width }, { xtype: "spinnerfield", fieldLabel: t("default_value"), name: "defaultValue", value: this.datax.defaultValue } ]); return this.layout; } });
bsd-3-clause
rsamec/business-rules-engine
src/customValidators/ParamValidator.ts
3840
///<reference path='../../typings/underscore/underscore.d.ts'/> ///<reference path='../../typings/q/q.d.ts'/> ///<reference path='../../typings/business-rules-engine/business-rules-engine.d.ts'/> import Q = require("q"); import _ = require("underscore"); /** * @ngdoc object * @name ParamValidator * * @requires Q * * @description * Returns true if the value is present in the list. Otherwise return false. * The list is returned via Options property that can be parametrize by the name of the list with ParamId parameter. * * @property Options * Promise that returns list of param items (key-value pairs) * * <pre> * var optionsFce = function (paramId:string) { * var deferral = Q.defer(); * setTimeout(function () { * var result:Array<any> = []; * if (paramId == "jobs") { * result = [ * { "value": 1, "text": "manager" }, * { "value": 2, "text": "programmer" }, * { "value": 3, "text": "shop assistant" }, * { "value": 4, "text": "unemployed" }, * { "value": 5, "text": "machinery" }, * { "value": 6, "text": "agriculture" }, * { "value": 7, "text": "academic" }, * { "value": 8, "text": "goverment" } * ]; * } * if (paramId == "countries") { * result = [ * { "value": "CZE", "text": "Czech Republic" }, * { "value": "Germany", "text": "Germany" }, * { "value": "France", "text": "France" }, * ]; * } * * * deferral.resolve(result); * }, 1000); * return deferral.promise; * }; * </pre> * * @property ParamId - The name of the list to be returned. * * @example * * <pre> * //when * var validator = new paramValidator(); * validator.Options = optionsFce; * validator.ParamId = "jobs"; * * //excercise * var promiseResult = validator.isAcceptable("programmer"); * * it('value from list should return true', function (done) { * * promiseResult.then(function(result) { * * //verify * expect(result).to.equal(true); * * done(); * * }).done(null, done); * }); * * //excercise * var promiseResult2 = validator.isAcceptable("non existing item"); * * it('value out of list should return false', function (done) { * * promiseResult2.then(function(result) { * * //verify * expect(result).to.equal(false); * * done(); * * }).done(null, done); * }); * </pre> * */ class ParamValidator implements Validation.IAsyncPropertyValidator{ /** * It checks validity of identification number of CZE company (called ico) * @param s value to check * @returns return true for valid value, otherwise false */ isAcceptable(s:string):Q.Promise<boolean> { var deferred = Q.defer<boolean>(); this.Options(this.ParamId).then(function (result) { var hasSome = _.some(result, function (item) { return item.text === s; }); if (hasSome) deferred.resolve(true); deferred.resolve(false); }); return deferred.promise; } public ParamId:string; public Options:{(string): Q.Promise<Array<any>>}; isAsync = true; tagName = "param"; } export = ParamValidator;
bsd-3-clause
cloudqiu1110/tinype
external/glslang/MachineIndependent/ParseHelper.cpp
264048
// //Copyright (C) 2002-2005 3Dlabs Inc. Ltd. //Copyright (C) 2012-2013 LunarG, 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 3Dlabs Inc. Ltd. 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 HOLDERS 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 "ParseHelper.h" #include "Scan.h" #include "../OSDependent/osinclude.h" #include <stdarg.h> #include <algorithm> #include "preprocessor/PpContext.h" extern int yyparse(glslang::TParseContext*); namespace glslang { TParseContext::TParseContext(TSymbolTable& symt, TIntermediate& interm, bool pb, int v, EProfile p, int spv, int vulkan, EShLanguage L, TInfoSink& is, bool fc, EShMessages m) : intermediate(interm), symbolTable(symt), infoSink(is), language(L), version(v), profile(p), spv(spv), vulkan(vulkan), forwardCompatible(fc), contextPragma(true, false), loopNestingLevel(0), structNestingLevel(0), controlFlowNestingLevel(0), statementNestingLevel(0), postMainReturn(false), tokensBeforeEOF(false), limits(resources.limits), messages(m), currentScanner(nullptr), numErrors(0), parsingBuiltins(pb), afterEOF(false), atomicUintOffsets(nullptr), anyIndexLimits(false) { // ensure we always have a linkage node, even if empty, to simplify tree topology algorithms linkage = new TIntermAggregate; // set all precision defaults to EpqNone, which is correct for all desktop types // and for ES types that don't have defaults (thus getting an error on use) for (int type = 0; type < EbtNumTypes; ++type) defaultPrecision[type] = EpqNone; for (int type = 0; type < maxSamplerIndex; ++type) defaultSamplerPrecision[type] = EpqNone; // replace with real defaults for those that have them if (profile == EEsProfile) { TSampler sampler; sampler.set(EbtFloat, Esd2D); defaultSamplerPrecision[computeSamplerTypeIndex(sampler)] = EpqLow; sampler.set(EbtFloat, EsdCube); defaultSamplerPrecision[computeSamplerTypeIndex(sampler)] = EpqLow; sampler.set(EbtFloat, Esd2D); sampler.external = true; defaultSamplerPrecision[computeSamplerTypeIndex(sampler)] = EpqLow; switch (language) { case EShLangFragment: defaultPrecision[EbtInt] = EpqMedium; defaultPrecision[EbtUint] = EpqMedium; break; default: defaultPrecision[EbtInt] = EpqHigh; defaultPrecision[EbtUint] = EpqHigh; defaultPrecision[EbtFloat] = EpqHigh; break; } defaultPrecision[EbtSampler] = EpqLow; defaultPrecision[EbtAtomicUint] = EpqHigh; } globalUniformDefaults.clear(); globalUniformDefaults.layoutMatrix = ElmColumnMajor; globalUniformDefaults.layoutPacking = vulkan > 0 ? ElpStd140 : ElpShared; globalBufferDefaults.clear(); globalBufferDefaults.layoutMatrix = ElmColumnMajor; globalBufferDefaults.layoutPacking = vulkan > 0 ? ElpStd430 : ElpShared; globalInputDefaults.clear(); globalOutputDefaults.clear(); // "Shaders in the transform // feedback capturing mode have an initial global default of // layout(xfb_buffer = 0) out;" if (language == EShLangVertex || language == EShLangTessControl || language == EShLangTessEvaluation || language == EShLangGeometry) globalOutputDefaults.layoutXfbBuffer = 0; if (language == EShLangGeometry) globalOutputDefaults.layoutStream = 0; } TParseContext::~TParseContext() { delete [] atomicUintOffsets; } void TParseContext::setLimits(const TBuiltInResource& r) { resources = r; anyIndexLimits = ! limits.generalAttributeMatrixVectorIndexing || ! limits.generalConstantMatrixVectorIndexing || ! limits.generalSamplerIndexing || ! limits.generalUniformIndexing || ! limits.generalVariableIndexing || ! limits.generalVaryingIndexing; intermediate.setLimits(resources); // "Each binding point tracks its own current default offset for // inheritance of subsequent variables using the same binding. The initial state of compilation is that all // binding points have an offset of 0." atomicUintOffsets = new int[resources.maxAtomicCounterBindings]; for (int b = 0; b < resources.maxAtomicCounterBindings; ++b) atomicUintOffsets[b] = 0; } // // Parse an array of strings using yyparse, going through the // preprocessor to tokenize the shader strings, then through // the GLSL scanner. // // Returns true for successful acceptance of the shader, false if any errors. // bool TParseContext::parseShaderStrings(TPpContext& ppContext, TInputScanner& input, bool versionWillBeError) { currentScanner = &input; ppContext.setInput(input, versionWillBeError); yyparse(this); if (! parsingBuiltins) finalErrorCheck(); return numErrors == 0; } // This is called from bison when it has a parse (syntax) error void TParseContext::parserError(const char* s) { if (afterEOF) { if (tokensBeforeEOF == 1) error(getCurrentLoc(), "", "premature end of input", s, ""); } else error(getCurrentLoc(), "", "", s, ""); } void TParseContext::handlePragma(const TSourceLoc& loc, const TVector<TString>& tokens) { if (pragmaCallback) pragmaCallback(loc.line, tokens); if (tokens.size() == 0) return; if (tokens[0].compare("optimize") == 0) { if (tokens.size() != 4) { error(loc, "optimize pragma syntax is incorrect", "#pragma", ""); return; } if (tokens[1].compare("(") != 0) { error(loc, "\"(\" expected after 'optimize' keyword", "#pragma", ""); return; } if (tokens[2].compare("on") == 0) contextPragma.optimize = true; else if (tokens[2].compare("off") == 0) contextPragma.optimize = false; else { error(loc, "\"on\" or \"off\" expected after '(' for 'optimize' pragma", "#pragma", ""); return; } if (tokens[3].compare(")") != 0) { error(loc, "\")\" expected to end 'optimize' pragma", "#pragma", ""); return; } } else if (tokens[0].compare("debug") == 0) { if (tokens.size() != 4) { error(loc, "debug pragma syntax is incorrect", "#pragma", ""); return; } if (tokens[1].compare("(") != 0) { error(loc, "\"(\" expected after 'debug' keyword", "#pragma", ""); return; } if (tokens[2].compare("on") == 0) contextPragma.debug = true; else if (tokens[2].compare("off") == 0) contextPragma.debug = false; else { error(loc, "\"on\" or \"off\" expected after '(' for 'debug' pragma", "#pragma", ""); return; } if (tokens[3].compare(")") != 0) { error(loc, "\")\" expected to end 'debug' pragma", "#pragma", ""); return; } } } /////////////////////////////////////////////////////////////////////// // // Sub- vector and matrix fields // //////////////////////////////////////////////////////////////////////// // // Look at a '.' field selector string and change it into offsets // for a vector or scalar // // Returns true if there is no error. // bool TParseContext::parseVectorFields(const TSourceLoc& loc, const TString& compString, int vecSize, TVectorFields& fields) { fields.num = (int) compString.size(); if (fields.num > 4) { error(loc, "illegal vector field selection", compString.c_str(), ""); return false; } enum { exyzw, ergba, estpq, } fieldSet[4]; for (int i = 0; i < fields.num; ++i) { switch (compString[i]) { case 'x': fields.offsets[i] = 0; fieldSet[i] = exyzw; break; case 'r': fields.offsets[i] = 0; fieldSet[i] = ergba; break; case 's': fields.offsets[i] = 0; fieldSet[i] = estpq; break; case 'y': fields.offsets[i] = 1; fieldSet[i] = exyzw; break; case 'g': fields.offsets[i] = 1; fieldSet[i] = ergba; break; case 't': fields.offsets[i] = 1; fieldSet[i] = estpq; break; case 'z': fields.offsets[i] = 2; fieldSet[i] = exyzw; break; case 'b': fields.offsets[i] = 2; fieldSet[i] = ergba; break; case 'p': fields.offsets[i] = 2; fieldSet[i] = estpq; break; case 'w': fields.offsets[i] = 3; fieldSet[i] = exyzw; break; case 'a': fields.offsets[i] = 3; fieldSet[i] = ergba; break; case 'q': fields.offsets[i] = 3; fieldSet[i] = estpq; break; default: error(loc, "illegal vector field selection", compString.c_str(), ""); return false; } } for (int i = 0; i < fields.num; ++i) { if (fields.offsets[i] >= vecSize) { error(loc, "vector field selection out of range", compString.c_str(), ""); return false; } if (i > 0) { if (fieldSet[i] != fieldSet[i-1]) { error(loc, "illegal - vector component fields not from the same set", compString.c_str(), ""); return false; } } } return true; } /////////////////////////////////////////////////////////////////////// // // Errors // //////////////////////////////////////////////////////////////////////// // // Used to output syntax, parsing, and semantic errors. // void TParseContext::outputMessage(const TSourceLoc& loc, const char* szReason, const char* szToken, const char* szExtraInfoFormat, TPrefixType prefix, va_list args) { const int maxSize = MaxTokenLength + 200; char szExtraInfo[maxSize]; safe_vsprintf(szExtraInfo, maxSize, szExtraInfoFormat, args); infoSink.info.prefix(prefix); infoSink.info.location(loc); infoSink.info << "'" << szToken << "' : " << szReason << " " << szExtraInfo << "\n"; if (prefix == EPrefixError) { ++numErrors; } } void C_DECL TParseContext::error(const TSourceLoc& loc, const char* szReason, const char* szToken, const char* szExtraInfoFormat, ...) { if (messages & EShMsgOnlyPreprocessor) return; va_list args; va_start(args, szExtraInfoFormat); outputMessage(loc, szReason, szToken, szExtraInfoFormat, EPrefixError, args); va_end(args); } void C_DECL TParseContext::warn(const TSourceLoc& loc, const char* szReason, const char* szToken, const char* szExtraInfoFormat, ...) { if (suppressWarnings()) return; va_list args; va_start(args, szExtraInfoFormat); outputMessage(loc, szReason, szToken, szExtraInfoFormat, EPrefixWarning, args); va_end(args); } void C_DECL TParseContext::ppError(const TSourceLoc& loc, const char* szReason, const char* szToken, const char* szExtraInfoFormat, ...) { va_list args; va_start(args, szExtraInfoFormat); outputMessage(loc, szReason, szToken, szExtraInfoFormat, EPrefixError, args); va_end(args); } void C_DECL TParseContext::ppWarn(const TSourceLoc& loc, const char* szReason, const char* szToken, const char* szExtraInfoFormat, ...) { va_list args; va_start(args, szExtraInfoFormat); outputMessage(loc, szReason, szToken, szExtraInfoFormat, EPrefixWarning, args); va_end(args); } // // Handle seeing a variable identifier in the grammar. // TIntermTyped* TParseContext::handleVariable(const TSourceLoc& loc, TSymbol* symbol, const TString* string) { TIntermTyped* node = nullptr; // Error check for requiring specific extensions present. if (symbol && symbol->getNumExtensions()) requireExtensions(loc, symbol->getNumExtensions(), symbol->getExtensions(), symbol->getName().c_str()); if (symbol && symbol->isReadOnly()) { // All shared things containing an implicitly sized array must be copied up // on first use, so that all future references will share its array structure, // so that editing the implicit size will effect all nodes consuming it, // and so that editing the implicit size won't change the shared one. // // If this is a variable or a block, check it and all it contains, but if this // is a member of an anonymous block, check the whole block, as the whole block // will need to be copied up if it contains an implicitly-sized array. if (symbol->getType().containsImplicitlySizedArray() || (symbol->getAsAnonMember() && symbol->getAsAnonMember()->getAnonContainer().getType().containsImplicitlySizedArray())) makeEditable(symbol); } const TVariable* variable; const TAnonMember* anon = symbol ? symbol->getAsAnonMember() : nullptr; if (anon) { // It was a member of an anonymous container. // The "getNumExtensions()" mechanism above doesn't yet work for block members blockMemberExtensionCheck(loc, nullptr, *string); // Create a subtree for its dereference. variable = anon->getAnonContainer().getAsVariable(); TIntermTyped* container = intermediate.addSymbol(*variable, loc); TIntermTyped* constNode = intermediate.addConstantUnion(anon->getMemberNumber(), loc); node = intermediate.addIndex(EOpIndexDirectStruct, container, constNode, loc); node->setType(*(*variable->getType().getStruct())[anon->getMemberNumber()].type); if (node->getType().hiddenMember()) error(loc, "member of nameless block was not redeclared", string->c_str(), ""); } else { // Not a member of an anonymous container. // The symbol table search was done in the lexical phase. // See if it was a variable. variable = symbol ? symbol->getAsVariable() : nullptr; if (variable) { if ((variable->getType().getBasicType() == EbtBlock || variable->getType().getBasicType() == EbtStruct) && variable->getType().getStruct() == nullptr) { error(loc, "cannot be used (maybe an instance name is needed)", string->c_str(), ""); variable = nullptr; } } else { if (symbol) error(loc, "variable name expected", string->c_str(), ""); } // Recovery, if it wasn't found or was not a variable. if (! variable) variable = new TVariable(string, TType(EbtVoid)); if (variable->getType().getQualifier().isFrontEndConstant()) node = intermediate.addConstantUnion(variable->getConstArray(), variable->getType(), loc); else node = intermediate.addSymbol(*variable, loc); } if (variable->getType().getQualifier().isIo()) intermediate.addIoAccessed(*string); return node; } // // Handle seeing a base[index] dereference in the grammar. // TIntermTyped* TParseContext::handleBracketDereference(const TSourceLoc& loc, TIntermTyped* base, TIntermTyped* index) { TIntermTyped* result = nullptr; int indexValue = 0; if (index->getQualifier().storage == EvqConst) { indexValue = index->getAsConstantUnion()->getConstArray()[0].getIConst(); checkIndex(loc, base->getType(), indexValue); } variableCheck(base); if (! base->isArray() && ! base->isMatrix() && ! base->isVector()) { if (base->getAsSymbolNode()) error(loc, " left of '[' is not of type array, matrix, or vector ", base->getAsSymbolNode()->getName().c_str(), ""); else error(loc, " left of '[' is not of type array, matrix, or vector ", "expression", ""); } else if (base->getType().getQualifier().storage == EvqConst && index->getQualifier().storage == EvqConst) return intermediate.foldDereference(base, indexValue, loc); else { // at least one of base and index is variable... if (base->getAsSymbolNode() && isIoResizeArray(base->getType())) handleIoResizeArrayAccess(loc, base); if (index->getQualifier().storage == EvqConst) { if (base->getType().isImplicitlySizedArray()) updateImplicitArraySize(loc, base, indexValue); result = intermediate.addIndex(EOpIndexDirect, base, index, loc); } else { if (base->getType().isImplicitlySizedArray()) { if (base->getAsSymbolNode() && isIoResizeArray(base->getType())) error(loc, "", "[", "array must be sized by a redeclaration or layout qualifier before being indexed with a variable"); else error(loc, "", "[", "array must be redeclared with a size before being indexed with a variable"); } if (base->getBasicType() == EbtBlock) { if (base->getQualifier().storage == EvqBuffer) requireProfile(base->getLoc(), ~EEsProfile, "variable indexing buffer block array"); else if (base->getQualifier().storage == EvqUniform) profileRequires(base->getLoc(), EEsProfile, 0, Num_AEP_gpu_shader5, AEP_gpu_shader5, "variable indexing uniform block array"); else { // input/output blocks either don't exist or can be variable indexed } } else if (language == EShLangFragment && base->getQualifier().isPipeOutput()) requireProfile(base->getLoc(), ~EEsProfile, "variable indexing fragment shader ouput array"); else if (base->getBasicType() == EbtSampler && version >= 130) { const char* explanation = "variable indexing sampler array"; requireProfile(base->getLoc(), EEsProfile | ECoreProfile | ECompatibilityProfile, explanation); profileRequires(base->getLoc(), EEsProfile, 0, Num_AEP_gpu_shader5, AEP_gpu_shader5, explanation); profileRequires(base->getLoc(), ECoreProfile | ECompatibilityProfile, 400, nullptr, explanation); } result = intermediate.addIndex(EOpIndexIndirect, base, index, loc); } } if (result == nullptr) { // Insert dummy error-recovery result result = intermediate.addConstantUnion(0.0, EbtFloat, loc); } else { // Insert valid dereferenced result TType newType(base->getType(), 0); // dereferenced type if (base->getType().getQualifier().storage == EvqConst && index->getQualifier().storage == EvqConst) newType.getQualifier().storage = EvqConst; else newType.getQualifier().storage = EvqTemporary; result->setType(newType); if (anyIndexLimits) handleIndexLimits(loc, base, index); } return result; } void TParseContext::checkIndex(const TSourceLoc& loc, const TType& type, int& index) { if (index < 0) { error(loc, "", "[", "index out of range '%d'", index); index = 0; } else if (type.isArray()) { if (type.isExplicitlySizedArray() && index >= type.getOuterArraySize()) { error(loc, "", "[", "array index out of range '%d'", index); index = type.getOuterArraySize() - 1; } } else if (type.isVector()) { if (index >= type.getVectorSize()) { error(loc, "", "[", "vector index out of range '%d'", index); index = type.getVectorSize() - 1; } } else if (type.isMatrix()) { if (index >= type.getMatrixCols()) { error(loc, "", "[", "matrix index out of range '%d'", index); index = type.getMatrixCols() - 1; } } } // for ES 2.0 (version 100) limitations for almost all index operations except vertex-shader uniforms void TParseContext::handleIndexLimits(const TSourceLoc& /*loc*/, TIntermTyped* base, TIntermTyped* index) { if ((! limits.generalSamplerIndexing && base->getBasicType() == EbtSampler) || (! limits.generalUniformIndexing && base->getQualifier().isUniformOrBuffer() && language != EShLangVertex) || (! limits.generalAttributeMatrixVectorIndexing && base->getQualifier().isPipeInput() && language == EShLangVertex && (base->getType().isMatrix() || base->getType().isVector())) || (! limits.generalConstantMatrixVectorIndexing && base->getAsConstantUnion()) || (! limits.generalVariableIndexing && ! base->getType().getQualifier().isUniformOrBuffer() && ! base->getType().getQualifier().isPipeInput() && ! base->getType().getQualifier().isPipeOutput() && base->getType().getQualifier().storage != EvqConst) || (! limits.generalVaryingIndexing && (base->getType().getQualifier().isPipeInput() || base->getType().getQualifier().isPipeOutput()))) { // it's too early to know what the inductive variables are, save it for post processing needsIndexLimitationChecking.push_back(index); } } // Make a shared symbol have a non-shared version that can be edited by the current // compile, such that editing its type will not change the shared version and will // effect all nodes sharing it. void TParseContext::makeEditable(TSymbol*& symbol) { // copyUp() does a deep copy of the type. symbol = symbolTable.copyUp(symbol); // Also, see if it's tied to IO resizing if (isIoResizeArray(symbol->getType())) ioArraySymbolResizeList.push_back(symbol); // Also, save it in the AST for linker use. intermediate.addSymbolLinkageNode(linkage, *symbol); } // Return true if this is a geometry shader input array or tessellation control output array. bool TParseContext::isIoResizeArray(const TType& type) const { return type.isArray() && ((language == EShLangGeometry && type.getQualifier().storage == EvqVaryingIn) || (language == EShLangTessControl && type.getQualifier().storage == EvqVaryingOut && ! type.getQualifier().patch)); } // If an array is not isIoResizeArray() but is an io array, make sure it has the right size void TParseContext::fixIoArraySize(const TSourceLoc& loc, TType& type) { if (! type.isArray() || type.getQualifier().patch || symbolTable.atBuiltInLevel()) return; assert(! isIoResizeArray(type)); if (type.getQualifier().storage != EvqVaryingIn || type.getQualifier().patch) return; if (language == EShLangTessControl || language == EShLangTessEvaluation) { if (type.getOuterArraySize() != resources.maxPatchVertices) { if (type.isExplicitlySizedArray()) error(loc, "tessellation input array size must be gl_MaxPatchVertices or implicitly sized", "[]", ""); type.changeOuterArraySize(resources.maxPatchVertices); } } } // Issue any errors if the non-array object is missing arrayness WRT // shader I/O that has array requirements. // All arrayness checking is handled in array paths, this is for void TParseContext::ioArrayCheck(const TSourceLoc& loc, const TType& type, const TString& identifier) { if (! type.isArray() && ! symbolTable.atBuiltInLevel()) { if (type.getQualifier().isArrayedIo(language)) error(loc, "type must be an array:", type.getStorageQualifierString(), identifier.c_str()); } } // Handle a dereference of a geometry shader input array or tessellation control output array. // See ioArraySymbolResizeList comment in ParseHelper.h. // void TParseContext::handleIoResizeArrayAccess(const TSourceLoc& /*loc*/, TIntermTyped* base) { TIntermSymbol* symbolNode = base->getAsSymbolNode(); assert(symbolNode); if (! symbolNode) return; // fix array size, if it can be fixed and needs to be fixed (will allow variable indexing) if (symbolNode->getType().isImplicitlySizedArray()) { int newSize = getIoArrayImplicitSize(); if (newSize > 0) symbolNode->getWritableType().changeOuterArraySize(newSize); } } // If there has been an input primitive declaration (geometry shader) or an output // number of vertices declaration(tessellation shader), make sure all input array types // match it in size. Types come either from nodes in the AST or symbols in the // symbol table. // // Types without an array size will be given one. // Types already having a size that is wrong will get an error. // void TParseContext::checkIoArraysConsistency(const TSourceLoc& loc, bool tailOnly) { int requiredSize = getIoArrayImplicitSize(); if (requiredSize == 0) return; const char* feature; if (language == EShLangGeometry) feature = TQualifier::getGeometryString(intermediate.getInputPrimitive()); else if (language == EShLangTessControl) feature = "vertices"; else feature = "unknown"; if (tailOnly) { checkIoArrayConsistency(loc, requiredSize, feature, ioArraySymbolResizeList.back()->getWritableType(), ioArraySymbolResizeList.back()->getName()); return; } for (size_t i = 0; i < ioArraySymbolResizeList.size(); ++i) checkIoArrayConsistency(loc, requiredSize, feature, ioArraySymbolResizeList[i]->getWritableType(), ioArraySymbolResizeList[i]->getName()); } int TParseContext::getIoArrayImplicitSize() const { if (language == EShLangGeometry) return TQualifier::mapGeometryToSize(intermediate.getInputPrimitive()); else if (language == EShLangTessControl) return intermediate.getVertices() != TQualifier::layoutNotSet ? intermediate.getVertices() : 0; else return 0; } void TParseContext::checkIoArrayConsistency(const TSourceLoc& loc, int requiredSize, const char* feature, TType& type, const TString& name) { if (type.isImplicitlySizedArray()) type.changeOuterArraySize(requiredSize); else if (type.getOuterArraySize() != requiredSize) { if (language == EShLangGeometry) error(loc, "inconsistent input primitive for array size of", feature, name.c_str()); else if (language == EShLangTessControl) error(loc, "inconsistent output number of vertices for array size of", feature, name.c_str()); else assert(0); } } // Handle seeing a binary node with a math operation. TIntermTyped* TParseContext::handleBinaryMath(const TSourceLoc& loc, const char* str, TOperator op, TIntermTyped* left, TIntermTyped* right) { rValueErrorCheck(loc, str, left->getAsTyped()); rValueErrorCheck(loc, str, right->getAsTyped()); TIntermTyped* result = intermediate.addBinaryMath(op, left, right, loc); if (! result) binaryOpError(loc, str, left->getCompleteString(), right->getCompleteString()); return result; } // Handle seeing a unary node with a math operation. TIntermTyped* TParseContext::handleUnaryMath(const TSourceLoc& loc, const char* str, TOperator op, TIntermTyped* childNode) { rValueErrorCheck(loc, str, childNode); TIntermTyped* result = intermediate.addUnaryMath(op, childNode, loc); if (result) return result; else unaryOpError(loc, str, childNode->getCompleteString()); return childNode; } // // Handle seeing a base.field dereference in the grammar. // TIntermTyped* TParseContext::handleDotDereference(const TSourceLoc& loc, TIntermTyped* base, const TString& field) { variableCheck(base); // // .length() can't be resolved until we later see the function-calling syntax. // Save away the name in the AST for now. Processing is compeleted in // handleLengthMethod(). // if (field == "length") { if (base->isArray()) { profileRequires(loc, ENoProfile, 120, E_GL_3DL_array_objects, ".length"); profileRequires(loc, EEsProfile, 300, nullptr, ".length"); } else if (base->isVector() || base->isMatrix()) { const char* feature = ".length() on vectors and matrices"; requireProfile(loc, ~EEsProfile, feature); profileRequires(loc, ~EEsProfile, 420, E_GL_ARB_shading_language_420pack, feature); } else { error(loc, "does not operate on this type:", field.c_str(), base->getType().getCompleteString().c_str()); return base; } return intermediate.addMethod(base, TType(EbtInt), &field, loc); } // It's not .length() if we get to here. if (base->isArray()) { error(loc, "cannot apply to an array:", ".", field.c_str()); return base; } // It's neither an array nor .length() if we get here, // leaving swizzles and struct/block dereferences. TIntermTyped* result = base; if (base->isVector() || base->isScalar()) { if (base->isScalar()) { const char* dotFeature = "scalar swizzle"; requireProfile(loc, ~EEsProfile, dotFeature); profileRequires(loc, ~EEsProfile, 420, E_GL_ARB_shading_language_420pack, dotFeature); } TVectorFields fields; if (! parseVectorFields(loc, field, base->getVectorSize(), fields)) { fields.num = 1; fields.offsets[0] = 0; } if (base->isScalar()) { if (fields.num == 1) return result; else { TType type(base->getBasicType(), EvqTemporary, fields.num); return addConstructor(loc, base, type, mapTypeToConstructorOp(type)); } } if (base->getType().getQualifier().storage == EvqConst) result = intermediate.foldSwizzle(base, fields, loc); else { if (fields.num == 1) { TIntermTyped* index = intermediate.addConstantUnion(fields.offsets[0], loc); result = intermediate.addIndex(EOpIndexDirect, base, index, loc); result->setType(TType(base->getBasicType(), EvqTemporary, base->getType().getQualifier().precision)); } else { TString vectorString = field; TIntermTyped* index = intermediate.addSwizzle(fields, loc); result = intermediate.addIndex(EOpVectorSwizzle, base, index, loc); result->setType(TType(base->getBasicType(), EvqTemporary, base->getType().getQualifier().precision, (int) vectorString.size())); } } } else if (base->getBasicType() == EbtStruct || base->getBasicType() == EbtBlock) { const TTypeList* fields = base->getType().getStruct(); bool fieldFound = false; int member; for (member = 0; member < (int)fields->size(); ++member) { if ((*fields)[member].type->getFieldName() == field) { fieldFound = true; break; } } if (fieldFound) { if (base->getType().getQualifier().storage == EvqConst) result = intermediate.foldDereference(base, member, loc); else { blockMemberExtensionCheck(loc, base, field); TIntermTyped* index = intermediate.addConstantUnion(member, loc); result = intermediate.addIndex(EOpIndexDirectStruct, base, index, loc); result->setType(*(*fields)[member].type); } } else error(loc, "no such field in structure", field.c_str(), ""); } else error(loc, "does not apply to this type:", field.c_str(), base->getType().getCompleteString().c_str()); return result; } void TParseContext::blockMemberExtensionCheck(const TSourceLoc& loc, const TIntermTyped* /*base*/, const TString& field) { if (profile == EEsProfile && field == "gl_PointSize") { if (language == EShLangGeometry) requireExtensions(loc, Num_AEP_geometry_point_size, AEP_geometry_point_size, "gl_PointSize"); else if (language == EShLangTessControl || language == EShLangTessEvaluation) requireExtensions(loc, Num_AEP_tessellation_point_size, AEP_tessellation_point_size, "gl_PointSize"); } } // // Handle seeing a function declarator in the grammar. This is the precursor // to recognizing a function prototype or function definition. // TFunction* TParseContext::handleFunctionDeclarator(const TSourceLoc& loc, TFunction& function, bool prototype) { // ES can't declare prototypes inside functions if (! symbolTable.atGlobalLevel()) requireProfile(loc, ~EEsProfile, "local function declaration"); // // Multiple declarations of the same function name are allowed. // // If this is a definition, the definition production code will check for redefinitions // (we don't know at this point if it's a definition or not). // // Redeclarations (full signature match) are allowed. But, return types and parameter qualifiers must also match. // - except ES 100, which only allows a single prototype // // ES 100 does not allow redefining, but does allow overloading of built-in functions. // ES 300 does not allow redefining or overloading of built-in functions. // bool builtIn; TSymbol* symbol = symbolTable.find(function.getMangledName(), &builtIn); if (symbol && symbol->getAsFunction() && builtIn) requireProfile(loc, ~EEsProfile, "redefinition of built-in function"); const TFunction* prevDec = symbol ? symbol->getAsFunction() : 0; if (prevDec) { if (prevDec->isPrototyped() && prototype) profileRequires(loc, EEsProfile, 300, nullptr, "multiple prototypes for same function"); if (prevDec->getType() != function.getType()) error(loc, "overloaded functions must have the same return type", function.getType().getBasicTypeString().c_str(), ""); for (int i = 0; i < prevDec->getParamCount(); ++i) { if ((*prevDec)[i].type->getQualifier().storage != function[i].type->getQualifier().storage) error(loc, "overloaded functions must have the same parameter storage qualifiers for argument", function[i].type->getStorageQualifierString(), "%d", i+1); if ((*prevDec)[i].type->getQualifier().precision != function[i].type->getQualifier().precision) error(loc, "overloaded functions must have the same parameter precision qualifiers for argument", function[i].type->getPrecisionQualifierString(), "%d", i+1); } } arrayObjectCheck(loc, function.getType(), "array in function return type"); if (prototype) { // All built-in functions are defined, even though they don't have a body. // Count their prototype as a definition instead. if (symbolTable.atBuiltInLevel()) function.setDefined(); else { if (prevDec && ! builtIn) symbol->getAsFunction()->setPrototyped(); // need a writable one, but like having prevDec as a const function.setPrototyped(); } } // This insert won't actually insert it if it's a duplicate signature, but it will still check for // other forms of name collisions. if (! symbolTable.insert(function)) error(loc, "function name is redeclaration of existing name", function.getName().c_str(), ""); // // If this is a redeclaration, it could also be a definition, // in which case, we need to use the parameter names from this one, and not the one that's // being redeclared. So, pass back this declaration, not the one in the symbol table. // return &function; } // // Handle seeing the function prototype in front of a function definition in the grammar. // The body is handled after this function returns. // TIntermAggregate* TParseContext::handleFunctionDefinition(const TSourceLoc& loc, TFunction& function) { currentCaller = function.getMangledName(); TSymbol* symbol = symbolTable.find(function.getMangledName()); TFunction* prevDec = symbol ? symbol->getAsFunction() : nullptr; if (! prevDec) error(loc, "can't find function", function.getName().c_str(), ""); // Note: 'prevDec' could be 'function' if this is the first time we've seen function // as it would have just been put in the symbol table. Otherwise, we're looking up // an earlier occurance. if (prevDec && prevDec->isDefined()) { // Then this function already has a body. error(loc, "function already has a body", function.getName().c_str(), ""); } if (prevDec && ! prevDec->isDefined()) { prevDec->setDefined(); // Remember the return type for later checking for RETURN statements. currentFunctionType = &(prevDec->getType()); } else currentFunctionType = new TType(EbtVoid); functionReturnsValue = false; // // Raise error message if main function takes any parameters or returns anything other than void // if (function.getName() == "main") { if (function.getParamCount() > 0) error(loc, "function cannot take any parameter(s)", function.getName().c_str(), ""); if (function.getType().getBasicType() != EbtVoid) error(loc, "", function.getType().getBasicTypeString().c_str(), "main function cannot return a value"); intermediate.addMainCount(); inMain = true; } else inMain = false; // // New symbol table scope for body of function plus its arguments // symbolTable.push(); // // Insert parameters into the symbol table. // If the parameter has no name, it's not an error, just don't insert it // (could be used for unused args). // // Also, accumulate the list of parameters into the HIL, so lower level code // knows where to find parameters. // TIntermAggregate* paramNodes = new TIntermAggregate; for (int i = 0; i < function.getParamCount(); i++) { TParameter& param = function[i]; if (param.name != nullptr) { TVariable *variable = new TVariable(param.name, *param.type); // Insert the parameters with name in the symbol table. if (! symbolTable.insert(*variable)) error(loc, "redefinition", variable->getName().c_str(), ""); else { // Transfer ownership of name pointer to symbol table. param.name = nullptr; // Add the parameter to the HIL paramNodes = intermediate.growAggregate(paramNodes, intermediate.addSymbol(*variable, loc), loc); } } else paramNodes = intermediate.growAggregate(paramNodes, intermediate.addSymbol(0, "", *param.type, loc), loc); } intermediate.setAggregateOperator(paramNodes, EOpParameters, TType(EbtVoid), loc); loopNestingLevel = 0; statementNestingLevel = 0; controlFlowNestingLevel = 0; postMainReturn = false; return paramNodes; } // // Handle seeing function call syntax in the grammar, which could be any of // - .length() method // - constructor // - a call to a built-in function mapped to an operator // - a call to a built-in function that will remain a function call (e.g., texturing) // - user function // - subroutine call (not implemented yet) // TIntermTyped* TParseContext::handleFunctionCall(const TSourceLoc& loc, TFunction* function, TIntermNode* arguments) { TIntermTyped* result = nullptr; TOperator op = function->getBuiltInOp(); if (op == EOpArrayLength) result = handleLengthMethod(loc, function, arguments); else if (op != EOpNull) { // // Then this should be a constructor. // Don't go through the symbol table for constructors. // Their parameters will be verified algorithmically. // TType type(EbtVoid); // use this to get the type back if (! constructorError(loc, arguments, *function, op, type)) { // // It's a constructor, of type 'type'. // result = addConstructor(loc, arguments, type, op); if (result == nullptr) error(loc, "cannot construct with these arguments", type.getCompleteString().c_str(), ""); } } else { // // Find it in the symbol table. // const TFunction* fnCandidate; bool builtIn; fnCandidate = findFunction(loc, *function, builtIn); if (fnCandidate) { // This is a declared function that might map to // - a built-in operator, // - a built-in function not mapped to an operator, or // - a user function. // Error check for a function requiring specific extensions present. if (builtIn && fnCandidate->getNumExtensions()) requireExtensions(loc, fnCandidate->getNumExtensions(), fnCandidate->getExtensions(), fnCandidate->getName().c_str()); if (arguments) { // Make sure qualifications work for these arguments. TIntermAggregate* aggregate = arguments->getAsAggregate(); for (int i = 0; i < fnCandidate->getParamCount(); ++i) { // At this early point there is a slight ambiguity between whether an aggregate 'arguments' // is the single argument itself or its children are the arguments. Only one argument // means take 'arguments' itself as the one argument. TIntermNode* arg = fnCandidate->getParamCount() == 1 ? arguments : (aggregate ? aggregate->getSequence()[i] : arguments); TQualifier& formalQualifier = (*fnCandidate)[i].type->getQualifier(); if (formalQualifier.storage == EvqOut || formalQualifier.storage == EvqInOut) { if (lValueErrorCheck(arguments->getLoc(), "assign", arg->getAsTyped())) error(arguments->getLoc(), "Non-L-value cannot be passed for 'out' or 'inout' parameters.", "out", ""); } TQualifier& argQualifier = arg->getAsTyped()->getQualifier(); if (argQualifier.isMemory()) { const char* message = "argument cannot drop memory qualifier when passed to formal parameter"; if (argQualifier.volatil && ! formalQualifier.volatil) error(arguments->getLoc(), message, "volatile", ""); if (argQualifier.coherent && ! formalQualifier.coherent) error(arguments->getLoc(), message, "coherent", ""); if (argQualifier.readonly && ! formalQualifier.readonly) error(arguments->getLoc(), message, "readonly", ""); if (argQualifier.writeonly && ! formalQualifier.writeonly) error(arguments->getLoc(), message, "writeonly", ""); } // TODO 4.5 functionality: A shader will fail to compile // if the value passed to the memargument of an atomic memory function does not correspond to a buffer or // shared variable. It is acceptable to pass an element of an array or a single component of a vector to the // memargument of an atomic memory function, as long as the underlying array or vector is a buffer or // shared variable. } // Convert 'in' arguments addInputArgumentConversions(*fnCandidate, arguments); // arguments may be modified if it's just a single argument node } op = fnCandidate->getBuiltInOp(); if (builtIn && op != EOpNull) { // A function call mapped to a built-in operation. checkLocation(loc, op); result = intermediate.addBuiltInFunctionCall(loc, op, fnCandidate->getParamCount() == 1, arguments, fnCandidate->getType()); if (result == nullptr) { error(arguments->getLoc(), " wrong operand type", "Internal Error", "built in unary operator function. Type: %s", static_cast<TIntermTyped*>(arguments)->getCompleteString().c_str()); } else if (result->getAsOperator()) { builtInOpCheck(loc, *fnCandidate, *result->getAsOperator()); } } else { // This is a function call not mapped to built-in operator. // It could still be a built-in function, but only if PureOperatorBuiltins == false. result = intermediate.setAggregateOperator(arguments, EOpFunctionCall, fnCandidate->getType(), loc); TIntermAggregate* call = result->getAsAggregate(); call->setName(fnCandidate->getMangledName()); // this is how we know whether the given function is a built-in function or a user-defined function // if builtIn == false, it's a userDefined -> could be an overloaded built-in function also // if builtIn == true, it's definitely a built-in function with EOpNull if (! builtIn) { call->setUserDefined(); if (symbolTable.atGlobalLevel()) error(loc, "can't call user function from global scope", fnCandidate->getName().c_str(), ""); else intermediate.addToCallGraph(infoSink, currentCaller, fnCandidate->getMangledName()); } if (builtIn) nonOpBuiltInCheck(loc, *fnCandidate, *call); } // Convert 'out' arguments. If it was a constant folded built-in, it won't be an aggregate anymore. // Built-ins with a single argument aren't called with an aggregate, but they also don't have an output. // Also, build the qualifier list for user function calls, which are always called with an aggregate. if (result->getAsAggregate()) { TQualifierList& qualifierList = result->getAsAggregate()->getQualifierList(); for (int i = 0; i < fnCandidate->getParamCount(); ++i) { TStorageQualifier qual = (*fnCandidate)[i].type->getQualifier().storage; qualifierList.push_back(qual); } result = addOutputArgumentConversions(*fnCandidate, *result->getAsAggregate()); } } } // generic error recovery // TODO: simplification: localize all the error recoveries that look like this, and taking type into account to reduce cascades if (result == nullptr) result = intermediate.addConstantUnion(0.0, EbtFloat, loc); return result; } // See if the operation is being done in an illegal location. void TParseContext::checkLocation(const TSourceLoc& loc, TOperator op) { switch (op) { case EOpBarrier: if (language == EShLangTessControl) { if (controlFlowNestingLevel > 0) error(loc, "tessellation control barrier() cannot be placed within flow control", "", ""); if (! inMain) error(loc, "tessellation control barrier() must be in main()", "", ""); else if (postMainReturn) error(loc, "tessellation control barrier() cannot be placed after a return from main()", "", ""); } break; default: break; } } // Finish processing object.length(). This started earlier in handleDotDereference(), where // the ".length" part was recognized and semantically checked, and finished here where the // function syntax "()" is recognized. // // Return resulting tree node. TIntermTyped* TParseContext::handleLengthMethod(const TSourceLoc& loc, TFunction* function, TIntermNode* intermNode) { int length = 0; if (function->getParamCount() > 0) error(loc, "method does not accept any arguments", function->getName().c_str(), ""); else { const TType& type = intermNode->getAsTyped()->getType(); if (type.isArray()) { if (type.isRuntimeSizedArray()) { // Create a unary op and let the back end handle it return intermediate.addBuiltInFunctionCall(loc, EOpArrayLength, true, intermNode, TType(EbtInt)); } else if (type.isImplicitlySizedArray()) { if (intermNode->getAsSymbolNode() && isIoResizeArray(type)) { // We could be between a layout declaration that gives a built-in io array implicit size and // a user redeclaration of that array, meaning we have to substitute its implicit size here // without actually redeclaring the array. (It is an error to use a member before the // redeclaration, but not an error to use the array name itself.) const TString& name = intermNode->getAsSymbolNode()->getName(); if (name == "gl_in" || name == "gl_out") length = getIoArrayImplicitSize(); } if (length == 0) { if (intermNode->getAsSymbolNode() && isIoResizeArray(type)) error(loc, "", function->getName().c_str(), "array must first be sized by a redeclaration or layout qualifier"); else error(loc, "", function->getName().c_str(), "array must be declared with a size before using this method"); } } else length = type.getOuterArraySize(); } else if (type.isMatrix()) length = type.getMatrixCols(); else if (type.isVector()) length = type.getVectorSize(); else { // we should not get here, because earlier semantic checking should have prevented this path error(loc, ".length()", "unexpected use of .length()", ""); } } if (length == 0) length = 1; return intermediate.addConstantUnion(length, loc); } // // Add any needed implicit conversions for function-call arguments to input parameters. // void TParseContext::addInputArgumentConversions(const TFunction& function, TIntermNode*& arguments) const { TIntermAggregate* aggregate = arguments->getAsAggregate(); // Process each argument's conversion for (int i = 0; i < function.getParamCount(); ++i) { // At this early point there is a slight ambiguity between whether an aggregate 'arguments' // is the single argument itself or its children are the arguments. Only one argument // means take 'arguments' itself as the one argument. TIntermTyped* arg = function.getParamCount() == 1 ? arguments->getAsTyped() : (aggregate ? aggregate->getSequence()[i]->getAsTyped() : arguments->getAsTyped()); if (*function[i].type != arg->getType()) { if (function[i].type->getQualifier().isParamInput()) { // In-qualified arguments just need an extra node added above the argument to // convert to the correct type. arg = intermediate.addConversion(EOpFunctionCall, *function[i].type, arg); if (arg) { if (function.getParamCount() == 1) arguments = arg; else { if (aggregate) aggregate->getSequence()[i] = arg; else arguments = arg; } } } } } } // // Add any needed implicit output conversions for function-call arguments. This // can require a new tree topology, complicated further by whether the function // has a return value. // // Returns a node of a subtree that evaluates to the return value of the function. // TIntermTyped* TParseContext::addOutputArgumentConversions(const TFunction& function, TIntermAggregate& intermNode) const { TIntermSequence& arguments = intermNode.getSequence(); // Will there be any output conversions? bool outputConversions = false; for (int i = 0; i < function.getParamCount(); ++i) { if (*function[i].type != arguments[i]->getAsTyped()->getType() && function[i].type->getQualifier().storage == EvqOut) { outputConversions = true; break; } } if (! outputConversions) return &intermNode; // Setup for the new tree, if needed: // // Output conversions need a different tree topology. // Out-qualified arguments need a temporary of the correct type, with the call // followed by an assignment of the temporary to the original argument: // void: function(arg, ...) -> ( function(tempArg, ...), arg = tempArg, ...) // ret = function(arg, ...) -> ret = (tempRet = function(tempArg, ...), arg = tempArg, ..., tempRet) // Where the "tempArg" type needs no conversion as an argument, but will convert on assignment. TIntermTyped* conversionTree = nullptr; TVariable* tempRet = nullptr; if (intermNode.getBasicType() != EbtVoid) { // do the "tempRet = function(...), " bit from above tempRet = makeInternalVariable("tempReturn", intermNode.getType()); TIntermSymbol* tempRetNode = intermediate.addSymbol(*tempRet, intermNode.getLoc()); conversionTree = intermediate.addAssign(EOpAssign, tempRetNode, &intermNode, intermNode.getLoc()); } else conversionTree = &intermNode; conversionTree = intermediate.makeAggregate(conversionTree); // Process each argument's conversion for (int i = 0; i < function.getParamCount(); ++i) { if (*function[i].type != arguments[i]->getAsTyped()->getType()) { if (function[i].type->getQualifier().isParamOutput()) { // Out-qualified arguments need to use the topology set up above. // do the " ...(tempArg, ...), arg = tempArg" bit from above TVariable* tempArg = makeInternalVariable("tempArg", *function[i].type); tempArg->getWritableType().getQualifier().makeTemporary(); TIntermSymbol* tempArgNode = intermediate.addSymbol(*tempArg, intermNode.getLoc()); TIntermTyped* tempAssign = intermediate.addAssign(EOpAssign, arguments[i]->getAsTyped(), tempArgNode, arguments[i]->getLoc()); conversionTree = intermediate.growAggregate(conversionTree, tempAssign, arguments[i]->getLoc()); // replace the argument with another node for the same tempArg variable arguments[i] = intermediate.addSymbol(*tempArg, intermNode.getLoc()); } } } // Finalize the tree topology (see bigger comment above). if (tempRet) { // do the "..., tempRet" bit from above TIntermSymbol* tempRetNode = intermediate.addSymbol(*tempRet, intermNode.getLoc()); conversionTree = intermediate.growAggregate(conversionTree, tempRetNode, intermNode.getLoc()); } conversionTree = intermediate.setAggregateOperator(conversionTree, EOpComma, intermNode.getType(), intermNode.getLoc()); return conversionTree; } // // Do additional checking of built-in function calls that is not caught // by normal semantic checks on argument type, extension tagging, etc. // // Assumes there has been a semantically correct match to a built-in function prototype. // void TParseContext::builtInOpCheck(const TSourceLoc& loc, const TFunction& fnCandidate, TIntermOperator& callNode) { // Set up convenience accessors to the argument(s). There is almost always // multiple arguments for the cases below, but when there might be one, // check the unaryArg first. const TIntermSequence* argp = nullptr; // confusing to use [] syntax on a pointer, so this is to help get a reference const TIntermTyped* unaryArg = nullptr; const TIntermTyped* arg0 = nullptr; if (callNode.getAsAggregate()) { argp = &callNode.getAsAggregate()->getSequence(); if (argp->size() > 0) arg0 = (*argp)[0]->getAsTyped(); } else { assert(callNode.getAsUnaryNode()); unaryArg = callNode.getAsUnaryNode()->getOperand(); arg0 = unaryArg; } const TIntermSequence& aggArgs = *argp; // only valid when unaryArg is nullptr // built-in texturing functions get their return value precision from the precision of the sampler if (fnCandidate.getType().getQualifier().precision == EpqNone && fnCandidate.getParamCount() > 0 && fnCandidate[0].type->getBasicType() == EbtSampler) callNode.getQualifier().precision = arg0->getQualifier().precision; switch (callNode.getOp()) { case EOpTextureGather: case EOpTextureGatherOffset: case EOpTextureGatherOffsets: { // Figure out which variants are allowed by what extensions, // and what arguments must be constant for which situations. TString featureString = fnCandidate.getName() + "(...)"; const char* feature = featureString.c_str(); profileRequires(loc, EEsProfile, 310, nullptr, feature); int compArg = -1; // track which argument, if any, is the constant component argument switch (callNode.getOp()) { case EOpTextureGather: // More than two arguments needs gpu_shader5, and rectangular or shadow needs gpu_shader5, // otherwise, need GL_ARB_texture_gather. if (fnCandidate.getParamCount() > 2 || fnCandidate[0].type->getSampler().dim == EsdRect || fnCandidate[0].type->getSampler().shadow) { profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_gpu_shader5, feature); if (! fnCandidate[0].type->getSampler().shadow) compArg = 2; } else profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_texture_gather, feature); break; case EOpTextureGatherOffset: // GL_ARB_texture_gather is good enough for 2D non-shadow textures with no component argument if (fnCandidate[0].type->getSampler().dim == Esd2D && ! fnCandidate[0].type->getSampler().shadow && fnCandidate.getParamCount() == 3) profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_texture_gather, feature); else profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_gpu_shader5, feature); if (! aggArgs[fnCandidate[0].type->getSampler().shadow ? 3 : 2]->getAsConstantUnion()) profileRequires(loc, EEsProfile, 0, Num_AEP_gpu_shader5, AEP_gpu_shader5, "non-constant offset argument"); if (! fnCandidate[0].type->getSampler().shadow) compArg = 3; break; case EOpTextureGatherOffsets: profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_gpu_shader5, feature); if (! fnCandidate[0].type->getSampler().shadow) compArg = 3; // check for constant offsets if (! aggArgs[fnCandidate[0].type->getSampler().shadow ? 3 : 2]->getAsConstantUnion()) error(loc, "must be a compile-time constant:", feature, "offsets argument"); break; default: break; } if (compArg > 0 && compArg < fnCandidate.getParamCount()) { if (aggArgs[compArg]->getAsConstantUnion()) { int value = aggArgs[compArg]->getAsConstantUnion()->getConstArray()[0].getIConst(); if (value < 0 || value > 3) error(loc, "must be 0, 1, 2, or 3:", feature, "component argument"); } else error(loc, "must be a compile-time constant:", feature, "component argument"); } break; } case EOpTextureOffset: case EOpTextureFetchOffset: case EOpTextureProjOffset: case EOpTextureLodOffset: case EOpTextureProjLodOffset: case EOpTextureGradOffset: case EOpTextureProjGradOffset: { // Handle texture-offset limits checking // Pick which argument has to hold constant offsets int arg = -1; switch (callNode.getOp()) { case EOpTextureOffset: arg = 2; break; case EOpTextureFetchOffset: arg = (arg0->getType().getSampler().dim != EsdRect) ? 3 : 2; break; case EOpTextureProjOffset: arg = 2; break; case EOpTextureLodOffset: arg = 3; break; case EOpTextureProjLodOffset: arg = 3; break; case EOpTextureGradOffset: arg = 4; break; case EOpTextureProjGradOffset: arg = 4; break; default: assert(0); break; } if (arg > 0) { if (! aggArgs[arg]->getAsConstantUnion()) error(loc, "argument must be compile-time constant", "texel offset", ""); else { const TType& type = aggArgs[arg]->getAsTyped()->getType(); for (int c = 0; c < type.getVectorSize(); ++c) { int offset = aggArgs[arg]->getAsConstantUnion()->getConstArray()[c].getIConst(); if (offset > resources.maxProgramTexelOffset || offset < resources.minProgramTexelOffset) error(loc, "value is out of range:", "texel offset", "[gl_MinProgramTexelOffset, gl_MaxProgramTexelOffset]"); } } } break; } case EOpTextureQuerySamples: case EOpImageQuerySamples: // GL_ARB_shader_texture_image_samples profileRequires(loc, ~EEsProfile, 450, E_GL_ARB_shader_texture_image_samples, "textureSamples and imageSamples"); break; case EOpImageAtomicAdd: case EOpImageAtomicMin: case EOpImageAtomicMax: case EOpImageAtomicAnd: case EOpImageAtomicOr: case EOpImageAtomicXor: case EOpImageAtomicExchange: case EOpImageAtomicCompSwap: { // Make sure the image types have the correct layout() format and correct argument types const TType& imageType = arg0->getType(); if (imageType.getSampler().type == EbtInt || imageType.getSampler().type == EbtUint) { if (imageType.getQualifier().layoutFormat != ElfR32i && imageType.getQualifier().layoutFormat != ElfR32ui) error(loc, "only supported on image with format r32i or r32ui", fnCandidate.getName().c_str(), ""); } else { if (fnCandidate.getName().compare(0, 19, "imageAtomicExchange") != 0) error(loc, "only supported on integer images", fnCandidate.getName().c_str(), ""); else if (imageType.getQualifier().layoutFormat != ElfR32f && profile == EEsProfile) error(loc, "only supported on image with format r32f", fnCandidate.getName().c_str(), ""); } break; } case EOpInterpolateAtCentroid: case EOpInterpolateAtSample: case EOpInterpolateAtOffset: // "For the interpolateAt* functions, the call will return a precision // qualification matching the precision of the 'interpolant' argument to // the function call." callNode.getQualifier().precision = arg0->getQualifier().precision; // Make sure the first argument is an interpolant, or an array element of an interpolant if (arg0->getType().getQualifier().storage != EvqVaryingIn) { // It might still be an array element. // // We could check more, but the semantics of the first argument are already met; the // only way to turn an array into a float/vec* is array dereference and swizzle. // // ES and desktop 4.3 and earlier: swizzles may not be used // desktop 4.4 and later: swizzles may be used bool swizzleOkay = (profile != EEsProfile) && (version >= 440); const TIntermTyped* base = TIntermediate::findLValueBase(arg0, swizzleOkay); if (base == nullptr || base->getType().getQualifier().storage != EvqVaryingIn) error(loc, "first argument must be an interpolant, or interpolant-array element", fnCandidate.getName().c_str(), ""); } break; default: break; } } extern bool PureOperatorBuiltins; // Deprecated! Use PureOperatorBuiltins == true instead, in which case this // functionality is handled in builtInOpCheck() instead of here. // // Do additional checking of built-in function calls that were not mapped // to built-in operations (e.g., texturing functions). // // Assumes there has been a semantically correct match to a built-in function. // void TParseContext::nonOpBuiltInCheck(const TSourceLoc& loc, const TFunction& fnCandidate, TIntermAggregate& callNode) { // Further maintenance of this function is deprecated, because the "correct" // future-oriented design is to not have to do string compares on function names. // If PureOperatorBuiltins == true, then all built-ins should be mapped // to a TOperator, and this function would then never get called. assert(PureOperatorBuiltins == false); // built-in texturing functions get their return value precision from the precision of the sampler if (fnCandidate.getType().getQualifier().precision == EpqNone && fnCandidate.getParamCount() > 0 && fnCandidate[0].type->getBasicType() == EbtSampler) callNode.getQualifier().precision = callNode.getSequence()[0]->getAsTyped()->getQualifier().precision; if (fnCandidate.getName().compare(0, 7, "texture") == 0) { if (fnCandidate.getName().compare(0, 13, "textureGather") == 0) { TString featureString = fnCandidate.getName() + "(...)"; const char* feature = featureString.c_str(); profileRequires(loc, EEsProfile, 310, nullptr, feature); int compArg = -1; // track which argument, if any, is the constant component argument if (fnCandidate.getName().compare("textureGatherOffset") == 0) { // GL_ARB_texture_gather is good enough for 2D non-shadow textures with no component argument if (fnCandidate[0].type->getSampler().dim == Esd2D && ! fnCandidate[0].type->getSampler().shadow && fnCandidate.getParamCount() == 3) profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_texture_gather, feature); else profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_gpu_shader5, feature); int offsetArg = fnCandidate[0].type->getSampler().shadow ? 3 : 2; if (! callNode.getSequence()[offsetArg]->getAsConstantUnion()) profileRequires(loc, EEsProfile, 0, Num_AEP_gpu_shader5, AEP_gpu_shader5, "non-constant offset argument"); if (! fnCandidate[0].type->getSampler().shadow) compArg = 3; } else if (fnCandidate.getName().compare("textureGatherOffsets") == 0) { profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_gpu_shader5, feature); if (! fnCandidate[0].type->getSampler().shadow) compArg = 3; // check for constant offsets int offsetArg = fnCandidate[0].type->getSampler().shadow ? 3 : 2; if (! callNode.getSequence()[offsetArg]->getAsConstantUnion()) error(loc, "must be a compile-time constant:", feature, "offsets argument"); } else if (fnCandidate.getName().compare("textureGather") == 0) { // More than two arguments needs gpu_shader5, and rectangular or shadow needs gpu_shader5, // otherwise, need GL_ARB_texture_gather. if (fnCandidate.getParamCount() > 2 || fnCandidate[0].type->getSampler().dim == EsdRect || fnCandidate[0].type->getSampler().shadow) { profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_gpu_shader5, feature); if (! fnCandidate[0].type->getSampler().shadow) compArg = 2; } else profileRequires(loc, ~EEsProfile, 400, E_GL_ARB_texture_gather, feature); } if (compArg > 0 && compArg < fnCandidate.getParamCount()) { if (callNode.getSequence()[compArg]->getAsConstantUnion()) { int value = callNode.getSequence()[compArg]->getAsConstantUnion()->getConstArray()[0].getIConst(); if (value < 0 || value > 3) error(loc, "must be 0, 1, 2, or 3:", feature, "component argument"); } else error(loc, "must be a compile-time constant:", feature, "component argument"); } } else { // this is only for functions not starting "textureGather"... if (fnCandidate.getName().find("Offset") != TString::npos) { // Handle texture-offset limits checking int arg = -1; if (fnCandidate.getName().compare("textureOffset") == 0) arg = 2; else if (fnCandidate.getName().compare("texelFetchOffset") == 0) arg = 3; else if (fnCandidate.getName().compare("textureProjOffset") == 0) arg = 2; else if (fnCandidate.getName().compare("textureLodOffset") == 0) arg = 3; else if (fnCandidate.getName().compare("textureProjLodOffset") == 0) arg = 3; else if (fnCandidate.getName().compare("textureGradOffset") == 0) arg = 4; else if (fnCandidate.getName().compare("textureProjGradOffset") == 0) arg = 4; if (arg > 0) { if (! callNode.getSequence()[arg]->getAsConstantUnion()) error(loc, "argument must be compile-time constant", "texel offset", ""); else { const TType& type = callNode.getSequence()[arg]->getAsTyped()->getType(); for (int c = 0; c < type.getVectorSize(); ++c) { int offset = callNode.getSequence()[arg]->getAsConstantUnion()->getConstArray()[c].getIConst(); if (offset > resources.maxProgramTexelOffset || offset < resources.minProgramTexelOffset) error(loc, "value is out of range:", "texel offset", "[gl_MinProgramTexelOffset, gl_MaxProgramTexelOffset]"); } } } } } } // GL_ARB_shader_texture_image_samples if (fnCandidate.getName().compare(0, 14, "textureSamples") == 0 || fnCandidate.getName().compare(0, 12, "imageSamples") == 0) profileRequires(loc, ~EEsProfile, 450, E_GL_ARB_shader_texture_image_samples, "textureSamples and imageSamples"); if (fnCandidate.getName().compare(0, 11, "imageAtomic") == 0) { const TType& imageType = callNode.getSequence()[0]->getAsTyped()->getType(); if (imageType.getSampler().type == EbtInt || imageType.getSampler().type == EbtUint) { if (imageType.getQualifier().layoutFormat != ElfR32i && imageType.getQualifier().layoutFormat != ElfR32ui) error(loc, "only supported on image with format r32i or r32ui", fnCandidate.getName().c_str(), ""); } else { if (fnCandidate.getName().compare(0, 19, "imageAtomicExchange") != 0) error(loc, "only supported on integer images", fnCandidate.getName().c_str(), ""); else if (imageType.getQualifier().layoutFormat != ElfR32f && profile == EEsProfile) error(loc, "only supported on image with format r32f", fnCandidate.getName().c_str(), ""); } } } // // Handle seeing a built-in constructor in a grammar production. // TFunction* TParseContext::handleConstructorCall(const TSourceLoc& loc, const TPublicType& publicType) { TType type(publicType); type.getQualifier().precision = EpqNone; if (type.isArray()) { profileRequires(loc, ENoProfile, 120, E_GL_3DL_array_objects, "arrayed constructor"); profileRequires(loc, EEsProfile, 300, nullptr, "arrayed constructor"); } TOperator op = mapTypeToConstructorOp(type); if (op == EOpNull) { error(loc, "cannot construct this type", type.getBasicString(), ""); op = EOpConstructFloat; TType errorType(EbtFloat); type.shallowCopy(errorType); } TString empty(""); return new TFunction(&empty, type, op); } // // Given a type, find what operation would fully construct it. // TOperator TParseContext::mapTypeToConstructorOp(const TType& type) const { TOperator op = EOpNull; switch (type.getBasicType()) { case EbtStruct: op = EOpConstructStruct; break; case EbtSampler: if (type.getSampler().combined) op = EOpConstructTextureSampler; break; case EbtFloat: if (type.isMatrix()) { switch (type.getMatrixCols()) { case 2: switch (type.getMatrixRows()) { case 2: op = EOpConstructMat2x2; break; case 3: op = EOpConstructMat2x3; break; case 4: op = EOpConstructMat2x4; break; default: break; // some compilers want this } break; case 3: switch (type.getMatrixRows()) { case 2: op = EOpConstructMat3x2; break; case 3: op = EOpConstructMat3x3; break; case 4: op = EOpConstructMat3x4; break; default: break; // some compilers want this } break; case 4: switch (type.getMatrixRows()) { case 2: op = EOpConstructMat4x2; break; case 3: op = EOpConstructMat4x3; break; case 4: op = EOpConstructMat4x4; break; default: break; // some compilers want this } break; default: break; // some compilers want this } } else { switch(type.getVectorSize()) { case 1: op = EOpConstructFloat; break; case 2: op = EOpConstructVec2; break; case 3: op = EOpConstructVec3; break; case 4: op = EOpConstructVec4; break; default: break; // some compilers want this } } break; case EbtDouble: if (type.getMatrixCols()) { switch (type.getMatrixCols()) { case 2: switch (type.getMatrixRows()) { case 2: op = EOpConstructDMat2x2; break; case 3: op = EOpConstructDMat2x3; break; case 4: op = EOpConstructDMat2x4; break; default: break; // some compilers want this } break; case 3: switch (type.getMatrixRows()) { case 2: op = EOpConstructDMat3x2; break; case 3: op = EOpConstructDMat3x3; break; case 4: op = EOpConstructDMat3x4; break; default: break; // some compilers want this } break; case 4: switch (type.getMatrixRows()) { case 2: op = EOpConstructDMat4x2; break; case 3: op = EOpConstructDMat4x3; break; case 4: op = EOpConstructDMat4x4; break; default: break; // some compilers want this } break; } } else { switch(type.getVectorSize()) { case 1: op = EOpConstructDouble; break; case 2: op = EOpConstructDVec2; break; case 3: op = EOpConstructDVec3; break; case 4: op = EOpConstructDVec4; break; default: break; // some compilers want this } } break; case EbtInt: switch(type.getVectorSize()) { case 1: op = EOpConstructInt; break; case 2: op = EOpConstructIVec2; break; case 3: op = EOpConstructIVec3; break; case 4: op = EOpConstructIVec4; break; default: break; // some compilers want this } break; case EbtUint: switch(type.getVectorSize()) { case 1: op = EOpConstructUint; break; case 2: op = EOpConstructUVec2; break; case 3: op = EOpConstructUVec3; break; case 4: op = EOpConstructUVec4; break; default: break; // some compilers want this } break; case EbtBool: switch(type.getVectorSize()) { case 1: op = EOpConstructBool; break; case 2: op = EOpConstructBVec2; break; case 3: op = EOpConstructBVec3; break; case 4: op = EOpConstructBVec4; break; default: break; // some compilers want this } break; default: break; } return op; } // // Same error message for all places assignments don't work. // void TParseContext::assignError(const TSourceLoc& loc, const char* op, TString left, TString right) { error(loc, "", op, "cannot convert from '%s' to '%s'", right.c_str(), left.c_str()); } // // Same error message for all places unary operations don't work. // void TParseContext::unaryOpError(const TSourceLoc& loc, const char* op, TString operand) { error(loc, " wrong operand type", op, "no operation '%s' exists that takes an operand of type %s (or there is no acceptable conversion)", op, operand.c_str()); } // // Same error message for all binary operations don't work. // void TParseContext::binaryOpError(const TSourceLoc& loc, const char* op, TString left, TString right) { error(loc, " wrong operand types:", op, "no operation '%s' exists that takes a left-hand operand of type '%s' and " "a right operand of type '%s' (or there is no acceptable conversion)", op, left.c_str(), right.c_str()); } // // A basic type of EbtVoid is a key that the name string was seen in the source, but // it was not found as a variable in the symbol table. If so, give the error // message and insert a dummy variable in the symbol table to prevent future errors. // void TParseContext::variableCheck(TIntermTyped*& nodePtr) { TIntermSymbol* symbol = nodePtr->getAsSymbolNode(); if (! symbol) return; if (symbol->getType().getBasicType() == EbtVoid) { error(symbol->getLoc(), "undeclared identifier", symbol->getName().c_str(), ""); // Add to symbol table to prevent future error messages on the same name if (symbol->getName().size() > 0) { TVariable* fakeVariable = new TVariable(&symbol->getName(), TType(EbtFloat)); symbolTable.insert(*fakeVariable); // substitute a symbol node for this new variable nodePtr = intermediate.addSymbol(*fakeVariable, symbol->getLoc()); } } else { switch (symbol->getQualifier().storage) { case EvqPointCoord: profileRequires(symbol->getLoc(), ENoProfile, 120, nullptr, "gl_PointCoord"); break; default: break; // some compilers want this } } } // // Both test and if necessary, spit out an error, to see if the node is really // an l-value that can be operated on this way. // // Returns true if the was an error. // bool TParseContext::lValueErrorCheck(const TSourceLoc& loc, const char* op, TIntermTyped* node) { TIntermBinary* binaryNode = node->getAsBinaryNode(); if (binaryNode) { bool errorReturn; switch(binaryNode->getOp()) { case EOpIndexDirect: case EOpIndexIndirect: // ... tessellation control shader ... // If a per-vertex output variable is used as an l-value, it is a // compile-time or link-time error if the expression indicating the // vertex index is not the identifier gl_InvocationID. if (language == EShLangTessControl) { const TType& leftType = binaryNode->getLeft()->getType(); if (leftType.getQualifier().storage == EvqVaryingOut && ! leftType.getQualifier().patch && binaryNode->getLeft()->getAsSymbolNode()) { // we have a per-vertex output const TIntermSymbol* rightSymbol = binaryNode->getRight()->getAsSymbolNode(); if (! rightSymbol || rightSymbol->getQualifier().builtIn != EbvInvocationId) error(loc, "tessellation-control per-vertex output l-value must be indexed with gl_InvocationID", "[]", ""); } } // fall through case EOpIndexDirectStruct: return lValueErrorCheck(loc, op, binaryNode->getLeft()); case EOpVectorSwizzle: errorReturn = lValueErrorCheck(loc, op, binaryNode->getLeft()); if (!errorReturn) { int offset[4] = {0,0,0,0}; TIntermTyped* rightNode = binaryNode->getRight(); TIntermAggregate *aggrNode = rightNode->getAsAggregate(); for (TIntermSequence::iterator p = aggrNode->getSequence().begin(); p != aggrNode->getSequence().end(); p++) { int value = (*p)->getAsTyped()->getAsConstantUnion()->getConstArray()[0].getIConst(); offset[value]++; if (offset[value] > 1) { error(loc, " l-value of swizzle cannot have duplicate components", op, "", ""); return true; } } } return errorReturn; default: break; } error(loc, " l-value required", op, "", ""); return true; } const char* symbol = nullptr; TIntermSymbol* symNode = node->getAsSymbolNode(); if (symNode != nullptr) symbol = symNode->getName().c_str(); const char* message = nullptr; switch (node->getQualifier().storage) { case EvqConst: message = "can't modify a const"; break; case EvqConstReadOnly: message = "can't modify a const"; break; case EvqVaryingIn: message = "can't modify shader input"; break; case EvqInstanceId: message = "can't modify gl_InstanceID"; break; case EvqVertexId: message = "can't modify gl_VertexID"; break; case EvqFace: message = "can't modify gl_FrontFace"; break; case EvqFragCoord: message = "can't modify gl_FragCoord"; break; case EvqPointCoord: message = "can't modify gl_PointCoord"; break; case EvqUniform: message = "can't modify a uniform"; break; case EvqBuffer: if (node->getQualifier().readonly) message = "can't modify a readonly buffer"; break; case EvqFragDepth: intermediate.setDepthReplacing(); // "In addition, it is an error to statically write to gl_FragDepth in the fragment shader." if (profile == EEsProfile && intermediate.getEarlyFragmentTests()) message = "can't modify gl_FragDepth if using early_fragment_tests"; break; default: // // Type that can't be written to? // switch (node->getBasicType()) { case EbtSampler: message = "can't modify a sampler"; break; case EbtAtomicUint: message = "can't modify an atomic_uint"; break; case EbtVoid: message = "can't modify void"; break; default: break; } } if (message == nullptr && binaryNode == nullptr && symNode == nullptr) { error(loc, " l-value required", op, "", ""); return true; } // // Everything else is okay, no error. // if (message == nullptr) return false; // // If we get here, we have an error and a message. // if (symNode) error(loc, " l-value required", op, "\"%s\" (%s)", symbol, message); else error(loc, " l-value required", op, "(%s)", message); return true; } // Test for and give an error if the node can't be read from. void TParseContext::rValueErrorCheck(const TSourceLoc& loc, const char* op, TIntermTyped* node) { if (! node) return; TIntermBinary* binaryNode = node->getAsBinaryNode(); if (binaryNode) { switch(binaryNode->getOp()) { case EOpIndexDirect: case EOpIndexIndirect: case EOpIndexDirectStruct: case EOpVectorSwizzle: rValueErrorCheck(loc, op, binaryNode->getLeft()); default: break; } return; } TIntermSymbol* symNode = node->getAsSymbolNode(); if (symNode && symNode->getQualifier().writeonly) error(loc, "can't read from writeonly object: ", op, symNode->getName().c_str()); } // // Both test, and if necessary spit out an error, to see if the node is really // a constant. // void TParseContext::constantValueCheck(TIntermTyped* node, const char* token) { if (node->getQualifier().storage != EvqConst) error(node->getLoc(), "constant expression required", token, ""); } // // Both test, and if necessary spit out an error, to see if the node is really // an integer. // void TParseContext::integerCheck(const TIntermTyped* node, const char* token) { if ((node->getBasicType() == EbtInt || node->getBasicType() == EbtUint) && node->isScalar()) return; error(node->getLoc(), "scalar integer expression required", token, ""); } // // Both test, and if necessary spit out an error, to see if we are currently // globally scoped. // void TParseContext::globalCheck(const TSourceLoc& loc, const char* token) { if (! symbolTable.atGlobalLevel()) error(loc, "not allowed in nested scope", token, ""); } // // Reserved errors for GLSL. // void TParseContext::reservedErrorCheck(const TSourceLoc& loc, const TString& identifier) { // "Identifiers starting with "gl_" are reserved for use by OpenGL, and may not be // declared in a shader; this results in a compile-time error." if (! symbolTable.atBuiltInLevel()) { if (builtInName(identifier)) error(loc, "identifiers starting with \"gl_\" are reserved", identifier.c_str(), ""); // "__" are not supposed to be an error. ES 310 (and desktop) added the clarification: // "In addition, all identifiers containing two consecutive underscores (__) are // reserved; using such a name does not itself result in an error, but may result // in undefined behavior." // however, before that, ES tests required an error. if (identifier.find("__") != TString::npos) { if (profile == EEsProfile && version <= 300) error(loc, "identifiers containing consecutive underscores (\"__\") are reserved, and an error if version <= 300", identifier.c_str(), ""); else warn(loc, "identifiers containing consecutive underscores (\"__\") are reserved", identifier.c_str(), ""); } } } // // Reserved errors for the preprocessor. // void TParseContext::reservedPpErrorCheck(const TSourceLoc& loc, const char* identifier, const char* op) { // "__" are not supposed to be an error. ES 310 (and desktop) added the clarification: // "All macro names containing two consecutive underscores ( __ ) are reserved; // defining such a name does not itself result in an error, but may result in // undefined behavior. All macro names prefixed with "GL_" ("GL" followed by a // single underscore) are also reserved, and defining such a name results in a // compile-time error." // however, before that, ES tests required an error. if (strncmp(identifier, "GL_", 3) == 0) ppError(loc, "names beginning with \"GL_\" can't be (un)defined:", op, identifier); else if (strncmp(identifier, "defined", 8) == 0) ppError(loc, "\"defined\" can't be (un)defined:", op, identifier); else if (strstr(identifier, "__") != 0) { if (profile == EEsProfile && version >= 300 && (strcmp(identifier, "__LINE__") == 0 || strcmp(identifier, "__FILE__") == 0 || strcmp(identifier, "__VERSION__") == 0)) ppError(loc, "predefined names can't be (un)defined:", op, identifier); else { if (profile == EEsProfile && version <= 300) ppError(loc, "names containing consecutive underscores are reserved, and an error if version <= 300:", op, identifier); else ppWarn(loc, "names containing consecutive underscores are reserved:", op, identifier); } } } // // See if this version/profile allows use of the line-continuation character '\'. // // Returns true if a line continuation should be done. // bool TParseContext::lineContinuationCheck(const TSourceLoc& loc, bool endOfComment) { const char* message = "line continuation"; bool lineContinuationAllowed = (profile == EEsProfile && version >= 300) || (profile != EEsProfile && (version >= 420 || extensionTurnedOn(E_GL_ARB_shading_language_420pack))); if (endOfComment) { if (lineContinuationAllowed) warn(loc, "used at end of comment; the following line is still part of the comment", message, ""); else warn(loc, "used at end of comment, but this version does not provide line continuation", message, ""); return lineContinuationAllowed; } if (relaxedErrors()) { if (! lineContinuationAllowed) warn(loc, "not allowed in this version", message, ""); return true; } else { profileRequires(loc, EEsProfile, 300, nullptr, message); profileRequires(loc, ~EEsProfile, 420, E_GL_ARB_shading_language_420pack, message); } return lineContinuationAllowed; } bool TParseContext::builtInName(const TString& identifier) { return identifier.compare(0, 3, "gl_") == 0; } // // Make sure there is enough data and not too many arguments provided to the // constructor to build something of the type of the constructor. Also returns // the type of the constructor. // // Returns true if there was an error in construction. // bool TParseContext::constructorError(const TSourceLoc& loc, TIntermNode* node, TFunction& function, TOperator op, TType& type) { type.shallowCopy(function.getType()); bool constructingMatrix = false; switch(op) { case EOpConstructTextureSampler: return constructorTextureSamplerError(loc, function); case EOpConstructMat2x2: case EOpConstructMat2x3: case EOpConstructMat2x4: case EOpConstructMat3x2: case EOpConstructMat3x3: case EOpConstructMat3x4: case EOpConstructMat4x2: case EOpConstructMat4x3: case EOpConstructMat4x4: case EOpConstructDMat2x2: case EOpConstructDMat2x3: case EOpConstructDMat2x4: case EOpConstructDMat3x2: case EOpConstructDMat3x3: case EOpConstructDMat3x4: case EOpConstructDMat4x2: case EOpConstructDMat4x3: case EOpConstructDMat4x4: constructingMatrix = true; break; default: break; } // // Walk the arguments for first-pass checks and collection of information. // int size = 0; bool constType = true; bool full = false; bool overFull = false; bool matrixInMatrix = false; bool arrayArg = false; for (int arg = 0; arg < function.getParamCount(); ++arg) { if (function[arg].type->isArray()) { if (! function[arg].type->isExplicitlySizedArray()) { // Can't construct from an unsized array. error(loc, "array argument must be sized", "constructor", ""); return true; } arrayArg = true; } if (constructingMatrix && function[arg].type->isMatrix()) matrixInMatrix = true; // 'full' will go to true when enough args have been seen. If we loop // again, there is an extra argument. if (full) { // For vectors and matrices, it's okay to have too many components // available, but not okay to have unused arguments. overFull = true; } size += function[arg].type->computeNumComponents(); if (op != EOpConstructStruct && ! type.isArray() && size >= type.computeNumComponents()) full = true; if (function[arg].type->getQualifier().storage != EvqConst) constType = false; } if (constType) type.getQualifier().storage = EvqConst; if (type.isArray()) { if (function.getParamCount() == 0) { error(loc, "array constructor must have at least one argument", "constructor", ""); return true; } if (type.isImplicitlySizedArray()) { // auto adapt the constructor type to the number of arguments type.changeOuterArraySize(function.getParamCount()); } else if (type.getOuterArraySize() != function.getParamCount()) { error(loc, "array constructor needs one argument per array element", "constructor", ""); return true; } if (type.isArrayOfArrays()) { // Types have to match, but we're still making the type. // Finish making the type, and the comparison is done later // when checking for conversion. TArraySizes& arraySizes = type.getArraySizes(); // At least the dimensionalities have to match. if (! function[0].type->isArray() || arraySizes.getNumDims() != function[0].type->getArraySizes().getNumDims() + 1) { error(loc, "array constructor argument not correct type to construct array element", "constructior", ""); return true; } if (arraySizes.isInnerImplicit()) { // "Arrays of arrays ..., and the size for any dimension is optional" // That means we need to adopt (from the first argument) the other array sizes into the type. for (int d = 1; d < arraySizes.getNumDims(); ++d) { if (arraySizes.getDimSize(d) == UnsizedArraySize) { arraySizes.setDimSize(d, function[0].type->getArraySizes().getDimSize(d - 1)); } } } } } if (arrayArg && op != EOpConstructStruct && ! type.isArrayOfArrays()) { error(loc, "constructing non-array constituent from array argument", "constructor", ""); return true; } if (matrixInMatrix && ! type.isArray()) { profileRequires(loc, ENoProfile, 120, nullptr, "constructing matrix from matrix"); // "If a matrix argument is given to a matrix constructor, // it is a compile-time error to have any other arguments." if (function.getParamCount() != 1) error(loc, "matrix constructed from matrix can only have one argument", "constructor", ""); return false; } if (overFull) { error(loc, "too many arguments", "constructor", ""); return true; } if (op == EOpConstructStruct && ! type.isArray() && (int)type.getStruct()->size() != function.getParamCount()) { error(loc, "Number of constructor parameters does not match the number of structure fields", "constructor", ""); return true; } if ((op != EOpConstructStruct && size != 1 && size < type.computeNumComponents()) || (op == EOpConstructStruct && size < type.computeNumComponents())) { error(loc, "not enough data provided for construction", "constructor", ""); return true; } TIntermTyped* typed = node->getAsTyped(); if (typed == nullptr) { error(loc, "constructor argument does not have a type", "constructor", ""); return true; } if (op != EOpConstructStruct && typed->getBasicType() == EbtSampler) { error(loc, "cannot convert a sampler", "constructor", ""); return true; } if (op != EOpConstructStruct && typed->getBasicType() == EbtAtomicUint) { error(loc, "cannot convert an atomic_uint", "constructor", ""); return true; } if (typed->getBasicType() == EbtVoid) { error(loc, "cannot convert a void", "constructor", ""); return true; } return false; } // Verify all the correct semantics for constructing a combined texture/sampler. // Return true if the semantics are incorrect. bool TParseContext::constructorTextureSamplerError(const TSourceLoc& loc, const TFunction& function) { TString constructorName = function.getType().getBasicTypeString(); // TODO: performance: should not be making copy; interface needs to change const char* token = constructorName.c_str(); // exactly two arguments needed if (function.getParamCount() != 2) { error(loc, "sampler-constructor requires two arguments", token, ""); return true; } // For now, not allowing arrayed constructors, the rest of this function // is set up to allow them, if this test is removed: if (function.getType().isArray()) { error(loc, "sampler-constructor cannot make an array of samplers", token, ""); return true; } // first argument // * the constructor's first argument must be a texture type // * the dimensionality (1D, 2D, 3D, Cube, Rect, Buffer, MS, and Array) // of the texture type must match that of the constructed sampler type // (that is, the suffixes of the type of the first argument and the // type of the constructor will be spelled the same way) if (function[0].type->getBasicType() != EbtSampler || ! function[0].type->getSampler().isTexture() || function[0].type->isArray()) { error(loc, "sampler-constructor first argument must be a scalar textureXXX type", token, ""); return true; } // simulate the first argument's impact on the result type, so it can be compared with the encapsulated operator!=() TSampler texture = function.getType().getSampler(); texture.combined = false; texture.shadow = false; if (texture != function[0].type->getSampler()) { error(loc, "sampler-constructor first argument must match type and dimensionality of constructor type", token, ""); return true; } // second argument // * the constructor's second argument must be a scalar of type // *sampler* or *samplerShadow* // * the presence or absence of depth comparison (Shadow) must match // between the constructed sampler type and the type of the second argument if ( function[1].type->getBasicType() != EbtSampler || ! function[1].type->getSampler().isPureSampler() || function[1].type->isArray()) { error(loc, "sampler-constructor second argument must be a scalar type 'sampler'", token, ""); return true; } if (function.getType().getSampler().shadow != function[1].type->getSampler().shadow) { error(loc, "sampler-constructor second argument presence of shadow must match constructor presence of shadow", token, ""); return true; } return false; } // Checks to see if a void variable has been declared and raise an error message for such a case // // returns true in case of an error // bool TParseContext::voidErrorCheck(const TSourceLoc& loc, const TString& identifier, const TBasicType basicType) { if (basicType == EbtVoid) { error(loc, "illegal use of type 'void'", identifier.c_str(), ""); return true; } return false; } // Checks to see if the node (for the expression) contains a scalar boolean expression or not void TParseContext::boolCheck(const TSourceLoc& loc, const TIntermTyped* type) { if (type->getBasicType() != EbtBool || type->isArray() || type->isMatrix() || type->isVector()) error(loc, "boolean expression expected", "", ""); } // This function checks to see if the node (for the expression) contains a scalar boolean expression or not void TParseContext::boolCheck(const TSourceLoc& loc, const TPublicType& pType) { if (pType.basicType != EbtBool || pType.arraySizes || pType.matrixCols > 1 || (pType.vectorSize > 1)) error(loc, "boolean expression expected", "", ""); } void TParseContext::samplerCheck(const TSourceLoc& loc, const TType& type, const TString& identifier, TIntermTyped* /*initializer*/) { if (type.getQualifier().storage == EvqUniform) return; if (type.getBasicType() == EbtStruct && containsFieldWithBasicType(type, EbtSampler)) error(loc, "non-uniform struct contains a sampler or image:", type.getBasicTypeString().c_str(), identifier.c_str()); else if (type.getBasicType() == EbtSampler && type.getQualifier().storage != EvqUniform) { // non-uniform sampler // not yet: okay if it has an initializer // if (! initializer) error(loc, "sampler/image types can only be used in uniform variables or function parameters:", type.getBasicTypeString().c_str(), identifier.c_str()); } } void TParseContext::atomicUintCheck(const TSourceLoc& loc, const TType& type, const TString& identifier) { if (type.getQualifier().storage == EvqUniform) return; if (type.getBasicType() == EbtStruct && containsFieldWithBasicType(type, EbtAtomicUint)) error(loc, "non-uniform struct contains an atomic_uint:", type.getBasicTypeString().c_str(), identifier.c_str()); else if (type.getBasicType() == EbtAtomicUint && type.getQualifier().storage != EvqUniform) error(loc, "atomic_uints can only be used in uniform variables or function parameters:", type.getBasicTypeString().c_str(), identifier.c_str()); } void TParseContext::transparentCheck(const TSourceLoc& loc, const TType& type, const TString& identifier) { // double standard due to gl_NumSamples if (parsingBuiltins) return; // Vulkan doesn't allow transparent uniforms outside of blocks if (vulkan == 0 || type.getQualifier().storage != EvqUniform) return; if (type.containsNonOpaque()) vulkanRemoved(loc, "non-opaque uniforms outside a block"); } // // Check/fix just a full qualifier (no variables or types yet, but qualifier is complete) at global level. // void TParseContext::globalQualifierFixCheck(const TSourceLoc& loc, TQualifier& qualifier) { // move from parameter/unknown qualifiers to pipeline in/out qualifiers switch (qualifier.storage) { case EvqIn: profileRequires(loc, ENoProfile, 130, nullptr, "in for stage inputs"); profileRequires(loc, EEsProfile, 300, nullptr, "in for stage inputs"); qualifier.storage = EvqVaryingIn; break; case EvqOut: profileRequires(loc, ENoProfile, 130, nullptr, "out for stage outputs"); profileRequires(loc, EEsProfile, 300, nullptr, "out for stage outputs"); qualifier.storage = EvqVaryingOut; break; case EvqInOut: qualifier.storage = EvqVaryingIn; error(loc, "cannot use 'inout' at global scope", "", ""); break; default: break; } invariantCheck(loc, qualifier); } // // Check a full qualifier and type (no variable yet) at global level. // void TParseContext::globalQualifierTypeCheck(const TSourceLoc& loc, const TQualifier& qualifier, const TPublicType& publicType) { if (! symbolTable.atGlobalLevel()) return; if (qualifier.isMemory() && ! publicType.isImage() && publicType.qualifier.storage != EvqBuffer) error(loc, "memory qualifiers cannot be used on this type", "", ""); if (qualifier.storage == EvqBuffer && publicType.basicType != EbtBlock) error(loc, "buffers can be declared only as blocks", "buffer", ""); if (qualifier.storage != EvqVaryingIn && qualifier.storage != EvqVaryingOut) return; if (publicType.shaderQualifiers.blendEquation) error(loc, "can only be applied to a standalone 'out'", "blend equation", ""); // now, knowing it is a shader in/out, do all the in/out semantic checks if (publicType.basicType == EbtBool) { error(loc, "cannot be bool", GetStorageQualifierString(qualifier.storage), ""); return; } if (publicType.basicType == EbtInt || publicType.basicType == EbtUint || publicType.basicType == EbtDouble) profileRequires(loc, EEsProfile, 300, nullptr, "shader input/output"); if (! qualifier.flat) { if (publicType.basicType == EbtInt || publicType.basicType == EbtUint || publicType.basicType == EbtDouble || (publicType.userDef && (publicType.userDef->containsBasicType(EbtInt) || publicType.userDef->containsBasicType(EbtUint) || publicType.userDef->containsBasicType(EbtDouble)))) { if (qualifier.storage == EvqVaryingIn && language == EShLangFragment) error(loc, "must be qualified as flat", TType::getBasicString(publicType.basicType), GetStorageQualifierString(qualifier.storage)); else if (qualifier.storage == EvqVaryingOut && language == EShLangVertex && version == 300) error(loc, "must be qualified as flat", TType::getBasicString(publicType.basicType), GetStorageQualifierString(qualifier.storage)); } } if (qualifier.patch && qualifier.isInterpolation()) error(loc, "cannot use interpolation qualifiers with patch", "patch", ""); if (qualifier.storage == EvqVaryingIn) { switch (language) { case EShLangVertex: if (publicType.basicType == EbtStruct) { error(loc, "cannot be a structure or array", GetStorageQualifierString(qualifier.storage), ""); return; } if (publicType.arraySizes) { requireProfile(loc, ~EEsProfile, "vertex input arrays"); profileRequires(loc, ENoProfile, 150, nullptr, "vertex input arrays"); } if (qualifier.isAuxiliary() || qualifier.isInterpolation() || qualifier.isMemory() || qualifier.invariant) error(loc, "vertex input cannot be further qualified", "", ""); break; case EShLangTessControl: if (qualifier.patch) error(loc, "can only use on output in tessellation-control shader", "patch", ""); break; case EShLangTessEvaluation: break; case EShLangGeometry: break; case EShLangFragment: if (publicType.userDef) { profileRequires(loc, EEsProfile, 300, nullptr, "fragment-shader struct input"); profileRequires(loc, ~EEsProfile, 150, nullptr, "fragment-shader struct input"); if (publicType.userDef->containsStructure()) requireProfile(loc, ~EEsProfile, "fragment-shader struct input containing structure"); if (publicType.userDef->containsArray()) requireProfile(loc, ~EEsProfile, "fragment-shader struct input containing an array"); } break; case EShLangCompute: if (! symbolTable.atBuiltInLevel()) error(loc, "global storage input qualifier cannot be used in a compute shader", "in", ""); break; default: break; } } else { // qualifier.storage == EvqVaryingOut switch (language) { case EShLangVertex: if (publicType.userDef) { profileRequires(loc, EEsProfile, 300, nullptr, "vertex-shader struct output"); profileRequires(loc, ~EEsProfile, 150, nullptr, "vertex-shader struct output"); if (publicType.userDef->containsStructure()) requireProfile(loc, ~EEsProfile, "vertex-shader struct output containing structure"); if (publicType.userDef->containsArray()) requireProfile(loc, ~EEsProfile, "vertex-shader struct output containing an array"); } break; case EShLangTessControl: break; case EShLangTessEvaluation: if (qualifier.patch) error(loc, "can only use on input in tessellation-evaluation shader", "patch", ""); break; case EShLangGeometry: break; case EShLangFragment: profileRequires(loc, EEsProfile, 300, nullptr, "fragment shader output"); if (publicType.basicType == EbtStruct) { error(loc, "cannot be a structure", GetStorageQualifierString(qualifier.storage), ""); return; } if (publicType.matrixRows > 0) { error(loc, "cannot be a matrix", GetStorageQualifierString(qualifier.storage), ""); return; } if (qualifier.isAuxiliary()) error(loc, "can't use auxiliary qualifier on a fragment output", "centroid/sample/patch", ""); if (qualifier.isInterpolation()) error(loc, "can't use interpolation qualifier on a fragment output", "flat/smooth/noperspective", ""); break; case EShLangCompute: error(loc, "global storage output qualifier cannot be used in a compute shader", "out", ""); break; default: break; } } } // // Merge characteristics of the 'src' qualifier into the 'dst'. // If there is duplication, issue error messages, unless 'force' // is specified, which means to just override default settings. // // Also, when force is false, it will be assumed that 'src' follows // 'dst', for the purpose of error checking order for versions // that require specific orderings of qualifiers. // void TParseContext::mergeQualifiers(const TSourceLoc& loc, TQualifier& dst, const TQualifier& src, bool force) { // Multiple auxiliary qualifiers (mostly done later by 'individual qualifiers') if (src.isAuxiliary() && dst.isAuxiliary()) error(loc, "can only have one auxiliary qualifier (centroid, patch, and sample)", "", ""); // Multiple interpolation qualifiers (mostly done later by 'individual qualifiers') if (src.isInterpolation() && dst.isInterpolation()) error(loc, "can only have one interpolation qualifier (flat, smooth, noperspective)", "", ""); // Ordering if (! force && ((profile != EEsProfile && version < 420) || (profile == EEsProfile && version < 310)) && ! extensionTurnedOn(E_GL_ARB_shading_language_420pack)) { // non-function parameters if (src.invariant && (dst.isInterpolation() || dst.isAuxiliary() || dst.storage != EvqTemporary || dst.precision != EpqNone)) error(loc, "invariant qualifier must appear first", "", ""); else if (src.isInterpolation() && (dst.isAuxiliary() || dst.storage != EvqTemporary || dst.precision != EpqNone)) error(loc, "interpolation qualifiers must appear before storage and precision qualifiers", "", ""); else if (src.isAuxiliary() && (dst.storage != EvqTemporary || dst.precision != EpqNone)) error(loc, "Auxiliary qualifiers (centroid, patch, and sample) must appear before storage and precision qualifiers", "", ""); else if (src.storage != EvqTemporary && (dst.precision != EpqNone)) error(loc, "precision qualifier must appear as last qualifier", "", ""); // function parameters if (src.storage == EvqConst && (dst.storage == EvqIn || dst.storage == EvqOut)) error(loc, "in/out must appear before const", "", ""); } // Storage qualification if (dst.storage == EvqTemporary || dst.storage == EvqGlobal) dst.storage = src.storage; else if ((dst.storage == EvqIn && src.storage == EvqOut) || (dst.storage == EvqOut && src.storage == EvqIn)) dst.storage = EvqInOut; else if ((dst.storage == EvqIn && src.storage == EvqConst) || (dst.storage == EvqConst && src.storage == EvqIn)) dst.storage = EvqConstReadOnly; else if (src.storage != EvqTemporary && src.storage != EvqGlobal) error(loc, "too many storage qualifiers", GetStorageQualifierString(src.storage), ""); // Precision qualifiers if (! force && src.precision != EpqNone && dst.precision != EpqNone) error(loc, "only one precision qualifier allowed", GetPrecisionQualifierString(src.precision), ""); if (dst.precision == EpqNone || (force && src.precision != EpqNone)) dst.precision = src.precision; // Layout qualifiers mergeObjectLayoutQualifiers(dst, src, false); // individual qualifiers bool repeated = false; #define MERGE_SINGLETON(field) repeated |= dst.field && src.field; dst.field |= src.field; MERGE_SINGLETON(invariant); MERGE_SINGLETON(centroid); MERGE_SINGLETON(smooth); MERGE_SINGLETON(flat); MERGE_SINGLETON(nopersp); MERGE_SINGLETON(patch); MERGE_SINGLETON(sample); MERGE_SINGLETON(coherent); MERGE_SINGLETON(volatil); MERGE_SINGLETON(restrict); MERGE_SINGLETON(readonly); MERGE_SINGLETON(writeonly); MERGE_SINGLETON(specConstant); if (repeated) error(loc, "replicated qualifiers", "", ""); } void TParseContext::setDefaultPrecision(const TSourceLoc& loc, TPublicType& publicType, TPrecisionQualifier qualifier) { TBasicType basicType = publicType.basicType; if (basicType == EbtSampler) { defaultSamplerPrecision[computeSamplerTypeIndex(publicType.sampler)] = qualifier; return; // all is well } if (basicType == EbtInt || basicType == EbtFloat) { if (publicType.isScalar()) { defaultPrecision[basicType] = qualifier; if (basicType == EbtInt) defaultPrecision[EbtUint] = qualifier; return; // all is well } } if (basicType == EbtAtomicUint) { if (qualifier != EpqHigh) error(loc, "can only apply highp to atomic_uint", "precision", ""); return; } error(loc, "cannot apply precision statement to this type; use 'float', 'int' or a sampler type", TType::getBasicString(basicType), ""); } // used to flatten the sampler type space into a single dimension // correlates with the declaration of defaultSamplerPrecision[] int TParseContext::computeSamplerTypeIndex(TSampler& sampler) { int arrayIndex = sampler.arrayed ? 1 : 0; int shadowIndex = sampler.shadow ? 1 : 0; int externalIndex = sampler.external ? 1 : 0; return EsdNumDims * (EbtNumTypes * (2 * (2 * arrayIndex + shadowIndex) + externalIndex) + sampler.type) + sampler.dim; } TPrecisionQualifier TParseContext::getDefaultPrecision(TPublicType& publicType) { if (publicType.basicType == EbtSampler) return defaultSamplerPrecision[computeSamplerTypeIndex(publicType.sampler)]; else return defaultPrecision[publicType.basicType]; } void TParseContext::precisionQualifierCheck(const TSourceLoc& loc, TBasicType baseType, TQualifier& qualifier) { // Built-in symbols are allowed some ambiguous precisions, to be pinned down // later by context. if (profile != EEsProfile || parsingBuiltins) return; if (baseType == EbtAtomicUint && qualifier.precision != EpqNone && qualifier.precision != EpqHigh) error(loc, "atomic counters can only be highp", "atomic_uint", ""); if (baseType == EbtFloat || baseType == EbtUint || baseType == EbtInt || baseType == EbtSampler || baseType == EbtAtomicUint) { if (qualifier.precision == EpqNone) { if (relaxedErrors()) warn(loc, "type requires declaration of default precision qualifier", TType::getBasicString(baseType), "substituting 'mediump'"); else error(loc, "type requires declaration of default precision qualifier", TType::getBasicString(baseType), ""); qualifier.precision = EpqMedium; defaultPrecision[baseType] = EpqMedium; } } else if (qualifier.precision != EpqNone) error(loc, "type cannot have precision qualifier", TType::getBasicString(baseType), ""); } void TParseContext::parameterTypeCheck(const TSourceLoc& loc, TStorageQualifier qualifier, const TType& type) { if ((qualifier == EvqOut || qualifier == EvqInOut) && (type.getBasicType() == EbtSampler || type.getBasicType() == EbtAtomicUint)) error(loc, "samplers and atomic_uints cannot be output parameters", type.getBasicTypeString().c_str(), ""); } bool TParseContext::containsFieldWithBasicType(const TType& type, TBasicType basicType) { if (type.getBasicType() == basicType) return true; if (type.getBasicType() == EbtStruct) { const TTypeList& structure = *type.getStruct(); for (unsigned int i = 0; i < structure.size(); ++i) { if (containsFieldWithBasicType(*structure[i].type, basicType)) return true; } } return false; } // // Do size checking for an array type's size. // void TParseContext::arraySizeCheck(const TSourceLoc& loc, TIntermTyped* expr, TArraySize& sizePair) { bool isConst = false; sizePair.size = 1; sizePair.node = nullptr; TIntermConstantUnion* constant = expr->getAsConstantUnion(); if (constant) { // handle true (non-specialization) constant sizePair.size = constant->getConstArray()[0].getIConst(); isConst = true; } else { // see if it's a specialization constant instead if (expr->getQualifier().isSpecConstant()) { isConst = true; sizePair.node = expr; TIntermSymbol* symbol = expr->getAsSymbolNode(); if (symbol && symbol->getConstArray().size() > 0) sizePair.size = symbol->getConstArray()[0].getIConst(); } } if (! isConst || (expr->getBasicType() != EbtInt && expr->getBasicType() != EbtUint)) { error(loc, "array size must be a constant integer expression", "", ""); return; } if (sizePair.size <= 0) { error(loc, "array size must be a positive integer", "", ""); return; } } // // See if this qualifier can be an array. // // Returns true if there is an error. // bool TParseContext::arrayQualifierError(const TSourceLoc& loc, const TQualifier& qualifier) { if (qualifier.storage == EvqConst) { profileRequires(loc, ENoProfile, 120, E_GL_3DL_array_objects, "const array"); profileRequires(loc, EEsProfile, 300, nullptr, "const array"); } if (qualifier.storage == EvqVaryingIn && language == EShLangVertex) { requireProfile(loc, ~EEsProfile, "vertex input arrays"); profileRequires(loc, ENoProfile, 150, nullptr, "vertex input arrays"); } return false; } // // See if this qualifier and type combination can be an array. // Assumes arrayQualifierError() was also called to catch the type-invariant tests. // // Returns true if there is an error. // bool TParseContext::arrayError(const TSourceLoc& loc, const TType& type) { if (type.getQualifier().storage == EvqVaryingOut && language == EShLangVertex) { if (type.isArrayOfArrays()) requireProfile(loc, ~EEsProfile, "vertex-shader array-of-array output"); else if (type.isStruct()) requireProfile(loc, ~EEsProfile, "vertex-shader array-of-struct output"); } if (type.getQualifier().storage == EvqVaryingIn && language == EShLangFragment) { if (type.isArrayOfArrays()) requireProfile(loc, ~EEsProfile, "fragment-shader array-of-array input"); else if (type.isStruct()) requireProfile(loc, ~EEsProfile, "fragment-shader array-of-struct input"); } if (type.getQualifier().storage == EvqVaryingOut && language == EShLangFragment) { if (type.isArrayOfArrays()) requireProfile(loc, ~EEsProfile, "fragment-shader array-of-array output"); } return false; } // // Require array to be completely sized // void TParseContext::arraySizeRequiredCheck(const TSourceLoc& loc, const TArraySizes& arraySizes) { if (arraySizes.isImplicit()) error(loc, "array size required", "", ""); } void TParseContext::structArrayCheck(const TSourceLoc& /*loc*/, const TType& type) { const TTypeList& structure = *type.getStruct(); for (int m = 0; m < (int)structure.size(); ++m) { const TType& member = *structure[m].type; if (member.isArray()) arraySizeRequiredCheck(structure[m].loc, *member.getArraySizes()); } } void TParseContext::arrayUnsizedCheck(const TSourceLoc& loc, const TQualifier& qualifier, const TArraySizes* arraySizes, bool initializer, bool lastMember) { assert(arraySizes); // always allow special built-in ins/outs sized to topologies if (parsingBuiltins) return; // always allow an initializer to set any unknown array sizes if (initializer) return; // No environment lets any non-outer-dimension that's to be implicitly sized if (arraySizes->isInnerImplicit()) error(loc, "only outermost dimension of an array of arrays can be implicitly sized", "[]", ""); // desktop always allows outer-dimension-unsized variable arrays, if (profile != EEsProfile) return; // for ES, if size isn't coming from an initializer, it has to be explicitly declared now, // with very few exceptions // last member of ssbo block exception: if (qualifier.storage == EvqBuffer && lastMember) return; // implicitly-sized io exceptions: switch (language) { case EShLangGeometry: if (qualifier.storage == EvqVaryingIn) if (extensionsTurnedOn(Num_AEP_geometry_shader, AEP_geometry_shader)) return; break; case EShLangTessControl: if ( qualifier.storage == EvqVaryingIn || (qualifier.storage == EvqVaryingOut && ! qualifier.patch)) if (extensionsTurnedOn(Num_AEP_tessellation_shader, AEP_tessellation_shader)) return; break; case EShLangTessEvaluation: if ((qualifier.storage == EvqVaryingIn && ! qualifier.patch) || qualifier.storage == EvqVaryingOut) if (extensionsTurnedOn(Num_AEP_tessellation_shader, AEP_tessellation_shader)) return; break; default: break; } arraySizeRequiredCheck(loc, *arraySizes); } void TParseContext::arrayOfArrayVersionCheck(const TSourceLoc& loc) { const char* feature = "arrays of arrays"; requireProfile(loc, EEsProfile | ECoreProfile | ECompatibilityProfile, feature); profileRequires(loc, EEsProfile, 310, nullptr, feature); profileRequires(loc, ECoreProfile | ECompatibilityProfile, 430, nullptr, feature); } void TParseContext::arrayDimCheck(const TSourceLoc& loc, const TArraySizes* sizes1, const TArraySizes* sizes2) { if ((sizes1 && sizes2) || (sizes1 && sizes1->getNumDims() > 1) || (sizes2 && sizes2->getNumDims() > 1)) arrayOfArrayVersionCheck(loc); } void TParseContext::arrayDimCheck(const TSourceLoc& loc, const TType* type, const TArraySizes* sizes2) { // skip checking for multiple dimensions on the type; it was caught earlier if ((type && type->isArray() && sizes2) || (sizes2 && sizes2->getNumDims() > 1)) arrayOfArrayVersionCheck(loc); } // Merge array dimensions listed in 'sizes' onto the type's array dimensions. // // From the spec: "vec4[2] a[3]; // size-3 array of size-2 array of vec4" // // That means, the 'sizes' go in front of the 'type' as outermost sizes. // 'type' is the type part of the declaration (to the left) // 'sizes' is the arrayness tagged on the identifier (to the right) // void TParseContext::arrayDimMerge(TType& type, const TArraySizes* sizes) { if (sizes) type.addArrayOuterSizes(*sizes); } // // Do all the semantic checking for declaring or redeclaring an array, with and // without a size, and make the right changes to the symbol table. // void TParseContext::declareArray(const TSourceLoc& loc, TString& identifier, const TType& type, TSymbol*& symbol, bool& newDeclaration) { if (! symbol) { bool currentScope; symbol = symbolTable.find(identifier, nullptr, &currentScope); if (symbol && builtInName(identifier) && ! symbolTable.atBuiltInLevel()) { // bad shader (errors already reported) trying to redeclare a built-in name as an array return; } if (symbol == nullptr || ! currentScope) { // // Successfully process a new definition. // (Redeclarations have to take place at the same scope; otherwise they are hiding declarations) // symbol = new TVariable(&identifier, type); symbolTable.insert(*symbol); newDeclaration = true; if (! symbolTable.atBuiltInLevel()) { if (isIoResizeArray(type)) { ioArraySymbolResizeList.push_back(symbol); checkIoArraysConsistency(loc, true); } else fixIoArraySize(loc, symbol->getWritableType()); } return; } if (symbol->getAsAnonMember()) { error(loc, "cannot redeclare a user-block member array", identifier.c_str(), ""); symbol = nullptr; return; } } // // Process a redeclaration. // if (! symbol) { error(loc, "array variable name expected", identifier.c_str(), ""); return; } // redeclareBuiltinVariable() should have already done the copyUp() TType& existingType = symbol->getWritableType(); if (! existingType.isArray()) { error(loc, "redeclaring non-array as array", identifier.c_str(), ""); return; } if (! existingType.sameElementType(type)) { error(loc, "redeclaration of array with a different element type", identifier.c_str(), ""); return; } if (! existingType.sameInnerArrayness(type)) { error(loc, "redeclaration of array with a different array dimensions or sizes", identifier.c_str(), ""); return; } if (existingType.isExplicitlySizedArray()) { // be more leniant for input arrays to geometry shaders and tessellation control outputs, where the redeclaration is the same size if (! (isIoResizeArray(type) && existingType.getOuterArraySize() == type.getOuterArraySize())) error(loc, "redeclaration of array with size", identifier.c_str(), ""); return; } arrayLimitCheck(loc, identifier, type.getOuterArraySize()); existingType.updateArraySizes(type); if (isIoResizeArray(type)) checkIoArraysConsistency(loc); } void TParseContext::updateImplicitArraySize(const TSourceLoc& loc, TIntermNode *node, int index) { // maybe there is nothing to do... TIntermTyped* typedNode = node->getAsTyped(); if (typedNode->getType().getImplicitArraySize() > index) return; // something to do... // Figure out what symbol to lookup, as we will use its type to edit for the size change, // as that type will be shared through shallow copies for future references. TSymbol* symbol = nullptr; int blockIndex = -1; const TString* lookupName = nullptr; if (node->getAsSymbolNode()) lookupName = &node->getAsSymbolNode()->getName(); else if (node->getAsBinaryNode()) { const TIntermBinary* deref = node->getAsBinaryNode(); // This has to be the result of a block dereference, unless it's bad shader code // If it's a uniform block, then an error will be issued elsewhere, but // return early now to avoid crashing later in this function. if (! deref->getLeft()->getAsSymbolNode() || deref->getLeft()->getBasicType() != EbtBlock || deref->getLeft()->getType().getQualifier().storage == EvqUniform || deref->getRight()->getAsConstantUnion() == nullptr) return; blockIndex = deref->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst(); lookupName = &deref->getLeft()->getAsSymbolNode()->getName(); if (IsAnonymous(*lookupName)) lookupName = &(*deref->getLeft()->getType().getStruct())[blockIndex].type->getFieldName(); } // Lookup the symbol, should only fail if shader code is incorrect symbol = symbolTable.find(*lookupName); if (symbol == nullptr) return; if (symbol->getAsFunction()) { error(loc, "array variable name expected", symbol->getName().c_str(), ""); return; } symbol->getWritableType().setImplicitArraySize(index + 1); } // Returns true if the first argument to the #line directive is the line number for the next line. // // Desktop, pre-version 3.30: "After processing this directive // (including its new-line), the implementation will behave as if it is compiling at line number line+1 and // source string number source-string-number." // // Desktop, version 3.30 and later, and ES: "After processing this directive // (including its new-line), the implementation will behave as if it is compiling at line number line and // source string number source-string-number. bool TParseContext::lineDirectiveShouldSetNextLine() const { return profile == EEsProfile || version >= 330; } // // Enforce non-initializer type/qualifier rules. // void TParseContext::nonInitConstCheck(const TSourceLoc& loc, TString& identifier, TType& type) { // // Make the qualifier make sense, given that there is an initializer. // if (type.getQualifier().storage == EvqConst || type.getQualifier().storage == EvqConstReadOnly) { type.getQualifier().storage = EvqTemporary; error(loc, "variables with qualifier 'const' must be initialized", identifier.c_str(), ""); } } // // See if the identifier is a built-in symbol that can be redeclared, and if so, // copy the symbol table's read-only built-in variable to the current // global level, where it can be modified based on the passed in type. // // Returns nullptr if no redeclaration took place; meaning a normal declaration still // needs to occur for it, not necessarily an error. // // Returns a redeclared and type-modified variable if a redeclarated occurred. // TSymbol* TParseContext::redeclareBuiltinVariable(const TSourceLoc& loc, const TString& identifier, const TQualifier& qualifier, const TShaderQualifiers& publicType, bool& newDeclaration) { if (! builtInName(identifier) || symbolTable.atBuiltInLevel() || ! symbolTable.atGlobalLevel()) return nullptr; bool nonEsRedecls = (profile != EEsProfile && (version >= 130 || identifier == "gl_TexCoord")); bool esRedecls = (profile == EEsProfile && extensionsTurnedOn(Num_AEP_shader_io_blocks, AEP_shader_io_blocks)); if (! esRedecls && ! nonEsRedecls) return nullptr; // Special case when using GL_ARB_separate_shader_objects bool ssoPre150 = false; // means the only reason this variable is redeclared is due to this combination if (profile != EEsProfile && version <= 140 && extensionTurnedOn(E_GL_ARB_separate_shader_objects)) { if (identifier == "gl_Position" || identifier == "gl_PointSize" || identifier == "gl_ClipVertex" || identifier == "gl_FogFragCoord") ssoPre150 = true; } // Potentially redeclaring a built-in variable... if (ssoPre150 || (identifier == "gl_FragDepth" && ((nonEsRedecls && version >= 420) || esRedecls)) || (identifier == "gl_FragCoord" && ((nonEsRedecls && version >= 150) || esRedecls)) || identifier == "gl_ClipDistance" || identifier == "gl_FrontColor" || identifier == "gl_BackColor" || identifier == "gl_FrontSecondaryColor" || identifier == "gl_BackSecondaryColor" || identifier == "gl_SecondaryColor" || (identifier == "gl_Color" && language == EShLangFragment) || identifier == "gl_TexCoord") { // Find the existing symbol, if any. bool builtIn; TSymbol* symbol = symbolTable.find(identifier, &builtIn); // If the symbol was not found, this must be a version/profile/stage // that doesn't have it. if (! symbol) return nullptr; // If it wasn't at a built-in level, then it's already been redeclared; // that is, this is a redeclaration of a redeclaration; reuse that initial // redeclaration. Otherwise, make the new one. if (builtIn) { // Copy the symbol up to make a writable version makeEditable(symbol); newDeclaration = true; } // Now, modify the type of the copy, as per the type of the current redeclaration. TQualifier& symbolQualifier = symbol->getWritableType().getQualifier(); if (ssoPre150) { if (intermediate.inIoAccessed(identifier)) error(loc, "cannot redeclare after use", identifier.c_str(), ""); if (qualifier.hasLayout()) error(loc, "cannot apply layout qualifier to", "redeclaration", symbol->getName().c_str()); if (qualifier.isMemory() || qualifier.isAuxiliary() || (language == EShLangVertex && qualifier.storage != EvqVaryingOut) || (language == EShLangFragment && qualifier.storage != EvqVaryingIn)) error(loc, "cannot change storage, memory, or auxiliary qualification of", "redeclaration", symbol->getName().c_str()); if (! qualifier.smooth) error(loc, "cannot change interpolation qualification of", "redeclaration", symbol->getName().c_str()); } else if (identifier == "gl_FrontColor" || identifier == "gl_BackColor" || identifier == "gl_FrontSecondaryColor" || identifier == "gl_BackSecondaryColor" || identifier == "gl_SecondaryColor" || identifier == "gl_Color") { symbolQualifier.flat = qualifier.flat; symbolQualifier.smooth = qualifier.smooth; symbolQualifier.nopersp = qualifier.nopersp; if (qualifier.hasLayout()) error(loc, "cannot apply layout qualifier to", "redeclaration", symbol->getName().c_str()); if (qualifier.isMemory() || qualifier.isAuxiliary() || symbol->getType().getQualifier().storage != qualifier.storage) error(loc, "cannot change storage, memory, or auxiliary qualification of", "redeclaration", symbol->getName().c_str()); } else if (identifier == "gl_TexCoord" || identifier == "gl_ClipDistance") { if (qualifier.hasLayout() || qualifier.isMemory() || qualifier.isAuxiliary() || qualifier.nopersp != symbolQualifier.nopersp || qualifier.flat != symbolQualifier.flat || symbolQualifier.storage != qualifier.storage) error(loc, "cannot change qualification of", "redeclaration", symbol->getName().c_str()); } else if (identifier == "gl_FragCoord") { if (intermediate.inIoAccessed("gl_FragCoord")) error(loc, "cannot redeclare after use", "gl_FragCoord", ""); if (qualifier.nopersp != symbolQualifier.nopersp || qualifier.flat != symbolQualifier.flat || qualifier.isMemory() || qualifier.isAuxiliary()) error(loc, "can only change layout qualification of", "redeclaration", symbol->getName().c_str()); if (qualifier.storage != EvqVaryingIn) error(loc, "cannot change input storage qualification of", "redeclaration", symbol->getName().c_str()); if (! builtIn && (publicType.pixelCenterInteger != intermediate.getPixelCenterInteger() || publicType.originUpperLeft != intermediate.getOriginUpperLeft())) error(loc, "cannot redeclare with different qualification:", "redeclaration", symbol->getName().c_str()); if (publicType.pixelCenterInteger) intermediate.setPixelCenterInteger(); if (publicType.originUpperLeft) intermediate.setOriginUpperLeft(); } else if (identifier == "gl_FragDepth") { if (qualifier.nopersp != symbolQualifier.nopersp || qualifier.flat != symbolQualifier.flat || qualifier.isMemory() || qualifier.isAuxiliary()) error(loc, "can only change layout qualification of", "redeclaration", symbol->getName().c_str()); if (qualifier.storage != EvqVaryingOut) error(loc, "cannot change output storage qualification of", "redeclaration", symbol->getName().c_str()); if (publicType.layoutDepth != EldNone) { if (intermediate.inIoAccessed("gl_FragDepth")) error(loc, "cannot redeclare after use", "gl_FragDepth", ""); if (! intermediate.setDepth(publicType.layoutDepth)) error(loc, "all redeclarations must use the same depth layout on", "redeclaration", symbol->getName().c_str()); } } // TODO: semantics quality: separate smooth from nothing declared, then use IsInterpolation for several tests above return symbol; } return nullptr; } // // Either redeclare the requested block, or give an error message why it can't be done. // // TODO: functionality: explicitly sizing members of redeclared blocks is not giving them an explicit size void TParseContext::redeclareBuiltinBlock(const TSourceLoc& loc, TTypeList& newTypeList, const TString& blockName, const TString* instanceName, TArraySizes* arraySizes) { const char* feature = "built-in block redeclaration"; profileRequires(loc, EEsProfile, 0, Num_AEP_shader_io_blocks, AEP_shader_io_blocks, feature); profileRequires(loc, ~EEsProfile, 410, E_GL_ARB_separate_shader_objects, feature); if (blockName != "gl_PerVertex" && blockName != "gl_PerFragment") { error(loc, "cannot redeclare block: ", "block declaration", blockName.c_str()); return; } // Redeclaring a built-in block... if (instanceName && ! builtInName(*instanceName)) { error(loc, "cannot redeclare a built-in block with a user name", instanceName->c_str(), ""); return; } // Blocks with instance names are easy to find, lookup the instance name, // Anonymous blocks need to be found via a member. bool builtIn; TSymbol* block; if (instanceName) block = symbolTable.find(*instanceName, &builtIn); else block = symbolTable.find(newTypeList.front().type->getFieldName(), &builtIn); // If the block was not found, this must be a version/profile/stage // that doesn't have it, or the instance name is wrong. const char* errorName = instanceName ? instanceName->c_str() : newTypeList.front().type->getFieldName().c_str(); if (! block) { error(loc, "no declaration found for redeclaration", errorName, ""); return; } // Built-in blocks cannot be redeclared more than once, which if happened, // we'd be finding the already redeclared one here, rather than the built in. if (! builtIn) { error(loc, "can only redeclare a built-in block once, and before any use", blockName.c_str(), ""); return; } // Copy the block to make a writable version, to insert into the block table after editing. block = symbolTable.copyUpDeferredInsert(block); if (block->getType().getBasicType() != EbtBlock) { error(loc, "cannot redeclare a non block as a block", errorName, ""); return; } // Edit and error check the container against the redeclaration // - remove unused members // - ensure remaining qualifiers/types match TType& type = block->getWritableType(); TTypeList::iterator member = type.getWritableStruct()->begin(); size_t numOriginalMembersFound = 0; while (member != type.getStruct()->end()) { // look for match bool found = false; TTypeList::const_iterator newMember; TSourceLoc memberLoc; memberLoc.init(); for (newMember = newTypeList.begin(); newMember != newTypeList.end(); ++newMember) { if (member->type->getFieldName() == newMember->type->getFieldName()) { found = true; memberLoc = newMember->loc; break; } } if (found) { ++numOriginalMembersFound; // - ensure match between redeclared members' types // - check for things that can't be changed // - update things that can be changed TType& oldType = *member->type; const TType& newType = *newMember->type; if (! newType.sameElementType(oldType)) error(memberLoc, "cannot redeclare block member with a different type", member->type->getFieldName().c_str(), ""); if (oldType.isArray() != newType.isArray()) error(memberLoc, "cannot change arrayness of redeclared block member", member->type->getFieldName().c_str(), ""); else if (! oldType.sameArrayness(newType) && oldType.isExplicitlySizedArray()) error(memberLoc, "cannot change array size of redeclared block member", member->type->getFieldName().c_str(), ""); else if (newType.isArray()) arrayLimitCheck(loc, member->type->getFieldName(), newType.getOuterArraySize()); if (newType.getQualifier().isMemory()) error(memberLoc, "cannot add memory qualifier to redeclared block member", member->type->getFieldName().c_str(), ""); if (newType.getQualifier().hasLayout()) error(memberLoc, "cannot add layout to redeclared block member", member->type->getFieldName().c_str(), ""); if (newType.getQualifier().patch) error(memberLoc, "cannot add patch to redeclared block member", member->type->getFieldName().c_str(), ""); oldType.getQualifier().centroid = newType.getQualifier().centroid; oldType.getQualifier().sample = newType.getQualifier().sample; oldType.getQualifier().invariant = newType.getQualifier().invariant; oldType.getQualifier().smooth = newType.getQualifier().smooth; oldType.getQualifier().flat = newType.getQualifier().flat; oldType.getQualifier().nopersp = newType.getQualifier().nopersp; // go to next member ++member; } else { // For missing members of anonymous blocks that have been redeclared, // hide the original (shared) declaration. // Instance-named blocks can just have the member removed. if (instanceName) member = type.getWritableStruct()->erase(member); else { member->type->hideMember(); ++member; } } } if (numOriginalMembersFound < newTypeList.size()) error(loc, "block redeclaration has extra members", blockName.c_str(), ""); if (type.isArray() != (arraySizes != nullptr)) error(loc, "cannot change arrayness of redeclared block", blockName.c_str(), ""); else if (type.isArray()) { if (type.isExplicitlySizedArray() && arraySizes->getOuterSize() == UnsizedArraySize) error(loc, "block already declared with size, can't redeclare as implicitly-sized", blockName.c_str(), ""); else if (type.isExplicitlySizedArray() && type.getArraySizes() != *arraySizes) error(loc, "cannot change array size of redeclared block", blockName.c_str(), ""); else if (type.isImplicitlySizedArray() && arraySizes->getOuterSize() != UnsizedArraySize) type.changeOuterArraySize(arraySizes->getOuterSize()); } symbolTable.insert(*block); // Check for general layout qualifier errors layoutObjectCheck(loc, *block); // Tracking for implicit sizing of array if (isIoResizeArray(block->getType())) { ioArraySymbolResizeList.push_back(block); checkIoArraysConsistency(loc, true); } else if (block->getType().isArray()) fixIoArraySize(loc, block->getWritableType()); // Save it in the AST for linker use. intermediate.addSymbolLinkageNode(linkage, *block); } void TParseContext::paramCheckFix(const TSourceLoc& loc, const TStorageQualifier& qualifier, TType& type) { switch (qualifier) { case EvqConst: case EvqConstReadOnly: type.getQualifier().storage = EvqConstReadOnly; break; case EvqIn: case EvqOut: case EvqInOut: type.getQualifier().storage = qualifier; break; case EvqGlobal: case EvqTemporary: type.getQualifier().storage = EvqIn; break; default: type.getQualifier().storage = EvqIn; error(loc, "storage qualifier not allowed on function parameter", GetStorageQualifierString(qualifier), ""); break; } } void TParseContext::paramCheckFix(const TSourceLoc& loc, const TQualifier& qualifier, TType& type) { if (qualifier.isMemory()) { type.getQualifier().volatil = qualifier.volatil; type.getQualifier().coherent = qualifier.coherent; type.getQualifier().readonly = qualifier.readonly; type.getQualifier().writeonly = qualifier.writeonly; type.getQualifier().restrict = qualifier.restrict; } if (qualifier.isAuxiliary() || qualifier.isInterpolation()) error(loc, "cannot use auxiliary or interpolation qualifiers on a function parameter", "", ""); if (qualifier.hasLayout()) error(loc, "cannot use layout qualifiers on a function parameter", "", ""); if (qualifier.invariant) error(loc, "cannot use invariant qualifier on a function parameter", "", ""); paramCheckFix(loc, qualifier.storage, type); } void TParseContext::nestedBlockCheck(const TSourceLoc& loc) { if (structNestingLevel > 0) error(loc, "cannot nest a block definition inside a structure or block", "", ""); ++structNestingLevel; } void TParseContext::nestedStructCheck(const TSourceLoc& loc) { if (structNestingLevel > 0) error(loc, "cannot nest a structure definition inside a structure or block", "", ""); ++structNestingLevel; } void TParseContext::arrayObjectCheck(const TSourceLoc& loc, const TType& type, const char* op) { // Some versions don't allow comparing arrays or structures containing arrays if (type.containsArray()) { profileRequires(loc, ENoProfile, 120, E_GL_3DL_array_objects, op); profileRequires(loc, EEsProfile, 300, nullptr, op); } } void TParseContext::opaqueCheck(const TSourceLoc& loc, const TType& type, const char* op) { if (containsFieldWithBasicType(type, EbtSampler)) error(loc, "can't use with samplers or structs containing samplers", op, ""); } void TParseContext::structTypeCheck(const TSourceLoc& /*loc*/, TPublicType& publicType) { const TTypeList& typeList = *publicType.userDef->getStruct(); // fix and check for member storage qualifiers and types that don't belong within a structure for (unsigned int member = 0; member < typeList.size(); ++member) { TQualifier& memberQualifier = typeList[member].type->getQualifier(); const TSourceLoc& memberLoc = typeList[member].loc; if (memberQualifier.isAuxiliary() || memberQualifier.isInterpolation() || (memberQualifier.storage != EvqTemporary && memberQualifier.storage != EvqGlobal)) error(memberLoc, "cannot use storage or interpolation qualifiers on structure members", typeList[member].type->getFieldName().c_str(), ""); if (memberQualifier.isMemory()) error(memberLoc, "cannot use memory qualifiers on structure members", typeList[member].type->getFieldName().c_str(), ""); if (memberQualifier.hasLayout()) { error(memberLoc, "cannot use layout qualifiers on structure members", typeList[member].type->getFieldName().c_str(), ""); memberQualifier.clearLayout(); } if (memberQualifier.invariant) error(memberLoc, "cannot use invariant qualifier on structure members", typeList[member].type->getFieldName().c_str(), ""); } } // // See if this loop satisfies the limitations for ES 2.0 (version 100) for loops in Appendex A: // // "The loop index has type int or float. // // "The for statement has the form: // for ( init-declaration ; condition ; expression ) // init-declaration has the form: type-specifier identifier = constant-expression // condition has the form: loop-index relational_operator constant-expression // where relational_operator is one of: > >= < <= == or != // expression [sic] has one of the following forms: // loop-index++ // loop-index-- // loop-index += constant-expression // loop-index -= constant-expression // // The body is handled in an AST traversal. // void TParseContext::inductiveLoopCheck(const TSourceLoc& loc, TIntermNode* init, TIntermLoop* loop) { // loop index init must exist and be a declaration, which shows up in the AST as an aggregate of size 1 of the declaration bool badInit = false; if (! init || ! init->getAsAggregate() || init->getAsAggregate()->getSequence().size() != 1) badInit = true; TIntermBinary* binaryInit = 0; if (! badInit) { // get the declaration assignment binaryInit = init->getAsAggregate()->getSequence()[0]->getAsBinaryNode(); if (! binaryInit) badInit = true; } if (badInit) { error(loc, "inductive-loop init-declaration requires the form \"type-specifier loop-index = constant-expression\"", "limitations", ""); return; } // loop index must be type int or float if (! binaryInit->getType().isScalar() || (binaryInit->getBasicType() != EbtInt && binaryInit->getBasicType() != EbtFloat)) { error(loc, "inductive loop requires a scalar 'int' or 'float' loop index", "limitations", ""); return; } // init is the form "loop-index = constant" if (binaryInit->getOp() != EOpAssign || ! binaryInit->getLeft()->getAsSymbolNode() || ! binaryInit->getRight()->getAsConstantUnion()) { error(loc, "inductive-loop init-declaration requires the form \"type-specifier loop-index = constant-expression\"", "limitations", ""); return; } // get the unique id of the loop index int loopIndex = binaryInit->getLeft()->getAsSymbolNode()->getId(); inductiveLoopIds.insert(loopIndex); // condition's form must be "loop-index relational-operator constant-expression" bool badCond = ! loop->getTest(); if (! badCond) { TIntermBinary* binaryCond = loop->getTest()->getAsBinaryNode(); badCond = ! binaryCond; if (! badCond) { switch (binaryCond->getOp()) { case EOpGreaterThan: case EOpGreaterThanEqual: case EOpLessThan: case EOpLessThanEqual: case EOpEqual: case EOpNotEqual: break; default: badCond = true; } } if (binaryCond && (! binaryCond->getLeft()->getAsSymbolNode() || binaryCond->getLeft()->getAsSymbolNode()->getId() != loopIndex || ! binaryCond->getRight()->getAsConstantUnion())) badCond = true; } if (badCond) { error(loc, "inductive-loop condition requires the form \"loop-index <comparison-op> constant-expression\"", "limitations", ""); return; } // loop-index++ // loop-index-- // loop-index += constant-expression // loop-index -= constant-expression bool badTerminal = ! loop->getTerminal(); if (! badTerminal) { TIntermUnary* unaryTerminal = loop->getTerminal()->getAsUnaryNode(); TIntermBinary* binaryTerminal = loop->getTerminal()->getAsBinaryNode(); if (unaryTerminal || binaryTerminal) { switch(loop->getTerminal()->getAsOperator()->getOp()) { case EOpPostDecrement: case EOpPostIncrement: case EOpAddAssign: case EOpSubAssign: break; default: badTerminal = true; } } else badTerminal = true; if (binaryTerminal && (! binaryTerminal->getLeft()->getAsSymbolNode() || binaryTerminal->getLeft()->getAsSymbolNode()->getId() != loopIndex || ! binaryTerminal->getRight()->getAsConstantUnion())) badTerminal = true; if (unaryTerminal && (! unaryTerminal->getOperand()->getAsSymbolNode() || unaryTerminal->getOperand()->getAsSymbolNode()->getId() != loopIndex)) badTerminal = true; } if (badTerminal) { error(loc, "inductive-loop termination requires the form \"loop-index++, loop-index--, loop-index += constant-expression, or loop-index -= constant-expression\"", "limitations", ""); return; } // the body inductiveLoopBodyCheck(loop->getBody(), loopIndex, symbolTable); } // Do limit checks for built-in arrays. void TParseContext::arrayLimitCheck(const TSourceLoc& loc, const TString& identifier, int size) { if (identifier.compare("gl_TexCoord") == 0) limitCheck(loc, size, "gl_MaxTextureCoords", "gl_TexCoord array size"); else if (identifier.compare("gl_ClipDistance") == 0) limitCheck(loc, size, "gl_MaxClipDistances", "gl_ClipDistance array size"); } // See if the provided value is less than the symbol indicated by limit, // which should be a constant in the symbol table. void TParseContext::limitCheck(const TSourceLoc& loc, int value, const char* limit, const char* feature) { TSymbol* symbol = symbolTable.find(limit); assert(symbol->getAsVariable()); const TConstUnionArray& constArray = symbol->getAsVariable()->getConstArray(); assert(! constArray.empty()); if (value >= constArray[0].getIConst()) error(loc, "must be less than", feature, "%s (%d)", limit, constArray[0].getIConst()); } // // Do any additional error checking, etc., once we know the parsing is done. // void TParseContext::finalErrorCheck() { // Check on array indexes for ES 2.0 (version 100) limitations. for (size_t i = 0; i < needsIndexLimitationChecking.size(); ++i) constantIndexExpressionCheck(needsIndexLimitationChecking[i]); // Check for stages that are enabled by extension. // Can't do this at the beginning, it is chicken and egg to add a stage by // extension. // Stage-specific features were correctly tested for already, this is just // about the stage itself. switch (language) { case EShLangGeometry: if (profile == EEsProfile && version == 310) requireExtensions(getCurrentLoc(), Num_AEP_geometry_shader, AEP_geometry_shader, "geometry shaders"); break; case EShLangTessControl: case EShLangTessEvaluation: if (profile == EEsProfile && version == 310) requireExtensions(getCurrentLoc(), Num_AEP_tessellation_shader, AEP_tessellation_shader, "tessellation shaders"); else if (profile != EEsProfile && version < 400) requireExtensions(getCurrentLoc(), 1, &E_GL_ARB_tessellation_shader, "tessellation shaders"); break; case EShLangCompute: if (profile != EEsProfile && version < 430) requireExtensions(getCurrentLoc(), 1, &E_GL_ARB_compute_shader, "tessellation shaders"); break; default: break; } } // // Layout qualifier stuff. // // Put the id's layout qualification into the public type, for qualifiers not having a number set. // This is before we know any type information for error checking. void TParseContext::setLayoutQualifier(const TSourceLoc& loc, TPublicType& publicType, TString& id) { std::transform(id.begin(), id.end(), id.begin(), ::tolower); if (id == TQualifier::getLayoutMatrixString(ElmColumnMajor)) { publicType.qualifier.layoutMatrix = ElmColumnMajor; return; } if (id == TQualifier::getLayoutMatrixString(ElmRowMajor)) { publicType.qualifier.layoutMatrix = ElmRowMajor; return; } if (id == TQualifier::getLayoutPackingString(ElpPacked)) { if (vulkan > 0) vulkanRemoved(loc, "packed"); publicType.qualifier.layoutPacking = ElpPacked; return; } if (id == TQualifier::getLayoutPackingString(ElpShared)) { if (vulkan > 0) vulkanRemoved(loc, "shared"); publicType.qualifier.layoutPacking = ElpShared; return; } if (id == TQualifier::getLayoutPackingString(ElpStd140)) { publicType.qualifier.layoutPacking = ElpStd140; return; } if (id == TQualifier::getLayoutPackingString(ElpStd430)) { requireProfile(loc, EEsProfile | ECoreProfile | ECompatibilityProfile, "std430"); profileRequires(loc, ECoreProfile | ECompatibilityProfile, 430, nullptr, "std430"); profileRequires(loc, EEsProfile, 310, nullptr, "std430"); publicType.qualifier.layoutPacking = ElpStd430; return; } // TODO: compile-time performance: may need to stop doing linear searches for (TLayoutFormat format = (TLayoutFormat)(ElfNone + 1); format < ElfCount; format = (TLayoutFormat)(format + 1)) { if (id == TQualifier::getLayoutFormatString(format)) { if ((format > ElfEsFloatGuard && format < ElfFloatGuard) || (format > ElfEsIntGuard && format < ElfIntGuard) || (format > ElfEsUintGuard && format < ElfCount)) requireProfile(loc, ENoProfile | ECoreProfile | ECompatibilityProfile, "image load-store format"); profileRequires(loc, ENoProfile | ECoreProfile | ECompatibilityProfile, 420, E_GL_ARB_shader_image_load_store, "image load store"); profileRequires(loc, EEsProfile, 310, E_GL_ARB_shader_image_load_store, "image load store"); publicType.qualifier.layoutFormat = format; return; } } if (id == "push_constant") { requireVulkan(loc, "push_constant"); publicType.qualifier.layoutPushConstant = true; return; } if (language == EShLangGeometry || language == EShLangTessEvaluation) { if (id == TQualifier::getGeometryString(ElgTriangles)) { publicType.shaderQualifiers.geometry = ElgTriangles; return; } if (language == EShLangGeometry) { if (id == TQualifier::getGeometryString(ElgPoints)) { publicType.shaderQualifiers.geometry = ElgPoints; return; } if (id == TQualifier::getGeometryString(ElgLineStrip)) { publicType.shaderQualifiers.geometry = ElgLineStrip; return; } if (id == TQualifier::getGeometryString(ElgLines)) { publicType.shaderQualifiers.geometry = ElgLines; return; } if (id == TQualifier::getGeometryString(ElgLinesAdjacency)) { publicType.shaderQualifiers.geometry = ElgLinesAdjacency; return; } if (id == TQualifier::getGeometryString(ElgTrianglesAdjacency)) { publicType.shaderQualifiers.geometry = ElgTrianglesAdjacency; return; } if (id == TQualifier::getGeometryString(ElgTriangleStrip)) { publicType.shaderQualifiers.geometry = ElgTriangleStrip; return; } } else { assert(language == EShLangTessEvaluation); // input primitive if (id == TQualifier::getGeometryString(ElgTriangles)) { publicType.shaderQualifiers.geometry = ElgTriangles; return; } if (id == TQualifier::getGeometryString(ElgQuads)) { publicType.shaderQualifiers.geometry = ElgQuads; return; } if (id == TQualifier::getGeometryString(ElgIsolines)) { publicType.shaderQualifiers.geometry = ElgIsolines; return; } // vertex spacing if (id == TQualifier::getVertexSpacingString(EvsEqual)) { publicType.shaderQualifiers.spacing = EvsEqual; return; } if (id == TQualifier::getVertexSpacingString(EvsFractionalEven)) { publicType.shaderQualifiers.spacing = EvsFractionalEven; return; } if (id == TQualifier::getVertexSpacingString(EvsFractionalOdd)) { publicType.shaderQualifiers.spacing = EvsFractionalOdd; return; } // triangle order if (id == TQualifier::getVertexOrderString(EvoCw)) { publicType.shaderQualifiers.order = EvoCw; return; } if (id == TQualifier::getVertexOrderString(EvoCcw)) { publicType.shaderQualifiers.order = EvoCcw; return; } // point mode if (id == "point_mode") { publicType.shaderQualifiers.pointMode = true; return; } } } if (language == EShLangFragment) { if (id == "origin_upper_left") { requireProfile(loc, ECoreProfile | ECompatibilityProfile, "origin_upper_left"); publicType.shaderQualifiers.originUpperLeft = true; return; } if (id == "pixel_center_integer") { requireProfile(loc, ECoreProfile | ECompatibilityProfile, "pixel_center_integer"); publicType.shaderQualifiers.pixelCenterInteger = true; return; } if (id == "early_fragment_tests") { profileRequires(loc, ENoProfile | ECoreProfile | ECompatibilityProfile, 420, E_GL_ARB_shader_image_load_store, "early_fragment_tests"); profileRequires(loc, EEsProfile, 310, nullptr, "early_fragment_tests"); publicType.shaderQualifiers.earlyFragmentTests = true; return; } for (TLayoutDepth depth = (TLayoutDepth)(EldNone + 1); depth < EldCount; depth = (TLayoutDepth)(depth+1)) { if (id == TQualifier::getLayoutDepthString(depth)) { requireProfile(loc, ECoreProfile | ECompatibilityProfile, "depth layout qualifier"); profileRequires(loc, ECoreProfile | ECompatibilityProfile, 420, nullptr, "depth layout qualifier"); publicType.shaderQualifiers.layoutDepth = depth; return; } } if (id.compare(0, 13, "blend_support") == 0) { bool found = false; for (TBlendEquationShift be = (TBlendEquationShift)0; be < EBlendCount; be = (TBlendEquationShift)(be + 1)) { if (id == TQualifier::getBlendEquationString(be)) { requireExtensions(loc, 1, &E_GL_KHR_blend_equation_advanced, "blend equation"); intermediate.addBlendEquation(be); publicType.shaderQualifiers.blendEquation = true; found = true; break; } } if (! found) error(loc, "unknown blend equation", "blend_support", ""); return; } } error(loc, "unrecognized layout identifier, or qualifier requires assignment (e.g., binding = 4)", id.c_str(), ""); } // Put the id's layout qualifier value into the public type, for qualifiers having a number set. // This is before we know any type information for error checking. void TParseContext::setLayoutQualifier(const TSourceLoc& loc, TPublicType& publicType, TString& id, const TIntermTyped* node) { const char* feature = "layout-id value"; const char* nonLiteralFeature = "non-literal layout-id value"; integerCheck(node, feature); const TIntermConstantUnion* constUnion = node->getAsConstantUnion(); int value; if (constUnion) { value = constUnion->getConstArray()[0].getIConst(); if (! constUnion->isLiteral()) { requireProfile(loc, ECoreProfile | ECompatibilityProfile, nonLiteralFeature); profileRequires(loc, ECoreProfile | ECompatibilityProfile, 440, E_GL_ARB_enhanced_layouts, nonLiteralFeature); } } else { // grammar should have give out the error message value = 0; } if (value < 0) { error(loc, "cannot be negative", feature, ""); return; } std::transform(id.begin(), id.end(), id.begin(), ::tolower); if (id == "offset") { const char* feature = "uniform offset"; requireProfile(loc, EEsProfile | ECoreProfile | ECompatibilityProfile, feature); const char* exts[2] = { E_GL_ARB_enhanced_layouts, E_GL_ARB_shader_atomic_counters }; profileRequires(loc, ECoreProfile | ECompatibilityProfile, 420, 2, exts, feature); profileRequires(loc, EEsProfile, 310, nullptr, feature); publicType.qualifier.layoutOffset = value; return; } else if (id == "align") { const char* feature = "uniform buffer-member align"; requireProfile(loc, ECoreProfile | ECompatibilityProfile, feature); profileRequires(loc, ECoreProfile | ECompatibilityProfile, 440, E_GL_ARB_enhanced_layouts, feature); // "The specified alignment must be a power of 2, or a compile-time error results." if (! IsPow2(value)) error(loc, "must be a power of 2", "align", ""); else publicType.qualifier.layoutAlign = value; return; } else if (id == "location") { profileRequires(loc, EEsProfile, 300, nullptr, "location"); const char* exts[2] = { E_GL_ARB_separate_shader_objects, E_GL_ARB_explicit_attrib_location }; profileRequires(loc, ~EEsProfile, 330, 2, exts, "location"); if ((unsigned int)value >= TQualifier::layoutLocationEnd) error(loc, "location is too large", id.c_str(), ""); else publicType.qualifier.layoutLocation = value; return; } else if (id == "set") { if ((unsigned int)value >= TQualifier::layoutSetEnd) error(loc, "set is too large", id.c_str(), ""); else publicType.qualifier.layoutSet = value; return; } else if (id == "binding") { profileRequires(loc, ~EEsProfile, 420, E_GL_ARB_shading_language_420pack, "binding"); profileRequires(loc, EEsProfile, 310, nullptr, "binding"); if ((unsigned int)value >= TQualifier::layoutBindingEnd) error(loc, "binding is too large", id.c_str(), ""); else publicType.qualifier.layoutBinding = value; return; } else if (id == "component") { requireProfile(loc, ECoreProfile | ECompatibilityProfile, "component"); profileRequires(loc, ECoreProfile | ECompatibilityProfile, 440, E_GL_ARB_enhanced_layouts, "component"); if ((unsigned)value >= TQualifier::layoutComponentEnd) error(loc, "component is too large", id.c_str(), ""); else publicType.qualifier.layoutComponent = value; return; } else if (id.compare(0, 4, "xfb_") == 0) { // "Any shader making any static use (after preprocessing) of any of these // *xfb_* qualifiers will cause the shader to be in a transform feedback // capturing mode and hence responsible for describing the transform feedback // setup." intermediate.setXfbMode(); const char* feature = "transform feedback qualifier"; requireStage(loc, (EShLanguageMask)(EShLangVertexMask | EShLangGeometryMask | EShLangTessControlMask | EShLangTessEvaluationMask), feature); requireProfile(loc, ECoreProfile | ECompatibilityProfile, feature); profileRequires(loc, ECoreProfile | ECompatibilityProfile, 440, E_GL_ARB_enhanced_layouts, feature); if (id == "xfb_buffer") { // "It is a compile-time error to specify an *xfb_buffer* that is greater than // the implementation-dependent constant gl_MaxTransformFeedbackBuffers." if (value >= resources.maxTransformFeedbackBuffers) error(loc, "buffer is too large:", id.c_str(), "gl_MaxTransformFeedbackBuffers is %d", resources.maxTransformFeedbackBuffers); if (value >= (int)TQualifier::layoutXfbBufferEnd) error(loc, "buffer is too large:", id.c_str(), "internal max is %d", TQualifier::layoutXfbBufferEnd-1); else publicType.qualifier.layoutXfbBuffer = value; return; } else if (id == "xfb_offset") { if (value >= (int)TQualifier::layoutXfbOffsetEnd) error(loc, "offset is too large:", id.c_str(), "internal max is %d", TQualifier::layoutXfbOffsetEnd-1); else publicType.qualifier.layoutXfbOffset = value; return; } else if (id == "xfb_stride") { // "The resulting stride (implicit or explicit), when divided by 4, must be less than or equal to the // implementation-dependent constant gl_MaxTransformFeedbackInterleavedComponents." if (value > 4 * resources.maxTransformFeedbackInterleavedComponents) error(loc, "1/4 stride is too large:", id.c_str(), "gl_MaxTransformFeedbackInterleavedComponents is %d", resources.maxTransformFeedbackInterleavedComponents); else if (value >= (int)TQualifier::layoutXfbStrideEnd) error(loc, "stride is too large:", id.c_str(), "internal max is %d", TQualifier::layoutXfbStrideEnd-1); if (value < (int)TQualifier::layoutXfbStrideEnd) publicType.qualifier.layoutXfbStride = value; return; } } if (id == "input_attachment_index") { requireVulkan(loc, "input_attachment_index"); if (value >= (int)TQualifier::layoutAttachmentEnd) error(loc, "attachment index is too large", id.c_str(), ""); else publicType.qualifier.layoutAttachment = value; return; } if (id == "constant_id") { requireSpv(loc, "constant_id"); if (value >= (int)TQualifier::layoutSpecConstantIdEnd) { error(loc, "specialization-constant id is too large", id.c_str(), ""); } else { publicType.qualifier.layoutSpecConstantId = value; publicType.qualifier.specConstant = true; } return; } switch (language) { case EShLangVertex: break; case EShLangTessControl: if (id == "vertices") { if (value == 0) error(loc, "must be greater than 0", "vertices", ""); else publicType.shaderQualifiers.vertices = value; return; } break; case EShLangTessEvaluation: break; case EShLangGeometry: if (id == "invocations") { profileRequires(loc, ECompatibilityProfile | ECoreProfile, 400, nullptr, "invocations"); if (value == 0) error(loc, "must be at least 1", "invocations", ""); else publicType.shaderQualifiers.invocations = value; return; } if (id == "max_vertices") { publicType.shaderQualifiers.vertices = value; if (value > resources.maxGeometryOutputVertices) error(loc, "too large, must be less than gl_MaxGeometryOutputVertices", "max_vertices", ""); return; } if (id == "stream") { requireProfile(loc, ~EEsProfile, "selecting output stream"); publicType.qualifier.layoutStream = value; return; } break; case EShLangFragment: if (id == "index") { requireProfile(loc, ECompatibilityProfile | ECoreProfile, "index layout qualifier on fragment output"); const char* exts[2] = { E_GL_ARB_separate_shader_objects, E_GL_ARB_explicit_attrib_location }; profileRequires(loc, ECompatibilityProfile | ECoreProfile, 330, 2, exts, "index layout qualifier on fragment output"); publicType.qualifier.layoutIndex = value; return; } break; case EShLangCompute: if (id.compare(0, 11, "local_size_") == 0) { if (id == "local_size_x") { publicType.shaderQualifiers.localSize[0] = value; return; } if (id == "local_size_y") { publicType.shaderQualifiers.localSize[1] = value; return; } if (id == "local_size_z") { publicType.shaderQualifiers.localSize[2] = value; return; } if (spv > 0) { if (id == "local_size_x_id") { publicType.shaderQualifiers.localSizeSpecId[0] = value; return; } if (id == "local_size_y_id") { publicType.shaderQualifiers.localSizeSpecId[1] = value; return; } if (id == "local_size_z_id") { publicType.shaderQualifiers.localSizeSpecId[2] = value; return; } } } break; default: break; } error(loc, "there is no such layout identifier for this stage taking an assigned value", id.c_str(), ""); } // Merge any layout qualifier information from src into dst, leaving everything else in dst alone // // "More than one layout qualifier may appear in a single declaration. // Additionally, the same layout-qualifier-name can occur multiple times // within a layout qualifier or across multiple layout qualifiers in the // same declaration. When the same layout-qualifier-name occurs // multiple times, in a single declaration, the last occurrence overrides // the former occurrence(s). Further, if such a layout-qualifier-name // will effect subsequent declarations or other observable behavior, it // is only the last occurrence that will have any effect, behaving as if // the earlier occurrence(s) within the declaration are not present. // This is also true for overriding layout-qualifier-names, where one // overrides the other (e.g., row_major vs. column_major); only the last // occurrence has any effect." // void TParseContext::mergeObjectLayoutQualifiers(TQualifier& dst, const TQualifier& src, bool inheritOnly) { if (src.hasMatrix()) dst.layoutMatrix = src.layoutMatrix; if (src.hasPacking()) dst.layoutPacking = src.layoutPacking; if (src.hasStream()) dst.layoutStream = src.layoutStream; if (src.hasFormat()) dst.layoutFormat = src.layoutFormat; if (src.hasXfbBuffer()) dst.layoutXfbBuffer = src.layoutXfbBuffer; if (src.hasAlign()) dst.layoutAlign = src.layoutAlign; if (! inheritOnly) { if (src.hasLocation()) dst.layoutLocation = src.layoutLocation; if (src.hasComponent()) dst.layoutComponent = src.layoutComponent; if (src.hasIndex()) dst.layoutIndex = src.layoutIndex; if (src.hasOffset()) dst.layoutOffset = src.layoutOffset; if (src.hasSet()) dst.layoutSet = src.layoutSet; if (src.layoutBinding != TQualifier::layoutBindingEnd) dst.layoutBinding = src.layoutBinding; if (src.hasXfbStride()) dst.layoutXfbStride = src.layoutXfbStride; if (src.hasXfbOffset()) dst.layoutXfbOffset = src.layoutXfbOffset; if (src.hasAttachment()) dst.layoutAttachment = src.layoutAttachment; if (src.hasSpecConstantId()) dst.layoutSpecConstantId = src.layoutSpecConstantId; if (src.layoutPushConstant) dst.layoutPushConstant = true; } } // Do error layout error checking given a full variable/block declaration. void TParseContext::layoutObjectCheck(const TSourceLoc& loc, const TSymbol& symbol) { const TType& type = symbol.getType(); const TQualifier& qualifier = type.getQualifier(); // first, cross check WRT to just the type layoutTypeCheck(loc, type); // now, any remaining error checking based on the object itself if (qualifier.hasAnyLocation()) { switch (qualifier.storage) { case EvqUniform: case EvqBuffer: if (symbol.getAsVariable() == nullptr) error(loc, "can only be used on variable declaration", "location", ""); break; default: break; } } // Check packing and matrix if (qualifier.hasUniformLayout()) { switch (qualifier.storage) { case EvqUniform: case EvqBuffer: if (type.getBasicType() != EbtBlock) { if (qualifier.hasMatrix()) error(loc, "cannot specify matrix layout on a variable declaration", "layout", ""); if (qualifier.hasPacking()) error(loc, "cannot specify packing on a variable declaration", "layout", ""); // "The offset qualifier can only be used on block members of blocks..." if (qualifier.hasOffset() && type.getBasicType() != EbtAtomicUint) error(loc, "cannot specify on a variable declaration", "offset", ""); // "The align qualifier can only be used on blocks or block members..." if (qualifier.hasAlign()) error(loc, "cannot specify on a variable declaration", "align", ""); if (qualifier.layoutPushConstant) error(loc, "can only specify on a uniform block", "push_constant", ""); } break; default: // these were already filtered by layoutTypeCheck() (or its callees) break; } } } // Do layout error checking with respect to a type. void TParseContext::layoutTypeCheck(const TSourceLoc& loc, const TType& type) { const TQualifier& qualifier = type.getQualifier(); // first, intra-layout qualifier-only error checking layoutQualifierCheck(loc, qualifier); // now, error checking combining type and qualifier if (qualifier.hasAnyLocation()) { if (qualifier.hasLocation()) { if (qualifier.storage == EvqVaryingOut && language == EShLangFragment) { if (qualifier.layoutLocation >= (unsigned int)resources.maxDrawBuffers) error(loc, "too large for fragment output", "location", ""); } } if (qualifier.hasComponent()) { // "It is a compile-time error if this sequence of components gets larger than 3." if (qualifier.layoutComponent + type.getVectorSize() > 4) error(loc, "type overflows the available 4 components", "component", ""); // "It is a compile-time error to apply the component qualifier to a matrix, a structure, a block, or an array containing any of these." if (type.isMatrix() || type.getBasicType() == EbtBlock || type.getBasicType() == EbtStruct) error(loc, "cannot apply to a matrix, structure, or block", "component", ""); } switch (qualifier.storage) { case EvqVaryingIn: case EvqVaryingOut: if (type.getBasicType() == EbtBlock) profileRequires(loc, ECoreProfile | ECompatibilityProfile, 440, E_GL_ARB_enhanced_layouts, "location qualifier on in/out block"); break; case EvqUniform: case EvqBuffer: break; default: error(loc, "can only appy to uniform, buffer, in, or out storage qualifiers", "location", ""); break; } bool typeCollision; int repeated = intermediate.addUsedLocation(qualifier, type, typeCollision); if (repeated >= 0 && ! typeCollision) error(loc, "overlapping use of location", "location", "%d", repeated); // "fragment-shader outputs ... if two variables are placed within the same // location, they must have the same underlying type (floating-point or integer)" if (typeCollision && language == EShLangFragment && qualifier.isPipeOutput()) error(loc, "fragment outputs sharing the same location must be the same basic type", "location", "%d", repeated); } if (qualifier.hasXfbOffset() && qualifier.hasXfbBuffer()) { int repeated = intermediate.addXfbBufferOffset(type); if (repeated >= 0) error(loc, "overlapping offsets at", "xfb_offset", "offset %d in buffer %d", repeated, qualifier.layoutXfbBuffer); // "The offset must be a multiple of the size of the first component of the first // qualified variable or block member, or a compile-time error results. Further, if applied to an aggregate // containing a double, the offset must also be a multiple of 8..." if (type.containsBasicType(EbtDouble) && ! IsMultipleOfPow2(qualifier.layoutXfbOffset, 8)) error(loc, "type contains double; xfb_offset must be a multiple of 8", "xfb_offset", ""); else if (! IsMultipleOfPow2(qualifier.layoutXfbOffset, 4)) error(loc, "must be a multiple of size of first component", "xfb_offset", ""); } if (qualifier.hasXfbStride() && qualifier.hasXfbBuffer()) { if (! intermediate.setXfbBufferStride(qualifier.layoutXfbBuffer, qualifier.layoutXfbStride)) error(loc, "all stride settings must match for xfb buffer", "xfb_stride", "%d", qualifier.layoutXfbBuffer); } if (qualifier.hasBinding()) { // Binding checking, from the spec: // // "If the binding point for any uniform or shader storage block instance is less than zero, or greater than or // equal to the implementation-dependent maximum number of uniform buffer bindings, a compile-time // error will occur. When the binding identifier is used with a uniform or shader storage block instanced as // an array of size N, all elements of the array from binding through binding + N - 1 must be within this // range." // if (type.getBasicType() != EbtSampler && type.getBasicType() != EbtBlock && type.getBasicType() != EbtAtomicUint) error(loc, "requires block, or sampler/image, or atomic-counter type", "binding", ""); if (type.getBasicType() == EbtSampler) { int lastBinding = qualifier.layoutBinding; if (type.isArray()) lastBinding += type.getCumulativeArraySize(); if (lastBinding >= resources.maxCombinedTextureImageUnits) error(loc, "sampler binding not less than gl_MaxCombinedTextureImageUnits", "binding", type.isArray() ? "(using array)" : ""); } if (type.getBasicType() == EbtAtomicUint) { if (qualifier.layoutBinding >= (unsigned int)resources.maxAtomicCounterBindings) { error(loc, "atomic_uint binding is too large; see gl_MaxAtomicCounterBindings", "binding", ""); return; } } } // atomic_uint if (type.getBasicType() == EbtAtomicUint) { if (! type.getQualifier().hasBinding()) error(loc, "layout(binding=X) is required", "atomic_uint", ""); } // "The offset qualifier can only be used on block members of blocks..." if (qualifier.hasOffset()) { if (type.getBasicType() == EbtBlock) error(loc, "only applies to block members, not blocks", "offset", ""); } // Image format if (qualifier.hasFormat()) { if (! type.isImage()) error(loc, "only apply to images", TQualifier::getLayoutFormatString(qualifier.layoutFormat), ""); else { if (type.getSampler().type == EbtFloat && qualifier.layoutFormat > ElfFloatGuard) error(loc, "does not apply to floating point images", TQualifier::getLayoutFormatString(qualifier.layoutFormat), ""); if (type.getSampler().type == EbtInt && (qualifier.layoutFormat < ElfFloatGuard || qualifier.layoutFormat > ElfIntGuard)) error(loc, "does not apply to signed integer images", TQualifier::getLayoutFormatString(qualifier.layoutFormat), ""); if (type.getSampler().type == EbtUint && qualifier.layoutFormat < ElfIntGuard) error(loc, "does not apply to unsigned integer images", TQualifier::getLayoutFormatString(qualifier.layoutFormat), ""); if (profile == EEsProfile) { // "Except for image variables qualified with the format qualifiers r32f, r32i, and r32ui, image variables must // specify either memory qualifier readonly or the memory qualifier writeonly." if (! (qualifier.layoutFormat == ElfR32f || qualifier.layoutFormat == ElfR32i || qualifier.layoutFormat == ElfR32ui)) { if (! qualifier.readonly && ! qualifier.writeonly) error(loc, "format requires readonly or writeonly memory qualifier", TQualifier::getLayoutFormatString(qualifier.layoutFormat), ""); } } } } else if (type.isImage() && ! qualifier.writeonly) error(loc, "image variables not declared 'writeonly' must have a format layout qualifier", "", ""); if (qualifier.layoutPushConstant && type.getBasicType() != EbtBlock) error(loc, "can only be used with a block", "push_constant", ""); // input attachment if (type.isSubpass()) { if (! qualifier.hasAttachment()) error(loc, "requires an input_attachment_index layout qualifier", "subpass", ""); } else { if (qualifier.hasAttachment()) error(loc, "can only be used with a subpass", "input_attachment_index", ""); } // specialization-constant id if (qualifier.hasSpecConstantId()) { if (type.getQualifier().storage != EvqConst) error(loc, "can only be applied to 'const'-qualified scalar", "constant_id", ""); if (! type.isScalar()) error(loc, "can only be applied to a scalar", "constant_id", ""); switch (type.getBasicType()) { case EbtInt: case EbtUint: case EbtBool: case EbtFloat: case EbtDouble: break; default: error(loc, "cannot be applied to this type", "constant_id", ""); break; } } } // Do layout error checking that can be done within a layout qualifier proper, not needing to know // if there are blocks, atomic counters, variables, etc. void TParseContext::layoutQualifierCheck(const TSourceLoc& loc, const TQualifier& qualifier) { if (qualifier.storage == EvqShared && qualifier.hasLayout()) error(loc, "cannot apply layout qualifiers to a shared variable", "shared", ""); // "It is a compile-time error to use *component* without also specifying the location qualifier (order does not matter)." if (qualifier.hasComponent() && ! qualifier.hasLocation()) error(loc, "must specify 'location' to use 'component'", "component", ""); if (qualifier.hasAnyLocation()) { // "As with input layout qualifiers, all shaders except compute shaders // allow *location* layout qualifiers on output variable declarations, // output block declarations, and output block member declarations." switch (qualifier.storage) { case EvqVaryingIn: { const char* feature = "location qualifier on input"; if (profile == EEsProfile && version < 310) requireStage(loc, EShLangVertex, feature); else requireStage(loc, (EShLanguageMask)~EShLangComputeMask, feature); if (language == EShLangVertex) { const char* exts[2] = { E_GL_ARB_separate_shader_objects, E_GL_ARB_explicit_attrib_location }; profileRequires(loc, ~EEsProfile, 330, 2, exts, feature); profileRequires(loc, EEsProfile, 300, nullptr, feature); } else { profileRequires(loc, ~EEsProfile, 410, E_GL_ARB_separate_shader_objects, feature); profileRequires(loc, EEsProfile, 310, nullptr, feature); } break; } case EvqVaryingOut: { const char* feature = "location qualifier on output"; if (profile == EEsProfile && version < 310) requireStage(loc, EShLangFragment, feature); else requireStage(loc, (EShLanguageMask)~EShLangComputeMask, feature); if (language == EShLangFragment) { const char* exts[2] = { E_GL_ARB_separate_shader_objects, E_GL_ARB_explicit_attrib_location }; profileRequires(loc, ~EEsProfile, 330, 2, exts, feature); profileRequires(loc, EEsProfile, 300, nullptr, feature); } else { profileRequires(loc, ~EEsProfile, 410, E_GL_ARB_separate_shader_objects, feature); profileRequires(loc, EEsProfile, 310, nullptr, feature); } break; } case EvqUniform: case EvqBuffer: { const char* feature = "location qualifier on uniform or buffer"; requireProfile(loc, EEsProfile | ECoreProfile | ECompatibilityProfile, feature); profileRequires(loc, ECoreProfile | ECompatibilityProfile, 430, nullptr, feature); profileRequires(loc, EEsProfile, 310, nullptr, feature); break; } default: break; } if (qualifier.hasIndex()) { if (qualifier.storage != EvqVaryingOut) error(loc, "can only be used on an output", "index", ""); if (! qualifier.hasLocation()) error(loc, "can only be used with an explicit location", "index", ""); } } if (qualifier.hasBinding()) { if (! qualifier.isUniformOrBuffer()) error(loc, "requires uniform or buffer storage qualifier", "binding", ""); } if (qualifier.hasStream()) { if (qualifier.storage != EvqVaryingOut) error(loc, "can only be used on an output", "stream", ""); } if (qualifier.hasXfb()) { if (qualifier.storage != EvqVaryingOut) error(loc, "can only be used on an output", "xfb layout qualifier", ""); } if (qualifier.hasUniformLayout()) { if (! qualifier.isUniformOrBuffer()) { if (qualifier.hasMatrix() || qualifier.hasPacking()) error(loc, "matrix or packing qualifiers can only be used on a uniform or buffer", "layout", ""); if (qualifier.hasOffset() || qualifier.hasAlign()) error(loc, "offset/align can only be used on a uniform or buffer", "layout", ""); } } if (qualifier.layoutPushConstant) { if (qualifier.storage != EvqUniform) error(loc, "can only be used with a uniform", "push_constant", ""); } } // For places that can't have shader-level layout qualifiers void TParseContext::checkNoShaderLayouts(const TSourceLoc& loc, const TShaderQualifiers& shaderQualifiers) { const char* message = "can only apply to a standalone qualifier"; if (shaderQualifiers.geometry != ElgNone) error(loc, message, TQualifier::getGeometryString(shaderQualifiers.geometry), ""); if (shaderQualifiers.invocations != TQualifier::layoutNotSet) error(loc, message, "invocations", ""); if (shaderQualifiers.vertices != TQualifier::layoutNotSet) { if (language == EShLangGeometry) error(loc, message, "max_vertices", ""); else if (language == EShLangTessControl) error(loc, message, "vertices", ""); else assert(0); } for (int i = 0; i < 3; ++i) { if (shaderQualifiers.localSize[i] > 1) error(loc, message, "local_size", ""); if (shaderQualifiers.localSizeSpecId[i] != TQualifier::layoutNotSet) error(loc, message, "local_size id", ""); } if (shaderQualifiers.blendEquation) error(loc, message, "blend equation", ""); // TBD: correctness: are any of these missing? pixelCenterInteger, originUpperLeft, spacing, order, pointmode, earlyfragment, depth } // Correct and/or advance an object's offset layout qualifier. void TParseContext::fixOffset(const TSourceLoc& loc, TSymbol& symbol) { const TQualifier& qualifier = symbol.getType().getQualifier(); if (symbol.getType().getBasicType() == EbtAtomicUint) { if (qualifier.hasBinding() && (int)qualifier.layoutBinding < resources.maxAtomicCounterBindings) { // Set the offset int offset; if (qualifier.hasOffset()) offset = qualifier.layoutOffset; else offset = atomicUintOffsets[qualifier.layoutBinding]; symbol.getWritableType().getQualifier().layoutOffset = offset; // Check for overlap int numOffsets = 4; if (symbol.getType().isArray()) numOffsets *= symbol.getType().getCumulativeArraySize(); int repeated = intermediate.addUsedOffsets(qualifier.layoutBinding, offset, numOffsets); if (repeated >= 0) error(loc, "atomic counters sharing the same offset:", "offset", "%d", repeated); // Bump the default offset atomicUintOffsets[qualifier.layoutBinding] = offset + numOffsets; } } } // // Look up a function name in the symbol table, and make sure it is a function. // // Return the function symbol if found, otherwise nullptr. // const TFunction* TParseContext::findFunction(const TSourceLoc& loc, const TFunction& call, bool& builtIn) { const TFunction* function = nullptr; if (symbolTable.isFunctionNameVariable(call.getName())) { error(loc, "can't use function syntax on variable", call.getName().c_str(), ""); return nullptr; } if (profile == EEsProfile || version < 120) function = findFunctionExact(loc, call, builtIn); else if (version < 400) function = findFunction120(loc, call, builtIn); else function = findFunction400(loc, call, builtIn); return function; } // Function finding algorithm for ES and desktop 110. const TFunction* TParseContext::findFunctionExact(const TSourceLoc& loc, const TFunction& call, bool& builtIn) { TSymbol* symbol = symbolTable.find(call.getMangledName(), &builtIn); if (symbol == nullptr) { error(loc, "no matching overloaded function found", call.getName().c_str(), ""); return nullptr; } return symbol->getAsFunction(); } // Function finding algorithm for desktop versions 120 through 330. const TFunction* TParseContext::findFunction120(const TSourceLoc& loc, const TFunction& call, bool& builtIn) { // first, look for an exact match TSymbol* symbol = symbolTable.find(call.getMangledName(), &builtIn); if (symbol) return symbol->getAsFunction(); // exact match not found, look through a list of overloaded functions of the same name // "If no exact match is found, then [implicit conversions] will be applied to find a match. Mismatched types // on input parameters (in or inout or default) must have a conversion from the calling argument type to the // formal parameter type. Mismatched types on output parameters (out or inout) must have a conversion // from the formal parameter type to the calling argument type. When argument conversions are used to find // a match, it is a semantic error if there are multiple ways to apply these conversions to make the call match // more than one function." const TFunction* candidate = nullptr; TVector<TFunction*> candidateList; symbolTable.findFunctionNameList(call.getMangledName(), candidateList, builtIn); for (TVector<TFunction*>::const_iterator it = candidateList.begin(); it != candidateList.end(); ++it) { const TFunction& function = *(*it); // to even be a potential match, number of arguments has to match if (call.getParamCount() != function.getParamCount()) continue; bool possibleMatch = true; for (int i = 0; i < function.getParamCount(); ++i) { // same types is easy if (*function[i].type == *call[i].type) continue; // We have a mismatch in type, see if it is implicitly convertible if (function[i].type->isArray() || call[i].type->isArray() || ! function[i].type->sameElementShape(*call[i].type)) possibleMatch = false; else { // do direction-specific checks for conversion of basic type if (function[i].type->getQualifier().isParamInput()) { if (! intermediate.canImplicitlyPromote(call[i].type->getBasicType(), function[i].type->getBasicType())) possibleMatch = false; } if (function[i].type->getQualifier().isParamOutput()) { if (! intermediate.canImplicitlyPromote(function[i].type->getBasicType(), call[i].type->getBasicType())) possibleMatch = false; } } if (! possibleMatch) break; } if (possibleMatch) { if (candidate) { // our second match, meaning ambiguity error(loc, "ambiguous function signature match: multiple signatures match under implicit type conversion", call.getName().c_str(), ""); } else candidate = &function; } } if (candidate == nullptr) error(loc, "no matching overloaded function found", call.getName().c_str(), ""); return candidate; } // Function finding algorithm for desktop version 400 and above. const TFunction* TParseContext::findFunction400(const TSourceLoc& loc, const TFunction& call, bool& builtIn) { // TODO: 4.00 functionality: findFunction400() return findFunction120(loc, call, builtIn); } // When a declaration includes a type, but not a variable name, it can be // to establish defaults. void TParseContext::declareTypeDefaults(const TSourceLoc& loc, const TPublicType& publicType) { if (publicType.basicType == EbtAtomicUint && publicType.qualifier.hasBinding() && publicType.qualifier.hasOffset()) { if (publicType.qualifier.layoutBinding >= (unsigned int)resources.maxAtomicCounterBindings) { error(loc, "atomic_uint binding is too large", "binding", ""); return; } atomicUintOffsets[publicType.qualifier.layoutBinding] = publicType.qualifier.layoutOffset; return; } if (publicType.qualifier.hasLayout()) warn(loc, "useless application of layout qualifier", "layout", ""); } // // Do everything necessary to handle a variable (non-block) declaration. // Either redeclaring a variable, or making a new one, updating the symbol // table, and all error checking. // // Returns a subtree node that computes an initializer, if needed. // Returns nullptr if there is no code to execute for initialization. // // 'publicType' is the type part of the declaration (to the left) // 'arraySizes' is the arrayness tagged on the identifier (to the right) // TIntermNode* TParseContext::declareVariable(const TSourceLoc& loc, TString& identifier, const TPublicType& publicType, TArraySizes* arraySizes, TIntermTyped* initializer) { TType type(publicType); // shallow copy; 'type' shares the arrayness and structure definition with 'publicType' if (type.isImplicitlySizedArray()) { // Because "int[] a = int[2](...), b = int[3](...)" makes two arrays a and b // of different sizes, for this case sharing the shallow copy of arrayness // with the publicType oversubscribes it, so get a deep copy of the arrayness. type.newArraySizes(*publicType.arraySizes); } if (voidErrorCheck(loc, identifier, type.getBasicType())) return nullptr; if (initializer) rValueErrorCheck(loc, "initializer", initializer); else nonInitConstCheck(loc, identifier, type); samplerCheck(loc, type, identifier, initializer); atomicUintCheck(loc, type, identifier); transparentCheck(loc, type, identifier); if (identifier != "gl_FragCoord" && (publicType.shaderQualifiers.originUpperLeft || publicType.shaderQualifiers.pixelCenterInteger)) error(loc, "can only apply origin_upper_left and pixel_center_origin to gl_FragCoord", "layout qualifier", ""); if (identifier != "gl_FragDepth" && publicType.shaderQualifiers.layoutDepth != EldNone) error(loc, "can only apply depth layout to gl_FragDepth", "layout qualifier", ""); // Check for redeclaration of built-ins and/or attempting to declare a reserved name bool newDeclaration = false; // true if a new entry gets added to the symbol table TSymbol* symbol = redeclareBuiltinVariable(loc, identifier, type.getQualifier(), publicType.shaderQualifiers, newDeclaration); if (! symbol) reservedErrorCheck(loc, identifier); inheritGlobalDefaults(type.getQualifier()); // Declare the variable if (arraySizes || type.isArray()) { // Arrayness is potentially coming both from the type and from the // variable: "int[] a[];" or just one or the other. // Merge it all to the type, so all arrayness is part of the type. arrayDimCheck(loc, &type, arraySizes); arrayDimMerge(type, arraySizes); // Check that implicit sizing is only where allowed. arrayUnsizedCheck(loc, type.getQualifier(), &type.getArraySizes(), initializer != nullptr, false); if (! arrayQualifierError(loc, type.getQualifier()) && ! arrayError(loc, type)) declareArray(loc, identifier, type, symbol, newDeclaration); if (initializer) { profileRequires(loc, ENoProfile, 120, E_GL_3DL_array_objects, "initializer"); profileRequires(loc, EEsProfile, 300, nullptr, "initializer"); } } else { // non-array case if (! symbol) symbol = declareNonArray(loc, identifier, type, newDeclaration); else if (type != symbol->getType()) error(loc, "cannot change the type of", "redeclaration", symbol->getName().c_str()); } if (! symbol) return nullptr; // Deal with initializer TIntermNode* initNode = nullptr; if (symbol && initializer) { TVariable* variable = symbol->getAsVariable(); if (! variable) { error(loc, "initializer requires a variable, not a member", identifier.c_str(), ""); return nullptr; } initNode = executeInitializer(loc, initializer, variable); } // look for errors in layout qualifier use layoutObjectCheck(loc, *symbol); fixOffset(loc, *symbol); // see if it's a linker-level object to track if (newDeclaration && symbolTable.atGlobalLevel()) intermediate.addSymbolLinkageNode(linkage, *symbol); return initNode; } // Pick up global defaults from the provide global defaults into dst. void TParseContext::inheritGlobalDefaults(TQualifier& dst) const { if (dst.storage == EvqVaryingOut) { if (! dst.hasStream() && language == EShLangGeometry) dst.layoutStream = globalOutputDefaults.layoutStream; if (! dst.hasXfbBuffer()) dst.layoutXfbBuffer = globalOutputDefaults.layoutXfbBuffer; } } // // Make an internal-only variable whose name is for debug purposes only // and won't be searched for. Callers will only use the return value to use // the variable, not the name to look it up. It is okay if the name // is the same as other names; there won't be any conflict. // TVariable* TParseContext::makeInternalVariable(const char* name, const TType& type) const { TString* nameString = new TString(name); TVariable* variable = new TVariable(nameString, type); symbolTable.makeInternalVariable(*variable); return variable; } // // Declare a non-array variable, the main point being there is no redeclaration // for resizing allowed. // // Return the successfully declared variable. // TVariable* TParseContext::declareNonArray(const TSourceLoc& loc, TString& identifier, TType& type, bool& newDeclaration) { // make a new variable TVariable* variable = new TVariable(&identifier, type); ioArrayCheck(loc, type, identifier); // add variable to symbol table if (! symbolTable.insert(*variable)) { error(loc, "redefinition", variable->getName().c_str(), ""); return nullptr; } else { newDeclaration = true; return variable; } } // // Handle all types of initializers from the grammar. // // Returning nullptr just means there is no code to execute to handle the // initializer, which will, for example, be the case for constant initializers. // TIntermNode* TParseContext::executeInitializer(const TSourceLoc& loc, TIntermTyped* initializer, TVariable* variable) { // // Identifier must be of type constant, a global, or a temporary, and // starting at version 120, desktop allows uniforms to have initializers. // TStorageQualifier qualifier = variable->getType().getQualifier().storage; if (! (qualifier == EvqTemporary || qualifier == EvqGlobal || qualifier == EvqConst || (qualifier == EvqUniform && profile != EEsProfile && version >= 120))) { error(loc, " cannot initialize this type of qualifier ", variable->getType().getStorageQualifierString(), ""); return nullptr; } arrayObjectCheck(loc, variable->getType(), "array initializer"); // // If the initializer was from braces { ... }, we convert the whole subtree to a // constructor-style subtree, allowing the rest of the code to operate // identically for both kinds of initializers. // initializer = convertInitializerList(loc, variable->getType(), initializer); if (! initializer) { // error recovery; don't leave const without constant values if (qualifier == EvqConst) variable->getWritableType().getQualifier().storage = EvqTemporary; return nullptr; } // Fix outer arrayness if variable is unsized, getting size from the initializer if (initializer->getType().isExplicitlySizedArray() && variable->getType().isImplicitlySizedArray()) variable->getWritableType().changeOuterArraySize(initializer->getType().getOuterArraySize()); // Inner arrayness can also get set by an initializer if (initializer->getType().isArrayOfArrays() && variable->getType().isArrayOfArrays() && initializer->getType().getArraySizes()->getNumDims() == variable->getType().getArraySizes()->getNumDims()) { // adopt unsized sizes from the initializer's sizes for (int d = 1; d < variable->getType().getArraySizes()->getNumDims(); ++d) { if (variable->getType().getArraySizes()->getDimSize(d) == UnsizedArraySize) variable->getWritableType().getArraySizes().setDimSize(d, initializer->getType().getArraySizes()->getDimSize(d)); } } // Uniform and global consts require a constant initializer if (qualifier == EvqUniform && initializer->getType().getQualifier().storage != EvqConst) { error(loc, "uniform initializers must be constant", "=", "'%s'", variable->getType().getCompleteString().c_str()); variable->getWritableType().getQualifier().storage = EvqTemporary; return nullptr; } if (qualifier == EvqConst && symbolTable.atGlobalLevel() && initializer->getType().getQualifier().storage != EvqConst) { error(loc, "global const initializers must be constant", "=", "'%s'", variable->getType().getCompleteString().c_str()); variable->getWritableType().getQualifier().storage = EvqTemporary; return nullptr; } // Const variables require a constant initializer, depending on version if (qualifier == EvqConst) { if (initializer->getType().getQualifier().storage != EvqConst) { const char* initFeature = "non-constant initializer"; requireProfile(loc, ~EEsProfile, initFeature); profileRequires(loc, ~EEsProfile, 420, E_GL_ARB_shading_language_420pack, initFeature); variable->getWritableType().getQualifier().storage = EvqConstReadOnly; qualifier = EvqConstReadOnly; } } else { // Non-const global variables in ES need a const initializer. // // "In declarations of global variables with no storage qualifier or with a const // qualifier any initializer must be a constant expression." if (symbolTable.atGlobalLevel() && initializer->getType().getQualifier().storage != EvqConst) { const char* initFeature = "non-constant global initializer"; if (relaxedErrors()) warn(loc, "not allowed in this version", initFeature, ""); else requireProfile(loc, ~EEsProfile, initFeature); } } if (qualifier == EvqConst || qualifier == EvqUniform) { // Compile-time tagging of the variable with it's constant value... initializer = intermediate.addConversion(EOpAssign, variable->getType(), initializer); if (! initializer || ! initializer->getAsConstantUnion() || variable->getType() != initializer->getType()) { error(loc, "non-matching or non-convertible constant type for const initializer", variable->getType().getStorageQualifierString(), ""); variable->getWritableType().getQualifier().storage = EvqTemporary; return nullptr; } variable->setConstArray(initializer->getAsConstantUnion()->getConstArray()); } else { // normal assigning of a value to a variable... TIntermSymbol* intermSymbol = intermediate.addSymbol(*variable, loc); TIntermNode* initNode = intermediate.addAssign(EOpAssign, intermSymbol, initializer, loc); if (! initNode) assignError(loc, "=", intermSymbol->getCompleteString(), initializer->getCompleteString()); return initNode; } return nullptr; } // // Reprocess any initializer-list { ... } parts of the initializer. // Need to heirarchically assign correct types and implicit // conversions. Will do this mimicking the same process used for // creating a constructor-style initializer, ensuring we get the // same form. // TIntermTyped* TParseContext::convertInitializerList(const TSourceLoc& loc, const TType& type, TIntermTyped* initializer) { // Will operate recursively. Once a subtree is found that is constructor style, // everything below it is already good: Only the "top part" of the initializer // can be an initializer list, where "top part" can extend for several (or all) levels. // see if we have bottomed out in the tree within the initializer-list part TIntermAggregate* initList = initializer->getAsAggregate(); if (! initList || initList->getOp() != EOpNull) return initializer; // Of the initializer-list set of nodes, need to process bottom up, // so recurse deep, then process on the way up. // Go down the tree here... if (type.isArray()) { // The type's array might be unsized, which could be okay, so base sizes on the size of the aggregate. // Later on, initializer execution code will deal with array size logic. TType arrayType; arrayType.shallowCopy(type); // sharing struct stuff is fine arrayType.newArraySizes(*type.getArraySizes()); // but get a fresh copy of the array information, to edit below // edit array sizes to fill in unsized dimensions arrayType.changeOuterArraySize((int)initList->getSequence().size()); TIntermTyped* firstInit = initList->getSequence()[0]->getAsTyped(); if (arrayType.isArrayOfArrays() && firstInit->getType().isArray() && arrayType.getArraySizes().getNumDims() == firstInit->getType().getArraySizes()->getNumDims() + 1) { for (int d = 1; d < arrayType.getArraySizes().getNumDims(); ++d) { if (arrayType.getArraySizes().getDimSize(d) == UnsizedArraySize) arrayType.getArraySizes().setDimSize(d, firstInit->getType().getArraySizes()->getDimSize(d - 1)); } } TType elementType(arrayType, 0); // dereferenced type for (size_t i = 0; i < initList->getSequence().size(); ++i) { initList->getSequence()[i] = convertInitializerList(loc, elementType, initList->getSequence()[i]->getAsTyped()); if (initList->getSequence()[i] == nullptr) return nullptr; } return addConstructor(loc, initList, arrayType, mapTypeToConstructorOp(arrayType)); } else if (type.isStruct()) { if (type.getStruct()->size() != initList->getSequence().size()) { error(loc, "wrong number of structure members", "initializer list", ""); return nullptr; } for (size_t i = 0; i < type.getStruct()->size(); ++i) { initList->getSequence()[i] = convertInitializerList(loc, *(*type.getStruct())[i].type, initList->getSequence()[i]->getAsTyped()); if (initList->getSequence()[i] == nullptr) return nullptr; } } else if (type.isMatrix()) { if (type.getMatrixCols() != (int)initList->getSequence().size()) { error(loc, "wrong number of matrix columns:", "initializer list", type.getCompleteString().c_str()); return nullptr; } TType vectorType(type, 0); // dereferenced type for (int i = 0; i < type.getMatrixCols(); ++i) { initList->getSequence()[i] = convertInitializerList(loc, vectorType, initList->getSequence()[i]->getAsTyped()); if (initList->getSequence()[i] == nullptr) return nullptr; } } else if (type.isVector()) { if (type.getVectorSize() != (int)initList->getSequence().size()) { error(loc, "wrong vector size (or rows in a matrix column):", "initializer list", type.getCompleteString().c_str()); return nullptr; } } else { error(loc, "unexpected initializer-list type:", "initializer list", type.getCompleteString().c_str()); return nullptr; } // now that the subtree is processed, process this node return addConstructor(loc, initList, type, mapTypeToConstructorOp(type)); } // // Test for the correctness of the parameters passed to various constructor functions // and also convert them to the right data type, if allowed and required. // // Returns nullptr for an error or the constructed node (aggregate or typed) for no error. // TIntermTyped* TParseContext::addConstructor(const TSourceLoc& loc, TIntermNode* node, const TType& type, TOperator op) { if (node == nullptr || node->getAsTyped() == nullptr) return nullptr; rValueErrorCheck(loc, "constructor", node->getAsTyped()); TIntermAggregate* aggrNode = node->getAsAggregate(); // Combined texture-sampler constructors are completely semantic checked // in constructorTextureSamplerError() if (op == EOpConstructTextureSampler) return intermediate.setAggregateOperator(aggrNode, op, type, loc); TTypeList::const_iterator memberTypes; if (op == EOpConstructStruct) memberTypes = type.getStruct()->begin(); TType elementType; if (type.isArray()) { TType dereferenced(type, 0); elementType.shallowCopy(dereferenced); } else elementType.shallowCopy(type); bool singleArg; if (aggrNode) { if (aggrNode->getOp() != EOpNull || aggrNode->getSequence().size() == 1) singleArg = true; else singleArg = false; } else singleArg = true; TIntermTyped *newNode; if (singleArg) { // If structure constructor or array constructor is being called // for only one parameter inside the structure, we need to call constructAggregate function once. if (type.isArray()) newNode = constructAggregate(node, elementType, 1, node->getLoc()); else if (op == EOpConstructStruct) newNode = constructAggregate(node, *(*memberTypes).type, 1, node->getLoc()); else newNode = constructBuiltIn(type, op, node->getAsTyped(), node->getLoc(), false); if (newNode && (type.isArray() || op == EOpConstructStruct)) newNode = intermediate.setAggregateOperator(newNode, EOpConstructStruct, type, loc); return newNode; } // // Handle list of arguments. // TIntermSequence &sequenceVector = aggrNode->getSequence(); // Stores the information about the parameter to the constructor // if the structure constructor contains more than one parameter, then construct // each parameter int paramCount = 0; // keeps a track of the constructor parameter number being checked // for each parameter to the constructor call, check to see if the right type is passed or convert them // to the right type if possible (and allowed). // for structure constructors, just check if the right type is passed, no conversion is allowed. for (TIntermSequence::iterator p = sequenceVector.begin(); p != sequenceVector.end(); p++, paramCount++) { if (type.isArray()) newNode = constructAggregate(*p, elementType, paramCount+1, node->getLoc()); else if (op == EOpConstructStruct) newNode = constructAggregate(*p, *(memberTypes[paramCount]).type, paramCount+1, node->getLoc()); else newNode = constructBuiltIn(type, op, (*p)->getAsTyped(), node->getLoc(), true); if (newNode) *p = newNode; else return nullptr; } TIntermTyped* constructor = intermediate.setAggregateOperator(aggrNode, op, type, loc); return constructor; } // Function for constructor implementation. Calls addUnaryMath with appropriate EOp value // for the parameter to the constructor (passed to this function). Essentially, it converts // the parameter types correctly. If a constructor expects an int (like ivec2) and is passed a // float, then float is converted to int. // // Returns nullptr for an error or the constructed node. // TIntermTyped* TParseContext::constructBuiltIn(const TType& type, TOperator op, TIntermTyped* node, const TSourceLoc& loc, bool subset) { TIntermTyped* newNode; TOperator basicOp; // // First, convert types as needed. // switch (op) { case EOpConstructVec2: case EOpConstructVec3: case EOpConstructVec4: case EOpConstructMat2x2: case EOpConstructMat2x3: case EOpConstructMat2x4: case EOpConstructMat3x2: case EOpConstructMat3x3: case EOpConstructMat3x4: case EOpConstructMat4x2: case EOpConstructMat4x3: case EOpConstructMat4x4: case EOpConstructFloat: basicOp = EOpConstructFloat; break; case EOpConstructDVec2: case EOpConstructDVec3: case EOpConstructDVec4: case EOpConstructDMat2x2: case EOpConstructDMat2x3: case EOpConstructDMat2x4: case EOpConstructDMat3x2: case EOpConstructDMat3x3: case EOpConstructDMat3x4: case EOpConstructDMat4x2: case EOpConstructDMat4x3: case EOpConstructDMat4x4: case EOpConstructDouble: basicOp = EOpConstructDouble; break; case EOpConstructIVec2: case EOpConstructIVec3: case EOpConstructIVec4: case EOpConstructInt: basicOp = EOpConstructInt; break; case EOpConstructUVec2: case EOpConstructUVec3: case EOpConstructUVec4: case EOpConstructUint: basicOp = EOpConstructUint; break; case EOpConstructBVec2: case EOpConstructBVec3: case EOpConstructBVec4: case EOpConstructBool: basicOp = EOpConstructBool; break; default: error(loc, "unsupported construction", "", ""); return nullptr; } newNode = intermediate.addUnaryMath(basicOp, node, node->getLoc()); if (newNode == nullptr) { error(loc, "can't convert", "constructor", ""); return nullptr; } // // Now, if there still isn't an operation to do the construction, and we need one, add one. // // Otherwise, skip out early. if (subset || (newNode != node && newNode->getType() == type)) return newNode; // setAggregateOperator will insert a new node for the constructor, as needed. return intermediate.setAggregateOperator(newNode, op, type, loc); } // This function tests for the type of the parameters to the structure or array constructor. Raises // an error message if the expected type does not match the parameter passed to the constructor. // // Returns nullptr for an error or the input node itself if the expected and the given parameter types match. // TIntermTyped* TParseContext::constructAggregate(TIntermNode* node, const TType& type, int paramCount, const TSourceLoc& loc) { TIntermTyped* converted = intermediate.addConversion(EOpConstructStruct, type, node->getAsTyped()); if (! converted || converted->getType() != type) { error(loc, "", "constructor", "cannot convert parameter %d from '%s' to '%s'", paramCount, node->getAsTyped()->getType().getCompleteString().c_str(), type.getCompleteString().c_str()); return nullptr; } return converted; } // // Do everything needed to add an interface block. // void TParseContext::declareBlock(const TSourceLoc& loc, TTypeList& typeList, const TString* instanceName, TArraySizes* arraySizes) { blockStageIoCheck(loc, currentBlockQualifier); blockQualifierCheck(loc, currentBlockQualifier, instanceName != nullptr); if (arraySizes) { arrayUnsizedCheck(loc, currentBlockQualifier, arraySizes, false, false); arrayDimCheck(loc, arraySizes, 0); if (arraySizes->getNumDims() > 1) requireProfile(loc, ~EEsProfile, "array-of-array of block"); } // fix and check for member storage qualifiers and types that don't belong within a block for (unsigned int member = 0; member < typeList.size(); ++member) { TType& memberType = *typeList[member].type; TQualifier& memberQualifier = memberType.getQualifier(); const TSourceLoc& memberLoc = typeList[member].loc; globalQualifierFixCheck(memberLoc, memberQualifier); if (memberQualifier.storage != EvqTemporary && memberQualifier.storage != EvqGlobal && memberQualifier.storage != currentBlockQualifier.storage) error(memberLoc, "member storage qualifier cannot contradict block storage qualifier", memberType.getFieldName().c_str(), ""); memberQualifier.storage = currentBlockQualifier.storage; if ((currentBlockQualifier.storage == EvqUniform || currentBlockQualifier.storage == EvqBuffer) && (memberQualifier.isInterpolation() || memberQualifier.isAuxiliary())) error(memberLoc, "member of uniform or buffer block cannot have an auxiliary or interpolation qualifier", memberType.getFieldName().c_str(), ""); if (memberType.isArray()) arrayUnsizedCheck(memberLoc, currentBlockQualifier, &memberType.getArraySizes(), false, member == typeList.size() - 1); if (memberQualifier.hasOffset()) { requireProfile(memberLoc, ~EEsProfile, "offset on block member"); profileRequires(memberLoc, ~EEsProfile, 440, E_GL_ARB_enhanced_layouts, "offset on block member"); } if (memberType.containsOpaque()) error(memberLoc, "member of block cannot be or contain a sampler, image, or atomic_uint type", typeList[member].type->getFieldName().c_str(), ""); } // This might be a redeclaration of a built-in block. If so, redeclareBuiltinBlock() will // do all the rest. if (! symbolTable.atBuiltInLevel() && builtInName(*blockName)) { redeclareBuiltinBlock(loc, typeList, *blockName, instanceName, arraySizes); return; } // Not a redeclaration of a built-in; check that all names are user names. reservedErrorCheck(loc, *blockName); if (instanceName) reservedErrorCheck(loc, *instanceName); for (unsigned int member = 0; member < typeList.size(); ++member) reservedErrorCheck(typeList[member].loc, typeList[member].type->getFieldName()); // Make default block qualification, and adjust the member qualifications TQualifier defaultQualification; switch (currentBlockQualifier.storage) { case EvqUniform: defaultQualification = globalUniformDefaults; break; case EvqBuffer: defaultQualification = globalBufferDefaults; break; case EvqVaryingIn: defaultQualification = globalInputDefaults; break; case EvqVaryingOut: defaultQualification = globalOutputDefaults; break; default: defaultQualification.clear(); break; } // Special case for "push_constant uniform", which has a default of std430, // contrary to normal uniform defaults, and can't have a default tracked for it. if (currentBlockQualifier.layoutPushConstant && !currentBlockQualifier.hasPacking()) currentBlockQualifier.layoutPacking = ElpStd430; // fix and check for member layout qualifiers mergeObjectLayoutQualifiers(defaultQualification, currentBlockQualifier, true); // "The offset qualifier can only be used on block members of blocks declared with std140 or std430 layouts." // "The align qualifier can only be used on blocks or block members, and only for blocks declared with std140 or std430 layouts." if (currentBlockQualifier.hasAlign() || currentBlockQualifier.hasAlign()) { if (defaultQualification.layoutPacking != ElpStd140 && defaultQualification.layoutPacking != ElpStd430) { error(loc, "can only be used with std140 or std430 layout packing", "offset/align", ""); defaultQualification.layoutAlign = -1; } } bool memberWithLocation = false; bool memberWithoutLocation = false; for (unsigned int member = 0; member < typeList.size(); ++member) { TQualifier& memberQualifier = typeList[member].type->getQualifier(); const TSourceLoc& memberLoc = typeList[member].loc; if (memberQualifier.hasStream()) { if (defaultQualification.layoutStream != memberQualifier.layoutStream) error(memberLoc, "member cannot contradict block", "stream", ""); } // "This includes a block's inheritance of the // current global default buffer, a block member's inheritance of the block's // buffer, and the requirement that any *xfb_buffer* declared on a block // member must match the buffer inherited from the block." if (memberQualifier.hasXfbBuffer()) { if (defaultQualification.layoutXfbBuffer != memberQualifier.layoutXfbBuffer) error(memberLoc, "member cannot contradict block (or what block inherited from global)", "xfb_buffer", ""); } if (memberQualifier.hasPacking()) error(memberLoc, "member of block cannot have a packing layout qualifier", typeList[member].type->getFieldName().c_str(), ""); if (memberQualifier.hasLocation()) { const char* feature = "location on block member"; switch (currentBlockQualifier.storage) { case EvqVaryingIn: case EvqVaryingOut: requireProfile(memberLoc, ECoreProfile | ECompatibilityProfile | EEsProfile, feature); profileRequires(memberLoc, ECoreProfile | ECompatibilityProfile, 440, E_GL_ARB_enhanced_layouts, feature); profileRequires(memberLoc, EEsProfile, 0, Num_AEP_shader_io_blocks, AEP_shader_io_blocks, feature); memberWithLocation = true; break; default: error(memberLoc, "can only use in an in/out block", feature, ""); break; } } else memberWithoutLocation = true; if (memberQualifier.hasAlign()) { if (defaultQualification.layoutPacking != ElpStd140 && defaultQualification.layoutPacking != ElpStd430) error(memberLoc, "can only be used with std140 or std430 layout packing", "align", ""); } TQualifier newMemberQualification = defaultQualification; mergeQualifiers(memberLoc, newMemberQualification, memberQualifier, false); memberQualifier = newMemberQualification; } // Process the members fixBlockLocations(loc, currentBlockQualifier, typeList, memberWithLocation, memberWithoutLocation); fixBlockXfbOffsets(currentBlockQualifier, typeList); fixBlockUniformOffsets(currentBlockQualifier, typeList); for (unsigned int member = 0; member < typeList.size(); ++member) layoutTypeCheck(typeList[member].loc, *typeList[member].type); // reverse merge, so that currentBlockQualifier now has all layout information // (can't use defaultQualification directly, it's missing other non-layout-default-class qualifiers) mergeObjectLayoutQualifiers(currentBlockQualifier, defaultQualification, true); // // Build and add the interface block as a new type named 'blockName' // TType blockType(&typeList, *blockName, currentBlockQualifier); if (arraySizes) blockType.newArraySizes(*arraySizes); else ioArrayCheck(loc, blockType, instanceName ? *instanceName : *blockName); // // Don't make a user-defined type out of block name; that will cause an error // if the same block name gets reused in a different interface. // // "Block names have no other use within a shader // beyond interface matching; it is a compile-time error to use a block name at global scope for anything // other than as a block name (e.g., use of a block name for a global variable name or function name is // currently reserved)." // // Use the symbol table to prevent normal reuse of the block's name, as a variable entry, // whose type is EbtBlock, but without all the structure; that will come from the type // the instances point to. // TType blockNameType(EbtBlock, blockType.getQualifier().storage); TVariable* blockNameVar = new TVariable(blockName, blockNameType); if (! symbolTable.insert(*blockNameVar)) { TSymbol* existingName = symbolTable.find(*blockName); if (existingName->getType().getBasicType() == EbtBlock) { if (existingName->getType().getQualifier().storage == blockType.getQualifier().storage) { error(loc, "Cannot reuse block name within the same interface:", blockName->c_str(), blockType.getStorageQualifierString()); return; } } else { error(loc, "block name cannot redefine a non-block name", blockName->c_str(), ""); return; } } // Add the variable, as anonymous or named instanceName. // Make an anonymous variable if no name was provided. if (! instanceName) instanceName = NewPoolTString(""); TVariable& variable = *new TVariable(instanceName, blockType); if (! symbolTable.insert(variable)) { if (*instanceName == "") error(loc, "nameless block contains a member that already has a name at global scope", blockName->c_str(), ""); else error(loc, "block instance name redefinition", variable.getName().c_str(), ""); return; } // Check for general layout qualifier errors layoutObjectCheck(loc, variable); if (isIoResizeArray(blockType)) { ioArraySymbolResizeList.push_back(&variable); checkIoArraysConsistency(loc, true); } else fixIoArraySize(loc, variable.getWritableType()); // Save it in the AST for linker use. intermediate.addSymbolLinkageNode(linkage, variable); } // Do all block-declaration checking regarding the combination of in/out/uniform/buffer // with a particular stage. void TParseContext::blockStageIoCheck(const TSourceLoc& loc, const TQualifier& qualifier) { switch (qualifier.storage) { case EvqUniform: profileRequires(loc, EEsProfile, 300, nullptr, "uniform block"); profileRequires(loc, ENoProfile, 140, nullptr, "uniform block"); if (currentBlockQualifier.layoutPacking == ElpStd430 && ! currentBlockQualifier.layoutPushConstant) error(loc, "requires the 'buffer' storage qualifier", "std430", ""); break; case EvqBuffer: requireProfile(loc, EEsProfile | ECoreProfile | ECompatibilityProfile, "buffer block"); profileRequires(loc, ECoreProfile | ECompatibilityProfile, 430, nullptr, "buffer block"); profileRequires(loc, EEsProfile, 310, nullptr, "buffer block"); break; case EvqVaryingIn: profileRequires(loc, ~EEsProfile, 150, E_GL_ARB_separate_shader_objects, "input block"); // It is a compile-time error to have an input block in a vertex shader or an output block in a fragment shader // "Compute shaders do not permit user-defined input variables..." requireStage(loc, (EShLanguageMask)(EShLangTessControlMask|EShLangTessEvaluationMask|EShLangGeometryMask|EShLangFragmentMask), "input block"); if (language == EShLangFragment) profileRequires(loc, EEsProfile, 0, Num_AEP_shader_io_blocks, AEP_shader_io_blocks, "fragment input block"); break; case EvqVaryingOut: profileRequires(loc, ~EEsProfile, 150, E_GL_ARB_separate_shader_objects, "output block"); requireStage(loc, (EShLanguageMask)(EShLangVertexMask|EShLangTessControlMask|EShLangTessEvaluationMask|EShLangGeometryMask), "output block"); // ES 310 can have a block before shader_io is turned on, so skip this test for built-ins if (language == EShLangVertex && ! parsingBuiltins) profileRequires(loc, EEsProfile, 0, Num_AEP_shader_io_blocks, AEP_shader_io_blocks, "vertex output block"); break; default: error(loc, "only uniform, buffer, in, or out blocks are supported", blockName->c_str(), ""); break; } } // Do all block-declaration checking regarding its qualifers. void TParseContext::blockQualifierCheck(const TSourceLoc& loc, const TQualifier& qualifier, bool instanceName) { // The 4.5 specification says: // // interface-block : // layout-qualifieropt interface-qualifier block-name { member-list } instance-nameopt ; // // interface-qualifier : // in // out // patch in // patch out // uniform // buffer // // Note however memory qualifiers aren't included, yet the specification also says // // "...memory qualifiers may also be used in the declaration of shader storage blocks..." if (qualifier.isInterpolation()) error(loc, "cannot use interpolation qualifiers on an interface block", "flat/smooth/noperspective", ""); if (qualifier.centroid) error(loc, "cannot use centroid qualifier on an interface block", "centroid", ""); if (qualifier.sample) error(loc, "cannot use sample qualifier on an interface block", "sample", ""); if (qualifier.invariant) error(loc, "cannot use invariant qualifier on an interface block", "invariant", ""); if (qualifier.layoutPushConstant) { intermediate.addPushConstantCount(); if (! instanceName) error(loc, "requires an instance name", "push_constant", ""); } } // // "For a block, this process applies to the entire block, or until the first member // is reached that has a location layout qualifier. When a block member is declared with a location // qualifier, its location comes from that qualifier: The member's location qualifier overrides the block-level // declaration. Subsequent members are again assigned consecutive locations, based on the newest location, // until the next member declared with a location qualifier. The values used for locations do not have to be // declared in increasing order." void TParseContext::fixBlockLocations(const TSourceLoc& loc, TQualifier& qualifier, TTypeList& typeList, bool memberWithLocation, bool memberWithoutLocation) { // "If a block has no block-level location layout qualifier, it is required that either all or none of its members // have a location layout qualifier, or a compile-time error results." if (! qualifier.hasLocation() && memberWithLocation && memberWithoutLocation) error(loc, "either the block needs a location, or all members need a location, or no members have a location", "location", ""); else { if (memberWithLocation) { // remove any block-level location and make it per *every* member int nextLocation = 0; // by the rule above, initial value is not relevant if (qualifier.hasAnyLocation()) { nextLocation = qualifier.layoutLocation; qualifier.layoutLocation = TQualifier::layoutLocationEnd; if (qualifier.hasComponent()) { // "It is a compile-time error to apply the *component* qualifier to a ... block" error(loc, "cannot apply to a block", "component", ""); } if (qualifier.hasIndex()) { error(loc, "cannot apply to a block", "index", ""); } } for (unsigned int member = 0; member < typeList.size(); ++member) { TQualifier& memberQualifier = typeList[member].type->getQualifier(); const TSourceLoc& memberLoc = typeList[member].loc; if (! memberQualifier.hasLocation()) { if (nextLocation >= (int)TQualifier::layoutLocationEnd) error(memberLoc, "location is too large", "location", ""); memberQualifier.layoutLocation = nextLocation; memberQualifier.layoutComponent = 0; } nextLocation = memberQualifier.layoutLocation + intermediate.computeTypeLocationSize(*typeList[member].type); } } } } void TParseContext::fixBlockXfbOffsets(TQualifier& qualifier, TTypeList& typeList) { // "If a block is qualified with xfb_offset, all its // members are assigned transform feedback buffer offsets. If a block is not qualified with xfb_offset, any // members of that block not qualified with an xfb_offset will not be assigned transform feedback buffer // offsets." if (! qualifier.hasXfbBuffer() || ! qualifier.hasXfbOffset()) return; int nextOffset = qualifier.layoutXfbOffset; for (unsigned int member = 0; member < typeList.size(); ++member) { TQualifier& memberQualifier = typeList[member].type->getQualifier(); bool containsDouble = false; int memberSize = intermediate.computeTypeXfbSize(*typeList[member].type, containsDouble); // see if we need to auto-assign an offset to this member if (! memberQualifier.hasXfbOffset()) { // "if applied to an aggregate containing a double, the offset must also be a multiple of 8" if (containsDouble) RoundToPow2(nextOffset, 8); memberQualifier.layoutXfbOffset = nextOffset; } else nextOffset = memberQualifier.layoutXfbOffset; nextOffset += memberSize; } // The above gave all block members an offset, so we can take it off the block now, // which will avoid double counting the offset usage. qualifier.layoutXfbOffset = TQualifier::layoutXfbOffsetEnd; } // Calculate and save the offset of each block member, using the recursively // defined block offset rules and the user-provided offset and align. // // Also, compute and save the total size of the block. For the block's size, arrayness // is not taken into account, as each element is backed by a separate buffer. // void TParseContext::fixBlockUniformOffsets(TQualifier& qualifier, TTypeList& typeList) { if (! qualifier.isUniformOrBuffer()) return; if (qualifier.layoutPacking != ElpStd140 && qualifier.layoutPacking != ElpStd430) return; int offset = 0; int memberSize; for (unsigned int member = 0; member < typeList.size(); ++member) { TQualifier& memberQualifier = typeList[member].type->getQualifier(); const TSourceLoc& memberLoc = typeList[member].loc; // "When align is applied to an array, it effects only the start of the array, not the array's internal stride." // modify just the children's view of matrix layout, if there is one for this member TLayoutMatrix subMatrixLayout = typeList[member].type->getQualifier().layoutMatrix; int dummyStride; int memberAlignment = intermediate.getBaseAlignment(*typeList[member].type, memberSize, dummyStride, qualifier.layoutPacking == ElpStd140, subMatrixLayout != ElmNone ? subMatrixLayout == ElmRowMajor : qualifier.layoutMatrix == ElmRowMajor); if (memberQualifier.hasOffset()) { // "The specified offset must be a multiple // of the base alignment of the type of the block member it qualifies, or a compile-time error results." if (! IsMultipleOfPow2(memberQualifier.layoutOffset, memberAlignment)) error(memberLoc, "must be a multiple of the member's alignment", "offset", ""); // "It is a compile-time error to specify an offset that is smaller than the offset of the previous // member in the block or that lies within the previous member of the block" if (memberQualifier.layoutOffset < offset) error(memberLoc, "cannot lie in previous members", "offset", ""); // "The offset qualifier forces the qualified member to start at or after the specified // integral-constant expression, which will be its byte offset from the beginning of the buffer. // "The actual offset of a member is computed as // follows: If offset was declared, start with that offset, otherwise start with the next available offset." offset = std::max(offset, memberQualifier.layoutOffset); } // "The actual alignment of a member will be the greater of the specified align alignment and the standard // (e.g., std140) base alignment for the member's type." if (memberQualifier.hasAlign()) memberAlignment = std::max(memberAlignment, memberQualifier.layoutAlign); // "If the resulting offset is not a multiple of the actual alignment, // increase it to the first offset that is a multiple of // the actual alignment." RoundToPow2(offset, memberAlignment); typeList[member].type->getQualifier().layoutOffset = offset; offset += memberSize; } } // For an identifier that is already declared, add more qualification to it. void TParseContext::addQualifierToExisting(const TSourceLoc& loc, TQualifier qualifier, const TString& identifier) { TSymbol* symbol = symbolTable.find(identifier); if (! symbol) { error(loc, "identifier not previously declared", identifier.c_str(), ""); return; } if (symbol->getAsFunction()) { error(loc, "cannot re-qualify a function name", identifier.c_str(), ""); return; } if (qualifier.isAuxiliary() || qualifier.isMemory() || qualifier.isInterpolation() || qualifier.hasLayout() || qualifier.storage != EvqTemporary || qualifier.precision != EpqNone) { error(loc, "cannot add storage, auxiliary, memory, interpolation, layout, or precision qualifier to an existing variable", identifier.c_str(), ""); return; } // For read-only built-ins, add a new symbol for holding the modified qualifier. // This will bring up an entire block, if a block type has to be modified (e.g., gl_Position inside a block) if (symbol->isReadOnly()) symbol = symbolTable.copyUp(symbol); if (qualifier.invariant) { if (intermediate.inIoAccessed(identifier)) error(loc, "cannot change qualification after use", "invariant", ""); symbol->getWritableType().getQualifier().invariant = true; invariantCheck(loc, symbol->getType().getQualifier()); } else warn(loc, "unknown requalification", "", ""); } void TParseContext::addQualifierToExisting(const TSourceLoc& loc, TQualifier qualifier, TIdentifierList& identifiers) { for (unsigned int i = 0; i < identifiers.size(); ++i) addQualifierToExisting(loc, qualifier, *identifiers[i]); } void TParseContext::invariantCheck(const TSourceLoc& loc, const TQualifier& qualifier) { if (! qualifier.invariant) return; bool pipeOut = qualifier.isPipeOutput(); bool pipeIn = qualifier.isPipeInput(); if (version >= 300 || (profile != EEsProfile && version >= 420)) { if (! pipeOut) error(loc, "can only apply to an output", "invariant", ""); } else { if ((language == EShLangVertex && pipeIn) || (! pipeOut && ! pipeIn)) error(loc, "can only apply to an output, or to an input in a non-vertex stage\n", "invariant", ""); } } // // Updating default qualifier for the case of a declaration with just a qualifier, // no type, block, or identifier. // void TParseContext::updateStandaloneQualifierDefaults(const TSourceLoc& loc, const TPublicType& publicType) { if (publicType.shaderQualifiers.vertices != TQualifier::layoutNotSet) { assert(language == EShLangTessControl || language == EShLangGeometry); const char* id = (language == EShLangTessControl) ? "vertices" : "max_vertices"; if (publicType.qualifier.storage != EvqVaryingOut) error(loc, "can only apply to 'out'", id, ""); if (! intermediate.setVertices(publicType.shaderQualifiers.vertices)) error(loc, "cannot change previously set layout value", id, ""); if (language == EShLangTessControl) checkIoArraysConsistency(loc); } if (publicType.shaderQualifiers.invocations != TQualifier::layoutNotSet) { if (publicType.qualifier.storage != EvqVaryingIn) error(loc, "can only apply to 'in'", "invocations", ""); if (! intermediate.setInvocations(publicType.shaderQualifiers.invocations)) error(loc, "cannot change previously set layout value", "invocations", ""); } if (publicType.shaderQualifiers.geometry != ElgNone) { if (publicType.qualifier.storage == EvqVaryingIn) { switch (publicType.shaderQualifiers.geometry) { case ElgPoints: case ElgLines: case ElgLinesAdjacency: case ElgTriangles: case ElgTrianglesAdjacency: case ElgQuads: case ElgIsolines: if (intermediate.setInputPrimitive(publicType.shaderQualifiers.geometry)) { if (language == EShLangGeometry) checkIoArraysConsistency(loc); } else error(loc, "cannot change previously set input primitive", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), ""); break; default: error(loc, "cannot apply to input", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), ""); } } else if (publicType.qualifier.storage == EvqVaryingOut) { switch (publicType.shaderQualifiers.geometry) { case ElgPoints: case ElgLineStrip: case ElgTriangleStrip: if (! intermediate.setOutputPrimitive(publicType.shaderQualifiers.geometry)) error(loc, "cannot change previously set output primitive", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), ""); break; default: error(loc, "cannot apply to 'out'", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), ""); } } else error(loc, "cannot apply to:", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), GetStorageQualifierString(publicType.qualifier.storage)); } if (publicType.shaderQualifiers.spacing != EvsNone) { if (publicType.qualifier.storage == EvqVaryingIn) { if (! intermediate.setVertexSpacing(publicType.shaderQualifiers.spacing)) error(loc, "cannot change previously set vertex spacing", TQualifier::getVertexSpacingString(publicType.shaderQualifiers.spacing), ""); } else error(loc, "can only apply to 'in'", TQualifier::getVertexSpacingString(publicType.shaderQualifiers.spacing), ""); } if (publicType.shaderQualifiers.order != EvoNone) { if (publicType.qualifier.storage == EvqVaryingIn) { if (! intermediate.setVertexOrder(publicType.shaderQualifiers.order)) error(loc, "cannot change previously set vertex order", TQualifier::getVertexOrderString(publicType.shaderQualifiers.order), ""); } else error(loc, "can only apply to 'in'", TQualifier::getVertexOrderString(publicType.shaderQualifiers.order), ""); } if (publicType.shaderQualifiers.pointMode) { if (publicType.qualifier.storage == EvqVaryingIn) intermediate.setPointMode(); else error(loc, "can only apply to 'in'", "point_mode", ""); } for (int i = 0; i < 3; ++i) { if (publicType.shaderQualifiers.localSize[i] > 1) { if (publicType.qualifier.storage == EvqVaryingIn) { if (! intermediate.setLocalSize(i, publicType.shaderQualifiers.localSize[i])) error(loc, "cannot change previously set size", "local_size", ""); else { int max = 0; switch (i) { case 0: max = resources.maxComputeWorkGroupSizeX; break; case 1: max = resources.maxComputeWorkGroupSizeY; break; case 2: max = resources.maxComputeWorkGroupSizeZ; break; default: break; } if (intermediate.getLocalSize(i) > (unsigned int)max) error(loc, "too large; see gl_MaxComputeWorkGroupSize", "local_size", ""); // Fix the existing constant gl_WorkGroupSize with this new information. bool builtIn; TSymbol* symbol = symbolTable.find("gl_WorkGroupSize", &builtIn); if (builtIn) makeEditable(symbol); TVariable* workGroupSize = symbol->getAsVariable(); workGroupSize->getWritableConstArray()[i].setUConst(intermediate.getLocalSize(i)); } } else error(loc, "can only apply to 'in'", "local_size", ""); } if (publicType.shaderQualifiers.localSizeSpecId[i] != TQualifier::layoutNotSet) { if (publicType.qualifier.storage == EvqVaryingIn) { if (! intermediate.setLocalSizeSpecId(i, publicType.shaderQualifiers.localSizeSpecId[i])) error(loc, "cannot change previously set size", "local_size", ""); } else error(loc, "can only apply to 'in'", "local_size id", ""); } } if (publicType.shaderQualifiers.earlyFragmentTests) { if (publicType.qualifier.storage == EvqVaryingIn) intermediate.setEarlyFragmentTests(); else error(loc, "can only apply to 'in'", "early_fragment_tests", ""); } if (publicType.shaderQualifiers.blendEquation) { if (publicType.qualifier.storage != EvqVaryingOut) error(loc, "can only apply to 'out'", "blend equation", ""); } const TQualifier& qualifier = publicType.qualifier; if (qualifier.isAuxiliary() || qualifier.isMemory() || qualifier.isInterpolation() || qualifier.precision != EpqNone) error(loc, "cannot use auxiliary, memory, interpolation, or precision qualifier in a default qualifier declaration (declaration with no type)", "qualifier", ""); // "The offset qualifier can only be used on block members of blocks..." // "The align qualifier can only be used on blocks or block members..." if (qualifier.hasOffset() || qualifier.hasAlign()) error(loc, "cannot use offset or align qualifiers in a default qualifier declaration (declaration with no type)", "layout qualifier", ""); layoutQualifierCheck(loc, qualifier); switch (qualifier.storage) { case EvqUniform: if (qualifier.hasMatrix()) globalUniformDefaults.layoutMatrix = qualifier.layoutMatrix; if (qualifier.hasPacking()) globalUniformDefaults.layoutPacking = qualifier.layoutPacking; break; case EvqBuffer: if (qualifier.hasMatrix()) globalBufferDefaults.layoutMatrix = qualifier.layoutMatrix; if (qualifier.hasPacking()) globalBufferDefaults.layoutPacking = qualifier.layoutPacking; break; case EvqVaryingIn: break; case EvqVaryingOut: if (qualifier.hasStream()) globalOutputDefaults.layoutStream = qualifier.layoutStream; if (qualifier.hasXfbBuffer()) globalOutputDefaults.layoutXfbBuffer = qualifier.layoutXfbBuffer; if (globalOutputDefaults.hasXfbBuffer() && qualifier.hasXfbStride()) { if (! intermediate.setXfbBufferStride(globalOutputDefaults.layoutXfbBuffer, qualifier.layoutXfbStride)) error(loc, "all stride settings must match for xfb buffer", "xfb_stride", "%d", qualifier.layoutXfbBuffer); } break; default: error(loc, "default qualifier requires 'uniform', 'buffer', 'in', or 'out' storage qualification", "", ""); return; } if (qualifier.hasBinding()) error(loc, "cannot declare a default, include a type or full declaration", "binding", ""); if (qualifier.hasAnyLocation()) error(loc, "cannot declare a default, use a full declaration", "location/component/index", ""); if (qualifier.hasXfbOffset()) error(loc, "cannot declare a default, use a full declaration", "xfb_offset", ""); if (qualifier.layoutPushConstant) error(loc, "cannot declare a default, can only be used on a block", "push_constant", ""); if (qualifier.hasSpecConstantId()) error(loc, "cannot declare a default, can only be used on a scalar", "constant_id", ""); } // // Take the sequence of statements that has been built up since the last case/default, // put it on the list of top-level nodes for the current (inner-most) switch statement, // and follow that by the case/default we are on now. (See switch topology comment on // TIntermSwitch.) // void TParseContext::wrapupSwitchSubsequence(TIntermAggregate* statements, TIntermNode* branchNode) { TIntermSequence* switchSequence = switchSequenceStack.back(); if (statements) { if (switchSequence->size() == 0) error(statements->getLoc(), "cannot have statements before first case/default label", "switch", ""); statements->setOperator(EOpSequence); switchSequence->push_back(statements); } if (branchNode) { // check all previous cases for the same label (or both are 'default') for (unsigned int s = 0; s < switchSequence->size(); ++s) { TIntermBranch* prevBranch = (*switchSequence)[s]->getAsBranchNode(); if (prevBranch) { TIntermTyped* prevExpression = prevBranch->getExpression(); TIntermTyped* newExpression = branchNode->getAsBranchNode()->getExpression(); if (prevExpression == nullptr && newExpression == nullptr) error(branchNode->getLoc(), "duplicate label", "default", ""); else if (prevExpression != nullptr && newExpression != nullptr && prevExpression->getAsConstantUnion() && newExpression->getAsConstantUnion() && prevExpression->getAsConstantUnion()->getConstArray()[0].getIConst() == newExpression->getAsConstantUnion()->getConstArray()[0].getIConst()) error(branchNode->getLoc(), "duplicated value", "case", ""); } } switchSequence->push_back(branchNode); } } // // Turn the top-level node sequence built up of wrapupSwitchSubsequence9) // into a switch node. // TIntermNode* TParseContext::addSwitch(const TSourceLoc& loc, TIntermTyped* expression, TIntermAggregate* lastStatements) { profileRequires(loc, EEsProfile, 300, nullptr, "switch statements"); profileRequires(loc, ENoProfile, 130, nullptr, "switch statements"); wrapupSwitchSubsequence(lastStatements, nullptr); if (expression == nullptr || (expression->getBasicType() != EbtInt && expression->getBasicType() != EbtUint) || expression->getType().isArray() || expression->getType().isMatrix() || expression->getType().isVector()) error(loc, "condition must be a scalar integer expression", "switch", ""); // If there is nothing to do, drop the switch but still execute the expression TIntermSequence* switchSequence = switchSequenceStack.back(); if (switchSequence->size() == 0) return expression; if (lastStatements == nullptr) { // This was originally an ERRROR, because early versions of the specification said // "it is an error to have no statement between a label and the end of the switch statement." // The specifications were updated to remove this (being ill-defined what a "statement" was), // so, this became a warning. However, 3.0 tests still check for the error. if (profile == EEsProfile && version <= 300 && ! relaxedErrors()) error(loc, "last case/default label not followed by statements", "switch", ""); else warn(loc, "last case/default label not followed by statements", "switch", ""); // emulate a break for error recovery lastStatements = intermediate.makeAggregate(intermediate.addBranch(EOpBreak, loc)); lastStatements->setOperator(EOpSequence); switchSequence->push_back(lastStatements); } TIntermAggregate* body = new TIntermAggregate(EOpSequence); body->getSequence() = *switchSequenceStack.back(); body->setLoc(loc); TIntermSwitch* switchNode = new TIntermSwitch(expression, body); switchNode->setLoc(loc); return switchNode; } void TParseContext::notifyVersion(int line, int version, const char* type_string) { if (versionCallback) { versionCallback(line, version, type_string); } } void TParseContext::notifyErrorDirective(int line, const char* error_message) { if (errorCallback) { errorCallback(line, error_message); } } void TParseContext::notifyLineDirective(int curLineNo, int newLineNo, bool hasSource, int sourceNum, const char* sourceName) { if (lineCallback) { lineCallback(curLineNo, newLineNo, hasSource, sourceNum, sourceName); } } void TParseContext::notifyExtensionDirective(int line, const char* extension, const char* behavior) { if (extensionCallback) { extensionCallback(line, extension, behavior); } } } // end namespace glslang
bsd-3-clause
mdedetrich/scalajs-antdesign
src/main/scala/scalajs/antdesign/Affix.scala
1345
package scalajs.antdesign import japgolly.scalajs.react.{CallbackTo, React, ReactComponentU_, ReactNode} import scala.scalajs.js import scala.scalajs.js.{Dynamic, Object} /** * @see https://ant.design/components/affix/ * @note Children of [[Affix]] can not be position: absolute, but you can set [[Affix]] as position: absolute: * @param offsetTop Pixels to offset from top when calculating position of scroll * @param offsetBottom Pixels to offset from bottom when calculating position of scroll * @param onChange Callback when affix state is changed */ case class Affix(offsetTop: js.UndefOr[Int] = js.undefined, offsetBottom: js.UndefOr[Int] = js.undefined, onChange: js.UndefOr[Boolean => CallbackTo[Unit]] = js.undefined) { def toJS: Object with Dynamic = { val p = js.Dynamic.literal() offsetTop.foreach { x => p.updateDynamic("offsetTop")(x) } offsetBottom.foreach { x => p.updateDynamic("offsetBottom")(x) } onChange.foreach { x => p.updateDynamic("onChange")( (v1: Boolean) => x(v1).runNow() ) } p } def apply(children: ReactNode*): ReactComponentU_ = { val f = React.asInstanceOf[js.Dynamic].createFactory(js.Dynamic.global.antd.Affix) f(toJS, children.toJsArray).asInstanceOf[ReactComponentU_] } }
bsd-3-clause
paksv/vijava
src/com/vmware/vim25/InsufficientPerCpuCapacity.java
1847
/*================================================================================ Copyright (c) 2013 Steve Jin. 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 VMware, 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 VMWARE, INC. 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.vmware.vim25; /** * @author Steve Jin (http://www.doublecloud.org) * @version 5.1 */ @SuppressWarnings("all") public class InsufficientPerCpuCapacity extends InsufficientHostCapacityFault { }
bsd-3-clause
genome-vendor/apollo
src/java/apollo/datamodel/EvidenceFinder.java
1087
package apollo.datamodel; import java.util.*; public class EvidenceFinder implements java.io.Serializable { private FeatureSetI fset; private Hashtable nameHash; public EvidenceFinder(FeatureSetI fset) { setFeatureSet(fset); } public void setFeatureSet(FeatureSetI fset) { this.fset = fset; nameHash = new Hashtable(); _hashSet(this.fset); } private void _hashSet(FeatureSetI subSet) { if (subSet != null) { for (int i=0; i<subSet.size(); i++) { SeqFeatureI sf = subSet.getFeatureAt(i); _putName(sf); if (sf.canHaveChildren()) { _hashSet((FeatureSetI)sf); } } } } private void _putName(SeqFeatureI sf) { if (sf.getId() != null) { nameHash.put(sf.getId(),sf); } } public SeqFeatureI findEvidence(String id) { if (id != null) { if (nameHash.containsKey(id)) { return (SeqFeatureI)nameHash.get(id); } else { return null; } } else { System.out.println("Null id in findEvidence."); return null; } } }
bsd-3-clause
vertica-as/Vertica.Utilities
src/Vertica.Utilities/Comparisons/Eq.cs
371
using System; namespace Vertica.Utilities.Comparisons { public static class Eq<T> { public static ChainableEqualizer<T> By<K>(Func<T, K> keySelector) { return new SelectorEqualizer<T, K>(keySelector); } public static ChainableEqualizer<T> By(Func<T, T, bool> equals, Func<T, int> hasher) { return new DelegatedEqualizer<T>(equals, hasher); } } }
bsd-3-clause
nbeckman/nolacoaster
Megabudget/src/com/nbeckman/megabudget/FullscreenActivity.java
18659
package com.nbeckman.megabudget; import java.io.IOException; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.Calendar; import java.util.List; import com.nbeckman.megabudget.util.SystemUiHider; import com.google.android.gms.auth.GoogleAuthException; import com.google.android.gms.auth.GoogleAuthUtil; import com.google.android.gms.auth.UserRecoverableAuthException; import com.google.android.gms.common.AccountPicker; import com.google.gdata.client.spreadsheet.SpreadsheetService; import com.google.gdata.data.spreadsheet.CellFeed; import com.google.gdata.data.spreadsheet.SpreadsheetEntry; import com.google.gdata.data.spreadsheet.SpreadsheetFeed; import com.google.gdata.data.spreadsheet.WorksheetEntry; import com.google.gdata.data.spreadsheet.WorksheetFeed; import com.google.gdata.util.ContentType; import com.google.gdata.util.ServiceException; import android.accounts.Account; import android.accounts.AccountManager; import android.annotation.TargetApi; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.text.format.Time; import android.view.MotionEvent; import android.view.View; /** * An example full-screen activity that shows and hides the system UI (i.e. * status bar and navigation/system bar) with user interaction. * * @see SystemUiHider */ public class FullscreenActivity extends Activity { /** * Whether or not the system UI should be auto-hidden after * {@link #AUTO_HIDE_DELAY_MILLIS} milliseconds. */ private static final boolean AUTO_HIDE = true; /** * If {@link #AUTO_HIDE} is set, the number of milliseconds to wait after * user interaction before hiding the system UI. */ private static final int AUTO_HIDE_DELAY_MILLIS = 3000; /** * If set, will toggle the system UI visibility upon interaction. Otherwise, * will show the system UI visibility upon interaction. */ private static final boolean TOGGLE_ON_CLICK = true; /** * The flags to pass to {@link SystemUiHider#getInstance}. */ private static final int HIDER_FLAGS = SystemUiHider.FLAG_HIDE_NAVIGATION; /** * The instance of the {@link SystemUiHider} for this activity. */ private SystemUiHider mSystemUiHider; private AccountManager mAccountManager; // The account name that the user wants to use. // Loaded from the preferences store. If not present, // we use the AccountManager to let the user choose an account. private String mAccountName; // The filename of the spreadsheet that holds the budget. It's // chosen initially by the ChooseFileActivity, and stored. private String mSpreadsheetFile; // The preference name for the stored account, picked initially and used forevermore // after that. private static final String kAccountPreferencesName = com.nbeckman.megabudget.AccountManager.kAccountPreferencesName; // The name of the spreadsheet, picked initially and used forevermore. // TODO(nbeckman): Allow this to be changed. // TODO(nbeckman): Wouldn't we rather store a doc ID or something? Something we are // not afraid of collisions? private static final String kBudgetSpreadsheetPreferencesName = MegaBudgetSettingsActivity.kBudgetSpreadsheetPreferencesName; private static final int kAccountChoiceIntent = 9; private static final int kModifySpreadSheetIntent = 10; private static final int kFileChoiceIntent = 11; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_fullscreen); final View controlsView = findViewById(R.id.fullscreen_content_controls); final View contentView = findViewById(R.id.fullscreen_content); // Set up an instance of SystemUiHider to control the system UI for // this activity. mSystemUiHider = SystemUiHider.getInstance(this, contentView, HIDER_FLAGS); mSystemUiHider.setup(); mSystemUiHider .setOnVisibilityChangeListener(new SystemUiHider.OnVisibilityChangeListener() { // Cached values. int mControlsHeight; int mShortAnimTime; @Override @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2) public void onVisibilityChange(boolean visible) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) { // If the ViewPropertyAnimator API is available // (Honeycomb MR2 and later), use it to animate the // in-layout UI controls at the bottom of the // screen. if (mControlsHeight == 0) { mControlsHeight = controlsView.getHeight(); } if (mShortAnimTime == 0) { mShortAnimTime = getResources().getInteger( android.R.integer.config_shortAnimTime); } controlsView.animate() .translationY(visible ? 0 : mControlsHeight) .setDuration(mShortAnimTime); } else { // If the ViewPropertyAnimator APIs aren't // available, simply show or hide the in-layout UI // controls. controlsView.setVisibility(visible ? View.VISIBLE : View.GONE); } if (visible && AUTO_HIDE) { // Schedule a hide(). delayedHide(AUTO_HIDE_DELAY_MILLIS); } } }); // Set up the user interaction to manually show or hide the system UI. contentView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (TOGGLE_ON_CLICK) { mSystemUiHider.toggle(); } else { mSystemUiHider.show(); } } }); // Upon interacting with UI controls, delay any scheduled hide() // operations to prevent the jarring behavior of controls going away // while interacting with the UI. findViewById(R.id.dummy_button).setOnTouchListener(mDelayHideTouchListener); findViewById(R.id.dummy_button).setOnClickListener(mButtonPressListener); // See if we have a preferred account stored, and if so, load it, // otherwise ask the user. SharedPreferences settings = getPreferences(MODE_PRIVATE); if (settings.contains(kAccountPreferencesName)) { this.mAccountName = settings.getString(kAccountPreferencesName, "nobody@google.com"); // Now, see if we have chosen a speadsheet file. if (settings.contains(kBudgetSpreadsheetPreferencesName)) { this.mSpreadsheetFile = settings.getString(mSpreadsheetFile, ""); // TODO(nbeckman): From this point we need to populate the UI... } else { this.launchChooseFileActivity(); } } else { Intent intent = AccountPicker.newChooseAccountIntent(null, null, new String[]{"com.google"}, false, null, null, null, null); startActivityForResult(intent, kAccountChoiceIntent); } } // Launches the choose file activity, which will look at the user's account and // determine which spreadsheets are available and let them choose which one they // want to be their budget. We'll probably only do this once, but it needs to be // done after we know the account. It also needs to be done with a connection // to the spreadsheets... private void launchChooseFileActivity() { // TODO(nbeckman): Put loading thingy onscreen because this takes a // while and you have no idea what is going on. (new AsyncTask<String, String,String>(){ @Override protected String doInBackground(String... arg0) { SpreadsheetFeed feed = null; try { feed = currentSpreadsheetFeedInThisThread(); } catch (UserRecoverableAuthException e) { // This is NECESSARY so the user can say, "yeah I want // this app to have permission to read my spreadsheet." // TODO Make sure we get back to this call if we go down this path. Intent recoveryIntent = e.getIntent(); startActivityForResult(recoveryIntent, 2); } if (feed != null) { // From the feed, get an array of file names to put in the request to // the file chooser activity. List<SpreadsheetEntry> spreadsheets = feed.getEntries(); String[] spreadsheet_file_names = new String[spreadsheets.size()]; int index = 0; for (SpreadsheetEntry spreadsheet : spreadsheets) { final String name = spreadsheet.getTitle().getPlainText(); spreadsheet_file_names[index] = name; index++; } Intent choose_file_intent = new Intent(FullscreenActivity.this, ChooseFileActivity.class); choose_file_intent.putExtra("spreadsheet_files", spreadsheet_file_names); startActivityForResult(choose_file_intent, kFileChoiceIntent); } return "WHAT"; }}).execute(); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); // Trigger the initial hide() shortly after the activity has been // created, to briefly hint to the user that UI controls // are available. delayedHide(100); } protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) { if (requestCode == kAccountChoiceIntent && resultCode == RESULT_OK) { final String accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME); this.mAccountName = accountName; // Account chosen for the first time. Store it to the preferences. SharedPreferences settings = getPreferences(MODE_PRIVATE); SharedPreferences.Editor editor = settings.edit(); editor.putString(kAccountPreferencesName, accountName); editor.commit(); // Now move on to choosing a budget file. this.launchChooseFileActivity(); } else if (requestCode == kModifySpreadSheetIntent && resultCode == RESULT_OK) { } else if (requestCode == 2 && resultCode == RESULT_OK) { // After the user YAYs or NAYs our permission request, we are // taken here, so if we wanted to grab the token now we could. } else if (requestCode == kFileChoiceIntent && resultCode == RESULT_OK) { // What file did the user choose? Save it to disk for next time so we don't // ask again. final String file_name = data.getStringExtra("result"); this.mSpreadsheetFile = file_name; SharedPreferences settings = getPreferences(MODE_PRIVATE); SharedPreferences.Editor editor = settings.edit(); editor.putString(kBudgetSpreadsheetPreferencesName, file_name); editor.commit(); // TODO(nbeckman): From this point we need to create the UI... } } /** * Touch listener to use for in-layout UI controls to delay hiding the * system UI. This is to prevent the jarring behavior of controls going away * while interacting with activity UI. */ View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { if (AUTO_HIDE) { delayedHide(AUTO_HIDE_DELAY_MILLIS); } return false; } }; View.OnClickListener mButtonPressListener = new View.OnClickListener() { @Override public void onClick(View v) { modifySpreadsheet(); } }; // Gets a token for the current user, mAccountName, which should not be null. // Will throw a UserRecoverableAuthException if the user has not yet // authorize spreadsheet access for this app, in which case the caller should // handle it and do something. private SpreadsheetService setupSpreadsheetServiceInThisThread() throws UserRecoverableAuthException { // Turn account name into a token, which must // be done in a background task, as it contacts // the network. String token = null; try { token = GoogleAuthUtil.getToken( FullscreenActivity.this, mAccountName, "oauth2:https://spreadsheets.google.com/feeds https://docs.google.com/feeds"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (GoogleAuthException e) { // TODO Auto-generated catch block e.printStackTrace(); } // Now that we have the token, can we actually list // the spreadsheets or anything... SpreadsheetService s = new SpreadsheetService("Megabudget"); s.setAuthSubToken(token); return s; } private SpreadsheetFeed currentSpreadsheetFeedInThisThread() throws UserRecoverableAuthException { SpreadsheetService service = setupSpreadsheetServiceInThisThread(); try { // Define the URL to request. This should never change. // (Magic URL good for all users.) URL SPREADSHEET_FEED_URL = new URL( "https://spreadsheets.google.com/feeds/spreadsheets/private/full"); // Make a request to the API and get all spreadsheets. SpreadsheetFeed feed = null; feed = service.getFeed(SPREADSHEET_FEED_URL, SpreadsheetFeed.class); return feed; } catch (MalformedURLException e) { // TODO When does this happen? Probably never e.printStackTrace(); } catch (IOException e) { // TODO When does this happen? e.printStackTrace(); } catch (ServiceException e) { // TODO When does this happen? e.printStackTrace(); } return null; } // Right now this function modifies a spreadsheet called 'foo' private void modifySpreadsheet() { (new AsyncTask<String, String,String>(){ @Override protected String doInBackground(String... arg0) { try { // Turn account name into a token, which must // be done in a background task, as it contacts // the network. String token = GoogleAuthUtil.getToken( FullscreenActivity.this, mAccountName, "oauth2:https://spreadsheets.google.com/feeds https://docs.google.com/feeds"); System.err.println("Token: " + token); // Now that we have the token, can we actually list // the spreadsheets or anything... SpreadsheetService s = new SpreadsheetService("Megabudget"); s.setAuthSubToken(token); // Define the URL to request. This should never change. // (Magic URL good for all users.) URL SPREADSHEET_FEED_URL = new URL( "https://spreadsheets.google.com/feeds/spreadsheets/private/full"); // Make a request to the API and get all spreadsheets. SpreadsheetFeed feed; try { feed = s.getFeed(SPREADSHEET_FEED_URL, SpreadsheetFeed.class); List<SpreadsheetEntry> spreadsheets = feed.getEntries(); // Iterate through all of the spreadsheets returned for (SpreadsheetEntry spreadsheet : spreadsheets) { // Print the title of this spreadsheet to the screen final String name = spreadsheet.getTitle().getPlainText(); System.err.println(name); if ("foo".equals(name)) { // Get the first work sheet, WorksheetFeed worksheetFeed = s.getFeed( spreadsheet.getWorksheetFeedUrl(), WorksheetFeed.class); List<WorksheetEntry> worksheets = worksheetFeed.getEntries(); WorksheetEntry worksheet = worksheets.get(0); //read cell A1 URL cellFeedUrl = new URI(worksheet.getCellFeedUrl().toString() + "?min-row=1&min-col=1&max-col=1&max-row=1").toURL(); CellFeed cell = s.getFeed(cellFeedUrl, CellFeed.class); System.err.println("Cell " + cell.getTitle().getPlainText() + " value is " + cell.getEntries().get(0).getCell().getInputValue()); // write the time to cell A2. // (if this cell doesn't already have some data in it, // we get an indexoutofboundsexception). URL a2CellFeedUrl = new URI(worksheet.getCellFeedUrl().toString() + "?min-row=2&min-col=1&max-col=1&max-row=2").toURL(); CellFeed a2Cell = s.getFeed(a2CellFeedUrl, CellFeed.class); Time now = new Time(); now.setToNow(); final String a2_value = now.format2445(); System.err.println("Setting cell " + a2Cell.getTitle().getPlainText() + " value to " + a2_value); a2Cell.getEntries().get(0).changeInputValueLocal(a2_value); a2Cell.getEntries().get(0).update(); } } } catch (ServiceException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (UserRecoverableAuthException e) { // This is NECESSARY so the user can say, "yeah I want // this app to have permission to read my spreadsheet." Intent recoveryIntent = e.getIntent(); startActivityForResult(recoveryIntent, 2); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (GoogleAuthException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; }}).execute(); } Handler mHideHandler = new Handler(); Runnable mHideRunnable = new Runnable() { @Override public void run() { mSystemUiHider.hide(); } }; /** * Schedules a call to hide() in [delay] milliseconds, canceling any * previously scheduled calls. */ private void delayedHide(int delayMillis) { mHideHandler.removeCallbacks(mHideRunnable); mHideHandler.postDelayed(mHideRunnable, delayMillis); } }
bsd-3-clause
anwarjaved/Innosparx
GoogleSDK/Analytics/PageTrackingResponse.cs
127
namespace GoogleSDK.Analytics { public class PageTrackingResponse : BaseResponse<PageTrackingResultTotal> { } }
bsd-3-clause
angavrilov/olmar
elsa/implconv.cc
12278
// implconv.cc see license.txt for copyright and terms of use // code for implconv.h #include "implconv.h" // this module #include "cc_env.h" // Env #include "variable.h" // Variable #include "overload.h" // resolveOverload #include "trace.h" // tracingSys // prototypes StandardConversion tryCallCtor (Variable const *var, SpecialExpr special, CType const *src); // ------------------- ImplicitConversion -------------------- char const * const ImplicitConversion::kindNames[NUM_KINDS] = { "IC_NONE", "IC_STANDARD", "IC_USER_DEFINED", "IC_ELLIPSIS", "IC_AMBIGUOUS" }; void ImplicitConversion::addStdConv(StandardConversion newScs) { if (kind != IC_NONE) { kind = IC_AMBIGUOUS; return; } kind = IC_STANDARD; scs = newScs; } void ImplicitConversion ::addUserConv(StandardConversion first, Variable *userFunc, StandardConversion second) { if (kind != IC_NONE) { kind = IC_AMBIGUOUS; return; } kind = IC_USER_DEFINED; scs = first; user = userFunc; scs2 = second; } void ImplicitConversion::addEllipsisConv() { if (kind != IC_NONE) { kind = IC_AMBIGUOUS; return; } kind = IC_ELLIPSIS; } CType *ImplicitConversion::getConcreteDestType (TypeFactory &tfac, CType *srcType, CType *destType) const { // skip past the user-defined conversion, if any StandardConversion sconv = scs; if (kind == IC_USER_DEFINED) { srcType = user->type->asFunctionType()->retType; sconv = scs2; } // 2005-04-15: in/k0032.cc: if both src and dest are reference // types, skip that if (srcType->isReference() && destType->isReference()) { CType *destAt = destType->getAtType(); CType *srcAt = srcType->getAtType(); CType *concrete = inner_getConcreteDestType(tfac, srcAt, destAt, sconv); if (concrete == destAt) { return destType; // was concrete already } else { // must re-construct the reference part of the type return tfac.makeReferenceType(concrete); } } return inner_getConcreteDestType(tfac, srcType, destType, sconv); } // this function exists just so that the reference/reference case // can use it as a subroutine ... CType *ImplicitConversion::inner_getConcreteDestType (TypeFactory &tfac, CType *srcType, CType *destType, StandardConversion sconv) const { if (destType->isPointer()) { // hmm.. operator+ has '<any obj> *' CType *destAtType = destType->getAtType(); if (!destAtType->isSimpleType()) { return destType; // easy } SimpleTypeId id = destAtType->asSimpleTypeC()->type; if (isConcreteSimpleType(id)) { return destType; // also easy } // if 'destType' is a reference to a polymorphic type, // then this wouldn't be right .... srcType = srcType->asRval(); // apply the conversion if (sconv == SC_ARRAY_TO_PTR) { srcType = tfac.makePointerType(CV_NONE, srcType->asArrayType()->eltType); } // anything more to do? not sure... return srcType; } // these first two conditions are the same as at the top // of OverloadResolver::getReturnType ... if (!destType->isSimpleType()) { return destType; // easy } SimpleTypeId id = destType->asSimpleTypeC()->type; if (isConcreteSimpleType(id)) { return destType; // also easy } // ask the standard conversion module what type results when using // 'sconv' to convert from 'srcType' to the polymorphic 'destType' SimpleTypeId destPolyType = destType->asSimpleTypeC()->type; return ::getConcreteDestType(tfac, srcType, sconv, destPolyType); } string ImplicitConversion::debugString() const { stringBuilder sb; sb << kindNames[kind]; if (kind == IC_STANDARD || kind == IC_USER_DEFINED) { sb << "(" << toString(scs); if (kind == IC_USER_DEFINED) { sb << ", " << user->name << " @ " << toString(user->loc) << ", " << toString(scs2); } sb << ")"; } return sb; } // --------------------- getImplicitConversion --------------- ImplicitConversion getImplicitConversion (Env &env, SpecialExpr special, CType *src, CType *dest, bool destIsReceiver) { xassert(src && dest); ImplicitConversion ret; if (src->asRval()->isGeneralizedDependent()) { ret.addStdConv(SC_IDENTITY); // could be as good as this return ret; } // 9/25/04: conversion from template class pointer requires // instantiating the template class, so we can try derived-to-base // conversions if (src->asRval()->isPointerType()) { CType *at = src->asRval()->asPointerType()->atType; if (at->isCompoundType()) { env.ensureClassBodyInstantiatedIfPossible(at->asCompoundType()); } } // check for a standard sequence { StandardConversion scs = getStandardConversion(NULL /*errorMsg*/, special, src, dest, destIsReceiver); if (scs != SC_ERROR) { ret.addStdConv(scs); return ret; } } // 13.3.3.1p6: derived-to-base conversion? (acts like a standard // conversion for overload resolution, but is not a "real" standard // conversion, because in actuality a constructor call is involved) if (dest->isCompoundType() && src->asRval()->isCompoundType()) { CompoundType *destCt = dest->asCompoundType(); CompoundType *srcCt = src->asRval()->asCompoundType(); if (srcCt->hasBaseClass(destCt)) { ret.addStdConv(SC_DERIVED_TO_BASE); return ret; } } // check for a constructor to make the dest type; for this to // work, the dest type must be a class type or a const reference // to one if (dest->isCompoundType() || (dest->asRval()->isCompoundType() && dest->asRval()->isConst())) { CompoundType *ct = dest->asRval()->asCompoundType(); // (in/t0514.cc) conversion to a template class specialization // requires that the specialization be instantiated env.ensureClassBodyInstantiatedIfPossible(ct); // get the overload set of constructors Variable *ctor = ct->getNamedField(env.constructorSpecialName, env); if (!ctor) { // ideally we'd have at least one ctor for every class, but I // think my current implementation doesn't add all of the // implicit constructors.. and if there are only implicit // constructors, they're handled specially anyway (I think), // so we can just disregard the possibility of using one } else { if (ctor->overload) { // multiple ctors, resolve overloading; but don't further // consider user-defined conversions; note that 'explicit' // constructors are disregarded (OF_NO_EXPLICIT) GrowArray<ArgumentInfo> argTypes(1); argTypes[0] = ArgumentInfo(special, src); OVERLOADINDTRACE("overloaded call to constructor " << ct->name); bool wasAmbig; ctor = resolveOverload(env, env.loc(), NULL /*errors*/, OF_NO_USER | OF_NO_EXPLICIT, ctor->overload->set, NULL /*finalName*/, argTypes, wasAmbig, ct->name); if (ctor) { // printing is now done inside 'resolveOverload' //TRACE("overload", " selected constructor at " << toString(ctor->loc)); } else if (wasAmbig) { //TRACE("overload", " ambiguity while selecting constructor"); ret.addAmbig(); } else { //TRACE("overload", " no constructor matches"); } } if (ctor) { // only one ctor now.. can we call it? StandardConversion first = tryCallCtor(ctor, special, src); if (first != SC_ERROR) { // success ret.addUserConv(first, ctor, SC_IDENTITY); } } } } // check for a conversion function if (src->asRval()->isCompoundType()) { ImplicitConversion conv = getConversionOperator( env, env.loc(), NULL /*errors*/, src, dest); if (conv) { if (ret) { // there's already a constructor-based conversion, so this // sequence is ambiguous ret.addAmbig(); } else { ret = conv; } } } return ret; } StandardConversion tryCallCtor (Variable const *var, SpecialExpr special, CType const *src) { // certainly should be a function FunctionType *ft = var->type->asFunctionType(); int numParams = ft->params.count(); if (numParams == 0) { if (ft->acceptsVarargs()) { // I'm not sure about this.. there's no SC_ELLIPSIS.. return SC_IDENTITY; } else { return SC_ERROR; } } if (numParams > 1) { if (ft->params.nthC(1)->varValue) { // the 2nd param has a default, which implies all params // after have defaults, so this is ok } else { return SC_ERROR; // requires at least 2 arguments } } Variable const *param = ft->params.firstC(); return getStandardConversion(NULL /*errorMsg*/, special, src, param->type); } // ----------------- test_getImplicitConversion ---------------- int getLine(SourceLoc loc) { return sourceLocManager->getLine(loc); } bool matchesExpectation(ImplicitConversion const &actual, int expectedKind, int expectedSCS, int expectedUserLine, int expectedSCS2) { if (expectedKind != actual.kind) return false; if (actual.kind == ImplicitConversion::IC_STANDARD) { return actual.scs == expectedSCS; } if (actual.kind == ImplicitConversion::IC_USER_DEFINED) { int actualLine = getLine(actual.user->loc); return actual.scs == expectedSCS && actualLine == expectedUserLine && actual.scs2 == expectedSCS2; } // other kinds are equal without further checking return true; } void test_getImplicitConversion( Env &env, SpecialExpr special, CType *src, CType *dest, int expectedKind, int expectedSCS, int expectedUserLine, int expectedSCS2) { // grab existing error messages ErrorList existing; existing.takeMessages(env.errors); // run our function ImplicitConversion actual = getImplicitConversion(env, special, src, dest); // turn any resulting messags into warnings, so I can see their // results without causing the final exit status to be nonzero env.errors.markAllAsWarnings(); // put the old messages back env.errors.takeMessages(existing); // did it behave as expected? bool matches = matchesExpectation(actual, expectedKind, expectedSCS, expectedUserLine, expectedSCS2); if (!matches || tracingSys("gIC")) { // construct a description of the actual result stringBuilder actualDesc; actualDesc << ImplicitConversion::kindNames[actual.kind]; if (actual.kind == ImplicitConversion::IC_STANDARD || actual.kind == ImplicitConversion::IC_USER_DEFINED) { actualDesc << "(" << toString(actual.scs); if (actual.kind == ImplicitConversion::IC_USER_DEFINED) { actualDesc << ", " << getLine(actual.user->loc) << ", " << toString(actual.scs2); } actualDesc << ")"; } // construct a description of the call site stringBuilder callDesc; callDesc << "getImplicitConversion(" << toString(special) << ", `" << src->toString() << "', `" << dest->toString() << "')"; if (!matches) { // construct a description of the expected result stringBuilder expectedDesc; xassert((unsigned)expectedKind <= (unsigned)ImplicitConversion::NUM_KINDS); expectedDesc << ImplicitConversion::kindNames[expectedKind]; if (expectedKind == ImplicitConversion::IC_STANDARD || expectedKind == ImplicitConversion::IC_USER_DEFINED) { expectedDesc << "(" << toString((StandardConversion)expectedSCS); if (expectedKind == ImplicitConversion::IC_USER_DEFINED) { expectedDesc << ", " << expectedUserLine << ", " << toString((StandardConversion)expectedSCS2); } expectedDesc << ")"; } env.error(stringc << callDesc << " yielded " << actualDesc << ", but I expected " << expectedDesc); } else { env.warning(stringc << callDesc << " yielded " << actualDesc); } } } // EOF
bsd-3-clause
vega/vega-parser
schema/legend.js
4100
import {layoutAlign} from './layout'; import { numberValue, stringValue, colorValue, alignValue, baselineValue, fontWeightValue, numberOrSignal, stringOrSignal, arrayOrSignal } from './util'; export default { "defs": { "guideEncode": { "type": "object", "properties": { "name": {"type": "string"}, "interactive": {"type": "boolean", "default": false}, "style": {"$ref": "#/refs/style"} }, "patternProperties": { "^(?!interactive|name|style).+$": {"$ref": "#/defs/encodeEntry"}, }, "additionalProperties": false }, "legend": { "type": "object", "properties": { "size": {"type": "string"}, "shape": {"type": "string"}, "fill": {"type": "string"}, "stroke": {"type": "string"}, "opacity": {"type": "string"}, "strokeDash": {"type": "string"}, "type": { "enum": ["gradient", "symbol"] }, "direction": { "enum": ["vertical", "horizontal"] }, "orient": { "enum": [ "none", "left", "right", "top", "bottom", "top-left", "top-right", "bottom-left", "bottom-right" ], "default": "right" }, "format": stringOrSignal, "title": stringOrSignal, "tickCount": {"$ref": "#/refs/tickCount"}, "values": arrayOrSignal, "zindex": {"type": "number"}, // LEGEND GROUP CONFIG "cornerRadius": numberValue, "fillColor": colorValue, "offset": numberValue, "padding": numberValue, "strokeColor": colorValue, "strokeWidth": numberValue, // LEGEND TITLE CONFIG "titleAlign": alignValue, "titleBaseline": baselineValue, "titleColor": colorValue, "titleFont": stringValue, "titleFontSize": numberValue, "titleFontWeight": fontWeightValue, "titleLimit": numberValue, "titleOpacity": numberValue, "titlePadding": numberValue, // GRADIENT CONFIG "gradientLength": numberOrSignal, "gradientOpacity": numberValue, "gradientStrokeColor": colorValue, "gradientStrokeWidth": numberValue, "gradientThickness": numberOrSignal, // SYMBOL LAYOUT CONFIG "clipHeight": numberOrSignal, "columns": numberOrSignal, "columnPadding": numberOrSignal, "rowPadding": numberOrSignal, "gridAlign": layoutAlign, // SYMBOL CONFIG "symbolFillColor": colorValue, "symbolOffset": numberValue, "symbolOpacity": numberValue, "symbolSize": numberValue, "symbolStrokeColor": colorValue, "symbolStrokeWidth": numberValue, "symbolType": stringValue, // LABEL CONFIG "labelAlign": alignValue, "labelBaseline": baselineValue, "labelColor": colorValue, "labelFont": stringValue, "labelFontSize": numberValue, "labelFontWeight": fontWeightValue, "labelLimit": numberValue, "labelOffset": numberValue, "labelOpacity": numberValue, "labelOverlap": {"$ref": "#/refs/labelOverlap"}, // CUSTOMIZED ENCODERS "encode": { "type": "object", "properties": { "title": {"$ref": "#/defs/guideEncode"}, "labels": {"$ref": "#/defs/guideEncode"}, "legend": {"$ref": "#/defs/guideEncode"}, "entries": {"$ref": "#/defs/guideEncode"}, "symbols": {"$ref": "#/defs/guideEncode"}, "gradient": {"$ref": "#/defs/guideEncode"} }, "additionalProperties": false } }, "additionalProperties": false, "anyOf": [ {"required": ["size"]}, {"required": ["shape"]}, {"required": ["fill"]}, {"required": ["stroke"]}, {"required": ["opacity"]}, {"required": ["strokeDash"]} ] } } };
bsd-3-clause